sanity-plugin-seo-copilot 0.2.0 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -33,18 +33,21 @@ __export(index_exports, {
33
33
  seoCopilot: () => seoCopilot
34
34
  });
35
35
  module.exports = __toCommonJS(index_exports);
36
- var import_sanity3 = require("sanity");
36
+ var import_sanity4 = require("sanity");
37
37
 
38
38
  // src/inspector.ts
39
39
  var import_react19 = require("react");
40
40
 
41
41
  // src/components/SEOCopilotPanel.tsx
42
42
  var import_react18 = require("react");
43
+ var import_sanity3 = require("sanity");
43
44
  var import_react_dom = require("react-dom");
44
45
 
45
46
  // src/hooks/useDocumentContent.ts
46
47
  var import_react = require("react");
47
48
  var import_structure = require("sanity/structure");
49
+
50
+ // src/lib/documentExtract.ts
48
51
  function extractText(blocks) {
49
52
  if (!blocks || !Array.isArray(blocks)) return "";
50
53
  const parts = [];
@@ -106,6 +109,72 @@ function extractBodyLinks(blocks) {
106
109
  }
107
110
  return Array.from(urls);
108
111
  }
112
+ function detectSlug(val) {
113
+ if (!val) return void 0;
114
+ const slugTypeFields = ["slug", "url", "urlSlug", "permalink", "pathname"];
115
+ for (const f of slugTypeFields) {
116
+ const obj = val[f];
117
+ if (obj && typeof obj === "object" && typeof obj.current === "string" && obj.current.trim()) {
118
+ return obj.current.trim();
119
+ }
120
+ }
121
+ const stringFields = ["urlSlug", "url", "URL", "path", "permalink", "pathname"];
122
+ const slugShape = /^[a-z0-9._~-]+(?:\/[a-z0-9._~-]+)*\/?$/i;
123
+ for (const f of stringFields) {
124
+ const v = val[f];
125
+ if (typeof v === "string") {
126
+ const trimmed = v.trim();
127
+ if (trimmed && !/^https?:\/\//i.test(trimmed) && slugShape.test(trimmed)) {
128
+ return trimmed;
129
+ }
130
+ }
131
+ }
132
+ return void 0;
133
+ }
134
+ function detectAuthor(val) {
135
+ if (!val) return { authorIsReference: false };
136
+ const candidateFields = [
137
+ "author",
138
+ "authors",
139
+ "byline",
140
+ "articleAuthor",
141
+ "primaryAuthor",
142
+ "writer",
143
+ "writers",
144
+ "contributor",
145
+ "contributors",
146
+ "authorMapping",
147
+ // MJH schema - array of author references
148
+ "Author",
149
+ "Authors"
150
+ // PascalCase variants
151
+ ];
152
+ for (const f of candidateFields) {
153
+ const raw = val[f];
154
+ if (!raw) continue;
155
+ const first = Array.isArray(raw) ? raw[0] : raw;
156
+ if (!first) continue;
157
+ if (typeof first === "string") {
158
+ const trimmed = first.trim();
159
+ if (trimmed) return { authorName: trimmed, authorIsReference: false };
160
+ continue;
161
+ }
162
+ if (typeof first === "object" && first !== null) {
163
+ const o = first;
164
+ const name = o.name || o.fullName || o.displayName;
165
+ const creds = o.credentials || o.title || o.suffix;
166
+ const slug = o.slug?.current;
167
+ const bio = o.bioUrl || (slug ? `/author/${slug}` : void 0);
168
+ if (name) {
169
+ return { authorName: name, authorCredentials: creds, authorBioUrl: bio, authorIsReference: false };
170
+ }
171
+ if (typeof o._ref === "string" || o._type === "reference") {
172
+ return { authorIsReference: true };
173
+ }
174
+ }
175
+ }
176
+ return { authorIsReference: false };
177
+ }
109
178
  function extractImageMeta(value) {
110
179
  const names = [];
111
180
  const titles = [];
@@ -122,8 +191,56 @@ function extractImageMeta(value) {
122
191
  if (typeof img.title === "string" && img.title) titles.push(img.title);
123
192
  else if (asset && typeof asset.title === "string" && asset.title) titles.push(asset.title);
124
193
  }
194
+ const body = value.body;
195
+ if (Array.isArray(body)) {
196
+ for (const blk of body) {
197
+ if (!blk || typeof blk !== "object") continue;
198
+ const b = blk;
199
+ if (b._type !== "figure" && b._type !== "image") continue;
200
+ const asset = b.asset && typeof b.asset === "object" ? b.asset : void 0;
201
+ if (!asset && b._type !== "image") continue;
202
+ count++;
203
+ if (typeof b.alt === "string" && b.alt) names.push(b.alt);
204
+ if (asset && typeof asset.originalFilename === "string" && asset.originalFilename) names.push(asset.originalFilename);
205
+ if (typeof b.title === "string" && b.title) titles.push(b.title);
206
+ else if (asset && typeof asset.title === "string" && asset.title) titles.push(asset.title);
207
+ }
208
+ }
125
209
  return { names, titles, count };
126
210
  }
