sdcvalidator 4.6.2__tar.gz → 4.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.
Files changed (42) hide show
  1. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/PKG-INFO +4 -1
  2. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/README.md +3 -0
  3. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/pyproject.toml +4 -1
  4. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/src/sdcvalidator/__init__.py +7 -2
  5. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/src/sdcvalidator/error_classifier.py +3 -25
  6. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/src/sdcvalidator/error_mapper.py +40 -34
  7. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/src/sdcvalidator/exceptions.py +4 -0
  8. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/src/sdcvalidator/instance_modifier.py +5 -91
  9. sdcvalidator-4.7.0/src/sdcvalidator/loading.py +65 -0
  10. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/src/sdcvalidator/mcp_server.py +1 -1
  11. sdcvalidator-4.7.0/src/sdcvalidator/paths.py +64 -0
  12. sdcvalidator-4.7.0/src/sdcvalidator/reference/sdc4.xsd +3492 -0
  13. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/src/sdcvalidator/validator.py +54 -26
  14. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/src/sdcvalidator.egg-info/PKG-INFO +4 -1
  15. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/src/sdcvalidator.egg-info/SOURCES.txt +6 -0
  16. sdcvalidator-4.7.0/tests/test_error_mapping_by_constraint.py +63 -0
  17. sdcvalidator-4.7.0/tests/test_offline_loading.py +78 -0
  18. sdcvalidator-4.7.0/tests/test_recovery_470.py +171 -0
  19. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/LICENSE +0 -0
  20. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/setup.cfg +0 -0
  21. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/src/sdcvalidator/cli.py +0 -0
  22. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/src/sdcvalidator/constants.py +0 -0
  23. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/src/sdcvalidator/converters.py +0 -0
  24. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/src/sdcvalidator/schema_checker.py +0 -0
  25. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/src/sdcvalidator/xsd11_restriction.py +0 -0
  26. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/src/sdcvalidator.egg-info/dependency_links.txt +0 -0
  27. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/src/sdcvalidator.egg-info/entry_points.txt +0 -0
  28. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/src/sdcvalidator.egg-info/requires.txt +0 -0
  29. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/src/sdcvalidator.egg-info/top_level.txt +0 -0
  30. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/tests/test_conformance.py +0 -0
  31. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/tests/test_converters.py +0 -0
  32. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/tests/test_error_classifier.py +0 -0
  33. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/tests/test_error_mapper.py +0 -0
  34. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/tests/test_instance_modifier.py +0 -0
  35. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/tests/test_mcp_server.py +0 -0
  36. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/tests/test_recovery.py +0 -0
  37. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/tests/test_recovery_460.py +0 -0
  38. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/tests/test_registry_launch.py +0 -0
  39. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/tests/test_schema_checker.py +0 -0
  40. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/tests/test_validator.py +0 -0
  41. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/tests/test_xsd11_restriction.py +0 -0
  42. {sdcvalidator-4.6.2 → sdcvalidator-4.7.0}/tests/test_xsi_type.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sdcvalidator
3
- Version: 4.6.2
3
+ Version: 4.7.0
4
4
  Summary: SDC4 structural validator with ExceptionalValue recovery — thin wrapper over xmlschema
5
5
  Author: Axius SDC, Inc.
6
6
  License-Expression: Apache-2.0
@@ -36,6 +36,7 @@ Dynamic: license-file
36
36
  - Checks SDC4 schema compliance (no `xsd:extension` — only `xsd:restriction`)
37
37
  - **Strict validation by default** — catches invalid restriction derivations (wrong element names, type mismatches) at schema load time
38
38
  - Converts between XML and JSON using schema-aware conversion
39
+ - **Works offline**: a schema loaded from a file reads local files only. The SDC4 reference model resolves to a `sdc4.xsd` beside the model (SDCStudio packages carry one) or to the copy bundled with sdcvalidator; a schema that includes anything over the network is refused. A record read from a file must not have a DOCTYPE (`SDC4DoctypeError`).
39
40
 
40
41
  ## Install
41
42
 
@@ -194,6 +195,8 @@ A client configuration needs only `"command": "uvx", "args": ["sdcvalidator"]`.
194
195
 
