import type { WorkbenchState } from '../types/state'; import type { EditPreviewRequest, EditPreviewResponse, EditSelection, EditStateResponse, SaveEditsRequest, SaveEditsResponse, } from '../edit/types'; /** Carries the status and parsed body so callers can branch on 409 rather than on message text. */ export class ApiError extends Error { constructor( message: string, readonly status: number, readonly body: unknown, ) { super(message); this.name = 'ApiError'; } } async function request(path: string, init?: RequestInit): Promise { const response = await fetch(path, { cache: 'no-store', ...init }); // Read as text first. A dead backend behind the dev proxy answers with an empty // body, and `response.json()` then throws "Unexpected end of JSON input" — // which says nothing about the actual problem. const text = await response.text(); if (!text) throw new ApiError(`${path} 返回空响应(HTTP ${response.status}),后端可能未启动`, response.status, null); let value: T & { ok?: boolean; error?: string }; try { value = JSON.parse(text) as T & { ok?: boolean; error?: string }; } catch { throw new ApiError(`${path} 返回了非 JSON 响应(HTTP ${response.status})`, response.status, text); } if (!response.ok || value.ok === false) throw new ApiError(value.error || `HTTP ${response.status}`, response.status, value); return value; } const json = (body: unknown, signal?: AbortSignal): RequestInit => ({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), ...(signal ? { signal } : {}), }); /** A save lost the single-writer race; `body.current.documentVersion` holds the server's version. */ export function isVersionConflict(error: unknown): error is ApiError { return error instanceof ApiError && error.status === 409; } export const api = { state: () => request('/api/state'), import: (file: File) => { const body = new FormData(); body.append('file', file, file.name); return request('/api/import', { method: 'POST', body }); }, overrides: (overrides: unknown[]) => request<{ overrides: WorkbenchState['overrides'] }>( '/api/overrides', json({ schema: 'native-road-overrides/v1', overrides }), ), compile: () => request('/api/compile', { method: 'POST' }), signals: (document: unknown) => request>('/api/traffic-signals', json(document)), generateSignals: () => request>('/api/traffic-signals/generate', { method: 'POST', }), acceptJunctionCandidate: (index: number) => request('/api/junction-clusters', json({ index })), // Direct-edit endpoints used by the in-page browser/edit switch. editState: (selection?: EditSelection) => { const query = selection ? `?${new URLSearchParams(selection as Record)}` : ''; return request(`/api/edit-state${query}`); }, /** * `signal` comes from the caller's AbortController: the request layer only * sends and cancels, while `EditSession` decides which responses to keep. */ editPreview: (body: EditPreviewRequest, signal?: AbortSignal) => request('/api/edit-preview', json(body, signal)), /** Throws an `ApiError` with status 409 when another writer moved the version. */ saveEdits: (body: SaveEditsRequest) => request('/api/edits', json(body)), };