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.
@@ -0,0 +1,280 @@
1
+ """Server-side resource ports for app-package and embedded resources."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable, Mapping
6
+ from pathlib import Path
7
+ from types import MappingProxyType
8
+
9
+ from webcompy.ports._resource import ResourceNotFoundError, ResourcePort
10
+
11
+
12
+ def _validate_resource_path(path: str, allow_list: frozenset[str]) -> None:
13
+ if not path:
14
+ raise ResourceNotFoundError(path or "<empty>", "server", reason="empty path")
15
+ if path.startswith("/"):
16
+ raise ResourceNotFoundError(path, "server", reason="path must be relative")
17
+ if "\\" in path:
18
+ raise ResourceNotFoundError(path, "server", reason="path must use POSIX separators")
19
+ segments = path.split("/")
20
+ if ".." in segments:
21
+ raise ResourceNotFoundError(path, "server", reason="path contains '..' segments")
22
+ if path not in allow_list:
23
+ raise ResourceNotFoundError(path, "server", reason="not in allow-list")
24
+
25
+
26
+ class ServerResourcePort(ResourcePort):
27
+ """Server-side resource loader that reads files from an app or public directory.
28
+
29
+ Args:
30
+ app_package_path: Filesystem root for relative resource resolution.
31
+ allow_list: Set of allowed package-relative POSIX paths.
32
+ cache: Whether to share loaded byte payloads across ``.fresh()`` clones.
33
+ When ``False`` (default), every load reads directly from disk.
34
+ _shared_cache: Internal shared cache passed across ``.fresh()`` clones.
35
+
36
+ Attributes:
37
+ cache: Whether cross-request byte caching is enabled.
38
+
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ app_package_path: Path,
44
+ allow_list: frozenset[str],
45
+ *,
46
+ cache: bool = False,
47
+ _shared_cache: dict[str, bytes] | None = None,
48
+ ) -> None:
49
+ self._app_package_path = app_package_path
50
+ self._allow_list = allow_list
51
+ self.cache = cache
52
+ self._shared_cache: dict[str, bytes] | None = (
53
+ _shared_cache if _shared_cache is not None else ({} if cache else None)
54
+ )
55
+ self._recorded: dict[str, bytes] = {}
56
+
57
+ def _validate(self, path: str) -> None:
58
+ _validate_resource_path(path, self._allow_list)
59
+
60
+ def _resolve(self, path: str) -> Path:
61
+ self._validate(path)
62
+ resolved = (self._app_package_path / path).resolve()
63
+ root_resolved = self._app_package_path.resolve()
64
+ try:
65
+ resolved.relative_to(root_resolved)
66
+ except ValueError as exc:
67
+ raise ResourceNotFoundError(path, "server", reason="path escapes app package") from exc
68
+ return resolved
69
+
70
+ async def load_text(self, path: str) -> str:
71
+ """Load a UTF-8 text resource.
72
+
73
+ Args:
74
+ path: Relative POSIX resource path.
75
+
76
+ Returns:
77
+ Decoded UTF-8 text content of the resource.
78
+
79
+ Raises:
80
+ ResourceNotFoundError: If the resource is missing, unreadable,
81
+ invalid UTF-8, or outside the allow-list.
82
+
83
+ """
84
+ if self._shared_cache is not None:
85
+ self._validate(path)
86
+ if path in self._shared_cache:
87
+ raw = self._shared_cache[path]
88
+ try:
89
+ text = raw.decode("utf-8")
90
+ except UnicodeDecodeError as exc:
91
+ raise ResourceNotFoundError(path, "server", reason=str(exc)) from exc
92
+ self._recorded[path] = raw
93
+ return text
94
+
95
+ resolved = self._resolve(path)
96
+ try:
97
+ if self._shared_cache is not None:
98
+ raw = resolved.read_bytes()
99
+ text = raw.decode("utf-8")
100
+ self._shared_cache[path] = raw
101
+ encoded = raw
102
+ else:
103
+ text = resolved.read_text(encoding="utf-8")
104
+ encoded = text.encode("utf-8")
105
+ except (OSError, UnicodeDecodeError) as exc:
106
+ raise ResourceNotFoundError(path, "server", reason=str(exc)) from exc
107
+ self._recorded[path] = encoded
108
+ return text
109
+
110
+ async def load_bytes(self, path: str) -> bytes:
111
+ """Load a binary resource.
112
+
113
+ Args:
114
+ path: Relative POSIX resource path.
115
+
116
+ Returns:
117
+ Binary content of the resource.
118
+
119
+ Raises:
120
+ ResourceNotFoundError: If the resource is missing, unreadable,
121
+ or outside the allow-list.
122
+
123
+ """
124
+ if self._shared_cache is not None:
125
+ self._validate(path)
126
+ if path in self._shared_cache:
127
+ content = self._shared_cache[path]
128
+ self._recorded[path] = content
129
+ return content
130
+
131
+ resolved = self._resolve(path)
132
+ try:
133
+ content = resolved.read_bytes()
134
+ except OSError as exc:
135
+ raise ResourceNotFoundError(path, "server", reason=str(exc)) from exc
136
+ if self._shared_cache is not None:
137
+ self._shared_cache[path] = content
138
+ self._recorded[path] = content
139
+ return content
140
+
141
+ def get_recorded_resources(self) -> dict[str, bytes]:
142
+ """Return recorded resource contents for the current request context.
143
+
144
+ Returns:
145
+ Mapping of loaded relative paths to raw byte contents.
146
+
147
+ """
148
+ return dict(self._recorded)
149
+
150
+ def fresh(self) -> ServerResourcePort:
151
+ """Create a per-request clone with an empty recorded-resource buffer.
152
+
153
+ Preserves configuration and shares the byte cache only when ``cache=True``.
154
+
155
+ Returns:
156
+ New ``ServerResourcePort`` with isolated per-request recording state.
157
+
158
+ """
159
+ return ServerResourcePort(
160
+ app_package_path=self._app_package_path,
161
+ allow_list=self._allow_list,
162
+ cache=self.cache,
163
+ _shared_cache=self._shared_cache,
164
+ )
165
+
166
+
167
+ class InMemoryServerResourcePort(ResourcePort):
168
+ """In-memory server resource port backed by embedded prebuild bytes.
169
+
170
+ Serves allow-listed resources with zero filesystem I/O while keeping
171
+ recorded hydration resources strictly isolated per ``.fresh()`` clone.
172
+
173
+ Args:
174
+ resources: Mapping from package-relative POSIX paths to raw bytes.
175
+ allow_list: Set of allowed package-relative POSIX paths.
176
+
177
+ """
178
+
179
+ def __init__(
180
+ self,
181
+ resources: Mapping[str, bytes],
182
+ allow_list: frozenset[str],
183
+ ) -> None:
184
+ self._resources: Mapping[str, bytes] = (
185
+ resources if isinstance(resources, MappingProxyType) else MappingProxyType(dict(resources))
186
+ )
187
+ self._allow_list = allow_list
188
+ self._recorded: dict[str, bytes] = {}
189
+
190
+ async def load_text(self, path: str) -> str:
191
+ """Load an embedded UTF-8 text resource from memory.
192
+
193
+ Args:
194
+ path: Relative POSIX resource path.
195
+
196
+ Returns:
197
+ Decoded UTF-8 text content of the resource.
198
+
199
+ Raises:
200
+ ResourceNotFoundError: If the resource is missing, not UTF-8,
201
+ or outside the allow-list.
202
+
203
+ """
204
+ _validate_resource_path(path, self._allow_list)
205
+ content = self._resources.get(path)
206
+ if content is None:
207
+ raise ResourceNotFoundError(path, "server", reason="missing embedded resource")
208
+ try:
209
+ text = content.decode("utf-8")
210
+ except UnicodeDecodeError as exc:
211
+ raise ResourceNotFoundError(path, "server", reason=str(exc)) from exc
212
+ self._recorded[path] = content
213
+ return text
214
+
215
+ async def load_bytes(self, path: str) -> bytes:
216
+ """Load an embedded binary resource from memory.
217
+
218
+ Args:
219
+ path: Relative POSIX resource path.
220
+
221
+ Returns:
222
+ Binary content of the resource.
223
+
224
+ Raises:
225
+ ResourceNotFoundError: If the resource is missing or outside
226
+ the allow-list.
227
+
228
+ """
229
+ _validate_resource_path(path, self._allow_list)
230
+ content = self._resources.get(path)
231
+ if content is None:
232
+ raise ResourceNotFoundError(path, "server", reason="missing embedded resource")
233
+ self._recorded[path] = content
234
+ return content
235
+
236
+ def get_recorded_resources(self) -> dict[str, bytes]:
237
+ """Return recorded resource contents for the current request context.
238
+
239
+ Returns:
240
+ Mapping of loaded relative paths to raw byte contents.
241
+
242
+ """
243
+ return dict(self._recorded)
244
+
245
+ def fresh(self) -> InMemoryServerResourcePort:
246
+ """Create a per-request clone sharing the immutable embedded bytes map.
247
+
248
+ Returns:
249
+ New ``InMemoryServerResourcePort`` with empty per-request recordings.
250
+
251
+ """
252
+ return InMemoryServerResourcePort(
253
+ resources=self._resources,
254
+ allow_list=self._allow_list,
255
+ )
256
+
257
+
258
+ class _RecordingResourcePortAdapter(ResourcePort):
259
+ def __init__(self, inner: ResourcePort) -> None:
260
+ self._inner = inner
261
+ self._recorded: dict[str, bytes] = {}
262
+
263
+ async def load_text(self, path: str) -> str:
264
+ text = await self._inner.load_text(path)
265
+ self._recorded[path] = text.encode("utf-8")
266
+ return text
267
+
268
+ async def load_bytes(self, path: str) -> bytes:
269
+ content = await self._inner.load_bytes(path)
270
+ self._recorded[path] = content
271
+ return content
272
+
273
+ async def preload(self, paths: Iterable[str]) -> None:
274
+ await self._inner.preload(paths)
275
+
276
+ def get_recorded_resources(self) -> dict[str, bytes]:
277
+ return dict(self._recorded)
278
+
279
+ def fresh(self) -> _RecordingResourcePortAdapter:
280
+ return _RecordingResourcePortAdapter(self._inner)
@@ -0,0 +1,238 @@
1
+ """Read-only CSS selector resolution over the server virtual DOM.
2
+
3
+ Implements a documented selector subset for ``ServerDOMPort.query_selector``:
4
+ type selectors, class selectors (``.name``), ID selectors (``#id``), their
5
+ compounds (``div.a#b``), descendant combinators (whitespace), child
6
+ combinators (``>``), and comma-separated groups. Any other syntax — attribute
7
+ selectors, pseudo-classes, wildcards, quotes — raises :class:`ValueError`.
8
+
9
+ Matching follows HTML document semantics: type selectors are matched ASCII
10
+ case-insensitively, while class and ID values are matched case-sensitively on
11
+ both the selector and the attribute side.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ from dataclasses import dataclass
18
+
19
+ from webcompy.ports._dom import DOMNode
20
+
21
+ _DESCENDANT = " "
22
+ _CHILD = ">"
23
+
24
+ _IDENTIFIER_START_RE = re.compile(r"[-A-Za-z_]")
25
+ _IDENTIFIER_BODY_RE = re.compile(r"[-A-Za-z0-9_]*")
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class _SimpleSelector:
30
+ """One compound term: optional tag plus class and id requirements."""
31
+
32
+ tag: str | None
33
+ classes: frozenset[str]
34
+ ids: frozenset[str]
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class _SelectorChain:
39
+ """A single compound sequence joined by combinators.
40
+
41
+ Each part holds a simple selector and the combinator linking it to the
42
+ *following* part (empty string on the last part).
43
+ """
44
+
45
+ parts: tuple[tuple[_SimpleSelector, str], ...]
46
+
47
+
48
+ def parse_selector(selector: str) -> list[_SelectorChain]:
49
+ """Parse ``selector`` into its comma-separated chains.
50
+
51
+ Type selectors are normalized to lower case; class and ID values are
52
+ kept verbatim so matching stays case-sensitive, mirroring HTML document
53
+ semantics.
54
+
55
+ Args:
56
+ selector: Selector text from the supported subset.
57
+
58
+ Returns:
59
+ Parsed chains in source order.
60
+
61
+ Raises:
62
+ ValueError: When the selector uses unsupported syntax or is empty.
63
+
64
+ """
65
+ text = selector.strip()
66
+ if not text:
67
+ raise ValueError(f"Empty selector: {selector!r}")
68
+ chains: list[_SelectorChain] = []
69
+ position = 0
70
+ while True:
71
+ parts, position = _parse_chain(text, position)
72
+ chains.append(_SelectorChain(parts))
73
+ if position >= len(text):
74
+ return chains
75
+ if text[position] != ",":
76
+ raise ValueError(f"Invalid selector syntax: {selector!r}")
77
+ position += 1
78
+ position = _skip_whitespace(text, position)
79
+ if position >= len(text):
80
+ raise ValueError(f"Invalid selector syntax: {selector!r}")
81
+
82
+
83
+ def resolve_first(root: DOMNode, selector: str) -> DOMNode | None:
84
+ """Return the first matching node in depth-first document order.
85
+
86
+ Type selectors match ASCII case-insensitively; class and ID values
87
+ match case-sensitively.
88
+
89
+ Args:
90
+ root: Node whose subtree (including itself) is searched.
91
+ selector: Selector text from the supported subset.
92
+
93
+ Returns:
94
+ First matching element node, or ``None`` when nothing matches.
95
+
96
+ Raises:
97
+ ValueError: When the selector uses unsupported syntax.
98
+
99
+ """
100
+ try:
101
+ parsed = parse_selector(selector)
102
+ except ValueError:
103
+ raise
104
+ return resolve_parsed(root, parsed)
105
+
106
+
107
+ def resolve_parsed(root: DOMNode, chains: list[_SelectorChain]) -> DOMNode | None:
108
+ """Return the first node matching pre-parsed ``chains``.
109
+
110
+ Args:
111
+ root: Node whose subtree (including itself) is searched.
112
+ chains: Parsed selector chains from :func:`parse_selector`.
113
+
114
+ Returns:
115
+ First matching element node, or ``None`` when nothing matches.
116
+
117
+ """
118
+ stack: list[DOMNode] = [root]
119
+ while stack:
120
+ node = stack.pop()
121
+ if node.nodeType != 1:
122
+ continue
123
+ if any(_matches_chain(node, chain, root) for chain in chains):
124
+ return node
125
+ children = node.childNodes
126
+ for index in range(children.length - 1, -1, -1):
127
+ stack.append(children[index])
128
+ return None
129
+
130
+
131
+ def _parse_chain(text: str, start: int) -> tuple[tuple[tuple[_SimpleSelector, str], ...], int]:
132
+ parts: list[tuple[_SimpleSelector, str]] = []
133
+ position = _skip_whitespace(text, start)
134
+ simple, position = _parse_compound(text, position)
135
+ parts.append((simple, ""))
136
+ while True:
137
+ position = _skip_whitespace(text, position)
138
+ if position >= len(text) or text[position] == ",":
139
+ return tuple(parts), position
140
+ combinator = _DESCENDANT
141
+ if text[position] == ">":
142
+ combinator = _CHILD
143
+ position = _skip_whitespace(text, position + 1)
144
+ following, position = _parse_compound(text, position)
145
+ latest = parts[-1][0]
146
+ parts[-1] = (latest, combinator)
147
+ parts.append((following, ""))
148
+
149
+
150
+ def _parse_compound(text: str, start: int) -> tuple[_SimpleSelector, int]:
151
+ tag: str | None = None
152
+ classes: set[str] = set()
153
+ ids: set[str] = set()
154
+ position = start
155
+ length = len(text)
156
+ while position < length:
157
+ char = text[position]
158
+ if char.isspace() or char in (",", ">"):
159
+ break
160
+ if char == ".":
161
+ name, position = _read_identifier(text, position + 1)
162
+ classes.add(name)
163
+ elif char == "#":
164
+ name, position = _read_identifier(text, position + 1)
165
+ ids.add(name)
166
+ else:
167
+ if tag is not None or classes or ids:
168
+ break
169
+ name, position = _read_identifier(text, position)
170
+ tag = name.lower()
171
+ if tag is None and not classes and not ids:
172
+ raise ValueError(f"Invalid selector syntax: {text!r}")
173
+ return _SimpleSelector(tag=tag, classes=frozenset(classes), ids=frozenset(ids)), position
174
+
175
+
176
+ def _read_identifier(text: str, position: int) -> tuple[str, int]:
177
+ if position >= len(text) or _IDENTIFIER_START_RE.match(text, position) is None:
178
+ raise ValueError(f"Unsupported selector syntax: {text!r}")
179
+ match = _IDENTIFIER_BODY_RE.match(text, position + 1)
180
+ rest = match.group(0) if match is not None else ""
181
+ return text[position] + rest, position + 1 + len(rest)
182
+
183
+
184
+ def _skip_whitespace(text: str, position: int) -> int:
185
+ length = len(text)
186
+ while position < length and text[position].isspace():
187
+ position += 1
188
+ return position
189
+
190
+
191
+ def _matches_chain(node: DOMNode, chain: _SelectorChain, root: DOMNode) -> bool:
192
+ parts = chain.parts
193
+ if not _matches_simple(node, parts[-1][0]):
194
+ return False
195
+ current = node
196
+ for index in range(len(parts) - 2, -1, -1):
197
+ previous = parts[index][0]
198
+ combinator = parts[index][1]
199
+ if combinator == _CHILD:
200
+ parent = current.parentNode
201
+ if parent is None or not _matches_simple(parent, previous):
202
+ return False
203
+ current = parent
204
+ else:
205
+ ancestor = current.parentNode
206
+ found = False
207
+ while True:
208
+ if ancestor is None:
209
+ break
210
+ if _matches_simple(ancestor, previous):
211
+ found = True
212
+ current = ancestor
213
+ break
214
+ if ancestor is root:
215
+ break
216
+ ancestor = ancestor.parentNode
217
+ if not found:
218
+ return False
219
+ return True
220
+
221
+
222
+ def _matches_simple(node: DOMNode, simple: _SimpleSelector) -> bool:
223
+ name = node.nodeName
224
+ if not isinstance(name, str):
225
+ return False
226
+ if simple.tag is not None and name.lower() != simple.tag:
227
+ return False
228
+ if simple.ids:
229
+ id_value = node.getAttribute("id")
230
+ if id_value is None or id_value not in simple.ids:
231
+ return False
232
+ if simple.classes:
233
+ class_value = node.getAttribute("class")
234
+ if class_value is not None and not isinstance(class_value, str):
235
+ return False
236
+ if not class_value or not simple.classes <= set(class_value.split()):
237
+ return False
238
+ return True
@@ -0,0 +1,75 @@
1
+ """Server-side transition port."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+ from webcompy.ports._dom import DOMNode
9
+ from webcompy.ports._transition import TransitionPort, TransitionStyle
10
+
11
+
12
+ class _EmptyTransitionStyle:
13
+ def get_property_value(self, name: str) -> str:
14
+ return ""
15
+
16
+
17
+ class ServerTransitionPort(TransitionPort):
18
+ """Server-side no-op transition port.
19
+
20
+ Attributes:
21
+ enabled: Always ``False`` on the server, so transitions degrade to
22
+ immediate mount/removal.
23
+
24
+ """
25
+
26
+ @property
27
+ def enabled(self) -> bool:
28
+ """Return whether transitions are enabled.
29
+
30
+ Returns:
31
+ ``False`` on the server.
32
+
33
+ """
34
+ return False
35
+
36
+ def schedule_next_frame(self, callback: Callable[[], Any]) -> Callable[[], None]:
37
+ """Schedule ``callback`` for the next frame.
38
+
39
+ Args:
40
+ callback: Callback to schedule.
41
+
42
+ Returns:
43
+ Callable that cancels the schedule.
44
+
45
+ """
46
+ return lambda: None
47
+
48
+ def schedule_timeout(
49
+ self,
50
+ callback: Callable[[], Any],
51
+ delay_ms: float,
52
+ ) -> Callable[[], None]:
53
+ """Schedule ``callback`` after a delay.
54
+
55
+ Args:
56
+ callback: Callback to schedule.
57
+ delay_ms: Delay in milliseconds.
58
+
59
+ Returns:
60
+ Callable that cancels the schedule.
61
+
62
+ """
63
+ return lambda: None
64
+
65
+ def get_computed_style(self, node: DOMNode) -> TransitionStyle:
66
+ """Return computed style for ``node``.
67
+
68
+ Args:
69
+ node: DOM node.
70
+
71
+ Returns:
72
+ Empty transition style on the server.
73
+
74
+ """
75
+ return _EmptyTransitionStyle()