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/_js.py
ADDED
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
"""JavaScript string, number, and object semantics that reach output.
|
|
2
|
+
|
|
3
|
+
The TypeScript package formats values with `String(number)`, `JSON.stringify`, and
|
|
4
|
+
`localeCompare`, and JavaScript objects list integer-like keys first. Every module that formats
|
|
5
|
+
output reuses these functions, so the Python port prints the same bytes. Floats format as
|
|
6
|
+
JavaScript numbers do; integers keep their exact value.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
from typing import TypeAlias
|
|
14
|
+
|
|
15
|
+
#: JSON data as this package handles it.
|
|
16
|
+
Json: TypeAlias = "bool | int | float | str | list[Json] | dict[str, Json] | None"
|
|
17
|
+
|
|
18
|
+
_WHITESPACE = frozenset(
|
|
19
|
+
"\t\n\x0b\x0c\r \xa0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009"
|
|
20
|
+
"\u200a\u2028\u2029\u202f\u205f\u3000\ufeff"
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def is_whitespace(ch: str) -> bool:
|
|
25
|
+
"""Whether a character is ECMAScript white space or a line terminator."""
|
|
26
|
+
return ch in _WHITESPACE
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def trim(value: str) -> str:
|
|
30
|
+
"""Trims ECMAScript whitespace, as `String.prototype.trim` does."""
|
|
31
|
+
start = 0
|
|
32
|
+
end = len(value)
|
|
33
|
+
while start < end and value[start] in _WHITESPACE:
|
|
34
|
+
start += 1
|
|
35
|
+
while end > start and value[end - 1] in _WHITESPACE:
|
|
36
|
+
end -= 1
|
|
37
|
+
return value[start:end]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def utf16_len(value: str) -> int:
|
|
41
|
+
"""Returns the length of a string in UTF-16 code units."""
|
|
42
|
+
return len(value) + sum(1 for ch in value if ord(ch) > 0xFFFF)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def utf16(value: str) -> list[int]:
|
|
46
|
+
"""Returns the UTF-16 code units of a string."""
|
|
47
|
+
data = value.encode("utf-16-le", "surrogatepass")
|
|
48
|
+
return [data[i] | (data[i + 1] << 8) for i in range(0, len(data), 2)]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def from_utf16(units: list[int]) -> str:
|
|
52
|
+
"""Decodes UTF-16 code units, replacing unpaired surrogates as `from_utf16_lossy` does."""
|
|
53
|
+
data = bytearray()
|
|
54
|
+
for unit in units:
|
|
55
|
+
data += bytes((unit & 0xFF, unit >> 8))
|
|
56
|
+
return bytes(data).decode("utf-16-le", "replace")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def number_to_string(value: float) -> str:
|
|
60
|
+
"""Formats a number as ECMAScript `Number.prototype.toString` does, and integers exactly."""
|
|
61
|
+
if isinstance(value, int):
|
|
62
|
+
return str(value)
|
|
63
|
+
# Data is finite: `normalize` and `to_json` store non-finite numbers as `None`.
|
|
64
|
+
if not value:
|
|
65
|
+
return "0"
|
|
66
|
+
sign = "-" if value < 0 else ""
|
|
67
|
+
mantissa, _, exp = repr(abs(value)).partition("e")
|
|
68
|
+
exponent = int(exp) if exp else 0
|
|
69
|
+
whole, _, frac = mantissa.partition(".")
|
|
70
|
+
if frac == "0":
|
|
71
|
+
frac = ""
|
|
72
|
+
n = exponent - (len(frac) - len(frac.lstrip("0"))) if whole == "0" else len(whole) + exponent
|
|
73
|
+
digits = (whole + frac).lstrip("0").rstrip("0")
|
|
74
|
+
k = len(digits)
|
|
75
|
+
if k <= n <= 21:
|
|
76
|
+
return sign + digits + "0" * (n - k)
|
|
77
|
+
if 0 < n <= 21:
|
|
78
|
+
return f"{sign}{digits[:n]}.{digits[n:]}"
|
|
79
|
+
if -6 < n <= 0:
|
|
80
|
+
return f"{sign}0.{'0' * -n}{digits}"
|
|
81
|
+
e = n - 1
|
|
82
|
+
rest = f".{digits[1:]}" if k > 1 else ""
|
|
83
|
+
return f"{sign}{digits[0]}{rest}e{'+' if e >= 0 else '-'}{abs(e)}"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
_PREFIXES = {"0x": 16, "0X": 16, "0o": 8, "0O": 8, "0b": 2, "0B": 2}
|
|
87
|
+
_RADIX_DIGITS = {16: "0123456789abcdefABCDEF", 8: "01234567", 2: "01"}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def to_number(text: str) -> float:
|
|
91
|
+
"""Converts a string to a number as ECMAScript `Number(string)` does."""
|
|
92
|
+
text = trim(text)
|
|
93
|
+
if not text:
|
|
94
|
+
return 0.0
|
|
95
|
+
radix = _PREFIXES.get(text[:2])
|
|
96
|
+
if radix is not None:
|
|
97
|
+
digits = text[2:]
|
|
98
|
+
if not digits or any(ch not in _RADIX_DIGITS[radix] for ch in digits):
|
|
99
|
+
return math.nan
|
|
100
|
+
return float(int(digits, radix))
|
|
101
|
+
unsigned = text[1:] if text[0] in "+-" else text
|
|
102
|
+
if unsigned == "Infinity":
|
|
103
|
+
return -math.inf if text[0] == "-" else math.inf
|
|
104
|
+
if not _is_decimal_literal(unsigned):
|
|
105
|
+
return math.nan
|
|
106
|
+
return float(text)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _is_decimal_literal(text: str) -> bool:
|
|
110
|
+
"""Whether `text` matches ECMAScript's `StrUnsignedDecimalLiteral` without `Infinity`."""
|
|
111
|
+
index = 0
|
|
112
|
+
size = len(text)
|
|
113
|
+
|
|
114
|
+
def digits() -> int:
|
|
115
|
+
nonlocal index
|
|
116
|
+
start = index
|
|
117
|
+
while index < size and text[index] in "0123456789":
|
|
118
|
+
index += 1
|
|
119
|
+
return index - start
|
|
120
|
+
|
|
121
|
+
mantissa = digits()
|
|
122
|
+
if index < size and text[index] == ".":
|
|
123
|
+
index += 1
|
|
124
|
+
mantissa += digits()
|
|
125
|
+
if mantissa == 0:
|
|
126
|
+
return False
|
|
127
|
+
if index < size and text[index] in "eE":
|
|
128
|
+
index += 1
|
|
129
|
+
if index < size and text[index] in "+-":
|
|
130
|
+
index += 1
|
|
131
|
+
if digits() == 0:
|
|
132
|
+
return False
|
|
133
|
+
return index == size
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _quote(value: str) -> str:
|
|
137
|
+
"""Returns a JSON string literal with `JSON.stringify` escaping."""
|
|
138
|
+
return json.dumps(value, ensure_ascii=False)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def stringify(value: Json, step: str | None = None, indent: str = "") -> str:
|
|
142
|
+
"""Serializes a value as `JSON.stringify(value)`, or with an indentation step."""
|
|
143
|
+
if value is None:
|
|
144
|
+
return "null"
|
|
145
|
+
if value is True:
|
|
146
|
+
return "true"
|
|
147
|
+
if value is False:
|
|
148
|
+
return "false"
|
|
149
|
+
if isinstance(value, int):
|
|
150
|
+
return str(value)
|
|
151
|
+
if isinstance(value, float):
|
|
152
|
+
return number_to_string(value) if math.isfinite(value) else "null"
|
|
153
|
+
if isinstance(value, str):
|
|
154
|
+
return _quote(value)
|
|
155
|
+
inner = None if step is None else indent + step
|
|
156
|
+
open_, close = ("[", "]") if isinstance(value, list) else ("{", "}")
|
|
157
|
+
if not value:
|
|
158
|
+
return open_ + close
|
|
159
|
+
if isinstance(value, list):
|
|
160
|
+
parts = [stringify(item, step, inner or "") for item in value]
|
|
161
|
+
else:
|
|
162
|
+
colon = ":" if inner is None else ": "
|
|
163
|
+
parts = [
|
|
164
|
+
_quote(key) + colon + stringify(item, step, inner or "") for key, item in value.items()
|
|
165
|
+
]
|
|
166
|
+
if inner is None:
|
|
167
|
+
return open_ + ",".join(parts) + close
|
|
168
|
+
return f"{open_}\n{inner}" + f",\n{inner}".join(parts) + f"\n{indent}{close}"
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def stringify_pretty(value: Json) -> str:
|
|
172
|
+
"""Serializes a value as `JSON.stringify(value, null, 2)` does."""
|
|
173
|
+
return stringify(value, " ")
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def array_index(key: str) -> int | None:
|
|
177
|
+
"""Parses a canonical array index, the keys JavaScript orders first."""
|
|
178
|
+
if not key or (len(key) > 1 and key[0] == "0") or any(ch not in "0123456789" for ch in key):
|
|
179
|
+
return None
|
|
180
|
+
index = int(key)
|
|
181
|
+
return index if index < 2**32 - 1 else None
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def normalize(value: Json) -> Json:
|
|
185
|
+
"""Reorders object keys as JavaScript stores them: integer-like keys first, ascending."""
|
|
186
|
+
if isinstance(value, list):
|
|
187
|
+
return [normalize(item) for item in value]
|
|
188
|
+
if isinstance(value, dict):
|
|
189
|
+
indices: list[tuple[int, str, Json]] = []
|
|
190
|
+
rest: dict[str, Json] = {}
|
|
191
|
+
for key, item in value.items():
|
|
192
|
+
index = array_index(key)
|
|
193
|
+
if index is None:
|
|
194
|
+
rest[key] = normalize(item)
|
|
195
|
+
else:
|
|
196
|
+
indices.append((index, key, normalize(item)))
|
|
197
|
+
indices.sort(key=lambda entry: entry[0])
|
|
198
|
+
out = {key: item for _, key, item in indices}
|
|
199
|
+
out.update(rest)
|
|
200
|
+
return out
|
|
201
|
+
return value
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def relative_index(value: float, length: int) -> int:
|
|
205
|
+
"""Resolves a `slice` bound as JavaScript does: truncated, from the end when negative."""
|
|
206
|
+
value = 0.0 if math.isnan(value) else min(max(value, -length), length)
|
|
207
|
+
index = math.trunc(value)
|
|
208
|
+
if index < 0:
|
|
209
|
+
index += length
|
|
210
|
+
return min(max(index, 0), length)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def element(items: list[str], value: float) -> str | None:
|
|
214
|
+
"""Returns the element JavaScript reads at `array[value]`."""
|
|
215
|
+
if value >= 0 and value == math.floor(value) and value < len(items):
|
|
216
|
+
return items[int(value)]
|
|
217
|
+
return None
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def to_string(value: Json) -> str:
|
|
221
|
+
"""Formats a value as `String(value)` does for JSON data."""
|
|
222
|
+
if value is None:
|
|
223
|
+
return "null"
|
|
224
|
+
if value is True:
|
|
225
|
+
return "true"
|
|
226
|
+
if value is False:
|
|
227
|
+
return "false"
|
|
228
|
+
if isinstance(value, (int, float)):
|
|
229
|
+
return number_to_string(value)
|
|
230
|
+
if isinstance(value, str):
|
|
231
|
+
return value
|
|
232
|
+
if isinstance(value, list):
|
|
233
|
+
return ",".join("" if item is None else to_string(item) for item in value)
|
|
234
|
+
return "[object Object]"
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def to_kebab(value: str) -> str:
|
|
238
|
+
"""Converts a camelCase name to kebab-case."""
|
|
239
|
+
return "".join(f"-{ch.lower()}" if "A" <= ch <= "Z" else ch for ch in value)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
_SYMBOLS = "\t\n\x0b\x0c\r _-,;:!?.'\"()[]{}@*/\\&#%`^+<=>|~$"
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _primary(ch: str) -> int:
|
|
246
|
+
"""Returns the primary collation weight of a character."""
|
|
247
|
+
index = _SYMBOLS.find(ch)
|
|
248
|
+
if index >= 0:
|
|
249
|
+
return index
|
|
250
|
+
if "0" <= ch <= "9":
|
|
251
|
+
return 100 + ord(ch)
|
|
252
|
+
if ch.isascii() and ch.isalpha():
|
|
253
|
+
return 200 + ord(ch.lower())
|
|
254
|
+
return 1000 + ord(ch)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def locale_key(value: str) -> tuple[list[int], list[bool], str]:
|
|
258
|
+
"""Returns a sort key matching `String.prototype.localeCompare` under the ICU root collation."""
|
|
259
|
+
return ([_primary(ch) for ch in value], [ch.isupper() for ch in value], value)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
class _SyntaxError(Exception):
|
|
263
|
+
"""A JSON syntax failure: `None` for an early end, a located message, or a bad token."""
|
|
264
|
+
|
|
265
|
+
def __init__(self, message: str | None = None, *, token: bool = False) -> None:
|
|
266
|
+
super().__init__(message)
|
|
267
|
+
self.message = message
|
|
268
|
+
self.token = token
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
class _Syntax:
|
|
272
|
+
"""A JSON syntax checker that reports failures the way V8 does."""
|
|
273
|
+
|
|
274
|
+
def __init__(self, units: list[int]) -> None:
|
|
275
|
+
self.units = units
|
|
276
|
+
self.pos = 0
|
|
277
|
+
|
|
278
|
+
def peek(self) -> int | None:
|
|
279
|
+
return self.units[self.pos] if self.pos < len(self.units) else None
|
|
280
|
+
|
|
281
|
+
def is_(self, ch: str) -> bool:
|
|
282
|
+
return self.peek() == ord(ch)
|
|
283
|
+
|
|
284
|
+
def digit(self) -> bool:
|
|
285
|
+
unit = self.peek()
|
|
286
|
+
return unit is not None and 0x30 <= unit <= 0x39
|
|
287
|
+
|
|
288
|
+
def whitespace(self) -> None:
|
|
289
|
+
while self.peek() in (0x20, 0x09, 0x0A, 0x0D):
|
|
290
|
+
self.pos += 1
|
|
291
|
+
|
|
292
|
+
def at(self, message: str) -> _SyntaxError:
|
|
293
|
+
before = self.units[: self.pos]
|
|
294
|
+
line = before.count(0x0A) + 1
|
|
295
|
+
last = len(before) - 1 - before[::-1].index(0x0A) if 0x0A in before else -1
|
|
296
|
+
column = self.pos - (last + 1) + 1
|
|
297
|
+
return _SyntaxError(f"{message} at position {self.pos} (line {line} column {column})")
|
|
298
|
+
|
|
299
|
+
def value(self) -> None:
|
|
300
|
+
self.whitespace()
|
|
301
|
+
unit = self.peek()
|
|
302
|
+
if unit is None:
|
|
303
|
+
raise _SyntaxError()
|
|
304
|
+
ch = chr(unit)
|
|
305
|
+
if ch == "{":
|
|
306
|
+
self.object()
|
|
307
|
+
elif ch == "[":
|
|
308
|
+
self.array()
|
|
309
|
+
elif ch == '"':
|
|
310
|
+
self.string()
|
|
311
|
+
elif ch == "-" or "0" <= ch <= "9":
|
|
312
|
+
self.number()
|
|
313
|
+
elif ch in "tfn":
|
|
314
|
+
self.literal({"t": "true", "f": "false", "n": "null"}[ch])
|
|
315
|
+
else:
|
|
316
|
+
raise _SyntaxError(token=True)
|
|
317
|
+
|
|
318
|
+
def object(self) -> None:
|
|
319
|
+
self.pos += 1
|
|
320
|
+
self.whitespace()
|
|
321
|
+
if self.is_("}"):
|
|
322
|
+
self.pos += 1
|
|
323
|
+
return
|
|
324
|
+
first = True
|
|
325
|
+
while True:
|
|
326
|
+
if not self.is_('"'):
|
|
327
|
+
raise self.at(
|
|
328
|
+
"Expected property name or '}' in JSON"
|
|
329
|
+
if first
|
|
330
|
+
else "Expected double-quoted property name in JSON"
|
|
331
|
+
)
|
|
332
|
+
first = False
|
|
333
|
+
self.string()
|
|
334
|
+
self.whitespace()
|
|
335
|
+
if not self.is_(":"):
|
|
336
|
+
raise self.at("Expected ':' after property name in JSON")
|
|
337
|
+
self.pos += 1
|
|
338
|
+
self.value()
|
|
339
|
+
self.whitespace()
|
|
340
|
+
if self.is_(","):
|
|
341
|
+
self.pos += 1
|
|
342
|
+
self.whitespace()
|
|
343
|
+
elif self.is_("}"):
|
|
344
|
+
self.pos += 1
|
|
345
|
+
return
|
|
346
|
+
else:
|
|
347
|
+
raise self.at("Expected ',' or '}' after property value in JSON")
|
|
348
|
+
|
|
349
|
+
def array(self) -> None:
|
|
350
|
+
self.pos += 1
|
|
351
|
+
self.whitespace()
|
|
352
|
+
if self.is_("]"):
|
|
353
|
+
self.pos += 1
|
|
354
|
+
return
|
|
355
|
+
while True:
|
|
356
|
+
self.value()
|
|
357
|
+
self.whitespace()
|
|
358
|
+
if self.is_(","):
|
|
359
|
+
self.pos += 1
|
|
360
|
+
elif self.is_("]"):
|
|
361
|
+
self.pos += 1
|
|
362
|
+
return
|
|
363
|
+
else:
|
|
364
|
+
raise self.at("Expected ',' or ']' after array element in JSON")
|
|
365
|
+
|
|
366
|
+
def string(self) -> None:
|
|
367
|
+
self.pos += 1
|
|
368
|
+
while True:
|
|
369
|
+
unit = self.peek()
|
|
370
|
+
if unit is None:
|
|
371
|
+
raise self.at("Unterminated string in JSON")
|
|
372
|
+
if unit == 0x22:
|
|
373
|
+
self.pos += 1
|
|
374
|
+
return
|
|
375
|
+
if unit < 0x20:
|
|
376
|
+
raise self.at("Bad control character in string literal in JSON")
|
|
377
|
+
if unit == 0x5C:
|
|
378
|
+
self.pos += 1
|
|
379
|
+
escape = self.peek()
|
|
380
|
+
if escape == ord("u"):
|
|
381
|
+
for _ in range(4):
|
|
382
|
+
self.pos += 1
|
|
383
|
+
hexdigit = self.peek()
|
|
384
|
+
if hexdigit is None or chr(hexdigit) not in "0123456789abcdefABCDEF":
|
|
385
|
+
raise self.at("Bad Unicode escape in JSON")
|
|
386
|
+
elif escape is None or chr(escape) not in '"\\/bfnrt':
|
|
387
|
+
raise self.at("Bad escaped character in JSON")
|
|
388
|
+
self.pos += 1
|
|
389
|
+
|
|
390
|
+
def number(self) -> None:
|
|
391
|
+
if self.is_("-"):
|
|
392
|
+
self.pos += 1
|
|
393
|
+
if not self.digit():
|
|
394
|
+
raise self.at("No number after minus sign in JSON")
|
|
395
|
+
if self.is_("0"):
|
|
396
|
+
self.pos += 1
|
|
397
|
+
else:
|
|
398
|
+
while self.digit():
|
|
399
|
+
self.pos += 1
|
|
400
|
+
if self.is_("."):
|
|
401
|
+
self.pos += 1
|
|
402
|
+
if not self.digit():
|
|
403
|
+
raise self.at("Unterminated fractional number in JSON")
|
|
404
|
+
while self.digit():
|
|
405
|
+
self.pos += 1
|
|
406
|
+
if self.is_("e") or self.is_("E"):
|
|
407
|
+
self.pos += 1
|
|
408
|
+
if self.is_("+") or self.is_("-"):
|
|
409
|
+
self.pos += 1
|
|
410
|
+
if not self.digit():
|
|
411
|
+
raise self.at("Exponent part is missing a number in JSON")
|
|
412
|
+
while self.digit():
|
|
413
|
+
self.pos += 1
|
|
414
|
+
|
|
415
|
+
def literal(self, word: str) -> None:
|
|
416
|
+
for expected in word:
|
|
417
|
+
unit = self.peek()
|
|
418
|
+
if unit is None:
|
|
419
|
+
raise _SyntaxError()
|
|
420
|
+
if unit != ord(expected):
|
|
421
|
+
raise _SyntaxError(token=True)
|
|
422
|
+
self.pos += 1
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def json_parse_error(source: str) -> str | None:
|
|
426
|
+
"""Returns the message V8's `JSON.parse` throws for invalid JSON, or `None` if it accepts."""
|
|
427
|
+
units = utf16(source)
|
|
428
|
+
parser = _Syntax(units)
|
|
429
|
+
try:
|
|
430
|
+
parser.value()
|
|
431
|
+
parser.whitespace()
|
|
432
|
+
if parser.digit():
|
|
433
|
+
raise parser.at("Unexpected number in JSON")
|
|
434
|
+
if parser.peek() is not None:
|
|
435
|
+
raise parser.at("Unexpected non-whitespace character after JSON")
|
|
436
|
+
except _SyntaxError as failure:
|
|
437
|
+
if failure.message is not None:
|
|
438
|
+
return failure.message
|
|
439
|
+
if not failure.token:
|
|
440
|
+
return "Unexpected end of JSON input"
|
|
441
|
+
pos = parser.pos
|
|
442
|
+
token = from_utf16(units[pos : pos + 1])
|
|
443
|
+
if len(units) < 21:
|
|
444
|
+
context = f'"{source}"'
|
|
445
|
+
else:
|
|
446
|
+
start = max(pos - 10, 0)
|
|
447
|
+
end = min(pos + 10, len(units))
|
|
448
|
+
before = "..." if start > 0 else ""
|
|
449
|
+
after = "..." if end < len(units) else ""
|
|
450
|
+
context = f'{before}"{from_utf16(units[start:end])}"{after}'
|
|
451
|
+
return f"Unexpected token '{token}', {context} is not valid JSON"
|
|
452
|
+
return None
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def parse_json(source: str) -> Json:
|
|
456
|
+
"""Parses JSON text that `json_parse_error` accepts, as `JSON.parse` does."""
|
|
457
|
+
return normalize(json.loads(source))
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def as_object(value: Json) -> dict[str, Json]:
|
|
461
|
+
"""Returns a JSON object, or an empty one for any other value."""
|
|
462
|
+
return value if isinstance(value, dict) else {}
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def as_list(value: Json) -> list[Json]:
|
|
466
|
+
"""Returns a JSON array, or an empty one for any other value."""
|
|
467
|
+
return value if isinstance(value, list) else []
|