195
196
  `validate_instance` and `validate_and_report` take `schema_path` and `instance_path`, plus an optional `check_compliance` boolean (default `true`). `check_schema_compliance` takes `schema_path` only.
196
197
 
198
+ Also listed on [mcprush](https://mcprush.com/semanticdatacharter/sdcvalidator-mcp).
199
+
197
200
  ## Two-Tier Error Classification
198
201
 
199
202
  | Tier | Type | Examples | Action |
@@ -14,6 +14,7 @@
14
14
  - Checks SDC4 schema compliance (no `xsd:extension` — only `xsd:restriction`)
15
15
  - **Strict validation by default** — catches invalid restriction derivations (wrong element names, type mismatches) at schema load time
16
16
  - Converts between XML and JSON using schema-aware conversion
17
+ - **Works offline**: a schema loaded from a file reads local files only. The SDC4 reference model resolves to a `sdc4.xsd` beside the model (SDCStudio packages carry one) or to the copy bundled with sdcvalidator; a schema that includes anything over the network is refused. A record read from a file must not have a DOCTYPE (`SDC4DoctypeError`).
17
18
 
18
19
  ## Install
19
20
 
@@ -172,6 +173,8 @@ A client configuration needs only `"command": "uvx", "args": ["sdcvalidator"]`.
172
173
 
173
174
  `validate_instance` and `validate_and_report` take `schema_path` and `instance_path`, plus an optional `check_compliance` boolean (default `true`). `check_schema_compliance` takes `schema_path` only.
174
175
 
176
+ Also listed on [mcprush](https://mcprush.com/semanticdatacharter/sdcvalidator-mcp).
177
+
175
178
  ## Two-Tier Error Classification
176
179
 
177
180
  | Tier | Type | Examples | Action |
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "sdcvalidator"
7
- version = "4.6.2"
7
+ version = "4.7.0"
8
8
  description = "SDC4 structural validator with ExceptionalValue recovery — thin wrapper over xmlschema"
9
9
  license = "Apache-2.0"
10
10
  requires-python = ">=3.10"
@@ -35,3 +35,6 @@ sdcvalidator = "sdcvalidator.mcp_server:main"
35
35
 
36
36
  [tool.setuptools.packages.find]
37
37
  where = ["src"]
38
+
39
+ [tool.setuptools.package-data]
40
+ sdcvalidator = ["reference/*.xsd"]
@@ -14,7 +14,7 @@ Thin wrapper over xmlschema with two-tier error classification and the SDC4
14
14
  "quarantine-and-tag" recovery pattern (ISO 21090 ExceptionalValues).
15
15
  """
16
16
 
17
- __version__ = "4.6.2"
17
+ __version__ = "4.7.0"
18
18
 
19
19
  # etree_tostring is re-exported from xmlschema so callers can serialize the
20
20
  # ElementTree returned by validate_with_recovery() without importing xmlschema
@@ -34,7 +34,8 @@ from .validator import (
34
34
  from .error_classifier import ErrorClassifier
35
35
  from .error_mapper import ErrorMapper
36
36
  from .instance_modifier import InstanceModifier
37
- from .exceptions import SDC4StructuralValidationError, SDC4UnrecoverableError
37
+ from .exceptions import SDC4DoctypeError, SDC4StructuralValidationError, SDC4UnrecoverableError
38
+ from .loading import BUNDLED_REFERENCE_MODEL, REFERENCE_MODEL_URL, load_schema
38
39
  from .constants import (
39
40
  ErrorTier,
40
41
  ExceptionalValueType,
@@ -74,5 +75,9 @@ __all__ = [
74
75
  "assert_sdc4_schema_compliance",
75
76
  "SDC4SchemaValidationError",
76
77
  "build_xsd11_schema",
78
+ "load_schema",
79
+ "BUNDLED_REFERENCE_MODEL",
80
+ "REFERENCE_MODEL_URL",
81
+ "SDC4DoctypeError",
77
82
  "is_substitution_group_restriction_false_positive",
78
83
  ]
@@ -18,6 +18,7 @@ from xmlschema.validators.exceptions import (
18
18
  XMLSchemaDecodeError,
19
19
  XMLSchemaChildrenValidationError
20
20
  )
21
+ from .paths import local_name
21
22
  from .constants import ErrorTier, STRUCTURAL_ELEMENTS
22
23
 
23
24
 
@@ -116,31 +117,8 @@ class ErrorClassifier:
116
117
  return False
117
118
 
118
119
  def _extract_element_name(self, xpath: Optional[str]) -> Optional[str]:
119
- """
120
- Extract the element name from an XPath expression.
121
-
122
- Handles paths like:
123
- - /DataModel/xdstring-value
124
- - /ns:DataModel/ns:xdstring-value[1]
125
- """
126
- if not xpath:
127
- return None
128
-
129
- parts = xpath.strip('/').split('/')
130
- if not parts:
131
- return None
132
-
133
- last_part = parts[-1]
134
-
135
- # Remove namespace prefix
136
- if ':' in last_part:
137
- last_part = last_part.split(':')[-1]
138
-
139
- # Remove predicates
140
- if '[' in last_part:
141
- last_part = last_part[:last_part.index('[')]
142
-
143
- return last_part if last_part else None
120
+ """The local name of the element an error path ends at (Clark, prefixed or bare; any position index dropped)."""
121
+ return local_name(xpath)
144
122
 
145
123
  def get_error_summary(self, error: XMLSchemaValidationError) -> Dict[str, str]:
146
124
  """
@@ -22,6 +22,9 @@ from xmlschema.validators.exceptions import (
22
22
  XMLSchemaDecodeError,
23
23
  XMLSchemaChildrenValidationError,
24
24
  )
25
+ from xmlschema.validators import XsdAssert, XsdComponent, XsdElement
26
+ from xmlschema.validators.facets import XsdEnumerationFacets, XsdFacet
27
+ from .paths import local_name
25
28
  from .constants import ExceptionalValueType, STRUCTURAL_ELEMENTS
26
29
  from .error_classifier import ErrorClassifier
27
30
 
@@ -122,6 +125,14 @@ class ErrorMapper:
122
125
  # Don't map to ExceptionalValue - let validation fail
123
126
  return None
124
127
 
128
+ # The constraint that failed decides, when xmlschema says which one it was. The wording rules
129
+ # below are the fallback: xmlschema's messages change between releases (4.6.2 and earlier
130
+ # mapped every facet violation to NI because "value must be one of [...]" and "value doesn't
131
+ # match any pattern of [...]" no longer matched them), and its validator classes do not.
132
+ ev_type = self._map_by_constraint(error)
133
+ if ev_type is not None:
134
+ return ev_type
135
+
125
136
  # For SDC4 data-bearing elements or unknown elements, map to appropriate ExceptionalValue
126
137
  # Note: We're permissive here - only STRUCTURAL_ELEMENTS fail validation
127
138
  # This allows the system to work with custom element names and future SDC versions
@@ -132,6 +143,33 @@ class ErrorMapper:
132
143
  # Should never reach here due to default rule, but just in case
133
144
  return ExceptionalValueType.NI
134
145
 
146
+ @staticmethod
147
+ def _map_by_constraint(error: XMLSchemaValidationError) -> Optional[ExceptionalValueType]:
148
+ """
149
+ The ExceptionalValue for an error, from the constraint xmlschema reports as having failed
150
+ (``error.validator``), or None when the constraint does not decide it.
151
+
152
+ - a value outside its enumeration: OTH;
153
+ - a value that breaks any other facet (pattern, length, range, digits), a built-in type's own
154
+ range (a negative nonNegativeInteger), an assertion, or an element's fixed value: INV;
155
+ - a value that is not of its type at all (a decode error): INV, as the wording rules give it.
156
+ """
157
+ if isinstance(error, XMLSchemaChildrenValidationError):
158
+ return None
159
+ if isinstance(error, XMLSchemaDecodeError):
160
+ return ExceptionalValueType.INV
161
+ validator = error.validator
162
+ if isinstance(validator, XsdEnumerationFacets):
163
+ return ExceptionalValueType.OTH
164
+ if isinstance(validator, (XsdFacet, XsdAssert)):
165
+ return ExceptionalValueType.INV
166
+ if isinstance(validator, XsdElement) and validator.fixed is not None:
167
+ return ExceptionalValueType.INV
168
+ if callable(validator) and not isinstance(validator, XsdComponent):
169
+ # A built-in type's own facet: xmlschema checks it with a plain function.
170
+ return ExceptionalValueType.INV
171
+ return None
172
+
135
173
  def is_structural_error(self, error: XMLSchemaValidationError) -> bool:
136
174
  """
137
175
  Classify an error as structural (Tier 1) vs semantic (Tier 2).
@@ -145,40 +183,8 @@ class ErrorMapper:
145
183
  return self._classifier.is_structural_error(error)
146
184
 
147
185
  def _extract_element_name(self, xpath: Optional[str]) -> Optional[str]:
148
- """
149
- Extract the element name from an XPath expression.
150
-
151
- Handles paths like:
152
- - /DataModel/xdstring-value
153
- - /ns:DataModel/ns:xdstring-value[1]
154
- - //xdcount-value
155
-
156
- :param xpath: The XPath expression from the validation error.
157
- :return: The local element name (without namespace prefix), or None.
158
- """
159
- if not xpath:
160
- return None
161
-
162
- # Get the last path component
163
- parts = xpath.strip('/').split('/')
164
- if not parts:
165
- return None
166
-
167
- last_part = parts[-1]
168
-
169
- # Remove namespace prefix (e.g., 'sdc4:xdstring-value' -> 'xdstring-value')
170
- if ':' in last_part:
171
- last_part = last_part.split(':')[-1]
172
-
173
- # Remove predicates (e.g., 'xdstring-value[1]' -> 'xdstring-value')
174
- if '[' in last_part:
175
- last_part = last_part[:last_part.index('[')]
176
-
177
- return last_part if last_part else None
178
-
179
- # =========================================================================
180
- # Error classification helper methods
181
- # =========================================================================
186
+ """The local name of the element an error path ends at (Clark, prefixed or bare; any position index dropped)."""
187
+ return local_name(xpath)
182
188
 
183
189
  def _is_missing_required(self, error: XMLSchemaValidationError) -> bool:
184
190
  """Check if error indicates missing required element/attribute."""
@@ -88,3 +88,7 @@ class SDC4UnrecoverableError(Exception):
88
88
  @property
89
89
  def error_count(self) -> int:
90
90
  return len(self.errors)
91
+
92
+
93
+ class SDC4DoctypeError(ValueError):
94
+ """A record read from a file has a DOCTYPE. SDC4 records never carry one, so it is refused before parsing."""
@@ -14,6 +14,7 @@ Modifies XML instance documents to insert SDC4 ExceptionalValue elements.
14
14
  import logging
15
15
  from typing import Optional, Dict
16
16
  from xml.etree import ElementTree as ET
17
+ from .paths import find as find_by_path, local_name
17
18
  from .constants import (
18
19
  SDC4_NAMESPACE,
19
20
  ExceptionalValueType,
@@ -102,31 +103,8 @@ class InstanceModifier:
102
103
  return True
103
104
 
104
105
  def _extract_element_name_from_xpath(self, xpath: str) -> Optional[str]:
105
- """
106
- Extract the element name from an XPath expression.
107
-
108
- :param xpath: The XPath expression.
109
- :return: The local element name (without namespace prefix), or None.
110
- """
111
- if not xpath:
112
- return None
113
-
114
- # Get the last path component
115
- parts = xpath.strip('/').split('/')
116
- if not parts:
117
- return None
118
-
119
- last_part = parts[-1]
120
-
121
- # Remove namespace prefix (e.g., 'sdc4:xdstring-value' -> 'xdstring-value')
122
- if ':' in last_part:
123
- last_part = last_part.split(':')[-1]
124
-
125
- # Remove predicates (e.g., 'xdstring-value[1]' -> 'xdstring-value')
126
- if '[' in last_part:
127
- last_part = last_part[:last_part.index('[')]
128
-
129
- return last_part if last_part else None
106
+ """The local name of the element an error path ends at (Clark, prefixed or bare; any position index dropped)."""
107
+ return local_name(xpath)
130
108
 
131
109
  def _register_namespace(self):
132
110
  """Register the SDC4 namespace with ElementTree."""
@@ -178,72 +156,8 @@ class InstanceModifier:
178
156
  return None
179
157
 
180
158
  def _find_element_by_clark_path(self, root: ET.Element, clark_path: str) -> Optional[ET.Element]:
181
- """
182
- Find an element by traversing a Clark notation path.
183
-
184
- Clark notation: /{namespace}localname/{namespace}localname/...
185
-
186
- :param root: The root element to search from.
187
- :param clark_path: The path using Clark notation.
188
- :return: The found element or None.
189
- """
190
- # Parse Clark notation path components
191
- # Need to be careful not to split on slashes inside the namespace URI
192
- parts = []
193
- i = 0
194
- while i < len(clark_path):
195
- if clark_path[i] == '/':
196
- # Skip slashes
197
- i += 1
198
- continue
199
- elif clark_path[i] == '{':
200
- # Start of namespaced element: {namespace}localname
201
- # Find the matching '}'
202
- end_brace = clark_path.index('}', i)
203
- # Find the next '/' or end of string
204
- next_slash = clark_path.find('/', end_brace)
205
- if next_slash == -1:
206
- next_slash = len(clark_path)
207
- # Extract the full element name with namespace
208
- part = clark_path[i:next_slash]
209
- parts.append(part)
210
- i = next_slash
211
- else:
212
- # Element without namespace
213
- next_slash = clark_path.find('/', i)
214
- if next_slash == -1:
215
- next_slash = len(clark_path)
216
- part = clark_path[i:next_slash]
217
- parts.append(part)
218
- i = next_slash
219
-
220
- if not parts:
221
- return None
222
-
223
- # Start from root
224
- current = root
225
-
226
- # Check if the first part is the root element itself
227
- if parts[0] == root.tag:
228
- # Skip the root element in the path
229
- parts = parts[1:]
230
- if not parts:
231
- return root
232
-
233
- # Traverse each part of the path
234
- for part in parts:
235
- # The part is in Clark notation: {namespace}localname or just localname
236
- found = False
237
- for child in current:
238
- if child.tag == part:
239
- current = child
240
- found = True
241
- break
242
-
243
- if not found:
244
- return None
245
-
246
- return current
159
+ """The element a Clark-form path names, honouring position indexes (see ``paths.find``)."""
160
+ return find_by_path(root, clark_path)
247
161
 
248
162
  def _find_parent_element(self, root: ET.Element, child: ET.Element) -> Optional[ET.Element]:
249
163
  """
@@ -0,0 +1,65 @@
1
+ #
2
+ # Copyright 2026 Semantic Data Charter Foundation
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ """
11
+ Loading schemas and records from files without the network.
12
+
13
+ A schema loaded from a path reads local files only. Every SDC4 data model includes the reference
14
+ model by its published URL (https://semanticdatacharter.com/ns/sdc4/sdc4.xsd); that URL resolves
15
+ to a ``sdc4.xsd`` beside the model when there is one (SDCStudio's packages and generated apps
16
+ carry it), and otherwise to the copy bundled in this package. A schema that includes or imports
17
+ anything over the network is refused.
18
+
19
+ A record read from a path is refused if it has a DOCTYPE: SDC4 records never carry one, and a
20
+ DTD is where entity expansion and external entities come from.
21
+ """
22
+ from pathlib import Path
23
+ from typing import Callable, Union
24
+ from xml.parsers import expat
25
+
26
+ from xmlschema import XMLSchema11
27
+
28
+ from .exceptions import SDC4DoctypeError
29
+ from .xsd11_restriction import build_xsd11_schema
30
+
31
+ REFERENCE_MODEL_URL = 'https://semanticdatacharter.com/ns/sdc4/sdc4.xsd'
32
+ #: The reference model bundled with sdcvalidator, byte-identical to the published one.
33
+ BUNDLED_REFERENCE_MODEL = Path(__file__).resolve().parent / 'reference' / 'sdc4.xsd'
34
+
35
+
36
+ def reference_model_mapper(schema_path: Union[str, Path]) -> Callable[[str], str]:
37
+ """A ``uri_mapper`` that resolves the reference model's URL to a local file, leaving other URLs as they are."""
38
+ beside = Path(schema_path).resolve().parent / 'sdc4.xsd'
39
+ local = beside if beside.is_file() else BUNDLED_REFERENCE_MODEL
40
+
41
+ def mapper(url: str) -> str:
42
+ return str(local) if url == REFERENCE_MODEL_URL else url
43
+
44
+ return mapper
45
+
46
+
47
+ def load_schema(schema_path: Union[str, Path], validation: str = 'strict') -> XMLSchema11:
48
+ """Build a model's schema from a file, reading local files only (``allow='local'``)."""
49
+ return build_xsd11_schema(str(schema_path), validation=validation,
50
+ uri_mapper=reference_model_mapper(schema_path), allow='local')
51
+
52
+
53
+ def refuse_doctype(record_path: Union[str, Path]) -> None:
54
+ """Raise SDC4DoctypeError if the record at ``record_path`` has a DOCTYPE; parse errors are left to the reader."""
55
+ parser = expat.ParserCreate()
56
+
57
+ def doctype(*_args):
58
+ raise SDC4DoctypeError(f"{record_path}: a record must not have a DOCTYPE")
59
+
60
+ parser.StartDoctypeDeclHandler = doctype
61
+ try:
62
+ with open(record_path, 'rb') as f:
63
+ parser.ParseFile(f)
64
+ except expat.ExpatError:
65
+ pass
@@ -36,7 +36,7 @@ from sdcvalidator.schema_checker import validate_sdc4_schema_compliance
36
36
  JSONRPC_VERSION = "2.0"
37
37
  MCP_PROTOCOL_VERSION = "2024-11-05"
38
38
  SERVER_NAME = "sdcvalidator"
39
- SERVER_VERSION = "4.6.2"
39
+ SERVER_VERSION = "4.7.0"
40
40
 
41
41
  # Validator cache: schema_path -> SDC4Validator
42
42
  _validators: dict[str, SDC4Validator] = {}
@@ -0,0 +1,64 @@
1
+ #
2
+ # Copyright 2026 Semantic Data Charter Foundation
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ """
11
+ Element paths as xmlschema reports them: Clark notation (``/{uri}local/...``), with a position index
12
+ (``name[2]``) on a step whose element has siblings of the same name. A namespace URI holds slashes,
13
+ so a path is read step by step, never split on ``/``.
14
+ """
15
+ import re
16
+ from typing import List, Optional, Tuple
17
+ from xml.etree import ElementTree as ET
18
+
19
+ # One step: an optional {uri} or prefix, the local name, and an optional [n].
20
+ _STEP = re.compile(r'(\{[^}]*\}[^/\[]+|[^/\[]+)(?:\[(\d+)\])?')
21
+
22
+
23
+ def steps(path: str) -> List[Tuple[str, Optional[int]]]:
24
+ """The steps of a path, as (name, position) pairs; position is None when the step has no index."""
25
+ return [(name, int(pos) if pos else None) for name, pos in _STEP.findall(path or '')]
26
+
27
+
28
+ def local_name(path: Optional[str]) -> Optional[str]:
29
+ """The local name of the element a path ends at, without its namespace, prefix, or position."""
30
+ parts = steps(path or '')
31
+ if not parts:
32
+ return None
33
+ name = parts[-1][0]
34
+ if name.startswith('{'):
35
+ name = name[name.index('}') + 1:]
36
+ elif ':' in name:
37
+ name = name.split(':', 1)[1]
38
+ return name or None
39
+
40
+
41
+ def find(root: ET.Element, path: str) -> Optional[ET.Element]:
42
+ """
43
+ The element a Clark-form path names, or None.
44
+
45
+ A step with a position index takes that sibling. A step without one must match exactly one
46
+ child, so a path that does not name a single element gives None rather than a guess.
47
+ """
48
+ parts = steps(path)
49
+ if not parts:
50
+ return None
51
+ if parts[0][0] == root.tag and parts[0][1] in (None, 1):
52
+ parts = parts[1:]
53
+ current = root
54
+ for name, pos in parts:
55
+ matches = [child for child in current if child.tag == name]
56
+ if pos is not None:
57
+ if pos < 1 or pos > len(matches):
58
+ return None
59
+ current = matches[pos - 1]
60
+ elif len(matches) == 1:
61
+ current = matches[0]
62
+ else:
63
+ return None
64
+ return current