sanity-plugin-seo-copilot 0.1.0 → 0.1.2

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 CHANGED
@@ -1,50 +1,50 @@
1
- # sanity-plugin-seo-copilot
2
-
3
- AI-powered SEO writing assistant for Sanity Studio v3.
4
-
5
- Adds an SEO Copilot inspector panel to every document in your Sanity Studio. Editors get real-time keyword analysis, search volume data, placement tracking, and an AI chat assistant - all without leaving the editor.
6
-
7
- ## Installation
8
-
9
- ```sh
10
- npm install sanity-plugin-seo-copilot
11
- ```
12
-
13
- ## Configuration
14
-
15
- Add the plugin to your `sanity.config.ts`:
16
-
17
- ```ts
18
- import { defineConfig } from 'sanity'
19
- import { seoCopilot } from 'sanity-plugin-seo-copilot'
20
-
21
- export default defineConfig({
22
- // ... your existing config
23
- plugins: [
24
- // ... your existing plugins
25
- seoCopilot({
26
- apiUrl: 'https://ecaruso.vercel.app',
27
- publication: 'Your Publication Name', // optional
28
- }),
29
- ],
30
- })
31
- ```
32
-
33
- ### Options
34
-
35
- | Option | Type | Required | Description |
36
- | ------------- | ------ | -------- | ------------------------------------------------ |
37
- | `apiUrl` | string | Yes | Backend API URL for SEO analysis |
38
- | `publication` | string | No | Publication name for tailored keyword suggestions |
39
-
40
- ## Usage
41
-
42
- Once installed, every document in your Studio gets an SEO Copilot icon in the toolbar. Click it to open the inspector panel with:
43
-
44
- - **Keywords tab** - Real-time keyword analysis with search volume data, placement indicators (body, title, description, image, URL), and AI-suggested keywords
45
- - **Chat tab** - AI assistant that understands your document content and can help with SEO strategy, title suggestions, meta descriptions, and more
46
-
47
- ## How it works
48
-
49
- The plugin reads document content from the Sanity editor and sends it to the backend API for analysis. The backend uses Claude AI for keyword analysis and SEMrush for search volume data. All processing happens server-side - the plugin itself is a lightweight UI.
50
-
1
+ # sanity-plugin-seo-copilot
2
+
3
+ AI-powered SEO writing assistant for Sanity Studio v3.
4
+
5
+ Adds an SEO Copilot inspector panel to every document in your Sanity Studio. Editors get real-time keyword analysis, search volume data, placement tracking, and an AI chat assistant - all without leaving the editor.
6
+
7
+ ## Installation
8
+
9
+ ```sh
10
+ npm install sanity-plugin-seo-copilot
11
+ ```
12
+
13
+ ## Configuration
14
+
15
+ Add the plugin to your `sanity.config.ts`:
16
+
17
+ ```ts
18
+ import { defineConfig } from 'sanity'
19
+ import { seoCopilot } from 'sanity-plugin-seo-copilot'
20
+
21
+ export default defineConfig({
22
+ // ... your existing config
23
+ plugins: [
24
+ // ... your existing plugins
25
+ seoCopilot({
26
+ apiUrl: 'https://ecaruso.vercel.app',
27
+ publication: 'Your Publication Name', // optional
28
+ }),
29
+ ],
30
+ })
31
+ ```
32
+
33
+ ### Options
34
+
35
+ | Option | Type | Required | Description |
36
+ | ------------- | ------ | -------- | ------------------------------------------------ |
37
+ | `apiUrl` | string | Yes | Backend API URL for SEO analysis |
38
+ | `publication` | string | No | Publication name for tailored keyword suggestions |
39
+
40
+ ## Usage
41
+
42
+ Once installed, every document in your Studio gets an SEO Copilot icon in the toolbar. Click it to open the inspector panel with:
43
+
44
+ - **Keywords tab** - Real-time keyword analysis with search volume data, placement indicators (body, title, description, image, URL), and AI-suggested keywords
45
+ - **Chat tab** - AI assistant that understands your document content and can help with SEO strategy, title suggestions, meta descriptions, and more
46
+
47
+ ## How it works
48
+
49
+ The plugin reads document content from the Sanity editor and sends it to the backend API for analysis. The backend uses Claude AI for keyword analysis and SEMrush for search volume data. All processing happens server-side - the plugin itself is a lightweight UI.
50
+
package/dist/index.js CHANGED
@@ -33,7 +33,7 @@ __export(index_exports, {
33
33
  seoCopilot: () => seoCopilot
34
34
  });
35
35
  module.exports = __toCommonJS(index_exports);
