ruml-parser 1.0.0__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.
Files changed (72) hide show
  1. ruml_parser/__init__.py +183 -0
  2. ruml_parser/internal/__init__.py +2 -0
  3. ruml_parser/internal/extension.py +91 -0
  4. ruml_parser/internal/mapping.py +731 -0
  5. ruml_parser/internal/ruml/__init__.py +237 -0
  6. ruml_parser/internal/ruml/actions/__init__.py +2 -0
  7. ruml_parser/internal/ruml/actions/actions_capability_declaration.py +23 -0
  8. ruml_parser/internal/ruml/actions/actions_node_capability.py +40 -0
  9. ruml_parser/internal/ruml/ai_query/__init__.py +2 -0
  10. ruml_parser/internal/ruml/ai_query/ai_query_capability_declaration.py +25 -0
  11. ruml_parser/internal/ruml/ai_query/ai_query_node_capability.py +66 -0
  12. ruml_parser/internal/ruml/aliases.py +93 -0
  13. ruml_parser/internal/ruml/capability/__init__.py +2 -0
  14. ruml_parser/internal/ruml/capability/abstract_capability_declaration.py +23 -0
  15. ruml_parser/internal/ruml/capability/abstract_node_capability.py +14 -0
  16. ruml_parser/internal/ruml/capability/capability_declaration.py +52 -0
  17. ruml_parser/internal/ruml/capability/capability_declarations.py +199 -0
  18. ruml_parser/internal/ruml/capability/extension_node_capability.py +17 -0
  19. ruml_parser/internal/ruml/capability/node_capabilities.py +113 -0
  20. ruml_parser/internal/ruml/capability/other_node_capability.py +21 -0
  21. ruml_parser/internal/ruml/context/__init__.py +2 -0
  22. ruml_parser/internal/ruml/context/context.py +40 -0
  23. ruml_parser/internal/ruml/context/context_capability_declaration.py +25 -0
  24. ruml_parser/internal/ruml/context/context_refs_node_capability.py +17 -0
  25. ruml_parser/internal/ruml/datapoints/__init__.py +2 -0
  26. ruml_parser/internal/ruml/datapoints/datapoint.py +101 -0
  27. ruml_parser/internal/ruml/datapoints/datapoint_set.py +20 -0
  28. ruml_parser/internal/ruml/datapoints/datapoints_capability_declaration.py +29 -0
  29. ruml_parser/internal/ruml/datapoints/option.py +11 -0
  30. ruml_parser/internal/ruml/expression/__init__.py +2 -0
  31. ruml_parser/internal/ruml/expression/expression_capability_declaration.py +23 -0
  32. ruml_parser/internal/ruml/expression/expression_node_capability.py +20 -0
  33. ruml_parser/internal/ruml/metadata.py +83 -0
  34. ruml_parser/internal/ruml/nodes/__init__.py +2 -0
  35. ruml_parser/internal/ruml/nodes/abstract_node.py +29 -0
  36. ruml_parser/internal/ruml/nodes/branch_node.py +15 -0
  37. ruml_parser/internal/ruml/nodes/leaf_node.py +10 -0
  38. ruml_parser/internal/ruml/nodes/node.py +6 -0
  39. ruml_parser/internal/ruml/protocol/__init__.py +2 -0
  40. ruml_parser/internal/ruml/protocol/protocol_capability_declaration.py +29 -0
  41. ruml_parser/internal/ruml/query/__init__.py +2 -0
  42. ruml_parser/internal/ruml/query/query_capability_declaration.py +23 -0
  43. ruml_parser/internal/ruml/query/query_node_capability.py +17 -0
  44. ruml_parser/internal/ruml/ruml_document.py +45 -0
  45. ruml_parser/internal/ruml/text_reference/__init__.py +2 -0
  46. ruml_parser/internal/ruml/text_reference/text.py +69 -0
  47. ruml_parser/internal/ruml/text_reference/text_reference_capability_declaration.py +25 -0
  48. ruml_parser/internal/ruml/text_reference/text_refs_node_capability.py +32 -0
  49. ruml_parser/internal/ruml/tree/__init__.py +2 -0
  50. ruml_parser/internal/ruml/tree/tree_capability_declarations.py +30 -0
  51. ruml_parser/internal/validation/__init__.py +14 -0
  52. ruml_parser/internal/validation/capabilities.py +227 -0
  53. ruml_parser/internal/validation/contexts.py +51 -0
  54. ruml_parser/internal/validation/datapoint_sets.py +125 -0
  55. ruml_parser/internal/validation/modular.py +42 -0
  56. ruml_parser/internal/validation/recursion.py +197 -0
  57. ruml_parser/internal/validation/root.py +36 -0
  58. ruml_parser/internal/validation/texts.py +50 -0
  59. ruml_parser/model/__init__.py +2 -0
  60. ruml_parser/model/ruml.py +1156 -0
  61. ruml_parser/model/ruml_result.py +430 -0
  62. ruml_parser/node_result_status.py +19 -0
  63. ruml_parser/pydantic.py +96 -0
  64. ruml_parser/ruml_parser.py +75 -0
  65. ruml_parser/schema_files.py +23 -0
  66. ruml_parser/schema_validation.py +354 -0
  67. ruml_parser/structural_error.py +36 -0
  68. ruml_parser/text.py +220 -0
  69. ruml_parser-1.0.0.dist-info/METADATA +119 -0
  70. ruml_parser-1.0.0.dist-info/RECORD +72 -0
  71. ruml_parser-1.0.0.dist-info/WHEEL +4 -0
  72. ruml_parser-1.0.0.dist-info/licenses/LICENSE +73 -0
