sanity-plugin-seo-copilot 0.2.14 → 0.2.16
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/README.md +63 -50
- package/dist/index.js +868 -797
- package/dist/index.mjs +791 -720
- package/package.json +9 -8
- package/dist/index.js.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/sanity.json +0 -3
- package/src/components/ChatPanel.tsx +0 -311
- package/src/components/ConfigContext.tsx +0 -22
- package/src/components/FeedbackButton.tsx +0 -218
- package/src/components/KeywordBadge.tsx +0 -50
- package/src/components/KeywordPanel.tsx +0 -1233
- package/src/components/OnboardingPopup.tsx +0 -108
- package/src/components/PlacementIndicators.tsx +0 -80
- package/src/components/ReportProblemButton.tsx +0 -212
- package/src/components/SEOCopilotPanel.tsx +0 -1287
- package/src/components/ScoreDonut.tsx +0 -158
- package/src/components/SeedKeywordInput.tsx +0 -128
- package/src/components/ShimmerLoader.tsx +0 -123
- package/src/components/TabBar.tsx +0 -373
- package/src/components/styles.ts +0 -158
- package/src/components/tabs/AEOTab.tsx +0 -585
- package/src/components/tabs/LinkingTab.tsx +0 -446
- package/src/components/tabs/MetaTab.tsx +0 -431
- package/src/components/tabs/SummaryTab.tsx +0 -405
- package/src/components/tabs/TechnicalTab.tsx +0 -933
- package/src/hooks/useDocumentContent.ts +0 -48
- package/src/hooks/useKeywordAnalysis.ts +0 -292
- package/src/hooks/useSEOChat.ts +0 -254
- package/src/index.ts +0 -16
- package/src/inspector.ts +0 -58
- package/src/lib/api.ts +0 -260
- package/src/lib/documentExtract.ts +0 -422
- package/src/lib/geoAnalysis.ts +0 -122
- package/src/lib/persistence.ts +0 -69
- package/src/lib/scoring.ts +0 -197
- package/src/lib/summary.ts +0 -645
- package/src/lib/types.ts +0 -212
- package/src/lib/utils.ts +0 -35
- package/v2-incompatible.js +0 -10
package/src/lib/api.ts
DELETED
|
@@ -1,260 +0,0 @@
|
|
|
1
|
-
import type { SEOAnalysis, DeepAnalysis, ChatMessage, DocumentFields, ContentSuggestions, LinkingSuggestion, LinkCheckResult } from "./types";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Safely parse JSON from a response that may have been truncated by
|
|
5
|
-
* Vercel's function timeout (HTML error appended after valid JSON).
|
|
6
|
-
*/
|
|
7
|
-
function safeParseJson<T>(text: string): T {
|
|
8
|
-
try {
|
|
9
|
-
return JSON.parse(text) as T;
|
|
10
|
-
} catch {
|
|
11
|
-
// Find the last } or ] and try parsing up to that point
|
|
12
|
-
for (let i = text.length - 1; i >= 0; i--) {
|
|
13
|
-
if (text[i] === "}" || text[i] === "]") {
|
|
14
|
-
try {
|
|
15
|
-
return JSON.parse(text.substring(0, i + 1)) as T;
|
|
16
|
-
} catch {
|
|
17
|
-
continue;
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
throw new Error("Invalid JSON response from server");
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
export async function fetchAnalysis(
|
|
26
|
-
apiUrl: string,
|
|
27
|
-
content: string,
|
|
28
|
-
mode: "realtime" | "deep",
|
|
29
|
-
publication?: string,
|
|
30
|
-
seedKeywords?: string[],
|
|
31
|
-
documentFields?: DocumentFields,
|
|
32
|
-
focusKeyword?: string,
|
|
33
|
-
secondaryKeyword?: string,
|
|
34
|
-
signal?: AbortSignal
|
|
35
|
-
): Promise<SEOAnalysis | DeepAnalysis> {
|
|
36
|
-
const response = await fetch(`${apiUrl}/api/seo-copilot/analyze`, {
|
|
37
|
-
method: "POST",
|
|
38
|
-
headers: { "Content-Type": "application/json" },
|
|
39
|
-
body: JSON.stringify({ content, mode, publication, seedKeywords, documentFields, focusKeyword, secondaryKeyword }),
|
|
40
|
-
signal,
|
|
41
|
-
});
|
|
42
|
-
|
|
43
|
-
const text = await response.text();
|
|
44
|
-
|
|
45
|
-
if (!response.ok) {
|
|
46
|
-
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
47
|
-
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
48
|
-
throw new Error("Something went wrong analyzing this document.");
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
return safeParseJson<SEOAnalysis | DeepAnalysis>(text);
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export async function fetchChatStream(
|
|
55
|
-
apiUrl: string,
|
|
56
|
-
messages: ChatMessage[],
|
|
57
|
-
documentContext: string,
|
|
58
|
-
publication?: string,
|
|
59
|
-
keywordPanelData?: {
|
|
60
|
-
primaryKeyword?: { term: string; volume: number | null };
|
|
61
|
-
supportingKeywords?: { term: string; volume: number | null }[];
|
|
62
|
-
missingKeywords?: { term: string; volume: number | null }[];
|
|
63
|
-
aeoData?: {
|
|
64
|
-
questionHeadings: { suggestedHeading: string; rationale: string }[];
|
|
65
|
-
};
|
|
66
|
-
},
|
|
67
|
-
signal?: AbortSignal
|
|
68
|
-
): Promise<ReadableStream<Uint8Array> | null> {
|
|
69
|
-
const response = await fetch(`${apiUrl}/api/seo-copilot/chat`, {
|
|
70
|
-
method: "POST",
|
|
71
|
-
headers: { "Content-Type": "application/json" },
|
|
72
|
-
body: JSON.stringify({ messages, documentContext, publication, keywordPanelData }),
|
|
73
|
-
signal,
|
|
74
|
-
});
|
|
75
|
-
|
|
76
|
-
if (!response.ok) {
|
|
77
|
-
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
78
|
-
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
79
|
-
throw new Error("Something went wrong. Please try again.");
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
return response.body;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
export async function fetchQuestions(
|
|
86
|
-
apiUrl: string,
|
|
87
|
-
keyword: string,
|
|
88
|
-
signal?: AbortSignal
|
|
89
|
-
): Promise<{ questions: { question: string; volume: number; cpc: number; competition: number }[]; apiUnitsUsed: number }> {
|
|
90
|
-
const response = await fetch(`${apiUrl}/api/seo-copilot/questions`, {
|
|
91
|
-
method: "POST",
|
|
92
|
-
headers: { "Content-Type": "application/json" },
|
|
93
|
-
body: JSON.stringify({ keyword }),
|
|
94
|
-
signal,
|
|
95
|
-
});
|
|
96
|
-
|
|
97
|
-
if (!response.ok) {
|
|
98
|
-
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
99
|
-
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
100
|
-
throw new Error("Something went wrong. Please try again.");
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
return response.json();
|
|
104
|
-
}
|
|
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
|
-
|
|
119
|
-
export async function submitFeedback(
|
|
120
|
-
apiUrl: string,
|
|
121
|
-
data: { suggestion_type: string; suggestion_text: string; vote: "up" | "down"; document_id?: string; publication?: string; user_id?: string; context?: FeedbackContext }
|
|
122
|
-
): Promise<void> {
|
|
123
|
-
const res = await fetch(`${apiUrl}/api/seo-copilot/feedback`, {
|
|
124
|
-
method: "POST",
|
|
125
|
-
headers: { "Content-Type": "application/json" },
|
|
126
|
-
body: JSON.stringify(data),
|
|
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}`);
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
export async function lookupKeywords(
|
|
134
|
-
apiUrl: string,
|
|
135
|
-
keywords: string[],
|
|
136
|
-
signal?: AbortSignal
|
|
137
|
-
): Promise<{ results: { keyword: string; volume: number; cpc: number; competition: number }[]; apiUnitsUsed: number }> {
|
|
138
|
-
const response = await fetch(`${apiUrl}/api/seo-copilot/keywords`, {
|
|
139
|
-
method: "POST",
|
|
140
|
-
headers: { "Content-Type": "application/json" },
|
|
141
|
-
body: JSON.stringify({ keywords }),
|
|
142
|
-
signal,
|
|
143
|
-
});
|
|
144
|
-
|
|
145
|
-
if (!response.ok) {
|
|
146
|
-
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
147
|
-
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
148
|
-
throw new Error("Something went wrong. Please try again.");
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
return response.json();
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
export async function loadChatHistory(
|
|
155
|
-
apiUrl: string,
|
|
156
|
-
userId: string,
|
|
157
|
-
documentId: string
|
|
158
|
-
): Promise<ChatMessage[]> {
|
|
159
|
-
try {
|
|
160
|
-
const res = await fetch(
|
|
161
|
-
`${apiUrl}/api/seo-copilot/chat-history?userId=${encodeURIComponent(userId)}&documentId=${encodeURIComponent(documentId)}`
|
|
162
|
-
);
|
|
163
|
-
if (!res.ok) return [];
|
|
164
|
-
const data = await res.json();
|
|
165
|
-
return (data.messages as ChatMessage[]) || [];
|
|
166
|
-
} catch {
|
|
167
|
-
return [];
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
export async function fetchContentSuggestions(
|
|
172
|
-
apiUrl: string,
|
|
173
|
-
content: string,
|
|
174
|
-
primaryKeyword: string,
|
|
175
|
-
publication?: string,
|
|
176
|
-
signal?: AbortSignal
|
|
177
|
-
): Promise<ContentSuggestions> {
|
|
178
|
-
const empty: ContentSuggestions = { keyTakeaways: [], infographicOpportunities: [], bulletListItems: [] };
|
|
179
|
-
try {
|
|
180
|
-
const res = await fetch(`${apiUrl}/api/seo-copilot/content-suggestions`, {
|
|
181
|
-
method: "POST",
|
|
182
|
-
headers: { "Content-Type": "application/json" },
|
|
183
|
-
body: JSON.stringify({ content, primaryKeyword, publication }),
|
|
184
|
-
signal,
|
|
185
|
-
});
|
|
186
|
-
if (!res.ok) return empty;
|
|
187
|
-
const data = await res.json().catch(() => null);
|
|
188
|
-
if (!data || typeof data !== "object") return empty;
|
|
189
|
-
return {
|
|
190
|
-
keyTakeaways: Array.isArray(data.keyTakeaways) ? data.keyTakeaways : [],
|
|
191
|
-
infographicOpportunities: Array.isArray(data.infographicOpportunities) ? data.infographicOpportunities : [],
|
|
192
|
-
bulletListItems: Array.isArray(data.bulletListItems) ? data.bulletListItems : [],
|
|
193
|
-
};
|
|
194
|
-
} catch {
|
|
195
|
-
return empty;
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
export async function fetchLinkingSuggestions(
|
|
200
|
-
apiUrl: string,
|
|
201
|
-
content: string,
|
|
202
|
-
primaryKeyword: string,
|
|
203
|
-
supportingKeywords: string[],
|
|
204
|
-
currentDocumentId?: string,
|
|
205
|
-
publication?: string,
|
|
206
|
-
signal?: AbortSignal
|
|
207
|
-
): Promise<LinkingSuggestion[]> {
|
|
208
|
-
if (!content || content.trim().length < 50) return [];
|
|
209
|
-
try {
|
|
210
|
-
const res = await fetch(`${apiUrl}/api/seo-copilot/linking-suggestions`, {
|
|
211
|
-
method: "POST",
|
|
212
|
-
headers: { "Content-Type": "application/json" },
|
|
213
|
-
body: JSON.stringify({ content, primaryKeyword, supportingKeywords, currentDocumentId, publication }),
|
|
214
|
-
signal,
|
|
215
|
-
});
|
|
216
|
-
if (!res.ok) return [];
|
|
217
|
-
const data = await res.json().catch(() => null);
|
|
218
|
-
if (!data || !Array.isArray(data.suggestions)) return [];
|
|
219
|
-
return data.suggestions as LinkingSuggestion[];
|
|
220
|
-
} catch {
|
|
221
|
-
return [];
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
// Calls the backend broken-link scanner. Returns one result per unique URL,
|
|
226
|
-
// or an empty array on failure (so callers don't have to handle errors).
|
|
227
|
-
export async function checkLinks(apiUrl: string, urls: string[]): Promise<LinkCheckResult[]> {
|
|
228
|
-
if (!urls || urls.length === 0) return [];
|
|
229
|
-
try {
|
|
230
|
-
const res = await fetch(`${apiUrl}/api/seo-copilot/check-links`, {
|
|
231
|
-
method: "POST",
|
|
232
|
-
headers: { "Content-Type": "application/json" },
|
|
233
|
-
body: JSON.stringify({ urls }),
|
|
234
|
-
});
|
|
235
|
-
if (!res.ok) return [];
|
|
236
|
-
const data = await res.json().catch(() => null);
|
|
237
|
-
if (!data || !Array.isArray(data.results)) return [];
|
|
238
|
-
return data.results as LinkCheckResult[];
|
|
239
|
-
} catch {
|
|
240
|
-
return [];
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
export async function saveChatHistory(
|
|
245
|
-
apiUrl: string,
|
|
246
|
-
userId: string,
|
|
247
|
-
documentId: string,
|
|
248
|
-
messages: ChatMessage[],
|
|
249
|
-
publication?: string
|
|
250
|
-
): Promise<void> {
|
|
251
|
-
try {
|
|
252
|
-
await fetch(`${apiUrl}/api/seo-copilot/chat-history`, {
|
|
253
|
-
method: "POST",
|
|
254
|
-
headers: { "Content-Type": "application/json" },
|
|
255
|
-
body: JSON.stringify({ userId, documentId, messages, publication }),
|
|
256
|
-
});
|
|
257
|
-
} catch {
|
|
258
|
-
// Silent - history save should never break chat
|
|
259
|
-
}
|
|
260
|
-
}
|
|
@@ -1,422 +0,0 @@
|
|
|
1
|
-
// Pure document-parsing helpers, split out of useDocumentContent so they can be
|
|
2
|
-
// unit-tested without a React / Sanity Studio runtime. No imports from "react"
|
|
3
|
-
// or "sanity" here - everything operates on plain Sanity document values.
|
|
4
|
-
|
|
5
|
-
import type { DocumentFields, HeadingItem } from "./types";
|
|
6
|
-
|
|
7
|
-
interface PortableTextSpan {
|
|
8
|
-
_type: string;
|
|
9
|
-
text?: string;
|
|
10
|
-
marks?: string[];
|
|
11
|
-
children?: PortableTextSpan[];
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
interface PortableTextMarkDef {
|
|
15
|
-
_key: string;
|
|
16
|
-
_type: string;
|
|
17
|
-
href?: string;
|
|
18
|
-
url?: string;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
interface PortableTextBlock {
|
|
22
|
-
_type: string;
|
|
23
|
-
style?: string;
|
|
24
|
-
children?: PortableTextSpan[];
|
|
25
|
-
markDefs?: PortableTextMarkDef[];
|
|
26
|
-
text?: string;
|
|
27
|
-
listItem?: string;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export function extractText(blocks: unknown): string {
|
|
31
|
-
if (!blocks || !Array.isArray(blocks)) return "";
|
|
32
|
-
const parts: string[] = [];
|
|
33
|
-
for (const block of blocks as PortableTextBlock[]) {
|
|
34
|
-
if (block._type === "block" && block.children) {
|
|
35
|
-
const blockText = block.children.map((child) => child.text || "").join("");
|
|
36
|
-
if (blockText) parts.push(blockText);
|
|
37
|
-
} else if (typeof block === "string") {
|
|
38
|
-
parts.push(block);
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
return parts.join("\n");
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export function extractHeadings(blocks: unknown): string[] {
|
|
45
|
-
if (!blocks || !Array.isArray(blocks)) return [];
|
|
46
|
-
const headings: string[] = [];
|
|
47
|
-
for (const block of blocks as PortableTextBlock[]) {
|
|
48
|
-
if (block._type === "block" && block.style && /^h[1-6]$/.test(block.style) && block.children) {
|
|
49
|
-
const text = block.children.map((child) => child.text || "").join("");
|
|
50
|
-
if (text) headings.push(text);
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
return headings;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
// Headings with their numeric level (1-6), so the Technical tab can audit hierarchy.
|
|
57
|
-
export function extractHeadingsDetailed(blocks: unknown): HeadingItem[] {
|
|
58
|
-
if (!blocks || !Array.isArray(blocks)) return [];
|
|
59
|
-
const out: HeadingItem[] = [];
|
|
60
|
-
for (const block of blocks as PortableTextBlock[]) {
|
|
61
|
-
if (block._type === "block" && block.style && /^h[1-6]$/.test(block.style) && block.children) {
|
|
62
|
-
const text = block.children.map((child) => child.text || "").join("").trim();
|
|
63
|
-
const level = Number(block.style.slice(1));
|
|
64
|
-
// Include empty headings too - the Technical tab flags them.
|
|
65
|
-
out.push({ text, level });
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
return out;
|
|
69
|
-
}
|
|
70
|
-
|
|
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
|
|
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.
|
|
146
|
-
for (const block of blocks as PortableTextBlock[]) {
|
|
147
|
-
if (block._type === "block" && Array.isArray(block.markDefs)) {
|
|
148
|
-
for (const md of block.markDefs) {
|
|
149
|
-
const href = md.href || md.url;
|
|
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);
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
}
|
|
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.".)
|
|
166
|
-
for (const block of blocks as PortableTextBlock[]) {
|
|
167
|
-
if (block._type === "block" && Array.isArray(block.children)) {
|
|
168
|
-
const blockText = block.children.map((c) => c.text || "").join(" ");
|
|
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); }
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
}
|
|
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);
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
// Slug detection across the common schema shapes. Looks for, in order:
|
|
184
|
-
// 1) A Sanity `slug` type object on any of several field names. MJH stores the
|
|
185
|
-
// slug at `url.current` (a Sanity slug type named "url"); the standard
|
|
186
|
-
// convention is `slug.current`. Check both, plus a few common variants.
|
|
187
|
-
// 2) Plain-string fields under common slug field names (fallback for schemas
|
|
188
|
-
// that store the slug as a flat string).
|
|
189
|
-
// We only accept a string if it looks slug-shaped (lowercase/hyphens, no spaces,
|
|
190
|
-
// no protocol) so we don't mistake a fully-qualified URL for a slug.
|
|
191
|
-
export function detectSlug(val: Record<string, unknown> | undefined): string | undefined {
|
|
192
|
-
if (!val) return undefined;
|
|
193
|
-
// Sanity slug-type objects: { _type: "slug", current: "..." }
|
|
194
|
-
const slugTypeFields = ["slug", "url", "urlSlug", "permalink", "pathname"];
|
|
195
|
-
for (const f of slugTypeFields) {
|
|
196
|
-
const obj = val[f] as { current?: unknown } | undefined;
|
|
197
|
-
if (obj && typeof obj === "object" && typeof obj.current === "string" && obj.current.trim()) {
|
|
198
|
-
return obj.current.trim();
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
// Plain-string fallbacks
|
|
202
|
-
const stringFields = ["urlSlug", "url", "URL", "path", "permalink", "pathname"];
|
|
203
|
-
const slugShape = /^[a-z0-9._~-]+(?:\/[a-z0-9._~-]+)*\/?$/i;
|
|
204
|
-
for (const f of stringFields) {
|
|
205
|
-
const v = val[f];
|
|
206
|
-
if (typeof v === "string") {
|
|
207
|
-
const trimmed = v.trim();
|
|
208
|
-
if (trimmed && !/^https?:\/\//i.test(trimmed) && slugShape.test(trimmed)) {
|
|
209
|
-
return trimmed;
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
return undefined;
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
// Author detection across a broad set of schema shapes. Tries every reasonable
|
|
217
|
-
// field name, handles inline strings, inline objects, and Sanity references
|
|
218
|
-
// (which we can't resolve here, so we mark them so the audit doesn't shout
|
|
219
|
-
// "Missing").
|
|
220
|
-
export function detectAuthor(val: Record<string, unknown> | undefined): {
|
|
221
|
-
authorName?: string;
|
|
222
|
-
authorCredentials?: string;
|
|
223
|
-
authorBioUrl?: string;
|
|
224
|
-
authorIsReference: boolean;
|
|
225
|
-
} {
|
|
226
|
-
if (!val) return { authorIsReference: false };
|
|
227
|
-
const candidateFields = [
|
|
228
|
-
"author", "authors", "byline", "articleAuthor", "primaryAuthor",
|
|
229
|
-
"writer", "writers", "contributor", "contributors",
|
|
230
|
-
"authorMapping", // MJH schema - array of author references
|
|
231
|
-
"Author", "Authors", // PascalCase variants
|
|
232
|
-
];
|
|
233
|
-
// Also scan any field whose NAME mentions author/byline (covers MJH's exact
|
|
234
|
-
// field name whatever it turns out to be), but never the fact-check / reviewer
|
|
235
|
-
// fields - those aren't the visible byline. This is why a referenced author was
|
|
236
|
-
// showing as "Missing": the real field name wasn't in the fixed list above.
|
|
237
|
-
const dynamic = Object.keys(val).filter(
|
|
238
|
-
// Author/byline-ish names, but never fact-check/reviewer fields, nor image/url/
|
|
239
|
-
// id sidecars (e.g. authorPhoto, authorImageUrl, authorId) that could otherwise
|
|
240
|
-
// be mistaken for a reference-typed author.
|
|
241
|
-
(k) => /author|byline/i.test(k) && !/fact|check|review|photo|image|avatar|picture|url|link|count|id$/i.test(k)
|
|
242
|
-
);
|
|
243
|
-
const fields = Array.from(new Set([...candidateFields, ...dynamic]));
|
|
244
|
-
for (const f of fields) {
|
|
245
|
-
const raw = val[f];
|
|
246
|
-
if (!raw) continue;
|
|
247
|
-
const first = Array.isArray(raw) ? raw[0] : raw;
|
|
248
|
-
if (!first) continue;
|
|
249
|
-
if (typeof first === "string") {
|
|
250
|
-
const trimmed = first.trim();
|
|
251
|
-
if (trimmed) return { authorName: trimmed, authorIsReference: false };
|
|
252
|
-
continue;
|
|
253
|
-
}
|
|
254
|
-
if (typeof first === "object" && first !== null) {
|
|
255
|
-
const o = first as Record<string, unknown>;
|
|
256
|
-
const name = ([o.name, o.fullName, o.displayName] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0);
|
|
257
|
-
const creds = ([o.credentials, o.title, o.suffix] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0);
|
|
258
|
-
const slug = (o.slug as { current?: string } | undefined)?.current;
|
|
259
|
-
const bio = (o.bioUrl as string | undefined) || (slug ? `/author/${slug}` : undefined);
|
|
260
|
-
if (name) {
|
|
261
|
-
return { authorName: name, authorCredentials: creds, authorBioUrl: bio, authorIsReference: false };
|
|
262
|
-
}
|
|
263
|
-
// Reference shape - has _ref, or is typed as a reference.
|
|
264
|
-
if (typeof o._ref === "string" || o._type === "reference") {
|
|
265
|
-
return { authorIsReference: true };
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
return { authorIsReference: false };
|
|
270
|
-
}
|
|
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
|
-
|
|
338
|
-
// Extracts image metadata from top-level image fields AND inline body
|
|
339
|
-
// figure/image blocks (where MJH stores article images):
|
|
340
|
-
// - names: alt text + asset filename (for the alt + filename audits)
|
|
341
|
-
// - titles: the `title` field on the image object or asset (the hover tooltip)
|
|
342
|
-
// - count: number of real images found (so the title audit can say "X of N")
|
|
343
|
-
export function extractImageMeta(value: Record<string, unknown>): { names: string[]; titles: string[]; count: number } {
|
|
344
|
-
const names: string[] = [];
|
|
345
|
-
const titles: string[] = [];
|
|
346
|
-
let count = 0;
|
|
347
|
-
const imageFields = ["mainImage", "image", "heroImage", "thumbnail", "featuredImage"];
|
|
348
|
-
for (const field of imageFields) {
|
|
349
|
-
const img = value[field] as Record<string, unknown> | undefined;
|
|
350
|
-
if (!img || typeof img !== "object") continue;
|
|
351
|
-
const asset = img.asset && typeof img.asset === "object" ? (img.asset as Record<string, unknown>) : undefined;
|
|
352
|
-
// Only count entries that are actually images (have an asset or an image _type).
|
|
353
|
-
if (!asset && img._type !== "image") continue;
|
|
354
|
-
count++;
|
|
355
|
-
if (typeof img.alt === "string" && img.alt) names.push(img.alt);
|
|
356
|
-
if (asset && typeof asset.originalFilename === "string" && asset.originalFilename) names.push(asset.originalFilename);
|
|
357
|
-
// The hover-tooltip title can live on the image object or on the asset.
|
|
358
|
-
if (typeof img.title === "string" && img.title) titles.push(img.title);
|
|
359
|
-
else if (asset && typeof asset.title === "string" && asset.title) titles.push(asset.title);
|
|
360
|
-
}
|
|
361
|
-
// Inline body images: MJH (and most editorial schemas) embed article images as
|
|
362
|
-
// `figure`/`image` blocks INSIDE the Portable Text body, not as a top-level
|
|
363
|
-
// field. Without this walk the entire image audit (count, alt, title) is blind
|
|
364
|
-
// to the images that are actually in the article.
|
|
365
|
-
const body = value.body;
|
|
366
|
-
if (Array.isArray(body)) {
|
|
367
|
-
for (const blk of body) {
|
|
368
|
-
if (!blk || typeof blk !== "object") continue;
|
|
369
|
-
const b = blk as Record<string, unknown>;
|
|
370
|
-
if (b._type !== "figure" && b._type !== "image") continue;
|
|
371
|
-
const asset = b.asset && typeof b.asset === "object" ? (b.asset as Record<string, unknown>) : undefined;
|
|
372
|
-
if (!asset && b._type !== "image") continue;
|
|
373
|
-
count++;
|
|
374
|
-
if (typeof b.alt === "string" && b.alt) names.push(b.alt);
|
|
375
|
-
// Asset is usually an unresolved reference here, so originalFilename is
|
|
376
|
-
// rarely present - push it only when the studio expanded the asset.
|
|
377
|
-
if (asset && typeof asset.originalFilename === "string" && asset.originalFilename) names.push(asset.originalFilename);
|
|
378
|
-
if (typeof b.title === "string" && b.title) titles.push(b.title);
|
|
379
|
-
else if (asset && typeof asset.title === "string" && asset.title) titles.push(asset.title);
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
return { names, titles, count };
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
// Assembles the full DocumentFields object from a raw Sanity document value.
|
|
386
|
-
// Pure + side-effect-free so it can be exercised against real fetched documents.
|
|
387
|
-
export function buildDocumentFields(value: Record<string, unknown> | undefined): DocumentFields {
|
|
388
|
-
const val = value;
|
|
389
|
-
const title = typeof val?.title === 'string' ? val.title : undefined;
|
|
390
|
-
const body = val?.body;
|
|
391
|
-
const { authorName, authorCredentials, authorBioUrl, authorIsReference } = detectAuthor(val);
|
|
392
|
-
const { factCheckerName, factCheckerIsReference } = detectFactChecker(val);
|
|
393
|
-
const imageMeta = val ? extractImageMeta(val) : { names: [], titles: [], count: 0 };
|
|
394
|
-
return {
|
|
395
|
-
title: title || undefined,
|
|
396
|
-
// MJH uses `summary`; standard Sanity SEO plugins use `metaDescription`
|
|
397
|
-
metaDescription: ([val?.metaDescription, val?.summary, val?.description, val?.seoDescription] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0),
|
|
398
|
-
slug: detectSlug(val),
|
|
399
|
-
imageNames: imageMeta.names,
|
|
400
|
-
imageTitles: imageMeta.titles,
|
|
401
|
-
imageCount: imageMeta.count,
|
|
402
|
-
headings: extractHeadings(body),
|
|
403
|
-
headingsDetailed: extractHeadingsDetailed(body),
|
|
404
|
-
unstyledHeadings: extractUnstyledHeadings(body),
|
|
405
|
-
bodyLinks: extractBodyLinks(body),
|
|
406
|
-
bodyLinksDetailed: extractBodyLinksDetailed(body),
|
|
407
|
-
contentCategory: typeof val?.contentCategory === 'string' ? val.contentCategory : typeof val?.category === 'string' ? val.category : undefined,
|
|
408
|
-
contentPlacement: Array.isArray(val?.contentPlacement) ? (val.contentPlacement as string[]) : undefined,
|
|
409
|
-
authorName,
|
|
410
|
-
authorCredentials,
|
|
411
|
-
authorBioUrl,
|
|
412
|
-
authorIsReference,
|
|
413
|
-
factCheckerName,
|
|
414
|
-
factCheckerIsReference,
|
|
415
|
-
// `published` is MJH's date field; `publishedAt`/`publishDate` cover other schemas
|
|
416
|
-
publishedAt: ([val?.publishedAt, val?.publishDate, val?.published, val?._createdAt] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0),
|
|
417
|
-
// `updatedOn` is MJH's "Updated On" field. `updatedAt` is the standard Sanity convention.
|
|
418
|
-
// `_updatedAt` is the Sanity-managed timestamp as a final fallback.
|
|
419
|
-
updatedAt: ([val?.updatedOn, val?.updatedAt, val?._updatedAt] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0),
|
|
420
|
-
lastReviewedAt: ([val?.lastReviewedAt, val?.lastReviewed, val?.medicallyReviewedAt] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0),
|
|
421
|
-
};
|
|
422
|
-
}
|