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,151 @@
1
+ // @ts-check
2
+ // Read-only Search Console access with the saved sign-in. It loads only session.mjs, none of the sign-in flow
3
+ // (browser, local server, prompts).
4
+ import { SC, SCOPES, Fail, Refused, fail, session, whoOf, explain } from "./session.mjs";
5
+
6
+ export { Fail, Refused };
7
+ export const SC_API = { name: "Google Search Console API", where: "Search Console → Settings → Users and permissions" };
8
+ // Logging problems Google lists, so a change they caused isn't read as real. type limits one to that search type.
9
+ // Add new ones from the same page.
10
+ const DISCOVER_LOSS = "Discover clicks and impressions were under-counted";
11
+ const ANOMALIES = [
12
+ {
13
+ from: "2025-05-13",
14
+ to: "2026-04-27",
15
+ what: "impressions weren't counted accurately, so CTR and average position were off too (clicks weren't affected)",
16
+ },
17
+ { from: "2026-05-07", to: "2026-05-08", type: "discover", what: DISCOVER_LOSS },
18
+ { from: "2026-05-21", to: "2026-05-21", type: "discover", what: DISCOVER_LOSS },
19
+ { from: "2026-06-24", to: "2026-06-24", type: "discover", what: DISCOVER_LOSS },
20
+ { from: "2026-08-13", to: "2026-08-13", type: "discover", what: DISCOVER_LOSS },
21
+ ].map(a => ({ ...a, url: "https://support.google.com/webmasters/answer/6211453" }));
22
+ export const anomaliesIn = (from, to, type) => ANOMALIES.filter(a => a.type === type && a.from <= to && a.to >= from);
23
+ // Shared by fetch, change-check and deploy-check. span names the dates read, e.g. "the dates compared".
24
+ export const anomalyNote = (a, span) =>
25
+ `Google's "Data anomalies in Search Console" page says that ${a.from === a.to ? `on ${a.from}` : `from ${a.from} to ${a.to}`} ${a.what}. This overlaps ${span}, so a change in those numbers may not be real: ${a.url}`;
26
+
27
+ export const httpUrl = (u, what, eg) => {
28
+ let x;
29
+ try {
30
+ x = new URL(u);
31
+ } catch {}
32
+ if (!x || !/^https?:$/.test(x.protocol)) fail(`google: ${what}, like ${eg} (got ${u}).`);
33
+ return x;
34
+ };
35
+
36
+ // Wraps a refused call as Refused with plain words; a Fail (no usable sign-in) passes through.
37
+ export const refused = (e, words) => (e instanceof Fail ? e : new Refused(words));
38
+
39
+ // The property: a domain property covering the host, else the longest URL-prefix property the site sits under.
40
+ export async function pickProperty(g, origin, who) {
41
+ let sites;
42
+ try {
43
+ sites = ((await g.call(`${g.E.searchConsole}/sites`)).siteEntry || []).filter(
44
+ x => x.permissionLevel !== "siteUnverifiedUser",
45
+ );
46
+ } catch (e) {
47
+ throw refused(e, explain(e, "the list of Search Console properties", SC_API, who));
48
+ }
49
+ const h = origin.hostname,
50
+ href = origin.origin + origin.pathname;
51
+ const prop = (
52
+ sites.find(
53
+ x => x.siteUrl.startsWith("sc-domain:") && (h === x.siteUrl.slice(10) || h.endsWith("." + x.siteUrl.slice(10))),
54
+ ) || sites.filter(x => href.startsWith(x.siteUrl)).sort((a, b) => b.siteUrl.length - a.siteUrl.length)[0]
55
+ )?.siteUrl;
56
+ if (!prop)
57
+ throw new Refused(
58
+ `${origin.origin} isn't in the Search Console properties this account can see (${sites.map(x => x.siteUrl).join(", ") || "it can't see any"}). Add and verify the site in Search Console, or connect with the Google account that has it.`,
59
+ );
60
+ return prop;
61
+ }
62
+ // Tracking parameters say where a click came from, not which page it was: the crawler's list (checks/coverage.mjs)
63
+ // plus srsltid, which Merchant Center auto-tagging adds to free product listing links.
64
+ export const TRACKING =
65
+ /^(utm_\w+|gclid|gbraid|wbraid|dclid|fbclid|msclkid|yclid|igshid|mc_cid|mc_eid|_gl|_ga|srsltid)$/i;
66
+ // A Search Console address as a path on the site's host, else null. www and apex count as one host, as in gsc-import.
67
+ // Tracking parameters are dropped so the row counts for the page itself; other parameters stay as written.
68
+ export const bare = x => x.replace(/^www\./, "");
69
+ export const pagePath = (u, host) => {
70
+ try {
71
+ const x = new URL(u);
72
+ if (bare(x.hostname) !== bare(host)) return null;
73
+ const parts = x.search.slice(1).split("&"),
74
+ kept = parts.filter(p => !TRACKING.test(p.split("=")[0]));
75
+ return x.pathname + (kept.length === parts.length ? x.search : kept.length ? "?" + kept.join("&") : "");
76
+ } catch {
77
+ return null;
78
+ }
79
+ };
80
+ // One key for /a and /a/, query kept: a crawled page and its Search Console row can differ there.
81
+ export const slashKey = p => p.replace(/^([^?]*[^/?])\/+(?=\?|$)/, "$1");
82
+ // Fails early when Search Console access wasn't granted at sign-in.
83
+ export function scSession(opts) {
84
+ const g = session(opts),
85
+ s = g.store(),
86
+ scope = s.scope || SCOPES.join(" ");
87
+ if (!scope.includes(SC))
88
+ fail(
89
+ "google: Search Console access wasn't granted when you signed in. Run node google.mjs connect again and leave the Search Console box ticked.",
90
+ );
91
+ return { g, scope, who: whoOf(s) };
92
+ }
93
+ // The site's property and a Search Analytics query on it for other scripts, with token renewal and plain errors.
94
+ /** @param {{ site?: string, home?: string, endpoints?: any }} [opts] */
95
+ export async function searchConsole({ site, home, endpoints } = {}) {
96
+ const origin = httpUrl(site, "--site must be the site's address", "https://www.example.com");
97
+ const { g, who } = scSession({ home, endpoints }),
98
+ prop = await pickProperty(g, origin, who);
99
+ return {
100
+ origin,
101
+ prop,
102
+ query: body => g.call(`${g.E.searchConsole}/sites/${encodeURIComponent(prop)}/searchAnalytics/query`, body),
103
+ explain: e => explain(e, `${prop} in Search Console`, SC_API, who),
104
+ };
105
+ }
106
+ // ---------- periods and rows ----------
107
+ // Search Console keeps the last 2-3 days provisional, so a period ends 3 days ago. The period before has the same
108
+ // length. Dates are UTC days.
109
+ export const daysAgo = n => new Date(Date.now() - n * 864e5).toISOString().slice(0, 10);
110
+ export const lastFinal = () => daysAgo(3);
111
+ export const periodOf = days => ({ endDate: lastFinal(), startDate: daysAgo(days + 2) });
112
+ export const periodBefore = days => ({ startDate: daysAgo(2 * days + 2), endDate: daysAgo(days + 3) });
113
+ // Validates --days the same way in every script. who is the script's name.
114
+ /** @param {unknown} v @param {string} who */
115
+ export const daysOf = (v, who, min = 1, max = 480, why = "Search Console keeps 16 months") => {
116
+ const n = typeof v === "number" || typeof v === "string" ? Number(v) : NaN;
117
+ return Number.isInteger(n) && n >= min && n <= max
118
+ ? n
119
+ : fail(
120
+ `${who}: --days must be a whole number from ${min} to ${max} (got ${v === true ? "no number" : v}). ${why}.`,
121
+ );
122
+ };
123
+ // The top 25,000 Search Analytics rows at most, pageSize per request. sa(body) queries the current period; dates
124
+ // replace it for the period before. A list cut at 25,000 is noted under label.
125
+ export async function readRows(
126
+ sa,
127
+ dimensions,
128
+ dates = {},
129
+ pageSize = 25000,
130
+ notes = [],
131
+ label = dates.startDate ? "the period before" : "this period",
132
+ ) {
133
+ const rows = [];
134
+ while (rows.length < 25000) {
135
+ const rowLimit = Math.min(pageSize, 25000 - rows.length),
136
+ got = (await sa({ ...dates, dimensions, rowLimit, startRow: rows.length })).rows || [];
137
+ rows.push(...got);
138
+ if (got.length < rowLimit) break;
139
+ }
140
+ if (rows.length >= 25000)
141
+ notes.push(
142
+ `Search Console has 25,000 or more ${{ page: "pages", query: "queries" }[dimensions.join()] || "page and query pairs"} for ${label}; only the top 25,000 were read, so the least-searched ones are left out.`,
143
+ );
144
+ return rows;
145
+ }
146
+
147
+ // A domain property covers its subdomains; a URL-prefix property only addresses that start with it.
148
+ export const inProperty = (prop, u) => {
149
+ const d = prop.startsWith("sc-domain:") && prop.slice(10);
150
+ return d ? u.hostname === d || u.hostname.endsWith("." + d) : u.href.startsWith(prop);
151
+ };
@@ -0,0 +1,167 @@
1
+ // @ts-check
2
+ // The saved Google sign-in and authorized calls. Signing in stays in google.mjs, so scripts that only read data never
3
+ // load a browser, local server or prompts.
4
+ import { sign } from "node:crypto";
5
+ import { readFileSync } from "node:fs";
6
+ import { Fail, Refused } from "../lib/cli.mjs";
7
+ import { retryAfter } from "../lib/http.mjs";
8
+ import { googleFile, writePrivate } from "../lib/settings-dir.mjs";
9
+
10
+ export const SC = "https://www.googleapis.com/auth/webmasters.readonly",
11
+ GA = "https://www.googleapis.com/auth/analytics.readonly";
12
+ export const SCOPES = [SC, GA];
13
+ // Each address can be overridden with SEO_GOOGLE_<NAME>_URL, e.g. SEO_GOOGLE_SEARCH_CONSOLE_URL.
14
+ const DEFAULTS = {
15
+ auth: "https://accounts.google.com/o/oauth2/v2/auth",
16
+ token: "https://oauth2.googleapis.com/token",
17
+ revoke: "https://oauth2.googleapis.com/revoke",
18
+ searchConsole: "https://www.googleapis.com/webmasters/v3",
19
+ inspection: "https://searchconsole.googleapis.com/v1",
20
+ analyticsAdmin: "https://analyticsadmin.googleapis.com/v1beta",
21
+ analyticsData: "https://analyticsdata.googleapis.com/v1beta",
22
+ };
23
+ export const endpointsFrom = (over = {}) =>
24
+ Object.fromEntries(
25
+ Object.entries(DEFAULTS).map(([k, v]) => [
26
+ k,
27
+ over[k] || process.env[`SEO_GOOGLE_${k.replace(/[A-Z]/g, c => "_" + c).toUpperCase()}_URL`] || v,
28
+ ]),
29
+ );
30
+ // Fail (exit 2): bad input or no usable sign-in; its message starts "google: ". Refused (exit 1): Google said no or
31
+ // couldn't be reached; runMain prefixes the script's name.
32
+ export { Fail, Refused };
33
+ export const fail = msg => {
34
+ throw new Fail(msg);
35
+ };
36
+ const sleep = ms => new Promise(ok => setTimeout(ok, ms));
37
+ export const FORM = { "content-type": "application/x-www-form-urlencoded" };
38
+
39
+ // ---------- the saved sign-in ----------
40
+ // In the settings folder, per client with SEO_SUPERVISOR_CLIENT (lib/settings-dir.mjs).
41
+ export const tokenFile = home => googleFile(process.env, home);
42
+ export const load = file => {
43
+ try {
44
+ return JSON.parse(readFileSync(file, "utf8"));
45
+ } catch {
46
+ return null;
47
+ }
48
+ };
49
+ // Renamed over the old file, so a crash never leaves half a sign-in, and readable by this user only where the system
50
+ // allows; { locked } says whether that held.
51
+ export const save = (file, data) => writePrivate(file, typeof data === "string" ? data : JSON.stringify(data, null, 2));
52
+
53
+ export async function tokenRequest(E, params) {
54
+ let r;
55
+ // A missing value (a client with no secret) is left out, never sent as "undefined".
56
+ const body = new URLSearchParams(Object.entries(params).filter(([, v]) => v != null && v !== ""));
57
+ try {
58
+ r = await fetch(E.token, { method: "POST", headers: FORM, body, signal: AbortSignal.timeout(30000) });
59
+ } catch (e) {
60
+ throw new Refused(
61
+ `couldn't reach Google's sign-in server (${e.cause?.code || e.message}). Check the internet connection and try again.`,
62
+ );
63
+ }
64
+ const j = /** @type {any} */ (await r.json().catch(() => ({})));
65
+ if (r.ok && j.access_token)
66
+ return {
67
+ access_token: j.access_token,
68
+ expires_at: Date.now() + (j.expires_in || 3600) * 1000,
69
+ ...(j.refresh_token ? { refresh_token: j.refresh_token } : {}),
70
+ ...(j.scope ? { scope: j.scope } : {}),
71
+ };
72
+ if (j.error === "invalid_grant")
73
+ throw new Refused(
74
+ `Google didn't accept the sign-in (${j.error_description || "invalid_grant"}). It may have been removed or expired: run node google.mjs connect again.`,
75
+ );
76
+ throw new Refused(
77
+ `Google's sign-in server answered ${r.status}${j.error ? ` ${j.error}` : ""}${j.error_description ? `: ${j.error_description}` : ""}.`,
78
+ );
79
+ }
80
+
81
+ // Service accounts sign their own RS256 JWT and trade it for an access token. There's no refresh token: a new JWT
82
+ // renews it, for the scopes saved with it.
83
+ // https://developers.google.com/identity/protocols/oauth2/service-account
84
+ function serviceAccountJwt(key) {
85
+ const iat = Math.floor(Date.now() / 1000),
86
+ b64 = o => Buffer.from(JSON.stringify(o)).toString("base64url");
87
+ const unsigned = `${b64({ alg: "RS256", typ: "JWT", ...(key.private_key_id ? { kid: key.private_key_id } : {}) })}.${b64({ iss: key.client_email, scope: key.scope || SCOPES.join(" "), aud: key.token_uri || DEFAULTS.token, iat, exp: iat + 3600 })}`;
88
+ return `${unsigned}.${sign("sha256", Buffer.from(unsigned), key.private_key).toString("base64url")}`;
89
+ }
90
+ export const serviceAccountToken = (E, key) =>
91
+ tokenRequest(E, { grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: serviceAccountJwt(key) });
92
+ function renew(E, s) {
93
+ if (s.method === "service-account") return serviceAccountToken(E, s);
94
+ if (!s.refresh_token) fail("google: the saved sign-in can't renew itself. Run node google.mjs connect again.");
95
+ return tokenRequest(E, {
96
+ grant_type: "refresh_token",
97
+ refresh_token: s.refresh_token,
98
+ client_id: s.client.id,
99
+ client_secret: s.client.secret,
100
+ });
101
+ }
102
+
103
+ // Authorized JSON calls: renews an expired token first, renews once more on a 401, retries a 429 once.
104
+ /** @param {{ home?: string, endpoints?: any }} [opts] */
105
+ export function session({ home, endpoints } = {}) {
106
+ const E = endpointsFrom(endpoints),
107
+ file = tokenFile(home);
108
+ let s = load(file);
109
+ if (!s)
110
+ fail(
111
+ "google: not connected to Google yet. Run node google.mjs connect (or node google.mjs guide to set it up yourself).",
112
+ );
113
+ const refresh = async () => {
114
+ s = { ...s, ...(await renew(E, s)) };
115
+ save(file, s);
116
+ };
117
+ async function call(url, body, method = body ? "POST" : "GET") {
118
+ let renewed = false,
119
+ retried = false;
120
+ for (;;) {
121
+ if (!s.access_token || Date.now() > s.expires_at - 60000) await refresh();
122
+ const r = await fetch(url, {
123
+ method,
124
+ headers: { authorization: `Bearer ${s.access_token}`, ...(body ? { "content-type": "application/json" } : {}) },
125
+ body: body && JSON.stringify(body),
126
+ signal: AbortSignal.timeout(60000),
127
+ }).catch(e => {
128
+ throw new Refused(
129
+ `couldn't reach Google (${e.cause?.code || e.message}). Check the internet connection and try again.`,
130
+ );
131
+ });
132
+ if (r.status === 401 && !renewed) {
133
+ renewed = true;
134
+ await r.text();
135
+ await refresh();
136
+ continue;
137
+ }
138
+ // Retry-After in seconds or as a date (lib/http.mjs); 2 s when it's missing or unreadable, 30 s at most.
139
+ if (r.status === 429 && !retried) {
140
+ retried = true;
141
+ await r.text();
142
+ await sleep(Math.min(retryAfter(r.headers.get("retry-after")) ?? 2000, 30000));
143
+ continue;
144
+ }
145
+ const j = /** @type {any} */ (await r.json().catch(() => ({})));
146
+ if (r.ok) return j;
147
+ throw Object.assign(new Error(j.error?.message || `HTTP ${r.status}`), { status: r.status });
148
+ }
149
+ }
150
+ return { E, call, store: () => s };
151
+ }
152
+
153
+ export const API_OFF = /has not been used|is disabled|SERVICE_DISABLED|accessNotConfigured/i;
154
+ export const whoOf = s => (s.method === "service-account" ? `The service account ${s.client_email}` : undefined);
155
+ // A plain sentence for a failed call: what went wrong and how to fix it.
156
+ export function explain(e, what, api, who = "The connected Google account") {
157
+ if (e instanceof Fail || e instanceof Refused) return e.message.replace(/^google: /, "");
158
+ if (e.status === 403 && API_OFF.test(e.message))
159
+ return `The ${api.name} is turned off in the Google Cloud project your sign-in uses, so ${what} couldn't be read. Turn it on at https://console.cloud.google.com/apis/library (search "${api.name}", click Enable), wait a minute, then try again.`;
160
+ if (e.status === 403)
161
+ return `${who} doesn't have access to ${what}. Ask the owner to add it under ${api.where}, or connect with an account that has access (node google.mjs disconnect, then connect).`;
162
+ if (e.status === 401) return `Google didn't accept the saved sign-in for ${what}. Run node google.mjs connect again.`;
163
+ if (e.status === 429)
164
+ return `Google said too many requests for ${what} (a usage limit). Try again in a few minutes, or tomorrow.`;
165
+ if (e.status === 404) return `Google couldn't find ${what} (${e.message}).`;
166
+ return `Google answered ${e.status || "with an error"} for ${what}: ${e.message}`;
167
+ }
@@ -0,0 +1,189 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ // Google ranking updates, and optionally Search Central blog posts, that overlap a period. Dates only: it never says an
4
+ // update caused a traffic change.
5
+ import { mkdirSync, writeFileSync } from "node:fs";
6
+ import { dirname, resolve } from "node:path";
7
+ import { isMain } from "./lib/is-main.mjs";
8
+ import { parseArgs } from "./lib/args.mjs";
9
+ import { Fail, runMain, warnProxy } from "./lib/cli.mjs";
10
+
11
+ // The Search Status Dashboard's history, in Google Cloud's status format.
12
+ export const FEED = "https://status.search.google.com/incidents.json";
13
+ // The feed holds the last 365 days only (its history pages go back further, as HTML), so an older period gets a note.
14
+ const FEED_DAYS = 365;
15
+ const ymd = t => {
16
+ const d = new Date(t);
17
+ return isNaN(d.getTime()) ? null : d.toISOString().slice(0, 10);
18
+ };
19
+
20
+ const isRanking = i =>
21
+ i?.service_name === "Ranking" ||
22
+ (Array.isArray(i?.affected_products) && i.affected_products.some(p => p?.title === "Ranking"));
23
+
24
+ /** Ranking incidents whose rollout overlaps from..to (inclusive dates), oldest first. */
25
+ export function rankingUpdates(incidents, { from, to, feed = FEED }) {
26
+ return incidents
27
+ .filter(isRanking)
28
+ .map(i => ({
29
+ name: String(i.external_desc || "").trim(),
30
+ start: ymd(i.begin),
31
+ end: i.end ? ymd(i.end) : null,
32
+ url: i.id ? new URL(`incidents/${encodeURIComponent(i.id)}`, feed).href : null,
33
+ }))
34
+ .filter(u => u.name && u.start && u.start <= to && (u.end ?? "9999-12-31") >= from)
35
+ .sort((a, b) => a.start.localeCompare(b.start));
36
+ }
37
+
38
+ // RSS 2.0 holding only the latest 10 posts, hence the note on older periods.
39
+ const BLOG = "https://developers.google.com/search/blog/feed.xml";
40
+ const XML_ENT = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
41
+ const unxml = s =>
42
+ s
43
+ .replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1")
44
+ .replace(/&(#x[\da-f]+|#\d+|\w+);/gi, (m, e) =>
45
+ e[0] === "#"
46
+ ? (n => (n <= 0x10ffff ? String.fromCodePoint(n) : m))(
47
+ e[1].toLowerCase() === "x" ? parseInt(e.slice(2), 16) : +e.slice(1),
48
+ )
49
+ : (XML_ENT[e] ?? m),
50
+ )
51
+ .trim(); // code points past U+10FFFF stay as written
52
+ const tag = (item, name) => unxml(item.match(new RegExp(`<${name}\\b[^>]*>([\\s\\S]*?)</${name}>`, "i"))?.[1] ?? "");
53
+ // Event posts (Search Central Live and its Deep Dives) are left out by title; every other post counts.
54
+ const EVENT = /\bSearch Central Live\b|\bDeep Dive\b/i;
55
+ const feedPosts = xml =>
56
+ [...String(xml).matchAll(/<item\b[^>]*>([\s\S]*?)<\/item>/gi)]
57
+ .map(m => ({ title: tag(m[1], "title"), date: ymd(tag(m[1], "pubDate")), url: tag(m[1], "link") }))
58
+ .filter(p => p.title && p.date)
59
+ .sort((a, b) => a.date.localeCompare(b.date));
60
+ /** Blog posts dated from..to (inclusive), events left out, oldest first. */
61
+ export const blogPosts = (xml, { from, to }) =>
62
+ feedPosts(xml).filter(p => p.date >= from && p.date <= to && !EVENT.test(p.title));
63
+
64
+ /** @type {(msg: string, code?: number) => never} */
65
+ const fail = (msg, code = 2) => {
66
+ throw new Fail("google-updates: " + msg, code);
67
+ };
68
+
69
+ const USAGE =
70
+ "usage: node google-updates.mjs [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--since YYYY-MM-DD] [--out seo-audit/google-updates.json] [--endpoint url] [--blog [url]] [--yes]";
71
+ async function main(argv) {
72
+ const args = parseArgs(argv, {
73
+ flags: ["from", "to", "since", "out", "endpoint", "blog"],
74
+ booleans: ["yes"],
75
+ positionals: 0,
76
+ usage: USAGE,
77
+ });
78
+ // A date, or the date part of a timestamp; "2026-02-30" isn't one.
79
+ const day = k => {
80
+ if (args[k] == null) return null;
81
+ const s = String(args[k]).slice(0, 10);
82
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(s) || ymd(s + "T00:00:00Z") !== s)
83
+ fail(`--${k} needs a date as YYYY-MM-DD (got ${args[k]}).`);
84
+ return s;
85
+ };
86
+ const today = ymd(Date.now()),
87
+ back = n => ymd(Date.now() - n * 864e5);
88
+ const to = day("to") || today,
89
+ from = day("from") || day("since") || back(90);
90
+ if (from > to) fail(`the period starts (${from}) after it ends (${to}); the start must come before the end.`);
91
+ // --endpoint, GOOGLE_STATUS_ENDPOINT and a URL after --blog point at the tests' feeds.
92
+ const feed = typeof args.endpoint === "string" ? args.endpoint : process.env.GOOGLE_STATUS_ENDPOINT || FEED;
93
+ const OUT = resolve(typeof args.out === "string" ? args.out : "seo-audit/google-updates.json");
94
+ const blog = args.blog ? (typeof args.blog === "string" ? args.blog : BLOG) : null;
95
+
96
+ if (!args.yes) {
97
+ console.log(
98
+ `google-updates: dry run, nothing fetched. With --yes it reads ${feed} (Google's public status feed: one plain GET, nothing about your site is sent)${blog ? ` and ${blog} (the Google Search Central blog's feed, the same way)` : ""} and lists Google's ranking updates${blog ? " and blog posts" : ""} from ${from} to ${to} in ${OUT}.`,
99
+ );
100
+ return 0;
101
+ }
102
+ let r, list;
103
+ try {
104
+ r = await fetch(feed, {
105
+ headers: { "user-agent": "seo-supervisor-google-updates" },
106
+ signal: AbortSignal.timeout(20000),
107
+ });
108
+ } catch (e) {
109
+ fail(`couldn't reach ${feed} (${e.cause?.code || e.message}). Nothing was written.`, 1);
110
+ }
111
+ if (!r.ok) fail(`${feed} returned ${r.status}. Nothing was written.`, 1);
112
+ try {
113
+ list = await r.json();
114
+ } catch {}
115
+ if (!Array.isArray(list)) fail(`${feed} isn't the list of incidents it used to be. Nothing was written.`, 1);
116
+ // Google announces several ranking updates a year, so a year of incidents with none marked Ranking means the labels
117
+ // changed, not a quiet year. Writing an empty list would make the report say none were announced.
118
+ if (list.length && !list.some(isRanking))
119
+ fail(
120
+ `none of the ${list.length} incidents in ${feed} is marked Ranking, so the feed's format may have changed. Nothing was written.`,
121
+ 1,
122
+ );
123
+
124
+ const updates = rankingUpdates(list, { from, to, feed });
125
+ const notes =
126
+ from < back(FEED_DAYS)
127
+ ? [`Google's feed covers the last 12 months, so updates before ${back(FEED_DAYS)} aren't listed.`]
128
+ : [];
129
+ // The blog is extra: when its feed fails, the ranking updates are still written, with a note instead of posts.
130
+ let posts = null;
131
+ if (blog) {
132
+ let xml = null,
133
+ why;
134
+ try {
135
+ const b = await fetch(blog, {
136
+ headers: { "user-agent": "seo-supervisor-google-updates" },
137
+ signal: AbortSignal.timeout(20000),
138
+ });
139
+ if (b.ok) xml = await b.text();
140
+ else why = `returned ${b.status}`;
141
+ } catch (e) {
142
+ why = `couldn't be reached (${e.cause?.code || e.message})`;
143
+ }
144
+ const all = xml == null ? [] : feedPosts(xml);
145
+ if (xml != null && !all.length) why = "had no posts in the format it used to have";
146
+ if (why) notes.push(`Google's Search Central blog's feed ${why}, so its posts aren't listed.`);
147
+ else {
148
+ posts = blogPosts(xml, { from, to });
149
+ const oldest = all[0].date,
150
+ day = new Date(oldest + "T00:00:00Z").toLocaleDateString("en-GB", {
151
+ day: "numeric",
152
+ month: "short",
153
+ year: "numeric",
154
+ timeZone: "UTC",
155
+ });
156
+ if (oldest > from)
157
+ notes.push(
158
+ `The Search Central blog's feed holds its latest posts only, back to ${day}, so earlier posts aren't listed.`,
159
+ );
160
+ }
161
+ }
162
+ const note = notes.join(" ") || null;
163
+ mkdirSync(dirname(OUT), { recursive: true });
164
+ writeFileSync(
165
+ OUT,
166
+ JSON.stringify(
167
+ { googleUpdates: { from, to, updates, ...(posts ? { posts } : {}), ...(note ? { note } : {}) } },
168
+ null,
169
+ 2,
170
+ ) + "\n",
171
+ );
172
+ console.log(
173
+ `google-updates: ${updates.length} Google ranking update${updates.length === 1 ? "" : "s"} from ${from} to ${to}${updates.length ? ":" : "."}`,
174
+ );
175
+ for (const u of updates) console.log(` ${u.name}: ${u.start}${u.end ? ` to ${u.end}` : ", still rolling out"}`);
176
+ if (posts)
177
+ console.log(
178
+ `google-updates: ${posts.length} Search Central blog post${posts.length === 1 ? "" : "s"} in the period${posts.length ? ":" : "."}`,
179
+ );
180
+ for (const p of posts || []) console.log(` ${p.date}: ${p.title}`);
181
+ if (note) console.log("note: " + note);
182
+ console.log("wrote " + OUT);
183
+ return 0;
184
+ }
185
+
186
+ if (isMain(import.meta.url)) {
187
+ warnProxy(); // once, before any request
188
+ await runMain(() => main(process.argv.slice(2)));
189
+ }