sanity-plugin-seo-copilot 0.2.5 → 0.2.7
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 +1123 -537
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1125 -539
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/components/KeywordPanel.tsx +164 -1
- package/src/components/OnboardingPopup.tsx +108 -0
- package/src/components/SEOCopilotPanel.tsx +105 -7
- package/src/components/styles.ts +8 -0
- package/src/components/tabs/LinkingTab.tsx +77 -4
- package/src/components/tabs/MetaTab.tsx +31 -109
- package/src/components/tabs/SummaryTab.tsx +19 -4
- package/src/components/tabs/TechnicalTab.tsx +132 -1
- package/src/hooks/useDocumentContent.ts +48 -47
- package/src/hooks/useKeywordAnalysis.ts +21 -4
- package/src/hooks/useSEOChat.ts +45 -9
- package/src/lib/api.ts +25 -7
- package/src/lib/documentExtract.ts +268 -257
- package/src/lib/scoring.ts +41 -14
- package/src/lib/summary.ts +116 -27
|
@@ -1,47 +1,48 @@
|
|
|
1
|
-
import { useState, useEffect, useRef } from "react";
|
|
2
|
-
import { useDocumentPane } from "sanity/structure";
|
|
3
|
-
import type { DocumentFields } from "../lib/types";
|
|
4
|
-
import { extractText, buildDocumentFields } from "../lib/documentExtract";
|
|
5
|
-
|
|
6
|
-
export function useDocumentContent(): { text: string; isLoading: boolean; documentFields: DocumentFields; documentId: string | undefined } {
|
|
7
|
-
const { value, ready } = useDocumentPane();
|
|
8
|
-
const documentId = (value?._id as string | undefined) || undefined;
|
|
9
|
-
const
|
|
10
|
-
const
|
|
11
|
-
const
|
|
12
|
-
const [
|
|
13
|
-
const [
|
|
14
|
-
const
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
//
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
const
|
|
29
|
-
const
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
//
|
|
33
|
-
//
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
}
|
|
1
|
+
import { useState, useEffect, useRef } from "react";
|
|
2
|
+
import { useDocumentPane } from "sanity/structure";
|
|
3
|
+
import type { DocumentFields } from "../lib/types";
|
|
4
|
+
import { extractText, buildDocumentFields } from "../lib/documentExtract";
|
|
5
|
+
|
|
6
|
+
export function useDocumentContent(): { text: string; isLoading: boolean; documentFields: DocumentFields; documentId: string | undefined; documentType: string | undefined } {
|
|
7
|
+
const { value, ready } = useDocumentPane();
|
|
8
|
+
const documentId = (value?._id as string | undefined) || undefined;
|
|
9
|
+
const documentType = (value?._type as string | undefined) || undefined;
|
|
10
|
+
const title = value?.title as string | undefined;
|
|
11
|
+
const body = value?.body;
|
|
12
|
+
const [debouncedText, setDebouncedText] = useState("");
|
|
13
|
+
const [isLoading, setIsLoading] = useState(!ready);
|
|
14
|
+
const [documentFields, setDocumentFields] = useState<DocumentFields>({});
|
|
15
|
+
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
16
|
+
const prevDocIdRef = useRef<string | undefined>(documentId);
|
|
17
|
+
|
|
18
|
+
// Reset loading state on doc switch so downstream tabs can show their own loading UI
|
|
19
|
+
// instead of flashing "Missing" cards based on the previous doc's data.
|
|
20
|
+
useEffect(() => {
|
|
21
|
+
if (prevDocIdRef.current !== documentId) {
|
|
22
|
+
prevDocIdRef.current = documentId;
|
|
23
|
+
setIsLoading(true);
|
|
24
|
+
}
|
|
25
|
+
}, [documentId]);
|
|
26
|
+
|
|
27
|
+
useEffect(() => {
|
|
28
|
+
const bodyText = extractText(body);
|
|
29
|
+
const fullText = [title, bodyText].filter(Boolean).join("\n\n");
|
|
30
|
+
const fields = buildDocumentFields(value as Record<string, unknown> | undefined);
|
|
31
|
+
|
|
32
|
+
// documentFields are cheap and shown immediately so the Technical tab doesn't flash
|
|
33
|
+
// "Missing" cards while the text debounce is pending. Only debounce text since that
|
|
34
|
+
// drives the expensive AI analysis calls.
|
|
35
|
+
setDocumentFields(fields);
|
|
36
|
+
|
|
37
|
+
if (timerRef.current) clearTimeout(timerRef.current);
|
|
38
|
+
|
|
39
|
+
timerRef.current = setTimeout(() => {
|
|
40
|
+
setDebouncedText(fullText);
|
|
41
|
+
setIsLoading(false);
|
|
42
|
+
}, 2000);
|
|
43
|
+
|
|
44
|
+
return () => { if (timerRef.current) clearTimeout(timerRef.current); };
|
|
45
|
+
}, [title, body, value]);
|
|
46
|
+
|
|
47
|
+
return { text: debouncedText, isLoading, documentFields, documentId, documentType };
|
|
48
|
+
}
|
|
@@ -80,6 +80,8 @@ export function useKeywordAnalysis(
|
|
|
80
80
|
return;
|
|
81
81
|
}
|
|
82
82
|
docVersionRef.current += 1;
|
|
83
|
+
volumeAbortRef.current?.abort();
|
|
84
|
+
volumeAbortRef.current = null;
|
|
83
85
|
const fresh = loadCached();
|
|
84
86
|
cached.current = fresh;
|
|
85
87
|
setAnalysisRaw(fresh.analysis);
|
|
@@ -126,6 +128,9 @@ export function useKeywordAnalysis(
|
|
|
126
128
|
// previous document can't write its result onto the document the editor
|
|
127
129
|
// switched to (the regular analysis effect already guards this via `cancelled`).
|
|
128
130
|
const docVersionRef = useRef(0);
|
|
131
|
+
// AbortController for the in-flight volume lookup. Cancelled on doc switch and
|
|
132
|
+
// before each new lookup so only one lookup is ever outstanding at a time.
|
|
133
|
+
const volumeAbortRef = useRef<AbortController | null>(null);
|
|
129
134
|
|
|
130
135
|
useEffect(() => {
|
|
131
136
|
if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) {
|
|
@@ -134,10 +139,11 @@ export function useKeywordAnalysis(
|
|
|
134
139
|
}
|
|
135
140
|
|
|
136
141
|
let cancelled = false;
|
|
142
|
+
const controller = new AbortController();
|
|
137
143
|
setIsLoading(true);
|
|
138
144
|
setError(null);
|
|
139
145
|
|
|
140
|
-
fetchAnalysis(apiUrl, text, "realtime", publication, effectiveSeeds, documentFields, focusPrimary)
|
|
146
|
+
fetchAnalysis(apiUrl, text, "realtime", publication, effectiveSeeds, documentFields, focusPrimary, controller.signal)
|
|
141
147
|
.then((result) => {
|
|
142
148
|
if (cancelled) return;
|
|
143
149
|
const analysisResult = result as SEOAnalysis;
|
|
@@ -162,6 +168,7 @@ export function useKeywordAnalysis(
|
|
|
162
168
|
}
|
|
163
169
|
})
|
|
164
170
|
.catch((err) => {
|
|
171
|
+
if (err instanceof Error && err.name === "AbortError") return;
|
|
165
172
|
if (!cancelled) {
|
|
166
173
|
setError(err.message);
|
|
167
174
|
setIsLoading(false);
|
|
@@ -170,8 +177,12 @@ export function useKeywordAnalysis(
|
|
|
170
177
|
|
|
171
178
|
return () => {
|
|
172
179
|
cancelled = true;
|
|
180
|
+
controller.abort();
|
|
173
181
|
};
|
|
174
|
-
|
|
182
|
+
// JSON.stringify(documentFields) used instead of documentFields directly to avoid
|
|
183
|
+
// re-running when the caller creates a new object reference with identical contents.
|
|
184
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
185
|
+
}, [text, apiUrl, publication, effectiveSeeds?.join(","), focusPrimary, JSON.stringify(documentFields)]);
|
|
175
186
|
|
|
176
187
|
const doVolumeLookup = useCallback((analysisResult: SEOAnalysis, terms?: string[]) => {
|
|
177
188
|
setIsVolumesLoading(true);
|
|
@@ -194,7 +205,12 @@ export function useKeywordAnalysis(
|
|
|
194
205
|
return;
|
|
195
206
|
}
|
|
196
207
|
|
|
197
|
-
|
|
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)
|
|
198
214
|
.then(({ results }) => {
|
|
199
215
|
if (docVersionRef.current !== myVersion) return; // document switched - drop stale volumes
|
|
200
216
|
// Add new results to persistent cache
|
|
@@ -210,7 +226,8 @@ export function useKeywordAnalysis(
|
|
|
210
226
|
} catch { /* ignore */ }
|
|
211
227
|
setIsVolumesLoading(false);
|
|
212
228
|
})
|
|
213
|
-
.catch(() => {
|
|
229
|
+
.catch((err) => {
|
|
230
|
+
if (err instanceof Error && err.name === "AbortError") return;
|
|
214
231
|
if (docVersionRef.current !== myVersion) return;
|
|
215
232
|
setIsVolumesLoading(false);
|
|
216
233
|
});
|
package/src/hooks/useSEOChat.ts
CHANGED
|
@@ -46,13 +46,15 @@ export function useSEOChat(
|
|
|
46
46
|
}, [chatCacheKey]);
|
|
47
47
|
|
|
48
48
|
const [messages, setMessagesRaw] = useState<ChatMessage[]>(loadCachedMessages);
|
|
49
|
+
// Ref always mirrors messages state so sendMessage doesn't need messages in its
|
|
50
|
+
// dependency array (avoiding a re-creation on every streamed token).
|
|
51
|
+
const messagesRef = useRef<ChatMessage[]>([]);
|
|
52
|
+
|
|
53
|
+
// Simplified wrapper - localStorage persistence moved to a debounced useEffect
|
|
54
|
+
// below so it doesn't fire on every individual token during streaming.
|
|
49
55
|
const setMessages = useCallback((msgs: ChatMessage[] | ((prev: ChatMessage[]) => ChatMessage[])) => {
|
|
50
|
-
setMessagesRaw(
|
|
51
|
-
|
|
52
|
-
try { localStorage.setItem(chatCacheKey, JSON.stringify(next)); } catch {}
|
|
53
|
-
return next;
|
|
54
|
-
});
|
|
55
|
-
}, [chatCacheKey]);
|
|
56
|
+
setMessagesRaw(msgs);
|
|
57
|
+
}, []);
|
|
56
58
|
|
|
57
59
|
const [isStreaming, setIsStreaming] = useState(false);
|
|
58
60
|
const [historyLoaded, setHistoryLoaded] = useState(false);
|
|
@@ -65,6 +67,30 @@ export function useSEOChat(
|
|
|
65
67
|
userId.current = sanityUser.id;
|
|
66
68
|
}
|
|
67
69
|
}, [sanityUser?.id]);
|
|
70
|
+
|
|
71
|
+
// Keep messagesRef in sync with state so sendMessage can read current messages
|
|
72
|
+
// without capturing a stale closure value.
|
|
73
|
+
useEffect(() => {
|
|
74
|
+
messagesRef.current = messages;
|
|
75
|
+
}, [messages]);
|
|
76
|
+
|
|
77
|
+
// Persist chat history to localStorage, debounced so we don't write on every
|
|
78
|
+
// individual token during streaming (only once the stream settles).
|
|
79
|
+
useEffect(() => {
|
|
80
|
+
const timer = setTimeout(() => {
|
|
81
|
+
try { localStorage.setItem(chatCacheKey, JSON.stringify(messages)); } catch {}
|
|
82
|
+
}, 500);
|
|
83
|
+
return () => clearTimeout(timer);
|
|
84
|
+
}, [messages, chatCacheKey]);
|
|
85
|
+
|
|
86
|
+
// AbortController for the in-flight chat stream. Aborted on doc switch and unmount.
|
|
87
|
+
const streamAbortRef = useRef<AbortController | null>(null);
|
|
88
|
+
|
|
89
|
+
// Abort any in-flight stream on unmount to prevent state updates on a dead component.
|
|
90
|
+
useEffect(() => {
|
|
91
|
+
return () => { streamAbortRef.current?.abort(); };
|
|
92
|
+
}, []);
|
|
93
|
+
|
|
68
94
|
const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
69
95
|
|
|
70
96
|
// Per-document operation version to invalidate stale in-flight loads
|
|
@@ -79,6 +105,8 @@ export function useSEOChat(
|
|
|
79
105
|
return;
|
|
80
106
|
}
|
|
81
107
|
opVersionRef.current += 1;
|
|
108
|
+
streamAbortRef.current?.abort();
|
|
109
|
+
streamAbortRef.current = null;
|
|
82
110
|
setMessagesRaw(loadCachedMessages());
|
|
83
111
|
setIsStreaming(false);
|
|
84
112
|
setHistoryLoaded(false);
|
|
@@ -118,17 +146,23 @@ export function useSEOChat(
|
|
|
118
146
|
async (text: string) => {
|
|
119
147
|
const myVersion = opVersionRef.current;
|
|
120
148
|
const userMessage: ChatMessage = { role: "user", content: text };
|
|
121
|
-
|
|
149
|
+
// Read from ref so messages is not needed in the dep array - prevents
|
|
150
|
+
// sendMessage from being recreated on every streamed token.
|
|
151
|
+
const updatedMessages = [...messagesRef.current, userMessage];
|
|
122
152
|
setMessages(updatedMessages);
|
|
123
153
|
setIsStreaming(true);
|
|
124
154
|
|
|
155
|
+
const controller = new AbortController();
|
|
156
|
+
streamAbortRef.current = controller;
|
|
157
|
+
|
|
125
158
|
try {
|
|
126
159
|
const stream = await fetchChatStream(
|
|
127
160
|
apiUrl,
|
|
128
161
|
updatedMessages,
|
|
129
162
|
documentText,
|
|
130
163
|
publication,
|
|
131
|
-
keywordPanelData
|
|
164
|
+
keywordPanelData,
|
|
165
|
+
controller.signal
|
|
132
166
|
);
|
|
133
167
|
|
|
134
168
|
if (!stream) {
|
|
@@ -189,6 +223,8 @@ export function useSEOChat(
|
|
|
189
223
|
scheduleSave(finalMessages);
|
|
190
224
|
}
|
|
191
225
|
} catch (err) {
|
|
226
|
+
// Abort is silent - happens on doc switch or unmount, not an error for the editor.
|
|
227
|
+
if (err instanceof Error && err.name === "AbortError") { setIsStreaming(false); return; }
|
|
192
228
|
if (opVersionRef.current !== myVersion) { setIsStreaming(false); return; }
|
|
193
229
|
const errorMsg = err instanceof Error ? err.message : "Chat failed";
|
|
194
230
|
setMessages((prev) => [
|
|
@@ -199,7 +235,7 @@ export function useSEOChat(
|
|
|
199
235
|
|
|
200
236
|
if (opVersionRef.current === myVersion) setIsStreaming(false);
|
|
201
237
|
},
|
|
202
|
-
[
|
|
238
|
+
[apiUrl, documentText, publication, keywordPanelData, scheduleSave]
|
|
203
239
|
);
|
|
204
240
|
|
|
205
241
|
const clearChat = useCallback(() => {
|
package/src/lib/api.ts
CHANGED
|
@@ -29,19 +29,24 @@ export async function fetchAnalysis(
|
|
|
29
29
|
publication?: string,
|
|
30
30
|
seedKeywords?: string[],
|
|
31
31
|
documentFields?: DocumentFields,
|
|
32
|
-
focusKeyword?: string
|
|
32
|
+
focusKeyword?: string,
|
|
33
|
+
signal?: AbortSignal
|
|
33
34
|
): Promise<SEOAnalysis | DeepAnalysis> {
|
|
34
35
|
const response = await fetch(`${apiUrl}/api/seo-copilot/analyze`, {
|
|
35
36
|
method: "POST",
|
|
36
37
|
headers: { "Content-Type": "application/json" },
|
|
37
38
|
body: JSON.stringify({ content, mode, publication, seedKeywords, documentFields, focusKeyword }),
|
|
39
|
+
signal,
|
|
38
40
|
});
|
|
39
41
|
|
|
40
42
|
const text = await response.text();
|
|
41
43
|
|
|
42
44
|
if (!response.ok) {
|
|
43
45
|
const err = safeParseJson<{ error?: string }>(text);
|
|
44
|
-
|
|
46
|
+
console.error("[seo-copilot] analyze error", response.status, err.error);
|
|
47
|
+
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
48
|
+
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
49
|
+
throw new Error("Something went wrong analyzing this document.");
|
|
45
50
|
}
|
|
46
51
|
|
|
47
52
|
return safeParseJson<SEOAnalysis | DeepAnalysis>(text);
|
|
@@ -59,17 +64,22 @@ export async function fetchChatStream(
|
|
|
59
64
|
aeoData?: {
|
|
60
65
|
questionHeadings: { suggestedHeading: string; rationale: string }[];
|
|
61
66
|
};
|
|
62
|
-
}
|
|
67
|
+
},
|
|
68
|
+
signal?: AbortSignal
|
|
63
69
|
): Promise<ReadableStream<Uint8Array> | null> {
|
|
64
70
|
const response = await fetch(`${apiUrl}/api/seo-copilot/chat`, {
|
|
65
71
|
method: "POST",
|
|
66
72
|
headers: { "Content-Type": "application/json" },
|
|
67
73
|
body: JSON.stringify({ messages, documentContext, publication, keywordPanelData }),
|
|
74
|
+
signal,
|
|
68
75
|
});
|
|
69
76
|
|
|
70
77
|
if (!response.ok) {
|
|
71
78
|
const err = await response.json().catch(() => ({ error: "Request failed" }));
|
|
72
|
-
|
|
79
|
+
console.error("[seo-copilot] chat error", response.status, err.error);
|
|
80
|
+
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
81
|
+
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
82
|
+
throw new Error("Something went wrong. Please try again.");
|
|
73
83
|
}
|
|
74
84
|
|
|
75
85
|
return response.body;
|
|
@@ -87,7 +97,10 @@ export async function fetchQuestions(
|
|
|
87
97
|
|
|
88
98
|
if (!response.ok) {
|
|
89
99
|
const err = await response.json().catch(() => ({ error: "Request failed" }));
|
|
90
|
-
|
|
100
|
+
console.error("[seo-copilot] questions error", response.status, err.error);
|
|
101
|
+
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
102
|
+
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
103
|
+
throw new Error("Something went wrong. Please try again.");
|
|
91
104
|
}
|
|
92
105
|
|
|
93
106
|
return response.json();
|
|
@@ -106,17 +119,22 @@ export async function submitFeedback(
|
|
|
106
119
|
|
|
107
120
|
export async function lookupKeywords(
|
|
108
121
|
apiUrl: string,
|
|
109
|
-
keywords: string[]
|
|
122
|
+
keywords: string[],
|
|
123
|
+
signal?: AbortSignal
|
|
110
124
|
): Promise<{ results: { keyword: string; volume: number; cpc: number; competition: number }[]; apiUnitsUsed: number }> {
|
|
111
125
|
const response = await fetch(`${apiUrl}/api/seo-copilot/keywords`, {
|
|
112
126
|
method: "POST",
|
|
113
127
|
headers: { "Content-Type": "application/json" },
|
|
114
128
|
body: JSON.stringify({ keywords }),
|
|
129
|
+
signal,
|
|
115
130
|
});
|
|
116
131
|
|
|
117
132
|
if (!response.ok) {
|
|
118
133
|
const err = await response.json().catch(() => ({ error: "Request failed" }));
|
|
119
|
-
|
|
134
|
+
console.error("[seo-copilot] keywords error", response.status, err.error);
|
|
135
|
+
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
136
|
+
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
137
|
+
throw new Error("Something went wrong. Please try again.");
|
|
120
138
|
}
|
|
121
139
|
|
|
122
140
|
return response.json();
|