generate.ts 2.28 KB
import path from 'node:path';
import { GenerateSchema } from '@coderio/shared';
import type { Route } from './context';
import type { Job } from '../types';

/**
 * POST /api/generate:核心入口,提交一次 Figma 转代码任务。
 * 入参 schema(GenerateSchema)由 @coderio/shared 统一提供,前后端共用同一契约。
 */
export const generateRoutes: Route[] = [
    {
        method: 'POST',
        path: '/api/generate',
        handle: async ({ ctx, req, res }) => {
            // 读体 + zod 校验一体完成;失败抛 ValidationError(全局返回 400)
            const body = await ctx.parseJsonBody(req, GenerateSchema);
            const { figmaUrl, mode, outputDir, appName, target, stack, fillContainer } = body;

            // 记录本次生成采用的模型(用于前端任务卡片与日志展示)
            const activeModel = ctx.model;
            const isLocalModel = /11434|localhost|127\.0\.0\.1/.test(activeModel.baseUrl ?? '');

            // 构造 Job 对象:默认 queued 状态,记录输出目录、应用名、目标栈等参数
            const job: Job = {
                id: `job-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
                status: 'queued',
                figmaUrl,
                mode,
                outputDir: outputDir ? path.resolve(outputDir) : ctx.opts.outputDir,
                appName,
                target: target ?? null,
                stack: stack ?? null,
                fillContainer,
                phase: null,
                progress: 0,
                model: activeModel.model ?? null,
                modelSource: isLocalModel ? 'local' : 'external',
                resultDir: null,
                reportPath: null,
                error: null,
                pid: null,
                createdAt: new Date().toISOString(),
                startedAt: null,
                finishedAt: null,
            };
            ctx.queue.submit(job); // 入队
            const position = ctx.queue.position(job.id); // 查询队列位置
            ctx.sendJson(res, 200, {
                jobId: job.id,
                position,
                message:
                    position > 0 ? `已加入队列,前方还有 ${position} 个任务` : '开始生成',
            });
        },
    },
];