jsonvet-cli 3.5.0

The jsonvet command: checks JSON, I-JSON, JSONC, JWCC (HuJSON), JSON5 and JSON Lines files, with JSON Schema checks, SARIF output, fixes and a formatter.
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
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
//! `--schema`: each file's values checked against one JSON Schema, every error placed at the
//! value it is about. The schema's size limits are in `limits`, the targets for placing errors in
//! `place`, folding events into a tree of the values in `fold`, and the tree in `nodes`.

mod fold;
mod limits;
mod nodes;
mod place;
pub(crate) mod select;
mod values;

use std::borrow::Cow;
use std::collections::{BTreeSet, HashMap};
use std::ops::Range;
use std::path::Path;
use std::sync::{Arc, OnceLock};

use jsonschema::error::ValidationErrorKind;
use jsonschema::json::{Array, Json, Node, Object};
use jsonschema::{
    JsonType, PatternOptions, ReferencingError, ValidationError, ValidationOptions, Validator,
};
use jsonvet::{Config, Dialect, Event, Report, Rule, Severity};
use serde_json::{Map, Value};

use crate::messages;
use crate::settings::Settings;
use fold::Fold;
use limits::{MAX_SCHEMA_DEPTH, PATTERN_BYTES, Reach, registry};
use nodes::{Nd, Own, Tree};
use place::{place_found, pointer_path, segments};

/// How deep a file checked against a schema is read. Past it, the file has a syntax error.
/// jsonschema validates recursively, so depth costs stack (see `STACK` in lib.rs). Its memory for
/// an error deep under a recursive `$ref` grows linearly with depth: 19 MB for a 60 KB file
/// nested 10,000 levels.
pub(crate) const SCHEMA_MAX_DEPTH: usize = 512;

/// How many schema errors one document reports, in the order jsonschema finds them; one more
/// line says there are more.
const MAX_ERRORS: usize = 100;

/// Past this many bytes, a message says "value" instead of quoting the value, and past it
/// still, it is cut short.
const MAX_MESSAGE: usize = 200;

/// How many times one regex match may backtrack before it fails. About one step per character
/// for a lookaround over the whole string, so a string over a few thousand characters can hit it.
const BACKTRACK_LIMIT: usize = 5_000;

/// The keys of a schema that check nothing themselves, kept beside the part checked on its own
/// when a schema is split, so that its `$ref`s resolve as before.
const NOT_CHECKS: [&str; 9] = [
    "$schema",
    "$id",
    "id",
    "$defs",
    "definitions",
    "$anchor",
    "$dynamicAnchor",
    "$vocabulary",
    "$comment",
];

/// The keywords that can apply a schema to an array's elements or an object's members besides
/// `items`, `properties`, `patternProperties` and `additionalProperties`, or change what those
/// check.
const ON_CHILDREN: [&str; 13] = [
    "allOf",
    "anyOf",
    "oneOf",
    "not",
    "if",
    "then",
    "else",
    "$ref",
    "$dynamicRef",
    "$recursiveRef",
    "dependentSchemas",
    "dependencies",
    "extends",
];

/// The keywords that check each member of an object on its own.
const ON_MEMBERS: [&str; 3] = ["properties", "patternProperties", "additionalProperties"];

/// Where the part of a split schema checked on each element or member is moved to.
const EACH: &str = "jsonvet-each";

pub(crate) struct Schema {
    compiled: Compiled,
    /// For a schema whose elements only `items` checks: the schema without `items`, checked
    /// once on the whole array, and `items` alone, checked on each element. jsonschema collects
    /// every error before handing out the first, so a 10 MB array failing everywhere took 2.0 GB
    /// in one pass; one element at a time, it holds at most one element's errors. Built the
    /// first time a document needs it, as its parts compile the schema's regexes again, so a
    /// file whose documents all pass a `linear` schema never pays for that.
    items: OnceLock<Option<Split>>,
    /// The same for an object whose members only `properties`, `patternProperties` and
    /// `additionalProperties` check, each member checked as an object of its own.
    members: OnceLock<Option<Split>>,
    /// Whether every `$ref` in the schema points into one of [`NOT_CHECKS`] at the root, as
    /// [`split`] needs.
    kept: bool,
    /// `{"pattern": p}` for each regex in the schema tried on keys: `patternProperties` and a
    /// `pattern` under `propertyNames`, to find the keys a regex error on an object is about.
    /// Empty for a `linear` schema, which has no such errors.
    key_patterns: Regexes,
    /// `{"pattern": p}` for each `pattern` in the schema, to name the one a regex error on a
    /// string is about when its schema path does not. Empty for a `linear` schema.
    string_patterns: Regexes,
    /// Whether every regex the schema uses compiles for the `regex` crate, which runs in linear
    /// time, so no match stops at [`BACKTRACK_LIMIT`]. Such a schema is built with it alone.
    linear: bool,
    /// For a schema the project picked, whose errors quote nothing from it (ADR 0012).
    quiet: Option<Quiet>,
}

/// What a quiet schema's errors say instead of its text: its name, and where in it each keyword
/// that holds such text is, as line and column by schema path.
struct Quiet {
    name: String,
    places: HashMap<String, (usize, usize)>,
    /// The root's base URI without a fragment. A schema path is relative to the nearest `$id`,
    /// so `places` holds only for errors whose keyword resolves against this.
    base: Option<String>,
}

/// The keywords whose values a jsonschema error message can quote, and those whose members' can.
/// Every other keyword's errors quote only the value checked, a type or a known format name.
const QUOTED: [&str; 21] = [
    "const",
    "enum",
    "pattern",
    "required",
    "not",
    "maximum",
    "minimum",
    "exclusiveMaximum",
    "exclusiveMinimum",
    "maxItems",
    "minItems",
    "maxLength",
    "minLength",
    "maxProperties",
    "minProperties",
    "multipleOf",
    "$ref",
    "$dynamicRef",
    "$recursiveRef",
    "dependentRequired",
    "dependencies",
];
const QUOTED_MEMBERS: [&str; 2] = ["dependentRequired", "dependencies"];

/// The keywords whose members are named by the schema's author, not keywords themselves.
const NAMES: [&str; 6] = [
    "properties",
    "patternProperties",
    "$defs",
    "definitions",
    "dependentSchemas",
    "dependencies",
];

impl Quiet {
    /// The places of the keywords in [`QUOTED`] in `schema`, found in its `events`, with the
    /// line and column of each from `report`.
    fn new(name: &str, schema: &Value, tree: &Tree<'_>, report: &jsonvet::Report<'_>) -> Quiet {
        let mut targets = Vec::new();
        quoted(schema, &mut Vec::new(), None, &mut targets);
        let places = tree
            .place(&targets)
            .into_iter()
            .zip(targets)
            .map(|((offset, _), (path, _))| {
                let at = report.location(offset);
                let mut pointer = String::new();
                for segment in path {
                    pointer.push('/');
                    pointer.push_str(&segment.replace('~', "~0").replace('/', "~1"));
                }
                (pointer, (at.line, at.column))
            })
            .collect();
        Quiet {
            name: name.to_owned(),
            places,
            base: limits::base(schema),
        }
    }

