const CHANNEL = "astrbot-plugin-page" const READY_RETRY_MS = 250 const DEFAULT_REQUEST_TIMEOUT_MS = 30000 const LONG_TASK_REQUEST_TIMEOUT_MS = 300000 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 PendingRequest = { resolve(value: unknown): void reject(error: Error): void timer: ReturnType } type BridgeMessage = { channel?: string kind?: string requestId?: string ok?: boolean data?: unknown error?: unknown } function toPostMessagePayload(payload: unknown): unknown { if (payload === undefined) return {} try { // Vue exposes settings drafts as reactive Proxy objects. Browsers cannot // structured-clone those objects for postMessage, while the bridge API is // JSON-only. Serializing here removes Proxy wrappers and also matches the // direct-fetch transport's JSON request semantics. const serialized = JSON.stringify(payload, (_key, value) => typeof value === "bigint" ? value.toString() : value, ) return serialized === undefined ? {} : JSON.parse(serialized) } catch (error) { const reason = error instanceof Error ? error.message : String(error) throw new Error(`AstrBot plugin bridge payload is not JSON serializable: ${reason}`) } } export function installAstrBotPluginPageBridge() { if (typeof window === "undefined" || window.parent === window) return const pending = new Map() let ready = false let readyTimer: ReturnType | undefined let resolveReady: (() => void) | undefined const readyPromise = new Promise((resolve) => { resolveReady = resolve }) const postReady = () => { window.parent.postMessage({ channel: CHANNEL, kind: "ready" }, "*") } const markReady = () => { if (ready) return ready = true if (readyTimer !== undefined) { window.clearInterval(readyTimer) readyTimer = undefined } resolveReady?.() } const onMessage = (event: MessageEvent) => { if (event.source !== window.parent) return const message = event.data if (!message || message.channel !== CHANNEL) return if (message.kind === "context") { markReady() return } if (message.kind !== "response" || !message.requestId) return const request = pending.get(message.requestId) if (!request) return pending.delete(message.requestId) window.clearTimeout(request.timer) if (message.ok) { request.resolve(message.data) } else { request.reject(new Error(typeof message.error === "string" ? message.error : "AstrBot plugin bridge request failed")) } } const request = async (action: "api:get" | "api:post", endpoint: string, payload?: unknown): Promise => { await readyPromise const requestId = `imagestudio_${Date.now()}_${Math.random().toString(36).slice(2)}` const cloneablePayload = toPostMessagePayload(payload) return new Promise((resolve, reject) => { const timeoutMs = action === "api:post" && LONG_TASK_ENDPOINT.test(endpoint) ? LONG_TASK_REQUEST_TIMEOUT_MS : DEFAULT_REQUEST_TIMEOUT_MS const timer = window.setTimeout(() => { pending.delete(requestId) reject(new Error(`AstrBot plugin bridge request timed out after ${Math.round(timeoutMs / 1000)} seconds: ${endpoint}`)) }, timeoutMs) pending.set(requestId, { resolve: (value) => resolve(value as T), reject, timer, }) window.parent.postMessage( { channel: CHANNEL, kind: "request", requestId, action, endpoint, ...(action === "api:get" ? { params: cloneablePayload } : { body: cloneablePayload }), }, "*", ) }) } window.addEventListener("message", onMessage) window.AstrBotPluginPage = { ready: () => readyPromise, apiGet: (path: string, params?: Record) => request("api:get", path, params), apiPost: (path: string, body?: unknown) => request("api:post", path, body), } postReady() readyTimer = window.setInterval(postReady, READY_RETRY_MS) }