preview.ts 2.76 KB
import path from 'node:path';
import { parseFigmaUrl } from 'coderio';
import type { Route } from './context';
import { PreviewManager } from '../preview';

/** 生成结果预览服务:状态、启动、停止、重启。 */
export const previewRoutes: Route[] = [
    // ---- GET /api/preview:查询预览服务状态 ----
    {
        method: 'GET',
        path: '/api/preview',
        handle: ({ ctx, res }) => {
            ctx.sendJson(res, 200, ctx.preview.state);
        },
    },

    // ---- POST /api/preview(启动预览)----
    {
        method: 'POST',
        path: '/api/preview',
        handle: async ({ ctx, req, res }) => {
            let body: { appPath?: string } = {};
            try {
                body = await ctx.readJsonBody<{ appPath?: string }>(req);
            } catch {
                /* 忽略解析失败,使用默认解析 */
            }
            // 解析生成的 app 目录:优先用最新完成任务的 Figma URL 重新解析(见下方说明),
            // 而非信任持久化的 resultDir——后者由 server 进程在 spawn 时计算,若 coderio
            // 包在 server 启动后被重建(开发期常见),存储值可能与引擎实际创建目录不一致,
            // 导致 preview 找不到 my-app。仅在 URL 解析失败时才回退到存储值。
            const latestDone = ctx.store.list().find((j) => j.status === 'done' && j.figmaUrl);
            let resolvedDir: string | null = null;
            if (latestDone?.figmaUrl) {
                try {
                    const projectName = parseFigmaUrl(latestDone.figmaUrl).projectName;
                    if (projectName) {
                        resolvedDir = path.resolve(ctx.opts.outputDir, 'coderio', projectName);
                    }
                } catch {
                    resolvedDir = null;
                }
            }
            if (!resolvedDir && latestDone?.resultDir) {
                resolvedDir = latestDone.resultDir;
            }
            const appPath = body.appPath || PreviewManager.defaultAppPath(resolvedDir);
            const r = ctx.preview.start(appPath);
            ctx.sendJson(res, r.ok ? 200 : 409, { ok: r.ok, error: r.error });
        },
    },

    // ---- POST /api/preview/stop:停止预览 ----
    {
        method: 'POST',
        path: '/api/preview/stop',
        handle: ({ ctx, res }) => {
            ctx.preview.stop();
            ctx.sendJson(res, 200, { ok: true });
        },
    },

    // ---- POST /api/preview/restart:重启预览 ----
    {
        method: 'POST',
        path: '/api/preview/restart',
        handle: ({ ctx, res }) => {
            const r = ctx.preview.restart();
            ctx.sendJson(res, r.ok ? 200 : 409, { ok: r.ok, error: r.error });
        },
    },
];