api.ts 3.69 KB
import type {
  Job,
  ServerConfigView,
  GenerateRequest,
  GenerateResponse,
  PreviewState,
  LogEntry,
  SystemStatus,
  ProjectProfile,
  FsListResult,
} from './types';

// 同源调用:开发时由 Vite 代理到后端 :4173;生产时后端直接托管本应用。
const BASE = '';

async function http<T>(path: string, init?: RequestInit): Promise<T> {
  const res = await fetch(BASE + path, {
    ...init,
    headers: { 'Content-Type': 'application/json', ...(init?.headers ?? {}) },
  });
  const text = await res.text();
  const data = text ? JSON.parse(text) : null;
  if (!res.ok) {
    throw new Error(data?.error || `请求失败 (${res.status})`);
  }
  return data as T;
}

export const api = {
  getConfig: () => http<ServerConfigView>('/api/config'),
  generate: (req: GenerateRequest) =>
    http<GenerateResponse>('/api/generate', {
      method: 'POST',
      body: JSON.stringify(req),
    }),
  listJobs: () => http<{ jobs: Job[] }>('/api/jobs'),
  getJob: (id: string) => http<Job>(`/api/job/${id}`),
  getLogs: () => http<{ logs: LogEntry[] }>('/api/logs'),
  cancelJob: (id: string) =>
    http<{ ok: boolean }>(`/api/jobs/${id}/cancel`, { method: 'POST' }),
  deleteJob: (id: string) =>
    http<{ ok: boolean }>(`/api/jobs/${id}`, { method: 'DELETE' }),
  clearJobs: () =>
    http<{ ok: boolean; count: number }>('/api/jobs', { method: 'DELETE' }),
  getPreview: () => http<PreviewState>('/api/preview'),
  startPreview: (appPath?: string) =>
    http<{ ok: boolean; error?: string }>('/api/preview', {
      method: 'POST',
      body: JSON.stringify({ appPath }),
    }),
  stopPreview: () =>
    http<{ ok: boolean }>('/api/preview/stop', { method: 'POST' }),
  restartPreview: () =>
    http<{ ok: boolean; error?: string }>('/api/preview/restart', { method: 'POST' }),
  getStatus: () => http<SystemStatus>('/api/admin/status'),
  restartServer: () =>
    http<{ ok: boolean }>('/api/admin/restart', { method: 'POST' }),
  shutdownServer: () =>
    http<{ ok: boolean }>('/api/admin/shutdown', { method: 'POST' }),
  getProjectProfile: () =>
    http<{ exists: boolean; profile: ProjectProfile }>('/api/project-profile'),
  putProjectProfile: (profile: ProjectProfile) =>
    http<{ ok: boolean; profile: ProjectProfile }>('/api/project-profile', {
      method: 'PUT',
      body: JSON.stringify(profile),
    }),
  scanProjectProfile: (rootDir: string) =>
    http<{ profile: ProjectProfile; pages: string[]; warnings: string[] }>(
      '/api/project-profile/scan',
      { method: 'POST', body: JSON.stringify({ rootDir }) },
    ),
  fsList: (dir?: string) =>
    http<FsListResult>(
      '/api/fs/list' + (dir ? `?dir=${encodeURIComponent(dir)}` : ''),
    ),
};

export type SSEEventName = 'log' | 'jobs' | 'preview' | string;

export interface SSEPayload {
  event: SSEEventName;
  data: unknown;
}

/**
 * 订阅后端 SSE 流(/api/stream)。后端会推送三种事件:
 *  - log:   实时引擎日志 (LogEntry)
 *  - jobs:  任务列表快照 (Job[]),每次状态变更都会重发
 *  - preview: 预览服务状态 (PreviewState)
 * 返回取消订阅函数。
 */
export function subscribeSSE(
  onMessage: (msg: SSEPayload) => void,
  onError?: (e: Event) => void,
): () => void {
  const es = new EventSource('/api/stream');
  const handle = (name: SSEEventName) => (e: MessageEvent) => {
    try {
      onMessage({ event: name, data: JSON.parse(e.data) });
    } catch {
      /* ignore malformed */
    }
  };
  es.addEventListener('log', handle('log') as EventListener);
  es.addEventListener('jobs', handle('jobs') as EventListener);
  es.addEventListener('preview', handle('preview') as EventListener);
  es.onerror = (e) => {
    onError?.(e);
  };
  return () => es.close();
}

export type { LogEntry, Job };