211
+ function buildDocumentFields(value) {
212
+ const val = value;
213
+ const title = val?.title;
214
+ const body = val?.body;
215
+ const { authorName, authorCredentials, authorBioUrl, authorIsReference } = detectAuthor(val);
216
+ const imageMeta = val ? extractImageMeta(val) : { names: [], titles: [], count: 0 };
217
+ return {
218
+ title: title || void 0,
219
+ // MJH uses `summary`; standard Sanity SEO plugins use `metaDescription`
220
+ metaDescription: val?.metaDescription || val?.summary || val?.description || val?.seoDescription,
221
+ slug: detectSlug(val),
222
+ imageNames: imageMeta.names,
223
+ imageTitles: imageMeta.titles,
224
+ imageCount: imageMeta.count,
225
+ headings: extractHeadings(body),
226
+ headingsDetailed: extractHeadingsDetailed(body),
227
+ bodyLinks: extractBodyLinks(body),
228
+ contentCategory: val?.contentCategory || val?.category,
229
+ contentPlacement: Array.isArray(val?.contentPlacement) ? val.contentPlacement : void 0,
230
+ authorName,
231
+ authorCredentials,
232
+ authorBioUrl,
233
+ authorIsReference,
234
+ // `published` is MJH's date field; `publishedAt`/`publishDate` cover other schemas
235
+ publishedAt: val?.published || val?.publishedAt || val?.publishDate || val?._createdAt,
236
+ // `updatedOn` is MJH's "Updated On" field. `updatedAt` is the standard Sanity convention.
237
+ // `_updatedAt` is the Sanity-managed timestamp as a final fallback.
238
+ updatedAt: val?.updatedOn || val?.updatedAt || val?._updatedAt,
239
+ lastReviewedAt: val?.lastReviewedAt || val?.lastReviewed || val?.medicallyReviewedAt
240
+ };
241
+ }
242
+
243
+ // src/hooks/useDocumentContent.ts
127
244
  function useDocumentContent() {
128
245
  const { value, ready } = (0, import_structure.useDocumentPane)();
129
246
  const documentId = value?._id || void 0;
@@ -143,43 +260,7 @@ function useDocumentContent() {
143
260
  (0, import_react.useEffect)(() => {
144
261
  const bodyText = extractText(body);
145
262
  const fullText = [title, bodyText].filter(Boolean).join("\n\n");
146
- const val = value;
147
- let authorName;
148
- let authorCredentials;
149
- let authorBioUrl;
150
- let authorIsReference = false;
151
- const author = val?.author || Array.isArray(val?.authors) && val.authors[0] || val?.byline;
152
- if (typeof author === "string") {
153
- authorName = author;
154
- } else if (author && typeof author === "object") {
155
- authorName = author.name || author.fullName || author.displayName;
156
- authorCredentials = author.credentials || author.title || author.suffix;
157
- authorBioUrl = author.bioUrl || (author.slug?.current ? `/author/${author.slug.current}` : void 0);
158
- if (!authorName && typeof author._ref === "string") {
159
- authorIsReference = true;
160
- }
161
- }
162
- const imageMeta = val ? extractImageMeta(val) : { names: [], titles: [], count: 0 };
163
- const fields = {
164
- title: title || void 0,
165
- metaDescription: val?.metaDescription || val?.summary || val?.description || val?.seoDescription,
166
- slug: val?.slug?.current || void 0,
167
- imageNames: imageMeta.names,
168
- imageTitles: imageMeta.titles,
169
- imageCount: imageMeta.count,
170
- headings: extractHeadings(body),
171
- headingsDetailed: extractHeadingsDetailed(body),
172
- bodyLinks: extractBodyLinks(body),
173
- contentCategory: val?.contentCategory || val?.category,
174
- contentPlacement: Array.isArray(val?.contentPlacement) ? val.contentPlacement : void 0,
175
- authorName,
176
- authorCredentials,
177
- authorBioUrl,
178
- authorIsReference,
179
- publishedAt: val?.publishedAt || val?.publishDate || val?._createdAt,
180
- updatedAt: val?.updatedAt || val?._updatedAt,
181
- lastReviewedAt: val?.lastReviewedAt || val?.lastReviewed || val?.medicallyReviewedAt
182
- };
263
+ const fields = buildDocumentFields(value);
183
264
  setDocumentFields(fields);
184
265
  if (timerRef.current) clearTimeout(timerRef.current);
185
266
  timerRef.current = setTimeout(() => {
@@ -389,6 +470,7 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
389
470
  cacheInitializedRef.current = true;
390
471
  return;
391
472
  }
473
+ docVersionRef.current += 1;
392
474
  const fresh = loadCached();
393
475
  cached.current = fresh;
394
476
  setAnalysisRaw(fresh.analysis);
@@ -425,6 +507,7 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
425
507
  }
426
508
  }, [text, deepAnalysis, aeoTextSnapshot]);
427
509
  const lastAnalysisRef = (0, import_react2.useRef)(null);
510
+ const docVersionRef = (0, import_react2.useRef)(0);
428
511
  (0, import_react2.useEffect)(() => {
429
512
  if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) {
430
513
  setAnalysis(null);
@@ -464,6 +547,7 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
464
547
  }, [text, apiUrl, publication, effectiveSeeds?.join(","), focusPrimary]);
465
548
  const doVolumeLookup = (0, import_react2.useCallback)((analysisResult, terms) => {
466
549
  setIsVolumesLoading(true);
550
+ const myVersion = docVersionRef.current;
467
551
  const lookupTerms = terms || (() => {
468
552
  const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
469
553
  return [
@@ -480,6 +564,7 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
480
564
  return;
481
565
  }
482
566
  lookupKeywords(apiUrl, lookupTerms).then(({ results }) => {
567
+ if (docVersionRef.current !== myVersion) return;
483
568
  results.forEach((r) => volumeMapRef.current.set(r.keyword.toLowerCase(), r));
484
569
  const current = lastAnalysisRef.current || analysisResult;
485
570
  const merged = mergeVolumes(current, volumeMapRef.current);
@@ -492,6 +577,7 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
492
577
  }
493
578
  setIsVolumesLoading(false);
494
579
  }).catch(() => {
580
+ if (docVersionRef.current !== myVersion) return;
495
581
  setIsVolumesLoading(false);
496
582
  });
497
583
  }, [apiUrl, cacheKey]);
@@ -506,10 +592,13 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
506
592
  setError(null);
507
593
  setAeoContentChanged(false);
508
594
  setAeoTextSnapshot(text);
595
+ const myVersion = docVersionRef.current;
509
596
  fetchAnalysis(apiUrl, text, "deep", publication, effectiveSeeds, documentFields, focusPrimary).then((result) => {
597
+ if (docVersionRef.current !== myVersion) return;
510
598
  setDeepAnalysis(result);
511
599
  setIsDeepLoading(false);
512
600
  }).catch((err) => {
601
+ if (docVersionRef.current !== myVersion) return;
513
602
  setError(err.message);
514
603
  setIsDeepLoading(false);
515
604
  });
@@ -614,6 +703,7 @@ function useSEOChat(apiUrl, documentText, publication, keywordPanelData, documen
614
703
  }, [apiUrl, documentId, publication]);
615
704
  const sendMessage = (0, import_react3.useCallback)(
616
705
  async (text) => {
706
+ const myVersion = opVersionRef.current;
617
707
  const userMessage = { role: "user", content: text };
618
708
  const updatedMessages = [...messages, userMessage];
619
709
  setMessages(updatedMessages);
@@ -633,10 +723,25 @@ function useSEOChat(apiUrl, documentText, publication, keywordPanelData, documen
633
723
  const reader = stream.getReader();
634
724
  const decoder = new TextDecoder();
635
725
  let assistantContent = "";
726
+ if (opVersionRef.current !== myVersion) {
727
+ try {
728
+ await reader.cancel();
729
+ } catch {
730
+ }
731
+ setIsStreaming(false);
732
+ return;
733
+ }
636
734
  setMessages((prev) => [...prev, { role: "assistant", content: "" }]);
637
735
  while (true) {
638
736
  const { done, value } = await reader.read();
639
737
  if (done) break;
738
+ if (opVersionRef.current !== myVersion) {
739
+ try {
740
+ await reader.cancel();
741
+ } catch {
742
+ }
743
+ break;
744
+ }
640
745
  const chunk = decoder.decode(value, { stream: true });
641
746
  const lines = chunk.split("\n");
642
747
  for (const line of lines) {
@@ -661,19 +766,25 @@ function useSEOChat(apiUrl, documentText, publication, keywordPanelData, documen
661
766
  }
662
767
  }
663
768
  }
664
- const finalMessages = [
665
- ...updatedMessages,
666
- { role: "assistant", content: assistantContent }
667
- ];
668
- scheduleSave(finalMessages);
769
+ if (opVersionRef.current === myVersion) {
770
+ const finalMessages = [
771
+ ...updatedMessages,
772
+ { role: "assistant", content: assistantContent }
773
+ ];
774
+ scheduleSave(finalMessages);
775
+ }
669
776
  } catch (err) {
777
+ if (opVersionRef.current !== myVersion) {
778
+ setIsStreaming(false);
779
+ return;
780
+ }
670
781
  const errorMsg = err instanceof Error ? err.message : "Chat failed";
671
782
  setMessages((prev) => [
672
783
  ...prev,
673
784
  { role: "assistant", content: `Error: ${errorMsg}` }
674
785
  ]);
675
786
  }
676
- setIsStreaming(false);
787
+ if (opVersionRef.current === myVersion) setIsStreaming(false);
677
788
  },
678
789
  [messages, apiUrl, documentText, publication, keywordPanelData, scheduleSave]
679
790
  );
@@ -1531,12 +1642,9 @@ function PrimaryKeywordSelector({
1531
1642
  fontWeight: isSelected ? 600 : 400,
1532
1643
  color: isSelected ? "#166534" : "#374151"
1533
1644
  }, children: candidate.term }),
1534
- candidate.volume != null && /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("span", { style: { fontSize: 11, fontWeight: 600, color: "#1f2937" }, children: [
1535
- abbrevVol(candidate.volume),
1536
- "/mo"
1537
- ] }),
1645
+ candidate.volume != null && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: { fontSize: 11, fontWeight: 600, color: "#1f2937" }, children: candidate.volume === 0 ? "N/A" : `${abbrevVol(candidate.volume)}/mo` }),
1538
1646
  /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("span", { style: { fontSize: 10, color: "#1f2937" }, children: [
1539
- Math.round(candidate.confidence * 100),
1647
+ Math.round((candidate.confidence ?? 0) * 100),
1540
1648
  "% confidence"
1541
1649
  ] })
