backlex 0.0.1__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.
backlex/__init__.py ADDED
@@ -0,0 +1,46 @@
1
+ """backlex — official Python client.
2
+
3
+ from backlex import create_client
4
+
5
+ client = create_client("https://api.example.com", api_key="pak_...")
6
+ posts = client.from_("posts").query().where(lambda f: f.eq("published", True)).list()
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from .client import Auth, Client, Collection, Storage, create_client
12
+ from .errors import BacklexError
13
+ from .query import FilterBuilder, QueryBuilder, normalize_condition
14
+ from .types import (
15
+ AuthResult,
16
+ AuthUser,
17
+ Condition,
18
+ Item,
19
+ ItemEvent,
20
+ ItemResponse,
21
+ ListQuery,
22
+ ListResponse,
23
+ )
24
+
25
+ __version__ = "0.0.1"
26
+
27
+ __all__ = [
28
+ "create_client",
29
+ "Client",
30
+ "Collection",
31
+ "Auth",
32
+ "Storage",
33
+ "QueryBuilder",
34
+ "FilterBuilder",
35
+ "normalize_condition",
36
+ "BacklexError",
37
+ "Condition",
38
+ "Item",
39
+ "ItemEvent",
40
+ "ItemResponse",
41
+ "ListQuery",
42
+ "ListResponse",
43
+ "AuthResult",
44
+ "AuthUser",
45
+ "__version__",
46
+ ]
backlex/client.py ADDED
@@ -0,0 +1,463 @@
1
+ """The backlex client — Python port of ``packages/client/src/index.ts``.
2
+
3
+ A thin, typed wrapper over the REST + SSE API. Three auth modes, mirrored from
4
+ the TS SDK:
5
+
6
+ * **Server-to-server** — pass ``api_key="pak_..."``; sent as a bearer on every call.
7
+ * **App mode** — pass ``workspace="<slug>"``; ``auth.*`` targets that workspace's
8
+ own auth surface, and the session token from ``auth.sign_in`` / ``auth.sign_up``
9
+ is captured and replayed as a bearer. Persist it with ``auth.get_token()`` and
10
+ restore via ``create_client(token=...)``.
11
+ * **Cookie session** — omit both; the underlying ``httpx`` client keeps cookies.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ from typing import Any, Dict, List, Optional, cast
18
+ from urllib.parse import quote, urlencode
19
+
20
+ import httpx
21
+
22
+ from .errors import BacklexError
23
+ from .query import QueryBuilder
24
+ from .realtime import OnError, OnEvent, Unsubscribe
25
+ from .realtime import subscribe as _sse_subscribe
26
+ from .types import (
27
+ AuthResult,
28
+ ItemResponse,
29
+ ListQuery,
30
+ ListResponse,
31
+ )
32
+
33
+
34
+ def _build_search(q: Optional[ListQuery]) -> str:
35
+ """Serialize a ``ListQuery`` into a URL query string (mirrors ``buildSearch``)."""
36
+ if not q:
37
+ return ""
38
+ params: List[tuple[str, str]] = []
39
+ if q.get("filter"):
40
+ params.append(("filter", json.dumps(q["filter"], separators=(",", ":"))))
41
+ sort = q.get("sort")
42
+ if sort:
43
+ params.append(("sort", ",".join(sort) if isinstance(sort, list) else str(sort)))
44
+ fields = q.get("fields")
45
+ if fields:
46
+ params.append(("fields", ",".join(fields) if isinstance(fields, list) else str(fields)))
47
+ expand = q.get("expand")
48
+ if expand:
49
+ params.append(("expand", ",".join(expand) if isinstance(expand, list) else str(expand)))
50
+ if q.get("limit") is not None:
51
+ params.append(("limit", str(q["limit"])))
52
+ if q.get("offset") is not None:
53
+ params.append(("offset", str(q["offset"])))
54
+ if q.get("meta"):
55
+ params.append(("meta", q["meta"]))
56
+ if q.get("locale"):
57
+ params.append(("locale", q["locale"]))
58
+ if q.get("q"):
59
+ params.append(("q", q["q"]))
60
+ s = urlencode(params)
61
+ return f"?{s}" if s else ""
62
+
63
+
64
+ class Collection:
65
+ """CRUD handle for one collection, returned by ``client.from_(slug)``."""
66
+
67
+ def __init__(self, client: "Client", slug: str) -> None:
68
+ self._client = client
69
+ self._slug = slug
70
+
71
+ def list(self, query: Optional[ListQuery] = None) -> ListResponse:
72
+ return cast(
73
+ ListResponse,
74
+ self._client.request("GET", f"/api/items/{self._slug}{_build_search(query)}"),
75
+ )
76
+
77
+ def query(self) -> QueryBuilder:
78
+ """Fluent, type-safe query builder that compiles to a ``ListQuery``."""
79
+ return QueryBuilder(self.list)
80
+
81
+ def aggregate(self, body: Dict[str, Any]) -> Dict[str, Any]:
82
+ """Single-function aggregate (count/sum/avg/min/max), optionally grouped.
83
+
84
+ ``body`` = ``{"agg": "sum", "field": "price", "groupBy": "status"}``.
85
+ """
86
+ return cast(
87
+ Dict[str, Any], self._client.request("POST", f"/api/items/{self._slug}/aggregate", body)
88
+ )
89
+
90
+ def one(self, id: str, query: Optional[ListQuery] = None) -> ItemResponse:
91
+ # The single-item endpoint accepts the same expand/locale params as list.
92
+ return cast(
93
+ ItemResponse,
94
+ self._client.request("GET", f"/api/items/{self._slug}/{id}{_build_search(query)}"),
95
+ )
96
+
97
+ def create(self, data: Dict[str, Any]) -> ItemResponse:
98
+ return cast(
99
+ ItemResponse, self._client.request("POST", f"/api/items/{self._slug}", data)
100
+ )
101
+
102
+ def update(self, id: str, patch: Dict[str, Any]) -> ItemResponse:
103
+ return cast(
104
+ ItemResponse,
105
+ self._client.request("PATCH", f"/api/items/{self._slug}/{id}", patch),
106
+ )
107
+
108
+ def delete(self, id: str) -> Dict[str, Any]:
109
+ return cast(
110
+ Dict[str, Any], self._client.request("DELETE", f"/api/items/{self._slug}/{id}")
111
+ )
112
+
113
+ def publish(self, id: str) -> ItemResponse:
114
+ """Flip a versioned item to published."""
115
+ return cast(
116
+ ItemResponse, self._client.request("POST", f"/api/items/{self._slug}/{id}/publish")
117
+ )
118
+
119
+ def unpublish(self, id: str) -> ItemResponse:
120
+ """Flip a versioned item back to draft."""
121
+ return cast(
122
+ ItemResponse,
123
+ self._client.request("POST", f"/api/items/{self._slug}/{id}/publish?unpublish=1"),
124
+ )
125
+
126
+
127
+ class Auth:
128
+ """Auth surface. In app mode (``workspace`` set), targets the workspace pool."""
129
+
130
+ def __init__(self, client: "Client") -> None:
131
+ self._client = client
132
+
133
+ @property
134
+ def _base(self) -> str:
135
+ ws = self._client._workspace
136
+ return f"/api/t/{quote(ws)}/auth" if ws else "/api/auth"
137
+
138
+ def _capture(self, result: AuthResult) -> AuthResult:
139
+ if self._client._workspace and isinstance(result.get("token"), str):
140
+ self._client._app_token = result["token"]
141
+ return result
142
+
143
+ def sign_up(self, email: str, password: str, name: Optional[str] = None) -> AuthResult:
144
+ body: Dict[str, Any] = {"email": email, "password": password}
145
+ if name is not None:
146
+ body["name"] = name
147
+ return self._capture(
148
+ cast(AuthResult, self._client.request("POST", f"{self._base}/sign-up/email", body))
149
+ )
150
+
151
+ def sign_in(self, email: str, password: str) -> AuthResult:
152
+ return self._capture(
153
+ cast(
154
+ AuthResult,
155
+ self._client.request(
156
+ "POST", f"{self._base}/sign-in/email", {"email": email, "password": password}
157
+ ),
158
+ )
159
+ )
160
+
161
+ def sign_in_social(
162
+ self,
163
+ provider: str,
164
+ callback_url: Optional[str] = None,
165
+ error_callback_url: Optional[str] = None,
166
+ ) -> Dict[str, Any]:
167
+ """Begin an OAuth sign-in; returns ``{ "url", "redirect" }`` to navigate to."""
168
+ body: Dict[str, Any] = {"provider": provider, "disableRedirect": True}
169
+ if callback_url is not None:
170
+ body["callbackURL"] = callback_url
171
+ if error_callback_url is not None:
172
+ body["errorCallbackURL"] = error_callback_url
173
+ return cast(
174
+ Dict[str, Any], self._client.request("POST", f"{self._base}/sign-in/social", body)
175
+ )
176
+
177
+ def sign_in_magic_link(
178
+ self, email: str, callback_url: Optional[str] = None
179
+ ) -> Dict[str, Any]:
180
+ body: Dict[str, Any] = {"email": email}
181
+ if callback_url is not None:
182
+ body["callbackURL"] = callback_url
183
+ return cast(
184
+ Dict[str, Any],
185
+ self._client.request("POST", f"{self._base}/sign-in/magic-link", body),
186
+ )
187
+
188
+ def send_verification_otp(self, email: str, type: str = "sign-in") -> Dict[str, Any]:
189
+ """Email a one-time numeric code (requires the ``email-otp`` provider).
190
+
191
+ ``type`` is ``"sign-in"`` (default), ``"email-verification"`` or
192
+ ``"forget-password"``. Complete a sign-in with ``sign_in_email_otp``.
193
+ """
194
+ return cast(
195
+ Dict[str, Any],
196
+ self._client.request(
197
+ "POST", f"{self._base}/email-otp/send-verification-otp",
198
+ {"email": email, "type": type},
199
+ ),
200
+ )
201
+
202
+ def sign_in_email_otp(self, email: str, otp: str) -> AuthResult:
203
+ """Complete an email-OTP sign-in with the code from ``send_verification_otp``."""
204
+ return self._capture(
205
+ cast(
206
+ AuthResult,
207
+ self._client.request(
208
+ "POST", f"{self._base}/sign-in/email-otp", {"email": email, "otp": otp}
209
+ ),
210
+ )
211
+ )
212
+
213
+ def request_password_reset(self, email: str, redirect_to: Optional[str] = None) -> Dict[str, Any]:
214
+ """Send a password-reset email. ``redirect_to`` is where the link points."""
215
+ body: Dict[str, Any] = {"email": email}
216
+ if redirect_to is not None:
217
+ body["redirectTo"] = redirect_to
218
+ return cast(
219
+ Dict[str, Any],
220
+ self._client.request("POST", f"{self._base}/request-password-reset", body),
221
+ )
222
+
223
+ def reset_password(self, new_password: str, token: str) -> Dict[str, Any]:
224
+ """Complete a reset with the token from the email and a new password."""
225
+ return cast(
226
+ Dict[str, Any],
227
+ self._client.request(
228
+ "POST", f"{self._base}/reset-password", {"newPassword": new_password, "token": token}
229
+ ),
230
+ )
231
+
232
+ def refresh(self) -> Dict[str, Any]:
233
+ """Mint a fresh access JWT from the stored session token (app mode)."""
234
+ return cast(
235
+ Dict[str, Any],
236
+ self._client.request(
237
+ "POST", f"{self._base}/token/refresh", {"refreshToken": self._client._app_token}
238
+ ),
239
+ )
240
+
241
+ def change_password(
242
+ self, new_password: str, current_password: str, revoke_other_sessions: bool = False
243
+ ) -> Dict[str, Any]:
244
+ """Change the signed-in user's password (requires the current password)."""
245
+ body: Dict[str, Any] = {
246
+ "newPassword": new_password,
247
+ "currentPassword": current_password,
248
+ "revokeOtherSessions": revoke_other_sessions,
249
+ }
250
+ return cast(Dict[str, Any], self._client.request("POST", f"{self._base}/change-password", body))
251
+
252
+ def update_user(self, attributes: Dict[str, Any]) -> Dict[str, Any]:
253
+ """Update the signed-in user's profile (e.g. ``{"name": ..., "image": ...}``)."""
254
+ return cast(
255
+ Dict[str, Any], self._client.request("POST", f"{self._base}/update-user", attributes)
256
+ )
257
+
258
+ def send_verification_email(self, email: str, callback_url: Optional[str] = None) -> Dict[str, Any]:
259
+ """Send an email-verification link."""
260
+ body: Dict[str, Any] = {"email": email}
261
+ if callback_url is not None:
262
+ body["callbackURL"] = callback_url
263
+ return cast(
264
+ Dict[str, Any],
265
+ self._client.request("POST", f"{self._base}/send-verification-email", body),
266
+ )
267
+
268
+ def sign_out(self) -> Dict[str, Any]:
269
+ result = cast(Dict[str, Any], self._client.request("POST", f"{self._base}/sign-out"))
270
+ if self._client._workspace:
271
+ self._client._app_token = None
272
+ return result
273
+
274
+ def get_session(self) -> Dict[str, Any]:
275
+ return cast(Dict[str, Any], self._client.request("GET", f"{self._base}/get-session"))
276
+
277
+ def list_sessions(self) -> List[Dict[str, Any]]:
278
+ """List the signed-in user's active sessions (one row per device/login)."""
279
+ return cast(List[Dict[str, Any]], self._client.request("GET", f"{self._base}/list-sessions"))
280
+
281
+ def revoke_session(self, token: str) -> Dict[str, Any]:
282
+ """Revoke one session by its ``token`` (from ``list_sessions``)."""
283
+ return cast(
284
+ Dict[str, Any],
285
+ self._client.request("POST", f"{self._base}/revoke-session", {"token": token}),
286
+ )
287
+
288
+ def revoke_other_sessions(self) -> Dict[str, Any]:
289
+ """Revoke every session except the current one (sign out other devices)."""
290
+ return cast(Dict[str, Any], self._client.request("POST", f"{self._base}/revoke-other-sessions"))
291
+
292
+ def revoke_sessions(self) -> Dict[str, Any]:
293
+ """Revoke all sessions, including the current one."""
294
+ return cast(Dict[str, Any], self._client.request("POST", f"{self._base}/revoke-sessions"))
295
+
296
+ def providers(self) -> Dict[str, Any]:
297
+ """Public auth surface (provider list + policy flags) — no secrets."""
298
+ r = cast(Dict[str, Any], self._client.request("GET", f"{self._base}/providers"))
299
+ return cast(Dict[str, Any], r["data"])
300
+
301
+ def get_token(self) -> Optional[str]:
302
+ """The current workspace session token (app mode); persist across reloads."""
303
+ return self._client._app_token
304
+
305
+ def set_token(self, token: Optional[str]) -> None:
306
+ self._client._app_token = token
307
+
308
+
309
+ class Storage:
310
+ """File operations against ``/api/storage``."""
311
+
312
+ def __init__(self, client: "Client") -> None:
313
+ self._client = client
314
+
315
+ def list(self, prefix: Optional[str] = None) -> Dict[str, Any]:
316
+ path = "/api/storage"
317
+ if prefix:
318
+ path += f"?prefix={quote(prefix)}"
319
+ return cast(Dict[str, Any], self._client.request("GET", path))
320
+
321
+ def put(
322
+ self,
323
+ key: str,
324
+ body: Any,
325
+ content_type: Optional[str] = None,
326
+ folder_id: Optional[str] = None,
327
+ ) -> Dict[str, Any]:
328
+ headers = dict(self._client._auth_header())
329
+ if content_type:
330
+ headers["content-type"] = content_type
331
+ url = f"{self._client._url}/api/storage/{quote(key)}"
332
+ if folder_id:
333
+ url += f"?folderId={folder_id}"
334
+ resp = self._client._http.put(url, headers=headers, content=body)
335
+ if not resp.is_success:
336
+ raise BacklexError(resp.status_code, _safe_json(resp))
337
+ return cast(Dict[str, Any], resp.json())
338
+
339
+ def download(self, key: str) -> httpx.Response:
340
+ """Return the raw response; read the bytes via ``.content``."""
341
+ resp = self._client._http.get(
342
+ f"{self._client._url}/api/storage/{quote(key)}",
343
+ headers=self._client._auth_header(),
344
+ )
345
+ if not resp.is_success:
346
+ raise BacklexError(resp.status_code, None)
347
+ return resp
348
+
349
+ def delete(self, key: str) -> Dict[str, Any]:
350
+ return cast(
351
+ Dict[str, Any], self._client.request("DELETE", f"/api/storage/{quote(key)}")
352
+ )
353
+
354
+
355
+ def _safe_json(resp: httpx.Response) -> Optional[dict[str, Any]]:
356
+ try:
357
+ return cast("dict[str, Any]", resp.json())
358
+ except Exception: # noqa: BLE001
359
+ return None
360
+
361
+
362
+ class Client:
363
+ """Top-level backlex client. Prefer the ``create_client`` factory."""
364
+
365
+ def __init__(
366
+ self,
367
+ url: str,
368
+ *,
369
+ api_key: Optional[str] = None,
370
+ workspace: Optional[str] = None,
371
+ token: Optional[str] = None,
372
+ tenant: Optional[str] = None,
373
+ http: Optional[httpx.Client] = None,
374
+ ) -> None:
375
+ self._url = url.rstrip("/")
376
+ self._api_key = api_key
377
+ self._workspace = workspace
378
+ self._app_token: Optional[str] = token
379
+ self._tenant = tenant
380
+ # ``follow_redirects`` keeps cookie-session flows working; the client
381
+ # owns a cookie jar so same-origin sessions persist across calls.
382
+ self._http = http or httpx.Client(follow_redirects=True)
383
+ self.auth = Auth(self)
384
+ self.storage = Storage(self)
385
+
386
+ # -- internals -----------------------------------------------------------
387
+
388
+ def _auth_header(self) -> Dict[str, str]:
389
+ # Auth + optional explicit tenant scoping (slug or id), used by every
390
+ # request path (data, storage, realtime).
391
+ headers: Dict[str, str] = {}
392
+ if self._api_key:
393
+ headers["authorization"] = f"Bearer {self._api_key}"
394
+ elif self._app_token:
395
+ headers["authorization"] = f"Bearer {self._app_token}"
396
+ if self._tenant:
397
+ headers["x-backlex-tenant"] = self._tenant
398
+ return headers
399
+
400
+ def request(
401
+ self,
402
+ method: str,
403
+ path: str,
404
+ body: Any = None,
405
+ extra_headers: Optional[Dict[str, str]] = None,
406
+ ) -> Any:
407
+ """Raw escape hatch — issues a request with auth headers applied."""
408
+ headers: Dict[str, str] = {"content-type": "application/json", **self._auth_header()}
409
+ if extra_headers:
410
+ headers.update(extra_headers)
411
+ resp = self._http.request(
412
+ method,
413
+ f"{self._url}{path}",
414
+ headers=headers,
415
+ content=None if body is None else json.dumps(body),
416
+ )
417
+ if not resp.is_success:
418
+ raise BacklexError(resp.status_code, _safe_json(resp))
419
+ if resp.status_code == 204 or not resp.content:
420
+ return None
421
+ return resp.json()
422
+
423
+ # -- public surface ------------------------------------------------------
424
+
425
+ def from_(self, slug: str) -> Collection:
426
+ """CRUD handle for a collection (``from`` is a Python keyword)."""
427
+ return Collection(self, slug)
428
+
429
+ def subscribe(
430
+ self,
431
+ channel: str,
432
+ on_event: OnEvent,
433
+ on_error: Optional[OnError] = None,
434
+ ) -> Unsubscribe:
435
+ """Subscribe to a realtime channel (e.g. ``"items:posts"``). Returns an
436
+ unsubscribe callable. Runs on a background daemon thread."""
437
+ url = f"{self._url}/api/realtime/{channel}/subscribe"
438
+ return _sse_subscribe(self._http, url, self._auth_header, on_event, on_error)
439
+
440
+ def close(self) -> None:
441
+ """Close the underlying HTTP client / cookie jar."""
442
+ self._http.close()
443
+
444
+ def __enter__(self) -> "Client":
445
+ return self
446
+
447
+ def __exit__(self, *exc: Any) -> None:
448
+ self.close()
449
+
450
+
451
+ def create_client(
452
+ url: str,
453
+ *,
454
+ api_key: Optional[str] = None,
455
+ workspace: Optional[str] = None,
456
+ token: Optional[str] = None,
457
+ tenant: Optional[str] = None,
458
+ http: Optional[httpx.Client] = None,
459
+ ) -> Client:
460
+ """Construct a :class:`Client`. Mirrors the TS ``createClient(opts)`` factory."""
461
+ return Client(
462
+ url, api_key=api_key, workspace=workspace, token=token, tenant=tenant, http=http
463
+ )
backlex/errors.py ADDED
@@ -0,0 +1,36 @@
1
+ """Error type mirrored from the TS SDK's ``BacklexError``.
2
+
3
+ The API returns errors as ``{ "error": { "code", "message", "details"? } }``;
4
+ this wraps that envelope so callers can branch on ``status`` / ``code`` instead
5
+ of parsing strings.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any, Optional
11
+
12
+
13
+ class BacklexError(Exception):
14
+ """A non-2xx response from the backlex API.
15
+
16
+ Attributes:
17
+ status: HTTP status code.
18
+ code: Machine-readable error code (e.g. ``"VALIDATION"``,
19
+ ``"UNAUTHORIZED"``); ``"UNKNOWN"`` if the body had no envelope.
20
+ details: Optional structured details from the error envelope.
21
+ """
22
+
23
+ status: int
24
+ code: str
25
+ details: Optional[Any]
26
+
27
+ def __init__(self, status: int, body: Optional[dict[str, Any]]) -> None:
28
+ err = (body or {}).get("error") if isinstance(body, dict) else None
29
+ message = (err or {}).get("message") or f"HTTP {status}"
30
+ super().__init__(message)
31
+ self.status = status
32
+ self.code = (err or {}).get("code") or "UNKNOWN"
33
+ self.details = (err or {}).get("details")
34
+
35
+ def __repr__(self) -> str: # pragma: no cover - debugging aid
36
+ return f"BacklexError(status={self.status}, code={self.code!r}, message={str(self)!r})"
backlex/py.typed ADDED
File without changes
backlex/query.py ADDED
@@ -0,0 +1,263 @@
1
+ """Fluent query builder + filter normalization.
2
+
3
+ A Python port of ``packages/client/src/query.ts`` and the schema-blind half of
4
+ ``packages/core/src/condition.ts``. It is **not** a new wire format: every
5
+ builder compiles to the same canonical JSON ``Condition`` / ``ListQuery`` the
6
+ REST API already speaks, so permissions, AI plans, and serialization all stay on
7
+ the one grammar.
8
+
9
+ rows = (
10
+ client.from_("orders").query()
11
+ .where(lambda f: f.and_(
12
+ f.eq("status", "active"),
13
+ f.gte("total", 100),
14
+ f.rel("customer", lambda c: c.eq("tier", "gold")), # -> "customer.tier"
15
+ f.gte("placed_at", f.now(sub={"months": 1})),
16
+ ))
17
+ .select("id", "total", "customer.name")
18
+ .order_by("-placed_at", "id")
19
+ .limit(50)
20
+ .list()
21
+ )["data"]
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from typing import Any, Callable, Dict, List, Optional, cast
27
+
28
+ from .types import Condition, ListQuery, ListResponse
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # normalize_condition — schema-blind subset (matches the SDK's usage, which
32
+ # never passes ``relationFields``: the builder already emits dotted keys).
33
+ # ---------------------------------------------------------------------------
34
+
35
+
36
+ def _is_plain_object(v: Any) -> bool:
37
+ return isinstance(v, dict)
38
+
39
+
40
+ def _looks_like_comparison(o: Dict[str, Any]) -> bool:
41
+ keys = list(o.keys())
42
+ return len(keys) > 0 and all(k.startswith("_") for k in keys)
43
+
44
+
45
+ def normalize_condition(raw: Any) -> Condition:
46
+ """Turn any accepted filter shape into the canonical ``Condition``.
47
+
48
+ Handles ``$and`` / ``$or`` / ``$not`` (and their ``_`` aliases) and implicit
49
+ equality (``{"status": "active"}`` -> ``{"status": {"_eq": "active"}}``).
50
+ Idempotent. Non-dict input is returned unchanged.
51
+ """
52
+ if not _is_plain_object(raw):
53
+ return cast(Condition, raw)
54
+
55
+ and_ = raw.get("$and", raw.get("_and"))
56
+ if isinstance(and_, list):
57
+ return {"$and": [normalize_condition(c) for c in and_]}
58
+ or_ = raw.get("$or", raw.get("_or"))
59
+ if isinstance(or_, list):
60
+ return {"$or": [normalize_condition(c) for c in or_]}
61
+ not_ = raw.get("$not", raw.get("_not"))
62
+ if not_ is not None:
63
+ return {"$not": normalize_condition(not_)}
64
+
65
+ out: Dict[str, Any] = {}
66
+ for key, value in raw.items():
67
+ if _is_plain_object(value) and _looks_like_comparison(value):
68
+ out[key] = value
69
+ elif _is_plain_object(value):
70
+ # Unknown object shape (json literal, schema-blind nesting) — pass through.
71
+ out[key] = value
72
+ else:
73
+ out[key] = {"_eq": value}
74
+ return out
75
+
76
+
77
+ def _prefix_keys(cond: Condition, head: str) -> Condition:
78
+ """Prefix every leaf field key of a condition with ``head.`` (relation hop)."""
79
+ if isinstance(cond.get("$and"), list):
80
+ return {"$and": [_prefix_keys(x, head) for x in cond["$and"]]}
81
+ if isinstance(cond.get("$or"), list):
82
+ return {"$or": [_prefix_keys(x, head) for x in cond["$or"]]}
83
+ if cond.get("$not") is not None:
84
+ return {"$not": _prefix_keys(cond["$not"], head)}
85
+ return {f"{head}.{k}": v for k, v in cond.items()}
86
+
87
+
88
+ # ---------------------------------------------------------------------------
89
+ # FilterBuilder — the ``f`` passed to ``.where(lambda f: ...)``.
90
+ # Python keywords (and/or/not/in) get a trailing underscore.
91
+ # ---------------------------------------------------------------------------
92
+
93
+
94
+ class FilterBuilder:
95
+ """Leaf + logical condition constructors. Each method returns a ``Condition``."""
96
+
97
+ @staticmethod
98
+ def _leaf(field: str, op: str, value: Any) -> Condition:
99
+ return {field: {op: value}}
100
+
101
+ def eq(self, field: str, value: Any) -> Condition:
102
+ return self._leaf(field, "_eq", value)
103
+
104
+ def neq(self, field: str, value: Any) -> Condition:
105
+ return self._leaf(field, "_neq", value)
106
+
107
+ def gt(self, field: str, value: Any) -> Condition:
108
+ return self._leaf(field, "_gt", value)
109
+
110
+ def gte(self, field: str, value: Any) -> Condition:
111
+ return self._leaf(field, "_gte", value)
112
+
113
+ def lt(self, field: str, value: Any) -> Condition:
114
+ return self._leaf(field, "_lt", value)
115
+
116
+ def lte(self, field: str, value: Any) -> Condition:
117
+ return self._leaf(field, "_lte", value)
118
+
119
+ def in_(self, field: str, values: List[Any]) -> Condition:
120
+ return self._leaf(field, "_in", values)
121
+
122
+ def nin(self, field: str, values: List[Any]) -> Condition:
123
+ return self._leaf(field, "_nin", values)
124
+
125
+ def between(self, field: str, lo: Any, hi: Any) -> Condition:
126
+ return self._leaf(field, "_between", [lo, hi])
127
+
128
+ def is_null(self, field: str, is_null: bool = True) -> Condition:
129
+ return self._leaf(field, "_null", is_null)
130
+
131
+ def empty(self, field: str) -> Condition:
132
+ return self._leaf(field, "_empty", True)
133
+
134
+ def nempty(self, field: str) -> Condition:
135
+ return self._leaf(field, "_nempty", True)
136
+
137
+ def contains(self, field: str, value: str) -> Condition:
138
+ return self._leaf(field, "_contains", value)
139
+
140
+ def icontains(self, field: str, value: str) -> Condition:
141
+ return self._leaf(field, "_icontains", value)
142
+
143
+ def starts_with(self, field: str, value: str) -> Condition:
144
+ return self._leaf(field, "_starts_with", value)
145
+
146
+ def ends_with(self, field: str, value: str) -> Condition:
147
+ return self._leaf(field, "_ends_with", value)
148
+
149
+ def and_(self, *conds: Condition) -> Condition:
150
+ return {"$and": list(conds)}
151
+
152
+ def or_(self, *conds: Condition) -> Condition:
153
+ return {"$or": list(conds)}
154
+
155
+ def not_(self, cond: Condition) -> Condition:
156
+ return {"$not": cond}
157
+
158
+ def rel(self, head: str, build: "Callable[[FilterBuilder], Condition]") -> Condition:
159
+ """Traverse a relation: keys produced by ``build`` are prefixed ``head.``."""
160
+ return _prefix_keys(build(FilterBuilder()), head)
161
+
162
+ def now(
163
+ self,
164
+ add: Optional[Dict[str, int]] = None,
165
+ sub: Optional[Dict[str, int]] = None,
166
+ ) -> Dict[str, Any]:
167
+ """Relative-date value, e.g. ``f.now(sub={"months": 1})``."""
168
+ opts: Dict[str, Any] = {}
169
+ if add is not None:
170
+ opts["add"] = add
171
+ if sub is not None:
172
+ opts["sub"] = sub
173
+ return {"$now": opts}
174
+
175
+
176
+ ListFn = Callable[[ListQuery], ListResponse]
177
+
178
+
179
+ class QueryBuilder:
180
+ """Chainable assembler that compiles to a plain ``ListQuery``."""
181
+
182
+ def __init__(self, list_fn: ListFn) -> None:
183
+ self._list_fn = list_fn
184
+ self._filter: Optional[Condition] = None
185
+ self._sort: List[str] = []
186
+ self._fields: List[str] = []
187
+ self._expand: List[str] = []
188
+ self._limit: Optional[int] = None
189
+ self._offset: Optional[int] = None
190
+ self._meta: Optional[str] = None
191
+ self._locale: Optional[str] = None
192
+ self._q: Optional[str] = None
193
+
194
+ def where(self, build: Callable[[FilterBuilder], Condition]) -> "QueryBuilder":
195
+ self._filter = normalize_condition(build(FilterBuilder()))
196
+ return self
197
+
198
+ def filter(self, cond: Condition) -> "QueryBuilder":
199
+ """Replace the filter with a raw canonical condition (escape hatch)."""
200
+ self._filter = normalize_condition(cond)
201
+ return self
202
+
203
+ def select(self, *fields: str) -> "QueryBuilder":
204
+ self._fields.extend(fields)
205
+ return self
206
+
207
+ def order_by(self, *sorts: str) -> "QueryBuilder":
208
+ self._sort.extend(sorts)
209
+ return self
210
+
211
+ def expand(self, *rels: str) -> "QueryBuilder":
212
+ """Inline single-hop relations (replaces each FK with the related object)."""
213
+ self._expand.extend(rels)
214
+ return self
215
+
216
+ def locale(self, loc: str) -> "QueryBuilder":
217
+ """Project ``i18n_text`` fields to one locale, or ``"*"`` for the full map."""
218
+ self._locale = loc
219
+ return self
220
+
221
+ def search(self, text: str) -> "QueryBuilder":
222
+ """Free-text search across readable text fields."""
223
+ self._q = text
224
+ return self
225
+
226
+ def limit(self, n: int) -> "QueryBuilder":
227
+ self._limit = n
228
+ return self
229
+
230
+ def offset(self, n: int) -> "QueryBuilder":
231
+ self._offset = n
232
+ return self
233
+
234
+ def with_meta(self, m: str) -> "QueryBuilder":
235
+ """Request an extra COUNT: ``"filter_count"``, ``"total_count"``, or ``"*"``."""
236
+ self._meta = m
237
+ return self
238
+
239
+ def to_query(self) -> ListQuery:
240
+ """Assemble the plain ``ListQuery`` — the canonical JSON the REST API takes."""
241
+ q: ListQuery = {}
242
+ if self._filter:
243
+ q["filter"] = self._filter
244
+ if self._sort:
245
+ q["sort"] = self._sort
246
+ if self._fields:
247
+ q["fields"] = self._fields
248
+ if self._expand:
249
+ q["expand"] = self._expand
250
+ if self._limit is not None:
251
+ q["limit"] = self._limit
252
+ if self._offset is not None:
253
+ q["offset"] = self._offset
254
+ if self._meta:
255
+ q["meta"] = self._meta
256
+ if self._locale:
257
+ q["locale"] = self._locale
258
+ if self._q:
259
+ q["q"] = self._q
260
+ return q
261
+
262
+ def list(self) -> ListResponse:
263
+ return self._list_fn(self.to_query())
backlex/realtime.py ADDED
@@ -0,0 +1,84 @@
1
+ """SSE realtime transport.
2
+
3
+ The backlex realtime plane is Server-Sent Events (not WebSockets), so this is a
4
+ minimal SSE reader running on a daemon thread. ``subscribe`` returns an
5
+ ``unsubscribe`` callable — the same ``() -> None`` contract as the TS SDK. The
6
+ reader auto-reconnects on a dropped stream (3s back-off, matching the server's
7
+ reconnect hint) and replays via ``Last-Event-ID`` when the server supplies ids.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import threading
14
+ from typing import Any, Callable, Dict, Optional
15
+
16
+ import httpx
17
+
18
+ from .errors import BacklexError
19
+ from .types import ItemEvent
20
+
21
+ OnEvent = Callable[[ItemEvent], None]
22
+ OnError = Callable[[Any], None]
23
+ Unsubscribe = Callable[[], None]
24
+
25
+ _RECONNECT_SECONDS = 3.0
26
+
27
+
28
+ def subscribe(
29
+ http: httpx.Client,
30
+ url: str,
31
+ auth_header: Callable[[], Dict[str, str]],
32
+ on_event: OnEvent,
33
+ on_error: Optional[OnError] = None,
34
+ ) -> Unsubscribe:
35
+ stop = threading.Event()
36
+
37
+ def run() -> None:
38
+ last_id: Optional[str] = None
39
+ while not stop.is_set():
40
+ headers = {"accept": "text/event-stream", **auth_header()}
41
+ if last_id is not None:
42
+ headers["last-event-id"] = last_id
43
+ try:
44
+ with http.stream("GET", url, headers=headers, timeout=None) as resp:
45
+ if resp.status_code != 200:
46
+ raise BacklexError(resp.status_code, None)
47
+ data_lines: list[str] = []
48
+ for line in resp.iter_lines():
49
+ if stop.is_set():
50
+ return
51
+ if line == "":
52
+ # Blank line dispatches the buffered event.
53
+ if data_lines:
54
+ payload = "\n".join(data_lines)
55
+ data_lines = []
56
+ try:
57
+ on_event(json.loads(payload))
58
+ except Exception as exc: # noqa: BLE001
59
+ if on_error:
60
+ on_error(exc)
61
+ continue
62
+ if line.startswith(":"):
63
+ # Comment / heartbeat frame.
64
+ continue
65
+ if line.startswith("id:"):
66
+ last_id = line[3:].strip()
67
+ continue
68
+ if line.startswith("data:"):
69
+ data_lines.append(line[5:].lstrip())
70
+ except Exception as exc: # noqa: BLE001
71
+ if stop.is_set():
72
+ return
73
+ if on_error:
74
+ on_error(exc)
75
+ # Reconnect after a short back-off unless we've been told to stop.
76
+ stop.wait(_RECONNECT_SECONDS)
77
+
78
+ thread = threading.Thread(target=run, name=f"backlex-sse:{url}", daemon=True)
79
+ thread.start()
80
+
81
+ def unsubscribe() -> None:
82
+ stop.set()
83
+
84
+ return unsubscribe
backlex/types.py ADDED
@@ -0,0 +1,75 @@
1
+ """Wire types, mirrored from ``packages/client/src/types.ts``.
2
+
3
+ These are intentionally thin: the API speaks plain JSON, so responses arrive as
4
+ ``dict`` / ``list``. ``TypedDict`` gives editors structure without forcing a
5
+ deserialization layer. The canonical ``Condition`` grammar is shared with the
6
+ TS SDK and the server — there is no Python-specific wire format.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import sys
12
+ from typing import Any, Dict, List, Optional
13
+
14
+ if sys.version_info >= (3, 11):
15
+ from typing import NotRequired, TypedDict
16
+ else: # pragma: no cover - 3.9 / 3.10 fallback
17
+ from typing_extensions import NotRequired, TypedDict
18
+
19
+ # A row from a collection. The SDK does not impose a schema — pair with
20
+ # ``backlex gen-types`` output (or hand-written ``TypedDict``s) for typing.
21
+ Item = Dict[str, Any]
22
+
23
+ # The canonical JSON filter grammar (``$and`` / ``$or`` / ``$not`` / leaf maps).
24
+ Condition = Dict[str, Any]
25
+
26
+ # Meta-count request flag.
27
+ MetaFlag = str # "filter_count" | "total_count" | "*"
28
+
29
+
30
+ class ListResponse(TypedDict):
31
+ """Result of a collection list/query call."""
32
+
33
+ data: List[Item]
34
+ limit: int
35
+ offset: int
36
+ meta: NotRequired[Dict[str, int]]
37
+
38
+
39
+ class ItemResponse(TypedDict):
40
+ """Single-item envelope: ``{ "data": {...} }``."""
41
+
42
+ data: Item
43
+
44
+
45
+ class ListQuery(TypedDict, total=False):
46
+ """The query parameters a list/query call serializes into the URL."""
47
+
48
+ filter: Condition
49
+ sort: Any # str | list[str]
50
+ fields: Any # str | list[str]
51
+ expand: Any # str | list[str] — inline single-hop relations
52
+ limit: int
53
+ offset: int
54
+ meta: MetaFlag
55
+ locale: str # collapse i18n_text to one locale, or "*" for the full map
56
+ q: str # free-text search across readable text fields
57
+
58
+
59
+ class ItemEvent(TypedDict):
60
+ """A realtime event frame: ``{ "event": ..., "data": {...} }``."""
61
+
62
+ event: str # "created" | "updated" | "deleted"
63
+ data: Item
64
+
65
+
66
+ class AuthUser(TypedDict, total=False):
67
+ id: str
68
+ email: str
69
+ name: Optional[str]
70
+ image: Optional[str]
71
+
72
+
73
+ class AuthResult(TypedDict, total=False):
74
+ user: AuthUser
75
+ token: str
@@ -0,0 +1,145 @@
1
+ Metadata-Version: 2.4
2
+ Name: backlex
3
+ Version: 0.0.1
4
+ Summary: Official Python client for the backlex API (CRUD, query builder, auth, realtime, storage).
5
+ Project-URL: Homepage, https://backlex.com
6
+ Project-URL: Documentation, https://backlex.com/docs/client-sdks
7
+ Project-URL: Repository, https://github.com/backlex/backlex
8
+ Author: backlex
9
+ License: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: baas,backend,backlex,rest,sdk
12
+ Requires-Python: >=3.9
13
+ Requires-Dist: httpx>=0.27
14
+ Requires-Dist: typing-extensions>=4.6; python_version < '3.11'
15
+ Provides-Extra: dev
16
+ Requires-Dist: mypy>=1.10; extra == 'dev'
17
+ Requires-Dist: pytest>=8; extra == 'dev'
18
+ Requires-Dist: ruff>=0.5; extra == 'dev'
19
+ Description-Content-Type: text/markdown
20
+
21
+ # backlex — Python SDK
22
+
23
+ Official Python client for the backlex API. A thin, typed wrapper over the same
24
+ REST + SSE surface the TypeScript SDK (`@backlex/client`) speaks — CRUD, a fluent
25
+ query builder, auth, realtime, and storage.
26
+
27
+ This package is the **reference port** for backlex's multi-language SDK effort
28
+ (Python → Go → .NET/Java → Swift/Kotlin). It demonstrates the **hybrid** model:
29
+ hand-written ergonomic layer on top, optional OpenAPI-generated models
30
+ underneath (see [Hybrid codegen](#hybrid-codegen)).
31
+
32
+ ```bash
33
+ pip install backlex # not yet published — for now: pip install -e sdks/python
34
+ ```
35
+
36
+ ## Quickstart
37
+
38
+ ```python
39
+ from backlex import create_client
40
+
41
+ client = create_client("https://api.example.com", api_key="pak_...")
42
+
43
+ # CRUD
44
+ post = client.from_("posts").create({"title": "Hello"})["data"]
45
+ client.from_("posts").update(post["id"], {"title": "Edited"})
46
+ client.from_("posts").delete(post["id"])
47
+
48
+ # Fluent query builder → compiles to canonical JSON (same wire format as TS)
49
+ rows = (
50
+ client.from_("orders").query()
51
+ .where(lambda f: f.and_(
52
+ f.eq("status", "active"),
53
+ f.gte("total", 100),
54
+ f.rel("customer", lambda c: c.eq("tier", "gold")), # → "customer.tier"
55
+ f.gte("placed_at", f.now(sub={"months": 1})),
56
+ ))
57
+ .select("id", "total", "customer.name")
58
+ .order_by("-placed_at", "id")
59
+ .limit(50)
60
+ .list()
61
+ )["data"]
62
+ ```
63
+
64
+ ## Auth
65
+
66
+ ```python
67
+ # Server-to-server: pass api_key="pak_..." to create_client (bearer on every call).
68
+
69
+ # App mode — end-users of a workspace:
70
+ client = create_client("https://api.example.com", workspace="myapp")
71
+ res = client.auth.sign_in("user@example.com", "password") # token auto-captured
72
+ token = client.auth.get_token() # persist this
73
+ # later: create_client(..., workspace="myapp", token=token) to restore the session
74
+ client.auth.sign_out()
75
+ ```
76
+
77
+ `auth.providers()` returns the public auth surface (provider list + policy flags)
78
+ for rendering a sign-in screen. `auth.sign_in_social(provider)` and
79
+ `auth.sign_in_magic_link(email)` are also available.
80
+
81
+ ## Realtime (SSE)
82
+
83
+ ```python
84
+ unsub = client.subscribe("items:posts", lambda ev: print(ev["event"], ev["data"]))
85
+ # ... runs on a background daemon thread, auto-reconnects ...
86
+ unsub()
87
+ ```
88
+
89
+ ## Storage
90
+
91
+ ```python
92
+ client.storage.put("avatars/me.png", open("me.png", "rb").read(), "image/png")
93
+ data = client.storage.download("avatars/me.png").content
94
+ client.storage.list(prefix="avatars/")
95
+ client.storage.delete("avatars/me.png")
96
+ ```
97
+
98
+ ## Errors
99
+
100
+ Every non-2xx response raises `BacklexError` with `.status`, `.code`, and
101
+ `.details` (the `{ "error": {...} }` envelope), so you branch on codes, not
102
+ strings.
103
+
104
+ ## Hybrid codegen
105
+
106
+ The hand-written layer above is stable and small. For **typed models** of your
107
+ collections and the system API, generate them from the OpenAPI spec the server
108
+ already ships — no Python-specific wire format is introduced.
109
+
110
+ ```bash
111
+ # 1. System API models from the static OpenAPI spec:
112
+ openapi-generator generate \
113
+ -i apps/web/src/server/lib/openapi-static.generated.json \
114
+ -g python -o sdks/python/_generated --skip-validate
115
+
116
+ # 2. Per-collection types: the `backlex gen-types` CLI emits these for the
117
+ # TS SDK today; the Python equivalent reads /api/collections and writes
118
+ # TypedDicts you pass as `client.from_("posts") # -> dict[Post]`.
119
+ ```
120
+
121
+ Generated models live alongside (not inside) the hand-written package, so the
122
+ ergonomic surface stays clean while models track the spec.
123
+
124
+ ## Develop
125
+
126
+ ```bash
127
+ cd sdks/python
128
+ pip install -e ".[dev]"
129
+ pytest # offline: query-builder + normalization contract tests
130
+ mypy # strict
131
+ ruff check .
132
+ ```
133
+
134
+ ## Parity with the TS SDK
135
+
136
+ | TS (`@backlex/client`) | Python (`backlex`) |
137
+ | ----------------------------- | ---------------------------------------- |
138
+ | `createClient(opts)` | `create_client(url, ...)` |
139
+ | `client.from(slug)` | `client.from_(slug)` |
140
+ | `.query().where(f => ...)` | `.query().where(lambda f: ...)` |
141
+ | `f.and / or / not / in` | `f.and_ / or_ / not_ / in_` |
142
+ | `.orderBy().withMeta()` | `.order_by().with_meta()` |
143
+ | `client.subscribe(ch, cb)` | `client.subscribe(ch, cb)` → `unsub()` |
144
+ | `auth.signIn / getToken` | `auth.sign_in / get_token` |
145
+ | `BacklexError` | `BacklexError` |
@@ -0,0 +1,11 @@
1
+ backlex/__init__.py,sha256=5j3S-JVjskJbkQbeydsxzGSqBAvYRb3SgZL0eT9pnA8,959
2
+ backlex/client.py,sha256=qgQZGY4X3deRCllU-u11Go0MnXotyd95ZG-YkK9FDDY,17430
3
+ backlex/errors.py,sha256=Xt-7Tz6JNlody8-bkqjCJs3dbxvhc_VETdIROtr-36E,1284
4
+ backlex/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ backlex/query.py,sha256=3pYshT3bYlrjEomrSaM2P5mqQ6WG1_-sKCYI_Wvu_ck,9296
6
+ backlex/realtime.py,sha256=gH12H5eY_7DvZVQXiK29tq1bmzMfrtbqsht9dG2D6io,3064
7
+ backlex/types.py,sha256=jU6_hXGiT17MajF4ma93C1eNb8z5NANx0R97ZFqrw-k,2116
8
+ backlex-0.0.1.dist-info/METADATA,sha256=XPJI9xJPWR6_zE1_iWInZeCzZQTASKF3VOqqtmNig7I,5189
9
+ backlex-0.0.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
10
+ backlex-0.0.1.dist-info/licenses/LICENSE,sha256=EsmwiN6x8FpGdneLPDRmUxEGqqWFxtz1b9Beu2eUdek,11344
11
+ backlex-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work, excluding
103
+ those notices that do not pertain to any part of the Derivative
104
+ Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and do
117
+ not modify the License. You may add Your own attribution notices
118
+ within Derivative Works that You distribute, alongside or as an
119
+ addendum to the NOTICE text from the Work, provided that such
120
+ additional attribution notices cannot be construed as modifying
121
+ the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Furkan Kınyas
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.