95 lines
2.3 KiB
TypeScript
95 lines
2.3 KiB
TypeScript
import "server-only";
|
||
|
||
import { getEnabledAiProviders } from "@/lib/db/queries";
|
||
|
||
export type KittyCadProviderSource = "provider" | "env";
|
||
|
||
export type KittyCadProviderConfig = {
|
||
apiKey: string;
|
||
baseUrl: string;
|
||
providerId?: string;
|
||
providerName?: string;
|
||
source: KittyCadProviderSource;
|
||
};
|
||
|
||
const DEFAULT_KITTYCAD_BASE_URL = "https://api.zoo.dev";
|
||
|
||
function stripUnsafeText(value: string): string {
|
||
let result = "";
|
||
|
||
for (const char of String(value || "")) {
|
||
const code = char.charCodeAt(0);
|
||
if (code === 0x20_28 || code === 0x20_29) {
|
||
continue;
|
||
}
|
||
if ((code >= 0 && code <= 0x1f) || code === 0x7f) {
|
||
continue;
|
||
}
|
||
result += char;
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
function sanitizeKittyCadToken(value: string): string {
|
||
return stripUnsafeText(value).trim();
|
||
}
|
||
|
||
function sanitizeKittyCadBaseUrl(value: string): string {
|
||
return stripUnsafeText(value).trim();
|
||
}
|
||
|
||
export async function findKittyCadProviderConfig(): Promise<KittyCadProviderConfig | null> {
|
||
const providers = await getEnabledAiProviders();
|
||
const kittyCadProvider = providers.find(
|
||
(item) => item.type === "kittycad-cad"
|
||
);
|
||
|
||
const providerApiKey = sanitizeKittyCadToken(
|
||
String(kittyCadProvider?.apiKey || "")
|
||
);
|
||
if (kittyCadProvider && providerApiKey) {
|
||
return {
|
||
apiKey: providerApiKey,
|
||
baseUrl:
|
||
sanitizeKittyCadBaseUrl(String(kittyCadProvider.baseUrl || "")) ||
|
||
DEFAULT_KITTYCAD_BASE_URL,
|
||
providerId: kittyCadProvider.id,
|
||
providerName: kittyCadProvider.name,
|
||
source: "provider",
|
||
};
|
||
}
|
||
|
||
const envApiKey = sanitizeKittyCadToken(
|
||
String(
|
||
process.env.KITTYCAD_API_TOKEN ||
|
||
process.env.KITTYCAD_API_KEY ||
|
||
process.env.ZOO_API_TOKEN ||
|
||
""
|
||
)
|
||
);
|
||
|
||
if (!envApiKey) {
|
||
return null;
|
||
}
|
||
|
||
return {
|
||
apiKey: envApiKey,
|
||
baseUrl:
|
||
sanitizeKittyCadBaseUrl(
|
||
String(process.env.KITTYCAD_BASE_URL || process.env.ZOO_BASE_URL || "")
|
||
) || DEFAULT_KITTYCAD_BASE_URL,
|
||
source: "env",
|
||
};
|
||
}
|
||
|
||
export async function getKittyCadProviderConfig(): Promise<KittyCadProviderConfig> {
|
||
const config = await findKittyCadProviderConfig();
|
||
if (!config) {
|
||
throw new Error(
|
||
"未配置 KittyCAD CAD API,请在系统设置-本地AI新增 KittyCAD CAD 提供商"
|
||
);
|
||
}
|
||
return config;
|
||
}
|