rendor 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
rendor/__init__.py ADDED
@@ -0,0 +1,92 @@
1
+ """Rendor server SDK for Python.
2
+
3
+ Build UI with generated component builders (``rendor gen --lang python``) or ``node()``,
4
+ return documents from screens and ops from events, and serve with ``app.serve()`` or mount
5
+ ``app.asgi()``. Internals live in submodules; tests use ``rendor.testing``.
6
+ """
7
+
8
+ from importlib import metadata as _metadata
9
+
10
+ from . import ops
11
+ from ._types import (
12
+ Action,
13
+ Child,
14
+ Document,
15
+ LiteralValue,
16
+ Node,
17
+ Op,
18
+ Ref,
19
+ SectionRef,
20
+ Source,
21
+ StateRef,
22
+ )
23
+ from .actions import (
24
+ action,
25
+ apply,
26
+ back,
27
+ navigate,
28
+ open_url,
29
+ refresh,
30
+ sequence,
31
+ server,
32
+ set_state,
33
+ toggle_state,
34
+ )
35
+ from .app import App, DedupeStore, Route
36
+ from .channels import MemoryBackend
37
+ from .client import ClientInfo
38
+ from .cors import Cors
39
+ from .diff import diff
40
+ from .errors import Logger, RendorError
41
+ from .nodes import defer, node, section
42
+ from .request import Context, Request
43
+ from .stream import StreamOptions
44
+ from .values import literal, state
45
+ from .windowing import feed_window
46
+
47
+ try:
48
+ __version__: str = _metadata.version("rendor")
49
+ except _metadata.PackageNotFoundError: # pragma: no cover - running from a source tree
50
+ __version__ = "0.0.0+unknown"
51
+
52
+ __all__ = [
53
+ "Action",
54
+ "App",
55
+ "Child",
56
+ "ClientInfo",
57
+ "Context",
58
+ "Cors",
59
+ "DedupeStore",
60
+ "Document",
61
+ "LiteralValue",
62
+ "Logger",
63
+ "MemoryBackend",
64
+ "Node",
65
+ "Op",
66
+ "Ref",
67
+ "RendorError",
68
+ "Request",
69
+ "Route",
70
+ "SectionRef",
71
+ "Source",
72
+ "StateRef",
73
+ "StreamOptions",
74
+ "action",
75
+ "apply",
76
+ "back",
77
+ "defer",
78
+ "diff",
79
+ "feed_window",
80
+ "literal",
81
+ "navigate",
82
+ "node",
83
+ "open_url",
84
+ "ops",
85
+ "refresh",
86
+ "section",
87
+ "sequence",
88
+ "server",
89
+ "set_state",
90
+ "state",
91
+ "toggle_state",
92
+ ]
rendor/__main__.py ADDED
@@ -0,0 +1,36 @@
1
+ """``python -m rendor sections export module:app`` prints the app's section manifest
2
+ (sections §6.1): compact JSON with the keys of every object sorted, the same bytes the
3
+ ``GET /_rendor/sections`` endpoint serves."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import importlib
8
+ import sys
9
+ from typing import Any
10
+
11
+ USAGE = "usage: python -m rendor sections export <module>[:<attribute>] (default attribute: app)"
12
+
13
+
14
+ def load_app(spec: str) -> Any:
15
+ module, _, attr = spec.partition(":")
16
+ sys.path.insert(0, "") # the working directory, like `python -m` and `uvicorn`
17
+ app: Any = getattr(importlib.import_module(module), attr or "app")
18
+ return app() if callable(app) and not hasattr(app, "sections_manifest_json") else app
19
+
20
+
21
+ def main(argv: list[str]) -> int:
22
+ if len(argv) != 3 or argv[:2] != ["sections", "export"]:
23
+ print(USAGE, file=sys.stderr)
24
+ return 2
25
+ try:
26
+ app = load_app(argv[2])
27
+ out: bytes = app.sections_manifest_json()
28
+ except (ImportError, AttributeError) as e:
29
+ print(f"rendor: can't load {argv[2]!r}: {e}", file=sys.stderr)
30
+ return 1
31
+ sys.stdout.buffer.write(out + b"\n")
32
+ return 0
33
+
34
+
35
+ if __name__ == "__main__":
36
+ raise SystemExit(main(sys.argv[1:]))
rendor/_tasks.py ADDED
@@ -0,0 +1,21 @@
1
+ """Concurrency helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from collections.abc import Coroutine
7
+ from typing import Any
8
+
9
+
10
+ async def gather[T](*coros: Coroutine[Any, Any, T]) -> list[T]:
11
+ """Runs coroutines concurrently and returns their results in order. The first failure
12
+ cancels the siblings that are still running and is raised as itself (not wrapped in an
13
+ exception group): ``asyncio.gather`` would leave them running."""
14
+ if len(coros) == 1:
15
+ return [await coros[0]]
16
+ try:
17
+ async with asyncio.TaskGroup() as tg:
18
+ tasks = [tg.create_task(c) for c in coros]
19
+ except BaseExceptionGroup as eg:
20
+ raise eg.exceptions[0] from None
21
+ return [t.result() for t in tasks]
rendor/_types.py ADDED
@@ -0,0 +1,94 @@
1
+ """Shapes shared by the builders, the encoder, and generated code.
2
+
3
+ Nodes, actions, and ops are plain ``dict``\\ s in wire field names (camelCase), so
4
+ they serialize directly with orjson and compare with ``==`` in tests. The aliases
5
+ below document intent; the builders are what keep them well-formed.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping, Sequence
11
+ from dataclasses import KW_ONLY, dataclass
12
+ from typing import Any, Literal, NotRequired, TypedDict
13
+
14
+ type Json = str | int | float | bool | None | Sequence[Json] | Mapping[str, Json]
15
+
16
+ #: A node as built on the server: ``{"type", "id"?, "props"?, "children"?, "slots"?, "on"?,
17
+ #: "visible"?, "fallback"?}``. Children, slots, and fallbacks may be section references.
18
+ type Node = dict[str, Any]
19
+ #: ``{"section", "params"?, "id"?, "fallback"?}``: a server-only placeholder (sections §1).
20
+ type SectionRef = dict[str, Any]
21
+ #: Anything that may stand where a node goes in source output.
22
+ type Source = Node | SectionRef
23
+ #: ``{"do": ..., ...}`` (protocol §7).
24
+ type Action = dict[str, Any]
25
+ #: ``{"op": ..., ...}`` (protocol §6).
26
+ type Op = dict[str, Any]
27
+ #: What ``children=`` and slot values accept: nodes, references, nested lists, and holes
28
+ #: (``None``/``False``/``True`` are dropped, so ``cond and Text(...)`` works).
29
+ type Child = Node | None | bool | Sequence[Child]
30
+
31
+ StateRef = TypedDict("StateRef", {"$state": str, "eq": NotRequired[Any], "not": NotRequired[bool]})
32
+ """``{"$state": key, "eq"?: value, "not"?: true}`` (protocol §4.1)."""
33
+
34
+ LiteralValue = TypedDict("LiteralValue", {"$literal": Any})
35
+ """``{"$literal": value}``: delivered verbatim (protocol §4.2)."""
36
+
37
+ #: Any prop can be a reference instead of a plain value.
38
+ type Ref = StateRef | LiteralValue
39
+
40
+ Concurrency = Literal["queue", "latest", "drop", "parallel"]
41
+ Presentation = Literal["push", "modal", "sheet"]
42
+ #: ``"start"``, ``"end"``, ``{"before": id}``, or ``{"after": id}``.
43
+ type Position = Literal["start", "end"] | Mapping[str, str]
44
+ #: ``True`` (platform default), a transition token name, or ``False``.
45
+ type Animate = bool | str
46
+ #: Context dimensions output may depend on (sections §2, http.md §7).
47
+ Variant = Literal["locale", "timezone", "catalog", "platform", "user"]
48
+ Mode = Literal["development", "production"]
49
+ #: Every context dimension, in canonical order.
50
+ VARIANTS: tuple[Variant, ...] = ("locale", "timezone", "platform", "catalog", "user")
51
+
52
+
53
+ @dataclass(slots=True)
54
+ class Document:
55
+ """What a screen returns: the document body (protocol §2).
56
+
57
+ ``path`` defaults to the request path (with its query string) and ``rendor``
58
+ to the protocol version. ``refresh_on_focus`` and ``offline`` are the document options.
59
+ """
60
+
61
+ root: Source
62
+ _: KW_ONLY
63
+ state: dict[str, Any] | None = None
64
+ meta: dict[str, Any] | None = None
65
+ subscribe: list[str] | None = None
66
+ refresh_on_focus: bool = False
67
+ offline: bool = False
68
+ path: str | None = None
69
+ rendor: str | None = None
70
+
71
+ def to_dict(self) -> dict[str, Any]:
72
+ """The source document as a dict (unset fields omitted)."""
73
+ out: dict[str, Any] = {"root": self.root}
74
+ for k in ("state", "meta", "subscribe", "path", "rendor"):
75
+ v = getattr(self, k)
76
+ if v is not None:
77
+ out[k] = v
78
+ options = {
79
+ k: True
80
+ for k, on in (("refreshOnFocus", self.refresh_on_focus), ("offline", self.offline))
81
+ if on
82
+ }
83
+ if options:
84
+ out["options"] = options
85
+ return out
86
+
87
+
88
+ def as_source_document(value: Any) -> dict[str, Any]:
89
+ """A source document dict from a ``Document`` or a dict with a ``root``."""
90
+ if isinstance(value, Document):
91
+ return value.to_dict()
92
+ if isinstance(value, Mapping) and "root" in value:
93
+ return dict(value)
94
+ raise TypeError(f"expected a Document or a dict with a root, got {type(value).__name__}")
rendor/actions.py ADDED
@@ -0,0 +1,136 @@
1
+ """Action builders (protocol §7). Keyword arguments are snake_case and map to the wire's
2
+ camelCase (``concurrency_key`` → ``concurrencyKey``, ``on_error`` → ``onError``). ``None``
3
+ means "not set"; fields equal to their default are omitted by the encoder."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from collections.abc import Iterable, Mapping, Sequence
8
+ from typing import Any, Literal
9
+
10
+ from ._types import Action, Concurrency, Op, Presentation, StateRef
11
+
12
+
13
+ def _with_once(out: Action, once: bool | None) -> Action:
14
+ if once is not None:
15
+ out["once"] = once
16
+ return out
17
+
18
+
19
+ def server(
20
+ event: str,
21
+ *,
22
+ args: Mapping[str, Any] | None = None,
23
+ send: Literal["all", "none"] | Sequence[str] | None = None,
24
+ pending: str | None = None,
25
+ concurrency: Concurrency | None = None,
26
+ concurrency_key: str | None = None,
27
+ debounce: int | None = None,
28
+ on_error: Action | None = None,
29
+ optimistic: Iterable[Op] | None = None,
30
+ section: str | None = None,
31
+ seal: bool | None = None,
32
+ once: bool | None = None,
33
+ ) -> Action:
34
+ """``{"do": "server", "event": ..., ...}`` (protocol §7.3). ``section`` is normally stamped
35
+ by section expansion; set it only to override.
36
+
37
+ ``seal=True`` makes the app send the action's ``args`` sealed (as ``sealed``, in place of
38
+ ``args``; protocol §7.3.1), which a ``sealed=True`` event handler requires. It needs the
39
+ app's ``seal_keys``. Sealed args are tamper-proof, not encrypted: the client can read them.
40
+ They must be constants (no state references).
41
+
42
+ ``optimistic`` lists ops (``replace``, ``update``, ``insert``, ``remove``, ``move``,
43
+ ``setState``) the client shows at dispatch, as a preview removed when the request settles
44
+ (protocol §7.3.2). Section references aren't allowed in them."""
45
+ out: Action = {"do": "server", "event": event}
46
+ if seal:
47
+ out["seal"] = True
48
+ if args is not None:
49
+ out["args"] = dict(args)
50
+ if send is not None:
51
+ out["send"] = send if isinstance(send, str) else list(send)
52
+ if pending is not None:
53
+ out["pending"] = pending
54
+ if concurrency is not None:
55
+ out["concurrency"] = concurrency
56
+ if concurrency_key is not None:
57
+ out["concurrencyKey"] = concurrency_key
58
+ if debounce is not None:
59
+ out["debounce"] = debounce
60
+ if section is not None:
61
+ out["section"] = section
62
+ if optimistic is not None:
63
+ out["optimistic"] = list(optimistic)
64
+ if on_error is not None:
65
+ out["onError"] = on_error
66
+ return _with_once(out, once)
67
+
68
+
69
+ def navigate(
70
+ to: str | StateRef,
71
+ *,
72
+ replace: bool | StateRef | None = None,
73
+ presentation: Presentation | None = None,
74
+ once: bool | None = None,
75
+ ) -> Action:
76
+ out: Action = {"do": "navigate", "to": to}
77
+ if replace is not None:
78
+ out["replace"] = replace
79
+ if presentation is not None:
80
+ out["presentation"] = presentation
81
+ return _with_once(out, once)
82
+
83
+
84
+ def back(*, once: bool | None = None) -> Action:
85
+ return _with_once({"do": "back"}, once)
86
+
87
+
88
+ def open_url(url: str | StateRef, *, once: bool | None = None) -> Action:
89
+ return _with_once({"do": "openUrl", "url": url}, once)
90
+
91
+
92
+ def set_state(values: Mapping[str, Any], *, once: bool | None = None) -> Action:
93
+ """Merges into state; ``None`` deletes a key. Values may be references."""
94
+ return _with_once({"do": "setState", "values": dict(values)}, once)
95
+
96
+
97
+ def toggle_state(key: str, *, once: bool | None = None) -> Action:
98
+ return _with_once({"do": "toggleState", "key": key}, once)
99
+
100
+
101
+ def apply(ops: Iterable[Op], *, once: bool | None = None) -> Action:
102
+ """Applies ops locally, with no network (protocol §7.2)."""
103
+ return _with_once({"do": "apply", "ops": list(ops)}, once)
104
+
105
+
106
+ def sequence(*actions: Action, once: bool | None = None) -> Action:
107
+ """Runs actions in order: ``sequence(a, b, c)`` or ``sequence(a, b, once=True)``."""
108
+ for a in actions:
109
+ if not isinstance(a, Mapping):
110
+ raise TypeError(
111
+ f"sequence(a, b, ...) takes actions as arguments, not {type(a).__name__}: "
112
+ "unpack a list with sequence(*actions)"
113
+ )
114
+ return _with_once({"do": "sequence", "actions": list(actions)}, once)
115
+
116
+
117
+ def refresh(*, keep: Sequence[str] | None = None, once: bool | None = None) -> Action:
118
+ out: Action = {"do": "refresh"}
119
+ if keep is not None:
120
+ out["keep"] = list(keep)
121
+ return _with_once(out, once)
122
+
123
+
124
+ def action(
125
+ name: str, /, params: Mapping[str, Any] | None = None, *, once: bool | None = None
126
+ ) -> Action:
127
+ """An app action with untyped params: ``action("toast.show", {"text": "Saved"}, once=True)``.
128
+ Params are an explicit dict (wire names, ``None`` values dropped), so a param can never
129
+ collide with an option such as ``once``. Generated modules have typed builders
130
+ (``toast_show(text=...)``)."""
131
+ out: Action = {"do": name}
132
+ if params:
133
+ for k, v in params.items():
134
+ if v is not None:
135
+ out[k] = v
136
+ return _with_once(out, once)