@withgateway/sdk 0.2.6 → 0.2.9
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.
- package/README.md +24 -8
- package/dist/cli.js +15468 -11263
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +15233 -11028
- package/dist/cli.mjs.map +1 -1
- package/dist/files/index.d.mts +1 -1
- package/dist/files/index.d.ts +1 -1
- package/dist/files/index.js +291 -40
- package/dist/files/index.js.map +1 -1
- package/dist/files/index.mjs +284 -37
- package/dist/files/index.mjs.map +1 -1
- package/dist/hooks/index.d.mts +1 -1
- package/dist/hooks/index.d.ts +1 -1
- package/dist/hooks/index.js +203 -47
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +198 -42
- package/dist/hooks/index.mjs.map +1 -1
- package/dist/{index-BaKu5ZSU.d.mts → index-C3UzD0G3.d.mts} +75 -1
- package/dist/{index-BaKu5ZSU.d.ts → index-C3UzD0G3.d.ts} +75 -1
- package/dist/{index-CLkMr6VG.d.ts → index-D-_4Ibcn.d.ts} +36 -4
- package/dist/{index-CdbmO4aX.d.mts → index-FfK4Nump.d.mts} +36 -4
- package/dist/index.d.mts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2149 -615
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2053 -566
- package/dist/index.mjs.map +1 -1
- package/dist/traces/index.js +268 -31
- package/dist/traces/index.js.map +1 -1
- package/dist/traces/index.mjs +262 -28
- package/dist/traces/index.mjs.map +1 -1
- package/dist/tracing/index.js +19 -11
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs +19 -11
- package/dist/tracing/index.mjs.map +1 -1
- package/dist/worlds/index.d.mts +886 -117
- package/dist/worlds/index.d.ts +886 -117
- package/dist/worlds/index.js +1770 -452
- package/dist/worlds/index.js.map +1 -1
- package/dist/worlds/index.mjs +1752 -434
- package/dist/worlds/index.mjs.map +1 -1
- package/package.json +14 -10
- package/runtime/gatewaysdk/environment/_toml.py +3 -10
- package/runtime/gatewaysdk/environment/_world.py +95 -28
- package/runtime/gatewaysdk/environment/runtime.py +10 -6
- package/runtime/gatewaysdk/environment/schema/__main__.py +35 -0
- package/runtime/gatewaysdk/environment/schema/api.py +19 -23
- package/runtime/gatewaysdk/environment/schema/batch.py +68 -14
- package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +4 -2
- package/runtime/gatewaysdk/environment/schema/cast.py +264 -0
- package/runtime/gatewaysdk/environment/schema/compiler.py +35 -1
- package/runtime/gatewaysdk/environment/schema/conform.py +28 -10
- package/runtime/gatewaysdk/environment/schema/connector.py +59 -14
- package/runtime/gatewaysdk/environment/schema/connectors/custom/handlers.py +38 -1
- package/runtime/gatewaysdk/environment/schema/connectors/google-drive/readers/merge.toml +3 -1
- package/runtime/gatewaysdk/environment/schema/credentials.py +20 -0
- package/runtime/gatewaysdk/environment/schema/csv_rows.py +117 -0
- package/runtime/gatewaysdk/environment/schema/cycles.py +121 -0
- package/runtime/gatewaysdk/environment/schema/data.py +21 -5
- package/runtime/gatewaysdk/environment/schema/grading.py +95 -13
- package/runtime/gatewaysdk/environment/schema/handler_errors.py +44 -0
- package/runtime/gatewaysdk/environment/schema/handler_scan.py +175 -0
- package/runtime/gatewaysdk/environment/schema/host.py +68 -115
- package/runtime/gatewaysdk/environment/schema/host_requests.py +78 -0
- package/runtime/gatewaysdk/environment/schema/host_surfaces.py +12 -0
- package/runtime/gatewaysdk/environment/schema/ingest.py +5 -18
- package/runtime/gatewaysdk/environment/schema/local.py +7 -10
- package/runtime/gatewaysdk/environment/schema/openapi_document.py +322 -0
- package/runtime/gatewaysdk/environment/schema/openapi_import.py +382 -0
- package/runtime/gatewaysdk/environment/schema/openapi_routes.py +441 -0
- package/runtime/gatewaysdk/environment/schema/openapi_schemas.py +629 -0
- package/runtime/gatewaysdk/environment/schema/openapi_source.py +210 -0
- package/runtime/gatewaysdk/environment/schema/platform.py +110 -299
- package/runtime/gatewaysdk/environment/schema/platform_import.py +182 -0
- package/runtime/gatewaysdk/environment/schema/platform_query.py +95 -0
- package/runtime/gatewaysdk/environment/schema/route_bindings.py +176 -0
- package/runtime/gatewaysdk/environment/schema/runtime.py +56 -7
- package/runtime/gatewaysdk/environment/schema/scaffold.py +64 -5
- package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +70 -22
- package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +54 -4
- package/runtime/gatewaysdk/environment/schema/skills/hooks-getting-started/SKILL.md +27 -2
- package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +62 -0
- package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +91 -54
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +146 -146
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +11 -7
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +30 -0
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/new-world-sandbox.md +43 -0
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/openapi-import.md +90 -0
- package/runtime/gatewaysdk/environment/schema/store.py +15 -6
- package/runtime/gatewaysdk/environment/schema/store_contract.py +119 -0
- package/runtime/gatewaysdk/environment/schema/tasks.py +121 -32
- package/runtime/gatewaysdk/environment/schema/tools_world.py +32 -10
- package/runtime/gatewaysdk/environment/schema/tree_import.py +228 -0
- package/runtime/gatewaysdk/environment/schema/ui.py +18 -2
- package/runtime/gatewaysdk/environment/schema/validation.py +35 -0
- package/runtime/gatewaysdk/environment/schema/verbs.py +8 -2
- package/runtime/gatewaysdk/environment/world.py +42 -3
- package/runtime/gatewaysdk/environment/world_session_contract.py +57 -0
- package/skills/benchmarks-getting-started/SKILL.md +70 -22
- package/skills/connector-schema-authoring/SKILL.md +54 -4
- package/skills/connector-schema-authoring/connector-worlds.md +21 -7
- package/skills/connector-schema-authoring/world-schema.md +144 -83
- package/skills/hooks-getting-started/SKILL.md +27 -2
- package/skills/world-data-ingestion/ROWS.md +62 -0
- package/skills/world-data-ingestion/SKILL.md +91 -54
- package/skills/worlds-getting-started/SKILL.md +146 -146
- package/skills/worlds-getting-started/references/cli-mcp-map.md +11 -7
- package/skills/worlds-getting-started/references/gotchas.md +30 -0
- package/skills/worlds-getting-started/references/new-world-sandbox.md +43 -0
- package/skills/worlds-getting-started/references/openapi-import.md +90 -0
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
"""The routes an OpenAPI import plans: every path+method of the document as one
|
|
2
|
+
``[[operations]]`` entry of connector.toml, or a skip with its reason.
|
|
3
|
+
|
|
4
|
+
An operation gets an entity when its success response is an entity schema (a
|
|
5
|
+
``get``/``update`` of one row), an array of one (a list route), or an envelope
|
|
6
|
+
holding exactly one such array (``{data: [...]}``; the key becomes
|
|
7
|
+
``envelope``). Writes whose response says nothing (``DELETE`` answering 204,
|
|
8
|
+
Swagger's form updates) take the entity of the ``GET`` on the same path, the
|
|
9
|
+
way a REST resource reads. Everything else stays a *passthrough* operation:
|
|
10
|
+
declared, served (``501 not_modelled``, so ``conform`` still sees the route),
|
|
11
|
+
carrying no entity, with the reason in the plan. Only what a connector cannot
|
|
12
|
+
declare at all is skipped: methods outside the allowed set, placeholders that
|
|
13
|
+
are not identifiers, and a route another operation already answers.
|
|
14
|
+
|
|
15
|
+
Path arguments bind the way ``route_bindings`` demands (W2): a placeholder
|
|
16
|
+
naming a field of the entity, or its key by an id-like name (``petId``,
|
|
17
|
+
``pet_id``, ``id``), becomes a ``filter``; any other placeholder is declared
|
|
18
|
+
in ``params`` as a scope segment. Declared query parameters naming an entity
|
|
19
|
+
field filter list routes (W5) and are said so in ``filter`` explicitly, so the
|
|
20
|
+
plan and the served route agree without anyone reading defaults.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import fnmatch
|
|
26
|
+
import re
|
|
27
|
+
from collections.abc import Callable
|
|
28
|
+
from dataclasses import dataclass, field
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
from .connector import PARAM, PLACEHOLDER
|
|
32
|
+
from .openapi_document import OpenApiDocument, OpenApiOperation
|
|
33
|
+
from .openapi_schemas import Names, Namespace
|
|
34
|
+
from .validation import MAX_OPERATION_NAME
|
|
35
|
+
|
|
36
|
+
#: Query parameters that page a list rather than select rows; never a filter.
|
|
37
|
+
PAGING_PARAMS = frozenset(
|
|
38
|
+
{"limit", "offset", "cursor", "page", "per_page", "perPage", "page_size", "pageSize", "page_token", "pageToken"}
|
|
39
|
+
)
|
|
40
|
+
_BRACED = re.compile(r"\{([^{}]*)\}")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class Entity:
|
|
45
|
+
"""One planned entity: the schema it came from and the names it got."""
|
|
46
|
+
|
|
47
|
+
name: str
|
|
48
|
+
source: str
|
|
49
|
+
pointer: str
|
|
50
|
+
key: str
|
|
51
|
+
key_type: str
|
|
52
|
+
fields: dict[str, str]
|
|
53
|
+
filterable: frozenset[str] = frozenset()
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def singular(self) -> str:
|
|
57
|
+
return Names.snake(self.source)
|
|
58
|
+
|
|
59
|
+
def field_for(self, argument: str) -> str | None:
|
|
60
|
+
"""The scalar row field a path argument or query parameter selects: the field
|
|
61
|
+
of that name, or the key when the argument is id-like for this entity."""
|
|
62
|
+
snake = Names.snake(argument)
|
|
63
|
+
if snake in {"id", self.singular, f"{self.singular}_id"}:
|
|
64
|
+
return self.key
|
|
65
|
+
if snake.endswith("_id") and self.singular.endswith(snake[:-3]):
|
|
66
|
+
return self.key
|
|
67
|
+
legal = self.fields.get(argument, Names.field(argument))
|
|
68
|
+
if legal in self.filterable:
|
|
69
|
+
return legal
|
|
70
|
+
prefixed = snake[len(self.singular) + 1 :] if snake.startswith(f"{self.singular}_") else ""
|
|
71
|
+
return prefixed if prefixed in self.filterable else None
|
|
72
|
+
|
|
73
|
+
def summary(self) -> dict:
|
|
74
|
+
return {"name": self.name, "key": self.key, "source": self.source, "pointer": self.pointer}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass(frozen=True)
|
|
78
|
+
class Shape:
|
|
79
|
+
"""What a response or request body holds: one entity row or many, wrapped or bare."""
|
|
80
|
+
|
|
81
|
+
entity: Entity
|
|
82
|
+
many: bool
|
|
83
|
+
envelope: str = ""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class Shapes:
|
|
87
|
+
"""Response and body schemas of the document read as entity shapes."""
|
|
88
|
+
|
|
89
|
+
def __init__(self, document: OpenApiDocument, entities: dict[str, Entity]):
|
|
90
|
+
self.document = document
|
|
91
|
+
self.entities = entities
|
|
92
|
+
|
|
93
|
+
def _named(self, schema: Any) -> Entity | None:
|
|
94
|
+
seen: set[str] = set()
|
|
95
|
+
while isinstance(schema, dict) and isinstance(schema.get("$ref"), str) and schema["$ref"] not in seen:
|
|
96
|
+
seen.add(schema["$ref"])
|
|
97
|
+
name = self.document.schema_name(schema["$ref"])
|
|
98
|
+
if name in self.entities:
|
|
99
|
+
return self.entities[name]
|
|
100
|
+
schema = self.document.lookup(schema["$ref"], "/paths")
|
|
101
|
+
return None
|
|
102
|
+
|
|
103
|
+
def of(self, schema: Any, at: str) -> Shape | None:
|
|
104
|
+
if not isinstance(schema, dict):
|
|
105
|
+
return None
|
|
106
|
+
entity = self._named(schema)
|
|
107
|
+
if entity is not None:
|
|
108
|
+
return Shape(entity, False)
|
|
109
|
+
node = self.document.resolve(schema, at)
|
|
110
|
+
if not isinstance(node, dict):
|
|
111
|
+
return None
|
|
112
|
+
if node.get("type") == "array":
|
|
113
|
+
items = self._named(node.get("items"))
|
|
114
|
+
return Shape(items, True) if items is not None else None
|
|
115
|
+
properties = node.get("properties")
|
|
116
|
+
if not isinstance(properties, dict):
|
|
117
|
+
return None
|
|
118
|
+
wrapped = [(key, self._array_of(value)) for key, value in properties.items()]
|
|
119
|
+
found = [(key, entity) for key, entity in wrapped if entity is not None]
|
|
120
|
+
if len(found) != 1:
|
|
121
|
+
return None
|
|
122
|
+
key, entity = found[0]
|
|
123
|
+
return Shape(entity, True, key)
|
|
124
|
+
|
|
125
|
+
def _array_of(self, schema: Any) -> Entity | None:
|
|
126
|
+
node = self.document.resolve(schema, "/paths") if isinstance(schema, dict) else None
|
|
127
|
+
if not isinstance(node, dict) or node.get("type") != "array":
|
|
128
|
+
return None
|
|
129
|
+
return self._named(node.get("items"))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@dataclass(frozen=True)
|
|
133
|
+
class Selection:
|
|
134
|
+
"""``--include`` / ``--exclude``: path globs (fnmatch, ``*`` crosses ``/``) or tags."""
|
|
135
|
+
|
|
136
|
+
include: tuple[str, ...] = ()
|
|
137
|
+
exclude: tuple[str, ...] = ()
|
|
138
|
+
|
|
139
|
+
@staticmethod
|
|
140
|
+
def _matches(pattern: str, operation: OpenApiOperation) -> bool:
|
|
141
|
+
return fnmatch.fnmatchcase(operation.path, pattern) or pattern in operation.tags
|
|
142
|
+
|
|
143
|
+
def selects(self, operation: OpenApiOperation) -> bool:
|
|
144
|
+
if self.include and not any(self._matches(p, operation) for p in self.include):
|
|
145
|
+
return False
|
|
146
|
+
return not any(self._matches(p, operation) for p in self.exclude)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@dataclass(frozen=True)
|
|
150
|
+
class Skipped:
|
|
151
|
+
method: str
|
|
152
|
+
path: str
|
|
153
|
+
pointer: str
|
|
154
|
+
reason: str
|
|
155
|
+
|
|
156
|
+
def summary(self) -> dict:
|
|
157
|
+
return {"method": self.method, "path": self.path, "pointer": self.pointer, "skipped_reason": self.reason}
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@dataclass
|
|
161
|
+
class OperationPlan:
|
|
162
|
+
"""One ``[[operations]]`` entry as the importer renders it."""
|
|
163
|
+
|
|
164
|
+
name: str
|
|
165
|
+
method: str
|
|
166
|
+
path: str
|
|
167
|
+
pointer: str
|
|
168
|
+
operation_id: str | None
|
|
169
|
+
summary_text: str = ""
|
|
170
|
+
params: tuple[str, ...] = ()
|
|
171
|
+
entity: str | None = None
|
|
172
|
+
action: str = "read"
|
|
173
|
+
single: bool = False
|
|
174
|
+
status: int | None = None
|
|
175
|
+
filter: dict[str, str] = field(default_factory=dict)
|
|
176
|
+
envelope: str | None = None
|
|
177
|
+
generate: dict[str, str] = field(default_factory=dict)
|
|
178
|
+
reason: str | None = None
|
|
179
|
+
|
|
180
|
+
def summary(self) -> dict:
|
|
181
|
+
out: dict[str, Any] = {
|
|
182
|
+
"name": self.name,
|
|
183
|
+
"method": self.method,
|
|
184
|
+
"path": self.path,
|
|
185
|
+
"entity": self.entity,
|
|
186
|
+
"action": self.action if self.entity else "passthrough",
|
|
187
|
+
"params": list(self.params),
|
|
188
|
+
"filter": dict(self.filter),
|
|
189
|
+
"pointer": self.pointer,
|
|
190
|
+
}
|
|
191
|
+
if self.operation_id and self.operation_id != self.name:
|
|
192
|
+
out["operation_id"] = self.operation_id
|
|
193
|
+
if self.envelope:
|
|
194
|
+
out["envelope"] = self.envelope
|
|
195
|
+
if self.reason:
|
|
196
|
+
out["reason"] = self.reason
|
|
197
|
+
return out
|
|
198
|
+
|
|
199
|
+
def toml(self) -> str:
|
|
200
|
+
lines = ["[[operations]]", f"name = {_s(self.name)}", f"method = {_s(self.method)}", f"path = {_s(self.path)}"]
|
|
201
|
+
if self.params:
|
|
202
|
+
lines.append(f"params = [{', '.join(_s(p) for p in self.params)}]")
|
|
203
|
+
if self.entity:
|
|
204
|
+
lines.append(f"entity = {_s(self.entity)}")
|
|
205
|
+
if self.envelope:
|
|
206
|
+
lines.append(f"results = {_s(self.envelope)}")
|
|
207
|
+
api = self._api_lines()
|
|
208
|
+
if api:
|
|
209
|
+
lines.append("[operations.api]")
|
|
210
|
+
lines.extend(api)
|
|
211
|
+
return "\n".join(lines) + "\n"
|
|
212
|
+
|
|
213
|
+
def _api_lines(self) -> list[str]:
|
|
214
|
+
if not self.entity:
|
|
215
|
+
return []
|
|
216
|
+
lines = []
|
|
217
|
+
if self.action != "read":
|
|
218
|
+
lines.append(f"action = {_s(self.action)}")
|
|
219
|
+
if self.status is not None:
|
|
220
|
+
lines.append(f"status = {self.status}")
|
|
221
|
+
if self.single:
|
|
222
|
+
lines.append("single = true")
|
|
223
|
+
if self.envelope:
|
|
224
|
+
lines.append(f"envelope = {_s(self.envelope)}")
|
|
225
|
+
if self.filter:
|
|
226
|
+
lines.append(f"filter = {_inline(self.filter)}")
|
|
227
|
+
if self.generate:
|
|
228
|
+
lines.append(f"generate = {_inline(self.generate)}")
|
|
229
|
+
return lines
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _s(text: str) -> str:
|
|
233
|
+
"""A TOML basic string (JSON's escapes are a subset of TOML's)."""
|
|
234
|
+
return '"' + text.replace("\\", "\\\\").replace('"', '\\"') + '"'
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _inline(mapping: dict[str, str]) -> str:
|
|
238
|
+
return "{ " + ", ".join(f"{_s(k)} = {_s(v)}" for k, v in mapping.items()) + " }"
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
class RoutePlanner:
|
|
242
|
+
"""Every selected operation of the document, planned in document order."""
|
|
243
|
+
|
|
244
|
+
def __init__(self, document: OpenApiDocument, entities: dict[str, Entity], selected: list[OpenApiOperation]):
|
|
245
|
+
self.document = document
|
|
246
|
+
self.shapes = Shapes(document, entities)
|
|
247
|
+
self.selected = selected
|
|
248
|
+
self.names = Namespace(limit=MAX_OPERATION_NAME)
|
|
249
|
+
self.warnings: list[str] = []
|
|
250
|
+
self.operations: list[OperationPlan] = []
|
|
251
|
+
self.skipped: list[Skipped] = []
|
|
252
|
+
self._routes: dict[tuple[str, str, tuple[str, ...]], str] = {}
|
|
253
|
+
self._reads: dict[str, Shape] = {}
|
|
254
|
+
|
|
255
|
+
def plan(self) -> RoutePlanner:
|
|
256
|
+
for operation in self.selected:
|
|
257
|
+
shape = self._response_shape(operation)
|
|
258
|
+
if operation.method == "GET" and shape is not None:
|
|
259
|
+
self._reads[operation.path] = shape
|
|
260
|
+
for operation in self.selected:
|
|
261
|
+
self._plan_one(operation)
|
|
262
|
+
for path, method, at in self.document.skipped_methods():
|
|
263
|
+
self.skipped.append(
|
|
264
|
+
Skipped(method.upper(), path, at, f"method {method.upper()} is not one a connector serves")
|
|
265
|
+
)
|
|
266
|
+
return self
|
|
267
|
+
|
|
268
|
+
# ------------------------------------------------------------- one operation
|
|
269
|
+
|
|
270
|
+
def _plan_one(self, operation: OpenApiOperation) -> None:
|
|
271
|
+
unservable = self._unservable_path(operation.path)
|
|
272
|
+
if unservable is not None:
|
|
273
|
+
self.skipped.append(Skipped(operation.method, operation.path, operation.pointer, unservable))
|
|
274
|
+
return
|
|
275
|
+
plan = self._route(operation)
|
|
276
|
+
route = (plan.method, _BRACED.sub("{}", plan.path), tuple(sorted(plan.params)))
|
|
277
|
+
if route in self._routes:
|
|
278
|
+
self.skipped.append(
|
|
279
|
+
Skipped(
|
|
280
|
+
plan.method,
|
|
281
|
+
plan.path,
|
|
282
|
+
operation.pointer,
|
|
283
|
+
f"{self._routes[route]} already answers {plan.method} {plan.path} with these params",
|
|
284
|
+
)
|
|
285
|
+
)
|
|
286
|
+
return
|
|
287
|
+
self._routes[route] = plan.name
|
|
288
|
+
self.operations.append(plan)
|
|
289
|
+
|
|
290
|
+
@staticmethod
|
|
291
|
+
def _unservable_path(path: str) -> str | None:
|
|
292
|
+
"""Why a connector cannot serve the path: a ``{segment}`` that is not an
|
|
293
|
+
identifier, or one that appears twice (the served router names each once)."""
|
|
294
|
+
illegal = [seg for seg in _BRACED.findall(path) if not PLACEHOLDER.fullmatch("{" + seg + "}")]
|
|
295
|
+
if illegal:
|
|
296
|
+
return f"path argument {{{illegal[0]}}} is not an identifier (letters, digits, _)"
|
|
297
|
+
placeholders = PLACEHOLDER.findall(path)
|
|
298
|
+
repeated = [p for p in placeholders if placeholders.count(p) > 1]
|
|
299
|
+
if repeated:
|
|
300
|
+
return f"path argument {{{repeated[0]}}} appears twice; each path argument may appear once"
|
|
301
|
+
return None
|
|
302
|
+
|
|
303
|
+
def _route(self, operation: OpenApiOperation) -> OperationPlan:
|
|
304
|
+
plan = OperationPlan(
|
|
305
|
+
name=self._name(operation),
|
|
306
|
+
method=operation.method,
|
|
307
|
+
path=operation.path,
|
|
308
|
+
pointer=operation.pointer,
|
|
309
|
+
operation_id=operation.operation_id,
|
|
310
|
+
summary_text=operation.summary,
|
|
311
|
+
)
|
|
312
|
+
plan.params = self._params(operation)
|
|
313
|
+
placeholders = tuple(PLACEHOLDER.findall(operation.path))
|
|
314
|
+
builder: Callable[[OpenApiOperation, OperationPlan, tuple[str, ...]], str | None] = {
|
|
315
|
+
"GET": self._read,
|
|
316
|
+
"POST": self._create,
|
|
317
|
+
"PUT": self._update,
|
|
318
|
+
"PATCH": self._update,
|
|
319
|
+
"DELETE": self._delete,
|
|
320
|
+
}[operation.method]
|
|
321
|
+
plan.reason = builder(operation, plan, placeholders)
|
|
322
|
+
if plan.reason is not None:
|
|
323
|
+
plan.entity = None
|
|
324
|
+
plan.filter = {}
|
|
325
|
+
plan.generate = {}
|
|
326
|
+
plan.single = False
|
|
327
|
+
plan.action = "read"
|
|
328
|
+
plan.status = None
|
|
329
|
+
plan.envelope = None
|
|
330
|
+
unbound = [p for p in placeholders if p not in plan.filter and p not in plan.params]
|
|
331
|
+
plan.params = (*plan.params, *unbound)
|
|
332
|
+
return plan
|
|
333
|
+
|
|
334
|
+
def _name(self, operation: OpenApiOperation) -> str:
|
|
335
|
+
source = operation.operation_id or f"{operation.method.lower()}_{operation.path}"
|
|
336
|
+
base = Names.operation(source, MAX_OPERATION_NAME)
|
|
337
|
+
name, renamed = self.names.claim(base)
|
|
338
|
+
if renamed:
|
|
339
|
+
self.warnings.append(f"{operation.pointer}: operation name {base} is taken; using {name}")
|
|
340
|
+
return name
|
|
341
|
+
|
|
342
|
+
def _params(self, operation: OpenApiOperation) -> tuple[str, ...]:
|
|
343
|
+
params: list[str] = []
|
|
344
|
+
for parameter in operation.query_parameters:
|
|
345
|
+
if not PARAM.match(parameter.name):
|
|
346
|
+
self.warnings.append(
|
|
347
|
+
f"{parameter.pointer}: query parameter {parameter.name} is not declarable; dropped"
|
|
348
|
+
)
|
|
349
|
+
continue
|
|
350
|
+
params.append(parameter.name)
|
|
351
|
+
return tuple(dict.fromkeys(params))
|
|
352
|
+
|
|
353
|
+
def _response_shape(self, operation: OpenApiOperation) -> Shape | None:
|
|
354
|
+
success = operation.success
|
|
355
|
+
if success is None:
|
|
356
|
+
return None
|
|
357
|
+
return self.shapes.of(success[1], f"{operation.pointer}/responses/{success[0]}")
|
|
358
|
+
|
|
359
|
+
def _body_shape(self, operation: OpenApiOperation) -> Shape | None:
|
|
360
|
+
return self.shapes.of(operation.request_body, f"{operation.pointer}/requestBody")
|
|
361
|
+
|
|
362
|
+
# ------------------------------------------------------------- per method
|
|
363
|
+
|
|
364
|
+
def _read(self, operation: OpenApiOperation, plan: OperationPlan, placeholders: tuple[str, ...]) -> str | None:
|
|
365
|
+
shape = self._response_shape(operation)
|
|
366
|
+
if shape is None:
|
|
367
|
+
return "response is not an entity schema, an array of one, or an envelope holding one"
|
|
368
|
+
plan.entity = shape.entity.name
|
|
369
|
+
plan.single = not shape.many
|
|
370
|
+
plan.envelope = shape.envelope or None
|
|
371
|
+
plan.filter = self._filters(shape.entity, placeholders, plan.params if shape.many else ())
|
|
372
|
+
return None
|
|
373
|
+
|
|
374
|
+
def _create(self, operation: OpenApiOperation, plan: OperationPlan, placeholders: tuple[str, ...]) -> str | None:
|
|
375
|
+
shape = self._response_shape(operation)
|
|
376
|
+
if shape is not None and shape.many:
|
|
377
|
+
plan.entity = shape.entity.name
|
|
378
|
+
plan.envelope = shape.envelope or None
|
|
379
|
+
plan.filter = self._filters(shape.entity, placeholders, plan.params)
|
|
380
|
+
return None
|
|
381
|
+
read = self._reads.get(operation.path)
|
|
382
|
+
if read is not None and not read.many and self._filters(read.entity, placeholders, ()):
|
|
383
|
+
return self._write(plan, read.entity, placeholders, "update", self._status(operation, 200))
|
|
384
|
+
entity = self._entity_of(shape, self._body_shape(operation), read)
|
|
385
|
+
if entity is None:
|
|
386
|
+
return "neither the response nor the body is an entity schema"
|
|
387
|
+
plan.entity = entity.name
|
|
388
|
+
plan.action = "create"
|
|
389
|
+
plan.single = True
|
|
390
|
+
plan.status = self._status(operation, 201)
|
|
391
|
+
plan.generate = {entity.key: "int" if entity.key_type == "integer" else "uuid"}
|
|
392
|
+
return None
|
|
393
|
+
|
|
394
|
+
def _update(self, operation: OpenApiOperation, plan: OperationPlan, placeholders: tuple[str, ...]) -> str | None:
|
|
395
|
+
entity = self._entity_of(
|
|
396
|
+
self._response_shape(operation), self._body_shape(operation), self._reads.get(operation.path)
|
|
397
|
+
)
|
|
398
|
+
if entity is None:
|
|
399
|
+
return "neither the response, the body nor the GET of this path names an entity"
|
|
400
|
+
return self._write(plan, entity, placeholders, "update", self._status(operation, 200))
|
|
401
|
+
|
|
402
|
+
def _delete(self, operation: OpenApiOperation, plan: OperationPlan, placeholders: tuple[str, ...]) -> str | None:
|
|
403
|
+
entity = self._entity_of(self._reads.get(operation.path), self._response_shape(operation), None)
|
|
404
|
+
if entity is None:
|
|
405
|
+
return "neither the response nor the GET of this path names an entity"
|
|
406
|
+
return self._write(plan, entity, placeholders, "delete", self._status(operation, 204))
|
|
407
|
+
|
|
408
|
+
def _write(
|
|
409
|
+
self, plan: OperationPlan, entity: Entity, placeholders: tuple[str, ...], action: str, status: int
|
|
410
|
+
) -> str | None:
|
|
411
|
+
filters = self._filters(entity, placeholders, ())
|
|
412
|
+
if not filters:
|
|
413
|
+
return f"no path argument names a field of {entity.name}, so the row to {action} cannot be found"
|
|
414
|
+
plan.entity = entity.name
|
|
415
|
+
plan.action = action
|
|
416
|
+
plan.single = True
|
|
417
|
+
plan.status = status
|
|
418
|
+
plan.filter = filters
|
|
419
|
+
return None
|
|
420
|
+
|
|
421
|
+
# ------------------------------------------------------------- helpers
|
|
422
|
+
|
|
423
|
+
@staticmethod
|
|
424
|
+
def _entity_of(*shapes: Shape | None) -> Entity | None:
|
|
425
|
+
for shape in shapes:
|
|
426
|
+
if shape is not None and not shape.many:
|
|
427
|
+
return shape.entity
|
|
428
|
+
return None
|
|
429
|
+
|
|
430
|
+
@staticmethod
|
|
431
|
+
def _status(operation: OpenApiOperation, default: int) -> int:
|
|
432
|
+
success = operation.success
|
|
433
|
+
if success is None or not success[0].isdigit():
|
|
434
|
+
return default
|
|
435
|
+
return int(success[0])
|
|
436
|
+
|
|
437
|
+
@staticmethod
|
|
438
|
+
def _filters(entity: Entity, placeholders: tuple[str, ...], params: tuple[str, ...]) -> dict[str, str]:
|
|
439
|
+
arguments = [*placeholders, *(p for p in params if p not in PAGING_PARAMS)]
|
|
440
|
+
found = {argument: entity.field_for(argument) for argument in arguments}
|
|
441
|
+
return {argument: target for argument, target in found.items() if target is not None}
|