ourseams-sdk 0.1.0__tar.gz
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.
- ourseams_sdk-0.1.0/.gitignore +23 -0
- ourseams_sdk-0.1.0/LICENSE +21 -0
- ourseams_sdk-0.1.0/PKG-INFO +60 -0
- ourseams_sdk-0.1.0/README.md +48 -0
- ourseams_sdk-0.1.0/pyproject.toml +47 -0
- ourseams_sdk-0.1.0/scripts/_emit.py +73 -0
- ourseams_sdk-0.1.0/scripts/_hints.py +54 -0
- ourseams_sdk-0.1.0/scripts/_resolve.py +40 -0
- ourseams_sdk-0.1.0/scripts/_shape.py +132 -0
- ourseams_sdk-0.1.0/scripts/generate.py +73 -0
- ourseams_sdk-0.1.0/src/seams/__init__.py +55 -0
- ourseams_sdk-0.1.0/src/seams/_generated/__init__.py +0 -0
- ourseams_sdk-0.1.0/src/seams/_generated/client.py +1205 -0
- ourseams_sdk-0.1.0/src/seams/_generated/models.py +1240 -0
- ourseams_sdk-0.1.0/src/seams/_transport.py +120 -0
- ourseams_sdk-0.1.0/src/seams/py.typed +0 -0
- ourseams_sdk-0.1.0/tests/test_client.py +187 -0
- ourseams_sdk-0.1.0/uv.lock +1084 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
.venv
|
|
2
|
+
.gstack/
|
|
3
|
+
.cursor/
|
|
4
|
+
.claude/
|
|
5
|
+
|
|
6
|
+
node_modules/
|
|
7
|
+
.pnpm-store/
|
|
8
|
+
dist/
|
|
9
|
+
.turbo/
|
|
10
|
+
.env*
|
|
11
|
+
!.env.example
|
|
12
|
+
!.env*.example
|
|
13
|
+
.next/
|
|
14
|
+
out/
|
|
15
|
+
next-env.d.ts
|
|
16
|
+
|
|
17
|
+
# the static export of apps/landing; built by `next build`, deployed by wrangler
|
|
18
|
+
out/
|
|
19
|
+
*.tsbuildinfo
|
|
20
|
+
__pycache__/
|
|
21
|
+
.pytest_cache/
|
|
22
|
+
.ruff_cache/
|
|
23
|
+
.mypy_cache/
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Seams
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: ourseams-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: The typed Python client for the seams control plane, generated from its OpenAPI document.
|
|
5
|
+
Project-URL: Homepage, https://ourseams.com
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Requires-Dist: httpx<1,>=0.27
|
|
10
|
+
Requires-Dist: pydantic<3,>=2.7
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# seams
|
|
14
|
+
|
|
15
|
+
The typed Python client for the seams control plane. **Generated from the OpenAPI document**, which is
|
|
16
|
+
emitted from the API's route table — so it cannot describe a shape the API does not serve, and it stays
|
|
17
|
+
in step with `@ourseams/sdk`.
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
import os
|
|
21
|
+
from seams import Seams
|
|
22
|
+
|
|
23
|
+
seams = Seams(api_key=os.environ["SEAMS_SECRET_KEY"])
|
|
24
|
+
|
|
25
|
+
seams.users.create("alice", models.CreateEndUserRequest(email="alice@firm.com"))
|
|
26
|
+
key = seams.keys.mint(models.MintKeyRequest(end_user_id="alice", bundle="pro"))
|
|
27
|
+
print(key.key)
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## One namespace per CLI command group
|
|
31
|
+
|
|
32
|
+
`operationId` carries the CLI's own verb, so the method reads like the command:
|
|
33
|
+
|
|
34
|
+
```text
|
|
35
|
+
seams models add smart … → seams.models.add("smart", …)
|
|
36
|
+
seams bundles price pro fast … → seams.bundles.price("pro", …)
|
|
37
|
+
seams outcomes runs → seams.outcomes.runs()
|
|
38
|
+
seams usage --by model → seams.usage(by="model")
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Top-level commands stay top-level: `usage`, `margin`, `audit`, `doctor`, `capabilities`. Routes the API
|
|
42
|
+
serves but does not offer a client carry `x-seams-internal: true` and get no method.
|
|
43
|
+
|
|
44
|
+
## Sync and async
|
|
45
|
+
|
|
46
|
+
`Seams` and `AsyncSeams` are generated from the same document and carry the same 76 methods.
|
|
47
|
+
|
|
48
|
+
## Two runtime dependencies
|
|
49
|
+
|
|
50
|
+
`httpx` for the transport and `pydantic` for the models. Field names are Python's — `end_users`, not
|
|
51
|
+
`endUsers` — with the wire name kept as an alias.
|
|
52
|
+
|
|
53
|
+
## Regenerating
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
uv run python scripts/generate.py # models and facade
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
`src/seams/_generated/` is written by the generator. Do not edit it. The document it reads,
|
|
60
|
+
`../openapi.json`, is emitted by [the TypeScript client](../typescript) from the API's route table.
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# seams
|
|
2
|
+
|
|
3
|
+
The typed Python client for the seams control plane. **Generated from the OpenAPI document**, which is
|
|
4
|
+
emitted from the API's route table — so it cannot describe a shape the API does not serve, and it stays
|
|
5
|
+
in step with `@ourseams/sdk`.
|
|
6
|
+
|
|
7
|
+
```python
|
|
8
|
+
import os
|
|
9
|
+
from seams import Seams
|
|
10
|
+
|
|
11
|
+
seams = Seams(api_key=os.environ["SEAMS_SECRET_KEY"])
|
|
12
|
+
|
|
13
|
+
seams.users.create("alice", models.CreateEndUserRequest(email="alice@firm.com"))
|
|
14
|
+
key = seams.keys.mint(models.MintKeyRequest(end_user_id="alice", bundle="pro"))
|
|
15
|
+
print(key.key)
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## One namespace per CLI command group
|
|
19
|
+
|
|
20
|
+
`operationId` carries the CLI's own verb, so the method reads like the command:
|
|
21
|
+
|
|
22
|
+
```text
|
|
23
|
+
seams models add smart … → seams.models.add("smart", …)
|
|
24
|
+
seams bundles price pro fast … → seams.bundles.price("pro", …)
|
|
25
|
+
seams outcomes runs → seams.outcomes.runs()
|
|
26
|
+
seams usage --by model → seams.usage(by="model")
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Top-level commands stay top-level: `usage`, `margin`, `audit`, `doctor`, `capabilities`. Routes the API
|
|
30
|
+
serves but does not offer a client carry `x-seams-internal: true` and get no method.
|
|
31
|
+
|
|
32
|
+
## Sync and async
|
|
33
|
+
|
|
34
|
+
`Seams` and `AsyncSeams` are generated from the same document and carry the same 76 methods.
|
|
35
|
+
|
|
36
|
+
## Two runtime dependencies
|
|
37
|
+
|
|
38
|
+
`httpx` for the transport and `pydantic` for the models. Field names are Python's — `end_users`, not
|
|
39
|
+
`endUsers` — with the wire name kept as an alias.
|
|
40
|
+
|
|
41
|
+
## Regenerating
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
uv run python scripts/generate.py # models and facade
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
`src/seams/_generated/` is written by the generator. Do not edit it. The document it reads,
|
|
48
|
+
`../openapi.json`, is emitted by [the TypeScript client](../typescript) from the API's route table.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "ourseams-sdk"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "The typed Python client for the seams control plane, generated from its OpenAPI document."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
dependencies = ["httpx>=0.27,<1", "pydantic>=2.7,<3"]
|
|
10
|
+
|
|
11
|
+
[project.urls]
|
|
12
|
+
Homepage = "https://ourseams.com"
|
|
13
|
+
|
|
14
|
+
[dependency-groups]
|
|
15
|
+
dev = [
|
|
16
|
+
"datamodel-code-generator>=0.25",
|
|
17
|
+
"pytest>=8",
|
|
18
|
+
"respx>=0.21",
|
|
19
|
+
"ruff>=0.6",
|
|
20
|
+
"mypy>=1.11",
|
|
21
|
+
"pytest-asyncio>=1.4.0",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[build-system]
|
|
25
|
+
requires = ["hatchling"]
|
|
26
|
+
build-backend = "hatchling.build"
|
|
27
|
+
|
|
28
|
+
[tool.hatch.build.targets.wheel]
|
|
29
|
+
packages = ["src/seams"]
|
|
30
|
+
|
|
31
|
+
[tool.ruff]
|
|
32
|
+
line-length = 100
|
|
33
|
+
target-version = "py310"
|
|
34
|
+
extend-exclude = ["src/seams/_generated"]
|
|
35
|
+
|
|
36
|
+
[tool.ruff.lint]
|
|
37
|
+
# typing.Self is 3.11; the floor here is 3.10, and neither client is meant to be subclassed.
|
|
38
|
+
ignore = ["PYI034"]
|
|
39
|
+
|
|
40
|
+
[tool.mypy]
|
|
41
|
+
python_version = "3.10"
|
|
42
|
+
strict = true
|
|
43
|
+
exclude = "src/seams/_generated"
|
|
44
|
+
|
|
45
|
+
[tool.pytest.ini_options]
|
|
46
|
+
testpaths = ["tests"]
|
|
47
|
+
asyncio_mode = "auto"
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Emits the facade: one class per CLI command group, sync and async."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from _shape import Group, Method, pascal
|
|
6
|
+
|
|
7
|
+
HEADER = """# generated by scripts/generate.py — do not edit.
|
|
8
|
+
# namespaces and verbs come from operationId, so seams models add reads as models.add().
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import NoReturn
|
|
13
|
+
|
|
14
|
+
from . import models as _models
|
|
15
|
+
from .._transport import AsyncTransport, Transport
|
|
16
|
+
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _body(method: Method, prefix: str, wait: str) -> str:
|
|
21
|
+
if method.result is None:
|
|
22
|
+
return f'{prefix}self._t.unbuilt("{method.verb}", {method.url})'
|
|
23
|
+
call = f'self._t.send("{method.verb}", {method.url}, _models.{method.result}{method.extras})'
|
|
24
|
+
return f"{prefix}{wait}{call}"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _method(method: Method, is_async: bool) -> str:
|
|
28
|
+
keyword = "async def" if is_async else "def"
|
|
29
|
+
wait = "await " if is_async else ""
|
|
30
|
+
hint = "NoReturn" if method.result is None else f"_models.{method.result}"
|
|
31
|
+
lines = [f" {keyword} {method.name}(self{method.signature}) -> {hint}:"]
|
|
32
|
+
if method.summary:
|
|
33
|
+
lines.append(f' """{method.summary}"""')
|
|
34
|
+
lines.append(_body(method, " return " if method.result else " ", wait))
|
|
35
|
+
return "\n".join(lines)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _group(group: Group, is_async: bool) -> str:
|
|
39
|
+
name = ("Async" if is_async else "") + pascal(group.name)
|
|
40
|
+
transport = "AsyncTransport" if is_async else "Transport"
|
|
41
|
+
members = "\n\n".join(_method(method, is_async) for method in group.methods)
|
|
42
|
+
return (
|
|
43
|
+
f"class {name}:\n"
|
|
44
|
+
f" def __init__(self, transport: {transport}) -> None:\n"
|
|
45
|
+
f" self._t = transport\n\n"
|
|
46
|
+
f"{members}\n"
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _surface(groups: list[Group], loose: list[Method], is_async: bool) -> str:
|
|
51
|
+
name = ("Async" if is_async else "") + "Surface"
|
|
52
|
+
transport = "AsyncTransport" if is_async else "Transport"
|
|
53
|
+
wiring = "\n".join(
|
|
54
|
+
f" self.{group.name}: {('Async' if is_async else '') + pascal(group.name)}"
|
|
55
|
+
f" = {('Async' if is_async else '') + pascal(group.name)}(transport)"
|
|
56
|
+
for group in groups
|
|
57
|
+
)
|
|
58
|
+
members = "\n\n".join(_method(method, is_async) for method in loose)
|
|
59
|
+
return (
|
|
60
|
+
f"class {name}:\n"
|
|
61
|
+
f" def __init__(self, transport: {transport}) -> None:\n"
|
|
62
|
+
f" self._t = transport\n"
|
|
63
|
+
f"{wiring}\n\n"
|
|
64
|
+
f"{members}\n"
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def render(groups: list[Group], loose: list[Method]) -> str:
|
|
69
|
+
blocks = [HEADER]
|
|
70
|
+
for is_async in (False, True):
|
|
71
|
+
blocks.extend(_group(group, is_async) for group in groups)
|
|
72
|
+
blocks.append(_surface(groups, loose, is_async))
|
|
73
|
+
return "\n\n".join(block.rstrip() for block in blocks) + "\n"
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Renders a generated pydantic field's annotation back into source text."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import enum
|
|
6
|
+
import types
|
|
7
|
+
import typing
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
|
|
10
|
+
SCALARS = {str: "str", int: "int", bool: "bool", float: "float", type(None): "None"}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _name(annotation: object) -> str:
|
|
14
|
+
if annotation in SCALARS:
|
|
15
|
+
return SCALARS[annotation]
|
|
16
|
+
origin = typing.get_origin(annotation)
|
|
17
|
+
if origin in (list, set, tuple):
|
|
18
|
+
inner = ", ".join(_name(arg) for arg in typing.get_args(annotation))
|
|
19
|
+
return f"{origin.__name__}[{inner}]"
|
|
20
|
+
if origin in (typing.Union, types.UnionType):
|
|
21
|
+
return " | ".join(_name(arg) for arg in typing.get_args(annotation))
|
|
22
|
+
if origin is dict:
|
|
23
|
+
key, value = typing.get_args(annotation)
|
|
24
|
+
return f"dict[{_name(key)}, {_name(value)}]"
|
|
25
|
+
if isinstance(annotation, type) and hasattr(annotation, "model_fields"):
|
|
26
|
+
return f"_models.{annotation.__name__}"
|
|
27
|
+
if isinstance(annotation, type) and issubclass(annotation, enum.Enum):
|
|
28
|
+
return f"_models.{annotation.__name__}"
|
|
29
|
+
return "typing.Any"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class Argument:
|
|
34
|
+
name: str
|
|
35
|
+
hint: str
|
|
36
|
+
required: bool
|
|
37
|
+
wire: str
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def declaration(self) -> str:
|
|
41
|
+
if self.required:
|
|
42
|
+
return f"{self.name}: {self.hint}"
|
|
43
|
+
# an optional field is already `X | None`; a second one reads as a mistake.
|
|
44
|
+
hint = self.hint if "None" in self.hint.split(" | ") else f"{self.hint} | None"
|
|
45
|
+
return f"{self.name}: {hint} = None"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def arguments(model: type) -> list[Argument]:
|
|
49
|
+
found = [
|
|
50
|
+
Argument(name, _name(field.annotation), field.is_required(), field.alias or name)
|
|
51
|
+
for name, field in model.model_fields.items()
|
|
52
|
+
]
|
|
53
|
+
# a python signature cannot put a defaulted argument before a required one.
|
|
54
|
+
return sorted(found, key=lambda argument: not argument.required)
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Maps a component schema name to the class the model generator actually emitted for it.
|
|
2
|
+
|
|
3
|
+
datamodel-code-generator names a class after the first schema it meets with that title, so an
|
|
4
|
+
inline object inside an earlier component can take the name and push the real one to `Usage1`.
|
|
5
|
+
The emitted name then keeps the component name as a prefix — `Usage1`, `ModelModel` — and the
|
|
6
|
+
field set says which of those candidates is the real one.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from types import ModuleType
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _fields(model: type) -> frozenset[str]:
|
|
16
|
+
return frozenset(field.alias or name for name, field in model.model_fields.items())
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def resolve(schemas: dict[str, Any], models: ModuleType) -> dict[str, str]:
|
|
20
|
+
emitted = {
|
|
21
|
+
name: value
|
|
22
|
+
for name, value in vars(models).items()
|
|
23
|
+
if isinstance(value, type) and hasattr(value, "model_fields")
|
|
24
|
+
}
|
|
25
|
+
found: dict[str, str] = {}
|
|
26
|
+
for name, schema in schemas.items():
|
|
27
|
+
want = frozenset(schema.get("properties", {}))
|
|
28
|
+
if not want:
|
|
29
|
+
continue
|
|
30
|
+
matches = [
|
|
31
|
+
emitted_name
|
|
32
|
+
for emitted_name, model in emitted.items()
|
|
33
|
+
if emitted_name.startswith(name) and _fields(model) == want
|
|
34
|
+
]
|
|
35
|
+
if len(matches) != 1:
|
|
36
|
+
raise SystemExit(
|
|
37
|
+
f"cannot resolve schema {name!r} to one generated class: {matches or 'no match'}"
|
|
38
|
+
)
|
|
39
|
+
found[name] = matches[0]
|
|
40
|
+
return found
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Reads the OpenAPI document into the shape the emitter needs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import TYPE_CHECKING
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from _hints import Argument
|
|
13
|
+
|
|
14
|
+
# one owner for the document: @ourseams/sdk emits it from the running api, both clients read it.
|
|
15
|
+
DOCUMENT = Path(__file__).resolve().parents[2] / "openapi.json"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def snake(name: str) -> str:
|
|
19
|
+
return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower().replace("-", "_")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def pascal(name: str) -> str:
|
|
23
|
+
return "".join(part.capitalize() for part in re.split(r"[-_.]", name))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class Method:
|
|
28
|
+
verb: str
|
|
29
|
+
path: str
|
|
30
|
+
name: str
|
|
31
|
+
summary: str
|
|
32
|
+
result: str | None
|
|
33
|
+
params: tuple[str, ...]
|
|
34
|
+
query: tuple[tuple[str, bool], ...]
|
|
35
|
+
body: str | None
|
|
36
|
+
fields: tuple[Argument, ...] = ()
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def signature(self) -> str:
|
|
40
|
+
args = [f"{snake(p)}: str" for p in self.params]
|
|
41
|
+
if self.fields:
|
|
42
|
+
args.extend(argument.declaration for argument in self.fields)
|
|
43
|
+
elif self.body is not None:
|
|
44
|
+
args.append(f"body: _models.{self.body}")
|
|
45
|
+
args.extend(
|
|
46
|
+
f"{snake(name)}: str" if required else f"{snake(name)}: str | None = None"
|
|
47
|
+
for name, required in self.query
|
|
48
|
+
)
|
|
49
|
+
return "".join(f", {arg}" for arg in args)
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def url(self) -> str:
|
|
53
|
+
rendered = re.sub(r"\{(\w+)\}", lambda m: f"{{{snake(m.group(1))}}}", self.path)
|
|
54
|
+
return f'f"{rendered}"' if self.params else f'"{rendered}"'
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def extras(self) -> str:
|
|
58
|
+
parts = []
|
|
59
|
+
if self.query:
|
|
60
|
+
pairs = ", ".join(f'"{name}": {snake(name)}' for name, _ in self.query)
|
|
61
|
+
parts.append(f"query={{{pairs}}}")
|
|
62
|
+
if self.fields:
|
|
63
|
+
pairs = ", ".join(f'"{f.wire}": {f.name}' for f in self.fields)
|
|
64
|
+
parts.append(f"body={{{pairs}}}")
|
|
65
|
+
elif self.body is not None:
|
|
66
|
+
parts.append("body=body.model_dump(mode='json', by_alias=True, exclude_none=True)")
|
|
67
|
+
return "".join(f", {part}" for part in parts)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass
|
|
71
|
+
class Group:
|
|
72
|
+
name: str
|
|
73
|
+
methods: list[Method] = field(default_factory=list)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _ref(schema: dict | None) -> str | None:
|
|
77
|
+
ref = (schema or {}).get("$ref")
|
|
78
|
+
return ref.rsplit("/", 1)[-1] if ref else None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _json_schema(holder: dict, key: str) -> dict | None:
|
|
82
|
+
content = holder.get(key, {}).get("content", {})
|
|
83
|
+
return content.get("application/json", {}).get("schema")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _class(schema: str | None, emitted: dict[str, str] | None) -> str | None:
|
|
87
|
+
return None if schema is None else (emitted or {}).get(schema, schema)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _keywords(found: tuple[Argument, ...], parameters: list[dict]) -> tuple[Argument, ...]:
|
|
91
|
+
taken = {snake(p["name"]) for p in parameters if p["in"] in ("path", "query")}
|
|
92
|
+
return () if any(argument.name in taken for argument in found) else found
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def read(
|
|
96
|
+
path: Path = DOCUMENT,
|
|
97
|
+
fields: dict[str, tuple[Argument, ...]] | None = None,
|
|
98
|
+
emitted: dict[str, str] | None = None,
|
|
99
|
+
) -> tuple[list[Group], list[Method]]:
|
|
100
|
+
document = json.loads(path.read_text())
|
|
101
|
+
groups: dict[str, Group] = {}
|
|
102
|
+
loose: list[Method] = []
|
|
103
|
+
|
|
104
|
+
for url, verbs in document["paths"].items():
|
|
105
|
+
for verb, operation in verbs.items():
|
|
106
|
+
identifier = operation.get("operationId")
|
|
107
|
+
# the mark, the probe and the document are served but not offered, same as @ourseams/sdk.
|
|
108
|
+
if identifier is None or operation.get("x-seams-internal") is True:
|
|
109
|
+
continue
|
|
110
|
+
parameters = operation.get("parameters", [])
|
|
111
|
+
method = Method(
|
|
112
|
+
verb=verb.upper(),
|
|
113
|
+
path=url,
|
|
114
|
+
name=snake(identifier.split(".")[-1]),
|
|
115
|
+
summary=operation.get("summary", ""),
|
|
116
|
+
result=_class(_ref(_json_schema(operation.get("responses", {}), "200")), emitted),
|
|
117
|
+
params=tuple(p["name"] for p in parameters if p["in"] == "path"),
|
|
118
|
+
query=tuple(
|
|
119
|
+
(p["name"], bool(p.get("required"))) for p in parameters if p["in"] == "query"
|
|
120
|
+
),
|
|
121
|
+
body=(body := _ref(_json_schema(operation, "requestBody"))),
|
|
122
|
+
fields=_keywords((fields or {}).get(body or "", ()), parameters),
|
|
123
|
+
)
|
|
124
|
+
if "." not in identifier:
|
|
125
|
+
loose.append(method)
|
|
126
|
+
else:
|
|
127
|
+
group = identifier.split(".")[0]
|
|
128
|
+
groups.setdefault(group, Group(group)).methods.append(method)
|
|
129
|
+
|
|
130
|
+
for group in groups.values():
|
|
131
|
+
group.methods.sort(key=lambda m: m.name)
|
|
132
|
+
return [groups[name] for name in sorted(groups)], sorted(loose, key=lambda m: m.name)
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Regenerates the models and the facade from the OpenAPI document."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib.util
|
|
6
|
+
import json
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from types import ModuleType
|
|
11
|
+
|
|
12
|
+
sys.path.insert(0, str(Path(__file__).parent))
|
|
13
|
+
|
|
14
|
+
from _emit import render
|
|
15
|
+
from _hints import arguments
|
|
16
|
+
from _resolve import resolve
|
|
17
|
+
from _shape import DOCUMENT, read
|
|
18
|
+
|
|
19
|
+
PACKAGE = Path(__file__).resolve().parents[1] / "src" / "seams"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _load(path: Path) -> ModuleType:
|
|
23
|
+
spec = importlib.util.spec_from_file_location("_seams_models", path)
|
|
24
|
+
assert spec is not None and spec.loader is not None
|
|
25
|
+
module = importlib.util.module_from_spec(spec)
|
|
26
|
+
sys.modules["_seams_models"] = module
|
|
27
|
+
spec.loader.exec_module(module)
|
|
28
|
+
return module
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def main() -> None:
|
|
32
|
+
subprocess.run(
|
|
33
|
+
[
|
|
34
|
+
"datamodel-codegen",
|
|
35
|
+
"--input",
|
|
36
|
+
str(DOCUMENT),
|
|
37
|
+
"--input-file-type",
|
|
38
|
+
"openapi",
|
|
39
|
+
"--output",
|
|
40
|
+
str(PACKAGE / "_generated" / "models.py"),
|
|
41
|
+
"--output-model-type",
|
|
42
|
+
"pydantic_v2.BaseModel",
|
|
43
|
+
"--target-python-version",
|
|
44
|
+
"3.10",
|
|
45
|
+
"--snake-case-field",
|
|
46
|
+
# a timestamp in the header makes every regeneration a diff, so the drift check cannot hold.
|
|
47
|
+
"--disable-timestamp",
|
|
48
|
+
"--custom-file-header",
|
|
49
|
+
"# generated by scripts/generate.py from packages/sdk/openapi.json — do not edit.",
|
|
50
|
+
# the client returns what the api sent: pydantic's AnyUrl appends a trailing slash.
|
|
51
|
+
"--type-mappings",
|
|
52
|
+
"string+uri=string",
|
|
53
|
+
"--formatters",
|
|
54
|
+
"black",
|
|
55
|
+
],
|
|
56
|
+
check=True,
|
|
57
|
+
)
|
|
58
|
+
# loaded by path, not by import: `seams` pulls in the facade this run is about to replace.
|
|
59
|
+
models = _load(PACKAGE / "_generated" / "models.py")
|
|
60
|
+
|
|
61
|
+
document = json.loads(DOCUMENT.read_text())
|
|
62
|
+
emitted = resolve(document.get("components", {}).get("schemas", {}), models)
|
|
63
|
+
fields = {schema: tuple(arguments(getattr(models, cls))) for schema, cls in emitted.items()}
|
|
64
|
+
groups, loose = read(fields=fields, emitted=emitted)
|
|
65
|
+
(PACKAGE / "_generated" / "client.py").write_text(render(groups, loose))
|
|
66
|
+
subprocess.run(["ruff", "format", str(PACKAGE / "_generated")], check=True)
|
|
67
|
+
print(
|
|
68
|
+
f"generated {len(groups)} namespaces, {sum(len(g.methods) for g in groups) + len(loose)} methods"
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
if __name__ == "__main__":
|
|
73
|
+
main()
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""The seams control plane, one namespace per CLI command group."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
|
|
7
|
+
from ._generated import models
|
|
8
|
+
from ._generated.client import AsyncSurface, Surface
|
|
9
|
+
from ._transport import DEFAULT_BASE_URL, AsyncTransport, SeamsError, Transport
|
|
10
|
+
|
|
11
|
+
__all__ = ["AsyncSeams", "Seams", "SeamsError", "models"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Seams(Surface):
|
|
15
|
+
"""
|
|
16
|
+
>>> seams = Seams(api_key=os.environ["SEAMS_SECRET_KEY"])
|
|
17
|
+
>>> seams.users.create("alice", email="alice@firm.com")
|
|
18
|
+
>>> seams.keys.mint(end_user_id="alice", bundle="pro").key
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
api_key: str,
|
|
24
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
25
|
+
http_client: httpx.Client | None = None,
|
|
26
|
+
) -> None:
|
|
27
|
+
super().__init__(Transport(api_key, base_url, http_client))
|
|
28
|
+
|
|
29
|
+
def close(self) -> None:
|
|
30
|
+
self._t.close()
|
|
31
|
+
|
|
32
|
+
def __enter__(self) -> Seams:
|
|
33
|
+
return self
|
|
34
|
+
|
|
35
|
+
def __exit__(self, *_: object) -> None:
|
|
36
|
+
self.close()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class AsyncSeams(AsyncSurface):
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
api_key: str,
|
|
43
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
44
|
+
http_client: httpx.AsyncClient | None = None,
|
|
45
|
+
) -> None:
|
|
46
|
+
super().__init__(AsyncTransport(api_key, base_url, http_client))
|
|
47
|
+
|
|
48
|
+
async def aclose(self) -> None:
|
|
49
|
+
await self._t.aclose()
|
|
50
|
+
|
|
51
|
+
async def __aenter__(self) -> AsyncSeams:
|
|
52
|
+
return self
|
|
53
|
+
|
|
54
|
+
async def __aexit__(self, *_: object) -> None:
|
|
55
|
+
await self.aclose()
|
|
File without changes
|