|
1 | | -"""Browser-backed render checks and standalone page export.""" |
| 1 | +"""Browser-backed validation of served pages.""" |
2 | 2 |
|
3 | | -import base64 |
4 | 3 | import contextlib |
5 | 4 | import json |
6 | | -import re |
7 | 5 | import secrets |
8 | 6 | import sys |
9 | 7 | import threading |
10 | 8 | from pathlib import Path |
11 | 9 | from urllib.parse import urljoin, urlsplit |
12 | 10 |
|
13 | | -from leaf.data import read_data |
14 | 11 | from leaf.event_log import flocked, now_iso, read_events |
15 | | -from leaf.files import published_versions, revision_label, version_name, version_num |
| 12 | +from leaf.files import revision_label, version_name, version_num |
16 | 13 | from leaf.hosting import LeafHTTPServer |
17 | 14 | from leaf.http import handler_for |
18 | 15 | from leaf.passages import EMPTY, spoken |
|
25 | 22 | install_window_errors, |
26 | 23 | wait_for_probe, |
27 | 24 | ) |
28 | | -from leaf.schema import _DIR_FILES, MEDIA_DIR, MEDIA_TYPES |
29 | 25 | from leaf.service import transition_lock |
30 | | -from leaf.structure import parse_structure |
31 | 26 | from leaf.validation import thread_universe |
32 | 27 |
|
33 | 28 | # ---------- check --render: the browser half of the gate ---------- |
@@ -748,143 +743,3 @@ def render_check( |
748 | 743 | "column, no sideways scroll" |
749 | 744 | ) |
750 | 745 | return 0 |
751 | | - |
752 | | - |
753 | | -# ---------- export: the page as one file ---------- |
754 | | -def inline_assets(html: str, page_dir: Path) -> str: |
755 | | - """Fold the served assets into the markup. The theme's link becomes the stylesheet |
756 | | - itself and each image becomes its own bytes, which is everything the document still |
757 | | - reaches the server for: the runtime's stylesheet arrived as a `<style>` in the DOM, |
758 | | - the widget modules were imports rather than elements, and a `lf-ref`'s link was |
759 | | - always somewhere else.""" |
760 | | - theme = (page_dir / "theme.css").read_text(encoding="utf-8") |
761 | | - html, n = re.subn( |
762 | | - r'<link[^>]+href="/theme\.css"[^>]*>', |
763 | | - lambda _: f"<style>{theme}</style>", |
764 | | - html, |
765 | | - count=1, |
766 | | - ) |
767 | | - if not n: |
768 | | - sys.exit( |
769 | | - "the rendered page carried no /theme.css link — it would open unstyled" |
770 | | - ) |
771 | | - # References from the parsed reading, never a scan of the text: a path standing |
772 | | - # in prose is the reader's words — the lesson `media_refs` itself carries — and |
773 | | - # a text scan crashed the export on a documented path no file answers. The |
774 | | - # attribute harvest is media_refs; a page <style>'s url(/media/…) is the one |
775 | | - # reference an attribute harvest can't see, so it is read from the parsed css. |
776 | | - # The substitution then rewrites only the two serialized forms a reference |
777 | | - # takes (`="…"`, `url(…)`); prose quoting the exact string of a path the page |
778 | | - # also really uses is the residual, and it is the author quoting live markup. |
779 | | - parsed = parse_structure(html) |
780 | | - css_refs = set( |
781 | | - re.findall(rf"url\((/{MEDIA_DIR}/{_DIR_FILES[MEDIA_DIR]})\)", parsed.css) |
782 | | - ) |
783 | | - for src in sorted(set(parsed.media_refs) | css_refs): |
784 | | - file = page_dir / src.lstrip("/") |
785 | | - data = base64.b64encode(file.read_bytes()).decode() |
786 | | - uri = f"data:{MEDIA_TYPES[file.suffix]};base64,{data}" |
787 | | - html = html.replace(f'="{src}"', f'="{uri}"').replace( |
788 | | - f"url({src})", f"url({uri})" |
789 | | - ) |
790 | | - return html |
791 | | - |
792 | | - |
793 | | -def export_page(browser, url: str, page_dir: Path) -> str: |
794 | | - """The served version at `url`, copied as one self-contained document. |
795 | | -
|
796 | | - One implementation has two callers, as `render_version` does: `version export` |
797 | | - supplies installed Chrome, while the suite drives this over the shipped |
798 | | - examples with its Chromium headless shell. That keeps the export behavior in |
799 | | - one function without claiming that the two browser launch paths are identical. |
800 | | -
|
801 | | - The user's decisions come with it. Replay is what puts them on the page, so |
802 | | - this waits for the runtime's caught-up stamp exactly as the gate does, and a page |
803 | | - whose board was rearranged copies rearranged.""" |
804 | | - from playwright.sync_api import Error as PlaywrightError |
805 | | - from playwright.sync_api import TimeoutError as PlaywrightTimeout |
806 | | - |
807 | | - page = browser.new_page(viewport=RENDER_VIEWPORT) |
808 | | - try: |
809 | | - # See the gate: a page listening for news is never network-idle. The |
810 | | - # stamps below are the arrival signal, and they are the precise one. |
811 | | - page.goto(url, wait_until="load") |
812 | | - try: |
813 | | - wait_for_probe(page, "upgraded") |
814 | | - wait_for_probe(page, "dataApplied", read_data(page_dir)["revision"]) |
815 | | - # Both replayed kinds, as the render gate counts them: the caught-up |
816 | | - # stamp counts reports beside actions, and a page whose only recorded |
817 | | - # state is a worker's report would otherwise copy before it painted. |
818 | | - n_replayed = len( |
819 | | - [e for e in read_events(page_dir) if e["kind"] in ("action", "report")] |
820 | | - ) |
821 | | - if n_replayed: |
822 | | - wait_for_probe(page, "logApplied", n_replayed) |
823 | | - return inline_assets(evaluate_probe(page, "bake"), page_dir) |
824 | | - except PlaywrightTimeout: |
825 | | - sys.exit( |
826 | | - f"{url.rsplit('/', 1)[-1]} never finished applying its live state in " |
827 | | - "the browser, so a copy would be half-drawn. `leaf version check " |
828 | | - "<page> --render` says what is wrong with it." |
829 | | - ) |
830 | | - except PlaywrightError as error: |
831 | | - sys.exit( |
832 | | - f"{url.rsplit('/', 1)[-1]} could not load its browser probe module " |
833 | | - f"({str(error).strip().splitlines()[0]}), so Leaf could not make a " |
834 | | - "trustworthy copy." |
835 | | - ) |
836 | | - finally: |
837 | | - page.close() |
838 | | - |
839 | | - |
840 | | -def cmd_export(page_dir: Path, out: Path, version, *, preview=None) -> int: |
841 | | - """One stamped version as a standalone HTML file. |
842 | | -
|
843 | | - The copy is the page as the browser finished drawing it, which is the only way to |
844 | | - get one: half the document is written by the widget layer at runtime, a mermaid |
845 | | - diagram becomes an SVG only once mermaid has drawn it, and a code block is colored |
846 | | - by the vendored tokenizer in the page rather than by anything that can read the |
847 | | - file. So Chrome is not an optimisation here and no `x-` key exempts a widget from |
848 | | - it; without a browser there is nothing to copy at all.""" |
849 | | - preview = preview_server if preview is None else preview |
850 | | - try: |
851 | | - from playwright.sync_api import Error as PlaywrightError |
852 | | - from playwright.sync_api import sync_playwright |
853 | | - except ImportError: |
854 | | - sys.exit( |
855 | | - "export needs Playwright; run it as\n" |
856 | | - " leaf version export <page> -o <file>\n" |
857 | | - "or, from a checkout,\n" |
858 | | - " plugins/leaf/bin/leaf version export <page> -o <file>" |
859 | | - ) |
860 | | - published = published_versions(page_dir, read_events(page_dir)) |
861 | | - if not published: |
862 | | - sys.exit( |
863 | | - f"{page_dir} has no stamped version to export; " |
864 | | - "run `leaf version stamp` first" |
865 | | - ) |
866 | | - version = version if version else published[-1] |
867 | | - if version not in published: |
868 | | - sys.exit( |
869 | | - f"v{version} is not stamped — stamped: " |
870 | | - + ", ".join(f"v{v}" for v in published) |
871 | | - ) |
872 | | - name = version_name(version) |
873 | | - |
874 | | - with preview(page_dir, version) as url, sync_playwright() as p: |
875 | | - try: |
876 | | - browser = p.chromium.launch(channel="chrome") |
877 | | - except PlaywrightError as e: |
878 | | - sys.exit( |
879 | | - f"export needs Chrome, and it didn't launch ({str(e).strip().splitlines()[0]}). " |
880 | | - "A copy is the drawn page, so there is nothing to write without one." |
881 | | - ) |
882 | | - try: |
883 | | - html = export_page(browser, url, page_dir) |
884 | | - finally: |
885 | | - browser.close() |
886 | | - |
887 | | - out.parent.mkdir(parents=True, exist_ok=True) |
888 | | - out.write_text(html, encoding="utf-8") |
889 | | - print(f"✓ {name} → {out} ({out.stat().st_size // 1024} KB, opens with no server)") |
890 | | - return 0 |
0 commit comments