Debian Codegraph @

lib/JSON/Schema/Modern.pm

raw
1 use strict;
2 use warnings;
3 package JSON::Schema::Modern; # git description: v0.649-2-g2ab7326f
4 # vim: set ts=8 sts=2 sw=2 tw=100 et :
5 # ABSTRACT: Validate data against a schema using a JSON Schema
6 # KEYWORDS: JSON Schema validator data validation structure specification
7
8 our $VERSION = '0.650';
9
10 use 5.020; # for fc, unicode_strings features
11 use Moo;
12 use strictures 2;
13 use stable 0.031 'postderef';
14 use experimental 'signatures';
15 no autovivification warn => qw(fetch store exists delete);
16 use if "$]" >= 5.022, experimental => 're_strict';
17 no if "$]" >= 5.031009, feature => 'indirect';
18 no if "$]" >= 5.033001, feature => 'multidimensional';
19 no if "$]" >= 5.033006, feature => 'bareword_filehandles';
20 no if "$]" >= 5.041009, feature => 'smartmatch';
21 no feature 'switch';
22 use Mojo::JSON (); # for JSON_XS, MOJO_NO_JSON_XS environment variables
23 use Carp qw(croak carp);
24 use List::Util 1.55 qw(pairs first uniqint pairmap uniqstr min);
25 use if "$]" < 5.041010, 'List::Util' => 'any';
26 use if "$]" >= 5.041010, experimental => 'keyword_any';
27 use builtin::compat qw(refaddr load_module blessed);
28 use Mojo::URL;
29 use Mojo::File 'path';
30 use Clone 'clone';
31 use File::ShareDir 'dist_dir';
32 use MooX::TypeTiny 0.002002;
33 use Types::Standard 1.016003 qw(Bool Int Str HasMethods Enum InstanceOf HashRef Dict CodeRef Optional Slurpy ArrayRef Undef ClassName Tuple Map);
34 use Digest::MD5 'md5';
35 use Feature::Compat::Try;
36 use JSON::Schema::Modern::Error;
37 use JSON::Schema::Modern::Result;
38 use JSON::Schema::Modern::Document;
39 use JSON::Schema::Modern::Utilities qw(get_type canonical_uri E abort annotate_self jsonp is_type assert_uri local_annotations is_schema json_pointer_type canonical_uri_type core_types_type core_formats_type load_cached_document jsonp_set);
40 use namespace::clean;
41
42 our @CARP_NOT = qw(
43 JSON::Schema::Modern::Document
44 JSON::Schema::Modern::Vocabulary
45 JSON::Schema::Modern::Vocabulary::Applicator
46 JSON::Schema::Modern::Document::OpenAPI
47 OpenAPI::Modern
48 );
49
50 use constant SPECIFICATION_VERSION_DEFAULT => 'draft2020-12';
51 use constant SPECIFICATION_VERSIONS_SUPPORTED => [qw(draft4 draft6 draft7 draft2019-09 draft2020-12)];
52
53 has specification_version => (
54 is => 'ro',
55 isa => Enum(SPECIFICATION_VERSIONS_SUPPORTED),
56 coerce => sub {
57 return $_[0] if any { $_[0] eq $_ } SPECIFICATION_VERSIONS_SUPPORTED->@*;
58 my $real = 'draft'.($_[0]//'');
59 (any { $real eq $_ } SPECIFICATION_VERSIONS_SUPPORTED->@*) ? $real : $_[0];
60 },
61 );
62
63 has output_format => (
64 is => 'ro',
65 isa => Enum(JSON::Schema::Modern::Result->OUTPUT_FORMATS),
66 default => 'basic',
67 );
68
69 has short_circuit => (
70 is => 'ro',
71 isa => Bool,
72 lazy => 1,
73 default => sub { $_[0]->output_format eq 'flag' && !$_[0]->collect_annotations },
74 );
75
76 has max_depth => (
77 is => 'ro',
78 isa => Int,
79 default => 50,
80 );
81
82 sub max_traversal_depth ($self) {
83 carp 'max_traversal_depth is deprecated and could be removed anytime after 2026-05-09; use max_depth instead';
84 $self->max_depth;
85 }
86
87 has validate_formats => (
88 is => 'ro',
89 isa => Bool,
90 lazy => 1,
91 # as specified by https://json-schema.org/draft/<version>/schema#/$vocabulary
92 default => sub { ($_[0]->specification_version//SPECIFICATION_VERSION_DEFAULT) =~ /^draft[467]\z/ ? 1 : 0 },
93 );
94
95 has validate_content_schemas => (
96 is => 'ro',
97 isa => Bool,
98 lazy => 1,
99 # defaults to false in latest versions, as specified by
100 # https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.8.2
101 default => sub { ($_[0]->specification_version//'') eq 'draft7' },
102 );
103
104 has [qw(collect_annotations scalarref_booleans stringy_numbers strict with_defaults)] => (
105 is => 'ro',
106 isa => Bool,
107 );
108
109
110 # { $format_name => { type => ..., sub => ... }, ... }
111 has _format_validations => (
112 is => 'bare',
113 isa => my $format_type = HashRef[Dict[
114 type => core_types_type|ArrayRef[core_types_type],
115 sub => CodeRef,
116 ]],
117 init_arg => 'format_validations',
118 );
119
120 sub _get_format_validation ($self, $format) { ($self->{_format_validations}//{})->{$format} }
121
122 sub add_format_validation ($self, $format, $definition) {
123 return if exists(($self->{_format_validations}//{})->{$format});
124
125 $definition = { type => 'string', sub => $definition } if ref $definition ne 'HASH';
126 $format_type->({ $format => $definition });
127
128 # all core formats are of type string (so far); changing type of custom format is permitted
129 croak "Type for override of format $format does not match original type"
130 if core_formats_type->check($format) and $definition->{type} ne 'string';
131
132 use autovivification 'store';
133 $self->{_format_validations}{$format} = $definition;
134 }
135
136 around BUILDARGS => sub ($orig, $class, @args) {
137 my $args = $class->$orig(@args);
138 croak 'output_format: strict_basic can only be used with specification_version: draft2019-09'
139 if ($args->{output_format}//'') eq 'strict_basic'
140 and ($args->{specification_version}//'') ne 'draft2019-09';
141
142 croak 'collect_annotations cannot be used with specification_version '.$args->{specification_version}
143 if $args->{collect_annotations} and ($args->{specification_version}//'') =~ /^draft[467]\z/;
144
145 $args->{max_depth} = delete $args->{max_traversal_depth} if exists $args->{max_traversal_depth};
146
147 $args->{format_validations} = +{
148 map +($_->[0] => ref $_->[1] eq 'HASH' ? $_->[1] : +{ type => 'string', sub => $_->[1] }),
149 pairs $args->{format_validations}->%*
150 } if $args->{format_validations};
151
152 return $args;
153 };
154
155 my $_isa = sub ($obj, $class) { blessed($obj) && $obj->isa($class) };
156
157 sub add_schema {
158 croak 'insufficient arguments' if @_ < 2;
159 my $self = shift;
160
161 if ($_[0]->$_isa('JSON::Schema::Modern::Document')) {
162 Carp::carp('use of deprecated form of add_schema with document');
163 return $self->add_document($_[0]);
164 }
165
166 # TODO: resolve $uri against $self->base_uri
167 my $uri = !is_schema($_[0]) ? Mojo::URL->new(shift)
168 : $_[0]->$_isa('Mojo::URL') ? shift : Mojo::URL->new;
169
170 croak 'cannot add a schema with a uri with a fragment' if defined $uri->fragment;
171 croak 'insufficient arguments' if not @_;
172
173 if ($_[0]->$_isa('JSON::Schema::Modern::Document')) {
174 Carp::carp('use of deprecated form of add_schema with document');
175 return $self->add_document($uri, $_[0]);
176 }
177
178 # document BUILD will trigger $self->traverse($schema)
179 # Note we do not pass the uri to the document constructor, so resources in that document may still
180 # be relative
181 my $document = JSON::Schema::Modern::Document->new(
182 schema => $_[0],
183 evaluator => $self, # used mainly for traversal during document construction
184 );
185
186 # try to reuse the same document, if the same schema is being added twice:
187 # this results in _add_resource silently ignoring the duplicate add, rather than erroring.
188 my $schema_checksum = $document->_checksum(md5($self->_json_decoder->encode($document->schema)));
189 if (my $existing_doc = first {
190 my $existing_checksum = $_->_checksum
191 // $_->_checksum(md5($self->_json_decoder->encode($_->schema)));
192 $existing_checksum eq $schema_checksum
193 and $_->canonical_uri eq $document->canonical_uri
194 # FIXME: must also check spec version/metaschema_uri/vocabularies
195 } uniqint map $_->{document}, $self->_canonical_resources) {
196 $document = $existing_doc;
197 }
198
199 $self->add_document($uri, $document);
200 }
201
202 sub add_document {
203 croak 'insufficient arguments' if @_ < 2;
204 my $self = shift;
205
206 # TODO: resolve $uri against $self->base_uri
207 my $base_uri = !$_[0]->$_isa('JSON::Schema::Modern::Document') ? Mojo::URL->new(shift)
208 : $_[0]->$_isa('Mojo::URL') ? shift : Mojo::URL->new;
209
210 croak 'cannot add a schema with a uri with a fragment' if defined $base_uri->fragment;
211 croak 'insufficient arguments' if not @_;
212
213 my $document = shift;
214 croak 'wrong document type' if not $document->$_isa('JSON::Schema::Modern::Document');
215
216 # we will never add a document to the resource index if it has errors
217 die JSON::Schema::Modern::Result->new(
218 output_format => $self->output_format,
219 valid => 0,
220 errors => [ $document->errors ],
221 exception => 1,
222 ) if $document->has_errors;
223
224 if (not length $base_uri){
225 foreach my $res_pair ($document->resource_pairs) {
226 my ($uri_string, $doc_resource) = @$res_pair;
227
228 # this might croak if there are duplicates or malformed entries.
229 $self->_add_resource($uri_string => +{ $doc_resource->%*, document => $document });
230 }
231
232 return $document;
233 }
234
235 my @root; # uri_string => resource hash of the resource at path ''
236
237 # document resources are added after resolving each resource against our provided base uri
238 foreach my $res_pair ($document->resource_pairs) {
239 my ($uri_string, $doc_resource) = @$res_pair;
240 $uri_string = Mojo::URL->new($uri_string)->to_abs($base_uri)->to_string;
241
242 my $new_resource = {
243 canonical_uri => Mojo::URL->new($doc_resource->{canonical_uri})->to_abs($base_uri),
244 $doc_resource->%{qw(path specification_version vocabularies)},
245 document => $document,
246 };
247
248 foreach my $anchor (keys (($doc_resource->{anchors}//{})->%*)) {
249 use autovivification 'store';
250 $new_resource->{anchors}{$anchor} = {
251 $doc_resource->{anchors}{$anchor}->%{path},
252 (map +($_->[1] ? @$_ : ()), [ $doc_resource->{anchors}{$anchor}->%{dynamic} ]),
253 canonical_uri => Mojo::URL->new($doc_resource->{anchors}{$anchor}{canonical_uri})->to_abs($base_uri),
254 };
255 }
256
257 # this might croak if there are duplicates or malformed entries.
258 $self->_add_resource($uri_string => $new_resource);
259 @root = ($uri_string => $new_resource) if $new_resource->{path} eq '' and $uri_string !~ /#./;
260 }
261
262 # associate the root resource with the base uri we were provided, if it does not already exist
263 $self->_add_resource($base_uri.'' => $root[1]) if $root[0] ne $base_uri;
264
265 return $document;
266 }
267
268 sub evaluate_json_string ($self, $json_data, $schema, $config_override = {}) {
269 croak 'evaluate_json_string called in void context' if not defined wantarray;
270
271 my $data;
272 try {
273 $data = $self->_json_decoder->decode($json_data)
274 }
275 catch ($e) {
276 return JSON::Schema::Modern::Result->new(
277 output_format => $self->output_format,
278 valid => 0,
279 exception => 1,
280 errors => [
281 JSON::Schema::Modern::Error->new(
282 depth => 0,
283 mode => 'traverse',
284 keyword => undef,
285 keyword_location => '',
286 error => $e,
287 )
288 ],
289 );
290 }
291
292 return $self->evaluate($data, $schema, $config_override);
293 }
294
295 # this is called whenever we need to walk a document for something.
296 # for now it is just called when a ::Document object is created, to verify the integrity of the
297 # schema structure, to identify the metaschema (via the $schema keyword), and to extract all
298 # embedded resources via $id and $anchor keywords within.
299 # Returns the internal $state object accumulated during the traversal.
300 sub traverse ($self, $schema_reference, $config_override = {}) {
301 my %overrides = %$config_override;
302 delete @overrides{qw(callbacks initial_schema_uri metaschema_uri traversed_keyword_path specification_version skip_ref_checks)};
303 croak join(', ', sort keys %overrides), ' not supported as a config override in traverse'
304 if keys %overrides;
305
306 # Note: the starting position is not guaranteed to be at the root of the $document,
307 # nor is the fragment portion of this uri necessarily empty
308 my $initial_uri = Mojo::URL->new($config_override->{initial_schema_uri} // ());
309 my $initial_path = $config_override->{traversed_keyword_path} // '';
310 my $spec_version = $config_override->{specification_version} // $self->specification_version // SPECIFICATION_VERSION_DEFAULT;
311
312 croak 'traversed_keyword_path must be a json pointer' if $initial_path !~ m{^(?:/|\z)};
313
314 if (length(my $uri_path = $initial_uri->fragment)) {
315 croak 'initial_schema_uri fragment must be a json pointer' if $uri_path !~ m{^/};
316
317 croak 'traversed_keyword_path does not match initial_schema_uri path fragment'
318 if substr($initial_path, -length($uri_path)) ne $uri_path;
319 }
320
321 my $state = {
322 depth => 0,
323 data_path => '', # this never changes since we don't have an instance yet
324 initial_schema_uri => $initial_uri, # the canonical URI as of the start of this method or last $id
325 traversed_keyword_path => $initial_path, # the accumulated traversal path as of the start or last $id
326 keyword_path => '', # the rest of the path, since the start of this method or last $id
327 specification_version => $spec_version,
328 errors => [],
329 identifiers => {},
330 subschemas => [],
331 $config_override->{skip_ref_checks} ? () : (references => []),
332 callbacks => $config_override->{callbacks} // {},
333 evaluator => $self,
334 traverse => 1,
335 };
336
337 my $valid = 1;
338
339 try {
340 # determine the initial value of specification_version and vocabularies, so we have something to start
341 # with in _traverse_subschema().
342 # a subsequent "$schema" keyword can still change these values, and it is always processed
343 # first, so the override is skipped if the keyword exists in the schema
344 $state->{metaschema_uri} =
345 (ref $schema_reference eq 'HASH' && exists $schema_reference->{'$schema'} ? undef
346 : $config_override->{metaschema_uri}) // $self->METASCHEMA_URIS->{$spec_version};
347
348 if (my $metaschema_info = $self->_get_metaschema_vocabulary_classes($state->{metaschema_uri})) {
349 $state->@{qw(specification_version vocabularies)} = @$metaschema_info;
350 }
351 else {
352 # metaschema has not been processed for vocabularies yet...
353
354 die 'something went wrong - cannot get metaschema data for '.$state->{metaschema_uri}
355 if not $config_override->{metaschema_uri};
356
357 # use the Core vocabulary to set metaschema info via the '$schema' keyword implementation
358 $valid = $self->_get_metaschema_vocabulary_classes($self->METASCHEMA_URIS->{$spec_version})->[1][0]
359 ->_traverse_keyword_schema({ '$schema' => $state->{metaschema_uri}.'' }, $state);
360 }
361
362 $valid = $self->_traverse_subschema($schema_reference, $state) if $valid and not $state->{errors}->@*;
363 die 'result is false but there are no errors' if not $valid and not $state->{errors}->@*;
364 die 'result is true but there are errors' if $valid and $state->{errors}->@*;
365 }
366 catch ($e) {
367 if ($e->$_isa('JSON::Schema::Modern::Result')) {
368 push $state->{errors}->@*, $e->errors;
369 }
370 elsif ($e->$_isa('JSON::Schema::Modern::Error')) {
371 # note: we should never be here, since traversal subs are no longer fatal
372 push $state->{errors}->@*, $e;
373 }
374 else {
375 E({ %$state, exception => 1 }, 'EXCEPTION: '.$e);
376 }
377 }
378
379 return $state;
380 }
381
382 # the actual runtime evaluation of the schema against input data.
383 sub evaluate ($self, $data, $schema_reference, $config_override = {}) {
384 croak 'evaluate called in void context' if not defined wantarray;
385
386 my %overrides = %$config_override;
387 delete @overrides{qw(validate_formats validate_content_schemas short_circuit collect_annotations scalarref_booleans stringy_numbers strict with_defaults callbacks data_path traversed_keyword_path _strict_schema_data)};
388 croak join(', ', sort keys %overrides), ' not supported as a config override in evaluate'
389 if keys %overrides;
390
391 my $state = {
392 data_path => $config_override->{data_path} // '',
393 traversed_keyword_path => $config_override->{traversed_keyword_path} // '', # the accumulated path as of the start of evaluation or last $id or $ref
394 initial_schema_uri => Mojo::URL->new, # the canonical URI as of the start of evaluation or last $id or $ref
395 keyword_path => '', # the rest of the path, since the start of evaluation or last $id or $ref
396 errors => [],
397 depth => 0,
398 };
399
400 $state->{data} = jsonp_set('', $state->{data_path}, ref $data ? clone($data) : $data);
401
402 my $valid;
403 try {
404 if (is_schema($schema_reference)) {
405 # traverse is called via add_schema -> ::Document->new -> ::Document->BUILD
406 $schema_reference = $self->add_schema($schema_reference)->canonical_uri;
407 }
408 elsif (ref $schema_reference and not $schema_reference->$_isa('Mojo::URL')) {
409 abort($state, 'invalid schema type: %s', get_type($schema_reference));
410 }
411
412 my $schema_info = $self->_fetch_from_uri($schema_reference);
413 abort($state, 'EXCEPTION: unable to find resource "%s"', $schema_reference)
414 if not $schema_info;
415
416 abort($state, 'EXCEPTION: "%s" is not a schema', $schema_reference)
417 if not $schema_info->{document}->get_entity_at_location($schema_info->{document_path});
418
419 $state = +{
420 %$state,
421 initial_schema_uri => $schema_info->{canonical_uri}, # the canonical URI as of the start of evaluation, or last $id or $ref
422 $schema_info->%{qw(document specification_version vocabularies)},
423 dynamic_scope => [ $schema_info->{canonical_uri}->clone->fragment(undef) ],
424 annotations => [],
425 seen => {},
426 callbacks => $config_override->{callbacks} // {},
427 evaluator => $self,
428 (map do {
429 my $val = $config_override->{$_} // $self->$_;
430 defined $val ? ($_ => $val) : ()
431 # note: this is a subset of the allowed overrides defined above
432 }, qw(validate_formats validate_content_schemas short_circuit collect_annotations scalarref_booleans stringy_numbers strict)),
433 $config_override->{with_defaults} // $self->with_defaults ? (defaults => {}) : (),
434 };
435
436 # this hash will be added to at each level of schema evaluation
437 $state->{seen_data_properties} = {} if $config_override->{_strict_schema_data};
438
439 # we're going to set collect_annotations during evaluation when we see an unevaluated* keyword
440 # (or for object data when the _strict_schema_data configuration is set),
441 # but after we pass to a new data scope we'll clear it again.. unless we've got the config set
442 # globally for the entire evaluation, so we store that value in a high bit.
443 $state->{collect_annotations} = ($state->{collect_annotations}//0) << 8;
444
445 $valid = $self->_evaluate_subschema($data, $schema_info->{schema}, $state);
446 warn 'result is false but there are no errors' if not $valid and not $state->{errors}->@*;
447 warn 'result is true but there are errors' if $valid and $state->{errors}->@*;
448 }
449 catch ($e) {
450 if ($e->$_isa('JSON::Schema::Modern::Result')) {
451 return $e;
452 }
453 elsif ($e->$_isa('JSON::Schema::Modern::Error')) {
454 push $state->{errors}->@*, $e;
455 }
456 else {
457 $valid = E({ %$state, exception => 1 }, 'EXCEPTION: '.$e);
458 }
459 }
460
461 if ($state->{seen_data_properties}) {
462 my %unknown_keywords;
463 foreach my $property (sort grep !$state->{seen_data_properties}{$_},
464 keys $state->{seen_data_properties}->%*) {
465 my ($parent, $keyword) = ($property =~ m{^(.*)/([^/]*)\z});
466 push(($unknown_keywords{$parent}//=[])->@*, $keyword);
467 }
468
469 foreach my $parent (sort keys %unknown_keywords) {
470 $valid = E({ %$state, data_path => $parent },
471 'unknown keyword%s seen in schema: %s', $unknown_keywords{$parent}->@* > 1 ? 's' : '',
472 join(', ', sort $unknown_keywords{$parent}->@*));
473 }
474 }
475
476 die 'evaluate validity inconsistent with error count' if $valid xor !$state->{errors}->@*;
477
478 return JSON::Schema::Modern::Result->new(
479 output_format => $self->output_format,
480 valid => $valid,
481 $valid
482 # strip annotations from result if user didn't explicitly ask for them
483 ? ($config_override->{collect_annotations} // $self->collect_annotations
484 ? (annotations => $state->{annotations}) : ())
485 : (errors => $state->{errors}),
486 $state->{defaults} ? (defaults => $state->{defaults}) : (),
487 data => $state->{data},
488 );
489 }
490
491 sub validate_schema ($self, $schema, $config_override = {}) {
492 croak 'validate_schema called in void context' if not defined wantarray;
493
494 my $metaschema_uri = ref $schema eq 'HASH' && $schema->{'$schema'} ? $schema->{'$schema'}
495 : $self->METASCHEMA_URIS->{$self->specification_version // $self->SPECIFICATION_VERSION_DEFAULT};
496
497 my $result = $self->evaluate($schema, $metaschema_uri,
498 {
499 %$config_override,
500 $self->strict || $config_override->{strict} ? (_strict_schema_data => 1) : (),
501 validate_formats => 1,
502 });
503
504 return $result if not $result->valid;
505
506 # the traversal pass will validate all constraints that weren't handled by the metaschema
507 my $state = $self->traverse($schema);
508 return JSON::Schema::Modern::Result->new(
509 output_format => $self->output_format,
510 valid => 0,
511 errors => $state->{errors},
512 ) if $state->{errors}->@*;
513
514 return $result; # valid: true
515 }
516
517 sub get ($self, $uri_reference) {
518 if (wantarray) {
519 my $schema_info = $self->_fetch_from_uri($uri_reference);
520 return if not $schema_info;
521 my $subschema = ref $schema_info->{schema} ? clone($schema_info->{schema}) : $schema_info->{schema};
522 return ($subschema, $schema_info->{canonical_uri});
523 }
524 else { # abridged version of _fetch_from_uri
525 $uri_reference = Mojo::URL->new($uri_reference) if not ref $uri_reference;
526 my $fragment = $uri_reference->fragment;
527 my $resource = $self->_get_or_load_resource($uri_reference->clone->fragment(undef));
528 return if not $resource;
529
530 my $schema;
531 if (not length($fragment) or $fragment =~ m{^/}) {
532 $schema = $resource->{document}->get($resource->{path}.($fragment//''));
533 }
534 else { # we are following a URI with a plain-name fragment
535 return if not my $subresource = ($resource->{anchors}//{})->{$fragment};
536 $schema = $resource->{document}->get($subresource->{path});
537 }
538 return ref $schema ? clone($schema) : $schema;
539 }
540 }
541
542 sub get_document ($self, $uri_reference) {
543 my $schema_info = $self->_fetch_from_uri($uri_reference);
544 return if not $schema_info;
545 return $schema_info->{document};
546 }
547
548 # defined lower down:
549 # sub add_media_type ($self, $media_type, $sub) { ... }
550 # sub get_media_type ($self, $media_type) { ... }
551 # sub add_encoding ($self, $encoding, $sub) { ... }
552 # sub get_encoding ($self, $encoding) { ... }
553 # sub add_vocabulary ($self, $classname) { ... }
554
555 ######## NO PUBLIC INTERFACES FOLLOW THIS POINT ########
556
557 # current spec version => { keyword => undef, or arrayref of alternatives }
558 my %removed_keywords = (
559 'draft4' => {
560 },
561 'draft6' => {
562 id => [ '$id' ],
563 },
564 'draft7' => {
565 id => [ '$id' ],
566 },
567 'draft2019-09' => {
568 id => [ '$id' ],
569 definitions => [ '$defs' ],
570 dependencies => [ qw(dependentSchemas dependentRequired) ],
571 },
572 'draft2020-12' => {
573 id => [ '$id' ],
574 definitions => [ '$defs' ],
575 dependencies => [ qw(dependentSchemas dependentRequired) ],
576 '$recursiveAnchor' => [ '$dynamicAnchor' ],
577 '$recursiveRef' => [ '$dynamicRef' ],
578 additionalItems => [ 'items' ],
579 },
580 );
581
582 # {
583 # $spec_version => {
584 # $vocabulary_class => {
585 # traverse => [ [ $keyword => $subref ], [ ... ] ],
586 # evaluate => [ [ $keyword => $subref ], [ ... ] ],
587 # }
588 # }
589 # }
590 # If we could serialize coderefs, this could be an object attribute;
591 # otherwise, we might as well persist this for the lifetime of the process.
592 our $vocabulary_cache = {};
593
594 sub _traverse_subschema ($self, $schema, $state) {
595 delete $state->@{'keyword', grep /^_/, keys %$state};
596
597 return E($state, 'EXCEPTION: maximum traversal depth (%d) exceeded', $self->max_depth)
598 if $state->{depth}++ > $self->max_depth;
599
600 push $state->{subschemas}->@*, $state->{traversed_keyword_path}.$state->{keyword_path};
601
602 my $schema_type = get_type($schema);
603 return 1 if $schema_type eq 'boolean'
604 and ($state->{specification_version} ne 'draft4'
605 or $state->{keyword_path} =~ m{/(?:additional(?:Items|Properties)|uniqueItems)\z});
606
607 return E($state, 'invalid schema type: %s', $schema_type) if $schema_type ne 'object';
608
609 return 1 if not keys %$schema;
610
611 my $valid = 1;
612 my %unknown_keywords = map +($_ => undef), grep !/^x-/, keys %$schema;
613
614 # we use an index rather than iterating through the lists directly because the lists of
615 # vocabularies and keywords can change after we have started. However, only the Core vocabulary
616 # and $schema keyword can make this change, and they both come first, therefore a simple index
617 # into the list is sufficient.
618 ALL_KEYWORDS:
619 for (my $vocab_index = 0; $vocab_index < $state->{vocabularies}->@*; $vocab_index++) {
620 my $vocabulary = $state->{vocabularies}[$vocab_index];
621 my $keyword_list;
622
623 for (my $keyword_index = 0;
624 $keyword_index < ($keyword_list //= do {
625 use autovivification qw(fetch store);
626 $vocabulary_cache->{$state->{specification_version}}{$vocabulary}{traverse} //= [
627 map [ $_ => $vocabulary->can('_traverse_keyword_'.($_ =~ s/^\$//r)) ],
628 $vocabulary->keywords($state->{specification_version})
629 ];
630 })->@*;
631 $keyword_index++) {
632 my ($keyword, $sub) = $keyword_list->[$keyword_index]->@*;
633 next if not exists $schema->{$keyword};
634
635 # keywords adjacent to $ref are not evaluated before draft2019-09
636 next if $keyword ne '$ref' and exists $schema->{'$ref'} and $state->{specification_version} =~ /^draft[467]\z/;
637
638 delete $unknown_keywords{$keyword};
639 $state->{keyword} = $keyword;
640
641 my $old_spec_version = $state->{specification_version};
642 my $error_count = $state->{errors}->@*;
643
644 if (not $sub->($vocabulary, $schema, $state)) {
645 die 'traverse result is false but there are no errors (keyword: '.$keyword.')'
646 if $error_count == $state->{errors}->@*;
647 $valid = 0;
648 next;
649 }
650 warn 'traverse result is true but there are errors ('.$keyword.': '.$state->{errors}[-1]->error
651 if $error_count != $state->{errors}->@*;
652
653 # a keyword changed the keyword list for this vocabulary; re-fetch the list before continuing
654 undef $keyword_list if $state->{specification_version} ne $old_spec_version;
655
656 if (my $callback = $state->{callbacks}{$keyword}) {
657 $error_count = $state->{errors}->@*;
658
659 if (not $callback->($schema, $state)) {
660 die 'callback result is false but there are no errors (keyword: '.$keyword.')'
661 if $error_count == $state->{errors}->@*;
662 $valid = 0;
663 next;
664 }
665 die 'callback result is true but there are errors (keyword: '.$keyword.')'
666 if $error_count != $state->{errors}->@*;
667 }
668 }
669 }
670
671 delete $state->{keyword};
672
673 if ($self->strict and keys %unknown_keywords) {
674 $valid = E($state, 'unknown keyword%s seen in schema: %s', keys %unknown_keywords > 1 ? 's' : '',
675 join(', ', sort keys %unknown_keywords));
676 }
677
678 # check for previously-supported but now removed keywords
679 foreach my $keyword (sort keys $removed_keywords{$state->{specification_version}}->%*) {
680 next if not exists $schema->{$keyword};
681 my $message ='no-longer-supported "'.$keyword.'" keyword present (at location "'
682 .canonical_uri($state).'")';
683 if (my $alternates = $removed_keywords{$state->{specification_version}}->{$keyword}) {
684 my @list = map '"'.$_.'"', @$alternates;
685 @list = ((map $_.',', @list[0..$#list-1]), $list[-1]) if @list > 2;
686 splice(@list, -1, 0, 'or') if @list > 1;
687 $message .= ': this should be rewritten as '.join(' ', @list);
688 }
689 carp $message;
690 }
691
692 return $valid;
693 }
694
695 sub _evaluate_subschema ($self, $data, $schema, $state) {
696 croak '_evaluate_subschema called in void context' if not defined wantarray;
697
698 # callers created a new $state for us, so we do not propagate upwards changes to depth, traversed
699 # paths; but annotations, errors are arrayrefs so their contents will be shared
700 $state->{dynamic_scope} = [ ($state->{dynamic_scope}//[])->@* ];
701 delete $state->@{'keyword', grep /^_/, keys %$state};
702
703 abort($state, 'EXCEPTION: maximum evaluation depth (%d) exceeded', $self->max_depth)
704 if $state->{depth}++ > $self->max_depth;
705
706 my $schema_type = get_type($schema);
707 return $schema || E($state, 'subschema is false') if $schema_type eq 'boolean';
708
709 # this should never happen, due to checks in traverse
710 abort($state, 'invalid schema type: %s', $schema_type) if $schema_type ne 'object';
711
712 return 1 if not keys %$schema;
713
714 # find all schema locations in effect at this data path + uri combination
715 # if any of them are absolute prefix of this schema location, we are in a loop.
716 my $canonical_uri = canonical_uri($state);
717 my $schema_location = $state->{traversed_keyword_path}.$state->{keyword_path};
718 {
719 use autovivification qw(fetch store);
720 abort($state, 'EXCEPTION: infinite loop detected (same location evaluated twice)')
721 if grep substr($schema_location, 0, length) eq $_,
722 keys $state->{seen}{$state->{data_path}}{$canonical_uri}->%*;
723 $state->{seen}{$state->{data_path}}{$canonical_uri}{$schema_location}++;
724 }
725
726 my $valid = 1;
727 my %unknown_keywords = map +($_ => undef), grep !/^x-/, keys %$schema;
728
729 # set aside annotations collected so far; they are not used in the current scope's evaluation
730 my $parent_annotations = $state->{annotations};
731 $state->{annotations} = [];
732
733 # in order to collect annotations from applicator keywords only when needed, we twiddle the low
734 # bit if we see a local unevaluated* keyword, and clear it again as we move on to a new data path.
735 # We also set it when _strict_schema_data is set, but only for object data instances.
736 $state->{collect_annotations} |=
737 0+((ref $data eq 'ARRAY' && exists $schema->{unevaluatedItems})
738 || ((my $is_object_data = ref $data eq 'HASH')
739 && (exists $schema->{unevaluatedProperties} || !!$state->{seen_data_properties})));
740
741 # set aside defaults collected so far; we need to keep the subschema's defaults separated in
742 # case they must be discarded due to overall invalidity of the subschema
743 my $defaults = $state->{defaults};
744 $state->{defaults} = {} if $state->{defaults};
745
746 # we use an index rather than iterating through the lists directly because the lists of
747 # vocabularies and keywords can change after we have started. However, only the Core vocabulary
748 # and $schema keyword can make this change, and they both come first, therefore a simple index
749 # into the list is sufficient.
750
751 ALL_KEYWORDS:
752 for (my $vocab_index = 0; $vocab_index < $state->{vocabularies}->@*; $vocab_index++) {
753 my $vocabulary = $state->{vocabularies}[$vocab_index];
754 my $keyword_list;
755
756 for (my $keyword_index = 0;
757 $keyword_index < ($keyword_list //= do {
758 use autovivification qw(fetch store);
759 $vocabulary_cache->{$state->{specification_version}}{$vocabulary}{evaluate} //= [
760 map [ $_ => $vocabulary->can('_eval_keyword_'.($_ =~ s/^\$//r)) ],
761 $vocabulary->keywords($state->{specification_version})
762 ];
763 })->@*;
764 $keyword_index++) {
765 my ($keyword, $sub) = $keyword_list->[$keyword_index]->@*;
766 next if not exists $schema->{$keyword};
767
768 # keywords adjacent to $ref are not evaluated before draft2019-09
769 next if $keyword ne '$ref' and exists $schema->{'$ref'} and $state->{specification_version} =~ /^draft[467]\z/;
770
771 delete $unknown_keywords{$keyword};
772 next if not $valid and $state->{short_circuit} and $state->{strict};
773
774 $state->{keyword} = $keyword;
775
776 if ($sub) {
777 my $old_spec_version = $state->{specification_version};
778 my $error_count = $state->{errors}->@*;
779
780 try {
781 if (not $sub->($vocabulary, $data, $schema, $state)) {
782 warn 'evaluation result is false but there are no errors (keyword: '.$keyword.')'
783 if $error_count == $state->{errors}->@*;
784 $valid = 0;
785
786 last ALL_KEYWORDS if $state->{short_circuit} and not $state->{strict};
787 next;
788 }
789
790 warn 'evaluation result is true but there are errors (keyword: '.$keyword.')'
791 if $error_count != $state->{errors}->@*;
792 }
793 catch ($e) {
794 die $e if $e->$_isa('JSON::Schema::Modern::Error');
795 abort($state, 'EXCEPTION: '.$e);
796 }
797
798 # a keyword changed the keyword list for this vocabulary; re-fetch the list before continuing
799 undef $keyword_list if $state->{specification_version} ne $old_spec_version;
800 }
801
802 if (my $callback = ($state->{callbacks}//{})->{$keyword}) {
803 my $error_count = $state->{errors}->@*;
804
805 if (not $callback->($data, $schema, $state)) {
806 warn 'callback result is false but there are no errors (keyword: '.$keyword.')'
807 if $error_count == $state->{errors}->@*;
808 $valid = 0;
809
810 last ALL_KEYWORDS if $state->{short_circuit} and not $state->{strict};
811 next;
812 }
813 warn 'callback result is true but there are errors (keyword: '.$keyword.')'
814 if $error_count != $state->{errors}->@*;
815 }
816 }
817 }
818
819 delete $state->{keyword};
820
821 if ($state->{strict} and keys %unknown_keywords) {
822 abort($state, 'unknown keyword%s seen in schema: %s', keys %unknown_keywords > 1 ? 's' : '',
823 join(', ', sort keys %unknown_keywords));
824 }
825
826 # Note: we can remove all of this entirely and just rely on strict mode when we (eventually!) remove
827 # the traverse phase and replace with evaluate-against-metaschema.
828 if ($state->{seen_data_properties} and $is_object_data) {
829 # record the locations of all local properties
830 $state->{seen_data_properties}{jsonp($state->{data_path}, $_)} |= 0
831 foreach grep !/^x-/, keys %$data;
832
833 my @evaluated_properties = map do {
834 my $keyword = $_->{keyword};
835 (grep $keyword eq $_, qw(properties additionalProperties patternProperties unevaluatedProperties))
836 ? $_->{annotation}->@* : ();
837 }, local_annotations($state);
838
839 # tick off properties that were recognized by this subschema
840 $state->{seen_data_properties}{jsonp($state->{data_path}, $_)} |= 1 foreach @evaluated_properties;
841
842 # weird! the draft4 metaschema doesn't know about '$ref' at all!
843 $state->{seen_data_properties}{$state->{data_path}.'/$ref'} |= 1
844 if exists $data->{'$ref'} and $state->{specification_version} eq 'draft4';
845 }
846
847 if ($valid and $state->{collect_annotations} and $state->{specification_version} !~ /^draft(?:[467]|2019-09)\z/) {
848 annotate_self(+{ %$state, keyword => $_, _unknown => 1 }, $schema)
849 foreach sort keys %unknown_keywords;
850 }
851
852 # only keep new annotations if schema is valid
853 push $parent_annotations->@*, $state->{annotations}->@* if $valid;
854
855 # only keep new defaults if schema is valid
856 $defaults->@{keys $state->{defaults}->%*} = values $state->{defaults}->%*
857 if $valid and $state->{defaults};
858
859 return $valid;
860 }
861
862 has _resource_index => (
863 is => 'bare',
864 isa => Map[my $resource_key_type = Str->where('!/#/'), my $resource_type = Dict[
865 canonical_uri => (InstanceOf['Mojo::URL'])->where(q{not defined $_->fragment}),
866 path => json_pointer_type, # JSON pointer relative to the document root
867 specification_version => my $spec_version_type = Enum(SPECIFICATION_VERSIONS_SUPPORTED),
868 document => InstanceOf['JSON::Schema::Modern::Document'],
869 # the vocabularies used when evaluating instance data against schema
870 vocabularies => ArrayRef[my $vocabulary_class_type = ClassName->where(q{$_->DOES('JSON::Schema::Modern::Vocabulary')})],
871 anchors => Optional[HashRef[Dict[
872 canonical_uri => canonical_uri_type, # equivalent uri with json pointer fragment
873 path => json_pointer_type, # JSON pointer relative to the document root
874 dynamic => Optional[Bool],
875 ]]],
876 Slurpy[HashRef[Undef]], # no other fields allowed
877 ]],
878 );
879
880 sub _get_resource {
881 die 'bad resource: ', $_[1] if $_[1] =~ /#/;
882 ($_[0]->{_resource_index}//{})->{$_[1]}
883 }
884
885 # does not check for duplicate entries, or for malformed uris
886 sub _add_resources_unsafe {
887 use autovivification 'store';
888 $_[0]->{_resource_index}{$resource_key_type->($_->[0])} = $resource_type->($_->[1])
889 foreach pairs @_[1..$#_];
890 }
891 sub _resource_index { ($_[0]->{_resource_index}//{})->%* }
892 sub _canonical_resources { values(($_[0]->{_resource_index}//{})->%*) }
893 sub _resource_pairs { pairs(($_[0]->{_resource_index}//{})->%*) }
894
895 sub _add_resource ($self, @kvs) {
896 foreach my $pair (sort { $a->[0] cmp $b->[0] } pairs @kvs) {
897 my ($canonical_uri, $resource) = @$pair;
898
899 if (my $existing = $self->_get_resource($canonical_uri)) {
900 # we allow overwriting canonical_uri = '' to allow for ad hoc evaluation of schemas that
901 # lack all identifiers altogether, but preserve other resources from the original document
902 if ($canonical_uri ne '') {
903 my @diffs = (
904 ($existing->{path} eq $resource->{path} ? () : 'path'),
905 ($existing->{canonical_uri} eq $resource->{canonical_uri} ? () : 'canonical_uri'),
906 ($existing->{specification_version} eq $resource->{specification_version} ? () : 'specification_version'),
907 (refaddr($existing->{document}) == refaddr($resource->{document}) ? () : 'refaddr'));
908 next if not @diffs;
909 croak 'uri "'.$canonical_uri.'" conflicts with an existing schema resource: documents differ by ',
910 join(', ', @diffs);
911 }
912 }
913 elsif (JSON::Schema::Modern::Utilities::get_schema_filename($canonical_uri)) {
914 croak 'uri "'.$canonical_uri.'" conflicts with an existing cached schema resource';
915 }
916
917 use autovivification 'store';
918 $self->{_resource_index}{$resource_key_type->($canonical_uri)} = $resource_type->($resource);
919 }
920 }
921
922 # $vocabulary uri (not its $id!) => [ specification_version, class ]
923 has _vocabulary_classes => (
924 is => 'bare',
925 isa => HashRef[
926 my $vocabulary_type = Tuple[
927 $spec_version_type,
928 $vocabulary_class_type,
929 ]
930 ],
931 reader => '__vocabulary_classes',
932 lazy => 1,
933 default => sub {
934 +{
935 map do { my $class = $_; pairmap { $a => [ $b, $class ] } $class->vocabulary },
936 map load_module('JSON::Schema::Modern::Vocabulary::'.$_),
937 qw(Core Applicator Validation FormatAssertion FormatAnnotation Content MetaData Unevaluated)
938 }
939 },
940 );
941
942 sub _get_vocabulary_class { $_[0]->__vocabulary_classes->{$_[1]} }
943
944 sub add_vocabulary ($self, $classname) {
945 return if grep $_->[1] eq $classname, values $self->__vocabulary_classes->%*;
946
947 $vocabulary_class_type->(load_module($classname));
948
949 # uri => version, uri => version
950 foreach my $pair (pairs $classname->vocabulary) {
951 my ($uri_string, $spec_version) = @$pair;
952 Str->where(q{my $uri = Mojo::URL->new($_); $uri->is_abs && !defined $uri->fragment})->($uri_string);
953 $spec_version_type->($spec_version);
954
955 croak 'keywords starting with "$" are reserved for core and cannot be used'
956 if grep /^\$/, $classname->keywords;
957
958 $self->{_vocabulary_classes}{$uri_string} = $vocabulary_type->([ $spec_version, $classname ]);
959 }
960 }
961
962 # $schema uri => [ specification_version, [ vocab classes, in evaluation order ] ].
963 has _metaschema_vocabulary_classes => (
964 is => 'bare',
965 isa => HashRef[
966 my $mvc_type = Tuple[
967 $spec_version_type,
968 ArrayRef[$vocabulary_class_type],
969 ]
970 ],
971 reader => '__metaschema_vocabulary_classes',
972 lazy => 1,
973 default => sub {
974 my @modules = map load_module('JSON::Schema::Modern::Vocabulary::'.$_),
975 qw(Core Validation FormatAnnotation Applicator Content MetaData Unevaluated);
976 +{
977 'https://json-schema.org/draft/2020-12/schema' => [ 'draft2020-12', [ @modules ] ],
978 do { pop @modules; () }, # remove Unevaluated
979 'https://json-schema.org/draft/2019-09/schema' => [ 'draft2019-09', [ @modules ] ],
980 'http://json-schema.org/draft-07/schema' => [ 'draft7', [ @modules ] ],
981 do { splice @modules, 4, 1; () }, # remove Content
982 'http://json-schema.org/draft-06/schema' => [ 'draft6', \@modules ],
983 'http://json-schema.org/draft-04/schema' => [ 'draft4', \@modules ],
984 },
985 },
986 );
987
988 sub _get_metaschema_vocabulary_classes { $_[0]->__metaschema_vocabulary_classes->{$_[1] =~ s/#\z//r} }
989 sub _set_metaschema_vocabulary_classes { $_[0]->__metaschema_vocabulary_classes->{$_[1] =~ s/#\z//r} = $mvc_type->($_[2]) }
990 sub __all_metaschema_vocabulary_classes { values $_[0]->__metaschema_vocabulary_classes->%* }
991
992 # translate vocabulary URIs into classes, caching the results (if any)
993 sub _fetch_vocabulary_data ($self, $state, $schema_info) {
994 if (not exists $schema_info->{schema}{'$vocabulary'}) {
995 # "If "$vocabulary" is absent, an implementation MAY determine behavior based on the meta-schema
996 # if it is recognized from the URI value of the referring schema's "$schema" keyword."
997 my $metaschema_uri = $self->METASCHEMA_URIS->{$schema_info->{specification_version}};
998 return $self->_get_metaschema_vocabulary_classes($metaschema_uri)->@*;
999 }
1000
1001 my $valid = 1;
1002 # Core §8.1.2-6: "The "$vocabulary" keyword SHOULD be used in the root schema of any schema
1003 # document intended for use as a meta-schema. It MUST NOT appear in subschemas."
1004 $valid = E($state, '$vocabulary can only appear at the document root') if length $schema_info->{document_path};
1005 $valid = E($state, 'metaschemas must have an $id') if not exists $schema_info->{schema}{'$id'};
1006
1007 return (undef, []) if not $valid;
1008
1009 my @vocabulary_classes;
1010
1011 foreach my $uri (sort keys $schema_info->{schema}{'$vocabulary'}->%*) {
1012 my $class_info = $self->_get_vocabulary_class($uri);
1013 $valid = E({ %$state, _keyword_path_suffix => $uri }, '"%s" is not a known vocabulary', $uri), next
1014 if $schema_info->{schema}{'$vocabulary'}{$uri} and not $class_info;
1015
1016 next if not $class_info; # vocabulary is not known, but marked as false in the metaschema
1017
1018 my ($spec_version, $class) = @$class_info;
1019 $valid = E({ %$state, _keyword_path_suffix => $uri }, '"%s" uses %s, but the metaschema itself uses %s',
1020 $uri, $spec_version, $schema_info->{specification_version}), next
1021 if $spec_version ne $schema_info->{specification_version};
1022
1023 push @vocabulary_classes, $class;
1024 }
1025
1026 @vocabulary_classes = sort {
1027 $a->evaluation_order <=> $b->evaluation_order
1028 || ($a->evaluation_order == 999 ? 0
1029 : ($valid = E($state, '%s and %s have a conflicting evaluation_order', sort $a, $b)))
1030 } @vocabulary_classes;
1031
1032 $valid = E($state, 'the first vocabulary (by evaluation_order) must be Core')
1033 if ($vocabulary_classes[0]//'') ne 'JSON::Schema::Modern::Vocabulary::Core';
1034
1035 my %seen_keyword;
1036 foreach my $class (@vocabulary_classes) {
1037 foreach my $keyword ($class->keywords($schema_info->{specification_version})) {
1038 $valid = E($state, '%s keyword "%s" conflicts with keyword of the same name from %s',
1039 $class, $keyword, $seen_keyword{$keyword})
1040 if $seen_keyword{$keyword};
1041 $seen_keyword{$keyword} = $class;
1042 }
1043 }
1044
1045 return ($schema_info->{specification_version}, $valid ? \@vocabulary_classes : []);
1046 }
1047
1048 # used for determining a default '$schema' keyword where there is none
1049 # these are also normalized as this is how we cache them
1050 use constant METASCHEMA_URIS => {
1051 'draft2020-12' => 'https://json-schema.org/draft/2020-12/schema',
1052 'draft2019-09' => 'https://json-schema.org/draft/2019-09/schema',
1053 'draft7' => 'http://json-schema.org/draft-07/schema',
1054 'draft6' => 'http://json-schema.org/draft-06/schema',
1055 'draft4' => 'http://json-schema.org/draft-04/schema',
1056 };
1057
1058 # for internal use only. files are under share/
1059 use constant _CACHED_METASCHEMAS => {
1060 'https://json-schema.org/draft/2020-12/meta/applicator' => 'draft2020-12/meta/applicator.json',
1061 'https://json-schema.org/draft/2020-12/meta/content' => 'draft2020-12/meta/content.json',
1062 'https://json-schema.org/draft/2020-12/meta/core' => 'draft2020-12/meta/core.json',
1063 'https://json-schema.org/draft/2020-12/meta/format-annotation' => 'draft2020-12/meta/format-annotation.json',
1064 'https://json-schema.org/draft/2020-12/meta/format-assertion' => 'draft2020-12/meta/format-assertion.json',
1065 'https://json-schema.org/draft/2020-12/meta/meta-data' => 'draft2020-12/meta/meta-data.json',
1066 'https://json-schema.org/draft/2020-12/meta/unevaluated' => 'draft2020-12/meta/unevaluated.json',
1067 'https://json-schema.org/draft/2020-12/meta/validation' => 'draft2020-12/meta/validation.json',
1068 'https://json-schema.org/draft/2020-12/output/schema' => 'draft2020-12/output/schema.json',
1069 'https://json-schema.org/draft/2020-12/schema' => 'draft2020-12/schema.json',
1070
1071 'https://json-schema.org/draft/2019-09/meta/applicator' => 'draft2019-09/meta/applicator.json',
1072 'https://json-schema.org/draft/2019-09/meta/content' => 'draft2019-09/meta/content.json',
1073 'https://json-schema.org/draft/2019-09/meta/core' => 'draft2019-09/meta/core.json',
1074 'https://json-schema.org/draft/2019-09/meta/format' => 'draft2019-09/meta/format.json',
1075 'https://json-schema.org/draft/2019-09/meta/meta-data' => 'draft2019-09/meta/meta-data.json',
1076 'https://json-schema.org/draft/2019-09/meta/validation' => 'draft2019-09/meta/validation.json',
1077 'https://json-schema.org/draft/2019-09/output/schema' => 'draft2019-09/output/schema.json',
1078 'https://json-schema.org/draft/2019-09/schema' => 'draft2019-09/schema.json',
1079
1080 # trailing # is omitted because we always cache documents by its canonical (fragmentless) URI
1081 'http://json-schema.org/draft-07/schema' => 'draft7/schema.json',
1082 'http://json-schema.org/draft-06/schema' => 'draft6/schema.json',
1083 'http://json-schema.org/draft-04/schema' => 'draft4/schema.json',
1084 };
1085
1086 # simple runtime-wide cache of metaschema document objects that are sourced from disk
1087 my $metaschema_cache = {};
1088
1089 {
1090 my $share_dir = dist_dir('JSON-Schema-Modern');
1091 JSON::Schema::Modern::Utilities::register_schema($_, $share_dir.'/'._CACHED_METASCHEMAS->{$_})
1092 foreach keys _CACHED_METASCHEMAS->%*;
1093 }
1094
1095 # returns the same as _get_resource
1096 sub _get_or_load_resource ($self, $uri) {
1097 my $resource = $self->_get_resource($uri);
1098 return $resource if $resource;
1099
1100 if (my $document = load_cached_document($self, $uri)) {
1101 return $self->_get_resource($uri);
1102 }
1103
1104 # TODO:
1105 # - load from network or disk
1106
1107 return;
1108 };
1109
1110 # returns information necessary to use a schema found at a particular URI or uri-reference:
1111 # - schema: a schema (which may not be at a document root)
1112 # - canonical_uri: the canonical uri for that schema,
1113 # - document: the JSON::Schema::Modern::Document object that holds that schema
1114 # - document_path: the path relative to the document root for this schema
1115 # - specification_version: the specification version that applies to this schema
1116 # - vocabularies: the vocabularies to use when considering schema keywords
1117 # creates a Document and adds it to the resource index, if not already present.
1118 sub _fetch_from_uri ($self, $uri_reference) {
1119 $uri_reference = Mojo::URL->new($uri_reference) if not ref $uri_reference;
1120
1121 # this is *a* resource that would contain our desired location, but may not be the closest one
1122 my $resource = $self->_get_or_load_resource($uri_reference->clone->fragment(undef));
1123 return if not $resource;
1124
1125 my $fragment = $uri_reference->fragment;
1126 if (not length($fragment) or $fragment =~ m{^/}) {
1127 my $subschema = $resource->{document}->get(my $document_path = $resource->{path}.($fragment//''));
1128 return if not defined $subschema;
1129
1130 my $closest_resource;
1131 if (not length $fragment) { # we already have the canonical resource root
1132 $closest_resource = [ undef, $resource ];
1133 }
1134 else {
1135 # determine the canonical uri by finding the closest schema resource(s)
1136 my $doc_addr = refaddr($resource->{document});
1137 my @closest_resources =
1138 sort { length($b->[1]{path}) <=> length($a->[1]{path}) } # sort by length, descending
1139 grep !length($_->[1]{path}) # document root
1140 || length($document_path)
1141 && $document_path =~ m{^\Q$_->[1]{path}\E(?:/|\z)}, # path is above desired location
1142 grep refaddr($_->[1]{document}) == $doc_addr, # in same document
1143 $self->_resource_pairs;
1144
1145 # now whittle down to all the resources with the same document path as the first candidate
1146 if (@closest_resources > 1) {
1147 # find the resource key that most closely matches the original query uri, by matching prefixes
1148 my $match = $uri_reference.'';
1149 @closest_resources =
1150 sort { _prefix_match_length($b->[0], $match) <=> _prefix_match_length($a->[0], $match) }
1151 grep $_->[1]{path} eq $closest_resources[0]->[1]{path},
1152 @closest_resources;
1153 }
1154
1155 $closest_resource = $closest_resources[0];
1156 }
1157
1158 my $canonical_uri = $closest_resource->[1]{canonical_uri}->clone
1159 ->fragment(substr($document_path, length($closest_resource->[1]{path})));
1160 $canonical_uri->fragment(undef) if not length($canonical_uri->fragment);
1161
1162 return {
1163 schema => $subschema,
1164 canonical_uri => $canonical_uri,
1165 document_path => $document_path,
1166 $closest_resource->[1]->%{qw(document specification_version vocabularies)}, # reference, not copy
1167 };
1168 }
1169 else { # we are following a URI with a plain-name fragment
1170 return if not my $subresource = ($resource->{anchors}//{})->{$fragment};
1171 return {
1172 schema => $resource->{document}->get($subresource->{path}),
1173 canonical_uri => $subresource->{canonical_uri}, # this is *not* the anchor-containing URI
1174 document_path => $subresource->{path},
1175 $resource->%{qw(document specification_version vocabularies)}, # reference, not copy
1176 };
1177 }
1178 }
1179
1180 # given two strings, determines the number of characters in common, starting from the first
1181 # character
1182 sub _prefix_match_length ($x, $y) {
1183 my $len = min(length($x), length($y));
1184 foreach my $pos (0..$len) {
1185 return $pos if substr($x, $pos, 1) ne substr($y, $pos, 1);
1186 }
1187 return $len;
1188 }
1189
1190 use constant _JSON_BACKEND => JSON::Schema::Modern::Utilities::_JSON_BACKEND;
1191
1192 # used for internal encoding as well (when caching serialized schemas)
1193 has _json_decoder => (
1194 is => 'ro',
1195 isa => HasMethods[qw(encode decode)],
1196 lazy => 1,
1197 default => sub { _JSON_BACKEND->new->allow_nonref(1)->canonical(1)->utf8(1)->allow_bignum(1)->convert_blessed(1) },
1198 );
1199
1200 # since media types are case-insensitive, all legacy type names must be casefolded on insertion.
1201 has _media_type => (
1202 is => 'bare',
1203 isa => ArrayRef[my $media_type_type = Str->where(q{$_ eq CORE::fc($_)})],
1204 reader => '__media_type',
1205 lazy => 1,
1206 default => sub ($self) { [] },
1207 );
1208
1209 my ($warn_add_media_type, $warn_get_media_type); # we will warn just once
1210
1211 # deprecated interface
1212 sub add_media_type ($self, $media_type, $decoder) {
1213 $media_type_type->($media_type);
1214
1215 carp '$jsm->add_media_type is deprecated; use the function in JSON::Schema::Modern::Utilities instead' if not $warn_add_media_type++;
1216
1217 # backcompat preservation: add to the global registry, and remove it again when this object goes
1218 # out of scope
1219 JSON::Schema::Modern::Utilities::add_media_type($media_type, $decoder, undef, refaddr $self);
1220 push $self->__media_type->@*, $media_type;
1221 return;
1222 }
1223
1224 sub DESTROY ($self) {
1225 foreach my $media_type (uniqstr $self->__media_type->@*) {
1226 JSON::Schema::Modern::Utilities::delete_media_type($media_type, refaddr $self);
1227 }
1228 }
1229
1230 # deprecated interface; will use global definitions
1231 sub get_media_type ($self, $type) {
1232 carp '$jsm->get_media_type is deprecated; use the function in JSON::Schema::Modern::Utilities instead' if not $warn_get_media_type++;
1233
1234 JSON::Schema::Modern::Utilities::_get_media_type_decoder($type);
1235 }
1236
1237 has _encoding => (
1238 is => 'bare',
1239 isa => HashRef[CodeRef],
1240 reader => '__encoding',
1241 lazy => 1,
1242 default => sub ($self) {
1243 +{
1244 identity => sub ($content_ref, @) { $content_ref },
1245 base64 => sub ($content_ref, @) {
1246 die "invalid characters\n"
1247 if $content_ref->$* =~ m{[^[:alnum:]+/=]}a or $content_ref->$* =~ m{=(?=[^=])};
1248 require MIME::Base64; \ MIME::Base64::decode_base64($content_ref->$*);
1249 },
1250 base64url => sub ($content_ref, @) {
1251 die "invalid characters\n"
1252 if $content_ref->$* =~ m{[^[:alnum:]=_-]}a or $content_ref->$* =~ m{=(?=[^=])};
1253 require MIME::Base64; \ MIME::Base64::decode_base64url($content_ref->$*);
1254 },
1255 };
1256 },
1257 );
1258
1259 sub get_encoding { $_[0]->__encoding->{$_[1]} }
1260 sub add_encoding { $_[0]->__encoding->{$_[1]} = CodeRef->($_[2]) }
1261
1262 # callback hook for Sereal::Encoder
1263 sub FREEZE ($self, $serializer) {
1264 my $data = +{ %$self };
1265 # Cpanel::JSON::XS doesn't serialize: https://github.com/Sereal/Sereal/issues/266
1266 # coderefs can't serialize cleanly and must be re-added by the user.
1267 delete $data->@{qw(_json_decoder _format_validations _media_type _encoding)};
1268 return $data;
1269 }
1270
1271 # callback hook for Sereal::Decoder
1272 sub THAW ($class, $serializer, $data) {
1273 $data->{max_depth} = delete $data->{max_traversal_depth} if exists $data->{max_traversal_depth};
1274 my $self = bless($data, $class);
1275
1276 # load all vocabulary classes, both those used by loaded schemas, as well as all the core modules
1277 load_module($_)
1278 foreach uniqstr(
1279 (map $_->{vocabularies}->@*, $self->_canonical_resources),
1280 (map $_->[1], values $self->__vocabulary_classes->%*));
1281
1282 # populate the global cache from our existing resources (otherwise already-existing resources
1283 # may be loaded from disk again)
1284 foreach my $resource ($self->_canonical_resources) {
1285 JSON::Schema::Modern::Utilities::__populate_cached_document($self, $resource->{canonical_uri}, $resource->{document});
1286
1287 # also update our existing resources from the global cache, to avoid future refaddr errors
1288 load_cached_document($self, $resource->{canonical_uri});
1289 }
1290
1291 return $self;
1292 }
1293
1294 1;
1295
1296 __END__
1297
1298 =pod
1299
1300 =encoding UTF-8
1301
1302 =for stopwords schema subschema metaschema validator evaluator OpenAPI
1303
1304 =head1 NAME
1305
1306 JSON::Schema::Modern - Validate data against a schema using a JSON Schema
1307
1308 =head1 VERSION
1309
1310 version 0.650
1311
1312 I use a linearly-increasing version numbering scheme. No meaning should be
1313 presumed or inferred from the version being less than 1.0.
1314
1315 =head1 SYNOPSIS
1316
1317 use JSON::Schema::Modern;
1318
1319 $js = JSON::Schema::Modern->new(
1320 specification_version => 'draft2020-12',
1321 output_format => 'flag',
1322 ... # other options
1323 );
1324 $result = $js->evaluate($instance_data, $schema_data);
1325
1326 =head1 DESCRIPTION
1327
1328 This module is a fully-compliant L<JSON Schema|https://json-schema.org/> evaluator and
1329 validator, targeting the currently-latest
1330 L<Draft 2020-12|https://json-schema.org/specification-links.html#2020-12>
1331 version of the specification.
1332
1333 =head1 CONSTRUCTOR ARGUMENTS
1334
1335 Unless otherwise noted, these are also available as read-only accessors.
1336
1337 =head2 specification_version
1338
1339 Indicates which version of the JSON Schema specification is used during evaluation. This value is
1340 overridden by the value determined from the C<$schema> keyword in the schema used in evaluation
1341 (when present), or defaults to the latest version (currently C<draft2020-12>).
1342
1343 The use of the C<$schema> keyword in your schema is I<HIGHLY> encouraged to ensure continued correct
1344 operation of your schema. The current default value will not stay the same over time.
1345
1346 May be one of:
1347
1348 =over 4
1349
1350 =item *
1351
1352 L<C<draft2020-12> or C<2020-12>|https://json-schema.org/specification-links.html#2020-12>, corresponding to metaschema C<https://json-schema.org/draft/2020-12/schema>
1353
1354 =item *
1355
1356 L<C<draft2019-09> or C<2019-09>|https://json-schema.org/specification-links.html#2019-09-formerly-known-as-draft-8>, corresponding to metaschema C<https://json-schema.org/draft/2019-09/schema>
1357
1358 =item *
1359
1360 L<C<draft7> or C<7>|https://json-schema.org/specification-links.html#draft-7>, corresponding to metaschema C<http://json-schema.org/draft-07/schema#>
1361
1362 =item *
1363
1364 L<C<draft6> or C<6>|https://json-schema.org/specification-links.html#draft-6>, corresponding to metaschema C<http://json-schema.org/draft-06/schema#>
1365
1366 =item *
1367
1368 L<C<draft4> or C<4>|https://json-schema.org/specification-links.html#draft-4>, corresponding to metaschema C<http://json-schema.org/draft-04/schema#>
1369
1370 =back
1371
1372 =head2 output_format
1373
1374 One of: C<flag>, C<basic>, C<strict_basic>, C<terse>. Defaults to C<basic>.
1375 C<strict_basic> can only be used with C<specification_version = draft2019-09>.
1376 Passed to L<JSON::Schema::Modern::Result/output_format>.
1377
1378 =head2 short_circuit
1379
1380 When true, evaluation will return early in any execution path as soon as the outcome can be
1381 determined, rather than continuing to find all errors or annotations.
1382 This option is safe to use in all circumstances, even in the presence of
1383 C<unevaluatedItems> and C<unevaluatedProperties> keywords: the validation result will not change;
1384 only some errors will be omitted from the result.
1385
1386 Defaults to true when C<output_format> is C<flag>, and false otherwise.
1387
1388 =for Pod::Coverage max_traversal_depth
1389
1390 =head2 max_depth
1391
1392 The maximum number of levels deep a schema evaluation may go before evaluation is halted. This is to
1393 protect against accidental infinite recursion, such as from two subschemas that each reference each
1394 other, or badly-written schemas that could be optimized. Defaults to 50.
1395
1396 =head2 validate_formats
1397
1398 When true, the C<format> keyword will be treated as an assertion, not merely an annotation. Defaults
1399 to true when specification_version is draft4, draft6 or draft7, and false for all other versions, but this may change in the future.
1400
1401 Note that the use of a format that does not have a defined handler will B<not> be interpreted as an
1402 error in this mode; instead, the undefined format will simply be ignored. If you instead want this
1403 to be treated as an evaluation error, you must define a custom schema dialect that uses the
1404 format-assertion vocabulary (available in specification version C<draft2020-12>) and reference it in
1405 your schema with the C<$schema> keyword.
1406
1407 =head2 format_validations
1408
1409 =for stopwords subref
1410
1411 An optional hashref that allows overriding the validation method for formats, or adding new ones.
1412 Overrides to existing formats (see L</Format Validation>)
1413 must be specified in the form of C<< { $format_name => $format_sub } >>, where
1414 the format sub is a subref that takes one argument and returns a boolean result. New formats must
1415 be specified in the form of C<< { $format_name => { type => $type, sub => $format_sub } } >>,
1416 where the type indicates which of the data model types (null, object, array, boolean, string,
1417 or number) the instance value must be for the format validation to be considered.
1418
1419 Not available as an accessor; see L</add_format_validation>.
1420
1421 =head2 validate_content_schemas
1422
1423 When true, the C<contentMediaType> and C<contentSchema> keywords are not treated as pure annotations:
1424 C<contentEncoding> (when present) is used to decode the applied data payload and then
1425 C<contentMediaType> will be used as the media-type for decoding to produce the data payload which is
1426 then applied to the schema in C<contentSchema> for validation. (Note that treating these keywords as
1427 anything beyond simple annotations is contrary to the specification, therefore this option defaults
1428 to false.) The decoded data is also reflected in L<JSON::Schema::Modern::Result/data>.
1429
1430 See L</add_media_type> and L</add_encoding> for adding additional type support.
1431
1432 =for stopwords shhh
1433
1434 Technically only draft4, draft6 and draft7 allow this and drafts 2019-09 and 2020-12 prohibit ever returning the
1435 subschema evaluation results together with their parent schema's results, so shhh. I'm trying to get this
1436 fixed for the next draft.
1437
1438 =head2 collect_annotations
1439
1440 When true, annotations are collected from keywords that produce them, when validation succeeds.
1441 These annotations are available in the returned result (see L<JSON::Schema::Modern::Result>).
1442 Not operational when L</specification_version> is C<draft4>, C<draft6> or C<draft7>.
1443
1444 Defaults to false.
1445
1446 =head2 scalarref_booleans
1447
1448 When true, any value that is expected to be a boolean B<in the instance data> may also be provided
1449 as the scalar references C<\0> or C<\1> (which are serialized as booleans by JSON backends).
1450
1451 Defaults to false.
1452
1453 =head2 stringy_numbers
1454
1455 When true, any value that is expected to be a number or integer B<in the instance data> may also be
1456 expressed as a string. This applies only to the following keywords:
1457
1458 =over 4
1459
1460 =item *
1461
1462 C<type> (where both C<string> and C<number> (and possibly C<integer>) are considered valid)
1463
1464 =item *
1465
1466 C<const> and C<enum> (where the string C<"1"> will match with C<"const": 1>)
1467
1468 =item *
1469
1470 C<uniqueItems> (where strings and numbers are compared numerically to each other, if either or both are numeric)
1471
1472 =item *
1473
1474 C<multipleOf>
1475
1476 =item *
1477
1478 C<maximum>
1479
1480 =item *
1481
1482 C<exclusiveMaximum>
1483
1484 =item *
1485
1486 C<minimum>
1487
1488 =item *
1489
1490 C<exclusiveMinimum>
1491
1492 =item *
1493
1494 C<format> (for formats defined to validate numbers)
1495
1496 =back
1497
1498 This allows you to write a schema like this (which validates a string representing an integer):
1499
1500 type: string
1501 pattern: ^[0-9]$
1502 multipleOf: 4
1503 minimum: 16
1504 maximum: 256
1505
1506 Such keywords are only applied if the value looks like a number, and do not generate a failure
1507 otherwise. Values are determined to be numbers via L<perlapi/looks_like_number>.
1508 This option is only intended to be used for evaluating data from sources that can only be strings,
1509 such as the extracted value of an HTTP header or query parameter, or a value from an XML document.
1510 In the OpenAPI context, it is preferable to use an explicit C<type> keyword in the schema to
1511 indicate the value should be deserialized as a number).
1512
1513 Defaults to false.
1514
1515 =head2 strict
1516
1517 When true, unrecognized keywords are disallowed in schemas (they will cause an immediate abort
1518 in L</traverse> or L</evaluate>), with the exception of keywords starting with C<x->. Note that
1519 this option is expected to become the default behaviour in future versions of JSON Schema.
1520
1521 Defaults to false.
1522
1523 =head2 with_defaults
1524
1525 When true, for any property name referenced by a C<properties> keyword, or array item referenced
1526 by a C<prefixItems> keyword (or the array form of C<items> in earlier specification versions), that
1527 does not exist in the object currently being evaluated, will result in an entry being added to the
1528 C<defaults> property in the result object (see L<JSON::Schema::Modern::Result/defaults>),
1529 indicating that the application may wish to add this default value to their instance data.
1530
1531 Defaults data accumulated in subschemas that are subsequently determined to be invalid are
1532 discarded, with the final results from all subschemas accumulated together in one hash. No attempt
1533 is made to resolve conflicting entries (last one wins).
1534
1535 For example, this data instance:
1536
1537 {
1538 "my_object": {
1539 "alpha": 1,
1540 "gamma": 3
1541 },
1542 "my_array": [
1543 "yellow"
1544 ]
1545 }
1546
1547 evaluated against this schema:
1548
1549 type: object
1550 properties:
1551 my_object:
1552 type: object
1553 properties:
1554 alpha:
1555 type: integer
1556 default: 10
1557 beta:
1558 type: integer
1559 default: 10
1560 gamma:
1561 type: integer
1562 default: 10
1563 my_array:
1564 type: array
1565 prefixItems:
1566 - type: string
1567 default: red
1568 - type: string
1569 default: green
1570
1571 will result in an C<defaults> entry of:
1572
1573 {
1574 '/my_object/beta' => 10,
1575 '/my_array/1' => 'green'
1576 }
1577
1578 This data can be manipulated with L<JSON::Schema::Modern::Utilities/jsonp_set>; it is also available
1579 already populated into the instance data via L<JSON::Schema::Modern::Result/data>.
1580
1581 =head1 METHODS
1582
1583 =for Pod::Coverage BUILDARGS FREEZE THAW
1584 METASCHEMA_URIS SPECIFICATION_VERSIONS_SUPPORTED SPECIFICATION_VERSION_DEFAULT
1585
1586 =head2 evaluate_json_string
1587
1588 $result = $js->evaluate_json_string($data_as_json_string, $schema);
1589 $result = $js->evaluate_json_string($data_as_json_string, $schema, { collect_annotations => 1 });
1590
1591 Evaluates the provided instance data against the known schema document.
1592
1593 The data is in the form of a JSON-encoded string (in accordance with
1594 L<RFC8259|https://datatracker.ietf.org/doc/html/rfc8259>). B<The string is expected to be UTF-8 encoded.>
1595
1596 The schema must be in one of these forms:
1597
1598 =over 4
1599
1600 =item *
1601
1602 a Perl data structure, such as what is returned from a JSON decode operation,
1603
1604 =item *
1605
1606 or a URI string indicating the identity of such a schema.
1607
1608 =back
1609
1610 Optionally, a hashref can be passed as a third parameter which allows changing the values of the
1611 L</short_circuit>, L</collect_annotations>, L</scalarref_booleans>,
1612 L</stringy_numbers>, L</strict>, L</with_defaults>, L</validate_formats>, and/or L</validate_content_schemas>
1613 settings for just this evaluation call.
1614
1615 You can also pass use these keys to alter behaviour (these are generally only used by custom validation
1616 applications that contain embedded JSON Schemas):
1617
1618 =over 4
1619
1620 =item *
1621
1622 C<data_path>: adjusts the effective path of the data instance as of the start of evaluation
1623
1624 =item *
1625
1626 C<traversed_keyword_path>: adjusts the accumulated path as of the start of evaluation (or last C<$id> or C<$ref>)
1627
1628 =item *
1629
1630 C<initial_schema_uri>: adjusts the recorded absolute keyword location of the start of evaluation
1631
1632 =back
1633
1634 The return value is a L<JSON::Schema::Modern::Result> object.
1635
1636 =head2 evaluate
1637
1638 $result = $js->evaluate($instance_data, $schema);
1639 $result = $js->evaluate($instance_data, $schema, { short_circuit => 0 });
1640
1641 Evaluates the provided instance data against the known schema document.
1642
1643 The data is in the form of an unblessed nested Perl data structure representing any type that JSON
1644 allows: null, boolean, string, number, object, array. (See L</Types> below.)
1645
1646 The schema must be in one of these forms:
1647
1648 =over 4
1649
1650 =item *
1651
1652 a Perl data structure, such as what is returned from a JSON decode operation
1653
1654 =item *
1655
1656 or a URI string (or L<Mojo::URL>) indicating the identity of such a schema.
1657
1658 =back
1659
1660 Optionally, a hashref can be passed as a third parameter which allows changing the values of the
1661 L</short_circuit>, L</collect_annotations>, L</scalarref_booleans>,
1662 L</stringy_numbers>, L</strict>, L</with_defaults>, L</validate_formats>, and/or L</validate_content_schemas>
1663 settings for just this evaluation call.
1664
1665 You can also pass use these keys to alter behaviour (these are generally only used by custom validation
1666 applications that contain embedded JSON Schemas):
1667
1668 =over 4
1669
1670 =item *
1671
1672 C<data_path>: adjusts the effective path of the data instance as of the start of evaluation
1673
1674 =item *
1675
1676 C<traversed_keyword_path>: adjusts the accumulated path as of the start of evaluation (or last C<$id> or C<$ref>)
1677
1678 =item *
1679
1680 C<callbacks>: see below
1681
1682 =back
1683
1684 You can pass a series of callback subs to this method, with the keys corresponding to keywords,
1685 which is useful for
1686 identifying various data that are not exposed by annotations.
1687 This feature is experimental and may change in the future.
1688
1689 For example, to find the locations where all C<$ref> keywords are applied B<successfully>:
1690
1691 my @used_ref_at;
1692 $js->evaluate($data, $schema_or_uri, {
1693 callbacks => {
1694 '$ref' => sub ($data, $schema, $state) {
1695 push @used_ref_at, $state->{data_path};
1696 }
1697 },
1698 });
1699
1700 Callbacks are not compatible with L</short_circuit> mode, as some keyword evaluations may be skipped.
1701
1702 The return value of C<evaluate> is a L<JSON::Schema::Modern::Result> object.
1703
1704 =head2 validate_schema
1705
1706 $result = $js->validate_schema($schema);
1707 $result = $js->validate_schema($schema, $config_override);
1708
1709 Evaluates the provided schema as instance data against its metaschema. Accepts C<$schema> and
1710 C<$config_override> parameters in the same form as L</evaluate>.
1711
1712 =head2 traverse
1713
1714 $result = $js->traverse($schema);
1715 $result = $js->traverse($schema, { initial_schema_uri => 'http://example.com' });
1716
1717 Traverses the provided schema without evaluating it against any instance data. Returns the
1718 internal state object accumulated during the traversal, including any identifiers found therein, and
1719 any errors found during parsing. For internal purposes only.
1720
1721 Optionally, a hashref can be passed as a second parameter which alters some
1722 behaviour (these are generally only used by custom validation
1723 applications that contain embedded JSON Schemas):
1724
1725 =over 4
1726
1727 =item *
1728
1729 C<traversed_keyword_path>: adjusts the accumulated path as of the start of evaluation (or last C<$id> or C<$ref>)
1730
1731 =item *
1732
1733 C<initial_schema_uri>: adjusts the absolute keyword location as of the start of evaluation
1734
1735 =item *
1736
1737 C<metaschema_uri>: use the indicated URI as the metaschema
1738
1739 =item *
1740
1741 C<callbacks>: see below
1742
1743 =item *
1744
1745 C<specification_version>: overrides the specification version to be used
1746
1747 =back
1748
1749 You can pass a series of callback subs to this method corresponding to keywords, which is useful for
1750 extracting data from within schemas and skipping properties that may look like keywords but actually
1751 are not (for example C<{"const": {"$ref": "this is not actually a $ref"}}>). This feature is
1752 experimental and is highly likely to change in the future.
1753
1754 For example, to find the resolved targets of all C<$ref> keywords in a schema document:
1755
1756 my @refs;
1757 JSON::Schema::Modern->new->traverse($schema, {
1758 callbacks => {
1759 '$ref' => sub ($schema, $state) {
1760 push @refs, Mojo::URL->new($schema->{'$ref'})
1761 ->to_abs(JSON::Schema::Modern::Utilities::canonical_uri($state));
1762 }
1763 },
1764 });
1765
1766 =head2 add_schema
1767
1768 $js->add_schema($uri => $schema);
1769 $js->add_schema($schema);
1770
1771 Introduces the (unblessed, nested) Perl data structure
1772 representing a JSON Schema to the implementation, registering it under the indicated URI if
1773 provided, and all identifiers found within the document will be resolved against this URI (if
1774 provided) and added as well. C<''> will be used if no other identifier can be found within.
1775
1776 You B<MUST> call C<add_schema> or L</add_document> (below) for any external resources that a schema may reference via C<$ref>
1777 before calling L</evaluate>, other than the standard metaschemas which are loaded from a local cache
1778 as needed.
1779
1780 If you add multiple schemas (either with this method, or implicitly via L</evaluate>) with no root
1781 identifier (either provided explicitly in the method call, or via an C<$id> keyword at the schema
1782 root), all such previous schemas are removed from memory and can no longer be referenced.
1783
1784 If there were errors in the document, will die with these errors;
1785 otherwise returns the L<JSON::Schema::Modern::Document> that contains the added schema. URIs
1786 identified within this document will not be resolved to the provided C<$uri> argument, so you can
1787 re-add the document object again (with L</add_document>, below) using a new base URI if you wish.
1788
1789 =head2 add_document
1790
1791 $js->add_document($uri => $document);
1792 $js->add_document($document);
1793
1794 Makes the L<JSON::Schema::Modern::Document> (or subclass)
1795 object, representing a JSON Schema, available to the evaluator. All identifiers known to the
1796 document are added to the evaluator's resource index; if the C<$uri> argument is provided, those
1797 identifiers are resolved against C<$uri> as they are added.
1798
1799 C<$uri> itself is also added to the resource index, referencing the root of the document itself.
1800
1801 If you add multiple documents (either with this method, or implicitly via C</add_schema> or L</evaluate>) with no root
1802 identifier (either provided explicitly in the method call, or via an C<$id> keyword at the schema
1803 root), all such previous schemas are removed from memory and can no longer be referenced.
1804
1805 If there were errors in the document, this method will die with these errors;
1806 otherwise it returns the L<JSON::Schema::Modern::Document> object.
1807
1808 =head2 add_format_validation
1809
1810 $js->add_format_validation(all_lc => sub ($value) { lc($value) eq $value });
1811
1812 =for comment we are the nine Eleven Deniers
1813
1814 or
1815
1816 $js->add_format_validation(no_nines => { type => 'number', sub => sub ($value) { $value =~ m/^[0-8]+\z/ });
1817
1818 $js->add_format_validation(8bits => { type => 'string', sub => sub ($value) { $value =~ m/^[\x00-\xFF]+\z/ });
1819
1820 Adds support for a custom format. If not supplied, the data type(s) that this format applies to
1821 defaults to string; all values of any other type will automatically be deemed to be valid, and will
1822 not be passed to the subref.
1823
1824 Additionally, you can redefine the definition for any core format (see L</Format Validation>), but
1825 the data type(s) supported by that format may not be changed.
1826
1827 Be careful to not mutate the type of the value while checking it -- for example, if it is a string,
1828 do not apply arithmetic operators to it -- or subsequent type checks on this value may fail.
1829
1830 See the official L<OpenAPI Format Registry|https://spec.openapis.org/registry/format>
1831 for a registry of known and useful formats; for
1832 compatibility reasons, avoid defining a format listed here with different semantics.
1833
1834 Format definitions cannot be overridden with a new definition.
1835
1836 =head2 add_vocabulary
1837
1838 $js->add_vocabulary('My::Custom::Vocabulary::Class');
1839
1840 Makes a custom vocabulary class available to metaschemas that make use of this vocabulary.
1841 as described in the specification at
1842 L<"Meta-Schemas and Vocabularies"|https://json-schema.org/draft/2020-12/json-schema-core.html#rfc.section.8.1>.
1843
1844 The class must compose the L<JSON::Schema::Modern::Vocabulary> role and implement the
1845 L<vocabulary|JSON::Schema::Modern::Vocabulary/vocabulary> and
1846 L<keywords|JSON::Schema::Modern::Vocabulary/keywords> methods, as well as
1847 C<< _traverse_keyword_<keyword name> >> methods for each keyword. C<< _eval_keyword_<keyword name> >>
1848 methods are optional; when not provided, evaluation will always return a true result.
1849
1850 Vocabularies cannot be redefined; subsequent calls to add the same vocabulary will do nothing.
1851
1852 =head2 add_media_type
1853
1854 $js->add_media_type('application/furble' => sub ($content_ref, @) {
1855 return ...; # data representing the deserialized text for Content-Type: application/furble
1856 });
1857
1858 Takes a media-type name and a subref which takes a single scalar reference, which is expected to be
1859 a reference to a string, which might contain wide characters (i.e. not octets), especially when used
1860 in conjunction with L</get_encoding> below. Must return B<a reference to a value of any type> (which is
1861 then dereferenced for the C<contentSchema> keyword).
1862
1863 This interface is B<deprecated> as of version 0.638 and may eventually be removed; use
1864 L<JSON::Schema::Modern::Utilities/add_media_type> instead, which supports defining an encoder as
1865 well, and supports media-type parameters.
1866
1867 =head2 get_media_type
1868
1869 $js->add_media_type('application/furble' => sub { ... }); # as above
1870 my $decoder = $self->get_media_type('application/furble') or die 'cannot find media type decoder';
1871 my $content_ref = $decoder->(\$content_string);
1872
1873 Fetches a decoder sub from the current object's registry for the indicated media type. Lookups are
1874 performed B<without case sensitivity>.
1875
1876 This interface is B<deprecated> as of version 0.638 and may eventually be removed; use
1877 L<JSON::Schema::Modern::Utilities/decode_media_type> instead.
1878
1879 =head2 add_encoding
1880
1881 $js->add_encoding('bloop' => sub ($content_ref, @) {
1882 return \ ...; # data representing the deserialized content for Content-Transfer-Encoding: bloop
1883 });
1884
1885 Takes an encoding name and a subref which takes a single scalar reference, which is expected to be
1886 a reference to a string, which SHOULD be a 7-bit or 8-bit string. Result values MUST be a scalar-reference
1887 to a string (which is then dereferenced for the C<contentMediaType> keyword).
1888
1889 Encoding definitions can be overridden with a new call to C<add_encoding>.
1890
1891 =for stopwords natively
1892
1893 Encodings handled natively are:
1894
1895 =over 4
1896
1897 =item *
1898
1899 C<identity> - passes strings through unchanged
1900
1901 =item *
1902
1903 C<base64> - see L<RFC 4648 §4|https://datatracker.ietf.org/doc/html/rfc4648#section-4>
1904
1905 =item *
1906
1907 C<base64url> - see L<RFC 4648 §5|https://datatracker.ietf.org/doc/html/rfc4648#section-5>
1908
1909 =back
1910
1911 See also L<HTTP::Message/encode>.
1912
1913 =head2 get_encoding
1914
1915 my $decoder = $self->get_encoding('base64') or die 'cannot find encoding decoder';
1916 my $content_ref = $decoder->(\$content_string);
1917
1918 Fetches a decoder sub for the indicated encoding. Incoming values MUST be a reference to an octet
1919 string. Result values will be a scalar-reference to a string, which might be passed to a media_type
1920 decoder (see above).
1921
1922 =head2 get
1923
1924 my $schema = $js->get($uri);
1925 my ($schema, $canonical_uri) = $js->get($uri);
1926
1927 Fetches the Perl data structure represented by the indicated identifier (uri or
1928 uri-reference). When called in list context, the canonical URI of that location is also returned, as
1929 a L<Mojo::URL>. Returns C<undef> if the schema with that URI has not been loaded (or cached).
1930
1931 Note that the data so returned may not be a JSON Schema, if the document encapsulating this location
1932 is a subclass of L<JSON::Schema::Modern::Document> (for example
1933 L<JSON::Schema::Modern::Document::OpenAPI>, which contains addressable locations of various semantic
1934 types).
1935
1936 =head2 get_document
1937
1938 my $document = $js->get_document($uri_reference);
1939
1940 Fetches the L<JSON::Schema::Modern::Document> object (or subclass) that contains the provided
1941 identifier (uri or uri-reference). C<undef> if the schema with that URI has not been loaded (or
1942 cached).
1943
1944 Note: this _does not download a document from the network_. It only fetches the document from the
1945 internal cache in the C<JSON::Schema::Modern> object.
1946
1947 =head1 CACHING
1948
1949 =for stopwords preforking
1950
1951 Very large documents, particularly those used by L<OpenAPI::Modern>, may take a noticeable time to be
1952 loaded and parsed. You can reduce the impact to your preforking application by loading all necessary
1953 documents at startup, and impact can be further reduced by saving objects to cache and then
1954 reloading them (perhaps by using a timestamp or checksum to determine if a fresh reload is needed).
1955
1956 Custom L<format validations|/add_format_validation>, L<media types|/add_media_type> or
1957 L<encodings|/add_encoding> are not serialized, as they are represented by subroutine references, and
1958 will need to be manually added after thawing.
1959
1960 sub get_evaluator (...) {
1961 my $serialized_file = path($filename);
1962 my $schema_file = path($schema_filename);
1963 my $js;
1964 if ($serialized_file->stat->mtime < $schema_file->stat->mtime)) {
1965 $js = JSON::Schema::Modern->new;
1966 $js->add_schema(decode_json($schema_file->slurp_raw)); # your application schema
1967 my $frozen = Sereal::Encoder->new({ freeze_callbacks => 1 })->encode($js);
1968 $serialized_file->spew_raw($frozen);
1969 }
1970 else {
1971 my $frozen = $serialized_file->slurp_raw;
1972 $js = Sereal::Decoder->new->decode($frozen);
1973 }
1974
1975 # add custom format validations, media types and encodings here
1976 $js->add_media_type(...);
1977
1978 return $js;
1979 }
1980
1981 See also L<OpenAPI::Modern/CACHING>.
1982
1983 =head1 LIMITATIONS
1984
1985 =head2 Types
1986
1987 Perl is a more loosely-typed language than JSON. This module delves into a value's internal
1988 representation in an attempt to derive the true "intended" type of the value.
1989 This should not be an issue if data validation is occurring
1990 immediately after decoding a JSON payload, or if the JSON string itself is passed to this module.
1991 If you are having difficulties, make sure you are using Perl's fastest and most trusted and
1992 reliable JSON decoder, L<Cpanel::JSON::XS>.
1993 Other JSON decoders are known to produce data with incorrect data types,
1994 and data from other sources may also be problematic.
1995
1996 For more information, see L<Cpanel::JSON::XS/MAPPING>.
1997
1998 =head2 Format Validation
1999
2000 By default (and unless you specify a custom metaschema with the C<$schema> keyword or
2001 L<JSON::Schema::Modern::Document/metaschema>),
2002 formats are treated only as annotations, not assertions. When L</validate_formats> is
2003 true, strings are also checked against the format as specified in the schema. At present the
2004 following formats are supported for the latest version of the specification
2005 (use of any other formats than these will always evaluate as true,
2006 but remember you can always supply custom format handlers; see L</format_validations> above):
2007
2008 =over 4
2009
2010 =item *
2011
2012 C<date-time>
2013
2014 =item *
2015
2016 C<date>
2017
2018 =item *
2019
2020 C<time>
2021
2022 =item *
2023
2024 C<duration>
2025
2026 =item *
2027
2028 C<email>
2029
2030 =item *
2031
2032 C<idn-email>
2033
2034 =item *
2035
2036 C<hostname>
2037
2038 =item *
2039
2040 C<idn-hostname>
2041
2042 =item *
2043
2044 C<ipv4>
2045
2046 =item *
2047
2048 C<ipv6>
2049
2050 =item *
2051
2052 C<uri>
2053
2054 =item *
2055
2056 C<uri-reference>
2057
2058 =item *
2059
2060 C<iri>
2061
2062 =item *
2063
2064 C<uuid>
2065
2066 =item *
2067
2068 C<json-pointer>
2069
2070 =item *
2071
2072 C<relative-json-pointer>
2073
2074 =item *
2075
2076 C<regex>
2077
2078 =back
2079
2080 A few optional prerequisites are needed for some of these (if the prerequisite is missing,
2081 validation will always succeed, unless draft2020-12 is in use with the Format-Assertion vocabulary
2082 declared in the metaschema, in which case use of the format will produce an error).
2083
2084 =over 4
2085
2086 =item *
2087
2088 C<email> and C<idn-email> require L<Email::Address::XS> version 1.04 (or higher)
2089
2090 =item *
2091
2092 C<hostname> and C<idn-hostname> require L<Data::Validate::Domain> version 0.13 (or higher)
2093
2094 =item *
2095
2096 C<idn-hostname> also requires L<Net::IDN::Encode>
2097
2098 =item *
2099
2100 C<uri> requires L<Data::Validate::URI>
2101
2102 =back
2103
2104 =head2 Specification Compliance
2105
2106 This implementation is now fully specification-compliant (for versions
2107 draft4, draft6, draft7, draft2019-09, draft2020-12).
2108
2109 However, some potentially-useful features are not yet implemented, such as:
2110
2111 =for stopwords Mojolicious
2112
2113 =over 4
2114
2115 =item *
2116
2117 loading schema documents from disk
2118
2119 =item *
2120
2121 loading schema documents from the network
2122
2123 =item *
2124
2125 loading schema documents from a local web application (e.g. L<Mojolicious>)
2126
2127 =item *
2128
2129 additional "official" output formats beyond C<flag>, C<basic>, and C<terse> (L<https://json-schema.org/draft/2020-12/json-schema-core.html#rfc.section.12>)
2130
2131 =back
2132
2133 =head1 SECURITY CONSIDERATIONS
2134
2135 The C<pattern> and C<patternProperties> keywords evaluate regular expressions from the schema,
2136 the C<regex> format validator evaluates regular expressions from the data, and some keywords
2137 in the Validation vocabulary perform floating point operations on potentially-very large numbers.
2138 No effort is taken (at this time) to sanitize the regular expressions for embedded code or
2139 detect potentially pathological constructs that may pose a security risk, either via denial of
2140 service or by allowing exposure to the internals of your application. B<DO NOT USE SCHEMAS FROM
2141 UNTRUSTED SOURCES.>
2142
2143 (In particular, see vulnerability
2144 L<perl5363delta/CVE-2023-47038-Write-past-buffer-end-via-illegal-user-defined-Unicode-property>,
2145 which was fixed in Perl releases 5.34.3, 5.36.3 and 5.38.1.)
2146
2147 =head1 BUNDLED META-SCHEMAS
2148
2149 These specification meta-schemas are bundled with this distribution and loaded as needed:
2150
2151 =over 4
2152
2153 =item *
2154
2155 C<http://json-schema.org/draft-04/schema#>
2156
2157 =item *
2158
2159 C<http://json-schema.org/draft-06/schema#>
2160
2161 =item *
2162
2163 C<http://json-schema.org/draft-07/schema#>
2164
2165 =item *
2166
2167 C<https://json-schema.org/draft/2019-09/schema>
2168
2169 =item *
2170
2171 C<https://json-schema.org/draft/2020-12/schema>
2172
2173 =back
2174
2175 =head1 SEE ALSO
2176
2177 =over 4
2178
2179 =item *
2180
2181 L<json-schema-eval>
2182
2183 =item *
2184
2185 L<https://json-schema.org>
2186
2187 =item *
2188
2189 L<RFC8259: The JavaScript Object Notation (JSON) Data Interchange Format|https://datatracker.ietf.org/doc/html/rfc8259>
2190
2191 =item *
2192
2193 L<RFC6901: JavaScript Object Notation (JSON) Pointer|https://datatracker.ietf.org/doc/html/rfc6901>
2194
2195 =item *
2196
2197 L<RFC3986: Uniform Resource Identifier (URI): Generic Syntax|https://datatracker.ietf.org/doc/html/rfc3986> dependencies and faster evaluation
2198
2199 =item *
2200
2201 L<https://json-schema.org/draft/2020-12>
2202
2203 =item *
2204
2205 L<https://json-schema.org/draft/2019-09>
2206
2207 =item *
2208
2209 L<https://json-schema.org/draft-07>
2210
2211 =item *
2212
2213 L<https://json-schema.org/draft-06>
2214
2215 =item *
2216
2217 L<https://json-schema.org/draft-04/draft-zyp-json-schema-04>
2218
2219 =item *
2220
2221 L<Understanding JSON Schema|https://json-schema.org/understanding-json-schema>: tutorial-focused documentation
2222
2223 =item *
2224
2225 L<Test::JSON::Schema>: test your data against a JSON Schema
2226
2227 =item *
2228
2229 L<Test::JSON::Schema::Acceptance>: contains the official JSON Schema test suite
2230
2231 =item *
2232
2233 L<JSON::Schema::Tiny>: a more stripped-down implementation of the specification, with fewer
2234
2235 =item *
2236
2237 L<OpenAPI::Modern>: a parser and evaluator for OpenAPI v3.1 documents
2238
2239 =item *
2240
2241 L<Mojolicious::Plugin::OpenAPI::Modern>: a Mojolicious plugin providing OpenAPI functionality
2242
2243 =item *
2244
2245 L<Test::Mojo::Role::OpenAPI::Modern>: test your Mojolicious application's OpenAPI compliance
2246
2247 =item *
2248
2249 L<https://spec.openapis.org/registry/format>
2250
2251 =item *
2252
2253 L<https://spec.openapis.org/registry/media-type>
2254
2255 =back
2256
2257 =head1 AVAILABILITY
2258
2259 This distribution and executable is available on modern Debian versions (via C<apt-get>) as the
2260 C<libjson-schema-modern-perl> package.
2261
2262 =head1 GIVING THANKS
2263
2264 =for stopwords MetaCPAN GitHub
2265
2266 If you found this module to be useful, please show your appreciation by
2267 adding a +1 in L<MetaCPAN|https://metacpan.org/dist/JSON-Schema-Modern>
2268 and a star in L<GitHub|https://github.com/karenetheridge/JSON-Schema-Modern>.
2269
2270 =head1 SUPPORT
2271
2272 Bugs may be submitted through L<https://github.com/karenetheridge/JSON-Schema-Modern/issues>.
2273
2274 I am also usually active on irc, as 'ether' at C<irc.perl.org> and C<irc.libera.chat>.
2275
2276 =for stopwords OpenAPI
2277
2278 You can also find me on the L<JSON Schema Slack server|https://json-schema.slack.com> and L<OpenAPI Slack
2279 server|https://open-api.slack.com>, which are also great resources for finding help.
2280
2281 =head1 AUTHOR
2282
2283 Karen Etheridge <[email protected]>
2284
2285 =head1 COPYRIGHT AND LICENCE
2286
2287 This software is copyright (c) 2020 by Karen Etheridge.
2288
2289 This is free software; you can redistribute it and/or modify it under
2290 the same terms as the Perl 5 programming language system itself.
2291
2292 Some schema files have their own licence, in share/LICENSE.
2293
2294 =cut