omnirank 0.5.0__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.
- omnirank/__init__.py +14 -0
- omnirank/__main__.py +6 -0
- omnirank/adapters/__init__.py +202 -0
- omnirank/adapters/astro.py +338 -0
- omnirank/adapters/base.py +372 -0
- omnirank/adapters/html.py +561 -0
- omnirank/adapters/jsx.py +340 -0
- omnirank/adapters/nextjs.py +692 -0
- omnirank/aeo/__init__.py +9 -0
- omnirank/aeo/extract.py +383 -0
- omnirank/aeo/propose.py +84 -0
- omnirank/aeo/rules.py +964 -0
- omnirank/aeo/runner.py +148 -0
- omnirank/applicability.py +98 -0
- omnirank/apply/__init__.py +23 -0
- omnirank/apply/engine.py +1254 -0
- omnirank/apply/journal.py +139 -0
- omnirank/apply/patch.py +144 -0
- omnirank/audit.py +185 -0
- omnirank/bands.py +106 -0
- omnirank/brief/__init__.py +0 -0
- omnirank/brief/analyze.py +197 -0
- omnirank/brief/constants.py +89 -0
- omnirank/brief/cost.py +62 -0
- omnirank/brief/egress.py +23 -0
- omnirank/brief/fetchpages.py +239 -0
- omnirank/brief/render.py +151 -0
- omnirank/brief/runner.py +369 -0
- omnirank/brief/serp.py +274 -0
- omnirank/brief/text.py +181 -0
- omnirank/cli.py +844 -0
- omnirank/clock.py +22 -0
- omnirank/cms/__init__.py +1 -0
- omnirank/cms/runner.py +170 -0
- omnirank/cms/wordpress.py +495 -0
- omnirank/cms/wordpress_apply.py +508 -0
- omnirank/cms/wordpress_plan.py +280 -0
- omnirank/config.py +81 -0
- omnirank/connect/__init__.py +4 -0
- omnirank/connect/bing.py +284 -0
- omnirank/connect/cloud_setup.py +43 -0
- omnirank/connect/confirm.py +242 -0
- omnirank/connect/constants.py +226 -0
- omnirank/connect/doctor.py +270 -0
- omnirank/connect/ga4.py +749 -0
- omnirank/connect/ga4_ai.py +123 -0
- omnirank/connect/google_auth.py +657 -0
- omnirank/connect/gsc.py +630 -0
- omnirank/connect/gsc_reports.py +169 -0
- omnirank/connect/http.py +310 -0
- omnirank/connect/indexnow.py +373 -0
- omnirank/connect/naver.py +536 -0
- omnirank/connect/runner.py +515 -0
- omnirank/connect/runner_ga4_ai.py +59 -0
- omnirank/connect/runner_more.py +489 -0
- omnirank/connect/runner_regional.py +260 -0
- omnirank/connect/secrets.py +190 -0
- omnirank/connect/urlcheck.py +41 -0
- omnirank/connect/yandex.py +350 -0
- omnirank/crawl/__init__.py +11 -0
- omnirank/crawl/analyze.py +493 -0
- omnirank/crawl/crawler.py +491 -0
- omnirank/crawl/custom.py +175 -0
- omnirank/crawl/export.py +67 -0
- omnirank/crawl/fetcher.py +212 -0
- omnirank/crawl/parse.py +102 -0
- omnirank/crawl/render.py +148 -0
- omnirank/crawl/robotsgate.py +198 -0
- omnirank/crawl/runner.py +295 -0
- omnirank/crawl/sitemap.py +99 -0
- omnirank/crawl/text.py +20 -0
- omnirank/crawl/urls.py +100 -0
- omnirank/crawlers.py +564 -0
- omnirank/data/ai_crawlers.json +269 -0
- omnirank/data/ai_referrers.json +42 -0
- omnirank/fetch.py +107 -0
- omnirank/fixes/__init__.py +92 -0
- omnirank/fixes/base.py +232 -0
- omnirank/fixes/canonical.py +243 -0
- omnirank/fixes/schema.py +126 -0
- omnirank/formats.py +134 -0
- omnirank/framework.py +223 -0
- omnirank/gates/__init__.py +48 -0
- omnirank/gates/aeo.py +114 -0
- omnirank/gates/contradictions.py +280 -0
- omnirank/gates/crawler_policy.py +85 -0
- omnirank/gates/geo.py +152 -0
- omnirank/gates/hygiene.py +81 -0
- omnirank/gates/jsonld.py +282 -0
- omnirank/gates/onpage.py +177 -0
- omnirank/gates/perf.py +115 -0
- omnirank/gates/security.py +264 -0
- omnirank/gates/seo.py +118 -0
- omnirank/gates/site.py +248 -0
- omnirank/geo_artifacts.py +199 -0
- omnirank/html.py +79 -0
- omnirank/keywords/__init__.py +5 -0
- omnirank/keywords/constants.py +69 -0
- omnirank/keywords/engine.py +384 -0
- omnirank/keywords/report.py +143 -0
- omnirank/keywords/runner.py +160 -0
- omnirank/keywords/source.py +60 -0
- omnirank/keywords/text.py +45 -0
- omnirank/locator.py +480 -0
- omnirank/logs/__init__.py +0 -0
- omnirank/logs/analyze.py +127 -0
- omnirank/logs/bots.py +69 -0
- omnirank/logs/ipranges.py +191 -0
- omnirank/logs/parse.py +452 -0
- omnirank/logs/paths.py +22 -0
- omnirank/logs/privacy.py +105 -0
- omnirank/logs/runner.py +179 -0
- omnirank/mcp_server.py +1480 -0
- omnirank/netguard.py +525 -0
- omnirank/packs/__init__.py +6 -0
- omnirank/packs/backlinks.py +535 -0
- omnirank/packs/blog.py +544 -0
- omnirank/packs/blog_cross.py +468 -0
- omnirank/packs/crawlers.py +23 -0
- omnirank/packs/entity.py +492 -0
- omnirank/packs/feeds.py +150 -0
- omnirank/packs/frontmatter.py +59 -0
- omnirank/packs/gsc.py +421 -0
- omnirank/packs/local.py +879 -0
- omnirank/packs/mdscan.py +326 -0
- omnirank/packs/miniyaml.py +378 -0
- omnirank/packs/model.py +46 -0
- omnirank/packs/product.py +979 -0
- omnirank/packs/refresh.py +165 -0
- omnirank/packs/runner.py +277 -0
- omnirank/packs/sitescan.py +294 -0
- omnirank/packs/textsafe.py +79 -0
- omnirank/packs/xmlsafe.py +92 -0
- omnirank/page.py +42 -0
- omnirank/registry.py +302 -0
- omnirank/report.py +251 -0
- omnirank/report_cmd/__init__.py +7 -0
- omnirank/report_cmd/delta.py +58 -0
- omnirank/report_cmd/files.py +64 -0
- omnirank/report_cmd/model.py +208 -0
- omnirank/report_cmd/notify.py +195 -0
- omnirank/report_cmd/pdf.py +83 -0
- omnirank/report_cmd/portfolio.py +342 -0
- omnirank/report_cmd/render.py +379 -0
- omnirank/report_cmd/runner.py +267 -0
- omnirank/robots.py +172 -0
- omnirank/scanner/__init__.py +10 -0
- omnirank/scanner/badge.py +90 -0
- omnirank/scanner/cache.py +69 -0
- omnirank/scanner/cli.py +96 -0
- omnirank/scanner/engine.py +289 -0
- omnirank/scanner/limits.py +98 -0
- omnirank/scanner/server.py +143 -0
- omnirank/scanner/service.py +328 -0
- omnirank/schema/__init__.py +13 -0
- omnirank/schema/catalog.py +679 -0
- omnirank/schema/catalog_specs.py +350 -0
- omnirank/schema/core.py +306 -0
- omnirank/schema/extract.py +396 -0
- omnirank/schema/gate.py +121 -0
- omnirank/schema/runner.py +213 -0
- omnirank/schema/validate.py +504 -0
- omnirank/schema/vocab.py +305 -0
- omnirank/schemas/omnirank.config.schema.json +268 -0
- omnirank/track/__init__.py +0 -0
- omnirank/track/ai_prompts.py +207 -0
- omnirank/track/analysis.py +197 -0
- omnirank/track/constants.py +155 -0
- omnirank/track/cost.py +229 -0
- omnirank/track/discover.py +277 -0
- omnirank/track/discover_cli.py +309 -0
- omnirank/track/discover_constants.py +95 -0
- omnirank/track/engines.py +216 -0
- omnirank/track/estimate_view.py +212 -0
- omnirank/track/history.py +261 -0
- omnirank/track/runner.py +586 -0
- omnirank/track/stats.py +138 -0
- omnirank/track/storage.py +128 -0
- omnirank-0.5.0.dist-info/METADATA +47 -0
- omnirank-0.5.0.dist-info/RECORD +183 -0
- omnirank-0.5.0.dist-info/WHEEL +5 -0
- omnirank-0.5.0.dist-info/entry_points.txt +2 -0
- omnirank-0.5.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,561 @@
|
|
|
1
|
+
"""Plain HTML adapter: edit the `<head>` of an `.html`/`.htm` file in place.
|
|
2
|
+
|
|
3
|
+
The markup machinery here (`Markup`) is shared with the Astro adapter, whose
|
|
4
|
+
templates are HTML plus `{expression}` attribute values and a frontmatter
|
|
5
|
+
fence. It finds tags with an attribute-aware scanner that skips comments and
|
|
6
|
+
the bodies of raw-text elements (script, style, textarea, title), so a decoy
|
|
7
|
+
`<title>` inside a comment or a script string is never edited. In plain HTML
|
|
8
|
+
mode the count it finds is cross-checked against BeautifulSoup: if the parser
|
|
9
|
+
and the scanner disagree about how many such tags exist, the edit is refused.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import html as htmllib
|
|
14
|
+
import json
|
|
15
|
+
import re
|
|
16
|
+
from collections.abc import Callable
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
|
|
19
|
+
from bs4 import BeautifulSoup
|
|
20
|
+
|
|
21
|
+
from ..fixes.base import link_close, newline_style, quote_char
|
|
22
|
+
from ..html import find_ldjson_scripts
|
|
23
|
+
from .base import (
|
|
24
|
+
Adapter,
|
|
25
|
+
Context,
|
|
26
|
+
Edit,
|
|
27
|
+
Refused,
|
|
28
|
+
check_mode,
|
|
29
|
+
collapse,
|
|
30
|
+
compact_jsonld,
|
|
31
|
+
js_string,
|
|
32
|
+
jsonld_match,
|
|
33
|
+
jsonld_type,
|
|
34
|
+
line_indent,
|
|
35
|
+
line_start,
|
|
36
|
+
parse_js_string,
|
|
37
|
+
pretty_jsonld,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
_COMMENT = re.compile(r"<!--.*?-->", re.DOTALL)
|
|
41
|
+
_RAW_TEXT = ("script", "style", "textarea", "title")
|
|
42
|
+
_HEAD_CLOSE = re.compile(r"</head\s*>", re.IGNORECASE)
|
|
43
|
+
_SPACE = re.compile(r"\s*")
|
|
44
|
+
_ATTR_NAME = re.compile(r"""[^\s"'>/=]+""")
|
|
45
|
+
_EQUALS = re.compile(r"\s*=\s*")
|
|
46
|
+
_UNQUOTED = re.compile(r"""[^\s"'=<>`]+""")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class Attr:
|
|
51
|
+
name: str
|
|
52
|
+
value: str | None # raw source text of the value (no quotes/braces)
|
|
53
|
+
kind: str # "quoted" | "unquoted" | "expr" | "bare"
|
|
54
|
+
quote: str # '"', "'" or ""
|
|
55
|
+
start: int # absolute span of the whole attribute
|
|
56
|
+
end: int
|
|
57
|
+
value_start: int # absolute span of the value INCLUDING quotes/braces
|
|
58
|
+
value_end: int
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True)
|
|
62
|
+
class Tag:
|
|
63
|
+
name: str
|
|
64
|
+
start: int
|
|
65
|
+
end: int # index just past ">"
|
|
66
|
+
name_end: int # index just past the tag name
|
|
67
|
+
attrs: tuple[Attr, ...]
|
|
68
|
+
self_closing: bool
|
|
69
|
+
|
|
70
|
+
def attr(self, name: str) -> Attr | None:
|
|
71
|
+
found = [a for a in self.attrs if a.name.lower() == name.lower()]
|
|
72
|
+
if len(found) > 1:
|
|
73
|
+
raise Refused(f"<{self.name}> declares {name} twice")
|
|
74
|
+
return found[0] if found else None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def expr_end(text: str, i: int) -> int | None:
|
|
78
|
+
"""Index just past the `}` closing the `{` at `i`; JS strings are skipped."""
|
|
79
|
+
depth = 0
|
|
80
|
+
while i < len(text):
|
|
81
|
+
ch = text[i]
|
|
82
|
+
if ch in "'\"`":
|
|
83
|
+
j = i + 1
|
|
84
|
+
while j < len(text) and text[j] != ch:
|
|
85
|
+
j += 2 if text[j] == "\\" else 1
|
|
86
|
+
i = j + 1
|
|
87
|
+
continue
|
|
88
|
+
if ch == "{":
|
|
89
|
+
depth += 1
|
|
90
|
+
elif ch == "}":
|
|
91
|
+
depth -= 1
|
|
92
|
+
if depth == 0:
|
|
93
|
+
return i + 1
|
|
94
|
+
i += 1
|
|
95
|
+
return None
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def scan_tag(text: str, i: int, *, astro: bool) -> tuple[int, tuple[Attr, ...], bool] | None:
|
|
99
|
+
"""Read a start tag's attributes from `i` (just past its name).
|
|
100
|
+
|
|
101
|
+
Returns (index just past `>`, attributes, ends with `/>`), or None when
|
|
102
|
+
the tag cannot be read. `{...}` values (Astro expressions) are scanned
|
|
103
|
+
with brace depth and JS strings, so JSON inside them is never cut short.
|
|
104
|
+
"""
|
|
105
|
+
attrs: list[Attr] = []
|
|
106
|
+
while i < len(text):
|
|
107
|
+
i = _SPACE.match(text, i).end()
|
|
108
|
+
if text.startswith("/>", i):
|
|
109
|
+
return i + 2, tuple(attrs), True
|
|
110
|
+
if text[i:i + 1] == ">":
|
|
111
|
+
return i + 1, tuple(attrs), False
|
|
112
|
+
if text[i:i + 1] == "/":
|
|
113
|
+
i += 1
|
|
114
|
+
continue
|
|
115
|
+
if astro and text[i:i + 1] == "{":
|
|
116
|
+
close = expr_end(text, i)
|
|
117
|
+
if close is None:
|
|
118
|
+
return None
|
|
119
|
+
attrs.append(Attr("{...}", text[i + 1:close - 1], "spread", "", i, close,
|
|
120
|
+
i, close))
|
|
121
|
+
i = close
|
|
122
|
+
continue
|
|
123
|
+
name = _ATTR_NAME.match(text, i)
|
|
124
|
+
if name is None:
|
|
125
|
+
return None
|
|
126
|
+
start, i = i, name.end()
|
|
127
|
+
equals = _EQUALS.match(text, i)
|
|
128
|
+
if equals is None or not equals.group(0).strip():
|
|
129
|
+
attrs.append(Attr(name.group(0), None, "bare", "", start, i, i, i))
|
|
130
|
+
continue
|
|
131
|
+
i = equals.end()
|
|
132
|
+
ch = text[i:i + 1]
|
|
133
|
+
if ch in ("'", '"'):
|
|
134
|
+
close = text.find(ch, i + 1)
|
|
135
|
+
if close == -1:
|
|
136
|
+
return None
|
|
137
|
+
attrs.append(Attr(name.group(0), text[i + 1:close], "quoted", ch, start,
|
|
138
|
+
close + 1, i, close + 1))
|
|
139
|
+
i = close + 1
|
|
140
|
+
elif ch == "{" and astro:
|
|
141
|
+
close = expr_end(text, i)
|
|
142
|
+
if close is None:
|
|
143
|
+
return None
|
|
144
|
+
attrs.append(Attr(name.group(0), text[i + 1:close - 1], "expr", "", start,
|
|
145
|
+
close, i, close))
|
|
146
|
+
i = close
|
|
147
|
+
else:
|
|
148
|
+
value = _UNQUOTED.match(text, i)
|
|
149
|
+
if value is None:
|
|
150
|
+
return None
|
|
151
|
+
attrs.append(Attr(name.group(0), value.group(0), "unquoted", "", start,
|
|
152
|
+
value.end(), i, value.end()))
|
|
153
|
+
i = value.end()
|
|
154
|
+
return None
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
# Resolve an `{expression}` value to the JS string literal that holds it:
|
|
158
|
+
# (literal start, literal end, current value, quote). Raises Refused.
|
|
159
|
+
Resolver = Callable[[str], tuple[int, int, str, str]]
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _no_expressions(expr: str) -> tuple[int, int, str, str]:
|
|
163
|
+
raise Refused(f"the value is an expression ({{{expr}}}), not literal text")
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class Markup:
|
|
167
|
+
"""Tag finding and splicing over `text[start:]` (the template region)."""
|
|
168
|
+
|
|
169
|
+
def __init__(self, text: str, *, start: int = 0, astro: bool = False,
|
|
170
|
+
resolve: Resolver = _no_expressions):
|
|
171
|
+
self.text = text
|
|
172
|
+
self.start = start
|
|
173
|
+
self.astro = astro
|
|
174
|
+
self.resolve = resolve
|
|
175
|
+
self.masked = self._mask()
|
|
176
|
+
self.expressions = self._expressions() if astro else []
|
|
177
|
+
self.noscript = self._noscript()
|
|
178
|
+
|
|
179
|
+
# -- scanning -----------------------------------------------------------------
|
|
180
|
+
|
|
181
|
+
def _mask(self) -> list[tuple[int, int]]:
|
|
182
|
+
spans = [(m.start(), m.end()) for m in _COMMENT.finditer(self.text, self.start)]
|
|
183
|
+
for name in _RAW_TEXT:
|
|
184
|
+
for tag in self._scan(name, spans):
|
|
185
|
+
if tag.self_closing:
|
|
186
|
+
continue
|
|
187
|
+
close = re.compile(rf"</{name}\s*>", re.IGNORECASE).search(self.text, tag.end)
|
|
188
|
+
end = close.start() if close else len(self.text)
|
|
189
|
+
spans.append((tag.end, end))
|
|
190
|
+
return spans
|
|
191
|
+
|
|
192
|
+
def _expressions(self) -> list[tuple[int, int]]:
|
|
193
|
+
"""Astro template `{...}` regions (outside tags, comments and raw text).
|
|
194
|
+
A tag inside one renders only if the expression says so."""
|
|
195
|
+
text, out, i = self.text, [], self.start
|
|
196
|
+
spans = sorted(self.masked)
|
|
197
|
+
while i < len(text):
|
|
198
|
+
inside = next((b for a, b in spans if a <= i < b), None)
|
|
199
|
+
if inside is not None:
|
|
200
|
+
i = inside
|
|
201
|
+
continue
|
|
202
|
+
ch = text[i]
|
|
203
|
+
if ch == "<":
|
|
204
|
+
name = re.compile(r"<([A-Za-z][\w.:-]*)").match(text, i)
|
|
205
|
+
read = scan_tag(text, name.end(), astro=True) if name else None
|
|
206
|
+
i = read[0] if read else i + 1
|
|
207
|
+
continue
|
|
208
|
+
if ch == "{":
|
|
209
|
+
end = expr_end(text, i)
|
|
210
|
+
if end is None:
|
|
211
|
+
raise Refused("an Astro template expression `{` is never closed")
|
|
212
|
+
out.append((i, end))
|
|
213
|
+
i = end
|
|
214
|
+
continue
|
|
215
|
+
i += 1
|
|
216
|
+
return out
|
|
217
|
+
|
|
218
|
+
def _noscript(self) -> list[tuple[int, int]]:
|
|
219
|
+
out = []
|
|
220
|
+
for match in re.finditer(r"<noscript\b[^>]*>", self.text[self.start:], re.IGNORECASE):
|
|
221
|
+
at = self.start + match.start()
|
|
222
|
+
if not self.live(at):
|
|
223
|
+
continue
|
|
224
|
+
close = re.compile(r"</noscript\s*>", re.IGNORECASE).search(self.text, at)
|
|
225
|
+
out.append((at, close.end() if close else len(self.text)))
|
|
226
|
+
return out
|
|
227
|
+
|
|
228
|
+
def live(self, index: int, spans: list[tuple[int, int]] | None = None) -> bool:
|
|
229
|
+
return not any(a <= index < b for a, b in (self.masked if spans is None else spans))
|
|
230
|
+
|
|
231
|
+
def _scan(self, name: str, spans: list[tuple[int, int]]) -> list[Tag]:
|
|
232
|
+
pattern = re.compile(rf"<({re.escape(name)})(?=[\s/>])", re.IGNORECASE)
|
|
233
|
+
out = []
|
|
234
|
+
for match in pattern.finditer(self.text, self.start):
|
|
235
|
+
if not self.live(match.start(), spans):
|
|
236
|
+
continue
|
|
237
|
+
read = scan_tag(self.text, match.end(), astro=self.astro)
|
|
238
|
+
if read is None:
|
|
239
|
+
raise Refused(f"a <{name}> tag at offset {match.start()} cannot be read")
|
|
240
|
+
end, attrs, closing = read
|
|
241
|
+
# `<x ... />` only self-closes in Astro's JSX-like templates; in HTML
|
|
242
|
+
# a `<script/>` still opens a raw-text body.
|
|
243
|
+
out.append(Tag(match.group(1), match.start(), end, match.end(), attrs,
|
|
244
|
+
self.astro and closing))
|
|
245
|
+
return out
|
|
246
|
+
|
|
247
|
+
def tags(self, name: str) -> list[Tag]:
|
|
248
|
+
found = self._scan(name, self.masked)
|
|
249
|
+
for tag in found:
|
|
250
|
+
if any(a <= tag.start < b for a, b in self.expressions):
|
|
251
|
+
raise Refused(f"a <{name}> tag sits inside a template expression "
|
|
252
|
+
"({...}); whether it renders is decided at build time, so "
|
|
253
|
+
"it is not edited")
|
|
254
|
+
return found
|
|
255
|
+
|
|
256
|
+
def head(self) -> tuple[int, int]:
|
|
257
|
+
"""(index just past `<head ...>` or region start, index of `</head>`)."""
|
|
258
|
+
opens = self.tags("head")
|
|
259
|
+
closes = [m for m in _HEAD_CLOSE.finditer(self.text, self.start) if self.live(m.start())]
|
|
260
|
+
if len(closes) != 1 or len(opens) > 1:
|
|
261
|
+
raise Refused(f"the file has {len(closes)} </head> tags; exactly one is "
|
|
262
|
+
"needed to place a head tag")
|
|
263
|
+
open_end = opens[0].end if opens else self.start
|
|
264
|
+
if open_end > closes[0].start():
|
|
265
|
+
raise Refused("<head> and </head> are out of order")
|
|
266
|
+
return open_end, closes[0].start()
|
|
267
|
+
|
|
268
|
+
def in_head(self, tag: Tag) -> bool:
|
|
269
|
+
open_end, close = self.head()
|
|
270
|
+
return open_end <= tag.start < close
|
|
271
|
+
|
|
272
|
+
# -- splicing ----------------------------------------------------------------
|
|
273
|
+
|
|
274
|
+
def splice(self, start: int, end: int, new: str) -> str:
|
|
275
|
+
return self.text[:start] + new + self.text[end:]
|
|
276
|
+
|
|
277
|
+
def insert_in_head(self, lines: list[str], inline: str) -> str:
|
|
278
|
+
"""Insert `lines` as new lines just before `</head>`, indented like the
|
|
279
|
+
line above it; or `inline` right before `</head>` when `</head>` shares
|
|
280
|
+
its line with other content (a minified or one-line head)."""
|
|
281
|
+
_, close = self.head()
|
|
282
|
+
text = self.text
|
|
283
|
+
begin = line_start(text, close)
|
|
284
|
+
if text[begin:close].strip():
|
|
285
|
+
return text[:close] + inline + text[close:]
|
|
286
|
+
before = [ln for ln in text[self.start:close].splitlines() if ln.strip()]
|
|
287
|
+
indent_source = before[-1] if before else ""
|
|
288
|
+
indent = indent_source[:len(indent_source) - len(indent_source.lstrip(" \t"))]
|
|
289
|
+
if before and re.match(r"\s*<head\b", indent_source, re.IGNORECASE):
|
|
290
|
+
indent += " "
|
|
291
|
+
eol = newline_style(text)
|
|
292
|
+
block = "".join(f"{indent}{line}{eol}" for line in lines)
|
|
293
|
+
return text[:begin] + block + text[begin:]
|
|
294
|
+
|
|
295
|
+
def quote(self) -> str:
|
|
296
|
+
return quote_char(self.text[self.start:])
|
|
297
|
+
|
|
298
|
+
def void_close(self) -> str:
|
|
299
|
+
"""` />` when the file self-closes its <link>/<meta> tags, else `>`."""
|
|
300
|
+
region = self.text[self.start:]
|
|
301
|
+
if re.search(r"<meta\b[^>]*/>", region, re.IGNORECASE):
|
|
302
|
+
return " />"
|
|
303
|
+
return link_close(region)
|
|
304
|
+
|
|
305
|
+
# -- value handling ----------------------------------------------------------
|
|
306
|
+
|
|
307
|
+
def attr_value(self, value: str, quote: str) -> str:
|
|
308
|
+
"""`value` written as an attribute value (with quotes)."""
|
|
309
|
+
if self.astro and any(c in value for c in "&<>\"'{}"):
|
|
310
|
+
return "{" + json.dumps(value, ensure_ascii=False) + "}"
|
|
311
|
+
escaped = (value.replace("&", "&").replace("<", "<").replace(">", ">"))
|
|
312
|
+
escaped = escaped.replace(quote, """ if quote == '"' else "'")
|
|
313
|
+
return f"{quote}{escaped}{quote}"
|
|
314
|
+
|
|
315
|
+
def text_value(self, value: str) -> str:
|
|
316
|
+
if self.astro and any(c in value for c in "&<>{}"):
|
|
317
|
+
return "{" + json.dumps(value, ensure_ascii=False) + "}"
|
|
318
|
+
return value.replace("&", "&").replace("<", "<").replace(">", ">")
|
|
319
|
+
|
|
320
|
+
def set_attr(self, tag: Tag, name: str, value: str, *, compare=None) -> str:
|
|
321
|
+
"""Set attribute `name` on `tag` to `value`; insert it when absent."""
|
|
322
|
+
compare = compare or (lambda a, b: a == b)
|
|
323
|
+
if any(a.kind == "spread" for a in tag.attrs):
|
|
324
|
+
raise Refused(f"<{tag.name}> has a spread attribute ({{...}}); a value set "
|
|
325
|
+
"beside it may be overridden or override it, so it is not edited")
|
|
326
|
+
attr = tag.attr(name)
|
|
327
|
+
quote = self.quote()
|
|
328
|
+
if attr is None:
|
|
329
|
+
return self.splice(tag.name_end, tag.name_end,
|
|
330
|
+
f" {name}={self.attr_value(value, quote)}")
|
|
331
|
+
if attr.kind == "expr":
|
|
332
|
+
literal = parse_js_string((attr.value or "").strip())
|
|
333
|
+
if literal is not None: # {"..."}: a literal written as an expression
|
|
334
|
+
if compare(literal, value):
|
|
335
|
+
return self.text
|
|
336
|
+
return self.splice(attr.value_start, attr.value_end,
|
|
337
|
+
self.attr_value(value, quote))
|
|
338
|
+
lit_start, lit_end, current, lit_quote = self.resolve(attr.value or "")
|
|
339
|
+
if compare(current, value):
|
|
340
|
+
return self.text
|
|
341
|
+
return self.splice(lit_start, lit_end, js_string(value, lit_quote))
|
|
342
|
+
current = htmllib.unescape(attr.value or "")
|
|
343
|
+
if attr.kind != "bare" and compare(current, value):
|
|
344
|
+
return self.text
|
|
345
|
+
return self.splice(attr.value_start, attr.value_end,
|
|
346
|
+
self.attr_value(value, attr.quote or quote))
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _rel_tokens(tag: Tag) -> list[str]:
|
|
350
|
+
attr = tag.attr("rel")
|
|
351
|
+
if attr is None or attr.kind == "expr":
|
|
352
|
+
return []
|
|
353
|
+
return (attr.value or "").lower().split()
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _matches(tag: Tag, key: str, value: str) -> bool:
|
|
357
|
+
attr = tag.attr(key)
|
|
358
|
+
return (attr is not None and attr.kind in ("quoted", "unquoted")
|
|
359
|
+
and (attr.value or "").strip().lower() == value.lower())
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
# --- the edits, shared by HTML and Astro ----------------------------------------------
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def find_one(doc: Markup, tags: list[Tag], label: str) -> Tag | None:
|
|
366
|
+
if len(tags) > 1:
|
|
367
|
+
raise Refused(f"the file declares {len(tags)} {label} tags; which one to edit "
|
|
368
|
+
"is ambiguous")
|
|
369
|
+
if tags and not doc.in_head(tags[0]):
|
|
370
|
+
raise Refused(f"the file's {label} tag is outside <head>")
|
|
371
|
+
if tags and any(a <= tags[0].start < b for a, b in doc.noscript):
|
|
372
|
+
raise Refused(f"the file's {label} tag is inside <noscript>; whether it counts is "
|
|
373
|
+
"unclear, so it is neither edited nor duplicated")
|
|
374
|
+
return tags[0] if tags else None
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def meta_tags(doc: Markup, edit: Edit) -> tuple[list[Tag], str, str]:
|
|
378
|
+
"""The matching <meta> tags, the key attribute and its value for `edit`."""
|
|
379
|
+
if edit.kind == "og":
|
|
380
|
+
key, value = "property", edit.name or ""
|
|
381
|
+
tags = [t for t in doc.tags("meta")
|
|
382
|
+
if _matches(t, "property", value) or _matches(t, "name", value)]
|
|
383
|
+
else:
|
|
384
|
+
key, value = "name", "description" if edit.kind == "description" else "robots"
|
|
385
|
+
tags = [t for t in doc.tags("meta") if _matches(t, "name", value)]
|
|
386
|
+
return tags, key, value
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def canonical_tags(doc: Markup) -> list[Tag]:
|
|
390
|
+
return [t for t in doc.tags("link") if "canonical" in _rel_tokens(t)]
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def edit_head(doc: Markup, edit: Edit) -> str:
|
|
394
|
+
"""Title, description, canonical, og:*, robots and lang -- not JSON-LD."""
|
|
395
|
+
q = doc.quote()
|
|
396
|
+
if edit.kind == "title":
|
|
397
|
+
tag = find_one(doc, doc.tags("title"), "<title>")
|
|
398
|
+
check_mode(edit, tag is not None, "a <title>")
|
|
399
|
+
if tag is None:
|
|
400
|
+
body = doc.text_value(edit.text)
|
|
401
|
+
return doc.insert_in_head([f"<title>{body}</title>"], f"<title>{body}</title>")
|
|
402
|
+
close = re.compile(r"</title\s*>", re.IGNORECASE).search(doc.text, tag.end)
|
|
403
|
+
if close is None:
|
|
404
|
+
raise Refused("the <title> tag is never closed")
|
|
405
|
+
body = doc.text[tag.end:close.start()]
|
|
406
|
+
expr = re.fullmatch(r"\s*\{(.*)\}\s*", body, re.DOTALL) if doc.astro else None
|
|
407
|
+
literal = parse_js_string(expr.group(1).strip()) if expr is not None else None
|
|
408
|
+
if literal is not None:
|
|
409
|
+
if collapse(literal) == collapse(edit.text):
|
|
410
|
+
return doc.text
|
|
411
|
+
return doc.splice(tag.end, close.start(), doc.text_value(edit.text))
|
|
412
|
+
if expr is not None:
|
|
413
|
+
lit_start, lit_end, current, lit_quote = doc.resolve(expr.group(1))
|
|
414
|
+
if collapse(current) == collapse(edit.text):
|
|
415
|
+
return doc.text
|
|
416
|
+
return doc.splice(lit_start, lit_end, js_string(edit.text, lit_quote))
|
|
417
|
+
if doc.astro and "{" in body:
|
|
418
|
+
raise Refused("the <title> text is computed by an expression")
|
|
419
|
+
if collapse(htmllib.unescape(body)) == collapse(edit.text):
|
|
420
|
+
return doc.text
|
|
421
|
+
return doc.splice(tag.end, close.start(), doc.text_value(edit.text))
|
|
422
|
+
|
|
423
|
+
if edit.kind in ("description", "robots", "og"):
|
|
424
|
+
tags, key, value = meta_tags(doc, edit)
|
|
425
|
+
tag = find_one(doc, tags, f"<meta {key}={value}>")
|
|
426
|
+
check_mode(edit, tag is not None, f"a <meta {key}={value}>")
|
|
427
|
+
if tag is None:
|
|
428
|
+
line = (f"<meta {key}={q}{value}{q} "
|
|
429
|
+
f"content={doc.attr_value(edit.text, q)}{doc.void_close()}")
|
|
430
|
+
return doc.insert_in_head([line], line)
|
|
431
|
+
return doc.set_attr(tag, "content", edit.text,
|
|
432
|
+
compare=lambda a, b: collapse(a) == collapse(b))
|
|
433
|
+
|
|
434
|
+
if edit.kind == "canonical":
|
|
435
|
+
tag = find_one(doc, canonical_tags(doc), "<link rel=canonical>")
|
|
436
|
+
check_mode(edit, tag is not None, "a rel=canonical")
|
|
437
|
+
if tag is None:
|
|
438
|
+
line = (f"<link rel={q}canonical{q} "
|
|
439
|
+
f"href={doc.attr_value(edit.text, q)}{doc.void_close()}")
|
|
440
|
+
return doc.insert_in_head([line], line)
|
|
441
|
+
return doc.set_attr(tag, "href", edit.text,
|
|
442
|
+
compare=lambda a, b: a.strip() == b)
|
|
443
|
+
|
|
444
|
+
if edit.kind == "lang":
|
|
445
|
+
tags = doc.tags("html")
|
|
446
|
+
if len(tags) != 1:
|
|
447
|
+
raise Refused(f"the file has {len(tags)} <html> tags; exactly one is needed "
|
|
448
|
+
"to set lang")
|
|
449
|
+
return doc.set_attr(tags[0], "lang", edit.text,
|
|
450
|
+
compare=lambda a, b: a.strip().lower() == b.lower())
|
|
451
|
+
|
|
452
|
+
raise Refused(f"unsupported edit {edit.kind}")
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
# --- JSON-LD in plain HTML ------------------------------------------------------------
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _is_ldjson(tag: Tag) -> bool:
|
|
459
|
+
attr = tag.attr("type")
|
|
460
|
+
return (attr is not None and attr.kind in ("quoted", "unquoted")
|
|
461
|
+
and (attr.value or "").strip().lower() == "application/ld+json")
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _script_body(doc: Markup, tag: Tag) -> tuple[int, int]:
|
|
465
|
+
close = re.compile(r"</script\s*>", re.IGNORECASE).search(doc.text, tag.end)
|
|
466
|
+
if close is None:
|
|
467
|
+
raise Refused("a JSON-LD <script> is never closed")
|
|
468
|
+
return tag.end, close.start()
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def _json_lines(node, indent: str, eol: str) -> str:
|
|
472
|
+
return eol.join(f"{indent} {line}" if line else line
|
|
473
|
+
for line in pretty_jsonld(node).split("\n"))
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def html_jsonld(doc: Markup, edit: Edit) -> str:
|
|
477
|
+
wanted = edit.value
|
|
478
|
+
match: list[tuple[int, int, object]] = []
|
|
479
|
+
for tag in doc.tags("script"):
|
|
480
|
+
if not _is_ldjson(tag):
|
|
481
|
+
continue
|
|
482
|
+
start, end = _script_body(doc, tag)
|
|
483
|
+
try:
|
|
484
|
+
existing = json.loads(doc.text[start:end])
|
|
485
|
+
except (json.JSONDecodeError, RecursionError) as exc:
|
|
486
|
+
raise Refused("an existing JSON-LD block does not parse; fix it first so "
|
|
487
|
+
"a duplicate node is never added beside it") from exc
|
|
488
|
+
if jsonld_match(existing, wanted):
|
|
489
|
+
match.append((start, end, existing))
|
|
490
|
+
if len(match) > 1:
|
|
491
|
+
raise Refused(f"{len(match)} JSON-LD blocks hold {jsonld_type(wanted)}; "
|
|
492
|
+
"which one to replace is ambiguous")
|
|
493
|
+
eol = newline_style(doc.text)
|
|
494
|
+
if match:
|
|
495
|
+
start, end, existing = match[0]
|
|
496
|
+
if existing == wanted:
|
|
497
|
+
return doc.text
|
|
498
|
+
indent = line_indent(doc.text, start)
|
|
499
|
+
body = doc.text[start:end]
|
|
500
|
+
if "\n" not in body:
|
|
501
|
+
return doc.splice(start, end, compact_jsonld(wanted))
|
|
502
|
+
return doc.splice(start, end, eol + _json_lines(wanted, indent, eol) + eol + indent)
|
|
503
|
+
q = doc.quote()
|
|
504
|
+
open_tag = f"<script type={q}application/ld+json{q}>"
|
|
505
|
+
lines = [open_tag, *[f" {ln}" for ln in pretty_jsonld(wanted).split("\n")], "</script>"]
|
|
506
|
+
return doc.insert_in_head(lines, f"{open_tag}{compact_jsonld(wanted)}</script>")
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def soup_count(text: str, edit: Edit) -> int:
|
|
510
|
+
"""How many tags BeautifulSoup sees for `edit` -- the cross-check."""
|
|
511
|
+
soup = BeautifulSoup(text, "lxml")
|
|
512
|
+
|
|
513
|
+
def attr(tag, name):
|
|
514
|
+
value = tag.get(name)
|
|
515
|
+
return (" ".join(value) if isinstance(value, list) else value or "").strip().lower()
|
|
516
|
+
|
|
517
|
+
if edit.kind == "title":
|
|
518
|
+
return len([t for t in soup.find_all("title") if t.find_parent("svg") is None])
|
|
519
|
+
if edit.kind == "lang":
|
|
520
|
+
return len(soup.find_all("html"))
|
|
521
|
+
if edit.kind == "canonical":
|
|
522
|
+
return len([t for t in soup.find_all("link") if "canonical" in attr(t, "rel").split()])
|
|
523
|
+
if edit.kind == "og":
|
|
524
|
+
return len([t for t in soup.find_all("meta")
|
|
525
|
+
if edit.name in (attr(t, "property"), attr(t, "name"))])
|
|
526
|
+
if edit.kind in ("description", "robots"):
|
|
527
|
+
key = "description" if edit.kind == "description" else "robots"
|
|
528
|
+
return len([t for t in soup.find_all("meta") if attr(t, "name") == key])
|
|
529
|
+
return 0
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
class HtmlAdapter(Adapter):
|
|
533
|
+
name = "html"
|
|
534
|
+
frameworks = ("static", "jekyll", "hugo")
|
|
535
|
+
suffixes = (".html", ".htm")
|
|
536
|
+
|
|
537
|
+
def edit_one(self, ctx: Context, text: str, edit: Edit) -> str:
|
|
538
|
+
doc = Markup(text)
|
|
539
|
+
if edit.kind == "jsonld":
|
|
540
|
+
return html_jsonld(doc, edit)
|
|
541
|
+
ours = {"title": lambda: doc.tags("title"),
|
|
542
|
+
"lang": lambda: doc.tags("html"),
|
|
543
|
+
"canonical": lambda: canonical_tags(doc)}.get(
|
|
544
|
+
edit.kind, lambda: meta_tags(doc, edit)[0])()
|
|
545
|
+
theirs = soup_count(text, edit)
|
|
546
|
+
if edit.kind != "lang" and len(ours) != theirs:
|
|
547
|
+
raise Refused(f"the parser sees {theirs} such tag(s) but {len(ours)} were "
|
|
548
|
+
"found in the source text; refusing a splice that may edit "
|
|
549
|
+
"the wrong one")
|
|
550
|
+
return edit_head(doc, edit)
|
|
551
|
+
|
|
552
|
+
def jsonld_health(self, text: str) -> tuple[int, int]:
|
|
553
|
+
blocks = find_ldjson_scripts(BeautifulSoup(text, "lxml"))
|
|
554
|
+
ok = 0
|
|
555
|
+
for block in blocks:
|
|
556
|
+
try:
|
|
557
|
+
json.loads(block.string or "")
|
|
558
|
+
ok += 1
|
|
559
|
+
except (json.JSONDecodeError, RecursionError):
|
|
560
|
+
pass
|
|
561
|
+
return len(blocks), ok
|