Skip to content

Commit 7fde234

Browse files
committed
Merge scalar-generated into scalar-next (build zBoiJoMbfsMlvkisWlpUb)
2 parents c3aacf0 + 6110007 commit 7fde234

40 files changed

Lines changed: 1555 additions & 1859 deletions

‎.github/workflows/sdk-ci.yml‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,5 +23,10 @@ jobs:
2323
# Verification only, never auto-fix: the SDK is generated formatted, so a diff here means
2424
# either hand-edited custom code or a regenerate that was not committed. ruff is pinned to
2525
# the release that produced these bytes, since a formatter minor can change them.
26-
- run: python -m pip install "ruff==0.16.8"
26+
- run: python -m pip install "ruff==0.17.4"
2727
- run: ruff format --check .
28+
# The smoke tests skip unless TEST_API_BASE_URL is set, so this only proves every test module
29+
# imports against the installed SDK; it never calls the API.
30+
- run: python -m pip install --upgrade pip
31+
- run: python -m pip install . --group dev
32+
- run: python -m pytest

‎api.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1251,7 +1251,7 @@ SDKs
12511251

12521252
### List all SDKs
12531253

1254-
List every SDK on the team with the languages its config declares, each with its version labels highest first, the current version label per language (`current`), and the `currentVersion` and `latestVersion` tags.
1254+
List every SDK on the team. `targets` are the languages its config declares, which the next build builds. `current` (the version label per language a request without a version serves) and each version label’s `languages`, highest label first, are what is served, and can include a language a later config dropped: a version keeps the languages its builds produced. Also returns the `currentVersion` and `latestVersion` tags.
12551255

