ai-direct-context.mjs
22.8 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
#!/usr/bin/env node
import fs from "node:fs";
import path from "node:path";
import process from "node:process";
import { loadComponentManifest } from "../packages/ai/design-mapper/src/index.mjs";
import { readProjectContext, toJson as toPrettyJson } from "../packages/ai/project-intelligence/src/index.mjs";
import {
fetchDesignContext,
fetchScreenshot,
fetchVariableDefs,
isMcpAvailable,
parseFigmaUrl,
} from "./mcp-bridge/figma-client.mjs";
import { requireWorkspaceRoot } from "./workspace-root.mjs";
const repoRoot = requireWorkspaceRoot();
const KNOWN_PROJECT_UI_PACKAGES = ["@vui/vue", "@vui/react", "@vui/uniapp", "element-plus", "ant-design-vue", "antd"];
const WORKSPACE_PACKAGE_ROOTS = {
"@vui/vue": "packages/vui/vue",
"@vui/react": "packages/vui/react",
"@vui/uniapp": "packages/vui/uniapp",
};
const FRAMEWORK_UI_RULES = {
vue: {
preferredVuiPackage: "@vui/vue",
fallbackPackages: ["element-plus"],
cliTemplate: "vue",
cliUiOption: "element-plus",
},
"micro-frontend": {
preferredVuiPackage: "@vui/vue",
fallbackPackages: ["element-plus"],
cliTemplate: "vue",
cliUiOption: "element-plus",
},
react: {
preferredVuiPackage: "@vui/react",
fallbackPackages: ["antd"],
cliTemplate: "react",
cliUiOption: "antd",
},
uniappX: {
preferredVuiPackage: "@vui/uniapp",
fallbackPackages: [],
cliTemplate: "",
cliUiOption: "",
},
unknown: {
preferredVuiPackage: "",
fallbackPackages: [],
cliTemplate: "",
cliUiOption: "",
},
};
function parseCliArgs() {
const args = process.argv.slice(2);
const parsed = {
projectDir: "",
figmaUrl: "",
pageName: "",
pageTitle: "",
outputDir: "",
withoutScreenshot: false,
withoutVariables: false,
};
for (let index = 0; index < args.length; index++) {
const arg = args[index];
const next = args[index + 1];
if (arg === "--project-dir" && next) {
parsed.projectDir = next;
index++;
} else if (arg === "--figma-url" && next) {
parsed.figmaUrl = next;
index++;
} else if (arg === "--page-name" && next) {
parsed.pageName = next;
index++;
} else if (arg === "--page-title" && next) {
parsed.pageTitle = next;
index++;
} else if (arg === "--output-dir" && next) {
parsed.outputDir = next;
index++;
} else if (arg === "--without-screenshot") {
parsed.withoutScreenshot = true;
} else if (arg === "--without-variables") {
parsed.withoutVariables = true;
}
}
return parsed;
}
function readJson(filePath) {
return JSON.parse(fs.readFileSync(filePath, "utf8"));
}
function ensureDir(targetDir) {
fs.mkdirSync(targetDir, { recursive: true });
}
function fileExists(targetPath) {
return fs.existsSync(targetPath);
}
function normalizePath(targetPath) {
return targetPath.replaceAll("\\", "/");
}
function screenshotExtensionForMimeType(mimeType) {
switch (String(mimeType || "").toLowerCase()) {
case "image/jpeg":
case "image/jpg": {
return ".jpg";
}
case "image/webp": {
return ".webp";
}
default: {
return ".png";
}
}
}
function toRelativeSchemaPath(fromDir, targetFile) {
return normalizePath(path.relative(fromDir, targetFile));
}
function slugify(value) {
const normalized = String(value || "")
.trim()
.toLowerCase()
.replaceAll(/[^a-z0-9]+/g, "-")
.replaceAll(/^-+|-+$/g, "");
return normalized || "figma-page";
}
function toPascalCase(value) {
return (
String(value || "")
.split(/[^a-z0-9]+/gi)
.filter(Boolean)
.map((token) => token.charAt(0).toUpperCase() + token.slice(1).toLowerCase())
.join("") || "FigmaPage"
);
}
function derivePageTitle(figmaUrl) {
try {
const url = new URL(figmaUrl);
const parts = url.pathname.split("/").filter(Boolean);
const rawTitle = parts[2] || parts.at(-1) || "Figma Page";
return decodeURIComponent(rawTitle);
} catch {
return "Figma Page";
}
}
function derivePageName(pageName, pageTitle, figmaUrl) {
if (pageName) {
return pageName;
}
const title = pageTitle || derivePageTitle(figmaUrl);
return toPascalCase(title);
}
function deriveOutputDir(projectDir, outputDir, pageSlug) {
if (outputDir) {
return path.isAbsolute(outputDir) ? outputDir : path.resolve(projectDir, outputDir);
}
return path.join(projectDir, ".ai-direct", pageSlug);
}
function normalizeFramework(projectContext) {
const framework = projectContext.framework || "unknown";
if (FRAMEWORK_UI_RULES[framework]) {
return framework;
}
if (framework === "vue" || framework === "react" || framework === "uniappX") {
return framework;
}
return "unknown";
}
function getFrameworkUiRule(projectContext) {
return FRAMEWORK_UI_RULES[normalizeFramework(projectContext)] || FRAMEWORK_UI_RULES.unknown;
}
function resolveManifestPathByPackage(packageName) {
const manifestByPackage = {
"@vui/vue": path.join(repoRoot, "packages/vui/vue/meta/index.json"),
"element-plus": path.join(repoRoot, "contracts/ai/element-plus.manifest.json"),
antd: path.join(repoRoot, "contracts/ai/antd.manifest.json"),
"ant-design-vue": path.join(repoRoot, "contracts/ai/ant-design-vue.manifest.json"),
};
const candidate = manifestByPackage[packageName];
if (!candidate || !fileExists(candidate)) {
return "";
}
return candidate;
}
function buildEmptyCatalog(packageName, framework, reason) {
return {
packageName,
framework,
notes: reason,
projectInstalled: false,
components: [],
};
}
function extractDependencies(projectDir) {
const packageJsonPath = path.join(projectDir, "package.json");
const packageJson = readJson(packageJsonPath);
return {
packageJson,
allDependencies: {
...packageJson.dependencies,
...packageJson.devDependencies,
},
};
}
function detectProjectUiPackages(allDependencies) {
return KNOWN_PROJECT_UI_PACKAGES.filter((pkg) => Boolean(allDependencies[pkg]));
}
function resolveWorkspacePackageRoot(packageName) {
const relativeRoot = WORKSPACE_PACKAGE_ROOTS[packageName];
if (!relativeRoot) {
return "";
}
const absoluteRoot = path.join(repoRoot, relativeRoot);
return fileExists(absoluteRoot) ? absoluteRoot : "";
}
function collectExportsFromSource(sourceText) {
const exportNames = new Set();
const matches = sourceText.matchAll(/export\s+\{\s*(?:default\s+as\s+)?(\w+)\s*\}\s+from/g);
for (const match of matches) {
exportNames.add(match[1]);
}
return [...exportNames];
}
function readWorkspacePackageExports(packageName) {
const packageRoot = resolveWorkspacePackageRoot(packageName);
if (!packageRoot) {
return null;
}
const packageJsonPath = path.join(packageRoot, "package.json");
const packageJson = readJson(packageJsonPath);
const sourceFiles = [
path.join(packageRoot, "src", "index.ts"),
path.join(packageRoot, "src", "components", "index.ts"),
].filter((filePath) => fileExists(filePath));
const exportNames = new Set();
for (const filePath of sourceFiles) {
const sourceText = fs.readFileSync(filePath, "utf8");
for (const exportName of collectExportsFromSource(sourceText)) {
exportNames.add(exportName);
}
}
return {
packageName,
packageRoot: normalizePath(path.relative(repoRoot, packageRoot)),
exportNames: [...exportNames].sort(),
version: packageJson.version || "0.0.0",
};
}
function summarizeComponent(component, manifestPackageName, projectUiPackages) {
return {
exportName: component.exportName,
category: component.category || "",
description: component.description || "",
source: component.source || "",
semanticRoles: component.semanticRoles || [],
supportedKinds: component.supportedKinds || [],
supportedActionKinds: component.supportedActionKinds || [],
supportedFieldTypes: component.supportedFieldTypes || [],
supportedScopes: component.supportedScopes || [],
props: (component.props || []).map((prop) => ({
name: prop.name,
type: prop.type || "",
description: prop.description || "",
})),
events: (component.events || []).map((event) => ({
name: event.name,
payload: event.payload || "",
description: event.description || "",
})),
slots: (component.slots || []).map((slot) => ({
name: slot.name,
description: slot.description || "",
})),
usageGuidance: component.usageGuidance || {},
figmaMapping: component.figmaMapping || {},
packageInstalledInProject: projectUiPackages.includes(manifestPackageName),
};
}
function buildManifestCatalog(manifest, projectUiPackages) {
return {
packageName: manifest.packageName,
framework: manifest.framework,
notes: manifest.notes || "",
projectInstalled: projectUiPackages.includes(manifest.packageName),
components: (manifest.components || []).map((component) =>
summarizeComponent(component, manifest.packageName, projectUiPackages),
),
};
}
function buildSelectionRules({ projectContext, projectUiPackages, workspaceExports }) {
const uiRule = getFrameworkUiRule(projectContext);
const framework = normalizeFramework(projectContext);
const preferredVuiPackage = uiRule.preferredVuiPackage;
const fallbackPackages = uiRule.fallbackPackages;
const preferredPackageExports =
workspaceExports.find((pkg) => pkg.packageName === preferredVuiPackage)?.exportNames || [];
const installedPreferredPackage = preferredVuiPackage && projectUiPackages.includes(preferredVuiPackage);
const componentSelection = [
"优先复用项目当前已安装且已导出的 UI 组件,不要为了贴近设计稿随意引入一个项目里没有的组件包。",
`当前框架按规则必须把 \`${preferredVuiPackage || "VUI"}\` 作为第一顺位组件体系。`,
"生成代码时必须基于组件 manifest 的 props、events、slots 和 usageGuidance,而不是凭印象猜组件。",
];
if (preferredVuiPackage) {
componentSelection.push(
installedPreferredPackage
? `项目已安装 \`${preferredVuiPackage}\`,AI 必须优先使用该包的组件;只有确认不覆盖目标场景时才允许降级。`
: `项目当前未安装 \`${preferredVuiPackage}\`。若要使用 VUI,AI 必须显式提出依赖补齐;若本次不调整依赖,再按框架规则降级。`,
);
}
if (preferredPackageExports.length > 0) {
componentSelection.push(
`${preferredVuiPackage} 当前可见导出组件: ${preferredPackageExports.join(", ")}。不得写出超出当前可见导出的组件 import。`,
);
}
if (fallbackPackages.length > 0) {
componentSelection.push(
`如果 ${preferredVuiPackage || "VUI"} 无法覆盖当前设计场景,按框架降级到: ${fallbackPackages.join(", ")}。降级组件只作为第二顺位,不能默认优先使用。`,
);
}
return {
framework,
preferredVuiPackage,
fallbackPackages,
enforcement: {
mustUseVuiFirst: Boolean(preferredVuiPackage),
allowedFallbacks: fallbackPackages,
},
previewProjectPolicy: {
mustUseVenusCli: true,
cliTemplate: uiRule.cliTemplate,
cliUiOption: uiRule.cliUiOption,
},
componentSelection,
generationConstraints: [
"页面生成由 AI 直接完成,Venus 不再负责中间映射裁决。",
"生成结果必须尽量保持设计结构,但优先保证组件选型与项目现有依赖一致。",
"页面级视觉和布局必须在本次生成产物内一并完成,不得依赖人工再到预览产物里补样式。",
"若设计稿表达与现有组件能力冲突,应先保证结构和交互合理,再在说明中标记差异点。",
"如果某个设计元素无法稳定映射到现有组件,优先退回基础容器和简单 DOM,而不是选择一个语义错误的复杂组件。",
"生成预览项目时必须使用 Venus CLI 创建项目骨架,不得手工新建一套独立脚手架。",
"不得假设预览项目壳层会额外提供业务页所需的头图、渐变背景、导航或布局补丁,页面应自带完整容器、间距、尺寸和必要样式。",
],
validationGoals: [
"通过 lint、typecheck、template contract、review trigger 和 fitness 等根级质量门禁。",
"不得引入项目中不存在的组件 import。",
"不得绕过项目现有路由、目录和命名约定。",
"必须优先满足 VUI 第一顺位与按框架降级的规则。",
"预览项目必须基于 Venus CLI 生成的项目结构。",
"预览页面不能依赖模板演示壳层样式才能成立,生成文件本身应包含可运行的页面结构与样式。",
],
};
}
function buildAiPrompt({
projectContext,
projectUiPackages,
pageName,
pageTitle,
figmaUrl,
bundleFileName,
designContextFileName,
variableDefsFileName,
screenshotFileName,
workspaceExports,
selectionRules,
}) {
const framework = normalizeFramework(projectContext);
const preferredVui = selectionRules.preferredVuiPackage || "VUI";
const fallbacks = selectionRules.fallbackPackages;
const previewTemplate = selectionRules.previewProjectPolicy.cliTemplate;
const previewUiOption = selectionRules.previewProjectPolicy.cliUiOption;
const previewCommand =
previewTemplate && previewUiOption
? `pnpm exec venus create ${slugify(pageName)}-preview --template ${previewTemplate} --router --store --ui ${previewUiOption} --eslint --no-install`
: "";
const lines = [
"# AI Direct Generation Context",
"",
"## Task",
"",
`- Generate a page for \`${projectContext.projectName}\` (framework: \`${framework}\`).`,
`- Page name: \`${pageName}\``,
`- Page title: \`${pageTitle}\``,
`- Figma URL: ${figmaUrl}`,
"",
"## Required Inputs",
"",
`- Read \`${bundleFileName}\` first for project constraints and component facts.`,
`- Read \`${designContextFileName}\` as the raw Figma developer MCP context.`,
];
if (variableDefsFileName) {
lines.push(`- Read \`${variableDefsFileName}\` for design token and variable hints.`);
}
if (screenshotFileName) {
lines.push(`- Read \`${screenshotFileName}\` as the rendered screenshot context of the selected Figma node.`);
}
lines.push(
"",
"## Project UI Packages",
"",
`- Installed UI packages: ${projectUiPackages.join(", ") || "none detected"}`,
"",
"## Package Exports",
"",
);
for (const packageExport of workspaceExports) {
lines.push(
`- ${packageExport.packageName}: ${packageExport.exportNames.join(", ") || "no source exports detected"}`,
);
}
lines.push(
"",
"## Generation Rules",
"",
`- VUI is mandatory first choice: prefer \`${preferredVui}\` before any fallback UI library.`,
`- Framework fallback chain: ${fallbacks.length > 0 ? fallbacks.join(" -> ") : "none"}.`,
"- Do not import components from packages that are not installed in the target project unless you explicitly plan a dependency change.",
"- When a design element cannot be mapped confidently, keep structure simple and explain the gap instead of forcing a wrong component.",
"- Keep output aligned with the target project's routing, naming, and directory conventions.",
"- Preview project scaffolding must use Venus CLI. Do not handcraft a new scaffold.",
...(previewCommand ? [`- Recommended preview command: \`${previewCommand}\`.`] : []),
"",
"## Expected Output",
"",
"- A directly usable Vue page implementation.",
"- A brief note listing any dependency gaps or component capability gaps that block closer restoration.",
"",
);
return `${lines.join("\n")}\n`;
}
function buildBundle({
schemaReference,
figmaUrl,
projectContext,
projectUiPackages,
pageName,
pageTitle,
pageSlug,
designContext,
variableDefsFile,
screenshotFile,
screenshotSummaryFile,
designContextFile,
promptFile,
workspaceExports,
selectionRules,
vuiCatalog,
fallbackCatalogs,
}) {
const { fileKey, nodeId } = parseFigmaUrl(figmaUrl);
return {
$schema: schemaReference,
meta: {
generator: "scripts/ai-direct-context.mjs",
mode: "ai-direct",
generatedAt: new Date().toISOString(),
repoRoot: normalizePath(repoRoot),
},
figma: {
figmaUrl,
fileKey: fileKey || "",
nodeId: nodeId || "",
pageName,
pageTitle,
pageSlug,
designContextExcerpt: designContext.slice(0, 2400),
},
projectContext,
projectUi: {
projectInstalledPackages: projectUiPackages,
workspacePackageExports: workspaceExports,
},
componentFacts: {
preferredPackages: selectionRules.preferredVuiPackage ? [selectionRules.preferredVuiPackage] : [],
fallbackPackages: selectionRules.fallbackPackages,
vuiCatalog,
fallbackCatalogs,
},
rules: selectionRules,
artifacts: {
designContextFile: normalizePath(designContextFile),
variableDefsFile: variableDefsFile ? normalizePath(variableDefsFile) : "",
screenshotFile: screenshotFile ? normalizePath(screenshotFile) : "",
screenshotSummaryFile: screenshotSummaryFile ? normalizePath(screenshotSummaryFile) : "",
promptFile: normalizePath(promptFile),
},
};
}
async function run() {
const args = parseCliArgs();
if (!args.projectDir || !args.figmaUrl) {
console.error(
'用法: node scripts/ai-direct-context.mjs --project-dir ./apps/web/demo --figma-url "https://www.figma.com/design/..."',
);
process.exit(1);
}
const projectDir = path.resolve(args.projectDir);
if (!fileExists(projectDir)) {
console.error(`错误: 项目目录不存在: ${projectDir}`);
process.exit(1);
}
console.log("[ai-direct-context] Venus AI 直生上下文打包器");
console.log(` → 项目目录: ${projectDir}`);
console.log(` → Figma URL: ${args.figmaUrl}`);
console.log("\n[step 0] 检查 figma-developer-mcp...");
const mcpAvailable = await isMcpAvailable();
if (!mcpAvailable) {
console.error(" ✗ figma-developer-mcp 不可达,无法准备 AI 直生上下文。");
process.exit(1);
}
console.log(" ✓ figma-developer-mcp 可用");
const pageTitle = args.pageTitle || derivePageTitle(args.figmaUrl);
const pageName = derivePageName(args.pageName, pageTitle, args.figmaUrl);
const pageSlug = slugify(pageName);
const outputDir = deriveOutputDir(projectDir, args.outputDir, pageSlug);
ensureDir(outputDir);
console.log("\n[step 1] 拉取 Figma 设计上下文...");
const designContext = await fetchDesignContext(args.figmaUrl);
console.log(` ✓ design context: ${designContext.length} 字符`);
let screenshot = null;
if (!args.withoutScreenshot) {
console.log("\n[step 2] 拉取 Figma 截图上下文...");
try {
screenshot = await fetchScreenshot(args.figmaUrl);
console.log(` ✓ screenshot fetched (${screenshot.mimeType || "image/png"})`);
} catch (error) {
console.warn(` ⚠ 截图获取失败,继续生成上下文包: ${error.message}`);
}
}
let variableDefs = null;
if (!args.withoutVariables) {
console.log("\n[step 3] 拉取 Figma 变量定义...");
try {
variableDefs = await fetchVariableDefs(args.figmaUrl);
console.log(" ✓ variable definitions fetched");
} catch (error) {
console.warn(` ⚠ 变量定义获取失败,继续生成上下文包: ${error.message}`);
}
}
console.log("\n[step 4] 读取项目上下文与组件事实源...");
const projectContext = readProjectContext(projectDir);
const { allDependencies } = extractDependencies(projectDir);
const projectUiPackages = detectProjectUiPackages(allDependencies);
const selectionRules = buildSelectionRules({ projectContext, projectUiPackages, workspaceExports: [] });
const workspaceExports = [
readWorkspacePackageExports("@vui/vue"),
readWorkspacePackageExports("@vui/react"),
readWorkspacePackageExports("@vui/uniapp"),
].filter(Boolean);
const finalizedSelectionRules = buildSelectionRules({ projectContext, projectUiPackages, workspaceExports });
const preferredManifestPath = resolveManifestPathByPackage(finalizedSelectionRules.preferredVuiPackage);
const preferredManifest = preferredManifestPath ? loadComponentManifest(preferredManifestPath) : null;
const vuiCatalog = preferredManifest
? buildManifestCatalog(preferredManifest, projectUiPackages)
: buildEmptyCatalog(
finalizedSelectionRules.preferredVuiPackage || "unknown",
normalizeFramework(projectContext),
"当前框架的 VUI manifest 尚未提供,AI 仍需遵守 VUI 第一顺位规则。",
);
const fallbackCatalogs = finalizedSelectionRules.fallbackPackages.map((pkg) => {
const manifestPath = resolveManifestPathByPackage(pkg);
const manifest = manifestPath ? loadComponentManifest(manifestPath) : null;
return manifest
? buildManifestCatalog(manifest, projectUiPackages)
: buildEmptyCatalog(pkg, normalizeFramework(projectContext), "当前降级包 manifest 尚未提供。");
});
console.log(` → 项目 UI 包: ${projectUiPackages.join(", ") || "none"}`);
console.log(` → Preferred VUI: ${finalizedSelectionRules.preferredVuiPackage || "none"}`);
console.log(` → Preferred VUI components: ${vuiCatalog.components.length}`);
console.log(
` → Fallback catalogs: ${fallbackCatalogs.map((catalog) => `${catalog.packageName}=${catalog.components.length}`).join(", ") || "none"}`,
);
console.log("\n[step 5] 写入上下文包...");
const designContextFile = path.join(outputDir, `${pageSlug}.design-context.html`);
const variableDefsFile = variableDefs ? path.join(outputDir, `${pageSlug}.variable-defs.json`) : "";
const screenshotFile = screenshot
? path.join(outputDir, `${pageSlug}.screenshot${screenshotExtensionForMimeType(screenshot.mimeType)}`)
: "";
const screenshotSummaryFile = screenshot ? path.join(outputDir, `${pageSlug}.screenshot-summary.json`) : "";
const promptFile = path.join(outputDir, `${pageSlug}.prompt.md`);
const bundleFile = path.join(outputDir, `${pageSlug}.ai-direct-context-bundle.json`);
const promptContent = buildAiPrompt({
projectContext,
projectUiPackages,
pageName,
pageTitle,
figmaUrl: args.figmaUrl,
bundleFileName: path.basename(bundleFile),
designContextFileName: path.basename(designContextFile),
variableDefsFileName: variableDefsFile ? path.basename(variableDefsFile) : "",
screenshotFileName: screenshotFile ? path.basename(screenshotFile) : "",
workspaceExports,
selectionRules: finalizedSelectionRules,
});
const bundle = buildBundle({
schemaReference: toRelativeSchemaPath(
outputDir,
path.join(repoRoot, "contracts/ai/ai-direct-context-bundle.schema.json"),
),
figmaUrl: args.figmaUrl,
projectContext,
projectUiPackages,
pageName,
pageTitle,
pageSlug,
designContext,
variableDefsFile,
screenshotFile,
screenshotSummaryFile,
designContextFile,
promptFile,
workspaceExports,
selectionRules: finalizedSelectionRules,
vuiCatalog,
fallbackCatalogs,
});
fs.writeFileSync(designContextFile, designContext, "utf8");
if (variableDefsFile) {
fs.writeFileSync(variableDefsFile, toPrettyJson(variableDefs), "utf8");
}
if (screenshotFile && screenshot?.base64) {
fs.writeFileSync(screenshotFile, Buffer.from(screenshot.base64, "base64"));
}
fs.writeFileSync(promptFile, promptContent, "utf8");
fs.writeFileSync(bundleFile, toPrettyJson(bundle), "utf8");
console.log("\n[ai-direct-context] ✓ 完成");
console.log(` → bundle: ${bundleFile}`);
console.log(` → prompt: ${promptFile}`);
console.log(` → design context: ${designContextFile}`);
if (variableDefsFile) {
console.log(` → variable defs: ${variableDefsFile}`);
}
if (screenshotFile) {
console.log(` → screenshot: ${screenshotFile}`);
}
}
run().catch((error) => {
console.error("[ai-direct-context] 执行失败:", error.message);
process.exit(1);
});