seo-supervisor 0.0.0-stage → 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 (218) hide show
  1. package/.claude-plugin/icon.png +0 -0
  2. package/.claude-plugin/marketplace.json +16 -0
  3. package/.claude-plugin/plugin.json +27 -0
  4. package/CHANGELOG.md +461 -0
  5. package/LICENSE +25 -0
  6. package/NOTICE +7 -0
  7. package/README.md +402 -2
  8. package/agents/seo-auditor.md +16 -0
  9. package/agents/seo-reviewer.md +16 -0
  10. package/bin/agents.mjs +230 -0
  11. package/bin/extras.mjs +422 -0
  12. package/bin/prompt.mjs +96 -0
  13. package/bin/seo-supervisor.mjs +477 -0
  14. package/commands/seo-audit.md +33 -0
  15. package/commands/seo-brief.md +28 -0
  16. package/commands/seo-connect.md +27 -0
  17. package/commands/seo-fix.md +34 -0
  18. package/commands/seo-grow.md +26 -0
  19. package/commands/seo-launch.md +21 -0
  20. package/commands/seo-review.md +19 -0
  21. package/commands/seo-rewrite.md +25 -0
  22. package/commands/seo-setup.md +35 -0
  23. package/commands/seo-watch.md +28 -0
  24. package/hooks/hooks.json +117 -0
  25. package/package.json +58 -4
  26. package/skills/seo-supervisor/NOTICE +7 -0
  27. package/skills/seo-supervisor/SKILL.md +480 -0
  28. package/skills/seo-supervisor/audience.md +61 -0
  29. package/skills/seo-supervisor/examples/drafts/security.md +41 -0
  30. package/skills/seo-supervisor/examples/hooks/README.md +28 -0
  31. package/skills/seo-supervisor/examples/hooks/claude-code-settings.json +15 -0
  32. package/skills/seo-supervisor/examples/hooks/codex-hooks.json +17 -0
  33. package/skills/seo-supervisor/examples/hooks/copilot-hooks.json +15 -0
  34. package/skills/seo-supervisor/examples/hooks/cursor-hooks.json +11 -0
  35. package/skills/seo-supervisor/examples/hooks/github-actions.yml +21 -0
  36. package/skills/seo-supervisor/examples/hooks/pre-commit +17 -0
  37. package/skills/seo-supervisor/examples/hooks/reading-ease.yml +24 -0
  38. package/skills/seo-supervisor/examples/sample-audit.json +532 -0
  39. package/skills/seo-supervisor/examples/sample-report.html +704 -0
  40. package/skills/seo-supervisor/examples/sample-report.md +360 -0
  41. package/skills/seo-supervisor/examples/scheduled-runs.md +89 -0
  42. package/skills/seo-supervisor/examples/security-tools-profile.md +73 -0
  43. package/skills/seo-supervisor/examples/snippets.md +781 -0
  44. package/skills/seo-supervisor/frameworks/nextjs.md +98 -0
  45. package/skills/seo-supervisor/frameworks/rails.md +34 -0
  46. package/skills/seo-supervisor/frameworks/spa.md +14 -0
  47. package/skills/seo-supervisor/grow.md +342 -0
  48. package/skills/seo-supervisor/og-images.md +85 -0
  49. package/skills/seo-supervisor/page-types.md +124 -0
  50. package/skills/seo-supervisor/planning.md +157 -0
  51. package/skills/seo-supervisor/profile-template.md +96 -0
  52. package/skills/seo-supervisor/report-format.md +313 -0
  53. package/skills/seo-supervisor/rewrite.md +59 -0
  54. package/skills/seo-supervisor/rules/ai-search.md +93 -0
  55. package/skills/seo-supervisor/rules/content.md +84 -0
  56. package/skills/seo-supervisor/rules/crawl-index.md +92 -0
  57. package/skills/seo-supervisor/rules/internal-linking.md +104 -0
  58. package/skills/seo-supervisor/rules/launch-monitoring.md +57 -0
  59. package/skills/seo-supervisor/rules/media.md +42 -0
  60. package/skills/seo-supervisor/rules/metadata.md +71 -0
  61. package/skills/seo-supervisor/rules/performance.md +78 -0
  62. package/skills/seo-supervisor/rules/rendering.md +79 -0
  63. package/skills/seo-supervisor/rules/search-intent.md +32 -0
  64. package/skills/seo-supervisor/rules/sitemaps-robots.md +49 -0
  65. package/skills/seo-supervisor/rules/structured-data.md +98 -0
  66. package/skills/seo-supervisor/rules/trust-security.md +48 -0
  67. package/skills/seo-supervisor/rules/urls.md +54 -0
  68. package/skills/seo-supervisor/scripts/ai-answers.mjs +314 -0
  69. package/skills/seo-supervisor/scripts/backlinks.mjs +412 -0
  70. package/skills/seo-supervisor/scripts/change-check.mjs +281 -0
  71. package/skills/seo-supervisor/scripts/checks/agents.mjs +488 -0
  72. package/skills/seo-supervisor/scripts/checks/assets.mjs +404 -0
  73. package/skills/seo-supervisor/scripts/checks/bots.mjs +146 -0
  74. package/skills/seo-supervisor/scripts/checks/business-type.mjs +193 -0
  75. package/skills/seo-supervisor/scripts/checks/content.mjs +391 -0
  76. package/skills/seo-supervisor/scripts/checks/coverage.mjs +184 -0
  77. package/skills/seo-supervisor/scripts/checks/crawl.mjs +95 -0
  78. package/skills/seo-supervisor/scripts/checks/hreflang.mjs +396 -0
  79. package/skills/seo-supervisor/scripts/checks/hygiene.mjs +227 -0
  80. package/skills/seo-supervisor/scripts/checks/lighthouse.mjs +271 -0
  81. package/skills/seo-supervisor/scripts/checks/link-strength.mjs +59 -0
  82. package/skills/seo-supervisor/scripts/checks/links.mjs +360 -0
  83. package/skills/seo-supervisor/scripts/checks/local.mjs +101 -0
  84. package/skills/seo-supervisor/scripts/checks/media.mjs +194 -0
  85. package/skills/seo-supervisor/scripts/checks/outbound.mjs +53 -0
  86. package/skills/seo-supervisor/scripts/checks/page.mjs +223 -0
  87. package/skills/seo-supervisor/scripts/checks/probes.mjs +130 -0
  88. package/skills/seo-supervisor/scripts/checks/render.mjs +552 -0
  89. package/skills/seo-supervisor/scripts/checks/robots.mjs +144 -0
  90. package/skills/seo-supervisor/scripts/checks/schema.mjs +206 -0
  91. package/skills/seo-supervisor/scripts/checks/site-agents.mjs +79 -0
  92. package/skills/seo-supervisor/scripts/checks/site-content.mjs +135 -0
  93. package/skills/seo-supervisor/scripts/checks/site-hygiene.mjs +202 -0
  94. package/skills/seo-supervisor/scripts/checks/site-pages.mjs +474 -0
  95. package/skills/seo-supervisor/scripts/checks/site-security.mjs +102 -0
  96. package/skills/seo-supervisor/scripts/checks/sitemap.mjs +473 -0
  97. package/skills/seo-supervisor/scripts/checks/speed.mjs +267 -0
  98. package/skills/seo-supervisor/scripts/checks/technical.mjs +368 -0
  99. package/skills/seo-supervisor/scripts/checks/tls.mjs +297 -0
  100. package/skills/seo-supervisor/scripts/checks/trust.mjs +421 -0
  101. package/skills/seo-supervisor/scripts/checks/visual.mjs +1132 -0
  102. package/skills/seo-supervisor/scripts/checks/writing.mjs +192 -0
  103. package/skills/seo-supervisor/scripts/commoncrawl.mjs +452 -0
  104. package/skills/seo-supervisor/scripts/connect-keys.mjs +422 -0
  105. package/skills/seo-supervisor/scripts/content-scan.mjs +530 -0
  106. package/skills/seo-supervisor/scripts/crawl/catalog.mjs +1248 -0
  107. package/skills/seo-supervisor/scripts/crawl/fetch.mjs +362 -0
  108. package/skills/seo-supervisor/scripts/crawl/page.mjs +741 -0
  109. package/skills/seo-supervisor/scripts/crawl/queue.mjs +190 -0
  110. package/skills/seo-supervisor/scripts/dashboard.mjs +140 -0
  111. package/skills/seo-supervisor/scripts/data/ai-bots.json +38 -0
  112. package/skills/seo-supervisor/scripts/data/build-schema-vocab.mjs +57 -0
  113. package/skills/seo-supervisor/scripts/data/business-types.json +338 -0
  114. package/skills/seo-supervisor/scripts/data/google-rich-results.json +79 -0
  115. package/skills/seo-supervisor/scripts/data/schema-vocab.json +1 -0
  116. package/skills/seo-supervisor/scripts/deploy-check.mjs +462 -0
  117. package/skills/seo-supervisor/scripts/disavow.mjs +176 -0
  118. package/skills/seo-supervisor/scripts/doctor.mjs +174 -0
  119. package/skills/seo-supervisor/scripts/fonts/OFL-BricolageGrotesque.txt +93 -0
  120. package/skills/seo-supervisor/scripts/fonts/OFL-Geist.txt +93 -0
  121. package/skills/seo-supervisor/scripts/fonts/OFL-GeistMono.txt +93 -0
  122. package/skills/seo-supervisor/scripts/fonts/bricolage-grotesque.woff2 +0 -0
  123. package/skills/seo-supervisor/scripts/fonts/geist-mono.woff2 +0 -0
  124. package/skills/seo-supervisor/scripts/fonts/geist.woff2 +0 -0
  125. package/skills/seo-supervisor/scripts/geo-grid.mjs +371 -0
  126. package/skills/seo-supervisor/scripts/google/search-console.mjs +151 -0
  127. package/skills/seo-supervisor/scripts/google/session.mjs +167 -0
  128. package/skills/seo-supervisor/scripts/google-updates.mjs +189 -0
  129. package/skills/seo-supervisor/scripts/google.mjs +1341 -0
  130. package/skills/seo-supervisor/scripts/gsc-import.mjs +298 -0
  131. package/skills/seo-supervisor/scripts/guard/adapters/claude-code.mjs +149 -0
  132. package/skills/seo-supervisor/scripts/guard/adapters/cline.mjs +28 -0
  133. package/skills/seo-supervisor/scripts/guard/adapters/codex.mjs +26 -0
  134. package/skills/seo-supervisor/scripts/guard/adapters/copilot.mjs +36 -0
  135. package/skills/seo-supervisor/scripts/guard/adapters/cursor.mjs +33 -0
  136. package/skills/seo-supervisor/scripts/guard/adapters/devin.mjs +25 -0
  137. package/skills/seo-supervisor/scripts/guard/adapters/edits.mjs +124 -0
  138. package/skills/seo-supervisor/scripts/guard/mode.mjs +37 -0
  139. package/skills/seo-supervisor/scripts/guard/rules.mjs +931 -0
  140. package/skills/seo-supervisor/scripts/guard.mjs +74 -0
  141. package/skills/seo-supervisor/scripts/images.mjs +408 -0
  142. package/skills/seo-supervisor/scripts/indexnow.mjs +300 -0
  143. package/skills/seo-supervisor/scripts/issues.mjs +217 -0
  144. package/skills/seo-supervisor/scripts/keys/authority.mjs +135 -0
  145. package/skills/seo-supervisor/scripts/keys/bing.mjs +239 -0
  146. package/skills/seo-supervisor/scripts/keys/clarity.mjs +137 -0
  147. package/skills/seo-supervisor/scripts/keys/dataforseo.mjs +57 -0
  148. package/skills/seo-supervisor/scripts/keys/googleplaces.mjs +26 -0
  149. package/skills/seo-supervisor/scripts/keys/http.mjs +212 -0
  150. package/skills/seo-supervisor/scripts/keys/matomo.mjs +138 -0
  151. package/skills/seo-supervisor/scripts/keys/openai.mjs +26 -0
  152. package/skills/seo-supervisor/scripts/keys/perplexity.mjs +26 -0
  153. package/skills/seo-supervisor/scripts/keys/posthog.mjs +165 -0
  154. package/skills/seo-supervisor/scripts/keys/semrush.mjs +25 -0
  155. package/skills/seo-supervisor/scripts/keys/services.mjs +41 -0
  156. package/skills/seo-supervisor/scripts/keys/store.mjs +140 -0
  157. package/skills/seo-supervisor/scripts/keys/visits.mjs +58 -0
  158. package/skills/seo-supervisor/scripts/keys/youtube.mjs +84 -0
  159. package/skills/seo-supervisor/scripts/keyword-data.mjs +316 -0
  160. package/skills/seo-supervisor/scripts/keyword-ideas.mjs +503 -0
  161. package/skills/seo-supervisor/scripts/lib/args.mjs +56 -0
  162. package/skills/seo-supervisor/scripts/lib/business.mjs +27 -0
  163. package/skills/seo-supervisor/scripts/lib/cdp.mjs +242 -0
  164. package/skills/seo-supervisor/scripts/lib/cli.mjs +56 -0
  165. package/skills/seo-supervisor/scripts/lib/csv.mjs +38 -0
  166. package/skills/seo-supervisor/scripts/lib/findings.mjs +100 -0
  167. package/skills/seo-supervisor/scripts/lib/google-client.mjs +9 -0
  168. package/skills/seo-supervisor/scripts/lib/html.mjs +146 -0
  169. package/skills/seo-supervisor/scripts/lib/http.mjs +28 -0
  170. package/skills/seo-supervisor/scripts/lib/image-size.mjs +78 -0
  171. package/skills/seo-supervisor/scripts/lib/is-main.mjs +13 -0
  172. package/skills/seo-supervisor/scripts/lib/net.mjs +116 -0
  173. package/skills/seo-supervisor/scripts/lib/proxy.mjs +47 -0
  174. package/skills/seo-supervisor/scripts/lib/recheck.mjs +106 -0
  175. package/skills/seo-supervisor/scripts/lib/redact.mjs +78 -0
  176. package/skills/seo-supervisor/scripts/lib/robots.mjs +73 -0
  177. package/skills/seo-supervisor/scripts/lib/score.mjs +266 -0
  178. package/skills/seo-supervisor/scripts/lib/settings-dir.mjs +81 -0
  179. package/skills/seo-supervisor/scripts/links-import.mjs +603 -0
  180. package/skills/seo-supervisor/scripts/log-scan.mjs +597 -0
  181. package/skills/seo-supervisor/scripts/og-card.mjs +273 -0
  182. package/skills/seo-supervisor/scripts/osm.mjs +359 -0
  183. package/skills/seo-supervisor/scripts/rdap.mjs +164 -0
  184. package/skills/seo-supervisor/scripts/render-report.mjs +340 -0
  185. package/skills/seo-supervisor/scripts/report/client.js +37 -0
  186. package/skills/seo-supervisor/scripts/report/diff.mjs +264 -0
  187. package/skills/seo-supervisor/scripts/report/findings.mjs +165 -0
  188. package/skills/seo-supervisor/scripts/report/format.mjs +111 -0
  189. package/skills/seo-supervisor/scripts/report/markdown.mjs +250 -0
  190. package/skills/seo-supervisor/scripts/report/model.mjs +171 -0
  191. package/skills/seo-supervisor/scripts/report/overview-lines.mjs +158 -0
  192. package/skills/seo-supervisor/scripts/report/overview.mjs +224 -0
  193. package/skills/seo-supervisor/scripts/report/page.mjs +127 -0
  194. package/skills/seo-supervisor/scripts/report/panel.mjs +172 -0
  195. package/skills/seo-supervisor/scripts/report/panels/ai.mjs +211 -0
  196. package/skills/seo-supervisor/scripts/report/panels/connections.mjs +139 -0
  197. package/skills/seo-supervisor/scripts/report/panels/content.mjs +204 -0
  198. package/skills/seo-supervisor/scripts/report/panels/data-search.mjs +379 -0
  199. package/skills/seo-supervisor/scripts/report/panels/data-site.mjs +44 -0
  200. package/skills/seo-supervisor/scripts/report/panels/links.mjs +380 -0
  201. package/skills/seo-supervisor/scripts/report/panels/local.mjs +221 -0
  202. package/skills/seo-supervisor/scripts/report/panels/site.mjs +359 -0
  203. package/skills/seo-supervisor/scripts/report/panels/speed-media.mjs +267 -0
  204. package/skills/seo-supervisor/scripts/report/sources.mjs +163 -0
  205. package/skills/seo-supervisor/scripts/report/styles.css +223 -0
  206. package/skills/seo-supervisor/scripts/report/traffic.mjs +264 -0
  207. package/skills/seo-supervisor/scripts/report-plan.mjs +241 -0
  208. package/skills/seo-supervisor/scripts/schema-check.mjs +717 -0
  209. package/skills/seo-supervisor/scripts/seo-crawl.mjs +1151 -0
  210. package/skills/seo-supervisor/scripts/seo-diff.mjs +584 -0
  211. package/skills/seo-supervisor/scripts/update-check.mjs +82 -0
  212. package/skills/seo-supervisor/site-types/content.md +55 -0
  213. package/skills/seo-supervisor/site-types/ecommerce.md +64 -0
  214. package/skills/seo-supervisor/site-types/local-business.md +118 -0
  215. package/skills/seo-supervisor/site-types/services.md +68 -0
  216. package/skills/seo-supervisor/site-types/tools.md +127 -0
  217. package/skills/seo-supervisor/strategy.md +232 -0
  218. package/skills/seo-supervisor/troubleshooting.md +56 -0
