incur-cli 0.10.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.
- incur/__init__.py +62 -0
- incur/_cli.py +2139 -0
- incur/_command.py +426 -0
- incur/_completions.py +170 -0
- incur/_errors.py +234 -0
- incur/_filter.py +173 -0
- incur/_formatter.py +112 -0
- incur/_gateway.py +173 -0
- incur/_help.py +260 -0
- incur/_http.py +389 -0
- incur/_js.py +467 -0
- incur/_jsonschema.py +320 -0
- incur/_mcp.py +872 -0
- incur/_mcpsource.py +226 -0
- incur/_model.py +348 -0
- incur/_openapi.py +640 -0
- incur/_parser.py +347 -0
- incur/_pm.py +49 -0
- incur/_schema.py +555 -0
- incur/_serve_http.py +236 -0
- incur/_skill.py +355 -0
- incur/_sync.py +403 -0
- incur/_syncmcp.py +188 -0
- incur/_tokens.py +130 -0
- incur/_toon.py +202 -0
- incur/_tree.py +273 -0
- incur/_update.py +373 -0
- incur/_yaml.py +651 -0
- incur/py.typed +0 -0
- incur_cli-0.10.0.dist-info/METADATA +376 -0
- incur_cli-0.10.0.dist-info/RECORD +32 -0
- incur_cli-0.10.0.dist-info/WHEEL +4 -0
incur/_schema.py
ADDED
|
@@ -0,0 +1,555 @@
|
|
|
1
|
+
"""Schema nodes, JSON Schema output, and Zod-compatible validation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass, field, replace
|
|
8
|
+
from typing import Literal, TypeAlias
|
|
9
|
+
|
|
10
|
+
from . import _js
|
|
11
|
+
from ._js import Json
|
|
12
|
+
|
|
13
|
+
#: The shape of a schema node.
|
|
14
|
+
Kind = Literal[
|
|
15
|
+
"array",
|
|
16
|
+
"boolean",
|
|
17
|
+
"enum",
|
|
18
|
+
"integer",
|
|
19
|
+
"intersection",
|
|
20
|
+
"literal",
|
|
21
|
+
"null",
|
|
22
|
+
"number",
|
|
23
|
+
"object",
|
|
24
|
+
"record",
|
|
25
|
+
"string",
|
|
26
|
+
"union",
|
|
27
|
+
"unknown",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
#: The pattern of Zod's `z.iso.datetime()`: UTC timestamps with optional seconds and fractions.
|
|
31
|
+
ISO_DATETIME = (
|
|
32
|
+
r"^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29"
|
|
33
|
+
r"|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)"
|
|
34
|
+
r"|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z))$"
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
#: The largest integer a JavaScript number represents exactly, which bounds Zod's `z.int()`.
|
|
38
|
+
MAX_SAFE_INTEGER = 9_007_199_254_740_991
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class Field:
|
|
43
|
+
"""A named field of an object schema."""
|
|
44
|
+
|
|
45
|
+
name: str
|
|
46
|
+
ty: Type
|
|
47
|
+
alias: str | None = None
|
|
48
|
+
attr: str = ""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class Type:
|
|
53
|
+
"""A schema node: a kind with the metadata Zod attaches through `.describe()` and friends."""
|
|
54
|
+
|
|
55
|
+
kind: Kind
|
|
56
|
+
count: bool = False
|
|
57
|
+
default: Json = None
|
|
58
|
+
deprecated: bool = False
|
|
59
|
+
description: str | None = None
|
|
60
|
+
optional: bool = False
|
|
61
|
+
min: float | None = None
|
|
62
|
+
max: float | None = None
|
|
63
|
+
items: Type | None = None
|
|
64
|
+
values: list[str] = field(default_factory=list[str])
|
|
65
|
+
fields: list[Field] = field(default_factory=list[Field])
|
|
66
|
+
py: type | None = None
|
|
67
|
+
coerce: bool = False
|
|
68
|
+
"""Whether input converts with JavaScript's `Number()` or `Boolean()` first, as
|
|
69
|
+
`z.coerce` does."""
|
|
70
|
+
pattern: str | None = None
|
|
71
|
+
"""A regular expression strings must match somewhere."""
|
|
72
|
+
format: str | None = None
|
|
73
|
+
"""A string format Zod checks, such as `date-time`."""
|
|
74
|
+
loose: bool = False
|
|
75
|
+
"""Whether an object keeps unknown keys."""
|
|
76
|
+
variants: list[Type] = field(default_factory=list["Type"])
|
|
77
|
+
"""The options of a union, or the two sides of an intersection."""
|
|
78
|
+
literal: Json = None
|
|
79
|
+
"""The value a `literal` schema accepts."""
|
|
80
|
+
exclusive: bool = False
|
|
81
|
+
"""Whether exactly one option of a union must match, as `z.xor` requires."""
|
|
82
|
+
extra: dict[str, Json] = field(default_factory=dict[str, Json])
|
|
83
|
+
"""Metadata that JSON Schema output carries verbatim, such as `example`."""
|
|
84
|
+
raw: dict[str, Json] | None = None
|
|
85
|
+
"""The JSON Schema to emit, for schemas converted from JSON Schema."""
|
|
86
|
+
required: bool | None = None
|
|
87
|
+
"""Whether an object lists the field as required, when it differs from `is_optional`."""
|
|
88
|
+
|
|
89
|
+
def field(self, name: str) -> Field | None:
|
|
90
|
+
"""Returns the field with the given name."""
|
|
91
|
+
return next((f for f in self.fields if f.name == name), None)
|
|
92
|
+
|
|
93
|
+
def is_optional(self) -> bool:
|
|
94
|
+
"""Whether the input may omit the field without a default, as Zod's `optout` reports."""
|
|
95
|
+
return self.optional and self.default is None
|
|
96
|
+
|
|
97
|
+
def is_flag(self) -> bool:
|
|
98
|
+
"""Whether the option reads no value from the next token."""
|
|
99
|
+
return self.count or self.kind == "boolean"
|
|
100
|
+
|
|
101
|
+
def type_name(self) -> str:
|
|
102
|
+
"""Returns the type label help output shows."""
|
|
103
|
+
if self.count:
|
|
104
|
+
return "count"
|
|
105
|
+
if self.kind == "enum":
|
|
106
|
+
return "|".join(self.values)
|
|
107
|
+
if self.kind == "integer":
|
|
108
|
+
return "number"
|
|
109
|
+
if self.kind in ("object", "record", "unknown"):
|
|
110
|
+
return "value"
|
|
111
|
+
return self.kind
|
|
112
|
+
|
|
113
|
+
def with_count(self) -> Type:
|
|
114
|
+
"""Marks the option as a counter of repeated flags: a number that defaults to 0."""
|
|
115
|
+
kind: Kind = "number" if self.kind == "integer" else self.kind
|
|
116
|
+
return replace(
|
|
117
|
+
self, count=True, kind=kind, default=0 if self.default is None else self.default
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def object_type(fields: list[Field]) -> Type:
|
|
122
|
+
"""Creates an object schema."""
|
|
123
|
+
return Type("object", fields=fields)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def json_schema(ty: Type, io: Literal["input", "output"] = "output") -> dict[str, Json]:
|
|
127
|
+
"""Converts a schema to the JSON Schema Zod's `z.toJSONSchema()` emits, in the same order.
|
|
128
|
+
|
|
129
|
+
The `input` view describes what the input may omit: fields with defaults are not required,
|
|
130
|
+
and objects accept other keys.
|
|
131
|
+
"""
|
|
132
|
+
if ty.raw is not None:
|
|
133
|
+
return dict(ty.raw)
|
|
134
|
+
out: dict[str, Json] = {}
|
|
135
|
+
wrapped = ty.optional or ty.default is not None
|
|
136
|
+
if wrapped:
|
|
137
|
+
_metadata(ty, out)
|
|
138
|
+
kind = ty.kind
|
|
139
|
+
if kind == "array":
|
|
140
|
+
_bound(out, "minItems", ty.min)
|
|
141
|
+
_bound(out, "maxItems", ty.max)
|
|
142
|
+
out["type"] = "array"
|
|
143
|
+
assert ty.items is not None
|
|
144
|
+
out["items"] = json_schema(ty.items, io)
|
|
145
|
+
elif kind == "enum":
|
|
146
|
+
out["type"] = "string"
|
|
147
|
+
values: list[Json] = [*ty.values]
|
|
148
|
+
out["enum"] = values
|
|
149
|
+
elif kind == "integer":
|
|
150
|
+
out["type"] = "integer"
|
|
151
|
+
_bound(out, "minimum", -MAX_SAFE_INTEGER if ty.min is None else ty.min)
|
|
152
|
+
_bound(out, "maximum", MAX_SAFE_INTEGER if ty.max is None else ty.max)
|
|
153
|
+
elif kind == "record":
|
|
154
|
+
out["type"] = "object"
|
|
155
|
+
out["propertyNames"] = {"type": "string"}
|
|
156
|
+
out["additionalProperties"] = {}
|
|
157
|
+
elif kind == "object":
|
|
158
|
+
out["type"] = "object"
|
|
159
|
+
out["properties"] = {f.name: json_schema(f.ty, io) for f in ty.fields}
|
|
160
|
+
required: list[Json] = [
|
|
161
|
+
f.name
|
|
162
|
+
for f in ty.fields
|
|
163
|
+
if (not f.ty.is_optional() if f.ty.required is None else f.ty.required)
|
|
164
|
+
and (io == "output" or f.ty.default is None)
|
|
165
|
+
]
|
|
166
|
+
if required:
|
|
167
|
+
out["required"] = required
|
|
168
|
+
if io == "output":
|
|
169
|
+
out["additionalProperties"] = False
|
|
170
|
+
elif kind != "unknown":
|
|
171
|
+
out["type"] = kind
|
|
172
|
+
if kind != "boolean":
|
|
173
|
+
prefix = "Length" if kind == "string" else "imum"
|
|
174
|
+
_bound(out, "min" + prefix, ty.min)
|
|
175
|
+
_bound(out, "max" + prefix, ty.max)
|
|
176
|
+
if not wrapped:
|
|
177
|
+
_metadata(ty, out)
|
|
178
|
+
return out
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _metadata(ty: Type, out: dict[str, Json]) -> None:
|
|
182
|
+
"""Writes the default, description, and `.meta()` keys of a node."""
|
|
183
|
+
if ty.default is not None:
|
|
184
|
+
out["default"] = ty.default
|
|
185
|
+
if ty.description is not None:
|
|
186
|
+
out["description"] = ty.description
|
|
187
|
+
if ty.count:
|
|
188
|
+
out["count"] = True
|
|
189
|
+
if ty.deprecated:
|
|
190
|
+
out["deprecated"] = True
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _bound(out: dict[str, Json], key: str, value: float | None) -> None:
|
|
194
|
+
"""Writes a numeric bound when present."""
|
|
195
|
+
if value is not None:
|
|
196
|
+
out[key] = value
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
@dataclass
|
|
200
|
+
class Issue:
|
|
201
|
+
"""A validation issue, matching the issues Zod reports."""
|
|
202
|
+
|
|
203
|
+
code: str
|
|
204
|
+
message: str
|
|
205
|
+
path: list[str | int]
|
|
206
|
+
expected: str = ""
|
|
207
|
+
format: str | None = None
|
|
208
|
+
received: str | None = None
|
|
209
|
+
values: list[Json] = field(default_factory=list[Json])
|
|
210
|
+
bound: float = 0.0
|
|
211
|
+
origin: str = ""
|
|
212
|
+
pattern: str = ""
|
|
213
|
+
errors: list[list[Issue]] = field(default_factory=list[list["Issue"]])
|
|
214
|
+
"""The issues of each option of a failed union, with paths relative to the union."""
|
|
215
|
+
inclusive: bool | None = None
|
|
216
|
+
"""`False` when more than one option of an exclusive union matched."""
|
|
217
|
+
|
|
218
|
+
def to_json(self) -> dict[str, Json]:
|
|
219
|
+
"""Returns the issue as Zod serializes it in `ZodError.message`, in the same order."""
|
|
220
|
+
out: dict[str, Json] = {}
|
|
221
|
+
if self.code == "invalid_type":
|
|
222
|
+
out["expected"] = self.expected
|
|
223
|
+
if self.format is not None:
|
|
224
|
+
out["format"] = self.format
|
|
225
|
+
out["code"] = self.code
|
|
226
|
+
if self.received is not None:
|
|
227
|
+
out["received"] = self.received
|
|
228
|
+
elif self.code == "invalid_value":
|
|
229
|
+
out["code"] = self.code
|
|
230
|
+
out["values"] = list(self.values)
|
|
231
|
+
elif self.code == "invalid_format":
|
|
232
|
+
out["origin"] = self.origin
|
|
233
|
+
out["code"] = self.code
|
|
234
|
+
out["format"] = self.format
|
|
235
|
+
out["pattern"] = self.pattern
|
|
236
|
+
elif self.code == "invalid_union":
|
|
237
|
+
out["code"] = self.code
|
|
238
|
+
out["errors"] = [[i.to_json() for i in option] for option in self.errors]
|
|
239
|
+
if self.inclusive is not None:
|
|
240
|
+
out["inclusive"] = self.inclusive
|
|
241
|
+
else:
|
|
242
|
+
key = "maximum" if self.code == "too_big" else "minimum"
|
|
243
|
+
# Zod's safe-integer check reports its issue with a note and a different key order.
|
|
244
|
+
if self.origin == "int":
|
|
245
|
+
out["code"] = self.code
|
|
246
|
+
out[key] = self.bound
|
|
247
|
+
out["note"] = "Integers must be within the safe integer range."
|
|
248
|
+
out["origin"] = self.origin
|
|
249
|
+
else:
|
|
250
|
+
out["origin"] = self.origin
|
|
251
|
+
out["code"] = self.code
|
|
252
|
+
out[key] = self.bound
|
|
253
|
+
out["inclusive"] = True
|
|
254
|
+
out["path"] = list(self.path)
|
|
255
|
+
out["message"] = self.message
|
|
256
|
+
return out
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
class _Absent:
|
|
260
|
+
"""Marks a value the input omits."""
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
_ABSENT = _Absent()
|
|
264
|
+
|
|
265
|
+
#: A value under validation, or `_ABSENT`.
|
|
266
|
+
Parsed: TypeAlias = "Json | _Absent"
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def parse(ty: Type, value: Parsed, path: list[str | int], issues: list[Issue]) -> Parsed:
|
|
270
|
+
"""Validates `value` against `ty`, applying defaults and stripping unknown object keys.
|
|
271
|
+
|
|
272
|
+
`value` is `_ABSENT` when the input omits it. Returns `_ABSENT` when an optional value is
|
|
273
|
+
absent or the value is invalid.
|
|
274
|
+
"""
|
|
275
|
+
if isinstance(value, _Absent):
|
|
276
|
+
if ty.default is not None:
|
|
277
|
+
return ty.default
|
|
278
|
+
if ty.optional or ty.kind == "unknown":
|
|
279
|
+
return _ABSENT
|
|
280
|
+
if ty.coerce:
|
|
281
|
+
# `Number(undefined)` is NaN; `Boolean(undefined)` is false.
|
|
282
|
+
return _parse_present(ty, math.nan if ty.kind == "number" else False, path, issues)
|
|
283
|
+
if ty.kind in ("enum", "literal"):
|
|
284
|
+
return _parse_choice(ty, value, path, issues)
|
|
285
|
+
if isinstance(value, _Absent):
|
|
286
|
+
_invalid_type(ty, "undefined", None, path, issues)
|
|
287
|
+
return _ABSENT
|
|
288
|
+
return _parse_present(ty, value, path, issues)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _parse_choice(ty: Type, value: Parsed, path: list[str | int], issues: list[Issue]) -> Parsed:
|
|
292
|
+
"""Validates a value against an enum or a literal, which report absent values the same."""
|
|
293
|
+
if ty.kind == "literal":
|
|
294
|
+
literal = ty.literal
|
|
295
|
+
# Zod compares with `===`: numbers by value, objects never.
|
|
296
|
+
numbers = is_number(literal) and not isinstance(value, (_Absent, bool)) and is_number(value)
|
|
297
|
+
same = numbers or (type(value) is type(literal) and not isinstance(value, (list, dict)))
|
|
298
|
+
if same and value == literal:
|
|
299
|
+
return value
|
|
300
|
+
message = f"Invalid input: expected {_js.stringify(literal)}"
|
|
301
|
+
issues.append(Issue("invalid_value", message, list(path), values=[literal]))
|
|
302
|
+
return _ABSENT
|
|
303
|
+
if isinstance(value, str) and value in ty.values:
|
|
304
|
+
return value
|
|
305
|
+
if len(ty.values) == 1:
|
|
306
|
+
message = f"Invalid input: expected {_js.stringify(ty.values[0])}"
|
|
307
|
+
else:
|
|
308
|
+
listed = "|".join(_js.stringify(v) for v in ty.values)
|
|
309
|
+
message = f"Invalid option: expected one of {listed}"
|
|
310
|
+
issues.append(Issue("invalid_value", message, list(path), values=list(ty.values)))
|
|
311
|
+
return _ABSENT
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _parse_present(ty: Type, value: Json, path: list[str | int], issues: list[Issue]) -> Parsed:
|
|
315
|
+
"""Validates a value that is present in the input."""
|
|
316
|
+
kind = ty.kind
|
|
317
|
+
if ty.coerce:
|
|
318
|
+
value = _js_number(value) if kind == "number" else _js_truthy(value)
|
|
319
|
+
if kind in ("enum", "literal"):
|
|
320
|
+
return _parse_choice(ty, value, path, issues)
|
|
321
|
+
if kind == "union":
|
|
322
|
+
return _parse_union(ty, value, path, issues)
|
|
323
|
+
if kind == "intersection":
|
|
324
|
+
return _parse_intersection(ty, value, path, issues)
|
|
325
|
+
if kind == "unknown" or (kind == "boolean" and isinstance(value, bool)):
|
|
326
|
+
return value
|
|
327
|
+
if kind == "null" and value is None:
|
|
328
|
+
return None
|
|
329
|
+
if kind == "record" and isinstance(value, dict):
|
|
330
|
+
return value
|
|
331
|
+
if kind == "array" and isinstance(value, list):
|
|
332
|
+
assert ty.items is not None
|
|
333
|
+
out: list[Json] = []
|
|
334
|
+
for index, item in enumerate(value):
|
|
335
|
+
path.append(index)
|
|
336
|
+
parsed = parse(ty.items, item, path, issues)
|
|
337
|
+
out.append(None if isinstance(parsed, _Absent) else parsed)
|
|
338
|
+
path.pop()
|
|
339
|
+
_check_bounds(len(value), ty.min, ty.max, "array", path, issues)
|
|
340
|
+
return out
|
|
341
|
+
if kind in ("integer", "number"):
|
|
342
|
+
if not isinstance(value, (int, float)) or isinstance(value, bool):
|
|
343
|
+
_invalid_type(ty, _received(value), None, path, issues)
|
|
344
|
+
return _ABSENT
|
|
345
|
+
if isinstance(value, float) and math.isnan(value):
|
|
346
|
+
# Zod names NaN in the message but reports infinities as numbers.
|
|
347
|
+
_invalid_type(ty, "NaN", "NaN", path, issues)
|
|
348
|
+
return _ABSENT
|
|
349
|
+
if isinstance(value, float) and math.isinf(value):
|
|
350
|
+
_invalid_type(ty, "number", "Infinity", path, issues)
|
|
351
|
+
return _ABSENT
|
|
352
|
+
if kind == "integer":
|
|
353
|
+
if value != math.floor(value):
|
|
354
|
+
issues.append(
|
|
355
|
+
Issue(
|
|
356
|
+
"invalid_type",
|
|
357
|
+
"Invalid input: expected int, received number",
|
|
358
|
+
list(path),
|
|
359
|
+
expected="int",
|
|
360
|
+
format="safeint",
|
|
361
|
+
)
|
|
362
|
+
)
|
|
363
|
+
return _ABSENT
|
|
364
|
+
low = -MAX_SAFE_INTEGER if ty.min is None else ty.min
|
|
365
|
+
high = MAX_SAFE_INTEGER if ty.max is None else ty.max
|
|
366
|
+
unsafe = (low == -MAX_SAFE_INTEGER and value < low) or (
|
|
367
|
+
high == MAX_SAFE_INTEGER and value > high
|
|
368
|
+
)
|
|
369
|
+
_check_bounds(value, low, high, "int" if unsafe else "number", path, issues)
|
|
370
|
+
return int(value)
|
|
371
|
+
_check_bounds(value, ty.min, ty.max, "number", path, issues)
|
|
372
|
+
return value
|
|
373
|
+
if kind == "object" and isinstance(value, dict):
|
|
374
|
+
result: dict[str, Json] = {}
|
|
375
|
+
for f in ty.fields:
|
|
376
|
+
path.append(f.name)
|
|
377
|
+
parsed = parse(f.ty, value.get(f.name, _ABSENT), path, issues)
|
|
378
|
+
if not isinstance(parsed, _Absent):
|
|
379
|
+
result[f.name] = parsed
|
|
380
|
+
path.pop()
|
|
381
|
+
if ty.loose:
|
|
382
|
+
known = {f.name for f in ty.fields}
|
|
383
|
+
result.update((k, v) for k, v in value.items() if k not in known)
|
|
384
|
+
return result
|
|
385
|
+
if kind == "string" and isinstance(value, str):
|
|
386
|
+
if ty.format == "date-time" and not re.search(ISO_DATETIME, value):
|
|
387
|
+
issues.append(
|
|
388
|
+
Issue(
|
|
389
|
+
"invalid_format",
|
|
390
|
+
"Invalid ISO datetime",
|
|
391
|
+
list(path),
|
|
392
|
+
format="datetime",
|
|
393
|
+
origin="string",
|
|
394
|
+
pattern=f"/{ISO_DATETIME}/",
|
|
395
|
+
)
|
|
396
|
+
)
|
|
397
|
+
_check_bounds(_js.utf16_len(value), ty.min, ty.max, "string", path, issues)
|
|
398
|
+
if ty.pattern is not None and not re.search(ty.pattern, value):
|
|
399
|
+
issues.append(
|
|
400
|
+
Issue(
|
|
401
|
+
"invalid_format",
|
|
402
|
+
f"Invalid string: must match pattern /{ty.pattern}/",
|
|
403
|
+
list(path),
|
|
404
|
+
format="regex",
|
|
405
|
+
origin="string",
|
|
406
|
+
pattern=f"/{ty.pattern}/",
|
|
407
|
+
)
|
|
408
|
+
)
|
|
409
|
+
return value
|
|
410
|
+
_invalid_type(ty, _received(value), None, path, issues)
|
|
411
|
+
return _ABSENT
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def is_number(value: Json) -> bool:
|
|
415
|
+
"""Whether a value is a JavaScript number: an `int` or `float`, but not a `bool`."""
|
|
416
|
+
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _js_number(value: Json) -> Json:
|
|
420
|
+
"""Converts a value as JavaScript's `Number()` does."""
|
|
421
|
+
if value is None or value is False:
|
|
422
|
+
return 0
|
|
423
|
+
if value is True:
|
|
424
|
+
return 1
|
|
425
|
+
if isinstance(value, str):
|
|
426
|
+
return _js.to_number(value)
|
|
427
|
+
return value if isinstance(value, (int, float)) else math.nan
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _js_truthy(value: Json) -> bool:
|
|
431
|
+
"""Converts a value as JavaScript's `Boolean()` does."""
|
|
432
|
+
return value not in (None, False, 0, "")
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def _parse_union(ty: Type, value: Json, path: list[str | int], issues: list[Issue]) -> Parsed:
|
|
436
|
+
"""Returns the value parsed by the first matching option, as `z.union` does."""
|
|
437
|
+
errors: list[list[Issue]] = []
|
|
438
|
+
matches: list[Parsed] = []
|
|
439
|
+
for variant in ty.variants:
|
|
440
|
+
attempt: list[Issue] = []
|
|
441
|
+
parsed = _parse_present(variant, value, [], attempt)
|
|
442
|
+
if not attempt and not ty.exclusive:
|
|
443
|
+
return parsed
|
|
444
|
+
if attempt:
|
|
445
|
+
errors.append(attempt)
|
|
446
|
+
else:
|
|
447
|
+
matches.append(parsed)
|
|
448
|
+
if len(matches) == 1:
|
|
449
|
+
return matches[0]
|
|
450
|
+
if matches:
|
|
451
|
+
# More than one option of `z.xor` matched.
|
|
452
|
+
issues.append(Issue("invalid_union", "Invalid input", list(path), inclusive=False))
|
|
453
|
+
else:
|
|
454
|
+
issues.append(Issue("invalid_union", "Invalid input", list(path), errors=errors))
|
|
455
|
+
return _ABSENT
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _parse_intersection(
|
|
459
|
+
ty: Type, value: Json, path: list[str | int], issues: list[Issue]
|
|
460
|
+
) -> Parsed:
|
|
461
|
+
"""Parses a value with both sides of an intersection and merges the results.
|
|
462
|
+
|
|
463
|
+
Raises:
|
|
464
|
+
ValueError: When both sides succeed with values that cannot merge, as Zod throws.
|
|
465
|
+
"""
|
|
466
|
+
count = len(issues)
|
|
467
|
+
left, right = (_parse_present(side, value, path, issues) for side in ty.variants)
|
|
468
|
+
if len(issues) > count or isinstance(left, _Absent) or isinstance(right, _Absent):
|
|
469
|
+
return _ABSENT
|
|
470
|
+
merged, at = _merge(left, right)
|
|
471
|
+
if at is not None:
|
|
472
|
+
raise ValueError(f"Unmergable intersection. Error path: {_js.stringify(at)}")
|
|
473
|
+
return merged
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _merge(a: Json, b: Json) -> tuple[Json, list[Json] | None]:
|
|
477
|
+
"""Merges the results of an intersection, as Zod's `mergeValues` does.
|
|
478
|
+
|
|
479
|
+
Returns the merged value and, when the results conflict, the path of the conflict.
|
|
480
|
+
"""
|
|
481
|
+
if a == b and type(a) is type(b):
|
|
482
|
+
return a, None
|
|
483
|
+
if isinstance(a, dict) and isinstance(b, dict):
|
|
484
|
+
out = {**a, **b}
|
|
485
|
+
for key in a.keys() & b.keys():
|
|
486
|
+
out[key], at = _merge(a[key], b[key])
|
|
487
|
+
if at is not None:
|
|
488
|
+
return None, [key, *at]
|
|
489
|
+
return out, None
|
|
490
|
+
if isinstance(a, list) and isinstance(b, list) and len(a) == len(b):
|
|
491
|
+
items: list[Json] = []
|
|
492
|
+
for index, (x, y) in enumerate(zip(a, b, strict=True)):
|
|
493
|
+
item, at = _merge(x, y)
|
|
494
|
+
if at is not None:
|
|
495
|
+
return None, [index, *at]
|
|
496
|
+
items.append(item)
|
|
497
|
+
return items, None
|
|
498
|
+
return None, []
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def _invalid_type(
|
|
502
|
+
ty: Type, received: str, reported: str | None, path: list[str | int], issues: list[Issue]
|
|
503
|
+
) -> None:
|
|
504
|
+
"""Reports an `invalid_type` issue for `ty`."""
|
|
505
|
+
expected = {"integer": "number", "unknown": "string", "enum": "string"}.get(ty.kind, ty.kind)
|
|
506
|
+
issues.append(
|
|
507
|
+
Issue(
|
|
508
|
+
"invalid_type",
|
|
509
|
+
f"Invalid input: expected {expected}, received {received}",
|
|
510
|
+
list(path),
|
|
511
|
+
expected=expected,
|
|
512
|
+
received=reported,
|
|
513
|
+
)
|
|
514
|
+
)
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def _check_bounds(
|
|
518
|
+
value: float,
|
|
519
|
+
low: float | None,
|
|
520
|
+
high: float | None,
|
|
521
|
+
origin: str,
|
|
522
|
+
path: list[str | int],
|
|
523
|
+
issues: list[Issue],
|
|
524
|
+
) -> None:
|
|
525
|
+
"""Reports `too_small` and `too_big` issues."""
|
|
526
|
+
unit = {"string": " characters", "array": " items"}.get(origin, "")
|
|
527
|
+
verb = "have" if unit else "be"
|
|
528
|
+
if low is not None and value < low:
|
|
529
|
+
bound = _js.number_to_string(low)
|
|
530
|
+
message = f"Too small: expected {origin} to {verb} >={bound}{unit}"
|
|
531
|
+
issues.append(Issue("too_small", message, list(path), bound=low, origin=origin))
|
|
532
|
+
if high is not None and value > high:
|
|
533
|
+
bound = _js.number_to_string(high)
|
|
534
|
+
message = f"Too big: expected {origin} to {verb} <={bound}{unit}"
|
|
535
|
+
issues.append(Issue("too_big", message, list(path), bound=high, origin=origin))
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def _received(value: Json) -> str:
|
|
539
|
+
"""Returns Zod's name for the type of a received value."""
|
|
540
|
+
if value is None:
|
|
541
|
+
return "null"
|
|
542
|
+
if isinstance(value, bool):
|
|
543
|
+
return "boolean"
|
|
544
|
+
if isinstance(value, (int, float)):
|
|
545
|
+
return "number"
|
|
546
|
+
if isinstance(value, str):
|
|
547
|
+
return "string"
|
|
548
|
+
return "array" if isinstance(value, list) else "object"
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def validate(ty: Type, data: dict[str, Json]) -> tuple[dict[str, Json], list[Issue]]:
|
|
552
|
+
"""Validates an object against a schema. Returns the parsed object and the issues."""
|
|
553
|
+
issues: list[Issue] = []
|
|
554
|
+
parsed = parse(ty, data, [], issues)
|
|
555
|
+
return (parsed if isinstance(parsed, dict) else {}), issues
|