vue.post.ts
2.67 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { parseFigmaUrl, fetchFigmaFile, buildDSL } from '../../utils/figmaParser'
import { dslToVueSFC } from '../../utils/vueGenerator'
import { generateVueWithAI, isAiConfigured, type AIConfig } from '../../utils/aiGenerator'
import type { VueGenerateResult } from '../../utils/types'
/**
* POST /api/figma/vue
* 输入:{ figmaUrl: string; componentName?: string; prompt?: string }
* 输出:VueGenerateResult { dsl, vue: { componentName, code, source } }
*
* 生成策略:
* 1. 若配置了 AI_API_KEY → 优先使用 AI 生成
* 2. AI 失败 → 自动降级到规则引擎
* 3. 未配置 AI → 直接使用规则引擎
*/
export default defineEventHandler(async (event) => {
const body = await readBody<{
figmaUrl?: string
componentName?: string
prompt?: string
}>(event)
const { figmaUrl, componentName = 'GeneratedComponent', prompt } = body ?? {}
if (!figmaUrl?.trim()) {
throw createError({ statusCode: 400, message: '请提供有效的 figmaUrl 参数' })
}
const config = useRuntimeConfig()
const token = config.figmaToken as string
if (!token) {
throw createError({
statusCode: 500,
message: '服务端未配置 FIGMA_PERSONAL_ACCESS_TOKEN,请在 .env 文件中设置',
})
}
try {
// 1. 解析 Figma URL 并拉取设计数据
const { fileKey, nodeId } = parseFigmaUrl(figmaUrl)
const figmaData = await fetchFigmaFile(fileKey, token, nodeId)
const dsl = buildDSL(figmaData, fileKey, nodeId)
// 2. 生成 Vue SFC(AI 优先,规则引擎兜底)
let vueCode: string
let source: 'ai' | 'rule' = 'rule'
const aiConfig: AIConfig = {
apiKey: (config.aiApiKey as string) || '',
baseUrl: (config.aiBaseUrl as string) || 'https://api.openai.com/v1',
model: (config.aiModel as string) || 'gpt-4o-mini',
}
if (isAiConfigured(aiConfig)) {
try {
vueCode = await generateVueWithAI(dsl.root, componentName, aiConfig, prompt)
source = 'ai'
console.log(`[D2C] AI 生成成功,模型:${aiConfig.model}`)
} catch (aiErr) {
console.warn('[D2C] AI 生成失败,自动降级到规则引擎:', aiErr)
vueCode = dslToVueSFC(dsl.root, { componentName })
}
} else {
vueCode = dslToVueSFC(dsl.root, { componentName })
console.log('[D2C] 未配置 AI,使用规则引擎生成')
}
const result: VueGenerateResult = {
dsl,
vue: {
componentName,
code: vueCode,
source,
},
}
return result
} catch (err: unknown) {
const message = err instanceof Error ? err.message : '生成 Vue 代码失败'
throw createError({ statusCode: 500, message })
}
})