seo-supervisor 1.2.0 → 2.0.0

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 (207) hide show
  1. package/.claude-plugin/icon.png +0 -0
  2. package/.claude-plugin/marketplace.json +2 -2
  3. package/.claude-plugin/plugin.json +16 -3
  4. package/CHANGELOG.md +430 -0
  5. package/NOTICE +7 -0
  6. package/README.md +230 -25
  7. package/agents/seo-auditor.md +16 -0
  8. package/agents/seo-reviewer.md +16 -0
  9. package/bin/agents.mjs +194 -29
  10. package/bin/extras.mjs +422 -0
  11. package/bin/prompt.mjs +34 -14
  12. package/bin/seo-supervisor.mjs +386 -53
  13. package/commands/seo-audit.md +29 -3
  14. package/commands/seo-brief.md +28 -0
  15. package/commands/seo-connect.md +27 -0
  16. package/commands/seo-fix.md +24 -3
  17. package/commands/seo-grow.md +26 -0
  18. package/commands/seo-launch.md +17 -3
  19. package/commands/seo-review.md +13 -1
  20. package/commands/seo-rewrite.md +25 -0
  21. package/commands/seo-setup.md +17 -1
  22. package/commands/seo-watch.md +28 -0
  23. package/hooks/hooks.json +117 -0
  24. package/package.json +20 -7
  25. package/skills/seo-supervisor/NOTICE +7 -0
  26. package/skills/seo-supervisor/SKILL.md +302 -21
  27. package/skills/seo-supervisor/audience.md +61 -0
  28. package/skills/seo-supervisor/examples/drafts/security.md +41 -0
  29. package/skills/seo-supervisor/examples/hooks/README.md +28 -0
  30. package/skills/seo-supervisor/examples/hooks/claude-code-settings.json +15 -0
  31. package/skills/seo-supervisor/examples/hooks/codex-hooks.json +17 -0
  32. package/skills/seo-supervisor/examples/hooks/copilot-hooks.json +15 -0
  33. package/skills/seo-supervisor/examples/hooks/cursor-hooks.json +11 -0
  34. package/skills/seo-supervisor/examples/hooks/github-actions.yml +21 -0
  35. package/skills/seo-supervisor/examples/hooks/pre-commit +17 -0
  36. package/skills/seo-supervisor/examples/hooks/reading-ease.yml +24 -0
  37. package/skills/seo-supervisor/examples/sample-audit.json +94 -2
  38. package/skills/seo-supervisor/examples/sample-report.html +111 -61
  39. package/skills/seo-supervisor/examples/sample-report.md +147 -44
  40. package/skills/seo-supervisor/examples/scheduled-runs.md +89 -0
  41. package/skills/seo-supervisor/examples/snippets.md +648 -1
  42. package/skills/seo-supervisor/grow.md +342 -0
  43. package/skills/seo-supervisor/og-images.md +85 -0
  44. package/skills/seo-supervisor/page-types.md +124 -0
  45. package/skills/seo-supervisor/planning.md +19 -7
  46. package/skills/seo-supervisor/profile-template.md +41 -0
  47. package/skills/seo-supervisor/report-format.md +177 -10
  48. package/skills/seo-supervisor/rewrite.md +59 -0
  49. package/skills/seo-supervisor/rules/ai-search.md +65 -12
  50. package/skills/seo-supervisor/rules/content.md +33 -9
  51. package/skills/seo-supervisor/rules/crawl-index.md +33 -6
  52. package/skills/seo-supervisor/rules/internal-linking.md +49 -6
  53. package/skills/seo-supervisor/rules/launch-monitoring.md +17 -8
  54. package/skills/seo-supervisor/rules/media.md +13 -1
  55. package/skills/seo-supervisor/rules/metadata.md +41 -9
  56. package/skills/seo-supervisor/rules/performance.md +50 -5
  57. package/skills/seo-supervisor/rules/rendering.md +39 -2
  58. package/skills/seo-supervisor/rules/search-intent.md +32 -0
  59. package/skills/seo-supervisor/rules/sitemaps-robots.md +24 -12
  60. package/skills/seo-supervisor/rules/structured-data.md +37 -14
  61. package/skills/seo-supervisor/rules/trust-security.md +25 -2
  62. package/skills/seo-supervisor/rules/urls.md +10 -2
  63. package/skills/seo-supervisor/scripts/ai-answers.mjs +314 -0
  64. package/skills/seo-supervisor/scripts/backlinks.mjs +412 -0
  65. package/skills/seo-supervisor/scripts/change-check.mjs +281 -0
  66. package/skills/seo-supervisor/scripts/checks/agents.mjs +488 -0
  67. package/skills/seo-supervisor/scripts/checks/assets.mjs +404 -0
  68. package/skills/seo-supervisor/scripts/checks/bots.mjs +146 -0
  69. package/skills/seo-supervisor/scripts/checks/business-type.mjs +193 -0
  70. package/skills/seo-supervisor/scripts/checks/content.mjs +391 -0
  71. package/skills/seo-supervisor/scripts/checks/coverage.mjs +184 -0
  72. package/skills/seo-supervisor/scripts/checks/crawl.mjs +95 -0
  73. package/skills/seo-supervisor/scripts/checks/hreflang.mjs +396 -0
  74. package/skills/seo-supervisor/scripts/checks/hygiene.mjs +227 -0
  75. package/skills/seo-supervisor/scripts/checks/lighthouse.mjs +271 -0
  76. package/skills/seo-supervisor/scripts/checks/link-strength.mjs +59 -0
  77. package/skills/seo-supervisor/scripts/checks/links.mjs +360 -0
  78. package/skills/seo-supervisor/scripts/checks/local.mjs +101 -0
  79. package/skills/seo-supervisor/scripts/checks/media.mjs +194 -0
  80. package/skills/seo-supervisor/scripts/checks/outbound.mjs +53 -0
  81. package/skills/seo-supervisor/scripts/checks/page.mjs +223 -0
  82. package/skills/seo-supervisor/scripts/checks/probes.mjs +130 -0
  83. package/skills/seo-supervisor/scripts/checks/render.mjs +552 -0
  84. package/skills/seo-supervisor/scripts/checks/robots.mjs +144 -0
  85. package/skills/seo-supervisor/scripts/checks/schema.mjs +206 -0
  86. package/skills/seo-supervisor/scripts/checks/site-agents.mjs +79 -0
  87. package/skills/seo-supervisor/scripts/checks/site-content.mjs +135 -0
  88. package/skills/seo-supervisor/scripts/checks/site-hygiene.mjs +202 -0
  89. package/skills/seo-supervisor/scripts/checks/site-pages.mjs +474 -0
  90. package/skills/seo-supervisor/scripts/checks/site-security.mjs +102 -0
  91. package/skills/seo-supervisor/scripts/checks/sitemap.mjs +473 -0
  92. package/skills/seo-supervisor/scripts/checks/speed.mjs +267 -0
  93. package/skills/seo-supervisor/scripts/checks/technical.mjs +368 -0
  94. package/skills/seo-supervisor/scripts/checks/tls.mjs +297 -0
  95. package/skills/seo-supervisor/scripts/checks/trust.mjs +421 -0
  96. package/skills/seo-supervisor/scripts/checks/visual.mjs +1132 -0
  97. package/skills/seo-supervisor/scripts/checks/writing.mjs +192 -0
  98. package/skills/seo-supervisor/scripts/commoncrawl.mjs +452 -0
  99. package/skills/seo-supervisor/scripts/connect-keys.mjs +422 -0
  100. package/skills/seo-supervisor/scripts/content-scan.mjs +515 -158
  101. package/skills/seo-supervisor/scripts/crawl/catalog.mjs +1248 -0
  102. package/skills/seo-supervisor/scripts/crawl/fetch.mjs +362 -0
  103. package/skills/seo-supervisor/scripts/crawl/page.mjs +741 -0
  104. package/skills/seo-supervisor/scripts/crawl/queue.mjs +190 -0
  105. package/skills/seo-supervisor/scripts/dashboard.mjs +140 -0
  106. package/skills/seo-supervisor/scripts/data/ai-bots.json +38 -0
  107. package/skills/seo-supervisor/scripts/data/build-schema-vocab.mjs +57 -0
  108. package/skills/seo-supervisor/scripts/data/business-types.json +338 -0
  109. package/skills/seo-supervisor/scripts/data/google-rich-results.json +79 -0
  110. package/skills/seo-supervisor/scripts/data/schema-vocab.json +1 -0
  111. package/skills/seo-supervisor/scripts/deploy-check.mjs +462 -0
  112. package/skills/seo-supervisor/scripts/disavow.mjs +176 -0
  113. package/skills/seo-supervisor/scripts/doctor.mjs +174 -0
  114. package/skills/seo-supervisor/scripts/geo-grid.mjs +371 -0
  115. package/skills/seo-supervisor/scripts/google/search-console.mjs +151 -0
  116. package/skills/seo-supervisor/scripts/google/session.mjs +167 -0
  117. package/skills/seo-supervisor/scripts/google-updates.mjs +189 -0
  118. package/skills/seo-supervisor/scripts/google.mjs +1341 -0
  119. package/skills/seo-supervisor/scripts/gsc-import.mjs +298 -0
  120. package/skills/seo-supervisor/scripts/guard/adapters/claude-code.mjs +149 -0
  121. package/skills/seo-supervisor/scripts/guard/adapters/cline.mjs +28 -0
  122. package/skills/seo-supervisor/scripts/guard/adapters/codex.mjs +26 -0
  123. package/skills/seo-supervisor/scripts/guard/adapters/copilot.mjs +36 -0
  124. package/skills/seo-supervisor/scripts/guard/adapters/cursor.mjs +33 -0
  125. package/skills/seo-supervisor/scripts/guard/adapters/devin.mjs +25 -0
  126. package/skills/seo-supervisor/scripts/guard/adapters/edits.mjs +124 -0
  127. package/skills/seo-supervisor/scripts/guard/mode.mjs +37 -0
  128. package/skills/seo-supervisor/scripts/guard/rules.mjs +931 -0
  129. package/skills/seo-supervisor/scripts/guard.mjs +74 -0
  130. package/skills/seo-supervisor/scripts/images.mjs +408 -0
  131. package/skills/seo-supervisor/scripts/indexnow.mjs +300 -0
  132. package/skills/seo-supervisor/scripts/issues.mjs +217 -0
  133. package/skills/seo-supervisor/scripts/keys/authority.mjs +135 -0
  134. package/skills/seo-supervisor/scripts/keys/bing.mjs +239 -0
  135. package/skills/seo-supervisor/scripts/keys/clarity.mjs +137 -0
  136. package/skills/seo-supervisor/scripts/keys/dataforseo.mjs +57 -0
  137. package/skills/seo-supervisor/scripts/keys/googleplaces.mjs +26 -0
  138. package/skills/seo-supervisor/scripts/keys/http.mjs +212 -0
  139. package/skills/seo-supervisor/scripts/keys/matomo.mjs +138 -0
  140. package/skills/seo-supervisor/scripts/keys/openai.mjs +26 -0
  141. package/skills/seo-supervisor/scripts/keys/perplexity.mjs +26 -0
  142. package/skills/seo-supervisor/scripts/keys/posthog.mjs +165 -0
  143. package/skills/seo-supervisor/scripts/keys/semrush.mjs +25 -0
  144. package/skills/seo-supervisor/scripts/keys/services.mjs +41 -0
  145. package/skills/seo-supervisor/scripts/keys/store.mjs +140 -0
  146. package/skills/seo-supervisor/scripts/keys/visits.mjs +58 -0
  147. package/skills/seo-supervisor/scripts/keys/youtube.mjs +84 -0
  148. package/skills/seo-supervisor/scripts/keyword-data.mjs +316 -0
  149. package/skills/seo-supervisor/scripts/keyword-ideas.mjs +503 -0
  150. package/skills/seo-supervisor/scripts/lib/args.mjs +56 -0
  151. package/skills/seo-supervisor/scripts/lib/business.mjs +27 -0
  152. package/skills/seo-supervisor/scripts/lib/cdp.mjs +242 -0
  153. package/skills/seo-supervisor/scripts/lib/cli.mjs +56 -0
  154. package/skills/seo-supervisor/scripts/lib/csv.mjs +38 -0
  155. package/skills/seo-supervisor/scripts/lib/findings.mjs +100 -0
  156. package/skills/seo-supervisor/scripts/lib/google-client.mjs +9 -0
  157. package/skills/seo-supervisor/scripts/lib/html.mjs +146 -0
  158. package/skills/seo-supervisor/scripts/lib/http.mjs +28 -0
  159. package/skills/seo-supervisor/scripts/lib/image-size.mjs +78 -0
  160. package/skills/seo-supervisor/scripts/lib/is-main.mjs +13 -0
  161. package/skills/seo-supervisor/scripts/lib/net.mjs +116 -0
  162. package/skills/seo-supervisor/scripts/lib/proxy.mjs +47 -0
  163. package/skills/seo-supervisor/scripts/lib/recheck.mjs +106 -0
  164. package/skills/seo-supervisor/scripts/lib/redact.mjs +78 -0
  165. package/skills/seo-supervisor/scripts/lib/robots.mjs +73 -0
  166. package/skills/seo-supervisor/scripts/lib/score.mjs +266 -0
  167. package/skills/seo-supervisor/scripts/lib/settings-dir.mjs +81 -0
  168. package/skills/seo-supervisor/scripts/links-import.mjs +603 -0
  169. package/skills/seo-supervisor/scripts/log-scan.mjs +597 -0
  170. package/skills/seo-supervisor/scripts/og-card.mjs +273 -0
  171. package/skills/seo-supervisor/scripts/osm.mjs +359 -0
  172. package/skills/seo-supervisor/scripts/rdap.mjs +164 -0
  173. package/skills/seo-supervisor/scripts/render-report.mjs +324 -690
  174. package/skills/seo-supervisor/scripts/report/client.js +37 -0
  175. package/skills/seo-supervisor/scripts/report/diff.mjs +264 -0
  176. package/skills/seo-supervisor/scripts/report/findings.mjs +165 -0
  177. package/skills/seo-supervisor/scripts/report/format.mjs +111 -0
  178. package/skills/seo-supervisor/scripts/report/markdown.mjs +250 -0
  179. package/skills/seo-supervisor/scripts/report/model.mjs +171 -0
  180. package/skills/seo-supervisor/scripts/report/overview-lines.mjs +158 -0
  181. package/skills/seo-supervisor/scripts/report/overview.mjs +224 -0
  182. package/skills/seo-supervisor/scripts/report/page.mjs +127 -0
  183. package/skills/seo-supervisor/scripts/report/panel.mjs +172 -0
  184. package/skills/seo-supervisor/scripts/report/panels/ai.mjs +211 -0
  185. package/skills/seo-supervisor/scripts/report/panels/connections.mjs +139 -0
  186. package/skills/seo-supervisor/scripts/report/panels/content.mjs +204 -0
  187. package/skills/seo-supervisor/scripts/report/panels/data-search.mjs +379 -0
  188. package/skills/seo-supervisor/scripts/report/panels/data-site.mjs +44 -0
  189. package/skills/seo-supervisor/scripts/report/panels/links.mjs +380 -0
  190. package/skills/seo-supervisor/scripts/report/panels/local.mjs +221 -0
  191. package/skills/seo-supervisor/scripts/report/panels/site.mjs +359 -0
  192. package/skills/seo-supervisor/scripts/report/panels/speed-media.mjs +267 -0
  193. package/skills/seo-supervisor/scripts/report/sources.mjs +163 -0
  194. package/skills/seo-supervisor/scripts/report/styles.css +223 -0
  195. package/skills/seo-supervisor/scripts/report/traffic.mjs +264 -0
  196. package/skills/seo-supervisor/scripts/report-plan.mjs +112 -33
  197. package/skills/seo-supervisor/scripts/schema-check.mjs +717 -0
  198. package/skills/seo-supervisor/scripts/seo-crawl.mjs +1086 -638
  199. package/skills/seo-supervisor/scripts/seo-diff.mjs +584 -0
  200. package/skills/seo-supervisor/scripts/update-check.mjs +82 -0
  201. package/skills/seo-supervisor/site-types/content.md +34 -1
  202. package/skills/seo-supervisor/site-types/ecommerce.md +38 -1
  203. package/skills/seo-supervisor/site-types/local-business.md +96 -6
  204. package/skills/seo-supervisor/site-types/services.md +46 -0
  205. package/skills/seo-supervisor/site-types/tools.md +3 -3
  206. package/skills/seo-supervisor/strategy.md +232 -0
  207. package/skills/seo-supervisor/troubleshooting.md +56 -0
