json-structure 0.6.1__tar.gz → 0.7.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: json-structure
3
- Version: 0.6.1
3
+ Version: 0.7.0
4
4
  Summary: Validators for JSON Structure schemas and instances
5
5
  Project-URL: Homepage, https://json-structure.org
6
6
  Project-URL: Documentation, https://github.com/json-structure/sdk
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.7.0'
22
+ __version_tuple__ = version_tuple = (0, 7, 0)
23
+
24
+ __commit_id__ = commit_id = None
@@ -247,12 +247,13 @@ class JSONStructureInstanceValidator:
247
247
  backup = list(self.errors)
248
248
  self.errors = []
249
249
  self.validate_instance(instance, {"type": t}, path)
250
- if not self.errors:
250
+ branch_errors = self.errors
251
+ self.errors = backup
252
+ if not branch_errors:
251
253
  union_valid = True
252
254
  break
253
255
  else:
254
- union_errors.extend(self.errors)
255
- self.errors = backup
256
+ union_errors.extend(branch_errors)
256
257
  if not union_valid:
257
258
  self.errors.append(f"Instance at {path} does not match any type in union: {union_errors}")
258
259
  return self.errors
@@ -77,7 +77,8 @@ class JSONStructureSchemaCoreValidator:
77
77
  # Extension names
78
78
  KNOWN_EXTENSIONS = {
79
79
  "JSONStructureImport", "JSONStructureAlternateNames", "JSONStructureUnits",
80
- "JSONStructureConditionalComposition", "JSONStructureValidation"
80
+ "JSONStructureConditionalComposition", "JSONStructureValidation",
81
+ "JSONStructureRelations"
81
82
  }
82
83
 
83
84
  def __init__(self, allow_dollar=False, allow_import=False, import_map=None, extended=False, external_schemas=None, warn_on_unused_extension_keywords=True, max_validation_depth=64):
@@ -207,7 +208,7 @@ class JSONStructureSchemaCoreValidator:
207
208
  if "$schema" in doc:
208
209
  self._check_is_absolute_uri(doc["$schema"], "$schema", "#/$schema")
209
210
  if "$id" in doc:
210
- self._check_is_absolute_uri(doc["$id"], "$id", "#/$id")
211
+ self._check_root_id(doc["$id"], "#/$id")
211
212
  if "$uses" in doc:
212
213
  self._check_uses(doc["$uses"], "#/$uses")
213
214
  if "type" in doc and "$root" in doc:
@@ -292,6 +293,19 @@ class JSONStructureSchemaCoreValidator:
292
293
  if not self.ABSOLUTE_URI_REGEX.search(value):
293
294
  self._err(f"'{keyword_name}' must be an absolute URI.", location)
294
295
 
296
+ def _check_root_id(self, value, location):
297
+ """
298
+ Validates the root $id keyword.
299
+ """
300
+ if not isinstance(value, str):
301
+ self._err("'$id' must be a string.", location)
302
+ return
303
+ if value.strip() == "":
304
+ self._err("$id must not be empty", location, ErrorCodes.SCHEMA_KEYWORD_EMPTY)
305
+ return
306
+ if not re.match(r'^[a-zA-Z][a-zA-Z0-9+\-.]*:', value):
307
+ self._err("$id must be a URI with a scheme", location, ErrorCodes.SCHEMA_CONSTRAINT_VALUE_INVALID)
308
+
295
309
  def _rewrite_refs(self, obj, target_path):
