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,504 @@
1
+ """JSON-LD validator: ``invalid`` (structure/vocabulary) vs ``not_eligible``.
2
+
3
+ A document is *valid* when it has no ``invalid`` issues. ``not_eligible`` issues list
4
+ properties that Google's rich-result documentation requires or recommends for the type
5
+ and that are missing; valid markup that lacks them is "valid but not eligible". The
6
+ tables below were transcribed by hand on ELIGIBILITY_CHECKED_ON and are NOT
7
+ re-verified at runtime. Eligible markup is never a promise of a rich result.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from dataclasses import dataclass, field
13
+
14
+ from bs4 import BeautifulSoup
15
+
16
+ from ..html import find_ldjson_scripts
17
+ from .vocab import (
18
+ KNOWN_TYPES,
19
+ PARENTS,
20
+ SCHEMA_CONTEXTS,
21
+ ancestors,
22
+ is_http_url,
23
+ is_iso_date,
24
+ is_subtype,
25
+ props_for,
26
+ rating_problem,
27
+ )
28
+
29
+ ELIGIBILITY_CHECKED_ON = "2026-11-29"
30
+
31
+ # Transcribed from Google Search Central structured-data pages on ELIGIBILITY_CHECKED_ON.
32
+ # A leading "a|b" means either property satisfies the entry. Dotted paths follow nodes.
33
+ ELIGIBILITY: dict[str, dict] = {
34
+ "Article": { # https://developers.google.com/search/docs/appearance/structured-data/article
35
+ "required": [],
36
+ "recommended": ["headline", "image", "datePublished", "dateModified", "author",
37
+ "author.name", "author.url|author.sameAs"],
38
+ },
39
+ "Organization": { # .../structured-data/organization (subset of the recommended list)
40
+ "required": [],
41
+ "recommended": ["name", "url", "logo", "sameAs", "address", "contactPoint"],
42
+ },
43
+ "WebSite": { # https://developers.google.com/search/docs/appearance/site-names
44
+ "required": ["name", "url"],
45
+ "recommended": ["alternateName"],
46
+ },
47
+ "ProfilePage": { # .../structured-data/profile-page
48
+ "required": ["mainEntity", "mainEntity.name"],
49
+ "recommended": ["dateCreated", "dateModified"],
50
+ },
51
+ }
52
+
53
+ _SD = "https://developers.google.com/search/docs/appearance/structured-data/"
54
+ # Catalog types, transcribed from the same pages on the same date (see ELIGIBILITY_SOURCES).
55
+ # Book (partner-only, Work/Edition split) and Quiz/Service/Podcast/media types without a
56
+ # Google page are deliberately NOT tabulated.
57
+ ELIGIBILITY.update({
58
+ "Product": { # .../structured-data/product-snippet
59
+ "required": ["name", "review|aggregateRating|offers"],
60
+ "recommended": ["aggregateRating", "offers", "review"],
61
+ },
62
+ "SoftwareApplication": { # .../structured-data/software-app
63
+ "required": ["name", "offers.price", "aggregateRating|review"],
64
+ "recommended": ["applicationCategory", "operatingSystem"],
65
+ },
66
+ "LocalBusiness": { # .../structured-data/local-business
67
+ "required": ["name", "address"],
68
+ "recommended": ["geo", "geo.latitude", "geo.longitude", "openingHoursSpecification",
69
+ "openingHoursSpecification.dayOfWeek",
70
+ "openingHoursSpecification.opens", "openingHoursSpecification.closes",
71
+ "priceRange", "telephone", "url"],
72
+ },
73
+ "Event": { # .../structured-data/event
74
+ "required": ["name", "startDate", "location", "location.address|location.name"],
75
+ "recommended": ["description", "endDate", "eventStatus", "image", "offers",
76
+ "offers.availability", "offers.price", "offers.priceCurrency",
77
+ "offers.url", "organizer", "organizer.name", "performer",
78
+ "performer.name", "previousStartDate"],
79
+ },
80
+ "VideoObject": { # .../structured-data/video
81
+ "required": ["name", "thumbnailUrl", "uploadDate"],
82
+ "recommended": ["contentUrl|embedUrl", "description", "duration",
83
+ "creator|author", "expires"],
84
+ },
85
+ "JobPosting": { # .../structured-data/job-posting
86
+ "required": ["datePosted", "description", "hiringOrganization", "jobLocation",
87
+ "title"],
88
+ "recommended": ["baseSalary", "employmentType", "identifier", "jobLocationType",
89
+ "validThrough"],
90
+ },
91
+ "Recipe": { # .../structured-data/recipe
92
+ "required": ["image", "name"],
93
+ "recommended": ["aggregateRating", "author", "cookTime", "datePublished",
94
+ "description", "keywords", "nutrition.calories", "prepTime",
95
+ "recipeCategory", "recipeCuisine", "recipeIngredient",
96
+ "recipeInstructions", "recipeYield", "totalTime", "video"],
97
+ },
98
+ "Movie": { # .../structured-data/movie (carousel)
99
+ "required": ["image", "name"],
100
+ "recommended": ["aggregateRating", "dateCreated", "director", "review"],
101
+ },
102
+ "Dataset": { # .../structured-data/dataset
103
+ "required": ["description", "name"],
104
+ "recommended": ["alternateName", "citation", "creator", "funder",
105
+ "hasPart|isPartOf", "identifier", "isAccessibleForFree", "keywords",
106
+ "license", "measurementTechnique", "sameAs", "spatialCoverage",
107
+ "temporalCoverage", "variableMeasured", "version", "url",
108
+ "includedInDataCatalog", "distribution", "distribution.contentUrl",
109
+ "distribution.encodingFormat"],
110
+ },
111
+ "QAPage": { # .../structured-data/qapage
112
+ "required": ["mainEntity", "mainEntity.name", "mainEntity.answerCount",
113
+ "mainEntity.acceptedAnswer|mainEntity.suggestedAnswer",
114
+ "mainEntity.acceptedAnswer.text|mainEntity.suggestedAnswer.text"],
115
+ "recommended": ["mainEntity.author", "mainEntity.datePublished",
116
+ "mainEntity.text", "mainEntity.upvoteCount"],
117
+ },
118
+ "DiscussionForumPosting": { # .../structured-data/discussion-forum
119
+ "required": ["author", "author.name", "datePublished", "text|image|video"],
120
+ "recommended": ["author.url", "comment", "commentCount", "creativeWorkStatus",
121
+ "dateModified", "headline", "image", "interactionStatistic",
122
+ "isPartOf", "sharedContent", "url", "video"],
123
+ },
124
+ "Review": { # .../structured-data/review-snippet (a standalone Review)
125
+ "required": ["author", "itemReviewed", "itemReviewed.name", "reviewRating",
126
+ "reviewRating.ratingValue"],
127
+ "recommended": ["datePublished", "reviewRating.bestRating",
128
+ "reviewRating.worstRating"],
129
+ },
130
+ })
131
+ # Nodes checked where they are nested (Product > Offer ...). Keyed by the nested type; the
132
+ # optional "parents" limits which parent types the rule applies to.
133
+ ELIGIBILITY_NESTED: dict[str, dict] = {
134
+ "Offer": { # .../structured-data/product-snippet (Offer)
135
+ "parents": ("Product",),
136
+ "required": ["price|priceSpecification.price"],
137
+ "recommended": ["availability", "priceCurrency|priceSpecification.priceCurrency",
138
+ "priceValidUntil"],
139
+ },
140
+ "AggregateRating": { # .../structured-data/review-snippet
141
+ "required": ["ratingValue", "ratingCount|reviewCount"],
142
+ "recommended": ["bestRating", "worstRating"],
143
+ },
144
+ "Review": { # .../structured-data/review-snippet (nested: itemReviewed is the parent)
145
+ "required": ["author", "reviewRating", "reviewRating.ratingValue"],
146
+ "recommended": ["datePublished", "reviewRating.bestRating",
147
+ "reviewRating.worstRating"],
148
+ },
149
+ }
150
+ # Google's June 2025 post lists these among the structured data features it phased out
151
+ # (Course info, Book actions, ...); its September 2025 update says the Course info page was
152
+ # removed. Verified on ELIGIBILITY_CHECKED_ON; no requirements are embedded for them.
153
+ RETIRED_SOURCE = "https://developers.google.com/search/blog/2025/06/simplifying-search-results"
154
+ ELIGIBILITY_RETIRED: dict[str, str] = {"Course": RETIRED_SOURCE, "Book": RETIRED_SOURCE}
155
+ RICH_RESULTS_ENDED = (
156
+ "FAQPage and HowTo: Google ended FAQ rich results on 7 May 2026 and HowTo rich results "
157
+ "are gone. This markup describes content structure only and is no rich-result promise. "
158
+ "Sources, checked on 2026-11-29: https://developers.google.com/search/docs/appearance/structured-data/faqpage (FAQ), https://developers.google.com/search/blog/2023/08/howto-faq-changes (HowTo).")
159
+ ELIGIBILITY_SOURCES = {
160
+ "Product": _SD + "product-snippet", "SoftwareApplication": _SD + "software-app",
161
+ "LocalBusiness": _SD + "local-business", "Event": _SD + "event",
162
+ "VideoObject": _SD + "video", "JobPosting": _SD + "job-posting",
163
+ "Recipe": _SD + "recipe", "Movie": _SD + "movie",
164
+ "Dataset": _SD + "dataset", "QAPage": _SD + "qapage",
165
+ "DiscussionForumPosting": _SD + "discussion-forum", "Review": _SD + "review-snippet",
166
+ "FAQPage": _SD + "faqpage (feature removed)",
167
+ "Article": "https://developers.google.com/search/docs/appearance/structured-data/article",
168
+ "Organization": "https://developers.google.com/search/docs/appearance/structured-data/organization",
169
+ "WebSite": "https://developers.google.com/search/docs/appearance/site-names",
170
+ "ProfilePage": "https://developers.google.com/search/docs/appearance/structured-data/profile-page",
171
+ "BreadcrumbList": "https://developers.google.com/search/docs/appearance/structured-data/breadcrumb",
172
+ }
173
+
174
+
175
+ @dataclass(frozen=True)
176
+ class Issue:
177
+ code: str
178
+ path: str
179
+ message: str
180
+ property: str | None = None
181
+ level: str | None = None # "required" | "recommended" for not_eligible
182
+
183
+ def to_dict(self) -> dict:
184
+ return {k: v for k, v in self.__dict__.items() if v is not None}
185
+
186
+
187
+ @dataclass
188
+ class ValidationReport:
189
+ invalid: list[Issue] = field(default_factory=list)
190
+ not_eligible: list[Issue] = field(default_factory=list)
191
+ unrecognised: list[Issue] = field(default_factory=list)
192
+ notes: list[str] = field(default_factory=list)
193
+ checked_on: str = ELIGIBILITY_CHECKED_ON
194
+
195
+ @property
196
+ def is_valid(self) -> bool:
197
+ return not self.invalid
198
+
199
+ def to_dict(self) -> dict:
200
+ return {"valid": self.is_valid, "invalid": [i.to_dict() for i in self.invalid],
201
+ "notEligible": [i.to_dict() for i in self.not_eligible],
202
+ "unrecognised": [i.to_dict() for i in self.unrecognised],
203
+ "notes": self.notes, "eligibilityCheckedOn": self.checked_on}
204
+
205
+
206
+ # --- extraction ----------------------------------------------------------------------
207
+
208
+
209
+ @dataclass
210
+ class Extracted:
211
+ blocks: list = field(default_factory=list)
212
+ errors: list[str] = field(default_factory=list)
213
+
214
+
215
+ def extract_jsonld(html: str) -> Extracted:
216
+ out = Extracted()
217
+ scripts = find_ldjson_scripts(BeautifulSoup(html, "lxml"))
218
+ for n, tag in enumerate(scripts, start=1):
219
+ try:
220
+ out.blocks.append(json.loads(tag.string or tag.get_text() or ""))
221
+ except (json.JSONDecodeError, RecursionError) as exc:
222
+ out.errors.append(f"script {n} is not valid JSON: {exc}")
223
+ return out
224
+
225
+
226
+ # --- structural validation ---------------------------------------------------------------
227
+
228
+
229
+ def _types(node: dict) -> list[str]:
230
+ t = node.get("@type")
231
+ return [t] if isinstance(t, str) else [x for x in t if isinstance(x, str)] \
232
+ if isinstance(t, list) else []
233
+
234
+
235
+ KNOWN_BY_LOWER = {t.lower(): t for t in KNOWN_TYPES}
236
+
237
+
238
+ class _Checker:
239
+ def __init__(self):
240
+ self.report = ValidationReport()
241
+ self.unchecked: set[str] = set()
242
+
243
+ def bad(self, code, path, message, prop=None):
244
+ self.report.invalid.append(Issue(code, path, message, prop))
245
+
246
+ def context(self, ctx, path):
247
+ values = ctx if isinstance(ctx, list) else [ctx]
248
+ if ctx is None:
249
+ self.bad("context.missing", path, "@context is missing; use https://schema.org")
250
+ elif not any((isinstance(v, str) and v in SCHEMA_CONTEXTS)
251
+ or (isinstance(v, dict) and v.get("@vocab") in SCHEMA_CONTEXTS)
252
+ for v in values):
253
+ self.bad("context.bad", path, f"@context {ctx!r} is not schema.org")
254
+
255
+ def node(self, node, path, depth=0):
256
+ if depth > 50:
257
+ return
258
+ types = _types(node)
259
+ if not types:
260
+ if set(node) != {"@id"}:
261
+ self.bad("type.missing", path, "node has no @type")
262
+ return
263
+ for t in types:
264
+ if t not in KNOWN_TYPES:
265
+ fixed = KNOWN_BY_LOWER.get(t.lower())
266
+ if fixed:
267
+ self.bad("type.case", path, f"unknown type {t!r}; did you mean {fixed!r}?")
268
+ else:
269
+ self.report.unrecognised.append(Issue(
270
+ "type.unrecognised", path,
271
+ f"type {t!r} is not in OmniRank's bundled subset of schema.org, so it "
272
+ "was not checked (not treated as an error; verify at https://schema.org)"))
273
+ modelled = next((t for t in types if t in PARENTS or t == "Thing"), None)
274
+ if modelled is None:
275
+ return
276
+ if is_subtype(modelled, "Rating") and (why := rating_problem(node)):
277
+ self.bad("value.range", f"{path}.ratingValue", why, "ratingValue")
278
+ table = props_for(modelled)
279
+ by_lower = {k.lower(): k for k in table}
280
+ for prop, value in node.items():
281
+ if prop.startswith("@"):
282
+ continue
283
+ where = f"{path}.{prop}"
284
+ if prop not in table:
285
+ if by_lower.get(prop.lower()):
286
+ self.bad("property.case", where,
287
+ f"unknown property {prop!r}; did you mean "
288
+ f"{by_lower[prop.lower()]!r}?", prop)
289
+ else:
290
+ self.unchecked.add(prop)
291
+ continue
292
+ items = value if isinstance(value, list) else [value]
293
+ for k, item in enumerate(items):
294
+ self.value(item, table[prop], f"{where}[{k}]" if isinstance(value, list)
295
+ else where, prop, depth)
296
+
297
+ def value(self, item, kinds, path, prop, depth):
298
+ if isinstance(item, dict):
299
+ wanted = [k[5:] for k in kinds if k.startswith("node:")]
300
+ if not wanted:
301
+ self.bad("value.type", path, f"{prop} must not be an object", prop)
302
+ return
303
+ if set(item) == {"@id"}:
304
+ if not isinstance(item["@id"], str) or not item["@id"].strip():
305
+ self.bad("value.type", path, "@id reference must be a non-empty string", prop)
306
+ return
307
+ item_types = _types(item)
308
+ modelled = [t for t in item_types if t in PARENTS]
309
+ if modelled and not any(is_subtype(t, w) for t in modelled for w in wanted):
310
+ self.bad("value.type", path, f"{prop} expects {' or '.join(wanted)}, got "
311
+ f"{', '.join(item_types)}", prop)
312
+ self.node(item, path, depth + 1)
313
+ return
314
+ if isinstance(item, bool) or item is None or isinstance(item, list):
315
+ self.bad("value.type", path, f"{prop} has an unusable value {item!r}", prop)
316
+ elif isinstance(item, (int, float)):
317
+ if "int" in kinds and isinstance(item, int) or "number" in kinds:
318
+ return
319
+ self.bad("value.type", path, f"{prop} expects {self.expect(kinds)}, got a number",
320
+ prop)
321
+ elif isinstance(item, str):
322
+ self.string(item, kinds, path, prop)
323
+
324
+ @staticmethod
325
+ def expect(kinds):
326
+ return " or ".join(k.removeprefix("node:") for k in kinds)
327
+
328
+ def string(self, item, kinds, path, prop):
329
+ if "date" in kinds and "text" not in kinds:
330
+ if not is_iso_date(item):
331
+ self.bad("value.date", path, f"{prop} {item!r} is not an ISO 8601 date", prop)
332
+ elif "url" in kinds and "text" not in kinds:
333
+ if is_http_url(item):
334
+ return
335
+ if "node:" in "".join(kinds) and item.startswith("#"):
336
+ return
337
+ self.bad("value.url", path, f"{prop} {item!r} is not an absolute http(s) URL", prop)
338
+ elif "text" in kinds:
339
+ if not item.strip():
340
+ self.bad("value.type", path, f"{prop} is empty", prop)
341
+ elif "int" in kinds or "number" in kinds:
342
+ self.bad("value.type", path, f"{prop} expects a number, got text", prop)
343
+ else:
344
+ self.bad("value.type", path, f"{prop} expects {self.expect(kinds)}, got text", prop)
345
+
346
+
347
+ # --- eligibility -----------------------------------------------------------------------------
348
+
349
+
350
+ def _resolve(value, by_id):
351
+ if isinstance(value, dict) and set(value) == {"@id"}:
352
+ return by_id.get(value["@id"])
353
+ return value
354
+
355
+
356
+ def _lookup(node: dict, dotted: str, by_id: dict):
357
+ current = [node]
358
+ for part in dotted.split("."):
359
+ nxt = []
360
+ for n in current:
361
+ n = _resolve(n, by_id)
362
+ if not isinstance(n, dict):
363
+ continue
364
+ v = n.get(part)
365
+ for item in (v if isinstance(v, list) else [v]):
366
+ resolved = _resolve(item, by_id)
367
+ if resolved not in (None, "", [], {}):
368
+ nxt.append(resolved)
369
+ current = nxt
370
+ return current
371
+
372
+
373
+ def _eligibility(checker: _Checker, nodes: list[tuple[dict, str]], by_id: dict):
374
+ report = checker.report
375
+ for node, path in nodes:
376
+ for t in _types(node):
377
+ chain = ancestors(t)
378
+ key = next((c for c in chain if c in ELIGIBILITY or c == "BreadcrumbList"), None)
379
+ if t in ("FAQPage", "HowTo") and RICH_RESULTS_ENDED not in report.notes:
380
+ report.notes.append(RICH_RESULTS_ENDED)
381
+ _nested(report, node, path, t, by_id)
382
+ if t in ELIGIBILITY_RETIRED:
383
+ note = (f"{t}: Google retired this rich result (see {ELIGIBILITY_RETIRED[t]}, "
384
+ f"checked on {ELIGIBILITY_CHECKED_ON}); the markup is still valid "
385
+ "schema.org and nothing was checked for eligibility")
386
+ if note not in report.notes:
387
+ report.notes.append(note)
388
+ continue
389
+ if key is None:
390
+ if t in PARENTS or t in KNOWN_TYPES:
391
+ note = (f"no Google rich-result requirements are embedded for {t}; "
392
+ "nothing was checked for eligibility")
393
+ if note not in report.notes:
394
+ report.notes.append(note)
395
+ continue
396
+ if key == "BreadcrumbList":
397
+ _breadcrumb(report, node, path, by_id)
398
+ continue
399
+ for level in ("required", "recommended"):
400
+ for entry in ELIGIBILITY[key][level]:
401
+ if not any(_lookup(node, alt, by_id) for alt in entry.split("|")):
402
+ report.not_eligible.append(Issue(
403
+ "eligibility.missing", path,
404
+ f"{t} is missing {entry!r} ({level} by Google's {key} "
405
+ f"documentation)", entry, level))
406
+
407
+
408
+ def _nested(report, node, path, parent_type, by_id, depth=0):
409
+ """Check Offer/AggregateRating/Review nodes where they sit inside another node."""
410
+ if depth > 10:
411
+ return
412
+ for prop, value in node.items():
413
+ if prop.startswith("@"):
414
+ continue
415
+ for k, item in enumerate(value if isinstance(value, list) else [value]):
416
+ if not isinstance(item, dict) or set(item) == {"@id"}:
417
+ continue
418
+ here = f"{path}.{prop}[{k}]" if isinstance(value, list) else f"{path}.{prop}"
419
+ for t in _types(item):
420
+ rule = ELIGIBILITY_NESTED.get(t)
421
+ if rule and (not rule.get("parents")
422
+ or any(p in ancestors(parent_type) for p in rule["parents"])):
423
+ for level in ("required", "recommended"):
424
+ for entry in rule[level]:
425
+ if not any(_lookup(item, alt, by_id) for alt in entry.split("|")):
426
+ report.not_eligible.append(Issue(
427
+ "eligibility.missing", here,
428
+ f"{t} is missing {entry!r} ({level} by Google's "
429
+ f"documentation for {t} inside {parent_type})",
430
+ entry, level))
431
+ nested_type = next(iter(_types(item)), parent_type)
432
+ _nested(report, item, here, nested_type, by_id, depth + 1)
433
+
434
+
435
+ def _breadcrumb(report, node, path, by_id):
436
+ items = _lookup(node, "itemListElement", by_id)
437
+ if len(items) < 2:
438
+ report.not_eligible.append(Issue(
439
+ "eligibility.missing", path, "BreadcrumbList needs at least two ListItem "
440
+ "entries (required by Google's breadcrumb documentation)", "itemListElement",
441
+ "required"))
442
+ for k, item in enumerate(items):
443
+ if not isinstance(item, dict):
444
+ continue
445
+ last = k == len(items) - 1
446
+ for prop in ("position", "name") + (() if last else ("item",)):
447
+ if prop == "name" and _lookup(item, "item.name", by_id):
448
+ continue
449
+ if not _lookup(item, prop, by_id):
450
+ report.not_eligible.append(Issue(
451
+ "eligibility.missing", f"{path}.itemListElement[{k}]",
452
+ f"ListItem is missing {prop!r} (required by Google's breadcrumb "
453
+ "documentation)", prop, "required"))
454
+
455
+
456
+ # --- entry point ---------------------------------------------------------------------------------
457
+
458
+
459
+ def validate(jsonld: dict | list) -> ValidationReport:
460
+ checker = _Checker()
461
+ docs = jsonld if isinstance(jsonld, list) else [jsonld]
462
+ nodes: list[tuple[dict, str]] = []
463
+ by_id: dict = {}
464
+ for n, doc in enumerate(docs):
465
+ base = f"$[{n}]" if isinstance(jsonld, list) else "$"
466
+ if not isinstance(doc, dict):
467
+ checker.bad("structure.root", base, "JSON-LD must be an object")
468
+ continue
469
+ checker.context(doc.get("@context"), f"{base}.@context")
470
+ if "@graph" in doc:
471
+ graph = doc["@graph"]
472
+ if not isinstance(graph, list):
473
+ checker.bad("graph.type", f"{base}.@graph", "@graph must be an array")
474
+ continue
475
+ if not graph:
476
+ checker.bad("graph.empty", f"{base}.@graph", "@graph has no nodes")
477
+ members = [(g, f"{base}.@graph[{k}]") for k, g in enumerate(graph)]
478
+ else:
479
+ members = [(doc, base)]
480
+ for member, path in members:
481
+ if not isinstance(member, dict):
482
+ checker.bad("structure.node", path, "graph entries must be objects")
483
+ continue
484
+ checker.node(member, path)
485
+ nodes.append((member, path))
486
+ seen: set[str] = set()
487
+ for node, path in nodes:
488
+ ident = node.get("@id")
489
+ if isinstance(ident, str) and ident:
490
+ if ident in seen:
491
+ checker.bad("id.duplicate", path, f"duplicate @id {ident!r} in the document")
492
+ seen.add(ident)
493
+ by_id.setdefault(ident, node)
494
+ if checker.report.is_valid or nodes:
495
+ _eligibility(checker, nodes, by_id)
496
+ report = checker.report
497
+ if checker.unchecked:
498
+ report.notes.append("properties outside OmniRank's bundled vocabulary subset were not "
499
+ "checked: " + ", ".join(sorted(checker.unchecked)))
500
+ report.notes.append(
501
+ f"Eligibility tables were transcribed on {ELIGIBILITY_CHECKED_ON} from Google's "
502
+ "documentation and were not re-verified at runtime; meeting them does not promise a "
503
+ "rich result.")
504
+ return report