12561256
| Direction | Type |
12571257
| --- | --- |
@@ -1280,7 +1280,7 @@ sdk = client.sdks.create(
12801280

12811281
### Get an SDK
12821282

1283-
Get a single SDK by its uid with the languages its config declares, its version labels highest first, the current version label per language (`current`), and the `currentVersion` and `latestVersion` tags.
1283+
Get a single SDK by its uid. `targets` are the languages its config declares, which the next build builds. `current` (the version label per language a request without a version serves) and each version label’s `languages`, highest label first, are what is served, and can include a language a later config dropped: a version keeps the languages its builds produced. Also returns the `currentVersion` and `latestVersion` tags.
12841284

12851285
| Direction | Type |
12861286
| --- | --- |

‎pyproject.toml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ Changelog = "https://github.com/scalar/scalar-python/blob/main/CHANGELOG.md"
2424
[project.optional-dependencies]
2525
aiohttp = ["aiohttp", "httpx_aiohttp>=0.1.9"]
2626

27+
[dependency-groups]
28+
dev = ["pytest>=8.3.4"]
29+
2730
[build-system]
2831
requires = ["hatchling>=1.18.0"]
2932
build-backend = "hatchling.build"
@@ -33,3 +36,6 @@ packages = ["src/scalar_sdk"]
3336

3437
[tool.ruff]
3538
line-length = 120
39+
40+
[tool.pytest.ini_options]
41+
testpaths = ["tests"]

‎scalar-sdk.manifest.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "Scalar",
33
"slug": "scalar",
4-
"generatorVersion": "0.38.0",
4+
"generatorVersion": "0.42.1",
55
"servers": [
66
"https://access.scalar.com"
77
],

‎src/scalar_sdk/_base_client.py‎

Lines changed: 107 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import platform
1313
import warnings
1414
import email.utils
15+
from urllib.parse import urlencode
1516
from types import TracebackType
1617
from random import random
1718
from dataclasses import field, dataclass
@@ -44,7 +45,7 @@
4445
from . import _exceptions
4546
from ._qs import Querystring
4647
from ._decoding import CodingRefused, BoundedDecoder, decoding_error
47-
from ._files import to_httpx_files, async_to_httpx_files
48+
from ._files import to_httpx_files, read_form_files, async_to_httpx_files, async_read_form_files
4849
from ._types import (
4950
Body,
5051
Omit,
@@ -320,6 +321,59 @@ def _merge_set_cookies(headers: httpx.Headers, response: httpx.Response, target:
320321
headers["Cookie"] = "; ".join(pairs.values())
321322

322323

324+
_FORM_URLENCODED = "application/x-www-form-urlencoded"
325+
326+
327+
def _is_form_urlencoded(content_type: object) -> bool:
328+
"""Whether a `Content-Type` names the form media type, in any casing and with any parameters."""
329+
return isinstance(content_type, str) and content_type.split(";", 1)[0].strip().lower() == _FORM_URLENCODED
330+
331+
332+
def _options_content_type(options: FinalRequestOptions) -> str | None:
333+
"""The `Content-Type` a request's own headers set, matched case-insensitively, if any.
334+
335+
The last match wins, as it does when `_build_request` collapses duplicate entries, so both agree
336+
on whether a request is a form.
337+
"""
338+
if not is_given(options.headers):
339+
return None
340+
content_type: str | None = None
341+
for name, value in options.headers.items():
342+
if name.lower() == "content-type" and isinstance(value, str):
343+
content_type = value
344+
return content_type
345+
346+
347+
def _form_text(value: object, array_format: str) -> object:
348+
"""A form body prepared for the query encoder.
349+
350+
Each bytes value is decoded with `surrogateescape`: `Querystring` renders a leaf with `str()`,
351+
which spells bytes as `b'...'`, and encoding the pairs back with the same error handler keeps
352+
every byte as it was. An empty list is dropped, since `comma` would otherwise send `key=`, which a
353+
server reads as one empty element. Under `comma` a list holding objects or lists is refused: the
354+
format joins items with `str()`, so they would go out as Python repr.
355+
"""
356+
if isinstance(value, (bytes, bytearray)):
357+
return bytes(value).decode("utf-8", "surrogateescape")
358+
if is_mapping(value):
359+
return {
360+
key: _form_text(item, array_format)
361+
for key, item in value.items()
362+
if not ((is_list(item) or isinstance(item, tuple)) and len(cast("list[object]", item)) == 0)
363+
}
364+
if is_list(value) or isinstance(value, tuple):
365+
items = cast("list[object]", value)
366+
if array_format == "comma" and any(
367+
is_mapping(item) or is_list(item) or isinstance(item, tuple) for item in items
368+
):
369+
raise TypeError(
370+
"A list of objects or lists cannot be sent in a form body under `arrayFormat: comma`;"
371+
" use `brackets`, `indices` or `repeat`."
372+
)
373+
return [_form_text(item, array_format) for item in items]
374+
return value
375+
376+
323377
def _describe_body(value: object) -> str:
324378
"""A request body as the debug log shows it: its shape and size, never its values.
325379
@@ -1151,9 +1205,33 @@ def _build_request(
11511205
params = _merge_mappings({**self._auth_query(options.security), **self.default_query}, options.params)
11521206
cookies = self._auth_cookies(options.security)
11531207
headers = self._build_headers(options, retries_taken=retries_taken, params=params, cookies=cookies)
1208+
content_types = headers.get_list("Content-Type")
1209+
if len(content_types) > 1:
1210+
# A `Content-Type` spelled in another casing than an earlier one is a second entry rather
1211+
# than a replacement, and two entries would join into a value neither encoder recognizes.
1212+
# The request's own headers (the method's, then the caller's `extra_headers`) win over a
1213+
# client-wide default, the same value `request()` read file fields for.
1214+
own_content_type = _options_content_type(options)
1215+
headers["Content-Type"] = own_content_type if own_content_type is not None else content_types[-1]
11541216
content_type = headers.get("Content-Type")
11551217
files = options.files
11561218

1219+
# A body under the form media type, in any casing, goes out encoded the way the query string
1220+
# is, through the client's own `qs`. A string or bytes body is a form already encoded and is
1221+
# sent as it is.
1222+
if _is_form_urlencoded(content_type) and json_data is not None and is_given(json_data):
1223+
if files:
1224+
# httpx sends `content` and drops `files` silently, so file parts would never arrive
1225+
raise TypeError("A form-urlencoded request body cannot carry multipart files")
1226+
if isinstance(json_data, str):
1227+
json_data = json_data.encode("utf-8")
1228+
elif not isinstance(json_data, bytes):
1229+
if not is_mapping(json_data):
1230+
raise TypeError(
1231+
f"Expected a mapping for a form-urlencoded request body but got {type(json_data)} instead."
1232+
)
1233+
json_data = self._serialize_form_urlencoded(json_data)
1234+
11571235
# If the given Content-Type header is multipart/form-data then it
11581236
# has to be removed so that httpx can generate the header with
11591237
# additional information for us as it has to be in this form
@@ -1227,12 +1305,29 @@ def _build_request(
12271305
**kwargs,
12281306
)
12291307

1308+
def _serialize_form_urlencoded(self, data: Mapping[str, object]) -> bytes:
1309+
"""Encodes a form-urlencoded body exactly as the query string is encoded.
1310+
1311+
Lists follow the client's `array_format` and object keys its `nested_format`, and a boolean
1312+
goes out as `true` / `false`, all from `self.qs`. A space is written `+`, the form convention.
1313+
An empty string goes out as `key=`, which the query string drops, so a field can be cleared;
1314+
only `None` is left out.
1315+
A bytes value (a file field's contents, by now) is decoded with `surrogateescape` and encoded
1316+
back the same way, so bytes that are not UTF-8 reach the wire unchanged rather than as the
1317+
`b'...'` spelling `str()` would give them.
1318+
"""
1319+
qs = self.qs
1320+
items = qs.stringify_items(cast(Mapping[str, Any], _form_text(data, qs.array_format)), keep_empty=True)
1321+
return urlencode(items, encoding="utf-8", errors="surrogateescape").encode("ascii")
1322+
12301323
def _serialize_multipartform(self, data: Mapping[object, object]) -> dict[str, object]:
12311324
items = self.qs.stringify_items(
12321325
# TODO: type ignore is required as stringify_items is well typed but we can't be
12331326
# well typed without heavy validation.
12341327
data, # type: ignore
12351328
array_format="brackets",
1329+
# multipart part names keep their bracketed form whatever the query string's nesting is
1330+
nested_format="brackets",
12361331
)
12371332
serialized: dict[str, object] = {}
12381333
for key, value in items:
@@ -1348,7 +1443,9 @@ def _validate_headers(
13481443

13491444
@property
13501445
def user_agent(self) -> str:
1351-
return f"{self.__class__.__name__}/Python {self._version}"
1446+
# A literal rather than `self.__class__.__name__`, so the sync and async clients send the
1447+
# same product and a subclass cannot change it.
1448+
return f"Scalar/Python {self._version}"
13521449

13531450
@property
13541451
def base_url(self) -> URL:
@@ -1676,6 +1773,10 @@ def request(
16761773
if input_options.idempotency_key is None and input_options.method.lower() != "get":
16771774
# ensure the idempotency key is reused between requests
16781775
input_options.idempotency_key = self._idempotency_key()
1776+
if _is_form_urlencoded(_options_content_type(input_options)):
1777+
# read file fields once, so every attempt sends the same contents
1778+
input_options.json_data = read_form_files(input_options.json_data)
1779+
input_options.extra_json = read_form_files(input_options.extra_json)
16791780

16801781
response: httpx.Response | None = None
16811782
max_retries = input_options.get_max_retries(self.max_retries)
@@ -2315,6 +2416,10 @@ async def request(
23152416
if input_options.idempotency_key is None and input_options.method.lower() != "get":
23162417
# ensure the idempotency key is reused between requests
23172418
input_options.idempotency_key = self._idempotency_key()
2419+
if _is_form_urlencoded(_options_content_type(input_options)):
2420+
# read file fields once, so every attempt sends the same contents
2421+
input_options.json_data = await async_read_form_files(input_options.json_data)
2422+
input_options.extra_json = await async_read_form_files(input_options.extra_json)
23182423

23192424
response: httpx.Response | None = None
23202425
max_retries = input_options.get_max_retries(self.max_retries)

‎src/scalar_sdk/_files.py‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import io
44
import os
5+
import inspect
56
import pathlib
67
from typing import Sequence, cast, overload
78
from typing_extensions import TypeVar, TypeGuard
@@ -125,6 +126,100 @@ async def async_read_file_content(file: FileContent) -> HttpxFileContent:
125126
return file
126127

127128

129+
def _is_form_file(obj: object) -> bool:
130+
"""Whether a value in a form-urlencoded body is a file whose contents the field carries.
131+
132+
Bytes, a file object and a path are files. A file object is anything with a callable `read`, not
133+
only an `io.IOBase`: `IO[bytes]` admits wrappers that are not one (`SpooledTemporaryFile` before
134+
Python 3.11, framework upload objects, whose `read()` may be async), and an unrecognized one
135+
would reach the query encoder's `str()` and go out as its repr. A tuple is one only in the `(filename, content, ...)` shape
136+
`FileTypes` allows, so a tuple of strings stays the list the query encoder reads it as.
137+
"""
138+
if _is_form_file_content(obj):
139+
return True
140+
return (
141+
isinstance(obj, tuple)
142+
and 2 <= len(cast("tuple[object, ...]", obj)) <= 4
143+
and (obj[0] is None or isinstance(obj[0], str))
144+
and _is_form_file_content(obj[1])
145+
)
146+
147+
148+
def _is_form_file_content(obj: object) -> bool:
149+
"""Whether a value is file content: bytes, a path, or an object with a callable `read`."""
150+
return isinstance(obj, (bytes, bytearray, os.PathLike)) or callable(getattr(obj, "read", None))
151+
152+
153+
def _form_file_source(obj: object) -> object:
154+
"""The content half of a form file value: the tuple's second item, or the value itself."""
155+
return cast("tuple[object, ...]", obj)[1] if isinstance(obj, tuple) else obj
156+
157+
158+
def _checked_form_contents(source: object, contents: object) -> object:
159+
"""A file object's `read()` result, refused unless it is bytes or text.
160+
161+
Anything else would reach the query encoder's `str()` and go out as its repr.
162+
"""
163+
if isinstance(contents, (bytes, bytearray, str)):
164+
return contents
165+
raise TypeError(f"Expected {type(source).__name__}.read() to return bytes or str but got {type(contents)} instead.")
166+
167+
168+
def read_form_files(data: _T) -> _T:
169+
"""Returns a form-urlencoded body with every file value replaced by its contents.
170+
171+
A form has no file parts, so a file field goes out as its contents, the way a string field would.
172+
A file object is read whole from its current position and a path from the start, with no size
173+
bound, which suits form fields but not large files; those belong in a multipart body. It runs
174+
once per call rather than per attempt, so a retry resends the same bytes instead of an exhausted
175+
file object's empty read. Every container is copied, so the caller's own body is left as it was.
176+
"""
177+
if _is_form_file(data):
178+
source = _form_file_source(data)
179+
if isinstance(source, os.PathLike):
180+
return cast(_T, pathlib.Path(cast("os.PathLike[str]", source)).read_bytes())
181+
if isinstance(source, (bytes, bytearray)):
182+
return cast(_T, bytes(source))
183+
contents: object = cast("io.BufferedIOBase", source).read()
184+
if inspect.isawaitable(contents):
185+
# an async `read()` (an ASGI upload object) cannot be awaited here; close it unawaited
186+
# rather than leave a warning, and point the caller at the client that can
187+
if inspect.iscoroutine(contents):
188+
contents.close()
189+
raise TypeError(
190+
f"{type(source).__name__}.read() is asynchronous; send it through the async client, or pass its bytes"
191+
)
192+
return cast(_T, _checked_form_contents(source, contents))
193+
if is_mapping(data):
194+
return cast(_T, {key: read_form_files(value) for key, value in data.items()})
195+
if is_list(data) or isinstance(data, tuple):
196+
return cast(_T, [read_form_files(item) for item in cast("Sequence[object]", data)])
197+
return data
198+
199+
200+
async def async_read_form_files(data: _T) -> _T:
201+
"""`read_form_files` for an async client.
202+
203+
It reads a path without blocking the event loop, and awaits a file object whose `read()` is
204+
asynchronous, as an ASGI framework's upload object's is.
205+
"""
206+
if _is_form_file(data):
207+
source = _form_file_source(data)
208+
if isinstance(source, os.PathLike):
209+
return cast(_T, await anyio.Path(cast("os.PathLike[str]", source)).read_bytes())
210+
if isinstance(source, (bytes, bytearray)):
211+
return cast(_T, bytes(source))
212+
contents: object = cast("io.BufferedIOBase", source).read()
213+
if inspect.isawaitable(contents):
214+
contents = await contents
215+
return cast(_T, _checked_form_contents(source, contents))
216+
if is_mapping(data):
217+
return cast(_T, {key: await async_read_form_files(value) for key, value in data.items()})
218+
if is_list(data) or isinstance(data, tuple):
219+
return cast(_T, [await async_read_form_files(item) for item in cast("Sequence[object]", data)])
220+
return data
221+
222+
128223
def deepcopy_with_paths(item: _T, paths: Sequence[Sequence[str]]) -> _T:
129224
"""Copy only the containers along the given paths.
130225

‎src/scalar_sdk/_qs.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,19 @@ def stringify_items(
5454
*,
5555
array_format: ArrayFormat | NotGiven = not_given,
5656
nested_format: NestedFormat | NotGiven = not_given,
57+
keep_empty: bool = False,
5758
) -> list[tuple[str, str]]:
59+
"""Flattens params into `(key, value)` pairs.
60+
61+
An empty-string value is dropped unless `keep_empty` is set: a query string has always left
62+
it out, while a form body sends it as `key=` so a field can be cleared. `None` is always
63+
dropped.
64+
"""
5865
opts = Options(
5966
qs=self,
6067
array_format=array_format,
6168
nested_format=nested_format,
69+
keep_empty=keep_empty,
6270
)
6371
return flatten([self._stringify_item(key, value, opts) for key, value in params.items()])
6472

@@ -113,7 +121,7 @@ def _stringify_item(
113121
)
114122

115123
serialised = self._primitive_value_to_str(value)
116-
if not serialised:
124+
if not serialised and (value is None or not opts.keep_empty):
117125
return []
118126
return [(key, serialised)]
119127

@@ -135,13 +143,16 @@ def _primitive_value_to_str(self, value: PrimitiveData) -> str:
135143
class Options:
136144
array_format: ArrayFormat
137145
nested_format: NestedFormat
146+
keep_empty: bool
138147

139148
def __init__(
140149
self,
141150
qs: Querystring = _qs,
142151
*,
143152
array_format: ArrayFormat | NotGiven = not_given,
144153
nested_format: NestedFormat | NotGiven = not_given,
154+
keep_empty: bool = False,
145155
) -> None:
146156
self.array_format = qs.array_format if isinstance(array_format, NotGiven) else array_format
147157
self.nested_format = qs.nested_format if isinstance(nested_format, NotGiven) else nested_format
158+
self.keep_empty = keep_empty

‎src/scalar_sdk/_utils/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
get_required_header as get_required_header,
3030
maybe_coerce_boolean as maybe_coerce_boolean,
3131
maybe_coerce_integer as maybe_coerce_integer,
32+
merge_default_headers as merge_default_headers,
3233
)
3334
from ._compat import (
3435
get_args as get_args,

0 commit comments

Comments
 (0)