sanity-plugin-seo-copilot 0.2.1 → 0.2.5

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.
@@ -32,9 +32,17 @@ function wordCount(s: string): number {
32
32
 
33
33
  export function analyzeHeadings(text: string, headings: string[]): HeadingAudit[] {
34
34
  if (!text || headings.length === 0) return [];
35
+ // Only QUESTION headings (those ending in "?") get a short-answer audit: the
36
+ // 40-60 word direct answer after a question is the chunk AI engines extract. A
37
+ // section/list heading ("Trials to Watch") - or a declarative one that merely
38
+ // starts with "Is"/"Are" ("Is This the Future of Oncology") - is not a question
39
+ // and shouldn't be audited. Requiring "?" also matches the AEO score's counter.
40
+ const isQuestion = (h: string) => /\?\s*$/.test(h.trim());
41
+ const questionHeadings = headings.filter(isQuestion);
42
+ if (questionHeadings.length === 0) return [];
35
43
  const headingSet = new Set(headings.map((h) => h.trim().toLowerCase()));
36
44
  const lower = text.toLowerCase();
37
- return headings.map((heading) => {
45
+ return questionHeadings.map((heading) => {
38
46
  const needle = heading.trim().toLowerCase();
39
47
  const idx = lower.indexOf(needle);
40
48
  if (idx === -1) {
@@ -75,7 +83,9 @@ export function analyzeFactDensity(text: string): FactDensityResult {
75
83
  const factsPer1000 = Math.round((factCount / total) * 1000);
76
84
 
77
85
  // Drift passages: sliding 200-word windows with zero facts
78
- const sentences = text.split(/(?<=[.!?])\s+/).filter((s) => s.trim().length > 0);
86
+ // NB: no lookbehind regex here - `(?<=...)` throws on Safari < 16.4 and would
87
+ // crash the whole AEO tab. Split on sentence-ending punctuation + whitespace.
88
+ const sentences = text.split(/[.!?]+\s+/).filter((s) => s.trim().length > 0);
79
89
  let drift = 0;
80
90
  let runWords = 0;
81
91
  let runHasFact = false;
@@ -93,8 +103,11 @@ export function analyzeFactDensity(text: string): FactDensityResult {
93
103
  // 2026 GEO research (Princeton, Averi citation benchmarks): the center of the
94
104
  // recommended fact-density range is ~8 stats per 1,000 words (1 every ~125
95
105
  // words). Anything below ~4/1k consistently under-cites in AI Overviews.
106
+ // Status is density-only. Drift passages (long stretches with no stat) are a
107
+ // SEPARATE signal surfaced on their own - they shouldn't demote an article
108
+ // that is otherwise densely-cited just because it has one narrative paragraph.
96
109
  let status: FactDensityResult["status"];
97
- if (factsPer1000 >= 8 && drift === 0) status = "strong";
110
+ if (factsPer1000 >= 8) status = "strong";
98
111
  else if (factsPer1000 >= 4) status = "moderate";
99
112
  else status = "weak";
100
113
 
@@ -1,4 +1,4 @@
1
- import type { SEOAnalysis } from "./types";
1
+ import type { SEOAnalysis, DocumentFields } from "./types";
2
2
 
3
3
  export interface ScoreComponent {
4
4
  label: string;
@@ -16,7 +16,7 @@ export interface ContentScore {
16
16
  * Client-side content score (0-100) with per-component breakdown.
17
17
  * Mirrors backend scoring.ts.
18
18
  */
19
- export function calculateContentScoreDetailed(content: string, analysis: SEOAnalysis): ContentScore {
19
+ export function calculateContentScoreDetailed(content: string, analysis: SEOAnalysis, documentFields?: DocumentFields): ContentScore {
20
20
  if (!content || !analysis) {
21
21
  return { total: 0, components: [] };
22
22
  }
@@ -31,13 +31,17 @@ export function calculateContentScoreDetailed(content: string, analysis: SEOAnal
31
31
  const primaryRegex = new RegExp(escaped, "gi");
32
32
  const primaryMatches = content.match(primaryRegex);
33
33
  const primaryCount = primaryMatches?.length || 0;
34
+ // Density counts keyword WORDS, not phrase occurrences, so a multi-word
35
+ // primary isn't unfairly scored "too thin": one mention of a 4-word phrase
36
+ // in 760 words reads as ~0.5% (the healthy floor), not 0.13%.
37
+ const primaryWordCount = Math.max(1, primaryTerm.split(/\s+/).filter(Boolean).length);
34
38
  let pts = 0;
35
39
  let detail: string;
36
40
  if (primaryCount === 0) {
37
41
  detail = `Primary keyword "${primaryTerm}" not found in content`;
38
42
  } else {
39
43
  pts += 12;
40
- const density = words > 0 ? (primaryCount / words) * 100 : 0;
44
+ const density = words > 0 ? ((primaryCount * primaryWordCount) / words) * 100 : 0;
41
45
  if (density >= 0.5 && density <= 2.5) {
42
46
  pts += 13;
43
47
  detail = `Primary keyword present, density ${density.toFixed(2)}% (ideal range)`;
@@ -89,15 +93,28 @@ export function calculateContentScoreDetailed(content: string, analysis: SEOAnal
89
93
  components.push({ label: "Word count", points: wcPts, max: 15, detail: wcDetail });
90
94
 
91
95
  // 4. Heading structure (up to 10)
92
- const hasH1orTitle = /^#\s|<h1/im.test(content);
93
- const hasSubheadings = /^##\s|^###\s|<h2|<h3/im.test(content);
96
+ // Prefer the structured heading data the plugin extracts from Portable Text.
97
+ // The plain `content` string has no markup, so regexing it for #/<h3> always
98
+ // misses real headings - fall back to the regex only for plain-text callers.
99
+ let hasH1orTitle: boolean;
100
+ let hasSubheadings: boolean;
101
+ if (documentFields) {
102
+ hasH1orTitle = !!(documentFields.title && documentFields.title.trim());
103
+ const det = documentFields.headingsDetailed;
104
+ hasSubheadings = det
105
+ ? det.some((h) => h.level >= 2 && h.level <= 4)
106
+ : (documentFields.headings?.length || 0) > 0;
107
+ } else {
108
+ hasH1orTitle = /^#\s|<h1/im.test(content);
109
+ hasSubheadings = /^##\s|^###\s|<h2|<h3/im.test(content);
110
+ }
94
111
  const structurePts = (hasH1orTitle ? 5 : 0) + (hasSubheadings ? 5 : 0);
95
112
  const structureDetail = !hasH1orTitle && !hasSubheadings
96
- ? "No headings detected - add H2/H3 structure"
113
+ ? "No title or subheadings detected"
97
114
  : !hasSubheadings
98
- ? "Has title but no subheadings"
115
+ ? "Has a title but no H2/H3 subheadings - add section headings"
99
116
  : !hasH1orTitle
100
- ? "Has subheadings but no clear H1"
117
+ ? "Has subheadings but no title"
101
118
  : "Title and subheadings present";
102
119
  components.push({ label: "Heading structure", points: structurePts, max: 10, detail: structureDetail });
103
120
 
@@ -122,13 +139,19 @@ export function calculateContentScoreDetailed(content: string, analysis: SEOAnal
122
139
  // 6. AEO signals (up to 10) - question-format headings that Google answer
123
140
  // features and AI engines surface directly. (FAQ scoring removed May 2026 after
124
141
  // Google sunset FAQ rich results - question headings are the modern equivalent.)
142
+ // Detect from the structured heading list (plain `content` has no heading
143
+ // markup to regex). Single clean tier: 0 / 4 / 7 / 10 for 0 / 1 / 2 / 3+.
144
+ let qCount: number;
145
+ if (documentFields) {
146
+ qCount = (documentFields.headings || []).filter((h) => h.trim().endsWith("?")).length;
147
+ } else {
148
+ const questionHeadings = content.match(/^#{1,6}\s+.*\?$/gm) || content.match(/<h[1-6][^>]*>.*\?<\/h[1-6]>/gi);
149
+ qCount = questionHeadings?.length || 0;
150
+ }
125
151
  let aeoPts = 0;
126
- const questionHeadings = content.match(/^#{1,6}\s+.*\?$/gm) || content.match(/<h[1-6][^>]*>.*\?<\/h[1-6]>/gi);
127
- const qCount = questionHeadings?.length || 0;
128
- if (qCount >= 3) aeoPts += 6;
129
- else if (qCount === 2) aeoPts += 4;
130
- else if (qCount === 1) aeoPts += 2;
131
- if (qCount > 0) aeoPts += 4;
152
+ if (qCount >= 3) aeoPts = 10;
153
+ else if (qCount === 2) aeoPts = 7;
154
+ else if (qCount === 1) aeoPts = 4;
132
155
  const aeoDetail =
133
156
  qCount === 0
134
157
  ? "No question-style headings - AI answer engines favor them"
@@ -31,6 +31,21 @@ function tokensContain(haystack: string, needle?: string): boolean {
31
31
  return tokens.every((t) => lower.includes(t));
32
32
  }
33
33
 
34
+ // Conference previews, news briefs, recaps, and listicles are legitimately short.
35
+ // Detect them so we don't nag "push past 1,500 words" on content that should be
36
+ // short. Uses the contentCategory field when present, else title-pattern signals.
37
+ function isShortFormContent(documentFields?: DocumentFields, title?: string): boolean {
38
+ // Token-match the category (not substring) so "newsletter" doesn't match "news"
39
+ // and "updated-guidelines" doesn't match "update".
40
+ const shortFormCats = new Set(["news", "brief", "preview", "recap", "update", "announcement", "roundup", "digest", "interview"]);
41
+ const catTokens = (documentFields?.contentCategory || "").toLowerCase().split(/[^a-z]+/).filter(Boolean);
42
+ if (catTokens.some((tok) => shortFormCats.has(tok))) return true;
43
+ const t = (title || "").toLowerCase();
44
+ if (/\b(preview|recap|roundup|digest)\b/.test(t)) return true;
45
+ if (/:\s*\d+\s+(trials|things|takeaways|highlights|tips|questions|charts)/.test(t)) return true;
46
+ return false;
47
+ }
48
+
34
49
  export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
35
50
  const items: SummaryItem[] = [];
36
51
  // contentScore is in BuildSummaryInput for forward-compat but is now shown
@@ -190,14 +205,14 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
190
205
  howToFix: "Add more body text. A link or image on its own doesn't count - the article needs real written substance.",
191
206
  jumpTo: { tab: "technical", anchorId: "anchor-word-count" },
192
207
  });
193
- } else if (wordCount < 1500) {
208
+ } else if (wordCount < 1500 && !isShortFormContent(documentFields, title)) {
194
209
  items.push({
195
210
  id: "content-short-for-clinical",
196
211
  category: "content",
197
- severity: "warning",
212
+ severity: "opportunity",
198
213
  label: "Article could be longer",
199
- description: `${wordCount} words. 1,500+ is the standard for competitive clinical articles.`,
200
- howToFix: "Expand sections with citations, comparative data, or guideline references.",
214
+ description: `${wordCount} words. For evergreen clinical topics 1,500+ tends to rank better - news, previews, and briefs are fine shorter.`,
215
+ howToFix: "If this is an in-depth clinical piece, expand with citations, comparative data, or guideline references. For news or previews, this length is appropriate.",
201
216
  jumpTo: { tab: "technical", anchorId: "anchor-word-count" },
202
217
  });
203
218
  }
@@ -208,8 +223,9 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
208
223
  // H2 count - prefer the detailed list (which records actual levels). When only
209
224
  // a flat list is available the typical case is "all H2s", so we use the total
210
225
  // as a fallback approximation.
226
+ // Count H2 AND H3 as section headings - an H3-only article is still sectioned.
211
227
  const h2Count = headingsDetailed
212
- ? headingsDetailed.filter((h) => h.level === 2).length
228
+ ? headingsDetailed.filter((h) => h.level === 2 || h.level === 3).length
213
229
  : headings.length;
214
230
  if (headings.length === 0 && wordCount > 200 && wordCount < 1000) {
215
231
  items.push({
@@ -387,6 +403,21 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
387
403
  jumpTo: { tab: "keywords" },
388
404
  });
389
405
  }
406
+ // Primary keyword with no measurable search volume. Only meaningful once deep
407
+ // analysis has fetched real SEMrush volumes (realtime leaves volume null), so
408
+ // gate on deepAnalysis to avoid false warnings mid-typing.
409
+ const primaryVolume = analysis?.primaryKeyword?.volume;
410
+ if (deepAnalysis && (primaryVolume === 0 || primaryVolume === null)) {
411
+ items.push({
412
+ id: "keywords-primary-zero-volume",
413
+ category: "keywords",
414
+ severity: "warning",
415
+ label: "Primary keyword has no search volume",
416
+ description: `"${primaryKeyword}" shows no measurable monthly searches, so even ranking #1 brings little traffic.`,
417
+ howToFix: "Pick a primary people actually search for - check your supporting keywords for higher-volume options, or set a new primary on the Keywords tab.",
418
+ jumpTo: { tab: "keywords" },
419
+ });
420
+ }
390
421
  }
391
422
 
392
423
  // ---------- CONTENT SCORE ----------
@@ -396,8 +427,13 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
396
427
  // short title, etc.) already produce their own actionable items above.
397
428
 
398
429
  // ---------- AEO: question headings ----------
399
- const questionHeadings = deepAnalysis?.aeo?.questionHeadings || [];
400
- if (deepAnalysis && questionHeadings.length === 0 && wordCount > 300) {
430
+ // Count the question headings the editor has ACTUALLY written (ending in "?"),
431
+ // matching the AEO score signal - NOT Claude's rewrite suggestions, which would
432
+ // contradict the score (an article with a real "?" heading must not also be told
433
+ // it has "no question-style headings"). Gate on deepAnalysis so it only surfaces
434
+ // once that tab has run.
435
+ const actualQuestionHeadings = (documentFields?.headings || []).filter((h) => h.trim().endsWith("?"));
436
+ if (deepAnalysis && actualQuestionHeadings.length === 0 && wordCount > 300) {
401
437
  items.push({
402
438
  id: "aeo-no-question-headings",
403
439
  category: "aeo",
@@ -437,6 +473,10 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
437
473
 
438
474
  // ---------- TECHNICAL: broken links (Other Recs tab) ----------
439
475
  // Only surfaces after the editor has actually run the check on the Other Recs tab.
476
+ // Truly broken (404/5xx/timeout/DNS-fail) is an error. 401/403/429 are
477
+ // "unverified" - the link may work for human readers but our server fetch was
478
+ // blocked by an anti-bot WAF, so we surface those as a softer warning rather
479
+ // than panicking the editor about links that are actually fine.
440
480
  if (linkCheckResults && linkCheckResults.length > 0) {
441
481
  const broken = linkCheckResults.filter((r) => r.category === "broken" || r.category === "error");
442
482
  if (broken.length > 0) {
@@ -450,6 +490,18 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
450
490
  jumpTo: { tab: "technical", anchorId: "anchor-link-check" },
451
491
  });
452
492
  }
493
+ const unverified = linkCheckResults.filter((r) => r.category === "unverified");
494
+ if (unverified.length > 0) {
495
+ items.push({
496
+ id: "unverified-links",
497
+ category: "technical",
498
+ severity: "warning",
499
+ label: `${unverified.length} link${unverified.length === 1 ? "" : "s"} couldn't be auto-verified`,
500
+ description: `${unverified.length} link${unverified.length === 1 ? " was" : "s were"} blocked by an anti-bot wall (401/403/429) - the URLs may work fine for readers, our server just couldn't confirm.`,
501
+ howToFix: "Open each one manually in a new tab to confirm it loads, then ignore the warning if it does.",
502
+ jumpTo: { tab: "technical", anchorId: "anchor-link-check" },
503
+ });
504
+ }
453
505
  }
454
506
 
455
507
  // ---------- DEEP ANALYSIS: readability / gaps / structure ----------
package/src/lib/types.ts CHANGED
@@ -179,7 +179,10 @@ export interface LinkCheckResult {
179
179
  // True when the request landed on a different URL than the original.
180
180
  redirected: boolean;
181
181
  // One-word category for the badge in the UI.
182
- category: "ok" | "redirect" | "broken" | "error";
182
+ // "unverified" = the URL responded 401/403/429 - usually anti-bot blocking
183
+ // server-side fetches (e.g. Cloudflare blocking cloud-provider egress IPs).
184
+ // The link may work fine for human readers; editors should click to verify.
185
+ category: "ok" | "redirect" | "broken" | "unverified" | "error";
183
186
  // Human-friendly message used when category is "error" (timeout, DNS fail, etc.).
184
187
  error?: string;
185
188
  }