sanity-plugin-seo-copilot 0.2.12 → 0.2.14
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.
- package/dist/index.js +1506 -1086
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1474 -1054
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/components/KeywordPanel.tsx +190 -176
- package/src/components/ReportProblemButton.tsx +212 -0
- package/src/components/SEOCopilotPanel.tsx +37 -9
- package/src/components/styles.ts +7 -0
- package/src/components/tabs/AEOTab.tsx +5 -1
- package/src/components/tabs/LinkingTab.tsx +39 -13
- package/src/components/tabs/MetaTab.tsx +122 -24
- package/src/components/tabs/SummaryTab.tsx +21 -15
- package/src/components/tabs/TechnicalTab.tsx +276 -269
- package/src/hooks/useKeywordAnalysis.ts +8 -7
- package/src/lib/api.ts +21 -52
- package/src/lib/documentExtract.ts +168 -14
- package/src/lib/scoring.ts +4 -4
- package/src/lib/summary.ts +23 -14
- package/src/lib/types.ts +12 -0
|
@@ -46,7 +46,8 @@ export function useKeywordAnalysis(
|
|
|
46
46
|
seedKeywords?: string[],
|
|
47
47
|
documentFields?: DocumentFields,
|
|
48
48
|
focusPrimary?: string,
|
|
49
|
-
documentId?: string
|
|
49
|
+
documentId?: string,
|
|
50
|
+
focusSecondary?: string
|
|
50
51
|
) {
|
|
51
52
|
const cacheKey = documentId ? `seo-copilot-cache-${documentId}` : "seo-copilot-cache-v2";
|
|
52
53
|
const loadCached = useCallback((): { analysis: SEOAnalysis | null; deepAnalysis: DeepAnalysis | null; seeds: string[] } => {
|
|
@@ -107,14 +108,14 @@ export function useKeywordAnalysis(
|
|
|
107
108
|
const prev = loadCached();
|
|
108
109
|
localStorage.setItem(cacheKey, JSON.stringify({ ...prev, analysis: withVolumes }));
|
|
109
110
|
} catch { /* ignore */ }
|
|
110
|
-
}, [cacheKey]);
|
|
111
|
+
}, [cacheKey, loadCached]);
|
|
111
112
|
const setDeepAnalysis = useCallback((val: DeepAnalysis | null) => {
|
|
112
113
|
setDeepAnalysisRaw(val);
|
|
113
114
|
try {
|
|
114
115
|
const prev = loadCached();
|
|
115
116
|
localStorage.setItem(cacheKey, JSON.stringify({ ...prev, deepAnalysis: val }));
|
|
116
117
|
} catch { /* ignore */ }
|
|
117
|
-
}, [cacheKey]);
|
|
118
|
+
}, [cacheKey, loadCached]);
|
|
118
119
|
|
|
119
120
|
const effectiveSeeds = seedKeywords;
|
|
120
121
|
|
|
@@ -205,7 +206,7 @@ export function useKeywordAnalysis(
|
|
|
205
206
|
setIsLoading(true);
|
|
206
207
|
setError(null);
|
|
207
208
|
|
|
208
|
-
fetchAnalysis(apiUrl, text, "realtime", publication, effectiveSeeds, documentFields, focusPrimary, controller.signal)
|
|
209
|
+
fetchAnalysis(apiUrl, text, "realtime", publication, effectiveSeeds, documentFields, focusPrimary, focusSecondary, controller.signal)
|
|
209
210
|
.then((result) => {
|
|
210
211
|
if (cancelled) return;
|
|
211
212
|
const analysisResult = result as SEOAnalysis;
|
|
@@ -244,7 +245,7 @@ export function useKeywordAnalysis(
|
|
|
244
245
|
// JSON.stringify(documentFields) used instead of documentFields directly to avoid
|
|
245
246
|
// re-running when the caller creates a new object reference with identical contents.
|
|
246
247
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
247
|
-
}, [text, apiUrl, publication, effectiveSeeds?.join(","), focusPrimary, JSON.stringify(documentFields)]);
|
|
248
|
+
}, [text, apiUrl, publication, effectiveSeeds?.join(","), focusPrimary, focusSecondary, JSON.stringify(documentFields)]);
|
|
248
249
|
|
|
249
250
|
const refreshVolumes = useCallback(() => {
|
|
250
251
|
const current = lastAnalysisRef.current || analysis;
|
|
@@ -262,7 +263,7 @@ export function useKeywordAnalysis(
|
|
|
262
263
|
|
|
263
264
|
const myVersion = docVersionRef.current;
|
|
264
265
|
deepAbortRef.current?.abort(); const deepController = new AbortController(); deepAbortRef.current = deepController;
|
|
265
|
-
fetchAnalysis(apiUrl, text, "deep", publication, effectiveSeeds, documentFields, focusPrimary, deepController.signal)
|
|
266
|
+
fetchAnalysis(apiUrl, text, "deep", publication, effectiveSeeds, documentFields, focusPrimary, focusSecondary, deepController.signal)
|
|
266
267
|
.then((result) => {
|
|
267
268
|
if (docVersionRef.current !== myVersion) return; // document switched - drop stale result
|
|
268
269
|
setDeepAnalysis(result as DeepAnalysis);
|
|
@@ -275,7 +276,7 @@ export function useKeywordAnalysis(
|
|
|
275
276
|
setError(err.message);
|
|
276
277
|
setIsDeepLoading(false);
|
|
277
278
|
});
|
|
278
|
-
}, [text, apiUrl, publication, effectiveSeeds?.join(","), documentFields, focusPrimary]);
|
|
279
|
+
}, [text, apiUrl, publication, effectiveSeeds?.join(","), documentFields, focusPrimary, focusSecondary]);
|
|
279
280
|
|
|
280
281
|
return {
|
|
281
282
|
analysis,
|
package/src/lib/api.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { SEOAnalysis, DeepAnalysis, ChatMessage, DocumentFields, ContentSuggestions,
|
|
1
|
+
import type { SEOAnalysis, DeepAnalysis, ChatMessage, DocumentFields, ContentSuggestions, LinkingSuggestion, LinkCheckResult } from "./types";
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Safely parse JSON from a response that may have been truncated by
|
|
@@ -30,19 +30,19 @@ export async function fetchAnalysis(
|
|
|
30
30
|
seedKeywords?: string[],
|
|
31
31
|
documentFields?: DocumentFields,
|
|
32
32
|
focusKeyword?: string,
|
|
33
|
+
secondaryKeyword?: string,
|
|
33
34
|
signal?: AbortSignal
|
|
34
35
|
): Promise<SEOAnalysis | DeepAnalysis> {
|
|
35
36
|
const response = await fetch(`${apiUrl}/api/seo-copilot/analyze`, {
|
|
36
37
|
method: "POST",
|
|
37
38
|
headers: { "Content-Type": "application/json" },
|
|
38
|
-
body: JSON.stringify({ content, mode, publication, seedKeywords, documentFields, focusKeyword }),
|
|
39
|
+
body: JSON.stringify({ content, mode, publication, seedKeywords, documentFields, focusKeyword, secondaryKeyword }),
|
|
39
40
|
signal,
|
|
40
41
|
});
|
|
41
42
|
|
|
42
43
|
const text = await response.text();
|
|
43
44
|
|
|
44
45
|
if (!response.ok) {
|
|
45
|
-
const err = safeParseJson<{ error?: string }>(text);
|
|
46
46
|
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
47
47
|
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
48
48
|
throw new Error("Something went wrong analyzing this document.");
|
|
@@ -74,7 +74,6 @@ export async function fetchChatStream(
|
|
|
74
74
|
});
|
|
75
75
|
|
|
76
76
|
if (!response.ok) {
|
|
77
|
-
const err = await response.json().catch(() => ({ error: "Request failed" }));
|
|
78
77
|
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
79
78
|
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
80
79
|
throw new Error("Something went wrong. Please try again.");
|
|
@@ -96,7 +95,6 @@ export async function fetchQuestions(
|
|
|
96
95
|
});
|
|
97
96
|
|
|
98
97
|
if (!response.ok) {
|
|
99
|
-
const err = await response.json().catch(() => ({ error: "Request failed" }));
|
|
100
98
|
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
101
99
|
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
102
100
|
throw new Error("Something went wrong. Please try again.");
|
|
@@ -105,15 +103,31 @@ export async function fetchQuestions(
|
|
|
105
103
|
return response.json();
|
|
106
104
|
}
|
|
107
105
|
|
|
106
|
+
// Telemetry attached to a "Report a problem" submission - which surface/tab the editor
|
|
107
|
+
// was on, etc. Keys must match the backend's strict schema in feedback/route.ts.
|
|
108
|
+
export interface FeedbackContext {
|
|
109
|
+
surface?: string;
|
|
110
|
+
activeTab?: string;
|
|
111
|
+
primaryKeyword?: string;
|
|
112
|
+
documentType?: string;
|
|
113
|
+
url?: string;
|
|
114
|
+
userAgent?: string;
|
|
115
|
+
appVersion?: string;
|
|
116
|
+
timestamp?: string;
|
|
117
|
+
}
|
|
118
|
+
|
|
108
119
|
export async function submitFeedback(
|
|
109
120
|
apiUrl: string,
|
|
110
|
-
data: { suggestion_type: string; suggestion_text: string; vote: "up" | "down"; document_id?: string; publication?: string; user_id?: string }
|
|
121
|
+
data: { suggestion_type: string; suggestion_text: string; vote: "up" | "down"; document_id?: string; publication?: string; user_id?: string; context?: FeedbackContext }
|
|
111
122
|
): Promise<void> {
|
|
112
|
-
await fetch(`${apiUrl}/api/seo-copilot/feedback`, {
|
|
123
|
+
const res = await fetch(`${apiUrl}/api/seo-copilot/feedback`, {
|
|
113
124
|
method: "POST",
|
|
114
125
|
headers: { "Content-Type": "application/json" },
|
|
115
126
|
body: JSON.stringify(data),
|
|
116
127
|
});
|
|
128
|
+
// Surface HTTP failures (500, 429, ...) so the caller can show a real error instead of a
|
|
129
|
+
// false "Thanks" - fetch() only rejects on network errors, not on a bad status.
|
|
130
|
+
if (!res.ok) throw new Error(`Feedback submit failed: HTTP ${res.status}`);
|
|
117
131
|
}
|
|
118
132
|
|
|
119
133
|
export async function lookupKeywords(
|
|
@@ -129,7 +143,6 @@ export async function lookupKeywords(
|
|
|
129
143
|
});
|
|
130
144
|
|
|
131
145
|
if (!response.ok) {
|
|
132
|
-
const err = await response.json().catch(() => ({ error: "Request failed" }));
|
|
133
146
|
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
134
147
|
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
135
148
|
throw new Error("Something went wrong. Please try again.");
|
|
@@ -183,50 +196,6 @@ export async function fetchContentSuggestions(
|
|
|
183
196
|
}
|
|
184
197
|
}
|
|
185
198
|
|
|
186
|
-
export async function fetchInternalLinks(
|
|
187
|
-
apiUrl: string,
|
|
188
|
-
keywords: string[],
|
|
189
|
-
currentDocumentId?: string,
|
|
190
|
-
publication?: string
|
|
191
|
-
): Promise<InternalLink[]> {
|
|
192
|
-
if (!keywords || keywords.length === 0) return [];
|
|
193
|
-
try {
|
|
194
|
-
const res = await fetch(`${apiUrl}/api/seo-copilot/articles`, {
|
|
195
|
-
method: "POST",
|
|
196
|
-
headers: { "Content-Type": "application/json" },
|
|
197
|
-
body: JSON.stringify({ action: "related", keywords, publication }),
|
|
198
|
-
});
|
|
199
|
-
if (!res.ok) return [];
|
|
200
|
-
const data = await res.json().catch(() => null);
|
|
201
|
-
if (!data || typeof data !== "object") return [];
|
|
202
|
-
type ArticleResult = { _id?: string; title?: string; slug?: string; publishedAt?: string };
|
|
203
|
-
const articles: ArticleResult[] = Array.isArray(data.articles) ? data.articles : [];
|
|
204
|
-
const filtered = currentDocumentId
|
|
205
|
-
? articles.filter((a) => a._id !== currentDocumentId)
|
|
206
|
-
: articles;
|
|
207
|
-
return filtered.map((a): InternalLink => ({
|
|
208
|
-
_id: a._id,
|
|
209
|
-
title: a.title || "Untitled",
|
|
210
|
-
slug: a.slug || "",
|
|
211
|
-
publishedAt: a.publishedAt,
|
|
212
|
-
relevanceReason: matchedKeyword(a.title, keywords),
|
|
213
|
-
}));
|
|
214
|
-
} catch {
|
|
215
|
-
return [];
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
function matchedKeyword(title: string | undefined, keywords: string[]): string {
|
|
220
|
-
const lower = (title || "").toLowerCase();
|
|
221
|
-
if (!lower) return "Related to current topic";
|
|
222
|
-
for (const kw of keywords) {
|
|
223
|
-
if (kw && lower.includes(kw.toLowerCase())) {
|
|
224
|
-
return `Matches "${kw}"`;
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
return "Related to current topic";
|
|
228
|
-
}
|
|
229
|
-
|
|
230
199
|
export async function fetchLinkingSuggestions(
|
|
231
200
|
apiUrl: string,
|
|
232
201
|
content: string,
|
|
@@ -24,6 +24,7 @@ interface PortableTextBlock {
|
|
|
24
24
|
children?: PortableTextSpan[];
|
|
25
25
|
markDefs?: PortableTextMarkDef[];
|
|
26
26
|
text?: string;
|
|
27
|
+
listItem?: string;
|
|
27
28
|
}
|
|
28
29
|
|
|
29
30
|
export function extractText(blocks: unknown): string {
|
|
@@ -67,34 +68,116 @@ export function extractHeadingsDetailed(blocks: unknown): HeadingItem[] {
|
|
|
67
68
|
return out;
|
|
68
69
|
}
|
|
69
70
|
|
|
70
|
-
//
|
|
71
|
-
//
|
|
72
|
-
//
|
|
73
|
-
|
|
74
|
-
const
|
|
71
|
+
// Normalize a candidate link to an absolute http(s) URL the link-health checker can
|
|
72
|
+
// fetch. Accepts "https://x.com/a" as-is, prepends https:// to scheme-less links like
|
|
73
|
+
// "www.google.com" or "example.com/page", and rejects anything that isn't domain-shaped.
|
|
74
|
+
function normalizeLink(raw: string): string | null {
|
|
75
|
+
const s = raw.trim().replace(/[.,;:!?]+$/, "");
|
|
76
|
+
if (!s) return null;
|
|
77
|
+
if (/^https?:\/\//i.test(s)) return s;
|
|
78
|
+
// www.something OR bare domain like example.com / sub.example.co.uk/path
|
|
79
|
+
if (/^www\.\S+\.\S+/i.test(s) || /^[a-z0-9-]+(\.[a-z0-9-]+)+(\/|$)/i.test(s)) return `https://${s}`;
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Body paragraphs that LOOK like section headings but are styled as plain text (the editor
|
|
84
|
+
// typed a heading instead of applying the H2 style, so the tool can't count it). Conservative
|
|
85
|
+
// on purpose - we only flag a SHORT, punctuation-free line that is immediately followed by a
|
|
86
|
+
// substantial paragraph (a heading introduces content), and is not a list item / caption /
|
|
87
|
+
// reference. This keeps precision high so the "style this as H2?" nudge is trustworthy.
|
|
88
|
+
// Real articles are well under this many blocks, and section headings that matter live near
|
|
89
|
+
// the top - so cap the scan to bound work on a pathological 10k-block document.
|
|
90
|
+
const UNSTYLED_HEADING_SCAN_CAP = 600;
|
|
91
|
+
export function extractUnstyledHeadings(blocks: unknown): string[] {
|
|
92
|
+
if (!Array.isArray(blocks)) return [];
|
|
93
|
+
const items = (blocks as PortableTextBlock[]).slice(0, UNSTYLED_HEADING_SCAN_CAP).map((b) => {
|
|
94
|
+
if (!b || b._type !== "block") return null;
|
|
95
|
+
const style = b.style || "normal";
|
|
96
|
+
const text = (b.children || []).map((c) => c.text || "").join("").trim();
|
|
97
|
+
return {
|
|
98
|
+
isHeading: /^h[1-6]$/.test(style),
|
|
99
|
+
isPlain: style === "normal",
|
|
100
|
+
isList: typeof b.listItem === "string" && b.listItem.length > 0,
|
|
101
|
+
text,
|
|
102
|
+
words: text ? text.split(/\s+/).filter(Boolean).length : 0,
|
|
103
|
+
};
|
|
104
|
+
});
|
|
105
|
+
const out: string[] = [];
|
|
106
|
+
for (let i = 0; i < items.length; i++) {
|
|
107
|
+
const it = items[i];
|
|
108
|
+
if (!it || it.isHeading || it.isList || !it.isPlain) continue;
|
|
109
|
+
if (it.words < 2 || it.words > 9) continue; // too short to mean anything / too long to be a heading
|
|
110
|
+
if (/[.!?]$/.test(it.text)) continue; // ends like a sentence, not a heading
|
|
111
|
+
if (!/[A-Za-z]/.test(it.text)) continue; // must contain letters
|
|
112
|
+
if (/https?:\/\/|doi:|\baccessed\b|image credit|stock\.adobe|^figure\b|^table\b|^source[:s]?\b|^references?\b/i.test(it.text)) continue; // caption / reference
|
|
113
|
+
// Must be immediately followed by a substantial paragraph - the hallmark of a heading.
|
|
114
|
+
let next: (typeof items)[number] = null;
|
|
115
|
+
for (let j = i + 1; j < items.length; j++) {
|
|
116
|
+
if (items[j] && items[j]!.text) { next = items[j]; break; }
|
|
117
|
+
}
|
|
118
|
+
if (!next || next.isHeading || next.words < 12) continue;
|
|
119
|
+
out.push(it.text);
|
|
120
|
+
if (out.length >= 8) break; // safety cap
|
|
121
|
+
}
|
|
122
|
+
return out;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Every URL in the article body, WITH whether it's an actual hyperlink. Sanity stores
|
|
126
|
+
// real links as Portable Text markDefs (_type "link" + href) - those are clickable
|
|
127
|
+
// (the editor Control-K'd them). A URL that only appears as inline text (typed/pasted,
|
|
128
|
+
// not wrapped in a link annotation) is NOT a hyperlink - readers can't click it and
|
|
129
|
+
// search engines won't follow it. Link Health uses this to tell editors which URLs are
|
|
130
|
+
// real links vs plain text they still need to link.
|
|
131
|
+
export interface BodyLink {
|
|
132
|
+
url: string;
|
|
133
|
+
hyperlinked: boolean;
|
|
134
|
+
// For a real hyperlink, the visible text the editor wrapped in the link (the anchor).
|
|
135
|
+
anchorText?: string;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function extractBodyLinksDetailed(blocks: unknown): BodyLink[] {
|
|
139
|
+
const linked = new Set<string>(); // URLs that appear in a link annotation (a real hyperlink)
|
|
140
|
+
const all = new Set<string>();
|
|
141
|
+
const anchorByUrl = new Map<string, string>(); // url -> the visible anchor text
|
|
75
142
|
if (Array.isArray(blocks)) {
|
|
143
|
+
// Pass 1: real hyperlinks (Control-K link annotations). Intentional, so a scheme-less
|
|
144
|
+
// href like "www.google.com" is accepted and normalized. Also grab the anchor text -
|
|
145
|
+
// the spans whose marks reference this link's _key.
|
|
76
146
|
for (const block of blocks as PortableTextBlock[]) {
|
|
77
147
|
if (block._type === "block" && Array.isArray(block.markDefs)) {
|
|
78
148
|
for (const md of block.markDefs) {
|
|
79
149
|
const href = md.href || md.url;
|
|
80
|
-
if (typeof href
|
|
81
|
-
|
|
82
|
-
|
|
150
|
+
if (typeof href !== "string") continue;
|
|
151
|
+
const n = normalizeLink(href);
|
|
152
|
+
if (!n) continue;
|
|
153
|
+
linked.add(n);
|
|
154
|
+
all.add(n);
|
|
155
|
+
const anchor = (block.children || [])
|
|
156
|
+
.filter((c) => Array.isArray(c.marks) && md._key && c.marks.includes(md._key))
|
|
157
|
+
.map((c) => c.text || "")
|
|
158
|
+
.join("")
|
|
159
|
+
.trim();
|
|
160
|
+
if (anchor && !anchorByUrl.has(n)) anchorByUrl.set(n, anchor);
|
|
83
161
|
}
|
|
84
162
|
}
|
|
85
163
|
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
if (Array.isArray(blocks)) {
|
|
164
|
+
// Pass 2: inline plain-text URLs - http(s):// OR www.-prefixed. (We don't match bare
|
|
165
|
+
// domains in prose to avoid false positives on things like "e.g." or "vs.".)
|
|
89
166
|
for (const block of blocks as PortableTextBlock[]) {
|
|
90
167
|
if (block._type === "block" && Array.isArray(block.children)) {
|
|
91
168
|
const blockText = block.children.map((c) => c.text || "").join(" ");
|
|
92
|
-
const matches = blockText.match(/https
|
|
93
|
-
if (matches) matches
|
|
169
|
+
const matches = blockText.match(/(?:https?:\/\/|www\.)[^\s"'<>)\]]+/gi);
|
|
170
|
+
if (matches) for (const u of matches) { const n = normalizeLink(u); if (n) all.add(n); }
|
|
94
171
|
}
|
|
95
172
|
}
|
|
96
173
|
}
|
|
97
|
-
return
|
|
174
|
+
return [...all].map((url) => ({ url, hyperlinked: linked.has(url), anchorText: anchorByUrl.get(url) }));
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Flat list of every body URL (both real hyperlinks and plain-text URLs). Used by the
|
|
178
|
+
// broken-link checker, which checks all of them regardless of whether they're linked.
|
|
179
|
+
export function extractBodyLinks(blocks: unknown): string[] {
|
|
180
|
+
return extractBodyLinksDetailed(blocks).map((l) => l.url);
|
|
98
181
|
}
|
|
99
182
|
|
|
100
183
|
// Slug detection across the common schema shapes. Looks for, in order:
|
|
@@ -186,6 +269,72 @@ export function detectAuthor(val: Record<string, unknown> | undefined): {
|
|
|
186
269
|
return { authorIsReference: false };
|
|
187
270
|
}
|
|
188
271
|
|
|
272
|
+
// A workflow-status value, not a person's name - so a `reviewer: "pending"` field doesn't
|
|
273
|
+
// read as a fact-checker literally named "pending" (a false "Set" that hides a missing one).
|
|
274
|
+
const FACT_CHECK_STATUS_WORDS = new Set([
|
|
275
|
+
"pending", "approved", "rejected", "done", "complete", "completed", "in review", "in progress",
|
|
276
|
+
"not started", "draft", "review", "reviewed", "unreviewed", "checked", "unchecked", "verified",
|
|
277
|
+
"unverified", "true", "false", "yes", "no", "n/a", "na", "none", "tbd", "todo", "to do",
|
|
278
|
+
]);
|
|
279
|
+
function isLikelyPersonName(s: string): boolean {
|
|
280
|
+
const t = s.trim().toLowerCase();
|
|
281
|
+
if (!t || FACT_CHECK_STATUS_WORDS.has(t)) return false;
|
|
282
|
+
return /[a-z]/i.test(s);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// Fact-checker / reviewer detection. A second named reviewer is a strong E-E-A-T trust
|
|
286
|
+
// signal (MJH renders a "Fact checked by ..." line). Mirrors detectAuthor: handles inline
|
|
287
|
+
// strings, inline objects, arrays of names, and unresolvable Sanity references. Date
|
|
288
|
+
// fields (lastReviewedAt, medicallyReviewedAt, reviewedDate) are explicitly excluded -
|
|
289
|
+
// those are timestamps, not people; status values (pending/approved/...) are excluded too.
|
|
290
|
+
export function detectFactChecker(val: Record<string, unknown> | undefined): {
|
|
291
|
+
factCheckerName?: string;
|
|
292
|
+
factCheckerIsReference: boolean;
|
|
293
|
+
} {
|
|
294
|
+
if (!val) return { factCheckerIsReference: false };
|
|
295
|
+
// Person-denoting field names only. We deliberately do NOT include the bare `factCheck` /
|
|
296
|
+
// `factChecked` flags - those are usually booleans or workflow-status strings ("pending"),
|
|
297
|
+
// not a person's name.
|
|
298
|
+
const candidateFields = [
|
|
299
|
+
"factChecker", "factCheckers", "factCheckedBy",
|
|
300
|
+
"reviewer", "reviewers", "reviewedBy", "medicalReviewer", "medicallyReviewedBy",
|
|
301
|
+
];
|
|
302
|
+
const dynamic = Object.keys(val).filter(
|
|
303
|
+
(k) =>
|
|
304
|
+
// Require "checker"/"checked by"/"reviewer"/"reviewed by" - NOT a bare "check" flag.
|
|
305
|
+
/factchecker|fact.?checked.?by|reviewer|reviewed.?by/i.test(k) &&
|
|
306
|
+
// never date/timestamp fields (lastReviewedAt, medicallyReviewedAt, reviewedDate),
|
|
307
|
+
// free-text/status/flag sidecars (reviewerNotes, reviewStatus), nor image/url/id fields.
|
|
308
|
+
!/at$|date$|on$|url|link|count|note|comment|status|flag|bool|photo|image|avatar|picture|id$/i.test(k)
|
|
309
|
+
);
|
|
310
|
+
const fields = Array.from(new Set([...candidateFields, ...dynamic]));
|
|
311
|
+
for (const f of fields) {
|
|
312
|
+
const raw = val[f];
|
|
313
|
+
if (!raw) continue;
|
|
314
|
+
// Array of plain-string names ("Fact checked by: A, B") - join the first few.
|
|
315
|
+
if (Array.isArray(raw)) {
|
|
316
|
+
const names = raw.filter((x): x is string => typeof x === "string" && isLikelyPersonName(x)).map((x) => x.trim());
|
|
317
|
+
if (names.length > 0) return { factCheckerName: names.slice(0, 3).join(", "), factCheckerIsReference: false };
|
|
318
|
+
}
|
|
319
|
+
const first = Array.isArray(raw) ? raw[0] : raw;
|
|
320
|
+
if (!first) continue;
|
|
321
|
+
if (typeof first === "string") {
|
|
322
|
+
const trimmed = first.trim();
|
|
323
|
+
if (trimmed && isLikelyPersonName(trimmed)) return { factCheckerName: trimmed, factCheckerIsReference: false };
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
326
|
+
if (typeof first === "object" && first !== null) {
|
|
327
|
+
const o = first as Record<string, unknown>;
|
|
328
|
+
const name = ([o.name, o.fullName, o.displayName] as unknown[]).find((v): v is string => typeof v === "string" && isLikelyPersonName(v));
|
|
329
|
+
if (name) return { factCheckerName: name, factCheckerIsReference: false };
|
|
330
|
+
if (typeof o._ref === "string" || o._type === "reference") {
|
|
331
|
+
return { factCheckerIsReference: true };
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
return { factCheckerIsReference: false };
|
|
336
|
+
}
|
|
337
|
+
|
|
189
338
|
// Extracts image metadata from top-level image fields AND inline body
|
|
190
339
|
// figure/image blocks (where MJH stores article images):
|
|
191
340
|
// - names: alt text + asset filename (for the alt + filename audits)
|
|
@@ -240,6 +389,7 @@ export function buildDocumentFields(value: Record<string, unknown> | undefined):
|
|
|
240
389
|
const title = typeof val?.title === 'string' ? val.title : undefined;
|
|
241
390
|
const body = val?.body;
|
|
242
391
|
const { authorName, authorCredentials, authorBioUrl, authorIsReference } = detectAuthor(val);
|
|
392
|
+
const { factCheckerName, factCheckerIsReference } = detectFactChecker(val);
|
|
243
393
|
const imageMeta = val ? extractImageMeta(val) : { names: [], titles: [], count: 0 };
|
|
244
394
|
return {
|
|
245
395
|
title: title || undefined,
|
|
@@ -251,13 +401,17 @@ export function buildDocumentFields(value: Record<string, unknown> | undefined):
|
|
|
251
401
|
imageCount: imageMeta.count,
|
|
252
402
|
headings: extractHeadings(body),
|
|
253
403
|
headingsDetailed: extractHeadingsDetailed(body),
|
|
404
|
+
unstyledHeadings: extractUnstyledHeadings(body),
|
|
254
405
|
bodyLinks: extractBodyLinks(body),
|
|
406
|
+
bodyLinksDetailed: extractBodyLinksDetailed(body),
|
|
255
407
|
contentCategory: typeof val?.contentCategory === 'string' ? val.contentCategory : typeof val?.category === 'string' ? val.category : undefined,
|
|
256
408
|
contentPlacement: Array.isArray(val?.contentPlacement) ? (val.contentPlacement as string[]) : undefined,
|
|
257
409
|
authorName,
|
|
258
410
|
authorCredentials,
|
|
259
411
|
authorBioUrl,
|
|
260
412
|
authorIsReference,
|
|
413
|
+
factCheckerName,
|
|
414
|
+
factCheckerIsReference,
|
|
261
415
|
// `published` is MJH's date field; `publishedAt`/`publishDate` cover other schemas
|
|
262
416
|
publishedAt: ([val?.publishedAt, val?.publishDate, val?.published, val?._createdAt] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0),
|
|
263
417
|
// `updatedOn` is MJH's "Updated On" field. `updatedAt` is the standard Sanity convention.
|
package/src/lib/scoring.ts
CHANGED
|
@@ -80,9 +80,9 @@ export function calculateContentScoreDetailed(content: string, analysis: SEOAnal
|
|
|
80
80
|
detail = `Primary keyword over-used at ${density.toFixed(2)}% density - reduce to 0.5-2.5%`;
|
|
81
81
|
}
|
|
82
82
|
}
|
|
83
|
-
components.push({ label: "Primary keyword", points: pts, max: 25, detail });
|
|
83
|
+
components.push({ label: "Primary keyword usage", points: pts, max: 25, detail });
|
|
84
84
|
} else {
|
|
85
|
-
components.push({ label: "Primary keyword", points: 0, max: 25, detail: "No primary keyword identified yet" });
|
|
85
|
+
components.push({ label: "Primary keyword usage", points: 0, max: 25, detail: "No primary keyword identified yet" });
|
|
86
86
|
}
|
|
87
87
|
|
|
88
88
|
// 2. Supporting keyword coverage (up to 25)
|
|
@@ -92,13 +92,13 @@ export function calculateContentScoreDetailed(content: string, analysis: SEOAnal
|
|
|
92
92
|
const coverageRatio = inContentCount / supportingKws.length;
|
|
93
93
|
const pts = Math.round(coverageRatio * 25);
|
|
94
94
|
components.push({
|
|
95
|
-
label: "Supporting
|
|
95
|
+
label: "Supporting keyword coverage",
|
|
96
96
|
points: pts,
|
|
97
97
|
max: 25,
|
|
98
98
|
detail: `${inContentCount} of ${supportingKws.length} supporting keywords present (${Math.round(coverageRatio * 100)}%)`,
|
|
99
99
|
});
|
|
100
100
|
} else {
|
|
101
|
-
components.push({ label: "Supporting
|
|
101
|
+
components.push({ label: "Supporting keyword coverage", points: 0, max: 25, detail: "No supporting keywords yet" });
|
|
102
102
|
}
|
|
103
103
|
|
|
104
104
|
// 3. Word count (up to 15)
|
package/src/lib/summary.ts
CHANGED
|
@@ -140,7 +140,7 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
|
|
|
140
140
|
severity: "warning",
|
|
141
141
|
label: "Meta description is short",
|
|
142
142
|
description: `Meta description is ${len} characters - below the 120-160 ideal.`,
|
|
143
|
-
howToFix: "Expand the description to 120-160 characters so
|
|
143
|
+
howToFix: "Expand the description to 120-160 characters so the full description shows in search.",
|
|
144
144
|
jumpTo: { tab: "meta", anchorId: "anchor-meta-description" },
|
|
145
145
|
});
|
|
146
146
|
} else if (len > 160) {
|
|
@@ -290,20 +290,9 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
|
|
|
290
290
|
jumpTo: { tab: "technical", anchorId: "anchor-headings-structure" },
|
|
291
291
|
});
|
|
292
292
|
}
|
|
293
|
-
// H1
|
|
293
|
+
// (H1-in-body is intentionally no longer flagged: the article title IS the H1, and the
|
|
294
|
+
// Heading Outline on the Other Recs tab now shows it explicitly instead of warning.)
|
|
294
295
|
if (headingsDetailed) {
|
|
295
|
-
const bodyH1 = headingsDetailed.filter((h) => h.level === 1).length;
|
|
296
|
-
if (bodyH1 > 0) {
|
|
297
|
-
items.push({
|
|
298
|
-
id: "headings-h1-in-body",
|
|
299
|
-
category: "headings",
|
|
300
|
-
severity: "warning",
|
|
301
|
-
label: "H1 inside the body",
|
|
302
|
-
description: `${bodyH1} H1 heading${bodyH1 === 1 ? "" : "s"} in the body of the article.`,
|
|
303
|
-
howToFix: "The article title is your H1. Body headings should start at H2 so the outline isn't ambiguous.",
|
|
304
|
-
jumpTo: { tab: "technical", anchorId: "anchor-headings-structure" },
|
|
305
|
-
});
|
|
306
|
-
}
|
|
307
296
|
// Skipped-level check
|
|
308
297
|
let prevLevel = 0;
|
|
309
298
|
let skips = 0;
|
|
@@ -335,6 +324,26 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
|
|
|
335
324
|
jumpTo: { tab: "technical", anchorId: "anchor-headings-structure" },
|
|
336
325
|
});
|
|
337
326
|
}
|
|
327
|
+
// Keyword-in-headings opportunity - mirrors the "Keywords in Headings" audit on the
|
|
328
|
+
// Other Recs tab so the nudge also surfaces in the Summary hub. Only when subheadings
|
|
329
|
+
// exist and neither target keyword appears in any of them.
|
|
330
|
+
const subheads = headingsDetailed.filter((h) => h.level >= 2);
|
|
331
|
+
if (subheads.length > 0 && (primaryKeyword || secondaryKeyword)) {
|
|
332
|
+
const subText = subheads.map((h) => h.text).join(" ");
|
|
333
|
+
const hasP = primaryKeyword ? containsKeywordTokens(subText, primaryKeyword) : false;
|
|
334
|
+
const hasS = secondaryKeyword ? containsKeywordTokens(subText, secondaryKeyword) : false;
|
|
335
|
+
if (!hasP && !hasS) {
|
|
336
|
+
items.push({
|
|
337
|
+
id: "headings-keyword-missing",
|
|
338
|
+
category: "headings",
|
|
339
|
+
severity: "opportunity",
|
|
340
|
+
label: "Keyword missing from subheadings",
|
|
341
|
+
description: "No H2/H3 subheading uses your primary or secondary keyword.",
|
|
342
|
+
howToFix: "Work your primary or secondary keyword into at least one subheading - keywords in headers reinforce relevance for readers and search.",
|
|
343
|
+
jumpTo: { tab: "technical", anchorId: "anchor-headings-keyword" },
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
}
|
|
338
347
|
}
|
|
339
348
|
|
|
340
349
|
// ---------- IMAGES ----------
|
package/src/lib/types.ts
CHANGED
|
@@ -99,9 +99,16 @@ export interface DocumentFields {
|
|
|
99
99
|
headings?: string[];
|
|
100
100
|
// Headings with their H-level, used by the Technical tab for hierarchy checks.
|
|
101
101
|
headingsDetailed?: HeadingItem[];
|
|
102
|
+
// Body paragraphs that look like section headings but were typed as plain text (not styled
|
|
103
|
+
// as H2). Drives the "this looks like a heading - style it as H2?" nudge.
|
|
104
|
+
unstyledHeadings?: string[];
|
|
102
105
|
// All URL links found in the body (from Portable Text markDefs + inline URL regex).
|
|
103
106
|
// Used by the Technical tab's broken-link checker.
|
|
104
107
|
bodyLinks?: string[];
|
|
108
|
+
// Same URLs, but flagged with whether each is an actual hyperlink (a Control-K link
|
|
109
|
+
// annotation) vs plain text the editor still needs to link, plus the visible anchor
|
|
110
|
+
// text for real links. Drives the Link Health "hyperlinked vs plain text" breakdown.
|
|
111
|
+
bodyLinksDetailed?: { url: string; hyperlinked: boolean; anchorText?: string }[];
|
|
105
112
|
contentCategory?: string;
|
|
106
113
|
contentPlacement?: string[];
|
|
107
114
|
// E-E-A-T fields - 2026 healthcare content scrutiny
|
|
@@ -111,6 +118,11 @@ export interface DocumentFields {
|
|
|
111
118
|
// True when the author field is set as a Sanity reference we can't resolve client-side
|
|
112
119
|
// (vs. truly missing). Lets the audit distinguish "schema uses refs, looks fine" from "no author".
|
|
113
120
|
authorIsReference?: boolean;
|
|
121
|
+
// Fact-checker / reviewer - a second named person who reviewed the article (MJH shows a
|
|
122
|
+
// "Fact checked by ..." line). Strong E-E-A-T trust signal for healthcare content.
|
|
123
|
+
// factCheckerIsReference mirrors the author's reference case.
|
|
124
|
+
factCheckerName?: string;
|
|
125
|
+
factCheckerIsReference?: boolean;
|
|
114
126
|
publishedAt?: string;
|
|
115
127
|
updatedAt?: string;
|
|
116
128
|
lastReviewedAt?: string;
|