vendor.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """Use the pinned browser distributions in standalone HTML without a network request."""
  2. import base64
  3. import hashlib
  4. import json
  5. import re
  6. from html import escape
  7. from html.parser import HTMLParser
  8. from pathlib import Path
  9. _VENDOR = Path(__file__).resolve().parents[1] / "assets" / "vendor"
  10. def embed_vendor_scripts(html: str) -> str:
  11. manifest = json.loads((_VENDOR / "manifest.json").read_text(encoding="utf-8"))
  12. resources = {entry["url"]: entry for entry in manifest["resources"]}
  13. if len(resources) != len(manifest["resources"]):
  14. raise ValueError("duplicate bundled resource URL")
  15. data_urls: dict[str, str] = {}
  16. offsets = [0] + [match.end() for match in re.finditer("\n", html)]
  17. replacements: list[tuple[int, int, str]] = []
  18. class Parser(HTMLParser):
  19. def handle_starttag(self, tag, attrs):
  20. if tag != "script":
  21. return
  22. src = next((value for name, value in attrs if name == "src"), None)
  23. entry = resources.get(src)
  24. if entry is None:
  25. return
  26. if src not in data_urls:
  27. file = entry["file"]
  28. if not re.fullmatch(r"[a-z0-9][a-z0-9.-]*\.js", file):
  29. raise ValueError("invalid bundled resource path")
  30. contents = (_VENDOR / file).read_bytes()
  31. if hashlib.sha256(contents).hexdigest() != entry["sha256"]:
  32. raise ValueError(f"bundled resource hash mismatch: {file}")
  33. data_urls[src] = "data:text/javascript;base64," + base64.b64encode(contents).decode("ascii")
  34. # 保留 async/id/onload 等属性;只换 src,不改变脚本顺序或重写作者的脚本正文。
  35. attributes = " ".join(
  36. name if value is None else f'{name}="{escape(data_urls[src] if name == "src" else value, quote=True)}"'
  37. for name, value in attrs
  38. )
  39. line, column = self.getpos()
  40. start = offsets[line - 1] + column
  41. raw = self.get_starttag_text()
  42. replacements.append((start, start + len(raw), "<script " + attributes + ("/>" if raw.endswith("/>") else ">")))
  43. Parser(convert_charrefs=False).feed(html)
  44. parts = []
  45. previous = 0
  46. for start, end, replacement in replacements:
  47. parts.extend((html[previous:start], replacement))
  48. previous = end
  49. parts.append(html[previous:])
  50. return "".join(parts)