@@ -0,0 +1,1341 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ // Search Console and GA4 data for the audit. Read-only, except submit-sitemap, which writes only with --yes.
4
+ import { createHash, randomBytes } from "node:crypto";
5
+ import { createServer } from "node:http";
6
+ import { spawn } from "node:child_process";
7
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
8
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
9
+ import { createInterface } from "node:readline/promises";
10
+ import { isMain } from "./lib/is-main.mjs";
11
+ import { isHelp, parseArgs } from "./lib/args.mjs";
12
+ import { runMain, warnProxy } from "./lib/cli.mjs";
13
+ import { loginDir, privacyOf } from "./lib/settings-dir.mjs";
14
+ import { SHARED_CLIENT } from "./lib/google-client.mjs";
15
+ import { addTraffic, gscFindings } from "./gsc-import.mjs";
16
+ import { foundOn } from "./lib/findings.mjs";
17
+ import {
18
+ SC,
19
+ GA,
20
+ SCOPES,
21
+ endpointsFrom,
22
+ Fail,
23
+ Refused,
24
+ fail,
25
+ FORM,
26
+ tokenFile,
27
+ load,
28
+ save,
29
+ tokenRequest,
30
+ serviceAccountToken,
31
+ session,
32
+ API_OFF,
33
+ whoOf,
34
+ explain,
35
+ } from "./google/session.mjs";
36
+ import {
37
+ SC_API,
38
+ anomaliesIn,
39
+ anomalyNote,
40
+ httpUrl,
41
+ refused,
42
+ pickProperty,
43
+ bare,
44
+ pagePath,
45
+ slashKey,
46
+ scSession,
47
+ searchConsole,
48
+ inProperty,
49
+ periodOf,
50
+ periodBefore,
51
+ daysOf,
52
+ readRows,
53
+ } from "./google/search-console.mjs";
54
+
55
+ // Re-exported for the tests.
56
+ export { Fail, anomaliesIn, pagePath, searchConsole };
57
+ // Read/write Search Console, asked for only by submit-sitemap --yes, never at connect.
58
+ const WM = "https://www.googleapis.com/auth/webmasters";
59
+ const has = (scope, x) => (scope || "").split(" ").includes(x); // not includes() on the string: WM is a prefix of SC
60
+ const ADMIN_API = {
61
+ name: "Google Analytics Admin API",
62
+ where: "Google Analytics → Admin → Property access management",
63
+ };
64
+ const DATA_API = { name: "Google Analytics Data API", where: ADMIN_API.where };
65
+ // Shares of queries, not of impressions, by average position; top10 includes top3.
66
+ export function positionShares(queries) {
67
+ if (!queries.length) return null;
68
+ const share = n => Math.round((1000 * n) / queries.length) / 1000,
69
+ top10 = queries.filter(q => q.position <= 10).length;
70
+ return {
71
+ queries: queries.length,
72
+ top3: share(queries.filter(q => q.position <= 3).length),
73
+ top10: share(top10),
74
+ beyond: share(queries.length - top10),
75
+ };
76
+ }
77
+
78
+ export const challengeFor = verifier => createHash("sha256").update(verifier).digest("base64url");
79
+ export function pkce() {
80
+ const verifier = randomBytes(32).toString("base64url");
81
+ return { verifier, challenge: challengeFor(verifier) };
82
+ }
83
+
84
+ // ---------- the saved sign-in (google/session.mjs keeps it and makes the calls) ----------
85
+ const pendingFile = () => join(loginDir(), "pending-signin.txt");
86
+ const readJson = f => {
87
+ let t;
88
+ try {
89
+ t = readFileSync(f, "utf8");
90
+ } catch (e) {
91
+ fail(`google: can't read ${f} (${e.code || e.message}).`);
92
+ }
93
+ try {
94
+ return JSON.parse(t);
95
+ } catch {
96
+ fail(`google: ${f} isn't a JSON file from Google Cloud.`);
97
+ }
98
+ };
99
+
100
+ // ---------- fetch ----------
101
+ // crawl, a parsed seo-crawl.json, lets URL Inspection sample key pages with no search traffic yet. inspect (paths or
102
+ // URLs) replaces the default sample.
103
+ /** @param {{ site?: string, days?: number | string, ga4Property?: string, crawl?: any, inspect?: string[], pageSize?: number, home?: string, endpoints?: any }} [opts] */
104
+ export async function fetchGoogle({
105
+ site,
106
+ days = 90,
107
+ ga4Property,
108
+ crawl,
109
+ inspect,
110
+ pageSize = 25000,
111
+ home,
112
+ endpoints,
113
+ } = {}) {
114
+ const origin = httpUrl(site, "--site must be the site's address", "https://www.example.com");
115
+ days = daysOf(days, "google");
116
+ const { g, scope, who } = scSession({ home, endpoints }),
117
+ { E } = g,
118
+ notes = [];
119
+ // A failed section becomes a note. A fatal one stops the pull, except on 429: a used-up quota is still only a note.
120
+ const attempt = async (what, api, fn, fatal = false) => {
121
+ try {
122
+ return await fn();
123
+ } catch (e) {
124
+ const msg = explain(e, what, api, who);
125
+ if (fatal && e.status !== 429) throw refused(e, msg);
126
+ notes.push(msg);
127
+ }
128
+ };
129
+
130
+ // Search Console's last 2-3 days are provisional, so periodOf ends the period 3 days ago.
131
+ const { startDate, endDate } = periodOf(days),
132
+ period = `Last ${days} days, ${startDate} to ${endDate}`;
133
+
134
+ const prop = await pickProperty(g, origin, who),
135
+ h = origin.hostname;
136
+ const scBase = `${E.searchConsole}/sites/${encodeURIComponent(prop)}`;
137
+
138
+ // www and apex count as one host; other subdomains of a domain property are left out. A row whose path differs from a
139
+ // crawled page's only by the trailing slash is filed under the crawled path, so the report finds its numbers.
140
+ const crawled = new Set(
141
+ (crawl?.pages || [])
142
+ .map(p => {
143
+ try {
144
+ const x = new URL(p.url);
145
+ return x.pathname + x.search;
146
+ } catch {
147
+ return null;
148
+ }
149
+ })
150
+ .filter(Boolean),
151
+ );
152
+ const bySlash = new Map([...crawled].map(p => [slashKey(p), p]));
153
+ const pathOf = u => {
154
+ const p = pagePath(u, h);
155
+ return p && !crawled.has(p) ? (bySlash.get(slashKey(p)) ?? p) : p;
156
+ };
157
+ const sa = body =>
158
+ g.call(`${scBase}/searchAnalytics/query`, { startDate, endDate, type: "web", dimensions: [], ...body });
159
+ const rowsFor = (dimensions, dates) => readRows(sa, dimensions, dates, pageSize, notes);
160
+ // Shared by the sections below. They run in order, and later ones read what earlier ones returned.
161
+ const c = { g, E, who, notes, attempt, origin, h, prop, scBase, startDate, endDate, pathOf, sa, rowsFor };
162
+
163
+ const { traffic, urls, pageQueries, queries, pagesRead, queriesRead } = await readPerformance(c);
164
+ const siteTotals = await readSiteTotals(c, queries, queriesRead);
165
+ const { startDate: prevStart, endDate: prevEnd } = periodBefore(days);
166
+ const trafficChange = await readTrafficChange(c, days, traffic, pagesRead, prevStart, prevEnd);
167
+ const newQueries = await readNewQueries(c, days, queries, queriesRead, prevStart, prevEnd);
168
+ const searchTypes = await readSearchTypes(c);
169
+ const { byDevice, byCountry } = await readDeviceAndCountry(c);
170
+ const brandSplit = await readBrandSplit(c, days, prevStart, prevEnd);
171
+ const inspection = await inspectPages(c, crawl, inspect, traffic, urls);
172
+ const sitemaps = await readSitemaps(c);
173
+ const { analytics, gaProp, gaRead } = await readAnalytics(c, scope, ga4Property);
174
+ const analyticsDetail = await readAnalyticsDetail(c, gaProp, gaRead);
175
+ const findings = googleFindings(notes, inspection, sitemaps, traffic, pageQueries, urls);
176
+ const anomalies = anomalyNotes(notes, trafficChange, searchTypes, startDate, endDate, prevStart);
177
+
178
+ return {
179
+ source: "google",
180
+ site: origin.origin,
181
+ properties: { searchConsole: prop, analytics: gaProp },
182
+ period,
183
+ traffic,
184
+ queries,
185
+ positions: positionShares(queries),
186
+ siteTotals,
187
+ pageQueries,
188
+ trafficChange,
189
+ newQueries,
190
+ searchTypes,
191
+ byDevice,
192
+ byCountry,
193
+ brandSplit,
194
+ inspection,
195
+ sitemaps,
196
+ analytics,
197
+ analyticsDetail,
198
+ anomalies,
199
+ findings,
200
+ notes,
201
+ };
202
+ }
203
+ const metrics = r => ({
204
+ clicks: r.clicks,
205
+ impressions: r.impressions,
206
+ ctr: Math.round(r.ctr * 10000) / 10000,
207
+ position: Math.round(r.position * 10) / 10,
208
+ });
209
+ const ci = r => ({ clicks: r.clicks, impressions: r.impressions });
210
+ const total = (m, k) => Object.values(m).reduce((s, x) => s + x[k], 0);
211
+
212
+ // Fatal on failure: without these there's nothing to report.
213
+ async function readPerformance({ attempt, prop, rowsFor, pathOf }) {
214
+ const traffic = {},
215
+ urls = {},
216
+ pageQueries = {},
217
+ pq = {};
218
+ let queries = [],
219
+ pagesRead = false,
220
+ queriesRead = false;
221
+ await attempt(
222
+ `${prop} in Search Console`,
223
+ SC_API,
224
+ async () => {
225
+ for (const r of await rowsFor(["page"])) {
226
+ const p = pathOf(r.keys[0]);
227
+ if (p) {
228
+ urls[p] ||= r.keys[0];
229
+ addTraffic(traffic, p, metrics(r));
230
+ }
231
+ }
232
+ pagesRead = true;
233
+ queries = (await rowsFor(["query"])).map(r => ({ query: r.keys[0], ...metrics(r) }));
234
+ queriesRead = true;
235
+ for (const r of await rowsFor(["page", "query"])) {
236
+ const p = pathOf(r.keys[0]);
237
+ if (p) {
238
+ urls[p] ||= r.keys[0];
239
+ addTraffic((pq[p] ||= {}), r.keys[1], metrics(r));
240
+ }
241
+ }
242
+ for (const [p, list] of Object.entries(pq))
243
+ pageQueries[p] = Object.entries(list).map(([query, m]) => ({ query, ...m }));
244
+ },
245
+ true,
246
+ );
247
+ return { traffic, urls, pageQueries, queries, pagesRead, queriesRead };
248
+ }
249
+
250
+ // A query with no dimensions gives the totals Search Console's chart shows, including the clicks of anonymized queries
251
+ // that query rows leave out. `complete` is null when the queries weren't read.
252
+ // https://developers.google.com/search/blog/2022/10/performance-data-deep-dive
253
+ async function readSiteTotals({ attempt, prop, sa }, queries, queriesRead) {
254
+ let siteTotals = null;
255
+ await attempt(`the site totals for ${prop} in Search Console`, SC_API, async () => {
256
+ const t = (await sa({})).rows?.[0];
257
+ if (!t) return;
258
+ const queryClicks = queries.reduce((s, q) => s + q.clicks, 0);
259
+ siteTotals = { ...metrics(t), queryClicks, complete: queriesRead ? queryClicks >= t.clicks : null };
260
+ });
261
+ return siteTotals;
262
+ }
263
+
264
+ // A drop is at least 20 clicks and 30% lost: below 20 a small page's weekly swing looks like a drop, and a big page
265
+ // loses 20 to noise.
266
+ const dropped = (before, after) => before - after >= 20 && after <= before * 0.7;
267
+ async function readTrafficChange(
268
+ { attempt, notes, prop, startDate, endDate, rowsFor, pathOf },
269
+ days,
270
+ traffic,
271
+ pagesRead,
272
+ prevStart,
273
+ prevEnd,
274
+ ) {
275
+ let trafficChange = null;
276
+ if (2 * days + 2 > 482)
277
+ notes.push(
278
+ "Search Console keeps 16 months of data, so a period longer than 240 days has no full period before it to compare with; the change in search clicks and the new searches were left out.",
279
+ );
280
+ // Without this period's pages every page would look like a drop to 0.
281
+ else if (!pagesRead)
282
+ notes.push(
283
+ "This period's pages couldn't be read from Search Console, so the change in search clicks from the period before was left out.",
284
+ );
285
+ else
286
+ await attempt(`${prop} in Search Console for the period before`, SC_API, async () => {
287
+ const before = {};
288
+ for (const r of await rowsFor(["page"], { startDate: prevStart, endDate: prevEnd })) {
289
+ const p = pathOf(r.keys[0]);
290
+ if (p) addTraffic(before, p, metrics(r));
291
+ }
292
+ const drops = Object.entries(before)
293
+ .map(([path, b]) => ({ path, before: b.clicks, after: traffic[path]?.clicks || 0 }))
294
+ .filter(d => dropped(d.before, d.after))
295
+ .sort((a, b) => b.before - b.after - (a.before - a.after))
296
+ .slice(0, 10);
297
+ trafficChange = {
298
+ previous: {
299
+ from: prevStart,
300
+ to: prevEnd,
301
+ clicks: total(before, "clicks"),
302
+ impressions: total(before, "impressions"),
303
+ },
304
+ current: {
305
+ from: startDate,
306
+ to: endDate,
307
+ clicks: total(traffic, "clicks"),
308
+ impressions: total(traffic, "impressions"),
309
+ },
310
+ drops,
311
+ };
312
+ });
313
+ return trafficChange;
314
+ }
315
+
316
+ // Queries with no row in the period before. Rows stop at 25,000 and leave out rare (anonymized) queries, so a search
317
+ // listed may have had a few impressions before. https://developers.google.com/webmaster-tools/v1/searchanalytics/query
318
+ async function readNewQueries({ attempt, notes, prop, rowsFor }, days, queries, queriesRead, prevStart, prevEnd) {
319
+ let newQueries = null;
320
+ if (2 * days + 2 <= 482 && queriesRead)
321
+ await attempt(`the searches for ${prop} in Search Console for the period before`, SC_API, async () => {
322
+ const before = await rowsFor(["query"], { startDate: prevStart, endDate: prevEnd }),
323
+ had = new Set(before.map(r => r.keys[0]));
324
+ newQueries = queries
325
+ .filter(q => q.impressions > 0 && !had.has(q.query))
326
+ .sort((a, b) => b.impressions - a.impressions || b.clicks - a.clicks)
327
+ .slice(0, 50);
328
+ if (before.length >= 25000 && newQueries.length)
329
+ notes.push(
330
+ "Only the period before's top 25,000 searches could be read, so some of the new searches may have been searched then too.",
331
+ );
332
+ });
333
+ return newQueries;
334
+ }
335
+
336
+ // Only the page dimension, which every type allows: Discover and Google News have no queries. Totals are the
337
+ // property's, other subdomains included.
338
+ async function readSearchTypes({ attempt, sa, pathOf }) {
339
+ const searchTypes = {};
340
+ // webMultimodal is Google Lens, Circle to Search and image uploads.
341
+ await attempt("the image, video, news, Discover and Lens results in Search Console", SC_API, async () => {
342
+ for (const type of ["image", "video", "news", "googleNews", "discover", "webMultimodal"]) {
343
+ const t = (await sa({ type })).rows?.[0];
344
+ if (!t?.impressions) continue;
345
+ const pages = {};
346
+ for (const r of (await sa({ type, dimensions: ["page"], rowLimit: 10 })).rows || []) {
347
+ const p = pathOf(r.keys[0]);
348
+ if (p)
349
+ pages[p] = {
350
+ clicks: (pages[p]?.clicks || 0) + r.clicks,
351
+ impressions: (pages[p]?.impressions || 0) + r.impressions,
352
+ };
353
+ }
354
+ searchTypes[type] = { ...ci(t), pages };
355
+ }
356
+ });
357
+ return searchTypes;
358
+ }
359
+
360
+ // Country keys are ISO 3166 alpha-3, lower case.
361
+ async function readDeviceAndCountry({ attempt, sa }) {
362
+ const byDevice = {},
363
+ byCountry = {};
364
+ await attempt("search by device and country in Search Console", SC_API, async () => {
365
+ for (const r of (await sa({ dimensions: ["device"] })).rows || []) byDevice[r.keys[0]] = ci(r);
366
+ for (const r of ((await sa({ dimensions: ["country"] })).rows || [])
367
+ .sort((a, b) => b.clicks - a.clicks || b.impressions - a.impressions)
368
+ .slice(0, 10))
369
+ byCountry[r.keys[0]] = ci(r);
370
+ });
371
+ return { byDevice, byCountry };
372
+ }
373
+
374
+ // brandedClassification has data from 21 Feb 2026, only for top-level properties with enough searches; others get no
375
+ // rows. It can't be combined with a query filter.
376
+ // https://developers.google.com/search/blog/2026/11/search-analytics-api-update
377
+ // The period before is compared only when fully labelled, so a non-brand fall hidden by brand growth is noted.
378
+ const BRAND_FROM = "2026-02-21";
379
+ async function readBrandSplit({ attempt, notes, sa }, days, prevStart, prevEnd) {
380
+ let brandSplit = null;
381
+ await attempt("the brand and non-brand split in Search Console", SC_API, async () => {
382
+ const split = async (dates = {}) => {
383
+ const rows = (await sa({ ...dates, dimensions: ["brandedClassification"] })).rows || [],
384
+ side = k => rows.find(r => r.keys?.[0] === k);
385
+ return side("BRANDED") || side("NON_BRANDED")
386
+ ? {
387
+ branded: ci(side("BRANDED") || { clicks: 0, impressions: 0 }),
388
+ nonBranded: ci(side("NON_BRANDED") || { clicks: 0, impressions: 0 }),
389
+ }
390
+ : null;
391
+ };
392
+ brandSplit = await split();
393
+ if (!brandSplit)
394
+ return void notes.push(
395
+ "Search Console labels brand searches only for top-level properties with enough searches (data from 21 Feb 2026), and this property isn't eligible, so there's no brand and non-brand split.",
396
+ );
397
+ if (2 * days + 2 > 482) return; // no full period before: readTrafficChange's note says so
398
+ if (prevStart < BRAND_FROM)
399
+ return void notes.push(
400
+ `Search Console labels brand searches from 21 Feb 2026, and the period before starts on ${prevStart}, so the brand and non-brand split isn't compared with the period before.`,
401
+ );
402
+ const was = await split({ startDate: prevStart, endDate: prevEnd });
403
+ if (!was) return;
404
+ brandSplit.previous = { from: prevStart, to: prevEnd, ...was };
405
+ const [b0, b1, n0, n1] = [
406
+ was.branded.clicks,
407
+ brandSplit.branded.clicks,
408
+ was.nonBranded.clicks,
409
+ brandSplit.nonBranded.clicks,
410
+ ];
411
+ if (dropped(n0, n1))
412
+ notes.push(
413
+ `Searches other than your brand fell from ${n0} to ${n1} clicks (-${Math.round(100 * (1 - n1 / n0))}%) compared with the period before (${prevStart} to ${prevEnd})${b1 > b0 ? `, while brand searches grew from ${b0} to ${b1}, so the site's total hides the fall` : ""}.`,
414
+ );
415
+ });
416
+ return brandSplit;
417
+ }
418
+
419
+ // Google allows 2,000 inspections a day per property and 600 a minute; 200 stays under the minute's limit and leaves
420
+ // most of the day's.
421
+ const INSPECT_MAX = 200;
422
+ // Default sample: the home page, up to 10 crawled pages (shallowest, most linked), then top pages by clicks, 20 in all.
423
+ // The crawl may be of a local build, so only its paths are used.
424
+ async function inspectPages({ g, E, who, notes, origin, prop }, crawl, inspect, traffic, urls) {
425
+ const pathOnly = u => {
426
+ try {
427
+ const x = new URL(u);
428
+ return x.pathname + x.search;
429
+ } catch {
430
+ return null;
431
+ }
432
+ };
433
+ const crawled = (crawl?.pages || [])
434
+ .filter(p => p.status === 200 && !p.noindex)
435
+ .sort((a, b) => (a.depth ?? 99) - (b.depth ?? 99) || (b.linksIn || 0) - (a.linksIn || 0))
436
+ .map(p => pathOnly(p.url))
437
+ .filter(Boolean);
438
+ const top = Object.entries(traffic)
439
+ .sort((a, b) => b[1].clicks - a[1].clicks || b[1].impressions - a[1].impressions)
440
+ .map(([p]) => p);
441
+ let picked = [...new Set(["/", ...crawled.slice(0, 10), ...top])]
442
+ .slice(0, 20)
443
+ .map(p => urls[p] || new URL(p, origin).href);
444
+ if (inspect?.length) {
445
+ const on = [],
446
+ off = [];
447
+ for (const u of inspect) {
448
+ let x;
449
+ try {
450
+ x = new URL(u, origin);
451
+ } catch {}
452
+ (x && /^https?:$/.test(x.protocol) && inProperty(prop, x) ? on : off).push(x?.href || u);
453
+ }
454
+ picked = [...new Set(on)];
455
+ if (off.length)
456
+ notes.push(
457
+ `${off.length} of the pages to inspect aren't in the Search Console property ${prop}, so they were skipped: ${off.slice(0, 10).join(", ")}.`,
458
+ );
459
+ if (picked.length > INSPECT_MAX)
460
+ notes.push(
461
+ `URL Inspection checked the first ${INSPECT_MAX} of ${picked.length} pages you listed. Google allows 2,000 a day per property (600 a minute), so run fetch again later with the rest.`,
462
+ );
463
+ }
464
+ const inspection = [];
465
+ const issues = (d, severity) => [
466
+ ...new Set(
467
+ (d.items || [])
468
+ .flatMap(i => i.issues || [])
469
+ .filter(i => i.severity === severity)
470
+ .map(i => i.issueMessage),
471
+ ),
472
+ ];
473
+ // Each page on its own, so one error loses only that page. A usage limit (429), a lost connection or a refused
474
+ // sign-in would fail every page after it, so those stop the run and keep what was read.
475
+ const toInspect = picked.slice(0, INSPECT_MAX),
476
+ failed = [];
477
+ for (const url of toInspect) {
478
+ let r;
479
+ try {
480
+ r =
481
+ (await g.call(`${E.inspection}/urlInspection/index:inspect`, { inspectionUrl: url, siteUrl: prop }))
482
+ .inspectionResult || {};
483
+ } catch (e) {
484
+ if (e.status === 429 || e instanceof Fail || e instanceof Refused) {
485
+ notes.push(
486
+ `${explain(e, "URL Inspection in Search Console", SC_API, who)} URL Inspection stopped after ${inspection.length + failed.length} of ${toInspect.length} pages; the ones it read are kept.`,
487
+ );
488
+ break;
489
+ }
490
+ failed.push(
491
+ `${url} (Google answered ${e.status || "with an error"}${/^HTTP \d+$/.test(e.message) ? "" : `: ${e.message}`})`,
492
+ );
493
+ continue;
494
+ }
495
+ const x = r.indexStatusResult || {},
496
+ rr = r.richResultsResult;
497
+ // referringUrls are pages linking to the URL, directly or indirectly; the first 10 are kept.
498
+ // https://developers.google.com/webmaster-tools/v1/urlInspection.index/UrlInspectionResult
499
+ inspection.push({
500
+ url,
501
+ verdict: x.verdict ?? null,
502
+ coverageState: x.coverageState ?? null,
503
+ indexingState: x.indexingState ?? null,
504
+ robotsTxtState: x.robotsTxtState ?? null,
505
+ pageFetchState: x.pageFetchState ?? null,
506
+ googleCanonical: x.googleCanonical ?? null,
507
+ userCanonical: x.userCanonical ?? null,
508
+ lastCrawlTime: x.lastCrawlTime ?? null,
509
+ crawledAs: x.crawledAs ?? null,
510
+ referringUrls: Array.isArray(x.referringUrls) ? x.referringUrls.slice(0, 10) : [],
511
+ link: r.inspectionResultLink ?? null,
512
+ richResults: rr
513
+ ? {
514
+ verdict: rr.verdict ?? null,
515
+ types: (rr.detectedItems || []).map(d => ({
516
+ type: d.richResultType,
517
+ items: (d.items || []).length,
518
+ errors: issues(d, "ERROR"),
519
+ warnings: issues(d, "WARNING"),
520
+ })),
521
+ }
522
+ : null,
523
+ });
524
+ }
525
+ if (failed.length)
526
+ notes.push(
527
+ `URL Inspection couldn't read ${failed.length} of ${toInspect.length} pages, so they're left out: ${failed.slice(0, 5).join(", ")}${failed.length > 5 ? ` and ${failed.length - 5} more` : ""}.`,
528
+ );
529
+ return inspection;
530
+ }
531
+
532
+ async function readSitemaps({ g, attempt, notes, prop, scBase }) {
533
+ const sitemaps = [];
534
+ await attempt("the sitemaps in Search Console", SC_API, async () => {
535
+ for (const x of (await g.call(`${scBase}/sitemaps`)).sitemap || [])
536
+ sitemaps.push({
537
+ path: x.path,
538
+ lastSubmitted: x.lastSubmitted ?? null,
539
+ lastDownloaded: x.lastDownloaded ?? null,
540
+ isPending: !!x.isPending,
541
+ errors: Number(x.errors || 0),
542
+ warnings: Number(x.warnings || 0),
543
+ });
544
+ if (!sitemaps.length)
545
+ notes.push(
546
+ `No sitemap is submitted in Search Console for ${prop}. Submit one under Indexing → Sitemaps so Google finds new and changed pages sooner.`,
547
+ );
548
+ });
549
+ return sitemaps;
550
+ }
551
+
552
+ // GA4: --ga4-property, else the one property whose web stream is this site (even when it's the only one).
553
+ async function readAnalytics({ g, E, attempt, notes, h, startDate, endDate }, scope, ga4Property) {
554
+ const analytics = {};
555
+ let gaProp = ga4Property ? String(ga4Property).replace(/^properties\//, "") : null,
556
+ gaRead = false;
557
+ if (!scope.includes(GA))
558
+ notes.push(
559
+ "Google Analytics wasn't included when you signed in, so there's no visit data. To add it, run node google.mjs connect again and leave the Google Analytics box ticked.",
560
+ );
561
+ else {
562
+ if (!gaProp)
563
+ await attempt("the Google Analytics property list", ADMIN_API, async () => {
564
+ const props = (
565
+ (await g.call(`${E.analyticsAdmin}/accountSummaries?pageSize=200`)).accountSummaries || []
566
+ ).flatMap(a => (a.propertySummaries || []).map(p => ({ id: p.property.split("/")[1], name: p.displayName })));
567
+ if (!props.length) {
568
+ notes.push(
569
+ "The connected account can't see any Google Analytics 4 property, so there's no visit data. Add it under " +
570
+ ADMIN_API.where +
571
+ ".",
572
+ );
573
+ return;
574
+ }
575
+ // Only the first 50 properties' web streams are checked; accounts with more pass --ga4-property.
576
+ const hostOf = u => {
577
+ try {
578
+ return bare(new URL(/^https?:/.test(u) ? u : "https://" + u).hostname);
579
+ } catch {
580
+ return null;
581
+ }
582
+ };
583
+ const matches = [],
584
+ name = p => `${p.name} (${p.id})`;
585
+ for (const p of props.slice(0, 50))
586
+ if (
587
+ ((await g.call(`${E.analyticsAdmin}/properties/${p.id}/dataStreams`)).dataStreams || []).some(
588
+ d => hostOf(d.webStreamData?.defaultUri || "") === bare(h),
589
+ )
590
+ )
591
+ matches.push(p);
592
+ if (matches.length === 1) gaProp = matches[0].id;
593
+ else if (props.length === 1)
594
+ notes.push(
595
+ `The only Google Analytics 4 property this account can see, ${name(props[0])}, has no web stream for ${h}, so its visits weren't used. If it is this site's property, run fetch again with --ga4-property ${props[0].id}.`,
596
+ );
597
+ else
598
+ notes.push(
599
+ `${matches.length ? "Several" : "None of the"} Google Analytics 4 properties ${matches.length ? "match" : "matches"} ${h}. Pick one with --ga4-property <id>: ${(matches.length ? matches : props).slice(0, 10).map(name).join(", ")}.`,
600
+ );
601
+ });
602
+ if (gaProp)
603
+ await attempt(`Google Analytics property ${gaProp}`, DATA_API, async () => {
604
+ const rep = await g.call(`${E.analyticsData}/properties/${gaProp}:runReport`, {
605
+ dateRanges: [{ startDate, endDate }],
606
+ dimensions: [{ name: "landingPage" }],
607
+ metrics: [{ name: "sessions" }, { name: "engagedSessions" }],
608
+ dimensionFilter: {
609
+ filter: {
610
+ fieldName: "sessionDefaultChannelGroup",
611
+ stringFilter: { matchType: "EXACT", value: "Organic Search" },
612
+ },
613
+ },
614
+ limit: 25000,
615
+ });
616
+ for (const r of rep.rows || []) {
617
+ const p = r.dimensionValues?.[0]?.value;
618
+ if (p && p !== "(not set)")
619
+ analytics[p] = { sessions: Number(r.metricValues[0].value), engaged: Number(r.metricValues[1].value) };
620
+ }
621
+ if (rep.rowCount > 25000)
622
+ notes.push(`Google Analytics has ${rep.rowCount} organic landing pages; only the top 25,000 are included.`);
623
+ gaRead = true;
624
+ });
625
+ }
626
+ return { analytics, gaProp, gaRead };
627
+ }
628
+
629
+ // Runs only after the landing pages were read: a refusal or a used-up quota there would only repeat here.
630
+ async function readAnalyticsDetail({ g, E, attempt, startDate, endDate }, gaProp, gaRead) {
631
+ let analyticsDetail = null;
632
+ if (gaRead)
633
+ await attempt(
634
+ `Google Analytics property ${gaProp} (users, days, devices, countries and AI assistants)`,
635
+ DATA_API,
636
+ async () => {
637
+ const rows = async (dimension, value = "Organic Search") =>
638
+ (
639
+ (
640
+ await g.call(`${E.analyticsData}/properties/${gaProp}:runReport`, {
641
+ dateRanges: [{ startDate, endDate }],
642
+ ...(dimension ? { dimensions: [{ name: dimension }] } : {}),
643
+ metrics: [{ name: "sessions" }, { name: "totalUsers" }],
644
+ dimensionFilter: {
645
+ filter: { fieldName: "sessionDefaultChannelGroup", stringFilter: { matchType: "EXACT", value } },
646
+ },
647
+ limit: 1000,
648
+ })
649
+ ).rows || []
650
+ ).map(r => [
651
+ r.dimensionValues?.[0]?.value,
652
+ Number(r.metricValues?.[0]?.value) || 0,
653
+ Number(r.metricValues?.[1]?.value) || 0,
654
+ ]);
655
+ const byName = (list, n = list.length) =>
656
+ Object.fromEntries(
657
+ list
658
+ .filter(([k, s]) => typeof k === "string" && k && k !== "(not set)" && s > 0)
659
+ .sort((a, b) => b[1] - a[1])
660
+ .slice(0, n)
661
+ .map(([k, sessions, users]) => [k, { sessions, users }]),
662
+ );
663
+ const [[, sessions = 0, users = 0] = []] = await rows();
664
+ const daily = Object.fromEntries(
665
+ (await rows("date"))
666
+ .filter(([d]) => /^\d{8}$/.test(d))
667
+ .sort()
668
+ .map(([d, s, u]) => [`${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6)}`, { sessions: s, users: u }]),
669
+ );
670
+ const byDevice = byName(await rows("deviceCategory")),
671
+ byCountry = byName(await rows("country"), 10);
672
+ // GA4's default channel group files ChatGPT, Gemini, Copilot and the like under "AI Assistant".
673
+ // https://support.google.com/analytics/answer/9756891
674
+ const ai = Object.entries(byName(await rows("sessionSource", "AI Assistant"), 10)).map(
675
+ ([k, v]) => /** @type {const} */ ([k, { sessions: v.sessions }]),
676
+ );
677
+ analyticsDetail = {
678
+ sessions,
679
+ users,
680
+ daily,
681
+ byDevice,
682
+ byCountry,
683
+ aiAssistant: { sessions: ai.reduce((s, [, v]) => s + v.sessions, 0), bySource: Object.fromEntries(ai) },
684
+ };
685
+ },
686
+ );
687
+ return analyticsDetail;
688
+ }
689
+
690
+ // ---------- findings ----------
691
+ // These stay in this file: lib/score.mjs knownChecks() reads check names from scripts/ and scripts/checks/ only.
692
+ function googleFindings(notes, inspection, sitemaps, traffic, pageQueries, urls) {
693
+ const own = [];
694
+ const finding = (check, rule, severity, category, title, why, fix, evidence) => {
695
+ if (!evidence.length) return;
696
+ own.push({
697
+ check,
698
+ rule,
699
+ severity,
700
+ category,
701
+ title,
702
+ what: foundOn(evidence.length, evidence[0]),
703
+ why,
704
+ fix,
705
+ count: evidence.length,
706
+ evidence,
707
+ source: "search-console",
708
+ status: "open",
709
+ });
710
+ };
711
+ // Only states where Google left the page out are findings. Others are notes: "URL is unknown to Google" is often a
712
+ // page that isn't live yet, "Page with redirect" a redirect doing its job.
713
+ const EXCLUDED =
714
+ /currently not indexed|noindex|blocked by robots\.txt|duplicate|soft 404|not found|server error|redirect error|blocked due to/i;
715
+ const outOfIndex = inspection.filter(i => i.verdict === "FAIL" || i.verdict === "NEUTRAL"),
716
+ other = outOfIndex.filter(i => !EXCLUDED.test(i.coverageState || ""));
717
+ if (other.length)
718
+ notes.push(
719
+ `URL Inspection: ${other.length} inspected page(s) aren't in Google's index for a reason that usually isn't a problem: ${other
720
+ .slice(0, 10)
721
+ .map(i => `${i.url} (${i.coverageState || "no reason given"})`)
722
+ .join(
723
+ ", ",
724
+ )}. "URL is unknown to Google" means Google hasn't found the page yet: if it's live, link to it and list it in the sitemap. "Page with redirect" means Google indexes the redirect's target instead.`,
725
+ );
726
+ const notIndexed = outOfIndex
727
+ .filter(i => !other.includes(i))
728
+ .map(i => ({
729
+ url: i.url,
730
+ detail: `${i.coverageState}${i.lastCrawlTime ? `, last crawled ${i.lastCrawlTime.slice(0, 10)}` : ""}`,
731
+ }));
732
+ finding(
733
+ "gsc-not-indexed",
734
+ "CRAWL-02",
735
+ "high",
736
+ "Crawling & indexing",
737
+ `${notIndexed.length} key page(s) aren't in Google's index`,
738
+ "Search Console's URL Inspection says Google hasn't indexed these pages, so they can't appear in search at all.",
739
+ "Open each page in Search Console's URL Inspection to see the reason. Fix what it names (a noindex, a robots.txt block, a redirect, thin or duplicate content), link to the page from related pages, then click Request indexing.",
740
+ notIndexed,
741
+ );
742
+ const canon = inspection
743
+ .filter(i => i.googleCanonical && i.userCanonical && i.googleCanonical !== i.userCanonical)
744
+ .map(i => ({ url: i.url, detail: `Google chose ${i.googleCanonical}, the page declares ${i.userCanonical}` }));
745
+ finding(
746
+ "gsc-canonical-differs",
747
+ "URL-04",
748
+ "medium",
749
+ "URLs & canonicals",
750
+ `${canon.length} page(s) where Google picked a different canonical than the page declares`,
751
+ "Google ranks the URL it picked instead, so links and signals collect there and the declared page may not show.",
752
+ "Make the canonical tag, internal links, the sitemap and redirects all point at the same URL. If the two pages are near-duplicates, make them clearly different or merge them.",
753
+ canon,
754
+ );
755
+ const broken = sitemaps
756
+ .filter(x => x.errors > 0)
757
+ .map(x => ({
758
+ url: x.path,
759
+ detail: `${x.errors} errors, ${x.warnings} warnings${x.lastDownloaded ? `, last read ${x.lastDownloaded.slice(0, 10)}` : ""}`,
760
+ }));
761
+ finding(
762
+ "gsc-sitemap-errors",
763
+ "MAP-01",
764
+ "medium",
765
+ "Sitemaps & robots",
766
+ `${broken.length} submitted sitemap(s) have errors in Search Console`,
767
+ "Search Console couldn't read all of these sitemaps, so Google may miss new pages or keep old ones.",
768
+ "Open Search Console → Indexing → Sitemaps and click each sitemap to see the error. Fix the file (valid XML, full URLs on this site, at most 50,000 URLs and 50 MB), then resubmit it.",
769
+ broken,
770
+ );
771
+ // Warnings only make a rich result plainer; Google shows nothing for an item with an error.
772
+ const rich = inspection.flatMap(i =>
773
+ (i.richResults?.types || [])
774
+ .filter(t => t.errors.length)
775
+ .map(t => ({ url: i.url, detail: `${t.type}: ${t.errors.join("; ")}` })),
776
+ );
777
+ finding(
778
+ "gsc-rich-result-errors",
779
+ "SCHEMA-08",
780
+ "medium",
781
+ "Structured data",
782
+ `${rich.length} rich result(s) on key pages have errors in Google's URL Inspection`,
783
+ "Google doesn't show a rich result (stars, prices, breadcrumbs and the like) for an item with an error, so these pages show as plain results.",
784
+ "Open each page in Search Console's URL Inspection, or Google's Rich Results Test, to see where the error is. Fix the markup in the template, then click Request indexing.",
785
+ rich,
786
+ );
787
+ return [...gscFindings(traffic, pageQueries, urls), ...own].map((f, i) => ({
788
+ ...f,
789
+ id: "G-" + String(i + 1).padStart(3, "0"),
790
+ }));
791
+ }
792
+
793
+ // Google's documented logging problems in this period or the one it's compared with (Discover's only for Discover).
794
+ function anomalyNotes(notes, trafficChange, searchTypes, startDate, endDate, prevStart) {
795
+ const anomalies = [
796
+ ...anomaliesIn(trafficChange ? prevStart : startDate, endDate),
797
+ ...(searchTypes.discover ? anomaliesIn(startDate, endDate, "discover") : []),
798
+ ];
799
+ for (const a of anomalies)
800
+ notes.push(anomalyNote(a, `the period read${trafficChange && !a.type ? " or the one it's compared with" : ""}`));
801
+ return anomalies;
802
+ }
803
+
804
+ // ---------- connect ----------
805
+ const SHARED_MISSING = `google: Sign in with Google isn't set up yet in this copy of SEO Supervisor (the project's shared Google sign-in hasn't been added).
806
+ You can set it up yourself instead, in about 10 minutes:
807
+ 1. Run: node google.mjs guide
808
+ 2. Follow its steps to make your own Google sign-in file.
809
+ 3. Run: node google.mjs connect --client-file <the file you downloaded>`;
810
+
811
+ function openBrowser(url) {
812
+ // cmd reads & as a command separator, so it's escaped; the empty "" is start's window title.
813
+ const [cmd, argv] =
814
+ process.platform === "win32"
815
+ ? ["cmd", ["/c", "start", "", url.replace(/&/g, "^&")]]
816
+ : [process.platform === "darwin" ? "open" : "xdg-open", [url]];
817
+ try {
818
+ spawn(cmd, argv, { stdio: "ignore", detached: true, windowsHide: true })
819
+ .on("error", () => {})
820
+ .unref();
821
+ } catch {} // the link is printed too
822
+ }
823
+
824
+ // Answers Google's redirect to the loopback address; ignores requests whose state doesn't match.
825
+ const waitForCode = (server, state, cmd) =>
826
+ new Promise((ok, no) => {
827
+ const timer = setTimeout(
828
+ () =>
829
+ no(
830
+ new Fail(
831
+ `google: no sign-in within 5 minutes, so nothing was saved. Run node google.mjs ${cmd} again when you're ready.`,
832
+ ),
833
+ ),
834
+ 5 * 60000,
835
+ );
836
+ server.on("request", (req, res) => {
837
+ const page = (status, text) =>
838
+ res
839
+ .writeHead(status, { "content-type": "text/html; charset=utf-8", connection: "close" })
840
+ .end(
841
+ `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>SEO Supervisor</title><body style="font:18px/1.5 system-ui,sans-serif;max-width:32em;margin:15vh auto;padding:0 16px"><p>${text}</p>`,
842
+ );
843
+ let q;
844
+ try {
845
+ q = new URL(req.url, "http://127.0.0.1").searchParams;
846
+ } catch {
847
+ return page(400, "That address isn't valid.");
848
+ }
849
+ if (!q.has("code") && !q.has("error")) return page(404, "Nothing here.");
850
+ if (q.get("state") !== state)
851
+ return page(
852
+ 400,
853
+ `This sign-in doesn't match the one the terminal started. Go back to the terminal and run ${cmd} again.`,
854
+ );
855
+ clearTimeout(timer);
856
+ if (q.has("error")) {
857
+ page(200, "Sign-in was cancelled. You can close this tab.");
858
+ no(
859
+ new Fail(
860
+ `google: sign-in didn't finish (${q.get("error")}), so nothing was saved. Run node google.mjs ${cmd} to try again.`,
861
+ ),
862
+ );
863
+ return;
864
+ }
865
+ page(200, "<b>Signed in.</b> You can close this tab and go back to the terminal.");
866
+ ok(q.get("code"));
867
+ });
868
+ });
869
+
870
+ // A browser on another computer can't reach this machine's 127.0.0.1, so the address it ended on is pasted here. PKCE
871
+ // and the state check apply as with the loopback redirect.
872
+ // https://developers.google.com/identity/protocols/oauth2/native-app
873
+ async function pastedCode(state, redirect, cmd) {
874
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
875
+ const closed = new Promise(ok => rl.once("close", () => ok(null)));
876
+ let line;
877
+ try {
878
+ line = await Promise.race([
879
+ rl.question("Copy that whole address from the browser's address bar and paste it here: ", {
880
+ signal: AbortSignal.timeout(5 * 60000),
881
+ }),
882
+ closed,
883
+ ]);
884
+ } catch {
885
+ fail(
886
+ `google: no address was pasted within 5 minutes, so nothing was saved. Run node google.mjs ${cmd} --paste again when you're ready.`,
887
+ );
888
+ } finally {
889
+ rl.close();
890
+ }
891
+ let q;
892
+ try {
893
+ const u = new URL(String(line ?? "").trim());
894
+ if (u.origin === new URL(redirect).origin) q = u.searchParams;
895
+ } catch {}
896
+ if (!q || (!q.has("code") && !q.has("error")))
897
+ fail(
898
+ `google: that isn't the address the browser ended on, which starts with ${redirect}/?state=. Nothing was saved. Run node google.mjs ${cmd} --paste again.`,
899
+ );
900
+ if (q.get("state") !== state)
901
+ fail(
902
+ `google: that address is from a different sign-in, so it doesn't match this one. Nothing was saved. Run node google.mjs ${cmd} --paste again.`,
903
+ );
904
+ if (q.has("error"))
905
+ fail(
906
+ `google: sign-in didn't finish (${q.get("error")}), so nothing was saved. Run node google.mjs ${cmd} --paste to try again.`,
907
+ );
908
+ return q.get("code");
909
+ }
910
+
911
+ const revoke = async (E, s) => {
912
+ const r = await fetch(E.revoke, {
913
+ method: "POST",
914
+ headers: FORM,
915
+ body: new URLSearchParams({ token: s.refresh_token || s.access_token }),
916
+ signal: AbortSignal.timeout(30000),
917
+ });
918
+ await r.text();
919
+ return r;
920
+ };
921
+ // Withdraws the sign-in being replaced, best effort. Not when it used the same client: Google withdraws the whole
922
+ // grant for that client and account, which would cancel the sign-in just made.
923
+ async function revokeReplaced(E, old, clientId) {
924
+ if (
925
+ !old ||
926
+ old.method === "service-account" ||
927
+ !(old.refresh_token || old.access_token) ||
928
+ old.client?.id === clientId
929
+ )
930
+ return;
931
+ try {
932
+ await revoke(E, old);
933
+ } catch {}
934
+ }
935
+ // The browser sign-in: loopback redirect, PKCE and a state check, then the code is traded for tokens.
936
+ // params: scope plus extra auth parameters; intro is printed before the link (after it with --print-url).
937
+ async function signIn(E, client, args, params, { cmd = "connect", intro = "" } = {}) {
938
+ const { verifier, challenge } = pkce(),
939
+ state = randomBytes(16).toString("base64url");
940
+ const server = createServer();
941
+ await /** @type {Promise<void>} */ (new Promise((ok, no) => server.once("error", no).listen(0, "127.0.0.1", ok)));
942
+ const redirect_uri = `http://127.0.0.1:${/** @type {import("node:net").AddressInfo} */ (server.address()).port}`;
943
+ // --paste: nothing listens, so the browser's redirect fails at once and its address can be copied (pastedCode).
944
+ const paste = args.paste === true;
945
+ if (paste) server.close();
946
+ const url = `${E.auth}?${new URLSearchParams({ client_id: client.id, redirect_uri, response_type: "code", code_challenge: challenge, code_challenge_method: "S256", state, access_type: "offline", prompt: "consent", ...params })}`;
947
+ // The link also goes to a file, for a caller running this in the background that can't see its output yet.
948
+ const pending = pendingFile();
949
+ let code;
950
+ try {
951
+ save(pending, url + "\n");
952
+ const text = paste
953
+ ? `${args["print-url"] === true ? url + "\n" : ""}${intro}google: open this link in a browser on any computer and sign in:\n\n ${url}\n\nThe link is also in ${pending} until signing in is done.\nAfter you allow access, the browser goes to an address that starts with ${redirect_uri} and shows an error page. That's expected.\n`
954
+ : `${args["print-url"] === true ? url + "\n" : ""}${intro}google: opening Google's sign-in page in your browser. If it doesn't open, copy this link into your browser:\n\n ${url}\n\nThe link is also in ${pending} until signing in is done.\nWaiting for you to finish signing in (up to 5 minutes)...\n`;
955
+ await new Promise(ok => process.stdout.write(text, ok)); // flushed before the wait, also into a pipe
956
+ if (args["no-browser"] !== true && !paste) openBrowser(url);
957
+ code = paste ? await pastedCode(state, redirect_uri, cmd) : await waitForCode(server, state, cmd);
958
+ } finally {
959
+ rmSync(pending, { force: true });
960
+ server.close();
961
+ setTimeout(() => server.closeAllConnections(), 1000).unref();
962
+ }
963
+ return tokenRequest(E, {
964
+ code,
965
+ client_id: client.id,
966
+ client_secret: client.secret,
967
+ redirect_uri,
968
+ grant_type: "authorization_code",
969
+ code_verifier: verifier,
970
+ });
971
+ }
972
+
973
+ // A key or client file inside the project could end up committed, and connect has already copied what it needs.
974
+ function leftInProject(f) {
975
+ const rel = relative(process.cwd(), resolve(f));
976
+ return rel && !isAbsolute(rel) && !/^\.\.([\\/]|$)/.test(rel)
977
+ ? `\nWarning: ${f} is inside this project and is no longer needed (its contents are saved in ${loginDir()}). Delete it, and never commit it.`
978
+ : "";
979
+ }
980
+
981
+ async function connect(args) {
982
+ const E = endpointsFrom(),
983
+ file = tokenFile(),
984
+ now = new Date().toISOString(),
985
+ old = load(file);
986
+ const keyFile = str(args["service-account"]),
987
+ clientFile = str(args["client-file"]);
988
+ const json = keyFile || clientFile ? readJson(keyFile || clientFile) : null;
989
+ if (json?.type === "service_account") {
990
+ if (!json.client_email || !json.private_key)
991
+ fail(
992
+ `google: ${keyFile || clientFile} is missing client_email or private_key. Download a new JSON key for the service account.`,
993
+ );
994
+ const t = await serviceAccountToken(E, json);
995
+ const saved = save(file, {
996
+ method: "service-account",
997
+ client_email: json.client_email,
998
+ private_key_id: json.private_key_id,
999
+ private_key: json.private_key,
1000
+ token_uri: json.token_uri,
1001
+ scope: SCOPES.join(" "),
1002
+ ...t,
1003
+ connected_at: now,
1004
+ });
1005
+ await revokeReplaced(E, old);
1006
+ console.log(
1007
+ `google: connected as the service account ${json.client_email}.\nIt sees the Search Console and GA4 properties where this email was added as a user.\nSaved to ${file} (${privacyOf(saved)}).${leftInProject(keyFile || clientFile)}`,
1008
+ );
1009
+ return 0;
1010
+ }
1011
+ if (keyFile)
1012
+ fail(
1013
+ `google: ${keyFile} isn't a service-account key. In Google Cloud open IAM & Admin → Service accounts → your account → Keys → Add key → JSON.`,
1014
+ );
1015
+ let client, method;
1016
+ if (clientFile) {
1017
+ const c = json.installed;
1018
+ if (!c?.client_id)
1019
+ fail(
1020
+ json.web
1021
+ ? `google: ${clientFile} is a "Web application" client. Signing in from the terminal needs a "Desktop app" client: create one (node google.mjs guide) and download its JSON.`
1022
+ : `google: ${clientFile} isn't a Google sign-in (OAuth client) file. Download it from your Desktop app client's page in Google Cloud.`,
1023
+ );
1024
+ // Google's sign-in for Desktop app clients needs the secret, so stop before the browser opens.
1025
+ if (!c.client_secret)
1026
+ fail(
1027
+ `google: ${clientFile} has no client secret, so Google would refuse the sign-in. Download it again from Google Cloud (Clients → your Desktop app client). If that download has no secret either, click Add secret on the same page and download the JSON straight away.`,
1028
+ );
1029
+ client = { id: c.client_id, secret: c.client_secret, file: resolve(clientFile) };
1030
+ method = "own-client";
1031
+ } else {
1032
+ // The env vars override the shared client; empty means none.
1033
+ const env = process.env;
1034
+ client = {
1035
+ id: env.SEO_GOOGLE_SHARED_CLIENT_ID ?? SHARED_CLIENT.id,
1036
+ secret: env.SEO_GOOGLE_SHARED_CLIENT_SECRET ?? SHARED_CLIENT.secret,
1037
+ };
1038
+ if (!client.id || !client.secret) fail(SHARED_MISSING);
1039
+ method = "shared";
1040
+ }
1041
+
1042
+ const t = await signIn(E, client, args, { scope: SCOPES.join(" ") });
1043
+ const scope = t.scope || SCOPES.join(" ");
1044
+ const saved = save(file, { method, client, ...t, scope, connected_at: now });
1045
+ await revokeReplaced(E, old, client.id);
1046
+ console.log(
1047
+ `google: connected. Search Console: ${scope.includes(SC) ? "yes" : "no (not allowed)"} · Google Analytics: ${scope.includes(GA) ? "yes" : "no (not allowed)"}.\nSaved to ${file} (${privacyOf(saved)}).${t.refresh_token ? "" : "\nGoogle didn't send a long-lived sign-in, so you'll need to connect again in about an hour."}${clientFile ? leftInProject(clientFile) : ""}\nNext: node google.mjs fetch --site https://your-site`,
1048
+ );
1049
+ return 0;
1050
+ }
1051
+
1052
+ async function status() {
1053
+ const file = tokenFile(),
1054
+ s = load(file);
1055
+ if (!s) {
1056
+ console.log(
1057
+ "google: Not connected. Run node google.mjs connect to sign in with Google, or node google.mjs guide to set it up yourself.",
1058
+ );
1059
+ return 1;
1060
+ }
1061
+ const scope = s.scope || "";
1062
+ const how =
1063
+ s.method === "service-account"
1064
+ ? `a service account (${s.client_email})`
1065
+ : s.method === "own-client"
1066
+ ? `your own Google Cloud client (${s.client.id}${s.client.file ? `, from ${s.client.file}` : ""})`
1067
+ : `Sign in with Google (SEO Supervisor's shared sign-in, ${s.client.id})`;
1068
+ const lines = [
1069
+ `Connected with: ${how}`,
1070
+ `Connected on: ${(s.connected_at || "unknown").slice(0, 10)}`,
1071
+ `Access: ${[scope.includes(SC) && "Search Console (read-only)", scope.includes(GA) && "Google Analytics (read-only)"].filter(Boolean).join(", ") || "none"}`,
1072
+ `Sitemap submitting: ${has(scope, WM) ? "allowed" : "not allowed (submit-sitemap --yes asks for it when you submit one)"}`,
1073
+ `Access token: ${s.expires_at > Date.now() ? `valid until ${new Date(s.expires_at).toISOString().slice(0, 16).replace("T", " ")} UTC` : "expired"}${s.refresh_token || s.private_key ? " (renews automatically)" : " (run connect again)"}`,
1074
+ `Saved in: ${file}`,
1075
+ ];
1076
+ try {
1077
+ const g = session();
1078
+ lines.push(
1079
+ `Search Console properties: ${((await g.call(`${g.E.searchConsole}/sites`)).siteEntry || []).map(x => x.siteUrl).join(", ") || "none"}`,
1080
+ );
1081
+ if (scope.includes(GA)) {
1082
+ try {
1083
+ lines.push(
1084
+ `Google Analytics 4 properties: ${((await g.call(`${g.E.analyticsAdmin}/accountSummaries?pageSize=200`)).accountSummaries || []).flatMap(a => (a.propertySummaries || []).map(p => `${p.displayName} (${p.property.split("/")[1]})`)).join(", ") || "none"}`,
1085
+ );
1086
+ } catch (e) {
1087
+ lines.push(
1088
+ `Google Analytics 4 properties: couldn't list them. ${explain(e, "the Google Analytics property list", ADMIN_API)}`,
1089
+ );
1090
+ }
1091
+ }
1092
+ } catch (e) {
1093
+ lines.push(
1094
+ `Search Console properties: couldn't list them. ${explain(e, "the Search Console property list", SC_API)}`,
1095
+ );
1096
+ }
1097
+ console.log(lines.join("\n"));
1098
+ return 0;
1099
+ }
1100
+
1101
+ async function disconnect() {
1102
+ const file = tokenFile(),
1103
+ s = load(file);
1104
+ if (!s && existsSync(file)) {
1105
+ rmSync(file, { force: true });
1106
+ console.log(
1107
+ `google: the saved sign-in (${file}) couldn't be read, so it was deleted. To withdraw access at Google too, open https://myaccount.google.com/connections.`,
1108
+ );
1109
+ return 0;
1110
+ }
1111
+ if (!s) {
1112
+ console.log("google: not connected, nothing to remove.");
1113
+ return 0;
1114
+ }
1115
+ let revoked = "";
1116
+ if (s.method !== "service-account") {
1117
+ try {
1118
+ const r = await revoke(endpointsFrom(), s);
1119
+ revoked = r.ok
1120
+ ? "Google has withdrawn SEO Supervisor's access."
1121
+ : `Google didn't confirm withdrawing access (${r.status}); it may have been withdrawn already.`;
1122
+ } catch (e) {
1123
+ revoked = `Couldn't reach Google to withdraw access (${e.cause?.code || e.message}).`;
1124
+ }
1125
+ }
1126
+ rmSync(file, { force: true });
1127
+ console.log(
1128
+ [
1129
+ `google: disconnected. Removed the saved sign-in (${file}).`,
1130
+ revoked,
1131
+ s.method === "service-account"
1132
+ ? `The service account ${s.client_email} keeps the access you gave it: remove it under ${SC_API.where} and ${ADMIN_API.where}, or delete its key in Google Cloud.`
1133
+ : "You can check or remove access any time at https://myaccount.google.com/connections.",
1134
+ ]
1135
+ .filter(Boolean)
1136
+ .join("\n"),
1137
+ );
1138
+ return 0;
1139
+ }
1140
+
1141
+ // ---------- submit-sitemap ----------
1142
+ // The only write, and only with --yes. The read/write scope is asked for here by incremental sign-in, never at connect.
1143
+ function submitError(e, prop, who = "The connected Google account") {
1144
+ if (e.status === 403 && !API_OFF.test(e.message))
1145
+ return `${who} isn't an owner or full user of ${prop}, so Google refused the sitemap. Submitting a sitemap needs Owner or Full permission (Restricted users can only read): ask the owner to change it under ${SC_API.where}, or connect with an owner's account.`;
1146
+ if (e.status === 404)
1147
+ return `Google couldn't find ${prop} for the connected account (404), so nothing was submitted. Check that --site is a property in Search Console, or connect with the Google account that has it.`;
1148
+ return explain(e, `${prop} in Search Console`, SC_API, who);
1149
+ }
1150
+
1151
+ async function submitSitemap(args) {
1152
+ if (!str(args.site) || !str(args.sitemap)) throw new Fail(USAGE);
1153
+ const origin = httpUrl(args.site, "--site must be the site's address", "https://www.example.com");
1154
+ const map = httpUrl(
1155
+ args.sitemap,
1156
+ "--sitemap must be the sitemap's full address",
1157
+ "https://www.example.com/sitemap.xml",
1158
+ );
1159
+ let g = session();
1160
+ const s = g.store(),
1161
+ who = whoOf(s),
1162
+ prop = await pickProperty(g, origin, who);
1163
+ const d = prop.startsWith("sc-domain:") && prop.slice(10);
1164
+ if (!inProperty(prop, map))
1165
+ fail(
1166
+ `google: ${map.href} isn't on ${prop}, so Search Console would refuse it. Submit a sitemap ${d ? `on ${d} or one of its subdomains` : `whose address starts with ${prop}`}, or pass the --site it belongs to.`,
1167
+ );
1168
+ const allowed = has(s.scope, WM);
1169
+ if (args.yes !== true) {
1170
+ console.log(
1171
+ [
1172
+ `google: dry run, nothing was sent.`,
1173
+ `Would submit: ${map.href}`,
1174
+ `To the Search Console property: ${prop}`,
1175
+ !allowed &&
1176
+ s.method !== "service-account" &&
1177
+ "First, Google shows a second short screen asking to allow submitting sitemaps (one extra permission).",
1178
+ "To submit it, run the same command with --yes.",
1179
+ ]
1180
+ .filter(Boolean)
1181
+ .join("\n"),
1182
+ );
1183
+ return 0;
1184
+ }
1185
+ if (!allowed) {
1186
+ const scope = `${s.scope || SCOPES.join(" ")} ${WM}`;
1187
+ let t;
1188
+ if (s.method === "service-account") t = { ...(await serviceAccountToken(g.E, { ...s, scope })), scope };
1189
+ else {
1190
+ t = await signIn(
1191
+ g.E,
1192
+ s.client,
1193
+ args,
1194
+ { scope: WM, include_granted_scopes: "true" },
1195
+ {
1196
+ cmd: "submit-sitemap",
1197
+ intro:
1198
+ "google: submitting a sitemap needs one more permission. Google will ask you to allow SEO Supervisor to submit sitemaps; everything else stays read-only.\n",
1199
+ },
1200
+ );
1201
+ t.scope ||= scope;
1202
+ }
1203
+ save(tokenFile(), { ...s, ...t });
1204
+ if (!has(t.scope, WM))
1205
+ fail(
1206
+ "google: submitting sitemaps wasn't allowed on Google's screen, so nothing was sent. Run the command again and allow it.",
1207
+ );
1208
+ g = session();
1209
+ }
1210
+ const feed = `${g.E.searchConsole}/sites/${encodeURIComponent(prop)}/sitemaps/${encodeURIComponent(map.href)}`;
1211
+ try {
1212
+ await g.call(feed, null, "PUT");
1213
+ } catch (e) {
1214
+ throw refused(e, submitError(e, prop, who));
1215
+ }
1216
+ const lines = [`google: submitted ${map.href} to ${prop}.`];
1217
+ try {
1218
+ const x = await g.call(feed),
1219
+ when = t => t && `${t.slice(0, 16).replace("T", " ")} UTC`;
1220
+ const n = (k, word) => `${Number(x[k] || 0)} ${word}${Number(x[k] || 0) === 1 ? "" : "s"}`;
1221
+ lines.push(
1222
+ `Last submitted: ${when(x.lastSubmitted) || "not shown yet"}`,
1223
+ `Status: ${x.isPending ? "waiting for Google to read it" : x.lastDownloaded ? `last read by Google ${when(x.lastDownloaded)}` : "not read by Google yet"}.`,
1224
+ Number(x.errors || 0) || Number(x.warnings || 0)
1225
+ ? `${n("errors", "error")}, ${n("warnings", "warning")}: open Search Console → Indexing → Sitemaps to see them.`
1226
+ : "No errors or warnings so far.",
1227
+ );
1228
+ } catch (e) {
1229
+ lines.push(
1230
+ `Google didn't show the sitemap's status yet (${explain(e, "the sitemap", SC_API, who)}). Check Search Console → Indexing → Sitemaps in a few minutes.`,
1231
+ );
1232
+ }
1233
+ console.log(lines.join("\n"));
1234
+ return 0;
1235
+ }
1236
+
1237
+ const GUIDE = `Set up Google access yourself (about 10 minutes). Pick one.
1238
+
1239
+ A. Your own sign-in (best for most people)
1240
+ 1. Open https://console.cloud.google.com/auth/overview/personal and sign in with the Google account that sees your site in Search Console.
1241
+ 2. Follow the steps to create a project and a client. When asked for the application type, choose "Desktop app".
1242
+ 3. Turn on three APIs. Open https://console.cloud.google.com/apis/library, search for each one and click Enable:
1243
+ "Google Search Console API", "Google Analytics Data API" and "Google Analytics Admin API".
1244
+ 4. On the client's page, click "Download JSON". Keep the file private.
1245
+ 5. Run: node google.mjs connect --client-file <the downloaded file>
1246
+ Your browser opens. Sign in and allow read-only access. Then delete the downloaded file: connect keeps what it needs.
1247
+ If you made the client through the regular Google Cloud setup instead of the personal page in step 1, also open
1248
+ Google Auth Platform → Audience → Publish app, so sign-ins don't expire after 7 days.
1249
+
1250
+ B. A service account (for servers and CI; no browser)
1251
+ 1. In Google Cloud, open IAM & Admin → Service accounts and create one. Then open it → Keys → Add key → JSON. Keep the file private.
1252
+ 2. Turn on the same three APIs as in A, step 3.
1253
+ 3. In Search Console, open Settings → Users and permissions → Add user, and add the service account's email (it ends in .iam.gserviceaccount.com) with Restricted permission
1254
+ (Full, if you want it to submit sitemaps with submit-sitemap).
1255
+ 4. In Google Analytics, open Admin → Property access management → Add users, and add the same email as a Viewer.
1256
+ 5. Run: node google.mjs connect --service-account <the key file>
1257
+
1258
+ Either way, access is read-only. Submitting a sitemap (submit-sitemap --yes) asks for that one extra permission
1259
+ when you use it. Undo it all any time with: node google.mjs disconnect`;
1260
+
1261
+ async function fetchCli(args) {
1262
+ if (!str(args.site)) throw new Fail(USAGE);
1263
+ const crawlPath = str(args.crawl) || "seo-audit/seo-crawl.json";
1264
+ let crawl = null;
1265
+ if (existsSync(crawlPath))
1266
+ try {
1267
+ crawl = JSON.parse(readFileSync(crawlPath, "utf8"));
1268
+ } catch {}
1269
+ // --inspect: a file with one URL or path per line (# starts a comment); --inspect-urls: a comma-separated list.
1270
+ const inspect = [];
1271
+ if (str(args.inspect))
1272
+ try {
1273
+ inspect.push(...readFileSync(args.inspect, "utf8").split(/\r?\n/));
1274
+ } catch (e) {
1275
+ fail(`google: can't read ${args.inspect} (${e.code || e.message}).`);
1276
+ }
1277
+ if (str(args["inspect-urls"])) inspect.push(...args["inspect-urls"].split(","));
1278
+ const out = resolve(str(args.out) || "seo-audit/google.json");
1279
+ const r = await fetchGoogle({
1280
+ site: args.site,
1281
+ days: args.days ?? 90,
1282
+ ga4Property: str(args["ga4-property"]),
1283
+ crawl,
1284
+ inspect: inspect.map(s => s.trim()).filter(s => s && !s.startsWith("#")),
1285
+ });
1286
+ mkdirSync(dirname(out), { recursive: true });
1287
+ writeFileSync(out, JSON.stringify(r, null, 2));
1288
+ console.log(
1289
+ `google: ${r.properties.searchConsole}${r.properties.analytics ? ` and GA4 property ${r.properties.analytics}` : ""} · ${Object.keys(r.traffic).length} pages, ${r.queries.length} queries, ${r.inspection.length} URLs inspected, ${r.sitemaps.length} sitemaps, ${Object.keys(r.analytics).length} GA4 landing pages, ${r.findings.length} findings · wrote ${out}`,
1290
+ );
1291
+ for (const n of r.notes) console.log("note: " + n);
1292
+ return 0;
1293
+ }
1294
+
1295
+ const str = v => (typeof v === "string" ? v : null);
1296
+ const USAGE = `usage: node google.mjs connect [--client-file client_secret.json | --service-account key.json] [--no-browser] [--print-url] [--paste]
1297
+ node google.mjs guide | status | disconnect
1298
+ node google.mjs fetch --site https://www.example.com [--days 90] [--ga4-property <id>] [--crawl seo-audit/seo-crawl.json] [--inspect pages.txt] [--inspect-urls /a/,/b/] [--out seo-audit/google.json]
1299
+ node google.mjs submit-sitemap --site https://www.example.com --sitemap https://www.example.com/sitemap.xml [--yes] [--no-browser] [--print-url]`;
1300
+
1301
+ const COMMANDS = {
1302
+ connect,
1303
+ status,
1304
+ disconnect,
1305
+ fetch: fetchCli,
1306
+ "submit-sitemap": submitSitemap,
1307
+ guide: async () => {
1308
+ console.log(GUIDE);
1309
+ return 0;
1310
+ },
1311
+ };
1312
+ const FLAGS = [
1313
+ "client-file",
1314
+ "service-account",
1315
+ "site",
1316
+ "days",
1317
+ "ga4-property",
1318
+ "crawl",
1319
+ "inspect",
1320
+ "inspect-urls",
1321
+ "out",
1322
+ "sitemap",
1323
+ ];
1324
+ // Exit codes as in connect-keys.mjs: 1 when Google refuses or can't be reached, or status finds nothing connected;
1325
+ // 2 on bad input or no usable sign-in.
1326
+ if (isMain(import.meta.url)) {
1327
+ warnProxy(); // stderr: connect --print-url keeps the link as stdout's first line
1328
+ const [cmd, ...rest] = process.argv.slice(2);
1329
+ // A word that isn't an option stops it, so a stray "yes" never counts as --yes.
1330
+ await runMain(() => {
1331
+ if (!Object.hasOwn(COMMANDS, cmd)) throw new Fail(USAGE, isHelp(cmd) ? 0 : 2);
1332
+ return COMMANDS[cmd](
1333
+ parseArgs(rest, {
1334
+ flags: FLAGS,
1335
+ booleans: ["no-browser", "print-url", "paste", "yes"],
1336
+ positionals: 0,
1337
+ usage: USAGE,
1338
+ }),
1339
+ );
1340
+ });
1341
+ }