    /// `error`'s message without text from the schema, unless its kind quotes none: the keyword
    /// it fails, and where that is in the schema if known. For the part of a split schema checked
    /// on each element or member, `moved` is where that part came from.
    fn message(
        &self,
        error: &ValidationError<'_>,
        moved: Option<&str>,
        node: Option<Nd<'_>>,
    ) -> String {
        use ValidationErrorKind as K;
        match error.kind() {
            // The error inside is about a name, not the value at the path.
            K::PropertyNames { error } => return self.message(error, moved, None),
            K::AdditionalItems { .. }
            | K::AdditionalProperties { .. }
            | K::AnyOf { .. }
            | K::OneOfMultipleValid { .. }
            | K::OneOfNotValid { .. }
            | K::Contains
            | K::ContentEncoding { .. }
            | K::ContentMediaType { .. }
            | K::FalseSchema
            | K::Format { .. }
            | K::FromUtf8 { .. }
            | K::Type { .. }
            | K::UnevaluatedItems { .. }
            | K::UnevaluatedProperties { .. }
            | K::UniqueItems => return message_at(error, node),
            K::BacktrackLimitExceeded { .. }
            | K::RegexEngineFailure { .. }
            | K::Constant { .. }
            | K::Custom { .. }
            | K::Enum { .. }
            | K::ExclusiveMaximum { .. }
            | K::ExclusiveMinimum { .. }
            | K::Maximum { .. }
            | K::Minimum { .. }
            | K::MaxItems { .. }
            | K::MaxLength { .. }
            | K::MaxProperties { .. }
            | K::MinItems { .. }
            | K::MinLength { .. }
            | K::MinProperties { .. }
            | K::MultipleOf { .. }
            | K::Not { .. }
            | K::Pattern { .. }
            | K::Required { .. }
            | K::Referencing(_) => {}
        }
        // A custom keyword's name is the schema's own; jsonvet adds none.
        let keyword = match error.kind() {
            K::Custom { .. } => messages::text("schema.custom-keyword"),
            kind => kind.keyword(),
        };
        let path = error.schema_path().as_str();
        let path = match (moved, path.strip_prefix(&format!("/{EACH}"))) {
            (Some(moved), Some(rest)) => Cow::Owned(format!("{moved}{rest}")),
            _ => Cow::Borrowed(path),
        };
        let name = &self.name;
        let at_root = error
            .absolute_keyword_location()
            .is_none_or(|uri| uri.as_str().split('#').next() == self.base.as_deref());
        match self.places.get(path.as_ref()).filter(|_| at_root) {
            Some((line, column)) => messages::fill(
                "schema.value-fails-at",
                &[
                    ("keyword", &keyword),
                    ("path", name),
                    ("line", line),
                    ("column", column),
                ],
            ),
            None => messages::fill(
                "schema.value-fails",
                &[("keyword", &keyword), ("path", name)],
            ),
        }
    }
}

/// The paths in `schema`, under `path`, of the keywords in [`QUOTED`], and of the members of
/// those in [`QUOTED_MEMBERS`], as targets for [`place`]. `parent` is the keyword `schema` is
/// the value of, if any.
fn quoted(
    schema: &Value,
    path: &mut Vec<String>,
    parent: Option<&str>,
    targets: &mut Vec<(Vec<String>, Vec<String>)>,
) {
    let members = parent.is_some_and(|parent| QUOTED_MEMBERS.contains(&parent));
    let names = parent.is_some_and(|parent| NAMES.contains(&parent));
    for (key, member) in children(schema) {
        path.push(key.clone().into_owned());
        if members || (!names && QUOTED.contains(&key.as_ref())) {
            targets.push((path.clone(), Vec::new()));
        }
        // An `enum` or `const` holds values, not schemas, and can be large. A name is no keyword.
        if names || !["enum", "const"].contains(&key.as_ref()) {
            quoted(member, path, (!names).then_some(key.as_ref()), targets);
        }
        path.pop();
    }
}

/// A schema split in two: the part checked on the whole value, and the part checked on each
/// element or member.
struct Split {
    whole: Compiled,
    each: Compiled,
}

/// A validator and the schema it was built from, which its errors' schema paths point into.
struct Compiled {
    validator: Validator<Own>,
    schema: Value,
    /// For the part of a split schema checked on each element or member: the path in the
    /// whole schema that its [`EACH`] stands for.
    moved: Option<&'static str>,
}

impl Compiled {
    /// `value`'s errors, after a quicker check that it has any.
    fn errors<'i>(&'i self, value: Nd<'i>) -> impl Iterator<Item = ValidationError<'i>> {
        let invalid = !self.validator.is_valid(value);
        invalid
            .then(|| self.validator.iter_errors(value))
            .into_iter()
            .flatten()
    }
}

/// The members of an object by key, or the elements of an array by index; nothing for any other
/// value.
fn children(value: &Value) -> impl Iterator<Item = (Cow<'_, str>, &Value)> {
    let members = value.as_object().into_iter().flatten();
    let items = value.as_array().into_iter().flatten().enumerate();
    members
        .map(|(key, member)| (Cow::Borrowed(key.as_str()), member))
        .chain(items.map(|(i, item)| (Cow::Owned(i.to_string()), item)))
}

/// Whether `error` says a regex match ran past [`BACKTRACK_LIMIT`] where its outcome decides
/// the result.
fn backtracked(error: &ValidationError<'_>) -> bool {
    matches!(
        error.kind(),
        ValidationErrorKind::BacktrackLimitExceeded { .. }
    )
}

/// The regex at `schema_path` in `schema`: a `patternProperties` key, or a `pattern`. For a path
/// relative to a subschema's own `$id`, this can be the wrong one, or none.
fn pattern_at(schema: &Value, schema_path: &str) -> Option<String> {
    let segments: Vec<String> = segments(schema_path).collect();
    match segments.as_slice() {
        [.., parent, regex] if parent == "patternProperties" => Some(regex.clone()),
        _ => schema.pointer(schema_path)?.as_str().map(str::to_owned),
    }
}

/// The message for a `what` that could not be matched on within [`BACKTRACK_LIMIT`], naming
/// `regex` if known.
fn costly(what: &str, regex: Option<&str>) -> String {
    let pattern = regex.map_or_else(
        || messages::text("schema.a-pattern").to_owned(),
        |r| messages::fill("schema.the-pattern", &[("regex", &r)]),
    );
    messages::fill(
        &format!("schema.costly.{what}"),
        &[("pattern", &pattern), ("limit", &BACKTRACK_LIMIT)],
    )
}