296
310
  """
297
311
  Recursively rewrites $ref pointers in an imported schema to be relative to the target path.
@@ -512,8 +526,8 @@ class JSONStructureSchemaCoreValidator:
512
526
  if not isinstance(schema_obj["name"], str):
513
527
  self._err(f"'name' must be a string.", path + "/name")
514
528
  else:
515
- if not self.identifier_regex.match(schema_obj["name"]):
516
- self._err(f"'name' must match the identifier pattern.", path + "/name")
529
+ if not re.match(r'^[A-Za-z_$][A-Za-z0-9_$]*$', schema_obj["name"]):
530
+ self._err("name must be a valid identifier", path + "/name", ErrorCodes.SCHEMA_NAME_INVALID)
517
531
  if "abstract" in schema_obj:
518
532
  if not isinstance(schema_obj["abstract"], bool):
519
533
  self._err(f"'abstract' keyword must be boolean.", path + "/abstract")
@@ -588,8 +602,12 @@ class JSONStructureSchemaCoreValidator:
588
602
  self._check_primitive_schema(schema_obj, path)
589
603
 
590
604
  # Extended validation checks
591
- if self.extended and "type" in schema_obj:
592
- self._check_extended_validation_keywords(schema_obj, path)
605
+ if self.extended:
606
+ if "type" in schema_obj:
607
+ self._check_extended_validation_keywords(schema_obj, path)
608
+ self._check_ucum_unit_keyword(schema_obj, path)
609
+ self._check_units_keywords(schema_obj, path)
610
+ self._check_relations_keywords(schema_obj, path)
593
611
 
594
612
  if "required" in schema_obj:
595
613
  req_val = schema_obj["required"]
@@ -631,6 +649,28 @@ class JSONStructureSchemaCoreValidator:
631
649
  seen.append(item_str)
632
650
  except (TypeError, ValueError):
633
651
  pass # Can't serialize, skip duplicate check for this item
652
+
653
+ type_str = schema_obj.get("type")
654
+ if isinstance(type_str, str) and type_str not in self.COMPOUND_TYPES:
655
+ is_valid = True
656
+ if type_str == "string":
657
+ is_valid = isinstance(item, str)
658
+ elif type_str in {
659
+ "number", "integer", "int8", "uint8", "int16", "uint16", "int32", "uint32",
660
+ "int64", "uint64", "int128", "uint128", "float8", "float", "double", "decimal"
661
+ }:
662
+ is_valid = isinstance(item, (int, float)) and not isinstance(item, bool)
663
+ elif type_str == "boolean":
664
+ is_valid = isinstance(item, bool)
665
+ elif type_str == "null":
666
+ is_valid = item is None
667
+
668
+ if not is_valid:
669
+ self._err(
670
+ f"enum value is not valid for type '{type_str}'",
671
+ f"{path}/enum[{idx}]",
672
+ ErrorCodes.SCHEMA_CONSTRAINT_TYPE_MISMATCH
673
+ )
634
674
  if "type" in schema_obj and isinstance(schema_obj["type"], str):
635
675
  if schema_obj["type"] in self.COMPOUND_TYPES:
636
676
  self._err("'enum' cannot be used with compound types.", path + "/enum")
@@ -740,7 +780,139 @@ class JSONStructureSchemaCoreValidator:
740
780
  if "default" in obj:
741
781
  if not validation_enabled:
742
782
  self._add_extension_keyword_warning("default", path)
783
+
784
+ def _check_ucum_unit_keyword(self, obj, path):
785
+ """
786
+ Check the ucumUnit keyword from the JSONStructureUnits extension.
787
+ """
788
+ if "ucumUnit" not in obj:
789
+ return
790
+
791
+ if "JSONStructureUnits" not in self.enabled_extensions:
792
+ self._err("'ucumUnit' requires JSONStructureUnits extension.", f"{path}/ucumUnit", ErrorCodes.SCHEMA_EXTENSION_KEYWORD_NOT_ENABLED)
793
+
794
+ ucum_unit = obj["ucumUnit"]
795
+ if not isinstance(ucum_unit, str):
796
+ self._err("'ucumUnit' must be a string.", f"{path}/ucumUnit", ErrorCodes.SCHEMA_KEYWORD_INVALID_TYPE)
797
+
798
+ numeric_types = {
799
+ "number", "integer", "float", "double", "decimal",
800
+ "int32", "uint32", "int64", "uint64", "int128", "uint128"
801
+ }
802
+ type_name = obj.get("type")
803
+ if not isinstance(type_name, str) or type_name not in numeric_types:
804
+ self._err("'ucumUnit' can only appear in numeric schemas.", f"{path}/ucumUnit", ErrorCodes.SCHEMA_CONSTRAINT_TYPE_MISMATCH)
805
+
806
+ def _check_units_keywords(self, obj, path):
807
+ """
808
+ Check the unit, currency, and symbols keywords from the JSONStructureUnits extension.
809
+ """
810
+ numeric_types = {
811
+ "number", "integer", "float", "double", "decimal",
812
+ "int32", "uint32", "int64", "uint64", "int128", "uint128"
813
+ }
814
+ units_enabled = "JSONStructureUnits" in self.enabled_extensions
815
+
816
+ for keyword in ("unit", "currency", "symbols"):
817
+ if keyword not in obj:
818
+ continue
819
+ if not units_enabled:
820
+ self._err(
821
+ f"'{keyword}' requires JSONStructureUnits extension.",
822
+ f"{path}/{keyword}",
823
+ ErrorCodes.SCHEMA_EXTENSION_KEYWORD_NOT_ENABLED,
824
+ )
825
+
826
+ if "unit" not in obj:
827
+ return
828
+
829
+ if not isinstance(obj["unit"], str):
830
+ self._err("'unit' must be a string.", f"{path}/unit", ErrorCodes.SCHEMA_KEYWORD_INVALID_TYPE)
743
831
 
832
+ type_name = obj.get("type")
833
+ if not isinstance(type_name, str) or type_name not in numeric_types:
834
+ self._err("'unit' can only appear in numeric schemas.", f"{path}/unit", ErrorCodes.SCHEMA_CONSTRAINT_TYPE_MISMATCH)
835
+
836
+ def _check_relations_keywords(self, obj, path):
837
+ """
838
+ Check identity and relations keywords from the JSONStructureRelations extension.
839
+ """
840
+ relation_keywords_used = "identity" in obj or "relations" in obj
841
+ if not relation_keywords_used:
842
+ return
843
+
844
+ relations_enabled = "JSONStructureRelations" in self.enabled_extensions
845
+ if not relations_enabled:
846
+ if "identity" in obj:
847
+ self._err("'identity' requires JSONStructureRelations extension.", f"{path}/identity")
848
+ if "relations" in obj:
849
+ self._err("'relations' requires JSONStructureRelations extension.", f"{path}/relations")
850
+
851
+ type_name = obj.get("type")
852
+ supports_relations = isinstance(type_name, str) and type_name in {"object", "tuple"}
853
+
854
+ if "identity" in obj:
855
+ identity = obj["identity"]
856
+ if not supports_relations:
857
+ self._err("'identity' can only appear in object or tuple schemas.", f"{path}/identity")
858
+ if not isinstance(identity, list):
859
+ self._err("'identity' must be an array.", f"{path}/identity")
860
+ else:
861
+ properties = obj.get("properties") if isinstance(obj.get("properties"), dict) else None
862
+ for idx, item in enumerate(identity):
863
+ item_path = f"{path}/identity[{idx}]"
864
+ if not isinstance(item, str):
865
+ self._err(f"'identity[{idx}]' must be a string.", item_path)
866
+ elif properties is not None and item not in properties:
867
+ self._err(f"'identity' references property '{item}' that is not in 'properties'.", item_path)
868
+
869
+ if "relations" in obj:
870
+ relations = obj["relations"]
871
+ if not supports_relations:
872
+ self._err("'relations' can only appear in object or tuple schemas.", f"{path}/relations")
873
+ if not isinstance(relations, dict):
874
+ self._err("'relations' must be an object.", f"{path}/relations")
875
+ else:
876
+ for relation_name, declaration in relations.items():
877
+ relation_path = f"{path}/relations/{relation_name}"
878
+ if not isinstance(declaration, dict):
879
+ self._err("Relation declaration must be an object.", relation_path)
880
+ continue
881
+
882
+ if "targettype" not in declaration:
883
+ self._err("Relation declaration must have 'targettype'.", f"{relation_path}/targettype")
884
+ else:
885
+ targettype = declaration["targettype"]
886
+ if not isinstance(targettype, dict) or "$ref" not in targettype:
887
+ self._err("'targettype' must be an object with '$ref'.", f"{relation_path}/targettype")
888
+ else:
889
+ self._check_json_pointer(targettype["$ref"], self.doc, f"{relation_path}/targettype/$ref")
890
+
891
+ if "cardinality" not in declaration:
892
+ self._err("Relation declaration must have 'cardinality'.", f"{relation_path}/cardinality")
893
+ else:
894
+ cardinality = declaration["cardinality"]
895
+ if cardinality not in {"single", "multiple"}:
896
+ self._err("'cardinality' must be 'single' or 'multiple'.", f"{relation_path}/cardinality")
897
+
898
+ if "scope" in declaration:
899
+ scope = declaration["scope"]
900
+ if isinstance(scope, str):
901
+ pass
902
+ elif isinstance(scope, list):
903
+ for idx, item in enumerate(scope):
904
+ if not isinstance(item, str):
905
+ self._err("'scope' array items must be strings.", f"{relation_path}/scope[{idx}]")
906
+ else:
907
+ self._err("'scope' must be a string or an array of strings.", f"{relation_path}/scope")
908
+
909
+ if "qualifiertype" in declaration:
910
+ qualifiertype = declaration["qualifiertype"]
911
+ if not isinstance(qualifiertype, dict) or "$ref" not in qualifiertype:
912
+ self._err("'qualifiertype' must be an object with '$ref'.", f"{relation_path}/qualifiertype")
913
+ else:
914
+ self._check_json_pointer(qualifiertype["$ref"], self.doc, f"{relation_path}/qualifiertype/$ref")
915
+
744
916
  def _check_numeric_validation(self, obj, path, type_name, validation_enabled=True):
745
917
  """
