sanity-plugin-seo-copilot 0.2.7 → 0.2.10

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.
@@ -82,6 +82,8 @@ export function useKeywordAnalysis(
82
82
  docVersionRef.current += 1;
83
83
  volumeAbortRef.current?.abort();
84
84
  volumeAbortRef.current = null;
85
+ deepAbortRef.current?.abort();
86
+ deepAbortRef.current = null;
85
87
  const fresh = loadCached();
86
88
  cached.current = fresh;
87
89
  setAnalysisRaw(fresh.analysis);
@@ -131,6 +133,66 @@ export function useKeywordAnalysis(
131
133
  // AbortController for the in-flight volume lookup. Cancelled on doc switch and
132
134
  // before each new lookup so only one lookup is ever outstanding at a time.
133
135
  const volumeAbortRef = useRef<AbortController | null>(null);
136
+ const deepAbortRef = useRef<AbortController | null>(null);
137
+
138
+ // Abort any in-flight volume lookup or deep analysis when the hook unmounts so a late
139
+ // resolver can't run after teardown and we don't waste backend (Claude/SEMrush) spend.
140
+ useEffect(() => () => {
141
+ volumeAbortRef.current?.abort();
142
+ deepAbortRef.current?.abort();
143
+ }, []);
144
+
145
+ const doVolumeLookup = useCallback((analysisResult: SEOAnalysis, terms?: string[]) => {
146
+ setIsVolumesLoading(true);
147
+ const myVersion = docVersionRef.current;
148
+
149
+ const lookupTerms = terms || (() => {
150
+ const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
151
+ return [
152
+ ...new Set([
153
+ ...candidateTerms,
154
+ analysisResult.primaryKeyword.term,
155
+ ...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
156
+ ...analysisResult.missingKeywords.map((kw) => kw.term),
157
+ ]),
158
+ ];
159
+ })();
160
+
161
+ if (lookupTerms.length === 0) {
162
+ setIsVolumesLoading(false);
163
+ return;
164
+ }
165
+
166
+ // Cancel any previous in-flight lookup before starting a new one
167
+ volumeAbortRef.current?.abort();
168
+ const controller = new AbortController();
169
+ volumeAbortRef.current = controller;
170
+
171
+ lookupKeywords(apiUrl, lookupTerms, controller.signal)
172
+ .then(({ results }) => {
173
+ if (docVersionRef.current !== myVersion) return; // document switched - drop stale volumes
174
+ // Add new results to persistent cache
175
+ results.forEach((r) => volumeMapRef.current.set(r.keyword.toLowerCase(), r));
176
+ // Re-apply all cached volumes to current analysis
177
+ const current = lastAnalysisRef.current || analysisResult;
178
+ const merged = mergeVolumes(current, volumeMapRef.current);
179
+ lastAnalysisRef.current = merged;
180
+ setAnalysisRaw(merged);
181
+ try {
182
+ const prev = loadCached();
183
+ localStorage.setItem(cacheKey, JSON.stringify({ ...prev, analysis: merged }));
184
+ } catch { /* ignore */ }
185
+ setIsVolumesLoading(false);
186
+ })
187
+ .catch((err) => {
188
+ if (err instanceof Error && err.name === "AbortError") return;
189
+ if (docVersionRef.current !== myVersion) return;
190
+ setIsVolumesLoading(false);
191
+ });
192
+ }, [apiUrl, cacheKey]);
193
+
194
+ const doVolumeLookupRef = useRef(doVolumeLookup);
195
+ useEffect(() => { doVolumeLookupRef.current = doVolumeLookup; }, [doVolumeLookup]);
134
196
 
135
197
  useEffect(() => {
136
198
  if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) {
@@ -164,7 +226,7 @@ export function useKeywordAnalysis(
164
226
  const uncachedTerms = allTerms.filter((t) => !volumeMapRef.current.has(t.toLowerCase()));
165
227
 
166
228
  if (uncachedTerms.length > 0) {
167
- doVolumeLookup(analysisResult, uncachedTerms);
229
+ doVolumeLookupRef.current(analysisResult, uncachedTerms);
168
230
  }
169
231
  })
170
232
  .catch((err) => {
@@ -184,55 +246,6 @@ export function useKeywordAnalysis(
184
246
  // eslint-disable-next-line react-hooks/exhaustive-deps
185
247
  }, [text, apiUrl, publication, effectiveSeeds?.join(","), focusPrimary, JSON.stringify(documentFields)]);
186
248
 
187
- const doVolumeLookup = useCallback((analysisResult: SEOAnalysis, terms?: string[]) => {
188
- setIsVolumesLoading(true);
189
- const myVersion = docVersionRef.current;
190
-
191
- const lookupTerms = terms || (() => {
192
- const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
193
- return [
194
- ...new Set([
195
- ...candidateTerms,
196
- analysisResult.primaryKeyword.term,
197
- ...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
198
- ...analysisResult.missingKeywords.map((kw) => kw.term),
199
- ]),
200
- ];
201
- })();
202
-
203
- if (lookupTerms.length === 0) {
204
- setIsVolumesLoading(false);
205
- return;
206
- }
207
-
208
- // Cancel any previous in-flight lookup before starting a new one
209
- volumeAbortRef.current?.abort();
210
- const controller = new AbortController();
211
- volumeAbortRef.current = controller;
212
-
213
- lookupKeywords(apiUrl, lookupTerms, controller.signal)
214
- .then(({ results }) => {
215
- if (docVersionRef.current !== myVersion) return; // document switched - drop stale volumes
216
- // Add new results to persistent cache
217
- results.forEach((r) => volumeMapRef.current.set(r.keyword.toLowerCase(), r));
218
- // Re-apply all cached volumes to current analysis
219
- const current = lastAnalysisRef.current || analysisResult;
220
- const merged = mergeVolumes(current, volumeMapRef.current);
221
- lastAnalysisRef.current = merged;
222
- setAnalysisRaw(merged);
223
- try {
224
- const prev = loadCached();
225
- localStorage.setItem(cacheKey, JSON.stringify({ ...prev, analysis: merged }));
226
- } catch { /* ignore */ }
227
- setIsVolumesLoading(false);
228
- })
229
- .catch((err) => {
230
- if (err instanceof Error && err.name === "AbortError") return;
231
- if (docVersionRef.current !== myVersion) return;
232
- setIsVolumesLoading(false);
233
- });
234
- }, [apiUrl, cacheKey]);
235
-
236
249
  const refreshVolumes = useCallback(() => {
237
250
  const current = lastAnalysisRef.current || analysis;
238
251
  if (!current) return;
@@ -248,18 +261,21 @@ export function useKeywordAnalysis(
248
261
  setAeoTextSnapshot(text);
249
262
 
250
263
  const myVersion = docVersionRef.current;
251
- fetchAnalysis(apiUrl, text, "deep", publication, effectiveSeeds, documentFields, focusPrimary)
264
+ deepAbortRef.current?.abort(); const deepController = new AbortController(); deepAbortRef.current = deepController;
265
+ fetchAnalysis(apiUrl, text, "deep", publication, effectiveSeeds, documentFields, focusPrimary, deepController.signal)
252
266
  .then((result) => {
253
267
  if (docVersionRef.current !== myVersion) return; // document switched - drop stale result
254
268
  setDeepAnalysis(result as DeepAnalysis);
255
269
  setIsDeepLoading(false);
256
270
  })
257
271
  .catch((err) => {
272
+ // Aborted (doc switch or unmount) is normal teardown, not an error to surface.
273
+ if (deepController.signal.aborted || err?.name === "AbortError") return;
258
274
  if (docVersionRef.current !== myVersion) return;
259
275
  setError(err.message);
260
276
  setIsDeepLoading(false);
261
277
  });
262
- }, [text, apiUrl, publication, effectiveSeeds?.join(","), documentFields]);
278
+ }, [text, apiUrl, publication, effectiveSeeds?.join(","), documentFields, focusPrimary]);
263
279
 
264
280
  return {
265
281
  analysis,
@@ -15,6 +15,7 @@ interface KeywordPanelData {
15
15
  }
16
16
 
17
17
  function getLocalUserId(): string {
18
+ if (typeof window === 'undefined') return 'anonymous';
18
19
  const key = "seo-copilot-user-id";
19
20
  try {
20
21
  let id = localStorage.getItem(key);
@@ -88,7 +89,10 @@ export function useSEOChat(
88
89
 
89
90
  // Abort any in-flight stream on unmount to prevent state updates on a dead component.
90
91
  useEffect(() => {
91
- return () => { streamAbortRef.current?.abort(); };
92
+ return () => {
93
+ streamAbortRef.current?.abort();
94
+ if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
95
+ };
92
96
  }, []);
93
97
 
94
98
  const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
package/src/inspector.ts CHANGED
@@ -42,7 +42,6 @@ export function seoCopilotInspector(config: SEOCopilotConfig): DocumentInspector
42
42
  useMenuItem: () => ({
43
43
  title: "SEO Copilot",
44
44
  icon: SEOIcon,
45
- showAsAction: true,
46
45
  }),
47
46
  component: function SEOCopilotInspector(props: DocumentInspectorProps) {
48
47
  return createElement(SEOCopilotPanel, { ...props, config });
package/src/lib/api.ts CHANGED
@@ -43,7 +43,6 @@ export async function fetchAnalysis(
43
43
 
44
44
  if (!response.ok) {
45
45
  const err = safeParseJson<{ error?: string }>(text);
46
- console.error("[seo-copilot] analyze error", response.status, err.error);
47
46
  if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
48
47
  if (response.status >= 500) throw new Error("Could not reach the SEO service.");
49
48
  throw new Error("Something went wrong analyzing this document.");
@@ -76,7 +75,6 @@ export async function fetchChatStream(
76
75
 
77
76
  if (!response.ok) {
78
77
  const err = await response.json().catch(() => ({ error: "Request failed" }));
79
- console.error("[seo-copilot] chat error", response.status, err.error);
80
78
  if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
81
79
  if (response.status >= 500) throw new Error("Could not reach the SEO service.");
82
80
  throw new Error("Something went wrong. Please try again.");
@@ -87,17 +85,18 @@ export async function fetchChatStream(
87
85
 
88
86
  export async function fetchQuestions(
89
87
  apiUrl: string,
90
- keyword: string
88
+ keyword: string,
89
+ signal?: AbortSignal
91
90
  ): Promise<{ questions: { question: string; volume: number; cpc: number; competition: number }[]; apiUnitsUsed: number }> {
92
91
  const response = await fetch(`${apiUrl}/api/seo-copilot/questions`, {
93
92
  method: "POST",
94
93
  headers: { "Content-Type": "application/json" },
95
94
  body: JSON.stringify({ keyword }),
95
+ signal,
96
96
  });
97
97
 
98
98
  if (!response.ok) {
99
99
  const err = await response.json().catch(() => ({ error: "Request failed" }));
100
- console.error("[seo-copilot] questions error", response.status, err.error);
101
100
  if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
102
101
  if (response.status >= 500) throw new Error("Could not reach the SEO service.");
103
102
  throw new Error("Something went wrong. Please try again.");
@@ -131,7 +130,6 @@ export async function lookupKeywords(
131
130
 
132
131
  if (!response.ok) {
133
132
  const err = await response.json().catch(() => ({ error: "Request failed" }));
134
- console.error("[seo-copilot] keywords error", response.status, err.error);
135
133
  if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
136
134
  if (response.status >= 500) throw new Error("Could not reach the SEO service.");
137
135
  throw new Error("Something went wrong. Please try again.");
@@ -161,7 +159,8 @@ export async function fetchContentSuggestions(
161
159
  apiUrl: string,
162
160
  content: string,
163
161
  primaryKeyword: string,
164
- publication?: string
162
+ publication?: string,
163
+ signal?: AbortSignal
165
164
  ): Promise<ContentSuggestions> {
166
165
  const empty: ContentSuggestions = { keyTakeaways: [], infographicOpportunities: [], bulletListItems: [] };
167
166
  try {
@@ -169,6 +168,7 @@ export async function fetchContentSuggestions(
169
168
  method: "POST",
170
169
  headers: { "Content-Type": "application/json" },
171
170
  body: JSON.stringify({ content, primaryKeyword, publication }),
171
+ signal,
172
172
  });
173
173
  if (!res.ok) return empty;
174
174
  const data = await res.json().catch(() => null);
@@ -233,7 +233,8 @@ export async function fetchLinkingSuggestions(
233
233
  primaryKeyword: string,
234
234
  supportingKeywords: string[],
235
235
  currentDocumentId?: string,
236
- publication?: string
236
+ publication?: string,
237
+ signal?: AbortSignal
237
238
  ): Promise<LinkingSuggestion[]> {
238
239
  if (!content || content.trim().length < 50) return [];
239
240
  try {
@@ -241,6 +242,7 @@ export async function fetchLinkingSuggestions(
241
242
  method: "POST",
242
243
  headers: { "Content-Type": "application/json" },
243
244
  body: JSON.stringify({ content, primaryKeyword, supportingKeywords, currentDocumentId, publication }),
245
+ signal,
244
246
  });
245
247
  if (!res.ok) return [];
246
248
  const data = await res.json().catch(() => null);
@@ -170,8 +170,8 @@ export function detectAuthor(val: Record<string, unknown> | undefined): {
170
170
  }
171
171
  if (typeof first === "object" && first !== null) {
172
172
  const o = first as Record<string, unknown>;
173
- const name = (o.name || o.fullName || o.displayName) as string | undefined;
174
- const creds = (o.credentials || o.title || o.suffix) as string | undefined;
173
+ const name = ([o.name, o.fullName, o.displayName] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0);
174
+ const creds = ([o.credentials, o.title, o.suffix] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0);
175
175
  const slug = (o.slug as { current?: string } | undefined)?.current;
176
176
  const bio = (o.bioUrl as string | undefined) || (slug ? `/author/${slug}` : undefined);
177
177
  if (name) {
@@ -237,14 +237,14 @@ export function extractImageMeta(value: Record<string, unknown>): { names: strin
237
237
  // Pure + side-effect-free so it can be exercised against real fetched documents.
238
238
  export function buildDocumentFields(value: Record<string, unknown> | undefined): DocumentFields {
239
239
  const val = value;
240
- const title = val?.title as string | undefined;
240
+ const title = typeof val?.title === 'string' ? val.title : undefined;
241
241
  const body = val?.body;
242
242
  const { authorName, authorCredentials, authorBioUrl, authorIsReference } = detectAuthor(val);
243
243
  const imageMeta = val ? extractImageMeta(val) : { names: [], titles: [], count: 0 };
244
244
  return {
245
245
  title: title || undefined,
246
246
  // MJH uses `summary`; standard Sanity SEO plugins use `metaDescription`
247
- metaDescription: (val?.metaDescription || val?.summary || val?.description || val?.seoDescription) as string | undefined,
247
+ metaDescription: ([val?.metaDescription, val?.summary, val?.description, val?.seoDescription] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0),
248
248
  slug: detectSlug(val),
249
249
  imageNames: imageMeta.names,
250
250
  imageTitles: imageMeta.titles,
@@ -252,17 +252,17 @@ export function buildDocumentFields(value: Record<string, unknown> | undefined):
252
252
  headings: extractHeadings(body),
253
253
  headingsDetailed: extractHeadingsDetailed(body),
254
254
  bodyLinks: extractBodyLinks(body),
255
- contentCategory: (val?.contentCategory || val?.category) as string | undefined,
255
+ contentCategory: typeof val?.contentCategory === 'string' ? val.contentCategory : typeof val?.category === 'string' ? val.category : undefined,
256
256
  contentPlacement: Array.isArray(val?.contentPlacement) ? (val.contentPlacement as string[]) : undefined,
257
257
  authorName,
258
258
  authorCredentials,
259
259
  authorBioUrl,
260
260
  authorIsReference,
261
261
  // `published` is MJH's date field; `publishedAt`/`publishDate` cover other schemas
262
- publishedAt: (val?.published || val?.publishedAt || val?.publishDate || val?._createdAt) as string | undefined,
262
+ publishedAt: ([val?.publishedAt, val?.publishDate, val?.published, val?._createdAt] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0),
263
263
  // `updatedOn` is MJH's "Updated On" field. `updatedAt` is the standard Sanity convention.
264
264
  // `_updatedAt` is the Sanity-managed timestamp as a final fallback.
265
- updatedAt: (val?.updatedOn || val?.updatedAt || val?._updatedAt) as string | undefined,
266
- lastReviewedAt: (val?.lastReviewedAt || val?.lastReviewed || val?.medicallyReviewedAt) as string | undefined,
265
+ updatedAt: ([val?.updatedOn, val?.updatedAt, val?._updatedAt] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0),
266
+ lastReviewedAt: ([val?.lastReviewedAt, val?.lastReviewed, val?.medicallyReviewedAt] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0),
267
267
  };
268
268
  }
@@ -41,7 +41,7 @@ export function calculateContentScoreDetailed(content: string, analysis: SEOAnal
41
41
  // adjacent phrase, but if every token is in the body the keyword IS present.
42
42
  // Try the exact phrase first; otherwise fall back to token co-occurrence (all
43
43
  // tokens present) and use the rarest token as the concept's mention count.
44
- // (This mirrors tokensContain() used by the Meta + Summary audits.)
44
+ // (This mirrors containsKeywordTokens() used by the Meta + Summary audits.)
45
45
  const tokens = primaryTerm.split(/\s+/).filter((t) => t.length > 1);
46
46
  const phraseCount = countWholeMatches(lowerContent, primaryTerm);
47
47
  let occurrences = phraseCount;
@@ -88,7 +88,7 @@ export function calculateContentScoreDetailed(content: string, analysis: SEOAnal
88
88
  // 2. Supporting keyword coverage (up to 25)
89
89
  const supportingKws = analysis.supportingKeywords || [];
90
90
  if (supportingKws.length > 0) {
91
- const inContentCount = supportingKws.filter((kw) => lowerContent.includes(kw.term.toLowerCase())).length;
91
+ const inContentCount = supportingKws.filter((kw) => kw != null && typeof kw.term === "string" && lowerContent.includes(kw.term.toLowerCase())).length;
92
92
  const coverageRatio = inContentCount / supportingKws.length;
93
93
  const pts = Math.round(coverageRatio * 25);
94
94
  components.push({
@@ -28,26 +28,7 @@ interface BuildSummaryInput {
28
28
  secondaryKeyword?: string;
29
29
  }
30
30
 
31
- function tokensContain(haystack: string, needle?: string): boolean {
32
- if (!needle) return true;
33
- const tokens = needle.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
34
- if (tokens.length === 0) return true;
35
- const lower = haystack.toLowerCase();
36
- return tokens.every((t) => lower.includes(t));
37
- }
38
-
39
- // True when the primary keyword leads the URL slug (within the first three words).
40
- function keywordLeadsSlug(slug: string, primaryKeyword: string): boolean {
41
- const slugWords = slug.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim().split(/\s+/).filter(Boolean);
42
- const tokens = primaryKeyword.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
43
- if (tokens.length === 0 || slugWords.length === 0) return true;
44
- let earliest = Infinity;
45
- for (const t of tokens) {
46
- const idx = slugWords.findIndex((w) => w.includes(t));
47
- if (idx >= 0) earliest = Math.min(earliest, idx);
48
- }
49
- return earliest <= 2;
50
- }
31
+ import { containsKeywordTokens, keywordLeadsSlug } from "./utils";
51
32
 
52
33
  // Conference previews, news briefs, recaps, and listicles are legitimately short.
53
34
  // Detect them so we don't nag "push past 1,500 words" on content that should be
@@ -76,6 +57,16 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
76
57
  const { analysis, deepAnalysis, documentFields, linkingSuggestions, linkCheckResults, text } = input;
77
58
  const primaryKeyword = input.primaryKeyword || analysis?.primaryKeyword?.term;
78
59
  const secondaryKeyword = input.secondaryKeyword || "";
60
+ // Body-only text: useDocumentContent prepends the document title so the AI
61
+ // analysis includes it, but word-count and keyword-in-body checks must not
62
+ // count the title as body content. Strip the title prefix when present.
63
+ const bodyText = (() => {
64
+ if (!documentFields?.title) return text;
65
+ if (!text.startsWith(documentFields.title)) return text;
66
+ const rest = text.slice(documentFields.title.length);
67
+ if (rest === "" || /^\s/.test(rest)) return rest.trimStart();
68
+ return text;
69
+ })();
79
70
 
80
71
  // ---------- META: title ----------
81
72
  // Length warnings removed - the article title IS the page title and editors
@@ -94,7 +85,7 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
94
85
  jumpTo: { tab: "meta", anchorId: "anchor-meta-title" },
95
86
  });
96
87
  } else if (primaryKeyword) {
97
- if (!tokensContain(title, primaryKeyword)) {
88
+ if (!containsKeywordTokens(title, primaryKeyword)) {
98
89
  items.push({
99
90
  id: "meta-title-no-keyword",
100
91
  category: "meta",
@@ -163,7 +154,7 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
163
154
  jumpTo: { tab: "meta", anchorId: "anchor-meta-description" },
164
155
  });
165
156
  }
166
- if (primaryKeyword && !tokensContain(meta, primaryKeyword)) {
157
+ if (primaryKeyword && !containsKeywordTokens(meta, primaryKeyword)) {
167
158
  items.push({
168
159
  id: "meta-desc-no-keyword",
169
160
  category: "meta",
@@ -192,7 +183,7 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
192
183
  });
193
184
  } else {
194
185
  const slugAsWords = slug.replace(/-/g, " ");
195
- if (primaryKeyword && !tokensContain(slugAsWords, primaryKeyword)) {
186
+ if (primaryKeyword && !containsKeywordTokens(slugAsWords, primaryKeyword)) {
196
187
  items.push({
197
188
  id: "meta-slug-no-keyword",
198
189
  category: "meta",
@@ -218,7 +209,7 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
218
209
  // ---------- CONTENT: word count ----------
219
210
  // 450 is the body-text floor (per editor guidance). 1,500+ is the competitive
220
211
  // target for HCP clinical articles.
221
- const wordCount = text ? text.trim().split(/\s+/).filter(Boolean).length : 0;
212
+ const wordCount = bodyText ? bodyText.trim().split(/\s+/).filter(Boolean).length : 0;
222
213
  // Videos, podcasts, news, briefs, etc. are legitimately short (the body is a
223
214
  // summary, not the deliverable), so they're exempt from the word-count floor.
224
215
  const isShortForm = isShortFormContent(documentFields, title);
@@ -256,7 +247,7 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
256
247
  const h2Count = headingsDetailed
257
248
  ? headingsDetailed.filter((h) => h.level === 2 || h.level === 3).length
258
249
  : headings.length;
259
- if (headings.length === 0 && wordCount > 200 && wordCount < 1000) {
250
+ if (h2Count === 0 && wordCount > 200 && wordCount < 1000) {
260
251
  items.push({
261
252
  id: "headings-missing",
262
253
  category: "headings",
@@ -369,7 +360,7 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
369
360
  if (GENERIC_FN_RE.test(base)) return true;
370
361
  if (/_/.test(base) || /\s/.test(base)) return true;
371
362
  const words = base.split("-").filter(Boolean);
372
- return words.length < 2 || words.length > 7;
363
+ return words.length < 2 || words.length > 5;
373
364
  });
374
365
  if (badFilenames.length > 0) {
375
366
  items.push({
@@ -387,7 +378,7 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
387
378
  if (!trimmed) return false;
388
379
  const len = trimmed.length;
389
380
  const wc = trimmed.split(/\s+/).filter(Boolean).length;
390
- return len > 125 || wc < 2;
381
+ return len >= 125 || wc < 2;
391
382
  });
392
383
  if (badAlts.length > 0) {
393
384
  items.push({
@@ -425,7 +416,7 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
425
416
  // Keywords haven't loaded - skip
426
417
  } else {
427
418
  // If primary is missing from body, flag it
428
- if (text && !tokensContain(text, primaryKeyword)) {
419
+ if (bodyText && !containsKeywordTokens(bodyText, primaryKeyword)) {
429
420
  items.push({
430
421
  id: "keywords-primary-not-in-body",
431
422
  category: "keywords",
@@ -460,7 +451,7 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
460
451
  // When the editor has chosen an optional secondary keyword, flag the spots it's
461
452
  // missing from so the "primary in, secondary out" gaps are visible at a glance.
462
453
  if (secondaryKeyword) {
463
- if (text && !tokensContain(text, secondaryKeyword)) {
454
+ if (bodyText && !containsKeywordTokens(bodyText, secondaryKeyword)) {
464
455
  items.push({
465
456
  id: "secondary-not-in-body",
466
457
  category: "keywords",
@@ -472,19 +463,19 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
472
463
  });
473
464
  }
474
465
  const titleVal = documentFields?.title;
475
- if (titleVal && !tokensContain(titleVal, secondaryKeyword)) {
466
+ if (titleVal && !containsKeywordTokens(titleVal, secondaryKeyword)) {
476
467
  items.push({
477
468
  id: "secondary-not-in-title",
478
469
  category: "meta",
479
470
  severity: "opportunity",
480
471
  label: "Secondary keyword not in title",
481
- description: `The title leads with the primary keyword but doesn't include "${secondaryKeyword}".`,
472
+ description: `The title doesn't include your secondary keyword "${secondaryKeyword}".`,
482
473
  howToFix: "If it fits naturally, include the secondary keyword in the title too - but never at the cost of the primary leading.",
483
474
  jumpTo: { tab: "meta", anchorId: "anchor-meta-title" },
484
475
  });
485
476
  }
486
477
  const metaVal = documentFields?.metaDescription;
487
- if (metaVal && !tokensContain(metaVal, secondaryKeyword)) {
478
+ if (metaVal && !containsKeywordTokens(metaVal, secondaryKeyword)) {
488
479
  items.push({
489
480
  id: "secondary-not-in-meta",
490
481
  category: "meta",
@@ -496,7 +487,7 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
496
487
  });
497
488
  }
498
489
  const slugVal = documentFields?.slug;
499
- if (slugVal && !tokensContain(slugVal.replace(/-/g, " "), secondaryKeyword)) {
490
+ if (slugVal && !containsKeywordTokens(slugVal.replace(/-/g, " "), secondaryKeyword)) {
500
491
  items.push({
501
492
  id: "secondary-not-in-url",
502
493
  category: "meta",
@@ -0,0 +1,35 @@
1
+ // Token-based keyword match: "selinexor in myelofibrosis" still counts as containing
2
+ // "selinexor myelofibrosis" because word order and connecting words don't matter.
3
+ export function containsKeywordTokens(haystack: string, needle?: string): boolean {
4
+ if (!needle) return true;
5
+ const tokens = needle.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
6
+ if (tokens.length === 0) return true;
7
+ const lower = haystack.toLowerCase();
8
+ return tokens.every((t) => lower.includes(t));
9
+ }
10
+
11
+ // True when the primary keyword sits near the start of the slug (within the first
12
+ // three slug words). Editors get the most SEO/CTR value when the keyword leads.
13
+ export function keywordLeadsSlug(slug: string, primaryKeyword?: string): boolean {
14
+ if (!primaryKeyword) return true;
15
+ const slugWords = slug.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim().split(/\s+/).filter(Boolean);
16
+ const tokens = primaryKeyword.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
17
+ if (tokens.length === 0 || slugWords.length === 0) return true;
18
+ let earliest = Infinity;
19
+ for (const t of tokens) {
20
+ const idx = slugWords.findIndex((w) => w.includes(t));
21
+ if (idx >= 0) earliest = Math.min(earliest, idx);
22
+ }
23
+ return earliest <= 2;
24
+ }
25
+
26
+ // MJH publications that use the /view/{slug} article route (verified via CDN probe).
27
+ // We only construct live URLs for known publications to avoid linking to 404s on
28
+ // brands that use a different route pattern.
29
+ export const KNOWN_MJH_PUBLICATIONS = new Set([
30
+ "onclive",
31
+ "hcplive",
32
+ "ajmc",
33
+ "pharmacytimes",
34
+ "cancernetwork",
35
+ ]);