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,925 @@
1
+ """HTML generation for server-side rendering and hydration payload injection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html as html_module
6
+ import json
7
+ import re
8
+ from logging import getLogger
9
+ from pathlib import Path
10
+ from typing import TYPE_CHECKING, TypeAlias, cast
11
+ from urllib.parse import parse_qsl
12
+
13
+ from webcompy.app._config import _LOADING_DEFAULTS, PluginScript
14
+ from webcompy.components._component import Component, _active_app_context, _set_app_instance
15
+ from webcompy.di import inject
16
+ from webcompy.elements.typealias import ElementChildren
17
+ from webcompy.elements.types import Element
18
+ from webcompy.elements.types._base import ElementWithChildren
19
+ from webcompy.exception import WebComPyException
20
+ from webcompy.ports._keys import ASYNC_SCHEDULER_PORT_KEY, DOM_PORT_KEY
21
+ from webcompy_server._teleport_emission import emit_teleport_blocks
22
+ from webcompy_server.ports._dom import ServerDOMPort
23
+
24
+ if TYPE_CHECKING:
25
+ from webcompy.app._render_context import RenderContext
26
+
27
+ _logger = getLogger(__name__)
28
+
29
+ Scripts: TypeAlias = list[tuple[dict[str, str], str | None]]
30
+
31
+ PYSCRIPT_VERSION = "2026.7.3"
32
+ PYSCRIPT_BASE_URL = f"https://pyscript.net/releases/{PYSCRIPT_VERSION}"
33
+
34
+
35
+ def get_runtime_asset_prefix(pyscript_version: str = PYSCRIPT_VERSION) -> str:
36
+ """Return the relative URL path prefix for versioned local runtime assets.
37
+
38
+ Args:
39
+ pyscript_version: Target PyScript version string. Defaults to
40
+ ``PYSCRIPT_VERSION``.
41
+
42
+ Returns:
43
+ Relative path prefix of the form ``_webcompy-assets/{pyscript_version}``.
44
+
45
+ """
46
+ return f"_webcompy-assets/{pyscript_version}"
47
+
48
+
49
+ class _DummyParent:
50
+ def __init__(self, node) -> None:
51
+ self._node = node
52
+
53
+ def _get_node(self):
54
+ return self._node
55
+
56
+ def _get_belonging_component(self):
57
+ return ""
58
+
59
+ def _get_belonging_components(self):
60
+ return ()
61
+
62
+ def _re_index_children(self, recursive):
63
+ pass
64
+
65
+
66
+ class _HtmlElement(Element):
67
+ def __init__(
68
+ self,
69
+ tag_name: str,
70
+ attrs: dict[str, str],
71
+ *children: ElementChildren,
72
+ ) -> None:
73
+ super().__init__(
74
+ tag_name, # type: ignore
75
+ attrs, # type: ignore
76
+ {},
77
+ None,
78
+ children,
79
+ )
80
+
81
+ async def render_html(self):
82
+ port = inject(DOM_PORT_KEY)
83
+ root_node = port.create_element("div")
84
+ root_node.__webcompy_node__ = False
85
+ root_node.__webcompy_prerendered_node__ = True
86
+ self._parent = cast("ElementWithChildren", _DummyParent(root_node))
87
+ self._node_idx = 0
88
+ self._clear_node_cache()
89
+ await self._render()
90
+ root_child = root_node.childNodes[0] if root_node.childNodes.length > 0 else None
91
+ if root_child is None:
92
+ return ""
93
+ return port.render_html(root_child)
94
+
95
+ def _get_belonging_component(self):
96
+ return ""
97
+
98
+ def _get_belonging_components(self) -> tuple[Component, ...]:
99
+ return tuple([])
100
+
101
+
102
+ class _Loadscreen(_HtmlElement):
103
+ def __init__(self, mode: str, structure: str, loading: dict) -> None:
104
+ delay_ms = loading["reveal_delay_ms"]
105
+ fade_ms = loading["fade_out_ms"]
106
+ children: list[ElementChildren] = []
107
+ if structure == "bar":
108
+ children.append(
109
+ _HtmlElement(
110
+ "div",
111
+ {"class": "wc-bar"},
112
+ _HtmlElement("div", {"class": "wc-bar-fill", "data-wc-bar": ""}),
113
+ )
114
+ )
115
+ elif structure == "splash":
116
+ children.append(
117
+ _HtmlElement(
118
+ "div",
119
+ {"class": "wc-splash"},
120
+ _HtmlElement("div", {"class": "wc-splash-logo", "aria-hidden": "true"}),
121
+ )
122
+ )
123
+ else:
124
+ children.append(_HtmlElement("div", {"class": "wc-loader"}))
125
+ if loading["stages"]:
126
+ children.append(
127
+ _HtmlElement(
128
+ "div",
129
+ {"class": "wc-status"},
130
+ _HtmlElement("span", {"data-wc-status": ""}),
131
+ _HtmlElement(
132
+ "span",
133
+ {"class": "wc-substatus", "data-wc-substatus": "", "aria-hidden": "true"},
134
+ ),
135
+ )
136
+ )
137
+ children.append(
138
+ _HtmlElement(
139
+ "div",
140
+ {"class": "wc-timeout", "data-wc-timeout": "", "hidden": ""},
141
+ _HtmlElement("span", {}, "Taking longer than usual… "),
142
+ _HtmlElement("button", {"class": "wc-reload", "data-wc-reload": ""}, "Reload"),
143
+ )
144
+ )
145
+ attrs: dict[str, str] = {
146
+ "id": "webcompy-loading",
147
+ "role": "status",
148
+ "data-wc-mode": mode,
149
+ "data-wc-fade": str(fade_ms),
150
+ "style": f"--wc-delay:{delay_ms}ms;--wc-fade:{fade_ms}ms",
151
+ }
152
+ if mode == "content":
153
+ attrs["data-wc-interaction"] = loading["interaction"]
154
+ super().__init__("div", attrs, *children)
155
+
156
+
157
+ _LOADING_BASE_CSS = (
158
+ "#webcompy-loading{position:fixed;inset:0;display:flex;flex-direction:column;align-items:center;"
159
+ "justify-content:center;gap:16px;background:var(--wc-backdrop, rgba(0, 0, 0, 0.15));z-index:9999;} "
160
+ "#webcompy-loading[data-wc-mode='content']{background:transparent;} "
161
+ "#webcompy-loading[data-wc-mode='content'][data-wc-interaction='passthrough']{pointer-events:none;} "
162
+ "#webcompy-loading [hidden]{display:none;} "
163
+ ".wc-bar{position:fixed;top:0;left:0;right:0;height:3px;opacity:0;"
164
+ "animation:wc-reveal 0.01s linear var(--wc-delay, 350ms) forwards;} "
165
+ ".wc-bar-fill{height:100%;background:var(--wc-accent, var(--color-accent, light-dark(#1d4ed8, #7dd3fc)));"
166
+ "transform:scaleX(var(--wc-progress, 0));transform-origin:left top;transition:transform 0.2s ease;} "
167
+ "#webcompy-loading[data-wc-complete] .wc-bar-fill{transform:scaleX(1);} "
168
+ ".wc-loader{opacity:0;width:40px;height:40px;border:3px solid;"
169
+ "border-color:var(--wc-ring, var(--color-border, light-dark(#d3d3d3, #4b5563)));"
170
+ "border-top-color:var(--wc-accent, var(--color-accent, light-dark(#87ceeb, #7dd3fc)));"
171
+ "border-radius:50%;animation:wc-spin 0.8s linear infinite, "
172
+ "wc-reveal 0.01s linear var(--wc-delay, 350ms) forwards;} "
173
+ ".wc-splash{display:flex;flex-direction:column;align-items:center;gap:8px;opacity:0;"
174
+ "animation:wc-reveal 0.01s linear var(--wc-delay, 350ms) forwards;} "
175
+ ".wc-splash-logo{width:48px;height:48px;border-radius:12px;"
176
+ "background:var(--color-bg-elevated, light-dark(#e5e7eb, #374151));} "
177
+ ".wc-status{opacity:0;animation:wc-reveal 0.01s linear var(--wc-delay, 350ms) forwards;"
178
+ "text-align:center;color:var(--wc-fg, var(--color-fg, light-dark(#333333, #cccccc)));font-family:system-ui, sans-serif;"
179
+ "font-size:14px;min-height:1.5em;} "
180
+ "#webcompy-loading[data-wc-mode='content'] .wc-status{position:fixed;left:16px;bottom:16px;text-align:left;} "
181
+ ".wc-substatus{display:block;font-size:12px;opacity:0.7;} "
182
+ ".wc-timeout{color:var(--wc-fg, var(--color-fg, light-dark(#333333, #cccccc)));font-family:system-ui, sans-serif;"
183
+ "font-size:14px;pointer-events:auto;} "
184
+ ".wc-reload{background:none;border:none;padding:0;color:var(--wc-accent, var(--color-accent, light-dark(#1d4ed8, #7dd3fc)));"
185
+ "text-decoration:underline;cursor:pointer;font:inherit;} "
186
+ "html[data-theme='dark'] .wc-loader{--wc-ring:#4b5563;--wc-accent:#7dd3fc;} "
187
+ "html[data-theme='dark'] .wc-status{--wc-fg:#cccccc;} "
188
+ "html[data-theme='dark'] .wc-timeout{--wc-fg:#cccccc;} "
189
+ "html[data-theme='dark'] .wc-reload{--wc-accent:#7dd3fc;} "
190
+ "html[data-theme='dark'] #webcompy-loading[data-wc-mode='overlay']{background:rgba(0, 0, 0, 0.35);} "
191
+ "@keyframes wc-spin{0%{transform:rotate(0deg);}100%{transform:rotate(360deg);}} "
192
+ "@keyframes wc-reveal{to{opacity:1;}} "
193
+ "@keyframes wc-dormant-in{to{opacity:var(--wc-dormant-opacity, 0.9);"
194
+ "filter:saturate(var(--wc-dormant-saturation, 0.85));}} "
195
+ "body.wc-booting #webcompy-app{animation:wc-dormant-in 0.01s linear var(--wc-delay, 350ms) forwards;} "
196
+ "body:is(.wc-booting, .wc-waking) #webcompy-app{transition:opacity 0.3s ease, filter 0.3s ease;} "
197
+ "body.wc-waking #webcompy-app{animation:none;opacity:1;filter:none;} "
198
+ "#webcompy-loading.wc-fading{opacity:0 !important;transition:opacity var(--wc-fade, 250ms) ease;} "
199
+ "@media (prefers-reduced-motion: reduce){"
200
+ ".wc-loader{animation:wc-reveal 0.01s linear var(--wc-delay, 350ms) forwards;}"
201
+ ".wc-status{animation:wc-reveal 0.01s linear var(--wc-delay, 350ms) forwards;}"
202
+ ".wc-bar-fill{transition:none;}"
203
+ "body:is(.wc-booting, .wc-waking) #webcompy-app{transition:none;}"
204
+ "#webcompy-loading.wc-fading{transition:none;}}"
205
+ )
206
+
207
+
208
+ def _loading_base_css(loading: dict, selector: str) -> str:
209
+ return (
210
+ _LOADING_BASE_CSS.replace("var(--wc-delay, 350ms)", f"var(--wc-delay, {loading['reveal_delay_ms']}ms)")
211
+ .replace("var(--wc-fade, 250ms)", f"var(--wc-fade, {loading['fade_out_ms']}ms)")
212
+ .replace("#webcompy-app", selector)
213
+ )
214
+
215
+
216
+ _LOADING_STRUCTURES = {"overlay": "spinner", "bar": "bar", "splash": "splash"}
217
+
218
+ _LOADING_TEMPLATE_HOOKS = ("data-wc-status", "data-wc-substatus", "data-wc-bar", "data-wc-timeout", "data-wc-reload")
219
+
220
+ _LOADING_TEMPLATE_MARKER = '<div id="webcompy-loading" data-wc-template-marker=""></div>'
221
+
222
+
223
+ def _loading_structure(loading: dict, mode: str) -> str:
224
+ template = loading["template"]
225
+ if template in _LOADING_STRUCTURES:
226
+ return _LOADING_STRUCTURES[template]
227
+ return "bar" if mode == "content" else "spinner"
228
+
229
+
230
+ def _resolve_loading_template(template: str | None, app_package_path: Path | None) -> str | None:
231
+ if template is None or template in _LOADING_STRUCTURES:
232
+ return None
233
+ if template.lstrip().startswith("<"):
234
+ return template
235
+ base = app_package_path or Path.cwd()
236
+ path = base / template
237
+ if not path.is_file():
238
+ raise WebComPyException(f"Loading template file not found: {path}")
239
+ return path.read_text(encoding="utf-8")
240
+
241
+
242
+ def _validate_loading_template(template_html: str) -> None:
243
+ matches = re.findall(r'id\s*=\s*["\']webcompy-loading["\']', template_html)
244
+ if len(matches) != 1:
245
+ raise WebComPyException(
246
+ f'Custom loading template must contain exactly one element with id="webcompy-loading", found {len(matches)}'
247
+ )
248
+ if not any(hook in template_html for hook in _LOADING_TEMPLATE_HOOKS):
249
+ _logger.warning("Custom loading template contains no documented hooks; progress plumbing will not drive it")
250
+
251
+
252
+ def _find_tag_end(html: str, start: int) -> int:
253
+ quote: str | None = None
254
+ for i in range(start, len(html)):
255
+ char = html[i]
256
+ if quote is not None:
257
+ if char == quote:
258
+ quote = None
259
+ elif char in ('"', "'"):
260
+ quote = char
261
+ elif char == ">":
262
+ return i
263
+ return -1
264
+
265
+
266
+ def _inject_loading_template_attrs(template_html: str, loading: dict, mode: str) -> str:
267
+ match = re.search(r'id\s*=\s*["\']webcompy-loading["\']', template_html)
268
+ if match is None:
269
+ raise WebComPyException('Custom loading template must contain exactly one element with id="webcompy-loading"')
270
+ tag_end = _find_tag_end(template_html, match.end())
271
+ if tag_end == -1:
272
+ raise WebComPyException("Custom loading template contains an unclosed #webcompy-loading tag")
273
+ tag = template_html[:tag_end]
274
+ injections: list[str] = []
275
+ if not re.search(r"role\s*=", tag):
276
+ injections.append('role="status"')
277
+ if "data-wc-mode" not in tag:
278
+ injections.append(f'data-wc-mode="{mode}"')
279
+ if mode == "content" and "data-wc-interaction" not in tag:
280
+ injections.append(f'data-wc-interaction="{loading["interaction"]}"')
281
+ if "data-wc-fade" not in tag:
282
+ injections.append(f'data-wc-fade="{loading["fade_out_ms"]}"')
283
+ if "style" not in tag:
284
+ injections.append(f'style="--wc-delay:{loading["reveal_delay_ms"]}ms;--wc-fade:{loading["fade_out_ms"]}ms"')
285
+ if not injections:
286
+ return template_html
287
+ return template_html[: match.end()] + " " + " ".join(injections) + template_html[match.end() :]
288
+
289
+
290
+ def _resolve_loading_config(config: dict | None) -> dict:
291
+ merged = dict(_LOADING_DEFAULTS)
292
+ if config:
293
+ merged.update(config)
294
+ merged["messages"] = dict(merged["messages"])
295
+ return merged
296
+
297
+
298
+ def _resolve_loading_mode(loading: dict, prerender: bool) -> str:
299
+ if loading["mode"] == "auto":
300
+ return "content" if prerender else "overlay"
301
+ return loading["mode"]
302
+
303
+
304
+ _LOADING_DEFAULT_MESSAGES = {
305
+ "runtime_prepare": "Preparing Python runtime…",
306
+ "runtime_download": "Downloading Python runtime…",
307
+ "packages": "Installing packages…",
308
+ "runtime_ready": "Runtime ready…",
309
+ "app_start": "Starting app…",
310
+ }
311
+
312
+ _LOADING_STAGE_CEILINGS = {
313
+ "runtime_prepare": 35,
314
+ "runtime_download": 60,
315
+ "packages": 85,
316
+ "runtime_ready": 93,
317
+ "app_start": 97,
318
+ }
319
+
320
+ _LOADING_STAGE_EVENTS = [
321
+ ("Loading Pyodide", "runtime_prepare"),
322
+ ("Loading interpreter", "runtime_download"),
323
+ ("Loaded interpreter", "packages"),
324
+ ("Loaded Pyodide", "runtime_ready"),
325
+ ]
326
+
327
+ _LOADING_CONTROLLER_TEMPLATE = """(function () {
328
+ var root = document.getElementById("webcompy-loading");
329
+ if (!root) return;
330
+ if (root.hasAttribute("data-wc-fade")) {
331
+ root.style.setProperty("--wc-fade", root.getAttribute("data-wc-fade") + "ms");
332
+ }
333
+ var CONFIG = __WC_CONFIG__;
334
+ var STAGES = __WC_STAGES__;
335
+ var CEILINGS = __WC_CEILINGS__;
336
+ var FIXED_CEILING = 97;
337
+ var statusEl = root.querySelector("[data-wc-status]");
338
+ var substatusEl = root.querySelector("[data-wc-substatus]");
339
+ var barEl = root.querySelector("[data-wc-bar]");
340
+ var timeoutEl = root.querySelector("[data-wc-timeout]");
341
+ var reloadEl = root.querySelector("[data-wc-reload]");
342
+ if (timeoutEl) timeoutEl.hidden = true;
343
+ var STAGE_KEYS = Object.keys(CEILINGS);
344
+ var ceiling = CONFIG.stages ? CEILINGS.runtime_prepare : FIXED_CEILING;
345
+ var progress = 0;
346
+ var start = Date.now();
347
+ var watchdog = null;
348
+ var showSub = false;
349
+ var reducedMotion = !!(window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches);
350
+
351
+ function setStage(key) {
352
+ var index = STAGE_KEYS.indexOf(key);
353
+ if (index > 0) setBar(CEILINGS[STAGE_KEYS[index - 1]]);
354
+ ceiling = CEILINGS[key];
355
+ showSub = key === "packages";
356
+ if (!CONFIG.stages) return;
357
+ if (statusEl) statusEl.textContent = (CONFIG.messages && CONFIG.messages[key]) || key;
358
+ }
359
+
360
+ function setSub(text) {
361
+ if (!CONFIG.stages || !substatusEl) return;
362
+ substatusEl.textContent = text;
363
+ }
364
+
365
+ function setBar(value) {
366
+ if (!barEl) return;
367
+ if (value <= progress) return;
368
+ progress = value;
369
+ barEl.style.setProperty("--wc-progress", String(value / 100));
370
+ }
371
+
372
+ function resetWatchdog() {
373
+ if (!CONFIG.timeoutSeconds) return;
374
+ if (watchdog) clearTimeout(watchdog);
375
+ watchdog = setTimeout(function () {
376
+ if (timeoutEl && timeoutEl.hidden && !root.hasAttribute("data-wc-complete")) timeoutEl.hidden = false;
377
+ }, CONFIG.timeoutSeconds * 1000);
378
+ }
379
+
380
+ function onProgress(e) {
381
+ var detail = e.detail;
382
+ if (typeof detail !== "string") return;
383
+ if (CONFIG.stages) {
384
+ for (var i = 0; i < STAGES.length; i++) {
385
+ if (STAGES[i][0] === detail) {
386
+ setStage(STAGES[i][1]);
387
+ resetWatchdog();
388
+ return;
389
+ }
390
+ }
391
+ if (showSub) setSub(detail);
392
+ }
393
+ resetWatchdog();
394
+ }
395
+
396
+ function onReady() {
397
+ setStage("app_start");
398
+ resetWatchdog();
399
+ }
400
+
401
+ if (CONFIG.stages) {
402
+ window.addEventListener("py:progress", onProgress);
403
+ window.addEventListener("py:ready", onReady);
404
+ } else {
405
+ window.addEventListener("py:progress", resetWatchdog);
406
+ window.addEventListener("py:ready", resetWatchdog);
407
+ }
408
+
409
+ if (reloadEl) {
410
+ reloadEl.addEventListener("click", function () {
411
+ window.location.reload();
412
+ });
413
+ }
414
+
415
+ function applyMountState() {
416
+ if (!CONFIG.selector) return;
417
+ var mount = document.querySelector(CONFIG.selector);
418
+ if (!mount) return;
419
+ mount.setAttribute("aria-busy", "true");
420
+ if (CONFIG.interaction === "inert") mount.setAttribute("inert", "");
421
+ }
422
+
423
+ if (document.readyState === "loading") {
424
+ document.addEventListener("DOMContentLoaded", applyMountState);
425
+ } else {
426
+ applyMountState();
427
+ }
428
+
429
+ function trickle() {
430
+ if (root.hasAttribute("data-wc-complete") || !root.isConnected || reducedMotion) return;
431
+ var elapsed = (Date.now() - start) / 1000;
432
+ var target = ceiling * (2 / Math.PI) * Math.atan(elapsed / 6);
433
+ setBar(target);
434
+ requestAnimationFrame(trickle);
435
+ }
436
+
437
+ resetWatchdog();
438
+ if (CONFIG.stages) setStage("runtime_prepare");
439
+ trickle();
440
+ })();"""
441
+
442
+
443
+ def _loading_controller_script(loading: dict, mode: str, selector: str) -> str:
444
+ messages = dict(_LOADING_DEFAULT_MESSAGES)
445
+ if loading["stages"]:
446
+ messages.update(loading.get("messages") or {})
447
+ config: dict = {
448
+ "stages": loading["stages"],
449
+ "timeoutSeconds": loading["timeout_seconds"],
450
+ "selector": selector,
451
+ }
452
+ if mode == "content":
453
+ config["interaction"] = loading["interaction"]
454
+ if loading["stages"]:
455
+ config["messages"] = messages
456
+ payload = json.dumps(config, ensure_ascii=False).replace("</", "<\\/")
457
+ stages_payload = json.dumps(_LOADING_STAGE_EVENTS).replace("</", "<\\/")
458
+ ceilings_payload = json.dumps(_LOADING_STAGE_CEILINGS).replace("</", "<\\/")
459
+ return (
460
+ _LOADING_CONTROLLER_TEMPLATE.replace("__WC_CONFIG__", payload)
461
+ .replace("__WC_STAGES__", stages_payload)
462
+ .replace("__WC_CEILINGS__", ceilings_payload)
463
+ )
464
+
465
+
466
+ _SPECIAL_SCHEME_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9+.-]*:")
467
+ _LINK_TAG_RE = re.compile(r"<link\b[^>]*>", re.IGNORECASE)
468
+ _HREF_ATTR_RE = re.compile(r'(\bhref\s*=\s*)(["\'])([^"\']*)\2', re.IGNORECASE)
469
+
470
+
471
+ def _append_asset_version(
472
+ url: str,
473
+ base_url: str,
474
+ asset_hashes: dict[str, str] | None,
475
+ ) -> str:
476
+ if not asset_hashes or not url:
477
+ return url
478
+ url_no_frag, frag_sep, fragment = url.partition("#")
479
+ path_part, _qsep, query = url_no_frag.partition("?")
480
+ if not path_part or path_part.startswith("//") or _SPECIAL_SCHEME_RE.match(path_part):
481
+ return url
482
+ if query and any(k == "v" for k, _ in parse_qsl(query, keep_blank_values=True)):
483
+ return url
484
+ stripped_base = base_url.strip("/")
485
+ normalized_base = f"/{stripped_base}/" if stripped_base else "/"
486
+ if path_part.startswith(normalized_base):
487
+ rel = path_part[len(normalized_base) :]
488
+ elif path_part.startswith("/"):
489
+ rel = path_part[1:]
490
+ else:
491
+ rel = path_part
492
+ while rel.startswith("./"):
493
+ rel = rel[2:]
494
+ digest = asset_hashes.get(rel)
495
+ if digest is None:
496
+ return url
497
+ new_query = f"{query}&v={digest}" if query else f"v={digest}"
498
+ return f"{path_part}?{new_query}{frag_sep}{fragment}"
499
+
500
+
501
+ def _rewrite_head_link_hrefs(
502
+ head_html: str,
503
+ base_url: str,
504
+ asset_hashes: dict[str, str] | None,
505
+ ) -> str:
506
+ if not asset_hashes or not head_html:
507
+ return head_html
508
+
509
+ def _rewrite_link_tag(tag_match: re.Match[str]) -> str:
510
+ tag = tag_match.group(0)
511
+
512
+ def _rewrite_href(attr_match: re.Match[str]) -> str:
513
+ prefix, quote, raw_href = attr_match.groups()
514
+ unescaped = html_module.unescape(raw_href)
515
+ rewritten = _append_asset_version(unescaped, base_url, asset_hashes)
516
+ if rewritten == unescaped:
517
+ return attr_match.group(0)
518
+ escaped = html_module.escape(rewritten, quote=True)
519
+ return f"{prefix}{quote}{escaped}{quote}"
520
+
521
+ return _HREF_ATTR_RE.sub(_rewrite_href, tag, count=1)
522
+
523
+ return _LINK_TAG_RE.sub(_rewrite_link_tag, head_html)
524
+
525
+
526
+ def _rewrite_script_attrs(
527
+ attrs: dict[str, str],
528
+ base_url: str,
529
+ asset_hashes: dict[str, str] | None,
530
+ ) -> dict[str, str]:
531
+ if not asset_hashes or "src" not in attrs:
532
+ return attrs
533
+ src = attrs["src"]
534
+ rewritten = _append_asset_version(src, base_url, asset_hashes)
535
+ if rewritten == src:
536
+ return attrs
537
+ updated = dict(attrs)
538
+ updated["src"] = rewritten
539
+ return updated
540
+
541
+
542
+ def _load_scripts(
543
+ scripts: Scripts,
544
+ *,
545
+ base_url: str = "",
546
+ asset_hashes: dict[str, str] | None = None,
547
+ ):
548
+ return [
549
+ _HtmlElement(
550
+ "script",
551
+ _rewrite_script_attrs(attrs, base_url, asset_hashes),
552
+ script,
553
+ )
554
+ for attrs, script in scripts
555
+ ]
556
+
557
+
558
+ def _render_plugin_script(
559
+ ps: PluginScript,
560
+ *,
561
+ base_url: str = "",
562
+ asset_hashes: dict[str, str] | None = None,
563
+ ) -> _HtmlElement:
564
+ attrs = _rewrite_script_attrs(ps.attrs, base_url, asset_hashes)
565
+ if ps.condition is None:
566
+ return _HtmlElement("script", attrs, ps.script)
567
+ target = "document.head" if (ps.in_head or ps.pre_paint) else "document.body"
568
+ if "src" in attrs:
569
+ js_parts: list[str] = [
570
+ "(function(){",
571
+ f" if ({ps.condition}) {{",
572
+ " var __wc_s = document.createElement('script');",
573
+ ]
574
+ for key, value in attrs.items():
575
+ escaped = json.dumps(value)
576
+ js_parts.append(f" __wc_s.setAttribute({json.dumps(key)}, {escaped});")
577
+ if ps.script:
578
+ js_parts.append(f" __wc_s.onload = function() {{ {ps.script} }};")
579
+ js_parts.append(f" {target}.appendChild(__wc_s);")
580
+ js_parts.extend([" }", "})();"])
581
+ return _HtmlElement("script", {}, "\n".join(js_parts))
582
+ if not ps.script:
583
+ return _HtmlElement("script", {})
584
+ js_parts = [
585
+ "(function(){",
586
+ f" if ({ps.condition}) {{",
587
+ f" {ps.script}",
588
+ " }",
589
+ "})();",
590
+ ]
591
+ return _HtmlElement("script", {}, "\n".join(js_parts))
592
+
593
+
594
+ async def generate_html(
595
+ ctx: RenderContext,
596
+ app_package_name: str,
597
+ dev_mode: bool,
598
+ prerender: bool,
599
+ wheel_filename: str,
600
+ pyodide_package_names: list[str] | None = None,
601
+ wasm_local_urls: dict[str, str] | None = None,
602
+ lockfile_url: str | None = None,
603
+ runtime_serving: str = "cdn",
604
+ extra_wheel_filenames: list[str] | None = None,
605
+ app_package_path: Path | None = None,
606
+ pwa_enabled: bool = False,
607
+ asset_hashes: dict[str, str] | None = None,
608
+ resource_version: str | None = None,
609
+ preloaded_loading_template: str | None = None,
610
+ ):
611
+ """Generate the full HTML document for the application.
612
+
613
+ Args:
614
+ ctx: Render context providing app config and DI scope.
615
+ app_package_name: Importable name of the app package.
616
+ dev_mode: Whether to inject dev-server reload support.
617
+ prerender: Whether to prerender the app root and inject hydration data.
618
+ wheel_filename: Filename of the app package wheel.
619
+ pyodide_package_names: Extra Pyodide packages to include.
620
+ wasm_local_urls: Mapping of package names to local WASM URLs.
621
+ lockfile_url: URL of the Pyodide lock file when serving remotely.
622
+ runtime_serving: How the PyScript runtime is served.
623
+ extra_wheel_filenames: Additional wheel filenames to preload.
624
+ app_package_path: Filesystem path of the app package for template resolution.
625
+ pwa_enabled: Whether to inject PWA manifest and worker registration.
626
+ asset_hashes: Optional mapping of relative asset paths (without
627
+ leading slash) to short content hashes appended as ``?v=<hash>``
628
+ to matching same-origin ``<link href>`` and ``<script src>`` URLs.
629
+ resource_version: Optional aggregate digest for allow-listed package
630
+ resources, emitted as ``<meta name="webcompy-resource-version">``
631
+ in non-dev builds.
632
+ preloaded_loading_template: Pre-resolved and pre-validated custom
633
+ loading template markup used without disk reads when provided.
634
+
635
+ Returns:
636
+ Rendered HTML string for the document.
637
+
638
+ """
639
+ token = _active_app_context.set(ctx)
640
+ _set_app_instance(ctx)
641
+ try:
642
+ html_output, app_loader_html, pre_paint_plugin_html = await _generate_html_impl(
643
+ ctx,
644
+ app_package_name,
645
+ dev_mode,
646
+ prerender,
647
+ wheel_filename,
648
+ pyodide_package_names,
649
+ wasm_local_urls,
650
+ lockfile_url,
651
+ runtime_serving,
652
+ extra_wheel_filenames,
653
+ app_package_path,
654
+ pwa_enabled,
655
+ asset_hashes,
656
+ resource_version,
657
+ preloaded_loading_template,
658
+ )
659
+ scheduler = inject(ASYNC_SCHEDULER_PORT_KEY)
660
+ await scheduler.await_pending()
661
+ assert ctx._root is not None
662
+ head_content_html = _rewrite_head_link_hrefs(
663
+ ctx._root._head_element.get_head_content_html(
664
+ extra_pre_paint_html=pre_paint_plugin_html,
665
+ script_attr_rewriter=lambda attrs: _rewrite_script_attrs(attrs, ctx.config.base_url, asset_hashes),
666
+ ),
667
+ ctx.config.base_url,
668
+ asset_hashes,
669
+ )
670
+ scoped_styles_html = ctx._root._head_element.get_scoped_styles_html()
671
+ html_output = html_output.replace("<head>", f"<head>\n{head_content_html}", 1)
672
+ if scoped_styles_html:
673
+ index_css_href = _append_asset_version(
674
+ f"{ctx.config.base_url}_webcompy-ui/index.css",
675
+ ctx.config.base_url,
676
+ asset_hashes,
677
+ )
678
+ index_css_link_html = f'<link rel="stylesheet" href="{html_module.escape(index_css_href, quote=True)}">'
679
+ assert index_css_link_html in html_output
680
+ html_output = html_output.replace(
681
+ index_css_link_html,
682
+ f"{index_css_link_html}\n{scoped_styles_html}",
683
+ 1,
684
+ )
685
+ if prerender and ctx._root is not None:
686
+ try:
687
+ payload_json = ctx._root._collect_transfer_data()
688
+ data_script = f'<script type="application/json" id="__webcompy_data__">{payload_json}</script>'
689
+ html_output = html_output.replace(
690
+ "</body>",
691
+ f"{data_script}\n{app_loader_html}</body>",
692
+ )
693
+ except Exception as e:
694
+ _logger.warning("Failed to inject hydration data payload: %s", e)
695
+ html_output = html_output.replace("</body>", f"{app_loader_html}</body>")
696
+ else:
697
+ html_output = html_output.replace("</body>", f"{app_loader_html}</body>")
698
+ return html_output
699
+ finally:
700
+ _active_app_context.reset(token)
701
+ _set_app_instance(None)
702
+
703
+
704
+ async def _generate_html_impl(
705
+ ctx: RenderContext,
706
+ app_package_name: str,
707
+ dev_mode: bool,
708
+ prerender: bool,
709
+ wheel_filename: str,
710
+ pyodide_package_names: list[str] | None = None,
711
+ wasm_local_urls: dict[str, str] | None = None,
712
+ lockfile_url: str | None = None,
713
+ runtime_serving: str = "cdn",
714
+ extra_wheel_filenames: list[str] | None = None,
715
+ app_package_path: Path | None = None,
716
+ pwa_enabled: bool = False,
717
+ asset_hashes: dict[str, str] | None = None,
718
+ resource_version: str | None = None,
719
+ preloaded_loading_template: str | None = None,
720
+ ):
721
+ app = ctx._app
722
+ base_url = ctx.config.base_url
723
+ selector_id = ctx.config.selector.lstrip("#")
724
+ loading_config = _resolve_loading_config(ctx.config.loading)
725
+ loading_mode = _resolve_loading_mode(loading_config, prerender)
726
+ body_attrs: dict[str, str] = {}
727
+ if loading_mode == "content" and loading_config["dormant"]:
728
+ body_attrs["class"] = "wc-booting"
729
+ app_root = (
730
+ ctx._root
731
+ if prerender
732
+ else _HtmlElement(
733
+ "div",
734
+ {"id": selector_id, "hidden": ""},
735
+ )
736
+ )
737
+ scripts_head: Scripts = []
738
+ scripts_body: Scripts = []
739
+
740
+ runtime_prefix = get_runtime_asset_prefix(PYSCRIPT_VERSION)
741
+ core_js_url = (
742
+ f"{base_url}{runtime_prefix}/core.js" if runtime_serving == "local" else f"{PYSCRIPT_BASE_URL}/core.js"
743
+ )
744
+ core_css_url = (
745
+ f"{base_url}{runtime_prefix}/core.css" if runtime_serving == "local" else f"{PYSCRIPT_BASE_URL}/core.css"
746
+ )
747
+
748
+ scripts_head.append(
749
+ (
750
+ {
751
+ "type": "module",
752
+ "src": core_js_url,
753
+ },
754
+ None,
755
+ )
756
+ )
757
+
758
+ app_wheel_url = f"{base_url}_webcompy-app-package/{wheel_filename}"
759
+ py_packages = [app_wheel_url]
760
+ if extra_wheel_filenames:
761
+ for name in extra_wheel_filenames:
762
+ py_packages.insert(0, f"{base_url}_webcompy-app-package/{name}")
763
+ for name in pyodide_package_names or []:
764
+ if wasm_local_urls and name in wasm_local_urls:
765
+ py_packages.append(wasm_local_urls[name])
766
+ else:
767
+ py_packages.append(name)
768
+ py_config_dict: dict = {"packages": py_packages, "experimental_create_proxy": "auto"}
769
+ if runtime_serving == "local":
770
+ py_config_dict["interpreter"] = f"{base_url}{runtime_prefix}/pyodide/pyodide.mjs"
771
+ py_config_dict["lockFileURL"] = f"{base_url}{runtime_prefix}/pyodide/pyodide-lock.json"
772
+ elif lockfile_url is not None:
773
+ py_config_dict["lockFileURL"] = lockfile_url
774
+ py_config = html_module.escape(
775
+ json.dumps(py_config_dict),
776
+ quote=True,
777
+ )
778
+ py_script_lines: list[str] = []
779
+ if ctx.config.profile:
780
+ py_script_lines.append("import time")
781
+ py_script_lines.append("_pyscript_ready = time.perf_counter()")
782
+ py_script_lines.append(f"from {app_package_name}.app import app")
783
+ if ctx.config.profile:
784
+ py_script_lines.append('app._profile_data["pyscript_ready"] = _pyscript_ready')
785
+ py_script_lines.append("app.run()")
786
+ py_script = "\n".join(py_script_lines)
787
+ app_loader_html = f'<script type="py" config="{py_config}">\n{py_script}\n</script>'
788
+
789
+ scripts_head.extend(ctx.head["script"])
790
+ scripts_body.extend(ctx.scripts)
791
+ plugin_pre_paint_scripts: list[_HtmlElement] = []
792
+ plugin_head_scripts: list[_HtmlElement] = []
793
+ plugin_body_scripts: list[_HtmlElement] = []
794
+ for ps in (*ctx.config.scripts, *app._plugin_manager.scripts):
795
+ rendered_script = _render_plugin_script(ps, base_url=base_url, asset_hashes=asset_hashes)
796
+ if ps.pre_paint:
797
+ plugin_pre_paint_scripts.append(rendered_script)
798
+ elif ps.in_head:
799
+ plugin_head_scripts.append(rendered_script)
800
+ else:
801
+ plugin_body_scripts.append(rendered_script)
802
+ if dev_mode:
803
+ scripts_body.append(
804
+ (
805
+ {"type": "text/javascript"},
806
+ " ".join(
807
+ (
808
+ f"var stream = new EventSource('{ctx.config.base_url}_webcompy_reload');",
809
+ "stream.addEventListener('error', (e) => window.location.reload());",
810
+ )
811
+ ),
812
+ )
813
+ )
814
+ if pwa_enabled:
815
+ sw_url = f"{base_url}sw.js"
816
+ registration_script = " ".join(
817
+ (
818
+ 'if ("serviceWorker" in navigator) {',
819
+ 'window.addEventListener("load", function () {',
820
+ f"navigator.serviceWorker.register({json.dumps(sw_url)}, {{ scope: {json.dumps(base_url)} }});",
821
+ "});}",
822
+ )
823
+ )
824
+ scripts_body.append(({"type": "text/javascript"}, registration_script))
825
+
826
+ assert ctx._root is not None
827
+ if preloaded_loading_template is not None:
828
+ custom_template: str | None = preloaded_loading_template
829
+ else:
830
+ custom_template = _resolve_loading_template(loading_config["template"], app_package_path)
831
+ if custom_template is not None:
832
+ _validate_loading_template(custom_template)
833
+ if custom_template is not None:
834
+ custom_template = _inject_loading_template_attrs(custom_template, loading_config, loading_mode)
835
+ loading_body: list[ElementChildren] = [
836
+ _HtmlElement("style", {}, _loading_base_css(loading_config, ctx.config.selector)),
837
+ _HtmlElement("div", {"id": "webcompy-loading", "data-wc-template-marker": ""}),
838
+ ]
839
+ else:
840
+ loading_body = [
841
+ _HtmlElement("style", {}, _loading_base_css(loading_config, ctx.config.selector)),
842
+ _Loadscreen(
843
+ loading_mode,
844
+ _loading_structure(loading_config, loading_mode),
845
+ loading_config,
846
+ ),
847
+ ]
848
+
849
+ pwa_head_links: list[_HtmlElement] = []
850
+ if pwa_enabled:
851
+ pwa_head_links.append(_HtmlElement("link", {"rel": "manifest", "href": f"{base_url}manifest.webmanifest"}))
852
+
853
+ index_css_href = _append_asset_version(f"{base_url}_webcompy-ui/index.css", base_url, asset_hashes)
854
+
855
+ meta_elements: list[_HtmlElement] = [
856
+ _HtmlElement("meta", {"name": "color-scheme", "content": "light dark"}),
857
+ ]
858
+ if not dev_mode and resource_version:
859
+ meta_elements.append(
860
+ _HtmlElement("meta", {"name": "webcompy-resource-version", "content": resource_version}),
861
+ )
862
+
863
+ document = _HtmlElement(
864
+ "html",
865
+ ctx._root.html_attrs,
866
+ _HtmlElement(
867
+ "head",
868
+ {},
869
+ _HtmlElement("base", {"href": ctx.config.base_url}),
870
+ *meta_elements,
871
+ _HtmlElement(
872
+ "link",
873
+ {"rel": "stylesheet", "href": index_css_href},
874
+ ),
875
+ _HtmlElement(
876
+ "link",
877
+ {"rel": "stylesheet", "href": core_css_url},
878
+ ),
879
+ *pwa_head_links,
880
+ *_load_scripts(scripts_head, base_url=base_url, asset_hashes=asset_hashes),
881
+ *plugin_head_scripts,
882
+ ),
883
+ _HtmlElement(
884
+ "body",
885
+ body_attrs,
886
+ *loading_body,
887
+ _HtmlElement(
888
+ "script",
889
+ {},
890
+ _loading_controller_script(loading_config, loading_mode, ctx.config.selector),
891
+ ),
892
+ app_root,
893
+ *_load_scripts(scripts_body, base_url=base_url, asset_hashes=asset_hashes),
894
+ *plugin_body_scripts,
895
+ ),
896
+ )
897
+
898
+ dom_port = inject(DOM_PORT_KEY)
899
+ dummy_root = dom_port.create_element("div")
900
+ document._parent = cast("ElementWithChildren", _DummyParent(dummy_root))
901
+ document._node_idx = 0
902
+ document._clear_node_cache()
903
+ await document._render()
904
+ scheduler = inject(ASYNC_SCHEDULER_PORT_KEY)
905
+ await scheduler.await_pending()
906
+ if prerender and isinstance(dom_port, ServerDOMPort) and dummy_root.childNodes.length > 0:
907
+ dom_port._attach_document_root(dummy_root.childNodes[0])
908
+ await emit_teleport_blocks(ctx._root._node_cache)
909
+ await scheduler.await_pending()
910
+ html_output = "<!doctype html>" + dom_port.render_html(dummy_root.childNodes[0])
911
+
912
+ if custom_template is not None:
913
+ if _LOADING_TEMPLATE_MARKER not in html_output:
914
+ raise WebComPyException(
915
+ "Failed to inject custom loading template: contract marker not found in generated HTML"
916
+ )
917
+ html_output = html_output.replace(_LOADING_TEMPLATE_MARKER, custom_template)
918
+
919
+ pre_paint_parts: list[str] = []
920
+ for script_el in plugin_pre_paint_scripts:
921
+ rendered_part = await script_el.render_html()
922
+ if rendered_part:
923
+ pre_paint_parts.append(rendered_part)
924
+
925
+ return html_output, app_loader_html, "\n".join(pre_paint_parts)