/// A validator for `schema`, offline, so a `$ref` to anything outside the schema file fails, and
/// whether every regex it uses suits the `regex` crate. Each build compiles every regex it uses,
/// so such a schema is built with that crate, which fancy-regex would hand them to anyway, rather
/// than compiled a second time to find that out.
fn build(schema: &Value) -> (Result<Validator<Own>, ValidationError<'_>>, bool) {
    if let Ok(validator) = options::<Own>(true).build(schema) {
        return (Ok(validator), true);
    }
    (options::<Own>(false).build(schema), false)
}

/// The options a schema is built with: for the `regex` crate if it is `linear`, else [`fancy`].
fn options<F: Json>(linear: bool) -> ValidationOptions<'static, Arc<dyn jsonschema::Retrieve>, F> {
    if !linear {
        return fancy();
    }
    jsonschema::options_for::<F>()
        .offline()
        .with_pattern_options(
            PatternOptions::regex()
                .size_limit(PATTERN_BYTES)
                .dfa_size_limit(PATTERN_BYTES),
        )
}

/// The options for a schema with a regex the `regex` crate cannot compile. fancy-regex
/// backtracks for back-references and lookaround, and its default limit of a million lets one
/// 30-byte string take 30 ms.
fn fancy<F: Json>() -> ValidationOptions<'static, Arc<dyn jsonschema::Retrieve>, F> {
    jsonschema::options_for::<F>()
        .offline()
        .with_pattern_options(
            PatternOptions::fancy_regex()
                .backtrack_limit(BACKTRACK_LIMIT)
                .size_limit(PATTERN_BYTES)
                .dfa_size_limit(PATTERN_BYTES),
        )
}

/// A regex of a schema that is not `linear`, as the schema `{"pattern": p}`, compiled the first
/// time a match past [`BACKTRACK_LIMIT`] needs it named. Compiled when the schema is, each would
/// cost again what the schema's build already did, for nothing unless such a match comes.
struct Regex {
    text: String,
    validator: OnceLock<Option<Validator>>,
}

impl Regex {
    fn validator(&self) -> Option<&Validator> {
        self.validator
            .get_or_init(|| {
                let schema = serde_json::json!({ "pattern": self.text });
                fancy::<jsonschema::json::SerdeJson>().build(&schema).ok()
            })
            .as_ref()
    }
}

/// Regexes in order of their text.
type Regexes = Vec<Arc<Regex>>;

/// The regexes in `schema` tried on keys, and those tried on strings, as [`Schema`] keeps them.
/// One tried on both is one [`Regex`], so it is compiled at most once.
fn regexes<'v>(schema: &'v Value) -> (Regexes, Regexes) {
    let (mut keys, mut strings) = (BTreeSet::new(), BTreeSet::new());
    patterns(schema, false, &mut keys, &mut strings);
    let mut all: HashMap<&'v str, Arc<Regex>> = HashMap::new();
    let mut each = |regexes: BTreeSet<&'v str>| {
        regexes
            .into_iter()
            .map(|regex| {
                let shared = all.entry(regex).or_insert_with(|| {
                    Arc::new(Regex {
                        text: regex.to_owned(),
                        validator: OnceLock::new(),
                    })
                });
                Arc::clone(shared)
            })
            .collect()
    };
    (each(keys), each(strings))
}

/// The regexes in `schema`: those tried on keys, and every `pattern`, tried on strings.
fn patterns<'v>(
    schema: &'v Value,
    names: bool,
    keys: &mut BTreeSet<&'v str>,
    strings: &mut BTreeSet<&'v str>,
) {
    for (key, member) in children(schema) {
        match (key.as_ref(), member) {
            ("patternProperties", Value::Object(regexes)) => {
                keys.extend(regexes.keys().map(String::as_str));
            }
            ("pattern", Value::String(regex)) => {
                strings.insert(regex);
                if names {
                    keys.insert(regex);
                }
            }
            _ => {}
        }
        patterns(member, names || key == "propertyNames", keys, strings);
    }
}

/// A schema error ready to be placed: the path of the value it is about, the keys in that value
/// it is placed at (the first one found), and its message. With `key`, it is about the one key
/// in `keys` itself, and names that member's path.
struct Found {
    path: Vec<String>,
    keys: Vec<String>,
    key: bool,
    message: String,
}

/// The first [`MAX_ERRORS`] errors in a document, and whether there are more.
#[derive(Default)]
struct Errors {
    kept: Vec<Found>,
    more: bool,
}

impl Errors {
    /// Keep each of `found` while there is room, and say whether to look for more.
    fn add(&mut self, found: impl IntoIterator<Item = Found>) -> bool {
        for found in found {
            if self.kept.len() == MAX_ERRORS {
                self.more = true;
                break;
            }
            self.kept.push(found);
        }
        !self.more
    }
}

/// `error`, on the element at `index` if any, as the errors to report: one per key for
/// unexpected properties, up to one more than [`MAX_ERRORS`]; otherwise one.
fn found(
    index: Option<usize>,
    value: Nd<'_>,
    error: &ValidationError<'_>,
    message: impl FnOnce() -> String,
) -> Vec<Found> {
    let path = pointer_path(index, error);
    if let Some(keys) = unexpected(value, error) {
        return keys
            .into_iter()
            .take(MAX_ERRORS + 1)
            .map(|key| Found {
                path: path.clone(),
                message: format!("Additional properties are not allowed ('{key}' was unexpected)"),
                keys: vec![key],
                key: true,
            })
            .collect();
    }
    let keys = match error.kind() {
        ValidationErrorKind::UnevaluatedProperties { unexpected } => unexpected.clone(),
        ValidationErrorKind::PropertyNames { error } => error
            .instance()
            .as_str()
            .map(|key| vec![key.to_owned()])
            .unwrap_or_default(),
        _ => Vec::new(),
    };
    vec![Found {
        path,
        keys,
        key: false,
        message: message(),
    }]
}

/// The keys an `additionalProperties` error is about, to report one error each: those it lists,
/// or every key for `"additionalProperties": false` with no `properties` or `patternProperties`
/// beside it, which jsonschema reports once as a false schema at the object's first value.
fn unexpected(value: Nd<'_>, error: &ValidationError<'_>) -> Option<Vec<String>> {
    match error.kind() {
        ValidationErrorKind::AdditionalProperties { unexpected } => Some(unexpected.clone()),
        ValidationErrorKind::FalseSchema
            if error
                .schema_path()
                .as_str()
                .ends_with("/additionalProperties") =>
        {
            // A `false` under `properties` with that name is about the value itself.
            let path: Vec<String> = segments(error.instance_path().as_str()).collect();
            let object = value.at(path.iter().map(String::as_str))?;
            object.as_object()?;
            (*object.to_value() != **error.instance()).then(|| object.keys())
        }
        _ => None,
    }
}