1542
1650
  ] }),
@@ -1953,10 +2061,7 @@ function SuggestedKeywordsCard({
1953
2061
  } }),
1954
2062
  /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: { fontSize: 12, fontWeight: kw.inContent ? 500 : 600, flexGrow: 1, color: "#1f2937" }, children: kw.term }),
1955
2063
  enrichingTerms.has(kw.term) && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(LoadingBars, { size: "xs", color: "#6b7280" }),
1956
- !enrichingTerms.has(kw.term) && kw.volume != null && /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("span", { style: { fontSize: 10.5, fontWeight: 600, color: "#1f2937", flexShrink: 0 }, title: "Monthly searches", children: [
1957
- abbrevVol(kw.volume),
1958
- "/mo"
1959
- ] }),
2064
+ !enrichingTerms.has(kw.term) && kw.volume != null && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: { fontSize: 10.5, fontWeight: 600, color: "#1f2937", flexShrink: 0 }, title: "Monthly searches", children: kw.volume === 0 ? "N/A" : `${abbrevVol(kw.volume)}/mo` }),
1960
2065
  kw.placement && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(PlacementIndicators, { placement: kw.placement }),
1961
2066
  !kw.inContent && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(LightbulbButton, { onClick: () => fetchHelp(kw.term), isLoading: loadingTerm === kw.term })
1962
2067
  ] }),
@@ -2778,7 +2883,7 @@ var DEFAULT_GENERATE_ALL_MESSAGES = [
2778
2883
  ];
2779
2884
 
2780
2885
  // src/lib/scoring.ts
