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,372 @@
|
|
|
1
|
+
"""Abstract edits and the adapter contract.
|
|
2
|
+
|
|
3
|
+
An `Edit` says WHAT a page should declare ("the title is X", "this JSON-LD
|
|
4
|
+
node exists"); an adapter says HOW that is expressed in one framework's source
|
|
5
|
+
file and returns the edited text. Adapters never write: the text they return
|
|
6
|
+
becomes a unified diff that `omnirank.apply.engine` hash-checks, journals and
|
|
7
|
+
writes like any other fix.
|
|
8
|
+
|
|
9
|
+
Every adapter follows the same three rules:
|
|
10
|
+
|
|
11
|
+
- **Refuse, never guess.** Anything the adapter cannot prove it understands
|
|
12
|
+
(a computed value, two candidate tags, a shape it does not recognise) is a
|
|
13
|
+
refusal with a reason, and the file is left alone for that edit.
|
|
14
|
+
- **Replace, never duplicate.** An existing tag/field is edited in place; a
|
|
15
|
+
value already equal to the requested one is "already in the desired state"
|
|
16
|
+
and produces no change (idempotency).
|
|
17
|
+
- **Splice, never reformat.** Only the bytes of the edited value or the
|
|
18
|
+
inserted lines change; line endings, quotes and indentation follow the file.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
import re
|
|
24
|
+
from collections.abc import Mapping, Sequence
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Literal
|
|
28
|
+
|
|
29
|
+
from ..schema.core import dump_jsonld
|
|
30
|
+
|
|
31
|
+
EditKind = Literal["title", "description", "canonical", "og", "robots", "lang", "jsonld"]
|
|
32
|
+
|
|
33
|
+
OG_PROPERTIES = ("og:title", "og:description", "og:url", "og:type", "og:site_name",
|
|
34
|
+
"og:locale", "og:image")
|
|
35
|
+
_URL_OG = ("og:url", "og:image")
|
|
36
|
+
_LANG = re.compile(r"^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$")
|
|
37
|
+
_CONTROL = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _http_url(value: str) -> bool:
|
|
41
|
+
return bool(re.match(r"^https?://[^\s/?#]+[^\s]*$", value))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class Edit:
|
|
46
|
+
"""One abstract page-level edit. Build with the module-level helpers."""
|
|
47
|
+
|
|
48
|
+
kind: EditKind
|
|
49
|
+
value: str | Mapping
|
|
50
|
+
name: str | None = None # the og: property, for kind == "og"
|
|
51
|
+
# "set" inserts or replaces; "insert" refuses when the tag/field already
|
|
52
|
+
# exists; "replace" refuses when it does not (used by mechanical fixes).
|
|
53
|
+
mode: Literal["set", "insert", "replace"] = "set"
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def id(self) -> str:
|
|
57
|
+
if self.kind == "og":
|
|
58
|
+
return f"edit.{self.name}"
|
|
59
|
+
if self.kind == "jsonld":
|
|
60
|
+
return f"edit.jsonld:{jsonld_type(self.value)}"
|
|
61
|
+
return f"edit.{self.kind}"
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def text(self) -> str:
|
|
65
|
+
assert isinstance(self.value, str)
|
|
66
|
+
return self.value
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def check_mode(edit: Edit, exists: bool, what: str) -> None:
|
|
70
|
+
"""Refuse when `edit.mode` forbids acting on an existing/absent `what`."""
|
|
71
|
+
if edit.mode == "insert" and exists:
|
|
72
|
+
raise Refused(f"the file already declares {what}")
|
|
73
|
+
if edit.mode == "replace" and not exists:
|
|
74
|
+
raise Refused(f"the file declares no {what} to replace")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _text(value: str, what: str) -> str:
|
|
78
|
+
if not isinstance(value, str) or not value.strip():
|
|
79
|
+
raise ValueError(f"{what} must be a non-empty string")
|
|
80
|
+
if _CONTROL.search(value):
|
|
81
|
+
raise ValueError(f"{what} contains a control character")
|
|
82
|
+
return value
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def set_title(text: str) -> Edit:
|
|
86
|
+
return Edit("title", _text(text, "title"))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def set_description(text: str) -> Edit:
|
|
90
|
+
return Edit("description", _text(text, "description"))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def set_canonical(url: str) -> Edit:
|
|
94
|
+
if not _http_url(_text(url, "canonical")):
|
|
95
|
+
raise ValueError(f"canonical must be an absolute http(s) URL, not {url!r}")
|
|
96
|
+
return Edit("canonical", url)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def set_og(prop: str, content: str) -> Edit:
|
|
100
|
+
if prop not in OG_PROPERTIES:
|
|
101
|
+
raise ValueError(f"unsupported Open Graph property {prop!r} "
|
|
102
|
+
f"(supported: {', '.join(OG_PROPERTIES)})")
|
|
103
|
+
_text(content, prop)
|
|
104
|
+
if prop in _URL_OG and not _http_url(content):
|
|
105
|
+
raise ValueError(f"{prop} must be an absolute http(s) URL, not {content!r}")
|
|
106
|
+
return Edit("og", content, prop)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def set_robots(content: str) -> Edit:
|
|
110
|
+
return Edit("robots", _text(content, "robots"))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def set_lang(code: str) -> Edit:
|
|
114
|
+
if not isinstance(code, str) or not _LANG.match(code):
|
|
115
|
+
raise ValueError(f"lang must be a BCP 47 tag such as 'en' or 'bn-BD', not {code!r}")
|
|
116
|
+
return Edit("lang", code)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def inject_jsonld(node: Mapping) -> Edit:
|
|
120
|
+
"""A JSON-LD block to declare: `omnirank.schema.generate(...).jsonld` (a
|
|
121
|
+
schema.org `@graph`) or a single node with a string `@type`.
|
|
122
|
+
|
|
123
|
+
It must carry the schema.org `@context`. An empty `@graph` -- the schema
|
|
124
|
+
generator found no sourced value -- is rejected rather than written.
|
|
125
|
+
Matching an existing block is by node (`@type`, plus `@id` when both sides
|
|
126
|
+
have one): a block whose nodes are all re-declared here is replaced, so a
|
|
127
|
+
second run never adds a duplicate.
|
|
128
|
+
"""
|
|
129
|
+
if not isinstance(node, Mapping):
|
|
130
|
+
raise TypeError("JSON-LD must be a single object")
|
|
131
|
+
if node.get("@context") not in ("https://schema.org", "http://schema.org",
|
|
132
|
+
"https://schema.org/", "http://schema.org/"):
|
|
133
|
+
raise ValueError("JSON-LD must carry the schema.org @context")
|
|
134
|
+
if "@graph" in node:
|
|
135
|
+
graph = node["@graph"]
|
|
136
|
+
if not isinstance(graph, list) or not graph:
|
|
137
|
+
raise ValueError("the JSON-LD @graph is empty: nothing sourced to inject")
|
|
138
|
+
if not all(isinstance(n, Mapping) and isinstance(n.get("@type"), str)
|
|
139
|
+
and n["@type"] for n in graph):
|
|
140
|
+
raise ValueError("every @graph node needs a single string @type")
|
|
141
|
+
elif not isinstance(node.get("@type"), str) or not node["@type"]:
|
|
142
|
+
raise ValueError("JSON-LD must have a single string @type (or a @graph)")
|
|
143
|
+
return Edit("jsonld", json.loads(json.dumps(node))) # TypeError on non-JSON
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def jsonld_type(node) -> str:
|
|
147
|
+
return "+".join(t for t, _ in node_keys(node)) or "?"
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def node_keys(block) -> list[tuple[str, str | None]]:
|
|
151
|
+
"""(@type, @id) of every node a JSON-LD block declares at the top level."""
|
|
152
|
+
if isinstance(block, Mapping) and isinstance(block.get("@graph"), list):
|
|
153
|
+
nodes = block["@graph"]
|
|
154
|
+
elif isinstance(block, list):
|
|
155
|
+
nodes = block
|
|
156
|
+
else:
|
|
157
|
+
nodes = [block]
|
|
158
|
+
out = []
|
|
159
|
+
for item in nodes:
|
|
160
|
+
if isinstance(item, Mapping):
|
|
161
|
+
kind = item.get("@type")
|
|
162
|
+
kind = "+".join(map(str, kind)) if isinstance(kind, list) else str(kind)
|
|
163
|
+
ident = item.get("@id")
|
|
164
|
+
out.append((kind, ident if isinstance(ident, str) else None))
|
|
165
|
+
return out
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _same(a: tuple[str, str | None], b: tuple[str, str | None]) -> bool:
|
|
169
|
+
return a[0] == b[0] and (a[1] is None or b[1] is None or a[1] == b[1])
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def jsonld_match(existing, wanted: Mapping) -> bool:
|
|
173
|
+
"""True when `existing` is the block `wanted` replaces.
|
|
174
|
+
|
|
175
|
+
Raises Refused when they share a node but `existing` ALSO declares nodes
|
|
176
|
+
`wanted` does not: replacing it would silently drop those.
|
|
177
|
+
"""
|
|
178
|
+
ours, theirs = node_keys(wanted), node_keys(existing)
|
|
179
|
+
if not any(_same(a, b) for a in ours for b in theirs):
|
|
180
|
+
return False
|
|
181
|
+
extra = [b for b in theirs if not any(_same(a, b) for a in ours)]
|
|
182
|
+
if extra:
|
|
183
|
+
raise Refused(f"an existing JSON-LD block declares {jsonld_type(wanted)} "
|
|
184
|
+
f"together with {', '.join(t for t, _ in extra)}; replacing it "
|
|
185
|
+
"would drop those, so it is left for you to merge")
|
|
186
|
+
return True
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def compact_jsonld(node: Mapping) -> str:
|
|
190
|
+
"""One-line JSON with `<`, U+2028 and U+2029 escaped (safe inside <script>)."""
|
|
191
|
+
body = json.dumps(node, ensure_ascii=False, separators=(",", ":"))
|
|
192
|
+
return body.replace("<", "\\u003c").replace("\u2028", "\\u2028").replace(
|
|
193
|
+
"\u2029", "\\u2029")
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def pretty_jsonld(node: Mapping) -> str:
|
|
197
|
+
return dump_jsonld(dict(node))
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
# --- results -------------------------------------------------------------------------
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@dataclass
|
|
204
|
+
class Rendered:
|
|
205
|
+
"""What an adapter did to one file's text.
|
|
206
|
+
|
|
207
|
+
`text` carries every accepted edit; `refused` pairs each refused edit with
|
|
208
|
+
its reason. An edit that was already satisfied is in `unchanged`.
|
|
209
|
+
"""
|
|
210
|
+
|
|
211
|
+
text: str
|
|
212
|
+
applied: list[Edit] = field(default_factory=list)
|
|
213
|
+
unchanged: list[Edit] = field(default_factory=list)
|
|
214
|
+
refused: list[tuple[Edit, str]] = field(default_factory=list)
|
|
215
|
+
notes: list[str] = field(default_factory=list)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
class Refused(Exception):
|
|
219
|
+
"""An edit the adapter will not make; the message is the reason."""
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@dataclass(frozen=True)
|
|
223
|
+
class Context:
|
|
224
|
+
"""Where the file lives, for adapters that must read sibling files
|
|
225
|
+
(Next.js ancestor layouts, an Astro layout component). Read-only."""
|
|
226
|
+
|
|
227
|
+
root: Path
|
|
228
|
+
rel: str
|
|
229
|
+
|
|
230
|
+
@property
|
|
231
|
+
def path(self) -> Path:
|
|
232
|
+
return self.root / self.rel
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
class Adapter:
|
|
236
|
+
"""Base class. Subclasses implement `edit_one` and `jsonld_health`."""
|
|
237
|
+
|
|
238
|
+
name: str = ""
|
|
239
|
+
frameworks: tuple[str, ...] = ()
|
|
240
|
+
suffixes: tuple[str, ...] = ()
|
|
241
|
+
|
|
242
|
+
def owns(self, rel: str) -> bool:
|
|
243
|
+
return rel.lower().endswith(self.suffixes)
|
|
244
|
+
|
|
245
|
+
def precheck(self, ctx: Context, text: str) -> str | None:
|
|
246
|
+
"""A refusal that applies to every edit on this file, or None."""
|
|
247
|
+
return None
|
|
248
|
+
|
|
249
|
+
def describe(self, ctx: Context, text: str) -> str | None:
|
|
250
|
+
"""Why this file's metadata is not editable at all, or None (used to
|
|
251
|
+
explain a locator `none`, e.g. Next.js generateMetadata)."""
|
|
252
|
+
return self.precheck(ctx, text)
|
|
253
|
+
|
|
254
|
+
def edit_one(self, ctx: Context, text: str, edit: Edit) -> str:
|
|
255
|
+
"""Return the new text (== `text` when already satisfied) or raise Refused."""
|
|
256
|
+
raise NotImplementedError
|
|
257
|
+
|
|
258
|
+
def jsonld_health(self, text: str) -> tuple[int, int]:
|
|
259
|
+
"""(JSON-LD blocks this adapter can see, how many of them parse)."""
|
|
260
|
+
raise NotImplementedError
|
|
261
|
+
|
|
262
|
+
def render(self, ctx: Context, text: str, edits: Sequence[Edit]) -> Rendered:
|
|
263
|
+
out = Rendered(text=text)
|
|
264
|
+
if not self.owns(ctx.rel):
|
|
265
|
+
reason = (f"the {self.name} adapter does not edit "
|
|
266
|
+
f"{Path(ctx.rel).suffix or 'extensionless'} files")
|
|
267
|
+
out.refused.extend((edit, reason) for edit in edits)
|
|
268
|
+
return out
|
|
269
|
+
blanket = self.precheck(ctx, text)
|
|
270
|
+
for edit in edits:
|
|
271
|
+
if blanket is not None:
|
|
272
|
+
out.refused.append((edit, blanket))
|
|
273
|
+
continue
|
|
274
|
+
try:
|
|
275
|
+
new = self.edit_one(ctx, out.text, edit)
|
|
276
|
+
except Refused as exc:
|
|
277
|
+
out.refused.append((edit, str(exc)))
|
|
278
|
+
continue
|
|
279
|
+
if new == out.text:
|
|
280
|
+
out.unchanged.append(edit)
|
|
281
|
+
else:
|
|
282
|
+
out.text = new
|
|
283
|
+
out.applied.append(edit)
|
|
284
|
+
return out
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def line_indent(text: str, index: int) -> str:
|
|
288
|
+
"""The leading whitespace of the line containing `index`."""
|
|
289
|
+
start = text.rfind("\n", 0, index) + 1
|
|
290
|
+
line = text[start:]
|
|
291
|
+
return line[:len(line) - len(line.lstrip(" \t"))]
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def line_start(text: str, index: int) -> int:
|
|
295
|
+
return text.rfind("\n", 0, index) + 1
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def collapse(value: str) -> str:
|
|
299
|
+
return " ".join(value.split())
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
# --- JavaScript string literals (Next.js and Astro frontmatter) ----------------------
|
|
303
|
+
|
|
304
|
+
_JS_ESCAPES = {"n": "\n", "r": "\r", "t": "\t", "b": "\b", "f": "\f", "v": "\v",
|
|
305
|
+
"0": "\0", "\n": "", "\\": "\\", "'": "'", '"': '"', "`": "`"}
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def parse_js_string(src: str) -> str | None:
|
|
309
|
+
"""The value of one JS string literal ('..', ".." or a `..` template with no
|
|
310
|
+
`${`), or None when `src` is not exactly that."""
|
|
311
|
+
if len(src) < 2 or src[0] not in "'\"`" or src[-1] != src[0]:
|
|
312
|
+
return None
|
|
313
|
+
quote, body = src[0], src[1:-1]
|
|
314
|
+
if quote == "`" and "${" in body:
|
|
315
|
+
return None
|
|
316
|
+
out: list[str] = []
|
|
317
|
+
i = 0
|
|
318
|
+
while i < len(body):
|
|
319
|
+
ch = body[i]
|
|
320
|
+
if ch == quote:
|
|
321
|
+
return None # an unescaped quote: not one literal
|
|
322
|
+
if ch in "\r\n" and quote != "`":
|
|
323
|
+
return None # a raw line break ends a '..'/".." literal
|
|
324
|
+
if ch != "\\":
|
|
325
|
+
out.append(ch)
|
|
326
|
+
i += 1
|
|
327
|
+
continue
|
|
328
|
+
i += 1
|
|
329
|
+
if i >= len(body):
|
|
330
|
+
return None
|
|
331
|
+
esc = body[i]
|
|
332
|
+
if esc == "u":
|
|
333
|
+
if body[i + 1:i + 2] == "{":
|
|
334
|
+
end = body.find("}", i)
|
|
335
|
+
if end == -1:
|
|
336
|
+
return None
|
|
337
|
+
try:
|
|
338
|
+
out.append(chr(int(body[i + 2:end], 16)))
|
|
339
|
+
except ValueError:
|
|
340
|
+
return None
|
|
341
|
+
i = end + 1
|
|
342
|
+
continue
|
|
343
|
+
try:
|
|
344
|
+
out.append(chr(int(body[i + 1:i + 5], 16)))
|
|
345
|
+
except ValueError:
|
|
346
|
+
return None
|
|
347
|
+
i += 5
|
|
348
|
+
continue
|
|
349
|
+
if esc == "x":
|
|
350
|
+
try:
|
|
351
|
+
out.append(chr(int(body[i + 1:i + 3], 16)))
|
|
352
|
+
except ValueError:
|
|
353
|
+
return None
|
|
354
|
+
i += 3
|
|
355
|
+
continue
|
|
356
|
+
if esc == "\r" and body[i + 1:i + 2] == "\n":
|
|
357
|
+
i += 2
|
|
358
|
+
continue
|
|
359
|
+
out.append(_JS_ESCAPES.get(esc, esc))
|
|
360
|
+
i += 1
|
|
361
|
+
return "".join(out)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def js_string(value: str, quote: str = '"') -> str:
|
|
365
|
+
"""`value` as a JS string literal in `quote` ('"' or "'"). Non-ASCII stays
|
|
366
|
+
literal; line terminators and the quote are escaped."""
|
|
367
|
+
if quote not in ("'", '"'):
|
|
368
|
+
quote = '"'
|
|
369
|
+
body = (value.replace("\\", "\\\\").replace(quote, "\\" + quote)
|
|
370
|
+
.replace("\n", "\\n").replace("\r", "\\r")
|
|
371
|
+
.replace("\u2028", "\\u2028").replace("\u2029", "\\u2029"))
|
|
372
|
+
return f"{quote}{body}{quote}"
|