/// A file's documents checked as their events come in.
struct Checking<'s, 'e> {
    schema: &'s Schema,
    fold: Fold<'e>,
    /// What each document with something to report has to report, in order: its errors, placed
    /// at their values, then a summary if it has more than [`MAX_ERRORS`], or why it is not
    /// checked.
    errors: Vec<(usize, String, bool)>,
}

impl<'e> Checking<'_, 'e> {
    /// Take the file's next event, and check the document it completes, if any.
    fn event(&mut self, event: &Event<'e>) {
        let Some(document) = self.fold.event(event) else {
            return;
        };
        self.document(&document);
        // The next line of JSON Lines builds its tree in this one's vectors.
        self.fold.recycle(document.tree);
    }

    /// Check one complete document.
    fn document(&mut self, document: &fold::Document<'e>) {
        if let Some((offset, reason)) = document.unchecked {
            self.errors.push((
                offset,
                messages::fill("schema.unchecked", &[("reason", &reason)]),
                false,
            ));
            return;
        }
        let found = self.schema.collect(&document.tree);
        if found.kept.is_empty() {
            return;
        }
        let spots = place_found(&document.tree, &found.kept);
        let mut placed: Vec<(usize, String, bool)> = found
            .kept
            .into_iter()
            .zip(spots)
            .map(|(found, (offset, at))| {
                let message = messages::fill(
                    "schema.found-at",
                    &[("message", &found.message), ("at", &at)],
                );
                (offset, cut(message), false)
            })
            .collect();
        // Stable, so errors at one value keep the schema's order.
        placed.sort_by_key(|(offset, ..)| *offset);
        self.errors.append(&mut placed);
        if found.more {
            self.errors.push((
                document.offset,
                messages::text("schema.more").to_owned(),
                true,
            ));
        }
    }
}

/// The message for a `$ref` that points outside the project, if `error` is one; for a `quiet`
/// schema it names only the path of the schema at `name`.
fn outside(error: &ReferencingError, name: &str, quiet: bool) -> Option<String> {
    match error {
        ReferencingError::Unretrievable { .. } if quiet => {
            Some(messages::fill("schema.ref-outside", &[("path", &name)]))
        }
        ReferencingError::Unretrievable { uri, .. } => Some(messages::fill(
            "schema.ref-outside-to",
            &[("path", &name), ("uri", uri)],
        )),
        _ => None,
    }
}

impl Schema {
    /// Read and compile the schema at `path`, in its dialect under `settings`. Any problem
    /// with it is a usage error. A `quiet` one names only the place, never text from the
    /// schema, as for a symlinked config file: a pull request picks a `$schema` or config
    /// schema, which could be a file that holds a secret (ADR 0012). `admit` takes the number of
    /// distinct regexes in it before any is compiled, and may refuse it.
    pub(crate) fn load(
        path: &Path,
        settings: &Settings,
        quiet: bool,
        admit: impl FnOnce(usize) -> Result<(), String>,
    ) -> Result<Schema, String> {
        let name = path.to_string_lossy();
        let text = crate::read_small(path, crate::MAX_SCHEMA_BYTES)
            .map_err(|e| messages::fill("schema.unreadable", &[("path", &name), ("error", &e)]))?;
        Self::load_text(path, &text, settings, quiet, admit)
    }

    /// Compile bounded schema text through the same limits as a schema on disk.
    pub(crate) fn load_text(
        path: &Path,
        text: &str,
        settings: &Settings,
        quiet: bool,
        admit: impl FnOnce(usize) -> Result<(), String>,
    ) -> Result<Schema, String> {
        let name = path.to_string_lossy();
        // jsonschema compiles a schema recursively: a deep one can take gigabytes or the stack.
        let mut config = settings.config_for(&name);
        // A schema is one value, so a JSON Lines dialect set for the documents does not apply.
        if config.dialect() == Dialect::JsonLines
            && Dialect::for_path(path) != Some(Dialect::JsonLines)
        {
            config = settings.config(&name, Dialect::Json5);
        }
        let config = config.max_depth(MAX_SCHEMA_DEPTH);
        let (report, events) = jsonvet::parse(text, &config);
        let at = |offset, problem: &dyn std::fmt::Display| {
            let at = report.location(offset);
            let place: [(&str, &dyn std::fmt::Display); 3] =
                [("path", &name), ("line", &at.line), ("column", &at.column)];
            if quiet {
                return messages::fill("schema.unusable", &place);
            }
            messages::fill(
                "schema.problem",
                &[place[0], place[1], place[2], ("problem", problem)],
            )
        };
        if let Some(problem) = report
            .problems()
            .iter()
            .find(|p| p.severity() == Severity::Error)
        {
            return Err(at(problem.offset(), &messages::problem(problem)));
        }
        let events = events.unwrap_or_default();
        let mut documents: Vec<_> = values::documents(&events).collect();
        if documents.len() != 1 {
            return Err(messages::fill("schema.one-value", &[("path", &name)]));
        }
        let document = documents.swap_remove(0);
        let events = &events[document.events.clone()];
        if let Some((offset, reason)) = document.unchecked {
            return Err(at(offset, &reason));
        }
        let schema = &document.value;
        let tree = || {
            fold::documents(events)
                .next()
                .map(|d| d.tree)
                .unwrap_or_default()
        };
        let outside = |error: &ReferencingError| outside(error, &name, quiet);
        // The same index of `$id`s and anchors jsonschema builds, offline.
        let registry = registry(schema)
            .map_err(|error| outside(&error).unwrap_or_else(|| at(events[0].offset, &error)))?;
        // jsonschema also validates recursively through each `$ref`, so a long chain of them
        // takes the stack or hours, however shallow the schema is.
        let refuse = |over: limits::Over| {
            let target = (over.path.clone(), vec![over.key.clone()]);
            at(tree().place(&[target])[0].0, &over.message())
        };
        let kept = Reach::new(schema).measure(&registry).map_err(refuse)?;
        admit(limits::patterns(schema).map_err(refuse)?)?;
        let (built, linear) = build(schema);
        let error = match built {
            Ok(validator) => {
                let (key_patterns, string_patterns) = if linear {
                    (Vec::new(), Vec::new())
                } else {
                    regexes(schema)
                };
                return Ok(Schema {
                    compiled: Compiled {
                        validator,
                        schema: schema.clone(),
                        moved: None,
                    },
                    items: OnceLock::new(),
                    members: OnceLock::new(),
                    kept,
                    key_patterns,
                    string_patterns,
                    linear,
                    quiet: quiet.then(|| Quiet::new(&name, schema, &tree(), &report)),
                });
            }
            Err(error) => error,
        };
        // A failed `$ref` has no instance path to place it by.
        if let ValidationErrorKind::Referencing(error) = error.kind()
            && let Some(message) = outside(error)
        {
            return Err(message);
        }
        let tree = tree();
        let errors = found(None, tree.root(), &error, String::new);
        let (offset, _) = place_found(&tree, &errors)[0];
        // A regex too large to compile is reported as no regex at all.
        if matches!(error.kind(), ValidationErrorKind::Format { format } if format == "regex") {
            let mb = PATTERN_BYTES >> 20;
            return Err(at(
                offset,
                &messages::fill("schema.regex-too-big", &[("error", &error), ("mb", &mb)]),
            ));
        }
        Err(at(offset, &error))
    }