2781
- function calculateContentScoreDetailed(content, analysis) {
2886
+ function calculateContentScoreDetailed(content, analysis, documentFields) {
2782
2887
  if (!content || !analysis) {
2783
2888
  return { total: 0, components: [] };
2784
2889
  }
@@ -2791,13 +2896,14 @@ function calculateContentScoreDetailed(content, analysis) {
2791
2896
  const primaryRegex = new RegExp(escaped, "gi");
2792
2897
  const primaryMatches = content.match(primaryRegex);
2793
2898
  const primaryCount = primaryMatches?.length || 0;
2899
+ const primaryWordCount = Math.max(1, primaryTerm.split(/\s+/).filter(Boolean).length);
2794
2900
  let pts = 0;
2795
2901
  let detail;
2796
2902
  if (primaryCount === 0) {
2797
2903
  detail = `Primary keyword "${primaryTerm}" not found in content`;
2798
2904
  } else {
2799
2905
  pts += 12;
2800
- const density = words > 0 ? primaryCount / words * 100 : 0;
2906
+ const density = words > 0 ? primaryCount * primaryWordCount / words * 100 : 0;
2801
2907
  if (density >= 0.5 && density <= 2.5) {
2802
2908
  pts += 13;
2803
2909
  detail = `Primary keyword present, density ${density.toFixed(2)}% (ideal range)`;
@@ -2842,10 +2948,18 @@ function calculateContentScoreDetailed(content, analysis) {
2842
2948
  wcDetail = `${words} words - start writing`;
2843
2949
  }
2844
2950
  components.push({ label: "Word count", points: wcPts, max: 15, detail: wcDetail });
2845
- const hasH1orTitle = /^#\s|<h1/im.test(content);
2846
- const hasSubheadings = /^##\s|^###\s|<h2|<h3/im.test(content);
2951
+ let hasH1orTitle;
2952
+ let hasSubheadings;
2953
+ if (documentFields) {
2954
+ hasH1orTitle = !!(documentFields.title && documentFields.title.trim());
2955
+ const det = documentFields.headingsDetailed;
2956
+ hasSubheadings = det ? det.some((h) => h.level >= 2 && h.level <= 4) : (documentFields.headings?.length || 0) > 0;
2957
+ } else {
2958
+ hasH1orTitle = /^#\s|<h1/im.test(content);
2959
+ hasSubheadings = /^##\s|^###\s|<h2|<h3/im.test(content);
2960
+ }
2847
2961
  const structurePts = (hasH1orTitle ? 5 : 0) + (hasSubheadings ? 5 : 0);
2848
- const structureDetail = !hasH1orTitle && !hasSubheadings ? "No headings detected - add H2/H3 structure" : !hasSubheadings ? "Has title but no subheadings" : !hasH1orTitle ? "Has subheadings but no clear H1" : "Title and subheadings present";
2962
+ const structureDetail = !hasH1orTitle && !hasSubheadings ? "No title or subheadings detected" : !hasSubheadings ? "Has a title but no H2/H3 subheadings - add section headings" : !hasH1orTitle ? "Has subheadings but no title" : "Title and subheadings present";
2849
2963
  components.push({ label: "Heading structure", points: structurePts, max: 10, detail: structureDetail });
2850
2964
  const missingCount = (analysis.missingKeywords || []).length;
2851
2965
  let mPts = 0;
@@ -2863,13 +2977,17 @@ function calculateContentScoreDetailed(content, analysis) {
2863
2977
  mDetail = `${missingCount} suggested keywords missing - significant gaps`;
2864
2978
  }
2865
2979
  components.push({ label: "Missing keyword gap", points: mPts, max: 15, detail: mDetail });
2980
+ let qCount;
2981
+ if (documentFields) {
2982
+ qCount = (documentFields.headings || []).filter((h) => h.trim().endsWith("?")).length;
2983
+ } else {
2984
+ const questionHeadings = content.match(/^#{1,6}\s+.*\?$/gm) || content.match(/<h[1-6][^>]*>.*\?<\/h[1-6]>/gi);
2985
+ qCount = questionHeadings?.length || 0;
2986
+ }
2866
2987
  let aeoPts = 0;
2867
- const questionHeadings = content.match(/^#{1,6}\s+.*\?$/gm) || content.match(/<h[1-6][^>]*>.*\?<\/h[1-6]>/gi);
2868
- const qCount = questionHeadings?.length || 0;
2869
- if (qCount >= 3) aeoPts += 6;
2870
- else if (qCount === 2) aeoPts += 4;
2871
- else if (qCount === 1) aeoPts += 2;
2872
- if (qCount > 0) aeoPts += 4;
2988
+ if (qCount >= 3) aeoPts = 10;
2989
+ else if (qCount === 2) aeoPts = 7;
2990
+ else if (qCount === 1) aeoPts = 4;
2873
2991
  const aeoDetail = qCount === 0 ? "No question-style headings - AI answer engines favor them" : `${qCount} question heading${qCount === 1 ? "" : "s"}`;
2874
2992
  components.push({ label: "AEO signals", points: aeoPts, max: 10, detail: aeoDetail });
2875
2993
  const total = components.reduce((sum, c) => sum + c.points, 0);
@@ -2884,6 +3002,15 @@ function tokensContain(haystack, needle) {
2884
3002
  const lower = haystack.toLowerCase();
2885
3003
  return tokens.every((t) => lower.includes(t));
2886
3004
  }
3005
+ function isShortFormContent(documentFields, title) {
3006
+ const shortFormCats = /* @__PURE__ */ new Set(["news", "brief", "preview", "recap", "update", "announcement", "roundup", "digest", "interview"]);
3007
+ const catTokens = (documentFields?.contentCategory || "").toLowerCase().split(/[^a-z]+/).filter(Boolean);
3008
+ if (catTokens.some((tok) => shortFormCats.has(tok))) return true;
3009
+ const t = (title || "").toLowerCase();
3010
+ if (/\b(preview|recap|roundup|digest)\b/.test(t)) return true;
3011
+ if (/:\s*\d+\s+(trials|things|takeaways|highlights|tips|questions|charts)/.test(t)) return true;
3012
+ return false;
3013
+ }
2887
3014
  function buildSummaryItems(input) {
2888
3015
  const items = [];
2889
3016
  const { analysis, deepAnalysis, documentFields, linkingSuggestions, linkCheckResults, text } = input;
@@ -3025,20 +3152,20 @@ function buildSummaryItems(input) {
3025
3152
  howToFix: "Add more body text. A link or image on its own doesn't count - the article needs real written substance.",
3026
3153
  jumpTo: { tab: "technical", anchorId: "anchor-word-count" }
3027
3154
  });
3028
- } else if (wordCount2 < 1500) {
3155
+ } else if (wordCount2 < 1500 && !isShortFormContent(documentFields, title)) {
3029
3156
  items.push({
3030
3157
  id: "content-short-for-clinical",
3031
3158
  category: "content",
3032
- severity: "warning",
3159
+ severity: "opportunity",
3033
3160
  label: "Article could be longer",
3034
- description: `${wordCount2} words. 1,500+ is the standard for competitive clinical articles.`,
3035
- howToFix: "Expand sections with citations, comparative data, or guideline references.",
3161
+ description: `${wordCount2} words. For evergreen clinical topics 1,500+ tends to rank better - news, previews, and briefs are fine shorter.`,
3162
+ howToFix: "If this is an in-depth clinical piece, expand with citations, comparative data, or guideline references. For news or previews, this length is appropriate.",
3036
3163
  jumpTo: { tab: "technical", anchorId: "anchor-word-count" }
3037
3164
  });
3038
3165
  }
3039
3166
  const headings = documentFields?.headings || [];
3040
3167
  const headingsDetailed = documentFields?.headingsDetailed;
3041
- const h2Count = headingsDetailed ? headingsDetailed.filter((h) => h.level === 2).length : headings.length;
3168
+ const h2Count = headingsDetailed ? headingsDetailed.filter((h) => h.level === 2 || h.level === 3).length : headings.length;
3042
3169
  if (headings.length === 0 && wordCount2 > 200 && wordCount2 < 1e3) {
3043
3170
  items.push({
3044
3171
  id: "headings-missing",
@@ -3203,9 +3330,21 @@ function buildSummaryItems(input) {
3203
3330
  jumpTo: { tab: "keywords" }
3204
3331
  });
3205
3332
  }
3333
+ const primaryVolume = analysis?.primaryKeyword?.volume;
3334
+ if (deepAnalysis && (primaryVolume === 0 || primaryVolume === null)) {
3335
+ items.push({
3336
+ id: "keywords-primary-zero-volume",
3337
+ category: "keywords",
3338
+ severity: "warning",
3339
+ label: "Primary keyword has no search volume",
3340
+ description: `"${primaryKeyword}" shows no measurable monthly searches, so even ranking #1 brings little traffic.`,
3341
+ howToFix: "Pick a primary people actually search for - check your supporting keywords for higher-volume options, or set a new primary on the Keywords tab.",
3342
+ jumpTo: { tab: "keywords" }
3343
+ });
3344
+ }
3206
3345
  }
3207
- const questionHeadings = deepAnalysis?.aeo?.questionHeadings || [];
3208
- if (deepAnalysis && questionHeadings.length === 0 && wordCount2 > 300) {
3346
+ const actualQuestionHeadings = (documentFields?.headings || []).filter((h) => h.trim().endsWith("?"));
3347
+ if (deepAnalysis && actualQuestionHeadings.length === 0 && wordCount2 > 300) {
3209
3348
  items.push({
3210
3349
  id: "aeo-no-question-headings",
3211
3350
  category: "aeo",
@@ -3253,6 +3392,18 @@ function buildSummaryItems(input) {
3253
3392
  jumpTo: { tab: "technical", anchorId: "anchor-link-check" }
3254
3393
  });
3255
3394
  }
3395
+ const unverified = linkCheckResults.filter((r) => r.category === "unverified");
3396
+ if (unverified.length > 0) {
3397
+ items.push({
3398
+ id: "unverified-links",
3399
+ category: "technical",
3400
+ severity: "warning",
3401
+ label: `${unverified.length} link${unverified.length === 1 ? "" : "s"} couldn't be auto-verified`,
3402
+ description: `${unverified.length} link${unverified.length === 1 ? " was" : "s were"} blocked by an anti-bot wall (401/403/429) - the URLs may work fine for readers, our server just couldn't confirm.`,
3403
+ howToFix: "Open each one manually in a new tab to confirm it loads, then ignore the warning if it does.",
3404
+ jumpTo: { tab: "technical", anchorId: "anchor-link-check" }
3405
+ });
3406
+ }
3256
3407
  }
3257
3408
  if (deepAnalysis) {
3258
3409
  const readability = deepAnalysis.readabilityNotes || [];
@@ -3489,8 +3640,8 @@ function SummaryTab({
3489
3640
  }) {
3490
3641
  const scoreDetail = (0, import_react13.useMemo)(() => {
3491
3642
  if (!analysis) return null;
3492
- return calculateContentScoreDetailed(text, analysis);
3493
- }, [text, analysis]);
3643
+ return calculateContentScoreDetailed(text, analysis, documentFields);
3644
+ }, [text, analysis, documentFields]);
3494
3645
  const score = scoreDetail?.total ?? null;
3495
3646
  const items = (0, import_react13.useMemo)(
3496
3647
  () => buildSummaryItems({
@@ -3605,9 +3756,12 @@ function wordCount(s) {
3605
3756
  }
3606
3757
  function analyzeHeadings(text, headings) {
3607
3758
  if (!text || headings.length === 0) return [];
3759
+ const isQuestion = (h) => /\?\s*$/.test(h.trim());
3760
+ const questionHeadings = headings.filter(isQuestion);
3761
+ if (questionHeadings.length === 0) return [];
3608
3762
  const headingSet = new Set(headings.map((h) => h.trim().toLowerCase()));
3609
3763
  const lower = text.toLowerCase();
3610
- return headings.map((heading) => {
3764
+ return questionHeadings.map((heading) => {
3611
3765
  const needle = heading.trim().toLowerCase();
3612
3766
  const idx = lower.indexOf(needle);
3613
3767
  if (idx === -1) {
@@ -3639,7 +3793,7 @@ function analyzeFactDensity(text) {
3639
3793
  const matches = text.match(new RegExp(FACT_PATTERN.source, "gi")) || [];
3640
3794
  const factCount = matches.length;
3641
3795
  const factsPer1000 = Math.round(factCount / total * 1e3);
3642
- const sentences = text.split(/(?<=[.!?])\s+/).filter((s) => s.trim().length > 0);
3796
+ const sentences = text.split(/[.!?]+\s+/).filter((s) => s.trim().length > 0);
3643
3797
  let drift = 0;
3644
3798
  let runWords = 0;
3645
3799
  let runHasFact = false;
@@ -3654,7 +3808,7 @@ function analyzeFactDensity(text) {
3654
3808
  }
3655
3809
  }
3656
3810
  let status;
3657
- if (factsPer1000 >= 8 && drift === 0) status = "strong";
3811
+ if (factsPer1000 >= 8) status = "strong";
3658
3812
  else if (factsPer1000 >= 4) status = "moderate";
3659
3813
  else status = "weak";
3660
3814
  return { totalWords: total, factCount, factsPerThousandWords: factsPer1000, driftPassages: drift, status };
@@ -3743,9 +3897,11 @@ function CopyButton({ text }) {
3743
3897
  function GEOCard({ geo, publication }) {
3744
3898
  const [showDetails, setShowDetails] = usePersistentState("seo-copilot-ui-geo-details", false);
3745
3899
  const fd = geo.factDensity;
3746
- const fdColor = fd.status === "strong" ? "#16a34a" : fd.status === "moderate" ? "#8B7310" : "#dc2626";
3747
- const fdLabel = fd.status === "strong" ? "Strong" : fd.status === "moderate" ? "Moderate" : "Weak";
3748
- const fdBg = fd.status === "strong" ? "rgba(22,163,74,0.1)" : fd.status === "moderate" ? "rgba(230,192,27,0.15)" : "rgba(220,38,38,0.08)";
3900
+ const isShort = fd.totalWords > 0 && fd.totalWords < 600;
3901
+ const effectiveStatus = fd.status === "weak" && isShort ? "moderate" : fd.status;
3902
+ const fdColor = effectiveStatus === "strong" ? "#16a34a" : effectiveStatus === "moderate" ? "#8B7310" : "#dc2626";
3903
+ const fdLabel = fd.status === "strong" ? "Strong" : fd.status === "moderate" ? "Moderate" : isShort ? "Light (short-form)" : "Weak";
3904
+ const fdBg = effectiveStatus === "strong" ? "rgba(22,163,74,0.1)" : effectiveStatus === "moderate" ? "rgba(230,192,27,0.15)" : "rgba(220,38,38,0.08)";
3749
3905
  const goodCount = geo.headingAudit.filter((h) => h.status === "good").length;
3750
3906
  const totalHeadings = geo.headingAudit.length;
3751
3907
  return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("div", { style: cardStyle3, children: [
@@ -3803,7 +3959,7 @@ function GEOCard({ geo, publication }) {
3803
3959
  fd.factsPerThousandWords,
3804
3960
  " per 1,000 words).",
3805
3961
  " ",
3806
- fd.status === "strong" ? "AI engines prefer this density." : fd.status === "moderate" ? "Aim for 8+ per 1,000 words with named sources (NEJM, JAMA, FDA, trial numbers, p-values)." : "Vague claims get skipped. Add specific numbers, trial citations, or dates."
3962
+ fd.status === "strong" ? "AI engines prefer this density." : fd.status === "moderate" ? "Aim for 8+ per 1,000 words with named sources (NEJM, JAMA, FDA, trial numbers, p-values)." : isShort ? "Short-form content naturally has fewer stats - fine for news and previews. Add a citation or two where you can." : "Vague claims get skipped. Add specific numbers, trial citations, or dates."
3807
3963
  ] })
3808
3964
  ] })
3809
3965
  ]
@@ -4812,11 +4968,9 @@ function daysSince(iso) {
4812
4968
  }
4813
4969
  function formatDateShort(iso) {
4814
4970
  if (!iso) return "";
4815
- try {
4816
- return new Date(iso).toLocaleDateString(void 0, { year: "numeric", month: "short", day: "numeric" });
4817
- } catch {
4818
- return "";
4819
- }
4971
+ const d = new Date(iso);
4972
+ if (isNaN(d.getTime())) return "";
4973
+ return d.toLocaleDateString(void 0, { year: "numeric", month: "short", day: "numeric" });
4820
4974
  }
4821
4975
  function MetaTab({ documentFields, primaryKeyword, isLoading }) {
4822
4976
  const audits = (0, import_react16.useMemo)(() => {
@@ -4835,7 +4989,7 @@ function MetaTab({ documentFields, primaryKeyword, isLoading }) {
4835
4989
  if (!author && authorIsRef) {
4836
4990
  items.push({ label: "Author Byline", value: "Set (reference)", status: "good", recommendation: "Author is linked as a reference, so we can't read credentials from this view. Open the linked author page to confirm name, credentials, and bio are set." });
4837
4991
  } else if (!author) {
4838
- items.push({ label: "Author Byline", value: "Missing", status: "error", recommendation: "Add a named author. Healthcare content needs visible authorship for Google to consider it trustworthy." });
4992
+ items.push({ label: "Author Byline", value: "Missing", status: "warning", recommendation: "Add a named author with credentials - healthcare (YMYL) content with visible authorship earns more trust from Google's E-E-A-T signals. Wire or news briefs published without a byline can disregard this." });
4839
4993
  } else if (!creds) {
4840
4994
  items.push({ label: "Author Byline", value: author, status: "warning", recommendation: "Author shown but credentials (MD, PharmD, RN, etc.) aren't visible. Add credential suffixes." });
4841
4995
  } else if (!bio) {
@@ -4852,6 +5006,8 @@ function MetaTab({ documentFields, primaryKeyword, isLoading }) {
4852
5006
  const freshness = Math.min(...[daysUpd, daysRev, daysPub].filter((d) => d !== null));
4853
5007
  if (!published) {
4854
5008
  items.push({ label: "Publish Date", value: "Missing", status: "error", recommendation: "Add a visible publish date. Required for healthcare content to be cited by Google and AI search." });
5009
+ } else if (daysPub === null) {
5010
+ items.push({ label: "Publish Date", value: "Unrecognized format", status: "warning", recommendation: "A publish date is set but couldn't be read as a valid date. Check the field value." });
4855
5011
  } else {
4856
5012
  items.push({ label: "Publish Date", value: formatDateShort(published), status: "good" });
4857
5013
  }
@@ -5040,9 +5196,11 @@ function imageFilenameAudit(filenames) {
5040
5196
  function imageAltTextAudit(altTexts) {
5041
5197
  if (altTexts.length === 0) return null;
5042
5198
  const issues = [];
5199
+ let audited = 0;
5043
5200
  for (const alt of altTexts) {
5044
5201
  const trimmed = alt.trim();
5045
5202
  if (!trimmed) continue;
5203
+ audited++;
5046
5204
  const len = trimmed.length;
5047
5205
  const wc = trimmed.split(/\s+/).filter(Boolean).length;
5048
5206
  if (len > 125) {
@@ -5051,10 +5209,11 @@ function imageAltTextAudit(altTexts) {
5051
5209
  issues.push({ alt: trimmed, reason: "just one word - use 2-5 descriptive keywords" });
5052
5210
  }
5053
5211
  }
5212
+ if (audited === 0) return null;
5054
5213
  if (issues.length === 0) {
5055
5214
  return {
5056
5215
  label: "Image Alt Text",
5057
- value: `${altTexts.length} alt text${altTexts.length === 1 ? "" : "s"} look well-formed`,
5216
+ value: `${audited} alt text${audited === 1 ? "" : "s"} look well-formed`,
5058
5217
  status: "good"
5059
5218
  };
5060
5219
  }
@@ -5064,7 +5223,7 @@ function imageAltTextAudit(altTexts) {
5064
5223
  }).join("; ");
5065
5224
  return {
5066
5225
  label: "Image Alt Text",
5067
- value: `${issues.length} of ${altTexts.length} alt text${altTexts.length === 1 ? "" : "s"} need attention`,
5226
+ value: `${issues.length} of ${audited} alt text${audited === 1 ? "" : "s"} need attention`,
5068
5227
  status: "warning",
5069
5228
  recommendation: `${examples}. Alt text should be 2-5 descriptive keywords that describe the image, ideally including the primary keyword, and stay under 125 characters.`
5070
5229
  };
@@ -5072,6 +5231,7 @@ function imageAltTextAudit(altTexts) {
5072
5231
  function imageTitleAudit(titles, imageCount) {
5073
5232
  if (imageCount <= 0) return null;
5074
5233
  const withTitle = titles.length;
5234
+ if (withTitle === 0) return null;
5075
5235
  const missing = imageCount - withTitle;
5076
5236
  if (missing > 0) {
5077
5237
  return {
@@ -5098,30 +5258,30 @@ function imageTitleAudit(titles, imageCount) {
5098
5258
  }
5099
5259
  function computeHeadingStructureAudits(headings, wordCount2) {
5100
5260
  const audits = [];
5101
- const h2Count = headings.filter((h) => h.level === 2).length;
5261
+ const sectionCount = headings.filter((h) => h.level === 2 || h.level === 3).length;
5102
5262
  let densityFired = false;
5103
- if (wordCount2 >= 1e3 && h2Count === 0) {
5263
+ if (wordCount2 >= 1e3 && sectionCount === 0) {
5104
5264
  audits.push({
5105
5265
  label: "Section Headings",
5106
- value: `No H2 headings in a ${wordCount2}-word article`,
5266
+ value: `No section headings in a ${wordCount2}-word article`,
5107
5267
  status: "error",
5108
- recommendation: "Articles this long need section headings. Add 2-3 H2 headings to break the body into scannable sections."
5268
+ recommendation: "Articles this long need section headings. Add 2-3 H2 (or H3) headings to break the body into scannable sections."
5109
5269
  });
5110
5270
  densityFired = true;
5111
- } else if (wordCount2 >= 2500 && h2Count < 5) {
5271
+ } else if (wordCount2 >= 2500 && sectionCount < 5) {
5112
5272
  audits.push({
5113
5273
  label: "Section Headings",
5114
- value: `${h2Count} H2 heading${h2Count === 1 ? "" : "s"} for a ${wordCount2}-word article`,
5274
+ value: `${sectionCount} section heading${sectionCount === 1 ? "" : "s"} for a ${wordCount2}-word article`,
5115
5275
  status: "warning",
5116
- recommendation: "Long articles read best with 1 H2 per 300-400 words. Break the content into more named sections so readers and search engines can navigate it."
5276
+ recommendation: "Long articles read best with 1 section heading per 300-400 words. Break the content into more named sections so readers and search engines can navigate it."
5117
5277
  });
5118
5278
  densityFired = true;
5119
- } else if (wordCount2 >= 1500 && h2Count < 3) {
5279
+ } else if (wordCount2 >= 1500 && sectionCount < 3) {
5120
5280
  audits.push({
5121
5281
  label: "Section Headings",
5122
- value: `${h2Count} H2 heading${h2Count === 1 ? "" : "s"} for a ${wordCount2}-word article`,
5282
+ value: `${sectionCount} section heading${sectionCount === 1 ? "" : "s"} for a ${wordCount2}-word article`,
5123
5283
  status: "warning",
5124
- recommendation: "Articles above 1,500 words usually need at least 3 H2 sections. Add named section breaks so the outline is scannable."
5284
+ recommendation: "Articles above 1,500 words usually need at least 3 named sections. Add section breaks so the outline is scannable."
5125
5285
  });
5126
5286
  densityFired = true;
5127
5287
  }
@@ -5194,8 +5354,9 @@ function LinkCheckCard({
5194
5354
  const redirects = results.filter((r) => r.category === "redirect").length;
5195
5355
  const broken = results.filter((r) => r.category === "broken").length;
5196
5356
  const errored = results.filter((r) => r.category === "error").length;
5357
+ const unverified = results.filter((r) => r.category === "unverified").length;
5197
5358
  const issues = results.filter((r) => r.category !== "ok");
5198
- return { total, valid, redirects, broken, errored, issues };
5359
+ return { total, valid, redirects, broken, errored, unverified, issues };
5199
5360
  }, [results]);
5200
5361
  return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)("div", { id: "anchor-link-check", style: cardStyle6, children: [
5201
5362
  /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, marginBottom: 6 }, children: [
@@ -5291,12 +5452,34 @@ function LinkCheckCard({
5291
5452
  }
5292
5453
  ),
5293
5454
  hasRun && !isLoading && !error && /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_jsx_runtime14.Fragment, { children: [
5294
- /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)("div", { style: { display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 6 }, children: [
5455
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)("div", { style: { display: "grid", gridTemplateColumns: counts.unverified > 0 ? "repeat(5, 1fr)" : "repeat(4, 1fr)", gap: 6 }, children: [
5295
5456
  /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(StatTile, { label: "Checked", value: counts.total, color: "#475569" }),
5296
5457
  /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(StatTile, { label: "Valid", value: counts.valid, color: "#16a34a" }),
5297
5458
  /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(StatTile, { label: "Redirects", value: counts.redirects, color: "#8B7310" }),
5298
- /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(StatTile, { label: "Broken", value: counts.broken + counts.errored, color: "#dc2626" })
5459
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(StatTile, { label: "Broken", value: counts.broken + counts.errored, color: "#dc2626" }),
5460
+ counts.unverified > 0 && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(StatTile, { label: "Blocked", value: counts.unverified, color: "#b45309" })
5299
5461
  ] }),
5462
+ counts.unverified > 0 && /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(
5463
+ "div",
5464
+ {
5465
+ style: {
5466
+ marginTop: 8,
5467
+ padding: "6px 10px",
5468
+ background: "rgba(245,158,11,0.08)",
5469
+ border: "1px solid rgba(245,158,11,0.25)",
5470
+ borderRadius: 6,
5471
+ fontSize: 10.5,
5472
+ color: "#92400e",
5473
+ lineHeight: 1.45
5474
+ },
5475
+ children: [
5476
+ counts.unverified,
5477
+ " link",
5478
+ counts.unverified === 1 ? "" : "s",
5479
+ " were blocked from our auto-check (likely anti-bot rules on the destination site). They may still work fine for human readers - click each to confirm."
5480
+ ]
5481
+ }
5482
+ ),
5300
5483
  counts.issues.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)("div", { style: { marginTop: 12, display: "flex", flexDirection: "column", gap: 6 }, children: [
5301
5484
  /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)("div", { style: { fontSize: 10, fontWeight: 700, color: "#4b5563", textTransform: "uppercase", letterSpacing: "0.06em" }, children: [
5302
5485
  counts.issues.length,
@@ -5355,9 +5538,12 @@ function LinkIssueRow({ result }) {
5355
5538
  ok: { bg: "rgba(22,163,74,0.06)", color: "#16a34a", label: "OK" },
5356
5539
  redirect: { bg: "rgba(230,192,27,0.12)", color: "#8B7310", label: result.status > 0 ? String(result.status) : "REDIR" },
5357
5540
  broken: { bg: "rgba(220,38,38,0.06)", color: "#dc2626", label: result.status > 0 ? String(result.status) : "404" },
5541
+ // Amber for unverified - the link may work fine, our server just couldn't confirm.
5542
+ unverified: { bg: "rgba(245,158,11,0.10)", color: "#b45309", label: result.status > 0 ? String(result.status) : "BLOCKED" },
5358
5543
  error: { bg: "rgba(220,38,38,0.06)", color: "#dc2626", label: "ERR" }
5359
5544
  };
5360
5545
  const c = map[result.category];
5546
+ const tooltip = result.category === "unverified" ? `${result.url} (couldn't auto-check; likely anti-bot blocking - open manually to verify)` : result.error ? `${result.url} (${result.error})` : result.url;
5361
5547
  return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(
5362
5548
  "a",
5363
5549
  {
@@ -5404,7 +5590,7 @@ function LinkIssueRow({ result }) {
5404
5590
  textOverflow: "ellipsis",
5405
5591
  whiteSpace: "nowrap"
5406
5592
  },
5407
- title: result.error ? `${result.url} (${result.error})` : result.url,
5593
+ title: tooltip,
5408
5594
  children: result.url
5409
5595
  }
5410
5596
  )
@@ -5456,12 +5642,7 @@ function TechnicalTab({
5456
5642
  status: "warning",
5457
5643
  recommendation: "Add at least one hero image with descriptive alt text. Articles with images perform better on both reader engagement and search."
5458
5644
  } : null;
5459
- const wordAudit = wordCount2 === 0 ? {
5460
- label: "Word Count",
5461
- value: "0 words",
5462
- status: "error",
5463
- recommendation: "Start writing. A link or image on its own doesn't count - the body needs real written substance."
5464
- } : wordCount2 < 450 ? {
5645
+ const wordAudit = wordCount2 === 0 ? null : wordCount2 < 450 ? {
5465
5646
  label: "Word Count",
5466
5647
  value: `${wordCount2} words`,
5467
5648
  status: "error",
@@ -5481,7 +5662,7 @@ function TechnicalTab({
5481
5662
  ] });
5482
5663
  }
5483
5664
  return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)("div", { style: { padding: 12, display: "flex", flexDirection: "column", gap: 10 }, children: [
5484
- /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
5665
+ wordAudit && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
5485
5666
  AuditCard2,
5486
5667
  {
5487
5668
  anchorId: "anchor-word-count",
@@ -6084,6 +6265,8 @@ function SEOCopilotInner({ config, onClose }) {
6084
6265
  const resizeStart = (0, import_react18.useRef)(null);
6085
6266
  const { text, isLoading: docLoading, documentFields, documentId } = useDocumentContent();
6086
6267
  const { apiUrl } = useConfig();
6268
+ const workspace = (0, import_sanity3.useWorkspace)();
6269
+ const effectivePublication = config.publication || workspace?.dataset;
6087
6270
  const seedCacheKey = documentId ? `seo-copilot-cache-${documentId}` : "seo-copilot-cache-v2";
6088
6271
  const loadSeedsFromCache = (0, import_react18.useCallback)(() => {
6089
6272
  try {
@@ -6118,7 +6301,7 @@ function SEOCopilotInner({ config, onClose }) {
6118
6301
  const [activeTab, setActiveTab] = (0, import_react18.useState)("keywords");
6119
6302
  const [chatOpen, setChatOpen] = usePersistentState("seo-copilot-ui-chat-open-v35", false);
6120
6303
  const [splitPercent, setSplitPercent] = usePersistentState("seo-copilot-ui-split", 70);
6121
- const keywordAnalysisState = useKeywordAnalysis(text, apiUrl, config.publication, seedKeywords, documentFields, selectedPrimary, documentId);
6304
+ const keywordAnalysisState = useKeywordAnalysis(text, apiUrl, effectivePublication, seedKeywords, documentFields, selectedPrimary, documentId);
6122
6305
  const effectivePrimary = selectedPrimary || keywordAnalysisState.analysis?.primaryKeyword?.term || "";
6123
6306
  const keywordPanelData = (0, import_react18.useMemo)(() => {
6124
6307
  const analysis = keywordAnalysisState.analysis;
@@ -6135,7 +6318,7 @@ function SEOCopilotInner({ config, onClose }) {
6135
6318
  } : void 0
6136
6319
  };
6137
6320
  }, [keywordAnalysisState.analysis, keywordAnalysisState.deepAnalysis]);
6138
- const chatHookState = useSEOChat(apiUrl, text, config.publication, keywordPanelData, documentId);
6321
+ const chatHookState = useSEOChat(apiUrl, text, effectivePublication, keywordPanelData, documentId);
6139
6322
  const contentSuggestionsKey = documentId ? `seo-copilot-content-suggestions-${documentId}` : "seo-copilot-content-suggestions-default";
6140
6323
  const [contentSuggestions, setContentSuggestions] = usePersistentState(contentSuggestionsKey, null);
6141
6324
  const [isCSLoading, setIsCSLoading] = (0, import_react18.useState)(false);
@@ -6156,7 +6339,7 @@ function SEOCopilotInner({ config, onClose }) {
6156
6339
  setIsCSLoading(true);
6157
6340
  setCsError(null);
6158
6341
  try {
6159
- const data = await fetchContentSuggestions(apiUrl, text, effectivePrimary, config.publication);
6342
+ const data = await fetchContentSuggestions(apiUrl, text, effectivePrimary, effectivePublication);
6160
6343
  if (aeoOpVersionRef.current !== myVersion) return;
6161
6344
  if (data.keyTakeaways.length === 0 && data.infographicOpportunities.length === 0 && data.bulletListItems.length === 0) {
6162
6345
  setCsError("No suggestions returned. Try again with more content.");
@@ -6169,7 +6352,7 @@ function SEOCopilotInner({ config, onClose }) {
6169
6352
  }
6170
6353
  if (aeoOpVersionRef.current !== myVersion) return;
6171
6354
  setIsCSLoading(false);
6172
- }, [apiUrl, text, effectivePrimary, config.publication]);
6355
+ }, [apiUrl, text, effectivePrimary, effectivePublication]);
6173
6356
  const linkingKey = documentId ? `seo-copilot-linking-${documentId}` : "seo-copilot-linking-default";
6174
6357
  const [linkingSuggestions, setLinkingSuggestions] = usePersistentState(linkingKey, []);
6175
6358
  const [isLinkingLoading, setIsLinkingLoading] = (0, import_react18.useState)(false);
@@ -6204,7 +6387,7 @@ function SEOCopilotInner({ config, onClose }) {
6204
6387
  effectivePrimary,
6205
6388
  supportingKeywordsForLinking,
6206
6389
  documentId,
6207
- config.publication
6390
+ effectivePublication
6208
6391
  );
6209
6392
  if (linkingVersionRef.current !== myVersion) return;
6210
6393
  setLinkingSuggestions(suggestions);
@@ -6215,7 +6398,7 @@ function SEOCopilotInner({ config, onClose }) {
6215
6398
  }
6216
6399
  if (linkingVersionRef.current !== myVersion) return;
6217
6400
  setIsLinkingLoading(false);
6218
- }, [apiUrl, text, effectivePrimary, supportingKeywordsForLinking, documentId, config.publication]);
6401
+ }, [apiUrl, text, effectivePrimary, supportingKeywordsForLinking, documentId, effectivePublication]);
6219
6402
  const isLinkingStale = (0, import_react18.useMemo)(() => {
6220
6403
  if (!linkingFetchedText || linkingSuggestions.length === 0) return false;
6221
6404
  if (Math.abs(text.length - linkingFetchedText.length) > 150) return true;
@@ -6329,7 +6512,7 @@ function SEOCopilotInner({ config, onClose }) {
6329
6512
  const panelContent = /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
6330
6513
  PanelContent,
6331
6514
  {
6332
- initialPublication: config.publication,
6515
+ initialPublication: effectivePublication,
6333
6516
  isFloating,
6334
6517
  isFullscreen,
6335
6518
  onToggleFloat: () => {
@@ -6554,7 +6737,7 @@ function seoCopilotInspector(config) {
6554
6737
  }
6555
6738
 
6556
6739
  // src/index.ts
6557
- var seoCopilot = (0, import_sanity3.definePlugin)((config) => ({
6740
+ var seoCopilot = (0, import_sanity4.definePlugin)((config) => ({
6558
6741
  name: "seo-copilot",
6559
6742
  document: {
6560
6743
  inspectors: (prev) => {