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,603 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ // Summarises Search Console's Links exports, the only source as the API has no Links report: who links to the site,
4
+ // the link-text mix, and changes since the last audit.
5
+ import { readFileSync, writeFileSync, mkdirSync, readdirSync, statSync, existsSync } from "node:fs";
6
+ import { basename, dirname, join, resolve } from "node:path";
7
+ import { domainToUnicode } from "node:url";
8
+ import { isMain } from "./lib/is-main.mjs";
9
+ import { parseCsv } from "./lib/csv.mjs";
10
+ import { parseArgs } from "./lib/args.mjs";
11
+ import { Fail, runMain } from "./lib/cli.mjs";
12
+ import { foundOn } from "./lib/findings.mjs";
13
+
14
+ const USAGE =
15
+ 'usage: node links-import.mjs --dir seo-audit/links --site https://www.example.com [--brand "Acme"] [--keys seo-audit/keys.json] [--previous <earlier links.json>] [--crawl seo-audit/seo-crawl.json] [--out seo-audit/links.json]';
16
+ const obj = x => (x && typeof x === "object" ? x : null);
17
+ const bare = h => h.toLowerCase().replace(/^www\./, "");
18
+
19
+ // The tables' first column and their link count, as the English UI names them. Google's help names the tables, not
20
+ // the columns; with other headers a file still counts when it has one text column holding the site's page URLs,
21
+ // domains or link text.
22
+ const KEY = {
23
+ sites: /^(top )?linking sites?$|^sites?$|^domains?$/i,
24
+ texts: /^(top )?linking texts?$|^link texts?$|^anchor texts?$/i,
25
+ pages: /^(top )?linked pages?$|^target (pages?|urls?)$|^pages?$|^urls?$/i,
26
+ };
27
+ const COUNT = /^(incoming |external )?links$|^linking pages$/i;
28
+ const FIELD = { sites: "domain", texts: "text", pages: "url" };
29
+ const NAME = { sites: "Top linking sites", texts: "Top linking text", pages: "Top linked pages" };
30
+ const NUM = /^\d[\d.,\s  ']*$/,
31
+ DOMAIN = /^[\p{L}\p{N}-]+(\.[\p{L}\p{N}-]+)+$/u;
32
+ // "~" and "-" export as 0, and each table holds at most 1,000 rows.
33
+ // https://support.google.com/webmasters/answer/9049606
34
+ const count = s => Number(String(s).replace(/\D/g, "") || 0); // "1,200", "1.200" and "1 200" are all 1200
35
+
36
+ // One export: { kind: "sites" | "texts" | "pages", rows } most links first, or { kind: null } when it's none of the
37
+ // three.
38
+ function readExport(text, site) {
39
+ const rows = parseCsv(text),
40
+ heads = Object.keys(rows[0] || {});
41
+ const numeric = h => rows.some(r => r[h]) && rows.every(r => !r[h] || NUM.test(r[h]));
42
+ const words = heads.filter(h => !numeric(h)),
43
+ nums = heads.filter(numeric);
44
+ let kind = Object.keys(KEY).find(k => words.some(h => KEY[k].test(h)));
45
+ if (!kind && words.length !== 1) return { kind: null }; // e.g. Latest links: linking page and date
46
+ const key = kind ? words.find(h => KEY[kind].test(h)) : words[0],
47
+ vals = rows.map(r => r[key]).filter(Boolean);
48
+ const host = bare(new URL(site).hostname);
49
+ const onSite = v => {
50
+ try {
51
+ const h = bare(new URL(v).hostname);
52
+ return /^https?:\/\//i.test(v) && (h === host || h.endsWith("." + host));
53
+ } catch {
54
+ return false;
55
+ }
56
+ };
57
+ // Other sites' URLs are linking pages (Latest links in another language), not this site's linked pages.
58
+ kind ||= !vals.length
59
+ ? null
60
+ : vals.every(onSite)
61
+ ? "pages"
62
+ : vals.some(v => /^https?:\/\//i.test(v))
63
+ ? null
64
+ : vals.every(v => DOMAIN.test(v))
65
+ ? "sites"
66
+ : "texts";
67
+ if (!kind) return { kind: null };
68
+ const n = nums.find(h => COUNT.test(h)) || nums[0];
69
+ // Top linking sites also has Target pages: how many of the site's pages each one links to. In another language it's
70
+ // the other number column.
71
+ const t =
72
+ kind !== "sites"
73
+ ? undefined
74
+ : nums.find(h => /^target pages?$/i.test(h)) || (nums.length === 2 ? nums.find(h => h !== n) : null);
75
+ const out = rows
76
+ .map(r => ({
77
+ [FIELD[kind]]: r[key],
78
+ links: n ? count(r[n]) : null,
79
+ ...(t !== undefined && { targets: t ? count(r[t]) : null }),
80
+ }))
81
+ .filter(r => kind === "texts" || r[FIELD[kind]]);
82
+ return { kind, rows: out.sort((a, b) => (b.links ?? 0) - (a.links ?? 0)) };
83
+ }
84
+
85
+ // Google calls "click here", "read more", "website" and "article" too generic; the rest are the same kind of words.
86
+ // https://developers.google.com/search/docs/crawling-indexing/links-crawlable
87
+ const GENERIC = new Set([
88
+ "click here",
89
+ "here",
90
+ "click",
91
+ "read more",
92
+ "more",
93
+ "learn more",
94
+ "find out more",
95
+ "more info",
96
+ "details",
97
+ "website",
98
+ "web site",
99
+ "this website",
100
+ "the website",
101
+ "site",
102
+ "this site",
103
+ "visit",
104
+ "visit site",
105
+ "visit website",
106
+ "link",
107
+ "this link",
108
+ "article",
109
+ "this article",
110
+ "source",
111
+ "home",
112
+ "homepage",
113
+ "home page",
114
+ "this",
115
+ "page",
116
+ "this page",
117
+ "continue reading",
118
+ ]);
119
+ const norm = s =>
120
+ String(s)
121
+ .toLowerCase()
122
+ .normalize("NFKD")
123
+ .replace(/[̀-ͯ]/g, "")
124
+ .replace(/[^\p{L}\p{N}]+/gu, " ")
125
+ .trim();
126
+ // Anything shaped like a host name is an address, so "Node.js" counts as one. That's rare in link text.
127
+ const ADDRESS = /^(https?:\/\/)?[\p{L}\p{N}-]+(\.[\p{L}\p{N}-]+)+(:\d+)?([/?#]\S*)?$/iu;
128
+ // The brand when one of its names ("Acme Plumbing|Acme") appears as whole words, also run together ("AcmePlumbing" for
129
+ // "Acme Plumbing", and back), so "Ace" isn't found inside "space". A legal ending ("Ltd", "Inc", "GmbH") isn't needed.
130
+ const LEGAL = / (ltd|limited|inc|llc|llp|plc|gmbh|co|corp|company|pty|bv|ag|sa|srl|sarl)$/;
131
+ const brandNames = brand =>
132
+ String(brand ?? "")
133
+ .split("|")
134
+ .map(b => {
135
+ let n = norm(b);
136
+ while (LEGAL.test(n)) n = n.replace(LEGAL, "");
137
+ return n.replace(/ /g, "");
138
+ })
139
+ .filter(Boolean);
140
+ const hasBrand = (text, brand) => {
141
+ const w = norm(text).split(" ");
142
+ return brandNames(brand).some(b => w.some((_, i) => w.slice(i).some((_, j) => w.slice(i, i + j + 1).join("") === b)));
143
+ };
144
+ export const classify = (text, brand) =>
145
+ ADDRESS.test(String(text).trim())
146
+ ? "address"
147
+ : hasBrand(text, brand)
148
+ ? "brand"
149
+ : GENERIC.has(norm(text))
150
+ ? "generic"
151
+ : "other";
152
+ // The site's name from its address, as Unicode: the label before the public suffix, so shop.acme.com and acme.co.uk
153
+ // give "acme" and xn--bcher-kva.de gives "bücher". A two-letter country code after a label of 3 letters or fewer counts
154
+ // as the suffix (co.uk, com.au). Use the Public Suffix List if a site's name comes out wrong.
155
+ export const siteName = host => {
156
+ const l = domainToUnicode(bare(host)).split(".");
157
+ return (
158
+ l[Math.max(l.length >= 3 && l.at(-1).length === 2 && l.at(-2).length <= 3 ? l.length - 3 : l.length - 2, 0)] || ""
159
+ );
160
+ };
161
+ // The brand names to match: the given ones ("Acme Plumbing|Acme") plus the site's name, each once.
162
+ export const withSiteName = (brand, host) => {
163
+ const seen = new Set();
164
+ return [...String(brand ?? "").split("|"), siteName(host)]
165
+ .map(s => s.trim())
166
+ .filter(s => {
167
+ const k = brandNames(s)[0];
168
+ return k && !seen.has(k) && seen.add(k);
169
+ })
170
+ .join("|");
171
+ };
172
+ // Links with no text (usually image links): Search Console exports them as empty rows. They have no words to judge.
173
+ const hasText = t => norm(t ?? "") !== "";
174
+
175
+ // Shares from 0 to 1 of the links with text: of links when the export counts them, else of the texts listed (Search
176
+ // Console merges duplicates).
177
+ export function anchorMix(texts, brand) {
178
+ texts = texts.filter(t => hasText(t.text));
179
+ const w = texts.every(t => t.links != null) ? t => t.links : () => 1,
180
+ total = texts.reduce((s, t) => s + w(t), 0);
181
+ if (!total) return null;
182
+ const mix = { brand: 0, address: 0, generic: 0, other: 0 };
183
+ for (const t of texts) mix[classify(t.text, brand)] += w(t);
184
+ for (const k in mix) mix[k] = Math.round((mix[k] / total) * 1000) / 1000;
185
+ return mix;
186
+ }
187
+
188
+ // Never a score or a finding, and never called "toxic": Google can usually judge links on its own and most sites never
189
+ // need the disavow tool, so each item says why it's listed and what to look at.
190
+ // https://support.google.com/webmasters/answer/2648487
191
+ // The cut-offs below are local lines for "stands out"; Google publishes none.
192
+ const ONLY = "Only disavow links you know are paid or were made to manipulate rankings.";
193
+ // https://developers.google.com/search/docs/essentials/spam-policies#link-spam
194
+ const SPAM =
195
+ "Google's spam policies count “links with optimized anchor text in articles, guest posts, or press releases distributed on other sites” as link spam.";
196
+ const pct = x => `${Math.round(x * 100)}%`;
197
+ // outDomains: the crawl's linksToOtherSites.domains ({ host: count }), the sites the crawled pages link to.
198
+ export function worthALook({ sites = [], texts = [], sample = [], outDomains }, site, brand) {
199
+ const own = bare(site.hostname),
200
+ mine = h => {
201
+ const b = bare(h);
202
+ return b === own || b.endsWith("." + own);
203
+ };
204
+ const out = [],
205
+ others = sites.filter(s => !mine(s.domain)),
206
+ total = others.reduce((n, s) => n + (s.links || 0), 0);
207
+ // Sitewide-looking: many of one site's pages link to few of this site's, and they're a big share of all links.
208
+ for (const s of others
209
+ .filter(s => s.links >= 50 && s.targets != null && s.targets <= 3 && s.links >= total * 0.2)
210
+ .slice(0, 5))
211
+ out.push({
212
+ kind: "sitewide",
213
+ subject: s.domain,
214
+ why: `Links to you from ${s.links.toLocaleString("en-US")} of its pages, but to only ${s.targets} of yours: ${pct(s.links / total)} of all the links Search Console listed. A link on every page like this is usually in a footer or sidebar.`,
215
+ look: `That's fine from a partner, a client, a supplier or another site you run. If you don't know the site, open a few of its pages and look at the link and its words. ${ONLY}`,
216
+ });
217
+ // Link text: 3 in 4 descriptive (not brand, address or generic), from at least 10 texts with words.
218
+ const named = texts.filter(t => hasText(t.text)),
219
+ mix = named.length >= 10 && anchorMix(named, brand);
220
+ if (mix && mix.other >= 0.75)
221
+ out.push({
222
+ kind: "keyword-text",
223
+ subject: "Link text to your site",
224
+ why: `${pct(mix.other)} of the link text is descriptive words, not your brand (read as “${String(brand)
225
+ .split("|")
226
+ .map(s => s.trim())
227
+ .filter(Boolean)
228
+ .join("” or “")}”) or your web address.`,
229
+ look: `That's normal when people link to articles by their titles. It's worth a look if you, or someone you paid, placed links: ${SPAM} ${ONLY}`,
230
+ examples: named
231
+ .filter(t => classify(t.text, brand) === "other")
232
+ .slice(0, 5)
233
+ .map(t => t.text),
234
+ });
235
+ // Bing's sample of links to the home page: the same descriptive words from 3 or more sites. People who link on their
236
+ // own rarely pick the same words.
237
+ const same = new Map();
238
+ for (const l of sample) {
239
+ let h;
240
+ try {
241
+ h = bare(new URL(l.url).hostname);
242
+ } catch {
243
+ continue;
244
+ }
245
+ if (
246
+ mine(h) ||
247
+ typeof l.anchorText !== "string" ||
248
+ !hasText(l.anchorText) ||
249
+ classify(l.anchorText, brand) !== "other"
250
+ )
251
+ continue;
252
+ const k = norm(l.anchorText),
253
+ g = same.get(k) || { text: l.anchorText.trim(), hosts: new Set(), urls: [] };
254
+ g.hosts.add(h);
255
+ g.urls.push(l.url);
256
+ same.set(k, g);
257
+ }
258
+ for (const g of [...same.values()]
259
+ .filter(g => g.hosts.size >= 3)
260
+ .sort((a, b) => b.hosts.size - a.hosts.size)
261
+ .slice(0, 5))
262
+ out.push({
263
+ kind: "same-text",
264
+ subject: g.text,
265
+ why: `The same link text comes from ${g.hosts.size} different sites in Bing's sample of links to your home page. People who link on their own rarely pick the same words.`,
266
+ look: `Check whether you, or someone you paid, placed these links. ${SPAM} ${ONLY}`,
267
+ examples: g.urls.slice(0, 5),
268
+ });
269
+ // Reciprocal: sites that link to you and that your crawled pages link to (a subdomain counts for its root domain, as
270
+ // Search Console lists sites by root domain). 10 or more sites and 10% of the linking sites listed are local lines.
271
+ const to = Object.keys(obj(outDomains) || {}).map(bare);
272
+ const both = others.filter(s => {
273
+ const d = bare(s.domain);
274
+ return to.some(h => h === d || h.endsWith("." + d));
275
+ });
276
+ if (both.length >= 10 && both.length * 10 >= others.length)
277
+ out.push({
278
+ kind: "reciprocal",
279
+ subject: "Sites you link to that link back",
280
+ why: `You link to ${both.length} of the ${others.length} sites that link to you, so many of the links go both ways.`,
281
+ look: `That's normal between partners, suppliers and sites that cover each other. It's worth a look if the links were swapped to get links: Google's spam policies count “Excessive link exchanges ("Link to me and I'll link to you") or partner pages exclusively for the sake of cross-linking” as link spam. ${ONLY}`,
282
+ examples: both.slice(0, 5).map(s => s.domain),
283
+ });
284
+ return out;
285
+ }
286
+
287
+ // An empty previous list may mean there was no export, so it isn't compared. Each export stops at 1,000 rows, so with
288
+ // either at 1,000 a "new" site may only have been past the cut before (capped).
289
+ export function newLinks(before, after, site) {
290
+ if (!Array.isArray(before?.sites) || !before.sites.length || !after?.length) return null;
291
+ const own = bare(site.hostname),
292
+ key = d => bare(String(d ?? "")),
293
+ mine = d => d === own || d.endsWith("." + own) || own.endsWith("." + d);
294
+ const had = new Set(before.sites.map(s => key(obj(s)?.domain)));
295
+ const fresh = after.filter(s => !had.has(key(s.domain)) && !mine(key(s.domain)));
296
+ return fresh.length
297
+ ? {
298
+ count: fresh.length,
299
+ sites: fresh.slice(0, 100).map(({ domain, links }) => ({ domain, links })),
300
+ since: typeof before.when === "string" ? before.when : null,
301
+ capped: before.sites.length >= 1000 || after.length >= 1000,
302
+ }
303
+ : null;
304
+ }
305
+
306
+ // Indexable crawled pages missing from Search Console's and Bing's linked pages, matched by path as in brokenLinked().
307
+ // Most pages of any site have no links from other sites, so this is never a finding.
308
+ export function unlinkedPages(linked, crawl, site) {
309
+ const host = bare(site.hostname),
310
+ url = u => {
311
+ try {
312
+ return new URL(u);
313
+ } catch {
314
+ return null;
315
+ }
316
+ },
317
+ pathOf = x => x.pathname + x.search;
318
+ const has = new Set(
319
+ linked
320
+ .map(l => url(l.url))
321
+ .filter(u => u && bare(u.hostname) === host)
322
+ .map(pathOf),
323
+ );
324
+ const pages = crawl.pages.filter(
325
+ p =>
326
+ obj(p) &&
327
+ !p.noindex &&
328
+ url(p.url) &&
329
+ (!p.canonical || pathOf(url(p.canonical) || url(p.url)) === pathOf(url(p.url))),
330
+ );
331
+ const none = pages.filter(p => !has.has(pathOf(url(p.url))));
332
+ return none.length ? { count: none.length, of: pages.length, urls: none.slice(0, 100).map(p => p.url) } : null;
333
+ }
334
+
335
+ // Latest links' date column (the linking page's last crawl) is never earlier than the day a link was found, so its
336
+ // newest date bounds when any link in it was found. https://support.google.com/webmasters/answer/9049606
337
+ const ISO = /^\d{4}-\d{2}-\d{2}/;
338
+ function newestLink(text) {
339
+ const rows = parseCsv(text),
340
+ heads = Object.keys(rows[0] || {});
341
+ const col = heads.find(h => rows.some(r => r[h]) && rows.every(r => !r[h] || ISO.test(r[h])));
342
+ return (
343
+ (col
344
+ ? rows
345
+ .map(r => String(r[col]).slice(0, 10))
346
+ .filter(d => ISO.test(d) && !isNaN(Date.parse(d)))
347
+ .sort()
348
+ : []
349
+ ).at(-1) || null
350
+ );
351
+ }
352
+ // No new link found for 3 months or more before the export's date: { newest, asOf }, or null.
353
+ export function noNewLinks(newest, asOf) {
354
+ if (!newest) return null;
355
+ const cut = new Date(asOf);
356
+ cut.setUTCMonth(cut.getUTCMonth() - 3);
357
+ return newest < cut.toISOString().slice(0, 10) ? { newest, asOf: new Date(asOf).toISOString().slice(0, 10) } : null;
358
+ }
359
+
360
+ // Linking sites (Search Console) or Bing's linked pages fell by 30% or more and by at least 10. A count is compared
361
+ // only when both summaries have it: an export missing this time is no data, not zero links. The bigger fall is
362
+ // reported.
363
+ export function linksChange(before, after) {
364
+ const fell = ["sites", "bingPages"]
365
+ .filter(
366
+ k =>
367
+ Number.isFinite(before?.[k]) &&
368
+ Number.isFinite(after[k]) &&
369
+ before[k] - after[k] >= 10 &&
370
+ (before[k] - after[k]) * 10 >= before[k] * 3,
371
+ )
372
+ .sort((a, b) => after[a] / before[a] - after[b] / before[b]);
373
+ return fell.length ? { kind: "links-dropped", what: fell[0], before: before[fell[0]], after: after[fell[0]] } : null;
374
+ }
375
+
376
+ // Linked pages the crawl found broken: 404 or 410, a redirect loop, or a redirect to the home page, which Google may
377
+ // treat as a soft 404. https://developers.google.com/search/docs/crawling-indexing/site-move-with-url-changes
378
+ // Matched by path so a local crawl works; other hosts' pages and pages the crawl didn't reach aren't judged.
379
+ function brokenLinked(linked, crawl, site) {
380
+ const host = bare(site.hostname),
381
+ url = u => {
382
+ try {
383
+ return new URL(u);
384
+ } catch {
385
+ return null;
386
+ }
387
+ },
388
+ pathOf = x => x.pathname + x.search;
389
+ const byPath = list =>
390
+ new Map(
391
+ (list || [])
392
+ .map(x => [url(x.url ?? x.from), x])
393
+ .filter(([u]) => u)
394
+ .map(([u, x]) => [pathOf(u), x]),
395
+ );
396
+ const pages = byPath(crawl.pages),
397
+ errors = byPath(crawl.errors),
398
+ redirects = byPath(crawl.redirects);
399
+ // The home page's other addresses (index.html, default.aspx, /home, a bare language prefix like /en/ or /en-us/)
400
+ // belong there.
401
+ const homeAlias = p => /^\/((index|default)\.\w+|home\/?|[a-z]{2}([-_][a-z]{2})?\/?)$/i.test(p);
402
+ const toHome = r => {
403
+ const t = url(r.to),
404
+ f = url(r.from);
405
+ return (
406
+ !!t &&
407
+ !!f &&
408
+ t.pathname === "/" &&
409
+ !t.search &&
410
+ pathOf(f) !== "/" &&
411
+ !homeAlias(f.pathname) &&
412
+ (t.origin === f.origin || bare(t.hostname) === host)
413
+ );
414
+ };
415
+ const seen = new Set(),
416
+ broken = [];
417
+ let unreached = 0;
418
+ for (const l of linked) {
419
+ const u = url(l.url);
420
+ if (!u || bare(u.hostname) !== host || seen.has(pathOf(u))) continue;
421
+ seen.add(pathOf(u));
422
+ const r = redirects.get(pathOf(u)),
423
+ status = errors.get(pathOf(u))?.status;
424
+ const why =
425
+ r && r.to == null
426
+ ? "redirects in a loop"
427
+ : r && toHome(r)
428
+ ? "redirects to the home page"
429
+ : status === 404 || status === 410
430
+ ? `returns ${status}`
431
+ : null;
432
+ const n = l.links,
433
+ from =
434
+ n == null
435
+ ? "linked from other sites"
436
+ : `${n.toLocaleString("en-US")} link${n === 1 ? "" : "s"} from other sites`;
437
+ if (why) broken.push({ url: l.url, links: n ?? 0, detail: `${why} · ${from} (${l.source})` });
438
+ else if (!r && !pages.has(pathOf(u)) && !errors.has(pathOf(u))) unreached++;
439
+ }
440
+ broken.sort((a, b) => b.links - a.links);
441
+ const findings = broken.length
442
+ ? [
443
+ {
444
+ id: "I-001",
445
+ check: "linked-page-broken",
446
+ rule: "URL-07",
447
+ severity: "medium",
448
+ category: "URLs & canonicals",
449
+ title: `${broken.length} page(s) other sites link to are broken or redirect to the home page`,
450
+ what: foundOn(broken.length, broken[0]),
451
+ why: "Other sites link to these pages, but they now return 404 or 410, redirect in a loop, or redirect to the home page, which Google may treat as a soft 404. Visitors who follow those links hit a dead end, and what the links brought the site is lost.",
452
+ fix: "Redirect each one with a 301 to the closest live page: the page that replaced it, or its section, never just the home page. If the content is gone for good and nothing comes close, keep the 404 or 410 and ask the linking sites to update the link (Search Console's Links report lists them).",
453
+ count: broken.length,
454
+ evidence: broken.slice(0, 100).map(b => ({ url: b.url, detail: b.detail })),
455
+ source: "links-import",
456
+ status: "open",
457
+ },
458
+ ]
459
+ : [];
460
+ return { findings, unreached };
461
+ }
462
+
463
+ function main(argv) {
464
+ const args = parseArgs(argv, {
465
+ flags: ["dir", "site", "brand", "keys", "previous", "crawl", "out"],
466
+ positionals: 0,
467
+ usage: USAGE,
468
+ });
469
+ const str = k => (typeof args[k] === "string" ? args[k] : null);
470
+ if (!str("dir") || !str("site")) throw new Fail(USAGE);
471
+ let site;
472
+ try {
473
+ site = new URL(args.site);
474
+ } catch {}
475
+ if (!site || !/^https?:$/.test(site.protocol))
476
+ throw new Fail(`links-import: --site must be the site's address, like https://www.example.com (got ${args.site})`);
477
+ const notes = [],
478
+ dir = resolve(args.dir);
479
+ // Subfolders too, so several zips can be unzipped side by side. Files are told apart by their columns, not names.
480
+ const all = existsSync(dir) && statSync(dir).isDirectory() ? readdirSync(dir, { recursive: true }).map(String) : [];
481
+
482
+ // Newest file first, so a second export of the same table replaces the older one.
483
+ // A list of linking pages whose name says "latest" is read as Latest links, for its newest date: More sample links
484
+ // has the same columns, but it's a sample, so its dates say nothing about new links.
485
+ const got = {};
486
+ let latest = null;
487
+ for (const f of all
488
+ .filter(f => /\.csv$/i.test(f))
489
+ .sort((a, b) => statSync(join(dir, b)).mtimeMs - statSync(join(dir, a)).mtimeMs)) {
490
+ const text = readFileSync(join(dir, f), "utf8"),
491
+ x = readExport(text, site.href),
492
+ newest = !x.kind && /latest/i.test(basename(f)) ? newestLink(text) : null;
493
+ if (newest && !latest) latest = { newest, when: statSync(join(dir, f)).mtime };
494
+ if (!x.kind)
495
+ notes.push(
496
+ newest
497
+ ? `${f} was read as Search Console's Latest links export, for the date of the newest link. To check those links are still there, pass it to backlinks.mjs --csv.`
498
+ : `${f} isn't Search Console's Top linking sites, Top linking text or Top linked pages export, so it wasn't read. A list of linking pages (Latest links or More sample links) goes to backlinks.mjs --csv instead, which checks those links are still there. Keep "latest" in the name of the Latest links export: its dates show whether new links still arrive.`,
499
+ );
500
+ else if (got[x.kind]) notes.push(`${f} is another ${NAME[x.kind]} export; the newer ${got[x.kind].f} was used.`);
501
+ else got[x.kind] = { f, rows: x.rows, when: statSync(join(dir, f)).mtime };
502
+ }
503
+ const kinds = Object.keys(got),
504
+ rows = k => got[k]?.rows || [];
505
+ const links = kinds.length
506
+ ? {
507
+ sites: rows("sites"),
508
+ texts: rows("texts"),
509
+ pages: rows("pages"),
510
+ source: "search-console",
511
+ when: new Date(Math.max(...kinds.map(k => got[k].when))).toISOString(),
512
+ }
513
+ : null;
514
+ const zips = all.filter(f => /\.zip$/i.test(f)).length;
515
+ if (!links)
516
+ notes.push(
517
+ `No Search Console links export was found in ${args.dir}${zips ? ` (${zips} zip file${zips === 1 ? " is" : "s are"} there: unzip ${zips === 1 ? "it" : "them"} first)` : ""}, so links from other sites weren't summarised this time. In Search Console, open Links, click More under Top linking sites, Top linking text and Top linked pages, and export each as CSV into that folder.`,
518
+ );
519
+
520
+ const brand = withSiteName(str("brand"), site.hostname);
521
+ if (links?.texts.length)
522
+ notes.push(
523
+ `Link text counts as your brand when it contains “${brand.split("|").join("” or “")}”${str("brand") ? " (from --brand and the site's address)" : ", taken from the site's address. Pass --brand with the business name if it's different"}.`,
524
+ );
525
+ const readJson = (f, what) => {
526
+ try {
527
+ return JSON.parse(readFileSync(f, "utf8"));
528
+ } catch (e) {
529
+ notes.push(
530
+ `Couldn't read ${f} (${e.code === "ENOENT" ? "it isn't there" : e.code || "it isn't JSON"}), so ${what}.`,
531
+ );
532
+ return null;
533
+ }
534
+ };
535
+ const keys = str("keys") ? readJson(args.keys, "Bing's linked pages weren't counted") : null;
536
+ const linkSummary = {
537
+ sites: got.sites ? links.sites.length : null,
538
+ pages: got.pages ? links.pages.length : null,
539
+ bingPages: Array.isArray(keys?.bing?.backlinks?.pages) ? keys.bing.backlinks.pages.length : null,
540
+ };
541
+ const previous = str("previous") ? readJson(args.previous, "there was nothing to compare with") : null;
542
+ // Checked against the crawl's data only; nothing is fetched.
543
+ let findings = [],
544
+ unlinked = null;
545
+ const crawl = str("crawl")
546
+ ? readJson(args.crawl, "the pages other sites link to weren't checked against the crawl")
547
+ : null;
548
+ if (crawl && !Array.isArray(crawl.pages))
549
+ notes.push(
550
+ `${args.crawl} isn't the crawler's seo-crawl.json, so the pages other sites link to weren't checked against it.`,
551
+ );
552
+ else if (crawl) {
553
+ const bing = Array.isArray(keys?.bing?.backlinks?.pages)
554
+ ? keys.bing.backlinks.pages.filter(obj).map(p => ({ url: p.url, links: p.count ?? null, source: "Bing" }))
555
+ : [];
556
+ // Pages with no links from other sites: only from a Top linked pages export under 1,000 rows, the most it holds.
557
+ if (got.pages && links.pages.length >= 1000)
558
+ notes.push(
559
+ "Top linked pages has 1,000 rows, the most an export holds, so pages past the cut may have links from other sites too: the pages with none weren't listed.",
560
+ );
561
+ else if (got.pages) unlinked = unlinkedPages([...links.pages, ...bing], crawl, site);
562
+ const checked = brokenLinked(
563
+ [...(links?.pages || []).map(p => ({ ...p, source: "Search Console" })), ...bing],
564
+ crawl,
565
+ site,
566
+ );
567
+ findings = checked.findings;
568
+ const n = checked.unreached;
569
+ if (n)
570
+ notes.push(
571
+ `${n} of the pages other sites link to ${n === 1 ? "wasn't" : "weren't"} reached by the crawl, so whether ${n === 1 ? "it still works" : "they still work"} wasn't checked. List them in a file, one per line, pass it to seo-crawl.mjs with --urls and run links-import again: the ones that fail or redirect are judged then.`,
572
+ );
573
+ }
574
+ const sample = Array.isArray(keys?.bing?.backlinks?.sample) ? keys.bing.backlinks.sample.filter(obj) : [];
575
+ const look = worthALook(
576
+ { sites: links?.sites, texts: links?.texts, sample, outDomains: obj(crawl?.linksToOtherSites)?.domains },
577
+ site,
578
+ brand,
579
+ );
580
+ const result = {
581
+ links,
582
+ linkSummary,
583
+ anchorMix: links?.texts.length ? anchorMix(links.texts, brand) : null,
584
+ linksChange: linksChange(obj(previous?.linkSummary), linkSummary),
585
+ newLinks: got.sites ? newLinks(obj(previous?.links), links.sites, site) : null,
586
+ noNewLinks: latest && noNewLinks(latest.newest, latest.when),
587
+ unlinkedPages: unlinked,
588
+ worthALook: look,
589
+ findings,
590
+ notes,
591
+ };
592
+
593
+ const out = resolve(str("out") || "seo-audit/links.json");
594
+ mkdirSync(dirname(out), { recursive: true });
595
+ writeFileSync(out, JSON.stringify(result, null, 2));
596
+ const c = result.linksChange;
597
+ console.log(
598
+ `links-import: ${links ? `${links.sites.length} linking sites, ${links.pages.length} linked pages, ${links.texts.length} link texts` : "no Search Console export"}${c ? ` · ${c.what} dropped ${c.before} → ${c.after}` : ""}${result.newLinks ? ` · ${result.newLinks.count} new linking site${result.newLinks.count === 1 ? "" : "s"}` : ""}${result.noNewLinks ? ` · no new links found since ${result.noNewLinks.newest}` : ""}${findings.length ? ` · ${findings[0].count} linked page(s) broken` : ""}${look.length ? ` · ${look.length} worth a look` : ""} · wrote ${out}`,
599
+ );
600
+ return 0;
601
+ }
602
+
603
+ if (isMain(import.meta.url)) await runMain(() => main(process.argv.slice(2)));