export function api(path: string) { return `${import.meta.env.BASE_URL}api/${path.replace(/^\/+/, '')}` } const KEY_STORE = 'cut-admin-key' export function getAdminKey() { try { return localStorage.getItem(KEY_STORE) || '' } catch { return '' } } export function setAdminKey(key: string) { try { if (key) localStorage.setItem(KEY_STORE, key) else localStorage.removeItem(KEY_STORE) } catch { /* private mode */ } } export class ApiError extends Error { status: number needsKey: boolean constructor(message: string, status: number, needsKey = false) { super(message) this.status = status this.needsKey = needsKey } } /** JSON request helper; sends the saved admin key and turns error bodies into ApiError. */ export async function request(path: string, init: { method?: string; body?: unknown } = {}): Promise { const headers: Record = {} const key = getAdminKey() if (key) headers['x-admin-key'] = key if (init.body !== undefined) headers['content-type'] = 'application/json' const res = await fetch(api(path), { method: init.method || (init.body !== undefined ? 'POST' : 'GET'), headers, body: init.body !== undefined ? JSON.stringify(init.body) : undefined, }) let body: any = null try { body = await res.json() } catch { /* empty body */ } if (!res.ok) throw new ApiError(body?.error || `请求失败(${res.status})`, res.status, Boolean(body?.needsKey)) return body as T }