746
918
  Check numeric validation keywords.
@@ -1092,10 +1264,20 @@ class JSONStructureSchemaCoreValidator:
1092
1264
  self._err("'tuple' keyword must be an array of strings.", path + "/tuple")
1093
1265
  else:
1094
1266
  for idx, element in enumerate(tuple_order):
1095
- if not isinstance(element, str):
1096
- self._err(f"Element at index {idx} in 'tuple' array must be a string.", path + f"/tuple[{idx}]")
1097
- elif "properties" in obj and isinstance(obj["properties"], dict) and element not in obj["properties"]:
1098
- self._err(f"Element '{element}' in 'tuple' does not correspond to any property in 'properties'.", path + f"/tuple[{idx}]")
1267
+ element_path = path + f"/tuple[{idx}]"
1268
+ if isinstance(element, str):
1269
+ if "properties" in obj and isinstance(obj["properties"], dict) and element not in obj["properties"]:
1270
+ self._err(f"Element '{element}' in 'tuple' does not correspond to any property in 'properties'.", element_path)
1271
+ elif isinstance(element, dict) and "$ref" in element:
1272
+ ref = element["$ref"]
1273
+ if not isinstance(ref, str):
1274
+ self._err("JSON Pointer must be a string.", element_path + "/$ref")
1275
+ elif not ref.startswith("#"):
1276
+ self._err("JSON Pointer must start with '#' when referencing the same document.", element_path + "/$ref")
1277
+ elif self._resolve_json_pointer(ref) is None:
1278
+ self._err(f"$ref target '{ref}' not found.", element_path + "/$ref", ErrorCodes.SCHEMA_REF_NOT_FOUND)
1279
+ else:
1280
+ self._err(f"Element at index {idx} in 'tuple' array must be a string or a $ref object.", element_path)
1099
1281
 
