sanity-plugin-seo-copilot 0.2.15 → 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 +841 -782
- package/dist/index.mjs +763 -704
- package/package.json +62 -64
- 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 -1234
- 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 -18
- package/src/inspector.ts +0 -58
- package/src/lib/api.ts +0 -262
- package/src/lib/apiKey.ts +0 -30
- 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
|
@@ -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
|
-
}
|
package/src/lib/geoAnalysis.ts
DELETED
|
@@ -1,122 +0,0 @@
|
|
|
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
|
-
// 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 [];
|
|
43
|
-
const headingSet = new Set(headings.map((h) => h.trim().toLowerCase()));
|
|
44
|
-
const lower = text.toLowerCase();
|
|
45
|
-
return questionHeadings.map((heading) => {
|
|
46
|
-
const needle = heading.trim().toLowerCase();
|
|
47
|
-
const idx = lower.indexOf(needle);
|
|
48
|
-
if (idx === -1) {
|
|
49
|
-
return { heading, words: 0, status: "missing-body" as const };
|
|
50
|
-
}
|
|
51
|
-
// Walk the lines after the heading: collect non-empty lines that aren't themselves
|
|
52
|
-
// another heading. Stop at the next heading (the next section starts).
|
|
53
|
-
// Portable Text blocks are joined with single \n by useDocumentContent.extractText,
|
|
54
|
-
// so the "answer paragraph" is the next non-empty, non-heading line(s).
|
|
55
|
-
const after = text.slice(idx + heading.length);
|
|
56
|
-
const lines = after.split(/\n/);
|
|
57
|
-
const answerParts: string[] = [];
|
|
58
|
-
for (const raw of lines) {
|
|
59
|
-
const t = raw.trim();
|
|
60
|
-
if (!t) continue;
|
|
61
|
-
if (headingSet.has(t.toLowerCase())) break;
|
|
62
|
-
answerParts.push(t);
|
|
63
|
-
// Cap collection so we don't walk an entire article if no next heading exists
|
|
64
|
-
const sofar = answerParts.join(" ");
|
|
65
|
-
if (sofar.split(/\s+/).length > 120) break;
|
|
66
|
-
}
|
|
67
|
-
const words = wordCount(answerParts.join(" "));
|
|
68
|
-
if (words === 0) return { heading, words: 0, status: "missing-body" as const };
|
|
69
|
-
if (words < 30) return { heading, words, status: "too-short" as const };
|
|
70
|
-
if (words > 70) return { heading, words, status: "too-long" as const };
|
|
71
|
-
return { heading, words, status: "good" as const };
|
|
72
|
-
});
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
export function analyzeFactDensity(text: string): FactDensityResult {
|
|
76
|
-
const total = wordCount(text);
|
|
77
|
-
if (total === 0) {
|
|
78
|
-
return { totalWords: 0, factCount: 0, factsPerThousandWords: 0, driftPassages: 0, status: "weak" };
|
|
79
|
-
}
|
|
80
|
-
// Count facts
|
|
81
|
-
const matches = text.match(new RegExp(FACT_PATTERN.source, "gi")) || [];
|
|
82
|
-
const factCount = matches.length;
|
|
83
|
-
const factsPer1000 = Math.round((factCount / total) * 1000);
|
|
84
|
-
|
|
85
|
-
// Drift passages: sliding 200-word windows with zero facts
|
|
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);
|
|
89
|
-
let drift = 0;
|
|
90
|
-
let runWords = 0;
|
|
91
|
-
let runHasFact = false;
|
|
92
|
-
for (const s of sentences) {
|
|
93
|
-
const w = wordCount(s);
|
|
94
|
-
if (new RegExp(FACT_PATTERN.source, "i").test(s)) runHasFact = true;
|
|
95
|
-
runWords += w;
|
|
96
|
-
if (runWords >= 200) {
|
|
97
|
-
if (!runHasFact) drift += 1;
|
|
98
|
-
runWords = 0;
|
|
99
|
-
runHasFact = false;
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
// 2026 GEO research (Princeton, Averi citation benchmarks): the center of the
|
|
104
|
-
// recommended fact-density range is ~8 stats per 1,000 words (1 every ~125
|
|
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.
|
|
109
|
-
let status: FactDensityResult["status"];
|
|
110
|
-
if (factsPer1000 >= 8) status = "strong";
|
|
111
|
-
else if (factsPer1000 >= 4) status = "moderate";
|
|
112
|
-
else status = "weak";
|
|
113
|
-
|
|
114
|
-
return { totalWords: total, factCount, factsPerThousandWords: factsPer1000, driftPassages: drift, status };
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
export function analyzeGEO(text: string, headings: string[]): GEOAnalysis {
|
|
118
|
-
return {
|
|
119
|
-
headingAudit: analyzeHeadings(text, headings),
|
|
120
|
-
factDensity: analyzeFactDensity(text),
|
|
121
|
-
};
|
|
122
|
-
}
|
package/src/lib/persistence.ts
DELETED
|
@@ -1,69 +0,0 @@
|
|
|
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
|
-
}
|