    /// `text`'s report under `config`, read no deeper than [`SCHEMA_MAX_DEPTH`], and its schema
    /// errors as (offset, message, summary): each document's in order, then a summary if it has
    /// more than [`MAX_ERRORS`]. A text with a syntax error gets none. The values are checked and
    /// their errors placed as the text is read, a document at a time, so its events are never all
    /// held at once.
    pub(crate) fn check<'t>(
        &self,
        text: &'t str,
        config: &Config,
    ) -> (Report<'t>, Vec<(usize, String, bool)>) {
        let config = config.clone().max_depth(SCHEMA_MAX_DEPTH);
        self.check_with(
            |sink| jsonvet::parse_with(text, &config, sink),
            |report| report.problems().iter().any(|p| p.rule() == Rule::Syntax),
            (text, config.dialect()),
        )
    }

    /// The `lines` of a JSON Lines `text`, one part of a split file, checked as [`Schema::check`]
    /// checks a whole text. Each line is a document.
    pub(crate) fn check_lines(
        &self,
        text: &str,
        lines: Range<usize>,
        config: &Config,
    ) -> (jsonvet::Lines, Vec<(usize, String, bool)>) {
        let config = config.clone().max_depth(SCHEMA_MAX_DEPTH);
        self.check_with(
            |sink| jsonvet::parse_lines(text, lines.clone(), &config, Some(sink)),
            jsonvet::Lines::syntax_error,
            (text, config.dialect()),
        )
    }

    /// What `read` gives, checking each event it hands its sink, and the schema errors unless
    /// `syntax_error` says it found one.
    fn check_with<'t, R>(
        &self,
        read: impl FnOnce(&mut dyn FnMut(Event<'t>)) -> R,
        syntax_error: impl FnOnce(&R) -> bool,
        (text, dialect): (&'t str, Dialect),
    ) -> (R, Vec<(usize, String, bool)>) {
        let mut checking = self.checking(text, dialect);
        let first = read(&mut |event| checking.event(&event));
        if syntax_error(&first) {
            return (first, Vec::new());
        }
        (first, checking.errors)
    }

    fn checking<'e>(&self, text: &'e str, dialect: Dialect) -> Checking<'_, 'e> {
        Checking {
            schema: self,
            fold: Fold::new(text, dialect),
            errors: Vec::new(),
        }
    }

    /// The first [`MAX_ERRORS`] errors in `value`, which stop being asked for once there is one
    /// too many.
    fn collect(&self, tree: &Tree<'_>) -> Errors {
        let value = tree.root();
        let mut errors = Errors::default();
        // One pass over the whole document finds a valid one quickest. A regex that can stop at
        // the backtrack limit makes that pass slow instead, as explained below.
        if self.linear && self.compiled.validator.is_valid(value) {
            return errors;
        }
        // Each error is turned into what is reported as it comes, as jsonschema's own holds
        // much of the schema: an `enum`'s values, or every branch's errors for an `anyOf`.
        // A split schema is also checked for validity a part at a time: jsonschema checks a
        // value again for each outcome of a regex match it cannot finish, so one pass over a
        // whole document repeats every costly match in it, past the error cap.
        let parts = if value.as_array().is_some() {
            self.split(false)
        } else if value.as_object().is_some() {
            self.split(true)
        } else {
            None
        };
        match (value.as_array(), value.as_object(), parts) {
            (Some(items), _, Some(Split { whole, each })) => {
                // jsonschema checks `contains` after `items`, and the rest before.
                let mut after = Vec::new();
                for error in whole.errors(value) {
                    let found = self.found(whole, None, value, &error);
                    let keyword = segments(error.schema_path().as_str()).next();
                    if keyword.is_some_and(|k| {
                        ["contains", "minContains", "maxContains"].contains(&k.as_str())
                    }) {
                        after.extend(found);
                    } else if !errors.add(found) {
                        return errors;
                    }
                }
                for (i, item) in items.elements().enumerate() {
                    for error in each.errors(item) {
                        if !errors.add(self.found(each, Some(i), item, &error)) {
                            return errors;
                        }
                    }
                }
                errors.add(after);
            }
            (_, Some(members), Some(Split { whole, each })) => {
                for error in whole.errors(value) {
                    if !errors.add(self.found(whole, None, value, &error)) {
                        return errors;
                    }
                }
                for position in 0..members.len() {
                    let one = value.only(u32::try_from(position).unwrap_or(u32::MAX));
                    for error in each.errors(one) {
                        if !errors.add(self.found(each, None, one, &error)) {
                            return errors;
                        }
                    }
                }
            }
            _ => {
                for error in self.compiled.errors(value) {
                    if !errors.add(self.found(&self.compiled, None, value, &error)) {
                        break;
                    }
                }
            }
        }
        errors
    }

    /// The schema split for arrays, or with `members` for objects, if it can be, built on first
    /// need. Threads checking parts of one file at once share it, and build it at most once.
    fn split(&self, members: bool) -> Option<&Split> {
        let parts = if members { &self.members } else { &self.items };
        parts
            .get_or_init(|| {
                let options = options::<Own>(self.linear);
                split(&self.compiled.schema, self.kept, members, &options)
            })
            .as_ref()
    }

    /// [`found`], except for a regex match past [`BACKTRACK_LIMIT`] that decides the result,
    /// which jsonschema reports once, at the object for a key. That one names its pattern, and
    /// on an object it is one error per key that pattern could not be matched on.
    fn found(
        &self,
        compiled: &Compiled,
        index: Option<usize>,
        value: Nd<'_>,
        error: &ValidationError<'_>,
    ) -> Vec<Found> {
        if !backtracked(error) {
            return found(index, value, error, || {
                let path: Vec<String> = segments(error.instance_path().as_str()).collect();
                let node = value.at(path.iter().map(String::as_str));
                match &self.quiet {
                    Some(quiet) => quiet.message(error, compiled.moved, node),
                    None => message_at(error, node),
                }
            });
        }
        let path = pointer_path(index, error);
        let at = pattern_at(&compiled.schema, error.schema_path().as_str());
        // The pattern at the error's schema path, if it is one of `patterns`; else, as a path
        // relative to a subschema's own `$id` points elsewhere, the first that is costly too.
        let named = |patterns: &[Arc<Regex>], subject: &str| {
            let subject = Value::String(subject.to_owned());
            let known = patterns
                .iter()
                .any(|regex| Some(&regex.text) == at.as_ref());
            patterns
                .iter()
                .filter(|regex| !known || Some(&regex.text) == at.as_ref())
                .find(|regex| {
                    regex
                        .validator()
                        .is_some_and(|v| v.validate(&subject).is_err_and(|e| backtracked(&e)))
                })
                .map(|regex| regex.text.clone())
        };
        // A quiet schema's regex is never named.
        let shown = |regex: Option<String>| regex.filter(|_| self.quiet.is_none());
        let keys: Vec<Found> = match error.instance().as_ref() {
            Value::Object(members) => members
                .keys()
                .filter_map(|key| {
                    let regex = named(&self.key_patterns, key)?;
                    Some(Found {
                        path: path.clone(),
                        message: costly("key", shown(Some(regex)).as_deref()),
                        keys: vec![key.clone()],
                        key: true,
                    })
                })
                .take(MAX_ERRORS + 1)
                .collect(),
            _ => Vec::new(),
        };
        if !keys.is_empty() {
            return keys;
        }
        let message = match error.instance().as_ref() {
            Value::String(string) => costly(
                "string",
                shown(named(&self.string_patterns, string)).as_deref(),
            ),
            _ => costly("value", shown(at.clone()).as_deref()),
        };
        vec![Found {
            path,
            keys: Vec::new(),
            key: false,
            message,
        }]
    }
}

