import { API_BASE } from "./endpoints" 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_REQUEST_TIMEOUT_MS = 5000 type PluginBridge = NonNullable export class ApiClientError extends Error { readonly code: string readonly details: Record constructor(code: string, message: string, details: Record = {}) { super(message) this.name = "ApiClientError" this.code = code this.details = details } } export async function getJson(endpoint: string, query?: Record) { return request(endpoint, { method: "GET", query }) } export async function postJson(endpoint: string, body?: unknown) { return request(endpoint, { method: "POST", body }) } export async function putJson(endpoint: string, body?: unknown) { return request(endpoint, { method: "PUT", body }) } export async function patchJson(endpoint: string, body?: unknown) { return request(endpoint, { method: "PATCH", body }) } export async function deleteJson(endpoint: string, body?: unknown) { return request(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( endpoint: string, options: { method?: ApiMethod query?: Record body?: unknown } = {}, ): Promise { const bridge = await pluginBridgeForRequest() if (bridge) { const bridgePayload = await requestViaPluginBridge(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(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( bridge: PluginBridge, endpoint: string, options: { method?: ApiMethod query?: Record body?: unknown }, ): Promise | AstrBotApiResponse | 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 | AstrBotApiResponse>(endpoint, compactQuery(options.query)), PLUGIN_BRIDGE_REQUEST_TIMEOUT_MS, "AstrBot Plugin Page GET request timed out", ) } if (method === "POST" && typeof bridge.apiPost === "function") { return withClientTimeout( bridge.apiPost | AstrBotApiResponse>(endpoint, options.body), PLUGIN_BRIDGE_REQUEST_TIMEOUT_MS, "AstrBot Plugin Page POST request timed out", ) } if (method === "PUT" && typeof bridge.apiPut === "function") { return bridge.apiPut | AstrBotApiResponse>(endpoint, options.body) } if (method === "PATCH" && typeof bridge.apiPatch === "function") { return bridge.apiPatch | AstrBotApiResponse>(endpoint, options.body) } if (method === "DELETE" && typeof bridge.apiDelete === "function") { return bridge.apiDelete | AstrBotApiResponse>(endpoint) } if (["PUT", "PATCH", "DELETE"].includes(method) && typeof bridge.apiPost === "function") { return bridge.apiPost | AstrBotApiResponse>(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", }) } async function pluginBridgeForRequest(): Promise { 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((resolve) => window.setTimeout(resolve, 100)) if (window.AstrBotPluginPage) return window.AstrBotPluginPage } return undefined } function withClientTimeout(promise: Promise, timeoutMs: number, message: string): Promise { 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(payload: T | ApiResponse | AstrBotApiResponse): 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( response: Response, endpoint: string, url: string, ): Promise | AstrBotApiResponse> { 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 | AstrBotApiResponse } 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 { 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 { 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 { return data && typeof data === "object" ? { bridge_data: data } : {} } function compactQuery(query?: Record): Record | undefined { if (!query) { return undefined } const compacted: Record = {} for (const [key, value] of Object.entries(query)) { if (value !== undefined) { compacted[key] = value } } return compacted } export function buildUrl(endpoint: string, query?: Record) { 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}` }