36
- var import_sanity = require("sanity");
36
+ var import_sanity3 = require("sanity");
37
37
 
38
38
  // src/inspector.ts
39
39
  var import_react11 = require("react");
@@ -210,6 +210,7 @@ async function saveChatHistory(apiUrl, userId, documentId, messages, publication
210
210
 
211
211
  // src/hooks/useKeywordAnalysis.ts
212
212
  function mergeVolumes(analysis, volumeMap) {
213
+ if (volumeMap.size === 0) return analysis;
213
214
  const updated = { ...analysis };
214
215
  if (updated.primaryKeywordCandidates && updated.primaryKeywordCandidates.length > 0) {
215
216
  updated.primaryKeywordCandidates = updated.primaryKeywordCandidates.map((candidate) => {
@@ -258,11 +259,13 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
258
259
  const [isDeepLoading, setIsDeepLoading] = (0, import_react2.useState)(false);
259
260
  const [aeoTextSnapshot, setAeoTextSnapshot] = (0, import_react2.useState)("");
260
261
  const [aeoContentChanged, setAeoContentChanged] = (0, import_react2.useState)(false);
262
+ const volumeMapRef = (0, import_react2.useRef)(/* @__PURE__ */ new Map());
261
263
  const setAnalysis = (0, import_react2.useCallback)((val) => {
262
- setAnalysisRaw(val);
264
+ const withVolumes = val ? mergeVolumes(val, volumeMapRef.current) : null;
265
+ setAnalysisRaw(withVolumes);
263
266
  try {
264
267
  const prev = loadCached();
265
- sessionStorage.setItem(cacheKey, JSON.stringify({ ...prev, analysis: val }));
268
+ sessionStorage.setItem(cacheKey, JSON.stringify({ ...prev, analysis: withVolumes }));
266
269
  } catch {
267
270
  }
268
271
  }, [cacheKey]);
@@ -280,21 +283,10 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
280
283
  setAeoContentChanged(true);
281
284
  }
282
285
  }, [text, deepAnalysis, aeoTextSnapshot]);
283
- const volumesLoadedRef = (0, import_react2.useRef)(false);
284
286
  const lastAnalysisRef = (0, import_react2.useRef)(null);
285
- const prevSeedsRef = (0, import_react2.useRef)(effectiveSeeds?.join(",") || "");
286
- const prevFocusRef = (0, import_react2.useRef)(focusPrimary || "");
287
- const currentSeedsKey = effectiveSeeds?.join(",") || "";
288
- const currentFocusKey = focusPrimary || "";
289
- if (currentSeedsKey !== prevSeedsRef.current || currentFocusKey !== prevFocusRef.current) {
290
- volumesLoadedRef.current = false;
291
- prevSeedsRef.current = currentSeedsKey;
292
- prevFocusRef.current = currentFocusKey;
293
- }
294
287
  (0, import_react2.useEffect)(() => {
295
288
  if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) {
296
289
  setAnalysis(null);
297
- volumesLoadedRef.current = false;
298
290
  return;
299
291
  }
300
292
  let cancelled = false;
@@ -306,9 +298,18 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
306
298
  lastAnalysisRef.current = analysisResult;
307
299
  setAnalysis(analysisResult);
308
300
  setIsLoading(false);
309
- if (!volumesLoadedRef.current) {
310
- volumesLoadedRef.current = true;
311
- doVolumeLookup(analysisResult, cancelled);
301
+ const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
302
+ const allTerms = [
303
+ .../* @__PURE__ */ new Set([
304
+ ...candidateTerms,
305
+ analysisResult.primaryKeyword.term,
306
+ ...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
307
+ ...analysisResult.missingKeywords.map((kw) => kw.term)
308
+ ])
309
+ ];
310
+ const uncachedTerms = allTerms.filter((t) => !volumeMapRef.current.has(t.toLowerCase()));
311
+ if (uncachedTerms.length > 0) {
312
+ doVolumeLookup(analysisResult, uncachedTerms);
312
313
  }
313
314
  }).catch((err) => {
314
315
  if (!cancelled) {
@@ -320,30 +321,39 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
320
321
  cancelled = true;
321
322
  };
322
323
  }, [text, apiUrl, publication, effectiveSeeds?.join(","), focusPrimary]);
323
- const doVolumeLookup = (0, import_react2.useCallback)((analysisResult, cancelled) => {
324
+ const doVolumeLookup = (0, import_react2.useCallback)((analysisResult, terms) => {
324
325
  setIsVolumesLoading(true);
325
- const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
326
- const allTerms = [
327
- .../* @__PURE__ */ new Set([
328
- ...candidateTerms,
329
- analysisResult.primaryKeyword.term,
330
- ...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
331
- ...analysisResult.missingKeywords.map((kw) => kw.term)
332
- ])
333
- ];
334
- lookupKeywords(apiUrl, allTerms).then(({ results }) => {
335
- if (cancelled) return;
336
- const volumeMap = new Map(
337
- results.map((r) => [r.keyword.toLowerCase(), r])
338
- );
339
- setAnalysis(mergeVolumes(analysisResult, volumeMap));
326
+ const lookupTerms = terms || (() => {
327
+ const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
328
+ return [
329
+ .../* @__PURE__ */ new Set([
330
+ ...candidateTerms,
331
+ analysisResult.primaryKeyword.term,
332
+ ...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
333
+ ...analysisResult.missingKeywords.map((kw) => kw.term)
334
+ ])
335
+ ];
336
+ })();
337
+ if (lookupTerms.length === 0) {
340
338
  setIsVolumesLoading(false);
341
- }).catch(() => {
342
- if (!cancelled) {
343
- setIsVolumesLoading(false);
339
+ return;
340
+ }
341
+ lookupKeywords(apiUrl, lookupTerms).then(({ results }) => {
342
+ results.forEach((r) => volumeMapRef.current.set(r.keyword.toLowerCase(), r));
343
+ const current = lastAnalysisRef.current || analysisResult;
344
+ const merged = mergeVolumes(current, volumeMapRef.current);
345
+ lastAnalysisRef.current = merged;
346
+ setAnalysisRaw(merged);
347
+ try {
348
+ const prev = loadCached();
349
+ sessionStorage.setItem(cacheKey, JSON.stringify({ ...prev, analysis: merged }));
350
+ } catch {
344
351
  }
352
+ setIsVolumesLoading(false);
353
+ }).catch(() => {
354
+ setIsVolumesLoading(false);
345
355
  });
346
- }, [apiUrl]);
356
+ }, [apiUrl, cacheKey]);
347
357
  const refreshVolumes = (0, import_react2.useCallback)(() => {
348
358
  const current = lastAnalysisRef.current || analysis;
349
359
  if (!current) return;
@@ -639,9 +649,11 @@ function SeedKeywordInput({ seeds, onSeedsChange }) {
639
649
 
640
650
  // src/components/FeedbackButton.tsx
641
651
  var import_react6 = require("react");
652
+ var import_sanity = require("sanity");
642
653
  var import_jsx_runtime4 = require("react/jsx-runtime");
643
654
  function FeedbackButton({ suggestionType, suggestionText, documentId, publication }) {
644
655
  const { apiUrl } = useConfig();
656
+ const sanityUser = (0, import_sanity.useCurrentUser)();
645
657
  const [vote, setVote] = (0, import_react6.useState)(null);
646
658
  const [showReasonPopup, setShowReasonPopup] = (0, import_react6.useState)(false);
647
659
  const [reason, setReason] = (0, import_react6.useState)("");
@@ -674,7 +686,8 @@ function FeedbackButton({ suggestionType, suggestionText, documentId, publicatio
674
686
  suggestion_text: suggestionText,
675
687
  vote: "down",
676
688
  document_id: documentId,
677
- publication
689
+ publication,
690
+ user_id: sanityUser?.id
678
691
  });
679
692
  } catch {
680
693
  }
@@ -690,7 +703,8 @@ function FeedbackButton({ suggestionType, suggestionText, documentId, publicatio
690
703
  suggestion_text: suggestionText,
691
704
  vote: newVote,
692
705
  document_id: documentId,
693
- publication
706
+ publication,
707
+ user_id: sanityUser?.id
694
708
  });
695
709
  } catch {
696
710
  }
@@ -705,7 +719,8 @@ function FeedbackButton({ suggestionType, suggestionText, documentId, publicatio
705
719
  suggestion_text: suggestionText + " | REASON: " + trimmed,
706
720
  vote: "down",
707
721
  document_id: documentId,
708
- publication
722
+ publication,
723
+ user_id: sanityUser?.id
709
724
  });
710
725
  } catch {
711
726
  }
@@ -868,16 +883,18 @@ function placementCount(p) {
868
883
  if (!p) return 0;
869
884
  return [p.inBody, p.inTitle, p.inMetaDescription, p.inImages, p.inUrl].filter(Boolean).length;
870
885
  }
871
- function buildSuggestedKeywords(supporting, missing, documentText) {
886
+ function buildSuggestedKeywords(supporting, missing, documentText, documentFields) {
872
887
  const merged = [];
873
888
  const lowerText = documentText.toLowerCase();
874
889
  for (const kw of supporting) {
875
890
  const actuallyInContent = lowerText.includes(kw.term.toLowerCase());
876
- merged.push({ term: kw.term, volume: kw.volume ?? 0, inContent: actuallyInContent, placement: kw.placement });
891
+ const livePlacement = computePlacementClient(kw.term, documentText, documentFields);
892
+ merged.push({ term: kw.term, volume: kw.volume ?? 0, inContent: actuallyInContent, placement: livePlacement });
877
893
  }
878
894
  for (const kw of missing) {
879
895
  const actuallyInContent = lowerText.includes(kw.term.toLowerCase());
880
- merged.push({ term: kw.term, volume: kw.volume ?? 0, inContent: actuallyInContent, reason: kw.reason, placement: kw.placement });
896
+ const livePlacement = computePlacementClient(kw.term, documentText, documentFields);
897
+ merged.push({ term: kw.term, volume: kw.volume ?? 0, inContent: actuallyInContent, reason: kw.reason, placement: livePlacement });
881
898
  }
882
899
  merged.sort((a, b) => {
883
900
  const pDiff = placementCount(b.placement) - placementCount(a.placement);
@@ -1655,9 +1672,14 @@ function KeywordPanel({
1655
1672
  const suggestedKeywords = buildSuggestedKeywords(
1656
1673
  analysis.supportingKeywords || [],
1657
1674
  analysis.missingKeywords,
1658
- text
1675
+ text,
1676
+ documentFields
1659
1677
  );
1660
- const candidates = analysis.primaryKeywordCandidates && analysis.primaryKeywordCandidates.length > 0 ? analysis.primaryKeywordCandidates : [analysis.primaryKeyword];
1678
+ const rawCandidates = analysis.primaryKeywordCandidates && analysis.primaryKeywordCandidates.length > 0 ? analysis.primaryKeywordCandidates : [analysis.primaryKeyword];
1679
+ const candidates = rawCandidates.map((c) => ({
1680
+ ...c,
1681
+ placement: computePlacementClient(c.term, text, documentFields)
1682
+ }));
1661
1683
  const activeTerm = candidates.find((c) => c.term === selectedPrimaryTerm) ? selectedPrimaryTerm : candidates[0]?.term ?? "";
1662
1684
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: { padding: 12, display: "flex", flexDirection: "column", gap: 12 }, children: [
1663
1685
  onSeedsChange && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(SeedKeywordInput, { seeds: seedKeywords, onSeedsChange }),
@@ -1811,7 +1833,8 @@ var import_structure2 = require("sanity/structure");
1811
1833
 
1812
1834
  // src/hooks/useSEOChat.ts
1813
1835
  var import_react8 = require("react");
1814
- function getUserId() {
1836
+ var import_sanity2 = require("sanity");
1837
+ function getLocalUserId() {
1815
1838
  const key = "seo-copilot-user-id";
1816
1839
  try {
1817
1840
  let id = localStorage.getItem(key);
@@ -1846,7 +1869,13 @@ function useSEOChat(apiUrl, documentText, publication, keywordPanelData, documen
1846
1869
  }, [chatCacheKey]);
1847
1870
  const [isStreaming, setIsStreaming] = (0, import_react8.useState)(false);
1848
1871
  const [historyLoaded, setHistoryLoaded] = (0, import_react8.useState)(false);
1849
- const userId = (0, import_react8.useRef)(getUserId());
1872
+ const sanityUser = (0, import_sanity2.useCurrentUser)();
1873
+ const userId = (0, import_react8.useRef)(sanityUser?.id || getLocalUserId());
1874
+ (0, import_react8.useEffect)(() => {
1875
+ if (sanityUser?.id && userId.current !== sanityUser.id) {
1876
+ userId.current = sanityUser.id;
1877
+ }
1878
+ }, [sanityUser?.id]);
1850
1879
  const saveTimerRef = (0, import_react8.useRef)(null);
1851
1880
  (0, import_react8.useEffect)(() => {
1852
1881
  if (!documentId || historyLoaded) return;
@@ -2691,7 +2720,7 @@ function seoCopilotInspector(config) {
2691
2720
  }
2692
2721
 
2693
2722
  // src/index.ts
2694
- var seoCopilot = (0, import_sanity.definePlugin)((config) => ({
2723
+ var seoCopilot = (0, import_sanity3.definePlugin)((config) => ({
2695
2724
  name: "seo-copilot",
2696
2725
  document: {
2697
2726
  inspectors: (prev) => {