canicode 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +298 -0
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +4399 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/index.d.ts +1104 -0
- package/dist/index.js +3513 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp/server.d.ts +1 -0
- package/dist/mcp/server.js +3009 -0
- package/dist/mcp/server.js.map +1 -0
- package/package.json +63 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,3513 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { readFile, writeFile, appendFile } from 'fs/promises';
|
|
3
|
+
import { basename, resolve, dirname } from 'path';
|
|
4
|
+
import { existsSync, mkdirSync } from 'fs';
|
|
5
|
+
|
|
6
|
+
// src/contracts/severity.ts
|
|
7
|
+
var SeveritySchema = z.enum([
|
|
8
|
+
"blocking",
|
|
9
|
+
"risk",
|
|
10
|
+
"missing-info",
|
|
11
|
+
"suggestion"
|
|
12
|
+
]);
|
|
13
|
+
var SEVERITY_WEIGHT = {
|
|
14
|
+
blocking: 10,
|
|
15
|
+
risk: 5,
|
|
16
|
+
"missing-info": 2,
|
|
17
|
+
suggestion: 1
|
|
18
|
+
};
|
|
19
|
+
var SEVERITY_LABELS = {
|
|
20
|
+
blocking: "Blocking",
|
|
21
|
+
risk: "Risk",
|
|
22
|
+
"missing-info": "Missing Info",
|
|
23
|
+
suggestion: "Suggestion"
|
|
24
|
+
};
|
|
25
|
+
var CategorySchema = z.enum([
|
|
26
|
+
"layout",
|
|
27
|
+
"token",
|
|
28
|
+
"component",
|
|
29
|
+
"naming",
|
|
30
|
+
"ai-readability",
|
|
31
|
+
"handoff-risk"
|
|
32
|
+
]);
|
|
33
|
+
var CATEGORIES = CategorySchema.options;
|
|
34
|
+
var CATEGORY_LABELS = {
|
|
35
|
+
layout: "Layout",
|
|
36
|
+
token: "Design Token",
|
|
37
|
+
component: "Component",
|
|
38
|
+
naming: "Naming",
|
|
39
|
+
"ai-readability": "AI Readability",
|
|
40
|
+
"handoff-risk": "Handoff Risk"
|
|
41
|
+
};
|
|
42
|
+
var AnalysisNodeTypeSchema = z.enum([
|
|
43
|
+
"DOCUMENT",
|
|
44
|
+
"CANVAS",
|
|
45
|
+
"FRAME",
|
|
46
|
+
"GROUP",
|
|
47
|
+
"SECTION",
|
|
48
|
+
"COMPONENT",
|
|
49
|
+
"COMPONENT_SET",
|
|
50
|
+
"INSTANCE",
|
|
51
|
+
"RECTANGLE",
|
|
52
|
+
"ELLIPSE",
|
|
53
|
+
"VECTOR",
|
|
54
|
+
"TEXT",
|
|
55
|
+
"LINE",
|
|
56
|
+
"BOOLEAN_OPERATION",
|
|
57
|
+
"STAR",
|
|
58
|
+
"REGULAR_POLYGON",
|
|
59
|
+
"SLICE",
|
|
60
|
+
"STICKY",
|
|
61
|
+
"SHAPE_WITH_TEXT",
|
|
62
|
+
"CONNECTOR",
|
|
63
|
+
"WIDGET",
|
|
64
|
+
"EMBED",
|
|
65
|
+
"LINK_UNFURL",
|
|
66
|
+
"TABLE",
|
|
67
|
+
"TABLE_CELL"
|
|
68
|
+
]);
|
|
69
|
+
var LayoutModeSchema = z.enum(["NONE", "HORIZONTAL", "VERTICAL"]);
|
|
70
|
+
var LayoutAlignSchema = z.enum(["MIN", "CENTER", "MAX", "STRETCH", "INHERIT"]);
|
|
71
|
+
var LayoutPositioningSchema = z.enum(["AUTO", "ABSOLUTE"]);
|
|
72
|
+
var BaseAnalysisNodeSchema = z.object({
|
|
73
|
+
// Basic identification
|
|
74
|
+
id: z.string(),
|
|
75
|
+
name: z.string(),
|
|
76
|
+
type: AnalysisNodeTypeSchema,
|
|
77
|
+
visible: z.boolean().default(true),
|
|
78
|
+
// Layout analysis
|
|
79
|
+
layoutMode: LayoutModeSchema.optional(),
|
|
80
|
+
layoutAlign: LayoutAlignSchema.optional(),
|
|
81
|
+
layoutPositioning: LayoutPositioningSchema.optional(),
|
|
82
|
+
primaryAxisAlignItems: z.string().optional(),
|
|
83
|
+
counterAxisAlignItems: z.string().optional(),
|
|
84
|
+
itemSpacing: z.number().optional(),
|
|
85
|
+
paddingLeft: z.number().optional(),
|
|
86
|
+
paddingRight: z.number().optional(),
|
|
87
|
+
paddingTop: z.number().optional(),
|
|
88
|
+
paddingBottom: z.number().optional(),
|
|
89
|
+
// Size/position analysis
|
|
90
|
+
absoluteBoundingBox: z.object({
|
|
91
|
+
x: z.number(),
|
|
92
|
+
y: z.number(),
|
|
93
|
+
width: z.number(),
|
|
94
|
+
height: z.number()
|
|
95
|
+
}).nullable().optional(),
|
|
96
|
+
// Component analysis
|
|
97
|
+
componentId: z.string().optional(),
|
|
98
|
+
componentPropertyDefinitions: z.record(z.string(), z.unknown()).optional(),
|
|
99
|
+
componentProperties: z.record(z.string(), z.unknown()).optional(),
|
|
100
|
+
// Style/token analysis
|
|
101
|
+
styles: z.record(z.string(), z.string()).optional(),
|
|
102
|
+
fills: z.array(z.unknown()).optional(),
|
|
103
|
+
strokes: z.array(z.unknown()).optional(),
|
|
104
|
+
effects: z.array(z.unknown()).optional(),
|
|
105
|
+
// Variable binding analysis (design tokens)
|
|
106
|
+
boundVariables: z.record(z.string(), z.unknown()).optional(),
|
|
107
|
+
// Text analysis
|
|
108
|
+
characters: z.string().optional(),
|
|
109
|
+
style: z.record(z.string(), z.unknown()).optional(),
|
|
110
|
+
// Handoff analysis
|
|
111
|
+
devStatus: z.object({
|
|
112
|
+
type: z.enum(["NONE", "READY_FOR_DEV", "COMPLETED"]),
|
|
113
|
+
description: z.string().optional()
|
|
114
|
+
}).optional(),
|
|
115
|
+
// Naming analysis metadata
|
|
116
|
+
isAsset: z.boolean().optional()
|
|
117
|
+
});
|
|
118
|
+
var AnalysisNodeSchema = BaseAnalysisNodeSchema.extend({
|
|
119
|
+
children: z.lazy(() => AnalysisNodeSchema.array().optional())
|
|
120
|
+
});
|
|
121
|
+
var AnalysisFileSchema = z.object({
|
|
122
|
+
fileKey: z.string(),
|
|
123
|
+
name: z.string(),
|
|
124
|
+
lastModified: z.string(),
|
|
125
|
+
version: z.string(),
|
|
126
|
+
document: AnalysisNodeSchema,
|
|
127
|
+
components: z.record(
|
|
128
|
+
z.string(),
|
|
129
|
+
z.object({
|
|
130
|
+
key: z.string(),
|
|
131
|
+
name: z.string(),
|
|
132
|
+
description: z.string()
|
|
133
|
+
})
|
|
134
|
+
),
|
|
135
|
+
styles: z.record(
|
|
136
|
+
z.string(),
|
|
137
|
+
z.object({
|
|
138
|
+
key: z.string(),
|
|
139
|
+
name: z.string(),
|
|
140
|
+
styleType: z.string()
|
|
141
|
+
})
|
|
142
|
+
)
|
|
143
|
+
});
|
|
144
|
+
var RuleDefinitionSchema = z.object({
|
|
145
|
+
id: z.string(),
|
|
146
|
+
name: z.string(),
|
|
147
|
+
category: CategorySchema,
|
|
148
|
+
why: z.string(),
|
|
149
|
+
impact: z.string(),
|
|
150
|
+
fix: z.string()
|
|
151
|
+
});
|
|
152
|
+
var RuleConfigSchema = z.object({
|
|
153
|
+
severity: SeveritySchema,
|
|
154
|
+
score: z.number().int().max(0),
|
|
155
|
+
depthWeight: z.number().min(1).max(2).optional(),
|
|
156
|
+
enabled: z.boolean().default(true),
|
|
157
|
+
options: z.record(z.string(), z.unknown()).optional()
|
|
158
|
+
});
|
|
159
|
+
var DEPTH_WEIGHT_CATEGORIES = ["layout", "handoff-risk"];
|
|
160
|
+
function supportsDepthWeight(category) {
|
|
161
|
+
return DEPTH_WEIGHT_CATEGORIES.includes(category);
|
|
162
|
+
}
|
|
163
|
+
var IssueSchema = z.object({
|
|
164
|
+
nodeId: z.string(),
|
|
165
|
+
nodePath: z.string(),
|
|
166
|
+
figmaDeepLink: z.string().url(),
|
|
167
|
+
ruleId: z.string(),
|
|
168
|
+
message: z.string(),
|
|
169
|
+
severity: SeveritySchema
|
|
170
|
+
});
|
|
171
|
+
var CategoryScoreSchema = z.object({
|
|
172
|
+
category: CategorySchema,
|
|
173
|
+
score: z.number().min(0).max(100),
|
|
174
|
+
maxScore: z.number().min(0).max(100),
|
|
175
|
+
issueCount: z.object({
|
|
176
|
+
error: z.number().int().min(0),
|
|
177
|
+
warning: z.number().int().min(0),
|
|
178
|
+
info: z.number().int().min(0)
|
|
179
|
+
})
|
|
180
|
+
});
|
|
181
|
+
var ReportMetadataSchema = z.object({
|
|
182
|
+
fileKey: z.string(),
|
|
183
|
+
fileName: z.string(),
|
|
184
|
+
analyzedAt: z.string().datetime(),
|
|
185
|
+
version: z.string()
|
|
186
|
+
});
|
|
187
|
+
var ReportSchema = z.object({
|
|
188
|
+
metadata: ReportMetadataSchema,
|
|
189
|
+
totalScore: z.number().min(0).max(100),
|
|
190
|
+
categoryScores: z.array(CategoryScoreSchema),
|
|
191
|
+
issues: z.array(IssueSchema),
|
|
192
|
+
summary: z.object({
|
|
193
|
+
totalNodes: z.number().int().min(0),
|
|
194
|
+
analyzedNodes: z.number().int().min(0),
|
|
195
|
+
errorCount: z.number().int().min(0),
|
|
196
|
+
warningCount: z.number().int().min(0),
|
|
197
|
+
infoCount: z.number().int().min(0)
|
|
198
|
+
})
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
// src/rules/rule-config.ts
|
|
202
|
+
var RULE_CONFIGS = {
|
|
203
|
+
// ============================================
|
|
204
|
+
// Layout (11 rules)
|
|
205
|
+
// ============================================
|
|
206
|
+
"no-auto-layout": {
|
|
207
|
+
severity: "blocking",
|
|
208
|
+
score: -7,
|
|
209
|
+
depthWeight: 1.5,
|
|
210
|
+
enabled: true
|
|
211
|
+
},
|
|
212
|
+
"absolute-position-in-auto-layout": {
|
|
213
|
+
severity: "blocking",
|
|
214
|
+
score: -10,
|
|
215
|
+
depthWeight: 1.3,
|
|
216
|
+
enabled: true
|
|
217
|
+
},
|
|
218
|
+
"fixed-width-in-responsive-context": {
|
|
219
|
+
severity: "risk",
|
|
220
|
+
score: -4,
|
|
221
|
+
depthWeight: 1.3,
|
|
222
|
+
enabled: true
|
|
223
|
+
},
|
|
224
|
+
"missing-responsive-behavior": {
|
|
225
|
+
severity: "risk",
|
|
226
|
+
score: -4,
|
|
227
|
+
depthWeight: 1.5,
|
|
228
|
+
enabled: true
|
|
229
|
+
},
|
|
230
|
+
"group-usage": {
|
|
231
|
+
severity: "risk",
|
|
232
|
+
score: -5,
|
|
233
|
+
depthWeight: 1.2,
|
|
234
|
+
enabled: true
|
|
235
|
+
},
|
|
236
|
+
"fixed-size-in-auto-layout": {
|
|
237
|
+
severity: "risk",
|
|
238
|
+
score: -5,
|
|
239
|
+
enabled: true
|
|
240
|
+
},
|
|
241
|
+
"missing-min-width": {
|
|
242
|
+
severity: "risk",
|
|
243
|
+
score: -5,
|
|
244
|
+
enabled: true
|
|
245
|
+
},
|
|
246
|
+
"missing-max-width": {
|
|
247
|
+
severity: "risk",
|
|
248
|
+
score: -4,
|
|
249
|
+
enabled: true
|
|
250
|
+
},
|
|
251
|
+
"deep-nesting": {
|
|
252
|
+
severity: "risk",
|
|
253
|
+
score: -4,
|
|
254
|
+
enabled: true,
|
|
255
|
+
options: {
|
|
256
|
+
maxDepth: 5
|
|
257
|
+
}
|
|
258
|
+
},
|
|
259
|
+
"overflow-hidden-abuse": {
|
|
260
|
+
severity: "missing-info",
|
|
261
|
+
score: -3,
|
|
262
|
+
enabled: true
|
|
263
|
+
},
|
|
264
|
+
"inconsistent-sibling-layout-direction": {
|
|
265
|
+
severity: "missing-info",
|
|
266
|
+
score: -2,
|
|
267
|
+
enabled: true
|
|
268
|
+
},
|
|
269
|
+
// ============================================
|
|
270
|
+
// Token (7 rules)
|
|
271
|
+
// ============================================
|
|
272
|
+
"raw-color": {
|
|
273
|
+
severity: "missing-info",
|
|
274
|
+
score: -2,
|
|
275
|
+
enabled: true
|
|
276
|
+
},
|
|
277
|
+
"raw-font": {
|
|
278
|
+
severity: "blocking",
|
|
279
|
+
score: -8,
|
|
280
|
+
enabled: true
|
|
281
|
+
},
|
|
282
|
+
"inconsistent-spacing": {
|
|
283
|
+
severity: "missing-info",
|
|
284
|
+
score: -2,
|
|
285
|
+
enabled: true,
|
|
286
|
+
options: {
|
|
287
|
+
gridBase: 8
|
|
288
|
+
}
|
|
289
|
+
},
|
|
290
|
+
"magic-number-spacing": {
|
|
291
|
+
severity: "risk",
|
|
292
|
+
score: -4,
|
|
293
|
+
enabled: true,
|
|
294
|
+
options: {
|
|
295
|
+
gridBase: 8
|
|
296
|
+
}
|
|
297
|
+
},
|
|
298
|
+
"raw-shadow": {
|
|
299
|
+
severity: "missing-info",
|
|
300
|
+
score: -3,
|
|
301
|
+
enabled: true
|
|
302
|
+
},
|
|
303
|
+
"raw-opacity": {
|
|
304
|
+
severity: "missing-info",
|
|
305
|
+
score: -2,
|
|
306
|
+
enabled: true
|
|
307
|
+
},
|
|
308
|
+
"multiple-fill-colors": {
|
|
309
|
+
severity: "missing-info",
|
|
310
|
+
score: -3,
|
|
311
|
+
enabled: true,
|
|
312
|
+
options: {
|
|
313
|
+
tolerance: 10
|
|
314
|
+
}
|
|
315
|
+
},
|
|
316
|
+
// ============================================
|
|
317
|
+
// Component (6 rules)
|
|
318
|
+
// ============================================
|
|
319
|
+
"missing-component": {
|
|
320
|
+
severity: "risk",
|
|
321
|
+
score: -7,
|
|
322
|
+
enabled: true,
|
|
323
|
+
options: {
|
|
324
|
+
minRepetitions: 3
|
|
325
|
+
}
|
|
326
|
+
},
|
|
327
|
+
"detached-instance": {
|
|
328
|
+
severity: "risk",
|
|
329
|
+
score: -5,
|
|
330
|
+
enabled: true
|
|
331
|
+
},
|
|
332
|
+
"nested-instance-override": {
|
|
333
|
+
severity: "risk",
|
|
334
|
+
score: -5,
|
|
335
|
+
enabled: true
|
|
336
|
+
},
|
|
337
|
+
"variant-not-used": {
|
|
338
|
+
severity: "missing-info",
|
|
339
|
+
score: -3,
|
|
340
|
+
enabled: true
|
|
341
|
+
},
|
|
342
|
+
"component-property-unused": {
|
|
343
|
+
severity: "missing-info",
|
|
344
|
+
score: -2,
|
|
345
|
+
enabled: true
|
|
346
|
+
},
|
|
347
|
+
"single-use-component": {
|
|
348
|
+
severity: "suggestion",
|
|
349
|
+
score: -1,
|
|
350
|
+
enabled: true
|
|
351
|
+
},
|
|
352
|
+
// ============================================
|
|
353
|
+
// Naming (5 rules)
|
|
354
|
+
// ============================================
|
|
355
|
+
"default-name": {
|
|
356
|
+
severity: "missing-info",
|
|
357
|
+
score: -2,
|
|
358
|
+
enabled: true
|
|
359
|
+
},
|
|
360
|
+
"non-semantic-name": {
|
|
361
|
+
severity: "missing-info",
|
|
362
|
+
score: -2,
|
|
363
|
+
enabled: true
|
|
364
|
+
},
|
|
365
|
+
"inconsistent-naming-convention": {
|
|
366
|
+
severity: "missing-info",
|
|
367
|
+
score: -2,
|
|
368
|
+
enabled: true
|
|
369
|
+
},
|
|
370
|
+
"numeric-suffix-name": {
|
|
371
|
+
severity: "suggestion",
|
|
372
|
+
score: -1,
|
|
373
|
+
enabled: true
|
|
374
|
+
},
|
|
375
|
+
"too-long-name": {
|
|
376
|
+
severity: "suggestion",
|
|
377
|
+
score: -1,
|
|
378
|
+
enabled: true,
|
|
379
|
+
options: {
|
|
380
|
+
maxLength: 50
|
|
381
|
+
}
|
|
382
|
+
},
|
|
383
|
+
// ============================================
|
|
384
|
+
// AI Readability (5 rules)
|
|
385
|
+
// ============================================
|
|
386
|
+
"ambiguous-structure": {
|
|
387
|
+
severity: "blocking",
|
|
388
|
+
score: -10,
|
|
389
|
+
depthWeight: 1.3,
|
|
390
|
+
enabled: true
|
|
391
|
+
},
|
|
392
|
+
"z-index-dependent-layout": {
|
|
393
|
+
severity: "risk",
|
|
394
|
+
score: -5,
|
|
395
|
+
depthWeight: 1.3,
|
|
396
|
+
enabled: true
|
|
397
|
+
},
|
|
398
|
+
"missing-layout-hint": {
|
|
399
|
+
severity: "risk",
|
|
400
|
+
score: -5,
|
|
401
|
+
enabled: true
|
|
402
|
+
},
|
|
403
|
+
"invisible-layer": {
|
|
404
|
+
severity: "blocking",
|
|
405
|
+
score: -10,
|
|
406
|
+
enabled: true
|
|
407
|
+
},
|
|
408
|
+
"empty-frame": {
|
|
409
|
+
severity: "missing-info",
|
|
410
|
+
score: -2,
|
|
411
|
+
enabled: true
|
|
412
|
+
},
|
|
413
|
+
// ============================================
|
|
414
|
+
// Handoff Risk (5 rules)
|
|
415
|
+
// ============================================
|
|
416
|
+
"hardcode-risk": {
|
|
417
|
+
severity: "risk",
|
|
418
|
+
score: -5,
|
|
419
|
+
depthWeight: 1.5,
|
|
420
|
+
enabled: true
|
|
421
|
+
},
|
|
422
|
+
"text-truncation-unhandled": {
|
|
423
|
+
severity: "risk",
|
|
424
|
+
score: -5,
|
|
425
|
+
enabled: true
|
|
426
|
+
},
|
|
427
|
+
"image-no-placeholder": {
|
|
428
|
+
severity: "missing-info",
|
|
429
|
+
score: -3,
|
|
430
|
+
enabled: true
|
|
431
|
+
},
|
|
432
|
+
"prototype-link-in-design": {
|
|
433
|
+
severity: "missing-info",
|
|
434
|
+
score: -2,
|
|
435
|
+
enabled: true
|
|
436
|
+
},
|
|
437
|
+
"no-dev-status": {
|
|
438
|
+
severity: "missing-info",
|
|
439
|
+
score: -2,
|
|
440
|
+
enabled: false
|
|
441
|
+
// Disabled by default
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
function getConfigsWithPreset(preset) {
|
|
445
|
+
const configs = { ...RULE_CONFIGS };
|
|
446
|
+
switch (preset) {
|
|
447
|
+
case "relaxed":
|
|
448
|
+
for (const [id, config] of Object.entries(configs)) {
|
|
449
|
+
if (config.severity === "blocking") {
|
|
450
|
+
configs[id] = {
|
|
451
|
+
...config,
|
|
452
|
+
severity: "risk",
|
|
453
|
+
score: Math.round(config.score * 0.5)
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
break;
|
|
458
|
+
case "dev-friendly":
|
|
459
|
+
for (const [id, config] of Object.entries(configs)) {
|
|
460
|
+
const ruleId = id;
|
|
461
|
+
if (!ruleId.includes("layout") && !ruleId.includes("handoff") && !ruleId.includes("responsive")) {
|
|
462
|
+
configs[ruleId] = { ...config, enabled: false };
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
break;
|
|
466
|
+
case "ai-ready":
|
|
467
|
+
for (const [id, config] of Object.entries(configs)) {
|
|
468
|
+
const ruleId = id;
|
|
469
|
+
if (ruleId.includes("ambiguous") || ruleId.includes("structure") || ruleId.includes("name")) {
|
|
470
|
+
configs[ruleId] = {
|
|
471
|
+
...config,
|
|
472
|
+
score: Math.round(config.score * 1.5)
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
break;
|
|
477
|
+
case "strict":
|
|
478
|
+
for (const [id, config] of Object.entries(configs)) {
|
|
479
|
+
configs[id] = {
|
|
480
|
+
...config,
|
|
481
|
+
enabled: true,
|
|
482
|
+
score: Math.round(config.score * 1.5)
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
break;
|
|
486
|
+
}
|
|
487
|
+
return configs;
|
|
488
|
+
}
|
|
489
|
+
function getRuleOption(ruleId, optionKey, defaultValue) {
|
|
490
|
+
const config = RULE_CONFIGS[ruleId];
|
|
491
|
+
if (!config.options) return defaultValue;
|
|
492
|
+
const value = config.options[optionKey];
|
|
493
|
+
return value ?? defaultValue;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// src/rules/rule-registry.ts
|
|
497
|
+
var RuleRegistry = class {
|
|
498
|
+
rules = /* @__PURE__ */ new Map();
|
|
499
|
+
/**
|
|
500
|
+
* Register a rule
|
|
501
|
+
*/
|
|
502
|
+
register(rule) {
|
|
503
|
+
this.rules.set(rule.definition.id, rule);
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* Get a rule by ID
|
|
507
|
+
*/
|
|
508
|
+
get(id) {
|
|
509
|
+
return this.rules.get(id);
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* Get all registered rules
|
|
513
|
+
*/
|
|
514
|
+
getAll() {
|
|
515
|
+
return Array.from(this.rules.values());
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Get rules by category
|
|
519
|
+
*/
|
|
520
|
+
getByCategory(category) {
|
|
521
|
+
return this.getAll().filter((rule) => rule.definition.category === category);
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Get enabled rules with their configs
|
|
525
|
+
*/
|
|
526
|
+
getEnabled(configs = RULE_CONFIGS) {
|
|
527
|
+
return this.getAll().filter((rule) => {
|
|
528
|
+
const config = configs[rule.definition.id];
|
|
529
|
+
return config?.enabled ?? true;
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* Get config for a rule
|
|
534
|
+
*/
|
|
535
|
+
getConfig(id, configs = RULE_CONFIGS) {
|
|
536
|
+
return configs[id];
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Check if a rule is registered
|
|
540
|
+
*/
|
|
541
|
+
has(id) {
|
|
542
|
+
return this.rules.has(id);
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* Get count of registered rules
|
|
546
|
+
*/
|
|
547
|
+
get size() {
|
|
548
|
+
return this.rules.size;
|
|
549
|
+
}
|
|
550
|
+
};
|
|
551
|
+
var ruleRegistry = new RuleRegistry();
|
|
552
|
+
function defineRule(rule) {
|
|
553
|
+
ruleRegistry.register(rule);
|
|
554
|
+
return rule;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
// src/core/rule-engine.ts
|
|
558
|
+
function calculateMaxDepth(node, currentDepth = 0) {
|
|
559
|
+
if (!node.children || node.children.length === 0) {
|
|
560
|
+
return currentDepth;
|
|
561
|
+
}
|
|
562
|
+
let maxChildDepth = currentDepth;
|
|
563
|
+
for (const child of node.children) {
|
|
564
|
+
const childDepth = calculateMaxDepth(child, currentDepth + 1);
|
|
565
|
+
if (childDepth > maxChildDepth) {
|
|
566
|
+
maxChildDepth = childDepth;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
return maxChildDepth;
|
|
570
|
+
}
|
|
571
|
+
function countNodes(node) {
|
|
572
|
+
let count = 1;
|
|
573
|
+
if (node.children) {
|
|
574
|
+
for (const child of node.children) {
|
|
575
|
+
count += countNodes(child);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
return count;
|
|
579
|
+
}
|
|
580
|
+
function findNodeById(node, nodeId) {
|
|
581
|
+
const normalizedId = nodeId.replace(/-/g, ":");
|
|
582
|
+
if (node.id === normalizedId) {
|
|
583
|
+
return node;
|
|
584
|
+
}
|
|
585
|
+
if (node.children) {
|
|
586
|
+
for (const child of node.children) {
|
|
587
|
+
const found = findNodeById(child, nodeId);
|
|
588
|
+
if (found) return found;
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
return null;
|
|
592
|
+
}
|
|
593
|
+
function calcDepthWeight(depth, maxDepth, depthWeight) {
|
|
594
|
+
if (!depthWeight || depthWeight <= 1) return 1;
|
|
595
|
+
if (maxDepth === 0) return depthWeight;
|
|
596
|
+
const ratio = depth / maxDepth;
|
|
597
|
+
return depthWeight - (depthWeight - 1) * ratio;
|
|
598
|
+
}
|
|
599
|
+
var RuleEngine = class {
|
|
600
|
+
configs;
|
|
601
|
+
enabledRuleIds;
|
|
602
|
+
disabledRuleIds;
|
|
603
|
+
targetNodeId;
|
|
604
|
+
constructor(options = {}) {
|
|
605
|
+
this.configs = options.configs ?? RULE_CONFIGS;
|
|
606
|
+
this.enabledRuleIds = options.enabledRules ? new Set(options.enabledRules) : null;
|
|
607
|
+
this.disabledRuleIds = new Set(options.disabledRules ?? []);
|
|
608
|
+
this.targetNodeId = options.targetNodeId;
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Analyze a Figma file and return issues
|
|
612
|
+
*/
|
|
613
|
+
analyze(file) {
|
|
614
|
+
let rootNode = file.document;
|
|
615
|
+
if (this.targetNodeId) {
|
|
616
|
+
const targetNode = findNodeById(file.document, this.targetNodeId);
|
|
617
|
+
if (!targetNode) {
|
|
618
|
+
throw new Error(`Node not found: ${this.targetNodeId}`);
|
|
619
|
+
}
|
|
620
|
+
rootNode = targetNode;
|
|
621
|
+
}
|
|
622
|
+
const maxDepth = calculateMaxDepth(rootNode);
|
|
623
|
+
const nodeCount = countNodes(rootNode);
|
|
624
|
+
const issues = [];
|
|
625
|
+
const enabledRules = this.getEnabledRules();
|
|
626
|
+
this.traverseAndCheck(
|
|
627
|
+
rootNode,
|
|
628
|
+
file,
|
|
629
|
+
enabledRules,
|
|
630
|
+
maxDepth,
|
|
631
|
+
issues,
|
|
632
|
+
0,
|
|
633
|
+
[],
|
|
634
|
+
void 0,
|
|
635
|
+
void 0
|
|
636
|
+
);
|
|
637
|
+
return {
|
|
638
|
+
file,
|
|
639
|
+
issues,
|
|
640
|
+
maxDepth,
|
|
641
|
+
nodeCount,
|
|
642
|
+
analyzedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
/**
|
|
646
|
+
* Get rules that should be run based on configuration
|
|
647
|
+
*/
|
|
648
|
+
getEnabledRules() {
|
|
649
|
+
return ruleRegistry.getAll().filter((rule) => {
|
|
650
|
+
const ruleId = rule.definition.id;
|
|
651
|
+
if (this.disabledRuleIds.has(ruleId)) return false;
|
|
652
|
+
if (this.enabledRuleIds && !this.enabledRuleIds.has(ruleId)) return false;
|
|
653
|
+
const config = this.configs[ruleId];
|
|
654
|
+
return config?.enabled ?? true;
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Recursively traverse the tree and run rules
|
|
659
|
+
*/
|
|
660
|
+
traverseAndCheck(node, file, rules, maxDepth, issues, depth, path, parent, siblings) {
|
|
661
|
+
const nodePath = [...path, node.name];
|
|
662
|
+
const context = {
|
|
663
|
+
file,
|
|
664
|
+
parent,
|
|
665
|
+
depth,
|
|
666
|
+
maxDepth,
|
|
667
|
+
path: nodePath,
|
|
668
|
+
siblings
|
|
669
|
+
};
|
|
670
|
+
for (const rule of rules) {
|
|
671
|
+
const ruleId = rule.definition.id;
|
|
672
|
+
const config = this.configs[ruleId];
|
|
673
|
+
const options = config?.options;
|
|
674
|
+
try {
|
|
675
|
+
const violation = rule.check(node, context, options);
|
|
676
|
+
if (violation) {
|
|
677
|
+
let calculatedScore = config.score;
|
|
678
|
+
if (supportsDepthWeight(rule.definition.category) && config.depthWeight) {
|
|
679
|
+
const weight = calcDepthWeight(depth, maxDepth, config.depthWeight);
|
|
680
|
+
calculatedScore = Math.round(config.score * weight);
|
|
681
|
+
}
|
|
682
|
+
issues.push({
|
|
683
|
+
violation,
|
|
684
|
+
rule,
|
|
685
|
+
config,
|
|
686
|
+
depth,
|
|
687
|
+
maxDepth,
|
|
688
|
+
calculatedScore
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
} catch (error) {
|
|
692
|
+
console.error(`Rule "${ruleId}" threw error on node "${node.name}":`, error);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
if (node.children && node.children.length > 0) {
|
|
696
|
+
for (const child of node.children) {
|
|
697
|
+
this.traverseAndCheck(
|
|
698
|
+
child,
|
|
699
|
+
file,
|
|
700
|
+
rules,
|
|
701
|
+
maxDepth,
|
|
702
|
+
issues,
|
|
703
|
+
depth + 1,
|
|
704
|
+
nodePath,
|
|
705
|
+
node,
|
|
706
|
+
node.children
|
|
707
|
+
);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
function createRuleEngine(options) {
|
|
713
|
+
return new RuleEngine(options);
|
|
714
|
+
}
|
|
715
|
+
function analyzeFile(file, options) {
|
|
716
|
+
const engine = createRuleEngine(options);
|
|
717
|
+
return engine.analyze(file);
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
// src/core/scoring.ts
|
|
721
|
+
var SEVERITY_DENSITY_WEIGHT = {
|
|
722
|
+
blocking: 3,
|
|
723
|
+
risk: 2,
|
|
724
|
+
"missing-info": 1,
|
|
725
|
+
suggestion: 0.5
|
|
726
|
+
};
|
|
727
|
+
var TOTAL_RULES_PER_CATEGORY = {
|
|
728
|
+
layout: 11,
|
|
729
|
+
token: 7,
|
|
730
|
+
component: 6,
|
|
731
|
+
naming: 5,
|
|
732
|
+
"ai-readability": 5,
|
|
733
|
+
"handoff-risk": 5
|
|
734
|
+
};
|
|
735
|
+
var CATEGORY_WEIGHT = {
|
|
736
|
+
layout: 1,
|
|
737
|
+
token: 1,
|
|
738
|
+
component: 1,
|
|
739
|
+
naming: 1,
|
|
740
|
+
"ai-readability": 1,
|
|
741
|
+
"handoff-risk": 1
|
|
742
|
+
};
|
|
743
|
+
var DENSITY_WEIGHT = 0.7;
|
|
744
|
+
var DIVERSITY_WEIGHT = 0.3;
|
|
745
|
+
var SCORE_FLOOR = 5;
|
|
746
|
+
function calculateGrade(percentage) {
|
|
747
|
+
if (percentage >= 95) return "S";
|
|
748
|
+
if (percentage >= 90) return "A+";
|
|
749
|
+
if (percentage >= 85) return "A";
|
|
750
|
+
if (percentage >= 80) return "B+";
|
|
751
|
+
if (percentage >= 75) return "B";
|
|
752
|
+
if (percentage >= 70) return "C+";
|
|
753
|
+
if (percentage >= 65) return "C";
|
|
754
|
+
if (percentage >= 50) return "D";
|
|
755
|
+
return "F";
|
|
756
|
+
}
|
|
757
|
+
function gradeToClassName(grade) {
|
|
758
|
+
return grade.replace("+", "plus");
|
|
759
|
+
}
|
|
760
|
+
function clamp(value, min, max) {
|
|
761
|
+
return Math.max(min, Math.min(max, value));
|
|
762
|
+
}
|
|
763
|
+
function calculateScores(result) {
|
|
764
|
+
const categoryScores = initializeCategoryScores();
|
|
765
|
+
const nodeCount = result.nodeCount;
|
|
766
|
+
const uniqueRulesPerCategory = /* @__PURE__ */ new Map();
|
|
767
|
+
for (const category of CATEGORIES) {
|
|
768
|
+
uniqueRulesPerCategory.set(category, /* @__PURE__ */ new Set());
|
|
769
|
+
}
|
|
770
|
+
for (const issue of result.issues) {
|
|
771
|
+
const category = issue.rule.definition.category;
|
|
772
|
+
const severity = issue.config.severity;
|
|
773
|
+
const ruleId = issue.rule.definition.id;
|
|
774
|
+
categoryScores[category].issueCount++;
|
|
775
|
+
categoryScores[category].bySeverity[severity]++;
|
|
776
|
+
categoryScores[category].weightedIssueCount += SEVERITY_DENSITY_WEIGHT[severity];
|
|
777
|
+
uniqueRulesPerCategory.get(category).add(ruleId);
|
|
778
|
+
}
|
|
779
|
+
for (const category of CATEGORIES) {
|
|
780
|
+
const catScore = categoryScores[category];
|
|
781
|
+
const uniqueRules = uniqueRulesPerCategory.get(category);
|
|
782
|
+
const totalRules = TOTAL_RULES_PER_CATEGORY[category];
|
|
783
|
+
catScore.uniqueRuleCount = uniqueRules.size;
|
|
784
|
+
let densityScore = 100;
|
|
785
|
+
if (nodeCount > 0 && catScore.issueCount > 0) {
|
|
786
|
+
const density = catScore.weightedIssueCount / nodeCount;
|
|
787
|
+
densityScore = clamp(Math.round(100 - density * 100), 0, 100);
|
|
788
|
+
}
|
|
789
|
+
catScore.densityScore = densityScore;
|
|
790
|
+
let diversityScore = 100;
|
|
791
|
+
if (catScore.issueCount > 0) {
|
|
792
|
+
const diversityRatio = uniqueRules.size / totalRules;
|
|
793
|
+
diversityScore = clamp(Math.round((1 - diversityRatio) * 100), 0, 100);
|
|
794
|
+
}
|
|
795
|
+
catScore.diversityScore = diversityScore;
|
|
796
|
+
const combinedScore = densityScore * DENSITY_WEIGHT + diversityScore * DIVERSITY_WEIGHT;
|
|
797
|
+
catScore.percentage = catScore.issueCount > 0 ? clamp(Math.round(combinedScore), SCORE_FLOOR, 100) : 100;
|
|
798
|
+
catScore.score = catScore.percentage;
|
|
799
|
+
catScore.maxScore = 100;
|
|
800
|
+
}
|
|
801
|
+
let totalWeight = 0;
|
|
802
|
+
let weightedSum = 0;
|
|
803
|
+
for (const category of CATEGORIES) {
|
|
804
|
+
const weight = CATEGORY_WEIGHT[category];
|
|
805
|
+
weightedSum += categoryScores[category].percentage * weight;
|
|
806
|
+
totalWeight += weight;
|
|
807
|
+
}
|
|
808
|
+
const overallPercentage = totalWeight > 0 ? Math.round(weightedSum / totalWeight) : 100;
|
|
809
|
+
const summary = {
|
|
810
|
+
totalIssues: result.issues.length,
|
|
811
|
+
blocking: 0,
|
|
812
|
+
risk: 0,
|
|
813
|
+
missingInfo: 0,
|
|
814
|
+
suggestion: 0,
|
|
815
|
+
nodeCount
|
|
816
|
+
};
|
|
817
|
+
for (const issue of result.issues) {
|
|
818
|
+
switch (issue.config.severity) {
|
|
819
|
+
case "blocking":
|
|
820
|
+
summary.blocking++;
|
|
821
|
+
break;
|
|
822
|
+
case "risk":
|
|
823
|
+
summary.risk++;
|
|
824
|
+
break;
|
|
825
|
+
case "missing-info":
|
|
826
|
+
summary.missingInfo++;
|
|
827
|
+
break;
|
|
828
|
+
case "suggestion":
|
|
829
|
+
summary.suggestion++;
|
|
830
|
+
break;
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
return {
|
|
834
|
+
overall: {
|
|
835
|
+
score: overallPercentage,
|
|
836
|
+
maxScore: 100,
|
|
837
|
+
percentage: overallPercentage,
|
|
838
|
+
grade: calculateGrade(overallPercentage)
|
|
839
|
+
},
|
|
840
|
+
byCategory: categoryScores,
|
|
841
|
+
summary
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
function initializeCategoryScores() {
|
|
845
|
+
const scores = {};
|
|
846
|
+
for (const category of CATEGORIES) {
|
|
847
|
+
scores[category] = {
|
|
848
|
+
category,
|
|
849
|
+
score: 100,
|
|
850
|
+
maxScore: 100,
|
|
851
|
+
percentage: 100,
|
|
852
|
+
issueCount: 0,
|
|
853
|
+
uniqueRuleCount: 0,
|
|
854
|
+
weightedIssueCount: 0,
|
|
855
|
+
densityScore: 100,
|
|
856
|
+
diversityScore: 100,
|
|
857
|
+
bySeverity: {
|
|
858
|
+
blocking: 0,
|
|
859
|
+
risk: 0,
|
|
860
|
+
"missing-info": 0,
|
|
861
|
+
suggestion: 0
|
|
862
|
+
}
|
|
863
|
+
};
|
|
864
|
+
}
|
|
865
|
+
return scores;
|
|
866
|
+
}
|
|
867
|
+
function formatScoreSummary(report) {
|
|
868
|
+
const lines = [];
|
|
869
|
+
lines.push(`Overall: ${report.overall.grade} (${report.overall.percentage}%)`);
|
|
870
|
+
lines.push("");
|
|
871
|
+
lines.push("By Category:");
|
|
872
|
+
for (const category of CATEGORIES) {
|
|
873
|
+
const cat = report.byCategory[category];
|
|
874
|
+
lines.push(` ${category}: ${cat.percentage}% (${cat.issueCount} issues, ${cat.uniqueRuleCount} rules)`);
|
|
875
|
+
}
|
|
876
|
+
lines.push("");
|
|
877
|
+
lines.push("Issues:");
|
|
878
|
+
lines.push(` Blocking: ${report.summary.blocking}`);
|
|
879
|
+
lines.push(` Risk: ${report.summary.risk}`);
|
|
880
|
+
lines.push(` Missing Info: ${report.summary.missingInfo}`);
|
|
881
|
+
lines.push(` Suggestion: ${report.summary.suggestion}`);
|
|
882
|
+
lines.push(` Total: ${report.summary.totalIssues}`);
|
|
883
|
+
return lines.join("\n");
|
|
884
|
+
}
|
|
885
|
+
function getCategoryLabel(category) {
|
|
886
|
+
const labels = {
|
|
887
|
+
layout: "Layout",
|
|
888
|
+
token: "Design Token",
|
|
889
|
+
component: "Component",
|
|
890
|
+
naming: "Naming",
|
|
891
|
+
"ai-readability": "AI Readability",
|
|
892
|
+
"handoff-risk": "Handoff Risk"
|
|
893
|
+
};
|
|
894
|
+
return labels[category];
|
|
895
|
+
}
|
|
896
|
+
function getSeverityLabel(severity) {
|
|
897
|
+
const labels = {
|
|
898
|
+
blocking: "Blocking",
|
|
899
|
+
risk: "Risk",
|
|
900
|
+
"missing-info": "Missing Info",
|
|
901
|
+
suggestion: "Suggestion"
|
|
902
|
+
};
|
|
903
|
+
return labels[severity];
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
// src/rules/layout/index.ts
|
|
907
|
+
function isContainerNode(node) {
|
|
908
|
+
return node.type === "FRAME" || node.type === "GROUP" || node.type === "COMPONENT";
|
|
909
|
+
}
|
|
910
|
+
function hasAutoLayout(node) {
|
|
911
|
+
return node.layoutMode !== void 0 && node.layoutMode !== "NONE";
|
|
912
|
+
}
|
|
913
|
+
function hasTextContent(node) {
|
|
914
|
+
return node.type === "TEXT" || (node.children?.some((c) => c.type === "TEXT") ?? false);
|
|
915
|
+
}
|
|
916
|
+
var noAutoLayoutDef = {
|
|
917
|
+
id: "no-auto-layout",
|
|
918
|
+
name: "No Auto Layout",
|
|
919
|
+
category: "layout",
|
|
920
|
+
why: "Frames without Auto Layout require manual positioning for every element",
|
|
921
|
+
impact: "Layout breaks on content changes, harder to maintain and scale",
|
|
922
|
+
fix: "Apply Auto Layout to the frame with appropriate direction and spacing"
|
|
923
|
+
};
|
|
924
|
+
var noAutoLayoutCheck = (node, context) => {
|
|
925
|
+
if (node.type !== "FRAME") return null;
|
|
926
|
+
if (hasAutoLayout(node)) return null;
|
|
927
|
+
if (!node.children || node.children.length === 0) return null;
|
|
928
|
+
return {
|
|
929
|
+
ruleId: noAutoLayoutDef.id,
|
|
930
|
+
nodeId: node.id,
|
|
931
|
+
nodePath: context.path.join(" > "),
|
|
932
|
+
message: `Frame "${node.name}" has no Auto Layout`
|
|
933
|
+
};
|
|
934
|
+
};
|
|
935
|
+
var noAutoLayout = defineRule({
|
|
936
|
+
definition: noAutoLayoutDef,
|
|
937
|
+
check: noAutoLayoutCheck
|
|
938
|
+
});
|
|
939
|
+
var absolutePositionInAutoLayoutDef = {
|
|
940
|
+
id: "absolute-position-in-auto-layout",
|
|
941
|
+
name: "Absolute Position in Auto Layout",
|
|
942
|
+
category: "layout",
|
|
943
|
+
why: "Absolute positioning inside Auto Layout breaks the automatic flow",
|
|
944
|
+
impact: "Element will not respond to sibling changes, may overlap unexpectedly",
|
|
945
|
+
fix: "Remove absolute positioning or use proper Auto Layout alignment"
|
|
946
|
+
};
|
|
947
|
+
var INTENTIONAL_ABSOLUTE_PATTERNS = /^(badge|close|dismiss|overlay|float|fab|dot|indicator|corner|decoration|tag|status|notification|x|icon[-_ ]?(close|dismiss|x)|btn[-_ ]?(close|dismiss))/i;
|
|
948
|
+
function isSmallRelativeToParent(node, parent) {
|
|
949
|
+
const nodeBB = node.absoluteBoundingBox;
|
|
950
|
+
const parentBB = parent.absoluteBoundingBox;
|
|
951
|
+
if (!nodeBB || !parentBB) return false;
|
|
952
|
+
if (parentBB.width === 0 || parentBB.height === 0) return false;
|
|
953
|
+
const widthRatio = nodeBB.width / parentBB.width;
|
|
954
|
+
const heightRatio = nodeBB.height / parentBB.height;
|
|
955
|
+
return widthRatio < 0.25 && heightRatio < 0.25;
|
|
956
|
+
}
|
|
957
|
+
var absolutePositionInAutoLayoutCheck = (node, context) => {
|
|
958
|
+
if (!context.parent) return null;
|
|
959
|
+
if (!hasAutoLayout(context.parent)) return null;
|
|
960
|
+
if (node.layoutPositioning !== "ABSOLUTE") return null;
|
|
961
|
+
if (INTENTIONAL_ABSOLUTE_PATTERNS.test(node.name)) return null;
|
|
962
|
+
if (isSmallRelativeToParent(node, context.parent)) return null;
|
|
963
|
+
if (context.parent.type === "COMPONENT") return null;
|
|
964
|
+
return {
|
|
965
|
+
ruleId: absolutePositionInAutoLayoutDef.id,
|
|
966
|
+
nodeId: node.id,
|
|
967
|
+
nodePath: context.path.join(" > "),
|
|
968
|
+
message: `"${node.name}" uses absolute positioning inside Auto Layout parent "${context.parent.name}". If intentional (badge, overlay, close button), rename to badge-*, overlay-*, close-* to suppress this warning.`
|
|
969
|
+
};
|
|
970
|
+
};
|
|
971
|
+
var absolutePositionInAutoLayout = defineRule({
|
|
972
|
+
definition: absolutePositionInAutoLayoutDef,
|
|
973
|
+
check: absolutePositionInAutoLayoutCheck
|
|
974
|
+
});
|
|
975
|
+
var fixedWidthInResponsiveContextDef = {
|
|
976
|
+
id: "fixed-width-in-responsive-context",
|
|
977
|
+
name: "Fixed Width in Responsive Context",
|
|
978
|
+
category: "layout",
|
|
979
|
+
why: "Fixed width inside Auto Layout prevents responsive behavior",
|
|
980
|
+
impact: "Content will not adapt to container size changes",
|
|
981
|
+
fix: "Use 'Fill' or 'Hug' instead of fixed width"
|
|
982
|
+
};
|
|
983
|
+
var fixedWidthInResponsiveContextCheck = (node, context) => {
|
|
984
|
+
if (!context.parent) return null;
|
|
985
|
+
if (!hasAutoLayout(context.parent)) return null;
|
|
986
|
+
if (!isContainerNode(node)) return null;
|
|
987
|
+
if (node.layoutAlign === "STRETCH") return null;
|
|
988
|
+
const bbox = node.absoluteBoundingBox;
|
|
989
|
+
if (!bbox) return null;
|
|
990
|
+
if (node.layoutAlign !== "INHERIT") return null;
|
|
991
|
+
return {
|
|
992
|
+
ruleId: fixedWidthInResponsiveContextDef.id,
|
|
993
|
+
nodeId: node.id,
|
|
994
|
+
nodePath: context.path.join(" > "),
|
|
995
|
+
message: `"${node.name}" has fixed width inside Auto Layout`
|
|
996
|
+
};
|
|
997
|
+
};
|
|
998
|
+
var fixedWidthInResponsiveContext = defineRule({
|
|
999
|
+
definition: fixedWidthInResponsiveContextDef,
|
|
1000
|
+
check: fixedWidthInResponsiveContextCheck
|
|
1001
|
+
});
|
|
1002
|
+
var missingResponsiveBehaviorDef = {
|
|
1003
|
+
id: "missing-responsive-behavior",
|
|
1004
|
+
name: "Missing Responsive Behavior",
|
|
1005
|
+
category: "layout",
|
|
1006
|
+
why: "Elements without constraints won't adapt to different screen sizes",
|
|
1007
|
+
impact: "Layout will break or look wrong on different devices",
|
|
1008
|
+
fix: "Set appropriate constraints (left/right, top/bottom, scale, etc.)"
|
|
1009
|
+
};
|
|
1010
|
+
var missingResponsiveBehaviorCheck = (node, context) => {
|
|
1011
|
+
if (!isContainerNode(node)) return null;
|
|
1012
|
+
if (context.parent && hasAutoLayout(context.parent)) return null;
|
|
1013
|
+
if (context.depth < 2) return null;
|
|
1014
|
+
if (!hasAutoLayout(node) && !node.layoutAlign) {
|
|
1015
|
+
return {
|
|
1016
|
+
ruleId: missingResponsiveBehaviorDef.id,
|
|
1017
|
+
nodeId: node.id,
|
|
1018
|
+
nodePath: context.path.join(" > "),
|
|
1019
|
+
message: `"${node.name}" has no responsive behavior configured`
|
|
1020
|
+
};
|
|
1021
|
+
}
|
|
1022
|
+
return null;
|
|
1023
|
+
};
|
|
1024
|
+
var missingResponsiveBehavior = defineRule({
|
|
1025
|
+
definition: missingResponsiveBehaviorDef,
|
|
1026
|
+
check: missingResponsiveBehaviorCheck
|
|
1027
|
+
});
|
|
1028
|
+
var groupUsageDef = {
|
|
1029
|
+
id: "group-usage",
|
|
1030
|
+
name: "Group Usage",
|
|
1031
|
+
category: "layout",
|
|
1032
|
+
why: "Groups don't support Auto Layout and have limited layout control",
|
|
1033
|
+
impact: "Harder to maintain consistent spacing and alignment",
|
|
1034
|
+
fix: "Convert Group to Frame and apply Auto Layout"
|
|
1035
|
+
};
|
|
1036
|
+
var groupUsageCheck = (node, context) => {
|
|
1037
|
+
if (node.type !== "GROUP") return null;
|
|
1038
|
+
return {
|
|
1039
|
+
ruleId: groupUsageDef.id,
|
|
1040
|
+
nodeId: node.id,
|
|
1041
|
+
nodePath: context.path.join(" > "),
|
|
1042
|
+
message: `"${node.name}" is a Group - consider converting to Frame with Auto Layout`
|
|
1043
|
+
};
|
|
1044
|
+
};
|
|
1045
|
+
var groupUsage = defineRule({
|
|
1046
|
+
definition: groupUsageDef,
|
|
1047
|
+
check: groupUsageCheck
|
|
1048
|
+
});
|
|
1049
|
+
var fixedSizeInAutoLayoutDef = {
|
|
1050
|
+
id: "fixed-size-in-auto-layout",
|
|
1051
|
+
name: "Fixed Size in Auto Layout",
|
|
1052
|
+
category: "layout",
|
|
1053
|
+
why: "Fixed sizes inside Auto Layout limit flexibility",
|
|
1054
|
+
impact: "Element won't adapt to content or container changes",
|
|
1055
|
+
fix: "Consider using 'Hug' for content-driven sizing"
|
|
1056
|
+
};
|
|
1057
|
+
var fixedSizeInAutoLayoutCheck = (node, context) => {
|
|
1058
|
+
if (!context.parent) return null;
|
|
1059
|
+
if (!hasAutoLayout(context.parent)) return null;
|
|
1060
|
+
if (!isContainerNode(node)) return null;
|
|
1061
|
+
if (!node.absoluteBoundingBox) return null;
|
|
1062
|
+
const { width, height } = node.absoluteBoundingBox;
|
|
1063
|
+
if (width <= 48 && height <= 48) return null;
|
|
1064
|
+
return null;
|
|
1065
|
+
};
|
|
1066
|
+
var fixedSizeInAutoLayout = defineRule({
|
|
1067
|
+
definition: fixedSizeInAutoLayoutDef,
|
|
1068
|
+
check: fixedSizeInAutoLayoutCheck
|
|
1069
|
+
});
|
|
1070
|
+
var missingMinWidthDef = {
|
|
1071
|
+
id: "missing-min-width",
|
|
1072
|
+
name: "Missing Min Width",
|
|
1073
|
+
category: "layout",
|
|
1074
|
+
why: "Without min-width, containers can collapse to unusable sizes",
|
|
1075
|
+
impact: "Text truncation or layout collapse on narrow screens",
|
|
1076
|
+
fix: "Set a minimum width constraint on the container"
|
|
1077
|
+
};
|
|
1078
|
+
var missingMinWidthCheck = (node, context) => {
|
|
1079
|
+
if (!isContainerNode(node) && !hasTextContent(node)) return null;
|
|
1080
|
+
if (node.absoluteBoundingBox) {
|
|
1081
|
+
const { width, height } = node.absoluteBoundingBox;
|
|
1082
|
+
if (width <= 48 && height <= 24) return null;
|
|
1083
|
+
}
|
|
1084
|
+
if (!context.parent || !hasAutoLayout(context.parent)) return null;
|
|
1085
|
+
return null;
|
|
1086
|
+
};
|
|
1087
|
+
var missingMinWidth = defineRule({
|
|
1088
|
+
definition: missingMinWidthDef,
|
|
1089
|
+
check: missingMinWidthCheck
|
|
1090
|
+
});
|
|
1091
|
+
var missingMaxWidthDef = {
|
|
1092
|
+
id: "missing-max-width",
|
|
1093
|
+
name: "Missing Max Width",
|
|
1094
|
+
category: "layout",
|
|
1095
|
+
why: "Without max-width, content can stretch too wide on large screens",
|
|
1096
|
+
impact: "Poor readability and layout on wide screens",
|
|
1097
|
+
fix: "Set a maximum width constraint, especially for text containers"
|
|
1098
|
+
};
|
|
1099
|
+
var missingMaxWidthCheck = (node, _context) => {
|
|
1100
|
+
if (!isContainerNode(node) && !hasTextContent(node)) return null;
|
|
1101
|
+
if (node.absoluteBoundingBox) {
|
|
1102
|
+
const { width } = node.absoluteBoundingBox;
|
|
1103
|
+
if (width <= 200) return null;
|
|
1104
|
+
}
|
|
1105
|
+
return null;
|
|
1106
|
+
};
|
|
1107
|
+
var missingMaxWidth = defineRule({
|
|
1108
|
+
definition: missingMaxWidthDef,
|
|
1109
|
+
check: missingMaxWidthCheck
|
|
1110
|
+
});
|
|
1111
|
+
var deepNestingDef = {
|
|
1112
|
+
id: "deep-nesting",
|
|
1113
|
+
name: "Deep Nesting",
|
|
1114
|
+
category: "layout",
|
|
1115
|
+
why: "Deep nesting makes the structure hard to understand and maintain",
|
|
1116
|
+
impact: "Increases complexity, harder to debug layout issues",
|
|
1117
|
+
fix: "Flatten the structure by removing unnecessary wrapper frames"
|
|
1118
|
+
};
|
|
1119
|
+
var deepNestingCheck = (node, context, options) => {
|
|
1120
|
+
const maxDepth = options?.["maxDepth"] ?? getRuleOption("deep-nesting", "maxDepth", 5);
|
|
1121
|
+
if (context.depth < maxDepth) return null;
|
|
1122
|
+
if (!isContainerNode(node)) return null;
|
|
1123
|
+
return {
|
|
1124
|
+
ruleId: deepNestingDef.id,
|
|
1125
|
+
nodeId: node.id,
|
|
1126
|
+
nodePath: context.path.join(" > "),
|
|
1127
|
+
message: `"${node.name}" is nested ${context.depth} levels deep (max: ${maxDepth})`
|
|
1128
|
+
};
|
|
1129
|
+
};
|
|
1130
|
+
var deepNesting = defineRule({
|
|
1131
|
+
definition: deepNestingDef,
|
|
1132
|
+
check: deepNestingCheck
|
|
1133
|
+
});
|
|
1134
|
+
var overflowHiddenAbuseDef = {
|
|
1135
|
+
id: "overflow-hidden-abuse",
|
|
1136
|
+
name: "Overflow Hidden Abuse",
|
|
1137
|
+
category: "layout",
|
|
1138
|
+
why: "Using clip content to hide layout problems masks underlying issues",
|
|
1139
|
+
impact: "Content may be unintentionally cut off, problems harder to diagnose",
|
|
1140
|
+
fix: "Fix the underlying layout issue instead of hiding overflow"
|
|
1141
|
+
};
|
|
1142
|
+
var overflowHiddenAbuseCheck = (_node, _context) => {
|
|
1143
|
+
return null;
|
|
1144
|
+
};
|
|
1145
|
+
var overflowHiddenAbuse = defineRule({
|
|
1146
|
+
definition: overflowHiddenAbuseDef,
|
|
1147
|
+
check: overflowHiddenAbuseCheck
|
|
1148
|
+
});
|
|
1149
|
+
var inconsistentSiblingLayoutDirectionDef = {
|
|
1150
|
+
id: "inconsistent-sibling-layout-direction",
|
|
1151
|
+
name: "Inconsistent Sibling Layout Direction",
|
|
1152
|
+
category: "layout",
|
|
1153
|
+
why: "Sibling containers with mixed layout directions without clear reason create confusion",
|
|
1154
|
+
impact: "Harder to understand and maintain the design structure",
|
|
1155
|
+
fix: "Use consistent layout direction for similar sibling elements"
|
|
1156
|
+
};
|
|
1157
|
+
var inconsistentSiblingLayoutDirectionCheck = (node, context) => {
|
|
1158
|
+
if (!isContainerNode(node)) return null;
|
|
1159
|
+
if (!context.siblings || context.siblings.length < 2) return null;
|
|
1160
|
+
const siblingContainers = context.siblings.filter(
|
|
1161
|
+
(s) => isContainerNode(s) && s.id !== node.id
|
|
1162
|
+
);
|
|
1163
|
+
if (siblingContainers.length === 0) return null;
|
|
1164
|
+
const myDirection = node.layoutMode;
|
|
1165
|
+
if (!myDirection || myDirection === "NONE") return null;
|
|
1166
|
+
const siblingDirections = siblingContainers.map((s) => s.layoutMode).filter((d) => d && d !== "NONE");
|
|
1167
|
+
if (siblingDirections.length === 0) return null;
|
|
1168
|
+
const allSameSiblingDirection = siblingDirections.every(
|
|
1169
|
+
(d) => d === siblingDirections[0]
|
|
1170
|
+
);
|
|
1171
|
+
if (allSameSiblingDirection && siblingDirections[0] !== myDirection) {
|
|
1172
|
+
if (context.parent?.layoutMode === "HORIZONTAL" && myDirection === "VERTICAL") {
|
|
1173
|
+
return null;
|
|
1174
|
+
}
|
|
1175
|
+
return {
|
|
1176
|
+
ruleId: inconsistentSiblingLayoutDirectionDef.id,
|
|
1177
|
+
nodeId: node.id,
|
|
1178
|
+
nodePath: context.path.join(" > "),
|
|
1179
|
+
message: `"${node.name}" has ${myDirection} layout while siblings use ${siblingDirections[0]}`
|
|
1180
|
+
};
|
|
1181
|
+
}
|
|
1182
|
+
return null;
|
|
1183
|
+
};
|
|
1184
|
+
var inconsistentSiblingLayoutDirection = defineRule({
|
|
1185
|
+
definition: inconsistentSiblingLayoutDirectionDef,
|
|
1186
|
+
check: inconsistentSiblingLayoutDirectionCheck
|
|
1187
|
+
});
|
|
1188
|
+
|
|
1189
|
+
// src/rules/token/index.ts
|
|
1190
|
+
function hasStyleReference(node, styleType) {
|
|
1191
|
+
return node.styles !== void 0 && styleType in node.styles;
|
|
1192
|
+
}
|
|
1193
|
+
function hasBoundVariable(node, key) {
|
|
1194
|
+
return node.boundVariables !== void 0 && key in node.boundVariables;
|
|
1195
|
+
}
|
|
1196
|
+
function isOnGrid(value, gridBase) {
|
|
1197
|
+
return value % gridBase === 0;
|
|
1198
|
+
}
|
|
1199
|
+
var rawColorDef = {
|
|
1200
|
+
id: "raw-color",
|
|
1201
|
+
name: "Raw Color",
|
|
1202
|
+
category: "token",
|
|
1203
|
+
why: "Raw hex colors are not connected to the design system",
|
|
1204
|
+
impact: "Color changes require manual updates across the entire design",
|
|
1205
|
+
fix: "Use a color style or variable instead of raw hex values"
|
|
1206
|
+
};
|
|
1207
|
+
var rawColorCheck = (node, context) => {
|
|
1208
|
+
if (!node.fills || !Array.isArray(node.fills)) return null;
|
|
1209
|
+
if (node.fills.length === 0) return null;
|
|
1210
|
+
if (hasStyleReference(node, "fill")) return null;
|
|
1211
|
+
if (hasBoundVariable(node, "fills")) return null;
|
|
1212
|
+
for (const fill of node.fills) {
|
|
1213
|
+
const fillObj = fill;
|
|
1214
|
+
if (fillObj["type"] === "SOLID" && fillObj["color"]) {
|
|
1215
|
+
return {
|
|
1216
|
+
ruleId: rawColorDef.id,
|
|
1217
|
+
nodeId: node.id,
|
|
1218
|
+
nodePath: context.path.join(" > "),
|
|
1219
|
+
message: `"${node.name}" uses raw color without style or variable`
|
|
1220
|
+
};
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
return null;
|
|
1224
|
+
};
|
|
1225
|
+
var rawColor = defineRule({
|
|
1226
|
+
definition: rawColorDef,
|
|
1227
|
+
check: rawColorCheck
|
|
1228
|
+
});
|
|
1229
|
+
var rawFontDef = {
|
|
1230
|
+
id: "raw-font",
|
|
1231
|
+
name: "Raw Font",
|
|
1232
|
+
category: "token",
|
|
1233
|
+
why: "Text without text styles is disconnected from the type system",
|
|
1234
|
+
impact: "Typography changes require manual updates across the design",
|
|
1235
|
+
fix: "Apply a text style to maintain consistency"
|
|
1236
|
+
};
|
|
1237
|
+
var rawFontCheck = (node, context) => {
|
|
1238
|
+
if (node.type !== "TEXT") return null;
|
|
1239
|
+
if (hasStyleReference(node, "text")) return null;
|
|
1240
|
+
if (hasBoundVariable(node, "fontFamily") || hasBoundVariable(node, "fontSize")) {
|
|
1241
|
+
return null;
|
|
1242
|
+
}
|
|
1243
|
+
return {
|
|
1244
|
+
ruleId: rawFontDef.id,
|
|
1245
|
+
nodeId: node.id,
|
|
1246
|
+
nodePath: context.path.join(" > "),
|
|
1247
|
+
message: `"${node.name}" has no text style applied`
|
|
1248
|
+
};
|
|
1249
|
+
};
|
|
1250
|
+
var rawFont = defineRule({
|
|
1251
|
+
definition: rawFontDef,
|
|
1252
|
+
check: rawFontCheck
|
|
1253
|
+
});
|
|
1254
|
+
var inconsistentSpacingDef = {
|
|
1255
|
+
id: "inconsistent-spacing",
|
|
1256
|
+
name: "Inconsistent Spacing",
|
|
1257
|
+
category: "token",
|
|
1258
|
+
why: "Spacing values outside the grid system break visual consistency",
|
|
1259
|
+
impact: "Inconsistent visual rhythm and harder to maintain",
|
|
1260
|
+
fix: "Use spacing values from the design system grid (e.g., 8pt increments)"
|
|
1261
|
+
};
|
|
1262
|
+
var inconsistentSpacingCheck = (node, context, options) => {
|
|
1263
|
+
const gridBase = options?.["gridBase"] ?? getRuleOption("inconsistent-spacing", "gridBase", 8);
|
|
1264
|
+
const paddings = [
|
|
1265
|
+
node.paddingLeft,
|
|
1266
|
+
node.paddingRight,
|
|
1267
|
+
node.paddingTop,
|
|
1268
|
+
node.paddingBottom
|
|
1269
|
+
].filter((p) => p !== void 0 && p > 0);
|
|
1270
|
+
for (const padding of paddings) {
|
|
1271
|
+
if (!isOnGrid(padding, gridBase)) {
|
|
1272
|
+
return {
|
|
1273
|
+
ruleId: inconsistentSpacingDef.id,
|
|
1274
|
+
nodeId: node.id,
|
|
1275
|
+
nodePath: context.path.join(" > "),
|
|
1276
|
+
message: `"${node.name}" has padding ${padding}px not on ${gridBase}pt grid`
|
|
1277
|
+
};
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
if (node.itemSpacing !== void 0 && node.itemSpacing > 0) {
|
|
1281
|
+
if (!isOnGrid(node.itemSpacing, gridBase)) {
|
|
1282
|
+
return {
|
|
1283
|
+
ruleId: inconsistentSpacingDef.id,
|
|
1284
|
+
nodeId: node.id,
|
|
1285
|
+
nodePath: context.path.join(" > "),
|
|
1286
|
+
message: `"${node.name}" has item spacing ${node.itemSpacing}px not on ${gridBase}pt grid`
|
|
1287
|
+
};
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
return null;
|
|
1291
|
+
};
|
|
1292
|
+
var inconsistentSpacing = defineRule({
|
|
1293
|
+
definition: inconsistentSpacingDef,
|
|
1294
|
+
check: inconsistentSpacingCheck
|
|
1295
|
+
});
|
|
1296
|
+
var magicNumberSpacingDef = {
|
|
1297
|
+
id: "magic-number-spacing",
|
|
1298
|
+
name: "Magic Number Spacing",
|
|
1299
|
+
category: "token",
|
|
1300
|
+
why: "Arbitrary spacing values make the system harder to understand",
|
|
1301
|
+
impact: "Unpredictable spacing, harder to create consistent layouts",
|
|
1302
|
+
fix: "Round spacing to the nearest grid value or use spacing tokens"
|
|
1303
|
+
};
|
|
1304
|
+
var magicNumberSpacingCheck = (node, context, options) => {
|
|
1305
|
+
const gridBase = options?.["gridBase"] ?? getRuleOption("magic-number-spacing", "gridBase", 8);
|
|
1306
|
+
const allSpacings = [
|
|
1307
|
+
node.paddingLeft,
|
|
1308
|
+
node.paddingRight,
|
|
1309
|
+
node.paddingTop,
|
|
1310
|
+
node.paddingBottom,
|
|
1311
|
+
node.itemSpacing
|
|
1312
|
+
].filter((s) => s !== void 0 && s > 0);
|
|
1313
|
+
for (const spacing of allSpacings) {
|
|
1314
|
+
const commonValues = [1, 2, 4];
|
|
1315
|
+
if (!isOnGrid(spacing, gridBase) && !commonValues.includes(spacing)) {
|
|
1316
|
+
if (spacing % 2 !== 0 && spacing > 4) {
|
|
1317
|
+
return {
|
|
1318
|
+
ruleId: magicNumberSpacingDef.id,
|
|
1319
|
+
nodeId: node.id,
|
|
1320
|
+
nodePath: context.path.join(" > "),
|
|
1321
|
+
message: `"${node.name}" uses magic number spacing: ${spacing}px`
|
|
1322
|
+
};
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
return null;
|
|
1327
|
+
};
|
|
1328
|
+
var magicNumberSpacing = defineRule({
|
|
1329
|
+
definition: magicNumberSpacingDef,
|
|
1330
|
+
check: magicNumberSpacingCheck
|
|
1331
|
+
});
|
|
1332
|
+
var rawShadowDef = {
|
|
1333
|
+
id: "raw-shadow",
|
|
1334
|
+
name: "Raw Shadow",
|
|
1335
|
+
category: "token",
|
|
1336
|
+
why: "Shadow effects without styles are disconnected from the design system",
|
|
1337
|
+
impact: "Shadow changes require manual updates across the design",
|
|
1338
|
+
fix: "Create and apply an effect style for shadows"
|
|
1339
|
+
};
|
|
1340
|
+
var rawShadowCheck = (node, context) => {
|
|
1341
|
+
if (!node.effects || !Array.isArray(node.effects)) return null;
|
|
1342
|
+
if (node.effects.length === 0) return null;
|
|
1343
|
+
if (hasStyleReference(node, "effect")) return null;
|
|
1344
|
+
for (const effect of node.effects) {
|
|
1345
|
+
const effectObj = effect;
|
|
1346
|
+
if (effectObj["type"] === "DROP_SHADOW" || effectObj["type"] === "INNER_SHADOW") {
|
|
1347
|
+
return {
|
|
1348
|
+
ruleId: rawShadowDef.id,
|
|
1349
|
+
nodeId: node.id,
|
|
1350
|
+
nodePath: context.path.join(" > "),
|
|
1351
|
+
message: `"${node.name}" has shadow effect without effect style`
|
|
1352
|
+
};
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
return null;
|
|
1356
|
+
};
|
|
1357
|
+
var rawShadow = defineRule({
|
|
1358
|
+
definition: rawShadowDef,
|
|
1359
|
+
check: rawShadowCheck
|
|
1360
|
+
});
|
|
1361
|
+
var rawOpacityDef = {
|
|
1362
|
+
id: "raw-opacity",
|
|
1363
|
+
name: "Raw Opacity",
|
|
1364
|
+
category: "token",
|
|
1365
|
+
why: "Hardcoded opacity values are not connected to design tokens",
|
|
1366
|
+
impact: "Opacity changes require manual updates",
|
|
1367
|
+
fix: "Use opacity variables or consider if opacity is truly needed"
|
|
1368
|
+
};
|
|
1369
|
+
var rawOpacityCheck = (node, _context) => {
|
|
1370
|
+
if (hasBoundVariable(node, "opacity")) return null;
|
|
1371
|
+
return null;
|
|
1372
|
+
};
|
|
1373
|
+
var rawOpacity = defineRule({
|
|
1374
|
+
definition: rawOpacityDef,
|
|
1375
|
+
check: rawOpacityCheck
|
|
1376
|
+
});
|
|
1377
|
+
var multipleFillColorsDef = {
|
|
1378
|
+
id: "multiple-fill-colors",
|
|
1379
|
+
name: "Multiple Fill Colors",
|
|
1380
|
+
category: "token",
|
|
1381
|
+
why: "Similar but slightly different colors indicate inconsistent token usage",
|
|
1382
|
+
impact: "Visual inconsistency and harder to maintain brand colors",
|
|
1383
|
+
fix: "Consolidate to a single color token or style"
|
|
1384
|
+
};
|
|
1385
|
+
var multipleFillColorsCheck = (_node, _context, _options) => {
|
|
1386
|
+
return null;
|
|
1387
|
+
};
|
|
1388
|
+
var multipleFillColors = defineRule({
|
|
1389
|
+
definition: multipleFillColorsDef,
|
|
1390
|
+
check: multipleFillColorsCheck
|
|
1391
|
+
});
|
|
1392
|
+
|
|
1393
|
+
// src/rules/component/index.ts
|
|
1394
|
+
function isComponentInstance(node) {
|
|
1395
|
+
return node.type === "INSTANCE";
|
|
1396
|
+
}
|
|
1397
|
+
function isComponent(node) {
|
|
1398
|
+
return node.type === "COMPONENT" || node.type === "COMPONENT_SET";
|
|
1399
|
+
}
|
|
1400
|
+
function collectFrameNames(node, names = /* @__PURE__ */ new Map()) {
|
|
1401
|
+
if (node.type === "FRAME" && node.name) {
|
|
1402
|
+
const existing = names.get(node.name) ?? [];
|
|
1403
|
+
existing.push(node.id);
|
|
1404
|
+
names.set(node.name, existing);
|
|
1405
|
+
}
|
|
1406
|
+
if (node.children) {
|
|
1407
|
+
for (const child of node.children) {
|
|
1408
|
+
collectFrameNames(child, names);
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
return names;
|
|
1412
|
+
}
|
|
1413
|
+
var missingComponentDef = {
|
|
1414
|
+
id: "missing-component",
|
|
1415
|
+
name: "Missing Component",
|
|
1416
|
+
category: "component",
|
|
1417
|
+
why: "Repeated identical structures should be componentized",
|
|
1418
|
+
impact: "Changes require manual updates in multiple places",
|
|
1419
|
+
fix: "Create a component from the repeated structure"
|
|
1420
|
+
};
|
|
1421
|
+
var missingComponentCheck = (node, context, options) => {
|
|
1422
|
+
if (node.type !== "FRAME") return null;
|
|
1423
|
+
const minRepetitions = options?.["minRepetitions"] ?? getRuleOption("missing-component", "minRepetitions", 3);
|
|
1424
|
+
const frameNames = collectFrameNames(context.file.document);
|
|
1425
|
+
const sameNameFrames = frameNames.get(node.name);
|
|
1426
|
+
if (sameNameFrames && sameNameFrames.length >= minRepetitions) {
|
|
1427
|
+
if (sameNameFrames[0] === node.id) {
|
|
1428
|
+
return {
|
|
1429
|
+
ruleId: missingComponentDef.id,
|
|
1430
|
+
nodeId: node.id,
|
|
1431
|
+
nodePath: context.path.join(" > "),
|
|
1432
|
+
message: `"${node.name}" appears ${sameNameFrames.length} times - consider making it a component`
|
|
1433
|
+
};
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
return null;
|
|
1437
|
+
};
|
|
1438
|
+
var missingComponent = defineRule({
|
|
1439
|
+
definition: missingComponentDef,
|
|
1440
|
+
check: missingComponentCheck
|
|
1441
|
+
});
|
|
1442
|
+
var detachedInstanceDef = {
|
|
1443
|
+
id: "detached-instance",
|
|
1444
|
+
name: "Detached Instance",
|
|
1445
|
+
category: "component",
|
|
1446
|
+
why: "Detached instances lose their connection to the source component",
|
|
1447
|
+
impact: "Updates to the component won't propagate to this instance",
|
|
1448
|
+
fix: "Reset the instance or create a new variant if customization is needed"
|
|
1449
|
+
};
|
|
1450
|
+
var detachedInstanceCheck = (node, context) => {
|
|
1451
|
+
if (node.type !== "FRAME") return null;
|
|
1452
|
+
const components = context.file.components;
|
|
1453
|
+
const nodeName = node.name.toLowerCase();
|
|
1454
|
+
for (const [, component] of Object.entries(components)) {
|
|
1455
|
+
if (nodeName.includes(component.name.toLowerCase())) {
|
|
1456
|
+
return {
|
|
1457
|
+
ruleId: detachedInstanceDef.id,
|
|
1458
|
+
nodeId: node.id,
|
|
1459
|
+
nodePath: context.path.join(" > "),
|
|
1460
|
+
message: `"${node.name}" may be a detached instance of component "${component.name}"`
|
|
1461
|
+
};
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
return null;
|
|
1465
|
+
};
|
|
1466
|
+
var detachedInstance = defineRule({
|
|
1467
|
+
definition: detachedInstanceDef,
|
|
1468
|
+
check: detachedInstanceCheck
|
|
1469
|
+
});
|
|
1470
|
+
var nestedInstanceOverrideDef = {
|
|
1471
|
+
id: "nested-instance-override",
|
|
1472
|
+
name: "Nested Instance Override",
|
|
1473
|
+
category: "component",
|
|
1474
|
+
why: "Excessive overrides in instances make components harder to maintain",
|
|
1475
|
+
impact: "Component updates may not work as expected",
|
|
1476
|
+
fix: "Create a variant or new component for significantly different use cases"
|
|
1477
|
+
};
|
|
1478
|
+
var nestedInstanceOverrideCheck = (node, context) => {
|
|
1479
|
+
if (!isComponentInstance(node)) return null;
|
|
1480
|
+
if (!node.componentProperties) return null;
|
|
1481
|
+
const overrideCount = Object.keys(node.componentProperties).length;
|
|
1482
|
+
if (overrideCount > 5) {
|
|
1483
|
+
return {
|
|
1484
|
+
ruleId: nestedInstanceOverrideDef.id,
|
|
1485
|
+
nodeId: node.id,
|
|
1486
|
+
nodePath: context.path.join(" > "),
|
|
1487
|
+
message: `"${node.name}" has ${overrideCount} property overrides - consider creating a variant`
|
|
1488
|
+
};
|
|
1489
|
+
}
|
|
1490
|
+
return null;
|
|
1491
|
+
};
|
|
1492
|
+
var nestedInstanceOverride = defineRule({
|
|
1493
|
+
definition: nestedInstanceOverrideDef,
|
|
1494
|
+
check: nestedInstanceOverrideCheck
|
|
1495
|
+
});
|
|
1496
|
+
var variantNotUsedDef = {
|
|
1497
|
+
id: "variant-not-used",
|
|
1498
|
+
name: "Variant Not Used",
|
|
1499
|
+
category: "component",
|
|
1500
|
+
why: "Using instances but not leveraging variants defeats their purpose",
|
|
1501
|
+
impact: "Manual changes instead of using designed variants",
|
|
1502
|
+
fix: "Use the appropriate variant instead of overriding the default"
|
|
1503
|
+
};
|
|
1504
|
+
var variantNotUsedCheck = (_node, _context) => {
|
|
1505
|
+
return null;
|
|
1506
|
+
};
|
|
1507
|
+
var variantNotUsed = defineRule({
|
|
1508
|
+
definition: variantNotUsedDef,
|
|
1509
|
+
check: variantNotUsedCheck
|
|
1510
|
+
});
|
|
1511
|
+
var componentPropertyUnusedDef = {
|
|
1512
|
+
id: "component-property-unused",
|
|
1513
|
+
name: "Component Property Unused",
|
|
1514
|
+
category: "component",
|
|
1515
|
+
why: "Component properties should be utilized to expose customization",
|
|
1516
|
+
impact: "Hardcoded values that should be configurable",
|
|
1517
|
+
fix: "Connect the value to a component property"
|
|
1518
|
+
};
|
|
1519
|
+
var componentPropertyUnusedCheck = (node, _context) => {
|
|
1520
|
+
if (!isComponent(node)) return null;
|
|
1521
|
+
if (!node.componentPropertyDefinitions) return null;
|
|
1522
|
+
const definedProps = Object.keys(node.componentPropertyDefinitions);
|
|
1523
|
+
if (definedProps.length === 0) return null;
|
|
1524
|
+
return null;
|
|
1525
|
+
};
|
|
1526
|
+
var componentPropertyUnused = defineRule({
|
|
1527
|
+
definition: componentPropertyUnusedDef,
|
|
1528
|
+
check: componentPropertyUnusedCheck
|
|
1529
|
+
});
|
|
1530
|
+
var singleUseComponentDef = {
|
|
1531
|
+
id: "single-use-component",
|
|
1532
|
+
name: "Single Use Component",
|
|
1533
|
+
category: "component",
|
|
1534
|
+
why: "Components used only once add complexity without reuse benefit",
|
|
1535
|
+
impact: "Unnecessary abstraction increases maintenance overhead",
|
|
1536
|
+
fix: "Consider inlining if this component won't be reused"
|
|
1537
|
+
};
|
|
1538
|
+
var singleUseComponentCheck = (node, context) => {
|
|
1539
|
+
if (!isComponent(node)) return null;
|
|
1540
|
+
let instanceCount = 0;
|
|
1541
|
+
function countInstances(n) {
|
|
1542
|
+
if (n.type === "INSTANCE" && n.componentId === node.id) {
|
|
1543
|
+
instanceCount++;
|
|
1544
|
+
}
|
|
1545
|
+
if (n.children) {
|
|
1546
|
+
for (const child of n.children) {
|
|
1547
|
+
countInstances(child);
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
countInstances(context.file.document);
|
|
1552
|
+
if (instanceCount === 1) {
|
|
1553
|
+
return {
|
|
1554
|
+
ruleId: singleUseComponentDef.id,
|
|
1555
|
+
nodeId: node.id,
|
|
1556
|
+
nodePath: context.path.join(" > "),
|
|
1557
|
+
message: `Component "${node.name}" is only used once`
|
|
1558
|
+
};
|
|
1559
|
+
}
|
|
1560
|
+
return null;
|
|
1561
|
+
};
|
|
1562
|
+
var singleUseComponent = defineRule({
|
|
1563
|
+
definition: singleUseComponentDef,
|
|
1564
|
+
check: singleUseComponentCheck
|
|
1565
|
+
});
|
|
1566
|
+
|
|
1567
|
+
// src/rules/naming/index.ts
|
|
1568
|
+
var DEFAULT_NAME_PATTERNS = [
|
|
1569
|
+
/^Frame\s*\d*$/i,
|
|
1570
|
+
/^Group\s*\d*$/i,
|
|
1571
|
+
/^Rectangle\s*\d*$/i,
|
|
1572
|
+
/^Ellipse\s*\d*$/i,
|
|
1573
|
+
/^Vector\s*\d*$/i,
|
|
1574
|
+
/^Line\s*\d*$/i,
|
|
1575
|
+
/^Text\s*\d*$/i,
|
|
1576
|
+
/^Image\s*\d*$/i,
|
|
1577
|
+
/^Component\s*\d*$/i,
|
|
1578
|
+
/^Instance\s*\d*$/i
|
|
1579
|
+
];
|
|
1580
|
+
var NON_SEMANTIC_NAMES = [
|
|
1581
|
+
"rectangle",
|
|
1582
|
+
"ellipse",
|
|
1583
|
+
"vector",
|
|
1584
|
+
"line",
|
|
1585
|
+
"polygon",
|
|
1586
|
+
"star",
|
|
1587
|
+
"path",
|
|
1588
|
+
"shape",
|
|
1589
|
+
"image",
|
|
1590
|
+
"fill",
|
|
1591
|
+
"stroke"
|
|
1592
|
+
];
|
|
1593
|
+
function isDefaultName(name) {
|
|
1594
|
+
return DEFAULT_NAME_PATTERNS.some((pattern) => pattern.test(name));
|
|
1595
|
+
}
|
|
1596
|
+
function isNonSemanticName(name) {
|
|
1597
|
+
const normalized = name.toLowerCase().trim();
|
|
1598
|
+
return NON_SEMANTIC_NAMES.includes(normalized);
|
|
1599
|
+
}
|
|
1600
|
+
function hasNumericSuffix(name) {
|
|
1601
|
+
return /\s+\d+$/.test(name);
|
|
1602
|
+
}
|
|
1603
|
+
function detectNamingConvention(name) {
|
|
1604
|
+
if (/^[a-z]+(-[a-z]+)*$/.test(name)) return "kebab-case";
|
|
1605
|
+
if (/^[a-z]+(_[a-z]+)*$/.test(name)) return "snake_case";
|
|
1606
|
+
if (/^[a-z]+([A-Z][a-z]*)*$/.test(name)) return "camelCase";
|
|
1607
|
+
if (/^[A-Z][a-z]+([A-Z][a-z]*)*$/.test(name)) return "PascalCase";
|
|
1608
|
+
if (/^[A-Z]+(_[A-Z]+)*$/.test(name)) return "SCREAMING_SNAKE_CASE";
|
|
1609
|
+
if (/\s/.test(name)) return "Title Case";
|
|
1610
|
+
return null;
|
|
1611
|
+
}
|
|
1612
|
+
var defaultNameDef = {
|
|
1613
|
+
id: "default-name",
|
|
1614
|
+
name: "Default Name",
|
|
1615
|
+
category: "naming",
|
|
1616
|
+
why: "Default names like 'Frame 123' provide no context about the element's purpose",
|
|
1617
|
+
impact: "Designers and developers cannot understand the structure",
|
|
1618
|
+
fix: "Rename with a descriptive, semantic name (e.g., 'Header', 'ProductCard')"
|
|
1619
|
+
};
|
|
1620
|
+
var defaultNameCheck = (node, context) => {
|
|
1621
|
+
if (!node.name) return null;
|
|
1622
|
+
if (!isDefaultName(node.name)) return null;
|
|
1623
|
+
return {
|
|
1624
|
+
ruleId: defaultNameDef.id,
|
|
1625
|
+
nodeId: node.id,
|
|
1626
|
+
nodePath: context.path.join(" > "),
|
|
1627
|
+
message: `"${node.name}" is a default name - provide a meaningful name`
|
|
1628
|
+
};
|
|
1629
|
+
};
|
|
1630
|
+
var defaultName = defineRule({
|
|
1631
|
+
definition: defaultNameDef,
|
|
1632
|
+
check: defaultNameCheck
|
|
1633
|
+
});
|
|
1634
|
+
var nonSemanticNameDef = {
|
|
1635
|
+
id: "non-semantic-name",
|
|
1636
|
+
name: "Non-Semantic Name",
|
|
1637
|
+
category: "naming",
|
|
1638
|
+
why: "Names like 'Rectangle' describe shape, not purpose",
|
|
1639
|
+
impact: "Structure is hard to understand without context",
|
|
1640
|
+
fix: "Use names that describe what the element represents (e.g., 'Divider', 'Avatar')"
|
|
1641
|
+
};
|
|
1642
|
+
var nonSemanticNameCheck = (node, context) => {
|
|
1643
|
+
if (!node.name) return null;
|
|
1644
|
+
if (!isNonSemanticName(node.name)) return null;
|
|
1645
|
+
if (!node.children || node.children.length === 0) {
|
|
1646
|
+
const shapeTypes = ["RECTANGLE", "ELLIPSE", "VECTOR", "LINE", "STAR", "REGULAR_POLYGON"];
|
|
1647
|
+
if (shapeTypes.includes(node.type)) return null;
|
|
1648
|
+
}
|
|
1649
|
+
return {
|
|
1650
|
+
ruleId: nonSemanticNameDef.id,
|
|
1651
|
+
nodeId: node.id,
|
|
1652
|
+
nodePath: context.path.join(" > "),
|
|
1653
|
+
message: `"${node.name}" is a non-semantic name - describe its purpose`
|
|
1654
|
+
};
|
|
1655
|
+
};
|
|
1656
|
+
var nonSemanticName = defineRule({
|
|
1657
|
+
definition: nonSemanticNameDef,
|
|
1658
|
+
check: nonSemanticNameCheck
|
|
1659
|
+
});
|
|
1660
|
+
var inconsistentNamingConventionDef = {
|
|
1661
|
+
id: "inconsistent-naming-convention",
|
|
1662
|
+
name: "Inconsistent Naming Convention",
|
|
1663
|
+
category: "naming",
|
|
1664
|
+
why: "Mixed naming conventions at the same level create confusion",
|
|
1665
|
+
impact: "Harder to navigate and maintain the design",
|
|
1666
|
+
fix: "Use a consistent naming convention for sibling elements"
|
|
1667
|
+
};
|
|
1668
|
+
var inconsistentNamingConventionCheck = (node, context) => {
|
|
1669
|
+
if (!context.siblings || context.siblings.length < 2) return null;
|
|
1670
|
+
const conventions = /* @__PURE__ */ new Map();
|
|
1671
|
+
for (const sibling of context.siblings) {
|
|
1672
|
+
if (!sibling.name) continue;
|
|
1673
|
+
const convention = detectNamingConvention(sibling.name);
|
|
1674
|
+
if (convention) {
|
|
1675
|
+
conventions.set(convention, (conventions.get(convention) ?? 0) + 1);
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
if (conventions.size < 2) return null;
|
|
1679
|
+
let dominantConvention = "";
|
|
1680
|
+
let maxCount = 0;
|
|
1681
|
+
for (const [convention, count] of conventions) {
|
|
1682
|
+
if (count > maxCount) {
|
|
1683
|
+
maxCount = count;
|
|
1684
|
+
dominantConvention = convention;
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
const nodeConvention = detectNamingConvention(node.name);
|
|
1688
|
+
if (nodeConvention && nodeConvention !== dominantConvention && maxCount >= 2) {
|
|
1689
|
+
return {
|
|
1690
|
+
ruleId: inconsistentNamingConventionDef.id,
|
|
1691
|
+
nodeId: node.id,
|
|
1692
|
+
nodePath: context.path.join(" > "),
|
|
1693
|
+
message: `"${node.name}" uses ${nodeConvention} while siblings use ${dominantConvention}`
|
|
1694
|
+
};
|
|
1695
|
+
}
|
|
1696
|
+
return null;
|
|
1697
|
+
};
|
|
1698
|
+
var inconsistentNamingConvention = defineRule({
|
|
1699
|
+
definition: inconsistentNamingConventionDef,
|
|
1700
|
+
check: inconsistentNamingConventionCheck
|
|
1701
|
+
});
|
|
1702
|
+
var numericSuffixNameDef = {
|
|
1703
|
+
id: "numeric-suffix-name",
|
|
1704
|
+
name: "Numeric Suffix Name",
|
|
1705
|
+
category: "naming",
|
|
1706
|
+
why: "Names with numeric suffixes often indicate copy-paste duplication",
|
|
1707
|
+
impact: "Suggests the element might need componentization",
|
|
1708
|
+
fix: "Remove the suffix or create a component if duplicated"
|
|
1709
|
+
};
|
|
1710
|
+
var numericSuffixNameCheck = (node, context) => {
|
|
1711
|
+
if (!node.name) return null;
|
|
1712
|
+
if (isDefaultName(node.name)) return null;
|
|
1713
|
+
if (!hasNumericSuffix(node.name)) return null;
|
|
1714
|
+
return {
|
|
1715
|
+
ruleId: numericSuffixNameDef.id,
|
|
1716
|
+
nodeId: node.id,
|
|
1717
|
+
nodePath: context.path.join(" > "),
|
|
1718
|
+
message: `"${node.name}" has a numeric suffix - consider renaming`
|
|
1719
|
+
};
|
|
1720
|
+
};
|
|
1721
|
+
var numericSuffixName = defineRule({
|
|
1722
|
+
definition: numericSuffixNameDef,
|
|
1723
|
+
check: numericSuffixNameCheck
|
|
1724
|
+
});
|
|
1725
|
+
var tooLongNameDef = {
|
|
1726
|
+
id: "too-long-name",
|
|
1727
|
+
name: "Too Long Name",
|
|
1728
|
+
category: "naming",
|
|
1729
|
+
why: "Very long names are hard to read and use in code",
|
|
1730
|
+
impact: "Clutters the layer panel and makes selectors unwieldy",
|
|
1731
|
+
fix: "Shorten the name while keeping it descriptive"
|
|
1732
|
+
};
|
|
1733
|
+
var tooLongNameCheck = (node, context, options) => {
|
|
1734
|
+
if (!node.name) return null;
|
|
1735
|
+
const maxLength = options?.["maxLength"] ?? getRuleOption("too-long-name", "maxLength", 50);
|
|
1736
|
+
if (node.name.length <= maxLength) return null;
|
|
1737
|
+
return {
|
|
1738
|
+
ruleId: tooLongNameDef.id,
|
|
1739
|
+
nodeId: node.id,
|
|
1740
|
+
nodePath: context.path.join(" > "),
|
|
1741
|
+
message: `"${node.name.substring(0, 30)}..." is ${node.name.length} chars (max: ${maxLength})`
|
|
1742
|
+
};
|
|
1743
|
+
};
|
|
1744
|
+
var tooLongName = defineRule({
|
|
1745
|
+
definition: tooLongNameDef,
|
|
1746
|
+
check: tooLongNameCheck
|
|
1747
|
+
});
|
|
1748
|
+
|
|
1749
|
+
// src/rules/ai-readability/index.ts
|
|
1750
|
+
function hasAutoLayout2(node) {
|
|
1751
|
+
return node.layoutMode !== void 0 && node.layoutMode !== "NONE";
|
|
1752
|
+
}
|
|
1753
|
+
function isContainerNode2(node) {
|
|
1754
|
+
return node.type === "FRAME" || node.type === "GROUP" || node.type === "COMPONENT";
|
|
1755
|
+
}
|
|
1756
|
+
function hasOverlappingBounds(a, b) {
|
|
1757
|
+
const boxA = a.absoluteBoundingBox;
|
|
1758
|
+
const boxB = b.absoluteBoundingBox;
|
|
1759
|
+
if (!boxA || !boxB) return false;
|
|
1760
|
+
return !(boxA.x + boxA.width <= boxB.x || boxB.x + boxB.width <= boxA.x || boxA.y + boxA.height <= boxB.y || boxB.y + boxB.height <= boxA.y);
|
|
1761
|
+
}
|
|
1762
|
+
var ambiguousStructureDef = {
|
|
1763
|
+
id: "ambiguous-structure",
|
|
1764
|
+
name: "Ambiguous Structure",
|
|
1765
|
+
category: "ai-readability",
|
|
1766
|
+
why: "Overlapping nodes without Auto Layout create ambiguous visual hierarchy",
|
|
1767
|
+
impact: "AI cannot reliably determine the reading order or structure",
|
|
1768
|
+
fix: "Use Auto Layout to create clear, explicit structure"
|
|
1769
|
+
};
|
|
1770
|
+
var ambiguousStructureCheck = (node, context) => {
|
|
1771
|
+
if (!isContainerNode2(node)) return null;
|
|
1772
|
+
if (hasAutoLayout2(node)) return null;
|
|
1773
|
+
if (!node.children || node.children.length < 2) return null;
|
|
1774
|
+
for (let i = 0; i < node.children.length; i++) {
|
|
1775
|
+
for (let j = i + 1; j < node.children.length; j++) {
|
|
1776
|
+
const childA = node.children[i];
|
|
1777
|
+
const childB = node.children[j];
|
|
1778
|
+
if (childA && childB && hasOverlappingBounds(childA, childB)) {
|
|
1779
|
+
if (childA.visible !== false && childB.visible !== false) {
|
|
1780
|
+
return {
|
|
1781
|
+
ruleId: ambiguousStructureDef.id,
|
|
1782
|
+
nodeId: node.id,
|
|
1783
|
+
nodePath: context.path.join(" > "),
|
|
1784
|
+
message: `"${node.name}" has overlapping children without Auto Layout`
|
|
1785
|
+
};
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
}
|
|
1790
|
+
return null;
|
|
1791
|
+
};
|
|
1792
|
+
var ambiguousStructure = defineRule({
|
|
1793
|
+
definition: ambiguousStructureDef,
|
|
1794
|
+
check: ambiguousStructureCheck
|
|
1795
|
+
});
|
|
1796
|
+
var zIndexDependentLayoutDef = {
|
|
1797
|
+
id: "z-index-dependent-layout",
|
|
1798
|
+
name: "Z-Index Dependent Layout",
|
|
1799
|
+
category: "ai-readability",
|
|
1800
|
+
why: "Using overlapping layers to create visual layout is hard to interpret",
|
|
1801
|
+
impact: "Code generation may misinterpret the intended layout",
|
|
1802
|
+
fix: "Restructure using Auto Layout to express the visual relationship explicitly"
|
|
1803
|
+
};
|
|
1804
|
+
var zIndexDependentLayoutCheck = (node, context) => {
|
|
1805
|
+
if (!isContainerNode2(node)) return null;
|
|
1806
|
+
if (!node.children || node.children.length < 2) return null;
|
|
1807
|
+
let significantOverlapCount = 0;
|
|
1808
|
+
for (let i = 0; i < node.children.length; i++) {
|
|
1809
|
+
for (let j = i + 1; j < node.children.length; j++) {
|
|
1810
|
+
const childA = node.children[i];
|
|
1811
|
+
const childB = node.children[j];
|
|
1812
|
+
if (!childA || !childB) continue;
|
|
1813
|
+
if (childA.visible === false || childB.visible === false) continue;
|
|
1814
|
+
const boxA = childA.absoluteBoundingBox;
|
|
1815
|
+
const boxB = childB.absoluteBoundingBox;
|
|
1816
|
+
if (!boxA || !boxB) continue;
|
|
1817
|
+
if (hasOverlappingBounds(childA, childB)) {
|
|
1818
|
+
const overlapX = Math.min(boxA.x + boxA.width, boxB.x + boxB.width) - Math.max(boxA.x, boxB.x);
|
|
1819
|
+
const overlapY = Math.min(boxA.y + boxA.height, boxB.y + boxB.height) - Math.max(boxA.y, boxB.y);
|
|
1820
|
+
if (overlapX > 0 && overlapY > 0) {
|
|
1821
|
+
const overlapArea = overlapX * overlapY;
|
|
1822
|
+
const smallerArea = Math.min(
|
|
1823
|
+
boxA.width * boxA.height,
|
|
1824
|
+
boxB.width * boxB.height
|
|
1825
|
+
);
|
|
1826
|
+
if (overlapArea > smallerArea * 0.2) {
|
|
1827
|
+
significantOverlapCount++;
|
|
1828
|
+
}
|
|
1829
|
+
}
|
|
1830
|
+
}
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
if (significantOverlapCount > 0) {
|
|
1834
|
+
return {
|
|
1835
|
+
ruleId: zIndexDependentLayoutDef.id,
|
|
1836
|
+
nodeId: node.id,
|
|
1837
|
+
nodePath: context.path.join(" > "),
|
|
1838
|
+
message: `"${node.name}" uses layer stacking for layout (${significantOverlapCount} overlaps)`
|
|
1839
|
+
};
|
|
1840
|
+
}
|
|
1841
|
+
return null;
|
|
1842
|
+
};
|
|
1843
|
+
var zIndexDependentLayout = defineRule({
|
|
1844
|
+
definition: zIndexDependentLayoutDef,
|
|
1845
|
+
check: zIndexDependentLayoutCheck
|
|
1846
|
+
});
|
|
1847
|
+
var missingLayoutHintDef = {
|
|
1848
|
+
id: "missing-layout-hint",
|
|
1849
|
+
name: "Missing Layout Hint",
|
|
1850
|
+
category: "ai-readability",
|
|
1851
|
+
why: "Complex nesting without Auto Layout makes structure unpredictable",
|
|
1852
|
+
impact: "AI may generate incorrect code due to ambiguous relationships",
|
|
1853
|
+
fix: "Add Auto Layout or simplify the nesting structure"
|
|
1854
|
+
};
|
|
1855
|
+
var missingLayoutHintCheck = (node, context) => {
|
|
1856
|
+
if (!isContainerNode2(node)) return null;
|
|
1857
|
+
if (hasAutoLayout2(node)) return null;
|
|
1858
|
+
if (!node.children || node.children.length === 0) return null;
|
|
1859
|
+
const nestedContainers = node.children.filter((c) => isContainerNode2(c));
|
|
1860
|
+
if (nestedContainers.length >= 2) {
|
|
1861
|
+
const withoutLayout = nestedContainers.filter((c) => !hasAutoLayout2(c));
|
|
1862
|
+
if (withoutLayout.length >= 2) {
|
|
1863
|
+
return {
|
|
1864
|
+
ruleId: missingLayoutHintDef.id,
|
|
1865
|
+
nodeId: node.id,
|
|
1866
|
+
nodePath: context.path.join(" > "),
|
|
1867
|
+
message: `"${node.name}" has ${withoutLayout.length} nested containers without layout hints`
|
|
1868
|
+
};
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
return null;
|
|
1872
|
+
};
|
|
1873
|
+
var missingLayoutHint = defineRule({
|
|
1874
|
+
definition: missingLayoutHintDef,
|
|
1875
|
+
check: missingLayoutHintCheck
|
|
1876
|
+
});
|
|
1877
|
+
var invisibleLayerDef = {
|
|
1878
|
+
id: "invisible-layer",
|
|
1879
|
+
name: "Invisible Layer",
|
|
1880
|
+
category: "ai-readability",
|
|
1881
|
+
why: "Hidden layers add noise and may confuse analysis tools",
|
|
1882
|
+
impact: "Exported code may include unnecessary elements",
|
|
1883
|
+
fix: "Delete hidden layers or move them to a separate 'archive' page"
|
|
1884
|
+
};
|
|
1885
|
+
var invisibleLayerCheck = (node, context) => {
|
|
1886
|
+
if (node.visible !== false) return null;
|
|
1887
|
+
if (context.parent?.visible === false) return null;
|
|
1888
|
+
return {
|
|
1889
|
+
ruleId: invisibleLayerDef.id,
|
|
1890
|
+
nodeId: node.id,
|
|
1891
|
+
nodePath: context.path.join(" > "),
|
|
1892
|
+
message: `"${node.name}" is hidden - consider removing if not needed`
|
|
1893
|
+
};
|
|
1894
|
+
};
|
|
1895
|
+
var invisibleLayer = defineRule({
|
|
1896
|
+
definition: invisibleLayerDef,
|
|
1897
|
+
check: invisibleLayerCheck
|
|
1898
|
+
});
|
|
1899
|
+
var emptyFrameDef = {
|
|
1900
|
+
id: "empty-frame",
|
|
1901
|
+
name: "Empty Frame",
|
|
1902
|
+
category: "ai-readability",
|
|
1903
|
+
why: "Empty frames add noise and may indicate incomplete design",
|
|
1904
|
+
impact: "Generates unnecessary wrapper elements in code",
|
|
1905
|
+
fix: "Remove the frame or add content"
|
|
1906
|
+
};
|
|
1907
|
+
var emptyFrameCheck = (node, context) => {
|
|
1908
|
+
if (node.type !== "FRAME") return null;
|
|
1909
|
+
if (node.children && node.children.length > 0) return null;
|
|
1910
|
+
if (node.absoluteBoundingBox) {
|
|
1911
|
+
const { width, height } = node.absoluteBoundingBox;
|
|
1912
|
+
if (width <= 48 && height <= 48) return null;
|
|
1913
|
+
}
|
|
1914
|
+
return {
|
|
1915
|
+
ruleId: emptyFrameDef.id,
|
|
1916
|
+
nodeId: node.id,
|
|
1917
|
+
nodePath: context.path.join(" > "),
|
|
1918
|
+
message: `"${node.name}" is an empty frame`
|
|
1919
|
+
};
|
|
1920
|
+
};
|
|
1921
|
+
var emptyFrame = defineRule({
|
|
1922
|
+
definition: emptyFrameDef,
|
|
1923
|
+
check: emptyFrameCheck
|
|
1924
|
+
});
|
|
1925
|
+
|
|
1926
|
+
// src/rules/handoff-risk/index.ts
|
|
1927
|
+
function hasAutoLayout3(node) {
|
|
1928
|
+
return node.layoutMode !== void 0 && node.layoutMode !== "NONE";
|
|
1929
|
+
}
|
|
1930
|
+
function isContainerNode3(node) {
|
|
1931
|
+
return node.type === "FRAME" || node.type === "GROUP" || node.type === "COMPONENT";
|
|
1932
|
+
}
|
|
1933
|
+
function isTextNode(node) {
|
|
1934
|
+
return node.type === "TEXT";
|
|
1935
|
+
}
|
|
1936
|
+
function isImageNode(node) {
|
|
1937
|
+
if (node.type === "RECTANGLE" && node.fills) {
|
|
1938
|
+
for (const fill of node.fills) {
|
|
1939
|
+
const fillObj = fill;
|
|
1940
|
+
if (fillObj["type"] === "IMAGE") return true;
|
|
1941
|
+
}
|
|
1942
|
+
}
|
|
1943
|
+
return false;
|
|
1944
|
+
}
|
|
1945
|
+
var hardcodeRiskDef = {
|
|
1946
|
+
id: "hardcode-risk",
|
|
1947
|
+
name: "Hardcode Risk",
|
|
1948
|
+
category: "handoff-risk",
|
|
1949
|
+
why: "Absolute positioning with fixed values creates inflexible layouts",
|
|
1950
|
+
impact: "Layout will break when content changes or on different screens",
|
|
1951
|
+
fix: "Use Auto Layout with relative positioning"
|
|
1952
|
+
};
|
|
1953
|
+
var hardcodeRiskCheck = (node, context) => {
|
|
1954
|
+
if (!isContainerNode3(node)) return null;
|
|
1955
|
+
if (node.layoutPositioning !== "ABSOLUTE") return null;
|
|
1956
|
+
if (context.parent && hasAutoLayout3(context.parent)) {
|
|
1957
|
+
return {
|
|
1958
|
+
ruleId: hardcodeRiskDef.id,
|
|
1959
|
+
nodeId: node.id,
|
|
1960
|
+
nodePath: context.path.join(" > "),
|
|
1961
|
+
message: `"${node.name}" uses absolute positioning with fixed values`
|
|
1962
|
+
};
|
|
1963
|
+
}
|
|
1964
|
+
return null;
|
|
1965
|
+
};
|
|
1966
|
+
var hardcodeRisk = defineRule({
|
|
1967
|
+
definition: hardcodeRiskDef,
|
|
1968
|
+
check: hardcodeRiskCheck
|
|
1969
|
+
});
|
|
1970
|
+
var textTruncationUnhandledDef = {
|
|
1971
|
+
id: "text-truncation-unhandled",
|
|
1972
|
+
name: "Text Truncation Unhandled",
|
|
1973
|
+
category: "handoff-risk",
|
|
1974
|
+
why: "Text nodes without truncation handling may overflow",
|
|
1975
|
+
impact: "Long text will break the layout",
|
|
1976
|
+
fix: "Set text truncation (ellipsis) or ensure container can grow"
|
|
1977
|
+
};
|
|
1978
|
+
var textTruncationUnhandledCheck = (node, context) => {
|
|
1979
|
+
if (!isTextNode(node)) return null;
|
|
1980
|
+
if (!context.parent) return null;
|
|
1981
|
+
if (!hasAutoLayout3(context.parent)) return null;
|
|
1982
|
+
if (node.absoluteBoundingBox) {
|
|
1983
|
+
const { width } = node.absoluteBoundingBox;
|
|
1984
|
+
if (node.characters && node.characters.length > 50 && width < 300) {
|
|
1985
|
+
return {
|
|
1986
|
+
ruleId: textTruncationUnhandledDef.id,
|
|
1987
|
+
nodeId: node.id,
|
|
1988
|
+
nodePath: context.path.join(" > "),
|
|
1989
|
+
message: `"${node.name}" may need text truncation handling`
|
|
1990
|
+
};
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
return null;
|
|
1994
|
+
};
|
|
1995
|
+
var textTruncationUnhandled = defineRule({
|
|
1996
|
+
definition: textTruncationUnhandledDef,
|
|
1997
|
+
check: textTruncationUnhandledCheck
|
|
1998
|
+
});
|
|
1999
|
+
var imageNoPlaceholderDef = {
|
|
2000
|
+
id: "image-no-placeholder",
|
|
2001
|
+
name: "Image No Placeholder",
|
|
2002
|
+
category: "handoff-risk",
|
|
2003
|
+
why: "Images without placeholder state may cause layout shifts",
|
|
2004
|
+
impact: "Poor user experience during image loading",
|
|
2005
|
+
fix: "Define a placeholder state or background color"
|
|
2006
|
+
};
|
|
2007
|
+
var imageNoPlaceholderCheck = (node, context) => {
|
|
2008
|
+
if (!isImageNode(node)) return null;
|
|
2009
|
+
if (node.fills && Array.isArray(node.fills) && node.fills.length === 1) {
|
|
2010
|
+
const fill = node.fills[0];
|
|
2011
|
+
if (fill["type"] === "IMAGE") {
|
|
2012
|
+
return {
|
|
2013
|
+
ruleId: imageNoPlaceholderDef.id,
|
|
2014
|
+
nodeId: node.id,
|
|
2015
|
+
nodePath: context.path.join(" > "),
|
|
2016
|
+
message: `"${node.name}" image has no placeholder fill`
|
|
2017
|
+
};
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
return null;
|
|
2021
|
+
};
|
|
2022
|
+
var imageNoPlaceholder = defineRule({
|
|
2023
|
+
definition: imageNoPlaceholderDef,
|
|
2024
|
+
check: imageNoPlaceholderCheck
|
|
2025
|
+
});
|
|
2026
|
+
var prototypeLinkInDesignDef = {
|
|
2027
|
+
id: "prototype-link-in-design",
|
|
2028
|
+
name: "Prototype Link in Design",
|
|
2029
|
+
category: "handoff-risk",
|
|
2030
|
+
why: "Prototype connections may affect how the design is interpreted",
|
|
2031
|
+
impact: "Developers may misunderstand which elements should be interactive",
|
|
2032
|
+
fix: "Document interactions separately or use clear naming"
|
|
2033
|
+
};
|
|
2034
|
+
var prototypeLinkInDesignCheck = (_node, _context) => {
|
|
2035
|
+
return null;
|
|
2036
|
+
};
|
|
2037
|
+
var prototypeLinkInDesign = defineRule({
|
|
2038
|
+
definition: prototypeLinkInDesignDef,
|
|
2039
|
+
check: prototypeLinkInDesignCheck
|
|
2040
|
+
});
|
|
2041
|
+
var noDevStatusDef = {
|
|
2042
|
+
id: "no-dev-status",
|
|
2043
|
+
name: "No Dev Status",
|
|
2044
|
+
category: "handoff-risk",
|
|
2045
|
+
why: "Without dev status, developers cannot know if a design is ready",
|
|
2046
|
+
impact: "May implement designs that are still in progress",
|
|
2047
|
+
fix: "Mark frames as 'Ready for Dev' or 'Completed' when appropriate"
|
|
2048
|
+
};
|
|
2049
|
+
var noDevStatusCheck = (node, context) => {
|
|
2050
|
+
if (node.type !== "FRAME") return null;
|
|
2051
|
+
if (context.depth > 1) return null;
|
|
2052
|
+
if (node.devStatus) return null;
|
|
2053
|
+
return {
|
|
2054
|
+
ruleId: noDevStatusDef.id,
|
|
2055
|
+
nodeId: node.id,
|
|
2056
|
+
nodePath: context.path.join(" > "),
|
|
2057
|
+
message: `"${node.name}" has no dev status set`
|
|
2058
|
+
};
|
|
2059
|
+
};
|
|
2060
|
+
var noDevStatus = defineRule({
|
|
2061
|
+
definition: noDevStatusDef,
|
|
2062
|
+
check: noDevStatusCheck
|
|
2063
|
+
});
|
|
2064
|
+
var FigmaUrlInfoSchema = z.object({
|
|
2065
|
+
fileKey: z.string(),
|
|
2066
|
+
nodeId: z.string().optional(),
|
|
2067
|
+
fileName: z.string().optional()
|
|
2068
|
+
});
|
|
2069
|
+
var FIGMA_URL_PATTERNS = [
|
|
2070
|
+
// https://www.figma.com/design/FILE_KEY/FILE_NAME?node-id=NODE_ID
|
|
2071
|
+
/figma\.com\/design\/([a-zA-Z0-9]+)(?:\/([^?]+))?(?:\?.*node-id=([^&]+))?/,
|
|
2072
|
+
// https://www.figma.com/file/FILE_KEY/FILE_NAME?node-id=NODE_ID
|
|
2073
|
+
/figma\.com\/file\/([a-zA-Z0-9]+)(?:\/([^?]+))?(?:\?.*node-id=([^&]+))?/,
|
|
2074
|
+
// https://www.figma.com/proto/FILE_KEY/FILE_NAME?node-id=NODE_ID
|
|
2075
|
+
/figma\.com\/proto\/([a-zA-Z0-9]+)(?:\/([^?]+))?(?:\?.*node-id=([^&]+))?/
|
|
2076
|
+
];
|
|
2077
|
+
function parseFigmaUrl(url) {
|
|
2078
|
+
for (const pattern of FIGMA_URL_PATTERNS) {
|
|
2079
|
+
const match = url.match(pattern);
|
|
2080
|
+
if (match) {
|
|
2081
|
+
const [, fileKey, fileName, nodeId] = match;
|
|
2082
|
+
if (!fileKey) {
|
|
2083
|
+
throw new FigmaUrlParseError(`Invalid Figma URL: missing file key`);
|
|
2084
|
+
}
|
|
2085
|
+
return {
|
|
2086
|
+
fileKey,
|
|
2087
|
+
fileName: fileName ? decodeURIComponent(fileName) : void 0,
|
|
2088
|
+
nodeId: nodeId ? decodeURIComponent(nodeId) : void 0
|
|
2089
|
+
};
|
|
2090
|
+
}
|
|
2091
|
+
}
|
|
2092
|
+
throw new FigmaUrlParseError(
|
|
2093
|
+
`Invalid Figma URL format. Expected: https://www.figma.com/design/FILE_KEY/...`
|
|
2094
|
+
);
|
|
2095
|
+
}
|
|
2096
|
+
var FigmaUrlParseError = class extends Error {
|
|
2097
|
+
constructor(message) {
|
|
2098
|
+
super(message);
|
|
2099
|
+
this.name = "FigmaUrlParseError";
|
|
2100
|
+
}
|
|
2101
|
+
};
|
|
2102
|
+
function buildFigmaDeepLink(fileKey, nodeId) {
|
|
2103
|
+
return `https://www.figma.com/design/${fileKey}?node-id=${encodeURIComponent(nodeId)}`;
|
|
2104
|
+
}
|
|
2105
|
+
|
|
2106
|
+
// src/adapters/figma-client.ts
|
|
2107
|
+
var FIGMA_API_BASE = "https://api.figma.com/v1";
|
|
2108
|
+
var FigmaClient = class _FigmaClient {
|
|
2109
|
+
token;
|
|
2110
|
+
constructor(options) {
|
|
2111
|
+
this.token = options.token;
|
|
2112
|
+
}
|
|
2113
|
+
static fromEnv() {
|
|
2114
|
+
const token = process.env["FIGMA_TOKEN"];
|
|
2115
|
+
if (!token) {
|
|
2116
|
+
throw new FigmaClientError(
|
|
2117
|
+
"FIGMA_TOKEN environment variable is not set"
|
|
2118
|
+
);
|
|
2119
|
+
}
|
|
2120
|
+
return new _FigmaClient({ token });
|
|
2121
|
+
}
|
|
2122
|
+
async getFile(fileKey) {
|
|
2123
|
+
const url = `${FIGMA_API_BASE}/files/${fileKey}`;
|
|
2124
|
+
const response = await fetch(url, {
|
|
2125
|
+
headers: {
|
|
2126
|
+
"X-Figma-Token": this.token
|
|
2127
|
+
}
|
|
2128
|
+
});
|
|
2129
|
+
if (!response.ok) {
|
|
2130
|
+
const error = await response.json().catch(() => ({}));
|
|
2131
|
+
throw new FigmaClientError(
|
|
2132
|
+
`Failed to fetch file: ${response.status} ${response.statusText}`,
|
|
2133
|
+
response.status,
|
|
2134
|
+
error
|
|
2135
|
+
);
|
|
2136
|
+
}
|
|
2137
|
+
return response.json();
|
|
2138
|
+
}
|
|
2139
|
+
/**
|
|
2140
|
+
* Get rendered images for specific nodes
|
|
2141
|
+
* Returns a map of nodeId → image URL
|
|
2142
|
+
*/
|
|
2143
|
+
async getNodeImages(fileKey, nodeIds, options) {
|
|
2144
|
+
const format = options?.format ?? "png";
|
|
2145
|
+
const scale = options?.scale ?? 2;
|
|
2146
|
+
const BATCH_SIZE = 50;
|
|
2147
|
+
const allImages = {};
|
|
2148
|
+
for (let i = 0; i < nodeIds.length; i += BATCH_SIZE) {
|
|
2149
|
+
const batch = nodeIds.slice(i, i + BATCH_SIZE);
|
|
2150
|
+
const ids = batch.join(",");
|
|
2151
|
+
const url = `${FIGMA_API_BASE}/images/${fileKey}?ids=${encodeURIComponent(ids)}&format=${format}&scale=${scale}`;
|
|
2152
|
+
const response = await fetch(url, {
|
|
2153
|
+
headers: {
|
|
2154
|
+
"X-Figma-Token": this.token
|
|
2155
|
+
}
|
|
2156
|
+
});
|
|
2157
|
+
if (!response.ok) {
|
|
2158
|
+
const error = await response.json().catch(() => ({}));
|
|
2159
|
+
throw new FigmaClientError(
|
|
2160
|
+
`Failed to fetch images: ${response.status} ${response.statusText}`,
|
|
2161
|
+
response.status,
|
|
2162
|
+
error
|
|
2163
|
+
);
|
|
2164
|
+
}
|
|
2165
|
+
const data = await response.json();
|
|
2166
|
+
for (const [nodeId, imageUrl] of Object.entries(data.images)) {
|
|
2167
|
+
allImages[nodeId] = imageUrl;
|
|
2168
|
+
}
|
|
2169
|
+
}
|
|
2170
|
+
return allImages;
|
|
2171
|
+
}
|
|
2172
|
+
/**
|
|
2173
|
+
* Download an image URL and return as base64
|
|
2174
|
+
*/
|
|
2175
|
+
async fetchImageAsBase64(imageUrl) {
|
|
2176
|
+
const response = await fetch(imageUrl);
|
|
2177
|
+
if (!response.ok) {
|
|
2178
|
+
throw new FigmaClientError(
|
|
2179
|
+
`Failed to download image: ${response.status}`,
|
|
2180
|
+
response.status
|
|
2181
|
+
);
|
|
2182
|
+
}
|
|
2183
|
+
const buffer = await response.arrayBuffer();
|
|
2184
|
+
return Buffer.from(buffer).toString("base64");
|
|
2185
|
+
}
|
|
2186
|
+
async getFileNodes(fileKey, nodeIds) {
|
|
2187
|
+
const ids = nodeIds.join(",");
|
|
2188
|
+
const url = `${FIGMA_API_BASE}/files/${fileKey}/nodes?ids=${encodeURIComponent(ids)}`;
|
|
2189
|
+
const response = await fetch(url, {
|
|
2190
|
+
headers: {
|
|
2191
|
+
"X-Figma-Token": this.token
|
|
2192
|
+
}
|
|
2193
|
+
});
|
|
2194
|
+
if (!response.ok) {
|
|
2195
|
+
const error = await response.json().catch(() => ({}));
|
|
2196
|
+
throw new FigmaClientError(
|
|
2197
|
+
`Failed to fetch nodes: ${response.status} ${response.statusText}`,
|
|
2198
|
+
response.status,
|
|
2199
|
+
error
|
|
2200
|
+
);
|
|
2201
|
+
}
|
|
2202
|
+
return response.json();
|
|
2203
|
+
}
|
|
2204
|
+
};
|
|
2205
|
+
var FigmaClientError = class extends Error {
|
|
2206
|
+
constructor(message, statusCode, responseBody) {
|
|
2207
|
+
super(message);
|
|
2208
|
+
this.statusCode = statusCode;
|
|
2209
|
+
this.responseBody = responseBody;
|
|
2210
|
+
this.name = "FigmaClientError";
|
|
2211
|
+
}
|
|
2212
|
+
};
|
|
2213
|
+
|
|
2214
|
+
// src/adapters/figma-transformer.ts
|
|
2215
|
+
function transformFigmaResponse(fileKey, response) {
|
|
2216
|
+
return {
|
|
2217
|
+
fileKey,
|
|
2218
|
+
name: response.name,
|
|
2219
|
+
lastModified: response.lastModified,
|
|
2220
|
+
version: response.version,
|
|
2221
|
+
document: transformNode(response.document),
|
|
2222
|
+
components: transformComponents(response.components),
|
|
2223
|
+
styles: transformStyles(response.styles)
|
|
2224
|
+
};
|
|
2225
|
+
}
|
|
2226
|
+
function transformNode(node) {
|
|
2227
|
+
const base = {
|
|
2228
|
+
id: node.id,
|
|
2229
|
+
name: node.name,
|
|
2230
|
+
type: node.type,
|
|
2231
|
+
visible: "visible" in node ? node.visible ?? true : true
|
|
2232
|
+
};
|
|
2233
|
+
if ("layoutMode" in node && node.layoutMode) {
|
|
2234
|
+
base.layoutMode = node.layoutMode;
|
|
2235
|
+
}
|
|
2236
|
+
if ("layoutAlign" in node && node.layoutAlign) {
|
|
2237
|
+
base.layoutAlign = node.layoutAlign;
|
|
2238
|
+
}
|
|
2239
|
+
if ("layoutPositioning" in node && node.layoutPositioning) {
|
|
2240
|
+
base.layoutPositioning = node.layoutPositioning;
|
|
2241
|
+
}
|
|
2242
|
+
if ("primaryAxisAlignItems" in node) {
|
|
2243
|
+
base.primaryAxisAlignItems = node.primaryAxisAlignItems;
|
|
2244
|
+
}
|
|
2245
|
+
if ("counterAxisAlignItems" in node) {
|
|
2246
|
+
base.counterAxisAlignItems = node.counterAxisAlignItems;
|
|
2247
|
+
}
|
|
2248
|
+
if ("itemSpacing" in node) {
|
|
2249
|
+
base.itemSpacing = node.itemSpacing;
|
|
2250
|
+
}
|
|
2251
|
+
if ("paddingLeft" in node) {
|
|
2252
|
+
base.paddingLeft = node.paddingLeft;
|
|
2253
|
+
}
|
|
2254
|
+
if ("paddingRight" in node) {
|
|
2255
|
+
base.paddingRight = node.paddingRight;
|
|
2256
|
+
}
|
|
2257
|
+
if ("paddingTop" in node) {
|
|
2258
|
+
base.paddingTop = node.paddingTop;
|
|
2259
|
+
}
|
|
2260
|
+
if ("paddingBottom" in node) {
|
|
2261
|
+
base.paddingBottom = node.paddingBottom;
|
|
2262
|
+
}
|
|
2263
|
+
if ("absoluteBoundingBox" in node && node.absoluteBoundingBox) {
|
|
2264
|
+
base.absoluteBoundingBox = node.absoluteBoundingBox;
|
|
2265
|
+
}
|
|
2266
|
+
if ("componentId" in node) {
|
|
2267
|
+
base.componentId = node.componentId;
|
|
2268
|
+
}
|
|
2269
|
+
if ("componentPropertyDefinitions" in node) {
|
|
2270
|
+
base.componentPropertyDefinitions = node.componentPropertyDefinitions;
|
|
2271
|
+
}
|
|
2272
|
+
if ("componentProperties" in node) {
|
|
2273
|
+
base.componentProperties = node.componentProperties;
|
|
2274
|
+
}
|
|
2275
|
+
if ("styles" in node) {
|
|
2276
|
+
base.styles = node.styles;
|
|
2277
|
+
}
|
|
2278
|
+
if ("fills" in node) {
|
|
2279
|
+
base.fills = node.fills;
|
|
2280
|
+
}
|
|
2281
|
+
if ("strokes" in node) {
|
|
2282
|
+
base.strokes = node.strokes;
|
|
2283
|
+
}
|
|
2284
|
+
if ("effects" in node) {
|
|
2285
|
+
base.effects = node.effects;
|
|
2286
|
+
}
|
|
2287
|
+
if ("boundVariables" in node && node.boundVariables) {
|
|
2288
|
+
base.boundVariables = node.boundVariables;
|
|
2289
|
+
}
|
|
2290
|
+
if ("characters" in node) {
|
|
2291
|
+
base.characters = node.characters;
|
|
2292
|
+
}
|
|
2293
|
+
if ("style" in node) {
|
|
2294
|
+
base.style = node.style;
|
|
2295
|
+
}
|
|
2296
|
+
if ("devStatus" in node && node.devStatus) {
|
|
2297
|
+
base.devStatus = node.devStatus;
|
|
2298
|
+
}
|
|
2299
|
+
if ("children" in node && Array.isArray(node.children)) {
|
|
2300
|
+
base.children = node.children.map(transformNode);
|
|
2301
|
+
}
|
|
2302
|
+
return base;
|
|
2303
|
+
}
|
|
2304
|
+
function transformComponents(components) {
|
|
2305
|
+
const result = {};
|
|
2306
|
+
for (const [id, component] of Object.entries(components)) {
|
|
2307
|
+
result[id] = {
|
|
2308
|
+
key: component.key,
|
|
2309
|
+
name: component.name,
|
|
2310
|
+
description: component.description
|
|
2311
|
+
};
|
|
2312
|
+
}
|
|
2313
|
+
return result;
|
|
2314
|
+
}
|
|
2315
|
+
function transformStyles(styles) {
|
|
2316
|
+
const result = {};
|
|
2317
|
+
for (const [id, style] of Object.entries(styles)) {
|
|
2318
|
+
result[id] = {
|
|
2319
|
+
key: style.key,
|
|
2320
|
+
name: style.name,
|
|
2321
|
+
styleType: style.styleType
|
|
2322
|
+
};
|
|
2323
|
+
}
|
|
2324
|
+
return result;
|
|
2325
|
+
}
|
|
2326
|
+
async function loadFigmaFileFromJson(filePath) {
|
|
2327
|
+
const content = await readFile(filePath, "utf-8");
|
|
2328
|
+
const data = JSON.parse(content);
|
|
2329
|
+
const fileKey = basename(filePath, ".json");
|
|
2330
|
+
return transformFigmaResponse(fileKey, data);
|
|
2331
|
+
}
|
|
2332
|
+
function parseFigmaJson(json, fileKey) {
|
|
2333
|
+
const data = JSON.parse(json);
|
|
2334
|
+
return transformFigmaResponse(fileKey, data);
|
|
2335
|
+
}
|
|
2336
|
+
var FigmaFileLoadError = class extends Error {
|
|
2337
|
+
constructor(message, filePath) {
|
|
2338
|
+
super(message);
|
|
2339
|
+
this.filePath = filePath;
|
|
2340
|
+
this.name = "FigmaFileLoadError";
|
|
2341
|
+
}
|
|
2342
|
+
};
|
|
2343
|
+
|
|
2344
|
+
// src/adapters/figma-mcp-adapter.ts
|
|
2345
|
+
var TAG_TYPE_MAP = {
|
|
2346
|
+
canvas: "CANVAS",
|
|
2347
|
+
frame: "FRAME",
|
|
2348
|
+
group: "GROUP",
|
|
2349
|
+
section: "SECTION",
|
|
2350
|
+
component: "COMPONENT",
|
|
2351
|
+
"component-set": "COMPONENT_SET",
|
|
2352
|
+
instance: "INSTANCE",
|
|
2353
|
+
rectangle: "RECTANGLE",
|
|
2354
|
+
"rounded-rectangle": "RECTANGLE",
|
|
2355
|
+
ellipse: "ELLIPSE",
|
|
2356
|
+
vector: "VECTOR",
|
|
2357
|
+
text: "TEXT",
|
|
2358
|
+
line: "LINE",
|
|
2359
|
+
"boolean-operation": "BOOLEAN_OPERATION",
|
|
2360
|
+
star: "STAR",
|
|
2361
|
+
"regular-polygon": "REGULAR_POLYGON",
|
|
2362
|
+
slice: "SLICE",
|
|
2363
|
+
sticky: "STICKY",
|
|
2364
|
+
table: "TABLE",
|
|
2365
|
+
"table-cell": "TABLE_CELL",
|
|
2366
|
+
symbol: "COMPONENT",
|
|
2367
|
+
slot: "FRAME"
|
|
2368
|
+
};
|
|
2369
|
+
function parseXml(xml) {
|
|
2370
|
+
const nodes = [];
|
|
2371
|
+
const stack = [];
|
|
2372
|
+
const tagRegex = /<(\/?)([\w-]+)([^>]*?)(\/?)>/g;
|
|
2373
|
+
let match;
|
|
2374
|
+
while ((match = tagRegex.exec(xml)) !== null) {
|
|
2375
|
+
const isClosing = match[1] === "/";
|
|
2376
|
+
const tagName = match[2];
|
|
2377
|
+
const attrString = match[3] ?? "";
|
|
2378
|
+
const isSelfClosing = match[4] === "/";
|
|
2379
|
+
if (isClosing) {
|
|
2380
|
+
const finished = stack.pop();
|
|
2381
|
+
if (finished) {
|
|
2382
|
+
const parent = stack[stack.length - 1];
|
|
2383
|
+
if (parent) {
|
|
2384
|
+
parent.children.push(finished);
|
|
2385
|
+
} else {
|
|
2386
|
+
nodes.push(finished);
|
|
2387
|
+
}
|
|
2388
|
+
}
|
|
2389
|
+
} else {
|
|
2390
|
+
const attrs = parseAttributes(attrString);
|
|
2391
|
+
const node = { tag: tagName, attrs, children: [] };
|
|
2392
|
+
if (isSelfClosing) {
|
|
2393
|
+
const parent = stack[stack.length - 1];
|
|
2394
|
+
if (parent) {
|
|
2395
|
+
parent.children.push(node);
|
|
2396
|
+
} else {
|
|
2397
|
+
nodes.push(node);
|
|
2398
|
+
}
|
|
2399
|
+
} else {
|
|
2400
|
+
stack.push(node);
|
|
2401
|
+
}
|
|
2402
|
+
}
|
|
2403
|
+
}
|
|
2404
|
+
while (stack.length > 0) {
|
|
2405
|
+
const finished = stack.pop();
|
|
2406
|
+
const parent = stack[stack.length - 1];
|
|
2407
|
+
if (parent) {
|
|
2408
|
+
parent.children.push(finished);
|
|
2409
|
+
} else {
|
|
2410
|
+
nodes.push(finished);
|
|
2411
|
+
}
|
|
2412
|
+
}
|
|
2413
|
+
return nodes;
|
|
2414
|
+
}
|
|
2415
|
+
function parseAttributes(attrString) {
|
|
2416
|
+
const attrs = {};
|
|
2417
|
+
const attrRegex = /([\w-]+)="([^"]*)"/g;
|
|
2418
|
+
let match;
|
|
2419
|
+
while ((match = attrRegex.exec(attrString)) !== null) {
|
|
2420
|
+
const key = match[1];
|
|
2421
|
+
const value = match[2];
|
|
2422
|
+
if (key && value !== void 0) {
|
|
2423
|
+
attrs[key] = value;
|
|
2424
|
+
}
|
|
2425
|
+
}
|
|
2426
|
+
return attrs;
|
|
2427
|
+
}
|
|
2428
|
+
function toAnalysisNode(xmlNode) {
|
|
2429
|
+
const type = TAG_TYPE_MAP[xmlNode.tag] ?? "FRAME";
|
|
2430
|
+
const id = xmlNode.attrs["id"] ?? "0:0";
|
|
2431
|
+
const name = xmlNode.attrs["name"] ?? xmlNode.tag;
|
|
2432
|
+
const hidden = xmlNode.attrs["hidden"] === "true";
|
|
2433
|
+
const x = parseFloat(xmlNode.attrs["x"] ?? "0");
|
|
2434
|
+
const y = parseFloat(xmlNode.attrs["y"] ?? "0");
|
|
2435
|
+
const width = parseFloat(xmlNode.attrs["width"] ?? "0");
|
|
2436
|
+
const height = parseFloat(xmlNode.attrs["height"] ?? "0");
|
|
2437
|
+
const node = {
|
|
2438
|
+
id,
|
|
2439
|
+
name,
|
|
2440
|
+
type,
|
|
2441
|
+
visible: !hidden,
|
|
2442
|
+
absoluteBoundingBox: { x, y, width, height }
|
|
2443
|
+
};
|
|
2444
|
+
if (xmlNode.children.length > 0) {
|
|
2445
|
+
node.children = xmlNode.children.map(toAnalysisNode);
|
|
2446
|
+
}
|
|
2447
|
+
return node;
|
|
2448
|
+
}
|
|
2449
|
+
function parseMcpMetadataXml(xml, fileKey, fileName) {
|
|
2450
|
+
const parsed = parseXml(xml);
|
|
2451
|
+
const children = parsed.map(toAnalysisNode);
|
|
2452
|
+
let document;
|
|
2453
|
+
if (children.length === 1 && children[0]) {
|
|
2454
|
+
document = children[0];
|
|
2455
|
+
} else {
|
|
2456
|
+
document = {
|
|
2457
|
+
id: "0:0",
|
|
2458
|
+
name: "Document",
|
|
2459
|
+
type: "DOCUMENT",
|
|
2460
|
+
visible: true,
|
|
2461
|
+
children
|
|
2462
|
+
};
|
|
2463
|
+
}
|
|
2464
|
+
return {
|
|
2465
|
+
fileKey,
|
|
2466
|
+
name: fileName ?? fileKey,
|
|
2467
|
+
lastModified: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2468
|
+
version: "mcp",
|
|
2469
|
+
document,
|
|
2470
|
+
components: {},
|
|
2471
|
+
styles: {}
|
|
2472
|
+
};
|
|
2473
|
+
}
|
|
2474
|
+
var SamplingStrategySchema = z.enum(["all", "top-issues", "random"]);
|
|
2475
|
+
var CalibrationStatusSchema = z.enum([
|
|
2476
|
+
"pending",
|
|
2477
|
+
"analyzing",
|
|
2478
|
+
"converting",
|
|
2479
|
+
"evaluating",
|
|
2480
|
+
"tuning",
|
|
2481
|
+
"completed",
|
|
2482
|
+
"failed"
|
|
2483
|
+
]);
|
|
2484
|
+
var CalibrationConfigSchema = z.object({
|
|
2485
|
+
input: z.string(),
|
|
2486
|
+
token: z.string().optional(),
|
|
2487
|
+
targetNodeId: z.string().optional(),
|
|
2488
|
+
maxConversionNodes: z.number().int().positive().default(20),
|
|
2489
|
+
samplingStrategy: SamplingStrategySchema.default("top-issues"),
|
|
2490
|
+
outputPath: z.string().default("logs/calibration/calibration-report.md")
|
|
2491
|
+
});
|
|
2492
|
+
var NodeIssueSummarySchema = z.object({
|
|
2493
|
+
nodeId: z.string(),
|
|
2494
|
+
nodePath: z.string(),
|
|
2495
|
+
totalScore: z.number(),
|
|
2496
|
+
issueCount: z.number(),
|
|
2497
|
+
flaggedRuleIds: z.array(z.string()),
|
|
2498
|
+
severities: z.array(z.string())
|
|
2499
|
+
});
|
|
2500
|
+
var DifficultySchema = z.enum(["easy", "moderate", "hard", "failed"]);
|
|
2501
|
+
var RuleRelatedStruggleSchema = z.object({
|
|
2502
|
+
ruleId: z.string(),
|
|
2503
|
+
description: z.string(),
|
|
2504
|
+
actualImpact: DifficultySchema
|
|
2505
|
+
});
|
|
2506
|
+
var UncoveredStruggleSchema = z.object({
|
|
2507
|
+
description: z.string(),
|
|
2508
|
+
suggestedCategory: z.string(),
|
|
2509
|
+
estimatedImpact: DifficultySchema
|
|
2510
|
+
});
|
|
2511
|
+
var ConversionRecordSchema = z.object({
|
|
2512
|
+
nodeId: z.string(),
|
|
2513
|
+
nodePath: z.string(),
|
|
2514
|
+
generatedCode: z.string(),
|
|
2515
|
+
difficulty: DifficultySchema,
|
|
2516
|
+
notes: z.string(),
|
|
2517
|
+
ruleRelatedStruggles: z.array(RuleRelatedStruggleSchema),
|
|
2518
|
+
uncoveredStruggles: z.array(UncoveredStruggleSchema),
|
|
2519
|
+
durationMs: z.number()
|
|
2520
|
+
});
|
|
2521
|
+
var MismatchTypeSchema = z.enum([
|
|
2522
|
+
"overscored",
|
|
2523
|
+
"underscored",
|
|
2524
|
+
"missing-rule",
|
|
2525
|
+
"validated"
|
|
2526
|
+
]);
|
|
2527
|
+
var MismatchCaseSchema = z.object({
|
|
2528
|
+
type: MismatchTypeSchema,
|
|
2529
|
+
nodeId: z.string(),
|
|
2530
|
+
nodePath: z.string(),
|
|
2531
|
+
ruleId: z.string().optional(),
|
|
2532
|
+
currentScore: z.number().optional(),
|
|
2533
|
+
currentSeverity: SeveritySchema.optional(),
|
|
2534
|
+
actualDifficulty: DifficultySchema,
|
|
2535
|
+
reasoning: z.string()
|
|
2536
|
+
});
|
|
2537
|
+
var ConfidenceSchema = z.enum(["high", "medium", "low"]);
|
|
2538
|
+
var ScoreAdjustmentSchema = z.object({
|
|
2539
|
+
ruleId: z.string(),
|
|
2540
|
+
currentScore: z.number(),
|
|
2541
|
+
proposedScore: z.number(),
|
|
2542
|
+
currentSeverity: SeveritySchema,
|
|
2543
|
+
proposedSeverity: SeveritySchema.optional(),
|
|
2544
|
+
reasoning: z.string(),
|
|
2545
|
+
confidence: ConfidenceSchema,
|
|
2546
|
+
supportingCases: z.number()
|
|
2547
|
+
});
|
|
2548
|
+
var NewRuleProposalSchema = z.object({
|
|
2549
|
+
suggestedId: z.string(),
|
|
2550
|
+
category: z.string(),
|
|
2551
|
+
description: z.string(),
|
|
2552
|
+
suggestedSeverity: SeveritySchema,
|
|
2553
|
+
suggestedScore: z.number(),
|
|
2554
|
+
reasoning: z.string(),
|
|
2555
|
+
supportingCases: z.number()
|
|
2556
|
+
});
|
|
2557
|
+
|
|
2558
|
+
// src/agents/analysis-agent.ts
|
|
2559
|
+
function buildNodeIssueSummaries(result) {
|
|
2560
|
+
const nodeMap = /* @__PURE__ */ new Map();
|
|
2561
|
+
for (const issue of result.issues) {
|
|
2562
|
+
const nodeId = issue.violation.nodeId;
|
|
2563
|
+
const existing = nodeMap.get(nodeId);
|
|
2564
|
+
if (existing) {
|
|
2565
|
+
existing.totalScore += issue.calculatedScore;
|
|
2566
|
+
existing.issueCount++;
|
|
2567
|
+
existing.ruleIds.add(issue.rule.definition.id);
|
|
2568
|
+
existing.severities.add(issue.config.severity);
|
|
2569
|
+
} else {
|
|
2570
|
+
nodeMap.set(nodeId, {
|
|
2571
|
+
nodePath: issue.violation.nodePath,
|
|
2572
|
+
totalScore: issue.calculatedScore,
|
|
2573
|
+
issueCount: 1,
|
|
2574
|
+
ruleIds: /* @__PURE__ */ new Set([issue.rule.definition.id]),
|
|
2575
|
+
severities: /* @__PURE__ */ new Set([issue.config.severity])
|
|
2576
|
+
});
|
|
2577
|
+
}
|
|
2578
|
+
}
|
|
2579
|
+
const summaries = [];
|
|
2580
|
+
for (const [nodeId, data] of nodeMap) {
|
|
2581
|
+
summaries.push({
|
|
2582
|
+
nodeId,
|
|
2583
|
+
nodePath: data.nodePath,
|
|
2584
|
+
totalScore: data.totalScore,
|
|
2585
|
+
issueCount: data.issueCount,
|
|
2586
|
+
flaggedRuleIds: [...data.ruleIds],
|
|
2587
|
+
severities: [...data.severities]
|
|
2588
|
+
});
|
|
2589
|
+
}
|
|
2590
|
+
summaries.sort((a, b) => a.totalScore - b.totalScore);
|
|
2591
|
+
return summaries;
|
|
2592
|
+
}
|
|
2593
|
+
function extractRuleScores(result) {
|
|
2594
|
+
const scores = {};
|
|
2595
|
+
for (const issue of result.issues) {
|
|
2596
|
+
const ruleId = issue.rule.definition.id;
|
|
2597
|
+
if (!scores[ruleId]) {
|
|
2598
|
+
scores[ruleId] = {
|
|
2599
|
+
score: issue.config.score,
|
|
2600
|
+
severity: issue.config.severity
|
|
2601
|
+
};
|
|
2602
|
+
}
|
|
2603
|
+
}
|
|
2604
|
+
return scores;
|
|
2605
|
+
}
|
|
2606
|
+
function runAnalysisAgent(input) {
|
|
2607
|
+
const { analysisResult } = input;
|
|
2608
|
+
const scoreReport = calculateScores(analysisResult);
|
|
2609
|
+
const nodeIssueSummaries = buildNodeIssueSummaries(analysisResult);
|
|
2610
|
+
return {
|
|
2611
|
+
analysisResult,
|
|
2612
|
+
scoreReport,
|
|
2613
|
+
nodeIssueSummaries
|
|
2614
|
+
};
|
|
2615
|
+
}
|
|
2616
|
+
|
|
2617
|
+
// src/agents/conversion-agent.ts
|
|
2618
|
+
async function runConversionAgent(input, executor) {
|
|
2619
|
+
const records = [];
|
|
2620
|
+
const skippedNodeIds = [];
|
|
2621
|
+
for (const node of input.nodes) {
|
|
2622
|
+
const startTime = Date.now();
|
|
2623
|
+
try {
|
|
2624
|
+
const result = await executor(
|
|
2625
|
+
node.nodeId,
|
|
2626
|
+
input.fileKey,
|
|
2627
|
+
node.flaggedRuleIds
|
|
2628
|
+
);
|
|
2629
|
+
const durationMs = Date.now() - startTime;
|
|
2630
|
+
records.push({
|
|
2631
|
+
nodeId: node.nodeId,
|
|
2632
|
+
nodePath: node.nodePath,
|
|
2633
|
+
generatedCode: result.generatedCode,
|
|
2634
|
+
difficulty: result.difficulty,
|
|
2635
|
+
notes: result.notes,
|
|
2636
|
+
ruleRelatedStruggles: result.ruleRelatedStruggles,
|
|
2637
|
+
uncoveredStruggles: result.uncoveredStruggles,
|
|
2638
|
+
durationMs
|
|
2639
|
+
});
|
|
2640
|
+
} catch {
|
|
2641
|
+
skippedNodeIds.push(node.nodeId);
|
|
2642
|
+
}
|
|
2643
|
+
}
|
|
2644
|
+
return { records, skippedNodeIds };
|
|
2645
|
+
}
|
|
2646
|
+
|
|
2647
|
+
// src/agents/conversion-agent.prompt.ts
|
|
2648
|
+
function buildConversionPrompt(nodeId, fileKey, flaggedRuleIds) {
|
|
2649
|
+
const ruleList = flaggedRuleIds.length > 0 ? flaggedRuleIds.map((id) => `- ${id}`).join("\n") : "- (none)";
|
|
2650
|
+
return `You are a frontend developer converting a Figma design node to production-ready CSS/HTML/React code.
|
|
2651
|
+
|
|
2652
|
+
## Task
|
|
2653
|
+
|
|
2654
|
+
Convert the Figma node to code, then assess the conversion difficulty.
|
|
2655
|
+
|
|
2656
|
+
## Node Information
|
|
2657
|
+
- **File Key**: ${fileKey}
|
|
2658
|
+
- **Node ID**: ${nodeId}
|
|
2659
|
+
|
|
2660
|
+
Use \`get_design_context\` to fetch the node's design details before attempting conversion.
|
|
2661
|
+
|
|
2662
|
+
## Flagged Design Issues
|
|
2663
|
+
|
|
2664
|
+
The following rules were flagged by the design readiness checker for this node:
|
|
2665
|
+
${ruleList}
|
|
2666
|
+
|
|
2667
|
+
## Instructions
|
|
2668
|
+
|
|
2669
|
+
1. Fetch the node's design context using MCP
|
|
2670
|
+
2. Attempt to convert it to production-ready CSS + HTML (or React component)
|
|
2671
|
+
3. For each flagged rule, note whether it actually made conversion harder
|
|
2672
|
+
4. Note any conversion difficulties NOT covered by the flagged rules
|
|
2673
|
+
|
|
2674
|
+
## Output Format
|
|
2675
|
+
|
|
2676
|
+
Respond with a JSON object matching this structure:
|
|
2677
|
+
|
|
2678
|
+
\`\`\`json
|
|
2679
|
+
{
|
|
2680
|
+
"generatedCode": "// The generated CSS/HTML/React code",
|
|
2681
|
+
"difficulty": "easy | moderate | hard | failed",
|
|
2682
|
+
"notes": "Brief summary of the conversion experience",
|
|
2683
|
+
"ruleRelatedStruggles": [
|
|
2684
|
+
{
|
|
2685
|
+
"ruleId": "rule-id",
|
|
2686
|
+
"description": "How this rule's issue affected conversion",
|
|
2687
|
+
"actualImpact": "easy | moderate | hard | failed"
|
|
2688
|
+
}
|
|
2689
|
+
],
|
|
2690
|
+
"uncoveredStruggles": [
|
|
2691
|
+
{
|
|
2692
|
+
"description": "A difficulty not covered by any flagged rule",
|
|
2693
|
+
"suggestedCategory": "layout | token | component | naming | ai-readability | handoff-risk",
|
|
2694
|
+
"estimatedImpact": "easy | moderate | hard | failed"
|
|
2695
|
+
}
|
|
2696
|
+
]
|
|
2697
|
+
}
|
|
2698
|
+
\`\`\`
|
|
2699
|
+
|
|
2700
|
+
## Difficulty Guidelines
|
|
2701
|
+
|
|
2702
|
+
- **easy**: Straightforward conversion, no guessing needed
|
|
2703
|
+
- **moderate**: Some ambiguity or manual adjustment required
|
|
2704
|
+
- **hard**: Significant guessing, multiple approaches needed, fragile output
|
|
2705
|
+
- **failed**: Could not produce usable code from the design
|
|
2706
|
+
`;
|
|
2707
|
+
}
|
|
2708
|
+
|
|
2709
|
+
// src/agents/evaluation-agent.ts
|
|
2710
|
+
var DIFFICULTY_SCORE_RANGES = {
|
|
2711
|
+
easy: { min: -3, max: 0 },
|
|
2712
|
+
moderate: { min: -7, max: -4 },
|
|
2713
|
+
hard: { min: -12, max: -8 },
|
|
2714
|
+
failed: { min: -12, max: -8 }
|
|
2715
|
+
};
|
|
2716
|
+
function scoreMatchesDifficulty(score, difficulty) {
|
|
2717
|
+
const range = DIFFICULTY_SCORE_RANGES[difficulty];
|
|
2718
|
+
return score >= range.min && score <= range.max;
|
|
2719
|
+
}
|
|
2720
|
+
function classifyFlaggedRule(currentScore, actualDifficulty) {
|
|
2721
|
+
if (scoreMatchesDifficulty(currentScore, actualDifficulty)) {
|
|
2722
|
+
return "validated";
|
|
2723
|
+
}
|
|
2724
|
+
if (actualDifficulty === "easy" && currentScore < -3 || actualDifficulty === "moderate" && currentScore < -7) {
|
|
2725
|
+
return "overscored";
|
|
2726
|
+
}
|
|
2727
|
+
return "underscored";
|
|
2728
|
+
}
|
|
2729
|
+
function buildReasoning(type, ruleId, currentScore, actualDifficulty) {
|
|
2730
|
+
const range = DIFFICULTY_SCORE_RANGES[actualDifficulty];
|
|
2731
|
+
switch (type) {
|
|
2732
|
+
case "validated":
|
|
2733
|
+
return `Rule "${ruleId}" score (${currentScore}) aligns with actual difficulty "${actualDifficulty}" (expected range: ${range.min} to ${range.max}).`;
|
|
2734
|
+
case "overscored":
|
|
2735
|
+
return `Rule "${ruleId}" score (${currentScore}) is too harsh for actual difficulty "${actualDifficulty}" (expected range: ${range.min} to ${range.max}).`;
|
|
2736
|
+
case "underscored":
|
|
2737
|
+
return `Rule "${ruleId}" score (${currentScore}) is too lenient for actual difficulty "${actualDifficulty}" (expected range: ${range.min} to ${range.max}).`;
|
|
2738
|
+
case "missing-rule":
|
|
2739
|
+
return `No rule covers this difficulty "${actualDifficulty}" (expected score range: ${range.min} to ${range.max}).`;
|
|
2740
|
+
}
|
|
2741
|
+
}
|
|
2742
|
+
function runEvaluationAgent(input) {
|
|
2743
|
+
const mismatches = [];
|
|
2744
|
+
const validatedRuleSet = /* @__PURE__ */ new Set();
|
|
2745
|
+
const nodeSummaryMap = new Map(
|
|
2746
|
+
input.nodeIssueSummaries.map((s) => [s.nodeId, s])
|
|
2747
|
+
);
|
|
2748
|
+
for (const record of input.conversionRecords) {
|
|
2749
|
+
const summary = nodeSummaryMap.get(record.nodeId);
|
|
2750
|
+
const difficulty = record.difficulty;
|
|
2751
|
+
for (const struggle of record.ruleRelatedStruggles) {
|
|
2752
|
+
const ruleInfo = input.ruleScores[struggle.ruleId];
|
|
2753
|
+
if (!ruleInfo) continue;
|
|
2754
|
+
const actualDifficulty = struggle.actualImpact;
|
|
2755
|
+
const type = classifyFlaggedRule(ruleInfo.score, actualDifficulty);
|
|
2756
|
+
if (type === "validated") {
|
|
2757
|
+
validatedRuleSet.add(struggle.ruleId);
|
|
2758
|
+
}
|
|
2759
|
+
mismatches.push({
|
|
2760
|
+
type,
|
|
2761
|
+
nodeId: record.nodeId,
|
|
2762
|
+
nodePath: record.nodePath,
|
|
2763
|
+
ruleId: struggle.ruleId,
|
|
2764
|
+
currentScore: ruleInfo.score,
|
|
2765
|
+
currentSeverity: ruleInfo.severity,
|
|
2766
|
+
actualDifficulty,
|
|
2767
|
+
reasoning: buildReasoning(type, struggle.ruleId, ruleInfo.score, actualDifficulty)
|
|
2768
|
+
});
|
|
2769
|
+
}
|
|
2770
|
+
if (summary) {
|
|
2771
|
+
const struggledRuleIds = new Set(
|
|
2772
|
+
record.ruleRelatedStruggles.map((s) => s.ruleId)
|
|
2773
|
+
);
|
|
2774
|
+
for (const ruleId of summary.flaggedRuleIds) {
|
|
2775
|
+
if (struggledRuleIds.has(ruleId)) continue;
|
|
2776
|
+
const ruleInfo = input.ruleScores[ruleId];
|
|
2777
|
+
if (!ruleInfo) continue;
|
|
2778
|
+
if (difficulty === "easy" || difficulty === "moderate") {
|
|
2779
|
+
mismatches.push({
|
|
2780
|
+
type: "overscored",
|
|
2781
|
+
nodeId: record.nodeId,
|
|
2782
|
+
nodePath: record.nodePath,
|
|
2783
|
+
ruleId,
|
|
2784
|
+
currentScore: ruleInfo.score,
|
|
2785
|
+
currentSeverity: ruleInfo.severity,
|
|
2786
|
+
actualDifficulty: "easy",
|
|
2787
|
+
reasoning: `Rule "${ruleId}" was flagged but caused no struggle during conversion (overall node difficulty: "${difficulty}").`
|
|
2788
|
+
});
|
|
2789
|
+
} else {
|
|
2790
|
+
validatedRuleSet.add(ruleId);
|
|
2791
|
+
mismatches.push({
|
|
2792
|
+
type: "validated",
|
|
2793
|
+
nodeId: record.nodeId,
|
|
2794
|
+
nodePath: record.nodePath,
|
|
2795
|
+
ruleId,
|
|
2796
|
+
currentScore: ruleInfo.score,
|
|
2797
|
+
currentSeverity: ruleInfo.severity,
|
|
2798
|
+
actualDifficulty: difficulty,
|
|
2799
|
+
reasoning: `Rule "${ruleId}" was flagged and overall conversion was "${difficulty}" \u2014 conservatively validated.`
|
|
2800
|
+
});
|
|
2801
|
+
}
|
|
2802
|
+
}
|
|
2803
|
+
}
|
|
2804
|
+
for (const uncovered of record.uncoveredStruggles) {
|
|
2805
|
+
const estimatedDifficulty = uncovered.estimatedImpact;
|
|
2806
|
+
mismatches.push({
|
|
2807
|
+
type: "missing-rule",
|
|
2808
|
+
nodeId: record.nodeId,
|
|
2809
|
+
nodePath: record.nodePath,
|
|
2810
|
+
actualDifficulty: estimatedDifficulty,
|
|
2811
|
+
reasoning: `Uncovered struggle: "${uncovered.description}" (category: ${uncovered.suggestedCategory}, impact: ${estimatedDifficulty}).`
|
|
2812
|
+
});
|
|
2813
|
+
}
|
|
2814
|
+
}
|
|
2815
|
+
return {
|
|
2816
|
+
mismatches,
|
|
2817
|
+
validatedRules: [...validatedRuleSet]
|
|
2818
|
+
};
|
|
2819
|
+
}
|
|
2820
|
+
|
|
2821
|
+
// src/agents/tuning-agent.ts
|
|
2822
|
+
var DIFFICULTY_MIDPOINT = {
|
|
2823
|
+
easy: -2,
|
|
2824
|
+
moderate: -5,
|
|
2825
|
+
hard: -10,
|
|
2826
|
+
failed: -12
|
|
2827
|
+
};
|
|
2828
|
+
var DIFFICULTY_SEVERITY = {
|
|
2829
|
+
easy: "suggestion",
|
|
2830
|
+
moderate: "risk",
|
|
2831
|
+
hard: "blocking",
|
|
2832
|
+
failed: "blocking"
|
|
2833
|
+
};
|
|
2834
|
+
function getConfidence(caseCount) {
|
|
2835
|
+
if (caseCount >= 3) return "high";
|
|
2836
|
+
if (caseCount >= 2) return "medium";
|
|
2837
|
+
return "low";
|
|
2838
|
+
}
|
|
2839
|
+
function proposedScoreFromDifficulties(difficulties) {
|
|
2840
|
+
const counts = {};
|
|
2841
|
+
for (const d of difficulties) {
|
|
2842
|
+
counts[d] = (counts[d] ?? 0) + 1;
|
|
2843
|
+
}
|
|
2844
|
+
let dominant = difficulties[0] ?? "moderate";
|
|
2845
|
+
let maxCount = 0;
|
|
2846
|
+
for (const [difficulty, count] of Object.entries(counts)) {
|
|
2847
|
+
if (count > maxCount) {
|
|
2848
|
+
maxCount = count;
|
|
2849
|
+
dominant = difficulty;
|
|
2850
|
+
}
|
|
2851
|
+
}
|
|
2852
|
+
return DIFFICULTY_MIDPOINT[dominant] ?? -5;
|
|
2853
|
+
}
|
|
2854
|
+
function proposeSeverity(currentSeverity, proposedScore) {
|
|
2855
|
+
let expectedSeverity;
|
|
2856
|
+
if (proposedScore <= -8) {
|
|
2857
|
+
expectedSeverity = "blocking";
|
|
2858
|
+
} else if (proposedScore <= -4) {
|
|
2859
|
+
expectedSeverity = "risk";
|
|
2860
|
+
} else if (proposedScore <= -2) {
|
|
2861
|
+
expectedSeverity = "missing-info";
|
|
2862
|
+
} else {
|
|
2863
|
+
expectedSeverity = "suggestion";
|
|
2864
|
+
}
|
|
2865
|
+
if (expectedSeverity !== currentSeverity) {
|
|
2866
|
+
return expectedSeverity;
|
|
2867
|
+
}
|
|
2868
|
+
return void 0;
|
|
2869
|
+
}
|
|
2870
|
+
function runTuningAgent(input) {
|
|
2871
|
+
const adjustments = [];
|
|
2872
|
+
const newRuleProposals = [];
|
|
2873
|
+
const overscoredByRule = /* @__PURE__ */ new Map();
|
|
2874
|
+
const underscoredByRule = /* @__PURE__ */ new Map();
|
|
2875
|
+
const missingRuleCases = [];
|
|
2876
|
+
for (const mismatch of input.mismatches) {
|
|
2877
|
+
switch (mismatch.type) {
|
|
2878
|
+
case "overscored": {
|
|
2879
|
+
if (!mismatch.ruleId) break;
|
|
2880
|
+
const existing = overscoredByRule.get(mismatch.ruleId);
|
|
2881
|
+
if (existing) {
|
|
2882
|
+
existing.push(mismatch);
|
|
2883
|
+
} else {
|
|
2884
|
+
overscoredByRule.set(mismatch.ruleId, [mismatch]);
|
|
2885
|
+
}
|
|
2886
|
+
break;
|
|
2887
|
+
}
|
|
2888
|
+
case "underscored": {
|
|
2889
|
+
if (!mismatch.ruleId) break;
|
|
2890
|
+
const existing = underscoredByRule.get(mismatch.ruleId);
|
|
2891
|
+
if (existing) {
|
|
2892
|
+
existing.push(mismatch);
|
|
2893
|
+
} else {
|
|
2894
|
+
underscoredByRule.set(mismatch.ruleId, [mismatch]);
|
|
2895
|
+
}
|
|
2896
|
+
break;
|
|
2897
|
+
}
|
|
2898
|
+
case "missing-rule":
|
|
2899
|
+
missingRuleCases.push(mismatch);
|
|
2900
|
+
break;
|
|
2901
|
+
}
|
|
2902
|
+
}
|
|
2903
|
+
for (const [ruleId, cases] of overscoredByRule) {
|
|
2904
|
+
const ruleInfo = input.ruleScores[ruleId];
|
|
2905
|
+
if (!ruleInfo) continue;
|
|
2906
|
+
const difficulties = cases.map((c) => c.actualDifficulty);
|
|
2907
|
+
const proposedScore = proposedScoreFromDifficulties(difficulties);
|
|
2908
|
+
const currentSeverity = ruleInfo.severity;
|
|
2909
|
+
const newSeverity = proposeSeverity(currentSeverity, proposedScore);
|
|
2910
|
+
adjustments.push({
|
|
2911
|
+
ruleId,
|
|
2912
|
+
currentScore: ruleInfo.score,
|
|
2913
|
+
proposedScore,
|
|
2914
|
+
currentSeverity,
|
|
2915
|
+
proposedSeverity: newSeverity,
|
|
2916
|
+
reasoning: `Overscored in ${cases.length} case(s). Actual difficulties: [${difficulties.join(", ")}]. Current score ${ruleInfo.score} is too harsh.`,
|
|
2917
|
+
confidence: getConfidence(cases.length),
|
|
2918
|
+
supportingCases: cases.length
|
|
2919
|
+
});
|
|
2920
|
+
}
|
|
2921
|
+
for (const [ruleId, cases] of underscoredByRule) {
|
|
2922
|
+
const ruleInfo = input.ruleScores[ruleId];
|
|
2923
|
+
if (!ruleInfo) continue;
|
|
2924
|
+
const difficulties = cases.map((c) => c.actualDifficulty);
|
|
2925
|
+
const proposedScore = proposedScoreFromDifficulties(difficulties);
|
|
2926
|
+
const currentSeverity = ruleInfo.severity;
|
|
2927
|
+
const newSeverity = proposeSeverity(currentSeverity, proposedScore);
|
|
2928
|
+
adjustments.push({
|
|
2929
|
+
ruleId,
|
|
2930
|
+
currentScore: ruleInfo.score,
|
|
2931
|
+
proposedScore,
|
|
2932
|
+
currentSeverity,
|
|
2933
|
+
proposedSeverity: newSeverity,
|
|
2934
|
+
reasoning: `Underscored in ${cases.length} case(s). Actual difficulties: [${difficulties.join(", ")}]. Current score ${ruleInfo.score} is too lenient.`,
|
|
2935
|
+
confidence: getConfidence(cases.length),
|
|
2936
|
+
supportingCases: cases.length
|
|
2937
|
+
});
|
|
2938
|
+
}
|
|
2939
|
+
const missingGrouped = /* @__PURE__ */ new Map();
|
|
2940
|
+
for (const c of missingRuleCases) {
|
|
2941
|
+
const categoryMatch = c.reasoning.match(/category:\s*([^,)]+)/);
|
|
2942
|
+
const category = categoryMatch?.[1]?.trim() ?? "unknown";
|
|
2943
|
+
const existing = missingGrouped.get(category);
|
|
2944
|
+
if (existing) {
|
|
2945
|
+
existing.push(c);
|
|
2946
|
+
} else {
|
|
2947
|
+
missingGrouped.set(category, [c]);
|
|
2948
|
+
}
|
|
2949
|
+
}
|
|
2950
|
+
for (const [category, cases] of missingGrouped) {
|
|
2951
|
+
const difficulties = cases.map((c) => c.actualDifficulty);
|
|
2952
|
+
const dominantDifficulty = getDominantDifficulty(difficulties);
|
|
2953
|
+
const descriptions = cases.map((c) => {
|
|
2954
|
+
const descMatch = c.reasoning.match(/Uncovered struggle: "([^"]+)"/);
|
|
2955
|
+
return descMatch?.[1] ?? c.reasoning;
|
|
2956
|
+
});
|
|
2957
|
+
newRuleProposals.push({
|
|
2958
|
+
suggestedId: `new-${category}-rule`,
|
|
2959
|
+
category,
|
|
2960
|
+
description: descriptions.join("; "),
|
|
2961
|
+
suggestedSeverity: DIFFICULTY_SEVERITY[dominantDifficulty] ?? "risk",
|
|
2962
|
+
suggestedScore: DIFFICULTY_MIDPOINT[dominantDifficulty] ?? -5,
|
|
2963
|
+
reasoning: `${cases.length} uncovered struggle(s) in category "${category}". Difficulties: [${difficulties.join(", ")}].`,
|
|
2964
|
+
supportingCases: cases.length
|
|
2965
|
+
});
|
|
2966
|
+
}
|
|
2967
|
+
return { adjustments, newRuleProposals };
|
|
2968
|
+
}
|
|
2969
|
+
function getDominantDifficulty(difficulties) {
|
|
2970
|
+
const counts = {};
|
|
2971
|
+
for (const d of difficulties) {
|
|
2972
|
+
counts[d] = (counts[d] ?? 0) + 1;
|
|
2973
|
+
}
|
|
2974
|
+
let dominant = difficulties[0] ?? "moderate";
|
|
2975
|
+
let maxCount = 0;
|
|
2976
|
+
for (const [difficulty, count] of Object.entries(counts)) {
|
|
2977
|
+
if (count > maxCount) {
|
|
2978
|
+
maxCount = count;
|
|
2979
|
+
dominant = difficulty;
|
|
2980
|
+
}
|
|
2981
|
+
}
|
|
2982
|
+
return dominant;
|
|
2983
|
+
}
|
|
2984
|
+
|
|
2985
|
+
// src/agents/report-generator.ts
|
|
2986
|
+
function generateCalibrationReport(data) {
|
|
2987
|
+
const lines = [];
|
|
2988
|
+
lines.push("# Calibration Report");
|
|
2989
|
+
lines.push("");
|
|
2990
|
+
lines.push(renderOverview(data));
|
|
2991
|
+
lines.push(renderCurrentScores(data));
|
|
2992
|
+
lines.push(renderAdjustmentProposals(data.adjustments));
|
|
2993
|
+
lines.push(renderNewRuleProposals(data.newRuleProposals));
|
|
2994
|
+
lines.push(renderValidatedRules(data.validatedRules));
|
|
2995
|
+
lines.push(renderMismatchDetails(data.mismatches));
|
|
2996
|
+
lines.push(renderApplicationGuide(data.adjustments));
|
|
2997
|
+
return lines.join("\n");
|
|
2998
|
+
}
|
|
2999
|
+
function renderOverview(data) {
|
|
3000
|
+
return `## Overview
|
|
3001
|
+
|
|
3002
|
+
| Metric | Value |
|
|
3003
|
+
|--------|-------|
|
|
3004
|
+
| File | ${data.fileName} (${data.fileKey}) |
|
|
3005
|
+
| Analyzed At | ${data.analyzedAt} |
|
|
3006
|
+
| Total Nodes | ${data.nodeCount} |
|
|
3007
|
+
| Total Issues | ${data.issueCount} |
|
|
3008
|
+
| Converted Nodes | ${data.convertedNodeCount} |
|
|
3009
|
+
| Skipped Nodes | ${data.skippedNodeCount} |
|
|
3010
|
+
| Overall Grade | ${data.scoreReport.overall.grade} (${data.scoreReport.overall.percentage}%) |
|
|
3011
|
+
`;
|
|
3012
|
+
}
|
|
3013
|
+
function renderCurrentScores(data) {
|
|
3014
|
+
const lines = [];
|
|
3015
|
+
lines.push("## Current Score Summary");
|
|
3016
|
+
lines.push("");
|
|
3017
|
+
lines.push("| Category | Score | Issues | Density | Diversity |");
|
|
3018
|
+
lines.push("|----------|-------|--------|---------|-----------|");
|
|
3019
|
+
for (const [category, catScore] of Object.entries(data.scoreReport.byCategory)) {
|
|
3020
|
+
lines.push(
|
|
3021
|
+
`| ${category} | ${catScore.percentage}% | ${catScore.issueCount} | ${catScore.densityScore} | ${catScore.diversityScore} |`
|
|
3022
|
+
);
|
|
3023
|
+
}
|
|
3024
|
+
lines.push("");
|
|
3025
|
+
return lines.join("\n");
|
|
3026
|
+
}
|
|
3027
|
+
function renderAdjustmentProposals(adjustments) {
|
|
3028
|
+
if (adjustments.length === 0) {
|
|
3029
|
+
return "## Score Adjustment Proposals\n\nNo adjustments proposed.\n";
|
|
3030
|
+
}
|
|
3031
|
+
const lines = [];
|
|
3032
|
+
lines.push("## Score Adjustment Proposals");
|
|
3033
|
+
lines.push("");
|
|
3034
|
+
lines.push("| Rule | Current Score | Proposed Score | Severity Change | Confidence | Cases | Reasoning |");
|
|
3035
|
+
lines.push("|------|--------------|----------------|-----------------|------------|-------|-----------|");
|
|
3036
|
+
for (const adj of adjustments) {
|
|
3037
|
+
const severityChange = adj.proposedSeverity ? `${adj.currentSeverity} -> ${adj.proposedSeverity}` : adj.currentSeverity;
|
|
3038
|
+
lines.push(
|
|
3039
|
+
`| ${adj.ruleId} | ${adj.currentScore} | ${adj.proposedScore} | ${severityChange} | ${adj.confidence} | ${adj.supportingCases} | ${adj.reasoning} |`
|
|
3040
|
+
);
|
|
3041
|
+
}
|
|
3042
|
+
lines.push("");
|
|
3043
|
+
return lines.join("\n");
|
|
3044
|
+
}
|
|
3045
|
+
function renderNewRuleProposals(proposals) {
|
|
3046
|
+
if (proposals.length === 0) {
|
|
3047
|
+
return "## New Rule Proposals\n\nNo new rules proposed.\n";
|
|
3048
|
+
}
|
|
3049
|
+
const lines = [];
|
|
3050
|
+
lines.push("## New Rule Proposals");
|
|
3051
|
+
lines.push("");
|
|
3052
|
+
for (const proposal of proposals) {
|
|
3053
|
+
lines.push(`### ${proposal.suggestedId}`);
|
|
3054
|
+
lines.push("");
|
|
3055
|
+
lines.push(`- **Category**: ${proposal.category}`);
|
|
3056
|
+
lines.push(`- **Suggested Severity**: ${proposal.suggestedSeverity}`);
|
|
3057
|
+
lines.push(`- **Suggested Score**: ${proposal.suggestedScore}`);
|
|
3058
|
+
lines.push(`- **Supporting Cases**: ${proposal.supportingCases}`);
|
|
3059
|
+
lines.push(`- **Description**: ${proposal.description}`);
|
|
3060
|
+
lines.push(`- **Reasoning**: ${proposal.reasoning}`);
|
|
3061
|
+
lines.push("");
|
|
3062
|
+
}
|
|
3063
|
+
return lines.join("\n");
|
|
3064
|
+
}
|
|
3065
|
+
function renderValidatedRules(validatedRules) {
|
|
3066
|
+
if (validatedRules.length === 0) {
|
|
3067
|
+
return "## Validated Rules\n\nNo rules were validated in this run.\n";
|
|
3068
|
+
}
|
|
3069
|
+
const lines = [];
|
|
3070
|
+
lines.push("## Validated Rules");
|
|
3071
|
+
lines.push("");
|
|
3072
|
+
lines.push("The following rules had scores that aligned with actual conversion difficulty:");
|
|
3073
|
+
lines.push("");
|
|
3074
|
+
for (const ruleId of validatedRules) {
|
|
3075
|
+
lines.push(`- \`${ruleId}\``);
|
|
3076
|
+
}
|
|
3077
|
+
lines.push("");
|
|
3078
|
+
return lines.join("\n");
|
|
3079
|
+
}
|
|
3080
|
+
function renderMismatchDetails(mismatches) {
|
|
3081
|
+
if (mismatches.length === 0) {
|
|
3082
|
+
return "## Detailed Mismatch List\n\nNo mismatches found.\n";
|
|
3083
|
+
}
|
|
3084
|
+
const lines = [];
|
|
3085
|
+
lines.push("## Detailed Mismatch List");
|
|
3086
|
+
lines.push("");
|
|
3087
|
+
const grouped = {};
|
|
3088
|
+
for (const m of mismatches) {
|
|
3089
|
+
const list = grouped[m.type];
|
|
3090
|
+
if (list) {
|
|
3091
|
+
list.push(m);
|
|
3092
|
+
} else {
|
|
3093
|
+
grouped[m.type] = [m];
|
|
3094
|
+
}
|
|
3095
|
+
}
|
|
3096
|
+
for (const [type, cases] of Object.entries(grouped)) {
|
|
3097
|
+
lines.push(`### ${type} (${cases.length})`);
|
|
3098
|
+
lines.push("");
|
|
3099
|
+
for (const c of cases) {
|
|
3100
|
+
const ruleInfo = c.ruleId ? ` | Rule: \`${c.ruleId}\`` : "";
|
|
3101
|
+
const scoreInfo = c.currentScore !== void 0 ? ` | Score: ${c.currentScore}` : "";
|
|
3102
|
+
lines.push(`- **${c.nodePath}** (${c.nodeId})${ruleInfo}${scoreInfo} | Difficulty: ${c.actualDifficulty}`);
|
|
3103
|
+
lines.push(` > ${c.reasoning}`);
|
|
3104
|
+
}
|
|
3105
|
+
lines.push("");
|
|
3106
|
+
}
|
|
3107
|
+
return lines.join("\n");
|
|
3108
|
+
}
|
|
3109
|
+
function renderApplicationGuide(adjustments) {
|
|
3110
|
+
const lines = [];
|
|
3111
|
+
lines.push("## Application Guide");
|
|
3112
|
+
lines.push("");
|
|
3113
|
+
lines.push("To apply these calibration results:");
|
|
3114
|
+
lines.push("");
|
|
3115
|
+
lines.push("1. Review each adjustment proposal above");
|
|
3116
|
+
lines.push("2. Edit `src/rules/rule-config.ts` to update scores and severities");
|
|
3117
|
+
lines.push("3. Run `pnpm test:run` to verify no tests break");
|
|
3118
|
+
lines.push("4. Re-run calibration to confirm improvements");
|
|
3119
|
+
lines.push("");
|
|
3120
|
+
if (adjustments.length > 0) {
|
|
3121
|
+
lines.push("### Suggested Changes to `rule-config.ts`");
|
|
3122
|
+
lines.push("");
|
|
3123
|
+
lines.push("```typescript");
|
|
3124
|
+
for (const adj of adjustments) {
|
|
3125
|
+
lines.push(`// ${adj.ruleId}: ${adj.currentScore} -> ${adj.proposedScore} (${adj.confidence} confidence)`);
|
|
3126
|
+
if (adj.proposedSeverity) {
|
|
3127
|
+
lines.push(`// severity: "${adj.currentSeverity}" -> "${adj.proposedSeverity}"`);
|
|
3128
|
+
}
|
|
3129
|
+
}
|
|
3130
|
+
lines.push("```");
|
|
3131
|
+
lines.push("");
|
|
3132
|
+
}
|
|
3133
|
+
return lines.join("\n");
|
|
3134
|
+
}
|
|
3135
|
+
function getTimestamp() {
|
|
3136
|
+
const now = /* @__PURE__ */ new Date();
|
|
3137
|
+
return now.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", hour12: false });
|
|
3138
|
+
}
|
|
3139
|
+
function getDateTimeString() {
|
|
3140
|
+
const now = /* @__PURE__ */ new Date();
|
|
3141
|
+
const year = now.getFullYear();
|
|
3142
|
+
const month = String(now.getMonth() + 1).padStart(2, "0");
|
|
3143
|
+
const day = String(now.getDate()).padStart(2, "0");
|
|
3144
|
+
const hours = String(now.getHours()).padStart(2, "0");
|
|
3145
|
+
const minutes = String(now.getMinutes()).padStart(2, "0");
|
|
3146
|
+
return `${year}-${month}-${day}-${hours}-${minutes}`;
|
|
3147
|
+
}
|
|
3148
|
+
function extractFixtureName(fixturePath) {
|
|
3149
|
+
const fileName = fixturePath.split("/").pop() ?? fixturePath;
|
|
3150
|
+
return fileName.replace(/\.json$/, "");
|
|
3151
|
+
}
|
|
3152
|
+
var ActivityLogger = class {
|
|
3153
|
+
logPath;
|
|
3154
|
+
initialized = false;
|
|
3155
|
+
constructor(fixturePath, logDir = "logs/activity") {
|
|
3156
|
+
const dateTimeStr = getDateTimeString();
|
|
3157
|
+
const fixtureName = fixturePath ? extractFixtureName(fixturePath) : "unknown";
|
|
3158
|
+
this.logPath = resolve(logDir, `${dateTimeStr}-${fixtureName}.md`);
|
|
3159
|
+
}
|
|
3160
|
+
/**
|
|
3161
|
+
* Ensure the log directory and file header exist
|
|
3162
|
+
*/
|
|
3163
|
+
async ensureInitialized() {
|
|
3164
|
+
if (this.initialized) return;
|
|
3165
|
+
const dir = dirname(this.logPath);
|
|
3166
|
+
if (!existsSync(dir)) {
|
|
3167
|
+
mkdirSync(dir, { recursive: true });
|
|
3168
|
+
}
|
|
3169
|
+
if (!existsSync(this.logPath)) {
|
|
3170
|
+
const ts = getDateTimeString();
|
|
3171
|
+
await writeFile(this.logPath, `# Calibration Activity Log \u2014 ${ts}
|
|
3172
|
+
|
|
3173
|
+
`, "utf-8");
|
|
3174
|
+
}
|
|
3175
|
+
this.initialized = true;
|
|
3176
|
+
}
|
|
3177
|
+
/**
|
|
3178
|
+
* Log a pipeline step
|
|
3179
|
+
*/
|
|
3180
|
+
async logStep(activity) {
|
|
3181
|
+
await this.ensureInitialized();
|
|
3182
|
+
const lines = [];
|
|
3183
|
+
lines.push(`## ${getTimestamp()} \u2014 ${activity.step}`);
|
|
3184
|
+
if (activity.nodePath) {
|
|
3185
|
+
lines.push(`- Node: ${activity.nodePath}`);
|
|
3186
|
+
}
|
|
3187
|
+
lines.push(`- Result: ${activity.result}`);
|
|
3188
|
+
lines.push(`- Duration: ${activity.durationMs}ms`);
|
|
3189
|
+
lines.push("");
|
|
3190
|
+
await appendFile(this.logPath, lines.join("\n") + "\n", "utf-8");
|
|
3191
|
+
}
|
|
3192
|
+
/**
|
|
3193
|
+
* Log a summary at pipeline completion
|
|
3194
|
+
*/
|
|
3195
|
+
async logSummary(summary) {
|
|
3196
|
+
await this.ensureInitialized();
|
|
3197
|
+
const lines = [];
|
|
3198
|
+
lines.push(`## ${getTimestamp()} \u2014 Pipeline Summary`);
|
|
3199
|
+
lines.push(`- Status: ${summary.status}`);
|
|
3200
|
+
lines.push(`- Total Duration: ${summary.totalDurationMs}ms`);
|
|
3201
|
+
lines.push(`- Nodes Analyzed: ${summary.nodesAnalyzed}`);
|
|
3202
|
+
lines.push(`- Nodes Converted: ${summary.nodesConverted}`);
|
|
3203
|
+
lines.push(`- Mismatches Found: ${summary.mismatches}`);
|
|
3204
|
+
lines.push(`- Adjustments Proposed: ${summary.adjustments}`);
|
|
3205
|
+
lines.push("");
|
|
3206
|
+
lines.push("---");
|
|
3207
|
+
lines.push("");
|
|
3208
|
+
await appendFile(this.logPath, lines.join("\n") + "\n", "utf-8");
|
|
3209
|
+
}
|
|
3210
|
+
getLogPath() {
|
|
3211
|
+
return this.logPath;
|
|
3212
|
+
}
|
|
3213
|
+
};
|
|
3214
|
+
|
|
3215
|
+
// src/agents/orchestrator.ts
|
|
3216
|
+
function selectNodes(summaries, strategy, maxNodes) {
|
|
3217
|
+
if (summaries.length === 0) return [];
|
|
3218
|
+
switch (strategy) {
|
|
3219
|
+
case "all":
|
|
3220
|
+
return summaries.slice(0, maxNodes);
|
|
3221
|
+
case "random": {
|
|
3222
|
+
const shuffled = [...summaries];
|
|
3223
|
+
for (let i = shuffled.length - 1; i > 0; i--) {
|
|
3224
|
+
const j = Math.floor(Math.random() * (i + 1));
|
|
3225
|
+
const temp = shuffled[i];
|
|
3226
|
+
shuffled[i] = shuffled[j];
|
|
3227
|
+
shuffled[j] = temp;
|
|
3228
|
+
}
|
|
3229
|
+
return shuffled.slice(0, maxNodes);
|
|
3230
|
+
}
|
|
3231
|
+
case "top-issues":
|
|
3232
|
+
default:
|
|
3233
|
+
return summaries.slice(0, maxNodes);
|
|
3234
|
+
}
|
|
3235
|
+
}
|
|
3236
|
+
var EXCLUDED_NODE_TYPES = /* @__PURE__ */ new Set([
|
|
3237
|
+
"VECTOR",
|
|
3238
|
+
"BOOLEAN_OPERATION",
|
|
3239
|
+
"STAR",
|
|
3240
|
+
"REGULAR_POLYGON",
|
|
3241
|
+
"ELLIPSE",
|
|
3242
|
+
"LINE"
|
|
3243
|
+
]);
|
|
3244
|
+
function findNode(root, nodeId) {
|
|
3245
|
+
if (root.id === nodeId) return root;
|
|
3246
|
+
if (root.children) {
|
|
3247
|
+
for (const child of root.children) {
|
|
3248
|
+
const found = findNode(child, nodeId);
|
|
3249
|
+
if (found) return found;
|
|
3250
|
+
}
|
|
3251
|
+
}
|
|
3252
|
+
return null;
|
|
3253
|
+
}
|
|
3254
|
+
function hasTextDescendant(node) {
|
|
3255
|
+
if (node.type === "TEXT") return true;
|
|
3256
|
+
if (node.children) {
|
|
3257
|
+
for (const child of node.children) {
|
|
3258
|
+
if (hasTextDescendant(child)) return true;
|
|
3259
|
+
}
|
|
3260
|
+
}
|
|
3261
|
+
return false;
|
|
3262
|
+
}
|
|
3263
|
+
var MIN_WIDTH = 200;
|
|
3264
|
+
var MIN_HEIGHT = 200;
|
|
3265
|
+
var ELIGIBLE_NODE_TYPES = /* @__PURE__ */ new Set([
|
|
3266
|
+
"FRAME",
|
|
3267
|
+
"COMPONENT",
|
|
3268
|
+
"INSTANCE"
|
|
3269
|
+
]);
|
|
3270
|
+
var ICON_NAME_PATTERN = /\b(icon|ico|badge|indicator)\b/i;
|
|
3271
|
+
function filterConversionCandidates(summaries, documentRoot) {
|
|
3272
|
+
return summaries.filter((summary) => {
|
|
3273
|
+
const node = findNode(documentRoot, summary.nodeId);
|
|
3274
|
+
if (!node) return false;
|
|
3275
|
+
if (EXCLUDED_NODE_TYPES.has(node.type)) return false;
|
|
3276
|
+
if (!ELIGIBLE_NODE_TYPES.has(node.type)) return false;
|
|
3277
|
+
if (ICON_NAME_PATTERN.test(node.name)) return false;
|
|
3278
|
+
const bbox = node.absoluteBoundingBox;
|
|
3279
|
+
if (bbox && (bbox.width < MIN_WIDTH || bbox.height < MIN_HEIGHT)) return false;
|
|
3280
|
+
if (!node.children || node.children.length < 3) return false;
|
|
3281
|
+
if (!hasTextDescendant(node)) return false;
|
|
3282
|
+
return true;
|
|
3283
|
+
});
|
|
3284
|
+
}
|
|
3285
|
+
function isFigmaUrl(input) {
|
|
3286
|
+
return input.includes("figma.com/");
|
|
3287
|
+
}
|
|
3288
|
+
function isJsonFile(input) {
|
|
3289
|
+
return input.endsWith(".json");
|
|
3290
|
+
}
|
|
3291
|
+
async function loadFile(input, token) {
|
|
3292
|
+
if (isJsonFile(input)) {
|
|
3293
|
+
const filePath = resolve(input);
|
|
3294
|
+
if (!existsSync(filePath)) {
|
|
3295
|
+
throw new Error(`File not found: ${filePath}`);
|
|
3296
|
+
}
|
|
3297
|
+
const file = await loadFigmaFileFromJson(filePath);
|
|
3298
|
+
return { file, fileKey: file.fileKey, nodeId: void 0 };
|
|
3299
|
+
}
|
|
3300
|
+
if (isFigmaUrl(input)) {
|
|
3301
|
+
const { fileKey, nodeId } = parseFigmaUrl(input);
|
|
3302
|
+
const figmaToken = token ?? process.env["FIGMA_TOKEN"];
|
|
3303
|
+
if (!figmaToken) {
|
|
3304
|
+
throw new Error(
|
|
3305
|
+
"Figma token required. Provide token or set FIGMA_TOKEN environment variable."
|
|
3306
|
+
);
|
|
3307
|
+
}
|
|
3308
|
+
const client = new FigmaClient({ token: figmaToken });
|
|
3309
|
+
const response = await client.getFile(fileKey);
|
|
3310
|
+
const file = transformFigmaResponse(fileKey, response);
|
|
3311
|
+
return { file, fileKey, nodeId };
|
|
3312
|
+
}
|
|
3313
|
+
throw new Error(
|
|
3314
|
+
`Invalid input: ${input}. Provide a Figma URL or JSON file path.`
|
|
3315
|
+
);
|
|
3316
|
+
}
|
|
3317
|
+
function buildRuleScoresMap() {
|
|
3318
|
+
const scores = {};
|
|
3319
|
+
for (const [id, config] of Object.entries(RULE_CONFIGS)) {
|
|
3320
|
+
scores[id] = { score: config.score, severity: config.severity };
|
|
3321
|
+
}
|
|
3322
|
+
return scores;
|
|
3323
|
+
}
|
|
3324
|
+
async function runCalibrationAnalyze(config) {
|
|
3325
|
+
const parsed = CalibrationConfigSchema.parse(config);
|
|
3326
|
+
const { file, fileKey, nodeId } = await loadFile(parsed.input, parsed.token);
|
|
3327
|
+
const analyzeOptions = nodeId ? { targetNodeId: nodeId } : {};
|
|
3328
|
+
const analysisResult = analyzeFile(file, analyzeOptions);
|
|
3329
|
+
const analysisOutput = runAnalysisAgent({ analysisResult });
|
|
3330
|
+
const ruleScores = {
|
|
3331
|
+
...buildRuleScoresMap(),
|
|
3332
|
+
...extractRuleScores(analysisResult)
|
|
3333
|
+
};
|
|
3334
|
+
return { analysisOutput, ruleScores, fileKey };
|
|
3335
|
+
}
|
|
3336
|
+
function runCalibrationEvaluate(analysisJson, conversionJson, ruleScores) {
|
|
3337
|
+
const evaluationOutput = runEvaluationAgent({
|
|
3338
|
+
nodeIssueSummaries: analysisJson.nodeIssueSummaries.map((s) => ({
|
|
3339
|
+
nodeId: s.nodeId,
|
|
3340
|
+
nodePath: s.nodePath,
|
|
3341
|
+
flaggedRuleIds: s.flaggedRuleIds
|
|
3342
|
+
})),
|
|
3343
|
+
conversionRecords: conversionJson.records,
|
|
3344
|
+
ruleScores
|
|
3345
|
+
});
|
|
3346
|
+
const tuningOutput = runTuningAgent({
|
|
3347
|
+
mismatches: evaluationOutput.mismatches,
|
|
3348
|
+
ruleScores
|
|
3349
|
+
});
|
|
3350
|
+
const report = generateCalibrationReport({
|
|
3351
|
+
fileKey: analysisJson.fileKey,
|
|
3352
|
+
fileName: analysisJson.fileName,
|
|
3353
|
+
analyzedAt: analysisJson.analyzedAt,
|
|
3354
|
+
nodeCount: analysisJson.nodeCount,
|
|
3355
|
+
issueCount: analysisJson.issueCount,
|
|
3356
|
+
convertedNodeCount: conversionJson.records.length,
|
|
3357
|
+
skippedNodeCount: conversionJson.skippedNodeIds.length,
|
|
3358
|
+
scoreReport: analysisJson.scoreReport,
|
|
3359
|
+
mismatches: evaluationOutput.mismatches,
|
|
3360
|
+
validatedRules: evaluationOutput.validatedRules,
|
|
3361
|
+
adjustments: tuningOutput.adjustments,
|
|
3362
|
+
newRuleProposals: tuningOutput.newRuleProposals
|
|
3363
|
+
});
|
|
3364
|
+
return {
|
|
3365
|
+
evaluationOutput,
|
|
3366
|
+
tuningOutput,
|
|
3367
|
+
report
|
|
3368
|
+
};
|
|
3369
|
+
}
|
|
3370
|
+
async function runCalibration(config, executor, options) {
|
|
3371
|
+
const parsed = CalibrationConfigSchema.parse(config);
|
|
3372
|
+
const pipelineStart = Date.now();
|
|
3373
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3374
|
+
const logger = options?.enableActivityLog ? new ActivityLogger(parsed.input) : null;
|
|
3375
|
+
try {
|
|
3376
|
+
let stepStart = Date.now();
|
|
3377
|
+
const { file, fileKey, nodeId } = await loadFile(parsed.input, parsed.token);
|
|
3378
|
+
const analyzeOptions = nodeId ? { targetNodeId: nodeId } : {};
|
|
3379
|
+
const analysisResult = analyzeFile(file, analyzeOptions);
|
|
3380
|
+
const analysisOutput = runAnalysisAgent({ analysisResult });
|
|
3381
|
+
const ruleScores = {
|
|
3382
|
+
...buildRuleScoresMap(),
|
|
3383
|
+
...extractRuleScores(analysisResult)
|
|
3384
|
+
};
|
|
3385
|
+
await logger?.logStep({
|
|
3386
|
+
step: "Analysis",
|
|
3387
|
+
result: `${analysisResult.nodeCount} nodes, ${analysisResult.issues.length} issues, grade ${analysisOutput.scoreReport.overall.grade}`,
|
|
3388
|
+
durationMs: Date.now() - stepStart
|
|
3389
|
+
});
|
|
3390
|
+
stepStart = Date.now();
|
|
3391
|
+
const candidates = filterConversionCandidates(
|
|
3392
|
+
analysisOutput.nodeIssueSummaries,
|
|
3393
|
+
analysisResult.file.document
|
|
3394
|
+
);
|
|
3395
|
+
const selectedNodes = selectNodes(
|
|
3396
|
+
candidates,
|
|
3397
|
+
parsed.samplingStrategy,
|
|
3398
|
+
parsed.maxConversionNodes
|
|
3399
|
+
);
|
|
3400
|
+
const conversionOutput = await runConversionAgent(
|
|
3401
|
+
{
|
|
3402
|
+
fileKey,
|
|
3403
|
+
nodes: selectedNodes.map((n) => ({
|
|
3404
|
+
nodeId: n.nodeId,
|
|
3405
|
+
nodePath: n.nodePath,
|
|
3406
|
+
flaggedRuleIds: n.flaggedRuleIds
|
|
3407
|
+
}))
|
|
3408
|
+
},
|
|
3409
|
+
executor
|
|
3410
|
+
);
|
|
3411
|
+
await logger?.logStep({
|
|
3412
|
+
step: "Conversion",
|
|
3413
|
+
result: `${conversionOutput.records.length} converted, ${conversionOutput.skippedNodeIds.length} skipped`,
|
|
3414
|
+
durationMs: Date.now() - stepStart
|
|
3415
|
+
});
|
|
3416
|
+
stepStart = Date.now();
|
|
3417
|
+
const evaluationOutput = runEvaluationAgent({
|
|
3418
|
+
nodeIssueSummaries: selectedNodes.map((n) => ({
|
|
3419
|
+
nodeId: n.nodeId,
|
|
3420
|
+
nodePath: n.nodePath,
|
|
3421
|
+
flaggedRuleIds: n.flaggedRuleIds
|
|
3422
|
+
})),
|
|
3423
|
+
conversionRecords: conversionOutput.records,
|
|
3424
|
+
ruleScores
|
|
3425
|
+
});
|
|
3426
|
+
await logger?.logStep({
|
|
3427
|
+
step: "Evaluation",
|
|
3428
|
+
result: `${evaluationOutput.mismatches.length} mismatches, ${evaluationOutput.validatedRules.length} validated`,
|
|
3429
|
+
durationMs: Date.now() - stepStart
|
|
3430
|
+
});
|
|
3431
|
+
stepStart = Date.now();
|
|
3432
|
+
const tuningOutput = runTuningAgent({
|
|
3433
|
+
mismatches: evaluationOutput.mismatches,
|
|
3434
|
+
ruleScores
|
|
3435
|
+
});
|
|
3436
|
+
await logger?.logStep({
|
|
3437
|
+
step: "Tuning",
|
|
3438
|
+
result: `${tuningOutput.adjustments.length} adjustments, ${tuningOutput.newRuleProposals.length} new rule proposals`,
|
|
3439
|
+
durationMs: Date.now() - stepStart
|
|
3440
|
+
});
|
|
3441
|
+
const report = generateCalibrationReport({
|
|
3442
|
+
fileKey,
|
|
3443
|
+
fileName: file.name,
|
|
3444
|
+
analyzedAt: startedAt,
|
|
3445
|
+
nodeCount: analysisResult.nodeCount,
|
|
3446
|
+
issueCount: analysisResult.issues.length,
|
|
3447
|
+
convertedNodeCount: conversionOutput.records.length,
|
|
3448
|
+
skippedNodeCount: conversionOutput.skippedNodeIds.length,
|
|
3449
|
+
scoreReport: analysisOutput.scoreReport,
|
|
3450
|
+
mismatches: evaluationOutput.mismatches,
|
|
3451
|
+
validatedRules: evaluationOutput.validatedRules,
|
|
3452
|
+
adjustments: tuningOutput.adjustments,
|
|
3453
|
+
newRuleProposals: tuningOutput.newRuleProposals
|
|
3454
|
+
});
|
|
3455
|
+
const reportPath = resolve(parsed.outputPath);
|
|
3456
|
+
const reportDir = resolve(parsed.outputPath, "..");
|
|
3457
|
+
if (!existsSync(reportDir)) {
|
|
3458
|
+
mkdirSync(reportDir, { recursive: true });
|
|
3459
|
+
}
|
|
3460
|
+
await writeFile(reportPath, report, "utf-8");
|
|
3461
|
+
await logger?.logSummary({
|
|
3462
|
+
totalDurationMs: Date.now() - pipelineStart,
|
|
3463
|
+
nodesAnalyzed: analysisResult.nodeCount,
|
|
3464
|
+
nodesConverted: conversionOutput.records.length,
|
|
3465
|
+
mismatches: evaluationOutput.mismatches.length,
|
|
3466
|
+
adjustments: tuningOutput.adjustments.length,
|
|
3467
|
+
status: "completed"
|
|
3468
|
+
});
|
|
3469
|
+
return {
|
|
3470
|
+
status: "completed",
|
|
3471
|
+
scoreReport: analysisOutput.scoreReport,
|
|
3472
|
+
nodeIssueSummaries: analysisOutput.nodeIssueSummaries,
|
|
3473
|
+
mismatches: evaluationOutput.mismatches,
|
|
3474
|
+
validatedRules: evaluationOutput.validatedRules,
|
|
3475
|
+
adjustments: tuningOutput.adjustments,
|
|
3476
|
+
newRuleProposals: tuningOutput.newRuleProposals,
|
|
3477
|
+
reportPath,
|
|
3478
|
+
logPath: logger?.getLogPath()
|
|
3479
|
+
};
|
|
3480
|
+
} catch (error) {
|
|
3481
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
3482
|
+
await logger?.logSummary({
|
|
3483
|
+
totalDurationMs: Date.now() - pipelineStart,
|
|
3484
|
+
nodesAnalyzed: 0,
|
|
3485
|
+
nodesConverted: 0,
|
|
3486
|
+
mismatches: 0,
|
|
3487
|
+
adjustments: 0,
|
|
3488
|
+
status: `failed: ${errorMessage}`
|
|
3489
|
+
});
|
|
3490
|
+
return {
|
|
3491
|
+
status: "failed",
|
|
3492
|
+
scoreReport: {
|
|
3493
|
+
overall: { score: 0, maxScore: 100, percentage: 0, grade: "F" },
|
|
3494
|
+
byCategory: {},
|
|
3495
|
+
summary: { totalIssues: 0, blocking: 0, risk: 0, missingInfo: 0, suggestion: 0, nodeCount: 0 }
|
|
3496
|
+
},
|
|
3497
|
+
nodeIssueSummaries: [],
|
|
3498
|
+
mismatches: [],
|
|
3499
|
+
validatedRules: [],
|
|
3500
|
+
adjustments: [],
|
|
3501
|
+
newRuleProposals: [],
|
|
3502
|
+
reportPath: parsed.outputPath,
|
|
3503
|
+
error: errorMessage
|
|
3504
|
+
};
|
|
3505
|
+
}
|
|
3506
|
+
}
|
|
3507
|
+
|
|
3508
|
+
// src/index.ts
|
|
3509
|
+
var VERSION = "0.1.0";
|
|
3510
|
+
|
|
3511
|
+
export { ActivityLogger, AnalysisFileSchema, AnalysisNodeSchema, AnalysisNodeTypeSchema, CATEGORIES, CATEGORY_LABELS, CalibrationConfigSchema, CalibrationStatusSchema, CategorySchema, CategoryScoreSchema, ConfidenceSchema, ConversionRecordSchema, DEPTH_WEIGHT_CATEGORIES, DifficultySchema, FigmaClient, FigmaClientError, FigmaFileLoadError, FigmaUrlInfoSchema, FigmaUrlParseError, IssueSchema, LayoutAlignSchema, LayoutModeSchema, LayoutPositioningSchema, MismatchCaseSchema, MismatchTypeSchema, NewRuleProposalSchema, NodeIssueSummarySchema, RULE_CONFIGS, ReportMetadataSchema, ReportSchema, RuleConfigSchema, RuleDefinitionSchema, RuleEngine, RuleRelatedStruggleSchema, SEVERITY_LABELS, SEVERITY_WEIGHT, SamplingStrategySchema, ScoreAdjustmentSchema, SeveritySchema, UncoveredStruggleSchema, VERSION, absolutePositionInAutoLayout, ambiguousStructure, analyzeFile, buildConversionPrompt, buildFigmaDeepLink, calculateScores, componentPropertyUnused, createRuleEngine, deepNesting, defaultName, defineRule, detachedInstance, emptyFrame, extractRuleScores, fixedSizeInAutoLayout, fixedWidthInResponsiveContext, formatScoreSummary, generateCalibrationReport, getCategoryLabel, getConfigsWithPreset, getRuleOption, getSeverityLabel, gradeToClassName, groupUsage, hardcodeRisk, imageNoPlaceholder, inconsistentNamingConvention, inconsistentSiblingLayoutDirection, inconsistentSpacing, invisibleLayer, loadFigmaFileFromJson, magicNumberSpacing, missingComponent, missingLayoutHint, missingMaxWidth, missingMinWidth, missingResponsiveBehavior, multipleFillColors, nestedInstanceOverride, noAutoLayout, noDevStatus, nonSemanticName, numericSuffixName, overflowHiddenAbuse, parseFigmaJson, parseFigmaUrl, parseMcpMetadataXml, prototypeLinkInDesign, rawColor, rawFont, rawOpacity, rawShadow, ruleRegistry, runAnalysisAgent, runCalibration, runCalibrationAnalyze, runCalibrationEvaluate, runConversionAgent, runEvaluationAgent, runTuningAgent, singleUseComponent, supportsDepthWeight, textTruncationUnhandled, tooLongName, transformFigmaResponse, variantNotUsed, zIndexDependentLayout };
|
|
3512
|
+
//# sourceMappingURL=index.js.map
|
|
3513
|
+
//# sourceMappingURL=index.js.map
|