@@ -0,0 +1,371 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ // Local rank grid: where a business's place ID ranks in Places text search at each point around it.
4
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { createInterface } from "node:readline/promises";
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
+ import { SERVICES, activeKeys, keyFile, call, Refused } from "./connect-keys.mjs";
11
+
12
+ const SIZES = [5, 7, 9],
13
+ SIZE = 7,
14
+ SPACING = 1,
15
+ MIN_SPACING = 0.1,
16
+ MAX_SPACING = 20,
17
+ MAX_KEYWORDS = 3,
18
+ TOP = 20,
19
+ FIND_MAX = 5; // local caps, not API limits
20
+ // IDs only keeps grid searches on the free Text Search Essentials IDs Only SKU.
21
+ // https://developers.google.com/maps/billing-and-pricing/pricing
22
+ const GRID_MASK = "places.id,places.attributions",
23
+ FIND_MASK = "places.id,places.displayName,places.formattedAddress";
24
+ const FINDER = "https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder";
25
+ const READ = "22 Nov 2026"; // when the prices quoted in the dry run were checked
26
+ export const LABEL =
27
+ "Where your business appears in the list Google's Places API returns near each point: an approximation of Google Maps results, not a copy.";
28
+ const USAGE = `usage: node geo-grid.mjs --place-id <id> --keywords "plumber, boiler repair" [--center lat,lng] [--size 5|7|9] [--spacing 1] [--out seo-audit/geo-grid.json] [--yes]
29
+ node geo-grid.mjs --find "Business name, town" [--yes]
30
+ --place-id your business's Google place ID. Find it on Google's Place ID Finder: ${FINDER}
31
+ or with --find, which shows Google's matches and saves the one you pick.
32
+ --keywords 1 to 3, each on its own, like plumber: not "plumber Leeds" or "plumber near me". A place name makes Google ignore each point.
33
+ --size points a side (default 7). --spacing: km between points (default 1). In the countryside, where businesses
34
+ are far apart, try --spacing 3 to 5.
35
+ --center the grid's middle, as latitude,longitude. Without it, Google is asked where your business is.`;
36
+ const fail = msg => {
37
+ throw new Fail("geo-grid: " + msg);
38
+ };
39
+ const PLACE_ID = /^[\w-]{10,}$/;
40
+ const r5 = x => Math.round(x * 1e5) / 1e5;
41
+ const KM_PER_DEG = (6371.0088 * Math.PI) / 180; // mean Earth radius, as in osm.mjs
42
+ // https://developers.google.com/maps/documentation/urls/get-started
43
+ const mapsLink = id =>
44
+ `https://www.google.com/maps/search/?api=1&query=business&query_place_id=${encodeURIComponent(id)}`;
45
+ // Google's text goes to a terminal, so control characters are stripped first.
46
+ const clean = s =>
47
+ String(s ?? "")
48
+ .replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ")
49
+ .trim();
50
+
51
+ // Points row by row from the north-west corner; the centre is at floor(size / 2) both ways. Flat steps are fine
52
+ // for a few dozen km. Use a geodesic if grids ever span hundreds.
53
+ export function gridPoints({ lat, lng }, size, spacingKm) {
54
+ const half = Math.floor(size / 2),
55
+ step = spacingKm / KM_PER_DEG,
56
+ cells = [];
57
+ for (let row = 0; row < size; row++) {
58
+ // A km east spans more degrees of longitude the further the row is from the equator.
59
+ const y = lat + (half - row) * step,
60
+ east = step / Math.cos((y * Math.PI) / 180);
61
+ for (let col = 0; col < size; col++)
62
+ cells.push({ row, col, lat: r5(y), lng: r5(((((lng + (col - half) * east) % 360) + 540) % 360) - 180) });
63
+ }
64
+ return cells;
65
+ }
66
+ const counts = cells => {
67
+ const n = f => cells.filter(c => f(c.rank)).length,
68
+ found = r => typeof r === "number";
69
+ return {
70
+ top3: n(r => found(r) && r <= 3),
71
+ top10: n(r => found(r) && r <= 10),
72
+ top20: n(found),
73
+ notFound: n(r => r === null),
74
+ failed: n(r => r === "error"),
75
+ };
76
+ };
77
+ const request = (key, mask, body) => ({
78
+ method: body ? "POST" : "GET",
79
+ redirect: "manual",
80
+ headers: { "x-goog-api-key": key, "x-goog-fieldmask": mask, "content-type": "application/json" },
81
+ ...(body && { body: JSON.stringify(body) }),
82
+ });
83
+
84
+ // The first refusal (bad key, API off, no billing, rate limit) stops the run and marks the remaining points "error".
85
+ // Lone 5xx answers aren't retried; add that if Google proves flaky.
86
+ async function runGrid({
87
+ placeId,
88
+ keywords,
89
+ center = null,
90
+ size = SIZE,
91
+ spacingKm = SPACING,
92
+ key,
93
+ endpoint,
94
+ log = s => {},
95
+ }) {
96
+ const notes = [],
97
+ date = new Date().toISOString().slice(0, 10);
98
+ const d = await call(
99
+ "googleplaces",
100
+ `${endpoint}/places/${encodeURIComponent(placeId)}`,
101
+ request(key, center ? "id" : "id,location"),
102
+ );
103
+ const ids = new Set([placeId, d?.id].filter(x => typeof x === "string")); // Google may answer with a newer ID
104
+ if (!center) {
105
+ const at = d?.location;
106
+ if (!Number.isFinite(at?.latitude) || !Number.isFinite(at?.longitude))
107
+ throw new Refused(
108
+ "Google has no map position for this business: a business that hides its address (a service-area business) has none. Pass --center latitude,longitude, the middle of the area you serve.",
109
+ );
110
+ // Places coordinates may be cached for 30 days at most (Service Specific Terms 14.3).
111
+ // https://cloud.google.com/maps-platform/terms/maps-service-terms
112
+ center = { lat: at.latitude, lng: at.longitude };
113
+ notes.push(
114
+ `The grid's centre came from Google's Places API, and Google's terms let you keep those coordinates for 30 days at most (Service Specific Terms 14.3). Delete this file by ${new Date(Date.now() + 30 * 864e5).toISOString().slice(0, 10)}, or run again with --center.`,
115
+ );
116
+ }
117
+ // The bias circle is the largest that fits each point's square, so neighbouring circles touch without overlapping.
118
+ const cells = gridPoints(center, size, spacingKm),
119
+ biasRadiusM = Math.round(spacingKm * 500),
120
+ credits = new Map();
121
+ let stop = null,
122
+ sent = 0;
123
+ const out = [];
124
+ for (const keyword of keywords) {
125
+ const done = [];
126
+ for (const c of cells) {
127
+ let rank = "error";
128
+ if (!stop) {
129
+ try {
130
+ // Without a bias Google ranks for the caller's IP, and a place name in the query overrides the bias, so the
131
+ // query is the bare keyword. Service-area businesses have no address and are only found with the flag set.
132
+ // https://developers.google.com/maps/documentation/places/web-service/text-search
133
+ const b = await call(
134
+ "googleplaces",
135
+ `${endpoint}/places:searchText`,
136
+ request(key, GRID_MASK, {
137
+ textQuery: keyword,
138
+ locationBias: { circle: { center: { latitude: c.lat, longitude: c.lng }, radius: biasRadiusM } },
139
+ includePureServiceAreaBusinesses: true,
140
+ }),
141
+ );
142
+ if (!b || typeof b !== "object")
143
+ throw new Refused(
144
+ "Google Places API's answer isn't the list of places it used to send, so the run stopped. Google may have changed the API.",
145
+ );
146
+ const places = Array.isArray(b.places) ? b.places : []; // Google leaves `places` out when nothing matches
147
+ for (const p of places)
148
+ for (const a of Array.isArray(p?.attributions) ? p.attributions : [])
149
+ if (typeof a?.provider === "string" && a.provider) credits.set(clean(a.provider), clean(a.providerUri));
150
+ // The position is Google's order as returned: the terms forbid re-sorting results (3.2.3(g)).
151
+ const i = places.findIndex(p => ids.has(p?.id));
152
+ rank = i >= 0 && i < TOP ? i + 1 : null;
153
+ sent++;
154
+ } catch (e) {
155
+ if (!(e instanceof Refused)) throw e;
156
+ stop = e.message;
157
+ }
158
+ }
159
+ done.push({ ...c, rank });
160
+ }
161
+ out.push({ keyword, cells: done, ...counts(done) });
162
+ log(`"${keyword}": ${done.filter(c => c.rank !== "error").length} of ${cells.length} points checked`);
163
+ }
164
+ // Places content must carry Google's attribution, plus any third-party credit it sends (3.2.2(b)).
165
+ if (credits.size)
166
+ notes.push(
167
+ `Google's results include data from ${[...credits].map(([p, u]) => (u ? `${p} (${u})` : p)).join(", ")}. Show this credit next to "Google Maps" wherever the grid is shown.`,
168
+ );
169
+ if (stop)
170
+ notes.push(
171
+ `Stopped after ${sent} of ${cells.length * keywords.length} searches: ${stop} The points not checked are marked as errors.`,
172
+ );
173
+ return {
174
+ result: {
175
+ source: "geo-grid",
176
+ date,
177
+ placeId,
178
+ center: { lat: r5(center.lat), lng: r5(center.lng) },
179
+ size,
180
+ spacingKm,
181
+ biasRadiusM,
182
+ attribution: "Google Maps",
183
+ label: LABEL,
184
+ keywords: out,
185
+ notes,
186
+ },
187
+ stop,
188
+ };
189
+ }
190
+
191
+ // One line from the terminal, or the first line piped in.
192
+ async function answer(prompt) {
193
+ const { stdin, stderr } = process;
194
+ if (stdin.isTTY) {
195
+ const rl = createInterface({ input: stdin, output: stderr });
196
+ try {
197
+ return await rl.question(prompt);
198
+ } catch {
199
+ return "";
200
+ } finally {
201
+ rl.close();
202
+ }
203
+ }
204
+ let text = "";
205
+ for await (const c of stdin) {
206
+ text += c;
207
+ if (text.includes("\n")) break;
208
+ }
209
+ return text.split(/\r?\n/)[0];
210
+ }
211
+
212
+ async function find({ text, key, from, endpoint, placeFile, yes }) {
213
+ if (!yes) {
214
+ console.log(
215
+ [
216
+ `geo-grid: dry run, nothing sent. With --yes it would send "${text}" to Google's Places API (New) at ${new URL(endpoint).host} once, ${from}, and ask for up to ${FIND_MAX} matches with their place ID, name and address.`,
217
+ `That request is billed as Text Search Pro: on ${READ} Google's price list showed 5,000 free a month, then $32.00 per 1,000 (developers.google.com/maps/billing-and-pricing/pricing).`,
218
+ "You pick your business from the list. Only its place ID is saved: Google's terms don't allow saving names or addresses.",
219
+ "Re-run with --yes once the owner agrees.",
220
+ ].join("\n"),
221
+ );
222
+ return 0;
223
+ }
224
+ const b = await call(
225
+ "googleplaces",
226
+ `${endpoint}/places:searchText`,
227
+ request(key, FIND_MASK, { textQuery: text, pageSize: FIND_MAX }),
228
+ );
229
+ const found = (Array.isArray(b?.places) ? b.places : [])
230
+ .filter(p => typeof p?.id === "string" && PLACE_ID.test(p.id))
231
+ .slice(0, FIND_MAX);
232
+ if (!found.length) {
233
+ console.log(
234
+ `geo-grid: Google found no match for "${text}". Try the name as it shows on Google Maps, with the town.`,
235
+ );
236
+ return 1;
237
+ }
238
+ console.log(
239
+ `geo-grid: Google's matches for "${text}" (shown here, not saved):\n${found.map((p, i) => ` ${i + 1}. ${[clean(p.displayName?.text), clean(p.formattedAddress)].filter(Boolean).join(", ")}\n place ID ${p.id}`).join("\n")}\nResults: Google Maps`,
240
+ );
241
+ const n = Number(
242
+ (await answer(`Which one is your business? Type its number and press Enter (just Enter for none): `)).trim(),
243
+ );
244
+ if (!(Number.isInteger(n) && n >= 1 && n <= found.length)) {
245
+ console.log(`geo-grid: Nothing saved. Run again and type a number, or pass --place-id to geo-grid.mjs.`);
246
+ return 0;
247
+ }
248
+ // Only place_id may be cached; names and addresses are shown, never saved (Service Specific Terms 3).
249
+ mkdirSync(dirname(placeFile), { recursive: true });
250
+ writeFileSync(placeFile, JSON.stringify({ placeId: found[n - 1].id }, null, 2) + "\n");
251
+ console.log(
252
+ `geo-grid: saved place ID ${found[n - 1].id} in ${placeFile} (only the ID). Check it's yours: ${mapsLink(found[n - 1].id)}\nNext: node geo-grid.mjs --keywords "your keyword" reads it from there.`,
253
+ );
254
+ return 0;
255
+ }
256
+
257
+ async function main(argv) {
258
+ const args = parseArgs(argv, {
259
+ flags: ["place-id", "keywords", "center", "size", "spacing", "out", "find"],
260
+ booleans: ["yes"],
261
+ positionals: 0,
262
+ usage: USAGE,
263
+ });
264
+ const str = k => (typeof args[k] === "string" ? args[k].trim() : null),
265
+ yes = args.yes === true;
266
+ const out = resolve(str("out") || "seo-audit/geo-grid.json"),
267
+ placeFile = join(dirname(out), "geo-grid-place.json");
268
+ const k = activeKeys().googleplaces,
269
+ s = SERVICES.googleplaces,
270
+ endpoint = (process.env[s.endpointEnv] || s.endpoint).replace(/\/+$/, "");
271
+ const from = k ? `with your key ${k.from === s.env ? `from ${s.env}` : `saved in ${keyFile()}`}` : "with your key";
272
+ const needKey = () =>
273
+ k?.key || fail("no Google Places key is set. To add one: node connect-keys.mjs guide googleplaces");
274
+ if (str("find")) return find({ text: str("find"), key: yes && needKey(), from, endpoint, placeFile, yes });
275
+
276
+ let saved = null;
277
+ if (!str("place-id"))
278
+ try {
279
+ saved = JSON.parse(readFileSync(placeFile, "utf8")).placeId;
280
+ } catch {}
281
+ const placeId = str("place-id") || (typeof saved === "string" ? saved : null);
282
+ if (!placeId && !str("keywords")) throw new Fail(USAGE);
283
+ if (!placeId)
284
+ fail(
285
+ `no place ID. Pass --place-id <id> (Google's Place ID Finder: ${FINDER}), or find it with --find "Business name, town".`,
286
+ );
287
+ if (!PLACE_ID.test(placeId))
288
+ fail(
289
+ `"${placeId}" isn't a place ID: those are long codes of letters, digits, - and _, like ChIJN1t_tDeuEmsRUsoyG83frY4. Find yours on Google's Place ID Finder: ${FINDER}`,
290
+ );
291
+ const keywords = [
292
+ ...new Set(
293
+ (str("keywords") || "")
294
+ .split(",")
295
+ .map(x => x.trim().replace(/\s+/g, " "))
296
+ .filter(Boolean),
297
+ ),
298
+ ];
299
+ if (!keywords.length)
300
+ fail(
301
+ `--keywords needs 1 to ${MAX_KEYWORDS} keywords, separated by commas, like --keywords "plumber, boiler repair".`,
302
+ );
303
+ if (keywords.length > MAX_KEYWORDS)
304
+ fail(
305
+ `${keywords.length} keywords, but a run takes at most ${MAX_KEYWORDS} (our own cap, to keep it small). Keep the ones that matter most.`,
306
+ );
307
+ const size = args.size === undefined ? SIZE : Number(str("size"));
308
+ if (!SIZES.includes(size)) fail(`--size must be 5, 7 or 9 points a side (got ${args.size}).`);
309
+ const spacingKm = args.spacing === undefined ? SPACING : Number(str("spacing"));
310
+ if (!(spacingKm >= MIN_SPACING && spacingKm <= MAX_SPACING))
311
+ fail(`--spacing must be from ${MIN_SPACING} to ${MAX_SPACING} km (our own limits; got ${args.spacing}).`);
312
+ let center = null;
313
+ if (args.center !== undefined) {
314
+ const [lat, lng] = String(args.center)
315
+ .split(",")
316
+ .map(x => (x.trim() ? Number(x) : NaN));
317
+ if (!(Math.abs(lat) <= 90 && Math.abs(lng) <= 180))
318
+ fail(`--center must be latitude,longitude, like 53.7976,-1.5453 (got ${args.center}).`);
319
+ center = { lat, lng };
320
+ }
321
+
322
+ const searches = size * size * keywords.length,
323
+ across = Number(((size - 1) * spacingKm).toFixed(2));
324
+ if (!yes) {
325
+ console.log(
326
+ [
327
+ `geo-grid: dry run, nothing sent. With --yes it would ask Google's Places API (New) at ${new URL(endpoint).host}, ${from}:`,
328
+ center
329
+ ? ` 1 check that the place ID ${placeId} is still current (Place Details, the ID only).`
330
+ : ` 1 lookup of where your business is on the map (Place Details for place ID ${placeId}, the location field only).`,
331
+ ` ${searches} searches: one at each point of a ${size} × ${size} grid, ${spacingKm} km apart (${across} km across), ${keywords.length === 1 ? "for the keyword" : `for each of ${keywords.length} keywords`} (${keywords.map(w => `"${w}"`).join(", ")}), centred on ${center ? `${center.lat}, ${center.lng}` : "your business"}.`,
332
+ ` ${searches + 1} requests in all.`,
333
+ `Each search sends the keyword alone, one point's latitude and longitude, a ${Math.round(spacingKm * 500)} m circle around it that Google favours, and a request for place IDs only. Nothing about your site goes.`,
334
+ `Cost: on ${READ} Google's price list (developers.google.com/maps/billing-and-pricing/pricing) listed searches for place IDs only (Text Search Essentials IDs Only) as free without limit, and ${center ? "the place ID check (Place Details Essentials IDs Only) as free without limit too" : "the location lookup (Place Details Essentials) at 10,000 free a month, then $5.00 per 1,000"}. Google still requires billing to be turned on in the key's project.`,
335
+ `Check the place ID is yours: ${mapsLink(placeId)}`,
336
+ "If your Google billing address is in the European Economic Area (EEA), Google's EEA terms apply. Their list of allowed uses for Places API results doesn't include rank tracking, though place IDs are left out of that limit. Whether to run this is your decision (cloud.google.com/terms/maps-platform/eea-places-api-permitted-uses).",
337
+ ...(k
338
+ ? []
339
+ : [
340
+ "No Google Places key is set yet, so nothing could be sent. To add one: node connect-keys.mjs guide googleplaces",
341
+ ]),
342
+ "The keywords and the points go to Google with your key, so re-run with --yes once the owner agrees.",
343
+ ].join("\n"),
344
+ );
345
+ return 0;
346
+ }
347
+ const r = await runGrid({
348
+ placeId,
349
+ keywords,
350
+ center,
351
+ size,
352
+ spacingKm,
353
+ key: needKey(),
354
+ endpoint,
355
+ log: x => console.error("geo-grid: " + x),
356
+ });
357
+ mkdirSync(dirname(out), { recursive: true });
358
+ writeFileSync(out, JSON.stringify(r.result, null, 2));
359
+ for (const w of r.result.keywords)
360
+ console.log(
361
+ `geo-grid: "${w.keyword}": in the top 3 at ${w.top3} of ${w.cells.length} points · top 10 at ${w.top10} · not in the top ${TOP} at ${w.notFound}${w.failed ? ` · errors at ${w.failed}` : ""}`,
362
+ );
363
+ for (const n of r.result.notes) console.log("geo-grid: " + n);
364
+ console.log(`geo-grid: ${LABEL}\ngeo-grid: Results: Google Maps\ngeo-grid: wrote ${out}`);
365
+ return r.stop ? 1 : 0;
366
+ }
367
+
368
+ if (isMain(import.meta.url)) {
369
+ warnProxy();
370
+ await runMain(() => main(process.argv.slice(2)));
371
+ }
@@ -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
+ };