astrbot_plugin_imagestudio/frontend/shared/api/client.ts

306 行
11 KiB
TypeScript

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

import { API_BASE } from "./endpoints"
import { LONG_TASK_TIMEOUT_MS } from "../config/timeouts"
import type { ApiResponse, AstrBotApiResponse } from "../types/api"
export type ApiTransport = "plugin-bridge" | "direct-fetch"
export type ApiMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE"
const METHOD_OVERRIDE_KEY = "__imagestudio_method"
const METHOD_OVERRIDE_BODY_KEY = "__imagestudio_body"
const PLUGIN_BRIDGE_DISCOVERY_TIMEOUT_MS = 2500
const PLUGIN_BRIDGE_READY_TIMEOUT_MS = 1200
const PLUGIN_BRIDGE_GET_TIMEOUT_MS = 15000
const PLUGIN_BRIDGE_POST_TIMEOUT_MS = 30000
const LONG_TASK_ENDPOINT = /(?:^|\/)(?:generate|retry|review|execute-character|expand|governance-preview|probe-provider|probe-model|recognize|re-recognize|renormalize|renormalize-batch|import-pack|migrate|restore)(?:\/|$)/
type PluginBridge = NonNullable<Window["AstrBotPluginPage"]>
export class ApiClientError extends Error {
readonly code: string
readonly details: Record<string, unknown>
constructor(code: string, message: string, details: Record<string, unknown> = {}) {
super(message)
this.name = "ApiClientError"
this.code = code
this.details = details
}
}
export async function getJson<T>(endpoint: string, query?: Record<string, string | number | boolean | undefined>) {
return request<T>(endpoint, { method: "GET", query })
}
export async function postJson<T>(endpoint: string, body?: unknown) {
return request<T>(endpoint, { method: "POST", body })
}
export async function putJson<T>(endpoint: string, body?: unknown) {
return request<T>(endpoint, { method: "PUT", body })
}
export async function patchJson<T>(endpoint: string, body?: unknown) {
return request<T>(endpoint, { method: "PATCH", body })
}
export async function deleteJson<T>(endpoint: string, body?: unknown) {
return request<T>(endpoint, { method: "DELETE", body })
}
export function getApiTransport(): ApiTransport {
const bridge = typeof window === "undefined" ? undefined : window.AstrBotPluginPage
return bridge && (typeof bridge.apiGet === "function" || typeof bridge.apiPost === "function")
? "plugin-bridge"
: "direct-fetch"
}
export async function request<T>(
endpoint: string,
options: {
method?: ApiMethod
query?: Record<string, string | number | boolean | undefined>
body?: unknown
} = {},
): Promise<T> {
const bridge = await pluginBridgeForRequest()
if (bridge) {
const bridgePayload = await requestViaPluginBridge<T>(bridge, endpoint, options)
if (bridgePayload === undefined) {
throw new ApiClientError("invalid_api_response", "AstrBot Plugin Page bridge returned no response", {
endpoint,
method: options.method ?? "GET",
transport: "plugin-bridge",
})
}
return unwrapApiResponse(bridgePayload)
}
const url = buildUrl(endpoint, options.query)
let response: Response
try {
response = await fetch(url, {
method: options.method ?? "GET",
headers: options.body === undefined ? undefined : { "Content-Type": "application/json" },
body: options.body === undefined ? undefined : JSON.stringify(options.body),
})
} catch (err) {
throw new ApiClientError("network_unreachable", "无法连接 ImageStudio 后端接口", {
endpoint,
transport: "direct-fetch",
url,
reason: err instanceof Error ? err.message : String(err),
})
}
const payload = await parseResponsePayload<T>(response, endpoint, url)
if (!response.ok && !isApiResponse(payload) && !isAstrBotApiResponse(payload)) {
throw new ApiClientError("http_error", `接口请求失败(HTTP ${response.status})`, {
endpoint,
transport: "direct-fetch",
url,
status: response.status,
status_text: response.statusText,
})
}
return unwrapApiResponse(payload)
}
async function requestViaPluginBridge<T>(
bridge: PluginBridge,
endpoint: string,
options: {
method?: ApiMethod
query?: Record<string, string | number | boolean | undefined>
body?: unknown
},
): Promise<T | ApiResponse<T> | AstrBotApiResponse<T> | undefined> {
const method = options.method ?? "GET"
if (typeof bridge.ready === "function") {
try {
await withClientTimeout(
Promise.resolve(bridge.ready()),
PLUGIN_BRIDGE_READY_TIMEOUT_MS,
"AstrBot Plugin Page bridge readiness timed out",
)
} catch {
// Some AstrBot builds leave ready() pending even though apiGet/apiPost
// are already usable. Continue with the concrete bridge method, which
// has its own timeout and can be retried by the app bootstrap loop.
}
}
if (method === "GET" && typeof bridge.apiGet === "function") {
return withClientTimeout(
bridge.apiGet<T | ApiResponse<T> | AstrBotApiResponse<T>>(endpoint, compactQuery(options.query)),
PLUGIN_BRIDGE_GET_TIMEOUT_MS,
"AstrBot Plugin Page GET request timed out",
)
}
if (method === "POST" && typeof bridge.apiPost === "function") {
const timeoutMs = pluginBridgePostTimeout(endpoint)
return withClientTimeout(
bridge.apiPost<T | ApiResponse<T> | AstrBotApiResponse<T>>(endpoint, options.body),
timeoutMs,
`AstrBot Plugin Page POST request timed out after ${Math.round(timeoutMs / 1000)} seconds`,
)
}
if (method === "PUT" && typeof bridge.apiPut === "function") {
return bridge.apiPut<T | ApiResponse<T> | AstrBotApiResponse<T>>(endpoint, options.body)
}
if (method === "PATCH" && typeof bridge.apiPatch === "function") {
return bridge.apiPatch<T | ApiResponse<T> | AstrBotApiResponse<T>>(endpoint, options.body)
}
if (method === "DELETE" && typeof bridge.apiDelete === "function") {
return bridge.apiDelete<T | ApiResponse<T> | AstrBotApiResponse<T>>(endpoint)
}
if (["PUT", "PATCH", "DELETE"].includes(method) && typeof bridge.apiPost === "function") {
return bridge.apiPost<T | ApiResponse<T> | AstrBotApiResponse<T>>(endpoint, {
[METHOD_OVERRIDE_KEY]: method,
[METHOD_OVERRIDE_BODY_KEY]: method === "DELETE" ? {} : options.body === undefined ? {} : options.body,
})
}
throw new ApiClientError("bridge_method_unavailable", `AstrBot Plugin Page bridge does not support ${method}`, {
endpoint,
method,
transport: "plugin-bridge",
})
}
function pluginBridgePostTimeout(endpoint: string) {
return LONG_TASK_ENDPOINT.test(endpoint)
? LONG_TASK_TIMEOUT_MS
: PLUGIN_BRIDGE_POST_TIMEOUT_MS
}
async function pluginBridgeForRequest(): Promise<PluginBridge | undefined> {
if (typeof window === "undefined") return undefined
if (window.AstrBotPluginPage) return window.AstrBotPluginPage
if (window.parent === window) return undefined
const deadline = Date.now() + PLUGIN_BRIDGE_DISCOVERY_TIMEOUT_MS
while (Date.now() < deadline) {
await new Promise<void>((resolve) => window.setTimeout(resolve, 100))
if (window.AstrBotPluginPage) return window.AstrBotPluginPage
}
return undefined
}
function withClientTimeout<T>(promise: Promise<T>, timeoutMs: number, message: string): Promise<T> {
return new Promise((resolve, reject) => {
const timer = window.setTimeout(() => reject(new ApiClientError("bridge_timeout", message)), timeoutMs)
promise.then(
(value) => {
window.clearTimeout(timer)
resolve(value)
},
(error) => {
window.clearTimeout(timer)
reject(error)
},
)
})
}
function unwrapApiResponse<T>(payload: T | ApiResponse<T> | AstrBotApiResponse<T>): T {
let current: unknown = payload
for (let depth = 0; depth < 4; depth += 1) {
if (isApiResponse(current)) {
if (!current.ok) {
throw new ApiClientError(current.error_code, current.message, current.details ?? {})
}
current = current.data
continue
}
if (isAstrBotApiResponse(current)) {
if (current.status === "error") {
if (isApiResponse(current.data)) {
current = current.data
continue
}
throw new ApiClientError(
current.error_code || "astrbot_bridge_error",
current.message || current.error || "AstrBot Plugin Page bridge request failed",
current.details ?? bridgeErrorDetails(current.data),
)
}
current = current.data
continue
}
return current as T
}
throw new ApiClientError("invalid_api_response", "API response wrapper nesting is too deep")
}
async function parseResponsePayload<T>(
response: Response,
endpoint: string,
url: string,
): Promise<T | ApiResponse<T> | AstrBotApiResponse<T>> {
const contentType = response.headers.get("content-type") ?? ""
const isJson = contentType.includes("application/json") || contentType.includes("+json")
if (!isJson) {
const preview = (await response.text()).slice(0, 240)
throw new ApiClientError("invalid_api_response", "接口返回了非 JSON 响应", {
endpoint,
transport: "direct-fetch",
url,
status: response.status,
status_text: response.statusText,
content_type: contentType,
preview,
})
}
try {
return (await response.json()) as T | ApiResponse<T> | AstrBotApiResponse<T>
} catch (err) {
throw new ApiClientError("invalid_api_response", "接口返回格式不正确", {
endpoint,
transport: "direct-fetch",
url,
status: response.status,
status_text: response.statusText,
content_type: contentType,
reason: err instanceof Error ? err.message : String(err),
})
}
}
function isApiResponse(payload: unknown): payload is ApiResponse<unknown> {
if (!payload || typeof payload !== "object" || !("ok" in payload) || typeof payload.ok !== "boolean") {
return false
}
return payload.ok ? "data" in payload : "error_code" in payload && "message" in payload
}
function isAstrBotApiResponse(payload: unknown): payload is AstrBotApiResponse<unknown> {
if (!payload || typeof payload !== "object" || !("status" in payload)) {
return false
}
return payload.status === "error" || (payload.status === "ok" && "data" in payload)
}
function bridgeErrorDetails(data: unknown): Record<string, unknown> {
return data && typeof data === "object" ? { bridge_data: data } : {}
}
function compactQuery(query?: Record<string, string | number | boolean | undefined>): Record<string, unknown> | undefined {
if (!query) {
return undefined
}
const compacted: Record<string, unknown> = {}
for (const [key, value] of Object.entries(query)) {
if (value !== undefined) {
compacted[key] = value
}
}
return compacted
}
export function buildUrl(endpoint: string, query?: Record<string, string | number | boolean | undefined>) {
const trimmed = endpoint.replace(/^\/+/, "")
const url = new URL(`${API_BASE}/${trimmed}`, window.location.origin)
for (const [key, value] of Object.entries(query ?? {})) {
if (value !== undefined) {
url.searchParams.set(key, String(value))
}
}
return `${url.pathname}${url.search}`
}