ai-direct-validate-output.mjs
49.9 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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
#!/usr/bin/env node
import childProcess from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";
import { requireWorkspaceRoot } from "./workspace-root.mjs";
const repoRoot = requireWorkspaceRoot();
const KNOWN_UI_PACKAGES = new Set([
"@venus/common-ui-vue",
"@vui/react",
"@vui/uniapp",
"@vui/vue",
"ant-design-vue",
"antd",
"element-plus",
]);
function parseCliArgs() {
const args = process.argv.slice(2);
const parsed = {
responseFile: "",
previewFile: "",
};
for (let index = 0; index < args.length; index++) {
const arg = args[index];
const next = args[index + 1];
if (arg === "--response-file" && next) {
parsed.responseFile = next;
index++;
} else if (arg === "--preview-file" && next) {
parsed.previewFile = next;
index++;
}
}
return parsed;
}
function readJson(filePath) {
return JSON.parse(fs.readFileSync(filePath, "utf8"));
}
function normalizePath(targetPath) {
return targetPath.replaceAll("\\", "/");
}
// #region debug-point B:report-helper
function reportDebugEvent(hypothesisId, location, msg, data = {}, runId = process.env.DEBUG_RUN_ID || "pre-fix") {
try {
const envPath = path.join(repoRoot, ".dbg", "provider-hang.env");
let debugServerUrl = "http://127.0.0.1:7777/event";
let sessionId = "provider-hang";
if (fs.existsSync(envPath)) {
const envText = fs.readFileSync(envPath, "utf8");
debugServerUrl = envText.match(/DEBUG_SERVER_URL=(.+)/)?.[1]?.trim() || debugServerUrl;
sessionId = envText.match(/DEBUG_SESSION_ID=(.+)/)?.[1]?.trim() || sessionId;
}
fetch(debugServerUrl, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
sessionId,
runId,
hypothesisId,
location,
msg,
data,
ts: Date.now(),
}),
}).catch(() => {});
} catch {}
}
// #endregion
function collectImports(fileContent) {
const imports = [];
const importRegex = /import\s+([^;]+?)\s+from\s+["']([^"']+)["']/g;
for (const match of fileContent.matchAll(importRegex)) {
const clause = match[1].trim();
const pkg = match[2].trim();
const namedMatch = clause.match(/\{([^}]+)\}/);
const namedImports = namedMatch
? namedMatch[1]
.split(",")
.map((part) =>
part
.trim()
.split(/\s+as\s+/i)[0]
.trim(),
)
.filter(Boolean)
: [];
imports.push({
packageName: pkg,
namedImports,
rawClause: clause,
});
}
return imports;
}
function validateUiRules({ response, bundle, preview }) {
const errors = [];
const warnings = [];
const projectRoot = preview.previewProject.projectRoot;
const preferredPackage = bundle.rules.preferredVuiPackage || "";
const allowedFallbacks = bundle.rules.enforcement?.allowedFallbacks || bundle.rules.fallbackPackages || [];
const installedPackages = bundle.projectUi.projectInstalledPackages || [];
const dependencyPlan = response.dependencyPlan || {};
const declaredDependencyChanges = dependencyPlan.needsDependencyChange ? dependencyPlan.packages || [] : [];
const preferredExports =
bundle.projectUi.workspacePackageExports.find((item) => item.packageName === preferredPackage)?.exportNames ||
bundle.componentFacts.vuiCatalog?.components?.map((component) => component.exportName) ||
[];
let preferredImportCount = 0;
let fallbackImportCount = 0;
for (const file of response.files) {
const absolutePath = path.resolve(projectRoot, file.path);
const repoRelativePath = normalizePath(path.relative(repoRoot, absolutePath));
const imports = collectImports(file.content);
for (const statement of imports) {
if (!KNOWN_UI_PACKAGES.has(statement.packageName)) {
continue;
}
if (statement.packageName === preferredPackage) {
preferredImportCount++;
if (
!installedPackages.includes(preferredPackage) &&
!declaredDependencyChanges.includes(preferredPackage)
) {
errors.push(`${repoRelativePath}: 使用了 ${preferredPackage},但 dependencyPlan 未声明补齐该依赖`);
}
for (const importedName of statement.namedImports) {
if (preferredExports.length > 0 && !preferredExports.includes(importedName)) {
errors.push(`${repoRelativePath}: ${preferredPackage} 不存在导出 ${importedName}`);
}
}
continue;
}
if (allowedFallbacks.includes(statement.packageName)) {
fallbackImportCount++;
continue;
}
errors.push(`${repoRelativePath}: 检测到不允许的 UI 包 ${statement.packageName}`);
}
}
if (
bundle.rules.enforcement?.mustUseVuiFirst &&
installedPackages.includes(preferredPackage) &&
fallbackImportCount > 0 &&
preferredImportCount === 0
) {
errors.push(`项目已安装 ${preferredPackage},但 AI 输出只使用了降级组件库,没有使用 VUI 第一顺位组件`);
}
if (!response.previewProject?.mustUseVenusCli) {
errors.push("AI 输出 previewProject.mustUseVenusCli 必须为 true");
}
if (
preview.previewProject.template !== bundle.rules.previewProjectPolicy.cliTemplate ||
preview.previewProject.ui !== bundle.rules.previewProjectPolicy.cliUiOption
) {
warnings.push("预览项目骨架与 bundle 规定的 Venus CLI 模板或 UI 选项不一致(管线问题,非 AI 输出问题)");
}
if (preferredImportCount === 0 && fallbackImportCount === 0) {
warnings.push("未检测到显式 UI 包 import;当前结果可能完全依赖全局注册或基础 DOM");
}
return { errors, warnings };
}
// 样式责任校验:仅作为 warning,不触发 repair
// 原因:缺少 style 块、全局样式干扰等属于优化建议,不是编译错误,AI repair 也难以精确修复
function validateGeneratedStyleOwnership({ response, bundle, preview }) {
const errors = []; // 保留但不再产生 error
const warnings = [];
const projectRoot = preview.previewProject.projectRoot;
if (bundle.rules.framework === "vue") {
const generatedViewFiles = response.files.filter((file) => /^src\/views\/.+\.vue$/u.test(file.path));
for (const file of generatedViewFiles) {
if (!/<style\b/i.test(file.content)) {
warnings.push(`${file.path}: 预览页面必须在生成阶段输出样式,Vue 页面需自带 <style> 块`);
}
}
const previewMainPath = path.join(projectRoot, "src", "main.ts");
const previewStylePath = path.join(projectRoot, "src", "style.css");
if (preview.previewProject.ui === "element-plus" && fs.existsSync(previewMainPath)) {
const mainContent = fs.readFileSync(previewMainPath, "utf8");
if (!mainContent.includes("element-plus/dist/index.css")) {
warnings.push("预览项目使用 element-plus UI 变体时,入口文件必须引入 element-plus 基础样式");
}
}
if (fs.existsSync(previewStylePath)) {
const styleContent = fs.readFileSync(previewStylePath, "utf8");
if (/color-scheme\s*:\s*light dark/i.test(styleContent)) {
warnings.push("预览项目全局样式仍保留模板级 light/dark demo 配色,会干扰业务页面视觉");
}
if (/place-items\s*:\s*center/i.test(styleContent)) {
warnings.push("预览项目全局样式仍保留 body 居中布局,会干扰页面生成结果");
}
}
}
for (const file of response.files) {
if (file.path === "src/router/index.ts" && fs.existsSync(path.join(projectRoot, "src", "router.ts"))) {
warnings.push(
"预览骨架已存在 src/router.ts,新增 src/router/index.ts 容易与现有结构冲突;建议直接修改现有路由文件",
);
}
}
return { errors, warnings };
}
function countMatches(pattern, text) {
const matches = text.match(pattern);
return matches ? matches.length : 0;
}
function collectDesignContextTexts(designContext) {
const lines = String(designContext || "").split(/\r?\n/u);
const texts = [];
for (let index = 0; index < lines.length; index++) {
const line = lines[index];
const match = line.match(/^(\s*)text:\s*(.*)$/u);
if (!match) {
continue;
}
const baseIndent = match[1].length;
const rawValue = match[2].trim();
if (rawValue === "|-" || rawValue === "|") {
const blockLines = [];
let cursor = index + 1;
while (cursor < lines.length) {
const nextLine = lines[cursor];
if (!nextLine.trim()) {
blockLines.push("");
cursor++;
continue;
}
const nextMatch = nextLine.match(/^(\s+)(.*)$/u);
if (!nextMatch || nextMatch[1].length <= baseIndent) {
break;
}
if (nextMatch[2] || blockLines.length > 0) {
blockLines.push(nextMatch[2].trimEnd());
}
cursor++;
}
const blockText = blockLines.join("\n").trim();
if (blockText) {
texts.push(blockText);
}
index = cursor - 1;
continue;
}
if (rawValue) {
texts.push(rawValue.replaceAll(/^['"]|['"]$/gu, "").trim());
}
}
return [...new Set(texts.map((item) => item.trim()).filter(Boolean))];
}
// 动态检测设计属性,不硬编码页面特定值
function extractPrimaryFigmaFacts(designContext) {
const designContextText = String(designContext || "");
const texts = collectDesignContextTexts(designContext);
const detectedTableHeaderBg = detectColorProperty(
designContextText,
/(?:header|表头|__header|th)[\s\S]{0,400}?background:\s*rgba\((\d+),\s*(\d+),\s*(\d+)/u,
);
const detectedTableFillWidth = /sizingH:\s*fill/u.test(designContextText);
const hasToolbarJustifyBetween = /justify:\s*space-between/u.test(designContextText);
const placeholderText = texts.find((item) => /请输入/u.test(item)) || "";
return {
designContextText,
texts,
toolbarHasJustifyBetween: hasToolbarJustifyBetween,
placeholderText,
tableHeaderBackground: detectedTableHeaderBg,
tableShouldFillWidth: detectedTableFillWidth,
};
}
function detectColorProperty(designContext, pattern) {
const match = designContext.match(pattern);
if (!match) {
return "";
}
const r = Number.parseInt(match[1], 10);
const g = Number.parseInt(match[2], 10);
const b = Number.parseInt(match[3], 10);
if (r > 240 && g > 240 && b > 240) {
return "";
}
return `rgb(${r}, ${g}, ${b})`;
}
function readDesignContext(bundle, bundlePath) {
const designContextFile = bundle.artifacts?.designContextFile;
if (!designContextFile) {
return "";
}
const bundleDir = path.dirname(bundlePath);
const designContextPath = path.isAbsolute(designContextFile)
? designContextFile
: path.resolve(bundleDir, designContextFile);
if (!fs.existsSync(designContextPath)) {
return "";
}
return fs.readFileSync(designContextPath, "utf8");
}
function readVisualSummary(bundle, bundlePath) {
const screenshotSummaryFile = bundle.artifacts?.screenshotSummaryFile;
if (!screenshotSummaryFile) {
return null;
}
const bundleDir = path.dirname(bundlePath);
const summaryPath = path.isAbsolute(screenshotSummaryFile)
? screenshotSummaryFile
: path.resolve(bundleDir, screenshotSummaryFile);
if (!fs.existsSync(summaryPath)) {
return null;
}
try {
return readJson(summaryPath);
} catch {
return null;
}
}
// 通用原则:只校验设计稿中可见的核心结构,放宽文本匹配,不做页面特定的硬编码检查
// 注意:此类校验仅作为 warning,不触发 repair,因为内容还原属于 AI 创作自由度范围
function validateVisualSummaryAdherence({ response, bundle, bundlePath }) {
const errors = []; // 不产生 error,所有内容问题降级为 warning
const warnings = [];
const summary = readVisualSummary(bundle, bundlePath);
if (!summary) {
return { errors, warnings };
}
const viewFiles = response.files.filter((file) => /^src\/views\/.+\.vue$/u.test(file.path));
if (viewFiles.length === 0) {
warnings.push("未检测到视图文件,跳过截图视觉摘要遵守性校验");
return { errors, warnings };
}
for (const file of viewFiles) {
const content = file.content;
// 标题:优先精确匹配,退化为部分匹配
if (summary.headerTitle && !content.includes(summary.headerTitle)) {
const titleCore = summary.headerTitle.replaceAll(/列表|管理|页面/gu, "");
if (titleCore && !content.includes(titleCore)) {
warnings.push(`${file.path}: 未检测到截图摘要中的标题 "${summary.headerTitle}"`);
}
}
// 筛选分组标签:允许部分匹配("调出方" 在代码中可能写作 "调出")
for (const label of summary.filterGroupLabels || []) {
if (!label) continue;
const coreLabel = label.replace(/方$/u, "");
const hasLabel = content.includes(label) || (coreLabel && content.includes(coreLabel));
if (!hasLabel) {
warnings.push(`${file.path}: 未检测到截图摘要中的筛选分组标签 "${label}"`);
}
}
// 选择框数量:接受组件别名 VSelect / ElSelect / GLSelect,并放宽阈值(≥ 期望值的 50% 即可)
if (summary.requiredSelectCount > 0) {
const selectCount =
countMatches(/<(VSelect|ElSelect|GLSelect)\b/g, content) + countMatches(/<(select|a-select)\b/gi, content);
const minimum = Math.max(1, Math.ceil(summary.requiredSelectCount * 0.5));
if (selectCount < minimum) {
warnings.push(
`${file.path}: 筛选选择框数量不足,截图摘要期望至少 ${summary.requiredSelectCount} 个,当前检测到 ${selectCount} 个`,
);
}
}
// 搜索标签:仅警告
if (summary.searchLabel && !content.includes(summary.searchLabel)) {
warnings.push(`${file.path}: 未检测到截图摘要中的搜索标签 "${summary.searchLabel}"`);
}
// 主按钮文案:降级为 warning(内容还原属于 AI 创作自由度)
if (summary.primaryActionLabel && !content.includes(summary.primaryActionLabel)) {
warnings.push(`${file.path}: 未体现截图摘要中的主按钮文案 "${summary.primaryActionLabel}"`);
}
// 表格列:部分匹配 + 放宽阈值(≥ 期望列数的 70% 即可)
if (Array.isArray(summary.tableColumns) && summary.tableColumns.length > 0) {
const presentColumns = summary.tableColumns.filter((column) => content.includes(column));
const minimumColumns = Math.max(1, Math.ceil(summary.tableColumns.length * 0.7));
if (presentColumns.length < minimumColumns) {
warnings.push(
`${file.path}: 表格列命中不足,截图摘要要求 ${summary.tableColumns.length} 列,当前命中 ${presentColumns.length} 列`,
);
}
}
// 操作文案:精确匹配
if (summary.actionLinkLabel && !content.includes(summary.actionLinkLabel)) {
warnings.push(`${file.path}: 未检测到截图摘要中的操作文案 "${summary.actionLinkLabel}"`);
}
// 分页:接受 layout 字符串或 page-sizes 属性两种写法
if (summary.pagination?.present) {
if (!/<(ElPagination|VPagination)\b/.test(content) && !/<el-pagination\b/.test(content)) {
warnings.push(`${file.path}: 截图摘要要求存在分页组件,但当前页面未检测到`);
}
const hasTotal = /layout\s*=\s*"[^"]*total/u.test(content) || /:show-total/u.test(content);
if (summary.pagination.totalTextVisible && !hasTotal) {
warnings.push(`${file.path}: 截图摘要要求分页显示总数,但未检测到对应配置`);
}
const hasSizes =
/layout\s*=\s*"[^"]*sizes/u.test(content) || /page-sizes?\s*=/u.test(content) || /:page-sizes/u.test(content);
if (summary.pagination.pageSizeSelectorVisible && !hasSizes) {
warnings.push(`${file.path}: 截图摘要要求分页显示每页条数选择器,但未检测到对应配置`);
}
const hasJumper =
/layout\s*=\s*"[^"]*jumper/u.test(content) ||
/:show-jumper/u.test(content) ||
/:showJumper/u.test(content) ||
/show-jumper\s*\b/u.test(content);
if (summary.pagination.jumperVisible && !hasJumper) {
warnings.push(`${file.path}: 截图摘要要求分页显示 jumper,但未检测到对应配置`);
}
if (summary.pagination.containerAlignment === "split") {
const hasSplitLayout =
/\.pagination-[\w-]+\s*\{[\s\S]*justify-content:\s*space-between/u.test(content) ||
/\.pagination-[\w-]+\s*\{[\s\S]*display:\s*grid/u.test(content);
if (!hasSplitLayout) {
warnings.push(`${file.path}: 截图摘要提示分页区域应左右拆分布局,当前未检测到明显的 split 布局样式`);
}
}
}
}
return { errors, warnings };
}
// 通用原则:只做基于检测到的设计属性的条件校验,不做页面特定的硬编码规则
function validatePrimaryFigmaDataAdherence({ response, bundle, bundlePath }) {
const errors = [];
const warnings = [];
const designContext = readDesignContext(bundle, bundlePath);
if (!designContext) {
return { errors, warnings };
}
const primaryFacts = extractPrimaryFigmaFacts(designContext);
const viewFiles = response.files.filter((file) => /^src\/views\/.+\.vue$/u.test(file.path));
for (const file of viewFiles) {
const content = file.content;
// 通用校验 1:占位符文本是否体现(仅当设计中检测到占位符时)
if (primaryFacts.placeholderText && !content.includes(primaryFacts.placeholderText)) {
warnings.push(`${file.path}: 设计中检测到占位符 "${primaryFacts.placeholderText}",但生成代码中未体现`);
}
// 通用校验 2:表格组件是否绑定了非空数据
const tableDataMatch = content.match(/<(VTable|ElTable)\b[\s\S]*?:data="([^"]+)"/u);
if (tableDataMatch?.[2]) {
const dataVarName = tableDataMatch[2];
const escapedVarName = dataVarName.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`);
const hasNonEmptyData = [
new RegExp(`const\\s+${escapedVarName}(?::\\s*[^=]+)?\\s*=\\s*\\[\\s*\\{`, "u"),
new RegExp(`const\\s+${escapedVarName}(?::\\s*[^=]+)?\\s*=\\s*ref(?:<[^>]+>)?\\(\\s*\\[\\s*\\{`, "u"),
new RegExp(`const\\s+${escapedVarName}(?::\\s*[^=]+)?\\s*=\\s*reactive(?:<[^>]+>)?\\(\\s*\\[\\s*\\{`, "u"),
].some((pattern) => pattern.test(content));
if (!hasNonEmptyData) {
warnings.push(`${file.path}: 表格已绑定数据源 "${dataVarName}",但未检测到非空示例数据`);
}
}
// 通用校验 3:表格列是否全部设固定 width(作为警告而非错误)
const columnsMatch = content.match(/const\s+columns\s*=\s*\[([\s\S]*?)\]/u);
if (columnsMatch) {
const columnsBlock = columnsMatch[1];
const columnEntries = columnsBlock.match(/\{[^}]+\}/gu) || [];
if (columnEntries.length > 0) {
const allHaveFixedWidth = columnEntries.every((entry) => /width:\s*\d+/u.test(entry));
if (allHaveFixedWidth) {
warnings.push(
`${file.path}: 所有表格列都设置了固定 width,可能导致表格无法自适应铺满容器;如设计未要求固定宽度,建议至少保留一列不设 width`,
);
}
}
}
// 通用校验 4:若设计中有 justify: space-between 结构,代码中应有对应实现
if (primaryFacts.toolbarHasJustifyBetween) {
const hasSpaceBetween = /justify-content:\s*space-between/u.test(content);
if (!hasSpaceBetween) {
warnings.push(
`${file.path}: 设计上下文包含 justify: space-between 布局,但生成代码中未检测到对应的 justify-content: space-between 样式`,
);
}
}
// 通用校验 5:若设计中表头有非白色背景,代码应有某种表头背景样式(不检查具体颜色)
if (primaryFacts.tableHeaderBackground) {
const hasAnyHeaderBackground =
/(?:th|__header)[\s\S]{0,300}?background/u.test(content) ||
/background[\s\S]{0,300}?(?:th|__header)/u.test(content);
if (!hasAnyHeaderBackground) {
warnings.push(`${file.path}: 设计中表头具有非白色背景,但生成代码未检测到表头背景样式`);
}
}
}
return { errors, warnings };
}
// 通用校验:AI 不应输出路由文件(由模板生成,管线自动注册路由)
function validateRouterConsistency({ response }) {
const errors = [];
const warnings = [];
const routerFilePatterns = new Set(["src/router.ts", "src/router/index.ts"]);
const generatedRouterFiles = response.files
.map((f) => f.path.replaceAll("\\", "/"))
.filter((p) => routerFilePatterns.has(p));
if (generatedRouterFiles.length > 0) {
warnings.push(
`AI 输出了路由文件 (${generatedRouterFiles.join(", ")}),但路由文件由模板生成,管线会自动注册路由。这些文件会被 apply 阶段跳过。`,
);
}
return { errors, warnings };
}
// 组件文件命名校验:拦截 Node123、Frame1、Group3、FigmaPage 等无意义名称
function validateComponentFileNaming({ response }) {
const errors = [];
const warnings = [];
const meaninglessPattern = /(?:^|\/)(?:Node\d+|Frame\s*\d+|Group\s*\d+|FigmaPage)\.vue$/i;
for (const file of response.files) {
const normalizedPath = file.path.replaceAll("\\", "/");
if (!normalizedPath.endsWith(".vue")) continue;
if (meaninglessPattern.test(normalizedPath)) {
errors.push(
`组件文件名无意义: \`${normalizedPath}\`。请根据组件内容归纳语义化名称(如 ProductList.vue、UserProfileCard.vue),不要使用 Figma 节点 ID 作为文件名。`,
);
}
}
return { errors, warnings };
}
/**
* 设计还原度校验:基于截图摘要和 Figma design context 检查布局、颜色、缺失元素
* 产生 error(触发 repair)的场景:
* - 设计稿关键颜色未在 CSS 中出现
* - 截图摘要中的 sectionOrder 与代码区块顺序不一致
* - listLayouts.columns 与 grid-template-columns 不匹配
* - bottomFixedBar 存在但代码中未生成固定底栏
* - 设计稿中可见的重要文本节点在代码中缺失
* 产生 warning 的场景:
* - 白色文字缺少深色背景
* - imageLayout 未完全匹配
* - floatingOverlay 位置偏差
*/
function validateDesignFidelity({ response, bundle, bundlePath }) {
const errors = [];
const warnings = [];
const designContext = readDesignContext(bundle, bundlePath);
const summary = readVisualSummary(bundle, bundlePath);
const viewFiles = response.files.filter((file) => /^src\/views\/.+\.vue$/u.test(file.path));
if (viewFiles.length === 0) {
return { errors, warnings };
}
for (const file of viewFiles) {
const content = file.content;
const cssBlock = extractCssBlock(content);
// === 1. 颜色校验:从 design context 提取关键颜色 ===
const designColors = extractDesignColors(designContext);
const cssColors = extractCssColors(cssBlock);
for (const color of designColors) {
if (!isCssColorPresent(cssBlock, color)) {
errors.push(
`${file.path}: 设计稿中的关键颜色 ${color} 未在生成代码的 CSS 中出现(可能被"合理推断"覆盖),必须使用设计稿原始颜色值`,
);
}
}
// 截图摘要中的 keyColors (降级为 warning,因为截图颜色是近似的)
for (const color of summary?.keyColors || []) {
// 跳过过于通用的颜色(纯黑、纯白、常见灰色)
if (isGenericColor(color)) continue;
if (!isCssColorPresent(cssBlock, color)) {
warnings.push(
`${file.path}: 截图摘要中的关键颜色 ${color} 未在生成代码的 CSS 中出现(截图颜色为近似值,可忽略)`,
);
}
}
// === 2. 白色文字对比度校验 ===
if (hasWhiteTextWithoutDarkBackground(content, cssBlock)) {
warnings.push(
`${file.path}: 检测到白色文字但缺少深色背景,可能导致对比度不足。设计稿中的白色文字通常意味着深色/图片背景`,
);
}
// === 3. sectionOrder / layoutOrder 顺序校验 ===
const expectedOrder = summary?.sectionOrder?.length > 0 ? summary.sectionOrder : summary?.layoutOrder || [];
if (expectedOrder.length > 0) {
const orderErrors = checkSectionOrder(content, expectedOrder);
for (const err of orderErrors) {
errors.push(`${file.path}: ${err}`);
}
}
// === 4. listLayouts 列数校验 ===
for (const layout of summary?.listLayouts || []) {
if (layout.columns && layout.columns > 1) {
const hasCorrectGrid = checkGridColumns(cssBlock, content, layout.columns);
if (!hasCorrectGrid) {
errors.push(
`${file.path}: 截图摘要要求 ${layout.section} 区域使用 ${layout.columns} 列布局(grid-template-columns: repeat(${layout.columns}, 1fr) 或等价的 1fr ... 写法),但 CSS 中未检测到匹配的列数`,
);
}
}
// direction 校验
if (layout.direction === "row") {
const sectionClass = inferSectionClass(content, layout.section);
if (sectionClass) {
const sectionCss = extractSectionCss(cssBlock, sectionClass);
if (sectionCss && /flex-direction:\s*column/u.test(sectionCss)) {
errors.push(
`${file.path}: 截图摘要要求 ${layout.section} 区域子元素横向排列(direction=row),但 CSS 中检测到 flex-direction: column,应改为 flex-direction: row 或移除该属性`,
);
}
}
}
// labelOnTop 校验
if (layout.labelOnTop === true) {
const sectionClass = inferSectionClass(content, layout.section);
if (sectionClass) {
const sectionHtml = extractSectionHtml(content, sectionClass);
if (sectionHtml) {
const firstChild = extractFirstTextContent(sectionHtml);
// 如果第一个子元素包含的值文本(如 "2022.02")出现在标签文本(如 "首次上牌")之前,则顺序反了
if (firstChild && !firstChild.labelBeforeValue) {
warnings.push(
`${file.path}: 截图摘要要求 ${layout.section} 区域标签在上、值在下(labelOnTop=true),请检查子元素的 DOM 顺序`,
);
}
}
}
}
}
// === 5. bottomFixedBar 校验 ===
if (summary?.bottomFixedBar?.present) {
const hasFixedBottom =
/position:\s*fixed[\s\S]{0,200}?bottom:\s*0/u.test(cssBlock) ||
/position:\s*sticky[\s\S]{0,200}?bottom:\s*0/u.test(cssBlock);
if (!hasFixedBottom) {
errors.push(
`${file.path}: 截图摘要显示页面底部有固定操作栏(bottomFixedBar),但 CSS 中未检测到 position: fixed + bottom: 0 的样式`,
);
}
if (summary.bottomFixedBar.primaryButtonText && !content.includes(summary.bottomFixedBar.primaryButtonText)) {
errors.push(
`${file.path}: 截图摘要要求底部操作栏包含按钮 "${summary.bottomFixedBar.primaryButtonText}",但代码中未找到该文本`,
);
}
}
// === 6. imageLayout 校验 ===
if (summary?.imageLayout?.pattern === "hero-first-then-grid" && summary.imageLayout.firstImageFullWidth) {
// 检查是否有独立的首图容器
const hasHeroImage = /class="[^"]*hero[^"]*"/u.test(content) || /class="[^"]*main-image[^"]*"/u.test(content);
if (!hasHeroImage) {
warnings.push(
`${file.path}: 截图摘要要求图片区域第一张图独占一行(hero-first-then-grid),建议为首图使用独立的容器类名`,
);
}
}
// === 7. floatingOverlays 位置校验 ===
for (const section of summary?.sections || []) {
for (const overlay of section.floatingOverlays || []) {
if (!overlay.text || !overlay.position) continue;
const textPresent = content.includes(overlay.text);
if (!textPresent) {
// 允许模糊匹配
const textCore = overlay.text.replaceAll(/[\d/]+/g, "").trim();
if (textCore && !content.includes(textCore)) {
warnings.push(
`${file.path}: 截图摘要中的浮动元素 "${overlay.text}"(位置: ${overlay.position})未在代码中找到`,
);
}
}
// 检查浮动元素的 CSS 定位是否与截图摘要的 position 一致
if (overlay.position && textPresent) {
const positionHints = resolveOverlayPositionHints(overlay.position);
if (positionHints) {
const overlayClass = inferElementClass(content, overlay.text);
if (overlayClass) {
const overlayCss = extractSectionCss(cssBlock, overlayClass);
if (overlayCss) {
for (const [prop, expected] of Object.entries(positionHints)) {
if (!new RegExp(`${prop}:\\s*${expected}`, "u").test(overlayCss)) {
warnings.push(
`${file.path}: 浮动元素 "${overlay.text}" 的位置应为 ${overlay.position},但 CSS 中 .${overlayClass} 的 ${prop} 不是 ${expected}`,
);
}
}
}
}
}
}
}
}
// === 8. 设计稿文本完整性校验 ===
if (designContext) {
const designTexts = collectDesignContextTexts(designContext);
const missingTexts = findMissingDesignTexts(content, designTexts);
for (const text of missingTexts) {
warnings.push(`${file.path}: 设计稿中的文本 "${text}" 未在生成代码中出现`);
}
}
}
return { errors, warnings };
}
// --- designFidelity 辅助函数 ---
function extractCssBlock(content) {
const styleMatch = content.match(/<style[^>]*>([\s\S]*?)<\/style>/i);
return styleMatch ? styleMatch[1] : "";
}
function extractDesignColors(designContext) {
if (!designContext) return [];
const colors = new Set();
const rgbaPattern = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d.]+)\s*\)/g;
let match;
while ((match = rgbaPattern.exec(designContext)) !== null) {
const r = Number.parseInt(match[1], 10);
const g = Number.parseInt(match[2], 10);
const b = Number.parseInt(match[3], 10);
const a = Number.parseFloat(match[4]);
// 排除纯白、纯灰、蒙版等低信息量颜色
if (r > 230 && g > 230 && b > 230) continue;
if (r === g && g === b && (r === 216 || r === 151 || r === 255)) continue;
// 只保留有辨识度的颜色(饱和度较高的)
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
if (max - min < 30) continue;
// 排除透明度很低(几乎不可见)的颜色
if (a < 0.1) continue;
colors.add(`rgba(${r}, ${g}, ${b}, ${a})`);
}
// 只保留前 8 个最重要的颜色,避免过多误报
return [...colors].slice(0, 8);
}
function isGenericColor(color) {
const c = color.toLowerCase();
// 跳过纯黑、纯白、常见灰色
if (c === "#000000" || c === "#000" || c === "black") return true;
if (c === "#ffffff" || c === "#fff" || c === "white") return true;
if (c === "#e0e0e0" || c === "#d0d0d0" || c === "#c0c0c0") return true;
if (c === "#333333" || c === "#333" || c === "#666666" || c === "#666") return true;
if (c === "#999999" || c === "#999" || c === "#cccccc" || c === "#ccc") return true;
// 跳过 rgb 格式的纯黑纯白
if (/^rgba?\(\s*0\s*,\s*0\s*,\s*0/i.test(c)) return true;
if (/^rgba?\(\s*255\s*,\s*255\s*,\s*255/i.test(c)) return true;
return false;
}
function extractCssColors(cssBlock) {
if (!cssBlock) return new Set();
const colors = new Set();
const rgbaPattern = /rgba?\(\s*(\d+)\s*(?:,\s*)?(\d+)\s*(?:,\s*)?(\d+)\s*(?:,?\s*([\d.]+))?\s*\)/g;
let match;
while ((match = rgbaPattern.exec(cssBlock)) !== null) {
colors.add(match[0]);
}
// 也收集 hex 颜色
const hexPattern = /#[0-9a-f]{3,8}/gi;
while ((match = hexPattern.exec(cssBlock)) !== null) {
colors.add(match[0]);
}
return colors;
}
function isCssColorPresent(cssBlock, designColor) {
if (!designColor) return true;
// 规范化 rgba 值进行比较
const rgbaMatch = designColor.match(/rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d.]+)\s*\)/);
if (!rgbaMatch) return cssBlock.includes(designColor);
const r = rgbaMatch[1];
const g = rgbaMatch[2];
const b = rgbaMatch[3];
const a = rgbaMatch[4];
// 检查 rgba(r, g, b, a) 格式
if (cssBlock.includes(`rgba(${r}, ${g}, ${b}, ${a})`)) return true;
// 检查 rgb(r g b / a%) 格式(CSS4 语法)
const aPercent = Math.round(Number.parseFloat(a) * 100);
if (cssBlock.includes(`rgb(${r} ${g} ${b}`)) return true;
if (cssBlock.includes(`rgb(${r} ${g} ${b} / ${aPercent}%)`)) return true;
// 检查不含 alpha 的 rgb
if (a === "1" || a === "1.0") {
if (cssBlock.includes(`rgb(${r}, ${g}, ${b})`)) return true;
if (cssBlock.includes(`rgb(${r} ${g} ${b}`)) return true;
}
return false;
}
function hasWhiteTextWithoutDarkBackground(content, cssBlock) {
// 检查是否有 color: white / rgba(255,255,255) 但没有对应深色背景
if (!/color:\s*(?:rgb\(255\s*255\s*255|rgba\(255,\s*255,\s*255|#fff)/u.test(cssBlock)) {
return false;
}
// 有白色文字,检查是否有深色背景
if (/background:\s*(?:rgb\(\d{1,2}\s|rgba\(\d{1,2},|#[0-3][0-9a-f])/u.test(cssBlock)) {
return false;
}
return true;
}
function checkSectionOrder(content, expectedOrder) {
const errors = [];
if (expectedOrder.length < 2) return errors;
// 在 template 中找到各 section 的首次出现位置
const templateMatch = content.match(/<template>([\s\S]*?)<\/template>/i);
if (!templateMatch) return errors;
const template = templateMatch[1];
const positions = [];
for (const sectionName of expectedOrder) {
const pattern = new RegExp(`class="[^"]*${sectionName.replaceAll("-", "[^\"-]*-?")}`, "i");
const match = template.match(pattern);
if (match) {
positions.push({ name: sectionName, index: template.indexOf(match[0]) });
}
}
// 检查顺序
for (let i = 0; i < positions.length - 1; i++) {
const current = positions[i];
const next = positions[i + 1];
if (current.index > next.index) {
errors.push(
`区块顺序错误: "${current.name}" 应出现在 "${next.name}" 之前(按 sectionOrder/layoutOrder 约束),但实际位置更靠后`,
);
}
}
return errors;
}
function checkGridColumns(cssBlock, content, expectedColumns) {
const searchTarget = cssBlock || content;
// 检查 repeat(N, ...) 写法
if (new RegExp(`grid-template-columns:\\s*repeat\\(\\s*${expectedColumns}\\s*,`, "u").test(searchTarget)) {
return true;
}
// 检查 1fr 1fr ... (N 个 1fr) 写法
const oneFrPattern = new RegExp(`grid-template-columns:\\s*(${String.raw`1fr\s*`.repeat(expectedColumns)})`, "u");
if (oneFrPattern.test(searchTarget)) {
return true;
}
// 检查 grid-template-columns: 后有 N 个列定义(任意单位)
const gridMatch = searchTarget.match(/grid-template-columns:\s*([^;]+)/u);
if (gridMatch) {
const cols = gridMatch[1].trim().split(/\s+/);
if (cols.length === expectedColumns) {
return true;
}
}
return false;
}
function inferSectionClass(content, sectionName) {
const safeSectionName = sectionName.replaceAll("-", "[^\"-]*-?");
const pattern = new RegExp(`class="([^"]*${safeSectionName}[^"]*)"`, "i");
const match = content.match(pattern);
return match ? match[1].split(/\s+/)[0] : "";
}
function extractSectionCss(cssBlock, className) {
if (!className) return "";
const escapedClass = className.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
const pattern = new RegExp(`\\.${escapedClass}\\s*\\{([^}]+)\\}`, "u");
const match = cssBlock.match(pattern);
return match ? match[1] : "";
}
function extractSectionHtml(content, className) {
if (!className) return "";
const escapedClass = className.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
const pattern = new RegExp(`class="${escapedClass}"[^>]*>([\\s\\S]*?)(?=</div>)`, "u");
const match = content.match(pattern);
return match ? match[1] : "";
}
function extractFirstTextContent(html) {
// 简单检查第一个子元素是 label 还是 value
const children = html.match(/<div[^>]*>([\s\S]*?)<\/div>/g);
if (!children || children.length < 2) return null;
// 检查类名中是否包含 label/value 相关关键词
const firstChild = children[0];
const hasLabelClass = /class="[^"]*(?:label|title|name)[^"]*"/i.test(firstChild);
const hasValueClass = /class="[^"]*(?:value|content|text)[^"]*"/i.test(firstChild);
return { labelBeforeValue: hasLabelClass || !hasValueClass };
}
function resolveOverlayPositionHints(position) {
const hints = {};
switch (position) {
case "center-top": {
hints.left = "50%"; break;
}
case "left-bottom": {
hints.left = "1"; hints.bottom = "1"; break;
}
case "left-center": {
hints.left = "1"; hints.top = "50%"; break;
}
case "left-top": {
hints.left = "1"; hints.top = "1"; break;
}
case "right-bottom": {
hints.right = "1"; hints.bottom = "1"; break;
}
case "right-center": {
hints.right = "0"; hints.top = "50%"; break;
}
case "right-top": {
hints.right = "1"; hints.top = "1"; break;
}
default: {
return null;
}
}
return hints;
}
function inferElementClass(content, text) {
const escapedText = text.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
// 向前查找包含该文本的最近父元素的 class
const pattern = new RegExp(`class="([^"]+)"[^>]*>[^<]*${escapedText}`, "u");
const match = content.match(pattern);
return match ? match[1].split(/\s+/)[0] : "";
}
function findMissingDesignTexts(content, designTexts) {
const missing = [];
// 排除不需要检测的系统/示意文本
const skipPatterns = [
/^\d+:\d+$/, // 状态栏时间 "9:41"
/^\d+\/\d+$/, // 分页索引 "5/10"
/^(信号|WiFi|电池|时间|状态栏)$/u, // 系统状态栏文本
/^[A-Z0-9\s]+%$/i, // 电池百分比 "100%"
];
// 只检查长度 >= 2 的重要文本(排除纯数字、单字、系统示意等)
const importantTexts = designTexts.filter((text) => {
if (text.length < 2) return false;
if (/^\d+$/.test(text)) return false;
if (skipPatterns.some((p) => p.test(text))) return false;
return true;
});
for (const text of importantTexts) {
if (!content.includes(text)) {
missing.push(text);
}
}
// 最多报告 10 个缺失
return missing.slice(0, 10);
}
// 轻量级本地导入一致性检查:不依赖 node_modules,只检查本地文件的 named import 是否在目标文件中有对应导出
function validateLocalImportConsistency({ preview }) {
const errors = [];
const warnings = [];
const projectRoot = preview.previewProject.projectRoot;
// 检查 main.ts 中关键导入的一致性(这是最常见的失败点)
const mainPath = path.join(projectRoot, "src", "main.ts");
if (!fs.existsSync(mainPath)) {
return { errors, warnings };
}
const mainContent = fs.readFileSync(mainPath, "utf8");
// 提取 named imports from local paths: import { X, Y } from "./foo"
const localImportRegex = /import\s*\{\s*([^}]+)\}\s*from\s*["'](\.[^"']+)["']/gu;
let importMatch;
while ((importMatch = localImportRegex.exec(mainContent)) !== null) {
const importedNames = importMatch[1].split(",").map((name) => name.trim().split(/\s+as\s+/)[0].trim()).filter(Boolean);
const importPath = importMatch[2];
// 解析目标文件
const resolvedCandidates = [
path.join(projectRoot, "src", importPath, "index.ts"),
path.join(projectRoot, "src", importPath, "index.tsx"),
path.join(projectRoot, "src", `${importPath}.ts`),
path.join(projectRoot, "src", `${importPath}.tsx`),
];
let targetContent = "";
let targetPath = "";
for (const candidate of resolvedCandidates) {
if (fs.existsSync(candidate)) {
targetContent = fs.readFileSync(candidate, "utf8");
targetPath = normalizePath(path.relative(projectRoot, candidate));
break;
}
}
if (!targetContent) continue;
for (const name of importedNames) {
// 检查目标文件是否有 named export 或 re-export
const hasNamedExport =
new RegExp(`export\\s+(?:function|const|let|var|class|type|interface|enum)\\s+${name}\\b`, "u").test(targetContent) ||
new RegExp(`export\\s*\\{[^}]*\\b${name}\\b[^}]*\\}`, "u").test(targetContent);
if (!hasNamedExport) {
errors.push(
`main.ts 导入 { ${name} } from "${importPath}",但 ${targetPath} 中未检测到对应的命名导出`,
);
}
}
}
return { errors, warnings };
}
// 页面目录结构规范校验:
// views/{pageName}/index.vue — 页面入口
// views/{pageName}/components/*.vue — 子组件
// views/{pageName}/tools/*.ts — 工具函数
// 禁止在 views/ 下直接放 .vue 文件(views/{pageName}.vue)
function validatePageDirectoryStructure({ response, preview }) {
const errors = [];
const warnings = [];
for (const file of response.files) {
const normalizedPath = file.path.replaceAll("\\", "/");
if (!normalizedPath.startsWith("src/views/")) continue;
const relativeToViews = normalizedPath.slice("src/views/".length);
// 检查:views/ 下直接放 .vue 文件(如 views/PageName.vue)
if (!relativeToViews.includes("/") && normalizedPath.endsWith(".vue")) {
errors.push(
`违反页面目录规范: \`${normalizedPath}\`。禁止在 src/views/ 下直接放置 .vue 文件,应放在 src/views/{pageName}/index.vue 目录下。`,
);
continue;
}
// 提取 pageName(第一级目录)
const pageDir = relativeToViews.split("/")[0];
const rest = relativeToViews.slice(pageDir.length + 1);
// 检查:非 index.vue、非 components/、非 tools/ 的文件
if (!rest.startsWith("index.vue") && !rest.startsWith("components/") && !rest.startsWith("tools/")) {
warnings.push(
`页面目录结构警告: \`${normalizedPath}\`。页面文件应放在 index.vue(入口)、components/(子组件)或 tools/(工具函数)下。`,
);
}
// 检查:components/ 下的文件应为 .vue
if (rest.startsWith("components/") && !rest.endsWith(".vue")) {
warnings.push(
`页面目录结构警告: \`${normalizedPath}\`。components/ 目录下的文件应为 .vue 组件。`,
);
}
// 检查:tools/ 下的文件应为 .ts
if (rest.startsWith("tools/") && !rest.endsWith(".ts") && !rest.endsWith(".d.ts")) {
warnings.push(
`页面目录结构警告: \`${normalizedPath}\`。tools/ 目录下的文件应为 .ts 工具函数。`,
);
}
}
return { errors, warnings };
}
function runCommand(command, cwd) {
const startedAt = Date.now();
// #region debug-point B:command-start
reportDebugEvent("B", "scripts/ai-direct-validate-output.mjs:runCommand:start", "[DEBUG] validate subcommand start", {
command,
cwd: normalizePath(cwd),
});
// #endregion
const result = childProcess.spawnSync(command, {
cwd,
shell: true,
encoding: "utf8",
});
// #region debug-point B:command-end
reportDebugEvent("B", "scripts/ai-direct-validate-output.mjs:runCommand:end", "[DEBUG] validate subcommand end", {
command,
cwd: normalizePath(cwd),
exitCode: result.status ?? 1,
durationMs: Date.now() - startedAt,
});
// #endregion
return {
command,
cwd: normalizePath(cwd),
exitCode: result.status ?? 1,
stdout: result.stdout || "",
stderr: result.stderr || "",
ok: (result.status ?? 1) === 0,
};
}
function skipCommand(command, cwd, reason) {
return {
command,
cwd: normalizePath(cwd),
exitCode: 0,
stdout: "",
stderr: "",
ok: true,
skipped: true,
reason,
};
}
function run() {
const args = parseCliArgs();
if (!args.responseFile || !args.previewFile) {
throw new Error(
"用法: node scripts/ai-direct-validate-output.mjs --response-file <ai-output.json> --preview-file <preview-project.json>",
);
}
const responsePath = path.resolve(args.responseFile);
const previewPath = path.resolve(args.previewFile);
const response = readJson(responsePath);
const preview = readJson(previewPath);
const bundlePath = path.resolve(preview.meta.bundleFile);
const bundle = readJson(bundlePath);
const projectRoot = preview.previewProject.projectRoot;
const changedFiles = response.files.map((file) =>
normalizePath(path.relative(repoRoot, path.resolve(projectRoot, file.path))),
);
const hasProjectNodeModules = fs.existsSync(path.join(projectRoot, "node_modules"));
console.log("[ai-direct-validate-output] 校验 AI 结果...");
console.log(` → response: ${responsePath}`);
console.log(` → project: ${projectRoot}`);
// #region debug-point B:validate-start
reportDebugEvent("B", "scripts/ai-direct-validate-output.mjs:run:start", "[DEBUG] validate entry", {
responseFile: normalizePath(responsePath),
previewFile: normalizePath(previewPath),
projectRoot: normalizePath(projectRoot),
changedFilesCount: changedFiles.length,
});
// #endregion
const uiRuleResult = validateUiRules({ response, bundle, preview });
const styleOwnershipResult = validateGeneratedStyleOwnership({ response, bundle, preview });
const primaryDataResult = validatePrimaryFigmaDataAdherence({ response, bundle, bundlePath });
const visualSummaryResult = validateVisualSummaryAdherence({ response, bundle, bundlePath });
const designFidelityResult = validateDesignFidelity({ response, bundle, bundlePath });
const routerConsistencyResult = validateRouterConsistency({ response });
const fileNamingResult = validateComponentFileNaming({ response });
const pageStructureResult = validatePageDirectoryStructure({ response, preview });
const importConsistencyResult = validateLocalImportConsistency({ preview });
const commands = [
runCommand(`node scripts/lint-changed.mjs ${changedFiles.map((file) => `"${file}"`).join(" ")}`, repoRoot),
runCommand(`node scripts/review-trigger.mjs ${changedFiles.map((file) => `"${file}"`).join(" ")}`, repoRoot),
runCommand(
`node scripts/check-file-budgets.mjs ${changedFiles.map((file) => `"${file}"`).join(" ")}`,
repoRoot,
),
];
// type-check 降级为 warning:不阻断校验,只记录结果
// 预览项目的 vue-tsc 全量扫描容易因前批次残留问题(失效路由引用等)误报,不应触发 repair
const typeCheckResult = hasProjectNodeModules
? runCommand("pnpm run type-check", projectRoot)
: skipCommand("pnpm run type-check", projectRoot, "预览项目尚未安装依赖,跳过本地 type-check");
const failedCommands = commands.filter((item) => !item.ok).map((item) => `${item.command} (exit=${item.exitCode})`);
const status =
uiRuleResult.errors.length === 0 &&
styleOwnershipResult.errors.length === 0 &&
primaryDataResult.errors.length === 0 &&
visualSummaryResult.errors.length === 0 &&
designFidelityResult.errors.length === 0 &&
routerConsistencyResult.errors.length === 0 &&
fileNamingResult.errors.length === 0 &&
pageStructureResult.errors.length === 0 &&
importConsistencyResult.errors.length === 0 &&
failedCommands.length === 0
? "passed"
: "failed";
const summary = {
meta: {
generator: "scripts/ai-direct-validate-output.mjs",
generatedAt: new Date().toISOString(),
responseFile: normalizePath(responsePath),
previewFile: normalizePath(previewPath),
bundleFile: normalizePath(bundlePath),
},
status,
files: changedFiles,
ruleValidation: uiRuleResult,
styleValidation: styleOwnershipResult,
primaryDataValidation: primaryDataResult,
visualSummaryValidation: visualSummaryResult,
designFidelityValidation: designFidelityResult,
routerConsistencyValidation: routerConsistencyResult,
fileNamingValidation: fileNamingResult,
pageStructureValidation: pageStructureResult,
importConsistencyValidation: importConsistencyResult,
commandResults: commands,
typeCheckResult,
};
const summaryPath = path.join(
path.dirname(responsePath),
`${path.basename(responsePath, path.extname(responsePath))}.validation-result.json`,
);
fs.writeFileSync(summaryPath, `${JSON.stringify(summary, null, 2)}\n`, "utf8");
// #region debug-point D:validate-summary-written
reportDebugEvent("D", "scripts/ai-direct-validate-output.mjs:run:summary", "[DEBUG] validation summary written", {
summaryPath: normalizePath(summaryPath),
status,
ruleErrorCount: uiRuleResult.errors.length,
styleErrorCount: styleOwnershipResult.errors.length,
visualErrorCount: visualSummaryResult.errors.length,
routerErrorCount: routerConsistencyResult.errors.length,
failedCommandCount: failedCommands.length,
});
// #endregion
if (uiRuleResult.errors.length > 0) {
console.error("[ai-direct-validate-output] 规则校验失败:");
for (const error of uiRuleResult.errors) {
console.error(` - ${error}`);
}
}
for (const warning of uiRuleResult.warnings) {
console.warn(`[ai-direct-validate-output] warning: ${warning}`);
}
if (styleOwnershipResult.errors.length > 0) {
console.error("[ai-direct-validate-output] 样式责任校验失败:");
for (const error of styleOwnershipResult.errors) {
console.error(` - ${error}`);
}
}
for (const warning of styleOwnershipResult.warnings) {
console.warn(`[ai-direct-validate-output] warning: ${warning}`);
}
if (primaryDataResult.errors.length > 0) {
console.error("[ai-direct-validate-output] Figma 原始数据校验失败:");
for (const error of primaryDataResult.errors) {
console.error(` - ${error}`);
}
}
for (const warning of primaryDataResult.warnings) {
console.warn(`[ai-direct-validate-output] warning: ${warning}`);
}
if (visualSummaryResult.errors.length > 0) {
console.error("[ai-direct-validate-output] 截图视觉摘要校验失败:");
for (const error of visualSummaryResult.errors) {
console.error(` - ${error}`);
}
}
for (const warning of visualSummaryResult.warnings) {
console.warn(`[ai-direct-validate-output] warning: ${warning}`);
}
if (designFidelityResult.errors.length > 0) {
console.error("[ai-direct-validate-output] 设计还原度校验失败:");
for (const error of designFidelityResult.errors) {
console.error(` - ${error}`);
}
}
for (const warning of designFidelityResult.warnings) {
console.warn(`[ai-direct-validate-output] warning: ${warning}`);
}
if (routerConsistencyResult.errors.length > 0) {
console.error("[ai-direct-validate-output] 路由导出一致性校验失败:");
for (const error of routerConsistencyResult.errors) {
console.error(` - ${error}`);
}
}
for (const warning of routerConsistencyResult.warnings) {
console.warn(`[ai-direct-validate-output] warning: ${warning}`);
}
if (fileNamingResult.errors.length > 0) {
console.error("[ai-direct-validate-output] 组件文件命名校验失败:");
for (const error of fileNamingResult.errors) {
console.error(` - ${error}`);
}
}
for (const warning of fileNamingResult.warnings) {
console.warn(`[ai-direct-validate-output] warning: ${warning}`);
}
if (pageStructureResult.errors.length > 0) {
console.error("[ai-direct-validate-output] 页面目录结构校验失败:");
for (const error of pageStructureResult.errors) {
console.error(` - ${error}`);
}
}
for (const warning of pageStructureResult.warnings) {
console.warn(`[ai-direct-validate-output] warning: ${warning}`);
}
if (importConsistencyResult.errors.length > 0) {
console.error("[ai-direct-validate-output] 本地导入一致性校验失败:");
for (const error of importConsistencyResult.errors) {
console.error(` - ${error}`);
}
}
for (const warning of importConsistencyResult.warnings) {
console.warn(`[ai-direct-validate-output] warning: ${warning}`);
}
if (failedCommands.length > 0) {
console.error("[ai-direct-validate-output] 命令校验失败:");
for (const item of failedCommands) {
console.error(` - ${item}`);
}
}
// type-check 仅作为 warning 输出,不阻断校验
if (!typeCheckResult.ok) {
console.warn(`[ai-direct-validate-output] warning: ${typeCheckResult.command} (exit=${typeCheckResult.exitCode}) — 不阻断校验`);
}
console.log(` → summary: ${summaryPath}`);
if (status !== "passed") {
process.exit(1);
}
console.log("[ai-direct-validate-output] ✓ 通过");
}
run();
process.exit(0);