sanity-plugin-seo-copilot 0.1.2 → 0.2.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.
@@ -0,0 +1,109 @@
1
+ // Client-side Generative Engine Optimization (GEO) analysis.
2
+ // 2026 research: AI engines (ChatGPT, Perplexity, Gemini, Google AI Overviews)
3
+ // preferentially cite content with high fact-density (verifiable stats every
4
+ // 150-200 words) and direct-answer blocks (40-60 word answers right after
5
+ // question / topic headings - the RAG extraction pattern).
6
+
7
+ const FACT_PATTERN =
8
+ /\d+(?:\.\d+)?\s*%|\b\d{1,3}(?:,\d{3})+\b|\bn\s*=\s*\d+\b|\bp\s*[<=]\s*0?\.\d+\b|\b\d+(?:\.\d+)?\s*(?:patients|participants|subjects|cases|deaths|adverse events|mg|mcg|hours|days|weeks|months|years|fold|x)\b|\b(?:NEJM|JAMA|FDA|EMA|CDC|WHO|NIH|ACC|ASCO|ASH|ESMO|AHA|ACS)\b|\bet al\.?\b|\b(?:phase|stage)\s+(?:I{1,3}V?|1|2|3|4)\b/i;
9
+
10
+ export interface HeadingAudit {
11
+ heading: string;
12
+ words: number;
13
+ status: "good" | "too-short" | "too-long" | "missing-body";
14
+ }
15
+
16
+ export interface FactDensityResult {
17
+ totalWords: number;
18
+ factCount: number;
19
+ factsPerThousandWords: number;
20
+ driftPassages: number;
21
+ status: "strong" | "moderate" | "weak";
22
+ }
23
+
24
+ export interface GEOAnalysis {
25
+ headingAudit: HeadingAudit[];
26
+ factDensity: FactDensityResult;
27
+ }
28
+
29
+ function wordCount(s: string): number {
30
+ return s.trim().split(/\s+/).filter(Boolean).length;
31
+ }
32
+
33
+ export function analyzeHeadings(text: string, headings: string[]): HeadingAudit[] {
34
+ if (!text || headings.length === 0) return [];
35
+ const headingSet = new Set(headings.map((h) => h.trim().toLowerCase()));
36
+ const lower = text.toLowerCase();
37
+ return headings.map((heading) => {
38
+ const needle = heading.trim().toLowerCase();
39
+ const idx = lower.indexOf(needle);
40
+ if (idx === -1) {
41
+ return { heading, words: 0, status: "missing-body" as const };
42
+ }
43
+ // Walk the lines after the heading: collect non-empty lines that aren't themselves
44
+ // another heading. Stop at the next heading (the next section starts).
45
+ // Portable Text blocks are joined with single \n by useDocumentContent.extractText,
46
+ // so the "answer paragraph" is the next non-empty, non-heading line(s).
47
+ const after = text.slice(idx + heading.length);
48
+ const lines = after.split(/\n/);
49
+ const answerParts: string[] = [];
50
+ for (const raw of lines) {
51
+ const t = raw.trim();
52
+ if (!t) continue;
53
+ if (headingSet.has(t.toLowerCase())) break;
54
+ answerParts.push(t);
55
+ // Cap collection so we don't walk an entire article if no next heading exists
56
+ const sofar = answerParts.join(" ");
57
+ if (sofar.split(/\s+/).length > 120) break;
58
+ }
59
+ const words = wordCount(answerParts.join(" "));
60
+ if (words === 0) return { heading, words: 0, status: "missing-body" as const };
61
+ if (words < 30) return { heading, words, status: "too-short" as const };
62
+ if (words > 70) return { heading, words, status: "too-long" as const };
63
+ return { heading, words, status: "good" as const };
64
+ });
65
+ }
66
+
67
+ export function analyzeFactDensity(text: string): FactDensityResult {
68
+ const total = wordCount(text);
69
+ if (total === 0) {
70
+ return { totalWords: 0, factCount: 0, factsPerThousandWords: 0, driftPassages: 0, status: "weak" };
71
+ }
72
+ // Count facts
73
+ const matches = text.match(new RegExp(FACT_PATTERN.source, "gi")) || [];
74
+ const factCount = matches.length;
75
+ const factsPer1000 = Math.round((factCount / total) * 1000);
76
+
77
+ // Drift passages: sliding 200-word windows with zero facts
78
+ const sentences = text.split(/(?<=[.!?])\s+/).filter((s) => s.trim().length > 0);
79
+ let drift = 0;
80
+ let runWords = 0;
81
+ let runHasFact = false;
82
+ for (const s of sentences) {
83
+ const w = wordCount(s);
84
+ if (new RegExp(FACT_PATTERN.source, "i").test(s)) runHasFact = true;
85
+ runWords += w;
86
+ if (runWords >= 200) {
87
+ if (!runHasFact) drift += 1;
88
+ runWords = 0;
89
+ runHasFact = false;
90
+ }
91
+ }
92
+
93
+ // 2026 GEO research (Princeton, Averi citation benchmarks): the center of the
94
+ // recommended fact-density range is ~8 stats per 1,000 words (1 every ~125
95
+ // words). Anything below ~4/1k consistently under-cites in AI Overviews.
96
+ let status: FactDensityResult["status"];
97
+ if (factsPer1000 >= 8 && drift === 0) status = "strong";
98
+ else if (factsPer1000 >= 4) status = "moderate";
99
+ else status = "weak";
100
+
101
+ return { totalWords: total, factCount, factsPerThousandWords: factsPer1000, driftPassages: drift, status };
102
+ }
103
+
104
+ export function analyzeGEO(text: string, headings: string[]): GEOAnalysis {
105
+ return {
106
+ headingAudit: analyzeHeadings(text, headings),
107
+ factDensity: analyzeFactDensity(text),
108
+ };
109
+ }
@@ -0,0 +1,69 @@
1
+ import { useState, useCallback, useEffect, useRef } from "react";
2
+
3
+ // localStorage so state survives:
4
+ // - dock/undock toggle (PanelContent remount)
5
+ // - tab switches (defensive, even though display:none preserves)
6
+ // - full page reload / browser close
7
+ // - Vite HMR rebuilds during local dev
8
+
9
+ const LS: Storage | null = typeof window !== "undefined" ? window.localStorage : null;
10
+
11
+ export function loadLocal<T>(key: string, fallback: T): T {
12
+ try {
13
+ if (!LS) return fallback;
14
+ const raw = LS.getItem(key);
15
+ if (raw === null) return fallback;
16
+ return JSON.parse(raw) as T;
17
+ } catch {
18
+ return fallback;
19
+ }
20
+ }
21
+
22
+ export function saveLocal(key: string, value: unknown): void {
23
+ try {
24
+ if (!LS) return;
25
+ LS.setItem(key, JSON.stringify(value));
26
+ } catch {
27
+ // localStorage may throw on quota / private mode - silent fallback to in-memory only
28
+ }
29
+ }
30
+
31
+ export function removeLocal(key: string): void {
32
+ try {
33
+ if (!LS) return;
34
+ LS.removeItem(key);
35
+ } catch {
36
+ /* silent */
37
+ }
38
+ }
39
+
40
+ /**
41
+ * useState that persists to localStorage. Value is reloaded when key changes
42
+ * (e.g., when documentId changes for per-doc keys).
43
+ */
44
+ export function usePersistentState<T>(
45
+ key: string,
46
+ initial: T
47
+ ): [T, (v: T | ((prev: T) => T)) => void] {
48
+ const [val, setVal] = useState<T>(() => loadLocal(key, initial));
49
+ // Track which key we currently hold so we don't reload on first render.
50
+ const heldKey = useRef(key);
51
+ useEffect(() => {
52
+ if (heldKey.current === key) return;
53
+ heldKey.current = key;
54
+ setVal(loadLocal(key, initial));
55
+ // eslint-disable-next-line react-hooks/exhaustive-deps
56
+ }, [key]);
57
+
58
+ const set = useCallback(
59
+ (v: T | ((prev: T) => T)) => {
60
+ setVal((prev) => {
61
+ const next = typeof v === "function" ? (v as (p: T) => T)(prev) : v;
62
+ saveLocal(key, next);
63
+ return next;
64
+ });
65
+ },
66
+ [key]
67
+ );
68
+ return [val, set];
69
+ }
@@ -0,0 +1,147 @@
1
+ import type { SEOAnalysis } from "./types";
2
+
3
+ export interface ScoreComponent {
4
+ label: string;
5
+ points: number;
6
+ max: number;
7
+ detail: string;
8
+ }
9
+
10
+ export interface ContentScore {
11
+ total: number;
12
+ components: ScoreComponent[];
13
+ }
14
+
15
+ /**
16
+ * Client-side content score (0-100) with per-component breakdown.
17
+ * Mirrors backend scoring.ts.
18
+ */
19
+ export function calculateContentScoreDetailed(content: string, analysis: SEOAnalysis): ContentScore {
20
+ if (!content || !analysis) {
21
+ return { total: 0, components: [] };
22
+ }
23
+ const lowerContent = content.toLowerCase();
24
+ const words = content.split(/\s+/).filter(Boolean).length;
25
+ const components: ScoreComponent[] = [];
26
+
27
+ // 1. Primary keyword (up to 25)
28
+ const primaryTerm = (analysis.primaryKeyword?.term || "").toLowerCase();
29
+ if (primaryTerm) {
30
+ const escaped = primaryTerm.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
31
+ const primaryRegex = new RegExp(escaped, "gi");
32
+ const primaryMatches = content.match(primaryRegex);
33
+ const primaryCount = primaryMatches?.length || 0;
34
+ let pts = 0;
35
+ let detail: string;
36
+ if (primaryCount === 0) {
37
+ detail = `Primary keyword "${primaryTerm}" not found in content`;
38
+ } else {
39
+ pts += 12;
40
+ const density = words > 0 ? (primaryCount / words) * 100 : 0;
41
+ if (density >= 0.5 && density <= 2.5) {
42
+ pts += 13;
43
+ detail = `Primary keyword present, density ${density.toFixed(2)}% (ideal range)`;
44
+ } else if (density < 0.5) {
45
+ pts += 7;
46
+ detail = `Primary keyword present but density only ${density.toFixed(2)}% - aim for 0.5-2.5%`;
47
+ } else {
48
+ pts += 4;
49
+ detail = `Primary keyword over-used at ${density.toFixed(2)}% density - reduce to 0.5-2.5%`;
50
+ }
51
+ }
52
+ components.push({ label: "Primary keyword", points: pts, max: 25, detail });
53
+ } else {
54
+ components.push({ label: "Primary keyword", points: 0, max: 25, detail: "No primary keyword identified yet" });
55
+ }
56
+
57
+ // 2. Supporting keyword coverage (up to 25)
58
+ const supportingKws = analysis.supportingKeywords || [];
59
+ if (supportingKws.length > 0) {
60
+ const inContentCount = supportingKws.filter((kw) => lowerContent.includes(kw.term.toLowerCase())).length;
61
+ const coverageRatio = inContentCount / supportingKws.length;
62
+ const pts = Math.round(coverageRatio * 25);
63
+ components.push({
64
+ label: "Supporting keywords",
65
+ points: pts,
66
+ max: 25,
67
+ detail: `${inContentCount} of ${supportingKws.length} supporting keywords present (${Math.round(coverageRatio * 100)}%)`,
68
+ });
69
+ } else {
70
+ components.push({ label: "Supporting keywords", points: 0, max: 25, detail: "No supporting keywords yet" });
71
+ }
72
+
73
+ // 3. Word count (up to 15)
74
+ // 450 is the body-text floor. 1,500+ is the competitive target for HCP clinical articles.
75
+ let wcPts = 0;
76
+ let wcDetail: string;
77
+ if (words >= 1500) {
78
+ wcPts = 15;
79
+ wcDetail = `${words} words - strong length for clinical content`;
80
+ } else if (words >= 450) {
81
+ wcPts = 11;
82
+ wcDetail = `${words} words - above the 450 floor; 1,500+ is the clinical target`;
83
+ } else if (words >= 200) {
84
+ wcPts = 5;
85
+ wcDetail = `${words} words - below the 450-word floor`;
86
+ } else {
87
+ wcDetail = `${words} words - start writing`;
88
+ }
89
+ components.push({ label: "Word count", points: wcPts, max: 15, detail: wcDetail });
90
+
91
+ // 4. Heading structure (up to 10)
92
+ const hasH1orTitle = /^#\s|<h1/im.test(content);
93
+ const hasSubheadings = /^##\s|^###\s|<h2|<h3/im.test(content);
94
+ const structurePts = (hasH1orTitle ? 5 : 0) + (hasSubheadings ? 5 : 0);
95
+ const structureDetail = !hasH1orTitle && !hasSubheadings
96
+ ? "No headings detected - add H2/H3 structure"
97
+ : !hasSubheadings
98
+ ? "Has title but no subheadings"
99
+ : !hasH1orTitle
100
+ ? "Has subheadings but no clear H1"
101
+ : "Title and subheadings present";
102
+ components.push({ label: "Heading structure", points: structurePts, max: 10, detail: structureDetail });
103
+
104
+ // 5. Missing keyword coverage (up to 15)
105
+ const missingCount = (analysis.missingKeywords || []).length;
106
+ let mPts = 0;
107
+ let mDetail: string;
108
+ if (missingCount === 0) {
109
+ mPts = 15;
110
+ mDetail = "No missing keywords flagged";
111
+ } else if (missingCount <= 2) {
112
+ mPts = 10;
113
+ mDetail = `${missingCount} suggested keywords missing - quick add`;
114
+ } else if (missingCount <= 4) {
115
+ mPts = 5;
116
+ mDetail = `${missingCount} suggested keywords missing`;
117
+ } else {
118
+ mDetail = `${missingCount} suggested keywords missing - significant gaps`;
119
+ }
120
+ components.push({ label: "Missing keyword gap", points: mPts, max: 15, detail: mDetail });
121
+
122
+ // 6. AEO signals (up to 10) - question-format headings that Google answer
123
+ // features and AI engines surface directly. (FAQ scoring removed May 2026 after
124
+ // Google sunset FAQ rich results - question headings are the modern equivalent.)
125
+ 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;
132
+ const aeoDetail =
133
+ qCount === 0
134
+ ? "No question-style headings - AI answer engines favor them"
135
+ : `${qCount} question heading${qCount === 1 ? "" : "s"}`;
136
+ components.push({ label: "AEO signals", points: aeoPts, max: 10, detail: aeoDetail });
137
+
138
+ const total = components.reduce((sum, c) => sum + c.points, 0);
139
+ return { total: Math.min(100, Math.max(0, total)), components };
140
+ }
141
+
142
+ /**
143
+ * Backward-compatible: returns just the numeric score.
144
+ */
145
+ export function calculateContentScore(content: string, analysis: SEOAnalysis): number {
146
+ return calculateContentScoreDetailed(content, analysis).total;
147
+ }