328 lines
8.7 KiB
TypeScript
328 lines
8.7 KiB
TypeScript
|
|
import { createApiClient } from "@geo/http-client";
|
||
|
|
import type {
|
||
|
|
ArticleDetail,
|
||
|
|
ArticleListParams,
|
||
|
|
ArticleListResponse,
|
||
|
|
ArticleVersion,
|
||
|
|
AuthTokens,
|
||
|
|
Brand,
|
||
|
|
BrandRequest,
|
||
|
|
Competitor,
|
||
|
|
CompetitorRequest,
|
||
|
|
JsonValue,
|
||
|
|
Keyword,
|
||
|
|
KeywordRequest,
|
||
|
|
LoginRequest,
|
||
|
|
LoginResponse,
|
||
|
|
QuotaSummary,
|
||
|
|
Question,
|
||
|
|
QuestionRequest,
|
||
|
|
QuestionVersion,
|
||
|
|
RecentArticle,
|
||
|
|
RefreshResponse,
|
||
|
|
TemplateDetail,
|
||
|
|
TemplateGenerateRequest,
|
||
|
|
TemplateGenerateResponse,
|
||
|
|
TemplateListItem,
|
||
|
|
TemplateSchema,
|
||
|
|
TemplateCard,
|
||
|
|
UpdateQuestionRequest,
|
||
|
|
UserInfo,
|
||
|
|
WorkspaceOverview,
|
||
|
|
} from "@geo/shared-types";
|
||
|
|
|
||
|
|
import {
|
||
|
|
clearStoredSession,
|
||
|
|
getStoredAccessToken,
|
||
|
|
getStoredRefreshToken,
|
||
|
|
setStoredTokens,
|
||
|
|
} from "./session";
|
||
|
|
|
||
|
|
const baseURL = import.meta.env.VITE_API_BASE_URL ?? "";
|
||
|
|
const generationStreamEnabled = import.meta.env.VITE_GENERATION_STREAM_ENABLED === "true";
|
||
|
|
|
||
|
|
const publicClient = createApiClient({ baseURL });
|
||
|
|
|
||
|
|
export const apiClient = createApiClient({
|
||
|
|
baseURL,
|
||
|
|
auth: {
|
||
|
|
getAccessToken: getStoredAccessToken,
|
||
|
|
getRefreshToken: getStoredRefreshToken,
|
||
|
|
setTokens: setStoredTokens,
|
||
|
|
clearTokens: clearStoredSession,
|
||
|
|
async refresh(refreshToken: string): Promise<AuthTokens> {
|
||
|
|
const data = await publicClient.post<RefreshResponse, { refresh_token: string }>(
|
||
|
|
"/api/auth/refresh",
|
||
|
|
{ refresh_token: refreshToken },
|
||
|
|
);
|
||
|
|
|
||
|
|
return {
|
||
|
|
accessToken: data.access_token,
|
||
|
|
refreshToken: data.refresh_token,
|
||
|
|
};
|
||
|
|
},
|
||
|
|
},
|
||
|
|
});
|
||
|
|
|
||
|
|
export const authApi = {
|
||
|
|
login(payload: LoginRequest) {
|
||
|
|
return publicClient.post<LoginResponse, LoginRequest>("/api/auth/login", payload);
|
||
|
|
},
|
||
|
|
me() {
|
||
|
|
return apiClient.get<UserInfo>("/api/auth/me");
|
||
|
|
},
|
||
|
|
logout() {
|
||
|
|
return apiClient.post<null>("/api/auth/logout");
|
||
|
|
},
|
||
|
|
};
|
||
|
|
|
||
|
|
export const workspaceApi = {
|
||
|
|
overview() {
|
||
|
|
return apiClient.get<WorkspaceOverview>("/api/tenant/workspace/overview");
|
||
|
|
},
|
||
|
|
recentArticles() {
|
||
|
|
return apiClient.get<RecentArticle[]>("/api/tenant/workspace/recent-articles");
|
||
|
|
},
|
||
|
|
quotaSummary() {
|
||
|
|
return apiClient.get<QuotaSummary>("/api/tenant/workspace/quota-summary");
|
||
|
|
},
|
||
|
|
templateCards() {
|
||
|
|
return apiClient.get<TemplateCard[]>("/api/tenant/workspace/template-cards");
|
||
|
|
},
|
||
|
|
};
|
||
|
|
|
||
|
|
export const templatesApi = {
|
||
|
|
list() {
|
||
|
|
return apiClient.get<TemplateListItem[]>("/api/tenant/templates");
|
||
|
|
},
|
||
|
|
detail(id: number) {
|
||
|
|
return apiClient.get<TemplateDetail>(`/api/tenant/templates/${id}`);
|
||
|
|
},
|
||
|
|
schema(id: number) {
|
||
|
|
return apiClient.get<TemplateSchema>(`/api/tenant/templates/${id}/schema`);
|
||
|
|
},
|
||
|
|
generate(id: number, payload: TemplateGenerateRequest) {
|
||
|
|
return apiClient.post<TemplateGenerateResponse, TemplateGenerateRequest>(
|
||
|
|
`/api/tenant/templates/${id}/generate`,
|
||
|
|
payload,
|
||
|
|
);
|
||
|
|
},
|
||
|
|
};
|
||
|
|
|
||
|
|
export const articlesApi = {
|
||
|
|
list(params: ArticleListParams) {
|
||
|
|
return apiClient.get<ArticleListResponse>("/api/tenant/articles", { params });
|
||
|
|
},
|
||
|
|
detail(id: number) {
|
||
|
|
return apiClient.get<ArticleDetail>(`/api/tenant/articles/${id}`);
|
||
|
|
},
|
||
|
|
versions(id: number) {
|
||
|
|
return apiClient.get<ArticleVersion[]>(`/api/tenant/articles/${id}/versions`);
|
||
|
|
},
|
||
|
|
remove(id: number) {
|
||
|
|
return apiClient.remove<null>(`/api/tenant/articles/${id}`);
|
||
|
|
},
|
||
|
|
};
|
||
|
|
|
||
|
|
export interface ArticleGenerationStreamEvent {
|
||
|
|
type: string;
|
||
|
|
article_id: number;
|
||
|
|
task_id?: number;
|
||
|
|
title?: string;
|
||
|
|
status?: string;
|
||
|
|
delta?: string;
|
||
|
|
content?: string;
|
||
|
|
error?: string;
|
||
|
|
done?: boolean;
|
||
|
|
updated_at?: string;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function isGenerationStreamEnabled(): boolean {
|
||
|
|
return generationStreamEnabled;
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function subscribeArticleGeneration(
|
||
|
|
articleId: number,
|
||
|
|
handlers: {
|
||
|
|
onEvent: (event: ArticleGenerationStreamEvent) => void;
|
||
|
|
onClose?: () => void;
|
||
|
|
},
|
||
|
|
signal: AbortSignal,
|
||
|
|
): Promise<void> {
|
||
|
|
const accessToken = getStoredAccessToken();
|
||
|
|
if (!accessToken) {
|
||
|
|
throw new Error("missing access token");
|
||
|
|
}
|
||
|
|
|
||
|
|
const response = await fetch(`${baseURL}/api/tenant/articles/${articleId}/stream`, {
|
||
|
|
method: "GET",
|
||
|
|
headers: {
|
||
|
|
Accept: "text/event-stream",
|
||
|
|
Authorization: `Bearer ${accessToken}`,
|
||
|
|
},
|
||
|
|
signal,
|
||
|
|
});
|
||
|
|
|
||
|
|
if (!response.ok) {
|
||
|
|
throw new Error(`stream request failed with status ${response.status}`);
|
||
|
|
}
|
||
|
|
if (!response.body) {
|
||
|
|
throw new Error("stream response body is empty");
|
||
|
|
}
|
||
|
|
|
||
|
|
const reader = response.body.getReader();
|
||
|
|
const decoder = new TextDecoder();
|
||
|
|
let buffer = "";
|
||
|
|
|
||
|
|
try {
|
||
|
|
while (true) {
|
||
|
|
const { done, value } = await reader.read();
|
||
|
|
if (done) {
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
|
||
|
|
buffer += decoder.decode(value, { stream: true });
|
||
|
|
buffer = consumeSSEBuffer(buffer, handlers.onEvent);
|
||
|
|
}
|
||
|
|
|
||
|
|
buffer += decoder.decode();
|
||
|
|
consumeSSEBuffer(buffer, handlers.onEvent);
|
||
|
|
} finally {
|
||
|
|
reader.releaseLock();
|
||
|
|
handlers.onClose?.();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
export const brandsApi = {
|
||
|
|
list() {
|
||
|
|
return apiClient.get<Brand[]>("/api/tenant/brands");
|
||
|
|
},
|
||
|
|
create(payload: BrandRequest) {
|
||
|
|
return apiClient.post<Brand, BrandRequest>("/api/tenant/brands", payload);
|
||
|
|
},
|
||
|
|
detail(id: number) {
|
||
|
|
return apiClient.get<Brand>(`/api/tenant/brands/${id}`);
|
||
|
|
},
|
||
|
|
update(id: number, payload: BrandRequest) {
|
||
|
|
return apiClient.put<null, BrandRequest>(`/api/tenant/brands/${id}`, payload);
|
||
|
|
},
|
||
|
|
remove(id: number) {
|
||
|
|
return apiClient.remove<null>(`/api/tenant/brands/${id}`);
|
||
|
|
},
|
||
|
|
listKeywords(brandId: number) {
|
||
|
|
return apiClient.get<Keyword[]>(`/api/tenant/brands/${brandId}/keywords`);
|
||
|
|
},
|
||
|
|
createKeyword(brandId: number, payload: KeywordRequest) {
|
||
|
|
return apiClient.post<Keyword, KeywordRequest>(
|
||
|
|
`/api/tenant/brands/${brandId}/keywords`,
|
||
|
|
payload,
|
||
|
|
);
|
||
|
|
},
|
||
|
|
updateKeyword(brandId: number, keywordId: number, payload: KeywordRequest) {
|
||
|
|
return apiClient.put<null, KeywordRequest>(
|
||
|
|
`/api/tenant/brands/${brandId}/keywords/${keywordId}`,
|
||
|
|
payload,
|
||
|
|
);
|
||
|
|
},
|
||
|
|
removeKeyword(brandId: number, keywordId: number) {
|
||
|
|
return apiClient.remove<null>(`/api/tenant/brands/${brandId}/keywords/${keywordId}`);
|
||
|
|
},
|
||
|
|
listQuestions(brandId: number, keywordId?: number | null) {
|
||
|
|
return apiClient.get<Question[]>(`/api/tenant/brands/${brandId}/questions`, {
|
||
|
|
params: keywordId ? { keyword_id: keywordId } : undefined,
|
||
|
|
});
|
||
|
|
},
|
||
|
|
createQuestion(brandId: number, payload: QuestionRequest) {
|
||
|
|
return apiClient.post<Question, QuestionRequest>(
|
||
|
|
`/api/tenant/brands/${brandId}/questions`,
|
||
|
|
payload,
|
||
|
|
);
|
||
|
|
},
|
||
|
|
updateQuestion(brandId: number, questionId: number, payload: UpdateQuestionRequest) {
|
||
|
|
return apiClient.put<null, UpdateQuestionRequest>(
|
||
|
|
`/api/tenant/brands/${brandId}/questions/${questionId}`,
|
||
|
|
payload,
|
||
|
|
);
|
||
|
|
},
|
||
|
|
removeQuestion(brandId: number, questionId: number) {
|
||
|
|
return apiClient.remove<null>(`/api/tenant/brands/${brandId}/questions/${questionId}`);
|
||
|
|
},
|
||
|
|
listQuestionVersions(brandId: number) {
|
||
|
|
return apiClient.get<QuestionVersion[]>(`/api/tenant/brands/${brandId}/question-versions`);
|
||
|
|
},
|
||
|
|
listCompetitors(brandId: number) {
|
||
|
|
return apiClient.get<Competitor[]>(`/api/tenant/brands/${brandId}/competitors`);
|
||
|
|
},
|
||
|
|
createCompetitor(brandId: number, payload: CompetitorRequest) {
|
||
|
|
return apiClient.post<Competitor, CompetitorRequest>(
|
||
|
|
`/api/tenant/brands/${brandId}/competitors`,
|
||
|
|
payload,
|
||
|
|
);
|
||
|
|
},
|
||
|
|
updateCompetitor(brandId: number, competitorId: number, payload: CompetitorRequest) {
|
||
|
|
return apiClient.put<null, CompetitorRequest>(
|
||
|
|
`/api/tenant/brands/${brandId}/competitors/${competitorId}`,
|
||
|
|
payload,
|
||
|
|
);
|
||
|
|
},
|
||
|
|
removeCompetitor(brandId: number, competitorId: number) {
|
||
|
|
return apiClient.remove<null>(`/api/tenant/brands/${brandId}/competitors/${competitorId}`);
|
||
|
|
},
|
||
|
|
};
|
||
|
|
|
||
|
|
export function normalizeInputParams(
|
||
|
|
payload: Record<string, JsonValue>,
|
||
|
|
): TemplateGenerateRequest {
|
||
|
|
return { input_params: payload };
|
||
|
|
}
|
||
|
|
|
||
|
|
function consumeSSEBuffer(
|
||
|
|
buffer: string,
|
||
|
|
onEvent: (event: ArticleGenerationStreamEvent) => void,
|
||
|
|
): string {
|
||
|
|
let next = buffer;
|
||
|
|
|
||
|
|
for (;;) {
|
||
|
|
const delimiterIndex = next.indexOf("\n\n");
|
||
|
|
if (delimiterIndex === -1) {
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
|
||
|
|
const rawEvent = next.slice(0, delimiterIndex);
|
||
|
|
next = next.slice(delimiterIndex + 2);
|
||
|
|
|
||
|
|
const parsed = parseSSEEvent(rawEvent);
|
||
|
|
if (parsed) {
|
||
|
|
onEvent(parsed);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return next;
|
||
|
|
}
|
||
|
|
|
||
|
|
function parseSSEEvent(raw: string): ArticleGenerationStreamEvent | null {
|
||
|
|
const lines = raw.split(/\r?\n/);
|
||
|
|
let event = "message";
|
||
|
|
const dataLines: string[] = [];
|
||
|
|
|
||
|
|
for (const line of lines) {
|
||
|
|
if (line.startsWith("event:")) {
|
||
|
|
event = line.slice(6).trim();
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
if (line.startsWith("data:")) {
|
||
|
|
dataLines.push(line.slice(5).trimStart());
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if (dataLines.length === 0) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
const data = JSON.parse(dataLines.join("\n")) as unknown as ArticleGenerationStreamEvent;
|
||
|
|
return {
|
||
|
|
...data,
|
||
|
|
type: event,
|
||
|
|
};
|
||
|
|
}
|