Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.
feat(render): js_gap in render_page.py; full-page screenshots scroll first
Agrici Danielee6b19bdb008
diff --git a/scripts/capture_screenshot.py b/scripts/capture_screenshot.pyindex 6f94db8..ec322ef 100755--- a/scripts/capture_screenshot.py+++ b/scripts/capture_screenshot.py@@ -7,17 +7,48 @@ Playwright route() handler aborts any subresource request whose hostnameresolves to a non-public IP (defence in depth against DNS rebindinginside Chromium's resolver).+Full-page captures (--full) get two hygiene steps before the picture is+taken, both bounded so a page cannot hang the capture:++- scroll-through: the page is scrolled once from top to bottom so lazy+ images load, then returned to the top. At most SCROLL_MAX_STEPS steps+ and SCROLL_MAX_MS of wall-clock time; the page height is read once, so+ an infinite-scroll page cannot extend it. Turn off with --no-scroll.+- settle: waits up to SETTLE_MAX_MS for finite animations to finish and,+ after a scroll-through, for the images it triggered.++--hide-overlays is opt-in and off by default: it hides fixed or stuck+floating elements (cookie banners, chat widgets, bottom bars) before the+capture. Leave it off for a visual audit, which has to see intrusive+overlays. When it is used the result says so.++Neither step opens a new navigation or request path: they only scroll and+restyle the page already loaded behind the url_safety route guard.+Usage:python capture_screenshot.py https://example.compython capture_screenshot.py https://example.com --viewport mobilepython capture_screenshot.py https://example.com --output screenshots/+ python capture_screenshot.py https://example.com --full --json+ python capture_screenshot.py https://example.com --full --hide-overlays++Output (--json prints {"captures": [...]}, one entry per viewport):+ url, output, viewport, success, error as before+ full_page True for a full-page capture+ scroll_through None, or {steps, capped, returned_to_top} (plus error)+ settle None, or {waited_ms, animations_pending, images_pending}+ hide_overlays True when --hide-overlays was used+ overlays_hidden None, or the number of elements hidden for the capture+ (hide_overlays_error is added when hiding failed)"""from __future__ import annotationsimport argparse+import jsonimport osimport sys+import timefrom urllib.parse import ParseResult, urlparsetry:@@ -51,6 +82,89 @@ VIEWPORTS = {"mobile": {"width": 375, "height": 812},}+# Full-page hygiene bounds. The scroll-through stops at whichever limit+# comes first, so an infinite-scroll page cannot hang the capture.+SCROLL_MAX_STEPS = 40 # viewport-height steps down the page+SCROLL_PAUSE_MS = 120 # pause per step so lazy loaders can fire+SCROLL_MAX_MS = 6000 # wall-clock budget for the scroll down+SCROLL_TOP_RETRIES = 10 # tries, SCROLL_TOP_PAUSE_MS apart, to get back to the top+SCROLL_TOP_PAUSE_MS = 50+SCROLL_REST_MS = 250 # after the return, so scroll handlers can run+SETTLE_MAX_MS = 1500 # wait for finite animations and triggered images+SETTLE_POLL_MS = 100++# The snippets below are adapted from web-obs (engine/page_snapshots.py).+# Each one is synchronous and returns at once; the waiting happens in+# Python, where it is counted against the bounds above.++# Smooth scrolling (common) turns every jump into a slow glide, so the+# steps would never reach their positions and the picture would be taken+# part way down. Scrolling is forced to be instant first. The height is+# read once here and never again.+_JS_SCROLL_PREPARE = """() => {+ for (const el of [document.documentElement, document.body]) {+ if (el) el.style.setProperty('scroll-behavior', 'auto', 'important');+ }+ return {+ height: document.documentElement.scrollHeight,+ step: Math.max(400, window.innerHeight),+ };+}"""++_JS_SCROLL_TO = """(y) => {+ window.scrollTo({ top: y, left: 0, behavior: 'instant' });+ return Math.round(window.scrollY);+}"""++# Animations that never end (spinners, marquees) are not waited for.+_JS_PENDING = """() => {+ let animations = 0;+ if (document.getAnimations) {+ for (const animation of document.getAnimations()) {+ if (animation.playState !== 'running') continue;+ const effect = animation.effect;+ const timing = effect && effect.getComputedTiming ? effect.getComputedTiming() : null;+ if (timing && timing.endTime === Infinity) continue;+ animations++;+ }+ }+ let images = 0;+ for (const img of document.images) if (!img.complete) images++;+ return { animations, images };+}"""++# Floating elements land on top of the content in a full-page picture.+# Hidden: fixed elements, except a bar pinned to the top edge (the site+# header) and a full-height rail on one side (a docs sidebar), and sticky+# elements that are stuck to the bottom edge. Other sticky elements sit in+# the page flow and stay. Styles are set through the CSSOM, which a strict+# Content-Security-Policy still allows.+_JS_HIDE_OVERLAYS = """() => {+ const vh = window.innerHeight, vw = window.innerWidth;+ let hidden = 0;+ for (const el of document.querySelectorAll('body *')) {+ const cs = getComputedStyle(el);+ if (cs.position !== 'fixed' && cs.position !== 'sticky') continue;+ if (cs.display === 'none' || cs.visibility === 'hidden') continue;+ if (el.closest('[data-claude-seo-hidden]')) continue;+ const r = el.getBoundingClientRect();+ if (r.width < 1 || r.height < 1) continue;+ if (cs.position === 'fixed') {+ const atTop = r.top <= vh * 0.1;+ const header = atTop && r.height <= vh * 0.3;+ const sideRail = atTop && r.height >= vh * 0.9 && r.width <= vw * 0.35;+ if (header || sideRail) continue;+ } else {+ const offset = parseFloat(cs.bottom);+ if (Number.isNaN(offset) || Math.abs(r.bottom + offset - vh) > 2) continue;+ }+ el.setAttribute('data-claude-seo-hidden', '');+ el.style.setProperty('visibility', 'hidden', 'important');+ hidden++;+ }+ return hidden;+}"""+def normalize_url(url: str) -> tuple[str, ParseResult]:"""Normalize URL and return (url, parsed_url).@@ -72,12 +186,79 @@ def normalize_url(url: str) -> tuple[str, ParseResult]:return url, parsed+def _error_text(exc: Exception) -> str:+ lines = str(exc).splitlines()+ return f"{type(exc).__name__}: {lines[0][:200] if lines else 'failed'}"+++def _scroll_through(page, clock=time.monotonic) -> dict: # type: ignore[no-untyped-def]+ """Scroll once down the page so lazy images load, then back to the top.++ Bounded by SCROLL_MAX_STEPS and SCROLL_MAX_MS, whichever comes first;+ ``capped`` is True when a limit cut the scroll short. Never raises: a+ failure is recorded under ``error`` and the capture goes on.+ """+ info: dict = {"steps": 0, "capped": False, "returned_to_top": False}+ deadline = clock() + SCROLL_MAX_MS / 1000.0+ try:+ dims = page.evaluate(_JS_SCROLL_PREPARE) or {}+ height = int(dims.get("height") or 0)+ step = max(1, int(dims.get("step") or 0))+ # The first screen is already on display, so start one step down.+ y = step+ while y < height:+ if info["steps"] >= SCROLL_MAX_STEPS or clock() >= deadline:+ info["capped"] = True+ break+ page.evaluate(_JS_SCROLL_TO, y)+ page.wait_for_timeout(SCROLL_PAUSE_MS)+ info["steps"] += 1+ y += step+ except Exception as exc:+ info["error"] = _error_text(exc)+ try:+ for _ in range(SCROLL_TOP_RETRIES):+ if not page.evaluate(_JS_SCROLL_TO, 0):+ info["returned_to_top"] = True+ break+ page.wait_for_timeout(SCROLL_TOP_PAUSE_MS)+ if info["steps"]:+ page.wait_for_timeout(SCROLL_REST_MS)+ except Exception as exc:+ info.setdefault("error", _error_text(exc))+ return info+++def _settle(page, wait_images: bool) -> dict: # type: ignore[no-untyped-def]+ """Wait up to SETTLE_MAX_MS for finite animations (and images) to finish.++ The ``*_pending`` counts are what was still unfinished when the wait+ ended. Never raises.+ """+ info: dict = {"waited_ms": 0, "animations_pending": 0, "images_pending": 0}+ try:+ while True:+ pending = page.evaluate(_JS_PENDING) or {}+ info["animations_pending"] = int(pending.get("animations") or 0)+ info["images_pending"] = int(pending.get("images") or 0) if wait_images else 0+ busy = info["animations_pending"] or info["images_pending"]+ if not busy or info["waited_ms"] >= SETTLE_MAX_MS:+ break+ page.wait_for_timeout(SETTLE_POLL_MS)+ info["waited_ms"] += SETTLE_POLL_MS+ except Exception as exc:+ info["error"] = _error_text(exc)+ return info++def capture_screenshot(url: str,output_path: str,viewport: str = "desktop",full_page: bool = False,timeout: int = 30000,+ scroll_through: bool = True,+ hide_overlays: bool = False,) -> dict:"""Capture a screenshot of a web page.@@ -88,6 +269,10 @@ def capture_screenshot(viewport: Viewport preset (desktop, laptop, tablet, mobile)full_page: Whether to capture full page or just viewporttimeout: Page load timeout in milliseconds+ scroll_through: For full-page captures, scroll the page once first+ so lazy images load (bounded). Ignored for viewport captures.+ hide_overlays: Hide fixed or stuck floating elements before the+ capture. Off by default: a visual audit must see them.Returns:Dictionary with capture results@@ -98,6 +283,11 @@ def capture_screenshot("viewport": viewport,"success": False,"error": None,+ "full_page": full_page,+ "scroll_through": None,+ "settle": None,+ "hide_overlays": hide_overlays,+ "overlays_hidden": None,}if viewport not in VIEWPORTS:@@ -144,6 +334,18 @@ def capture_screenshot(# Wait a bit more for any lazy-loaded contentpage.wait_for_timeout(1000)+ if full_page:+ if scroll_through:+ result["scroll_through"] = _scroll_through(page)+ result["settle"] = _settle(page, wait_images=scroll_through)++ if hide_overlays:+ try:+ result["overlays_hidden"] = int(page.evaluate(_JS_HIDE_OVERLAYS) or 0)+ except Exception as exc:+ result["overlays_hidden"] = 0+ result["hide_overlays_error"] = _error_text(exc)+# Capture screenshotpage.screenshot(path=output_path, full_page=full_page)@@ -187,6 +389,18 @@ def main():parser.add_argument("--all", "-a", action="store_true", help="Capture all viewports")parser.add_argument("--full", "-f", action="store_true", help="Capture full page")parser.add_argument("--timeout", "-t", type=int, default=30000, help="Timeout in ms")+ parser.add_argument(+ "--no-scroll",+ action="store_true",+ help="With --full: skip the scroll-through that loads lazy images",+ )+ parser.add_argument(+ "--hide-overlays",+ action="store_true",+ help="Hide fixed or stuck floating elements (cookie banners, chat widgets) "+ "before the capture. Off by default; do not use for a visual audit",+ )+ parser.add_argument("--json", action="store_true", help="Print the results as JSON")args = parser.parse_args()@@ -209,24 +423,41 @@ def main():base_name = parsed_url.netloc.replace(".", "_")viewports = VIEWPORTS.keys() if args.all else [args.viewport]+ # With --json, stdout carries the JSON only; progress goes to stderr.+ progress = sys.stderr if args.json else sys.stdout+ captures = []for viewport in viewports:filename = f"{base_name}_{viewport}.png"output_path = os.path.join(output_dir, filename)- print(f"Capturing {viewport} screenshot...")+ print(f"Capturing {viewport} screenshot...", file=progress)result = capture_screenshot(normalized_url,output_path,viewport=viewport,full_page=args.full,timeout=args.timeout,+ scroll_through=not args.no_scroll,+ hide_overlays=args.hide_overlays,)+ captures.append(result)if result["success"]:- print(f" ✓ Saved to {output_path}")+ print(f" ✓ Saved to {output_path}", file=progress)+ if args.hide_overlays:+ print(+ f" --hide-overlays: {result.get('overlays_hidden') or 0} "+ "floating element(s) hidden, this is not what a visitor sees",+ file=progress,+ )else:- print(f" ✗ Failed: {result['error']}")+ print(f" ✗ Failed: {result['error']}", file=progress)++ if args.json:+ print(json.dumps({"captures": captures}, indent=2, default=str))+ if not all(capture.get("success") for capture in captures):+ sys.exit(1)if __name__ == "__main__":diff --git a/scripts/render_page.py b/scripts/render_page.pyindex 19062a8..62c7ba2 100644--- a/scripts/render_page.py+++ b/scripts/render_page.py@@ -47,8 +47,32 @@ A dict with::render_ms elapsed wall-clock for the render stepmode_used 'rendered' or 'raw'too_large True when the raw body hit the size cap (MAX_PAGE_BYTES)+ js_gap raw-versus-rendered difference (see below), or None+ when no render happened (or the HTML was too large+ to compare, which render_diagnostics then says)error str or None+JavaScript content gap+======================+When a page is rendered, ``js_gap`` compares the HTML as served with the+DOM after JavaScript ran (:func:`js_gap`, a pure function over two HTML+strings)::++ raw, rendered per version: words, links, schema_types, h1, title,+ canonical, canonical_all, meta_robots+ diff words_only_rendered and links_only_rendered with their+ *_share of the rendered total (0 to 1),+ schema_types_only_rendered, h1_only_rendered,+ title_changed, canonical_changed, meta_robots_changed+ raw_truncated True when the raw body was cut at the size cap, so+ the gap may be overstated+ significant True when ``reasons`` is not empty+ reasons plain-language findings; empty when nothing stands out++Words are every text token outside script, style, noscript, template and+head; hidden elements are not detected. The share limits (``JS_GAP_*``) are+this tool's heuristics, not Google rules.+SSRF====The URL is validated via :func:`url_safety.validate_url_strict` before@@ -73,6 +97,7 @@ import osimport reimport sysimport time+from collections import Counterfrom typing import Any, Optionalfrom bs4 import BeautifulSoup@@ -166,6 +191,26 @@ JSON_LD_MAX_DEPTH = 40ACCESSIBILITY_MAX_NODES = 10_000ACCESSIBILITY_MAX_DEPTH = 50+# JavaScript content gap. These limits decide when a raw-versus-rendered+# difference is called "significant". They are this tool's heuristics, not+# Google rules: Google publishes no threshold for either.+JS_GAP_WORDS_SHARE = 0.30 # share of rendered words that exist only after JS+JS_GAP_WORDS_MIN = 25 # and at least this many such words+JS_GAP_LINKS_SHARE = 0.30 # share of rendered links that exist only after JS+JS_GAP_LINKS_MIN = 3 # and at least this many such links+# Output bounds, so a hostile page cannot inflate the JSON.+JS_GAP_MAX_ITEMS = 12 # schema types, H1 texts, robots directives+JS_GAP_MAX_CANONICALS = 5+JS_GAP_MAX_TEXT = 300 # characters kept per title, H1 or canonical+JS_GAP_REASON_TEXT = 80 # characters of page text quoted inside a reason+# The comparison parses both versions again. Past this size it is skipped+# (js_gap stays None, with a render diagnostic) so a huge DOM cannot stall it.+JS_GAP_MAX_HTML_CHARS = 5_000_000++_WORD = re.compile(r"\w+")+_NON_VISIBLE_TAGS = ("script", "style", "noscript", "template", "head", "title")+_NON_LINK_HREF = ("#", "javascript:", "mailto:", "tel:", "data:")+def _visible_body_text(lower_html: str) -> str:body_start = lower_html.find("<body")@@ -200,8 +245,16 @@ def _schema_types(data: object) -> tuple[list[str], bool]:return sorted(types)[:100], truncated or len(types) > 100-def _extract_json_ld(html: Optional[str], *, include_full: bool = False) -> dict:- """Extract full-page JSON-LD with strict block, byte, and traversal bounds."""+def _extract_json_ld(+ html: Optional[str],+ *,+ include_full: bool = False,+ soup: Optional[BeautifulSoup] = None,+) -> dict:+ """Extract full-page JSON-LD with strict block, byte, and traversal bounds.++ ``soup`` lets a caller that already parsed ``html`` skip a second parse.+ """result = {"block_count": 0,"processed_count": 0,@@ -212,7 +265,8 @@ def _extract_json_ld(html: Optional[str], *, include_full: bool = False) -> dictif not html:return result- soup = BeautifulSoup(html, "html.parser")+ if soup is None:+ soup = BeautifulSoup(html, "html.parser")scripts = [script for script in soup.find_all("script")if str(script.get("type", "")).strip().lower() == "application/ld+json"@@ -291,6 +345,196 @@ def _is_spa(raw_html: Optional[str]) -> bool:return False+def _clean_text(value: object) -> str:+ return _WHITESPACE.sub(" ", str(value or "")).strip()[:JS_GAP_MAX_TEXT]+++def _gap_signals(html: str) -> tuple[dict, dict]:+ """Collect one version's SEO signals for :func:`js_gap`.++ Returns the published signals plus the word and link multisets used to+ work out what exists only after rendering. Raw and rendered HTML go+ through the same code, so the two sides are counted the same way.+ """+ soup = BeautifulSoup(html or "", "html.parser")++ # Dicts keep first-seen order and make de-duplication linear, so a page+ # with a huge number of distinct values cannot slow the comparison down.+ schema_types: dict[str, None] = {}+ for block in _extract_json_ld(html, soup=soup)["blocks"]:+ schema_types.update(dict.fromkeys(block.get("types") or []))++ # An <svg><title> is an accessible name, not the document title.+ title = None+ for tag in soup.find_all("title"):+ if tag.find_parent("svg") is None:+ title = _clean_text(tag.get_text(" ")) or None+ break++ canonicals: dict[str, None] = {}+ for tag in soup.find_all("link"):+ rel = tag.get("rel") or []+ rel = rel.split() if isinstance(rel, str) else rel+ href = _clean_text(tag.get("href"))+ if href and any(str(item).lower() == "canonical" for item in rel):+ canonicals[href] = None++ # Several robots meta tags combine, so their directives are merged.+ robots: dict[str, None] = {}+ for tag in soup.find_all("meta"):+ if str(tag.get("name") or "").strip().lower() != "robots":+ continue+ for directive in str(tag.get("content") or "").lower().split(","):+ directive = _clean_text(directive)+ if directive:+ robots[directive] = None++ for tag in soup(list(_NON_VISIBLE_TAGS)):+ tag.decompose()++ h1: dict[str, None] = {}+ for tag in soup.find_all("h1"):+ text = _clean_text(tag.get_text(" ", strip=True))+ if text:+ h1[text] = None++ hrefs: Counter = Counter()+ for anchor in soup.find_all("a", href=True):+ href = str(anchor.get("href") or "").strip()+ if href and not href.lower().startswith(_NON_LINK_HREF):+ hrefs[href] += 1++ words = Counter(_WORD.findall(soup.get_text(" ", strip=True).lower()))++ signals = {+ "words": sum(words.values()),+ "links": sum(hrefs.values()),+ "schema_types": list(schema_types)[:JS_GAP_MAX_ITEMS],+ "h1": list(h1)[:JS_GAP_MAX_ITEMS],+ "title": title,+ "canonical": next(iter(canonicals), None),+ "canonical_all": list(canonicals)[:JS_GAP_MAX_CANONICALS],+ "meta_robots": ", ".join(list(robots)[:JS_GAP_MAX_ITEMS]) or None,+ }+ return signals, {"words": words, "hrefs": hrefs}+++def _only_after(raw: Counter, rendered: Counter) -> tuple[int, float]:+ """Items in ``rendered`` with no counterpart in ``raw``: count and share."""+ total = sum(rendered.values())+ added = sum((rendered - raw).values())+ return added, (round(added / total, 3) if total else 0.0)+++def js_gap(+ raw_html: Optional[str],+ rendered_html: Optional[str],+ *,+ raw_truncated: bool = False,+) -> Optional[dict]:+ """Compare the HTML as served with the DOM after JavaScript ran.++ Pure: two HTML strings in, a JSON-ready dict out, no browser or network.+ Returns None when either version is missing (no render happened). An+ empty string is a real, empty document and is compared.++ Title, canonical and meta robots are reported as changed when the raw+ and rendered values differ in any way (added, removed or replaced). A+ mismatch between the two is the case Google's JavaScript SEO guidance+ warns about.+ """+ if raw_html is None or rendered_html is None:+ return None+ raw, raw_sets = _gap_signals(raw_html)+ rendered, rendered_sets = _gap_signals(rendered_html)+ words_added, words_share = _only_after(raw_sets["words"], rendered_sets["words"])+ links_added, links_share = _only_after(raw_sets["hrefs"], rendered_sets["hrefs"])+ gap: dict = {+ "raw": raw,+ "rendered": rendered,+ "diff": {+ "words_only_rendered": words_added,+ "words_only_rendered_share": words_share,+ "links_only_rendered": links_added,+ "links_only_rendered_share": links_share,+ "schema_types_only_rendered": [+ name for name in rendered["schema_types"]+ if name not in raw["schema_types"]+ ],+ "h1_only_rendered": [text for text in rendered["h1"] if text not in raw["h1"]],+ "title_changed": raw["title"] != rendered["title"],+ "canonical_changed": (+ set(raw["canonical_all"]) != set(rendered["canonical_all"])+ ),+ "meta_robots_changed": (+ set((raw["meta_robots"] or "").split(", "))+ != set((rendered["meta_robots"] or "").split(", "))+ ),+ },+ "raw_truncated": bool(raw_truncated),+ }+ gap["reasons"] = js_gap_reasons(gap)+ gap["significant"] = bool(gap["reasons"])+ return gap+++def _quoted(value: object) -> str:+ """Page text for a reason line: bounded, or 'none' when absent."""+ if isinstance(value, list):+ value = " | ".join(str(item) for item in value)+ text = str(value or "")+ if not text:+ return "none"+ if len(text) > JS_GAP_REASON_TEXT:+ text = text[:JS_GAP_REASON_TEXT] + "..."+ return f"'{text}'"+++def js_gap_reasons(gap: Optional[dict]) -> list[str]:+ """Plain-language reasons a :func:`js_gap` result matters. Empty when none do."""+ if not gap:+ return []+ raw, rendered, diff = gap["raw"], gap["rendered"], gap["diff"]+ reasons: list[str] = []+ if (+ diff["words_only_rendered_share"] >= JS_GAP_WORDS_SHARE+ and diff["words_only_rendered"] >= JS_GAP_WORDS_MIN+ ):+ reasons.append(+ f"{round(diff['words_only_rendered_share'] * 100)}% of visible words appear "+ f"only after JavaScript runs ({raw['words']} raw, {rendered['words']} rendered)"+ )+ if (+ diff["links_only_rendered_share"] >= JS_GAP_LINKS_SHARE+ and diff["links_only_rendered"] >= JS_GAP_LINKS_MIN+ ):+ reasons.append(+ f"{diff['links_only_rendered']} of {rendered['links']} links appear only "+ f"after JavaScript runs ({raw['links']} in the raw HTML)"+ )+ if diff["schema_types_only_rendered"]:+ reasons.append(+ "structured data appears only after JavaScript: "+ + ", ".join(diff["schema_types_only_rendered"][:5])+ )+ if diff["h1_only_rendered"]:+ reasons.append(+ "the H1 changes after JavaScript" if raw["h1"]+ else "the H1 appears only after JavaScript"+ )+ for flag, label, key in (+ ("title_changed", "title", "title"),+ ("canonical_changed", "canonical URL", "canonical_all"),+ ("meta_robots_changed", "meta robots value", "meta_robots"),+ ):+ if diff[flag]:+ reasons.append(+ f"the {label} is not the same before and after JavaScript "+ f"(raw: {_quoted(raw[key])}, rendered: {_quoted(rendered[key])})"+ )+ return reasons++def _wait_for_dom_stability(page, timeout_ms: int) -> bool: # type: ignore[no-untyped-def]"""Wait up to five seconds for meaningful body text and a stable DOM."""budget_ms = max(250, min(timeout_ms, 5000))@@ -443,6 +687,7 @@ def render_page("render_ms": None,"mode_used": None,"too_large": False,+ "js_gap": None,"error": None,}@@ -596,6 +841,25 @@ def render_page(finally:result["render_ms"] = (time.monotonic() - start) * 1000.0+ # Both versions exist: measure what only JavaScript provides.+ try:+ largest = max(len(result["raw_content"] or ""), len(result["content"] or ""))+ if largest > JS_GAP_MAX_HTML_CHARS:+ result["render_diagnostics"].append(+ f"js_gap skipped: HTML is larger than {JS_GAP_MAX_HTML_CHARS} characters"+ )+ else:+ result["js_gap"] = js_gap(+ result["raw_content"],+ result["content"],+ raw_truncated=result["too_large"],+ )+ except Exception as exc:+ # The comparison is best-effort; never block the audit on it.+ result["render_diagnostics"].append(+ f"js_gap comparison failed: {type(exc).__name__}: {exc}"+ )+# Step 2: content extraction (works on either raw or rendered HTML).if extract_content and result["content"]:if trafilatura is not None:@@ -765,6 +1029,8 @@ def _cli() -> None:)if res["publication_date"]:print(f"Publication date: {res['publication_date']}", file=sys.stderr)+ for reason in (res.get("js_gap") or {}).get("reasons", []):+ print(f"JS gap: {reason}", file=sys.stderr)if res["console_errors"]:print(f"Console errors ({len(res['console_errors'])}):", file=sys.stderrdiff --git a/tests/test_capture_screenshot_hygiene.py b/tests/test_capture_screenshot_hygiene.pynew file mode 100644index 0000000..3e3fe2e--- /dev/null+++ b/tests/test_capture_screenshot_hygiene.py@@ -0,0 +1,411 @@+"""capture_screenshot.py full-page hygiene: scroll-through, settle, --hide-overlays.++Playwright is mocked the way tests/test_render_page.py does it: a fake page+records every call in order, and the context is built by the real+url_safety.new_guarded_context, so the tests also prove the guards are still+installed. No browser and no network.+"""++from __future__ import annotations++import json+import sys+from pathlib import Path+from types import SimpleNamespace++import pytest++pytest.importorskip("playwright")+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))+import capture_screenshot as cs # noqa: E402+import url_safety # noqa: E402++URL = "https://site.example/"+++class FakePage:+ """Records calls in order; answers the hygiene snippets like a page would."""++ def __init__(self, *, height=5000, step=1000, pending=(), overlays=3, top_lag=(), fail=None):+ self.height = height+ self.step = step+ self.pending = list(pending) # successive _JS_PENDING answers; last one repeats+ self.overlays = overlays+ self.top_lag = list(top_lag) # scrollY values reported before the page is at 0+ self.fail = fail # snippet whose evaluation raises+ self.calls: list[tuple] = []+ self.routes: list[tuple] = []++ def route(self, pattern, handler):+ self.routes.append((pattern, handler))++ def goto(self, url, **kwargs):+ self.calls.append(("goto", url, kwargs))++ def wait_for_timeout(self, ms):+ self.calls.append(("wait", ms))++ def screenshot(self, **kwargs):+ self.calls.append(("screenshot", kwargs))++ def evaluate(self, snippet, arg=None):+ name = {+ cs._JS_SCROLL_PREPARE: "prepare",+ cs._JS_SCROLL_TO: "scroll_to",+ cs._JS_PENDING: "pending",+ cs._JS_HIDE_OVERLAYS: "hide_overlays",+ }[snippet]+ self.calls.append((name, arg))+ if self.fail == name:+ raise RuntimeError("Execution context was destroyed\nstack line")+ if name == "prepare":+ return {"height": self.height, "step": self.step}+ if name == "scroll_to":+ if arg == 0 and self.top_lag:+ return self.top_lag.pop(0)+ return arg+ if name == "pending":+ if len(self.pending) > 1:+ return self.pending.pop(0)+ return self.pending[0] if self.pending else {"animations": 0, "images": 0}+ return self.overlays++ def names(self) -> list[str]:+ return [call[0] for call in self.calls]++ def waited(self) -> int:+ return sum(call[1] for call in self.calls if call[0] == "wait")+++class FakeManager:+ def __init__(self, page):+ page.context_kwargs = None+ page.context_routes = []+ page.context_ws_routes = []+ context = SimpleNamespace(+ new_page=lambda: page,+ route=lambda pattern, handler: page.context_routes.append((pattern, handler)),+ route_web_socket=lambda pattern, handler: page.context_ws_routes.append(+ (pattern, handler)+ ),+ )++ def new_context(**kwargs):+ page.context_kwargs = kwargs+ return context++ browser = SimpleNamespace(new_context=new_context, close=lambda: None)+ self.playwright = SimpleNamespace(+ chromium=SimpleNamespace(launch=lambda **_kwargs: browser)+ )++ def __enter__(self):+ return self.playwright++ def __exit__(self, *_args):+ return False+++def _capture(monkeypatch, page, **kwargs):+ monkeypatch.setattr(cs, "validate_url_strict", lambda url: (url, "93.184.216.34"))+ monkeypatch.setattr(cs, "sync_playwright", lambda: FakeManager(page))+ return cs.capture_screenshot(URL, "/out/shot.png", **kwargs)+++# ---------------------------------------------------------------------------+# Defaults: who gets the new steps and who does not+# ---------------------------------------------------------------------------+++def test_viewport_capture_is_unchanged(monkeypatch) -> None:+ page = FakePage()+ result = _capture(monkeypatch, page)+ assert result["success"] is True+ # Same call sequence as before: no snippet runs for a viewport capture.+ assert page.calls == [+ ("goto", URL, {"wait_until": "networkidle", "timeout": 30000}),+ ("wait", 1000),+ ("screenshot", {"path": "/out/shot.png", "full_page": False}),+ ]+ assert result["full_page"] is False+ assert result["scroll_through"] is None+ assert result["settle"] is None+ assert result["hide_overlays"] is False+ assert result["overlays_hidden"] is None+++def test_full_page_capture_scrolls_returns_to_top_then_settles(monkeypatch) -> None:+ page = FakePage(height=5000, step=1000)+ result = _capture(monkeypatch, page, full_page=True)+ assert result["success"] is True+ assert result["scroll_through"] == {"steps": 4, "capped": False, "returned_to_top": True}+ assert result["settle"] == {"waited_ms": 0, "animations_pending": 0, "images_pending": 0}+ scrolls = [call[1] for call in page.calls if call[0] == "scroll_to"]+ assert scrolls == [1000, 2000, 3000, 4000, 0]+ # Order: load, scroll down, back to the top, settle, and only then the picture.+ names = page.names()+ assert names[:2] == ["goto", "wait"]+ assert names.index("prepare") < names.index("scroll_to") < names.index("pending")+ assert names[-1] == "screenshot"+ assert page.calls[-1] == ("screenshot", {"path": "/out/shot.png", "full_page": True})+ # Overlays stay: hiding them is opt-in.+ assert "hide_overlays" not in names+ assert result["hide_overlays"] is False+ assert result["overlays_hidden"] is None+++def test_no_scroll_flag_skips_the_scroll_but_still_settles(monkeypatch) -> None:+ # Images below the fold never load without the scroll, so they are not waited for.+ page = FakePage(pending=[{"animations": 0, "images": 7}])+ result = _capture(monkeypatch, page, full_page=True, scroll_through=False)+ assert result["scroll_through"] is None+ assert result["settle"] == {"waited_ms": 0, "animations_pending": 0, "images_pending": 0}+ assert "prepare" not in page.names() and "scroll_to" not in page.names()+ assert page.names()[-1] == "screenshot"+++def test_page_shorter_than_the_viewport_adds_no_wait(monkeypatch) -> None:+ page = FakePage(height=700, step=1080)+ result = _capture(monkeypatch, page, full_page=True)+ assert result["scroll_through"] == {"steps": 0, "capped": False, "returned_to_top": True}+ assert page.waited() == 1000 # only the wait that was always there+++# ---------------------------------------------------------------------------+# Bounds: an endless or slow page cannot hang the capture+# ---------------------------------------------------------------------------+++def test_scroll_steps_are_capped_on_an_endless_page(monkeypatch) -> None:+ page = FakePage(height=10**9, step=1000)+ result = _capture(monkeypatch, page, full_page=True)+ assert result["scroll_through"] == {+ "steps": cs.SCROLL_MAX_STEPS, "capped": True, "returned_to_top": True,+ }+ assert result["success"] is True+ assert page.names()[-1] == "screenshot"+ # Worst case added by the scroll: the steps plus the rest at the top.+ assert page.waited() - 1000 == cs.SCROLL_MAX_STEPS * cs.SCROLL_PAUSE_MS + cs.SCROLL_REST_MS+++def test_height_is_read_once_so_a_growing_page_cannot_extend_the_scroll() -> None:+ page = FakePage(height=3000, step=1000)+ original = page.evaluate++ def growing(snippet, arg=None):+ answer = original(snippet, arg)+ page.height += 5000 # infinite scroll: the page is taller after every call+ return answer++ page.evaluate = growing+ info = cs._scroll_through(page)+ assert info == {"steps": 2, "capped": False, "returned_to_top": True}+ assert page.names().count("prepare") == 1+++def test_scroll_stops_at_the_time_budget() -> None:+ page = FakePage(height=10**9, step=1000)+ ticks = iter(range(0, 1000, 2)) # the fake clock advances 2 s per reading+ info = cs._scroll_through(page, clock=lambda: float(next(ticks)))+ # Budget is SCROLL_MAX_MS (6 s): readings at 2 s and 4 s pass, 6 s stops it.+ assert info == {"steps": 2, "capped": True, "returned_to_top": True}+++def test_return_to_top_retries_are_bounded() -> None:+ page = FakePage(height=3000, step=1000, top_lag=[900, 300])+ info = cs._scroll_through(page)+ assert info["returned_to_top"] is True+ assert [call[1] for call in page.calls if call[0] == "scroll_to"][-3:] == [0, 0, 0]++ stuck = FakePage(height=3000, step=1000, top_lag=[500] * 100)+ info = cs._scroll_through(stuck)+ assert info["returned_to_top"] is False+ top_tries = [call for call in stuck.calls if call == ("scroll_to", 0)]+ assert len(top_tries) == cs.SCROLL_TOP_RETRIES+++def test_settle_waits_for_animations_and_images_then_stops() -> None:+ page = FakePage(pending=[+ {"animations": 2, "images": 3},+ {"animations": 0, "images": 1},+ {"animations": 0, "images": 0},+ ])+ info = cs._settle(page, wait_images=True)+ assert info == {+ "waited_ms": 2 * cs.SETTLE_POLL_MS, "animations_pending": 0, "images_pending": 0,+ }+++def test_settle_is_bounded_and_reports_what_was_still_pending() -> None:+ page = FakePage(pending=[{"animations": 4, "images": 9}])+ info = cs._settle(page, wait_images=True)+ assert info == {+ "waited_ms": cs.SETTLE_MAX_MS, "animations_pending": 4, "images_pending": 9,+ }+ assert page.waited() == cs.SETTLE_MAX_MS+++def test_worst_case_added_time_stays_under_nine_seconds() -> None:+ worst_ms = (+ cs.SCROLL_MAX_MS + cs.SCROLL_PAUSE_MS+ + cs.SCROLL_TOP_RETRIES * cs.SCROLL_TOP_PAUSE_MS + cs.SCROLL_REST_MS+ + cs.SETTLE_MAX_MS+ )+ assert worst_ms == 8370+ assert cs.SCROLL_MAX_STEPS * cs.SCROLL_PAUSE_MS <= cs.SCROLL_MAX_MS+++def test_hygiene_failure_never_fails_the_capture(monkeypatch) -> None:+ for snippet in ("prepare", "scroll_to", "pending", "hide_overlays"):+ page = FakePage(fail=snippet)+ result = _capture(monkeypatch, page, full_page=True, hide_overlays=True)+ assert result["success"] is True, snippet+ assert result["error"] is None, snippet+ assert page.names()[-1] == "screenshot", snippet+ assert result["overlays_hidden"] == 0+ assert result["hide_overlays_error"] == "RuntimeError: Execution context was destroyed"++ page = FakePage(fail="scroll_to")+ result = _capture(monkeypatch, page, full_page=True)+ assert result["scroll_through"]["error"] == "RuntimeError: Execution context was destroyed"+ assert result["scroll_through"]["returned_to_top"] is False+++# ---------------------------------------------------------------------------+# --hide-overlays: opt-in, and said so in the result+# ---------------------------------------------------------------------------+++def test_hide_overlays_is_opt_in_and_reported(monkeypatch) -> None:+ page = FakePage(overlays=3)+ result = _capture(monkeypatch, page, full_page=True, hide_overlays=True)+ assert result["hide_overlays"] is True+ assert result["overlays_hidden"] == 3+ names = page.names()+ # After the scroll and settle (overlays can appear on scroll), before the picture.+ assert names.index("pending") < names.index("hide_overlays") < names.index("screenshot")+ assert names.count("hide_overlays") == 1+++def test_hide_overlays_also_works_for_a_viewport_capture(monkeypatch) -> None:+ page = FakePage(overlays=1)+ result = _capture(monkeypatch, page, hide_overlays=True)+ assert page.names() == ["goto", "wait", "hide_overlays", "screenshot"]+ assert result["overlays_hidden"] == 1+ assert result["scroll_through"] is None+++# ---------------------------------------------------------------------------+# Safety properties are untouched+# ---------------------------------------------------------------------------+++def test_guards_are_installed_and_only_one_navigation_happens(monkeypatch) -> None:+ page = FakePage()+ result = _capture(monkeypatch, page, full_page=True, hide_overlays=True)+ assert result["success"] is True+ assert page.context_kwargs["service_workers"] == "block"+ assert [pattern for pattern, _handler in page.context_routes] == ["**/*"]+ assert [pattern for pattern, _handler in page.context_ws_routes] == ["**/*"]+ assert page.context_ws_routes[0][1] is url_safety._never_connect_web_socket+ # The page-level route uses the same guard as the context.+ assert page.routes == [("**/*", page.context_routes[0][1])]+ assert page.names().count("goto") == 1+ # The route guard is installed before the page is loaded.+ assert page.calls[0][0] == "goto"+++def test_private_address_is_refused_before_any_browser_starts(monkeypatch) -> None:+ def no_browser():+ raise AssertionError("the browser must not start for a refused URL")++ monkeypatch.setattr(cs, "sync_playwright", no_browser)+ result = cs.capture_screenshot(+ "http://127.0.0.1/", "/out/shot.png", full_page=True, hide_overlays=True+ )+ assert result["success"] is False+ assert result["error"].startswith("url_safety:")+++def test_snippets_open_no_request_or_navigation_path() -> None:+ """The page-side code only scrolls, reads state and restyles elements."""+ forbidden = (+ "fetch", "XMLHttpRequest", "sendBeacon", "WebSocket", "EventSource", "import(",+ "location", "open(", "href", "src", "createElement", "innerHTML", "eval(",+ "navigator", "postMessage", "submit", "click", "url(",+ )+ for snippet in (+ cs._JS_SCROLL_PREPARE, cs._JS_SCROLL_TO, cs._JS_PENDING, cs._JS_HIDE_OVERLAYS,+ ):+ for token in forbidden:+ assert token not in snippet, (token, snippet[:40])+ assert "async" not in snippet and "await" not in snippet+++# ---------------------------------------------------------------------------+# CLI+# ---------------------------------------------------------------------------+++def cli(tmp_path, monkeypatch):+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ monkeypatch.chdir(tmp_path)+ calls: list[dict] = []+ outcome = {"success": True}++ def fake_capture(url, path, **kwargs):+ calls.append(kwargs)+ return {+ "url": url, "output": path, "viewport": kwargs["viewport"],+ "success": outcome["success"],+ "error": None if outcome["success"] else "boom",+ "hide_overlays": kwargs["hide_overlays"],+ "overlays_hidden": 2 if kwargs["hide_overlays"] else None,+ }++ monkeypatch.setattr(cs, "capture_screenshot", fake_capture)++ def run(*args):+ monkeypatch.setattr(sys, "argv", ["capture_screenshot.py", URL, *args])+ cs.main()+ return calls++ run.outcome = outcome+ return run+++def test_cli_defaults_scroll_on_and_overlays_visible(cli, capsys) -> None:+ calls = cli("--full")+ assert calls[0]["full_page"] is True+ assert calls[0]["scroll_through"] is True+ assert calls[0]["hide_overlays"] is False+ out = capsys.readouterr().out+ assert "Capturing desktop screenshot..." in out+ assert "hide-overlays" not in out+++def test_cli_flags_reach_the_capture_and_are_announced(cli, capsys) -> None:+ calls = cli("--full", "--no-scroll", "--hide-overlays")+ assert calls[0]["scroll_through"] is False+ assert calls[0]["hide_overlays"] is True+ assert "--hide-overlays: 2 floating element(s) hidden" in capsys.readouterr().out+++def test_cli_json_prints_one_document_and_names_the_overlay_flag(cli, capsys) -> None:+ cli("--all", "--full", "--hide-overlays", "--json")+ captured = capsys.readouterr()+ payload = json.loads(captured.out) # stdout is JSON only+ assert [item["viewport"] for item in payload["captures"]] == list(cs.VIEWPORTS)+ assert all(item["hide_overlays"] is True for item in payload["captures"])+ assert all(item["overlays_hidden"] == 2 for item in payload["captures"])+ assert "Capturing desktop screenshot..." in captured.err+++def test_cli_json_exits_non_zero_when_a_capture_fails(cli, capsys) -> None:+ cli.outcome["success"] = False+ with pytest.raises(SystemExit) as exc:+ cli("--json")+ assert exc.value.code == 1+ assert json.loads(capsys.readouterr().out)["captures"][0]["error"] == "boom"diff --git a/tests/test_render_js_gap.py b/tests/test_render_js_gap.pynew file mode 100644index 0000000..1b0ce19--- /dev/null+++ b/tests/test_render_js_gap.py@@ -0,0 +1,276 @@+"""render_page.js_gap: what a page only has after JavaScript ran.++js_gap is a pure function over two HTML strings (raw as served, rendered+DOM), so every test here runs without a browser or the network. The first+test is ported from web-obs (scripts/verify-browser-audit.py), where the+comparison was first written.+"""++from __future__ import annotations++import json+import os+import sys++import pytest++_SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts")+if _SCRIPTS not in sys.path:+ sys.path.insert(0, _SCRIPTS)++pytest.importorskip("requests")+import render_page # noqa: E402+from render_page import js_gap, js_gap_reasons # noqa: E402++SHELL = "<html><head><title>App</title></head><body><p>one two</p></body></html>"+HYDRATED = (+ "<html><head><title>App</title>"+ '<script type="application/ld+json">{"@type": ["Organization", "Brand"]}</script></head>'+ "<body><h1>Title here</h1>"+ + "<p>word word word word word</p>" * 10+ + '<a href="/a">a</a>' * 6+ + "</body></html>"+)+++def _page(head: str = "", body: str = "") -> str:+ filler = "<p>" + "steady server rendered copy " * 20 + "</p>"+ return f"<html><head>{head}</head><body>{filler}{body}</body></html>"+++def test_js_gap_measures_words_links_schema_and_h1() -> None:+ gap = js_gap(SHELL, HYDRATED)+ assert gap["raw"]["words"] == 2+ assert gap["rendered"]["words"] == 58+ assert gap["rendered"]["links"] == 6+ assert gap["rendered"]["schema_types"] == ["Brand", "Organization"]+ diff = gap["diff"]+ assert diff["words_only_rendered"] == 58+ assert diff["words_only_rendered_share"] == 1.0+ assert diff["links_only_rendered"] == 6+ assert diff["links_only_rendered_share"] == 1.0+ assert diff["schema_types_only_rendered"] == ["Brand", "Organization"]+ assert diff["h1_only_rendered"] == ["Title here"]+ assert diff["title_changed"] is False+ assert gap["significant"] is True+ assert len(gap["reasons"]) == 4, gap["reasons"]+ assert gap["reasons"][0].startswith("100% of visible words appear only after JavaScript")+ assert gap["reasons"] == js_gap_reasons(gap)+ json.dumps(gap) # the object goes straight into the CLI JSON+++def test_identical_html_has_no_gap_and_no_reasons() -> None:+ gap = js_gap(HYDRATED, HYDRATED)+ assert gap["diff"]["words_only_rendered"] == 0+ assert gap["diff"]["words_only_rendered_share"] == 0.0+ assert gap["diff"]["links_only_rendered"] == 0+ assert gap["reasons"] == []+ assert gap["significant"] is False+++def test_missing_side_means_no_render_and_returns_none() -> None:+ assert js_gap(None, HYDRATED) is None+ assert js_gap(SHELL, None) is None+ assert js_gap_reasons(None) == []+++def test_empty_raw_body_is_compared_not_skipped() -> None:+ gap = js_gap("", HYDRATED)+ assert gap["raw"] == {+ "words": 0, "links": 0, "schema_types": [], "h1": [], "title": None,+ "canonical": None, "canonical_all": [], "meta_robots": None,+ }+ assert gap["diff"]["words_only_rendered_share"] == 1.0+ assert gap["diff"]["title_changed"] is True+++def test_title_canonical_and_robots_changes_are_flagged() -> None:+ raw = _page(+ "<title>Server title</title>"+ '<link rel="canonical" href="https://shop.example/a">'+ '<meta name="robots" content="noindex">'+ )+ rendered = _page(+ "<title>Client title</title>"+ '<link rel="canonical" href="https://shop.example/b">'+ '<meta name="robots" content="index, follow">'+ )+ gap = js_gap(raw, rendered)+ assert gap["raw"]["canonical"] == "https://shop.example/a"+ assert gap["rendered"]["canonical"] == "https://shop.example/b"+ assert gap["raw"]["meta_robots"] == "noindex"+ assert gap["rendered"]["meta_robots"] == "index, follow"+ assert gap["diff"]["title_changed"] is True+ assert gap["diff"]["canonical_changed"] is True+ assert gap["diff"]["meta_robots_changed"] is True+ # Same words and links on both sides: only the three head tags differ.+ assert gap["diff"]["words_only_rendered"] == 0+ assert gap["significant"] is True+ assert gap["reasons"] == [+ "the title is not the same before and after JavaScript "+ "(raw: 'Server title', rendered: 'Client title')",+ "the canonical URL is not the same before and after JavaScript "+ "(raw: 'https://shop.example/a', rendered: 'https://shop.example/b')",+ "the meta robots value is not the same before and after JavaScript "+ "(raw: 'noindex', rendered: 'index, follow')",+ ]+++def test_head_tags_added_only_by_javascript_count_as_changed() -> None:+ rendered = _page(+ "<title>Client title</title>"+ '<link rel="canonical" href="https://shop.example/b">'+ '<meta name="robots" content="noindex">'+ )+ gap = js_gap(_page(), rendered)+ assert gap["diff"]["title_changed"] is True+ assert gap["diff"]["canonical_changed"] is True+ assert gap["diff"]["meta_robots_changed"] is True+ assert "(raw: none, rendered: 'noindex')" in gap["reasons"][-1]+++def test_second_canonical_injected_by_javascript_is_a_change() -> None:+ first = '<link rel="canonical" href="https://shop.example/a">'+ gap = js_gap(+ _page(first),+ _page(first + '<link href="https://shop.example/b" rel="alternate CANONICAL">'),+ )+ assert gap["rendered"]["canonical"] == "https://shop.example/a"+ assert gap["rendered"]["canonical_all"] == [+ "https://shop.example/a", "https://shop.example/b",+ ]+ assert gap["diff"]["canonical_changed"] is True+ assert "'https://shop.example/a | https://shop.example/b'" in gap["reasons"][0]+++def test_robots_directive_order_case_and_split_tags_are_not_a_change() -> None:+ raw = _page('<meta name="ROBOTS" content="NOINDEX,nofollow">')+ rendered = _page(+ '<meta name="robots" content="nofollow"><meta name="robots" content=" noindex ">'+ )+ gap = js_gap(raw, rendered)+ assert gap["raw"]["meta_robots"] == "noindex, nofollow"+ assert gap["rendered"]["meta_robots"] == "nofollow, noindex"+ assert gap["diff"]["meta_robots_changed"] is False+ assert gap["reasons"] == []+++def test_replaced_copy_counts_even_when_the_word_total_is_equal() -> None:+ raw = "<html><body><p>" + "loading " * 40 + "</p></body></html>"+ rendered = "<html><body><p>" + "product " * 40 + "</p></body></html>"+ gap = js_gap(raw, rendered)+ assert gap["raw"]["words"] == gap["rendered"]["words"] == 40+ assert gap["diff"]["words_only_rendered"] == 40+ assert gap["significant"] is True+++def test_links_are_matched_by_href_and_non_links_are_ignored() -> None:+ raw = _page(body='<a href="/a">a</a><a href="/b">b</a>')+ rendered = _page(+ body='<a href="/a">a</a><a href="/b">b</a><a href="/c">c</a>'+ '<a href="#top">top</a><a href="javascript:void(0)">x</a>'+ '<a href="mailto:[email protected]">m</a><a>no href</a>'+ )+ gap = js_gap(raw, rendered)+ assert gap["raw"]["links"] == 2+ assert gap["rendered"]["links"] == 3+ assert gap["diff"]["links_only_rendered"] == 1+ assert gap["diff"]["links_only_rendered_share"] == 0.333+++def test_significance_thresholds_are_the_named_constants(monkeypatch) -> None:+ raw = "<html><body><p>" + "base " * 100 + "</p></body></html>"+ rendered = (+ "<html><body><p>" + "base " * 100 + "extra " * 20 + "</p>"+ '<a href="/1">1</a><a href="/2">2</a></body></html>'+ )+ gap = js_gap(raw, rendered)+ # 22 of 122 words (18%) and 2 links: under every default limit.+ assert gap["diff"]["words_only_rendered"] == 22+ assert gap["reasons"] == []++ monkeypatch.setattr(render_page, "JS_GAP_WORDS_SHARE", 0.10)+ monkeypatch.setattr(render_page, "JS_GAP_WORDS_MIN", 10)+ monkeypatch.setattr(render_page, "JS_GAP_LINKS_MIN", 2)+ reasons = js_gap_reasons(gap)+ assert len(reasons) == 2+ assert reasons[0].startswith("18% of visible words")+ assert reasons[1].startswith("2 of 2 links appear only after JavaScript")+++def test_a_few_new_words_on_a_tiny_page_are_not_significant() -> None:+ gap = js_gap(+ "<html><body><p>hello</p></body></html>",+ "<html><body><p>hello there dear visitor</p></body></html>",+ )+ assert gap["diff"]["words_only_rendered_share"] == 0.75+ assert gap["significant"] is False+++def test_non_visible_markup_is_not_counted_as_words_links_or_title() -> None:+ html = (+ "<html><head><title>Real title</title><style>.a{color:red}</style></head><body>"+ "<svg><title>Icon name</title></svg>"+ "<script>var hidden = 'one two three';</script>"+ '<noscript><h1>No script</h1><a href="/ns">enable js</a></noscript>'+ '<template><h1>Tpl</h1><a href="/tpl">tpl</a></template>'+ "<h1>Seen</h1><p>four visible words here</p></body></html>"+ )+ signals = js_gap(html, html)["raw"]+ assert signals["title"] == "Real title"+ assert signals["h1"] == ["Seen"]+ assert signals["links"] == 0+ assert signals["words"] == 5+++def test_svg_title_alone_is_not_a_document_title() -> None:+ signals = js_gap("<body><svg><title>Icon</title></svg></body>", "")["raw"]+ assert signals["title"] is None+++def test_h1_change_and_removed_tags_are_reported() -> None:+ gap = js_gap(+ _page("<title>T</title>", "<h1>Old heading</h1>"),+ _page("", "<h1>New heading</h1>"),+ )+ assert gap["diff"]["h1_only_rendered"] == ["New heading"]+ assert gap["reasons"] == [+ "the H1 changes after JavaScript",+ "the title is not the same before and after JavaScript (raw: 'T', rendered: none)",+ ]+++def test_output_is_bounded_for_hostile_pages() -> None:+ hostile = (+ "<html><head><title>" + "t" * 5000 + "</title>"+ + "".join(f'<link rel="canonical" href="https://x.example/{i}">' for i in range(40))+ + '<meta name="robots" content="' + ",".join(f"d{i}" for i in range(500)) + '">'+ + '<script type="application/ld+json">['+ + ",".join('{"@type":"T%d"}' % i for i in range(60))+ + "]</script></head><body>"+ + "".join(f"<h1>Heading {i}</h1>" for i in range(60))+ + "</body></html>"+ )+ gap = js_gap("", hostile, raw_truncated=True)+ rendered = gap["rendered"]+ assert len(rendered["title"]) == render_page.JS_GAP_MAX_TEXT+ assert len(rendered["h1"]) == render_page.JS_GAP_MAX_ITEMS+ assert len(rendered["schema_types"]) == render_page.JS_GAP_MAX_ITEMS+ assert len(rendered["canonical_all"]) == render_page.JS_GAP_MAX_CANONICALS+ assert len(rendered["meta_robots"].split(", ")) == render_page.JS_GAP_MAX_ITEMS+ assert gap["raw_truncated"] is True+ assert all(len(reason) < 400 for reason in gap["reasons"])+++def test_malformed_json_ld_and_markup_do_not_raise() -> None:+ broken = (+ '<html><head><script type="application/ld+json">{"@type": </script>'+ "<link rel=canonical><meta name=robots><title></title></head>"+ "<body><h1></h1><a href=''>x</a><p>unclosed"+ )+ gap = js_gap(broken, broken)+ assert gap["raw"]["schema_types"] == []+ assert gap["raw"]["canonical"] is None+ assert gap["raw"]["meta_robots"] is None+ assert gap["raw"]["title"] is None+ assert gap["reasons"] == []diff --git a/tests/test_render_page.py b/tests/test_render_page.pyindex 31db07c..793bd46 100644--- a/tests/test_render_page.py+++ b/tests/test_render_page.py@@ -575,9 +575,61 @@ def test_render_page_result_dict_has_all_documented_fields() -> None:"extracted_text", "publication_date", "accessibility_tree","accessibility_error", "accessibility_partial","headers", "redirect_chain", "console_errors", "render_engine",- "render_diagnostics", "render_ms", "mode_used", "too_large", "error",+ "render_diagnostics", "render_ms", "mode_used", "too_large", "js_gap",+ "error",}assert set(result.keys()) == expected_fields+ # No render happened, so there is nothing to compare.+ assert result["js_gap"] is None+++def test_rendered_result_carries_the_js_gap() -> None:+ """A rendered page compares the raw shell with the hydrated DOM."""+ page = _FakeBrowserPage([(200, 20), (200, 20), (200, 20)])+ result = _render_with_fake_browser(page)+ gap = result["js_gap"]+ assert result["mode_used"] == "rendered"+ assert gap["raw"]["words"] == 0+ assert gap["rendered"]["words"] == 40+ assert gap["diff"]["words_only_rendered_share"] == 1.0+ assert gap["raw_truncated"] is False+ assert gap["significant"] is True+ # The CLI JSON is built from the full strings, before --max-text cuts them.+ summary = render_page._json_summary(result, max_text=10)+ assert summary["js_gap"] == gap+ json.dumps(summary)+++def test_js_gap_stays_null_when_the_render_fails() -> None:+ spa_html = '<html><body><div id="root"></div></body></html>'+ with patch.object(render_page, "validate_url_strict", side_effect=_mock_validate_strict), \+ patch.object(render_page, "safe_requests_get",+ return_value=_fake_response(spa_html)), \+ patch.object(render_page, "sync_playwright", None):+ result = render_page.render_page("https://app.example/", mode="auto")+ assert result["error"] is not None+ assert result["js_gap"] is None+++def test_js_gap_is_skipped_for_oversized_html(monkeypatch) -> None:+ monkeypatch.setattr(render_page, "JS_GAP_MAX_HTML_CHARS", 100)+ page = _FakeBrowserPage([(200, 20), (200, 20), (200, 20)])+ result = _render_with_fake_browser(page)+ assert result["error"] is None+ assert result["js_gap"] is None+ assert result["render_diagnostics"] == [+ "js_gap skipped: HTML is larger than 100 characters"+ ]+++def test_js_gap_failure_is_a_diagnostic_not_an_error() -> None:+ page = _FakeBrowserPage([(200, 20), (200, 20), (200, 20)])+ with patch.object(render_page, "js_gap", side_effect=RuntimeError("boom")):+ result = _render_with_fake_browser(page)+ assert result["error"] is None+ assert result["js_gap"] is None+ assert result["content"].startswith("<html>")+ assert any("js_gap comparison failed" in item for item in result["render_diagnostics"])def test_cdp_accessibility_nodes_are_bounded_and_rebuilt(monkeypatch) -> None: