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.
Files changed (183) hide show
  1. omnirank/__init__.py +14 -0
  2. omnirank/__main__.py +6 -0
  3. omnirank/adapters/__init__.py +202 -0
  4. omnirank/adapters/astro.py +338 -0
  5. omnirank/adapters/base.py +372 -0
  6. omnirank/adapters/html.py +561 -0
  7. omnirank/adapters/jsx.py +340 -0
  8. omnirank/adapters/nextjs.py +692 -0
  9. omnirank/aeo/__init__.py +9 -0
  10. omnirank/aeo/extract.py +383 -0
  11. omnirank/aeo/propose.py +84 -0
  12. omnirank/aeo/rules.py +964 -0
  13. omnirank/aeo/runner.py +148 -0
  14. omnirank/applicability.py +98 -0
  15. omnirank/apply/__init__.py +23 -0
  16. omnirank/apply/engine.py +1254 -0
  17. omnirank/apply/journal.py +139 -0
  18. omnirank/apply/patch.py +144 -0
  19. omnirank/audit.py +185 -0
  20. omnirank/bands.py +106 -0
  21. omnirank/brief/__init__.py +0 -0
  22. omnirank/brief/analyze.py +197 -0
  23. omnirank/brief/constants.py +89 -0
  24. omnirank/brief/cost.py +62 -0
  25. omnirank/brief/egress.py +23 -0
  26. omnirank/brief/fetchpages.py +239 -0
  27. omnirank/brief/render.py +151 -0
  28. omnirank/brief/runner.py +369 -0
  29. omnirank/brief/serp.py +274 -0
  30. omnirank/brief/text.py +181 -0
  31. omnirank/cli.py +844 -0
  32. omnirank/clock.py +22 -0
  33. omnirank/cms/__init__.py +1 -0
  34. omnirank/cms/runner.py +170 -0
  35. omnirank/cms/wordpress.py +495 -0
  36. omnirank/cms/wordpress_apply.py +508 -0
  37. omnirank/cms/wordpress_plan.py +280 -0
  38. omnirank/config.py +81 -0
  39. omnirank/connect/__init__.py +4 -0
  40. omnirank/connect/bing.py +284 -0
  41. omnirank/connect/cloud_setup.py +43 -0
  42. omnirank/connect/confirm.py +242 -0
  43. omnirank/connect/constants.py +226 -0
  44. omnirank/connect/doctor.py +270 -0
  45. omnirank/connect/ga4.py +749 -0
  46. omnirank/connect/ga4_ai.py +123 -0
  47. omnirank/connect/google_auth.py +657 -0
  48. omnirank/connect/gsc.py +630 -0
  49. omnirank/connect/gsc_reports.py +169 -0
  50. omnirank/connect/http.py +310 -0
  51. omnirank/connect/indexnow.py +373 -0
  52. omnirank/connect/naver.py +536 -0
  53. omnirank/connect/runner.py +515 -0
  54. omnirank/connect/runner_ga4_ai.py +59 -0
  55. omnirank/connect/runner_more.py +489 -0
  56. omnirank/connect/runner_regional.py +260 -0
  57. omnirank/connect/secrets.py +190 -0
  58. omnirank/connect/urlcheck.py +41 -0
  59. omnirank/connect/yandex.py +350 -0
  60. omnirank/crawl/__init__.py +11 -0
  61. omnirank/crawl/analyze.py +493 -0
  62. omnirank/crawl/crawler.py +491 -0
  63. omnirank/crawl/custom.py +175 -0
  64. omnirank/crawl/export.py +67 -0
  65. omnirank/crawl/fetcher.py +212 -0
  66. omnirank/crawl/parse.py +102 -0
  67. omnirank/crawl/render.py +148 -0
  68. omnirank/crawl/robotsgate.py +198 -0
  69. omnirank/crawl/runner.py +295 -0
  70. omnirank/crawl/sitemap.py +99 -0
  71. omnirank/crawl/text.py +20 -0
  72. omnirank/crawl/urls.py +100 -0
  73. omnirank/crawlers.py +564 -0
  74. omnirank/data/ai_crawlers.json +269 -0
  75. omnirank/data/ai_referrers.json +42 -0
  76. omnirank/fetch.py +107 -0
  77. omnirank/fixes/__init__.py +92 -0
  78. omnirank/fixes/base.py +232 -0
  79. omnirank/fixes/canonical.py +243 -0
  80. omnirank/fixes/schema.py +126 -0
  81. omnirank/formats.py +134 -0
  82. omnirank/framework.py +223 -0
  83. omnirank/gates/__init__.py +48 -0
  84. omnirank/gates/aeo.py +114 -0
  85. omnirank/gates/contradictions.py +280 -0
  86. omnirank/gates/crawler_policy.py +85 -0
  87. omnirank/gates/geo.py +152 -0
  88. omnirank/gates/hygiene.py +81 -0
  89. omnirank/gates/jsonld.py +282 -0
  90. omnirank/gates/onpage.py +177 -0
  91. omnirank/gates/perf.py +115 -0
  92. omnirank/gates/security.py +264 -0
  93. omnirank/gates/seo.py +118 -0
  94. omnirank/gates/site.py +248 -0
  95. omnirank/geo_artifacts.py +199 -0
  96. omnirank/html.py +79 -0
  97. omnirank/keywords/__init__.py +5 -0
  98. omnirank/keywords/constants.py +69 -0
  99. omnirank/keywords/engine.py +384 -0
  100. omnirank/keywords/report.py +143 -0
  101. omnirank/keywords/runner.py +160 -0
  102. omnirank/keywords/source.py +60 -0
  103. omnirank/keywords/text.py +45 -0
  104. omnirank/locator.py +480 -0
  105. omnirank/logs/__init__.py +0 -0
  106. omnirank/logs/analyze.py +127 -0
  107. omnirank/logs/bots.py +69 -0
  108. omnirank/logs/ipranges.py +191 -0
  109. omnirank/logs/parse.py +452 -0
  110. omnirank/logs/paths.py +22 -0
  111. omnirank/logs/privacy.py +105 -0
  112. omnirank/logs/runner.py +179 -0
  113. omnirank/mcp_server.py +1480 -0
  114. omnirank/netguard.py +525 -0
  115. omnirank/packs/__init__.py +6 -0
  116. omnirank/packs/backlinks.py +535 -0
  117. omnirank/packs/blog.py +544 -0
  118. omnirank/packs/blog_cross.py +468 -0
  119. omnirank/packs/crawlers.py +23 -0
  120. omnirank/packs/entity.py +492 -0
  121. omnirank/packs/feeds.py +150 -0
  122. omnirank/packs/frontmatter.py +59 -0
  123. omnirank/packs/gsc.py +421 -0
  124. omnirank/packs/local.py +879 -0
  125. omnirank/packs/mdscan.py +326 -0
  126. omnirank/packs/miniyaml.py +378 -0
  127. omnirank/packs/model.py +46 -0
  128. omnirank/packs/product.py +979 -0
  129. omnirank/packs/refresh.py +165 -0
  130. omnirank/packs/runner.py +277 -0
  131. omnirank/packs/sitescan.py +294 -0
  132. omnirank/packs/textsafe.py +79 -0
  133. omnirank/packs/xmlsafe.py +92 -0
  134. omnirank/page.py +42 -0
  135. omnirank/registry.py +302 -0
  136. omnirank/report.py +251 -0
  137. omnirank/report_cmd/__init__.py +7 -0
  138. omnirank/report_cmd/delta.py +58 -0
  139. omnirank/report_cmd/files.py +64 -0
  140. omnirank/report_cmd/model.py +208 -0
  141. omnirank/report_cmd/notify.py +195 -0
  142. omnirank/report_cmd/pdf.py +83 -0
  143. omnirank/report_cmd/portfolio.py +342 -0
  144. omnirank/report_cmd/render.py +379 -0
  145. omnirank/report_cmd/runner.py +267 -0
  146. omnirank/robots.py +172 -0
  147. omnirank/scanner/__init__.py +10 -0
  148. omnirank/scanner/badge.py +90 -0
  149. omnirank/scanner/cache.py +69 -0
  150. omnirank/scanner/cli.py +96 -0
  151. omnirank/scanner/engine.py +289 -0
  152. omnirank/scanner/limits.py +98 -0
  153. omnirank/scanner/server.py +143 -0
  154. omnirank/scanner/service.py +328 -0
  155. omnirank/schema/__init__.py +13 -0
  156. omnirank/schema/catalog.py +679 -0
  157. omnirank/schema/catalog_specs.py +350 -0
  158. omnirank/schema/core.py +306 -0
  159. omnirank/schema/extract.py +396 -0
  160. omnirank/schema/gate.py +121 -0
  161. omnirank/schema/runner.py +213 -0
  162. omnirank/schema/validate.py +504 -0
  163. omnirank/schema/vocab.py +305 -0
  164. omnirank/schemas/omnirank.config.schema.json +268 -0
  165. omnirank/track/__init__.py +0 -0
  166. omnirank/track/ai_prompts.py +207 -0
  167. omnirank/track/analysis.py +197 -0
  168. omnirank/track/constants.py +155 -0
  169. omnirank/track/cost.py +229 -0
  170. omnirank/track/discover.py +277 -0
  171. omnirank/track/discover_cli.py +309 -0
  172. omnirank/track/discover_constants.py +95 -0
  173. omnirank/track/engines.py +216 -0
  174. omnirank/track/estimate_view.py +212 -0
  175. omnirank/track/history.py +261 -0
  176. omnirank/track/runner.py +586 -0
  177. omnirank/track/stats.py +138 -0
  178. omnirank/track/storage.py +128 -0
  179. omnirank-0.5.0.dist-info/METADATA +47 -0
  180. omnirank-0.5.0.dist-info/RECORD +183 -0
  181. omnirank-0.5.0.dist-info/WHEEL +5 -0
  182. omnirank-0.5.0.dist-info/entry_points.txt +2 -0
  183. omnirank-0.5.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,282 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+
5
+ from bs4 import BeautifulSoup
6
+
7
+ from ..html import find_ldjson_scripts
8
+ from ..report import Finding
9
+
10
+
11
+ def _f(id_: str, gate: str, url: str, severity: str, observed: str,
12
+ expected: str, fix: str) -> Finding:
13
+ return Finding(id=id_, severity=severity, layer="seo", url=url, gate=gate,
14
+ observed=observed, expected=expected, fix=fix)
15
+
16
+
17
+ def _raw_scripts(html: str) -> list[str]:
18
+ # type="application/LD+JSON" and type="application/ld+json; charset=utf-8" are
19
+ # both valid JSON-LD script tags -- MIME type tokens are case-insensitive and a
20
+ # trailing ;charset parameter is not part of the type. find_ldjson_scripts
21
+ # normalises both before matching; a literal attrs={"type": "application/ld+json"}
22
+ # search would silently miss both and report the page as having no JSON-LD at all.
23
+ soup = BeautifulSoup(html, "lxml")
24
+ return [s.string or "" for s in find_ldjson_scripts(soup)]
25
+
26
+
27
+ def extract_blocks(html: str) -> list[dict]:
28
+ """Parse every ld+json script, flattening @graph so all nodes are top level."""
29
+ blocks: list[dict] = []
30
+ for raw in _raw_scripts(html):
31
+ try:
32
+ data = json.loads(raw)
33
+ except (json.JSONDecodeError, RecursionError):
34
+ continue
35
+ for node in data if isinstance(data, list) else [data]:
36
+ if not isinstance(node, dict):
37
+ continue
38
+ graph = node.get("@graph")
39
+ if isinstance(graph, list):
40
+ context = node.get("@context")
41
+ for n in graph:
42
+ if isinstance(n, dict):
43
+ if context is not None:
44
+ n.setdefault("@context", context)
45
+ blocks.append(n)
46
+ else:
47
+ blocks.append(node)
48
+ return blocks
49
+
50
+
51
+ MAX_WALK_DEPTH = 100
52
+
53
+
54
+ def _walk(node: object, depth: int = 0) -> list[dict]:
55
+ """Every dict anywhere in the tree, so nested ratings and reviews are seen.
56
+
57
+ Depth-capped: OmniRank parses untrusted third-party markup, and an
58
+ unbounded walk turns a hostile or malformed document into a crashed scan.
59
+ """
60
+ if depth > MAX_WALK_DEPTH:
61
+ return []
62
+ out: list[dict] = []
63
+ if isinstance(node, dict):
64
+ out.append(node)
65
+ for value in node.values():
66
+ out.extend(_walk(value, depth + 1))
67
+ elif isinstance(node, list):
68
+ for item in node:
69
+ out.extend(_walk(item, depth + 1))
70
+ return out
71
+
72
+
73
+ def _fabrication(blocks: list[dict], url: str) -> list[Finding]:
74
+ findings: list[Finding] = []
75
+ for node in [n for block in blocks for n in _walk(block)]:
76
+ types = node.get("@type", "")
77
+ types = types if isinstance(types, list) else [types]
78
+
79
+ if "AggregateRating" in types:
80
+ count = node.get("ratingCount") or node.get("reviewCount")
81
+ if not count or str(count) in {"0", "0.0"}:
82
+ findings.append(_f(
83
+ "seo.schema-fabrication.unbacked-rating", "schema-fabrication",
84
+ url, "error",
85
+ f"AggregateRating with ratingValue {node.get('ratingValue')!r} "
86
+ "and no ratingCount",
87
+ "a rating backed by a real, countable set of reviews",
88
+ "Remove the AggregateRating until real reviews exist. Unbacked "
89
+ "ratings are a manual-action risk and destroy the trust the "
90
+ "markup is meant to build."))
91
+
92
+ if "Review" in types and not node.get("author"):
93
+ findings.append(_f(
94
+ "seo.schema-fabrication.anonymous-review", "schema-fabrication",
95
+ url, "error",
96
+ "Review without an author", "a named, attributable author",
97
+ "Attribute the review to a real person or organisation, or remove it."))
98
+ return findings
99
+
100
+
101
+ # The date this table was transcribed from Google's rich-result documentation.
102
+ # Named in every finding: the table is OmniRank's reading of Google's docs on one
103
+ # day, not a live contract, and a reader is entitled to judge its age. SS6 of
104
+ # docs/research/2026-08-04-competitive-gap-analysis.md is explicit that a stale
105
+ # required-property table produces FABRICATED errors -- which is why these findings
106
+ # are `warning` and not `error` until a freshness test exists to back them.
107
+ RICH_RESULT_RULES_AS_OF = "2026-08-04"
108
+
109
+ # type -> the groups of properties Google documents as REQUIRED for that type's
110
+ # rich result. Each inner tuple is an alternatives group: at least one member must
111
+ # be present. That single shape expresses both "Article needs headline AND image
112
+ # AND datePublished" (three one-member groups) and "Product needs name AND (offers
113
+ # OR aggregateRating OR review)" (a one-member group plus a three-member one).
114
+ #
115
+ # These are GOOGLE's requirements, not schema.org's -- schema.org marks no property
116
+ # required at all, so a page can be flawless schema.org and still ineligible for
117
+ # the rich result. Every finding says so.
118
+ RICH_RESULT_RULES: dict[str, tuple[tuple[str, ...], ...]] = {
119
+ "Article": (("headline",), ("image",), ("datePublished",)),
120
+ "NewsArticle": (("headline",), ("image",), ("datePublished",)),
121
+ "BlogPosting": (("headline",), ("image",), ("datePublished",)),
122
+ "Product": (("name",), ("offers", "aggregateRating", "review")),
123
+ "FAQPage": (("mainEntity",),),
124
+ "BreadcrumbList": (("itemListElement",),),
125
+ "Organization": (("name",), ("url",)),
126
+ "LocalBusiness": (("name",), ("address",)),
127
+ }
128
+
129
+ # A node carrying @id and nothing but @id/@type/@context is a REFERENCE to an
130
+ # entity declared elsewhere -- the `@id` cross-reference pattern the design spec
131
+ # recommends. Checking it for required properties would flag correct markup.
132
+ _REFERENCE_KEYS = frozenset({"@id", "@type", "@context"})
133
+
134
+
135
+ def _types_of(node: dict) -> list[str]:
136
+ raw = node.get("@type", "")
137
+ values = raw if isinstance(raw, list) else [raw]
138
+ return [v for v in values if isinstance(v, str)]
139
+
140
+
141
+ def _present(node: dict, prop: str) -> bool:
142
+ """True when `prop` has a value worth calling present.
143
+
144
+ An empty string, an all-whitespace string, an empty list and an empty object
145
+ are all absent for this purpose -- they are what a template emits when its data
146
+ did not arrive. A numeric 0 or a False is present: those are real values.
147
+ """
148
+ value = node.get(prop)
149
+ if value is None:
150
+ return False
151
+ if isinstance(value, str):
152
+ return bool(value.strip())
153
+ if isinstance(value, (list, tuple, dict)):
154
+ return len(value) > 0
155
+ return True
156
+
157
+
158
+ def _as_nodes(value: object) -> list[dict]:
159
+ items = value if isinstance(value, list) else [value]
160
+ return [item for item in items if isinstance(item, dict)]
161
+
162
+
163
+ def _faq_missing(node: dict) -> list[str]:
164
+ """`acceptedAnswer` when no mainEntity Question carries one."""
165
+ questions = _as_nodes(node.get("mainEntity"))
166
+ if questions and not any(_present(q, "acceptedAnswer") for q in questions):
167
+ return ["acceptedAnswer (on a mainEntity Question)"]
168
+ return []
169
+
170
+
171
+ def _listitem_has_name(item: dict) -> bool:
172
+ """Google documents a ListItem name either at the top level or under `item`.
173
+
174
+ Both shapes are valid and widely emitted; checking only the top level would
175
+ report a fabricated error on entirely correct markup.
176
+ """
177
+ if _present(item, "name"):
178
+ return True
179
+ nested = item.get("item")
180
+ return isinstance(nested, dict) and _present(nested, "name")
181
+
182
+
183
+ def _breadcrumb_missing(node: dict) -> list[str]:
184
+ items = _as_nodes(node.get("itemListElement"))
185
+ if not items:
186
+ return []
187
+ missing: list[str] = []
188
+ if any(not _present(item, "position") for item in items):
189
+ missing.append("position (on an itemListElement)")
190
+ if any(not _listitem_has_name(item) for item in items):
191
+ missing.append("name (on an itemListElement)")
192
+ return missing
193
+
194
+
195
+ def _missing_for_type(node: dict, type_name: str) -> list[str]:
196
+ missing: list[str] = []
197
+ for group in RICH_RESULT_RULES[type_name]:
198
+ if not any(_present(node, prop) for prop in group):
199
+ missing.append(" or ".join(group))
200
+ if type_name == "FAQPage":
201
+ missing.extend(_faq_missing(node))
202
+ elif type_name == "BreadcrumbList":
203
+ missing.extend(_breadcrumb_missing(node))
204
+ return missing
205
+
206
+
207
+ def _required_properties(blocks: list[dict], url: str) -> list[Finding]:
208
+ """Google's REQUIRED rich-result properties, per top-level typed node.
209
+
210
+ Top-level nodes only (extract_blocks has already flattened @graph). Walking
211
+ into nested objects would flag the reference stubs and partial sub-objects that
212
+ correct markup is full of.
213
+
214
+ One finding per NODE, listing every missing property, and one finding ID for
215
+ the whole class: the fix is the same action every time (author the value), so
216
+ the fix tier is identical, and a page missing six properties is one bad
217
+ template rather than six separate defects -- which is also what keeps GATE_CAP
218
+ charging this the once.
219
+ """
220
+ findings: list[Finding] = []
221
+ for node in blocks:
222
+ if "@id" in node and not (set(node) - _REFERENCE_KEYS):
223
+ continue # a reference, not a declaration
224
+ missing: list[str] = []
225
+ for type_name in _types_of(node):
226
+ if type_name in RICH_RESULT_RULES:
227
+ missing.extend(_missing_for_type(node, type_name))
228
+ if not missing:
229
+ continue
230
+ types = "/".join(t for t in _types_of(node) if t in RICH_RESULT_RULES)
231
+ findings.append(_f(
232
+ "seo.schema-required.missing-property", "schema-required", url,
233
+ "warning",
234
+ f"{types} node missing {', '.join(missing)}",
235
+ f"the properties Google documents as required for a {types} rich result",
236
+ f"Add {', '.join(missing)} to the {types} markup. This node is valid "
237
+ "schema.org -- schema.org marks no property as required, so nothing "
238
+ "here is malformed. What is unmet is GOOGLE's rich-result requirement "
239
+ f"for {types}, as transcribed on {RICH_RESULT_RULES_AS_OF} into "
240
+ "RICH_RESULT_RULES in gates/jsonld.py: without these the page stays "
241
+ "valid and simply is not eligible for the rich result. Eligibility is "
242
+ "also not display -- Google decides per query whether to show one, and "
243
+ "OmniRank cannot observe that."))
244
+ return findings
245
+
246
+
247
+ def run(html: str, url: str) -> list[Finding]:
248
+ raws = _raw_scripts(html)
249
+ if not raws:
250
+ return [_f("seo.schema.absent", "schema", url, "error",
251
+ "no application/ld+json blocks", "at least one typed entity",
252
+ "Emit JSON-LD describing this page and cross-reference the site "
253
+ "organisation by stable @id.")]
254
+
255
+ findings: list[Finding] = []
256
+ for raw in raws:
257
+ try:
258
+ json.loads(raw)
259
+ except (json.JSONDecodeError, RecursionError) as exc:
260
+ findings.append(_f(
261
+ "seo.schema.malformed", "schema", url, "error",
262
+ f"unparseable ld+json: {exc}", "valid JSON",
263
+ "Fix the JSON-LD. Malformed blocks are discarded silently by "
264
+ "crawlers, so the markup does nothing."))
265
+
266
+ blocks = extract_blocks(html)
267
+ for node in blocks:
268
+ if not node.get("@type"):
269
+ findings.append(_f(
270
+ "seo.schema.no-type", "schema", url, "error",
271
+ "JSON-LD node without @type", "an explicit @type",
272
+ "Add @type. A node without a type conveys nothing to a parser."))
273
+ elif not node.get("@context"):
274
+ findings.append(_f(
275
+ "seo.schema.no-context", "schema", url, "warning",
276
+ f"{node.get('@type')} node without @context",
277
+ 'an @context of "https://schema.org"',
278
+ "Add @context, or nest the node inside a block that declares it."))
279
+
280
+ findings.extend(_fabrication(blocks, url))
281
+ findings.extend(_required_properties(blocks, url))
282
+ return findings
@@ -0,0 +1,177 @@
1
+ """On-page markup gates that overlap accessibility.
2
+
3
+ Kept out of `seo.py` so neither file carries two responsibilities: `seo.py` owns
4
+ the <head>'s indexing signals (canonical, title, description, og, hreflang), and
5
+ this module owns body markup that engines and assistive technology both read.
6
+
7
+ These findings are worth shipping in an SEO tool for a reason beyond compliance:
8
+ LLM retrieval chunks on heading boundaries, so a broken outline degrades
9
+ extractability directly (SS5.4C of the gap analysis) -- a stronger argument for
10
+ heading-order integrity here than in any classic SEO tool.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ from itertools import pairwise
15
+
16
+ from bs4 import BeautifulSoup, Tag
17
+
18
+ from ..report import Finding
19
+
20
+ MAX_EXAMPLES = 3
21
+
22
+ # Explicitly decorative markers. An <img> carrying any of these is telling the
23
+ # accessibility tree to ignore it, and demanding alt text there is wrong advice.
24
+ # alt="" is handled separately and is the most important of the four: it is the
25
+ # spec's own way to mark an image decorative, so a check that flags it tells users
26
+ # to make their markup worse.
27
+ _DECORATIVE_ROLES = frozenset({"presentation", "none"})
28
+
29
+ # English-only by construction, which is exactly why seo.link-text.generic is
30
+ # `info`: on a Bengali or Japanese page this list matches nothing and the gate is
31
+ # silent, so it must never be able to fail a build. Kept deliberately short --
32
+ # every entry has to be text that conveys nothing WITHOUT its surrounding sentence.
33
+ GENERIC_ANCHORS: frozenset[str] = frozenset({
34
+ "click here", "click", "here", "read more", "more", "learn more",
35
+ "see more", "find out more", "this", "this link", "link", "continue",
36
+ "continue reading", "details", "go", "info",
37
+ })
38
+
39
+ _HEADINGS = ("h1", "h2", "h3", "h4", "h5", "h6")
40
+
41
+
42
+ def _f(id_: str, gate: str, url: str, severity: str, observed: str,
43
+ expected: str, fix: str) -> Finding:
44
+ return Finding(id=id_, severity=severity, layer="seo", url=url, gate=gate,
45
+ observed=observed, expected=expected, fix=fix)
46
+
47
+
48
+ def _attr(tag: Tag, name: str) -> str:
49
+ value = tag.get(name)
50
+ return value.strip().lower() if isinstance(value, str) else ""
51
+
52
+
53
+ def _image_alt(soup: BeautifulSoup, url: str) -> list[Finding]:
54
+ """<img> with no alt ATTRIBUTE AT ALL -- never alt="", which is correct."""
55
+ bad = [
56
+ img for img in soup.find_all("img")
57
+ if not img.has_attr("alt")
58
+ and _attr(img, "role") not in _DECORATIVE_ROLES
59
+ and _attr(img, "aria-hidden") != "true"
60
+ ]
61
+ if not bad:
62
+ return []
63
+ srcs = ", ".join(img.get("src", "?") for img in bad[:MAX_EXAMPLES])
64
+ return [_f("seo.image-alt.missing", "image-alt", url, "warning",
65
+ f"{len(bad)} <img> with no alt attribute ({srcs})",
66
+ "an alt attribute on every <img>",
67
+ 'Add alt text describing what the image conveys, or alt="" if it is '
68
+ "purely decorative. An absent alt attribute is different from an "
69
+ 'empty one: alt="" says "ignore this image" and is correct for '
70
+ "decoration, while no attribute at all leaves screen readers "
71
+ "announcing the filename and leaves engines with nothing to read.")]
72
+
73
+
74
+ def _heading_order(soup: BeautifulSoup, url: str) -> list[Finding]:
75
+ """The first place the outline jumps more than one level deeper.
76
+
77
+ Only INCREASES count. Going h3 -> h1 closes two sections and is correct; going
78
+ h1 -> h3 leaves a level with no parent. One finding per page: the outline is
79
+ fixed once, and one finding per skip would flood a long document.
80
+ """
81
+ levels = [int(tag.name[1]) for tag in soup.find_all(_HEADINGS)]
82
+ for previous, current in pairwise(levels):
83
+ if current > previous + 1:
84
+ return [_f("seo.heading-order.skipped", "heading-order", url, "warning",
85
+ f"outline jumps from h{previous} to h{current}",
86
+ "each heading at most one level deeper than the last",
87
+ f"Insert an h{previous + 1} above the h{current}, or demote "
88
+ f"the h{current} to h{previous + 1}. A skipped level leaves "
89
+ "a section with no parent, which breaks the document outline "
90
+ "assistive technology navigates by -- and answer engines "
91
+ "chunk retrieved passages on heading boundaries, so a broken "
92
+ "outline degrades what they can extract.")]
93
+ return []
94
+
95
+
96
+ def _accessible_name(tag: Tag) -> str:
97
+ """The text a user or a crawler would perceive as this link's label."""
98
+ text = tag.get_text(" ", strip=True)
99
+ if text:
100
+ return text
101
+ for attr in ("aria-label", "title"):
102
+ value = tag.get(attr)
103
+ if isinstance(value, str) and value.strip():
104
+ return value.strip()
105
+ for img in tag.find_all("img"):
106
+ alt = img.get("alt")
107
+ if isinstance(alt, str) and alt.strip():
108
+ return alt.strip()
109
+ return ""
110
+
111
+
112
+ def _link_text(soup: BeautifulSoup, url: str) -> list[Finding]:
113
+ """Links with no accessible name, and links whose name conveys nothing.
114
+
115
+ Links inside <nav> are exempt: navigation labels are terse by design and take
116
+ their meaning from the nav itself, so flagging them is the kind of noise that
117
+ trains users to ignore a report.
118
+ """
119
+ empty: list[str] = []
120
+ generic: list[str] = []
121
+ for link in soup.find_all("a", href=True):
122
+ if link.find_parent("nav") is not None:
123
+ continue
124
+ name = _accessible_name(link)
125
+ if not name:
126
+ empty.append(link["href"])
127
+ elif " ".join(name.split()).lower() in GENERIC_ANCHORS:
128
+ generic.append(f"{name!r} -> {link['href']}")
129
+
130
+ findings: list[Finding] = []
131
+ if empty:
132
+ shown = ", ".join(empty[:MAX_EXAMPLES])
133
+ findings.append(_f(
134
+ "seo.link-text.empty", "link-text", url, "warning",
135
+ f"{len(empty)} <a href> with no accessible name ({shown})",
136
+ "every link carrying text, an aria-label, or an image with alt",
137
+ "Give each link visible text, an aria-label, or an image with alt text. "
138
+ "A link with no name is announced as its URL by a screen reader and "
139
+ "passes no anchor context to whatever it points at."))
140
+ if generic:
141
+ shown = ", ".join(generic[:MAX_EXAMPLES])
142
+ findings.append(_f(
143
+ "seo.link-text.generic", "link-text", url, "info",
144
+ f"{len(generic)} link(s) whose text conveys nothing alone ({shown})",
145
+ "anchor text that describes the destination",
146
+ "Rewrite the anchor text to name the destination. Reported as info, not "
147
+ "a defect: the word list behind this check is English-only, so it is "
148
+ "silent on other languages by construction and must never fail a build. "
149
+ "Links inside <nav> are exempt."))
150
+ return findings
151
+
152
+
153
+ def _lang(soup: BeautifulSoup, url: str) -> list[Finding]:
154
+ tag = soup.find("html")
155
+ if tag is not None:
156
+ value = tag.get("lang")
157
+ if isinstance(value, str) and value.strip():
158
+ return []
159
+ return [_f("seo.lang.missing", "lang", url, "error",
160
+ "<html> has no lang attribute",
161
+ "<html lang> naming the page's language",
162
+ 'Add lang to the <html> element (for example <html lang="en">). This '
163
+ "is an error rather than a nicety because OmniRank's own AnswerBlock "
164
+ "sizing reads it: with no lang, bands.resolve_band() falls back to "
165
+ "the space-delimited Latin default, so a page written in a script "
166
+ "without word separators is measured against a word band it cannot "
167
+ "meet and aeo.answer-block.length reports a length problem that does "
168
+ "not exist. A missing lang makes another gate lie.")]
169
+
170
+
171
+ def run(html: str, url: str) -> list[Finding]:
172
+ """On-page markup gates for one already-fetched page."""
173
+ soup = BeautifulSoup(html, "lxml")
174
+ findings: list[Finding] = []
175
+ for check in (_image_alt, _heading_order, _link_text, _lang):
176
+ findings.extend(check(soup, url))
177
+ return findings
omnirank/gates/perf.py ADDED
@@ -0,0 +1,115 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+
5
+ from ..page import PageData
6
+ from ..report import Finding
7
+
8
+ RESPONSE_WARN_MS = 2000
9
+ RESPONSE_ERROR_MS = 5000
10
+ HTML_WARN_BYTES = 500_000
11
+ MAX_HEAD_SCRIPTS = 2
12
+
13
+ # gzip and deflate are the only encodings OmniRank's own client (see fetch.py) ever
14
+ # advertises in Accept-Encoding, so they are the only ones it can actually observe
15
+ # a server choosing. br/zstd are matched defensively in case a server ignores
16
+ # Accept-Encoding and sends one anyway (fetch() already handles that response
17
+ # gracefully), but OmniRank never claims to verify them — see docs/audit-guide.md.
18
+ _COMPRESSED = ("gzip", "br", "deflate", "zstd")
19
+
20
+
21
+ def _f(id_: str, gate: str, url: str, severity: str, observed: str,
22
+ expected: str, fix: str) -> Finding:
23
+ return Finding(id=id_, severity=severity, layer="perf", url=url, gate=gate,
24
+ observed=observed, expected=expected, fix=fix)
25
+
26
+
27
+ def _response_time(page: PageData) -> list[Finding]:
28
+ """Wall-clock time for OmniRank's own request, start to finish.
29
+
30
+ This is NOT time-to-first-byte: `page.elapsed_ms` brackets the entire
31
+ `client.get()` call — DNS, TCP, TLS, request, and reading the *complete* response
32
+ body — not the time until the first byte arrived. Measuring it as TTFB overstates
33
+ the real figure severalfold on anything but a tiny page, and produces false
34
+ positives that vanish on re-measurement. This is a smoke signal derived from a
35
+ full download, not a user-experienced metric and not real TTFB; the finding text
36
+ says so.
37
+ """
38
+ if page.elapsed_ms >= RESPONSE_ERROR_MS:
39
+ return [_f("perf.response-time.critical", "response-time", page.url, "error",
40
+ f"{page.elapsed_ms} ms for the full response to this audit's request",
41
+ f"under {RESPONSE_WARN_MS} ms",
42
+ "Investigate server response time: cold starts, uncached database "
43
+ "queries, or origin distance. This measures the complete download, "
44
+ "not server think-time, and is measured from where this audit ran, "
45
+ "so treat it as a signal to investigate rather than a user metric.")]
46
+ if page.elapsed_ms >= RESPONSE_WARN_MS:
47
+ return [_f("perf.response-time.slow", "response-time", page.url, "warning",
48
+ f"{page.elapsed_ms} ms for the full response to this audit's request",
49
+ f"under {RESPONSE_WARN_MS} ms",
50
+ "Consider caching or a CDN. This measures the complete download, "
51
+ "not server think-time, and is measured from where this audit ran, "
52
+ "so treat it as a signal to investigate rather than a user metric.")]
53
+ return []
54
+
55
+
56
+ def _page_weight(page: PageData) -> list[Finding]:
57
+ """Report the byte count, not a unit-confused KiB truncation.
58
+
59
+ At exactly 500,001 bytes, `size // 1024` and `HTML_WARN_BYTES // 1024` are both
60
+ 488 — the finding would read "488 KB ... expected under 488 KB", contradicting
61
+ itself about a page that is in fact over the limit. Reporting the exact byte
62
+ count alongside a correctly-labelled KiB figure (KiB, since this divides by
63
+ 1024, not 1000) avoids both the self-contradiction and the KB/KiB mislabel.
64
+ """
65
+ size = len(page.html.encode("utf-8"))
66
+ if size <= HTML_WARN_BYTES:
67
+ return []
68
+ size_kib = math.ceil(size / 1024)
69
+ return [_f("perf.page-weight.heavy", "page-weight", page.url, "warning",
70
+ f"{size} bytes ({size_kib} KiB) of HTML before any subresource",
71
+ f"under {HTML_WARN_BYTES} bytes ({HTML_WARN_BYTES // 1024} KiB)",
72
+ "Large HTML delays parsing and inflates every cache. Look for inlined "
73
+ "data, embedded base64, or a component rendering the whole dataset.")]
74
+
75
+
76
+ def _compression(page: PageData) -> list[Finding]:
77
+ encoding = page.headers.get("content-encoding", "").lower()
78
+ if any(algo in encoding for algo in _COMPRESSED):
79
+ return []
80
+ return [_f("perf.compression.missing", "compression", page.url, "warning",
81
+ "response carried no content-encoding header",
82
+ "gzip, brotli or zstd",
83
+ "Enable compression at the origin or CDN. HTML compresses well and "
84
+ "this is usually a one-line server change.")]
85
+
86
+
87
+ def _render_blocking(page: PageData) -> list[Finding]:
88
+ head = page.soup().find("head")
89
+ if not head:
90
+ return []
91
+ blocking = [s for s in head.find_all("script")
92
+ if s.get("src") and not s.has_attr("async") and not s.has_attr("defer")]
93
+ if len(blocking) <= MAX_HEAD_SCRIPTS:
94
+ return []
95
+ srcs = ", ".join(s.get("src") for s in blocking[:3])
96
+ return [_f("perf.render-blocking.head-scripts", "render-blocking", page.url,
97
+ "warning",
98
+ f"{len(blocking)} render-blocking scripts in <head> ({srcs})",
99
+ f"at most {MAX_HEAD_SCRIPTS}",
100
+ "Add async or defer, or move these below the fold. Each blocks HTML "
101
+ "parsing until it has downloaded and executed.")]
102
+
103
+
104
+ def run(page: PageData) -> list[Finding]:
105
+ """Performance signals derivable from one HTTP response.
106
+
107
+ Deliberately excludes anything requiring a browser — no LCP, CLS, INP or
108
+ Lighthouse score. OmniRank does not measure those and must not imply it does.
109
+ """
110
+ return [
111
+ *_response_time(page),
112
+ *_page_weight(page),
113
+ *_compression(page),
114
+ *_render_blocking(page),
115
+ ]