generate.ts
2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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} 个任务` : '开始生成',
});
},
},
];