/// `schema` split for its arrays, or with `members` for its objects, if nothing but `items`, or
/// `properties`, `patternProperties` and `additionalProperties`, checks their elements or
/// members, and every `$ref` in it points into one of [`NOT_CHECKS`] at the root (`kept`), as
/// those are kept in both parts. `None` also when either part fails to build: the whole schema
/// is then checked in one pass.
/// NOTE: each part compiles its regexes again, as jsonschema keeps compiled regexes per build, so
/// [`Schema::split`] calls this only once a document needs it; [`limits::patterns`] bounds what
/// that costs.
fn split(
    schema: &Value,
    kept: bool,
    members: bool,
    options: &ValidationOptions<'_, Arc<dyn jsonschema::Retrieve>, Own>,
) -> Option<Split> {
    let all = schema.as_object()?;
    let (moved, also): (&[&str], &[&str]) = if members {
        (&ON_MEMBERS, &["unevaluatedProperties"])
    } else {
        (&["items"], &["prefixItems", "unevaluatedItems"])
    };
    let checks = |key: &&str| all.contains_key(*key);
    if !kept || ON_CHILDREN.iter().chain(also).any(checks) || !moved.iter().any(checks) {
        return None;
    }
    let mut whole = all.clone();
    let mut part = Map::new();
    for key in moved {
        if let Some(value) = whole.remove(*key) {
            part.insert((*key).to_owned(), value);
        }
    }
    let part = match (members, part.remove("items")) {
        // `items` with an array of schemas checks elements by position.
        (false, Some(items)) if items.is_object() || items.is_boolean() => items,
        (false, _) => return None,
        (true, _) => Value::Object(part),
    };
    let mut each: Map<String, Value> = all
        .iter()
        .filter(|(key, _)| NOT_CHECKS.contains(&key.as_str()))
        .map(|(key, value)| (key.clone(), value.clone()))
        .collect();
    each.insert(EACH.to_owned(), part);
    // Under `allOf`, so a draft 7 `$id` beside it still sets the base for the part's `$ref`s.
    each.insert(
        "allOf".to_owned(),
        serde_json::json!([{ "$ref": format!("#/{EACH}") }]),
    );
    let compile = |schema: Map<String, Value>, moved| {
        let schema = Value::Object(schema);
        let validator = options.build(&schema).ok()?;
        Some(Compiled {
            validator,
            schema,
            moved,
        })
    };
    Some(Split {
        whole: compile(whole, None)?,
        each: compile(each, Some(if members { "" } else { "/items" }))?,
    })
}

/// An error's message, quoting the value it is about only when that is short.
#[cfg(test)]
fn message(error: &ValidationError<'_>) -> String {
    message_at(error, None)
}

/// [`message`], told the `node` the error is about if it is known, so that a value too big to
/// quote is not read out of the text just to find that out.
fn message_at(error: &ValidationError<'_>, node: Option<Nd<'_>>) -> String {
    let short = node.map_or_else(|| fits(error.instance()), |node| fits_node(&node));
    if short {
        let message = error.to_string();
        if message.len() <= MAX_MESSAGE {
            return message;
        }
    }
    error.masked().to_string()
}

/// Whether `node` as compact JSON takes [`MAX_MESSAGE`] bytes or fewer, counted as `serde_json`
/// writes it, and stopping at the first byte past that.
fn fits_node(node: &Nd<'_>) -> bool {
    struct Left(usize);
    impl Left {
        fn take(&mut self, n: usize) -> bool {
            self.0.checked_sub(n).map(|rest| self.0 = rest).is_some()
        }

        fn string(&mut self, text: &str) -> bool {
            self.take(2)
                && text.chars().all(|c| {
                    self.take(match c {
                        '"' | '\\' | '\u{8}' | '\u{c}' | '\n' | '\r' | '\t' => 2,
                        c if c < ' ' => 6,
                        c => c.len_utf8(),
                    })
                })
        }

        fn node(&mut self, node: &Nd<'_>) -> bool {
            match node.json_type() {
                JsonType::Null => self.take(4),
                JsonType::Boolean => self.take(if node.as_boolean() == Some(true) {
                    4
                } else {
                    5
                }),
                JsonType::String => node.as_string().is_some_and(|s| self.string(&s)),
                JsonType::Array => node.as_array().is_some_and(|array| {
                    self.take(2 + array.len().saturating_sub(1))
                        && array.elements().all(|item| self.node(&item))
                }),
                JsonType::Object => node.as_object().is_some_and(|object| {
                    self.take(2 + object.len().saturating_sub(1))
                        && object.members().all(|(key, value)| {
                            self.string(key) && self.take(1) && self.node(&value)
                        })
                }),
                _ => node
                    .as_number()
                    .is_some_and(|n| self.take(n.to_string().len())),
            }
        }
    }
    Left(MAX_MESSAGE).node(node)
}

