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/_help.py ADDED
@@ -0,0 +1,260 @@
1
+ """Help text for command groups and commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from dataclasses import dataclass, field
7
+
8
+ from . import _js
9
+ from ._schema import Type
10
+
11
+
12
+ @dataclass
13
+ class Entry:
14
+ """A command listed in help output."""
15
+
16
+ name: str
17
+ description: str | None
18
+
19
+
20
+ @dataclass
21
+ class Usage:
22
+ """An alternative usage line shown in command help."""
23
+
24
+ args: list[str] = field(default_factory=list[str])
25
+ """Arguments shown as `<name>`."""
26
+ options: list[str] = field(default_factory=list[str])
27
+ """Options shown as `--name <name>`."""
28
+ prefix: str | None = None
29
+ """Text before the command, such as `cat file.txt |`."""
30
+ suffix: str | None = None
31
+ """Text after the command, such as `| head`."""
32
+
33
+
34
+ @dataclass
35
+ class Example:
36
+ """A usage example: the arguments after the command name and what the example shows."""
37
+
38
+ command: str = ""
39
+ """The arguments and options after the command name."""
40
+ description: str | None = None
41
+ """What the example shows."""
42
+
43
+
44
+ @dataclass
45
+ class Options:
46
+ """Inputs of `format_root` and `format_command`."""
47
+
48
+ aliases: list[str] = field(default_factory=list[str])
49
+ args: Type | None = None
50
+ commands: list[Entry] | None = None
51
+ config_flag: str | None = None
52
+ description: str | None = None
53
+ env: Type | None = None
54
+ env_source: Callable[[str], str | None] | None = None
55
+ examples: list[Example] | None = None
56
+ globals: Type | None = None
57
+ hide_global_options: bool = False
58
+ hide_skills: bool = False
59
+ hide_update: bool = False
60
+ hint: str | None = None
61
+ options: Type | None = None
62
+ root: bool = False
63
+ usage: list[Usage] = field(default_factory=list[Usage])
64
+ version: str | None = None
65
+
66
+
67
+ def _title(name: str, options: Options) -> str:
68
+ title = name if options.version is None else f"{name}@{options.version}"
69
+ return f"{title} \u2014 {options.description}" if options.description else title
70
+
71
+
72
+ def _pad(value: str, width: int) -> str:
73
+ return value + " " * max(width - _js.utf16_len(value), 0)
74
+
75
+
76
+ def _width(values: list[str]) -> int:
77
+ return max((_js.utf16_len(v) for v in values), default=0)
78
+
79
+
80
+ def _commands(lines: list[str], entries: list[Entry]) -> None:
81
+ width = _width([e.name for e in entries])
82
+ for entry in entries:
83
+ if entry.description:
84
+ lines.append(f" {_pad(entry.name, width)} {entry.description}")
85
+ else:
86
+ lines.append(f" {entry.name}")
87
+
88
+
89
+ def format_root(name: str, options: Options) -> str:
90
+ """Formats help for a command group."""
91
+ lines = [_title(name, options), "", f"Usage: {name} <command>"]
92
+ if options.aliases:
93
+ lines.append(f"Aliases: {', '.join(options.aliases)}")
94
+ if options.commands:
95
+ lines += ["", "Commands:"]
96
+ _commands(lines, options.commands)
97
+ _global_lines(lines, options)
98
+ return "\n".join(lines)
99
+
100
+
101
+ def format_command(name: str, options: Options) -> str:
102
+ """Formats help for a command."""
103
+ lines = [_title(name, options), ""]
104
+ if not options.usage:
105
+ synopsis = [name]
106
+ for f in options.args.fields if options.args else []:
107
+ type_name = f.ty.type_name()
108
+ label = type_name if "|" in type_name else f.name
109
+ if type_name == "array":
110
+ label += "..."
111
+ synopsis.append(f"[{label}]" if f.ty.is_optional() else f"<{label}>")
112
+ opts = " [options]" if options.options is not None else ""
113
+ subcommands = " | <command>" if options.commands else ""
114
+ lines.append(f"Usage: {' '.join(synopsis)}{opts}{subcommands}")
115
+ else:
116
+ for index, usage in enumerate(options.usage):
117
+ parts: list[str] = []
118
+ if usage.prefix:
119
+ parts.append(usage.prefix)
120
+ parts.append(name)
121
+ parts += [f"<{a}>" for a in usage.args]
122
+ parts += [f"--{o} <{o}>" for o in usage.options]
123
+ if usage.suffix:
124
+ parts.append(usage.suffix)
125
+ lines.append(("Usage: " if index == 0 else " ") + " ".join(parts))
126
+ if options.aliases:
127
+ lines.append(f"Aliases: {', '.join(options.aliases)}")
128
+
129
+ if options.args is not None and options.args.fields:
130
+ lines += ["", "Arguments:"]
131
+ width = _width([f.name for f in options.args.fields])
132
+ for f in options.args.fields:
133
+ lines.append(f" {_pad(f.name, width)} {f.ty.description or ''}")
134
+
135
+ if options.options is not None and options.options.fields:
136
+ lines += ["", "Options:"]
137
+ _option_lines(lines, options.options)
138
+
139
+ if options.examples:
140
+ lines += ["", "Examples:"]
141
+
142
+ def full(e: Example) -> str:
143
+ return f"{name} {e.command}" if e.command else name
144
+
145
+ width = _width([full(e) for e in options.examples])
146
+ for example in options.examples:
147
+ command = full(example)
148
+ if example.description:
149
+ lines.append(f" {_pad(command, width)} # {example.description}")
150
+ else:
151
+ lines.append(f" {command}")
152
+
153
+ if options.hint:
154
+ lines += ["", options.hint]
155
+
156
+ if options.commands:
157
+ lines += ["", "Commands:"]
158
+ _commands(lines, options.commands)
159
+
160
+ if not options.hide_global_options:
161
+ _global_lines(lines, options)
162
+
163
+ if options.env is not None and options.env.fields:
164
+ lines += ["", "Environment Variables:"]
165
+ width = _width([f.name for f in options.env.fields])
166
+ for f in options.env.fields:
167
+ parts = [f.ty.description or ""]
168
+ value = options.env_source(f.name) if options.env_source else None
169
+ if value is not None:
170
+ parts.append(f"set: {_redact(value)}")
171
+ default = _display_default(f.ty)
172
+ if default is not None:
173
+ parts.append(f"default: {default}")
174
+ description = f"{parts[0]} ({', '.join(parts[1:])})" if len(parts) > 1 else parts[0]
175
+ lines.append(f" {_pad(f.name, width)} {description}")
176
+
177
+ return "\n".join(lines)
178
+
179
+
180
+ def _display_default(ty: Type) -> str | None:
181
+ """Returns the default shown in help, omitting empty arrays."""
182
+ if ty.default is None or ty.default == []:
183
+ return None
184
+ return _js.to_string(ty.default)
185
+
186
+
187
+ def _option_lines(lines: list[str], schema: Type) -> None:
188
+ """Lists options with flags, aliases, value hints, and defaults."""
189
+ entries: list[tuple[str, str]] = []
190
+ for f in schema.fields:
191
+ type_name = f.ty.type_name()
192
+ kebab = _js.to_kebab(f.name)
193
+ hint = "" if type_name == "boolean" else f" <{type_name}>"
194
+ flag = f"--{kebab}, -{f.alias}{hint}" if f.alias else f"--{kebab}{hint}"
195
+ default = (
196
+ None if type_name == "boolean" and f.ty.default is False else _display_default(f.ty)
197
+ )
198
+ prefix = "[deprecated] " if f.ty.deprecated else ""
199
+ description = prefix + (f.ty.description or "")
200
+ if default is not None:
201
+ description += f" (default: {default})"
202
+ entries.append((flag, description))
203
+ width = _width([flag for flag, _ in entries])
204
+ for flag, description in entries:
205
+ lines.append(f" {_pad(flag, width)} {description}")
206
+
207
+
208
+ _INTEGRATIONS = (
209
+ ("completions", "Generate shell completion script"),
210
+ ("mcp", "Register as MCP server (add, doctor)"),
211
+ ("skills", "Sync skill files to agents (add, list)"),
212
+ )
213
+
214
+
215
+ def _global_lines(lines: list[str], options: Options) -> None:
216
+ """Writes the integrations and global options sections."""
217
+ if options.root:
218
+ builtins = [b for b in _INTEGRATIONS if not options.hide_skills or b[0] != "skills"]
219
+ width = _width([n for n, _ in builtins])
220
+ lines += ["", "Integrations:"]
221
+ for name, description in builtins:
222
+ lines.append(f" {_pad(name, width)} {description}")
223
+
224
+ if options.globals is not None and options.globals.fields:
225
+ lines += ["", "Custom Global Options:"]
226
+ _option_lines(lines, options.globals)
227
+
228
+ flags: list[tuple[str, str]] = []
229
+ if options.config_flag is not None:
230
+ flag = options.config_flag
231
+ flags.append((f"--{flag} <path>", "Load JSON option defaults from a file"))
232
+ flags.append((f"--no-{flag}", "Disable JSON option defaults for this run"))
233
+ flags += [
234
+ ("--filter-output <keys>", "Filter output by key paths (e.g. foo,bar.baz,a[0,3])"),
235
+ ("--format <toon|json|yaml|md|jsonl>", "Output format"),
236
+ ("--help", "Show help"),
237
+ ("--llms, --llms-full", "Print LLM-readable manifest"),
238
+ ("--schema", "Show JSON Schema for command"),
239
+ ("--token-count", "Print token count of output (instead of output)"),
240
+ ("--token-limit <n>", "Limit output to n tokens"),
241
+ ("--token-offset <n>", "Skip first n tokens of output"),
242
+ ("--full-output", "Show full output envelope"),
243
+ ]
244
+ if options.root:
245
+ flags += [("--mcp", "Start as MCP stdio server"), ("--version", "Show version")]
246
+ if not options.hide_update:
247
+ flags.append(("--update", "Update to latest version"))
248
+ flags.sort(key=lambda entry: _js.locale_key(entry[0]))
249
+ width = max(len(flag) for flag, _ in flags)
250
+ lines += ["", "Global Options:"]
251
+ for flag, description in flags:
252
+ lines.append(f" {_pad(flag, width)} {description}")
253
+
254
+
255
+ def _redact(value: str) -> str:
256
+ """Redacts a value, keeping only the last four characters of long values."""
257
+ units = _js.utf16(value)
258
+ if len(units) <= 4:
259
+ return "****"
260
+ return "****" + _js.from_utf16(units[-4:])
incur/_http.py ADDED
@@ -0,0 +1,389 @@
1
+ """HTTP messages for fetch handlers, the ASGI application, and outgoing requests.
2
+
3
+ `Request`, `Response`, and `Headers` follow the Fetch API that the TypeScript package builds on:
4
+ header names are case-insensitive and list lowercased in name order, and a text body without a
5
+ `content-type` is sent as `text/plain;charset=UTF-8`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import urllib.error
12
+ import urllib.parse
13
+ import urllib.request
14
+ from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Callable, Iterable, Iterator
15
+ from collections.abc import Mapping as MappingABC
16
+ from typing import Any, cast
17
+
18
+ from . import _js
19
+ from ._js import Json
20
+
21
+ _TEXT = "text/plain;charset=UTF-8"
22
+ _STANDARD_METHODS = frozenset({"DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"})
23
+
24
+
25
+ class Headers:
26
+ """Case-insensitive HTTP headers. Iteration yields lowercased names in name order.
27
+
28
+ >>> headers = Headers({"Content-Type": "text/plain"})
29
+ >>> headers.get("content-type"), list(headers)
30
+ ('text/plain', ['content-type'])
31
+ """
32
+
33
+ def __init__(
34
+ self, init: Headers | MappingABC[str, str] | Iterable[tuple[str, str]] | None = None
35
+ ) -> None:
36
+ """Creates headers from a mapping, pairs, or other headers."""
37
+ self._values: dict[str, str] = {}
38
+ if init is None:
39
+ return
40
+ mapping = isinstance(init, (Headers, MappingABC))
41
+ pairs = cast("Headers | MappingABC[str, str]", init).items() if mapping else init
42
+ for name, value in pairs:
43
+ self.append(name, value)
44
+
45
+ def get(self, name: str) -> str | None:
46
+ """Returns a header value, or `None` when absent."""
47
+ return self._values.get(name.lower())
48
+
49
+ def set(self, name: str, value: str) -> None:
50
+ """Sets a header, replacing earlier values."""
51
+ self._values[name.lower()] = value.strip()
52
+
53
+ def append(self, name: str, value: str) -> None:
54
+ """Adds a value, joining it to an existing one with `, `."""
55
+ key = name.lower()
56
+ current = self._values.get(key)
57
+ self._values[key] = value.strip() if current is None else f"{current}, {value.strip()}"
58
+
59
+ def delete(self, name: str) -> None:
60
+ """Removes a header."""
61
+ self._values.pop(name.lower(), None)
62
+
63
+ def __contains__(self, name: object) -> bool:
64
+ return isinstance(name, str) and name.lower() in self._values
65
+
66
+ def __iter__(self) -> Iterator[str]:
67
+ return iter(sorted(self._values))
68
+
69
+ def items(self) -> list[tuple[str, str]]:
70
+ """Returns `(name, value)` pairs in name order."""
71
+ return [(name, self._values[name]) for name in self]
72
+
73
+ def __repr__(self) -> str:
74
+ return f"Headers({dict(self.items())!r})"
75
+
76
+
77
+ def _body_bytes(body: bytes | str | None, headers: Headers) -> bytes:
78
+ """Encodes a body, defaulting a text body's content type as the Fetch API does."""
79
+ if isinstance(body, str):
80
+ if "content-type" not in headers:
81
+ headers.set("content-type", _TEXT)
82
+ return body.encode()
83
+ return body or b""
84
+
85
+
86
+ class Request:
87
+ """An HTTP request, as a fetch handler or `Cli.fetch` receives it.
88
+
89
+ >>> request = Request("http://localhost/users?limit=2", method="post", body="hi")
90
+ >>> request.method, request.path, request.query, request.headers.get("content-type")
91
+ ('POST', '/users', {'limit': '2'}, 'text/plain;charset=UTF-8')
92
+ """
93
+
94
+ def __init__(
95
+ self,
96
+ url: str,
97
+ *,
98
+ method: str = "GET",
99
+ headers: Headers | MappingABC[str, str] | Iterable[tuple[str, str]] | None = None,
100
+ body: bytes | str | None = None,
101
+ ) -> None:
102
+ """Creates a request.
103
+
104
+ Args:
105
+ url: The absolute URL.
106
+ method: The HTTP method. Standard methods are uppercased.
107
+ headers: Request headers.
108
+ body: The body. Text without a `content-type` is sent as `text/plain;charset=UTF-8`.
109
+ """
110
+ self.url = normalize_url(url)
111
+ """The absolute URL."""
112
+ upper = method.upper()
113
+ self.method = upper if upper in _STANDARD_METHODS else method
114
+ """The HTTP method."""
115
+ self.headers = Headers(headers)
116
+ """The request headers."""
117
+ self.body = _body_bytes(body, self.headers)
118
+ """The body bytes."""
119
+
120
+ @property
121
+ def path(self) -> str:
122
+ """The URL path."""
123
+ return urllib.parse.urlsplit(self.url).path or "/"
124
+
125
+ @property
126
+ def query(self) -> dict[str, str]:
127
+ """The query parameters. A repeated name keeps its last value."""
128
+ return dict(search_params(urllib.parse.urlsplit(self.url).query))
129
+
130
+ def text(self) -> str:
131
+ """Returns the body as text."""
132
+ return self.body.decode("utf-8", "replace")
133
+
134
+ def json(self) -> Json:
135
+ """Parses the body as JSON. Raises `ValueError` when it is not JSON."""
136
+ return parse_json(self.text())
137
+
138
+ def __repr__(self) -> str:
139
+ return f"Request({self.method} {self.url})"
140
+
141
+
142
+ class Response:
143
+ """An HTTP response, as a fetch handler or `Cli.fetch` returns it.
144
+
145
+ The body is bytes, text, or an async iterable of byte chunks for streamed responses.
146
+
147
+ >>> import asyncio
148
+ >>> response = Response.json({"ok": True}, status=201)
149
+ >>> response.status, response.headers.get("content-type"), asyncio.run(response.text())
150
+ (201, 'application/json', '{"ok":true}')
151
+ """
152
+
153
+ def __init__(
154
+ self,
155
+ body: bytes | str | AsyncIterable[bytes] | None = None,
156
+ *,
157
+ status: int = 200,
158
+ headers: Headers | MappingABC[str, str] | Iterable[tuple[str, str]] | None = None,
159
+ ) -> None:
160
+ """Creates a response.
161
+
162
+ Args:
163
+ body: The body: bytes, text, an async iterable of byte chunks, or `None`.
164
+ status: The HTTP status code.
165
+ headers: Response headers.
166
+ """
167
+ self.status = status
168
+ """The HTTP status code."""
169
+ self.headers = Headers(headers)
170
+ """The response headers."""
171
+ self.body: bytes | AsyncIterable[bytes] = (
172
+ body if isinstance(body, AsyncIterable) else _body_bytes(body, self.headers)
173
+ )
174
+ """The body bytes, or an async iterable of chunks."""
175
+
176
+ @classmethod
177
+ def json(
178
+ cls,
179
+ data: Json,
180
+ *,
181
+ status: int = 200,
182
+ headers: Headers | MappingABC[str, str] | Iterable[tuple[str, str]] | None = None,
183
+ ) -> Response:
184
+ """Creates a JSON response, serialized as `JSON.stringify` does."""
185
+ response = cls(_js.stringify(data).encode(), status=status, headers=headers)
186
+ if "content-type" not in response.headers:
187
+ response.headers.set("content-type", "application/json")
188
+ return response
189
+
190
+ @property
191
+ def ok(self) -> bool:
192
+ """Whether the status is in the 200 range."""
193
+ return 200 <= self.status <= 299
194
+
195
+ async def chunks(self) -> AsyncIterator[bytes]:
196
+ """Yields the body in chunks, as they arrive for a streamed response."""
197
+ body = self.body
198
+ if isinstance(body, bytes):
199
+ if body:
200
+ yield body
201
+ return
202
+ async for chunk in body:
203
+ yield chunk
204
+
205
+ async def read(self) -> bytes:
206
+ """Reads the whole body."""
207
+ return b"".join([chunk async for chunk in self.chunks()])
208
+
209
+ async def text(self) -> str:
210
+ """Reads the body as text."""
211
+ return (await self.read()).decode("utf-8", "replace")
212
+
213
+ def __repr__(self) -> str:
214
+ return f"Response({self.status})"
215
+
216
+
217
+ #: Handles a request and returns a response: a fetch handler, such as an HTTP client or an
218
+ #: in-process application. It may be an `async def` function.
219
+ FetchHandler = Callable[[Request], "Awaitable[Response] | Response"]
220
+
221
+
222
+ async def _urllib_fetch(request: Request) -> Response:
223
+ """Sends a request over the network with `urllib`, in a worker thread."""
224
+
225
+ def send() -> Response:
226
+ outgoing = urllib.request.Request(
227
+ request.url,
228
+ data=request.body or None,
229
+ headers=dict(request.headers.items()),
230
+ method=request.method,
231
+ )
232
+ try:
233
+ with urllib.request.urlopen(outgoing) as reply:
234
+ return Response(reply.read(), status=reply.status, headers=reply.headers.items())
235
+ except urllib.error.HTTPError as error:
236
+ return Response(error.read(), status=error.code, headers=error.headers.items())
237
+ except (urllib.error.URLError, OSError) as error:
238
+ raise TypeError("fetch failed") from error
239
+
240
+ return await asyncio.to_thread(send)
241
+
242
+
243
+ _fetcher: list[FetchHandler] = [_urllib_fetch]
244
+
245
+
246
+ def set_fetch(handler: FetchHandler | None) -> None:
247
+ """Replaces the handler that sends every outgoing request, or restores the network default.
248
+
249
+ Hosted fetch sources, OpenAPI document URLs, remote MCP servers without a handler, and
250
+ update checks send requests through it. Tests use it to route requests to fakes.
251
+ """
252
+ _fetcher[0] = handler or _urllib_fetch
253
+
254
+
255
+ async def fetch(request: Request) -> Response:
256
+ """Sends a request through the outgoing handler that `set_fetch` installed."""
257
+ return await call(_fetcher[0], request)
258
+
259
+
260
+ async def call(handler: FetchHandler, request: Request) -> Response:
261
+ """Calls a fetch handler, awaiting it when it is asynchronous."""
262
+ result = handler(request)
263
+ if isinstance(result, Response):
264
+ return result
265
+ return await result
266
+
267
+
268
+ class RequestSource:
269
+ """A hosted API reached over the network: forwards requests to a base URL.
270
+
271
+ Create it with `incur.from_request`. Its `url` resolves relative OpenAPI document paths.
272
+ """
273
+
274
+ def __init__(self, url: str, headers: MappingABC[str, str] | None = None) -> None:
275
+ """Creates a source that forwards requests under `url` with default `headers`."""
276
+ self.url = normalize_url(url)
277
+ """The base URL."""
278
+ self.headers = dict(headers or {})
279
+ """Headers merged into every forwarded request. Request headers take precedence."""
280
+
281
+ async def __call__(self, request: Request) -> Response:
282
+ """Forwards a request: its path joins the base path, and its query replaces the base's."""
283
+ base = urllib.parse.urlsplit(self.url)
284
+ incoming = urllib.parse.urlsplit(request.url)
285
+ prefix = base.path[:-1] if base.path.endswith("/") else base.path
286
+ suffix = incoming.path if incoming.path.startswith("/") else f"/{incoming.path}"
287
+ target = base._replace(path=f"{prefix}{suffix}" or "/", query=incoming.query, fragment="")
288
+ headers = Headers(self.headers)
289
+ for name, value in request.headers.items():
290
+ headers.set(name, value)
291
+ forwarded = Request(urllib.parse.urlunsplit(target), method=request.method, headers=headers)
292
+ forwarded.body = request.body
293
+ return await fetch(forwarded)
294
+
295
+
296
+ def from_request(url: str, *, headers: MappingABC[str, str] | None = None) -> RequestSource:
297
+ """Creates a hosted fetch source that forwards requests under a base URL.
298
+
299
+ >>> source = from_request("https://api.example.com/v1/", headers={"authorization": "Bearer t"})
300
+ >>> source.url
301
+ 'https://api.example.com/v1/'
302
+ """
303
+ return RequestSource(url, headers)
304
+
305
+
306
+ def normalize_url(url: str) -> str:
307
+ """Normalizes an absolute URL as the WHATWG URL parser does for common inputs."""
308
+ parts = urllib.parse.urlsplit(url)
309
+ scheme = parts.scheme.lower()
310
+ netloc = parts.netloc.lower()
311
+ path = parts.path or ("/" if scheme in ("http", "https") else "")
312
+ path = urllib.parse.quote(path, safe="/%:@!$&'()*+,;=-._~")
313
+ query = urllib.parse.quote(parts.query, safe="/%:@!$&'()*+,;=-._~?")
314
+ return urllib.parse.urlunsplit((scheme, netloc, path, query, parts.fragment))
315
+
316
+
317
+ def join_url(base: str, reference: str) -> str:
318
+ """Resolves a URL reference against a base URL."""
319
+ return normalize_url(urllib.parse.urljoin(base, reference))
320
+
321
+
322
+ def origin(url: str) -> str:
323
+ """Returns the origin of a URL: scheme, host, and port."""
324
+ parts = urllib.parse.urlsplit(url)
325
+ return f"{parts.scheme}://{parts.netloc}"
326
+
327
+
328
+ def search_params(query: str) -> list[tuple[str, str]]:
329
+ """Parses a query string as `URLSearchParams` does."""
330
+ return urllib.parse.parse_qsl(query, keep_blank_values=True)
331
+
332
+
333
+ def encode_params(params: Iterable[tuple[str, str]]) -> str:
334
+ """Serializes query parameters as `URLSearchParams.toString()` does."""
335
+
336
+ def encode(text: str) -> str:
337
+ return urllib.parse.quote_plus(text, safe="*").replace("~", "%7E")
338
+
339
+ return "&".join(f"{encode(key)}={encode(value)}" for key, value in params)
340
+
341
+
342
+ def parse_json(text: str) -> Json:
343
+ """Parses JSON text as `JSON.parse` does. Raises `ValueError` when it is not JSON."""
344
+ if _js.json_parse_error(text) is not None:
345
+ raise ValueError(text)
346
+ return _js.parse_json(text)
347
+
348
+
349
+ def asgi(handler: Callable[[Request], Awaitable[Response]]) -> Any:
350
+ """Wraps a fetch handler as an ASGI 3 HTTP application."""
351
+
352
+ async def app(scope: dict[str, Any], receive: Any, send: Any) -> None:
353
+ if scope["type"] == "lifespan":
354
+ while True:
355
+ message = await receive()
356
+ if message["type"] == "lifespan.startup":
357
+ await send({"type": "lifespan.startup.complete"})
358
+ else:
359
+ await send({"type": "lifespan.shutdown.complete"})
360
+ return
361
+ body = b""
362
+ while True:
363
+ message = await receive()
364
+ body += message.get("body", b"")
365
+ if not message.get("more_body"):
366
+ break
367
+ headers = [(k.decode("latin-1"), v.decode("latin-1")) for k, v in scope["headers"]]
368
+ host = next((v for k, v in headers if k.lower() == "host"), None)
369
+ if host is None:
370
+ server = scope.get("server") or ("localhost", None)
371
+ host = server[0] if server[1] in (None, 80, 443) else f"{server[0]}:{server[1]}"
372
+ path = scope.get("raw_path", b"").decode("latin-1") or urllib.parse.quote(scope["path"])
373
+ query = scope.get("query_string", b"").decode("latin-1")
374
+ url = f"{scope.get('scheme', 'http')}://{host}{path}" + (f"?{query}" if query else "")
375
+ request = Request(url, method=scope["method"], headers=headers)
376
+ request.body = body
377
+ response = await handler(request)
378
+ await send(
379
+ {
380
+ "type": "http.response.start",
381
+ "status": response.status,
382
+ "headers": [(k.encode(), v.encode()) for k, v in response.headers.items()],
383
+ }
384
+ )
385
+ async for chunk in response.chunks():
386
+ await send({"type": "http.response.body", "body": chunk, "more_body": True})
387
+ await send({"type": "http.response.body", "body": b""})
388
+
389
+ return app