webcompy-server 0.0.14__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.
- webcompy_server/__init__.py +91 -0
- webcompy_server/_asgi.py +832 -0
- webcompy_server/_context.py +106 -0
- webcompy_server/_html.py +925 -0
- webcompy_server/_prebuild.py +487 -0
- webcompy_server/_static_route.py +41 -0
- webcompy_server/_teleport_emission.py +94 -0
- webcompy_server/contrib/__init__.py +0 -0
- webcompy_server/contrib/fastapi.py +42 -0
- webcompy_server/ports/__init__.py +35 -0
- webcompy_server/ports/_async_scheduler.py +74 -0
- webcompy_server/ports/_cookie.py +154 -0
- webcompy_server/ports/_custom_element.py +72 -0
- webcompy_server/ports/_dom.py +380 -0
- webcompy_server/ports/_event_source.py +48 -0
- webcompy_server/ports/_fetch.py +290 -0
- webcompy_server/ports/_ffi.py +72 -0
- webcompy_server/ports/_history.py +47 -0
- webcompy_server/ports/_host.py +71 -0
- webcompy_server/ports/_media_query.py +27 -0
- webcompy_server/ports/_resource.py +280 -0
- webcompy_server/ports/_selector.py +238 -0
- webcompy_server/ports/_transition.py +75 -0
- webcompy_server/ports/_virtual_dom.py +590 -0
- webcompy_server/ports/_websocket.py +54 -0
- webcompy_server/py.typed +0 -0
- webcompy_server/rpc/__init__.py +8 -0
- webcompy_server/rpc/_dispatcher.py +424 -0
- webcompy_server/rpc/_streams.py +102 -0
- webcompy_server/rpc/_subscriptions.py +235 -0
- webcompy_server/rpc/_ws_endpoint.py +102 -0
- webcompy_server-0.0.14.dist-info/METADATA +45 -0
- webcompy_server-0.0.14.dist-info/RECORD +35 -0
- webcompy_server-0.0.14.dist-info/WHEEL +4 -0
- webcompy_server-0.0.14.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
"""Server-side DOM port backed by a virtual DOM."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import html as html_module
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from webcompy.ports._dom import DOMEvent, DOMNode, DOMPort
|
|
10
|
+
from webcompy_server.ports._selector import parse_selector, resolve_parsed
|
|
11
|
+
from webcompy_server.ports._virtual_dom import VirtualDOMEvent, VirtualDOMNode
|
|
12
|
+
|
|
13
|
+
_VOID_ELEMENTS = frozenset(
|
|
14
|
+
{
|
|
15
|
+
"area",
|
|
16
|
+
"base",
|
|
17
|
+
"br",
|
|
18
|
+
"col",
|
|
19
|
+
"embed",
|
|
20
|
+
"hr",
|
|
21
|
+
"img",
|
|
22
|
+
"input",
|
|
23
|
+
"link",
|
|
24
|
+
"meta",
|
|
25
|
+
"param",
|
|
26
|
+
"source",
|
|
27
|
+
"track",
|
|
28
|
+
"wbr",
|
|
29
|
+
}
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
_RAW_CONTENT_ELEMENTS = frozenset({"script", "style"})
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ServerDOMPort(DOMPort):
|
|
37
|
+
"""Server-side DOM port that creates virtual nodes and serializes HTML."""
|
|
38
|
+
|
|
39
|
+
def __init__(self) -> None:
|
|
40
|
+
self._document_root: DOMNode | None = None
|
|
41
|
+
|
|
42
|
+
def _attach_document_root(self, root: DOMNode) -> None:
|
|
43
|
+
"""Attach the completed document tree node for selector resolution.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
root: Rendered document root node (typically the ``<html>``
|
|
47
|
+
element produced by HTML assembly).
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
``None``.
|
|
51
|
+
|
|
52
|
+
"""
|
|
53
|
+
self._document_root = root
|
|
54
|
+
|
|
55
|
+
def _create_static_element(
|
|
56
|
+
self,
|
|
57
|
+
tag: str,
|
|
58
|
+
attrs: dict[str, str | None],
|
|
59
|
+
*,
|
|
60
|
+
static_spec: Any,
|
|
61
|
+
belonging_component: str = "",
|
|
62
|
+
) -> DOMNode:
|
|
63
|
+
node = self.create_element(tag)
|
|
64
|
+
for name, value in attrs.items():
|
|
65
|
+
if value is not None:
|
|
66
|
+
node.setAttribute(name, value)
|
|
67
|
+
node._lazy_inner_html = static_spec.render_inner_html(belonging_component)
|
|
68
|
+
return node
|
|
69
|
+
|
|
70
|
+
def create_element(self, tag: str) -> DOMNode:
|
|
71
|
+
"""Create an element node for ``tag``.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
tag: Tag name.
|
|
75
|
+
|
|
76
|
+
Returns:
|
|
77
|
+
New virtual element node.
|
|
78
|
+
|
|
79
|
+
"""
|
|
80
|
+
return VirtualDOMNode(tag)
|
|
81
|
+
|
|
82
|
+
def create_text_node(self, text: str) -> DOMNode:
|
|
83
|
+
"""Create a text node.
|
|
84
|
+
|
|
85
|
+
Args:
|
|
86
|
+
text: Text content.
|
|
87
|
+
|
|
88
|
+
Returns:
|
|
89
|
+
New virtual text node.
|
|
90
|
+
|
|
91
|
+
"""
|
|
92
|
+
return VirtualDOMNode("#text", node_type=3, text_content=text)
|
|
93
|
+
|
|
94
|
+
def create_comment(self, data: str) -> DOMNode:
|
|
95
|
+
"""Create a comment node.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
data: Comment data.
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
New virtual comment node.
|
|
102
|
+
|
|
103
|
+
"""
|
|
104
|
+
return VirtualDOMNode("#comment", node_type=8, text_content=data)
|
|
105
|
+
|
|
106
|
+
def create_event(
|
|
107
|
+
self,
|
|
108
|
+
event_type: str,
|
|
109
|
+
*,
|
|
110
|
+
bubbles: bool = False,
|
|
111
|
+
cancelable: bool = False,
|
|
112
|
+
) -> DOMEvent:
|
|
113
|
+
"""Create a virtual DOM event.
|
|
114
|
+
|
|
115
|
+
Args:
|
|
116
|
+
event_type: Event type name.
|
|
117
|
+
bubbles: Whether the event bubbles.
|
|
118
|
+
cancelable: Whether the event is cancelable.
|
|
119
|
+
|
|
120
|
+
Returns:
|
|
121
|
+
New virtual event.
|
|
122
|
+
|
|
123
|
+
"""
|
|
124
|
+
return VirtualDOMEvent(event_type, bubbles=bubbles, cancelable=cancelable)
|
|
125
|
+
|
|
126
|
+
def query_selector(self, selector: str) -> DOMNode | None:
|
|
127
|
+
"""Query the attached document tree for ``selector``.
|
|
128
|
+
|
|
129
|
+
Resolution supports a documented CSS subset (type/class/id
|
|
130
|
+
selectors, compounds, descendant and child combinators, comma
|
|
131
|
+
groups) and returns the first depth-first match. Unsupported
|
|
132
|
+
syntax raises ``ValueError``.
|
|
133
|
+
|
|
134
|
+
Args:
|
|
135
|
+
selector: CSS selector from the supported subset.
|
|
136
|
+
|
|
137
|
+
Returns:
|
|
138
|
+
First matching node, or ``None`` when nothing matches or no
|
|
139
|
+
document tree has been attached yet.
|
|
140
|
+
|
|
141
|
+
Raises:
|
|
142
|
+
ValueError: When the selector uses unsupported syntax.
|
|
143
|
+
|
|
144
|
+
"""
|
|
145
|
+
try:
|
|
146
|
+
parsed = parse_selector(selector)
|
|
147
|
+
except ValueError:
|
|
148
|
+
raise
|
|
149
|
+
if self._document_root is None:
|
|
150
|
+
return None
|
|
151
|
+
return resolve_parsed(self._document_root, parsed)
|
|
152
|
+
|
|
153
|
+
def query_selector_all(
|
|
154
|
+
self,
|
|
155
|
+
selector: str,
|
|
156
|
+
*,
|
|
157
|
+
root: DOMNode | None = None,
|
|
158
|
+
) -> list[DOMNode]:
|
|
159
|
+
"""Query for all matching nodes, scoped to ``root`` when given.
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
selector: CSS selector string.
|
|
163
|
+
root: Optional subtree root.
|
|
164
|
+
|
|
165
|
+
Returns:
|
|
166
|
+
Matching element nodes in document order.
|
|
167
|
+
|
|
168
|
+
"""
|
|
169
|
+
scope = root if root is not None else self._document_root
|
|
170
|
+
if scope is None:
|
|
171
|
+
return []
|
|
172
|
+
nodes = _collect_all(selector, scope)
|
|
173
|
+
return nodes
|
|
174
|
+
|
|
175
|
+
def get_element_by_id(self, element_id: str) -> DOMNode | None:
|
|
176
|
+
"""Return the element with ``element_id``.
|
|
177
|
+
|
|
178
|
+
Args:
|
|
179
|
+
element_id: Element ID.
|
|
180
|
+
|
|
181
|
+
Returns:
|
|
182
|
+
``None`` on the server.
|
|
183
|
+
|
|
184
|
+
"""
|
|
185
|
+
return None
|
|
186
|
+
|
|
187
|
+
def set_title(self, title: str) -> None:
|
|
188
|
+
"""Set the document title.
|
|
189
|
+
|
|
190
|
+
Args:
|
|
191
|
+
title: Title to set.
|
|
192
|
+
|
|
193
|
+
Returns:
|
|
194
|
+
``None``.
|
|
195
|
+
|
|
196
|
+
"""
|
|
197
|
+
pass
|
|
198
|
+
|
|
199
|
+
def add_document_event_listener(
|
|
200
|
+
self, event_type: str, handler: Any, *, capture: bool = False
|
|
201
|
+
) -> Callable[[], None]:
|
|
202
|
+
"""Add a document-level event listener.
|
|
203
|
+
|
|
204
|
+
Args:
|
|
205
|
+
event_type: Event type.
|
|
206
|
+
handler: Event handler.
|
|
207
|
+
capture: Ignored on the server; accepted for interface parity
|
|
208
|
+
with the browser port.
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
Callable that removes the listener.
|
|
212
|
+
|
|
213
|
+
"""
|
|
214
|
+
return lambda: None
|
|
215
|
+
|
|
216
|
+
def render_html(self, node: DOMNode) -> str:
|
|
217
|
+
"""Serialize ``node`` to HTML.
|
|
218
|
+
|
|
219
|
+
Args:
|
|
220
|
+
node: Virtual DOM node to serialize.
|
|
221
|
+
|
|
222
|
+
Returns:
|
|
223
|
+
HTML string for ``node``.
|
|
224
|
+
|
|
225
|
+
"""
|
|
226
|
+
return _serialize_node(node)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _collect_all(selector: str, scope: DOMNode) -> list[DOMNode]:
|
|
230
|
+
"""Collect all nodes matching ``selector`` within ``scope``."""
|
|
231
|
+
try:
|
|
232
|
+
parsed = parse_selector(selector)
|
|
233
|
+
except ValueError:
|
|
234
|
+
return _collect_by_attribute_fallback(selector, scope)
|
|
235
|
+
collected: list[DOMNode] = []
|
|
236
|
+
stack: list[DOMNode] = [scope]
|
|
237
|
+
while stack:
|
|
238
|
+
node = stack.pop()
|
|
239
|
+
if node.nodeType != 1:
|
|
240
|
+
continue
|
|
241
|
+
from webcompy_server.ports._selector import _matches_chain # type: ignore[attr-defined]
|
|
242
|
+
|
|
243
|
+
if any(_matches_chain(node, chain, scope) for chain in parsed): # type: ignore[arg-type]
|
|
244
|
+
collected.append(node)
|
|
245
|
+
children = node.childNodes
|
|
246
|
+
for index in range(children.length - 1, -1, -1):
|
|
247
|
+
stack.append(children[index])
|
|
248
|
+
return _sort_document_order(collected, scope)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _sort_document_order(nodes: list[DOMNode], scope: DOMNode) -> list[DOMNode]:
|
|
252
|
+
order: list[DOMNode] = []
|
|
253
|
+
stack: list[DOMNode] = [scope]
|
|
254
|
+
while stack:
|
|
255
|
+
current = stack.pop()
|
|
256
|
+
order.append(current)
|
|
257
|
+
children = current.childNodes
|
|
258
|
+
for index in range(children.length - 1, -1, -1):
|
|
259
|
+
stack.append(children[index])
|
|
260
|
+
index_map = {id(n): i for i, n in enumerate(order)}
|
|
261
|
+
return sorted(nodes, key=lambda n: index_map.get(id(n), len(order)))
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _collect_by_attribute_fallback(selector: str, scope: DOMNode) -> list[DOMNode]:
|
|
265
|
+
"""Fallback for attribute-containing selectors on the server virtual DOM."""
|
|
266
|
+
|
|
267
|
+
results: list[DOMNode] = []
|
|
268
|
+
stack: list[DOMNode] = [scope]
|
|
269
|
+
while stack:
|
|
270
|
+
node = stack.pop()
|
|
271
|
+
if node.nodeType == 1 and _node_matches_any_group(node, selector):
|
|
272
|
+
results.append(node)
|
|
273
|
+
children = node.childNodes
|
|
274
|
+
for index in range(children.length - 1, -1, -1):
|
|
275
|
+
stack.append(children[index])
|
|
276
|
+
return _sort_document_order(results, scope)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _node_matches_any_group(node: DOMNode, selector: str) -> bool:
|
|
280
|
+
for group in selector.split(","):
|
|
281
|
+
group = group.strip()
|
|
282
|
+
if group and _matches_attr_group(node, group):
|
|
283
|
+
return True
|
|
284
|
+
return False
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _matches_attr_group(node: DOMNode, group: str) -> bool:
|
|
288
|
+
|
|
289
|
+
if ":not(" in group:
|
|
290
|
+
outer, _, inner = group.partition(":not(")
|
|
291
|
+
inner = inner.rstrip(")")
|
|
292
|
+
outer = outer.strip()
|
|
293
|
+
if not _attr_match(node, outer):
|
|
294
|
+
return False
|
|
295
|
+
return not _attr_match(node, inner.strip())
|
|
296
|
+
return _attr_match(node, group)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _attr_match(node: DOMNode, expr: str) -> bool:
|
|
300
|
+
import re as _re
|
|
301
|
+
|
|
302
|
+
expr = expr.strip()
|
|
303
|
+
if not expr:
|
|
304
|
+
return False
|
|
305
|
+
tag: str | None = None
|
|
306
|
+
tag_m = _re.match(r"^([a-zA-Z][a-zA-Z0-9]*)", expr)
|
|
307
|
+
rest = expr
|
|
308
|
+
if tag_m:
|
|
309
|
+
tag = tag_m.group(1).lower()
|
|
310
|
+
rest = expr[len(tag_m.group(1)) :]
|
|
311
|
+
if not rest.strip():
|
|
312
|
+
return node.nodeName.lower() == tag
|
|
313
|
+
rest = rest.strip()
|
|
314
|
+
if tag is not None and not rest:
|
|
315
|
+
return node.nodeName.lower() == tag
|
|
316
|
+
attr_re = _re.compile(r'^\[([a-zA-Z0-9_-]+)(?:="([^"]*)")?\]')
|
|
317
|
+
has_attr = False
|
|
318
|
+
while rest:
|
|
319
|
+
rest = rest.strip()
|
|
320
|
+
if not rest:
|
|
321
|
+
break
|
|
322
|
+
m = attr_re.match(rest)
|
|
323
|
+
if m is None:
|
|
324
|
+
return False
|
|
325
|
+
has_attr = True
|
|
326
|
+
attr_name = m.group(1)
|
|
327
|
+
attr_value = m.group(2)
|
|
328
|
+
actual = node.getAttribute(attr_name)
|
|
329
|
+
if attr_value is None:
|
|
330
|
+
if actual is None:
|
|
331
|
+
return False
|
|
332
|
+
else:
|
|
333
|
+
if actual != attr_value:
|
|
334
|
+
return False
|
|
335
|
+
rest = rest[m.end() :]
|
|
336
|
+
if has_attr:
|
|
337
|
+
return not (tag is not None and node.nodeName.lower() != tag)
|
|
338
|
+
if tag is not None:
|
|
339
|
+
return node.nodeName.lower() == tag
|
|
340
|
+
return False
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _serialize_node(node: DOMNode) -> str:
|
|
344
|
+
if node.nodeType == 8:
|
|
345
|
+
data = node.textContent or ""
|
|
346
|
+
if "--" in data or data.endswith("-"):
|
|
347
|
+
raise ValueError(f"Comment data must not contain '--' or end with '-': {data!r}")
|
|
348
|
+
return f"<!--{data}-->"
|
|
349
|
+
if node.nodeType == 3:
|
|
350
|
+
text = node.textContent or ""
|
|
351
|
+
parent = node.parentNode
|
|
352
|
+
if parent is not None and parent.nodeName.lower() in _RAW_CONTENT_ELEMENTS:
|
|
353
|
+
return text
|
|
354
|
+
return html_module.escape(text)
|
|
355
|
+
tag_lower = node.nodeName.lower()
|
|
356
|
+
attrs_str = _serialize_attrs(node)
|
|
357
|
+
if tag_lower in _VOID_ELEMENTS:
|
|
358
|
+
return f"<{tag_lower}{attrs_str}>"
|
|
359
|
+
inner_html = getattr(node, "innerHTML", None)
|
|
360
|
+
if inner_html is not None:
|
|
361
|
+
return f"<{tag_lower}{attrs_str}>{inner_html}</{tag_lower}>"
|
|
362
|
+
lazy_inner_html = getattr(node, "_lazy_inner_html", None)
|
|
363
|
+
if lazy_inner_html is not None:
|
|
364
|
+
return f"<{tag_lower}{attrs_str}>{lazy_inner_html}</{tag_lower}>"
|
|
365
|
+
children_html = "".join(_serialize_node(node.childNodes[i]) for i in range(node.childNodes.length))
|
|
366
|
+
return f"<{tag_lower}{attrs_str}>{children_html}</{tag_lower}>"
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _serialize_attrs(node: DOMNode) -> str:
|
|
370
|
+
parts: list[str] = []
|
|
371
|
+
for name in node.getAttributeNames():
|
|
372
|
+
value = node.getAttribute(name)
|
|
373
|
+
if value is None:
|
|
374
|
+
parts.append(name)
|
|
375
|
+
else:
|
|
376
|
+
escaped = html_module.escape(value, quote=True)
|
|
377
|
+
parts.append(f'{name}="{escaped}"')
|
|
378
|
+
if parts:
|
|
379
|
+
return " " + " ".join(parts)
|
|
380
|
+
return ""
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Server-side event source port."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
|
|
7
|
+
from webcompy.ports._event_source import EventSourcePort
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ServerEventSourcePort(EventSourcePort):
|
|
11
|
+
"""Server-side no-op ``EventSourcePort``.
|
|
12
|
+
|
|
13
|
+
``noop = True`` marks this port as a pure no-op: ``use_event_source`` uses
|
|
14
|
+
it as the signal that SSR/SSG degradation (warning + empty closed handle)
|
|
15
|
+
applies, rather than opening a connection through the port.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
noop = True
|
|
19
|
+
|
|
20
|
+
def open(
|
|
21
|
+
self,
|
|
22
|
+
url: str,
|
|
23
|
+
*,
|
|
24
|
+
events: tuple[str, ...],
|
|
25
|
+
on_open: Callable[[], None],
|
|
26
|
+
on_message: Callable[[str, str, str], None],
|
|
27
|
+
on_error: Callable[[], None],
|
|
28
|
+
on_close: Callable[[], None],
|
|
29
|
+
) -> Callable[[], None]:
|
|
30
|
+
"""Open an event source connection.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
url: Event source URL.
|
|
34
|
+
events: Event types to listen for.
|
|
35
|
+
on_open: Callback when the connection opens.
|
|
36
|
+
on_message: Callback for incoming messages.
|
|
37
|
+
on_error: Callback for errors.
|
|
38
|
+
on_close: Callback when the connection closes.
|
|
39
|
+
|
|
40
|
+
Returns:
|
|
41
|
+
Callable that closes the connection.
|
|
42
|
+
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def _noop() -> None:
|
|
46
|
+
pass
|
|
47
|
+
|
|
48
|
+
return _noop
|