/// Whether `value` as compact JSON takes [`MAX_MESSAGE`] bytes or fewer. Writing stops at the
/// first byte past that.
fn fits(value: &Value) -> bool {
    struct Budget(usize);
    impl std::io::Write for Budget {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            self.0 = self
                .0
                .checked_sub(bytes.len())
                .ok_or(std::io::ErrorKind::WriteZero)?;
            Ok(bytes.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }
    serde_json::to_writer(Budget(MAX_MESSAGE), value).is_ok()
}

/// `message` cut to [`MAX_MESSAGE`] bytes at a character boundary, ending in `...` if cut.
fn cut(mut message: String) -> String {
    if message.len() > MAX_MESSAGE {
        let mut end = MAX_MESSAGE;
        while !message.is_char_boundary(end) {
            end -= 1;
        }
        message.truncate(end);
        message.push_str("...");
    }
    message
}

#[cfg(test)]
mod tests {
    use super::limits::{Reach, registry};
    use super::{Compiled, MAX_MESSAGE, Schema, cut, fits, fits_node, message, split};
    use jsonvet::{Config, Dialect};
    use proptest::prelude::*;
    use serde_json::{Value, json};
    use std::sync::OnceLock;

    use super::fold::documents;
    use super::fold::tests::any_json;

    /// Whether the JSON `text` fits in a message, counted by `fits_node`.
    fn text_fits(text: &str) -> bool {
        let (_, events) = jsonvet::parse(text, &Config::new(Dialect::Json));
        let events = events.unwrap_or_default();
        let document = documents(&events).next().expect("a document");
        fits_node(&document.tree.root())
    }

    #[test]
    fn a_string_is_counted_by_the_bytes_it_is_written_in() {
        // A space takes one byte and the quotes two.
        assert!(text_fits(&format!("\"{}\"", " ".repeat(MAX_MESSAGE - 2))));
        assert!(!text_fits(&format!("\"{}\"", " ".repeat(MAX_MESSAGE - 1))));
        // A control character takes six: \u0001.
        let controls = |n: usize| format!("\"{}\"", "\\u0001".repeat(n));
        assert!(text_fits(&controls((MAX_MESSAGE - 2) / 6)));
        assert!(!text_fits(&controls((MAX_MESSAGE - 2) / 6 + 1)));
    }

    #[test]
    fn every_kind_of_value_is_counted_at_the_bytes_it_is_written_in() {
        let shapes: [fn(&str) -> String; 7] = [
            |p| format!(r#"[true,false,null,"{p}"]"#),
            |p| format!(r#"[[true],[false],[null],["{p}"]]"#),
            |p| format!(r#"{{"a":true,"b":false,"c":null,"d":"{p}"}}"#),
            |p| format!(r#"{{"a":[1,2],"b":{{"c":"{p}"}}}}"#),
            |p| format!(r#"["{p}",true]"#),
            |p| format!(r#"["{p}",-1.5,12]"#),
            |p| format!(r#"{{"{p}":null}}"#),
        ];
        for shape in shapes {
            let base =
                serde_json::to_string(&serde_json::from_str::<Value>(&shape("")).expect("json"))
                    .expect("json")
                    .len();
            let pad = "x".repeat(MAX_MESSAGE - base);
            assert!(text_fits(&shape(&pad)), "{}", shape(&pad));
            assert!(!text_fits(&shape(&format!("{pad}x"))), "{}", shape(&pad));
        }
    }

    #[test]
    fn a_large_nested_value_is_named_not_quoted() {
        let validator = jsonschema::validator_for(&json!({"type": "string"})).expect("a schema");
        let long = "x".repeat(300);
        for instance in [
            json!([{"a": [long.clone()]}]),
            json!({"a": {"b": long.clone()}}),
            json!({ long.clone(): 1 }),
        ] {
            let error = validator.iter_errors(&instance).next().expect("an error");
            assert_eq!(message(&error), "value is not of type \"string\"");
        }
        let small = json!([{"a": [1]}]);
        let error = validator.iter_errors(&small).next().expect("an error");
        assert_eq!(message(&error), "[{\"a\":[1]}] is not of type \"string\"");
    }

    #[test]
    fn a_value_fits_while_its_json_takes_at_most_the_budget() {
        let x = |n| json!("x".repeat(n));
        assert!(fits(&x(MAX_MESSAGE - 2)));
        assert!(!fits(&x(MAX_MESSAGE - 1)));
    }

    #[test]
    fn a_long_message_is_cut_at_a_character_boundary() {
        // `é` takes two bytes, and the one-byte `x` puts the cut inside one.
        let long = format!("x{}", "\u{e9}".repeat(200));
        let message = cut(long.clone());
        assert_eq!(message.len(), MAX_MESSAGE - 1 + "...".len());
        assert!(message.ends_with("\u{e9}..."), "{message}");
        assert_eq!(
            cut(long[..MAX_MESSAGE - 1].to_owned()),
            long[..MAX_MESSAGE - 1]
        );
        let full = "x".repeat(MAX_MESSAGE);
        assert_eq!(cut(full.clone()), full);
    }

    /// Schemas that only `items` checks the elements of, and so are split, then ones that are not.
    fn split_schemas() -> [(Value, bool); 10] {
        [
            (
                json!({"items": {"type": "string"}, "minItems": 2, "uniqueItems": true}),
                true,
            ),
            (
                json!({
                    "items": {"$ref": "#/$defs/p"},
                    "contains": {"type": "null"},
                    "minContains": 2,
                    "$defs": {"p": {"properties": {"a": {"type": "integer"}}, "additionalProperties": false}},
                }),
                true,
            ),
            (
                json!({
                    "$schema": "http://json-schema.org/draft-07/schema#",
                    "$id": "https://example.com/r.json",
                    "items": {"$ref": "#/definitions/n"},
                    "definitions": {"n": {"type": ["array", "integer"], "items": {"$ref": "#/definitions/n"}}},
                }),
                true,
            ),
            (
                json!({"items": {"additionalProperties": false}, "maxItems": 3}),
                true,
            ),
            (json!({"items": false}), true),
            (json!({"items": {"$ref": "#"}, "type": "array"}), false),
            (
                json!({"items": {"anyOf": [{"$ref": "#"}]}, "type": "array"}),
                false,
            ),
            (
                json!({"items": {"type": "string"}, "allOf": [{"items": {"minLength": 1}}]}),
                false,
            ),
            (
                json!({"$schema": "https://json-schema.org/draft/2019-09/schema", "items": [{"type": "string"}]}),
                false,
            ),
            (
                json!({"items": {"type": "string"}, "$defs": {"a": {"$ref": "#/items"}}, "contains": {"$ref": "#/$defs/a"}}),
                false,
            ),
        ]
    }

    /// The schema errors [`Schema::check`] returns.
    type Errors = Vec<(usize, String, bool)>;

    /// `text`'s schema errors under `schema`, checked in one pass and, if it can be, split.
    fn one_pass_and_split(schema: &Value, text: &str) -> (Errors, Option<Errors>) {
        let options = jsonschema::options_for::<crate::schema::Own>();
        let registry = registry(schema).expect("a registry");
        let kept = Reach::new(schema).measure(&registry).is_ok_and(|kept| kept);
        let checked = |items, members| {
            let schema = Schema {
                compiled: Compiled {
                    validator: options.build(schema).expect("a schema"),
                    schema: schema.clone(),
                    moved: None,
                },
                items: OnceLock::from(items),
                members: OnceLock::from(members),
                kept,
                key_patterns: Vec::new(),
                string_patterns: Vec::new(),
                linear: true,
                quiet: None,
            };
            schema.check(text, &Config::new(Dialect::Json)).1
        };
        let items = split(schema, kept, false, &options);
        let members = split(schema, kept, true, &options);
        let split = (items.is_some() || members.is_some()).then(|| checked(items, members));
        (checked(None, None), split)
    }

    #[test]
    fn a_split_schema_reports_what_one_pass_does_past_the_cap() {
        // 150 elements, each failing `items`, beside errors about the whole array.
        let text = format!("[{}]", vec!["{\"a\": 1, \"b\": 1}"; 150].join(","));
        for (schema, splits) in split_schemas() {
            let (one_pass, split) = one_pass_and_split(&schema, &text);
            assert_eq!(split.is_some(), splits, "{schema}");
            if let Some(split) = split {
                assert_eq!(split, one_pass, "{schema}");
            }
        }
    }

    /// Schemas that only `properties`, `patternProperties` and `additionalProperties` check the
    /// members of, and so are split, then ones that are not.
    fn member_schemas() -> [(Value, bool); 7] {
        [
            (
                json!({"properties": {"a": {"type": "string"}, "b": {"const": 1}}, "required": ["c"], "maxProperties": 2}),
                true,
            ),
            (
                json!({"patternProperties": {"^a": {"type": "integer"}}, "additionalProperties": false, "propertyNames": {"maxLength": 2}}),
                true,
            ),
            (
                json!({"additionalProperties": false, "minProperties": 1}),
                true,
            ),
            (
                json!({"additionalProperties": {"$ref": "#/$defs/n"}, "$defs": {"n": {"type": ["object", "null"], "additionalProperties": {"$ref": "#/$defs/n"}}}}),
                true,
            ),
            (
                json!({"properties": {"a": true}, "unevaluatedProperties": false}),
                false,
            ),
            (
                json!({"properties": {"a": {"type": "string"}}, "anyOf": [{"required": ["a"]}]}),
                false,
            ),
            (
                json!({"additionalProperties": {"$ref": "#/properties/a"}, "properties": {"a": {"type": "null"}}}),
                false,
            ),
        ]
    }

    #[test]
    fn a_split_object_schema_reports_as_many_errors_past_the_cap() {
        // 150 members, each failing, beside errors about the whole object. Past the cap, the
        // first 100 are by member, not by keyword.
        let members: Vec<String> = (0..150)
            .map(|i| format!("\"a{i}\": {{\"b\": 1}}"))
            .collect();
        let text = format!("{{{}}}", members.join(","));
        for (schema, splits) in member_schemas() {
            let (one_pass, split) = one_pass_and_split(&schema, &text);
            assert_eq!(split.is_some(), splits, "{schema}");
            if let Some(split) = split {
                assert_eq!(split.len(), one_pass.len(), "{schema}");
                assert_eq!(split.last(), one_pass.last(), "{schema}");
            }
        }
    }

    #[test]
    fn check_lines_places_schema_errors_across_lines() {
        let schema_val = json!({
            "properties": {"a": {"type": "integer"}},
            "required": ["a"]
        });
        let options = jsonschema::options_for::<crate::schema::Own>();
        let schema = Schema {
            compiled: Compiled {
                validator: options.build(&schema_val).expect("a schema"),
                schema: schema_val,
                moved: None,
            },
            items: OnceLock::new(),
            members: OnceLock::new(),
            kept: false,
            key_patterns: Vec::new(),
            string_patterns: Vec::new(),
            linear: true,
            quiet: None,
        };
        // Line 1 and Line 2 fail schema consecutively; Line 3 passes; Line 4 fails.
        let text = "{\"a\": \"bad1\"}\n{\"a\": \"bad2\"}\n{\"a\": 3}\n{\"a\": \"bad4\"}\n";
        let config = Config::new(Dialect::JsonLines);
        let (_, errors) = schema.check_lines(text, 0..text.len(), &config);
        assert_eq!(errors.len(), 3);
        assert_eq!(errors[0].0, 6);
        assert_eq!(errors[1].0, 20);
        assert_eq!(errors[2].0, 43);

        // Subrange starting at line 2 (offset 14) to end of text
        let (_, errors) = schema.check_lines(text, 14..text.len(), &config);
        assert_eq!(errors.len(), 2);
        assert_eq!(errors[0].0, 20);
        assert_eq!(errors[1].0, 43);
    }

    proptest! {
        #[test]
        fn a_tree_fits_when_its_value_does(value in any_json()) {
            let text = serde_json::to_string(&value).unwrap_or_default();
            let (_, events) = jsonvet::parse(&text, &Config::new(Dialect::Json));
            let events = events.unwrap_or_default();
            let document = documents(&events).next().expect("a document");
            prop_assert_eq!(fits_node(&document.tree.root()), fits(&value), "{}", text);
        }
    }

    proptest! {
        #[test]
        fn a_split_object_schema_reports_what_one_pass_does(members in prop::collection::vec(("[ab]{1,2}", any_json()), 0..6)) {
            let object: serde_json::Map<String, Value> = members.into_iter().collect();
            let text = serde_json::to_string(&object).unwrap_or_default();
            for (schema, _) in member_schemas() {
                let (one_pass, split) = one_pass_and_split(&schema, &text);
                if let Some(split) = split {
                    prop_assert_eq!(split, one_pass, "{}", schema);
                }
            }
        }

        #[test]
        fn a_split_schema_reports_what_one_pass_does(items in prop::collection::vec(any_json(), 0..6)) {
            let text = serde_json::to_string(&items).unwrap_or_default();
            for (schema, _) in split_schemas() {
                let (one_pass, split) = one_pass_and_split(&schema, &text);
                if let Some(split) = split {
                    prop_assert_eq!(split, one_pass, "{}", schema);
                }
            }
        }
    }
}