flow-lang-toolkit 0.1.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.
@@ -0,0 +1,1546 @@
1
+ """Type-directed conversion between Python values and the value encoding.
2
+
3
+ Each Flow type has one ``Codec``: ``encode`` turns a Python value into a
4
+ ``JsonValue`` (written canonically by ``write_json``), and ``decode`` reads a
5
+ ``JsonValue`` strictly, refusing with ``DecodeError`` anything the encoding
6
+ does not allow. Decoding never coerces, guesses a constructor, fills a default
7
+ or repairs a value.
8
+
9
+ | Flow | Python |
10
+ | --- | --- |
11
+ | ``Int`` | ``int`` |
12
+ | ``Decimal`` | ``decimal.Decimal``, normalized |
13
+ | ``Bool`` | ``bool`` |
14
+ | ``Text`` | ``str`` |
15
+ | ``Bytes`` | ``bytes`` |
16
+ | ``Duration``, ``Instant`` | ``Duration``, ``Instant`` |
17
+ | ``Unit`` | ``()`` |
18
+ | ``json.Value`` | ``JsonValue`` |
19
+ | ``List<T>`` | ``list`` |
20
+ | ``Set<T>`` | ``FlowSet`` |
21
+ | ``Dict<K, V>`` | ``FlowDict`` |
22
+ | tuple | ``tuple`` |
23
+ | ``Option<T>`` | ``T | None``, or ``Some[T] | None`` when ``T`` can itself be ``None`` |
24
+ | record | a frozen dataclass |
25
+ | enum | one frozen dataclass per constructor |
26
+ | ``@tool type`` | a ``HostToken`` subclass |
27
+
28
+ A ``FlowSet`` and a ``FlowDict`` tell elements and keys apart by Flow equality
29
+ and iterate in Flow's order; encoding writes them in that order. Encoding also
30
+ takes a plain ``set``, ``frozenset`` or ``dict`` holding values Python can hash.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import base64
36
+ import binascii
37
+ import dataclasses
38
+ from abc import ABC, abstractmethod
39
+ from collections.abc import Callable, Mapping, Sequence
40
+ from collections.abc import Set as AbstractSet
41
+ from decimal import Decimal
42
+ from typing import Any, Generic, Never, TypeVar, cast
43
+
44
+ from ._collections import FlowDict, FlowSet, Key, order_key
45
+ from ._json import (
46
+ MAX_INT_DIGITS,
47
+ DuplicateKeysObject,
48
+ JsonError,
49
+ JsonValue,
50
+ decimal_text,
51
+ has_lone_surrogate,
52
+ write_json,
53
+ )
54
+ from ._time import Duration, Instant
55
+
56
+ T = TypeVar("T")
57
+ K = TypeVar("K")
58
+ V = TypeVar("V")
59
+
60
+
61
+ class _PathError(ValueError):
62
+ def __init__(self, reason: str, path: tuple[str, ...] = ()) -> None:
63
+ super().__init__(reason)
64
+ self.reason = reason
65
+ self.path = path
66
+
67
+ def at(self, segment: str) -> _PathError:
68
+ """The same failure one level further out."""
69
+ return type(self)(self.reason, (segment, *self.path))
70
+
71
+ def __str__(self) -> str:
72
+ if not self.path:
73
+ return self.reason
74
+ where = ""
75
+ for segment in self.path:
76
+ where += segment if segment.startswith("[") or not where else "." + segment
77
+ return f"at {where}: {self.reason}"
78
+
79
+
80
+ class DecodeError(_PathError):
81
+ """A JSON value that does not decode at the declared type."""
82
+
83
+
84
+ class EncodeError(_PathError):
85
+ """A Python value that is not a value of the declared type."""
86
+
87
+
88
+ def _kind(data: object) -> str:
89
+ if data is None:
90
+ return "null"
91
+ if isinstance(data, bool):
92
+ return "a boolean"
93
+ if isinstance(data, (int, Decimal)):
94
+ return "a number"
95
+ if isinstance(data, str):
96
+ return "a string"
97
+ if isinstance(data, list):
98
+ return "an array"
99
+ if isinstance(data, dict):
100
+ return "an object"
101
+ return type(data).__name__
102
+
103
+
104
+ def _object(data: JsonValue, what: str) -> dict[str, JsonValue]:
105
+ if not isinstance(data, dict):
106
+ raise DecodeError(f"expected {what}, found {_kind(data)}")
107
+ if isinstance(data, DuplicateKeysObject):
108
+ raise DecodeError(f"the key {data.duplicate!r} appears twice in one object")
109
+ return data
110
+
111
+
112
+ @dataclasses.dataclass(frozen=True)
113
+ class Some(Generic[T]):
114
+ """``Some(value)`` of an ``Option`` whose ``T`` can itself be ``None``,
115
+ so ``Option<Option<Int>>`` keeps ``Some(None)`` apart from ``None``."""
116
+
117
+ value: T
118
+
119
+
120
+ @dataclasses.dataclass(frozen=True)
121
+ class HostToken:
122
+ """A value of a ``@tool type``: the token the implementation chose.
123
+
124
+ Generated code declares one subclass per host type, so tokens of
125
+ different types never mix.
126
+ """
127
+
128
+ token: str
129
+
130
+
131
+ class Codec(ABC, Generic[T]):
132
+ """Encoding and decoding for one Flow type."""
133
+
134
+ @property
135
+ def is_text(self) -> bool:
136
+ return isinstance(self, _TextCodec)
137
+
138
+ def compare(self, left: T, right: T) -> int:
139
+ a = order_key(self.decode(self.encode(left)))
140
+ b = order_key(self.decode(self.encode(right)))
141
+ return (a > b) - (a < b)
142
+
143
+ @abstractmethod
144
+ def encode(self, value: T) -> JsonValue:
145
+ """The JSON value of ``value``; raises ``EncodeError``."""
146
+
147
+ @abstractmethod
148
+ def decode(self, data: JsonValue) -> T:
149
+ """The value ``data`` encodes; raises ``DecodeError``."""
150
+
151
+
152
+ class _IntCodec(Codec[int]):
153
+ def encode(self, value: int) -> JsonValue:
154
+ if isinstance(value, bool) or not isinstance(value, int):
155
+ raise EncodeError(f"expected an int, found {type(value).__name__}")
156
+ return value
157
+
158
+ def decode(self, data: JsonValue) -> int:
159
+ if isinstance(data, bool) or not isinstance(data, (int, Decimal)):
160
+ raise DecodeError(f"expected an integer, found {_kind(data)}")
161
+ if isinstance(data, int):
162
+ return data
163
+ try:
164
+ text = decimal_text(data)
165
+ except JsonError:
166
+ raise DecodeError("an integer past the size limit") from None
167
+ if "." in text:
168
+ raise DecodeError(f"expected a whole number, found {text}")
169
+ if len(text.lstrip("-")) > MAX_INT_DIGITS:
170
+ raise DecodeError("an integer past the size limit")
171
+ return int(text)
172
+
173
+
174
+ class _DecimalCodec(Codec[Decimal]):
175
+ def encode(self, value: Decimal) -> JsonValue:
176
+ if isinstance(value, bool) or not isinstance(value, (Decimal, int)):
177
+ raise EncodeError(f"expected a Decimal, found {type(value).__name__}")
178
+ try:
179
+ return Decimal(decimal_text(Decimal(value)))
180
+ except JsonError as error:
181
+ raise EncodeError(str(error)) from None
182
+
183
+ def decode(self, data: JsonValue) -> Decimal:
184
+ if isinstance(data, bool) or not isinstance(data, (int, Decimal)):
185
+ raise DecodeError(f"expected a number, found {_kind(data)}")
186
+ try:
187
+ return Decimal(decimal_text(Decimal(data)))
188
+ except JsonError as error:
189
+ raise DecodeError(str(error)) from None
190
+
191
+
192
+ class _BoolCodec(Codec[bool]):
193
+ def encode(self, value: bool) -> JsonValue:
194
+ if not isinstance(value, bool):
195
+ raise EncodeError(f"expected a bool, found {type(value).__name__}")
196
+ return value
197
+
198
+ def decode(self, data: JsonValue) -> bool:
199
+ if not isinstance(data, bool):
200
+ raise DecodeError(f"expected a boolean, found {_kind(data)}")
201
+ return data
202
+
203
+
204
+ class _TextCodec(Codec[str]):
205
+ def encode(self, value: str) -> JsonValue:
206
+ if not isinstance(value, str):
207
+ raise EncodeError(f"expected a str, found {type(value).__name__}")
208
+ if has_lone_surrogate(value):
209
+ raise EncodeError("text holding a lone surrogate has no encoding")
210
+ return value
211
+
212
+ def decode(self, data: JsonValue) -> str:
213
+ if not isinstance(data, str):
214
+ raise DecodeError(f"expected a string, found {_kind(data)}")
215
+ if has_lone_surrogate(data):
216
+ raise DecodeError("a string names a lone surrogate")
217
+ return data
218
+
219
+
220
+ class _BytesCodec(Codec[bytes]):
221
+ def encode(self, value: bytes) -> JsonValue:
222
+ if not isinstance(value, (bytes, bytearray)):
223
+ raise EncodeError(f"expected bytes, found {type(value).__name__}")
224
+ return base64.b64encode(bytes(value)).decode("ascii")
225
+
226
+ def decode(self, data: JsonValue) -> bytes:
227
+ if not isinstance(data, str):
228
+ raise DecodeError(f"expected a base64 string, found {_kind(data)}")
229
+ try:
230
+ value = base64.b64decode(data.encode("ascii"), validate=True)
231
+ except (binascii.Error, UnicodeEncodeError):
232
+ raise DecodeError("not standard base64 with padding") from None
233
+ if base64.b64encode(value).decode("ascii") != data:
234
+ raise DecodeError("not standard base64 with padding")
235
+ return value
236
+
237
+
238
+ class _DurationCodec(Codec[Duration]):
239
+ def encode(self, value: Duration) -> JsonValue:
240
+ if not isinstance(value, Duration):
241
+ raise EncodeError(f"expected a Duration, found {type(value).__name__}")
242
+ return str(value)
243
+
244
+ def decode(self, data: JsonValue) -> Duration:
245
+ if not isinstance(data, str):
246
+ raise DecodeError(f"expected a duration string, found {_kind(data)}")
247
+ try:
248
+ return Duration.parse(data)
249
+ except ValueError as error:
250
+ raise DecodeError(str(error)) from None
251
+
252
+
253
+ class _InstantCodec(Codec[Instant]):
254
+ def encode(self, value: Instant) -> JsonValue:
255
+ if not isinstance(value, Instant):
256
+ raise EncodeError(f"expected an Instant, found {type(value).__name__}")
257
+ return str(value)
258
+
259
+ def decode(self, data: JsonValue) -> Instant:
260
+ if not isinstance(data, str):
261
+ raise DecodeError(f"expected an instant string, found {_kind(data)}")
262
+ try:
263
+ return Instant.parse(data)
264
+ except ValueError as error:
265
+ raise DecodeError(str(error)) from None
266
+
267
+
268
+ class _UnitCodec(Codec[tuple[()]]):
269
+ def encode(self, value: tuple[()]) -> JsonValue:
270
+ if value != () or not isinstance(value, tuple):
271
+ raise EncodeError(f"expected (), found {value!r}")
272
+ return []
273
+
274
+ def decode(self, data: JsonValue) -> tuple[()]:
275
+ if data != [] or not isinstance(data, list):
276
+ raise DecodeError(f"expected [], found {_kind(data)}")
277
+ return ()
278
+
279
+
280
+ class _NeverCodec(Codec[Never]):
281
+ def encode(self, value: Never) -> JsonValue:
282
+ raise EncodeError("Never has no values")
283
+
284
+ def decode(self, data: JsonValue) -> Never:
285
+ raise DecodeError("Never has no values")
286
+
287
+
288
+ def _check_json(data: JsonValue, encoding: bool) -> JsonValue:
289
+ error = EncodeError if encoding else DecodeError
290
+ if data is None or isinstance(data, (bool, int, str, list, dict, Decimal)):
291
+ try:
292
+ write_json(data)
293
+ except (JsonError, RecursionError) as problem:
294
+ raise error(str(problem)) from None
295
+ return data
296
+ raise error(f"{type(data).__name__} is not a JSON value")
297
+
298
+
299
+ class _JsonCodec(Codec[JsonValue]):
300
+ def encode(self, value: JsonValue) -> JsonValue:
301
+ return _check_json(value, encoding=True)
302
+
303
+ def decode(self, data: JsonValue) -> JsonValue:
304
+ return _check_json(data, encoding=False)
305
+
306
+
307
+ INT: Codec[int] = _IntCodec()
308
+ DECIMAL: Codec[Decimal] = _DecimalCodec()
309
+ BOOL: Codec[bool] = _BoolCodec()
310
+ TEXT: Codec[str] = _TextCodec()
311
+ BYTES: Codec[bytes] = _BytesCodec()
312
+ DURATION: Codec[Duration] = _DurationCodec()
313
+ INSTANT: Codec[Instant] = _InstantCodec()
314
+ UNIT: Codec[tuple[()]] = _UnitCodec()
315
+ NEVER: Codec[Never] = _NeverCodec()
316
+ JSON: Codec[JsonValue] = _JsonCodec()
317
+ """``json.Value``, and a generic Tool's type parameter: raw JSON, exact numbers."""
318
+
319
+
320
+ def _key(value: Any, error: type[_PathError]) -> Key:
321
+ """``value``'s ``order_key``, or why it has none."""
322
+ try:
323
+ return order_key(value)
324
+ except TypeError as problem:
325
+ raise error(str(problem)) from None
326
+
327
+
328
+ class ListCodec(Codec[list[T]]):
329
+ """``List<T>``: an array in list order."""
330
+
331
+ def __init__(self, item: Codec[T]) -> None:
332
+ self.item = item
333
+
334
+ def encode(self, value: list[T]) -> JsonValue:
335
+ if not isinstance(value, list):
336
+ raise EncodeError(f"expected a list, found {type(value).__name__}")
337
+ out: list[JsonValue] = []
338
+ for index, element in enumerate(value):
339
+ try:
340
+ out.append(self.item.encode(element))
341
+ except EncodeError as error:
342
+ raise error.at(f"[{index}]") from None
343
+ return out
344
+
345
+ def decode(self, data: JsonValue) -> list[T]:
346
+ if not isinstance(data, list):
347
+ raise DecodeError(f"expected an array, found {_kind(data)}")
348
+ out: list[T] = []
349
+ for index, element in enumerate(data):
350
+ try:
351
+ out.append(self.item.decode(element))
352
+ except DecodeError as error:
353
+ raise error.at(f"[{index}]") from None
354
+ return out
355
+
356
+
357
+ class SetCodec(Codec[FlowSet[T]]):
358
+ """``Set<T>``: an array in ascending order, no duplicates; repeats collapse
359
+ on decode. Elements are told apart by Flow equality and ordered by Flow's
360
+ order (``order_key``)."""
361
+
362
+ def __init__(self, item: Codec[T]) -> None:
363
+ self.item = item
364
+
365
+ def encode(self, value: AbstractSet[T]) -> JsonValue:
366
+ if not isinstance(value, AbstractSet):
367
+ raise EncodeError(f"expected a FlowSet, found {type(value).__name__}")
368
+ try:
369
+ elements = value if isinstance(value, FlowSet) else FlowSet(value)
370
+ except TypeError as problem:
371
+ raise EncodeError(str(problem)) from None
372
+ out: list[JsonValue] = []
373
+ for index, element in enumerate(elements):
374
+ try:
375
+ out.append(self.item.encode(element))
376
+ except EncodeError as error:
377
+ raise error.at(f"[{index}]") from None
378
+ return out
379
+
380
+ def decode(self, data: JsonValue) -> FlowSet[T]:
381
+ if not isinstance(data, list):
382
+ raise DecodeError(f"expected an array, found {_kind(data)}")
383
+ out: list[T] = []
384
+ for index, element in enumerate(data):
385
+ try:
386
+ out.append(self.item.decode(element))
387
+ except DecodeError as error:
388
+ raise error.at(f"[{index}]") from None
389
+ return FlowSet(out)
390
+
391
+
392
+ class DictCodec(Codec[FlowDict[K, V]]):
393
+ """``Dict<K, V>``: an object for ``Text`` keys, otherwise an array of
394
+ ``[key, value]`` pairs in ascending key order. Keys are told apart by Flow
395
+ equality and ordered by Flow's order (``order_key``); two equal keys are
396
+ refused."""
397
+
398
+ def __init__(self, key: Codec[K], value: Codec[V], *, text_keys: bool = False) -> None:
399
+ self.key = key
400
+ self.value = value
401
+ self.text_keys = text_keys
402
+
403
+ def encode(self, value: Mapping[K, V]) -> JsonValue:
404
+ if not isinstance(value, Mapping):
405
+ raise EncodeError(f"expected a FlowDict, found {type(value).__name__}")
406
+ if self.text_keys:
407
+ obj: dict[str, JsonValue] = {}
408
+ for key, item in value.items():
409
+ encoded_key = self.key.encode(key)
410
+ assert isinstance(encoded_key, str)
411
+ try:
412
+ obj[encoded_key] = self.value.encode(item)
413
+ except EncodeError as error:
414
+ raise error.at(encoded_key) from None
415
+ return obj
416
+ entries: dict[Key, tuple[JsonValue, V]] = {}
417
+ for key, item in value.items():
418
+ try:
419
+ encoded_key = self.key.encode(key)
420
+ except EncodeError as error:
421
+ raise error.at("key") from None
422
+ order = _key(key, EncodeError)
423
+ if order in entries:
424
+ raise EncodeError(f"two equal keys in one dictionary: {write_json(encoded_key)}")
425
+ entries[order] = (encoded_key, item)
426
+ pairs: list[JsonValue] = []
427
+ for _, (encoded_key, item) in sorted(entries.items(), key=lambda entry: entry[0]):
428
+ try:
429
+ pairs.append([encoded_key, self.value.encode(item)])
430
+ except EncodeError as error:
431
+ raise error.at(f"[{write_json(encoded_key)}]") from None
432
+ return pairs
433
+
434
+ def _put(self, out: dict[Key, tuple[K, V]], key: K, item: V, where: str) -> None:
435
+ order = _key(key, DecodeError)
436
+ if order in out:
437
+ raise DecodeError("two equal keys in one dictionary").at(where)
438
+ out[order] = (key, item)
439
+
440
+ def decode(self, data: JsonValue) -> FlowDict[K, V]:
441
+ out: dict[Key, tuple[K, V]] = {}
442
+ if self.text_keys:
443
+ obj = _object(data, "an object")
444
+ for raw_key, raw_value in obj.items():
445
+ try:
446
+ key = self.key.decode(raw_key)
447
+ item = self.value.decode(raw_value)
448
+ except DecodeError as error:
449
+ raise error.at(raw_key) from None
450
+ self._put(out, key, item, raw_key)
451
+ return FlowDict(out.values())
452
+ if not isinstance(data, list):
453
+ raise DecodeError(f"expected an array of [key, value] pairs, found {_kind(data)}")
454
+ for index, pair in enumerate(data):
455
+ where = f"[{index}]"
456
+ if not isinstance(pair, list) or len(pair) != 2:
457
+ raise DecodeError("expected a [key, value] pair").at(where)
458
+ try:
459
+ key = self.key.decode(pair[0])
460
+ item = self.value.decode(pair[1])
461
+ except DecodeError as error:
462
+ raise error.at(where) from None
463
+ self._put(out, key, item, where)
464
+ return FlowDict(out.values())
465
+
466
+
467
+ class TupleCodec(Codec[tuple[Any, ...]]):
468
+ """A tuple: an array of its elements."""
469
+
470
+ def __init__(self, items: Sequence[Codec[Any]]) -> None:
471
+ self.items = tuple(items)
472
+
473
+ def encode(self, value: tuple[Any, ...]) -> JsonValue:
474
+ if not isinstance(value, tuple) or len(value) != len(self.items):
475
+ raise EncodeError(f"expected a tuple of {len(self.items)}, found {value!r}")
476
+ out: list[JsonValue] = []
477
+ for index, (codec, element) in enumerate(zip(self.items, value)):
478
+ try:
479
+ out.append(codec.encode(element))
480
+ except EncodeError as error:
481
+ raise error.at(f"[{index}]") from None
482
+ return out
483
+
484
+ def decode(self, data: JsonValue) -> tuple[Any, ...]:
485
+ if not isinstance(data, list) or len(data) != len(self.items):
486
+ raise DecodeError(f"expected an array of {len(self.items)}, found {_kind(data)}")
487
+ out: list[Any] = []
488
+ for index, (codec, element) in enumerate(zip(self.items, data)):
489
+ try:
490
+ out.append(codec.decode(element))
491
+ except DecodeError as error:
492
+ raise error.at(f"[{index}]") from None
493
+ return tuple(out)
494
+
495
+
496
+ def _wrap(value: Any, some: bool) -> Any:
497
+ return Some(value) if some else value
498
+
499
+
500
+ def _unwrap(value: Any, some: bool) -> Any:
501
+ if not some:
502
+ return value
503
+ if not isinstance(value, Some):
504
+ raise EncodeError(f"expected Some(...) or None, found {value!r}")
505
+ return value.value
506
+
507
+
508
+ class OptionCodec(Codec[Any]):
509
+ """``Option<T>`` anywhere but a record field: ``"None"`` or ``{"Some": v}``.
510
+
511
+ With ``some`` the Python value is ``Some(v) | None``, otherwise ``v | None``.
512
+ """
513
+
514
+ def __init__(self, item: Codec[Any], *, some: bool = False) -> None:
515
+ self.item = item
516
+ self.some = some
517
+
518
+ def encode(self, value: Any) -> JsonValue:
519
+ if value is None:
520
+ return "None"
521
+ try:
522
+ return {"Some": self.item.encode(_unwrap(value, self.some))}
523
+ except EncodeError as error:
524
+ raise error.at("Some") from None
525
+
526
+ def decode(self, data: JsonValue) -> Any:
527
+ if data == "None":
528
+ return None
529
+ if isinstance(data, dict) and len(data) == 1 and "Some" in data:
530
+ obj = _object(data, "an object")
531
+ try:
532
+ return _wrap(self.item.decode(obj["Some"]), self.some)
533
+ except DecodeError as error:
534
+ raise error.at("Some") from None
535
+ raise DecodeError(f'expected "None" or {{"Some": ...}}, found {_kind(data)}')
536
+
537
+
538
+ @dataclasses.dataclass(frozen=True)
539
+ class Field:
540
+ """One field of a record or of a named constructor payload.
541
+
542
+ ``optional`` marks an ``Option`` field, whose ``codec`` is then the
543
+ codec of the type inside the ``Option``: ``None`` is left out and
544
+ ``Some(v)`` is written as ``v``; a missing or ``null`` field decodes
545
+ as ``None``. ``some`` says the Python value is wrapped in ``Some``.
546
+ """
547
+
548
+ wire: str
549
+ attr: str
550
+ codec: Codec[Any]
551
+ optional: bool = False
552
+ some: bool = False
553
+
554
+ def encode_into(self, value: Any, out: dict[str, JsonValue]) -> None:
555
+ item = getattr(value, self.attr)
556
+ try:
557
+ if self.optional:
558
+ if item is None:
559
+ return
560
+ out[self.wire] = self.codec.encode(_unwrap(item, self.some))
561
+ else:
562
+ out[self.wire] = self.codec.encode(item)
563
+ except EncodeError as error:
564
+ raise error.at(self.wire) from None
565
+
566
+ def decode_from(self, obj: dict[str, JsonValue]) -> Any:
567
+ if self.optional:
568
+ raw = obj.get(self.wire)
569
+ if raw is None:
570
+ return None
571
+ try:
572
+ return _wrap(self.codec.decode(raw), self.some)
573
+ except DecodeError as error:
574
+ raise error.at(self.wire) from None
575
+ if self.wire not in obj:
576
+ raise DecodeError(f"the field {self.wire!r} is missing")
577
+ try:
578
+ return self.codec.decode(obj[self.wire])
579
+ except DecodeError as error:
580
+ raise error.at(self.wire) from None
581
+
582
+
583
+ def _encode_fields(fields: Sequence[Field], value: Any) -> dict[str, JsonValue]:
584
+ out: dict[str, JsonValue] = {}
585
+ for item in fields:
586
+ item.encode_into(value, out)
587
+ return out
588
+
589
+
590
+ def _decode_fields(fields: Sequence[Field], data: JsonValue) -> dict[str, Any]:
591
+ obj = _object(data, "an object")
592
+ return {item.attr: item.decode_from(obj) for item in fields}
593
+
594
+
595
+ class RecordCodec(Codec[T]):
596
+ """A record: an object keyed by field name; extra fields are ignored.
597
+
598
+ ``fields`` is called once, on first use, so records can refer to types
599
+ declared after them.
600
+ """
601
+
602
+ def __init__(self, cls: Callable[..., T], fields: Callable[[], Sequence[Field]]) -> None:
603
+ self.cls = cls
604
+ self._fields_thunk = fields
605
+ self._fields: Sequence[Field] | None = None
606
+
607
+ @property
608
+ def fields(self) -> Sequence[Field]:
609
+ if self._fields is None:
610
+ self._fields = tuple(self._fields_thunk())
611
+ return self._fields
612
+
613
+ def encode(self, value: T) -> JsonValue:
614
+ if not isinstance(value, self.cls): # type: ignore[arg-type]
615
+ raise EncodeError(
616
+ f"expected {getattr(self.cls, '__name__', 'a record')}, found {type(value).__name__}"
617
+ )
618
+ return _encode_fields(self.fields, value)
619
+
620
+ def decode(self, data: JsonValue) -> T:
621
+ return self.cls(**_decode_fields(self.fields, data))
622
+
623
+
624
+ @dataclasses.dataclass(frozen=True)
625
+ class Constructor:
626
+ """One enum constructor: its wire name, its class, and its payload.
627
+
628
+ ``positional`` lists the codecs of a positional payload, held in the
629
+ class's fields ``_0``, ``_1``, ...; ``named`` the fields of a named one.
630
+ Neither: a constructor with no payload.
631
+ """
632
+
633
+ name: str
634
+ cls: type[Any]
635
+ positional: Sequence[Codec[Any]] | None = None
636
+ named: Sequence[Field] | None = None
637
+
638
+
639
+ class EnumCodec(Codec[T]):
640
+ """An enum: ``"Name"`` for no payload, ``{"Name": v}`` for one positional
641
+ value, ``{"Name": [a, b]}`` for several, ``{"Name": {...}}`` for a named
642
+ payload. An unknown constructor name is refused."""
643
+
644
+ def __init__(self, name: str, constructors: Callable[[], Sequence[Constructor]]) -> None:
645
+ self.name = name
646
+ self._thunk = constructors
647
+ self._by_name: dict[str, Constructor] | None = None
648
+ self._by_class: dict[type[Any], Constructor] = {}
649
+
650
+ def _table(self) -> dict[str, Constructor]:
651
+ if self._by_name is None:
652
+ constructors = tuple(self._thunk())
653
+ self._by_class = {c.cls: c for c in constructors}
654
+ self._by_name = {c.name: c for c in constructors}
655
+ return self._by_name
656
+
657
+ def encode(self, value: T) -> JsonValue:
658
+ self._table()
659
+ constructor = self._by_class.get(type(value))
660
+ if constructor is None:
661
+ raise EncodeError(f"expected a constructor of {self.name}, found {type(value).__name__}")
662
+ name = constructor.name
663
+ try:
664
+ if constructor.named is not None:
665
+ return {name: _encode_fields(constructor.named, value)}
666
+ if constructor.positional is None:
667
+ return name
668
+ parts: list[JsonValue] = []
669
+ for index, codec in enumerate(constructor.positional):
670
+ try:
671
+ parts.append(codec.encode(getattr(value, f"_{index}")))
672
+ except EncodeError as error:
673
+ raise error.at(f"[{index}]") if len(constructor.positional) > 1 else error
674
+ return {name: parts[0] if len(parts) == 1 else parts}
675
+ except EncodeError as error:
676
+ raise error.at(name) from None
677
+
678
+ def decode(self, data: JsonValue) -> T:
679
+ table = self._table()
680
+ if isinstance(data, str):
681
+ constructor = table.get(data)
682
+ if constructor is None:
683
+ raise DecodeError(f"{data!r} is not a constructor of {self.name}")
684
+ if constructor.positional is not None or constructor.named is not None:
685
+ raise DecodeError(f"{data!r} carries a payload")
686
+ result: T = constructor.cls()
687
+ return result
688
+ obj = _object(data, f"a constructor of {self.name}")
689
+ if len(obj) != 1:
690
+ raise DecodeError(f"expected an object with one constructor name, found {len(obj)} keys")
691
+ ((name, payload),) = obj.items()
692
+ constructor = table.get(name)
693
+ if constructor is None:
694
+ raise DecodeError(f"{name!r} is not a constructor of {self.name}")
695
+ try:
696
+ if constructor.named is not None:
697
+ result = constructor.cls(**_decode_fields(constructor.named, payload))
698
+ return result
699
+ if constructor.positional is None:
700
+ raise DecodeError("this constructor carries no payload")
701
+ codecs = constructor.positional
702
+ if len(codecs) == 1:
703
+ result = constructor.cls(codecs[0].decode(payload))
704
+ return result
705
+ if not isinstance(payload, list) or len(payload) != len(codecs):
706
+ raise DecodeError(f"expected an array of {len(codecs)}, found {_kind(payload)}")
707
+ values = []
708
+ for index, (codec, raw) in enumerate(zip(codecs, payload)):
709
+ try:
710
+ values.append(codec.decode(raw))
711
+ except DecodeError as error:
712
+ raise error.at(f"[{index}]") from None
713
+ result = constructor.cls(*values)
714
+ return result
715
+ except DecodeError as error:
716
+ raise error.at(name) from None
717
+
718
+
719
+ H = TypeVar("H", bound=HostToken)
720
+
721
+
722
+ class HostCodec(Codec[H]):
723
+ """A ``@tool type`` value: the token string, as the implementation chose it."""
724
+
725
+ def __init__(self, cls: type[H]) -> None:
726
+ self.cls = cls
727
+
728
+ def encode(self, value: H) -> JsonValue:
729
+ if type(value) is not self.cls:
730
+ raise EncodeError(f"expected {self.cls.__name__}, found {type(value).__name__}")
731
+ return TEXT.encode(value.token)
732
+
733
+ def decode(self, data: JsonValue) -> H:
734
+ return self.cls(TEXT.decode(data))
735
+
736
+ # Type descriptions are a separate ordering owner from JSON Schema.
737
+ def _shape(value: Any, keys: set[str]) -> dict[str, Any]:
738
+ obj = _object(value, "type description object")
739
+ if set(obj) != keys:
740
+ raise DecodeError(f"type description requires exactly {sorted(keys)}")
741
+ return cast(dict[str, Any], obj)
742
+
743
+
744
+ def _names(values: Any) -> list[str]:
745
+ if not isinstance(values, list) or any(not isinstance(v, str) for v in values) or len(set(values)) != len(values):
746
+ raise DecodeError("expected unique names")
747
+ return values
748
+
749
+
750
+ def _parts(template: Any) -> list[Any]:
751
+ if template["kind"] == "record":
752
+ return [f["type"] for f in template["fields"]]
753
+ if template["kind"] == "enum":
754
+ return [t for c in template["constructors"] if c["payload"] is not None
755
+ for t in (c["payload"].get("positional", []) if "positional" in c["payload"] else [f["type"] for f in c["payload"]["named"]])]
756
+ return []
757
+
758
+
759
+ def _subst(term: Any, args: Sequence[Any]) -> Any:
760
+ if isinstance(term, str):
761
+ return term
762
+ tag, value = next(iter(term.items()))
763
+ if tag == "Param":
764
+ return args[value["index"]]
765
+ if tag == "Named":
766
+ return {tag: {"declaration": value["declaration"], "args": [_subst(t, args) for t in value["args"]]}}
767
+ if tag == "Function":
768
+ return {tag: {"params": [_subst(t, args) for t in value["params"]], "result": _subst(value["result"], args)}}
769
+ return {tag: [_subst(t, args) for t in value] if isinstance(value, list) else _subst(value, args)}
770
+
771
+
772
+ _PRIMITIVES: dict[str, Codec[Any]] = {"Int": INT, "Decimal": DECIMAL, "Bool": BOOL, "Text": TEXT,
773
+ "Bytes": BYTES, "Duration": DURATION, "Instant": INSTANT, "Unit": UNIT, "Never": NEVER, "json.Value": JSON}
774
+
775
+
776
+ class TypeSpec:
777
+ """A validated served signature and its finite declaration templates."""
778
+
779
+ def __init__(self, value: JsonValue) -> None:
780
+ from ._json import read_json
781
+ self._wire = write_json(value)
782
+ self._spec: Any = read_json(self._wire)
783
+ spec = _shape(self._spec, {"generic", "params", "ok", "err", "declarations"})
784
+ _names(spec["generic"])
785
+ self._validate_graph(spec, True)
786
+
787
+ @staticmethod
788
+ def _validate_graph(view: Any, static: bool) -> None:
789
+ declarations: dict[str, Any] = cast(dict[str, Any], _object(view["declarations"], "declarations"))
790
+ def fields(values: Any) -> None:
791
+ if not isinstance(values, list):
792
+ raise DecodeError("fields must be an array")
793
+ names = []
794
+ for field in values:
795
+ _shape(field, {"name", "type", "doc"})
796
+ if field["doc"] is not None and not isinstance(field["doc"], str):
797
+ raise DecodeError("invalid field doc")
798
+ names.append(field["name"])
799
+ _names(names)
800
+ for key, decl in declarations.items():
801
+ common = {"name", "identity", "lexical_ordinal", "generic", "opaque", "kind", "doc"}
802
+ kind = decl.get("kind") if isinstance(decl, dict) else None
803
+ _shape(decl, common | ({"fields"} if kind == "record" else {"constructors"} if kind == "enum" else set()))
804
+ if kind not in ("record", "enum", "host", "nondata") or not isinstance(decl["name"], str) or not isinstance(decl["identity"], str):
805
+ raise DecodeError("invalid declaration")
806
+ if type(decl["lexical_ordinal"]) is not int or decl["lexical_ordinal"] < 1 or type(decl["opaque"]) is not bool:
807
+ raise DecodeError("invalid declaration ordinal/opaque")
808
+ if decl["doc"] is not None and not isinstance(decl["doc"], str):
809
+ raise DecodeError("invalid declaration doc")
810
+ _names(decl["generic"])
811
+ if kind == "record":
812
+ fields(decl["fields"])
813
+ if kind == "enum":
814
+ names = []
815
+ if not isinstance(decl["constructors"], list):
816
+ raise DecodeError("constructors must be an array")
817
+ for ctor in decl["constructors"]:
818
+ _shape(ctor, {"name", "doc", "payload"})
819
+ names.append(ctor["name"])
820
+ if ctor["doc"] is not None and not isinstance(ctor["doc"], str):
821
+ raise DecodeError("invalid constructor doc")
822
+ payload = ctor["payload"]
823
+ if payload is not None:
824
+ if not isinstance(payload, dict) or set(payload) not in ({"named"}, {"positional"}):
825
+ raise DecodeError("invalid payload")
826
+ if "named" in payload:
827
+ fields(payload["named"])
828
+ elif not isinstance(payload["positional"], list):
829
+ raise DecodeError("invalid positional payload")
830
+ _names(names)
831
+ nominal = [(d["identity"], d["lexical_ordinal"]) for d in declarations.values()]
832
+ if len(nominal) != len(set(nominal)):
833
+ raise DecodeError("conflicting declaration identity/ordinal")
834
+ reached: set[str] = set()
835
+ edges: dict[str, list[tuple[str, Any]]] = {k: [] for k in declarations}
836
+ def term(t: Any, owner: str | None, root: bool = False) -> None:
837
+ if isinstance(t, str):
838
+ if t not in _PRIMITIVES:
839
+ raise DecodeError("unknown primitive")
840
+ return
841
+ if not isinstance(t, dict) or len(t) != 1 or isinstance(t, DuplicateKeysObject):
842
+ raise DecodeError("invalid term")
843
+ tag, v = next(iter(t.items()))
844
+ if tag == "Param":
845
+ _shape(v, {"owner", "index"})
846
+ arity = len(view["generic"]) if root else len(declarations[owner]["generic"]) if owner in declarations else 0
847
+ if v["owner"] != owner or type(v["index"]) is not int or not 0 <= v["index"] < arity:
848
+ raise DecodeError("invalid Param owner/index")
849
+ elif tag == "Named":
850
+ _shape(v, {"declaration", "args"})
851
+ key = v["declaration"]
852
+ if not isinstance(key, str) or key not in declarations or not isinstance(v["args"], list) or len(v["args"]) != len(declarations[key]["generic"]):
853
+ raise DecodeError("unresolved Named or wrong arity")
854
+ if not root and owner in edges:
855
+ edges[owner].append((key, v["args"]))
856
+ for a in v["args"]:
857
+ term(a, owner, root)
858
+ if key not in reached:
859
+ reached.add(key)
860
+ for a in _parts(declarations[key]):
861
+ term(a, key)
862
+ elif tag == "Function":
863
+ _shape(v, {"params", "result"})
864
+ if not isinstance(v["params"], list):
865
+ raise DecodeError("invalid Function")
866
+ for a in v["params"] + [v["result"]]:
867
+ term(a, owner, root)
868
+ elif tag in ("List", "Set", "Option", "Task"):
869
+ term(v, owner, root)
870
+ elif tag in ("Dict", "Tuple"):
871
+ if not isinstance(v, list) or (len(v) != 2 if tag == "Dict" else len(v) < 2):
872
+ raise DecodeError("invalid compound arity")
873
+ for a in v:
874
+ term(a, owner, root)
875
+ else:
876
+ raise DecodeError("unknown term tag")
877
+ for name in ("params",) if static else ("bindings", "params"):
878
+ if not isinstance(view[name], list):
879
+ raise DecodeError("root names must be array")
880
+ names = []
881
+ for root in view[name]:
882
+ _shape(root, {"name", "type"})
883
+ names.append(root["name"])
884
+ term(root["type"], "tool" if static else None, static)
885
+ _names(names)
886
+ term(view["ok"], "tool" if static else None, static)
887
+ term(view["err"], "tool" if static else None, static)
888
+ if reached != set(declarations):
889
+ raise DecodeError("disconnected declarations")
890
+ # Root-relative permutations establish the recursive substitution law.
891
+ def reachable(start: str, target: str) -> bool:
892
+ seen = set()
893
+ pending = [start]
894
+ while pending:
895
+ node = pending.pop()
896
+ if node == target:
897
+ return True
898
+ if node not in seen:
899
+ seen.add(node)
900
+ pending.extend(k for k, _ in edges[node])
901
+ return False
902
+ visited: set[str] = set()
903
+ for root in declarations:
904
+ if root in visited:
905
+ continue
906
+ component = {k for k in declarations if reachable(root, k) and reachable(k, root)}
907
+ visited.update(component)
908
+ assignments = {root: tuple(range(len(declarations[root]["generic"])))}
909
+ pending = [root]
910
+ while pending:
911
+ node = pending.pop()
912
+ for child, args in edges[node]:
913
+ if child not in component:
914
+ continue
915
+ n = len(assignments[node])
916
+ if len(args) != n or any(not isinstance(a, dict) or set(a) != {"Param"} for a in args):
917
+ raise DecodeError("changing recursive arguments")
918
+ indices = [a["Param"]["index"] for a in args]
919
+ if set(indices) != set(range(n)):
920
+ raise DecodeError("non-bijective recursive arguments")
921
+ permutation = tuple(assignments[node][i] for i in indices)
922
+ if child in assignments and assignments[child] != permutation:
923
+ raise DecodeError("inconsistent recursive permutation")
924
+ if child not in assignments:
925
+ assignments[child] = permutation
926
+ pending.append(child)
927
+
928
+ def validate(self, schema: JsonValue | None, types: JsonValue | None, *, schema_present: bool, types_present: bool) -> TypeView:
929
+ from ._json import read_json
930
+ spec = self._spec
931
+ if not spec["generic"]:
932
+ if schema_present or types_present:
933
+ raise DecodeError("nongeneric call carries generic metadata")
934
+ return TypeView(spec, None, False)
935
+ if not schema_present or not types_present or schema is None or types is None:
936
+ raise DecodeError("generic call requires schema and types")
937
+ view: Any = read_json(write_json(types))
938
+ _shape(view, {"bindings", "params", "ok", "err", "declarations"})
939
+ self._validate_graph(view, False)
940
+ if [b["name"] for b in view["bindings"]] != spec["generic"]:
941
+ raise DecodeError("binding order differs")
942
+ bindings = [b["type"] for b in view["bindings"]]
943
+ actual = view["declarations"]
944
+ mapping: dict[str, str] = {}
945
+ for key, decl in spec["declarations"].items():
946
+ candidates = [k for k, d in actual.items() if d["identity"] == decl["identity"] and d["lexical_ordinal"] == decl["lexical_ordinal"]]
947
+ if len(candidates) != 1:
948
+ raise DecodeError("known declaration missing/conflicting")
949
+ mapping[key] = candidates[0]
950
+ def remap(t: Any) -> Any:
951
+ if isinstance(t, str):
952
+ return t
953
+ tag, v = next(iter(t.items()))
954
+ if tag == "Param":
955
+ return {tag: dict(v, owner=mapping.get(v["owner"], v["owner"]))}
956
+ if tag == "Named":
957
+ return {tag: {"declaration": mapping[v["declaration"]], "args": [remap(a) for a in v["args"]]}}
958
+ if tag == "Function":
959
+ return {tag: {"params": [remap(a) for a in v["params"]], "result": remap(v["result"])}}
960
+ return {tag: [remap(a) for a in v] if isinstance(v, list) else remap(v)}
961
+ def semantics(d: Any, rewrite: bool) -> Any:
962
+ result = {k: v for k, v in d.items() if k != "doc"}
963
+ result["generic"] = len(d["generic"])
964
+ if d["kind"] == "record":
965
+ result["fields"] = [{"name": f["name"], "type": remap(f["type"]) if rewrite else f["type"]} for f in d["fields"]]
966
+ if d["kind"] == "enum":
967
+ result["constructors"] = []
968
+ for c in d["constructors"]:
969
+ p = c["payload"]
970
+ if p is not None:
971
+ p = {"positional": [remap(t) if rewrite else t for t in p["positional"]]} if "positional" in p else {"named": [{"name": f["name"], "type": remap(f["type"]) if rewrite else f["type"]} for f in p["named"]]}
972
+ result["constructors"].append({"name": c["name"], "payload": p})
973
+ return result
974
+ for key, target in mapping.items():
975
+ if semantics(spec["declarations"][key], True) != semantics(actual[target], False):
976
+ raise DecodeError("known declaration template differs")
977
+ def instantiate(t: Any) -> Any:
978
+ # Caller bindings are already in caller-local ids; substitute after remapping.
979
+ return _subst(remap(t), bindings)
980
+ expected = [{"name": p["name"], "type": instantiate(p["type"])} for p in spec["params"]]
981
+ if view["params"] != expected or view["ok"] != instantiate(spec["ok"]) or view["err"] != instantiate(spec["err"]):
982
+ raise DecodeError("concrete signature differs")
983
+ result = TypeView(view, schema, True)
984
+ result._served_declarations = spec["declarations"]
985
+ for binding in bindings:
986
+ result._check_data(binding, noopaque=True, crossing=False)
987
+ if write_json(result._schema(view["ok"])) != write_json(schema):
988
+ raise DecodeError("success schema differs")
989
+ return result
990
+
991
+
992
+ class TypeView:
993
+ """One call's immutable, fully validated metadata and compiled roots."""
994
+
995
+ def __init__(self, value: Any, schema: JsonValue | None, generic: bool) -> None:
996
+ from ._json import read_json
997
+ self._value: Any = read_json(write_json(value))
998
+ self._schema_wire = None if schema is None else write_json(schema)
999
+ self._generic = generic
1000
+ self._cache: dict[str, ContextCodec] = {}
1001
+ self._served_declarations: Any = cast(Any, self._value)["declarations"]
1002
+ for root in [p["type"] for p in value["params"]]:
1003
+ self._check_data(root, noopaque=False, crossing=True)
1004
+ for root in [value["ok"], value["err"]]:
1005
+ self._check_data(root, noopaque=True, crossing=True)
1006
+
1007
+ @property
1008
+ def generic(self) -> bool:
1009
+ return self._generic
1010
+
1011
+ @property
1012
+ def schema(self) -> JsonValue | None:
1013
+ from ._json import read_json
1014
+ return None if self._schema_wire is None else read_json(self._schema_wire)
1015
+
1016
+ def _check_data(self, root: Any, noopaque: bool = False, crossing: bool = True) -> None:
1017
+ seen = set()
1018
+ pending = [root]
1019
+ while pending:
1020
+ t = pending.pop()
1021
+ if isinstance(t, str):
1022
+ continue
1023
+ tag, v = next(iter(t.items()))
1024
+ if tag in ("Function", "Task"):
1025
+ raise DecodeError("nondata value position")
1026
+ if tag == "Named":
1027
+ key = write_json(t)
1028
+ if key in seen:
1029
+ continue
1030
+ seen.add(key)
1031
+ d = self._value["declarations"][v["declaration"]]
1032
+ if d["kind"] == "nondata" or (noopaque and d["opaque"]) or (not crossing and d["kind"] == "host"):
1033
+ raise DecodeError("nondata/opaque binding")
1034
+ pending.extend(_subst(a, v["args"]) for a in _parts(d))
1035
+ elif tag == "Param":
1036
+ if not self.generic:
1037
+ continue
1038
+ raise DecodeError("free Param")
1039
+ else:
1040
+ if crossing and tag == "Option" and v == "json.Value":
1041
+ raise DecodeError("Option<json.Value> has no boundary encoding")
1042
+ pending.extend(v if isinstance(v, list) else [v])
1043
+
1044
+ def _codec(self, t: Any) -> ContextCodec:
1045
+ key = write_json(t)
1046
+ if key not in self._cache:
1047
+ self._cache[key] = ContextCodec(self, t)
1048
+ return self._cache[key]
1049
+
1050
+ def codec(self, binding: str) -> ContextCodec:
1051
+ for b in self._value.get("bindings", []):
1052
+ if b["name"] == binding:
1053
+ self._check_data(b["type"])
1054
+ return self._codec(b["type"])
1055
+ raise DecodeError(f"unknown binding {binding!r}")
1056
+
1057
+ def argument_codec(self, name: str) -> ContextCodec:
1058
+ for p in self._value["params"]:
1059
+ if p["name"] == name:
1060
+ return self._codec(p["type"])
1061
+ raise DecodeError(f"unknown argument {name!r}")
1062
+
1063
+ def _schema(self, root: Any) -> JsonValue:
1064
+ defs: dict[str, Any] = {}
1065
+ keys: dict[str, str] = {}
1066
+ pending: list[tuple[str, Any, Any]] = []
1067
+ def array(parts: list[Any]) -> Any:
1068
+ return {"type": "array", "prefixItems": parts, "items": False, "minItems": len(parts)}
1069
+ def single(name: str, item: Any) -> Any:
1070
+ return {"type": "object", "properties": {name: item}, "required": [name], "additionalProperties": False}
1071
+ def described(item: Any, doc: Any) -> Any:
1072
+ if doc is None:
1073
+ return item
1074
+ return dict(item, description=doc) if isinstance(item, dict) else {"allOf": [item], "description": doc}
1075
+ def written(t: Any) -> str:
1076
+ if isinstance(t, str):
1077
+ return str(t)
1078
+ tag, v = next(iter(t.items()))
1079
+ if tag == "Named":
1080
+ name = self._value["declarations"][v["declaration"]]["identity"]
1081
+ return str(name) + ("<" + ", ".join(written(a) for a in v["args"]) + ">" if v["args"] else "")
1082
+ if tag == "Tuple":
1083
+ return "(" + ", ".join(written(a) for a in v) + ")"
1084
+ if tag == "Function":
1085
+ return "(" + ", ".join(written(a) for a in v["params"]) + ") -> " + written(v["result"])
1086
+ return ("task.Task" if tag == "Task" else str(tag)) + "<" + ", ".join(written(a) for a in (v if isinstance(v, list) else [v])) + ">"
1087
+ def fields(items: Any, args: Any) -> Any:
1088
+ props = {}
1089
+ required = []
1090
+ for f in items:
1091
+ t = _subst(f["type"], args)
1092
+ if isinstance(t, dict) and "Option" in t:
1093
+ t = t["Option"]
1094
+ else:
1095
+ required.append(f["name"])
1096
+ props[f["name"]] = described(schema(t), f["doc"])
1097
+ return {"type": "object", "properties": props, "required": required}
1098
+ def schema(t: Any) -> Any:
1099
+ if isinstance(t, str):
1100
+ primitive: dict[str, Any] = {"Int": {"type": "integer"}, "Decimal": {"type": "number"}, "Bool": {"type": "boolean"}, "Text": {"type": "string"}, "Bytes": {"type": "string", "contentEncoding": "base64"}, "Duration": {"type": "string", "format": "duration"}, "Instant": {"type": "string", "format": "date-time"}, "Unit": array([]), "Never": False, "json.Value": {}}
1101
+ return primitive[t]
1102
+ tag, v = next(iter(t.items()))
1103
+ if tag == "Named":
1104
+ token = write_json(t)
1105
+ if token not in keys:
1106
+ base = written(t)
1107
+ name = base
1108
+ count = 2
1109
+ while name in defs:
1110
+ name = f"{base}#{count}"
1111
+ count += 1
1112
+ keys[token] = name
1113
+ defs[name] = None
1114
+ pending.append((name, self._value["declarations"][v["declaration"]], v["args"]))
1115
+ from urllib.parse import quote
1116
+ return {"$ref": "#/$defs/" + quote(keys[token].replace("~", "~0").replace("/", "~1"), safe="-._~!$&'()*+,;=:@/")}
1117
+ if tag in ("List", "Set"):
1118
+ return dict({"type": "array", "items": schema(v)}, **({"uniqueItems": True} if tag == "Set" else {}))
1119
+ if tag == "Dict":
1120
+ return {"type": "object", "additionalProperties": schema(v[1])} if v[0] == "Text" else {"type": "array", "items": array([schema(a) for a in v])}
1121
+ if tag == "Tuple":
1122
+ return array([schema(a) for a in v])
1123
+ if tag == "Option":
1124
+ return {"oneOf": [{"const": "None"}, single("Some", schema(v))]}
1125
+ raise DecodeError("type has no schema")
1126
+ result = schema(root)
1127
+ for name, d, args in pending:
1128
+ if d["kind"] == "record":
1129
+ body = fields(d["fields"], args)
1130
+ elif d["kind"] == "host":
1131
+ body = {"type": "string"}
1132
+ elif d["kind"] == "enum":
1133
+ branches = []
1134
+ for c in d["constructors"]:
1135
+ p = c["payload"]
1136
+ if p is None:
1137
+ branch = {"const": c["name"]}
1138
+ else:
1139
+ item = fields(p["named"], args) if "named" in p else schema(_subst(p["positional"][0], args)) if len(p["positional"]) == 1 else array([schema(_subst(a, args)) for a in p["positional"]])
1140
+ branch = single(c["name"], item)
1141
+ branches.append(described(branch, c["doc"]))
1142
+ body = {"oneOf": branches}
1143
+ else:
1144
+ raise DecodeError("type has no schema")
1145
+ defs[name] = described(body, d["doc"])
1146
+ result = dict(result) if isinstance(result, dict) else {"allOf": [result]}
1147
+ result["$schema"] = "https://json-schema.org/draft/2020-12/schema"
1148
+ if defs:
1149
+ result["$defs"] = defs
1150
+ return result
1151
+
1152
+
1153
+ class ContextCodec(Codec[JsonValue]):
1154
+ """Raw JSON conversion and comparison directed by one concrete Flow type."""
1155
+
1156
+ def __init__(self, view: TypeView, term: Any) -> None:
1157
+ self._view, self._term = view, term
1158
+
1159
+ @property
1160
+ def is_text(self) -> bool:
1161
+ return bool(self._term == "Text")
1162
+
1163
+ def _child(self, term: Any) -> ContextCodec:
1164
+ return self._view._codec(term)
1165
+
1166
+ def element(self, index: int | None = None) -> ContextCodec:
1167
+ t = self._term
1168
+ if isinstance(t, dict) and next(iter(t)) in ("List", "Set", "Option") and index is None:
1169
+ return self._child(next(iter(t.values())))
1170
+ if isinstance(t, dict) and "Tuple" in t and type(index) is int and 0 <= index < len(t["Tuple"]):
1171
+ return self._child(t["Tuple"][index])
1172
+ raise DecodeError("not an element view")
1173
+
1174
+ def key(self) -> ContextCodec:
1175
+ if isinstance(self._term, dict) and "Dict" in self._term:
1176
+ return self._child(self._term["Dict"][0])
1177
+ raise DecodeError("not a Dict view")
1178
+
1179
+ def value(self) -> ContextCodec:
1180
+ if isinstance(self._term, dict) and "Dict" in self._term:
1181
+ return self._child(self._term["Dict"][1])
1182
+ raise DecodeError("not a Dict view")
1183
+
1184
+ def _declaration(self) -> tuple[Any, Any]:
1185
+ if not isinstance(self._term, dict) or "Named" not in self._term:
1186
+ raise DecodeError("not a named view")
1187
+ v = self._term["Named"]
1188
+ return self._view._value["declarations"][v["declaration"]], v["args"]
1189
+
1190
+ def field(self, name: str) -> ContextCodec:
1191
+ d, args = self._declaration()
1192
+ if d["kind"] == "record":
1193
+ for f in d["fields"]:
1194
+ if f["name"] == name:
1195
+ return self._child(_subst(f["type"], args))
1196
+ raise DecodeError("unknown record field")
1197
+
1198
+ def variant(self, name: str) -> PayloadView:
1199
+ d, args = self._declaration()
1200
+ if d["kind"] == "enum":
1201
+ for c in d["constructors"]:
1202
+ if c["name"] == name:
1203
+ return PayloadView(self, c["payload"], args)
1204
+ raise DecodeError("unknown constructor")
1205
+
1206
+ def decode_field(self, parent: JsonValue, name: str) -> JsonValue:
1207
+ return self.field(name)._decode_presence(parent, name)
1208
+
1209
+ def encode_field(self, value: JsonValue, name: str) -> tuple[bool, JsonValue]:
1210
+ return self.field(name)._encode_presence(value)
1211
+
1212
+ def _decode_presence(self, parent: JsonValue, name: str) -> JsonValue:
1213
+ obj = _object(parent, "record")
1214
+ if isinstance(self._term, dict) and "Option" in self._term:
1215
+ return "None" if obj.get(name) is None else {"Some": self.element().decode(obj[name])}
1216
+ if name not in obj:
1217
+ raise DecodeError(f"missing field {name!r}")
1218
+ return self.decode(obj[name])
1219
+
1220
+ def _encode_presence(self, value: JsonValue) -> tuple[bool, JsonValue]:
1221
+ value = self.encode(value)
1222
+ if isinstance(self._term, dict) and "Option" in self._term:
1223
+ return (False, None) if value == "None" else (True, cast(dict[str, JsonValue], value)["Some"])
1224
+ return True, value
1225
+
1226
+ def encode(self, value: JsonValue) -> JsonValue:
1227
+ try:
1228
+ return self.decode(value)
1229
+ except DecodeError as e:
1230
+ raise EncodeError(e.reason, e.path) from None
1231
+
1232
+ def decode(self, data: JsonValue) -> JsonValue:
1233
+ t = self._term
1234
+ if isinstance(t, str):
1235
+ return _PRIMITIVES[t].encode(_PRIMITIVES[t].decode(data))
1236
+ tag, v = next(iter(t.items()))
1237
+ if tag == "Option":
1238
+ if data == "None":
1239
+ return "None"
1240
+ obj = _shape(data, {"Some"})
1241
+ return {"Some": self.element().decode(obj["Some"])}
1242
+ if tag in ("List", "Set", "Tuple"):
1243
+ if not isinstance(data, list):
1244
+ raise DecodeError("expected array")
1245
+ if tag == "Tuple" and len(data) != len(v):
1246
+ raise DecodeError("tuple length differs")
1247
+ values = [self.element(i if tag == "Tuple" else None).decode(a) for i, a in enumerate(data)]
1248
+ if tag == "Set":
1249
+ from functools import cmp_to_key
1250
+ child = self.element()
1251
+ values.sort(key=cmp_to_key(child.compare))
1252
+ values = [a for i, a in enumerate(values) if i == 0 or child.compare(values[i-1], a)]
1253
+ return values
1254
+ if tag == "Dict":
1255
+ from functools import cmp_to_key
1256
+ if v[0] == "Text":
1257
+ obj = _object(data, "Text Dict")
1258
+ return {k: self.value().decode(obj[k]) for k in sorted(obj)}
1259
+ if not isinstance(data, list) or any(not isinstance(p, list) or len(p) != 2 for p in data):
1260
+ raise DecodeError("expected key/value pairs")
1261
+ pairs: Any = [[self.key().decode(p[0]), self.value().decode(p[1])] for p in cast(list[list[JsonValue]], data)]
1262
+ def compare_pair(a: Any, b: Any) -> int:
1263
+ return self.key().compare(a[0], b[0])
1264
+ pairs.sort(key=cmp_to_key(compare_pair))
1265
+ if any(self.key().compare(a[0], b[0]) == 0 for a, b in zip(pairs, pairs[1:])):
1266
+ raise DecodeError("duplicate Dict key")
1267
+ return cast(JsonValue, pairs)
1268
+ if tag != "Named":
1269
+ raise DecodeError("type has no encoding")
1270
+ d, args = self._declaration()
1271
+ if d["kind"] == "host":
1272
+ return TEXT.decode(data)
1273
+ if d["kind"] == "record":
1274
+ _object(data, "record")
1275
+ out = {}
1276
+ for f in d["fields"]:
1277
+ child = self.field(f["name"])
1278
+ present, item = child._encode_presence(child._decode_presence(data, f["name"]))
1279
+ if present:
1280
+ out[f["name"]] = item
1281
+ return out
1282
+ if d["kind"] == "enum":
1283
+ if isinstance(data, str):
1284
+ p = self.variant(data)
1285
+ if p.kind != "none":
1286
+ raise DecodeError("constructor requires payload")
1287
+ return data
1288
+ obj = _object(data, "enum")
1289
+ if len(obj) != 1:
1290
+ raise DecodeError("enum requires one constructor")
1291
+ name, raw = next(iter(obj.items()))
1292
+ p = self.variant(name)
1293
+ return {name: p.decode(raw)}
1294
+ raise DecodeError("type has no encoding")
1295
+
1296
+ def compare(self, left: JsonValue, right: JsonValue) -> int:
1297
+ a: Any = self.decode(left)
1298
+ b: Any = self.decode(right)
1299
+ def cmp(x: Any, y: Any) -> int:
1300
+ return int(x > y) - int(x < y)
1301
+ t = self._term
1302
+ if isinstance(t, str):
1303
+ return cmp(order_key(_PRIMITIVES[t].decode(a)), order_key(_PRIMITIVES[t].decode(b)))
1304
+ tag, v = next(iter(t.items()))
1305
+ if tag == "Option":
1306
+ if a == "None" or b == "None":
1307
+ return cmp(a != "None", b != "None")
1308
+ return self.element().compare(a["Some"], b["Some"])
1309
+ if tag in ("List", "Set", "Tuple", "Dict"):
1310
+ if tag == "Dict":
1311
+ aa = list(a.items()) if isinstance(a, dict) else a
1312
+ bb = list(b.items()) if isinstance(b, dict) else b
1313
+ for x, y in zip(aa, bb):
1314
+ order = self.key().compare(x[0], y[0]) or self.value().compare(x[1], y[1])
1315
+ if order:
1316
+ return order
1317
+ else:
1318
+ for i, (x, y) in enumerate(zip(cast(Any, a), cast(Any, b))):
1319
+ order = self.element(i if tag == "Tuple" else None).compare(x, y)
1320
+ if order:
1321
+ return order
1322
+ return cmp(len(a), len(b))
1323
+ d, args = self._declaration()
1324
+ if d["kind"] == "host":
1325
+ return cmp(a, b)
1326
+ if d["kind"] == "record":
1327
+ for f in d["fields"]:
1328
+ order = self.field(f["name"]).compare(self.decode_field(a, f["name"]), self.decode_field(b, f["name"]))
1329
+ if order:
1330
+ return order
1331
+ return 0
1332
+ an = a if isinstance(a, str) else next(iter(a))
1333
+ bn = b if isinstance(b, str) else next(iter(b))
1334
+ names = [c["name"] for c in d["constructors"]]
1335
+ if an != bn:
1336
+ return cmp(names.index(an), names.index(bn))
1337
+ return 0 if isinstance(a, str) else self.variant(an).compare(a[an], b[bn])
1338
+
1339
+
1340
+ class PayloadView:
1341
+ def __init__(self, parent: ContextCodec, payload: Any, args: Any) -> None:
1342
+ self._parent, self._payload, self._args = parent, payload, args
1343
+ self._kind = "none" if payload is None else "named" if "named" in payload else "positional"
1344
+
1345
+ @property
1346
+ def kind(self) -> str:
1347
+ return self._kind
1348
+
1349
+ def positional(self, index: int) -> ContextCodec:
1350
+ if self.kind != "positional" or type(index) is not int or not 0 <= index < len(self._payload["positional"]):
1351
+ raise DecodeError("invalid positional view")
1352
+ return self._parent._child(_subst(self._payload["positional"][index], self._args))
1353
+
1354
+ def field(self, name: str) -> ContextCodec:
1355
+ if self.kind == "named":
1356
+ for f in self._payload["named"]:
1357
+ if f["name"] == name:
1358
+ return self._parent._child(_subst(f["type"], self._args))
1359
+ raise DecodeError("unknown payload field")
1360
+
1361
+ def decode_field(self, parent: JsonValue, name: str) -> JsonValue:
1362
+ return self.field(name)._decode_presence(parent, name)
1363
+
1364
+ def encode_field(self, value: JsonValue, name: str) -> tuple[bool, JsonValue]:
1365
+ return self.field(name)._encode_presence(value)
1366
+
1367
+ def decode(self, raw: JsonValue) -> JsonValue:
1368
+ if self.kind == "none":
1369
+ raise DecodeError("constructor has no payload")
1370
+ if self.kind == "positional":
1371
+ terms = self._payload["positional"]
1372
+ if len(terms) == 1:
1373
+ return self.positional(0).decode(raw)
1374
+ if not isinstance(raw, list) or len(raw) != len(terms):
1375
+ raise DecodeError("payload length differs")
1376
+ return [self.positional(i).decode(a) for i, a in enumerate(raw)]
1377
+ _object(raw, "named payload")
1378
+ out = {}
1379
+ for f in self._payload["named"]:
1380
+ present, value = self.encode_field(self.decode_field(raw, f["name"]), f["name"])
1381
+ if present:
1382
+ out[f["name"]] = value
1383
+ return out
1384
+
1385
+ def compare(self, a: JsonValue, b: JsonValue) -> int:
1386
+ if self.kind == "named":
1387
+ for f in self._payload["named"]:
1388
+ order = self.field(f["name"]).compare(self.decode_field(a, f["name"]), self.decode_field(b, f["name"]))
1389
+ if order:
1390
+ return order
1391
+ return 0
1392
+ if len(self._payload["positional"]) == 1:
1393
+ return self.positional(0).compare(a, b)
1394
+ for i, (x, y) in enumerate(zip(cast(Any, a), cast(Any, b))):
1395
+ order = self.positional(i).compare(x, y)
1396
+ if order:
1397
+ return order
1398
+ return 0
1399
+
1400
+
1401
+ def contextual_codec(context: Any, term: JsonValue, projections: list[tuple[JsonValue, object]]) -> Codec[Any]:
1402
+ """Compose native generated projections over a validated concrete root."""
1403
+ from ._collections import ContextDict, ContextSet
1404
+ view: TypeView = context._view
1405
+ bindings = [b["type"] for b in view._value.get("bindings", [])]
1406
+ def concrete(t: Any) -> Any:
1407
+ if isinstance(t, str):
1408
+ return t
1409
+ tag, v = next(iter(t.items()))
1410
+ if tag == "Param":
1411
+ return bindings[v if isinstance(v, int) else v["index"]] if isinstance(v, dict) else bindings[view._value["bindings"].index(next(b for b in view._value["bindings"] if b["name"] == v))]
1412
+ if tag == "Named":
1413
+ d = context._view._value["declarations"]
1414
+ spec = context._view._served_declarations if hasattr(context._view, "_served_declarations") else d
1415
+ source = spec.get(v["declaration"])
1416
+ key = v["declaration"]
1417
+ if source is not None:
1418
+ key = next(k for k, x in d.items() if x["identity"] == source["identity"] and x["lexical_ordinal"] == source["lexical_ordinal"])
1419
+ return {tag: {"declaration": key, "args": [concrete(a) for a in v["args"]]}}
1420
+ return {tag: [concrete(a) for a in v] if isinstance(v, list) else concrete(v)}
1421
+ plans: dict[str, Codec[Any]] = {}
1422
+ def build(t: Any) -> Codec[Any]:
1423
+ if isinstance(t, str):
1424
+ return _PRIMITIVES[t]
1425
+ # Keep native terms distinct: a Param is raw even when its concrete
1426
+ # binding is a known type with a native projection.
1427
+ key = write_json(t)
1428
+ if key not in plans:
1429
+ plans[key] = compile_native(t)
1430
+ return plans[key]
1431
+ def compile_native(t: Any) -> Codec[Any]:
1432
+ tag, v = next(iter(t.items()))
1433
+ raw = view._codec(concrete(t))
1434
+ if tag == "Param":
1435
+ return raw
1436
+ if tag == "List":
1437
+ return ListCodec(build(v))
1438
+ if tag == "Tuple":
1439
+ return TupleCodec(tuple(build(a) for a in v))
1440
+ if tag == "Option":
1441
+ return OptionCodec(build(v), some=v == "json.Value" or isinstance(v, dict) and next(iter(v)) in ("Option", "Param"))
1442
+ projection = next((p for key, p in projections if concrete(key) == concrete(t)), None)
1443
+ if isinstance(projection, Codec):
1444
+ return projection
1445
+ class Native(Codec[Any]):
1446
+ def decode(self, data: Any) -> Any:
1447
+ normalized: Any = raw.decode(data)
1448
+ data = normalized
1449
+ if tag == "Set":
1450
+ return ContextSet(build(v), [build(v).decode(a) for a in data])
1451
+ if tag == "Dict":
1452
+ pairs = data.items() if isinstance(data, dict) else data
1453
+ return ContextDict(build(v[0]), build(v[1]), [(build(v[0]).decode(a), build(v[1]).decode(b)) for a, b in pairs])
1454
+ if isinstance(projection, tuple):
1455
+ cls, attrs = projection[:2]
1456
+ return cls(**{attr: field_decode(data, wire, raw.field(wire), child(wire)) for wire, attr in attrs})
1457
+ if isinstance(projection, list):
1458
+ name = data if isinstance(data, str) else next(iter(data))
1459
+ selected = next(p for p in projection if p[0] == name)
1460
+ _, cls, attrs = selected[:3]
1461
+ if attrs is None:
1462
+ return cls()
1463
+ payload = raw.variant(name)
1464
+ item = data[name]
1465
+ if payload.kind == "named":
1466
+ return cls(**{attr: field_decode(item, wire, payload.field(wire), child(wire, name)) for wire, attr in attrs})
1467
+ values = [item] if len(attrs) == 1 else item
1468
+ return cls(**{attr: child(wire, name).decode(values[i]) for i, (wire, attr) in enumerate(attrs)})
1469
+ if isinstance(projection, type) and issubclass(projection, HostToken):
1470
+ return projection(data)
1471
+ return data
1472
+
1473
+ def encode(self, value: Any) -> JsonValue:
1474
+ if tag in ("Set", "Dict"):
1475
+ if hasattr(value, "canonical_json"):
1476
+ return raw.encode(value.canonical_json())
1477
+ if tag == "Set":
1478
+ return raw.encode([build(v).encode(item) for item in value])
1479
+ pairs = [(build(v[0]).encode(key), build(v[1]).encode(item)) for key, item in value.items()]
1480
+ return raw.encode(dict(cast(Any, pairs)) if v[0] == "Text" else [list(pair) for pair in pairs])
1481
+ if isinstance(projection, tuple):
1482
+ cls, attrs = projection[:2]
1483
+ if type(value) is not cls:
1484
+ raise EncodeError("wrong generated record")
1485
+ out = {}
1486
+ for wire, attr in attrs:
1487
+ present, item = field_encode(getattr(value, attr), raw.field(wire), child(wire))
1488
+ if present:
1489
+ out[wire] = item
1490
+ return raw.encode(out)
1491
+ if isinstance(projection, list):
1492
+ for selected in projection:
1493
+ name, cls, attrs = selected[:3]
1494
+ if type(value) is cls:
1495
+ if attrs is None:
1496
+ return raw.encode(name)
1497
+ payload = raw.variant(name)
1498
+ if payload.kind == "named":
1499
+ out = {}
1500
+ for wire, attr in attrs:
1501
+ present, item = field_encode(getattr(value, attr), payload.field(wire), child(wire, name))
1502
+ if present:
1503
+ out[wire] = item
1504
+ return raw.encode({name: out})
1505
+ parts = [child(wire, name).encode(getattr(value, attr)) for wire, attr in attrs]
1506
+ return raw.encode({name: parts[0] if len(parts) == 1 else parts})
1507
+ raise EncodeError("wrong generated constructor")
1508
+ if isinstance(projection, type) and issubclass(projection, HostToken):
1509
+ if type(value) is not projection:
1510
+ raise EncodeError("wrong nominal host token")
1511
+ return raw.encode(value.token)
1512
+ return raw.encode(value)
1513
+
1514
+ def compare(self, a: Any, b: Any) -> int:
1515
+ return raw.compare(self.encode(a), self.encode(b))
1516
+ def child(name: str, constructor: str | None = None) -> Codec[Any]:
1517
+ overrides: Any = None
1518
+ if isinstance(projection, tuple) and len(projection) == 3:
1519
+ overrides = projection[2]
1520
+ elif isinstance(projection, list) and constructor is not None:
1521
+ selected = next(p for p in projection if p[0] == constructor)
1522
+ if len(selected) == 4:
1523
+ overrides = selected[3]
1524
+ if overrides is not None and name in overrides:
1525
+ return cast(Codec[Any], overrides[name](context))
1526
+ d = view._value["declarations"][concrete(t)["Named"]["declaration"]]
1527
+ args = v["args"]
1528
+ if constructor is None:
1529
+ fields = d["fields"]
1530
+ else:
1531
+ payload = next(c for c in d["constructors"] if c["name"] == constructor)["payload"]
1532
+ if "positional" in payload:
1533
+ return build(_subst(payload["positional"][int(name)], args))
1534
+ fields = payload["named"]
1535
+ return build(_subst(next(f["type"] for f in fields if f["name"] == name), args))
1536
+ def field_decode(parent: Any, name: str, wire: ContextCodec, native: Codec[Any]) -> Any:
1537
+ canonical = wire._decode_presence(parent, name)
1538
+ if isinstance(wire._term, dict) and "Option" in wire._term:
1539
+ if isinstance(native, ContextCodec):
1540
+ return canonical
1541
+ return native.decode(canonical)
1542
+ return native.decode(canonical)
1543
+ def field_encode(value: Any, wire: ContextCodec, native: Codec[Any]) -> tuple[bool, JsonValue]:
1544
+ return wire._encode_presence(native.encode(value))
1545
+ return Native()
1546
+ return build(term)