json-structure 0.1.11__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1137 @@
1
+ # encoding: utf-8
2
+ # Suppress the runpy module import warning when running as python -m
3
+ import warnings
4
+ warnings.filterwarnings("ignore", message="'json_structure.*' found in sys.modules")
5
+
6
+ """
7
+ json_structure_schema_validator.py
8
+
9
+ A validation tool for the experimental JSON Structure Core specification
10
+ published by C. Vasters (Microsoft) in February 2025.
11
+ This version optionally supports the JSON Structure JSONStructureImport extension via the
12
+ --allowimport flag and allows passing a mapping of URI to filenames via the
13
+ --importmap option.
14
+ It also supports extended validation features via the --extended flag.
15
+
16
+ Usage:
17
+ python json_structure_schema_validator.py [--metaschema] [--allowimport] [--extended] [--importmap URI=filename ...] <path_to_json_file>
18
+
19
+ The --metaschema parameter allows '$' in property names.
20
+ The --allowimport parameter enables processing of the $import and $importdefs keywords.
21
+ The --extended parameter enables validation of conditional composition and validation extensions.
22
+ If a URI mapping is provided via --importmap, the external schema file is loaded from the given path.
23
+ """
24
+
25
+ import sys
26
+ import json
27
+ import re
28
+ from urllib.parse import urlparse
29
+ from typing import List, Optional, Union
30
+ from .error_codes import ValidationError, ValidationSeverity, JsonLocation
31
+ from .json_source_locator import JsonSourceLocator
32
+ from . import error_codes as ErrorCodes
33
+
34
+
35
+ class JSONStructureSchemaCoreValidator:
36
+ """
37
+ Validates JSON Structure Core documents for conformance with the specification.
38
+ Provides error messages annotated with estimated line and column numbers.
39
+ Optionally supports the JSON Structure JSONStructureImport extension if allow_import is True.
40
+ Optionally supports extended validation features if extended is True.
41
+ """
42
+
43
+ ABSOLUTE_URI_REGEX = re.compile(r'^[a-zA-Z][a-zA-Z0-9+\-.]*://')
44
+ MAP_KEY_REGEX = re.compile(r'^[A-Za-z0-9._-]+$')
45
+ RESERVED_KEYWORDS = {
46
+ "definitions", "$extends", "$id", "$ref", "$root", "$schema", "$uses",
47
+ "$offers", "abstract", "additionalProperties", "const", "default",
48
+ "description", "enum", "examples", "format", "items", "maxLength",
49
+ "name", "precision", "properties", "required", "scale", "type",
50
+ "values", "choices", "selector", "tuple"
51
+ }
52
+ PRIMITIVE_TYPES = {
53
+ "string", "number", "integer", "boolean", "null", "int8", "uint8", "int16", "uint16",
54
+ "int32", "uint32", "int64", "uint64", "int128", "uint128", "float8",
55
+ "float", "double", "decimal", "date", "datetime", "time", "duration",
56
+ "uuid", "uri", "binary", "jsonpointer"
57
+ }
58
+ COMPOUND_TYPES = {"object", "array", "set", "map", "tuple", "choice", "any"}
59
+
60
+ # Extended keywords for conditional composition
61
+ COMPOSITION_KEYWORDS = {"allOf", "anyOf", "oneOf", "not", "if", "then", "else"}
62
+
63
+ # Extended keywords for validation
64
+ NUMERIC_VALIDATION_KEYWORDS = {"minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf"}
65
+ STRING_VALIDATION_KEYWORDS = {"minLength", "maxLength", "pattern", "format"}
66
+ ARRAY_VALIDATION_KEYWORDS = {"minItems", "maxItems", "uniqueItems", "contains", "minContains", "maxContains"}
67
+ OBJECT_VALIDATION_KEYWORDS = {"minProperties", "maxProperties", "minEntries", "maxEntries",
68
+ "dependentRequired", "patternProperties", "patternKeys",
69
+ "propertyNames", "keyNames", "has"}
70
+
71
+ # Valid format values
72
+ VALID_FORMATS = {
73
+ "ipv4", "ipv6", "email", "idn-email", "hostname", "idn-hostname",
74
+ "iri", "iri-reference", "uri-template", "relative-json-pointer", "regex"
75
+ }
76
+
77
+ # Extension names
78
+ KNOWN_EXTENSIONS = {
79
+ "JSONStructureImport", "JSONStructureAlternateNames", "JSONStructureUnits",
80
+ "JSONStructureConditionalComposition", "JSONStructureValidation"
81
+ }
82
+
83
+ def __init__(self, allow_dollar=False, allow_import=False, import_map=None, extended=False, external_schemas=None):
84
+ """
85
+ Initializes a validator instance.
86
+ :param allow_dollar: Boolean flag to allow '$' in property names.
87
+ :param allow_import: Boolean flag to enable processing of $import/$importdefs.
88
+ :param import_map: Dictionary mapping URI to local filenames.
89
+ :param extended: Boolean flag to enable extended validation features.
90
+ :param external_schemas: List of schema dicts to use for resolving imports by $id.
91
+ Each schema should have a '$id' field matching the import URI.
92
+ """
93
+ self.errors: List[ValidationError] = []
94
+ self.doc = None
95
+ self.source_text = None
96
+ self.source_locator: Optional[JsonSourceLocator] = None
97
+ self.allow_import = allow_import
98
+ self.import_map = import_map if import_map is not None else {}
99
+ self.extended = extended
100
+ self.enabled_extensions = set()
101
+ # Build lookup for external schemas by $id
102
+ self.external_schemas = {}
103
+ if external_schemas:
104
+ import copy
105
+ for schema in external_schemas:
106
+ if isinstance(schema, dict) and "$id" in schema:
107
+ # Deep copy to avoid modifying the original
108
+ self.external_schemas[schema["$id"]] = copy.deepcopy(schema)
109
+ # Process imports in external schemas (they may import each other)
110
+ # Do multiple passes to handle chained imports
111
+ if allow_import:
112
+ for _ in range(len(self.external_schemas)):
113
+ for schema_id, schema in self.external_schemas.items():
114
+ self._process_imports_in_external_schema(schema)
115
+ if allow_dollar:
116
+ self.identifier_regex = re.compile(r'^[A-Za-z_$][A-Za-z0-9_$]*$')
117
+ else:
118
+ self.identifier_regex = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$')
119
+
120
+ def _process_imports_in_external_schema(self, obj):
121
+ """
122
+ Processes $import and $importdefs in an external schema during initialization.
123
+ This is a simplified version that doesn't track errors, just merges definitions.
124
+ Called on external_schemas during __init__ to ensure imported definitions are available.
125
+ """
126
+ if not isinstance(obj, dict):
127
+ return
128
+
129
+ for key in list(obj.keys()):
130
+ if key in ("$import", "$importdefs"):
131
+ uri = obj[key]
132
+ if not isinstance(uri, str):
133
+ continue
134
+ # Try to fetch from external_schemas
135
+ external = self.external_schemas.get(uri)
136
+ if external is None:
137
+ continue
138
+
139
+ if key == "$import":
140
+ imported_defs = {}
141
+ if "type" in external and "name" in external:
142
+ imported_defs[external["name"]] = external
143
+ if "definitions" in external and isinstance(external["definitions"], dict):
144
+ imported_defs.update(external["definitions"])
145
+ else: # $importdefs
146
+ if "definitions" in external and isinstance(external["definitions"], dict):
147
+ imported_defs = external["definitions"]
148
+ else:
149
+ imported_defs = {}
150
+
151
+ # Merge into definitions at root level
152
+ target_path = "#/definitions"
153
+ if "definitions" not in obj:
154
+ obj["definitions"] = {}
155
+ merge_target = obj["definitions"]
156
+
157
+ # Rewrite refs and merge
158
+ import copy
159
+ for k, v in imported_defs.items():
160
+ if isinstance(v, dict):
161
+ v = copy.deepcopy(v)
162
+ self._rewrite_refs(v, target_path)
163
+ imported_defs[k] = v
164
+
165
+ for k, v in imported_defs.items():
166
+ if k not in merge_target:
167
+ merge_target[k] = v
168
+
169
+ del obj[key]
170
+
171
+ def validate(self, doc, source_text=None):
172
+ """
173
+ Main entry point for validating a JSON Structure Core document.
174
+ :param doc: A dict parsed from JSON.
175
+ :param source_text: The original JSON text for computing line and column.
176
+ :return: List of ValidationError objects, empty if valid.
177
+ """
178
+ self.errors = []
179
+ self.doc = doc
180
+ self.source_text = source_text
181
+
182
+ # Initialize source locator for location tracking
183
+ if source_text:
184
+ self.source_locator = JsonSourceLocator(source_text)
185
+ else:
186
+ self.source_locator = None
187
+
188
+ if not isinstance(doc, dict):
189
+ self._err("Root of the document must be a JSON object.", "#", ErrorCodes.SCHEMA_INVALID_TYPE)
190
+ return self.errors
191
+
192
+ # Process $import and $importdefs keywords recursively.
193
+ self._process_imports(doc, "#")
194
+
195
+ # Check which extensions are enabled
196
+ if self.extended:
197
+ self._check_enabled_extensions(doc)
198
+
199
+ self._check_required_top_level_keywords(doc, "#")
200
+ if "$schema" in doc:
201
+ self._check_is_absolute_uri(doc["$schema"], "$schema", "#/$schema")
202
+ if "$id" in doc:
203
+ self._check_is_absolute_uri(doc["$id"], "$id", "#/$id")
204
+ if "$uses" in doc:
205
+ self._check_uses(doc["$uses"], "#/$uses")
206
+ if "type" in doc and "$root" in doc:
207
+ self._err("Document cannot have both 'type' at root and '$root' at the same time.", "#", ErrorCodes.SCHEMA_ROOT_CONFLICT)
208
+ if "type" in doc:
209
+ self._validate_schema(doc, is_root=True, path="#", name_in_namespace=None)
210
+ if "$root" in doc:
211
+ self._check_json_pointer(doc["$root"], self.doc, "#/$root")
212
+ if "definitions" in doc:
213
+ if not isinstance(doc["definitions"], dict):
214
+ self._err("definitions must be an object.", "#/definitions", ErrorCodes.SCHEMA_KEYWORD_INVALID_TYPE)
215
+ else:
216
+ self._validate_namespace(doc["definitions"], "#/definitions")
217
+ if "$offers" in doc:
218
+ self._check_offers(doc["$offers"], "#/$offers")
219
+
220
+ # Check for composition keywords at root if no type is present
221
+ if self.extended and "type" not in doc:
222
+ self._check_composition_keywords(doc, "#")
223
+
224
+ return self.errors
225
+
226
+ def _check_enabled_extensions(self, doc):
227
+ """
228
+ Check which extensions are enabled based on $schema and $uses.
229
+ """
230
+ schema_uri = doc.get("$schema", "")
231
+ uses = doc.get("$uses", [])
232
+
233
+ # Check if using extended or validation meta-schema
234
+ if "extended" in schema_uri or "validation" in schema_uri:
235
+ # These meta-schemas enable certain extensions by default
236
+ if "validation" in schema_uri:
237
+ self.enabled_extensions.add("JSONStructureConditionalComposition")
238
+ self.enabled_extensions.add("JSONStructureValidation")
239
+
240
+ # Check $uses array
241
+ if isinstance(uses, list):
242
+ for ext in uses:
243
+ if ext in self.KNOWN_EXTENSIONS:
244
+ self.enabled_extensions.add(ext)
245
+
246
+ def _check_uses(self, uses, path):
247
+ """
248
+ Validate the $uses keyword.
249
+ """
250
+ if not isinstance(uses, list):
251
+ self._err("$uses must be an array.", path, ErrorCodes.SCHEMA_KEYWORD_INVALID_TYPE)
252
+ return
253
+
254
+ for idx, ext in enumerate(uses):
255
+ if not isinstance(ext, str):
256
+ self._err(f"$uses[{idx}] must be a string.", f"{path}[{idx}]", ErrorCodes.SCHEMA_KEYWORD_INVALID_TYPE)
257
+ elif self.extended and ext not in self.KNOWN_EXTENSIONS:
258
+ self._err(f"Unknown extension '{ext}' in $uses.", f"{path}[{idx}]", ErrorCodes.SCHEMA_USES_UNKNOWN_EXTENSION)
259
+
260
+ def _check_required_top_level_keywords(self, obj, location):
261
+ """
262
+ Ensures $schema and $id are present at the root level.
263
+ """
264
+ if "$schema" not in obj:
265
+ self._err("Missing required '$schema' keyword at root.", location)
266
+ if "$id" not in obj:
267
+ self._err("Missing required '$id' keyword at root.", location)
268
+
269
+ def _check_is_absolute_uri(self, value, keyword_name, location):
270
+ """
271
+ Checks if a given string is an absolute URI.
272
+ """
273
+ if not isinstance(value, str):
274
+ self._err(f"'{keyword_name}' must be a string.", location)
275
+ return
276
+ if not self.ABSOLUTE_URI_REGEX.search(value):
277
+ self._err(f"'{keyword_name}' must be an absolute URI.", location)
278
+
279
+ def _rewrite_refs(self, obj, target_path):
280
+ """
281
+ Recursively rewrites $ref pointers in an imported schema to be relative to the target path.
282
+ When a schema is imported at path (e.g., #/definitions), all internal $ref pointers
283
+ like #/definitions/X or #/X need to be rewritten to point to target_path/X.
284
+ References to nested paths like #/definitions/features/Y are preserved with their structure.
285
+ [Metaschema: JSONStructureImport extension - reference rewriting]
286
+ :param obj: The imported schema object to rewrite.
287
+ :param target_path: The JSON pointer path where the schema is being imported (e.g., "#/definitions").
288
+ """
289
+ if isinstance(obj, dict):
290
+ for key, value in obj.items():
291
+ if key == "$ref" and isinstance(value, str) and value.startswith("#"):
292
+ # Rewrite the $ref to be relative to target_path
293
+ # Strip the "#" and split
294
+ ref_parts = value.lstrip("#").lstrip("/").split("/")
295
+ if ref_parts and ref_parts[0]:
296
+ # Skip 'definitions' if present at the start since we're importing into definitions
297
+ if ref_parts[0] == "definitions" and len(ref_parts) > 1:
298
+ # Keep everything after 'definitions'
299
+ remaining_path = "/".join(ref_parts[1:])
300
+ obj[key] = f"{target_path}/{remaining_path}"
301
+ else:
302
+ # For other refs, just append the full path
303
+ remaining_path = "/".join(ref_parts)
304
+ obj[key] = f"{target_path}/{remaining_path}"
305
+ elif key == "$extends" and isinstance(value, str) and value.startswith("#"):
306
+ # Also rewrite $extends references
307
+ ref_parts = value.lstrip("#").lstrip("/").split("/")
308
+ if ref_parts and ref_parts[0]:
309
+ if ref_parts[0] == "definitions" and len(ref_parts) > 1:
310
+ remaining_path = "/".join(ref_parts[1:])
311
+ obj[key] = f"{target_path}/{remaining_path}"
312
+ else:
313
+ remaining_path = "/".join(ref_parts)
314
+ obj[key] = f"{target_path}/{remaining_path}"
315
+ else:
316
+ self._rewrite_refs(value, target_path)
317
+ elif isinstance(obj, list):
318
+ for item in obj:
319
+ self._rewrite_refs(item, target_path)
320
+
321
+ def _process_imports(self, obj, path):
322
+ """
323
+ Recursively processes $import and $importdefs keywords.
324
+ If allow_import is False, an error is reported.
325
+ Otherwise, external schemas are fetched and their definitions merged appropriately.
326
+ - If the import is at the root level, definitions go into obj["definitions"]
327
+ - If the import is inside a namespace (e.g., definitions/People), definitions merge directly into obj
328
+ This merging is done in-place so that imported definitions appear as if they were defined locally.
329
+ After merging, $ref pointers in the imported content are rewritten to point to their new locations.
330
+ """
331
+ if isinstance(obj, dict):
332
+ # Process import keywords at current level.
333
+ for key in list(obj.keys()):
334
+ if key in ("$import", "$importdefs"):
335
+ if not self.allow_import:
336
+ self._err(f"JSONStructureImport keyword '{key}' encountered but allow_import not enabled.", f"{path}/{key}")
337
+ continue
338
+ uri = obj[key]
339
+ if not isinstance(uri, str):
340
+ self._err(f"JSONStructureImport keyword '{key}' value must be a string URI.", f"{path}/{key}")
341
+ continue
342
+ # Allow relative URIs if they're in import_map or external_schemas
343
+ if not self.ABSOLUTE_URI_REGEX.search(uri):
344
+ if uri not in self.import_map and uri not in self.external_schemas:
345
+ self._err(f"JSONStructureImport keyword '{key}' value must be an absolute URI.", f"{path}/{key}")
346
+ continue
347
+ external = self._fetch_external_schema(uri)
348
+ if external is None:
349
+ self._err(f"Unable to fetch external schema from {uri}.", f"{path}/{key}")
350
+ continue
351
+ if key == "$import":
352
+ imported_defs = {}
353
+ # Import root type if available.
354
+ if "type" in external and "name" in external:
355
+ imported_defs[external["name"]] = external
356
+ # Also import definitions from definitions if available.
357
+ if "definitions" in external and isinstance(external["definitions"], dict):
358
+ imported_defs.update(external["definitions"])
359
+ else: # $importdefs
360
+ if "definitions" in external and isinstance(external["definitions"], dict):
361
+ imported_defs = external["definitions"]
362
+ else:
363
+ imported_defs = {}
364
+ # Determine where to merge and the actual target path for ref rewriting
365
+ if path == "#":
366
+ # Root level import - put in definitions
367
+ target_path = "#/definitions"
368
+ if "definitions" not in obj:
369
+ obj["definitions"] = {}
370
+ merge_target = obj["definitions"]
371
+ else:
372
+ # Nested import (e.g., inside a namespace) - merge directly into current object
373
+ target_path = path
374
+ merge_target = obj
375
+ # Rewrite $ref pointers in imported content to point to their new location
376
+ for k, v in imported_defs.items():
377
+ if isinstance(v, dict):
378
+ # Deep copy to avoid modifying cached schemas
379
+ import copy
380
+ v = copy.deepcopy(v)
381
+ self._rewrite_refs(v, target_path)
382
+ imported_defs[k] = v
383
+ # Merge imported definitions
384
+ for k, v in imported_defs.items():
385
+ if k not in merge_target:
386
+ merge_target[k] = v
387
+ del obj[key]
388
+ # Recurse into all values, but skip recursing into 'properties' values
389
+ # since those contain property name definitions, not import directives
390
+ for key, value in obj.items():
391
+ # Skip processing inside 'properties' - $import/$importdefs there are property names, not directives
392
+ if key == "properties":
393
+ continue
394
+ self._process_imports(value, f"{path}/{key}")
395
+ elif isinstance(obj, list):
396
+ for idx, item in enumerate(obj):
397
+ self._process_imports(item, f"{path}[{idx}]")
398
+
399
+ def _fetch_external_schema(self, uri):
400
+ """
401
+ Fetches an external schema from a URI.
402
+ Resolution order:
403
+ 1. Check external_schemas (pre-loaded schemas matched by $id)
404
+ 2. Check import_map (URI to file path mapping)
405
+
406
+ When loading from file, recursively processes imports in the loaded schema.
407
+ """
408
+ # First check sideloaded schemas by $id
409
+ if uri in self.external_schemas:
410
+ return self.external_schemas[uri]
411
+ # Then check import_map for file paths
412
+ if uri in self.import_map:
413
+ try:
414
+ with open(self.import_map[uri], "r", encoding="utf-8") as f:
415
+ import copy
416
+ schema = json.load(f)
417
+ # Deep copy to avoid modifying the original
418
+ schema = copy.deepcopy(schema)
419
+ # Recursively process imports in the loaded schema
420
+ self._process_imports(schema, "#")
421
+ # Cache the processed schema for future use
422
+ self.external_schemas[uri] = schema
423
+ return schema
424
+ except Exception as e:
425
+ self._err(f"Failed to load imported schema from {self.import_map[uri]}: {e}", "#/import")
426
+ return None
427
+ # URI not found in external_schemas or import_map
428
+ return None
429
+
430
+ def _validate_namespace(self, obj, path):
431
+ """
432
+ Recursively validates objects in definitions as either a namespace or a schema.
433
+ """
434
+ if not isinstance(obj, dict):
435
+ self._err(f"{path} must be an object.", path)
436
+ return
437
+ for k, v in obj.items():
438
+ subpath = f"{path}/{k}"
439
+ if isinstance(v, dict) and ("type" in v or "$ref" in v or
440
+ (self.extended and self._has_composition_keywords(v))):
441
+ self._validate_schema(v, is_root=False, path=subpath, name_in_namespace=k)
442
+ else:
443
+ if not isinstance(v, dict):
444
+ self._err(f"{subpath} is not a valid namespace or schema object.", subpath)
445
+ else:
446
+ self._validate_namespace(v, subpath)
447
+
448
+ def _has_composition_keywords(self, obj):
449
+ """
450
+ Check if object has any composition keywords.
451
+ """
452
+ return any(key in obj for key in self.COMPOSITION_KEYWORDS)
453
+
454
+ def _validate_schema(self, schema_obj, is_root=False, path="", name_in_namespace=None):
455
+ """
456
+ Validates an individual schema object.
457
+ """
458
+ if not isinstance(schema_obj, dict):
459
+ self._err(f"{path} must be an object to be a schema.", path)
460
+ return
461
+
462
+ # Check composition keywords if extended validation is enabled
463
+ if self.extended:
464
+ self._check_composition_keywords(schema_obj, path)
465
+
466
+ if is_root and "type" in schema_obj and "name" not in schema_obj:
467
+ if not isinstance(schema_obj["type"], list):
468
+ self._err("Root schema with 'type' must have a 'name' property.", path)
469
+ if "name" in schema_obj:
470
+ if not isinstance(schema_obj["name"], str):
471
+ self._err(f"'name' must be a string.", path + "/name")
472
+ else:
473
+ if not self.identifier_regex.match(schema_obj["name"]):
474
+ self._err(f"'name' must match the identifier pattern.", path + "/name")
475
+ if "abstract" in schema_obj:
476
+ if not isinstance(schema_obj["abstract"], bool):
477
+ self._err(f"'abstract' keyword must be boolean.", path + "/abstract")
478
+ if "$extends" in schema_obj:
479
+ if not isinstance(schema_obj["$extends"], str):
480
+ self._err(f"'$extends' must be a JSON pointer string.", path + "/$extends")
481
+ else:
482
+ self._check_json_pointer(schema_obj["$extends"], self.doc, path + "/$extends")
483
+
484
+ # Check if this is a non-schema with composition keywords
485
+ has_type_or_ref = "type" in schema_obj or "$ref" in schema_obj
486
+ has_composition = self.extended and self._has_composition_keywords(schema_obj)
487
+
488
+ if not has_type_or_ref and not has_composition:
489
+ self._err("Missing required 'type' or '$ref' in schema object.", path)
490
+ return
491
+
492
+ if "type" in schema_obj and "$ref" in schema_obj:
493
+ self._err("Cannot have both 'type' and '$ref'.", path)
494
+ return
495
+
496
+ if "$ref" in schema_obj:
497
+ if not isinstance(schema_obj["$ref"], str):
498
+ self._err("'$ref' must be a string.", path + "/$ref")
499
+ else:
500
+ self._check_json_pointer(schema_obj["$ref"], self.doc, path + "/$ref")
501
+ return
502
+
503
+ if "type" in schema_obj:
504
+ tval = schema_obj["type"]
505
+ if isinstance(tval, list):
506
+ if not tval:
507
+ self._err("Type union cannot be empty.", path + "/type")
508
+ else:
509
+ for idx, union_item in enumerate(tval):
510
+ self._check_union_type_item(union_item, f"{path}/type[{idx}]")
511
+ elif isinstance(tval, dict):
512
+ if "$ref" not in tval:
513
+ if "type" in tval or "properties" in tval:
514
+ self._validate_schema(tval, is_root=False, path=f"{path}/type(inline)")
515
+ else:
516
+ self._err("Type dict must have '$ref' or be a valid schema object.", path + "/type")
517
+ else:
518
+ self._check_json_pointer(tval["$ref"], self.doc, path + "/type/$ref")
519
+ else:
520
+ if not isinstance(tval, str):
521
+ self._err("Type must be a string, list, or object with $ref.", path + "/type")
522
+ else:
523
+ if (tval not in self.PRIMITIVE_TYPES and
524
+ tval not in self.COMPOUND_TYPES):
525
+ self._err(f"Type '{tval}' is not a recognized primitive or compound type.", path + "/type")
526
+ else:
527
+ if tval == "any":
528
+ pass
529
+ elif tval == "object":
530
+ self._check_object_schema(schema_obj, path)
531
+ elif tval == "array":
532
+ self._check_array_schema(schema_obj, path)
533
+ elif tval == "set":
534
+ self._check_set_schema(schema_obj, path)
535
+ elif tval == "map":
536
+ self._check_map_schema(schema_obj, path)
537
+ elif tval == "tuple":
538
+ self._check_tuple_schema(schema_obj, path)
539
+ elif tval == "choice":
540
+ self._check_choice_schema(schema_obj, path)
541
+ else:
542
+ self._check_primitive_schema(schema_obj, path)
543
+
544
+ # Extended validation checks
545
+ if self.extended and "type" in schema_obj:
546
+ self._check_extended_validation_keywords(schema_obj, path)
547
+
548
+ if "required" in schema_obj:
549
+ if "type" in schema_obj and isinstance(schema_obj["type"], str):
550
+ if schema_obj["type"] != "object":
551
+ self._err("'required' can only appear in an object schema.", path + "/required")
552
+ if "additionalProperties" in schema_obj:
553
+ if "type" in schema_obj and isinstance(schema_obj["type"], str):
554
+ if schema_obj["type"] != "object":
555
+ self._err("'additionalProperties' can only appear in an object schema.", path + "/additionalProperties")
556
+ if "enum" in schema_obj:
557
+ if not isinstance(schema_obj["enum"], list):
558
+ self._err("Enum must be an array.", path + "/enum")
559
+ if "type" in schema_obj and isinstance(schema_obj["type"], str):
560
+ if schema_obj["type"] in self.COMPOUND_TYPES:
561
+ self._err("'enum' cannot be used with compound types.", path + "/enum")
562
+ if "const" in schema_obj:
563
+ if "type" in schema_obj and isinstance(schema_obj["type"], str):
564
+ if schema_obj["type"] in self.COMPOUND_TYPES:
565
+ self._err("'const' cannot be used with compound types.", path + "/const")
566
+
567
+ def _check_composition_keywords(self, obj, path):
568
+ """
569
+ Check conditional composition keywords if the extension is enabled.
570
+ """
571
+ if not self.extended:
572
+ return
573
+
574
+ # Check if conditional composition is enabled
575
+ if "JSONStructureConditionalComposition" not in self.enabled_extensions:
576
+ for key in self.COMPOSITION_KEYWORDS:
577
+ if key in obj:
578
+ self._err(f"Conditional composition keyword '{key}' requires JSONStructureConditionalComposition extension.", f"{path}/{key}")
579
+ return
580
+
581
+ # Validate allOf, anyOf, oneOf
582
+ for key in ["allOf", "anyOf", "oneOf"]:
583
+ if key in obj:
584
+ val = obj[key]
585
+ if not isinstance(val, list):
586
+ self._err(f"'{key}' must be an array.", f"{path}/{key}")
587
+ elif len(val) == 0:
588
+ self._err(f"'{key}' array cannot be empty.", f"{path}/{key}")
589
+ else:
590
+ for idx, item in enumerate(val):
591
+ if isinstance(item, dict):
592
+ self._validate_schema(item, is_root=False, path=f"{path}/{key}[{idx}]")
593
+ else:
594
+ self._err(f"'{key}' array items must be schema objects.", f"{path}/{key}[{idx}]")
595
+
596
+ # Validate not
597
+ if "not" in obj:
598
+ val = obj["not"]
599
+ if isinstance(val, dict):
600
+ self._validate_schema(val, is_root=False, path=f"{path}/not")
601
+ else:
602
+ self._err("'not' must be a schema object.", f"{path}/not")
603
+
604
+ # Validate if/then/else
605
+ for key in ["if", "then", "else"]:
606
+ if key in obj:
607
+ val = obj[key]
608
+ if isinstance(val, dict):
609
+ self._validate_schema(val, is_root=False, path=f"{path}/{key}")
610
+ else:
611
+ self._err(f"'{key}' must be a schema object.", f"{path}/{key}")
612
+
613
+ def _check_extended_validation_keywords(self, obj, path):
614
+ """
615
+ Check extended validation keywords based on type.
616
+ """
617
+ if "JSONStructureValidation" not in self.enabled_extensions:
618
+ # Check if any validation keywords are present without the extension
619
+ all_validation_keywords = (self.NUMERIC_VALIDATION_KEYWORDS |
620
+ self.STRING_VALIDATION_KEYWORDS |
621
+ self.ARRAY_VALIDATION_KEYWORDS |
622
+ self.OBJECT_VALIDATION_KEYWORDS |
623
+ {"default"})
624
+ for key in all_validation_keywords:
625
+ if key in obj:
626
+ self._err(f"Validation keyword '{key}' requires JSONStructureValidation extension.", f"{path}/{key}")
627
+ return
628
+
629
+ tval = obj.get("type")
630
+ if isinstance(tval, str):
631
+ # Check numeric validation keywords
632
+ if tval in ["number", "integer", "float", "double", "decimal",
633
+ "int8", "uint8", "int16", "uint16", "int32", "uint32",
634
+ "int64", "uint64", "int128", "uint128", "float8"]:
635
+ self._check_numeric_validation(obj, path, tval)
636
+
637
+ # Check string validation keywords
638
+ elif tval == "string":
639
+ self._check_string_validation(obj, path)
640
+
641
+ # Check array/set validation keywords
642
+ elif tval in ["array", "set"]:
643
+ self._check_array_validation(obj, path, tval)
644
+
645
+ # Check object/map validation keywords
646
+ elif tval in ["object", "map"]:
647
+ self._check_object_validation(obj, path, tval)
648
+
649
+ # Check default keyword
650
+ if "default" in obj:
651
+ # Default can be any value, just ensure it's present
652
+ pass
653
+
654
+ def _check_numeric_validation(self, obj, path, type_name):
655
+ """
656
+ Check numeric validation keywords.
657
+ """
658
+ # For extended types whose base is string, values should be strings
659
+ string_based_types = {"int64", "uint64", "int128", "uint128", "decimal"}
660
+ expects_string = type_name in string_based_types
661
+
662
+ for key in ["minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf"]:
663
+ if key in obj:
664
+ val = obj[key]
665
+ if expects_string:
666
+ if not isinstance(val, str):
667
+ self._err(f"'{key}' for type '{type_name}' must be a string.", f"{path}/{key}")
668
+ else:
669
+ if not isinstance(val, (int, float)):
670
+ self._err(f"'{key}' must be a number.", f"{path}/{key}")
671
+ elif key == "multipleOf" and val <= 0:
672
+ self._err(f"'multipleOf' must be a positive number.", f"{path}/{key}")
673
+
674
+ def _check_string_validation(self, obj, path):
675
+ """
676
+ Check string validation keywords.
677
+ """
678
+ if "minLength" in obj:
679
+ val = obj["minLength"]
680
+ if not isinstance(val, int) or val < 0:
681
+ self._err("'minLength' must be a non-negative integer.", f"{path}/minLength")
682
+
683
+ if "maxLength" in obj:
684
+ val = obj["maxLength"]
685
+ if not isinstance(val, int) or val < 0:
686
+ self._err("'maxLength' must be a non-negative integer.", f"{path}/maxLength")
687
+
688
+ if "pattern" in obj:
689
+ val = obj["pattern"]
690
+ if not isinstance(val, str):
691
+ self._err("'pattern' must be a string.", f"{path}/pattern")
692
+ else:
693
+ # Try to compile the regex
694
+ try:
695
+ re.compile(val)
696
+ except re.error as e:
697
+ self._err(f"'pattern' is not a valid regular expression: {e}", f"{path}/pattern")
698
+
699
+ if "format" in obj:
700
+ val = obj["format"]
701
+ if not isinstance(val, str):
702
+ self._err("'format' must be a string.", f"{path}/format")
703
+ elif val not in self.VALID_FORMATS:
704
+ self._err(f"Unknown format '{val}'.", f"{path}/format")
705
+
706
+ def _check_array_validation(self, obj, path, type_name):
707
+ """
708
+ Check array/set validation keywords.
709
+ """
710
+ for key in ["minItems", "maxItems"]:
711
+ if key in obj:
712
+ val = obj[key]
713
+ if not isinstance(val, int) or val < 0:
714
+ self._err(f"'{key}' must be a non-negative integer.", f"{path}/{key}")
715
+
716
+ if "uniqueItems" in obj:
717
+ val = obj["uniqueItems"]
718
+ if not isinstance(val, bool):
719
+ self._err("'uniqueItems' must be a boolean.", f"{path}/uniqueItems")
720
+ elif type_name == "set" and val is False:
721
+ self._err("'uniqueItems' cannot be false for 'set' type.", f"{path}/uniqueItems")
722
+
723
+ if "contains" in obj:
724
+ val = obj["contains"]
725
+ if isinstance(val, dict):
726
+ self._validate_schema(val, is_root=False, path=f"{path}/contains")
727
+ else:
728
+ self._err("'contains' must be a schema object.", f"{path}/contains")
729
+
730
+ for key in ["minContains", "maxContains"]:
731
+ if key in obj:
732
+ val = obj[key]
733
+ if not isinstance(val, int) or val < 0:
734
+ self._err(f"'{key}' must be a non-negative integer.", f"{path}/{key}")
735
+ # These require 'contains' to be present
736
+ if "contains" not in obj:
737
+ self._err(f"'{key}' requires 'contains' to be present.", f"{path}/{key}")
738
+
739
+ def _check_object_validation(self, obj, path, type_name):
740
+ """
741
+ Check object/map validation keywords.
742
+ """
743
+ # Handle minProperties/minEntries and maxProperties/maxEntries
744
+ min_key = "minEntries" if type_name == "map" else "minProperties"
745
+ max_key = "maxEntries" if type_name == "map" else "maxProperties"
746
+
747
+ for key in [min_key, max_key, "minProperties", "maxProperties", "minEntries", "maxEntries"]:
748
+ if key in obj:
749
+ # Check if using the right keyword for the type
750
+ if type_name == "map" and key in ["minProperties", "maxProperties"]:
751
+ self._err(f"Use '{key.replace('Properties', 'Entries')}' for map type instead of '{key}'.", f"{path}/{key}")
752
+ elif type_name == "object" and key in ["minEntries", "maxEntries"]:
753
+ self._err(f"Use '{key.replace('Entries', 'Properties')}' for object type instead of '{key}'.", f"{path}/{key}")
754
+
755
+ val = obj[key]
756
+ if not isinstance(val, int) or val < 0:
757
+ self._err(f"'{key}' must be a non-negative integer.", f"{path}/{key}")
758
+
759
+ if "dependentRequired" in obj:
760
+ if type_name != "object":
761
+ self._err("'dependentRequired' only applies to object type.", f"{path}/dependentRequired")
762
+ else:
763
+ val = obj["dependentRequired"]
764
+ if not isinstance(val, dict):
765
+ self._err("'dependentRequired' must be an object.", f"{path}/dependentRequired")
766
+ else:
767
+ for prop, deps in val.items():
768
+ if not isinstance(deps, list):
769
+ self._err(f"'dependentRequired/{prop}' must be an array.", f"{path}/dependentRequired/{prop}")
770
+ else:
771
+ for idx, dep in enumerate(deps):
772
+ if not isinstance(dep, str):
773
+ self._err(f"'dependentRequired/{prop}[{idx}]' must be a string.", f"{path}/dependentRequired/{prop}[{idx}]")
774
+
775
+ # Handle patternProperties/patternKeys
776
+ pattern_key = "patternKeys" if type_name == "map" else "patternProperties"
777
+ for key in ["patternProperties", "patternKeys"]:
778
+ if key in obj:
779
+ if type_name == "map" and key == "patternProperties":
780
+ self._err(f"Use 'patternKeys' for map type instead of 'patternProperties'.", f"{path}/{key}")
781
+ elif type_name == "object" and key == "patternKeys":
782
+ self._err(f"Use 'patternProperties' for object type instead of 'patternKeys'.", f"{path}/{key}")
783
+
784
+ val = obj[key]
785
+ if not isinstance(val, dict):
786
+ self._err(f"'{key}' must be an object.", f"{path}/{key}")
787
+ else:
788
+ for pattern, schema in val.items():
789
+ # Try to compile the pattern
790
+ try:
791
+ re.compile(pattern)
792
+ except re.error as e:
793
+ self._err(f"'{key}/{pattern}' is not a valid regular expression: {e}", f"{path}/{key}/{pattern}")
794
+ if isinstance(schema, dict):
795
+ self._validate_schema(schema, is_root=False, path=f"{path}/{key}/{pattern}")
796
+ else:
797
+ self._err(f"'{key}/{pattern}' must be a schema object.", f"{path}/{key}/{pattern}")
798
+
799
+
800
+ # Handle propertyNames/keyNames
801
+ name_key = "keyNames" if type_name == "map" else "propertyNames"
802
+ for key in ["propertyNames", "keyNames"]:
803
+ if key in obj:
804
+ if type_name == "map" and key == "propertyNames":
805
+ self._err(f"Use 'keyNames' for map type instead of 'propertyNames'.", f"{path}/{key}")
806
+ elif type_name == "object" and key == "keyNames":
807
+ self._err(f"Use 'propertyNames' for object type instead of 'keyNames'.", f"{path}/{key}")
808
+
809
+ val = obj[key]
810
+ if isinstance(val, dict):
811
+ # Must be a string type schema
812
+ if "type" in val and val["type"] != "string":
813
+ self._err(f"'{key}' schema must have type 'string'.", f"{path}/{key}")
814
+ self._validate_schema(val, is_root=False, path=f"{path}/{key}")
815
+ else:
816
+ self._err(f"'{key}' must be a schema object.", f"{path}/{key}")
817
+
818
+ if "has" in obj:
819
+ val = obj["has"]
820
+ if isinstance(val, dict):
821
+ self._validate_schema(val, is_root=False, path=f"{path}/has")
822
+ else:
823
+ self._err("'has' must be a schema object.", f"{path}/has")
824
+
825
+ def _check_union_type_item(self, union_item, path):
826
+ """
827
+ Checks one item in a union's type array.
828
+ """
829
+ if isinstance(union_item, str):
830
+ if (union_item not in self.PRIMITIVE_TYPES and
831
+ union_item not in self.COMPOUND_TYPES):
832
+ self._err(f"'{union_item}' not recognized as a valid type name.", path)
833
+ if union_item in self.COMPOUND_TYPES:
834
+ self._err(f"Inline compound type '{union_item}' is not permitted in a union. Must use a $ref.", path)
835
+ elif isinstance(union_item, dict):
836
+ if "$ref" not in union_item:
837
+ self._err("Inline compound definitions not allowed in union. Must be a $ref.", path)
838
+ else:
839
+ self._check_json_pointer(union_item["$ref"], self.doc, path + "/$ref")
840
+ else:
841
+ self._err("Union item must be a string or an object with $ref.", path)
842
+
843
+ def _check_object_schema(self, obj, path):
844
+ """
845
+ Checks constraints specific to an 'object' type.
846
+ If the object extends another type via '$extends', 'properties' is optional.
847
+ """
848
+ if "properties" not in obj and "$extends" not in obj:
849
+ self._err("Object type must have 'properties' if not extending another type.", path + "/properties")
850
+ elif "properties" in obj:
851
+ props = obj["properties"]
852
+ if not isinstance(props, dict):
853
+ self._err("Properties must be an object.", path + "/properties")
854
+ else:
855
+ for prop_name, prop_schema in props.items():
856
+ if not self.identifier_regex.match(prop_name):
857
+ self._err(f"Property key '{prop_name}' does not match the identifier pattern.", path + f"/properties/{prop_name}")
858
+ if isinstance(prop_schema, dict):
859
+ self._validate_schema(prop_schema, is_root=False, path=f"{path}/properties/{prop_name}")
860
+ else:
861
+ self._err(f"Property '{prop_name}' must be an object (a schema).", path + f"/properties/{prop_name}")
862
+
863
+ def _check_array_schema(self, obj, path):
864
+ """
865
+ Checks constraints for an 'array' type.
866
+ """
867
+ if "items" not in obj:
868
+ self._err("Array type must have 'items'.", path + "/items")
869
+ else:
870
+ items_schema = obj["items"]
871
+ if not isinstance(items_schema, dict):
872
+ self._err("'items' must be an object (a schema).", path + "/items")
873
+ else:
874
+ self._validate_schema(items_schema, is_root=False, path=path + "/items")
875
+
876
+ def _check_set_schema(self, obj, path):
877
+ """
878
+ Checks constraints for a 'set' type.
879
+ """
880
+ if "items" not in obj:
881
+ self._err("Set type must have 'items'.", path + "/items")
882
+ else:
883
+ items_schema = obj["items"]
884
+ if not isinstance(items_schema, dict):
885
+ self._err("'items' must be an object (a schema).", path + "/items")
886
+ else:
887
+ self._validate_schema(items_schema, is_root=False, path=path + "/items")
888
+
889
+ def _check_map_schema(self, obj, path):
890
+ """
891
+ Checks constraints for a 'map' type.
892
+ """
893
+ if "values" not in obj:
894
+ self._err("Map type must have 'values'.", path + "/values")
895
+ else:
896
+ values_schema = obj["values"]
897
+ if not isinstance(values_schema, dict):
898
+ self._err("'values' must be an object (a schema).", path + "/values")
899
+ else:
900
+ self._validate_schema(values_schema, is_root=False, path=path + "/values")
901
+
902
+ def _check_tuple_schema(self, obj, path):
903
+ """
904
+ Checks constraints for a 'tuple' type.
905
+ A valid tuple schema must:
906
+ - Include a 'name' attribute.
907
+ - Have a 'properties' object where each key is a valid identifier.
908
+ - Include a 'tuple' keyword that is an array of strings defining the order.
909
+ - Ensure that every element in the 'tuple' array corresponds to a property in 'properties'.
910
+ """
911
+ # Check that 'name' is present.
912
+ if "name" not in obj:
913
+ self._err("Tuple type must include a 'name' attribute.", path + "/name")
914
+
915
+ # Validate properties.
916
+ if "properties" not in obj:
917
+ self._err("Tuple type must have 'properties'.", path + "/properties")
918
+ else:
919
+ props = obj["properties"]
920
+ if not isinstance(props, dict):
921
+ self._err("'properties' must be an object.", path + "/properties")
922
+ else:
923
+ for prop_name, prop_schema in props.items():
924
+ if not self.identifier_regex.match(prop_name):
925
+ self._err(f"Tuple property key '{prop_name}' does not match the identifier pattern.", path + f"/properties/{prop_name}")
926
+ if isinstance(prop_schema, dict):
927
+ self._validate_schema(prop_schema, is_root=False, path=f"{path}/properties/{prop_name}")
928
+ else:
929
+ self._err(f"Tuple property '{prop_name}' must be an object (a schema).", path + f"/properties/{prop_name}")
930
+
931
+ # Check that the 'tuple' keyword is present.
932
+ if "tuple" not in obj:
933
+ self._err("Tuple type must include the 'tuple' keyword defining the order of elements.", path + "/tuple")
934
+ else:
935
+ tuple_order = obj["tuple"]
936
+ if not isinstance(tuple_order, list):
937
+ self._err("'tuple' keyword must be an array of strings.", path + "/tuple")
938
+ else:
939
+ for idx, element in enumerate(tuple_order):
940
+ if not isinstance(element, str):
941
+ self._err(f"Element at index {idx} in 'tuple' array must be a string.", path + f"/tuple[{idx}]")
942
+ elif "properties" in obj and isinstance(obj["properties"], dict) and element not in obj["properties"]:
943
+ self._err(f"Element '{element}' in 'tuple' does not correspond to any property in 'properties'.", path + f"/tuple[{idx}]")
944
+
945
+ def _check_choice_schema(self, obj, path):
946
+ """
947
+ Checks constraints for a 'choice' type (tagged or inline union).
948
+ """
949
+ if "choices" not in obj:
950
+ self._err("Choice type must have 'choices'.", path + "/choices")
951
+ else:
952
+ choices = obj["choices"]
953
+ if not isinstance(choices, dict):
954
+ self._err("'choices' must be an object (map).", path + "/choices")
955
+ else:
956
+ for name, choice_schema in choices.items():
957
+ if not isinstance(name, str):
958
+ self._err(f"Choice key '{name}' must be a string.", path + f"/choices/{name}")
959
+ if isinstance(choice_schema, dict):
960
+ self._validate_schema(choice_schema, is_root=False, path=f"{path}/choices/{name}")
961
+ else:
962
+ self._err(f"Choice value for '{name}' must be an object (schema).", path + f"/choices/{name}")
963
+ if "selector" in obj and not isinstance(obj.get("selector"), str):
964
+ self._err("'selector' must be a string.", path + "/selector")
965
+
966
+ def _check_primitive_schema(self, obj, path):
967
+ """
968
+ Checks constraints for a recognized primitive type.
969
+ Additional annotation checks can be added here.
970
+ """
971
+ pass
972
+
973
+ def _check_json_pointer(self, pointer, doc, path):
974
+ """
975
+ Validates that the pointer is a valid JSON Pointer within the same document.
976
+ """
977
+ if not isinstance(pointer, str):
978
+ self._err("JSON Pointer must be a string.", path)
979
+ return
980
+ if not pointer.startswith("#"):
981
+ self._err("JSON Pointer must start with '#' when referencing the same document.", path)
982
+ return
983
+ parts = pointer.split("/")
984
+ cur = doc
985
+ if pointer == "#":
986
+ return
987
+ for i, p in enumerate(parts):
988
+ if i == 0:
989
+ continue
990
+ p = p.replace("~1", "/").replace("~0", "~")
991
+ if isinstance(cur, dict):
992
+ if p in cur:
993
+ cur = cur[p]
994
+ else:
995
+ self._err(f"JSON Pointer segment '/{p}' not found.", path)
996
+ return
997
+ else:
998
+ self._err(f"JSON Pointer segment '/{p}' not applicable to non-object.", path)
999
+ return
1000
+
1001
+ def _check_offers(self, offers, path):
1002
+ """
1003
+ Validates the structure of the $offers map.
1004
+ """
1005
+ if not isinstance(offers, dict):
1006
+ self._err("$offers must be an object.", path)
1007
+ return
1008
+ for addin_name, addin_val in offers.items():
1009
+ if not isinstance(addin_name, str):
1010
+ self._err("$offers keys must be strings.", path)
1011
+ if isinstance(addin_val, str):
1012
+ self._check_json_pointer(addin_val, self.doc, f"{path}/{addin_name}")
1013
+ elif isinstance(addin_val, list):
1014
+ for idx, pointer in enumerate(addin_val):
1015
+ if not isinstance(pointer, str):
1016
+ self._err(f"$offers/{addin_name}[{idx}] must be a string (JSON Pointer).", f"{path}/{addin_name}[{idx}]")
1017
+ else:
1018
+ self._check_json_pointer(pointer, self.doc, f"{path}/{addin_name}[{idx}]")
1019
+ else:
1020
+ self._err(f"$offers/{addin_name} must be a string or array of strings.", f"{path}/{addin_name}")
1021
+
1022
+ def _locate(self, pointer):
1023
+ """
1024
+ Heuristically locates the first occurrence of the JSON pointer path in the source text.
1025
+ Returns a tuple (line, column) if found, or None.
1026
+ """
1027
+ if not self.source_text or not pointer.startswith("#"):
1028
+ return None
1029
+ parts = pointer[1:].split("/")
1030
+ pos = 0
1031
+ for part in parts:
1032
+ part = part.replace("~1", "/").replace("~0", "~")
1033
+ pattern = f'"{part}"'
1034
+ found = self.source_text.find(pattern, pos)
1035
+ if found == -1:
1036
+ return None
1037
+ pos = found + len(pattern)
1038
+ line = self.source_text.count("\n", 0, pos) + 1
1039
+ last_newline = self.source_text.rfind("\n", 0, pos)
1040
+ col = pos - last_newline if last_newline != -1 else pos + 1
1041
+ return (line, col)
1042
+
1043
+ def _err(self, message: str, location: str = "#", code: str = ErrorCodes.SCHEMA_ERROR):
1044
+ """
1045
+ Appends a ValidationError with line and column information (if available)
1046
+ to the validation errors.
1047
+ """
1048
+ if self.source_locator:
1049
+ loc = self.source_locator.get_location(location)
1050
+ else:
1051
+ loc = JsonLocation.unknown()
1052
+
1053
+ error = ValidationError(
1054
+ code=code,
1055
+ message=message,
1056
+ path=location,
1057
+ severity=ValidationSeverity.ERROR,
1058
+ location=loc
1059
+ )
1060
+ self.errors.append(error)
1061
+
1062
+
1063
+ def validate_json_structure_schema_core(schema_document, source_text=None, allow_dollar=False, allow_import=False, import_map=None, extended=False):
1064
+ """
1065
+ Validates the provided schema_document dict against the JSON Structure Core specification.
1066
+ :param schema_document: Parsed JSON Structure document.
1067
+ :param source_text: Original JSON text.
1068
+ :param allow_dollar: Allow '$' in property names.
1069
+ :param allow_import: Enable processing of $import/$importdefs keywords.
1070
+ :param import_map: Dictionary mapping URI to local filenames.
1071
+ :param extended: Enable extended validation features.
1072
+ :return: List of error strings; empty if valid.
1073
+ """
1074
+ validator = JSONStructureSchemaCoreValidator(allow_dollar=allow_dollar, allow_import=allow_import, import_map=import_map, extended=extended)
1075
+ return validator.validate(schema_document, source_text)
1076
+
1077
+
1078
+ def main():
1079
+ """Command line entry point for validating JSON Structure schema files."""
1080
+ import argparse
1081
+ parser = argparse.ArgumentParser(
1082
+ prog='json-structure-check',
1083
+ description='Validate JSON Structure schema files for conformance with the specification.',
1084
+ epilog='Example: json-structure-check schema.json'
1085
+ )
1086
+ parser.add_argument('schema_file', help='Path to the JSON Structure schema file to validate')
1087
+ parser.add_argument('--metaschema', action='store_true',
1088
+ help="Allow '$' in property names (for validating metaschemas)")
1089
+ parser.add_argument('--extended', '-e', action='store_true',
1090
+ help='Enable extended validation features (conditional composition, validation keywords)')
1091
+ parser.add_argument('--allowimport', '-i', action='store_true',
1092
+ help='Enable processing of $import and $importdefs keywords')
1093
+ parser.add_argument('--importmap', '-m', action='append', metavar='URI=FILE',
1094
+ help='Map import URI to local file (can be specified multiple times)')
1095
+ parser.add_argument('--quiet', '-q', action='store_true',
1096
+ help='Only output errors, suppress success message')
1097
+ args = parser.parse_args()
1098
+
1099
+ # Build import map from arguments
1100
+ import_map = {}
1101
+ if args.importmap:
1102
+ for mapping in args.importmap:
1103
+ if '=' not in mapping:
1104
+ print(f"Error: Invalid --importmap format '{mapping}'. Expected URI=FILE")
1105
+ sys.exit(1)
1106
+ uri, filename = mapping.split('=', 1)
1107
+ import_map[uri] = filename
1108
+
1109
+ try:
1110
+ with open(args.schema_file, "r", encoding="utf-8") as file_in:
1111
+ source_text = file_in.read()
1112
+ data = json.loads(source_text)
1113
+ except FileNotFoundError:
1114
+ print(f"Error: Schema file not found: {args.schema_file}")
1115
+ sys.exit(1)
1116
+ except json.JSONDecodeError as ex:
1117
+ print(f"Error: Invalid JSON in schema file: {ex.msg} (Line: {ex.lineno}, Column: {ex.colno})")
1118
+ sys.exit(1)
1119
+
1120
+ errors = validate_json_structure_schema_core(
1121
+ data, source_text,
1122
+ allow_dollar=args.metaschema,
1123
+ allow_import=args.allowimport,
1124
+ import_map=import_map,
1125
+ extended=args.extended
1126
+ )
1127
+ if errors:
1128
+ print("Schema is invalid:")
1129
+ for err in errors:
1130
+ print(" -", err)
1131
+ sys.exit(1)
1132
+ if not args.quiet:
1133
+ print("Schema is valid.")
1134
+
1135
+
1136
+ if __name__ == "__main__":
1137
+ main()