@@ -0,0 +1,430 @@
1
+ # SPDX-FileCopyrightText: 2026 Rulemapping Group GmbH
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ # generated by datamodel-codegen:
4
+ # filename: ruml-result.schema.json
5
+
6
+ from collections.abc import Mapping, Sequence
7
+ from enum import Enum, StrEnum
8
+ from typing import Annotated, Any, Literal
9
+ from uuid import UUID
10
+
11
+ from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, constr
12
+
13
+
14
+ class FieldSpecVersion(StrEnum):
15
+ field_1_0 = "1.0"
16
+
17
+
18
+ type Uuid = UUID
19
+
20
+
21
+ class RumlReference(BaseModel):
22
+ model_config = ConfigDict(
23
+ extra="forbid",
24
+ populate_by_name=True,
25
+ frozen=True,
26
+ )
27
+ id: Uuid = Field(..., description="Id of the source RUML document evaluated")
28
+ hash: constr(pattern=r"^(?:sha3-256|sha256|blake3):[0-9a-f]{64}$") | None = Field(
29
+ None,
30
+ description="Integrity hash pinning the exact RUML content evaluated (`<algorithm>:<hex>`)",
31
+ )
32
+
33
+
34
+ type Timestamp = AwareDatetime
35
+
36
+
37
+ class EvaluationMode(StrEnum):
38
+ optimized = "optimized"
39
+ complete = "complete"
40
+
41
+
42
+ class OfficialCapabilityId(StrEnum):
43
+ ruml_datapoints = "ruml:datapoints"
44
+ ruml_text_reference = "ruml:text-reference"
45
+ ruml_context = "ruml:context"
46
+ ruml_query = "ruml:query"
47
+ ruml_ai_query = "ruml:ai-query"
48
+ ruml_expression = "ruml:expression"
49
+ ruml_actions = "ruml:actions"
50
+ ruml_protocol = "ruml:protocol"
51
+
52
+
53
+ type DraftCapabilityId = Annotated[
54
+ constr(pattern=r"^ruml:draft(?:\/[A-Za-z0-9_-]+)+$", min_length=1, max_length=128),
55
+ Field(
56
+ ...,
57
+ description="Local draft capability id (e.g. `ruml:draft/my-capability`). Used for in-progress capabilities.",
58
+ ),
59
+ ]
60
+
61
+
62
+ type ReverseDomainCapabilityId = Annotated[
63
+ constr(
64
+ pattern=r"^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+(?:\/[A-Za-z0-9_-]+)+$",
65
+ min_length=1,
66
+ max_length=128,
67
+ ),
68
+ Field(
69
+ ...,
70
+ description="Third-party capability id in reverse-domain form (e.g. `com.example/my-capability`).",
71
+ ),
72
+ ]
73
+
74
+
75
+ type NodePath = constr(pattern=r"^[1-9][0-9]*(\.[1-9][0-9]*)*$")
76
+
77
+
78
+ type LexId = constr(pattern=r"^[1-9][0-9]*$")
79
+
80
+
81
+ type CapabilityJson = (
82
+ str | float | bool | Sequence[CapabilityJson] | Mapping[str, CapabilityJson] | None
83
+ )
84
+
85
+
86
+ class IgnoredReasonType(StrEnum):
87
+ shortCircuit = "shortCircuit"
88
+ manualSkip = "manualSkip"
89
+ conditionalDeactivation = "conditionalDeactivation"
90
+
91
+
92
+ class ShortCircuitOperator(StrEnum):
93
+ AND = "AND"
94
+ XOR = "XOR"
95
+ NOT_AND = "NOT_AND"
96
+ NOT_XOR = "NOT_XOR"
97
+ undefined = "undefined"
98
+
99
+
100
+ class Type(Enum):
101
+ error = "error"
102
+ default = "default"
103
+
104
+
105
+ class UndefinedReason(BaseModel):
106
+ model_config = ConfigDict(
107
+ extra="forbid",
108
+ populate_by_name=True,
109
+ frozen=True,
110
+ )
111
+ type: Type = Field(
112
+ ...,
113
+ description="Cause: `error` (a technical error, such as a failed API call, a timeout or exceeding the maximum recursion depth of §6.4) or `default` (any other cause)",
114
+ )
115
+ message: constr(min_length=1) = Field(..., description="Human-readable explanation")
116
+
117
+
118
+ class Operator(StrEnum):
119
+ AND = "AND"
120
+ OR = "OR"
121
+ XOR = "XOR"
122
+ NOT_AND = "NOT_AND"
123
+ NOT_OR = "NOT_OR"
124
+ NOT_XOR = "NOT_XOR"
125
+ DELEGATED = "DELEGATED"
126
+ undefined = "undefined"
127
+
128
+
129
+ class Result(StrEnum):
130
+ true = "true"
131
+ false = "false"
132
+ undefined = "undefined"
133
+
134
+
135
+ class CapabilityQueryResult(BaseModel):
136
+ model_config = ConfigDict(
137
+ extra="forbid",
138
+ populate_by_name=True,
139
+ frozen=True,
140
+ )
141
+ expression: constr(min_length=1) = Field(
142
+ ..., description="The query expression that was evaluated"
143
+ )
144
+ inputs: Mapping[str, CapabilityJson] = Field(
145
+ ..., description="Resolved input values referenced by the expression"
146
+ )
147
+ result: Result = Field(
148
+ ...,
149
+ description="Computed result of evaluating the expression. Same string vocabulary as node status, without 'ignored'.",
150
+ )
151
+
152
+
153
+ class Status(StrEnum):
154
+ true = "true"
155
+ false = "false"
156
+
157
+
158
+ class Child(BaseModel):
159
+ model_config = ConfigDict(
160
+ extra="forbid",
161
+ populate_by_name=True,
162
+ frozen=True,
163
+ )
164
+ lexId: LexId
165
+ status: Status = Field(
166
+ ...,
167
+ description="The child's status as the expression saw it; the expression does not run when a child is `undefined`, so this payload exists only when every child is `true` or `false`",
168
+ )
169
+
170
+
171
+ class CapabilityExpressionResult(BaseModel):
172
+ model_config = ConfigDict(
173
+ extra="forbid",
174
+ populate_by_name=True,
175
+ frozen=True,
176
+ )
177
+ expression: constr(min_length=1) = Field(
178
+ ..., description="The expression that was evaluated"
179
+ )
180
+ inputs: Mapping[str, CapabilityJson] = Field(
181
+ ...,
182
+ description="Resolved datapoint values referenced by the expression; empty when it reads none",
183
+ )
184
+ children: Sequence[Child] = Field(
185
+ ..., description="The child results the expression saw, in `children` order"
186
+ )
187
+ result: Result = Field(
188
+ ...,
189
+ description="Computed result of evaluating the expression. Same string vocabulary as node status, without 'ignored'.",
190
+ )
191
+
192
+
193
+ class Type1(StrEnum):
194
+ ruml_evaluation_started = "ruml.evaluation.started"
195
+ ruml_evaluation_completed = "ruml.evaluation.completed"
196
+ ruml_evaluation_aborted = "ruml.evaluation.aborted"
197
+ ruml_node_evaluated = "ruml.node.evaluated"
198
+ ruml_node_skipped = "ruml.node.skipped"
199
+ ruml_datapoint_resolved = "ruml.datapoint.resolved"
200
+ ruml_action_triggered = "ruml.action.triggered"
201
+ ruml_warning = "ruml.warning"
202
+ ruml_error = "ruml.error"
203
+
204
+
205
+ class CloudEvent(BaseModel):
206
+ model_config = ConfigDict(
207
+ populate_by_name=True,
208
+ frozen=True,
209
+ )
210
+ specversion: Literal["1.0"]
211
+ id: constr(min_length=1) = Field(..., description="Unique together with source")
212
+ source: constr(min_length=1) = Field(
213
+ ...,
214
+ description="Identifies the evaluating engine; an absolute URI is RECOMMENDED",
215
+ )
216
+ type: Type1 | str = Field(
217
+ ...,
218
+ description="A ruml.* event type, or a custom type not using the ruml. prefix",
219
+ )
220
+ time: Timestamp = Field(
221
+ ..., description="REQUIRED in this profile, unlike in CloudEvents"
222
+ )
223
+ subject: constr(min_length=1) | None = Field(
224
+ None, description="Node path or datapoint id the event refers to"
225
+ )
226
+ data: Any | None = Field(None, description="Event payload as a direct JSON value")
227
+
228
+
229
+ class Level(StrEnum):
230
+ standard = "standard"
231
+ verbose = "verbose"
232
+
233
+
234
+ class ProtocolResult(BaseModel):
235
+ model_config = ConfigDict(
236
+ extra="forbid",
237
+ populate_by_name=True,
238
+ frozen=True,
239
+ )
240
+ level: Level | None = Field(
241
+ None, description="The verbosity the protocol was recorded at"
242
+ )
243
+ events: Sequence[CloudEvent] = Field(
244
+ ..., description="CloudEvents v1.0 JSON Batch Format"
245
+ )
246
+
247
+
248
+ type CapabilityId = OfficialCapabilityId | DraftCapabilityId | ReverseDomainCapabilityId
249
+
250
+
251
+ class IgnoredReason(BaseModel):
252
+ model_config = ConfigDict(
253
+ extra="forbid",
254
+ populate_by_name=True,
255
+ frozen=True,
256
+ )
257
+ type: IgnoredReasonType = Field(
258
+ ..., description="Reason of why the node was ignored"
259
+ )
260
+ trigger: constr(min_length=1) = Field(
261
+ ..., description="Identifier of the sibling/node that caused the ignore"
262
+ )
263
+ operator: Operator = Field(
264
+ ...,
265
+ description="Operator of the parent node; tools use it to display the result",
266
+ )
267
+ mode: EvaluationMode = Field(
268
+ ..., description="Evaluation mode under which the node was ignored"
269
+ )
270
+
271
+
272
+ class ResultCapabilityEntry(BaseModel):
273
+ model_config = ConfigDict(
274
+ extra="forbid",
275
+ populate_by_name=True,
276
+ frozen=True,
277
+ )
278
+ id: CapabilityId = Field(..., description="The capability this entry reports on")
279
+ payload: Mapping[str, Any] | None = Field(
280
+ None, description="Capability-defined content produced by the evaluation"
281
+ )
282
+
283
+
284
+ class ResultNodeCapabilityEntry(ResultCapabilityEntry):
285
+ model_config = ConfigDict(
286
+ populate_by_name=True,
287
+ frozen=True,
288
+ )
289
+
290
+
291
+ type ResultNodeCapabilities = Annotated[
292
+ Sequence[ResultNodeCapabilityEntry],
293
+ Field(
294
+ ...,
295
+ description="Node-level capability results, in order (§5.1); the order is significant",
296
+ ),
297
+ ]
298
+
299
+
300
+ class NodeResultBase(BaseModel):
301
+ model_config = ConfigDict(
302
+ populate_by_name=True,
303
+ frozen=True,
304
+ )
305
+ lexId: LexId = Field(..., description="LexId of the node this result refers to")
306
+ evaluatedAt: Timestamp | None = Field(
307
+ None, description="Optional timestamp when the node was evaluated"
308
+ )
309
+ capabilities: ResultNodeCapabilities | None = Field(
310
+ None, description="Optional resolved capability result values for the node"
311
+ )
312
+
313
+
314
+ class TrueResult(NodeResultBase):
315
+ model_config = ConfigDict(
316
+ extra="forbid",
317
+ populate_by_name=True,
318
+ frozen=True,
319
+ )
320
+ status: Literal["true"] = Field(
321
+ ..., description="Final evaluated status of the node"
322
+ )
323
+ reason: str = Field(..., description="Human-readable explanation of the outcome")
324
+
325
+
326
+ class FalseResult(NodeResultBase):
327
+ model_config = ConfigDict(
328
+ extra="forbid",
329
+ populate_by_name=True,
330
+ frozen=True,
331
+ )
332
+ status: Literal["false"] = Field(
333
+ ..., description="Final evaluated status of the node"
334
+ )
335
+ reason: str = Field(..., description="Human-readable explanation of the outcome")
336
+
337
+
338
+ class UndefinedResult(NodeResultBase):
339
+ model_config = ConfigDict(
340
+ extra="forbid",
341
+ populate_by_name=True,
342
+ frozen=True,
343
+ )
344
+ status: Literal["undefined"] = Field(
345
+ ..., description="Final evaluated status of the node"
346
+ )
347
+ reason: UndefinedReason = Field(..., description="Why the node is `undefined`")
348
+
349
+
350
+ class IgnoredResult(NodeResultBase):
351
+ model_config = ConfigDict(
352
+ extra="forbid",
353
+ populate_by_name=True,
354
+ frozen=True,
355
+ )
356
+ status: Literal["ignored"] = Field(
357
+ ..., description="Final evaluated status of the node"
358
+ )
359
+ reason: IgnoredReason = Field(..., description="Why the node was ignored")
360
+
361
+
362
+ type NodeResult = Annotated[
363
+ TrueResult | FalseResult | UndefinedResult | IgnoredResult,
364
+ Field(
365
+ ...,
366
+ description="Result of one node instance; its status decides the shape of `reason`",
367
+ ),
368
+ ]
369
+
370
+
371
+ class Evaluation(BaseModel):
372
+ model_config = ConfigDict(
373
+ extra="forbid",
374
+ populate_by_name=True,
375
+ frozen=True,
376
+ )
377
+ id: Uuid = Field(..., description="Unique id of this evaluation run")
378
+ timestamp: Timestamp = Field(
379
+ ..., description="Timestamp when the evaluation completed"
380
+ )
381
+ mode: EvaluationMode = Field(
382
+ ..., description="Mode under which the rulemap was evaluated"
383
+ )
384
+ caseId: str | None = Field(
385
+ None, description="Optional id of the case this evaluation belongs to"
386
+ )
387
+ userId: str | None = Field(
388
+ None, description="Optional id of the user who ran the evaluation"
389
+ )
390
+ toolId: str | None = Field(
391
+ None, description="Optional id of the tool that produced this result"
392
+ )
393
+ toolVersion: str | None = Field(
394
+ None, description="Optional version of the tool that produced this result"
395
+ )
396
+ startTimestamp: Timestamp | None = Field(
397
+ None, description="Optional timestamp when the evaluation started"
398
+ )
399
+ capabilities: Sequence[ResultCapabilityEntry] | None = Field(
400
+ None,
401
+ description="Capabilities active during evaluation, in order; the order is significant",
402
+ )
403
+ results: Mapping[NodePath, NodeResult] = Field(
404
+ ..., description="Per-node evaluation results, keyed by node lex-path"
405
+ )
406
+
407
+
408
+ class RumlResultRumlEvaluationResultFormat(BaseModel):
409
+ model_config = ConfigDict(
410
+ extra="forbid",
411
+ populate_by_name=True,
412
+ frozen=True,
413
+ )
414
+ field_format: Literal["RUML-Result"] = Field(
415
+ ...,
416
+ alias="$format",
417
+ description="Format discriminator identifying this as a RUML result",
418
+ )
419
+ field_specVersion: FieldSpecVersion = Field(
420
+ ...,
421
+ alias="$specVersion",
422
+ description="RUML spec version this result conforms to",
423
+ )
424
+ rumlReference: RumlReference = Field(
425
+ ...,
426
+ description="Reference to the source RUML document this result was produced from",
427
+ )
428
+ evaluation: Evaluation = Field(
429
+ ..., description="The evaluation run and its per-node results, indexed by path"
430
+ )
@@ -0,0 +1,19 @@
1
+ # SPDX-FileCopyrightText: 2026 Rulemapping Group GmbH
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """The statuses a node result of a RUML-Result document can have.
4
+
5
+ Hand-written because the RUML-Result schema has no enum of the statuses: each one
6
+ selects its own result shape (`TrueResult`, ..., `IgnoredResult` in
7
+ `ruml_parser.model.ruml_result`), whose `status` is a constant.
8
+ """
9
+
10
+ from enum import StrEnum
11
+
12
+
13
+ class NodeResultStatus(StrEnum):
14
+ """Final evaluated status of a node; `pending` nodes are omitted from results."""
15
+
16
+ true = "true"
17
+ false = "false"
18
+ undefined = "undefined"
19
+ ignored = "ignored"
@@ -0,0 +1,96 @@
1
+ # SPDX-FileCopyrightText: 2026 Rulemapping Group GmbH
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Support for using rulemaps in Pydantic models and similar structures."""
4
+
5
+ from collections.abc import Mapping
6
+ from functools import cache
7
+ from typing import Annotated, Any, NoReturn
8
+
9
+ import jsonschema
10
+ from pydantic import GetPydanticSchema, ValidationError
11
+ from pydantic_core import InitErrorDetails, PydanticCustomError, core_schema
12
+
13
+ from ruml_parser.internal.ruml import RumlDocument
14
+ from ruml_parser.model.ruml import RumlRulemappingLogicFormat
15
+ from ruml_parser.ruml_parser import RumlParser
16
+ from ruml_parser.schema_validation import RumlValidationError, offending_path
17
+
18
+
19
+ @cache
20
+ def _parser() -> RumlParser:
21
+ """Build the parser of every `ParsedRumlDocument`, on first use rather than import."""
22
+ return RumlParser()
23
+
24
+
25
+ def _parse(
26
+ value: Any, handler: core_schema.ValidatorFunctionWrapHandler
27
+ ) -> RumlDocument:
28
+ """Parse ``value`` with `_parser()`, raising its schema errors as Pydantic ones.
29
+
30
+ A mapping (a dict, or decoded JSON) is checked against the schema as it is; anything
31
+ else must validate as the generated model, whose dump is then checked.
32
+ """
33
+ try:
34
+ if isinstance(value, Mapping):
35
+ return _parser().parse_dict(value)
36
+ return _parser().parse_model(handler(value))
37
+ except RumlValidationError as error:
38
+ raise _located_validation_error(error) from error
39
+
40
+
41
+ def _located_validation_error(error: RumlValidationError) -> ValidationError:
42
+ """Turn ``error``'s violations into Pydantic errors, each at its own location.
43
+
44
+ Raised from a validator, these show up under the field's location, like the errors
45
+ of a nested model do.
46
+ """
47
+ return ValidationError.from_exception_data(
48
+ RumlRulemappingLogicFormat.__name__,
49
+ [_line_error(violation) for violation in error.errors],
50
+ )
51
+
52
+
53
+ def _line_error(violation: jsonschema.exceptions.ValidationError) -> InitErrorDetails:
54
+ """Convert ``violation`` to Pydantic error details at the location it concerns."""
55
+ return InitErrorDetails(
56
+ type=PydanticCustomError(
57
+ "ruml_schema", "{message}", {"message": violation.message}
58
+ ),
59
+ loc=tuple(offending_path(violation)),
60
+ input=violation.instance,
61
+ )
62
+
63
+
64
+ def _refuse_serialization(document: RumlDocument) -> NoReturn:
65
+ raise TypeError(
66
+ "a RumlDocument cannot be serialized: there is no mapping back to RUML"
67
+ )
68
+
69
+
70
+ # See: https://pydantic.dev/docs/validation/latest/concepts/types/#using-getpydanticschema-to-reduce-boilerplate
71
+ ParsedRumlDocument = Annotated[
72
+ RumlDocument,
73
+ GetPydanticSchema(
74
+ lambda _source, handler: core_schema.no_info_wrap_validator_function(
75
+ _parse,
76
+ handler(RumlRulemappingLogicFormat),
77
+ serialization=core_schema.plain_serializer_function_ser_schema(
78
+ _refuse_serialization
79
+ ),
80
+ )
81
+ ),
82
+ ]
83
+ """Pydantic type that accepts RUML and yields the internal `RumlDocument`.
84
+
85
+ Parses its input with a `RumlParser`, so it checks the input against the RUML schema
86
+ before `to_internal` maps it. Each schema violation becomes an error at the location it
87
+ concerns (within the field's), and the `ValueError` that `to_internal` raises becomes
88
+ part of the `ValidationError` as usual. Its JSON schema, e.g. in an OpenAPI document, is
89
+ that of `RumlRulemappingLogicFormat`, which it also accepts instances of (see
90
+ `RumlParser.parse_model` for how those are checked).
91
+
92
+ A field of this type can't be serialized, as nothing maps a `RumlDocument` back to RUML.
93
+
94
+ A plain alias rather than a `type` statement, as the latter would show up under its own
95
+ name in JSON schemas, making an implementation detail part of e.g. an OpenAPI document.
96
+ """
@@ -0,0 +1,75 @@
1
+ # SPDX-FileCopyrightText: 2026 Rulemapping Group GmbH
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """``RumlParser``: RUML in any of its forms, parsed into the internal ``RumlDocument``."""
4
+
5
+ import json
6
+ from collections.abc import Iterable, Mapping
7
+ from typing import Any
8
+
9
+ from ruml_parser.internal.extension import CapabilityExtension
10
+ from ruml_parser.internal.mapping import to_internal
11
+ from ruml_parser.internal.ruml import RumlDocument
12
+ from ruml_parser.model.ruml import RumlRulemappingLogicFormat
13
+ from ruml_parser.schema_validation import RumlValidationError, ruml_validator
14
+
15
+
16
+ class RumlParser:
17
+ """Parses RUML into the internal model, modeling the capabilities of ``extensions``.
18
+
19
+ Every ``parse_*`` method checks its input against the RUML schema and the
20
+ extensions' payload schemas, then maps it with ``to_internal``, which checks the
21
+ spec's cross-object rules and the extensions' own.
22
+
23
+ The generated Pydantic model alone is not a faithful validator: codegen drops the
24
+ schema's top-level ``allOf`` cross-field rules and cannot follow the ``if``/``then``
25
+ rules that pick a capability payload's schema by its id (see
26
+ scripts/update_models.py). Validating against the schema first catches what the
27
+ model would silently accept.
28
+
29
+ The schema validator is built once, on construction, so reuse an instance rather
30
+ than creating one per document.
31
+
32
+ Raises (from every ``parse_*`` method):
33
+ RumlValidationError: If the document violates the RUML schema or an
34
+ extension's payload schema.
35
+ ValueError: If it violates a rule that ``to_internal`` checks; see there.
36
+ """
37
+
38
+ def __init__(self, *, extensions: Iterable[CapabilityExtension] = ()) -> None:
39
+ self._extensions = tuple(extensions)
40
+ self._validator = ruml_validator(self._extensions)
41
+
42
+ def parse_json(self, ruml: str | bytes) -> RumlDocument:
43
+ """Parse a RUML document given as JSON text.
44
+
45
+ Raises:
46
+ json.JSONDecodeError: If ``ruml`` is not JSON (a ``ValueError`` as well).
47
+ """
48
+ return self.parse_dict(json.loads(ruml))
49
+
50
+ def parse_dict(self, ruml: Mapping[str, Any]) -> RumlDocument:
51
+ """Parse a RUML document given as decoded JSON, e.g. from ``json.loads``."""
52
+ self._validate_schema(ruml)
53
+ return self._to_internal(RumlRulemappingLogicFormat.model_validate(ruml))
54
+
55
+ def parse_model(self, ruml: RumlRulemappingLogicFormat) -> RumlDocument:
56
+ """Parse a RUML document given as the generated Pydantic model.
57
+
58
+ The model accepts documents the schema rejects (see the class docstring), so it is
59
+ dumped back to JSON to be checked against the schema as well. Its dump
60
+ reflects what the model holds, though, not the JSON it was validated from:
61
+ values the model normalizes (e.g. an upper-case UUID) pass even where the
62
+ schema rejects their original form.
63
+ """
64
+ self._validate_schema(
65
+ ruml.model_dump(mode="json", by_alias=True, exclude_unset=True)
66
+ )
67
+ return self._to_internal(ruml)
68
+
69
+ def _validate_schema(self, ruml: Mapping[str, Any]) -> None:
70
+ errors = list(self._validator.iter_errors(ruml))
71
+ if errors:
72
+ raise RumlValidationError(errors)
73
+
74
+ def _to_internal(self, ruml: RumlRulemappingLogicFormat) -> RumlDocument:
75
+ return to_internal(ruml, self._extensions)
@@ -0,0 +1,23 @@
1
+ # SPDX-FileCopyrightText: 2026 Rulemapping Group GmbH
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Paths of & metadata handling for the RUML JSON Schema files.
4
+
5
+ The files come with the `ruml-schema` package, which this package pins to the version
6
+ its models are generated from.
7
+ """
8
+
9
+ import json
10
+ from pathlib import Path
11
+
12
+ from ruml_schema import RUML_RESULT_SCHEMA_PATH, RUML_SCHEMA_PATH
13
+
14
+ SCHEMA_PATH = RUML_SCHEMA_PATH
15
+ """The RUML schema."""
16
+
17
+ RESULT_SCHEMA_PATH = RUML_RESULT_SCHEMA_PATH
18
+ """The RUML-Result schema."""
19
+
20
+
21
+ def schema_id(path: Path) -> str:
22
+ """Read the ``$id`` that the schema file at ``path`` declares."""
23
+ return json.loads(path.read_text(encoding="utf-8"))["$id"]