1100
1282
  def _check_choice_schema(self, obj, path):
1101
1283
  """
@@ -1187,7 +1369,13 @@ class JSONStructureSchemaCoreValidator:
1187
1369
  resolved = self._resolve_json_pointer(ref)
1188
1370
  if resolved is None:
1189
1371
  self._err(f"$extends reference '{ref}' not found.", ref_path, ErrorCodes.SCHEMA_EXTENDS_NOT_FOUND)
1190
- elif isinstance(resolved, dict) and "$extends" in resolved:
1372
+ elif not isinstance(resolved, dict) or ("type" in resolved and resolved.get("type") not in {"object", "tuple", "map", "array", "set", "choice"}):
1373
+ self._err(
1374
+ f"$extends target '{ref}' must not resolve to a primitive type",
1375
+ ref_path,
1376
+ ErrorCodes.SCHEMA_CONSTRAINT_TYPE_MISMATCH
1377
+ )
1378
+ elif "$extends" in resolved:
1191
1379
  # Recursively validate the extended schema's $extends
1192
1380
  self._validate_extends_keyword(resolved["$extends"], ref_path)
1193
1381
 
@@ -1,34 +0,0 @@
1
- # file generated by setuptools-scm
2
- # don't change, don't track in version control
3
-
4
- __all__ = [
5
- "__version__",
6
- "__version_tuple__",
7
- "version",
8
- "version_tuple",
9
- "__commit_id__",
10
- "commit_id",
11
- ]
12
-
13
- TYPE_CHECKING = False
14
- if TYPE_CHECKING:
15
- from typing import Tuple
16
- from typing import Union
17
-
18
- VERSION_TUPLE = Tuple[Union[int, str], ...]
19
- COMMIT_ID = Union[str, None]
20
- else:
21
- VERSION_TUPLE = object
22
- COMMIT_ID = object
23
-
24
- version: str
25
- __version__: str
26
- __version_tuple__: VERSION_TUPLE
27
- version_tuple: VERSION_TUPLE
28
- commit_id: COMMIT_ID
29
- __commit_id__: COMMIT_ID
30
-
31
- __version__ = version = '0.6.1'
32
- __version_tuple__ = version_tuple = (0, 6, 1)
33
-
34
- __commit_id__ = commit_id = None
File without changes