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,1247 @@
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_instance_validator.py
8
+
9
+ Validates JSON document instances against JSON Structures conforming to the experimental
10
+ JSON Structure Core specification (C. Vasters, Microsoft, February 2025), including
11
+ all constructs from the core spec: primitive types, compound types, abstract types,
12
+ $extends, $offers, $uses, as well as the JSON Structure JSONStructureImport extensions ($import and $importdefs).
13
+
14
+ Additionally, if the instance provides a "$uses" clause containing "JSONStructureConditionalComposition" and/or "JSONStructureValidation",
15
+ the corresponding conditional composition and validation addin constraints are enforced.
16
+ Extensions such as "JSONStructureAlternateNames" or "JSONStructureUnits" are generally ignored for validation.
17
+
18
+ Furthermore, when the root schema’s "$schema" equals
19
+ "https://json-structure.org/meta/extended/v0/#"
20
+ all addins (i.e. all keys offered in "$offers") are automatically enabled.
21
+
22
+ This implementation also supports extended validation keywords as defined in the
23
+ "JSON Structure JSONStructureValidation" spec, including numeric, string, array, object constraints,
24
+ and the "has" keyword.
25
+
26
+ Usage:
27
+ python json_structure_instance_validator.py <schema_file> <instance_file>
28
+
29
+ The code sections are annotated with references to the metaschema constructs.
30
+ """
31
+
32
+ import sys
33
+ import json
34
+ import re
35
+ import datetime
36
+ import uuid
37
+ from urllib.parse import urlparse
38
+
39
+ # Regular expressions for date, datetime, time, duration and JSON pointer.
40
+ _DATE_REGEX = re.compile(r'^\d{4}-\d{2}-\d{2}$')
41
+ _DATETIME_REGEX = re.compile(
42
+ r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+\-]\d{2}:\d{2})$'
43
+ )
44
+ _TIME_REGEX = re.compile(r'^\d{2}:\d{2}:\d{2}(?:\.\d+)?$')
45
+ # ISO 8601 duration pattern: P[n]Y[n]M[n]DT[n]H[n]M[n]S or P[n]W
46
+ _DURATION_REGEX = re.compile(
47
+ r'^P(?:\d+Y)?(?:\d+M)?(?:\d+D)?(?:T(?:\d+H)?(?:\d+M)?(?:\d+(?:\.\d+)?S)?)?$|^P\d+W$'
48
+ )
49
+ _JSONPOINTER_REGEX = re.compile(r'^#(\/[^\/]+)*$')
50
+
51
+
52
+ class JSONStructureInstanceValidator:
53
+ """
54
+ Validator for JSON document instances against full JSON Structure Core schemas.
55
+ Implements all core constructs including abstract types, $extends, $offers, $uses,
56
+ the JSONStructureImport extension ($import and $importdefs), as well as conditional composition
57
+ (allOf, anyOf, oneOf, not, if/then/else) and validation addin constraints.
58
+ """
59
+ ABSOLUTE_URI_REGEX = re.compile(r'^[a-zA-Z][a-zA-Z0-9+\-.]*://')
60
+
61
+ def __init__(self, root_schema, allow_import=False, import_map=None, extended=False, external_schemas=None):
62
+ """
63
+ Initializes the validator.
64
+ :param root_schema: The JSON Structure (as dict).
65
+ :param allow_import: Enables processing of $import/$importdefs.
66
+ :param import_map: Dict mapping URIs to local filenames.
67
+ :param extended: Enable extended validation features.
68
+ :param external_schemas: List of schema dicts to use for resolving imports by $id.
69
+ Each schema should have a '$id' field matching the import URI.
70
+ """
71
+ self.root_schema = root_schema
72
+ self.errors = []
73
+ self.allow_import = allow_import
74
+ self.import_map = import_map if import_map is not None else {}
75
+ self.extended = extended
76
+ self.enabled_extensions = set()
77
+ # Build lookup for external schemas by $id
78
+ self.external_schemas = {}
79
+ if external_schemas:
80
+ for schema in external_schemas:
81
+ if isinstance(schema, dict) and "$id" in schema:
82
+ self.external_schemas[schema["$id"]] = schema
83
+ # Process $import and $importdefs if enabled. [Metaschema: JSONStructureImport extension constructs]
84
+ if self.allow_import:
85
+ self._process_imports(self.root_schema, "#")
86
+ self._detect_enabled_extensions()
87
+
88
+ def _detect_enabled_extensions(self):
89
+ schema_uri = self.root_schema.get("$schema", "")
90
+ uses = self.root_schema.get("$uses", [])
91
+ if "extended" in schema_uri or "validation" in schema_uri:
92
+ self.enabled_extensions.add("JSONStructureConditionalComposition")
93
+ self.enabled_extensions.add("JSONStructureValidation")
94
+ if isinstance(uses, list):
95
+ for ext in uses:
96
+ self.enabled_extensions.add(ext)
97
+ # If extended=True was passed to constructor, enable validation extensions
98
+ if self.extended:
99
+ self.enabled_extensions.add("JSONStructureConditionalComposition")
100
+ self.enabled_extensions.add("JSONStructureValidation")
101
+
102
+ def validate_instance(self, instance, schema=None, path="#", meta=None):
103
+ """
104
+ Validates an instance against a schema.
105
+ Resolves $ref, processes $extends, rejects abstract schemas, applies $uses,
106
+ then validates based on type. Finally, conditionally validates conditional composition
107
+ and validation addin constraints.
108
+ :param instance: The JSON instance.
109
+ :param schema: The schema to validate against (defaults to root schema).
110
+ :param path: JSON Pointer for error reporting.
111
+ :return: List of error messages.
112
+ """
113
+ if schema is None:
114
+ schema = self.root_schema
115
+
116
+ # Handle $root - redirect to the designated root type
117
+ # [Metaschema: $root keyword designates a reusable type as the root]
118
+ if "$root" in schema and "type" not in schema:
119
+ root_ref = schema.get("$root")
120
+ if root_ref:
121
+ resolved = self._resolve_ref(root_ref)
122
+ if resolved is None:
123
+ self.errors.append(f"Cannot resolve $root reference {root_ref}")
124
+ return self.errors
125
+ return self.validate_instance(instance, resolved, path)
126
+
127
+ # --- Automatically enable all addins if using extended metaschema ---
128
+ # Only do this if $uses is present; otherwise, do NOT auto-enable addins (per spec)
129
+ if self.root_schema.get("$schema") == "https://json-structure.org/meta/extended/v0/#":
130
+ if "$uses" in schema:
131
+ all_addins = [
132
+ "JSONStructureConditionalComposition",
133
+ "JSONStructureValidation",
134
+ "JSONStructureUnits",
135
+ "JSONStructureAlternateNames"
136
+ ]
137
+ schema.setdefault("$uses", [])
138
+ for addin in all_addins:
139
+ if addin not in schema["$uses"]:
140
+ schema["$uses"].append(addin)
141
+ # If $uses is not present, do not auto-enable addins; enforcement is handled later
142
+
143
+ if isinstance(instance, dict) and "$uses" in instance and self.root_schema.get("$schema") == "https://json-structure.org/meta/validation/v0/#":
144
+ # Automatically enable the JSONStructureValidation addin.
145
+ schema.setdefault("$uses", [])
146
+ if "JSONStructureValidation" in instance["$uses"] and not "JSONStructureValidation" in schema["$uses"]:
147
+ schema["$uses"].append("JSONStructureValidation")
148
+ if "JSONStructureConditionalComposition" in instance["$uses"] and not "JSONStructureConditionalComposition" in schema["$uses"]:
149
+ schema["$uses"].append("JSONStructureConditionalComposition")
150
+ # [Metaschema: JSONStructureValidation metaschema automatically enables JSONStructureValidation addin]
151
+
152
+ # the core schema https://json-structure.org/meta/validation/v0/# has no JSONStructureConditionalComposition or JSONStructureValidation addins
153
+ # an instance referencing these addins will be rejected
154
+ if isinstance(instance, dict) and "$uses" in instance and self.root_schema.get("$schema") == "https://json-structure.org/meta/core/v0/#":
155
+ if "JSONStructureValidation" in instance["$uses"] or "JSONStructureConditionalComposition" in instance["$uses"]:
156
+ self.errors.append(
157
+ f"Instance at {path} references JSONStructureConditionalComposition or JSONStructureValidation addins but the schema does not support them")
158
+
159
+ # Resolve $ref at schema level. [Metaschema: TypeReference]
160
+ if "$ref" in schema:
161
+ ref = schema["$ref"]
162
+ resolved = self._resolve_ref(ref)
163
+ if resolved is None:
164
+ self.errors.append(f"Cannot resolve $ref {ref} at {path}")
165
+ return self.errors
166
+ return self.validate_instance(instance, resolved, path)
167
+
168
+ hasConditionals = False
169
+ if "$uses" in self.root_schema:
170
+ if "JSONStructureConditionalComposition" in self.root_schema["$uses"]:
171
+ hasConditionals = self._validate_conditionals(schema, instance, path) # Handle schemas that are only conditional composition at the root (no 'type')
172
+ conditional_keywords = ("allOf", "anyOf", "oneOf", "not", "if", "then", "else")
173
+ has_conditionals_at_root = any(k in schema for k in conditional_keywords)
174
+ if not schema.get("type") and has_conditionals_at_root:
175
+ schema_uri = self.root_schema.get("$schema", "")
176
+ is_validation = schema_uri.endswith("/validation/v0/#")
177
+ is_extended = schema_uri.endswith("/extended/v0/#")
178
+
179
+ # Check extended metaschema enforcement first
180
+ if is_extended and not (isinstance(self.root_schema, dict) and "$uses" in self.root_schema and "JSONStructureConditionalComposition" in self.root_schema["$uses"]):
181
+ self.errors.append(
182
+ "Conditional composition is not enabled: $uses must include 'JSONStructureConditionalComposition' for the extended metaschema")
183
+ return self.errors
184
+
185
+ enable_conditional = (
186
+ self.extended or
187
+ is_validation or
188
+ (isinstance(self.root_schema, dict) and "$uses" in self.root_schema and (
189
+ "JSONStructureConditionalComposition" in self.root_schema["$uses"] or "JSONStructureValidation" in self.root_schema["$uses"]
190
+ ))
191
+ )
192
+
193
+ if enable_conditional:
194
+ self._validate_conditionals(schema, instance, path)
195
+ return self.errors
196
+ else:
197
+ self.errors.append(f"Conditional composition keywords present at {path} but not enabled")
198
+ return self.errors
199
+
200
+ # Handle case where "type" is a dict with a $ref. [Metaschema: PrimitiveOrReference]
201
+ schema_type = schema.get("type")
202
+ if not schema_type:
203
+ self.errors.append(f"Schema at {path} has no 'type'")
204
+ return self.errors
205
+
206
+ if isinstance(schema_type, dict):
207
+ if "$ref" in schema_type:
208
+ resolved = self._resolve_ref(schema_type["$ref"])
209
+ if resolved is None:
210
+ self.errors.append(f"Cannot resolve $ref {schema_type['$ref']} at {path}/type")
211
+ return self.errors
212
+ new_schema = dict(schema)
213
+ new_schema["type"] = resolved.get("type")
214
+ if "properties" in resolved:
215
+ merged_props = dict(resolved.get("properties"))
216
+ merged_props.update(new_schema.get("properties", {}))
217
+ new_schema["properties"] = merged_props
218
+ # Also copy tuple keyword for tuple types
219
+ if "tuple" in resolved:
220
+ new_schema["tuple"] = resolved.get("tuple")
221
+ # Copy required if present
222
+ if "required" in resolved and "required" not in new_schema:
223
+ new_schema["required"] = resolved.get("required")
224
+ # Copy choices for choice types
225
+ if "choices" in resolved:
226
+ new_schema["choices"] = resolved.get("choices")
227
+ # Copy selector for inline unions
228
+ if "selector" in resolved:
229
+ new_schema["selector"] = resolved.get("selector")
230
+ # Copy $extends for inherited types
231
+ if "$extends" in resolved and "$extends" not in new_schema:
232
+ new_schema["$extends"] = resolved.get("$extends")
233
+ schema = new_schema
234
+ schema_type = schema.get("type")
235
+ else:
236
+ self.errors.append(f"Schema at {path} has invalid 'type'")
237
+ return self.errors
238
+
239
+ # Handle union types. [Metaschema: TypeUnion]
240
+ if isinstance(schema_type, list):
241
+ union_valid = False
242
+ union_errors = []
243
+ for t in schema_type:
244
+ backup = list(self.errors)
245
+ self.errors = []
246
+ self.validate_instance(instance, {"type": t}, path)
247
+ if not self.errors:
248
+ union_valid = True
249
+ break
250
+ else:
251
+ union_errors.extend(self.errors)
252
+ self.errors = backup
253
+ if not union_valid:
254
+ self.errors.append(f"Instance at {path} does not match any type in union: {union_errors}")
255
+ return self.errors
256
+
257
+ if not isinstance(schema_type, str):
258
+ self.errors.append(f"Schema at {path} has invalid 'type'")
259
+ return self.errors # Process $extends. [Metaschema: $extends in ObjectType/TupleType]
260
+ if schema_type != "choice" and "$extends" in schema:
261
+ base = self._resolve_ref(schema["$extends"])
262
+ if base is None:
263
+ self.errors.append(f"Cannot resolve $extends {schema['$extends']} at {path}")
264
+ return self.errors
265
+ base_props = base.get("properties", {})
266
+ derived_props = schema.get("properties", {})
267
+ for key in base_props:
268
+ if key in derived_props:
269
+ self.errors.append(
270
+ f"Property '{key}' is inherited via $extends and must not be redefined at {path}")
271
+ merged = dict(base)
272
+ merged.update(schema)
273
+ # Properly merge properties: base properties + derived properties
274
+ if "properties" in base or "properties" in schema:
275
+ merged_props = dict(base_props)
276
+ merged_props.update(derived_props)
277
+ merged["properties"] = merged_props
278
+ merged.pop("$extends", None)
279
+ merged.pop("abstract", None)
280
+ schema = merged
281
+
282
+ # Reject abstract schemas. [Metaschema: abstract property]
283
+ if schema.get("abstract") is True:
284
+ self.errors.append(f"Abstract schema at {path} cannot be used for instance validation")
285
+ return self.errors
286
+
287
+ # Process $uses add-in. [Metaschema: $offers and $uses]
288
+ if isinstance(instance, dict) and "$uses" in instance:
289
+ schema = self._apply_uses(schema, instance)
290
+ instance.pop("$uses")
291
+
292
+ # --- Begin type-based validation ---
293
+ # Primitive types.
294
+ if schema_type == "any":
295
+ pass
296
+ elif schema_type == "string":
297
+ if not isinstance(instance, str):
298
+ self.errors.append(f"Expected string at {path}, got {type(instance).__name__}")
299
+ elif schema_type == "number":
300
+ if isinstance(instance, bool) or not isinstance(instance, (int, float)):
301
+ self.errors.append(f"Expected number at {path}, got {type(instance).__name__}")
302
+ elif schema_type == "boolean":
303
+ if not isinstance(instance, bool):
304
+ self.errors.append(f"Expected boolean at {path}, got {type(instance).__name__}")
305
+ elif schema_type == "null":
306
+ if instance is not None:
307
+ self.errors.append(f"Expected null at {path}, got {type(instance).__name__}")
308
+ elif schema_type == "int8":
309
+ if not isinstance(instance, int):
310
+ self.errors.append(f"Expected int8 at {path}, got {type(instance).__name__}")
311
+ elif not (-2**7 <= instance <= 2**7 - 1):
312
+ self.errors.append(f"int8 value at {path} out of range")
313
+ elif schema_type == "uint8":
314
+ if not isinstance(instance, int):
315
+ self.errors.append(f"Expected uint8 at {path}, got {type(instance).__name__}")
316
+ elif not (0 <= instance <= 2**8 - 1):
317
+ self.errors.append(f"uint8 value at {path} out of range")
318
+ elif schema_type == "int16":
319
+ if not isinstance(instance, int):
320
+ self.errors.append(f"Expected int16 at {path}, got {type(instance).__name__}")
321
+ elif not (-2**15 <= instance <= 2**15 - 1):
322
+ self.errors.append(f"int16 value at {path} out of range")
323
+ elif schema_type == "uint16":
324
+ if not isinstance(instance, int):
325
+ self.errors.append(f"Expected uint16 at {path}, got {type(instance).__name__}")
326
+ elif not (0 <= instance <= 2**16 - 1):
327
+ self.errors.append(f"uint16 value at {path} out of range")
328
+ elif schema_type == "int32" or schema_type == "integer":
329
+ if not isinstance(instance, int):
330
+ self.errors.append(f"Expected {schema_type} at {path}, got {type(instance).__name__}")
331
+ elif not (-2**31 <= instance <= 2**31 - 1):
332
+ self.errors.append(f"{schema_type} value at {path} out of range")
333
+ elif schema_type == "uint32":
334
+ if not isinstance(instance, int):
335
+ self.errors.append(f"Expected uint32 at {path}, got {type(instance).__name__}")
336
+ elif not (0 <= instance <= 2**32 - 1):
337
+ self.errors.append(f"uint32 value at {path} out of range")
338
+ elif schema_type == "int64":
339
+ if not isinstance(instance, str):
340
+ self.errors.append(f"Expected int64 as string at {path}, got {type(instance).__name__}")
341
+ else:
342
+ try:
343
+ value = int(instance)
344
+ if not (-2**63 <= value <= 2**63 - 1):
345
+ self.errors.append(f"int64 value at {path} out of range")
346
+ except ValueError:
347
+ self.errors.append(f"Invalid int64 format at {path}")
348
+ elif schema_type == "uint64":
349
+ if not isinstance(instance, str):
350
+ self.errors.append(f"Expected uint64 as string at {path}, got {type(instance).__name__}")
351
+ else:
352
+ try:
353
+ value = int(instance)
354
+ if not (0 <= value <= 2**64 - 1):
355
+ self.errors.append(f"uint64 value at {path} out of range")
356
+ except ValueError:
357
+ self.errors.append(f"Invalid uint64 format at {path}")
358
+ elif schema_type == "int128":
359
+ if not isinstance(instance, str):
360
+ self.errors.append(f"Expected int128 as string at {path}, got {type(instance).__name__}")
361
+ else:
362
+ try:
363
+ value = int(instance)
364
+ if not (-2**127 <= value <= 2**127 - 1):
365
+ self.errors.append(f"int128 value at {path} out of range")
366
+ except ValueError:
367
+ self.errors.append(f"Invalid int128 format at {path}")
368
+ elif schema_type == "uint128":
369
+ if not isinstance(instance, str):
370
+ self.errors.append(f"Expected uint128 as string at {path}, got {type(instance).__name__}")
371
+ else:
372
+ try:
373
+ value = int(instance)
374
+ if not (0 <= value <= 2**128 - 1):
375
+ self.errors.append(f"uint128 value at {path} out of range")
376
+ except ValueError:
377
+ self.errors.append(f"Invalid uint128 format at {path}")
378
+ elif schema_type == "float8":
379
+ if not isinstance(instance, (int, float)):
380
+ self.errors.append(f"Expected float8 at {path}, got {type(instance).__name__}")
381
+ elif schema_type in ("float", "double"):
382
+ if not isinstance(instance, (int, float)):
383
+ self.errors.append(f"Expected {schema_type} at {path}, got {type(instance).__name__}")
384
+ elif schema_type == "decimal":
385
+ if not isinstance(instance, str):
386
+ self.errors.append(f"Expected decimal as string at {path}, got {type(instance).__name__}")
387
+ else:
388
+ try:
389
+ float(instance)
390
+ except ValueError:
391
+ self.errors.append(f"Invalid decimal format at {path}")
392
+ elif schema_type == "date":
393
+ if not isinstance(instance, str) or not _DATE_REGEX.match(instance):
394
+ self.errors.append(f"Expected date (YYYY-MM-DD) at {path}")
395
+ elif schema_type == "datetime":
396
+ if not isinstance(instance, str) or not _DATETIME_REGEX.match(instance):
397
+ self.errors.append(f"Expected datetime (RFC3339) at {path}")
398
+ elif schema_type == "time":
399
+ if not isinstance(instance, str) or not _TIME_REGEX.match(instance):
400
+ self.errors.append(f"Expected time (HH:MM:SS) at {path}")
401
+ elif schema_type == "duration":
402
+ if not isinstance(instance, str):
403
+ self.errors.append(f"Expected duration as string at {path}")
404
+ elif not _DURATION_REGEX.match(instance):
405
+ self.errors.append(f"Expected duration (ISO 8601 format) at {path}")
406
+ elif schema_type == "uuid":
407
+ if not isinstance(instance, str):
408
+ self.errors.append(f"Expected uuid as string at {path}")
409
+ else:
410
+ try:
411
+ uuid.UUID(instance)
412
+ except ValueError:
413
+ self.errors.append(f"Invalid uuid format at {path}")
414
+ elif schema_type == "uri":
415
+ if not isinstance(instance, str):
416
+ self.errors.append(f"Expected uri as string at {path}")
417
+ else:
418
+ parsed = urlparse(instance)
419
+ if not parsed.scheme:
420
+ self.errors.append(f"Invalid uri format at {path}")
421
+ elif schema_type == "binary":
422
+ if not isinstance(instance, str):
423
+ self.errors.append(f"Expected binary (base64 string) at {path}")
424
+ elif schema_type == "jsonpointer":
425
+ if not isinstance(instance, str) or not _JSONPOINTER_REGEX.match(instance):
426
+ self.errors.append(f"Expected JSON pointer format at {path}")
427
+ # Compound types.
428
+ elif schema_type == "object":
429
+ # Validate schema: properties MUST have at least one entry if present,
430
+ # unless the schema uses $extends (properties may be inherited)
431
+ if "properties" in schema:
432
+ props_def = schema["properties"]
433
+ if not isinstance(props_def, dict) or (len(props_def) == 0 and "$extends" not in schema):
434
+ self.errors.append(f"Object schema at {path} has 'properties' but it is empty - properties MUST have at least one entry")
435
+ return self.errors
436
+
437
+ if not isinstance(instance, dict):
438
+ self.errors.append(f"Expected object at {path}, got {type(instance).__name__}")
439
+ else:
440
+ props = schema.get("properties", {})
441
+ req = schema.get("required", [])
442
+ for r in req:
443
+ if r not in instance:
444
+ self.errors.append(f"Missing required property '{r}' at {path}")
445
+ for prop, prop_schema in props.items():
446
+ if prop in instance:
447
+ self.validate_instance(instance[prop], prop_schema, f"{path}/{prop}")
448
+ if "additionalProperties" in schema:
449
+ addl = schema["additionalProperties"]
450
+ # $schema is a built-in property allowed in all instances
451
+ reserved_props = {"$schema"}
452
+ if addl is False:
453
+ for key in instance.keys():
454
+ if key not in props and key not in reserved_props:
455
+ self.errors.append(f"Additional property '{key}' not allowed at {path}")
456
+ elif isinstance(addl, dict):
457
+ for key in instance.keys():
458
+ if key not in props and key not in reserved_props:
459
+ self.validate_instance(instance[key], addl, f"{path}/{key}")
460
+ # Extended object constraint: "has" keyword. [Metaschema: ObjectValidationAddIn]
461
+ if "has" in schema:
462
+ has_schema = schema["has"]
463
+ valid = any(len(self.validate_instance(val, has_schema, f"{path}/{prop}")) == 0
464
+ for prop, val in instance.items())
465
+ if not valid:
466
+ self.errors.append(f"Object at {path} does not have any property satisfying 'has' schema")
467
+ # dependencies (dependentRequired) validation
468
+ if "dependentRequired" in schema and isinstance(schema["dependentRequired"], dict):
469
+ for prop_name, required_deps in schema["dependentRequired"].items():
470
+ if prop_name in instance and isinstance(required_deps, list):
471
+ for dep in required_deps:
472
+ if dep not in instance:
473
+ self.errors.append(
474
+ f"Property '{prop_name}' at {path} requires dependent property '{dep}'")
475
+ elif schema_type == "array":
476
+ if not isinstance(instance, list):
477
+ self.errors.append(f"Expected array at {path}, got {type(instance).__name__}")
478
+ else:
479
+ items_schema = schema.get("items")
480
+ if items_schema:
481
+ for idx, item in enumerate(instance):
482
+ self.validate_instance(item, items_schema, f"{path}[{idx}]")
483
+ elif schema_type == "set":
484
+ if not isinstance(instance, list):
485
+ self.errors.append(f"Expected set (unique array) at {path}, got {type(instance).__name__}")
486
+ else:
487
+ serialized = [json.dumps(x, sort_keys=True) for x in instance]
488
+ if len(serialized) != len(set(serialized)):
489
+ self.errors.append(f"Set at {path} contains duplicate items")
490
+ items_schema = schema.get("items")
491
+ if items_schema:
492
+ for idx, item in enumerate(instance):
493
+ self.validate_instance(item, items_schema, f"{path}[{idx}]")
494
+ elif schema_type == "map":
495
+ if not isinstance(instance, dict):
496
+ self.errors.append(f"Expected map (object) at {path}, got {type(instance).__name__}")
497
+ else:
498
+ # Map keys MAY be any valid JSON string (no restrictions on key format)
499
+ values_schema = schema.get("values")
500
+ if values_schema:
501
+ for key, val in instance.items():
502
+ self.validate_instance(val, values_schema, f"{path}/{key}")
503
+ elif schema_type == "tuple":
504
+ if not isinstance(instance, list):
505
+ self.errors.append(f"Expected tuple (array) at {path}, got {type(instance).__name__}")
506
+ else:
507
+ # Retrieve the tuple ordering
508
+ order = schema.get("tuple")
509
+ props = schema.get("properties", {})
510
+ if order is None:
511
+ self.errors.append(f"Tuple schema at {path} is missing the required 'tuple' keyword for ordering")
512
+ elif not isinstance(order, list):
513
+ self.errors.append(f"'tuple' keyword at {path} must be an array of property names")
514
+ else:
515
+ # Verify each name in order exists in properties
516
+ for prop_name in order:
517
+ if prop_name not in props:
518
+ self.errors.append(f"Tuple order key '{prop_name}' at {path} not defined in properties")
519
+ expected_len = len(order)
520
+ if len(instance) != expected_len:
521
+ self.errors.append(f"Tuple at {path} length {len(instance)} does not equal expected {expected_len}")
522
+ else:
523
+ for idx, prop_name in enumerate(order):
524
+ prop_schema = props[prop_name]
525
+ self.validate_instance(instance[idx], prop_schema, f"{path}/{prop_name}")
526
+ elif schema_type == "choice":
527
+ if not isinstance(instance, dict):
528
+ self.errors.append(f"Expected choice object at {path}, got {type(instance).__name__}")
529
+ else:
530
+ choices = schema.get("choices", {})
531
+ extends = schema.get("$extends")
532
+ selector = schema.get("selector")
533
+ if extends is None:
534
+ # Tagged union: exactly one property matching a choice key
535
+ if len(instance) != 1:
536
+ self.errors.append(f"Tagged union at {path} must have a single property")
537
+ else:
538
+ key, value = next(iter(instance.items()))
539
+ if key not in choices:
540
+ self.errors.append(f"Property '{key}' at {path} not one of choices {list(choices.keys())}")
541
+ else:
542
+ self.validate_instance(value, choices[key], f"{path}/{key}")
543
+ else:
544
+ # Inline union: must have selector property
545
+ if selector is None:
546
+ self.errors.append(f"Inline union at {path} missing 'selector' in schema")
547
+ else:
548
+ sel_val = instance.get(selector)
549
+ if not isinstance(sel_val, str):
550
+ self.errors.append(f"Selector '{selector}' at {path} must be a string")
551
+ elif sel_val not in choices:
552
+ self.errors.append(f"Selector '{sel_val}' at {path} not one of choices {list(choices.keys())}")
553
+ else:
554
+ # validate remaining properties against chosen variant
555
+ variant = choices[sel_val]
556
+ inst_copy = dict(instance)
557
+ inst_copy.pop(selector, None)
558
+ self.validate_instance(inst_copy, variant, path)
559
+ else:
560
+ self.errors.append(f"Unsupported type '{schema_type}' at {path}")
561
+
562
+ # --- Enforce extended features if enabled ---
563
+ # Only enable conditional composition if explicitly enabled via $uses or the validation metaschema
564
+ schema_uri = self.root_schema.get("$schema", "")
565
+ is_validation = schema_uri.endswith("/validation/v0/#")
566
+ is_extended = schema_uri.endswith("/extended/v0/#")
567
+ # Only enable if:
568
+ # - self.extended is set (CLI override)
569
+ # - validation metaschema (enables both addins by default)
570
+ # - $uses in schema explicitly enables the addin
571
+ enable_conditional = (
572
+ self.extended or
573
+ is_validation or
574
+ (isinstance(schema, dict) and "$uses" in schema and (
575
+ "JSONStructureConditionalComposition" in schema["$uses"] or "JSONStructureValidation" in schema["$uses"]
576
+ ))
577
+ )
578
+ # If the schema is the extended metaschema and has any conditional composition keyword but does NOT have $uses, this is an error (per spec)
579
+ conditional_keywords = ("allOf", "anyOf", "oneOf", "not", "if", "then", "else")
580
+ if is_extended and any(k in schema for k in conditional_keywords):
581
+ if not (isinstance(schema, dict) and "$uses" in schema and "JSONStructureConditionalComposition" in schema["$uses"]):
582
+ self.errors.append(
583
+ "Conditional composition is not enabled: $uses must include 'JSONStructureConditionalComposition' for the extended metaschema")
584
+ return self.errors
585
+ if enable_conditional:
586
+ # Conditional composition (allOf, anyOf, oneOf, not, if/then/else)
587
+ if ("JSONStructureConditionalComposition" in self.enabled_extensions or
588
+ is_validation or
589
+ (isinstance(schema, dict) and "$uses" in schema and "JSONStructureConditionalComposition" in schema["$uses"])):
590
+ self._validate_conditionals(schema, instance, path)
591
+ # Validation keywords (min/max, pattern, etc.)
592
+ if ("JSONStructureValidation" in self.enabled_extensions or
593
+ is_validation or
594
+ (isinstance(schema, dict) and "$uses" in schema and "JSONStructureValidation" in schema["$uses"])):
595
+ self._validate_validation_addins(schema, instance, path)
596
+
597
+ if "const" in schema:
598
+ if instance != schema["const"]:
599
+ self.errors.append(f"Value at {path} does not equal const {schema['const']}")
600
+ if "enum" in schema:
601
+ if instance not in schema["enum"]:
602
+ self.errors.append(f"Value at {path} not in enum {schema['enum']}")
603
+ return self.errors
604
+
605
+ def validate(self, instance, schema=None):
606
+ if schema is None:
607
+ schema = self.root_schema
608
+
609
+ # First, run the core validation (handles $root, types, required, etc.)
610
+ # Pass None for schema to trigger $root handling if this is the root schema
611
+ self.errors = []
612
+ self.validate_instance(instance, None if schema is self.root_schema else schema, "#")
613
+ errors = list(self.errors)
614
+
615
+ # Extended: conditional composition
616
+ if self.extended and "JSONStructureConditionalComposition" in self.enabled_extensions:
617
+ for key in ("allOf", "anyOf", "oneOf"):
618
+ if key in schema:
619
+ subschemas = schema[key]
620
+ if key == "allOf":
621
+ for idx, subschema in enumerate(subschemas):
622
+ errors += self.validate(instance, subschema)
623
+ elif key == "anyOf":
624
+ if not any(not self.validate(instance, subschema) for subschema in subschemas):
625
+ errors.append(f"Instance does not match anyOf at {key}")
626
+ elif key == "oneOf":
627
+ matches = sum(1 for subschema in subschemas if not self.validate(instance, subschema))
628
+ if matches != 1:
629
+ errors.append(f"Instance does not match exactly one subschema in oneOf at {key}")
630
+ if "not" in schema:
631
+ if not self.validate(instance, schema["not"]):
632
+ errors.append("Instance must not match 'not' subschema")
633
+ if "if" in schema:
634
+ if not self.validate(instance, schema["if"]):
635
+ if "else" in schema:
636
+ errors += self.validate(instance, schema["else"])
637
+ else:
638
+ if "then" in schema:
639
+ errors += self.validate(instance, schema["then"])
640
+ # Extended: validation keywords
641
+ if self.extended and "JSONStructureValidation" in self.enabled_extensions:
642
+ t = schema.get("type")
643
+ if t == "string":
644
+ if "minLength" in schema and isinstance(instance, str):
645
+ if len(instance) < schema["minLength"]:
646
+ errors.append(f"String shorter than minLength {schema['minLength']}")
647
+ if "pattern" in schema and isinstance(instance, str):
648
+ import re
649
+ if not re.match(schema["pattern"], instance):
650
+ errors.append(f"String does not match pattern {schema['pattern']}")
651
+ if t in ("number", "integer", "float", "double", "float8", "decimal",
652
+ "int8", "uint8", "int16", "uint16", "int32", "uint32",
653
+ "int64", "uint64", "int128", "uint128"):
654
+ if "minimum" in schema and instance < schema["minimum"]:
655
+ errors.append(f"Number less than minimum {schema['minimum']}")
656
+ if "maximum" in schema and instance > schema["maximum"]:
657
+ errors.append(f"Number greater than maximum {schema['maximum']}")
658
+ if "multipleOf" in schema and instance % schema["multipleOf"] != 0:
659
+ errors.append(f"Number not a multiple of {schema['multipleOf']}")
660
+ if t == "array":
661
+ if "minItems" in schema and len(instance) < schema["minItems"]:
662
+ errors.append(f"Array has fewer than minItems {schema['minItems']}")
663
+ if "maxItems" in schema and len(instance) > schema["maxItems"]:
664
+ errors.append(f"Array has more than maxItems {schema['maxItems']}")
665
+ if "uniqueItems" in schema and schema["uniqueItems"]:
666
+ if len(instance) != len(set(map(str, instance))):
667
+ errors.append("Array items are not unique")
668
+ return errors
669
+
670
+ def _validate_conditionals(self, schema, instance, path) -> bool:
671
+ """
672
+ Validates conditional composition keywords: allOf, anyOf, oneOf, not, if/then/else.
673
+ [Metaschema: JSON Structure Conditional Composition]
674
+ returns True if the instance contains any conditional composition keywords
675
+ """
676
+ hasConditionals = False
677
+ if "allOf" in schema:
678
+ hasConditionals = True
679
+ subschemas = schema["allOf"]
680
+ for idx, subschema in enumerate(subschemas):
681
+ backup = list(self.errors)
682
+ # Ensure subschema inherits validation context from parent
683
+ enhanced_subschema = dict(subschema)
684
+ if self.root_schema.get("$uses"):
685
+ if "$uses" not in enhanced_subschema:
686
+ enhanced_subschema["$uses"] = list(self.root_schema["$uses"])
687
+ else:
688
+ # Merge validation addins
689
+ for addin in self.root_schema["$uses"]:
690
+ if addin not in enhanced_subschema["$uses"]:
691
+ enhanced_subschema["$uses"].append(addin)
692
+ self.validate_instance(instance, enhanced_subschema, f"{path}/allOf[{idx}]")
693
+ if self.errors:
694
+ self.errors = backup + self.errors
695
+ if "anyOf" in schema:
696
+ hasConditionals = True
697
+ subschemas = schema["anyOf"]
698
+ valid = False
699
+ errors_any = []
700
+ for idx, subschema in enumerate(subschemas):
701
+ backup = list(self.errors)
702
+ self.errors = []
703
+ # Ensure subschema inherits validation context from parent
704
+ enhanced_subschema = dict(subschema)
705
+ if self.root_schema.get("$uses"):
706
+ if "$uses" not in enhanced_subschema:
707
+ enhanced_subschema["$uses"] = list(self.root_schema["$uses"])
708
+ else:
709
+ # Merge validation addins
710
+ for addin in self.root_schema["$uses"]:
711
+ if addin not in enhanced_subschema["$uses"]:
712
+ enhanced_subschema["$uses"].append(addin)
713
+ self.validate_instance(instance, enhanced_subschema, f"{path}/anyOf[{idx}]")
714
+ if not self.errors:
715
+ valid = True
716
+ break
717
+ else:
718
+ errors_any.append(f"anyOf[{idx}]: {self.errors}")
719
+ self.errors = backup
720
+ if not valid:
721
+ self.errors.append(f"Instance at {path} does not satisfy anyOf: {errors_any}")
722
+ if "oneOf" in schema:
723
+ hasConditionals = True
724
+ subschemas = schema["oneOf"]
725
+ valid_count = 0
726
+ errors_one = []
727
+ for idx, subschema in enumerate(subschemas):
728
+ backup = list(self.errors)
729
+ self.errors = []
730
+ # Ensure subschema inherits validation context from parent
731
+ enhanced_subschema = dict(subschema)
732
+ if self.root_schema.get("$uses"):
733
+ if "$uses" not in enhanced_subschema:
734
+ enhanced_subschema["$uses"] = list(self.root_schema["$uses"])
735
+ else:
736
+ # Merge validation addins
737
+ for addin in self.root_schema["$uses"]:
738
+ if addin not in enhanced_subschema["$uses"]:
739
+ enhanced_subschema["$uses"].append(addin)
740
+ self.validate_instance(instance, enhanced_subschema, f"{path}/oneOf[{idx}]")
741
+ if not self.errors:
742
+ valid_count += 1
743
+ else:
744
+ errors_one.append(f"oneOf[{idx}]: {self.errors}")
745
+ self.errors = backup
746
+ if valid_count != 1:
747
+ self.errors.append(
748
+ f"Instance at {path} must match exactly one subschema in oneOf; matched {valid_count}. Details: {errors_one}")
749
+ if "not" in schema:
750
+ hasConditionals = True
751
+ subschema = schema["not"]
752
+ backup = list(self.errors)
753
+ self.errors = []
754
+ self.validate_instance(instance, subschema, f"{path}/not")
755
+ if not self.errors:
756
+ self.errors = backup + [f"Instance at {path} should not validate against 'not' schema"]
757
+ else:
758
+ self.errors = backup
759
+ if "if" in schema:
760
+ hasConditionals = True
761
+ backup = list(self.errors)
762
+ self.errors = []
763
+ self.validate_instance(instance, schema["if"], f"{path}/if")
764
+ if_valid = not self.errors
765
+ self.errors = backup
766
+ if if_valid:
767
+ if "then" in schema:
768
+ self.validate_instance(instance, schema["then"], f"{path}/then")
769
+ else:
770
+ if "else" in schema:
771
+ self.validate_instance(instance, schema["else"], f"{path}/else")
772
+ return hasConditionals
773
+
774
+ def _validate_validation_addins(self, schema, instance, path):
775
+ """
776
+ Validates additional constraints defined by the JSONStructureValidation addins.
777
+ [Metaschema: JSON Structure JSONStructureValidation]
778
+ """
779
+ # Numeric constraints.
780
+ if schema.get("type") in ("number", "integer", "float", "double", "decimal",
781
+ "int8", "uint8", "int16", "uint16", "int32", "uint32",
782
+ "int64", "uint64", "int128", "uint128", "float8"):
783
+ if "minimum" in schema:
784
+ try:
785
+ if instance < schema["minimum"]:
786
+ self.errors.append(f"Value at {path} is less than minimum {schema['minimum']}")
787
+ except Exception:
788
+ self.errors.append(f"Cannot compare value at {path} with minimum constraint")
789
+ if "maximum" in schema:
790
+ try:
791
+ if instance > schema["maximum"]:
792
+ self.errors.append(f"Value at {path} is greater than maximum {schema['maximum']}")
793
+ except Exception:
794
+ self.errors.append(f"Cannot compare value at {path} with maximum constraint")
795
+ if schema.get("exclusiveMinimum") is True:
796
+ try:
797
+ if instance <= schema.get("minimum", float("-inf")):
798
+ self.errors.append(
799
+ f"Value at {path} is not greater than exclusive minimum {schema.get('minimum')}")
800
+ except Exception:
801
+ self.errors.append(f"Cannot evaluate exclusiveMinimum constraint at {path}")
802
+ if schema.get("exclusiveMaximum") is True:
803
+ try:
804
+ if instance >= schema.get("maximum", float("inf")): self.errors.append(
805
+ f"Value at {path} is not less than exclusive maximum {schema.get('maximum')}")
806
+ except Exception:
807
+ self.errors.append(f"Cannot evaluate exclusiveMaximum constraint at {path}")
808
+ if "multipleOf" in schema:
809
+ try:
810
+ # Handle floating point precision issues
811
+ multiple_of = schema["multipleOf"]
812
+ quotient = instance / multiple_of
813
+ # Check if the quotient is close to an integer within a small tolerance
814
+ if abs(quotient - round(quotient)) > 1e-10:
815
+ self.errors.append(f"Value at {path} is not a multiple of {schema['multipleOf']}")
816
+ except Exception:
817
+ self.errors.append(f"Cannot evaluate multipleOf constraint at {path}")
818
+
819
+ # String constraints.
820
+ if schema.get("type") == "string":
821
+ if "minLength" in schema:
822
+ try:
823
+ if len(instance) < schema["minLength"]:
824
+ self.errors.append(f"String at {path} shorter than minLength {schema['minLength']}")
825
+ except TypeError:
826
+ self.errors.append(f"Invalid minLength constraint at {path}")
827
+ if "maxLength" in schema:
828
+ try:
829
+ if len(instance) > schema["maxLength"]:
830
+ self.errors.append(f"String at {path} exceeds maxLength {schema['maxLength']}")
831
+ except TypeError:
832
+ self.errors.append(f"Invalid maxLength constraint at {path}")
833
+ if "pattern" in schema:
834
+ try:
835
+ pattern = re.compile(schema["pattern"])
836
+ if not pattern.search(instance):
837
+ self.errors.append(f"String at {path} does not match pattern {schema['pattern']}")
838
+ except (re.error, TypeError):
839
+ self.errors.append(f"Invalid pattern constraint at {path}")
840
+ if "format" in schema:
841
+ fmt = schema["format"]
842
+ try:
843
+ if fmt == "email":
844
+ # Simple email validation
845
+ if "@" not in instance or not re.match(r'^[^@]+@[^@]+\.[^@]+$', instance):
846
+ self.errors.append(f"String at {path} does not match format email")
847
+ elif fmt == "ipv4":
848
+ # IPv4 validation
849
+ parts = instance.split('.')
850
+ if len(parts) != 4 or not all(0 <= int(part) <= 255 for part in parts):
851
+ self.errors.append(f"String at {path} does not match format ipv4")
852
+ elif fmt == "ipv6":
853
+ # Basic IPv6 validation
854
+ if not re.match(r'^[0-9a-fA-F:]+$', instance):
855
+ self.errors.append(f"String at {path} does not match format ipv6")
856
+ elif fmt == "uri":
857
+ parsed = urlparse(instance)
858
+ if not parsed.scheme:
859
+ self.errors.append(f"String at {path} does not match format uri")
860
+ elif fmt == "hostname":
861
+ if not re.match(r'^[a-zA-Z0-9.-]+$', instance):
862
+ self.errors.append(f"String at {path} does not match format hostname")
863
+ # Add more format validations as needed
864
+ except (ValueError, TypeError):
865
+ self.errors.append(f"String at {path} does not match format {fmt}") # Array constraints.
866
+ if schema.get("type") == "array":
867
+ if "minItems" in schema:
868
+ if len(instance) < schema["minItems"]:
869
+ self.errors.append(f"Array at {path} has fewer items than minItems {schema['minItems']}")
870
+ if "maxItems" in schema:
871
+ if len(instance) > schema["maxItems"]:
872
+ self.errors.append(f"Array at {path} has more items than maxItems {schema['maxItems']}")
873
+ if schema.get("uniqueItems") is True:
874
+ serialized = [json.dumps(x, sort_keys=True) for x in instance]
875
+ if len(serialized) != len(set(serialized)):
876
+ self.errors.append(f"Array at {path} does not have unique items")
877
+
878
+ # contains validation
879
+ if "contains" in schema:
880
+ contains_schema = schema["contains"]
881
+ matches = []
882
+ for i, item in enumerate(instance):
883
+ temp_validator = JSONStructureInstanceValidator(contains_schema, import_map=self.import_map, allow_import=self.allow_import, external_schemas=list(self.external_schemas.values()) if self.external_schemas else None)
884
+ item_errors = temp_validator.validate_instance(item)
885
+ if not item_errors:
886
+ matches.append(i)
887
+
888
+ if not matches:
889
+ self.errors.append(f"Array at {path} does not contain required element")
890
+
891
+ # minContains validation
892
+ if "minContains" in schema:
893
+ if len(matches) < schema["minContains"]:
894
+ self.errors.append(f"Array at {path} contains fewer than minContains {schema['minContains']} matching elements")
895
+
896
+ # maxContains validation
897
+ if "maxContains" in schema:
898
+ if len(matches) > schema["maxContains"]:
899
+ self.errors.append(f"Array at {path} contains more than maxContains {schema['maxContains']} matching elements")
900
+ # Object constraints.
901
+ if schema.get("type") == "object":
902
+ if "minProperties" in schema:
903
+ if len(instance.keys()) < schema["minProperties"]:
904
+ self.errors.append(
905
+ f"Object at {path} has fewer properties than minProperties {schema['minProperties']}")
906
+ if "maxProperties" in schema:
907
+ if len(instance.keys()) > schema["maxProperties"]:
908
+ self.errors.append(
909
+ f"Object at {path} has more properties than maxProperties {schema['maxProperties']}")
910
+
911
+ # patternProperties validation
912
+ if "patternProperties" in schema and isinstance(schema["patternProperties"], dict):
913
+ for pattern_str, pattern_schema in schema["patternProperties"].items():
914
+ try:
915
+ pattern = re.compile(pattern_str)
916
+ for prop_name, prop_value in instance.items():
917
+ if pattern.search(prop_name):
918
+ self.validate_instance(prop_value, pattern_schema, f"{path}/{prop_name}")
919
+ except re.error:
920
+ self.errors.append(f"Invalid regular expression '{pattern_str}' in patternProperties at {path}")
921
+
922
+ # propertyNames validation
923
+ if "propertyNames" in schema:
924
+ property_names_schema = schema["propertyNames"]
925
+ if not isinstance(property_names_schema, dict) or property_names_schema.get("type") != "string":
926
+ self.errors.append(f"propertyNames schema must be of type string at {path}")
927
+ else:
928
+ for prop_name in instance.keys():
929
+ self.validate_instance(prop_name, property_names_schema, f"{path}/propertyName({prop_name})")
930
+
931
+ # dependencies (dependentRequired) validation
932
+ if "dependentRequired" in schema and isinstance(schema["dependentRequired"], dict):
933
+ for prop_name, required_deps in schema["dependentRequired"].items():
934
+ if prop_name in instance and isinstance(required_deps, list):
935
+ for dep in required_deps:
936
+ if dep not in instance:
937
+ self.errors.append(
938
+ f"Property '{prop_name}' at {path} requires dependent property '{dep}'") # Map constraints
939
+ if schema.get("type") == "map":
940
+ # minEntries and maxEntries validation
941
+ if "minEntries" in schema:
942
+ if len(instance) < schema["minEntries"]:
943
+ self.errors.append(f"Map at {path} has fewer than minEntries {schema['minEntries']}")
944
+ if "maxEntries" in schema:
945
+ if len(instance) > schema["maxEntries"]:
946
+ self.errors.append(f"Map at {path} has more than maxEntries {schema['maxEntries']}")
947
+
948
+ # patternKeys validation
949
+ if "patternKeys" in schema and isinstance(schema["patternKeys"], dict):
950
+ for pattern_str, pattern_schema in schema["patternKeys"].items():
951
+ try:
952
+ pattern = re.compile(pattern_str)
953
+ for key_name, key_value in instance.items():
954
+ if pattern.search(key_name):
955
+ self.validate_instance(key_value, pattern_schema, f"{path}/{key_name}")
956
+ except re.error:
957
+ self.errors.append(f"Invalid regular expression '{pattern_str}' in patternKeys at {path}")
958
+
959
+ # keyNames validation
960
+ if "keyNames" in schema:
961
+ key_names_schema = schema["keyNames"]
962
+ if not isinstance(key_names_schema, dict) or key_names_schema.get("type") != "string":
963
+ self.errors.append(f"keyNames schema must be of type string at {path}")
964
+ else:
965
+ for key_name in instance.keys():
966
+ # Ensure validation addins are enabled for keyNames schema validation
967
+ keynames_validation_schema = dict(key_names_schema)
968
+ if "$uses" not in keynames_validation_schema:
969
+ keynames_validation_schema["$uses"] = ["JSONStructureValidation"]
970
+ elif "JSONStructureValidation" not in keynames_validation_schema["$uses"]:
971
+ keynames_validation_schema["$uses"].append("JSONStructureValidation")
972
+
973
+ temp_validator = JSONStructureInstanceValidator(keynames_validation_schema, import_map=self.import_map, allow_import=self.allow_import, external_schemas=list(self.external_schemas.values()) if self.external_schemas else None)
974
+ key_errors = temp_validator.validate_instance(key_name)
975
+ if key_errors:
976
+ self.errors.append(f"Map key name '{key_name}' at {path} does not match keyNames constraint")
977
+
978
+ def _resolve_ref(self, ref):
979
+ """
980
+ Resolves a $ref within the root schema using JSON Pointer syntax.
981
+ [Metaschema: TypeReference]
982
+ :param ref: A JSON pointer string starting with '#'.
983
+ :return: The referenced schema object or None.
984
+ """
985
+ if not ref.startswith("#"):
986
+ return None
987
+ parts = ref.lstrip("#").split("/")
988
+ target = self.root_schema
989
+ for part in parts:
990
+ if part == "":
991
+ continue
992
+ part = part.replace("~1", "/").replace("~0", "~")
993
+ if isinstance(target, dict) and part in target:
994
+ target = target[part]
995
+ else:
996
+ return None
997
+ return target
998
+
999
+ def _rewrite_refs(self, obj, target_path):
1000
+ """
1001
+ Recursively rewrites $ref pointers in an imported schema to be relative to the target path.
1002
+ When a schema is imported at path (e.g., #/definitions/People), all internal $ref pointers
1003
+ like #/definitions/X or #/X need to be rewritten to point to target_path/X.
1004
+ [Metaschema: JSONStructureImport extension - reference rewriting]
1005
+ :param obj: The imported schema object to rewrite.
1006
+ :param target_path: The JSON pointer path where the schema is being imported (e.g., "#/definitions/People").
1007
+ """
1008
+ if isinstance(obj, dict):
1009
+ for key, value in obj.items():
1010
+ if key == "$ref" and isinstance(value, str) and value.startswith("#"):
1011
+ # Rewrite the $ref to be relative to target_path
1012
+ # Original ref like "#/definitions/Address" or "#/Address"
1013
+ # needs to become "target_path/Address"
1014
+ ref_parts = value.lstrip("#").split("/")
1015
+ # Get the final referenced name (last part of the path)
1016
+ if ref_parts and ref_parts[-1]:
1017
+ ref_name = ref_parts[-1]
1018
+ # Rewrite to point to the same name under target_path
1019
+ obj[key] = f"{target_path}/{ref_name}"
1020
+ elif key == "$extends" and isinstance(value, str) and value.startswith("#"):
1021
+ # Also rewrite $extends references
1022
+ ref_parts = value.lstrip("#").split("/")
1023
+ if ref_parts and ref_parts[-1]:
1024
+ ref_name = ref_parts[-1]
1025
+ obj[key] = f"{target_path}/{ref_name}"
1026
+ else:
1027
+ self._rewrite_refs(value, target_path)
1028
+ elif isinstance(obj, list):
1029
+ for item in obj:
1030
+ self._rewrite_refs(item, target_path)
1031
+
1032
+ def _process_imports(self, obj, path):
1033
+ """
1034
+ Recursively processes $import and $importdefs keywords in the schema.
1035
+ [Metaschema: JSONStructureImport extension constructs]
1036
+ Merges imported definitions appropriately:
1037
+ - If the import is at the root level, definitions go into obj["definitions"]
1038
+ - If the import is inside a namespace (e.g., definitions/People), definitions merge directly into obj
1039
+ Uses self.import_map if the URI is mapped to a local file.
1040
+ After merging, $ref pointers in the imported content are rewritten to point
1041
+ to their new locations in the merged document.
1042
+ """
1043
+ if isinstance(obj, dict):
1044
+ for key in list(obj.keys()):
1045
+ if key in ("$import", "$importdefs"):
1046
+ if not self.allow_import:
1047
+ self.errors.append(
1048
+ f"JSONStructureImport keyword '{key}' encountered but allow_import not enabled at {path}/{key}")
1049
+ continue
1050
+ uri = obj[key]
1051
+ if not isinstance(uri, str):
1052
+ self.errors.append(f"JSONStructureImport keyword '{key}' value must be a string URI at {path}/{key}")
1053
+ continue
1054
+ # Allow relative URIs if they're in import_map or external_schemas
1055
+ if not self.ABSOLUTE_URI_REGEX.search(uri):
1056
+ if uri not in self.import_map and uri not in self.external_schemas:
1057
+ self.errors.append(f"JSONStructureImport keyword '{key}' value must be an absolute URI at {path}/{key}")
1058
+ continue
1059
+ external = self._fetch_external_schema(uri)
1060
+ if external is None:
1061
+ self.errors.append(f"Unable to fetch external schema from {uri} at {path}/{key}")
1062
+ continue
1063
+ if key == "$import":
1064
+ imported_defs = {}
1065
+ if "type" in external and "name" in external:
1066
+ imported_defs[external["name"]] = external
1067
+ if "definitions" in external and isinstance(external["definitions"], dict):
1068
+ imported_defs.update(external["definitions"])
1069
+ else: # $importdefs
1070
+ if "definitions" in external and isinstance(external["definitions"], dict):
1071
+ imported_defs = external["definitions"]
1072
+ else:
1073
+ imported_defs = {}
1074
+ # Determine where to merge and the actual target path for ref rewriting
1075
+ if path == "#":
1076
+ # Root level import - put in definitions
1077
+ target_path = "#/definitions"
1078
+ if "definitions" not in obj:
1079
+ obj["definitions"] = {}
1080
+ merge_target = obj["definitions"]
1081
+ else:
1082
+ # Nested import (e.g., inside a namespace) - merge directly into current object
1083
+ target_path = path
1084
+ merge_target = obj
1085
+ # Rewrite $ref pointers in imported content to point to their new location
1086
+ for k, v in imported_defs.items():
1087
+ if isinstance(v, dict):
1088
+ # Deep copy to avoid modifying cached schemas
1089
+ import copy
1090
+ v = copy.deepcopy(v)
1091
+ self._rewrite_refs(v, target_path)
1092
+ imported_defs[k] = v
1093
+ # Merge imported definitions
1094
+ for k, v in imported_defs.items():
1095
+ if k not in merge_target:
1096
+ merge_target[k] = v
1097
+ del obj[key]
1098
+ for k, v in obj.items():
1099
+ self._process_imports(v, f"{path}/{k}")
1100
+ elif isinstance(obj, list):
1101
+ for idx, item in enumerate(obj):
1102
+ self._process_imports(item, f"{path}[{idx}]")
1103
+
1104
+ def _fetch_external_schema(self, uri):
1105
+ """
1106
+ Fetches an external schema from a URI.
1107
+ [Metaschema: JSONStructureImport extension resolution]
1108
+ Resolution order:
1109
+ 1. Check external_schemas (pre-loaded schemas matched by $id)
1110
+ 2. Check import_map (URI to file path mapping)
1111
+ """
1112
+ # First check sideloaded schemas by $id
1113
+ if uri in self.external_schemas:
1114
+ return self.external_schemas[uri]
1115
+ # Then check import_map for file paths
1116
+ if uri in self.import_map:
1117
+ try:
1118
+ with open(self.import_map[uri], "r", encoding="utf-8") as f:
1119
+ return json.load(f)
1120
+ except Exception as e:
1121
+ self.errors.append(f"Failed to load imported schema from {self.import_map[uri]}: {e}")
1122
+ return None
1123
+ # URI not found in external_schemas or import_map
1124
+ return None
1125
+
1126
+ def _apply_uses(self, schema, instance):
1127
+ """
1128
+ Applies add-in types to the effective schema if the instance declares "$uses".
1129
+ [Metaschema: $offers and $uses in SchemaDocument]
1130
+ The $uses keyword is expected to be an array of add-in names.
1131
+ The root schema must have a "$offers" mapping.
1132
+ :param schema: The current schema.
1133
+ :param instance: The instance dict containing "$uses".
1134
+ :return: The merged schema with add-ins applied.
1135
+ """
1136
+ uses = instance.get("$uses")
1137
+ if not uses:
1138
+ return schema
1139
+ if not isinstance(uses, list):
1140
+ uses = [uses]
1141
+ offers = self.root_schema.get("$offers", {})
1142
+ merged = dict(schema)
1143
+ merged.setdefault("properties", {})
1144
+ for use in [u for u in uses if not u in ["JSONStructureValidation", "JSONStructureConditionalComposition", "JSONStructureAlternateNames", "JSONStructureUnits"]]:
1145
+ if use not in offers:
1146
+ self.errors.append(f"Add-in '{use}' not offered in $offers")
1147
+ continue
1148
+ addin = offers[use]
1149
+ if isinstance(addin, list):
1150
+ for ref in addin:
1151
+ resolved = self._resolve_ref(ref) if isinstance(ref, str) else ref
1152
+ if isinstance(resolved, dict):
1153
+ addin_props = resolved.get("properties", {})
1154
+ for prop in addin_props:
1155
+ if prop in merged["properties"]:
1156
+ self.errors.append(
1157
+ f"Add-in property '{prop}' from add-in '{use}' conflicts with existing property")
1158
+ merged["properties"].update(addin_props)
1159
+ elif isinstance(addin, dict) and "$ref" in addin:
1160
+ resolved = self._resolve_ref(addin["$ref"])
1161
+ if isinstance(resolved, dict):
1162
+ addin_props = resolved.get("properties", {})
1163
+ for prop in addin_props:
1164
+ if prop in merged["properties"]:
1165
+ self.errors.append(
1166
+ f"Add-in property '{prop}' from add-in '{use}' conflicts with existing property")
1167
+ merged["properties"].update(addin_props)
1168
+ elif isinstance(addin, dict):
1169
+ addin_props = addin.get("properties", {})
1170
+ for prop in addin_props:
1171
+ if prop in merged["properties"]:
1172
+ self.errors.append(
1173
+ f"Add-in property '{prop}' from add-in '{use}' conflicts with existing property")
1174
+ merged["properties"].update(addin_props)
1175
+ else:
1176
+ self.errors.append(f"Invalid add-in definition for '{use}'")
1177
+ return merged
1178
+
1179
+
1180
+ def main():
1181
+ """Command line entry point for validating JSON instances against JSON Structure schemas."""
1182
+ import argparse
1183
+ parser = argparse.ArgumentParser(
1184
+ prog='json-structure-validate',
1185
+ description='Validate JSON instances against JSON Structure schemas.',
1186
+ epilog='Example: json-structure-validate instance.json schema.json'
1187
+ )
1188
+ parser.add_argument('instance_file', help='Path to the JSON instance file to validate')
1189
+ parser.add_argument('schema_file', help='Path to the JSON Structure schema file')
1190
+ parser.add_argument('--extended', '-e', action='store_true',
1191
+ help='Enable extended validation features (conditional composition, validation keywords)')
1192
+ parser.add_argument('--allowimport', '-i', action='store_true',
1193
+ help='Enable processing of $import and $importdefs keywords')
1194
+ parser.add_argument('--importmap', '-m', action='append', metavar='URI=FILE',
1195
+ help='Map import URI to local file (can be specified multiple times)')
1196
+ parser.add_argument('--quiet', '-q', action='store_true',
1197
+ help='Only output errors, suppress success message')
1198
+ args = parser.parse_args()
1199
+
1200
+ # Build import map from arguments
1201
+ import_map = {}
1202
+ if args.importmap:
1203
+ for mapping in args.importmap:
1204
+ if '=' not in mapping:
1205
+ print(f"Error: Invalid --importmap format '{mapping}'. Expected URI=FILE")
1206
+ sys.exit(1)
1207
+ uri, filename = mapping.split('=', 1)
1208
+ import_map[uri] = filename
1209
+
1210
+ try:
1211
+ with open(args.schema_file, 'r', encoding='utf-8') as f:
1212
+ schema = json.load(f)
1213
+ except FileNotFoundError:
1214
+ print(f"Error: Schema file not found: {args.schema_file}")
1215
+ sys.exit(1)
1216
+ except json.JSONDecodeError as ex:
1217
+ print(f"Error: Invalid JSON in schema file: {ex}")
1218
+ sys.exit(1)
1219
+
1220
+ try:
1221
+ with open(args.instance_file, 'r', encoding='utf-8') as f:
1222
+ instance = json.load(f)
1223
+ except FileNotFoundError:
1224
+ print(f"Error: Instance file not found: {args.instance_file}")
1225
+ sys.exit(1)
1226
+ except json.JSONDecodeError as ex:
1227
+ print(f"Error: Invalid JSON in instance file: {ex}")
1228
+ sys.exit(1)
1229
+
1230
+ validator = JSONStructureInstanceValidator(
1231
+ schema,
1232
+ allow_import=args.allowimport,
1233
+ import_map=import_map,
1234
+ extended=args.extended
1235
+ )
1236
+ errors = validator.validate(instance)
1237
+ if errors:
1238
+ print("Instance is invalid:")
1239
+ for err in errors:
1240
+ print(" -", err)
1241
+ sys.exit(1)
1242
+ if not args.quiet:
1243
+ print("Instance is valid.")
1244
+
1245
+
1246
+ if __name__ == "__main__":
1247
+ main()