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,489 @@
1
+ """CLI handlers for `omnirank connect ga4|bing|indexnow` (same conventions as `connect gsc`).
2
+
3
+ Exit codes: 0 done; 1 work left undone (a declined write, tag findings, stats truncated);
4
+ 2 usage, refusal, authentication or API failure. Messages go through ``redact()``; data
5
+ output is scrubbed of registered credential values.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ from pathlib import Path
12
+
13
+ from .. import __version__
14
+ from . import bing, ga4, google_auth, indexnow
15
+ from .confirm import ActionLog, confirm_and_run
16
+ from .constants import (
17
+ BING_MAX_URLS_PER_BATCH,
18
+ GA4_API_HOSTS,
19
+ INDEXNOW_MAX_URLS_PER_REQUEST,
20
+ SCOPE_GA4_READONLY,
21
+ SCOPE_GSC_READONLY,
22
+ )
23
+ from .http import ApiClient
24
+ from .secrets import scrub_registered
25
+
26
+ ENV_INDEXNOW_KEY = "OMNIRANK_INDEXNOW_KEY"
27
+ MAX_URLS_FILE = 10_000_000
28
+
29
+
30
+ class UsageError(Exception):
31
+ pass
32
+
33
+
34
+ def _emit(data: object) -> None:
35
+ print(scrub_registered(json.dumps(data, indent=2, ensure_ascii=False)))
36
+
37
+
38
+ def _line(text: str) -> None:
39
+ print(scrub_registered(text))
40
+
41
+
42
+ def read_urls(urls: list[str] | None, urls_file: str | None, *, required: bool = True
43
+ ) -> list[str]:
44
+ out = list(urls or [])
45
+ if urls_file:
46
+ p = Path(urls_file)
47
+ try:
48
+ if p.stat().st_size > MAX_URLS_FILE:
49
+ raise UsageError(f"{urls_file} is larger than {MAX_URLS_FILE} bytes")
50
+ out += [line.strip() for line in p.read_text(encoding="utf-8").splitlines()]
51
+ except OSError as exc:
52
+ raise UsageError(f"cannot read {urls_file}: {exc.strerror or exc}") from None
53
+ except UnicodeDecodeError:
54
+ raise UsageError(f"{urls_file} is not UTF-8 text") from None
55
+ out = [u for u in out if u and not u.startswith("#")]
56
+ if required and not out:
57
+ raise UsageError("give at least one URL (--url or --urls-file)")
58
+ return out
59
+
60
+
61
+ # --- ga4 ----------------------------------------------------------------------------------------
62
+
63
+ def _ga4_client(root: Path) -> ga4.Ga4Client:
64
+ source = google_auth.resolve_token_source([SCOPE_GA4_READONLY], project_root=root)
65
+ return ga4.Ga4Client(ApiClient(source.token, allowed_hosts=GA4_API_HOSTS))
66
+
67
+
68
+ def _ga4_login(args, root: Path) -> int:
69
+ opener = None
70
+ if args.open_browser:
71
+ import webbrowser
72
+ opener = webbrowser.open
73
+ google_auth.loopback_login(args.client_file, [SCOPE_GSC_READONLY, SCOPE_GA4_READONLY],
74
+ project_root=root, open_browser=opener)
75
+ return 0
76
+
77
+
78
+ def _ga4_tags(args, root: Path) -> int:
79
+ try:
80
+ if args.file:
81
+ findings, scanned = [], 0
82
+ for f in args.file:
83
+ p = Path(f)
84
+ if p.is_symlink():
85
+ raise UsageError(f"{f} is a symlink; not followed")
86
+ if p.stat().st_size > ga4.MAX_HTML_BYTES:
87
+ raise UsageError(f"{f} is larger than {ga4.MAX_HTML_BYTES} bytes")
88
+ html = p.read_text(encoding="utf-8", errors="replace")
89
+ findings += ga4.analyze_tags(html, path=f, expect_id=args.expect_id)["findings"]
90
+ scanned += 1
91
+ res = {"files_scanned": scanned, "findings": findings, "skipped": []}
92
+ else:
93
+ res = ga4.scan_tags(root, expect_id=args.expect_id)
94
+ except ValueError as exc:
95
+ raise UsageError(str(exc)) from None
96
+ except OSError as exc:
97
+ raise UsageError(f"cannot read: {exc.strerror or exc}") from None
98
+ problems = [f for f in res["findings"] if f["severity"] in ("error", "warning")]
99
+ if args.json:
100
+ _emit({**res, "note": ga4.TAGS_NOTE})
101
+ else:
102
+ print(f"OmniRank {__version__} — GA4 tag check (offline HTML analysis; "
103
+ f"{res['files_scanned']} file(s))")
104
+ for f in res["findings"]:
105
+ _line(f" {f['severity'].upper():7} {f['id']} {f['evidence']} {f['path'] or ''}")
106
+ _line(f" {f['message']}")
107
+ for s in res["skipped"]:
108
+ _line(f" skipped {s['path']}: {s['reason']}")
109
+ print(f"\n {len(problems)} problem(s). {ga4.TAGS_NOTE}")
110
+ return 1 if problems else 0
111
+
112
+
113
+ def _ga4_report(args, root: Path) -> int:
114
+ if args.top < 0:
115
+ raise UsageError("--top must be 0 or more")
116
+ referrers = ga4.load_ai_referrers() if args.preset == "ai-referrals" else None
117
+ dims, metrics, flt = ga4.preset(args.preset, referrers)
118
+ ga4.validate_property_id(args.property)
119
+ client = _ga4_client(root)
120
+ res = client.run_report(args.property, args.start, args.end, dims, metrics,
121
+ dimension_filter=flt, max_rows=args.max_rows)
122
+ data = {"property": ga4.validate_property_id(args.property), "report": args.preset,
123
+ "startDate": args.start, "endDate": args.end, "dimensions": dims,
124
+ "metrics": metrics, "rows": res.rows, "rowCount": res.row_count,
125
+ "skippedRows": res.skipped, "truncated": res.truncated, "requests": res.requests,
126
+ "thresholded": res.thresholded}
127
+ if referrers is not None:
128
+ data["ai_referrals"] = ga4.ai_referral_summary(res.rows, referrers)
129
+ if args.json:
130
+ _emit(data)
131
+ return 1 if res.truncated else 0
132
+ print(f"OmniRank {__version__} — GA4 {args.preset} {data['property']} "
133
+ f"{args.start}..{args.end} (read-only Data API runReport)")
134
+ print(f" {len(res.rows)} row(s) in {res.requests} request(s)"
135
+ + (f"; {res.skipped} malformed row(s) skipped" if res.skipped else "")
136
+ + ("; TRUNCATED at --max-rows" if res.truncated else ""))
137
+ if res.thresholded:
138
+ print(" Google applied thresholding to this report: small numbers may be hidden.")
139
+ for row in res.rows[:args.top]:
140
+ key = " | ".join(row["dimensions"].values())
141
+ mets = " ".join(f"{k} {v:g}" for k, v in row["metrics"].items())
142
+ _line(f" {key} {mets}")
143
+ if len(res.rows) > args.top:
144
+ print(f" …and {len(res.rows) - args.top} more (use --json for every row)")
145
+ if referrers is not None:
146
+ s = data["ai_referrals"]
147
+ print(f"\n AI ASSISTANT REFERRALS: at least {s['total_sessions_at_least']:g} session(s)")
148
+ for a in s["by_assistant"]:
149
+ print(f" {a['name']}: at least {a['sessions']:g} session(s)")
150
+ print(f" {s['caveat']}")
151
+ return 1 if res.truncated else 0
152
+
153
+
154
+ def _ga4_streams(args, root: Path) -> int:
155
+ ga4.validate_property_id(args.property)
156
+ streams = _ga4_client(root).list_data_streams(args.property)
157
+ if args.json:
158
+ _emit({"property": ga4.validate_property_id(args.property), "dataStreams": streams})
159
+ return 0
160
+ if not streams:
161
+ print("No data streams on this property.")
162
+ for s in streams:
163
+ _line(f" {s['type'] or '?'} {s['displayName'] or ''} {s['measurementId'] or '-'} "
164
+ f"{s['defaultUri'] or ''}")
165
+ return 0
166
+
167
+
168
+ def _ga4_key_events(args, root: Path) -> int:
169
+ ga4.validate_property_id(args.property)
170
+ events = _ga4_client(root).list_key_events(args.property)
171
+ if args.json:
172
+ _emit({"property": ga4.validate_property_id(args.property), "keyEvents": events})
173
+ return 0
174
+ if not events:
175
+ print("No key events are configured on this property.")
176
+ for e in events:
177
+ _line(f" {e['eventName'] or '?'} ({e['countingMethod'] or 'counting method ?'})")
178
+ return 0
179
+
180
+
181
+ def _ga4_sc_link(args, root: Path) -> int:
182
+ print(ga4.search_console_link_guidance(args.property))
183
+ return 0
184
+
185
+
186
+ def _ga4_ai_referrals(args, root: Path) -> int:
187
+ from .runner_ga4_ai import run
188
+ return run(args, root, _ga4_client, _emit)
189
+
190
+
191
+ GA4 = {"login": _ga4_login, "tags": _ga4_tags, "report": _ga4_report,
192
+ "streams": _ga4_streams, "key-events": _ga4_key_events,
193
+ "search-console-link": _ga4_sc_link, "ai-referrals": _ga4_ai_referrals}
194
+
195
+
196
+ # --- bing ---------------------------------------------------------------------------------------
197
+
198
+ def _bing_client() -> bing.BingClient:
199
+ return bing.make_client(bing.api_key_from_env())
200
+
201
+
202
+ def _bing_read(args, root: Path) -> int:
203
+ cmd = args.bing_command
204
+ if getattr(args, "top", 0) < 0:
205
+ raise UsageError("--top must be 0 or more")
206
+ if cmd == "sites":
207
+ data = _bing_client().sites()
208
+ if args.json:
209
+ _emit({"sites": data})
210
+ else:
211
+ if not data:
212
+ print("No sites are visible to this API key.")
213
+ for s in data:
214
+ _line(f" {s['url']} verified: {s['verified']}")
215
+ return 0
216
+ bing.validate_site(args.site)
217
+ client = _bing_client()
218
+ if cmd == "quota":
219
+ data = client.url_quota(args.site)
220
+ if args.json:
221
+ _emit({"site": args.site, **data})
222
+ else:
223
+ print(f" URL submission quota for {args.site}: {data['daily']} today, "
224
+ f"{data['monthly']} this month")
225
+ return 0
226
+ if cmd == "backlinks":
227
+ data = client.link_counts(args.site, max_pages=args.max_pages)
228
+ if args.json:
229
+ _emit({"site": args.site, **data})
230
+ else:
231
+ print(f"OmniRank {__version__} — Bing inbound links for {args.site} "
232
+ f"(pages with links; {len(data['links'])} row(s))")
233
+ for link in data["links"][:args.top]:
234
+ _line(f" {link['url']} {link['count']}")
235
+ if data["truncated"]:
236
+ print(f" TRUNCATED at --max-pages {args.max_pages} of {data['total_pages']}")
237
+ return 1 if data["truncated"] else 0
238
+ method = {"crawl-stats": client.crawl_stats, "query-stats": client.query_stats,
239
+ "page-stats": client.page_stats, "crawl-issues": client.crawl_issues}[cmd]
240
+ rows = method(args.site)
241
+ if args.json:
242
+ _emit({"site": args.site, cmd.replace("-", "_"): rows})
243
+ return 0
244
+ print(f"OmniRank {__version__} — Bing {cmd} for {args.site} ({len(rows)} row(s))")
245
+ for row in rows[:args.top]:
246
+ _line(" " + " ".join(f"{k} {v}" for k, v in row.items() if v is not None))
247
+ if len(rows) > args.top:
248
+ print(f" …and {len(rows) - args.top} more (use --json)")
249
+ return 0
250
+
251
+
252
+ def _bing_submit_sitemap(args, root: Path) -> int:
253
+ action = bing.submit_feed_action(args.site, args.sitemap)
254
+ client = _bing_client() if args.send else None
255
+ return confirm_and_run(action, send=args.send, yes=args.yes, log=ActionLog(root),
256
+ execute=lambda: client.execute(action))
257
+
258
+
259
+ def _bing_submit_urls(args, root: Path) -> int:
260
+ urls = read_urls(args.url, args.urls_file)
261
+ action = bing.submit_urls_action(args.site, urls)
262
+ client = None
263
+ if args.send:
264
+ client = _bing_client()
265
+ quota = client.check_quota(args.site, len(action.body["urlList"]))
266
+ print(f"Bing URL submission quota for {args.site}: {quota['daily']} today, "
267
+ f"{quota['monthly']} this month; this request uses "
268
+ f"{len(action.body['urlList'])}.")
269
+ return confirm_and_run(action, send=args.send, yes=args.yes, log=ActionLog(root),
270
+ execute=lambda: client.execute(action))
271
+
272
+
273
+ def _bing_import_gsc(args, root: Path) -> int:
274
+ print(bing.gsc_import_guidance())
275
+ return 0
276
+
277
+
278
+ BING = {"sites": _bing_read, "crawl-stats": _bing_read, "query-stats": _bing_read,
279
+ "page-stats": _bing_read, "crawl-issues": _bing_read, "backlinks": _bing_read,
280
+ "quota": _bing_read, "submit-sitemap": _bing_submit_sitemap,
281
+ "submit-urls": _bing_submit_urls, "import-gsc": _bing_import_gsc}
282
+
283
+
284
+ # --- indexnow -----------------------------------------------------------------------------------
285
+
286
+ def _indexnow_key(args, root: Path) -> int:
287
+ key = indexnow.generate_key()
288
+ print(f"New IndexNow key (public by design; it is served from your site): {key}")
289
+ print("Next steps:")
290
+ print(f" 1. Create the key file: omnirank connect indexnow key-file --key {key} "
291
+ "--dir <the directory your site serves from, e.g. public> [--send]")
292
+ print(f" 2. Deploy, then check https://<your-host>/{key}.txt shows exactly the key.")
293
+ print(f" 3. Keep the key for submissions: export {ENV_INDEXNOW_KEY}={key} (or --key).")
294
+ print(indexnow.GOOGLE_NOTE)
295
+ return 0
296
+
297
+
298
+ def _indexnow_key_file(args, root: Path) -> int:
299
+ action, state = indexnow.key_file_action(root, args.dir, args.key)
300
+ if state == "present":
301
+ print(f"{action.url} already contains this key; nothing to write.")
302
+ return 0
303
+ return confirm_and_run(action, send=args.send, yes=args.yes, log=ActionLog(root),
304
+ execute=lambda: indexnow.write_key_file(root, action.url, args.key))
305
+
306
+
307
+ def _indexnow_submit(args, root: Path) -> int:
308
+ key = args.key or os.environ.get(ENV_INDEXNOW_KEY, "").strip()
309
+ if not key:
310
+ raise UsageError(f"give --key or set {ENV_INDEXNOW_KEY} (run `omnirank connect "
311
+ "indexnow key` to make one)")
312
+ indexnow.validate_key(key)
313
+ indexnow.validate_host(args.host)
314
+ if not 1 <= args.max <= INDEXNOW_MAX_URLS_PER_REQUEST:
315
+ raise UsageError(f"--max must be 1..{INDEXNOW_MAX_URLS_PER_REQUEST}")
316
+ if args.changed_since:
317
+ if args.url or args.urls_file:
318
+ raise UsageError("use either --changed-since (with --sitemap) or --url/--urls-file")
319
+ if not args.sitemap:
320
+ raise UsageError("--changed-since needs --sitemap PATH (a local <urlset> sitemap "
321
+ "used to map changed files to URLs)")
322
+ mapping = indexnow.changed_urls(root, args.changed_since, args.sitemap, args.host)
323
+ urls = mapping["urls"]
324
+ print(f"Changed since {args.changed_since} (framework: {mapping['framework']}): "
325
+ f"{len(urls)} URL(s) mapped through the locator.")
326
+ for u in mapping["unmapped"]:
327
+ _line(f" skipped {u['path']}: {u['reason']}")
328
+ if mapping["off_host_sitemap_urls"]:
329
+ print(f" {mapping['off_host_sitemap_urls']} sitemap URL(s) not on {args.host} "
330
+ "were ignored")
331
+ if not urls:
332
+ print("Nothing to submit.")
333
+ print(indexnow.GOOGLE_NOTE)
334
+ return 0
335
+ else:
336
+ urls = read_urls(args.url, args.urls_file)
337
+ ok, rejected = indexnow.check_urls(args.host, urls)
338
+ if rejected:
339
+ raise UsageError(f"{len(rejected)} URL(s) are not on {args.host} (first: "
340
+ f"{rejected[0][:200]}); nothing was sent")
341
+ indexnow.enforce_cap(len(ok), args.max, all_confirmed=args.all_confirmed)
342
+ actions = indexnow.submit_actions(args.host, key, args.key_location, ok)
343
+ print(indexnow.GOOGLE_NOTE)
344
+ print(f"Make sure {args.key_location or indexnow.default_key_location(args.host, key)} "
345
+ "serves exactly the key, or engines answer 403.")
346
+ client = indexnow.make_client() if args.send else None
347
+ log = ActionLog(root)
348
+ for action in actions:
349
+ code = confirm_and_run(action, send=args.send, yes=args.yes, log=log,
350
+ execute=lambda a=action: indexnow.execute(client, a))
351
+ if code != 0:
352
+ return code
353
+ return 0
354
+
355
+
356
+ INDEXNOW = {"key": _indexnow_key, "key-file": _indexnow_key_file, "submit": _indexnow_submit}
357
+
358
+
359
+ def dispatch(args, root: Path) -> int:
360
+ if args.connect_command == "ga4":
361
+ return GA4[args.ga4_command](args, root)
362
+ if args.connect_command == "bing":
363
+ return BING[args.bing_command](args, root)
364
+ return INDEXNOW[args.indexnow_command](args, root)
365
+
366
+
367
+ ERRORS = (UsageError, ga4.Ga4Error, bing.BingError, indexnow.IndexNowError)
368
+
369
+
370
+ # --- parsers ------------------------------------------------------------------------------------
371
+
372
+ def _root(parser) -> None:
373
+ parser.add_argument("--root", default=".",
374
+ help="Project root: the action log goes in <root>/.omnirank/ "
375
+ "(default: .)")
376
+
377
+
378
+ def _write_flags(parser) -> None:
379
+ parser.add_argument("--send", action="store_true",
380
+ help="Actually send/write it (after y/N). Without it: dry run")
381
+ parser.add_argument("--yes", action="store_true",
382
+ help="Confirm in advance (non-interactive). The request is still "
383
+ "printed first")
384
+
385
+
386
+ def add_parsers(csub) -> None:
387
+ g = csub.add_parser("ga4", help="Google Analytics 4: offline tag check and read-only "
388
+ "Data/Admin API reports")
389
+ gsub = g.add_subparsers(dest="ga4_command", required=True)
390
+ login = gsub.add_parser("login", help="Log in (Desktop OAuth client, loopback) with the "
391
+ "read-only Analytics and Search Console scopes")
392
+ _root(login)
393
+ login.add_argument("--client-file", required=True, metavar="PATH")
394
+ login.add_argument("--open-browser", action="store_true")
395
+ tags = gsub.add_parser("tags", help="Offline check of gtag.js/GTM tags in HTML files "
396
+ "(duplicates, IDs, page_view, Consent Mode)")
397
+ _root(tags)
398
+ tags.add_argument("--file", action="append", metavar="PATH",
399
+ help="HTML file to check (repeatable; default: every .html under --root)")
400
+ tags.add_argument("--expect-id", metavar="G-XXXXXXXXXX",
401
+ help="The measurement ID the pages should use")
402
+ tags.add_argument("--json", action="store_true")
403
+ rep = gsub.add_parser("report", help="Data API runReport preset (read-only)")
404
+ _root(rep)
405
+ rep.add_argument("--property", required=True, help="GA4 property ID (digits)")
406
+ rep.add_argument("--start", required=True, metavar="YYYY-MM-DD")
407
+ rep.add_argument("--end", required=True, metavar="YYYY-MM-DD")
408
+ rep.add_argument("--preset", required=True, choices=list(ga4.PRESETS))
409
+ rep.add_argument("--max-rows", type=int, default=10_000)
410
+ rep.add_argument("--top", type=int, default=25)
411
+ rep.add_argument("--json", action="store_true")
412
+ for name, help_text in (("streams", "List data streams (Admin API, read-only)"),
413
+ ("key-events", "List key events (Admin API, read-only)"),
414
+ ("search-console-link", ("Where to check the linked Search "
415
+ "Console property (guidance only)"))):
416
+ sp = gsub.add_parser(name, help=help_text)
417
+ _root(sp)
418
+ sp.add_argument("--property", required=True)
419
+ if name != "search-console-link":
420
+ sp.add_argument("--json", action="store_true")
421
+ from .runner_ga4_ai import add_parser as add_ai_referrals_parser
422
+ add_ai_referrals_parser(gsub, _root)
423
+
424
+ b = csub.add_parser("bing", help=f"Bing Webmaster Tools (API key from "
425
+ f"{bing.ENV_BING_KEY}; writes are dry runs unless --send)")
426
+ bsub = b.add_subparsers(dest="bing_command", required=True)
427
+ sites = bsub.add_parser("sites", help="Sites visible to the API key")
428
+ _root(sites)
429
+ sites.add_argument("--json", action="store_true")
430
+ for name, help_text in (("crawl-stats", "Crawl statistics"),
431
+ ("query-stats", "Top query traffic statistics"),
432
+ ("page-stats", "Top page traffic statistics"),
433
+ ("crawl-issues", "URLs with crawl issues"),
434
+ ("backlinks", "Pages with inbound links and their counts"),
435
+ ("quota", "Remaining URL submission quota")):
436
+ sp = bsub.add_parser(name, help=help_text)
437
+ _root(sp)
438
+ sp.add_argument("--site", required=True, help="Site URL as Bing lists it")
439
+ sp.add_argument("--json", action="store_true")
440
+ sp.add_argument("--top", type=int, default=25)
441
+ if name == "backlinks":
442
+ sp.add_argument("--max-pages", type=int, default=5,
443
+ help=f"Result pages to read (1..{bing.MAX_LINK_PAGES}, default 5)")
444
+ sm = bsub.add_parser("submit-sitemap", help="Submit a sitemap/feed (WRITE)")
445
+ _root(sm)
446
+ sm.add_argument("--site", required=True)
447
+ sm.add_argument("--sitemap", required=True, metavar="URL")
448
+ _write_flags(sm)
449
+ su = bsub.add_parser("submit-urls", help=f"Submit up to {BING_MAX_URLS_PER_BATCH} URLs "
450
+ "within the live quota (WRITE)")
451
+ _root(su)
452
+ su.add_argument("--site", required=True)
453
+ su.add_argument("--url", action="append", metavar="URL")
454
+ su.add_argument("--urls-file", metavar="PATH")
455
+ _write_flags(su)
456
+ ig = bsub.add_parser("import-gsc", help="Steps to import sites from Google Search "
457
+ "Console (guidance only)")
458
+ _root(ig)
459
+
460
+ x = csub.add_parser("indexnow", help="IndexNow: key, key file and changed-URL "
461
+ "submission (Google does not use IndexNow)")
462
+ xsub = x.add_subparsers(dest="indexnow_command", required=True)
463
+ k = xsub.add_parser("key", help="Generate a new random key and print the next steps")
464
+ _root(k)
465
+ kf = xsub.add_parser("key-file", help="Create <dir>/<key>.txt inside the project (WRITE: "
466
+ "dry run unless --send)")
467
+ _root(kf)
468
+ kf.add_argument("--key", required=True)
469
+ kf.add_argument("--dir", default="",
470
+ help="Directory your site serves from, relative to --root (default: root)")
471
+ _write_flags(kf)
472
+ s = xsub.add_parser("submit", help="POST changed URLs to api.indexnow.org (WRITE)")
473
+ _root(s)
474
+ s.add_argument("--host", required=True, help="Bare host name, e.g. example.com")
475
+ s.add_argument("--key", help=f"The key (default: ${ENV_INDEXNOW_KEY})")
476
+ s.add_argument("--key-location", metavar="URL",
477
+ help="Full URL of the key file (default: https://<host>/<key>.txt)")
478
+ s.add_argument("--url", action="append", metavar="URL")
479
+ s.add_argument("--urls-file", metavar="PATH")
480
+ s.add_argument("--changed-since", metavar="GIT_REF",
481
+ help="Submit the pages whose files changed in GIT_REF..HEAD")
482
+ s.add_argument("--sitemap", metavar="PATH",
483
+ help="Local <urlset> sitemap used to map changed files to URLs")
484
+ s.add_argument("--max", type=int, default=indexnow.DEFAULT_CAP,
485
+ help=f"Refuse more URLs than this (default {indexnow.DEFAULT_CAP})")
486
+ s.add_argument("--all-confirmed", action="store_true",
487
+ help="Every URL above the cap really changed; send them anyway")
488
+ _write_flags(s)
489
+