248 行
8.5 KiB
TypeScript
248 行
8.5 KiB
TypeScript
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"
|
||
|
||
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 hasPluginBridge = typeof window !== "undefined" && Boolean(window.AstrBotPluginPage)
|
||
const bridgePayload = await requestViaPluginBridge<T>(endpoint, options)
|
||
if (hasPluginBridge) {
|
||
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>(
|
||
endpoint: string,
|
||
options: {
|
||
method?: ApiMethod
|
||
query?: Record<string, string | number | boolean | undefined>
|
||
body?: unknown
|
||
},
|
||
): Promise<T | ApiResponse<T> | AstrBotApiResponse<T> | undefined> {
|
||
const bridge = window.AstrBotPluginPage
|
||
if (!bridge) {
|
||
return undefined
|
||
}
|
||
const method = options.method ?? "GET"
|
||
if (typeof bridge.ready === "function") {
|
||
await bridge.ready()
|
||
}
|
||
if (method === "GET" && typeof bridge.apiGet === "function") {
|
||
return bridge.apiGet<T | ApiResponse<T> | AstrBotApiResponse<T>>(endpoint, compactQuery(options.query))
|
||
}
|
||
if (method === "POST" && typeof bridge.apiPost === "function") {
|
||
return bridge.apiPost<T | ApiResponse<T> | AstrBotApiResponse<T>>(endpoint, options.body)
|
||
}
|
||
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 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}`
|
||
}
|