canicode 0.9.0 → 0.9.1

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/comparison/visual-compare-helpers.ts","../../src/core/comparison/visual-compare.ts","../../src/core/contracts/category.ts","../../src/core/contracts/severity.ts","../../src/core/contracts/rule.ts","../../src/core/rules/rule-config.ts","../../src/core/rules/rule-registry.ts","../../src/core/engine/rule-engine.ts","../../src/core/adapters/figma-client.ts","../../src/core/adapters/figma-transformer.ts","../../src/core/adapters/component-resolver.ts","../../src/core/contracts/figma-node.ts","../../src/core/adapters/figma-file-loader.ts","../../src/core/adapters/figma-url-parser.ts","../../src/core/engine/config-store.ts","../../src/core/engine/loader.ts","../../package.json","../../src/core/engine/scoring.ts","../../src/core/ui-constants.ts","../../src/core/ui-helpers.ts","../../src/core/report-html/render.ts","../../src/core/report-html/index.ts","../../src/core/rules/config-loader.ts","../../src/core/monitoring/events.ts","../../src/core/monitoring/capture.ts","../../src/core/monitoring/index.ts","../../src/core/monitoring/keys.ts","../../src/core/rules/node-semantics.ts","../../src/core/rules/rule-exceptions.ts","../../src/core/rules/rule-messages.ts","../../src/core/rules/structure/index.ts","../../src/core/rules/token/index.ts","../../src/core/rules/component/index.ts","../../src/core/rules/naming/index.ts","../../src/core/rules/interaction/index.ts","../../src/mcp/server.ts"],"names":["resolve","statSync","readFileSync","width","height","mkdirSync","dirname","writeFileSync","existsSync","PNG","z","config","BATCH_SIZE","join","response","file","componentDefs","interactionDests","esc","readFile","version","require","visualCompare"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAwBO,SAAS,iBAAiB,QAAA,EAA0B;AACzD,EAAA,OAAO,eAAA,CAAgB,QAAA,CAAS,QAAQ,CAAA,GAAI,CAAA,GAAI,CAAA;AAClD;AAoBO,SAAS,iBAAA,CAAkB,OAAA,EAAiB,MAAA,EAAgB,KAAA,EAAuB;AAExF,EAAA,MAAM,U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C5C,EAAA,MAAM,IAAA,GAAO,cAAa,IAAK,UAAA;AAC/B,mBAA2B,SAAA,GAAY,IAAA;AACvC,EAAA,gBAAA,CAAiB,aAAa,WAAA,EAAY;AAC1C,EAAA,cAAA,CAAe,gBAAgB,CAAA;AAE/B,EAAA,MAAM,SAAA,GAAY,IAAI,oBAAA,EAAqB;AAC3C,EAAA,MAAM,MAAA,CAAO,QAAQ,SAAS,CAAA;AAChC;AAEA,OAAA,CAAQ,EAAA,CAAG,cAAc,MAAM;AAC7B,EAAA,kBAAA,EAAmB;AACrB,CAAC,CAAA;AAED,IAAA,EAAK,CAAE,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA","file":"server.js","sourcesContent":["/**\n * Pure helper functions extracted from visual-compare.ts.\n * These have no side effects beyond file I/O and can be tested directly.\n */\n\nimport { writeFileSync, readFileSync, mkdirSync, statSync } from \"node:fs\";\nimport { resolve, dirname } from \"node:path\";\nimport pixelmatch from \"pixelmatch\";\nimport { PNG } from \"pngjs\";\n\n/** Directory used for caching Figma screenshots. */\nexport const FIGMA_CACHE_DIR = \"/tmp/canicode-figma-cache\";\n\n/**\n * Known @1x screenshot widths from fixture convention.\n * Screenshots at these widths are captured at 1x scale (pixel width = logical width).\n * All other widths are assumed @2x (e.g., 2400px PNG = 1200px logical).\n */\nexport const KNOWN_1X_WIDTHS = [1920, 768];\n\n/**\n * Infer the export scale of a fixture screenshot based on its pixel width.\n * Uses KNOWN_1X_WIDTHS convention: 1920/768 = @1x, others = @2x.\n */\nexport function inferExportScale(pngWidth: number): number {\n return KNOWN_1X_WIDTHS.includes(pngWidth) ? 1 : 2;\n}\n\n/** Cache time-to-live: 1 hour. */\nexport const FIGMA_CACHE_TTL_MS = 60 * 60 * 1000;\n\n/**\n * Tolerance for detecting integer scale factors (@2x, @3x).\n * Broader tolerance because render/rounding errors accumulate at higher scales.\n */\nexport const SCALE_ROUNDING_TOLERANCE = 0.08;\n\n/**\n * Tolerance for detecting 1x (unity) scale.\n * Tighter to avoid false positives — misidentifying a scaled PNG as 1x.\n */\nexport const UNITY_SCALE_TOLERANCE = 0.02;\n\n/**\n * Get the cache path for a given fileKey + nodeId combination.\n */\nexport function getFigmaCachePath(fileKey: string, nodeId: string, scale: number): string {\n // Sanitize nodeId for use as filename (replace : with -)\n const safeNodeId = nodeId.replace(/:/g, \"-\");\n return resolve(FIGMA_CACHE_DIR, `${fileKey}_${safeNodeId}@${scale}x.png`);\n}\n\n/**\n * Check if a cached Figma screenshot exists and is still fresh (within TTL).\n */\nexport function isCacheFresh(cachePath: string): boolean {\n try {\n const stats = statSync(cachePath);\n return Date.now() - stats.mtimeMs < FIGMA_CACHE_TTL_MS;\n } catch {\n // File doesn't exist or was removed between check and stat (TOCTOU safe)\n return false;\n }\n}\n\n/**\n * Infer device pixel ratio so the Playwright screenshot matches Figma PNG pixel dimensions.\n */\nexport function inferDeviceScaleFactor(\n pngW: number,\n pngH: number,\n logicalW: number,\n logicalH: number,\n fallback: number,\n): number {\n if (logicalW <= 0 || logicalH <= 0) return 1;\n const sx = pngW / logicalW;\n const sy = pngH / logicalH;\n const rounded = Math.round((sx + sy) / 2);\n if (rounded >= 2 && Math.abs(sx - rounded) < SCALE_ROUNDING_TOLERANCE && Math.abs(sy - rounded) < SCALE_ROUNDING_TOLERANCE) {\n return rounded;\n }\n if (Math.abs(sx - 1) < UNITY_SCALE_TOLERANCE && Math.abs(sy - 1) < UNITY_SCALE_TOLERANCE) return 1;\n return fallback >= 2 ? fallback : Math.max(1, Math.round(sx));\n}\n\n/**\n * Pad a PNG to target dimensions with a high-contrast fill color (magenta #FF00FF).\n * Unlike resize, padding preserves original pixels 1:1 and guarantees that\n * any size difference is counted as mismatched pixels by pixelmatch.\n *\n * Note: If both images contain magenta in the padded area, those pixels\n * will match — extremely rare in real designs but theoretically possible.\n */\nexport function padPng(png: PNG, targetWidth: number, targetHeight: number): PNG {\n const padded = new PNG({ width: targetWidth, height: targetHeight });\n // Fill entire canvas with magenta (FF00FF) — guaranteed to differ from any real content\n for (let i = 0; i < padded.data.length; i += 4) {\n padded.data[i] = 255; // R\n padded.data[i + 1] = 0; // G\n padded.data[i + 2] = 255; // B\n padded.data[i + 3] = 255; // A\n }\n // Copy original pixels into top-left corner\n for (let y = 0; y < png.height; y++) {\n for (let x = 0; x < png.width; x++) {\n const srcIdx = (y * png.width + x) * 4;\n const dstIdx = (y * targetWidth + x) * 4;\n padded.data[dstIdx] = png.data[srcIdx]!;\n padded.data[dstIdx + 1] = png.data[srcIdx + 1]!;\n padded.data[dstIdx + 2] = png.data[srcIdx + 2]!;\n padded.data[dstIdx + 3] = png.data[srcIdx + 3]!;\n }\n }\n return padded;\n}\n\n/** Options for screenshot comparison. */\nexport interface CompareOptions {\n /** How to handle size mismatches: \"pad\" (magenta fill) or \"crop\" (min dimensions). Default: \"pad\". */\n sizeMismatch?: \"pad\" | \"crop\";\n /** pixelmatch threshold (0-1). Default: 0.1. */\n threshold?: number;\n}\n\n/**\n * Crop a PNG to target dimensions (top-left corner preserved).\n */\nexport function cropPng(png: PNG, targetWidth: number, targetHeight: number): PNG {\n const cropped = new PNG({ width: targetWidth, height: targetHeight });\n for (let y = 0; y < targetHeight; y++) {\n png.data.copy(cropped.data, y * targetWidth * 4, y * png.width * 4, y * png.width * 4 + targetWidth * 4);\n }\n return cropped;\n}\n\n/**\n * Compare two PNG files using pixelmatch.\n */\nexport function compareScreenshots(\n path1: string,\n path2: string,\n diffOutputPath: string,\n options?: CompareOptions,\n): { similarity: number; diffPixels: number; totalPixels: number; width: number; height: number } {\n const sizeMismatch = options?.sizeMismatch ?? \"pad\";\n const threshold = options?.threshold ?? 0.1;\n const raw1 = PNG.sync.read(readFileSync(path1));\n const raw2 = PNG.sync.read(readFileSync(path2));\n\n let img1: PNG = raw1;\n let img2: PNG = raw2;\n\n // Size mismatch — normalize to same dimensions\n if (raw1.width !== raw2.width || raw1.height !== raw2.height) {\n if (sizeMismatch === \"crop\") {\n const width = Math.min(raw1.width, raw2.width);\n const height = Math.min(raw1.height, raw2.height);\n img1 = cropPng(raw1, width, height);\n img2 = cropPng(raw2, width, height);\n } else {\n const width = Math.max(raw1.width, raw2.width);\n const height = Math.max(raw1.height, raw2.height);\n img1 = padPng(raw1, width, height);\n img2 = padPng(raw2, width, height);\n }\n }\n\n const { width, height } = img1;\n const diff = new PNG({ width, height });\n const diffPixels = pixelmatch(img1.data, img2.data, diff.data, width, height, { threshold });\n\n mkdirSync(dirname(diffOutputPath), { recursive: true });\n writeFileSync(diffOutputPath, PNG.sync.write(diff));\n\n const totalPixels = width * height;\n const similarity = diffPixels === 0 ? 100 : Math.floor((1 - diffPixels / totalPixels) * 100);\n\n return { similarity, diffPixels, totalPixels, width, height };\n}\n\n// ── Root width expansion (for responsive comparison) ─────────────────────\n\n/**\n * Replace fixed root-element widths in HTML with fluid values so the layout\n * can expand to fill a wider viewport.\n *\n * Targets the first CSS rule that sets a pixel `width` on the root container\n * (commonly `.root`, `body > div`, etc.) and replaces it with `width: 100%`.\n * Also removes `min-width` pixel constraints.\n *\n * Originally from `src/experiments/ablation/run-condition.ts`.\n */\nexport function expandRootWidth(html: string): string {\n const styleMatch = html.match(/<style[\\s\\S]*?<\\/style>/i);\n if (!styleMatch) return html;\n\n const style = styleMatch[0];\n // Find the first CSS rule block (the root element's rule)\n const firstRuleMatch = style.match(/([^{}]*\\{)([^}]*)\\}/);\n if (!firstRuleMatch) return html;\n\n const rulePrefix = firstRuleMatch[1]!; // e.g. \".root {\"\n const ruleBody = firstRuleMatch[2]!; // e.g. \" width: 375px; min-width: 375px; \"\n\n // Replace width and min-width only inside the first rule\n const newBody = ruleBody\n .replace(/(?<![-\\w])width:\\s*\\d+px/, \"width: 100%\")\n .replace(/min-width:\\s*\\d+px/g, \"min-width: 0\");\n\n const newRule = `${rulePrefix}${newBody}}`;\n const newStyle = style.replace(firstRuleMatch[0], newRule);\n return html.replace(style, newStyle);\n}\n\n// ── Code metrics (shared with ablation helpers) ─────────────────────────\n\n/** Count unique CSS class selectors in an HTML string's <style> block. */\nexport function countCssClasses(html: string): number {\n const styleMatch = html.match(/<style[\\s\\S]*?<\\/style>/i);\n if (!styleMatch) return 0;\n const classes = styleMatch[0].match(/\\.[a-zA-Z][\\w-]*\\s*[{,:]/g);\n return new Set(classes?.map((c) => c.replace(/\\s*[{,:]$/, \"\"))).size;\n}\n\n/** Count unique CSS custom property definitions in an HTML string's <style> block. */\nexport function countCssVariables(html: string): number {\n const styleMatch = html.match(/<style[\\s\\S]*?<\\/style>/i);\n if (!styleMatch) return 0;\n const vars = styleMatch[0].match(/--[\\w-]+\\s*:/g);\n return new Set(vars?.map((v) => v.replace(/\\s*:$/, \"\"))).size;\n}\n\n/** Compute code metrics from an HTML string. */\nexport function computeCodeMetrics(html: string): {\n htmlBytes: number;\n htmlLines: number;\n cssClassCount: number;\n cssVariableCount: number;\n} {\n return {\n htmlBytes: Buffer.byteLength(html, \"utf-8\"),\n htmlLines: html.split(\"\\n\").length,\n cssClassCount: countCssClasses(html),\n cssVariableCount: countCssVariables(html),\n };\n}\n","/**\n * Visual comparison: renders HTML code with Playwright, fetches Figma screenshot,\n * and computes pixel-level similarity using pixelmatch.\n */\n\nimport { writeFileSync, readFileSync, mkdirSync, existsSync, copyFileSync } from \"node:fs\";\nimport { resolve, dirname } from \"node:path\";\nimport { PNG } from \"pngjs\";\nimport {\n FIGMA_CACHE_DIR,\n getFigmaCachePath,\n isCacheFresh,\n inferDeviceScaleFactor,\n inferExportScale,\n compareScreenshots,\n expandRootWidth,\n type CompareOptions,\n} from \"./visual-compare-helpers.js\";\n\n/** Result of a visual comparison between Figma design and rendered code. */\nexport interface VisualCompareResult {\n similarity: number;\n diffPixels: number;\n totalPixels: number;\n width: number;\n height: number;\n figmaScreenshotPath: string;\n codeScreenshotPath: string;\n diffPath: string;\n}\n\n/** Options for the visual comparison pipeline. */\nexport interface VisualCompareOptions {\n figmaUrl: string;\n figmaToken: string;\n codePath: string;\n outputDir?: string | undefined;\n /**\n * Logical CSS viewport (CSS pixels). Omit a dimension to infer from the Figma PNG\n * using `figmaExportScale`. When the whole object is omitted, both dimensions are inferred.\n */\n viewport?: { width?: number; height?: number } | undefined;\n /**\n * Figma Images API `scale` and assumed scale for fixture `figma.png` (e.g. from `save-fixture`).\n * Default 2 matches REST exports and avoids comparing a @2x PNG against a 1× Playwright capture.\n */\n figmaExportScale?: number | undefined;\n /**\n * Path to a local Figma screenshot file. When provided, skips URL-based fetch\n * and uses this file directly as the ground truth. Useful for responsive comparison\n * where multiple fixture screenshots exist at different viewports.\n */\n figmaScreenshotPath?: string | undefined;\n /**\n * When true, replace the root element's fixed pixel width with `width: 100%`\n * before rendering. This allows the layout to expand to fill the viewport,\n * which is needed for responsive comparison (e.g., 375px design rendered at 768px).\n */\n expandRoot?: boolean | undefined;\n}\n\n/**\n * Fetch Figma node screenshot via REST API, with file-based caching.\n * Cache key: fileKey + nodeId. Cache location: /tmp/canicode-figma-cache/. TTL: 1 hour.\n */\nasync function fetchFigmaScreenshot(\n fileKey: string,\n nodeId: string,\n token: string,\n outputPath: string,\n scale: number,\n): Promise<void> {\n const cachePath = getFigmaCachePath(fileKey, nodeId, scale);\n\n // Return cached version if fresh\n if (isCacheFresh(cachePath)) {\n mkdirSync(dirname(outputPath), { recursive: true });\n copyFileSync(cachePath, outputPath);\n return;\n }\n\n const res = await fetch(\n `https://api.figma.com/v1/images/${fileKey}?ids=${nodeId}&format=png&scale=${scale}`,\n { headers: { \"X-Figma-Token\": token } },\n );\n if (!res.ok) throw new Error(`Figma Images API: ${res.status} ${res.statusText}`);\n\n const data = (await res.json()) as { images: Record<string, string | null> };\n const imgUrl = data.images[nodeId];\n if (!imgUrl) throw new Error(`No image returned for node ${nodeId}`);\n\n const imgRes = await fetch(imgUrl);\n if (!imgRes.ok) throw new Error(`Failed to download Figma screenshot: ${imgRes.status}`);\n\n const buffer = Buffer.from(await imgRes.arrayBuffer());\n\n // Write to output path\n mkdirSync(dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, buffer);\n\n // Save to cache\n mkdirSync(FIGMA_CACHE_DIR, { recursive: true });\n writeFileSync(cachePath, buffer);\n}\n\n/**\n * Render HTML file with Playwright and take a screenshot.\n * @param deviceScaleFactor - Pass 2 when the Figma reference is @2x and `viewport` is logical CSS size.\n */\nexport async function renderCodeScreenshot(\n codePath: string,\n outputPath: string,\n logicalViewport: { width: number; height: number },\n deviceScaleFactor: number = 1,\n): Promise<void> {\n // Dynamic import — playwright is an optional dependency\n const { chromium } = await import(\"playwright\");\n const browser = await chromium.launch();\n try {\n const context = await browser.newContext({\n viewport: logicalViewport,\n deviceScaleFactor,\n });\n const page = await context.newPage();\n\n await page.goto(`file://${resolve(codePath)}`, {\n waitUntil: \"networkidle\",\n timeout: 30_000,\n });\n await page.waitForTimeout(1000);\n\n // Capture only the first child element (the design root), not the full body/viewport\n const root = page.locator(\"body > *:first-child\");\n if (await root.count() > 0) {\n await root.screenshot({ path: outputPath });\n } else {\n await page.screenshot({ path: outputPath });\n }\n } finally {\n await browser.close();\n }\n}\n\n/**\n * Run full visual comparison pipeline.\n */\nexport async function visualCompare(options: VisualCompareOptions): Promise<VisualCompareResult> {\n const outputDir = options.outputDir ?? \"/tmp/canicode-visual-compare\";\n const figmaScreenshotPath = resolve(outputDir, \"figma.png\");\n const codeScreenshotPath = resolve(outputDir, \"code.png\");\n const diffPath = resolve(outputDir, \"diff.png\");\n\n // Parse Figma URL\n const urlMatch = options.figmaUrl.match(/\\/design\\/([^/]+)\\//);\n const fileKey = urlMatch?.[1];\n if (!fileKey) throw new Error(\"Invalid Figma URL — could not extract file key\");\n\n const nodeIdMatch = options.figmaUrl.match(/node-id=([^&\\s]+)/);\n const nodeId = nodeIdMatch?.[1]?.replace(/-/g, \":\");\n if (!nodeId) throw new Error(\"Invalid Figma URL — missing node-id\");\n\n // Step 1: Figma screenshot — use local file if provided, otherwise fetch via API\n if (options.figmaScreenshotPath) {\n if (!existsSync(options.figmaScreenshotPath)) {\n throw new Error(`Figma screenshot not found: ${options.figmaScreenshotPath}`);\n }\n mkdirSync(dirname(figmaScreenshotPath), { recursive: true });\n copyFileSync(options.figmaScreenshotPath, figmaScreenshotPath);\n } else if (!existsSync(figmaScreenshotPath)) {\n const fetchScale = options.figmaExportScale ?? 2;\n await fetchFigmaScreenshot(fileKey, nodeId, options.figmaToken, figmaScreenshotPath, fetchScale);\n if (!existsSync(figmaScreenshotPath)) {\n throw new Error(`Figma screenshot was not created at expected path: ${figmaScreenshotPath}`);\n }\n }\n\n // Step 2: Logical viewport + deviceScaleFactor so code.png matches figma.png pixels (@2x, etc.)\n const figmaPng = PNG.sync.read(readFileSync(figmaScreenshotPath));\n // Auto-detect export scale from PNG width when using local screenshot (KNOWN_1X_WIDTHS convention)\n const exportScale = options.figmaExportScale ?? inferExportScale(figmaPng.width);\n const hasViewportOverride = options.viewport !== undefined;\n let logicalW: number;\n let logicalH: number;\n let deviceScaleFactor: number;\n\n if (!hasViewportOverride) {\n logicalW = Math.max(1, Math.round(figmaPng.width / exportScale));\n logicalH = Math.max(1, Math.round(figmaPng.height / exportScale));\n deviceScaleFactor = exportScale;\n } else {\n logicalW =\n options.viewport!.width ?? Math.max(1, Math.round(figmaPng.width / exportScale));\n logicalH =\n options.viewport!.height ?? Math.max(1, Math.round(figmaPng.height / exportScale));\n deviceScaleFactor = inferDeviceScaleFactor(\n figmaPng.width,\n figmaPng.height,\n logicalW,\n logicalH,\n exportScale,\n );\n }\n\n // Step 3: Render code screenshot at matching physical resolution\n let renderPath = options.codePath;\n if (options.expandRoot) {\n const originalHtml = readFileSync(resolve(options.codePath), \"utf-8\");\n const expandedHtml = expandRootWidth(originalHtml);\n renderPath = resolve(outputDir, \"code-expanded.html\");\n writeFileSync(renderPath, expandedHtml);\n }\n await renderCodeScreenshot(\n renderPath,\n codeScreenshotPath,\n { width: logicalW, height: logicalH },\n deviceScaleFactor,\n );\n\n // Validate both screenshots exist before comparing\n if (!existsSync(codeScreenshotPath)) {\n throw new Error(`Code screenshot was not created at expected path: ${codeScreenshotPath}`);\n }\n\n // Compare\n const result = compareScreenshots(figmaScreenshotPath, codeScreenshotPath, diffPath);\n\n return {\n ...result,\n figmaScreenshotPath,\n codeScreenshotPath,\n diffPath,\n };\n}\n\n/** Options for renderAndCompare. */\nexport interface RenderAndCompareOptions {\n /** How to handle size mismatches. Default: \"pad\". */\n sizeMismatch?: CompareOptions[\"sizeMismatch\"];\n /** Output file suffix (e.g. \"baseline\", \"stripped-layout\"). */\n suffix?: string;\n /** pixelmatch threshold. Default: 0.1. */\n threshold?: number;\n /** Replace root element's fixed width with 100% before rendering. */\n expandRoot?: boolean;\n}\n\n/**\n * Render HTML → screenshot, then compare against a Figma screenshot.\n * Handles export scale inference and size normalization.\n *\n * Extracted from ablation helpers to be shared by calibration + experiments.\n */\nexport async function renderAndCompare(\n htmlPath: string,\n figmaScreenshotPath: string,\n outputDir: string,\n options?: RenderAndCompareOptions,\n): Promise<{ similarity: number }> {\n const suffix = options?.suffix ?? \"output\";\n const sizeMismatch = options?.sizeMismatch ?? \"pad\";\n const threshold = options?.threshold;\n\n const figmaImage = PNG.sync.read(readFileSync(figmaScreenshotPath));\n const figmaWidth = figmaImage.width;\n const exportScale = inferExportScale(figmaWidth);\n const logicalW = Math.max(1, Math.round(figmaWidth / exportScale));\n const logicalH = Math.max(1, Math.round(figmaImage.height / exportScale));\n\n let renderHtmlPath = htmlPath;\n if (options?.expandRoot) {\n const originalHtml = readFileSync(resolve(htmlPath), \"utf-8\");\n const expandedHtml = expandRootWidth(originalHtml);\n renderHtmlPath = resolve(outputDir, `code-expanded-${suffix}.html`);\n writeFileSync(renderHtmlPath, expandedHtml);\n }\n const codePngPath = resolve(outputDir, `code-${suffix}.png`);\n await renderCodeScreenshot(renderHtmlPath, codePngPath, { width: logicalW, height: logicalH }, exportScale);\n\n const figmaCopyPath = resolve(outputDir, `figma-${suffix}.png`);\n copyFileSync(figmaScreenshotPath, figmaCopyPath);\n\n const diffPath = resolve(outputDir, `diff-${suffix}.png`);\n const compareOpts: CompareOptions = { sizeMismatch };\n if (threshold !== undefined) compareOpts.threshold = threshold;\n return compareScreenshots(figmaCopyPath, codePngPath, diffPath, compareOpts);\n}\n","import { z } from \"zod\";\n\nexport const CategorySchema = z.enum([\n \"pixel-critical\",\n \"responsive-critical\",\n \"code-quality\",\n \"token-management\",\n \"semantic\",\n \"interaction\",\n]);\n\nexport type Category = z.infer<typeof CategorySchema>;\n\nexport const CATEGORIES = CategorySchema.options;\n\nexport const CATEGORY_LABELS: Record<Category, string> = {\n \"pixel-critical\": \"Pixel Critical\",\n \"responsive-critical\": \"Responsive Critical\",\n \"code-quality\": \"Code Quality\",\n \"token-management\": \"Token Management\",\n \"semantic\": \"Semantic\",\n \"interaction\": \"Interaction\",\n};\n","import { z } from \"zod\";\n\nexport const SeveritySchema = z.enum([\n \"blocking\",\n \"risk\",\n \"missing-info\",\n \"suggestion\",\n]);\n\nexport type Severity = z.infer<typeof SeveritySchema>;\n\nexport const SEVERITY_WEIGHT: Record<Severity, number> = {\n blocking: 10,\n risk: 5,\n \"missing-info\": 2,\n suggestion: 1,\n};\n\nexport const SEVERITY_LABELS: Record<Severity, string> = {\n blocking: \"Blocking\",\n risk: \"Risk\",\n \"missing-info\": \"Missing Info\",\n suggestion: \"Suggestion\",\n};\n","import { z } from \"zod\";\nimport { CategorySchema, type Category } from \"./category.js\";\nimport { SeveritySchema } from \"./severity.js\";\nimport type { AnalysisFile, AnalysisNode } from \"./figma-node.js\";\n\n/**\n * Rule definition - static metadata (does not change)\n */\nexport const RuleDefinitionSchema = z.object({\n id: z.string(),\n name: z.string(),\n category: CategorySchema,\n why: z.string(),\n impact: z.string(),\n fix: z.string(),\n});\n\nexport type RuleDefinition = z.infer<typeof RuleDefinitionSchema>;\n\n/**\n * Rule config - adjustable settings (can be modified via presets)\n */\nexport const RuleConfigSchema = z.object({\n severity: SeveritySchema,\n score: z.number().int().max(0),\n depthWeight: z.number().min(1).max(2).optional(),\n enabled: z.boolean().default(true),\n options: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type RuleConfig = z.infer<typeof RuleConfigSchema>;\n\n/**\n * Context passed to rule check functions\n */\nexport interface RuleContext {\n file: AnalysisFile;\n parent?: AnalysisNode | undefined;\n depth: number;\n /** Depth relative to the nearest COMPONENT/INSTANCE ancestor. Resets at component boundaries. */\n componentDepth: number;\n maxDepth: number;\n path: string[];\n /** Ancestor node types from root to parent (excludes current node). */\n ancestorTypes: string[];\n siblings?: AnalysisNode[] | undefined;\n /** Per-analysis shared state. Created fresh for each analysis run, eliminating module-level mutable state. */\n analysisState: Map<string, unknown>;\n}\n\n/**\n * Get or initialize per-analysis state for a rule.\n * Each key gets its own lazily-initialized state that persists for the duration of one analysis run.\n */\nexport function getAnalysisState<T>(context: RuleContext, key: string, init: () => T): T {\n if (context.analysisState.has(key)) {\n return context.analysisState.get(key) as T;\n }\n const value = init();\n context.analysisState.set(key, value);\n return value;\n}\n\n/**\n * Rule violation result from check function\n */\nexport interface RuleViolation {\n ruleId: string;\n subType?: string;\n nodeId: string;\n nodePath: string;\n message: string;\n suggestion: string;\n guide?: string;\n}\n\n/**\n * Rule check function signature\n */\nexport type RuleCheckFn = (\n node: AnalysisNode,\n context: RuleContext,\n options?: Record<string, unknown>\n) => RuleViolation | null;\n\n/**\n * Complete rule with definition, config, and check function\n */\nexport interface Rule {\n definition: RuleDefinition;\n check: RuleCheckFn;\n}\n\n/**\n * Rule ID type for type safety\n */\nexport type RuleId =\n // Pixel Critical — layout issues that directly affect pixel accuracy (ΔV ≥ 5%)\n | \"no-auto-layout\"\n | \"absolute-position-in-auto-layout\"\n | \"non-layout-container\"\n // Responsive Critical — size issues that break at different viewports (ΔV ≥ 15%)\n | \"fixed-size-in-auto-layout\"\n | \"missing-size-constraint\"\n // Code Quality — structural issues affecting code reuse (ΔV ≈ 0%, CSS classes -8~15)\n | \"missing-component\"\n | \"detached-instance\"\n | \"variant-structure-mismatch\"\n | \"deep-nesting\"\n // Token Management — raw values without design tokens\n | \"raw-value\"\n | \"irregular-spacing\"\n // Interaction — missing state variants and prototype links for interactive components\n | \"missing-interaction-state\"\n | \"missing-prototype\"\n // Semantic — naming issues with negligible pixel impact (ΔV < 2%)\n | \"non-standard-naming\"\n | \"non-semantic-name\"\n | \"inconsistent-naming-convention\";\n\n/**\n * Categories that support depthWeight\n */\nexport const DEPTH_WEIGHT_CATEGORIES: Category[] = [\"pixel-critical\", \"responsive-critical\"];\n\n/**\n * Check if a category supports depth weighting\n */\nexport function supportsDepthWeight(category: Category): boolean {\n return DEPTH_WEIGHT_CATEGORIES.includes(category);\n}\n","import type { Category } from \"../contracts/category.js\";\nimport type { RuleConfig, RuleId } from \"../contracts/rule.js\";\n\n/**\n * Maps each rule ID to its category.\n * Categories are based on ablation experiment data (PR #149, #150):\n * - pixel-critical: ΔV ≥ 5% — layout info removal directly degrades pixel accuracy\n * - responsive-critical: ΔV ≥ 15% at expanded viewport — size info critical for responsive\n * - code-quality: ΔV ≈ 0% but CSS classes -8~15 — affects code structure, not pixels\n * - token-management: raw values without design tokens — wrong input = wrong output\n * - semantic: ΔV < 2%, negligible code difference — naming and semantic issues\n */\nexport const RULE_ID_CATEGORY: Record<RuleId, Category> = {\n // Pixel Critical\n \"no-auto-layout\": \"pixel-critical\",\n \"absolute-position-in-auto-layout\": \"pixel-critical\",\n \"non-layout-container\": \"pixel-critical\",\n // Responsive Critical\n \"fixed-size-in-auto-layout\": \"responsive-critical\",\n \"missing-size-constraint\": \"responsive-critical\",\n // Code Quality\n \"missing-component\": \"code-quality\",\n \"detached-instance\": \"code-quality\",\n \"variant-structure-mismatch\": \"code-quality\",\n \"deep-nesting\": \"code-quality\",\n // Token Management\n \"raw-value\": \"token-management\",\n \"irregular-spacing\": \"token-management\",\n // Interaction\n \"missing-interaction-state\": \"interaction\",\n \"missing-prototype\": \"interaction\",\n // Semantic\n \"non-standard-naming\": \"semantic\",\n \"non-semantic-name\": \"semantic\",\n \"inconsistent-naming-convention\": \"semantic\",\n};\n\n/**\n * Central configuration for all rules.\n * Scores based on ablation experiment + AI implementation interview (#200):\n * - pixel-critical: -10 ~ -7 (layout strip caused ΔV +5.4%)\n * - responsive-critical: -8 ~ -6 (size-constraints ΔV +15.9% at responsive viewports)\n * - code-quality: -7 ~ -3 (CSS classes -8~15, no pixel impact)\n * - token-management: -5 ~ -4 (wrong input = wrong output, irregular spacing actively causes errors)\n * - interaction: -1 (uncalibrated — no metric to validate, kept minimal #210)\n * - semantic: -4 ~ -1 (non-semantic-name upgraded per interview — causes actual implementation errors)\n *\n * Category weights removed (#196) — overall score is simple average of categories.\n */\nexport const RULE_CONFIGS: Record<RuleId, RuleConfig> = {\n // ── Pixel Critical ──\n \"no-auto-layout\": {\n severity: \"blocking\",\n score: -10,\n depthWeight: 1.5,\n enabled: true,\n },\n \"absolute-position-in-auto-layout\": {\n severity: \"blocking\",\n score: -7,\n depthWeight: 1.3,\n enabled: true,\n },\n \"non-layout-container\": {\n severity: \"blocking\",\n score: -8,\n depthWeight: 1.2,\n enabled: true,\n },\n\n // ── Responsive Critical ──\n \"fixed-size-in-auto-layout\": {\n severity: \"risk\",\n score: -6,\n enabled: true,\n },\n \"missing-size-constraint\": {\n severity: \"risk\",\n score: -8,\n enabled: true,\n },\n\n // ── Code Quality ──\n \"missing-component\": {\n severity: \"risk\",\n score: -7,\n enabled: true,\n options: {\n minRepetitions: 2,\n structureMinRepetitions: 2,\n maxFingerprintDepth: 3,\n },\n },\n \"detached-instance\": {\n severity: \"risk\",\n score: -4,\n enabled: true,\n },\n \"variant-structure-mismatch\": {\n severity: \"risk\",\n score: -6,\n enabled: true,\n },\n \"deep-nesting\": {\n severity: \"risk\",\n score: -3,\n enabled: true,\n options: {\n maxDepth: 5,\n },\n },\n\n // ── Token Management ──\n \"raw-value\": {\n severity: \"missing-info\",\n score: -4,\n enabled: true,\n },\n \"irregular-spacing\": {\n severity: \"risk\",\n score: -5,\n enabled: true,\n options: {\n gridBase: 2,\n },\n },\n\n // ── Interaction ──\n \"missing-interaction-state\": {\n severity: \"suggestion\",\n score: -1, // uncalibrated: no metric to validate score (#210), kept at -1 to preserve category visibility\n enabled: true,\n },\n \"missing-prototype\": {\n severity: \"missing-info\",\n score: -3,\n enabled: false, // disabled: interactionDestinations data missing from fixtures (#139)\n },\n\n // ── Semantic ──\n \"non-standard-naming\": {\n severity: \"suggestion\",\n score: -3, // higher than other naming rules: non-standard state names break interaction detection pipeline\n enabled: true,\n },\n \"non-semantic-name\": {\n severity: \"risk\",\n score: -4,\n enabled: true,\n },\n \"inconsistent-naming-convention\": {\n severity: \"suggestion\",\n score: -1,\n enabled: true,\n },\n};\n\n/**\n * Preset types for different analysis modes\n */\nexport type Preset = \"relaxed\" | \"dev-friendly\" | \"ai-ready\" | \"strict\";\n\n/**\n * Get rule configs with preset applied\n */\nexport function getConfigsWithPreset(\n preset: Preset\n): Record<RuleId, RuleConfig> {\n const configs = { ...RULE_CONFIGS };\n\n switch (preset) {\n case \"relaxed\":\n // Disable blocking rules, reduce scores\n for (const [id, config] of Object.entries(configs)) {\n if (config.severity === \"blocking\") {\n configs[id as RuleId] = {\n ...config,\n severity: \"risk\",\n score: Math.round(config.score * 0.5),\n };\n }\n }\n break;\n\n case \"dev-friendly\":\n // Focus on pixel-critical and responsive-critical issues\n for (const [id, config] of Object.entries(configs)) {\n const ruleId = id as RuleId;\n const category = RULE_ID_CATEGORY[ruleId];\n if (category !== \"pixel-critical\" && category !== \"responsive-critical\") {\n configs[ruleId] = { ...config, enabled: false };\n }\n }\n break;\n\n case \"ai-ready\":\n // Boost pixel-critical and token-management rules\n for (const [id, config] of Object.entries(configs)) {\n const ruleId = id as RuleId;\n const category = RULE_ID_CATEGORY[ruleId];\n if (category === \"pixel-critical\" || category === \"token-management\") {\n configs[ruleId] = {\n ...config,\n score: Math.round(config.score * 1.5),\n };\n }\n }\n break;\n\n case \"strict\":\n // Increase scores but respect disabled rules\n for (const [id, config] of Object.entries(configs)) {\n configs[id as RuleId] = {\n ...config,\n score: Math.round(config.score * 1.5),\n };\n }\n break;\n }\n\n return configs;\n}\n\n/**\n * Get option value for a rule with type safety\n */\nexport function getRuleOption<T>(\n ruleId: RuleId,\n optionKey: string,\n defaultValue: T\n): T {\n const config = RULE_CONFIGS[ruleId];\n if (!config.options) return defaultValue;\n const value = config.options[optionKey];\n return (value as T) ?? defaultValue;\n}\n","import type { Rule, RuleConfig, RuleId } from \"../contracts/rule.js\";\nimport type { Category } from \"../contracts/category.js\";\nimport { RULE_CONFIGS } from \"./rule-config.js\";\n\n/**\n * Registry for all rules\n */\nclass RuleRegistry {\n private rules: Map<RuleId, Rule> = new Map();\n\n /**\n * Register a rule\n */\n register(rule: Rule): void {\n this.rules.set(rule.definition.id as RuleId, rule);\n }\n\n /**\n * Get a rule by ID\n */\n get(id: RuleId): Rule | undefined {\n return this.rules.get(id);\n }\n\n /**\n * Get all registered rules\n */\n getAll(): Rule[] {\n return Array.from(this.rules.values());\n }\n\n /**\n * Get rules by category\n */\n getByCategory(category: Category): Rule[] {\n return this.getAll().filter((rule) => rule.definition.category === category);\n }\n\n /**\n * Get enabled rules with their configs\n */\n getEnabled(configs: Record<RuleId, RuleConfig> = RULE_CONFIGS): Rule[] {\n return this.getAll().filter((rule) => {\n const config = configs[rule.definition.id as RuleId];\n return config?.enabled ?? true;\n });\n }\n\n /**\n * Get config for a rule\n */\n getConfig(\n id: RuleId,\n configs: Record<RuleId, RuleConfig> = RULE_CONFIGS\n ): RuleConfig {\n return configs[id];\n }\n\n /**\n * Check if a rule is registered\n */\n has(id: RuleId): boolean {\n return this.rules.has(id);\n }\n\n /**\n * Get count of registered rules\n */\n get size(): number {\n return this.rules.size;\n }\n}\n\n/**\n * Global rule registry instance\n */\nexport const ruleRegistry = new RuleRegistry();\n\n/**\n * Helper to create and register a rule\n */\nexport function defineRule(rule: Rule): Rule {\n ruleRegistry.register(rule);\n return rule;\n}\n","import type { AnalysisFile, AnalysisNode } from \"../contracts/figma-node.js\";\nimport type {\n Rule,\n RuleConfig,\n RuleContext,\n RuleId,\n RuleViolation,\n} from \"../contracts/rule.js\";\nimport { supportsDepthWeight } from \"../contracts/rule.js\";\nimport { ruleRegistry } from \"../rules/rule-registry.js\";\nimport { RULE_CONFIGS } from \"../rules/rule-config.js\";\n\n/**\n * Analysis issue with calculated score and metadata\n */\nexport interface AnalysisIssue {\n violation: RuleViolation;\n rule: Rule;\n config: RuleConfig;\n depth: number;\n maxDepth: number;\n calculatedScore: number;\n}\n\n/**\n * Information about a rule that threw during analysis\n */\nexport interface RuleFailure {\n ruleId: string;\n nodeName: string;\n nodeId: string;\n error: string;\n}\n\n/**\n * Analysis result from the rule engine\n */\nexport interface AnalysisResult {\n file: AnalysisFile;\n issues: AnalysisIssue[];\n failedRules: RuleFailure[];\n maxDepth: number;\n nodeCount: number;\n analyzedAt: string;\n}\n\n/**\n * Options for the rule engine\n */\nexport interface RuleEngineOptions {\n configs?: Record<RuleId, RuleConfig>;\n enabledRules?: RuleId[];\n disabledRules?: RuleId[];\n targetNodeId?: string;\n excludeNodeNames?: string[];\n excludeNodeTypes?: string[];\n}\n\n/**\n * Calculate the maximum depth of a node tree\n */\nfunction calculateMaxDepth(node: AnalysisNode, currentDepth = 0): number {\n if (!node.children || node.children.length === 0) {\n return currentDepth;\n }\n\n let maxChildDepth = currentDepth;\n for (const child of node.children) {\n const childDepth = calculateMaxDepth(child, currentDepth + 1);\n if (childDepth > maxChildDepth) {\n maxChildDepth = childDepth;\n }\n }\n\n return maxChildDepth;\n}\n\n/**\n * Count total nodes in a tree\n */\nfunction countNodes(node: AnalysisNode): number {\n let count = 1;\n if (node.children) {\n for (const child of node.children) {\n count += countNodes(child);\n }\n }\n return count;\n}\n\n/**\n * Find a node by ID in the tree\n */\nfunction findNodeById(node: AnalysisNode, nodeId: string): AnalysisNode | null {\n // Figma node IDs use \":\" separator, URL uses \"-\"\n const normalizedId = nodeId.replace(/-/g, \":\");\n\n if (node.id === normalizedId) {\n return node;\n }\n\n if (node.children) {\n for (const child of node.children) {\n const found = findNodeById(child, nodeId);\n if (found) return found;\n }\n }\n\n return null;\n}\n\n/**\n * Calculate depth weight multiplier for a rule\n * Higher values (closer to 1.5x) at root level, 1.0x at leaf level\n */\nfunction calcDepthWeight(\n depth: number,\n maxDepth: number,\n depthWeight?: number\n): number {\n if (!depthWeight || depthWeight <= 1) return 1;\n if (maxDepth === 0) return depthWeight;\n\n // Linear interpolation: depthWeight at depth 0, 1.0 at maxDepth\n const ratio = depth / maxDepth;\n return depthWeight - (depthWeight - 1) * ratio;\n}\n\n/**\n * Rule engine for analyzing Figma files\n */\nexport class RuleEngine {\n private configs: Record<RuleId, RuleConfig>;\n private enabledRuleIds: Set<RuleId> | null;\n private disabledRuleIds: Set<RuleId>;\n private targetNodeId: string | undefined;\n private excludeNamePattern: RegExp | null;\n private excludeNodeTypes: Set<string> | null;\n\n constructor(options: RuleEngineOptions = {}) {\n this.configs = options.configs ?? RULE_CONFIGS;\n this.enabledRuleIds = options.enabledRules\n ? new Set(options.enabledRules)\n : null;\n this.disabledRuleIds = new Set(options.disabledRules ?? []);\n this.targetNodeId = options.targetNodeId;\n this.excludeNamePattern = options.excludeNodeNames && options.excludeNodeNames.length > 0\n ? new RegExp(`\\\\b(${options.excludeNodeNames.join(\"|\")})\\\\b`, \"i\")\n : null;\n this.excludeNodeTypes = options.excludeNodeTypes && options.excludeNodeTypes.length > 0\n ? new Set(options.excludeNodeTypes)\n : null;\n }\n\n /**\n * Analyze a Figma file and return issues\n */\n analyze(file: AnalysisFile): AnalysisResult {\n // Fresh per-analysis state — eliminates module-level mutable state in rules\n const analysisState = new Map<string, unknown>();\n\n // Find target node if specified\n let rootNode = file.document;\n if (this.targetNodeId) {\n const targetNode = findNodeById(file.document, this.targetNodeId);\n if (!targetNode) {\n throw new Error(`Node not found: ${this.targetNodeId}`);\n }\n rootNode = targetNode;\n }\n\n // Calculate max depth before analysis\n const maxDepth = calculateMaxDepth(rootNode);\n const nodeCount = countNodes(rootNode);\n\n const issues: AnalysisIssue[] = [];\n const failedRules: RuleFailure[] = [];\n const enabledRules = this.getEnabledRules();\n\n // Traverse the tree and run rules on each node\n this.traverseAndCheck(\n rootNode,\n file,\n enabledRules,\n maxDepth,\n issues,\n failedRules,\n 0,\n [],\n [],\n 0,\n analysisState,\n undefined,\n undefined\n );\n\n return {\n file,\n issues,\n failedRules,\n maxDepth,\n nodeCount,\n analyzedAt: new Date().toISOString(),\n };\n }\n\n /**\n * Get rules that should be run based on configuration\n */\n private getEnabledRules(): Rule[] {\n return ruleRegistry.getAll().filter((rule) => {\n const ruleId = rule.definition.id as RuleId;\n\n // Check if explicitly disabled\n if (this.disabledRuleIds.has(ruleId)) return false;\n\n // Check if we have an explicit enable list\n if (this.enabledRuleIds && !this.enabledRuleIds.has(ruleId)) return false;\n\n // Check config enabled status\n const config = this.configs[ruleId];\n return config?.enabled ?? true;\n });\n }\n\n /**\n * Recursively traverse the tree and run rules\n */\n private traverseAndCheck(\n node: AnalysisNode,\n file: AnalysisFile,\n rules: Rule[],\n maxDepth: number,\n issues: AnalysisIssue[],\n failedRules: RuleFailure[],\n depth: number,\n path: string[],\n ancestorTypes: string[],\n componentDepth: number,\n analysisState: Map<string, unknown>,\n parent?: AnalysisNode,\n siblings?: AnalysisNode[]\n ): void {\n const nodePath = [...path, node.name];\n\n // Reset componentDepth at component boundaries\n const isComponentBoundary = node.type === \"COMPONENT\" || node.type === \"COMPONENT_SET\" || node.type === \"INSTANCE\";\n const currentComponentDepth = isComponentBoundary ? 0 : componentDepth;\n\n // Skip nodes matching excluded types or name patterns\n if (this.excludeNodeTypes && this.excludeNodeTypes.has(node.type)) {\n return;\n }\n if (this.excludeNamePattern && this.excludeNamePattern.test(node.name)) {\n return;\n }\n\n // Build context for this node\n const context: RuleContext = {\n file,\n parent,\n depth,\n componentDepth: currentComponentDepth,\n maxDepth,\n path: nodePath,\n ancestorTypes,\n siblings,\n analysisState,\n };\n\n // Run each rule on this node\n for (const rule of rules) {\n const ruleId = rule.definition.id as RuleId;\n const config = this.configs[ruleId];\n const options = config?.options;\n\n try {\n const violation = rule.check(node, context, options);\n\n if (violation) {\n // Calculate score with depth weight if applicable\n let calculatedScore = config.score;\n\n if (\n supportsDepthWeight(rule.definition.category) &&\n config.depthWeight\n ) {\n const weight = calcDepthWeight(depth, maxDepth, config.depthWeight);\n calculatedScore = Math.round(config.score * weight);\n }\n\n issues.push({\n violation,\n rule,\n config,\n depth,\n maxDepth,\n calculatedScore,\n });\n }\n } catch (error) {\n // Track failure and continue — never let one rule break the whole analysis\n failedRules.push({\n ruleId,\n nodeName: node.name,\n nodeId: node.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n // Recurse into children\n if (node.children && node.children.length > 0) {\n const childAncestorTypes = [...ancestorTypes, node.type];\n for (const child of node.children) {\n this.traverseAndCheck(\n child,\n file,\n rules,\n maxDepth,\n issues,\n failedRules,\n depth + 1,\n nodePath,\n childAncestorTypes,\n currentComponentDepth + 1,\n analysisState,\n node,\n node.children\n );\n }\n }\n }\n}\n\n/**\n * Create a rule engine with default configuration\n */\nexport function createRuleEngine(options?: RuleEngineOptions): RuleEngine {\n return new RuleEngine(options);\n}\n\n/**\n * Convenience function to analyze a file with default settings\n */\nexport function analyzeFile(\n file: AnalysisFile,\n options?: RuleEngineOptions\n): AnalysisResult {\n const engine = createRuleEngine(options);\n return engine.analyze(file);\n}\n","import type { GetFileResponse, Node } from \"@figma/rest-api-spec\";\n\nconst FIGMA_API_BASE = \"https://api.figma.com/v1\";\n\nexport interface GetFileNodesResponse {\n name: string;\n lastModified: string;\n version: string;\n nodes: Record<string, {\n document: Node;\n components: GetFileResponse[\"components\"];\n styles: GetFileResponse[\"styles\"];\n }>;\n}\n\nexport interface FigmaClientOptions {\n token: string;\n}\n\nexport class FigmaClient {\n private token: string;\n\n constructor(options: FigmaClientOptions) {\n this.token = options.token;\n }\n\n static fromEnv(): FigmaClient {\n const token = process.env[\"FIGMA_TOKEN\"];\n if (!token) {\n throw new FigmaClientError(\n \"FIGMA_TOKEN environment variable is not set\"\n );\n }\n return new FigmaClient({ token });\n }\n\n async getFile(fileKey: string): Promise<GetFileResponse> {\n const url = `${FIGMA_API_BASE}/files/${fileKey}`;\n const response = await fetch(url, {\n headers: {\n \"X-Figma-Token\": this.token,\n },\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new FigmaClientError(\n `Failed to fetch file: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n return response.json() as Promise<GetFileResponse>;\n }\n\n /**\n * Get rendered images for specific nodes\n * Returns a map of nodeId → image URL\n */\n async getNodeImages(\n fileKey: string,\n nodeIds: string[],\n options?: { format?: \"png\" | \"svg\" | \"jpg\"; scale?: number }\n ): Promise<Record<string, string | null>> {\n const format = options?.format ?? \"png\";\n const scale = options?.scale ?? 2;\n\n // Batch into chunks to avoid 414 URI Too Large\n const BATCH_SIZE = 50;\n const allImages: Record<string, string | null> = {};\n\n for (let i = 0; i < nodeIds.length; i += BATCH_SIZE) {\n const batch = nodeIds.slice(i, i + BATCH_SIZE);\n const ids = batch.join(\",\");\n const url = `${FIGMA_API_BASE}/images/${fileKey}?ids=${encodeURIComponent(ids)}&format=${format}&scale=${scale}`;\n const response = await fetch(url, {\n headers: {\n \"X-Figma-Token\": this.token,\n },\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new FigmaClientError(\n `Failed to fetch images: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n const data = await response.json() as { images: Record<string, string | null> };\n for (const [nodeId, imageUrl] of Object.entries(data.images)) {\n allImages[nodeId] = imageUrl;\n }\n }\n\n return allImages;\n }\n\n /**\n * Get original image fill URLs by imageRef.\n * Returns a mapping of imageRef → download URL for all image fills in the file.\n */\n async getImageFills(fileKey: string): Promise<Record<string, string>> {\n const url = `${FIGMA_API_BASE}/files/${fileKey}/images`;\n const response = await fetch(url, {\n headers: { \"X-Figma-Token\": this.token },\n });\n if (!response.ok) {\n const error = await response.text().catch(() => \"\");\n throw new FigmaClientError(\n `Failed to fetch image fills: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n const data = await response.json() as { meta?: { images?: Record<string, string> } };\n return data.meta?.images ?? {};\n }\n\n /**\n * Download an image URL and return as base64\n */\n async fetchImageAsBase64(imageUrl: string): Promise<string> {\n const response = await fetch(imageUrl);\n if (!response.ok) {\n throw new FigmaClientError(\n `Failed to download image: ${response.status}`,\n response.status\n );\n }\n const buffer = await response.arrayBuffer();\n return Buffer.from(buffer).toString(\"base64\");\n }\n\n async getFileNodes(\n fileKey: string,\n nodeIds: string[]\n ): Promise<GetFileNodesResponse> {\n const ids = nodeIds.join(\",\");\n const url = `${FIGMA_API_BASE}/files/${fileKey}/nodes?ids=${encodeURIComponent(ids)}`;\n const response = await fetch(url, {\n headers: {\n \"X-Figma-Token\": this.token,\n },\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new FigmaClientError(\n `Failed to fetch nodes: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n return response.json() as Promise<GetFileNodesResponse>;\n }\n}\n\nexport class FigmaClientError extends Error {\n constructor(\n message: string,\n public statusCode?: number,\n public responseBody?: unknown\n ) {\n super(message);\n this.name = \"FigmaClientError\";\n }\n}\n","import type { GetFileResponse, Node } from \"@figma/rest-api-spec\";\nimport type { GetFileNodesResponse } from \"./figma-client.js\";\nimport type { AnalysisFile, AnalysisNode } from \"../contracts/figma-node.js\";\n\n/**\n * Transform Figma API response to analysis types\n */\nexport function transformFigmaResponse(\n fileKey: string,\n response: GetFileResponse\n): AnalysisFile {\n return {\n fileKey,\n name: response.name,\n lastModified: response.lastModified,\n version: response.version,\n document: transformNode(response.document),\n components: transformComponents(response.components),\n styles: transformStyles(response.styles),\n };\n}\n\nfunction transformNode(node: Node): AnalysisNode {\n const base: AnalysisNode = {\n id: node.id,\n name: node.name,\n type: node.type as AnalysisNode[\"type\"],\n visible: \"visible\" in node ? (node.visible ?? true) : true,\n };\n\n // Layout properties\n if (\"layoutMode\" in node && node.layoutMode) {\n base.layoutMode = node.layoutMode as AnalysisNode[\"layoutMode\"];\n }\n if (\"layoutAlign\" in node && node.layoutAlign) {\n base.layoutAlign = node.layoutAlign as AnalysisNode[\"layoutAlign\"];\n }\n if (\"layoutPositioning\" in node && node.layoutPositioning) {\n base.layoutPositioning =\n node.layoutPositioning as AnalysisNode[\"layoutPositioning\"];\n }\n if (\"layoutSizingHorizontal\" in node && node.layoutSizingHorizontal) {\n base.layoutSizingHorizontal =\n node.layoutSizingHorizontal as AnalysisNode[\"layoutSizingHorizontal\"];\n }\n if (\"layoutSizingVertical\" in node && node.layoutSizingVertical) {\n base.layoutSizingVertical =\n node.layoutSizingVertical as AnalysisNode[\"layoutSizingVertical\"];\n }\n if (\"primaryAxisAlignItems\" in node) {\n base.primaryAxisAlignItems = node.primaryAxisAlignItems as string;\n }\n if (\"counterAxisAlignItems\" in node) {\n base.counterAxisAlignItems = node.counterAxisAlignItems as string;\n }\n if (\"itemSpacing\" in node) {\n base.itemSpacing = node.itemSpacing as number;\n }\n if (\"paddingLeft\" in node) {\n base.paddingLeft = node.paddingLeft as number;\n }\n if (\"paddingRight\" in node) {\n base.paddingRight = node.paddingRight as number;\n }\n if (\"paddingTop\" in node) {\n base.paddingTop = node.paddingTop as number;\n }\n if (\"paddingBottom\" in node) {\n base.paddingBottom = node.paddingBottom as number;\n }\n\n // Size constraints (responsive)\n if (\"minWidth\" in node && typeof node.minWidth === \"number\") {\n base.minWidth = node.minWidth;\n }\n if (\"maxWidth\" in node && typeof node.maxWidth === \"number\") {\n base.maxWidth = node.maxWidth;\n }\n if (\"minHeight\" in node && typeof node.minHeight === \"number\") {\n base.minHeight = node.minHeight;\n }\n if (\"maxHeight\" in node && typeof node.maxHeight === \"number\") {\n base.maxHeight = node.maxHeight;\n }\n if (\"layoutGrow\" in node && node.layoutGrow !== undefined) {\n base.layoutGrow = node.layoutGrow as 0 | 1;\n }\n if (\"constraints\" in node && node.constraints) {\n base.constraints = node.constraints as AnalysisNode[\"constraints\"];\n }\n\n // Wrap (flex-wrap)\n if (\"layoutWrap\" in node && node.layoutWrap) {\n base.layoutWrap = node.layoutWrap as AnalysisNode[\"layoutWrap\"];\n }\n if (\"counterAxisSpacing\" in node && typeof node.counterAxisSpacing === \"number\") {\n base.counterAxisSpacing = node.counterAxisSpacing;\n }\n if (\"counterAxisAlignContent\" in node && node.counterAxisAlignContent) {\n base.counterAxisAlignContent =\n node.counterAxisAlignContent as AnalysisNode[\"counterAxisAlignContent\"];\n }\n\n // Grid layout (container)\n if (\"gridRowCount\" in node && typeof node.gridRowCount === \"number\") {\n base.gridRowCount = node.gridRowCount;\n }\n if (\"gridColumnCount\" in node && typeof node.gridColumnCount === \"number\") {\n base.gridColumnCount = node.gridColumnCount;\n }\n if (\"gridRowGap\" in node && typeof node.gridRowGap === \"number\") {\n base.gridRowGap = node.gridRowGap;\n }\n if (\"gridColumnGap\" in node && typeof node.gridColumnGap === \"number\") {\n base.gridColumnGap = node.gridColumnGap;\n }\n if (\"gridColumnsSizing\" in node && typeof node.gridColumnsSizing === \"string\") {\n base.gridColumnsSizing = node.gridColumnsSizing;\n }\n if (\"gridRowsSizing\" in node && typeof node.gridRowsSizing === \"string\") {\n base.gridRowsSizing = node.gridRowsSizing;\n }\n\n // Grid layout (child)\n if (\"gridChildHorizontalAlign\" in node && node.gridChildHorizontalAlign) {\n base.gridChildHorizontalAlign =\n node.gridChildHorizontalAlign as AnalysisNode[\"gridChildHorizontalAlign\"];\n }\n if (\"gridChildVerticalAlign\" in node && node.gridChildVerticalAlign) {\n base.gridChildVerticalAlign =\n node.gridChildVerticalAlign as AnalysisNode[\"gridChildVerticalAlign\"];\n }\n if (\"gridRowSpan\" in node && typeof node.gridRowSpan === \"number\") {\n base.gridRowSpan = node.gridRowSpan;\n }\n if (\"gridColumnSpan\" in node && typeof node.gridColumnSpan === \"number\") {\n base.gridColumnSpan = node.gridColumnSpan;\n }\n if (\"gridRowAnchorIndex\" in node && typeof node.gridRowAnchorIndex === \"number\") {\n base.gridRowAnchorIndex = node.gridRowAnchorIndex;\n }\n if (\"gridColumnAnchorIndex\" in node && typeof node.gridColumnAnchorIndex === \"number\") {\n base.gridColumnAnchorIndex = node.gridColumnAnchorIndex;\n }\n\n // Overflow / clip\n if (\"clipsContent\" in node && typeof node.clipsContent === \"boolean\") {\n base.clipsContent = node.clipsContent;\n }\n if (\"overflowDirection\" in node && node.overflowDirection) {\n base.overflowDirection =\n node.overflowDirection as AnalysisNode[\"overflowDirection\"];\n }\n\n // Size/position\n if (\"absoluteBoundingBox\" in node && node.absoluteBoundingBox) {\n base.absoluteBoundingBox = node.absoluteBoundingBox;\n }\n\n // Component properties\n if (\"componentId\" in node) {\n base.componentId = node.componentId as string;\n }\n if (\"componentPropertyDefinitions\" in node) {\n base.componentPropertyDefinitions =\n node.componentPropertyDefinitions as Record<string, unknown>;\n }\n if (\"componentProperties\" in node) {\n base.componentProperties = node.componentProperties as Record<\n string,\n unknown\n >;\n }\n\n // Style properties\n if (\"styles\" in node) {\n base.styles = node.styles as Record<string, string>;\n }\n if (\"fills\" in node) {\n base.fills = node.fills as unknown[];\n }\n if (\"strokes\" in node) {\n base.strokes = node.strokes as unknown[];\n }\n if (\"strokeWeight\" in node && typeof node.strokeWeight === \"number\") {\n base.strokeWeight = node.strokeWeight;\n }\n if (\"individualStrokeWeights\" in node && node.individualStrokeWeights) {\n base.individualStrokeWeights = node.individualStrokeWeights as Record<string, number>;\n }\n if (\"effects\" in node) {\n base.effects = node.effects as unknown[];\n }\n if (\"cornerRadius\" in node && typeof node.cornerRadius === \"number\") {\n base.cornerRadius = node.cornerRadius;\n }\n if (\"opacity\" in node && typeof node.opacity === \"number\" && node.opacity < 1) {\n base.opacity = node.opacity;\n }\n\n // Variable bindings\n if (\"boundVariables\" in node && node.boundVariables) {\n base.boundVariables = node.boundVariables as Record<string, unknown>;\n }\n\n // Text properties\n if (\"characters\" in node) {\n base.characters = node.characters as string;\n }\n if (\"style\" in node) {\n base.style = node.style as Record<string, unknown>;\n }\n if (\"textTruncation\" in node && (node.textTruncation === \"DISABLED\" || node.textTruncation === \"ENDING\")) {\n base.textTruncation = node.textTruncation;\n }\n if (\"maxLines\" in node && typeof node.maxLines === \"number\") {\n base.maxLines = node.maxLines;\n }\n\n // Handoff status\n if (\"devStatus\" in node && node.devStatus) {\n base.devStatus = node.devStatus as AnalysisNode[\"devStatus\"];\n }\n\n // Prototype interactions\n if (\"interactions\" in node && Array.isArray(node.interactions) && node.interactions.length > 0) {\n base.interactions = node.interactions;\n }\n\n // Recursively transform children\n if (\"children\" in node && Array.isArray(node.children)) {\n base.children = node.children.map(transformNode);\n }\n\n return base;\n}\n\n/**\n * Transform Figma /v1/files/{key}/nodes response to analysis types.\n * Returns the first node's subtree as the document.\n */\nexport function transformFileNodesResponse(\n fileKey: string,\n response: GetFileNodesResponse\n): AnalysisFile {\n const entries = Object.values(response.nodes);\n const first = entries[0];\n if (!first)\n throw new Error(\n \"No nodes returned from Figma API — the node-id in the URL may be invalid or deleted. \" +\n \"Try selecting the frame in Figma and copying the link again.\"\n );\n\n return {\n fileKey,\n name: response.name,\n lastModified: response.lastModified,\n version: response.version,\n document: transformNode(first.document),\n components: transformComponents(first.components),\n styles: transformStyles(first.styles),\n };\n}\n\n/**\n * Transform component master nodes from a /v1/files/{key}/nodes response.\n * Each requested node ID is transformed into an AnalysisNode if present.\n */\nexport function transformComponentMasterNodes(\n response: GetFileNodesResponse,\n requestedIds: string[]\n): Record<string, AnalysisNode> {\n const result: Record<string, AnalysisNode> = {};\n for (const id of requestedIds) {\n const entry = response.nodes[id];\n if (entry?.document) {\n result[id] = transformNode(entry.document);\n }\n }\n return result;\n}\n\nfunction transformComponents(\n components: GetFileResponse[\"components\"]\n): AnalysisFile[\"components\"] {\n const result: AnalysisFile[\"components\"] = {};\n for (const [id, component] of Object.entries(components)) {\n result[id] = {\n key: component.key,\n name: component.name,\n description: component.description,\n };\n }\n return result;\n}\n\nfunction transformStyles(\n styles: GetFileResponse[\"styles\"]\n): AnalysisFile[\"styles\"] {\n const result: AnalysisFile[\"styles\"] = {};\n for (const [id, style] of Object.entries(styles)) {\n result[id] = {\n key: style.key,\n name: style.name,\n styleType: style.styleType,\n };\n }\n return result;\n}\n","import type { FigmaClient } from \"./figma-client.js\";\nimport type { AnalysisNode } from \"../contracts/figma-node.js\";\nimport { transformComponentMasterNodes } from \"./figma-transformer.js\";\n\nconst BATCH_SIZE = 50;\n\n/**\n * Recursively collect all unique componentId values from INSTANCE nodes.\n */\nexport function collectComponentIds(node: AnalysisNode): Set<string> {\n const ids = new Set<string>();\n\n function walk(n: AnalysisNode): void {\n if (n.type === \"INSTANCE\" && n.componentId) {\n ids.add(n.componentId);\n }\n if (n.children) {\n for (const child of n.children) {\n walk(child);\n }\n }\n }\n\n walk(node);\n return ids;\n}\n\n/**\n * Recursively collect all unique interaction destination IDs from nodes.\n * These are the node IDs that interactions (e.g., ON_HOVER → CHANGE_TO) point to.\n */\nexport function collectInteractionDestinationIds(node: AnalysisNode): Set<string> {\n const ids = new Set<string>();\n\n function walk(n: AnalysisNode): void {\n if (n.interactions && Array.isArray(n.interactions)) {\n for (const interaction of n.interactions) {\n const i = interaction as {\n trigger?: { type?: string };\n actions?: Array<{ destinationId?: string; navigation?: string }>;\n };\n if (i.trigger?.type === \"ON_HOVER\" && i.actions) {\n for (const action of i.actions) {\n if (action.navigation === \"CHANGE_TO\" && action.destinationId) {\n ids.add(action.destinationId);\n }\n }\n }\n }\n }\n if (n.children) {\n for (const child of n.children) {\n walk(child);\n }\n }\n }\n\n walk(node);\n return ids;\n}\n\n/**\n * Resolve component master node trees via multi-pass fetching.\n *\n * Pass 1: collect component IDs from the document tree, fetch their masters.\n * Pass 2+: collect component IDs from fetched masters that were not in previous passes.\n * Repeats up to maxPasses (default 2).\n *\n * Batches API calls at BATCH_SIZE IDs per request.\n * Skips IDs that return null (e.g. external library components).\n */\nexport async function resolveComponentDefinitions(\n client: FigmaClient,\n fileKey: string,\n document: AnalysisNode,\n maxPasses = 2\n): Promise<Record<string, AnalysisNode>> {\n const allDefinitions: Record<string, AnalysisNode> = {};\n const resolvedIds = new Set<string>();\n\n // Pass 1: collect from the original document\n let pendingIds = collectComponentIds(document);\n\n for (let pass = 0; pass < maxPasses; pass++) {\n // Filter out already-resolved IDs\n const idsToFetch = [...pendingIds].filter((id) => !resolvedIds.has(id));\n if (idsToFetch.length === 0) break;\n\n // Fetch in batches\n for (let i = 0; i < idsToFetch.length; i += BATCH_SIZE) {\n const batch = idsToFetch.slice(i, i + BATCH_SIZE);\n try {\n const response = await client.getFileNodes(fileKey, batch);\n const transformed = transformComponentMasterNodes(response, batch);\n for (const [id, node] of Object.entries(transformed)) {\n allDefinitions[id] = node;\n }\n } catch (err) {\n // Skip failed batches (e.g. external library components)\n console.debug(`[component-resolver] batch fetch failed (${batch.length} ids):`, err);\n }\n }\n\n // Mark all attempted IDs as resolved (even if they failed/returned null)\n for (const id of idsToFetch) {\n resolvedIds.add(id);\n }\n\n // Collect new IDs only from masters fetched in this pass (not all accumulated)\n pendingIds = new Set<string>();\n for (const id of idsToFetch) {\n const node = allDefinitions[id];\n if (node) {\n for (const nestedId of collectComponentIds(node)) {\n if (!resolvedIds.has(nestedId)) {\n pendingIds.add(nestedId);\n }\n }\n }\n }\n }\n\n return allDefinitions;\n}\n\n/**\n * Resolve interaction destination nodes (e.g., hover variants).\n *\n * Collects all destinationId values from interactions in the document,\n * excludes those already in componentDefinitions, and fetches them.\n */\nexport async function resolveInteractionDestinations(\n client: FigmaClient,\n fileKey: string,\n document: AnalysisNode,\n existingDefinitions?: Record<string, AnalysisNode>,\n): Promise<Record<string, AnalysisNode>> {\n const destIds = collectInteractionDestinationIds(document);\n if (destIds.size === 0) return {};\n\n const allDestinations: Record<string, AnalysisNode> = {};\n const idsToFetch: string[] = [];\n\n for (const id of destIds) {\n const existing = existingDefinitions?.[id];\n if (existing) {\n allDestinations[id] = existing;\n } else {\n idsToFetch.push(id);\n }\n }\n\n if (idsToFetch.length === 0) return allDestinations;\n\n for (let i = 0; i < idsToFetch.length; i += BATCH_SIZE) {\n const batch = idsToFetch.slice(i, i + BATCH_SIZE);\n try {\n const response = await client.getFileNodes(fileKey, batch);\n const transformed = transformComponentMasterNodes(response, batch);\n for (const [id, node] of Object.entries(transformed)) {\n allDestinations[id] = node;\n }\n } catch (err) {\n console.debug(`[component-resolver] interaction destination fetch failed (${batch.length} ids):`, err);\n }\n }\n\n return allDestinations;\n}\n","import { z } from \"zod\";\n\n/**\n * Figma node types required for analysis\n * See @figma/rest-api-spec for full API types\n */\n\nexport const AnalysisNodeTypeSchema = z.enum([\n \"DOCUMENT\",\n \"CANVAS\",\n \"FRAME\",\n \"GROUP\",\n \"SECTION\",\n \"COMPONENT\",\n \"COMPONENT_SET\",\n \"INSTANCE\",\n \"RECTANGLE\",\n \"ELLIPSE\",\n \"VECTOR\",\n \"TEXT\",\n \"LINE\",\n \"BOOLEAN_OPERATION\",\n \"STAR\",\n \"REGULAR_POLYGON\",\n \"SLICE\",\n \"STICKY\",\n \"SHAPE_WITH_TEXT\",\n \"CONNECTOR\",\n \"WIDGET\",\n \"EMBED\",\n \"LINK_UNFURL\",\n \"TABLE\",\n \"TABLE_CELL\",\n \"SLOT\",\n]);\n\nexport type AnalysisNodeType = z.infer<typeof AnalysisNodeTypeSchema>;\n\nexport const LayoutModeSchema = z.enum([\"NONE\", \"HORIZONTAL\", \"VERTICAL\", \"GRID\"]);\nexport type LayoutMode = z.infer<typeof LayoutModeSchema>;\n\nexport const LayoutAlignSchema = z.enum([\"MIN\", \"CENTER\", \"MAX\", \"STRETCH\", \"INHERIT\"]);\nexport type LayoutAlign = z.infer<typeof LayoutAlignSchema>;\n\nexport const LayoutPositioningSchema = z.enum([\"AUTO\", \"ABSOLUTE\"]);\nexport type LayoutPositioning = z.infer<typeof LayoutPositioningSchema>;\n\nexport const LayoutConstraintSchema = z.object({\n horizontal: z.enum([\"LEFT\", \"RIGHT\", \"CENTER\", \"LEFT_RIGHT\", \"SCALE\"]),\n vertical: z.enum([\"TOP\", \"BOTTOM\", \"CENTER\", \"TOP_BOTTOM\", \"SCALE\"]),\n});\nexport type LayoutConstraint = z.infer<typeof LayoutConstraintSchema>;\n\nexport const LayoutWrapSchema = z.enum([\"NO_WRAP\", \"WRAP\"]);\nexport type LayoutWrap = z.infer<typeof LayoutWrapSchema>;\n\nexport const OverflowDirectionSchema = z.enum([\n \"HORIZONTAL_SCROLLING\",\n \"VERTICAL_SCROLLING\",\n \"HORIZONTAL_AND_VERTICAL_SCROLLING\",\n \"NONE\",\n]);\nexport type OverflowDirection = z.infer<typeof OverflowDirectionSchema>;\n\nexport const GridChildAlignSchema = z.enum([\"AUTO\", \"MIN\", \"CENTER\", \"MAX\"]);\nexport type GridChildAlign = z.infer<typeof GridChildAlignSchema>;\n\n/**\n * Lightweight FigmaNode type for analysis\n * Contains only properties needed by rules\n */\nconst BaseAnalysisNodeSchema = z.object({\n // Basic identification\n id: z.string(),\n name: z.string(),\n type: AnalysisNodeTypeSchema,\n visible: z.boolean().default(true),\n\n // Layout analysis\n layoutMode: LayoutModeSchema.optional(),\n layoutAlign: LayoutAlignSchema.optional(),\n layoutPositioning: LayoutPositioningSchema.optional(),\n layoutSizingHorizontal: z.enum([\"FIXED\", \"HUG\", \"FILL\"]).optional(),\n layoutSizingVertical: z.enum([\"FIXED\", \"HUG\", \"FILL\"]).optional(),\n primaryAxisAlignItems: z.string().optional(),\n counterAxisAlignItems: z.string().optional(),\n itemSpacing: z.number().optional(),\n paddingLeft: z.number().optional(),\n paddingRight: z.number().optional(),\n paddingTop: z.number().optional(),\n paddingBottom: z.number().optional(),\n\n // Size constraints (responsive)\n minWidth: z.number().optional(),\n maxWidth: z.number().optional(),\n minHeight: z.number().optional(),\n maxHeight: z.number().optional(),\n layoutGrow: z.union([z.literal(0), z.literal(1)]).optional(),\n constraints: LayoutConstraintSchema.optional(),\n\n // Wrap (flex-wrap)\n layoutWrap: LayoutWrapSchema.optional(),\n counterAxisSpacing: z.number().optional(),\n counterAxisAlignContent: z.enum([\"AUTO\", \"SPACE_BETWEEN\"]).optional(),\n\n // Grid layout (container)\n gridRowCount: z.number().optional(),\n gridColumnCount: z.number().optional(),\n gridRowGap: z.number().optional(),\n gridColumnGap: z.number().optional(),\n gridColumnsSizing: z.string().optional(),\n gridRowsSizing: z.string().optional(),\n\n // Grid layout (child)\n gridChildHorizontalAlign: GridChildAlignSchema.optional(),\n gridChildVerticalAlign: GridChildAlignSchema.optional(),\n gridRowSpan: z.number().optional(),\n gridColumnSpan: z.number().optional(),\n gridRowAnchorIndex: z.number().optional(),\n gridColumnAnchorIndex: z.number().optional(),\n\n // Overflow / clip\n clipsContent: z.boolean().optional(),\n overflowDirection: OverflowDirectionSchema.optional(),\n\n // Size/position analysis\n absoluteBoundingBox: z\n .object({\n x: z.number(),\n y: z.number(),\n width: z.number(),\n height: z.number(),\n })\n .nullable()\n .optional(),\n\n // Component analysis\n componentId: z.string().optional(),\n componentPropertyDefinitions: z.record(z.string(), z.unknown()).optional(),\n componentProperties: z.record(z.string(), z.unknown()).optional(),\n\n // Style/token analysis\n styles: z.record(z.string(), z.string()).optional(),\n fills: z.array(z.unknown()).optional(),\n strokes: z.array(z.unknown()).optional(),\n strokeWeight: z.number().optional(),\n individualStrokeWeights: z.record(z.string(), z.number()).optional(),\n effects: z.array(z.unknown()).optional(),\n cornerRadius: z.number().optional(),\n opacity: z.number().optional(),\n\n // Variable binding analysis (design tokens)\n boundVariables: z.record(z.string(), z.unknown()).optional(),\n\n // Text analysis\n characters: z.string().optional(),\n style: z.record(z.string(), z.unknown()).optional(),\n textTruncation: z.enum([\"DISABLED\", \"ENDING\"]).optional(),\n maxLines: z.number().optional(),\n\n // Handoff analysis\n devStatus: z\n .object({\n type: z.enum([\"NONE\", \"READY_FOR_DEV\", \"COMPLETED\"]),\n description: z.string().optional(),\n })\n .optional(),\n\n // Prototype interactions\n interactions: z.array(z.unknown()).optional(),\n\n // Naming analysis metadata\n isAsset: z.boolean().optional(),\n});\n\nexport type AnalysisNode = z.infer<typeof BaseAnalysisNodeSchema> & {\n children?: AnalysisNode[] | undefined;\n};\n\nexport const AnalysisNodeSchema: z.ZodType<AnalysisNode> =\n BaseAnalysisNodeSchema.extend({\n children: z.lazy(() => AnalysisNodeSchema.array().optional()),\n }) as z.ZodType<AnalysisNode>;\n\n/**\n * Figma file metadata for analysis\n */\nexport const AnalysisFileSchema = z.object({\n fileKey: z.string(),\n name: z.string(),\n lastModified: z.string(),\n version: z.string(),\n sourceUrl: z.string().optional(),\n document: AnalysisNodeSchema,\n components: z.record(\n z.string(),\n z.object({\n key: z.string(),\n name: z.string(),\n description: z.string(),\n })\n ),\n componentDefinitions: z.record(z.string(), AnalysisNodeSchema).optional(),\n interactionDestinations: z.record(z.string(), AnalysisNodeSchema).optional(),\n styles: z.record(\n z.string(),\n z.object({\n key: z.string(),\n name: z.string(),\n styleType: z.string(),\n })\n ),\n});\n\nexport type AnalysisFile = z.infer<typeof AnalysisFileSchema>;\n","import { readFile } from \"node:fs/promises\";\nimport { basename, dirname } from \"node:path\";\nimport type { GetFileResponse } from \"@figma/rest-api-spec\";\nimport type { AnalysisFile, AnalysisNode } from \"../contracts/figma-node.js\";\nimport { AnalysisNodeSchema } from \"../contracts/figma-node.js\";\nimport { transformFigmaResponse } from \"./figma-transformer.js\";\n\n/**\n * Extract fileKey from fixture path.\n * - fixtures/name/data.json → name (directory-based fixture)\n * - fixtures/name.json → name (legacy flat fixture)\n */\nfunction extractFileKey(filePath: string): string {\n const fileName = basename(filePath, \".json\");\n if (fileName === \"data\") {\n // Directory-based fixture: use parent directory name\n return basename(dirname(filePath));\n }\n return fileName;\n}\n\n/**\n * Load Figma data from a JSON file\n * For MVP testing and fixture support\n */\nexport async function loadFigmaFileFromJson(\n filePath: string\n): Promise<AnalysisFile> {\n const content = await readFile(filePath, \"utf-8\");\n const data = JSON.parse(content) as GetFileResponse & {\n componentDefinitions?: Record<string, unknown>;\n interactionDestinations?: Record<string, unknown>;\n };\n\n const fileKey = extractFileKey(filePath);\n\n const file = transformFigmaResponse(fileKey, data);\n\n // Preserve componentDefinitions from previously-saved fixtures\n if (data.componentDefinitions) {\n const parsed: Record<string, AnalysisNode> = {};\n for (const [id, raw] of Object.entries(data.componentDefinitions)) {\n const result = AnalysisNodeSchema.safeParse(raw);\n if (result.success) {\n parsed[id] = result.data;\n } else {\n console.debug(`[figma-file-loader] componentDefinitions[${id}] failed validation:`, result.error.issues);\n }\n }\n if (Object.keys(parsed).length > 0) {\n file.componentDefinitions = parsed;\n }\n }\n\n // Preserve interactionDestinations from previously-saved fixtures\n if (data.interactionDestinations) {\n const parsed: Record<string, AnalysisNode> = {};\n for (const [id, raw] of Object.entries(data.interactionDestinations)) {\n const result = AnalysisNodeSchema.safeParse(raw);\n if (result.success) {\n parsed[id] = result.data;\n } else {\n console.debug(`[figma-file-loader] interactionDestinations[${id}] failed validation:`, result.error.issues);\n }\n }\n if (Object.keys(parsed).length > 0) {\n file.interactionDestinations = parsed;\n }\n }\n\n return file;\n}\n\n/**\n * Parse Figma data from a JSON string\n */\nexport function parseFigmaJson(\n json: string,\n fileKey: string\n): AnalysisFile {\n const data = JSON.parse(json) as GetFileResponse;\n return transformFigmaResponse(fileKey, data);\n}\n\nexport class FigmaFileLoadError extends Error {\n constructor(message: string, public filePath?: string) {\n super(message);\n this.name = \"FigmaFileLoadError\";\n }\n}\n","import { z } from \"zod\";\n\nexport const FigmaUrlInfoSchema = z.object({\n fileKey: z.string(),\n nodeId: z.string().optional(),\n fileName: z.string().optional(),\n});\n\nexport type FigmaUrlInfo = z.infer<typeof FigmaUrlInfoSchema>;\n\nconst FIGMA_URL_PATTERNS = [\n // https://www.figma.com/design/FILE_KEY/FILE_NAME?node-id=NODE_ID\n /figma\\.com\\/design\\/([a-zA-Z0-9]+)(?:\\/([^?]+))?(?:\\?.*node-id=([^&]+))?/,\n // https://www.figma.com/file/FILE_KEY/FILE_NAME?node-id=NODE_ID\n /figma\\.com\\/file\\/([a-zA-Z0-9]+)(?:\\/([^?]+))?(?:\\?.*node-id=([^&]+))?/,\n // https://www.figma.com/proto/FILE_KEY/FILE_NAME?node-id=NODE_ID\n /figma\\.com\\/proto\\/([a-zA-Z0-9]+)(?:\\/([^?]+))?(?:\\?.*node-id=([^&]+))?/,\n];\n\nexport function parseFigmaUrl(url: string): FigmaUrlInfo {\n for (const pattern of FIGMA_URL_PATTERNS) {\n const match = url.match(pattern);\n if (match) {\n const [, fileKey, fileName, nodeId] = match;\n if (!fileKey) {\n throw new FigmaUrlParseError(`Invalid Figma URL: missing file key`);\n }\n return {\n fileKey,\n fileName: fileName ? decodeURIComponent(fileName) : undefined,\n nodeId: nodeId ? decodeURIComponent(nodeId) : undefined,\n };\n }\n }\n\n throw new FigmaUrlParseError(\n `Invalid Figma URL format. Expected: https://www.figma.com/design/FILE_KEY/...`\n );\n}\n\nexport class FigmaUrlParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"FigmaUrlParseError\";\n }\n}\n\n/**\n * Extract the commentable node ID from a potentially nested instance path.\n * Instance-internal IDs like \"I3010:7457;1442:7704\" use semicolons to\n * separate path segments. The Figma Comments API only accepts simple IDs\n * (e.g. \"3010:7457\"), so we take the first segment and strip the \"I\" prefix.\n */\nexport function toCommentableNodeId(nodeId: string): string {\n const firstSegment = nodeId.split(\";\")[0]!;\n return firstSegment.replace(/^I/, \"\");\n}\n\nexport function buildFigmaDeepLink(fileKey: string, nodeId: string): string {\n // Strip instance-internal path to top-level node:\n // \"I175:7425;1442:7704\" → \"175:7425\" → \"175-7425\"\n const topNodeId = toCommentableNodeId(nodeId).replace(/:/g, \"-\");\n return `https://www.figma.com/design/${fileKey}?node-id=${topNodeId}`;\n}\n","import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { randomUUID } from \"node:crypto\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nconst AIREADY_DIR = join(homedir(), \".canicode\");\nconst CONFIG_PATH = join(AIREADY_DIR, \"config.json\");\nconst REPORTS_DIR = join(AIREADY_DIR, \"reports\");\n\ninterface AireadyConfig {\n figmaToken?: string;\n telemetry?: boolean;\n posthogApiKey?: string;\n sentryDsn?: string;\n deviceId?: string;\n}\n\nfunction hardenPermissions(path: string, mode: number): void {\n if (process.platform !== \"win32\") {\n chmodSync(path, mode);\n }\n}\n\nfunction ensureDir(dir: string): void {\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n hardenPermissions(dir, 0o700);\n}\n\nexport function readConfig(): AireadyConfig {\n if (!existsSync(CONFIG_PATH)) {\n return {};\n }\n try {\n const raw = readFileSync(CONFIG_PATH, \"utf-8\");\n return JSON.parse(raw) as AireadyConfig;\n } catch {\n return {};\n }\n}\n\nexport function writeConfig(config: AireadyConfig): void {\n ensureDir(AIREADY_DIR);\n writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + \"\\n\", {\n encoding: \"utf-8\",\n mode: 0o600,\n });\n hardenPermissions(CONFIG_PATH, 0o600);\n}\n\nexport function getFigmaToken(): string | undefined {\n // Priority: env var > config file\n return process.env[\"FIGMA_TOKEN\"] ?? readConfig().figmaToken;\n}\n\nexport function setFigmaToken(token: string): void {\n const config = readConfig();\n config.figmaToken = token;\n writeConfig(config);\n}\n\nexport function hasConfig(): boolean {\n return existsSync(CONFIG_PATH);\n}\n\nexport function getConfigPath(): string {\n return CONFIG_PATH;\n}\n\nexport function getReportsDir(): string {\n return REPORTS_DIR;\n}\n\nexport function ensureReportsDir(): void {\n ensureDir(AIREADY_DIR);\n ensureDir(REPORTS_DIR);\n}\n\nexport function getTelemetryEnabled(): boolean {\n return readConfig().telemetry !== false;\n}\n\nexport function setTelemetryEnabled(enabled: boolean): void {\n const config = readConfig();\n config.telemetry = enabled;\n writeConfig(config);\n}\n\nexport function getPosthogApiKey(): string | undefined {\n return process.env[\"POSTHOG_API_KEY\"] ?? readConfig().posthogApiKey;\n}\n\nexport function getSentryDsn(): string | undefined {\n return process.env[\"SENTRY_DSN\"] ?? readConfig().sentryDsn;\n}\n\n/**\n * Get or create a stable anonymous device ID for telemetry.\n * Stored in ~/.canicode/config.json, persists across sessions.\n */\nexport function getDeviceId(): string {\n const config = readConfig();\n if (config.deviceId) return config.deviceId;\n\n const id = randomUUID();\n config.deviceId = id;\n writeConfig(config);\n return id;\n}\n\n/**\n * Initialize canicode: write config + create reports dir\n */\nexport function initAiready(token: string): void {\n setFigmaToken(token);\n ensureReportsDir();\n}\n","import { existsSync, statSync } from \"node:fs\";\nimport { resolve, join } from \"node:path\";\nimport { FigmaClient } from \"../adapters/figma-client.js\";\nimport { resolveComponentDefinitions, resolveInteractionDestinations } from \"../adapters/component-resolver.js\";\nimport { loadFigmaFileFromJson } from \"../adapters/figma-file-loader.js\";\nimport { transformFigmaResponse, transformFileNodesResponse } from \"../adapters/figma-transformer.js\";\nimport { parseFigmaUrl } from \"../adapters/figma-url-parser.js\";\nimport { getFigmaToken } from \"./config-store.js\";\nimport type { AnalysisFile } from \"../contracts/figma-node.js\";\n\nexport interface LoadResult {\n file: AnalysisFile;\n nodeId?: string | undefined;\n}\n\n/** Check if input string is a Figma URL. */\nexport function isFigmaUrl(input: string): boolean {\n return input.includes(\"figma.com/\");\n}\n\n/** Check if input string is a JSON file path. */\nexport function isJsonFile(input: string): boolean {\n return input.endsWith(\".json\");\n}\n\n/**\n * Check if input is a fixture directory (contains data.json).\n */\nexport function isFixtureDir(input: string): boolean {\n const resolved = resolve(input);\n if (!existsSync(resolved)) return false;\n try {\n if (!statSync(resolved).isDirectory()) return false;\n } catch {\n return false;\n }\n return existsSync(join(resolved, \"data.json\"));\n}\n\n/**\n * Resolve fixture input to data.json path.\n * Input: fixtures/name/ or fixtures/name → fixtures/name/data.json\n */\nexport function resolveFixturePath(input: string): string {\n if (isJsonFile(input)) return resolve(input);\n return resolve(join(input, \"data.json\"));\n}\n\n/**\n * Load a Figma file from a URL, JSON file, or fixture directory.\n * Resolves component master node trees for accurate analysis.\n */\nexport async function loadFile(\n input: string,\n token?: string,\n): Promise<LoadResult> {\n if (isJsonFile(input) || isFixtureDir(input)) {\n const filePath = resolveFixturePath(input);\n if (!existsSync(filePath)) {\n throw new Error(`File not found: ${filePath}`);\n }\n console.error(`Loading from JSON: ${filePath}`);\n return { file: await loadFigmaFileFromJson(filePath) };\n }\n\n if (isFigmaUrl(input)) {\n const { fileKey, nodeId } = parseFigmaUrl(input);\n return loadFromApi(fileKey, nodeId, token);\n }\n\n throw new Error(\n `Invalid input: ${input}. Provide a Figma URL or fixture directory path.`\n );\n}\n\nasync function loadFromApi(\n fileKey: string,\n nodeId: string | undefined,\n token?: string\n): Promise<LoadResult> {\n console.error(`Fetching from Figma REST API: ${fileKey}`);\n if (nodeId) {\n console.error(`Target node: ${nodeId}`);\n }\n\n const figmaToken = token ?? getFigmaToken();\n if (!figmaToken) {\n throw new Error(\n \"Figma token required. Run 'canicode init --token YOUR_TOKEN' or set FIGMA_TOKEN env var.\"\n );\n }\n\n const client = new FigmaClient({ token: figmaToken });\n\n if (nodeId) {\n // Fetch only the target node subtree — faster, less rate limit impact\n const response = await client.getFileNodes(fileKey, [nodeId.replace(/-/g, \":\")]);\n const file = transformFileNodesResponse(fileKey, response);\n\n // Resolve component master node trees for accurate analysis\n const componentDefs = await resolveComponentDefinitions(client, fileKey, file.document);\n if (Object.keys(componentDefs).length > 0) {\n file.componentDefinitions = componentDefs;\n }\n\n // Resolve interaction destination nodes (e.g., hover variants)\n const interactionDests = await resolveInteractionDestinations(client, fileKey, file.document, file.componentDefinitions);\n if (Object.keys(interactionDests).length > 0) {\n file.interactionDestinations = interactionDests;\n }\n\n return { file, nodeId };\n }\n\n const response = await client.getFile(fileKey);\n const file = transformFigmaResponse(fileKey, response);\n\n // Full file fetch may still miss component masters from external libraries\n const componentDefs = await resolveComponentDefinitions(client, fileKey, file.document);\n if (Object.keys(componentDefs).length > 0) {\n file.componentDefinitions = componentDefs;\n }\n\n // Resolve interaction destination nodes (e.g., hover variants)\n const interactionDests = await resolveInteractionDestinations(client, fileKey, file.document, file.componentDefinitions);\n if (Object.keys(interactionDests).length > 0) {\n file.interactionDestinations = interactionDests;\n }\n\n return { file, nodeId };\n}\n","{\n \"name\": \"canicode\",\n \"version\": \"0.9.0\",\n \"mcpName\": \"io.github.let-sunny/canicode\",\n \"description\": \"Score your Figma designs with AI-calibrated rules. CLI + MCP server.\",\n \"type\": \"module\",\n \"main\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"bin\": {\n \"canicode\": \"dist/cli/index.js\",\n \"canicode-mcp\": \"dist/mcp/server.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\"\n }\n },\n \"scripts\": {\n \"build\": \"tsup --config tsup.config.ts\",\n \"build:web\": \"bash scripts/build-web.sh\",\n \"dev\": \"tsup --watch\",\n \"test\": \"vitest\",\n \"test:run\": \"vitest run\",\n \"lint\": \"tsc --noEmit\",\n \"build:plugin\": \"bash scripts/build-plugin.sh\",\n \"sync-docs\": \"tsx scripts/sync-rule-docs.ts\",\n \"clean\": \"rm -rf dist\"\n },\n \"files\": [\n \"dist\",\n \"docs/CUSTOMIZATION.md\",\n \".claude/skills/design-to-code/PROMPT.md\"\n ],\n \"keywords\": [\n \"figma\",\n \"design\",\n \"analysis\",\n \"cli\",\n \"mcp\",\n \"readiness\",\n \"ai\"\n ],\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/let-sunny/canicode.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/let-sunny/canicode/issues\"\n },\n \"homepage\": \"https://github.com/let-sunny/canicode\",\n \"author\": \"minseon\",\n \"license\": \"MIT\",\n \"pnpm\": {\n \"overrides\": {\n \"picomatch\": \"4.0.4\",\n \"path-to-regexp\": \"8.4.0\"\n }\n },\n \"packageManager\": \"pnpm@10.32.1\",\n \"engines\": {\n \"node\": \">=22\"\n },\n \"dependencies\": {\n \"@figma/rest-api-spec\": \"^0.36.0\",\n \"@modelcontextprotocol/sdk\": \"^1.27.1\",\n \"cac\": \"^7.0.0\",\n \"dotenv\": \"^17.3.1\",\n \"pixelmatch\": \"^7.1.0\",\n \"pngjs\": \"^7.0.0\",\n \"zod\": \"^4.3.6\"\n },\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.80.0\",\n \"@figma/plugin-typings\": \"^1.123.0\",\n \"@types/node\": \"^25.5.0\",\n \"@types/pngjs\": \"^6.0.5\",\n \"playwright\": \"^1.58.2\",\n \"tsup\": \"^8.5.1\",\n \"tsx\": \"^4.19.0\",\n \"typescript\": \"^5.9.3\",\n \"vitest\": \"^4.1.0\"\n }\n}\n","import type { Category } from \"../contracts/category.js\";\nimport { CATEGORIES, CATEGORY_LABELS } from \"../contracts/category.js\";\nimport type { RuleId, RuleConfig } from \"../contracts/rule.js\";\nimport type { Severity } from \"../contracts/severity.js\";\nimport type { AnalysisResult } from \"./rule-engine.js\";\nimport { RULE_CONFIGS, RULE_ID_CATEGORY } from \"../rules/rule-config.js\";\nimport { version as VERSION } from \"../../../package.json\";\n\n/**\n * Score breakdown for a single category\n */\nexport interface CategoryScoreResult {\n category: Category;\n score: number;\n maxScore: number;\n percentage: number;\n issueCount: number;\n uniqueRuleCount: number;\n weightedIssueCount: number;\n densityScore: number;\n diversityScore: number;\n bySeverity: Record<Severity, number>;\n}\n\n/**\n * Overall score report\n */\nexport interface ScoreReport {\n overall: {\n score: number;\n maxScore: number;\n percentage: number;\n grade: Grade;\n };\n byCategory: Record<Category, CategoryScoreResult>;\n summary: {\n totalIssues: number;\n blocking: number;\n risk: number;\n missingInfo: number;\n suggestion: number;\n nodeCount: number;\n };\n}\n\n/**\n * Grade levels based on percentage\n */\nexport type Grade = \"S\" | \"A+\" | \"A\" | \"B+\" | \"B\" | \"C+\" | \"C\" | \"D\" | \"F\";\n\n/**\n * Density weighting uses per-rule base |score| with sqrt damping (#226).\n *\n * Previously, each issue's |calculatedScore| was summed linearly — a rule\n * triggering N times contributed N× its score. This over-penalized designs\n * with many instances of the same issue (e.g., raw-value ×79 = -316 weight),\n * causing most real files to score Grade D/F with no differentiation.\n *\n * Now: same rule triggered N times contributes |score| × sqrt(N).\n * raw-value ×79 = 4 × sqrt(79) ≈ 36 instead of 316.\n * At low counts sqrt ≈ linear (sqrt(1)=1, sqrt(4)=2), preserving sensitivity.\n * At high counts the curve flattens — 79th occurrence adds ~0.2 vs 1st adding 4.\n *\n * Category weights removed (#196) — overall score is simple average of categories.\n * Category importance is already encoded in rule scores (pixel-critical -10\n * vs semantic -4), so per-category weighting is unnecessary.\n */\n\n/**\n * Compute sum of |score| for all rules in each category from a given config map.\n * Used as denominator for severity-weighted diversity scoring.\n * Must use the same preset-adjusted config map that produced the analysis issues,\n * otherwise diversity ratios will be incorrect.\n */\nfunction computeTotalScorePerCategory(\n configs: Record<RuleId, RuleConfig>\n): Record<Category, number> {\n const totals = Object.fromEntries(\n CATEGORIES.map(c => [c, 0])\n ) as Record<Category, number>;\n\n for (const [id, config] of Object.entries(configs)) {\n const category = RULE_ID_CATEGORY[id as RuleId];\n if (category && config.enabled) {\n totals[category] += Math.abs(config.score);\n }\n }\n\n return totals;\n}\n\n/**\n * Score composition weights (initial intuition, pending calibration validation).\n *\n * Density (0.7): \"how many issues per node\" — measures issue volume relative to design size.\n * Designs with many issues per node are harder to implement accurately.\n *\n * Diversity (0.3): \"how many different rule types triggered\" — measures issue breadth.\n * A design that triggers 1 rule 50 times is easier to fix than one triggering 10 different rules.\n *\n * The 70:30 ratio prioritizes volume over variety. Rationale: a design with a single\n * systemic problem (e.g., all frames missing auto-layout) is still very hard to implement,\n * even though diversity is low. Density captures this; diversity adds a penalty for\n * designs with scattered, unrelated issues.\n *\n * Status: initial values. To be validated via /calibrate-loop against visual-compare results.\n */\nconst DENSITY_WEIGHT = 0.7;\nconst DIVERSITY_WEIGHT = 0.3;\n\n/**\n * Minimum score floor.\n * Even the worst design gets 5% instead of 0%. Rationale: a score of 0 implies\n * \"completely unimplementable\", but any Figma file with visible nodes provides\n * some structural information. The floor also avoids demoralizing UX — seeing 0%\n * feels like the tool failed, not that the design needs improvement.\n */\nconst SCORE_FLOOR = 5;\n\n/**\n * Calculate grade from percentage.\n * Thresholds follow a 5-point interval pattern (95/90/85/80/75/70/65) with a wider\n * gap for D (50-64) and F (<50). This mirrors academic grading conventions where\n * the top tiers are tightly spaced and the failing range is broad.\n */\nfunction calculateGrade(percentage: number): Grade {\n if (percentage >= 95) return \"S\";\n if (percentage >= 90) return \"A+\";\n if (percentage >= 85) return \"A\";\n if (percentage >= 80) return \"B+\";\n if (percentage >= 75) return \"B\";\n if (percentage >= 70) return \"C+\";\n if (percentage >= 65) return \"C\";\n if (percentage >= 50) return \"D\";\n return \"F\";\n}\n\n/**\n * Convert grade to a CSS-safe class name suffix\n * e.g. \"A+\" -> \"Aplus\", \"B+\" -> \"Bplus\", \"C+\" -> \"Cplus\"\n */\nexport function gradeToClassName(grade: Grade): string {\n return grade.replace(\"+\", \"plus\");\n}\n\n/**\n * Clamp a value between min and max\n */\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * Calculate scores from analysis result using density + diversity scoring\n *\n * Density Score = 100 - (weighted issue count / node count) * 100\n * Diversity Score = (1 - weighted triggered rule scores / total category scores) * 100\n * Final Score = density * 0.7 + diversity * 0.3\n *\n * @param result Analysis result with issues\n * @param configs Optional preset-adjusted config map used to produce the issues.\n * If not provided, diversity totals are reconstructed from issue.config values.\n */\nexport function calculateScores(\n result: AnalysisResult,\n configs?: Record<RuleId, RuleConfig>\n): ScoreReport {\n const categoryScores = initializeCategoryScores();\n const nodeCount = result.nodeCount;\n\n // Track unique rules and their base |score| per category\n const uniqueRulesPerCategory = new Map<Category, Set<string>>();\n const ruleScorePerCategory = new Map<Category, Map<string, number>>();\n // Track issue counts per rule per category for sqrt damping (#226)\n const ruleIssueCountPerCategory = new Map<Category, Map<string, number>>();\n for (const category of CATEGORIES) {\n uniqueRulesPerCategory.set(category, new Set());\n ruleScorePerCategory.set(category, new Map());\n ruleIssueCountPerCategory.set(category, new Map());\n }\n\n // Compute totals from the config map.\n // If configs provided: use preset-adjusted totals (recommended when using presets).\n // If not: fall back to static RULE_CONFIGS — only correct when issues were\n // produced with default RULE_CONFIGS, otherwise diversity ratios will be skewed.\n const totalScorePerCategory = computeTotalScorePerCategory(configs ?? RULE_CONFIGS);\n\n // Count issues by severity per category and track unique rules with scores\n for (const issue of result.issues) {\n const category = issue.rule.definition.category;\n const severity = issue.config.severity;\n const ruleId = issue.rule.definition.id;\n\n categoryScores[category].issueCount++;\n categoryScores[category].bySeverity[severity]++;\n uniqueRulesPerCategory.get(category)!.add(ruleId);\n ruleScorePerCategory.get(category)!.set(ruleId, Math.abs(issue.config.score));\n // Accumulate per-rule issue count (using |calculatedScore| as weight unit)\n const ruleCountMap = ruleIssueCountPerCategory.get(category)!;\n ruleCountMap.set(ruleId, (ruleCountMap.get(ruleId) ?? 0) + 1);\n }\n\n // Compute weightedIssueCount with sqrt damping per rule (#226).\n // Same rule triggered N times contributes |score| × sqrt(N) instead of |score| × N.\n // Rationale: 79 raw-value issues represent one systemic problem, not 79× the difficulty.\n // First few occurrences identify the problem; subsequent ones have diminishing impact.\n // At low counts sqrt ≈ linear (sqrt(1)=1, sqrt(4)=2), preserving sensitivity for rare issues.\n for (const category of CATEGORIES) {\n const ruleCountMap = ruleIssueCountPerCategory.get(category)!;\n const ruleScoreMap = ruleScorePerCategory.get(category)!;\n let dampedWeight = 0;\n for (const [ruleId, count] of ruleCountMap) {\n const ruleScore = ruleScoreMap.get(ruleId) ?? 0;\n dampedWeight += ruleScore * Math.sqrt(count);\n }\n categoryScores[category].weightedIssueCount = dampedWeight;\n }\n\n // Calculate percentage for each category based on density + diversity\n for (const category of CATEGORIES) {\n const catScore = categoryScores[category];\n const uniqueRules = uniqueRulesPerCategory.get(category)!;\n\n catScore.uniqueRuleCount = uniqueRules.size;\n\n // Density score: lower density = higher score\n let densityScore = 100;\n if (nodeCount > 0 && catScore.issueCount > 0) {\n const density = catScore.weightedIssueCount / nodeCount;\n densityScore = clamp(Math.round(100 - density * 100), 0, 100);\n }\n catScore.densityScore = densityScore;\n\n // Diversity score: weighted by base rule |score| (config.score, not calculatedScore).\n // Uses base score intentionally — diversity measures \"what types of problems exist\",\n // not \"where they occur\". depthWeight affects density (volume penalty) but not diversity\n // (breadth penalty). A blocking rule (score -10) penalizes diversity more than a\n // suggestion (score -1), so low-severity-only designs correctly get high diversity scores.\n let diversityScore = 100;\n if (catScore.issueCount > 0) {\n const ruleScores = ruleScorePerCategory.get(category)!;\n const weightedTriggered = Array.from(ruleScores.values()).reduce((sum, s) => sum + s, 0);\n const weightedTotal = totalScorePerCategory[category];\n const diversityRatio = weightedTotal > 0 ? weightedTriggered / weightedTotal : 0;\n diversityScore = clamp(Math.round((1 - diversityRatio) * 100), 0, 100);\n }\n catScore.diversityScore = diversityScore;\n\n // Combined score with floor\n const combinedScore = densityScore * DENSITY_WEIGHT + diversityScore * DIVERSITY_WEIGHT;\n catScore.percentage = catScore.issueCount > 0\n ? clamp(Math.round(combinedScore), SCORE_FLOOR, 100)\n : 100;\n\n catScore.score = catScore.percentage;\n catScore.maxScore = 100;\n }\n\n // Calculate overall score as simple average of categories\n // Category importance is already encoded in rule scores (weight baked in),\n // so no per-category weighting is needed.\n let categorySum = 0;\n for (const category of CATEGORIES) {\n categorySum += categoryScores[category].percentage;\n }\n\n const overallPercentage = CATEGORIES.length > 0\n ? Math.round(categorySum / CATEGORIES.length)\n : 100;\n\n // Count issues by severity\n const summary = {\n totalIssues: result.issues.length,\n blocking: 0,\n risk: 0,\n missingInfo: 0,\n suggestion: 0,\n nodeCount,\n };\n\n for (const issue of result.issues) {\n switch (issue.config.severity) {\n case \"blocking\":\n summary.blocking++;\n break;\n case \"risk\":\n summary.risk++;\n break;\n case \"missing-info\":\n summary.missingInfo++;\n break;\n case \"suggestion\":\n summary.suggestion++;\n break;\n }\n }\n\n return {\n overall: {\n score: overallPercentage,\n maxScore: 100,\n percentage: overallPercentage,\n grade: calculateGrade(overallPercentage),\n },\n byCategory: categoryScores,\n summary,\n };\n}\n\n/**\n * Initialize empty category scores\n */\nfunction initializeCategoryScores(): Record<Category, CategoryScoreResult> {\n const scores: Partial<Record<Category, CategoryScoreResult>> = {};\n\n for (const category of CATEGORIES) {\n scores[category] = {\n category,\n score: 100,\n maxScore: 100,\n percentage: 100,\n issueCount: 0,\n uniqueRuleCount: 0,\n weightedIssueCount: 0,\n densityScore: 100,\n diversityScore: 100,\n bySeverity: {\n blocking: 0,\n risk: 0,\n \"missing-info\": 0,\n suggestion: 0,\n },\n };\n }\n\n return scores as Record<Category, CategoryScoreResult>;\n}\n\n/**\n * Format score report as a summary string\n */\nexport function formatScoreSummary(report: ScoreReport): string {\n const lines: string[] = [];\n\n lines.push(`Overall: ${report.overall.grade} (${report.overall.percentage}%)`);\n lines.push(\"\");\n lines.push(\"By Category:\");\n\n for (const category of CATEGORIES) {\n const cat = report.byCategory[category];\n lines.push(` ${category}: ${cat.percentage}% (${cat.issueCount} issues, ${cat.uniqueRuleCount} rules)`);\n }\n\n lines.push(\"\");\n lines.push(\"Issues:\");\n lines.push(` Blocking: ${report.summary.blocking}`);\n lines.push(` Risk: ${report.summary.risk}`);\n lines.push(` Missing Info: ${report.summary.missingInfo}`);\n lines.push(` Suggestion: ${report.summary.suggestion}`);\n lines.push(` Total: ${report.summary.totalIssues}`);\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Get category label for display\n */\nexport function getCategoryLabel(category: Category): string {\n return CATEGORY_LABELS[category];\n}\n\n/**\n * Get severity label for display\n */\nexport function getSeverityLabel(severity: Severity): string {\n const labels: Record<Severity, string> = {\n blocking: \"Blocking\",\n risk: \"Risk\",\n \"missing-info\": \"Missing Info\",\n suggestion: \"Suggestion\",\n };\n return labels[severity];\n}\n\n/**\n * Build a JSON-serializable analysis result summary.\n * Shared by CLI (--json) and MCP server (analyze tool response).\n */\nexport function buildResultJson(\n fileName: string,\n result: AnalysisResult,\n scores: ScoreReport,\n options?: { fileKey?: string },\n): Record<string, unknown> {\n const issuesByRule: Record<string, number> = {};\n for (const issue of result.issues) {\n const id = issue.violation.ruleId;\n issuesByRule[id] = (issuesByRule[id] ?? 0) + 1;\n }\n\n const issues = result.issues.map((issue) => ({\n ruleId: issue.violation.ruleId,\n ...(issue.violation.subType && { subType: issue.violation.subType }),\n severity: issue.config.severity,\n nodeId: issue.violation.nodeId,\n nodePath: issue.violation.nodePath,\n message: issue.violation.message,\n }));\n\n const json: Record<string, unknown> = {\n version: VERSION,\n analyzedAt: result.analyzedAt,\n ...(options?.fileKey && { fileKey: options.fileKey }),\n fileName,\n nodeCount: result.nodeCount,\n maxDepth: result.maxDepth,\n issueCount: result.issues.length,\n scores: {\n overall: scores.overall,\n categories: scores.byCategory,\n },\n issuesByRule,\n issues,\n summary: formatScoreSummary(scores),\n };\n\n if (result.failedRules.length > 0) {\n json[\"failedRules\"] = result.failedRules;\n }\n\n return json;\n}","// Shared UI constants — single source of truth for report-html (Node) and app/shared (browser)\n\nimport type { Category } from \"./contracts/category.js\";\nimport type { Severity } from \"./contracts/severity.js\";\n\n// Re-export category/severity constants that already exist\nexport { CATEGORIES, CATEGORY_LABELS } from \"./contracts/category.js\";\nexport { SEVERITY_LABELS } from \"./contracts/severity.js\";\n\n// Gauge geometry\nexport const GAUGE_R = 54;\nexport const GAUGE_C = Math.round(2 * Math.PI * GAUGE_R); // ~339\n\nexport const CATEGORY_DESCRIPTIONS: Record<Category, string> = {\n \"pixel-critical\":\n \"Auto Layout, absolute positioning, group usage — layout issues that directly affect pixel accuracy\",\n \"responsive-critical\":\n \"Fixed sizing, size constraints, responsive behavior — issues that break at different viewports\",\n \"code-quality\":\n \"Component reuse, detached instances, variant structure, nesting depth\",\n \"token-management\":\n \"Design token binding for colors, fonts, shadows, opacity, spacing grid\",\n \"interaction\":\n \"State variants for interactive components — hover, disabled, active, focus\",\n \"semantic\":\n \"Semantic layer names, naming conventions, default names\",\n};\n\nexport const SEVERITY_ORDER: Severity[] = [\n \"blocking\",\n \"risk\",\n \"missing-info\",\n \"suggestion\",\n];\n","// Shared UI helper functions — single source of truth for report-html (Node) and app/shared (browser)\n// All functions here must be pure (no Node.js or DOM dependencies)\n\nimport type { Severity } from \"./contracts/severity.js\";\nimport { GAUGE_R, GAUGE_C } from \"./ui-constants.js\";\n\n/** Map a percentage score to a color hex string */\nexport function gaugeColor(pct: number): string {\n if (pct >= 75) return \"#22c55e\";\n if (pct >= 50) return \"#f59e0b\";\n return \"#ef4444\";\n}\n\n/** Map a percentage score to a color class name (green/amber/red) */\nexport function scoreClass(pct: number): string {\n if (pct >= 75) return \"green\";\n if (pct >= 50) return \"amber\";\n return \"red\";\n}\n\n/** Escape HTML special characters — works in both Node.js and browser */\nexport function escapeHtml(text: string): string {\n return text\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#039;\");\n}\n\n\n/** Severity to CSS modifier class (used with .rpt-dot, .rpt-issue-score) */\nexport function severityDot(sev: Severity): string {\n const map: Record<Severity, string> = {\n blocking: \"sev-blocking\",\n risk: \"sev-risk\",\n \"missing-info\": \"sev-missing\",\n suggestion: \"sev-suggestion\",\n };\n return map[sev];\n}\n\n/** Severity to CSS modifier class (used with .rpt-issue-score) */\nexport function severityBadge(sev: Severity): string {\n const map: Record<Severity, string> = {\n blocking: \"sev-blocking\",\n risk: \"sev-risk\",\n \"missing-info\": \"sev-missing\",\n suggestion: \"sev-suggestion\",\n };\n return map[sev];\n}\n\n/** Score percentage to CSS modifier class (used with .rpt-badge) */\nexport function scoreBadgeStyle(pct: number): string {\n if (pct >= 75) return \"score-green\";\n if (pct >= 50) return \"score-amber\";\n return \"score-red\";\n}\n\n/** Render a circular gauge SVG string — works in both Node.js and browser */\nexport function renderGaugeSvg(\n pct: number,\n size: number,\n strokeW: number,\n grade?: string\n): string {\n const offset = GAUGE_C * (1 - pct / 100);\n const color = gaugeColor(pct);\n if (grade) {\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 120 120\" class=\"gauge-svg\">\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke-width=\"${strokeW}\" stroke=\"#e4e4e7\" />\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"${strokeW}\" stroke-linecap=\"round\" stroke-dasharray=\"${GAUGE_C}\" stroke-dashoffset=\"${offset}\" transform=\"rotate(-90 60 60)\" class=\"gauge-fill\" />\n <text x=\"60\" y=\"60\" text-anchor=\"middle\" dominant-baseline=\"central\" fill=\"currentColor\" font-size=\"48\" font-weight=\"700\" font-family=\"Inter,-apple-system,sans-serif\">${escapeHtml(grade)}</text>\n </svg>`;\n }\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 120 120\" class=\"gauge-svg\">\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke-width=\"${strokeW}\" stroke=\"#e4e4e7\" />\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"${strokeW}\" stroke-linecap=\"round\" stroke-dasharray=\"${GAUGE_C}\" stroke-dashoffset=\"${offset}\" transform=\"rotate(-90 60 60)\" class=\"gauge-fill\" />\n <text x=\"60\" y=\"62\" text-anchor=\"middle\" dominant-baseline=\"central\" fill=\"currentColor\" font-size=\"28\" font-weight=\"700\" font-family=\"Inter,-apple-system,sans-serif\">${pct}</text>\n </svg>`;\n}\n","/**\n * Pure template functions for report HTML rendering.\n * No Node.js dependencies — usable in browser via CanICode.* globals.\n *\n * Single source of truth for all report UI:\n * - CLI: generateHtmlReport() wraps with <html> shell\n * - Web app: CanICode.renderReportBody() → innerHTML\n * - Figma plugin: CanICode.renderReportBody() → innerHTML\n *\n * Layout: category tabs → rule sections (static info) → node accordion (dynamic info)\n * Styled via self-contained CSS (app/shared/styles.css) — no Tailwind dependency.\n */\n\nimport type { Category } from \"../contracts/category.js\";\nimport type { AnalysisIssue } from \"../engine/rule-engine.js\";\nimport type { ScoreReport } from \"../engine/scoring.js\";\nimport { version as VERSION } from \"../../../package.json\";\nimport { buildFigmaDeepLink } from \"../adapters/figma-url-parser.js\";\nimport {\n CATEGORIES,\n CATEGORY_LABELS,\n} from \"../ui-constants.js\";\nimport {\n escapeHtml,\n severityDot,\n severityBadge,\n renderGaugeSvg,\n} from \"../ui-helpers.js\";\n\n// ---- Data interface ----\n\nexport interface ReportData {\n fileName: string;\n fileKey: string;\n scores: ScoreReport;\n issues: AnalysisIssue[];\n nodeCount: number;\n maxDepth: number;\n figmaToken?: string;\n}\n\n/** Issues grouped by rule within a category */\ninterface RuleGroup {\n ruleId: string;\n ruleName: string;\n severity: string;\n severityClass: string;\n why: string;\n impact: string;\n fix: string;\n issues: AnalysisIssue[];\n totalScore: number;\n}\n\n// ---- Main render ----\n\n/**\n * Render the report body content (everything inside <main>).\n * Does NOT include <html>, <head>, <body> — caller wraps as needed.\n */\nexport function renderReportBody(data: ReportData): string {\n const { scores, issues, fileKey, figmaToken } = data;\n const issuesByCategory = groupIssuesByCategory(issues);\n const ruleOpportunities = getTopRules(issues, 5);\n\n return `\n <!-- Overall Score -->\n <section class=\"rpt-overall\">\n ${renderGaugeSvg(scores.overall.percentage, 200, 10, scores.overall.grade)}\n <div class=\"rpt-score\">\n <span class=\"rpt-score-value\">${scores.overall.percentage}</span>\n <span class=\"rpt-score-max\">/ 100</span>\n </div>\n <p class=\"rpt-score-label\">Overall Score</p>\n </section>\n\n <!-- Category Gauges -->\n <section class=\"card rpt-gauges\">\n <div class=\"rpt-gauges-grid\">\n${CATEGORIES.map((cat) => {\n const cs = scores.byCategory[cat];\n return ` <button type=\"button\" class=\"rpt-gauge-item\" data-tab=\"${cat}\">\n ${renderGaugeSvg(cs.percentage, 100, 7)}\n <span class=\"rpt-gauge-label\">${CATEGORY_LABELS[cat]}</span>\n <span class=\"rpt-gauge-count\">${cs.issueCount} issues</span>\n </button>`;\n }).join(\"\\n\")}\n </div>\n </section>\n\n <!-- Issue Summary -->\n <section class=\"card rpt-summary\">\n <div class=\"rpt-summary-inner\">\n ${renderSummaryDot(\"sev-blocking\", scores.summary.blocking, \"Blocking\")}\n ${renderSummaryDot(\"sev-risk\", scores.summary.risk, \"Risk\")}\n ${renderSummaryDot(\"sev-missing\", scores.summary.missingInfo, \"Missing Info\")}\n ${renderSummaryDot(\"sev-suggestion\", scores.summary.suggestion, \"Suggestion\")}\n <div class=\"rpt-summary-total\">\n <span class=\"rpt-summary-count\">${scores.summary.totalIssues}</span>\n <span class=\"rpt-summary-label\">Total</span>\n </div>\n </div>\n </section>\n\n${ruleOpportunities.length > 0 ? renderOpportunities(ruleOpportunities) : \"\"}\n\n <!-- Category Tabs -->\n <div class=\"rpt-tabs\">\n <div class=\"rpt-tab-list\" role=\"tablist\">\n${CATEGORIES.map((cat, i) => {\n const cs = scores.byCategory[cat];\n return ` <button type=\"button\" role=\"tab\" class=\"rpt-tab${i === 0 ? \" active\" : \"\"}\" data-tab=\"${cat}\" aria-selected=\"${i === 0}\">${CATEGORY_LABELS[cat]} <span class=\"rpt-tab-count\">${cs.issueCount}</span></button>`;\n }).join(\"\\n\")}\n </div>\n\n${CATEGORIES.map((cat, i) => {\n const catIssues = issuesByCategory.get(cat) ?? [];\n const ruleGroups = groupIssuesByRule(catIssues);\n return ` <div class=\"rpt-tab-panel${i === 0 ? \" active\" : \"\"}\" data-panel=\"${cat}\" role=\"tabpanel\">\n${ruleGroups.length === 0\n ? ' <div class=\"rpt-cat-empty\">No issues found</div>'\n : ruleGroups.map(rg => renderRuleSection(rg, fileKey, figmaToken)).join(\"\\n\")\n}\n </div>`;\n }).join(\"\\n\")}\n </div>\n\n <!-- Footer -->\n <footer class=\"rpt-footer\">\n <p class=\"rpt-footer-main\"><strong>CanICode</strong> <span style=\"opacity:0.5\">v${VERSION}</span></p>\n <p class=\"rpt-footer-meta\">${new Date().toLocaleString()} · ${data.nodeCount} nodes · Max depth ${data.maxDepth}</p>\n <p class=\"rpt-footer-links\"><a href=\"https://github.com/let-sunny/canicode/issues\" target=\"_blank\" rel=\"noopener\">Feedback</a> <span style=\"opacity:0.3\">&middot;</span> <a href=\"https://github.com/let-sunny/canicode/discussions/new?category=share-your-figma\" target=\"_blank\" rel=\"noopener\">Share your Figma</a></p>\n </footer>`;\n}\n\n// ---- Components ----\n\nexport function renderSummaryDot(sevClass: string, count: number, label: string): string {\n return `<div class=\"rpt-summary-item\">\n <span class=\"rpt-dot ${sevClass}\"></span>\n <span class=\"rpt-summary-count\">${count}</span>\n <span class=\"rpt-summary-label\">${label}</span>\n </div>`;\n}\n\nexport function renderOpportunities(ruleGroups: RuleGroup[]): string {\n const maxAbs = ruleGroups.reduce((m, rg) => Math.max(m, Math.abs(rg.totalScore)), 1);\n return `\n <!-- Opportunities -->\n <section class=\"card rpt-opps\">\n <div class=\"rpt-opps-header\">\n <h2 class=\"rpt-opps-title\">\n <span class=\"rpt-dot sev-blocking\"></span>\n Opportunities\n </h2>\n <p class=\"rpt-opps-desc\">Top impact rules — fix these first for the biggest improvement.</p>\n </div>\n <div class=\"rpt-opps-list\">\n${ruleGroups.map(rg => {\n const barW = Math.round((Math.abs(rg.totalScore) / maxAbs) * 100);\n const cat = rg.issues[0]?.rule.definition.category ?? \"\";\n return ` <div class=\"rpt-opps-item\" data-opp-rule=\"${esc(rg.ruleId)}\" data-opp-cat=\"${cat}\" style=\"cursor:pointer\">\n <div class=\"rpt-opps-info\">\n <div class=\"rpt-opps-name\">${esc(rg.ruleName)}</div>\n <div class=\"rpt-opps-msg\">${rg.issues.length} issues</div>\n </div>\n <div class=\"rpt-opps-bar-wrap\">\n <div class=\"rpt-opps-bar\">\n <div class=\"rpt-opps-bar-fill\" style=\"width:${barW}%\"></div>\n </div>\n <span class=\"rpt-opps-score\">${rg.totalScore}</span>\n </div>\n </div>`;\n }).join(\"\\n\")}\n </div>\n </section>`;\n}\n\nexport function renderRuleSection(\n rg: RuleGroup,\n fileKey: string,\n figmaToken?: string\n): string {\n const isOpen = rg.severity === \"blocking\" || rg.severity === \"risk\";\n return ` <details class=\"card rpt-rule\" data-rule=\"${esc(rg.ruleId)}\"${isOpen ? \" open\" : \"\"}>\n <summary class=\"rpt-rule-header\">\n <span class=\"rpt-badge score-red\">${rg.totalScore}</span>\n <span class=\"rpt-rule-title\">\n <span class=\"rpt-rule-name\">${esc(rg.ruleName)}</span>\n <span class=\"rpt-rule-meta\">\n <span class=\"rpt-dot-sm ${rg.severityClass}\"></span>\n ${esc(rg.severity)} · ${rg.issues.length} issues\n </span>\n <span class=\"rpt-rule-info\">\n <span class=\"rpt-rule-info-line\"><strong>Why:</strong> ${esc(rg.why)}</span>\n <span class=\"rpt-rule-info-line\"><strong>Impact:</strong> ${esc(rg.impact)}</span>\n <span class=\"rpt-rule-info-line\"><strong>Fix:</strong> ${esc(rg.fix)}</span>\n </span>\n </span>\n <svg class=\"rpt-rule-chevron no-print\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M19 9l-7 7-7-7\"/></svg>\n </summary>\n <div class=\"rpt-rule-issues\">\n${rg.issues.map(issue => renderIssueRow(issue, fileKey, figmaToken)).join(\"\\n\")}\n </div>\n </details>`;\n}\n\nexport function renderIssueRow(\n issue: AnalysisIssue,\n fileKey: string,\n figmaToken?: string\n): string {\n const sev = issue.config.severity;\n const v = issue.violation;\n const link = buildFigmaDeepLink(fileKey, v.nodeId);\n\n return ` <details class=\"rpt-issue\">\n <summary class=\"rpt-issue-header\">\n <span class=\"rpt-issue-msg\">${esc(v.message)}</span>\n <span class=\"rpt-issue-score ${severityBadge(sev)}\">${issue.calculatedScore}</span>\n </summary>\n <div class=\"rpt-issue-body\">\n <div class=\"rpt-issue-suggestion\">${esc(v.suggestion)}</div>${v.guide ? `\n <div class=\"rpt-issue-guide\">${esc(v.guide)}</div>` : \"\"}\n <div class=\"rpt-issue-path\">${esc(v.nodePath)}</div>\n <div class=\"rpt-issue-actions no-print\">\n <a href=\"${link}\" target=\"_blank\" rel=\"noopener\" data-node-id=\"${esc(v.nodeId)}\" class=\"rpt-btn\">Go to node <span>→</span></a>${figmaToken ? `\n <button onclick=\"postComment(this)\" data-file-key=\"${esc(fileKey)}\" data-node-id=\"${esc(v.nodeId)}\" data-message=\"${esc(v.message)} — ${esc(v.suggestion)}\" class=\"rpt-btn\">Comment on Figma</button>` : \"\"}\n </div>\n </div>\n </details>`;\n}\n\n// ---- Interactions ----\n\n/**\n * Initialize tab switching + navigation for a rendered report.\n * Call after inserting renderReportBody() HTML into a container.\n * Uses 'any' to avoid DOM type dependency (this file targets Node.js).\n */\nexport function initReportInteractions(container: any): void {\n // Remove previous handler if re-initialized (e.g., re-analysis)\n if (container._rptHandler) {\n container.removeEventListener(\"click\", container._rptHandler);\n }\n function activate(cat: string, scrollTo: boolean) {\n container.querySelectorAll(\".rpt-tab\").forEach((t: any) => {\n const active = t.dataset.tab === cat;\n t.classList.toggle(\"active\", active);\n t.setAttribute(\"aria-selected\", String(active));\n });\n container.querySelectorAll(\".rpt-tab-panel\").forEach((p: any) => {\n p.classList.toggle(\"active\", p.dataset.panel === cat);\n });\n if (scrollTo) {\n const tabList = container.querySelector(\".rpt-tab-list\");\n if (tabList) tabList.scrollIntoView({ behavior: \"smooth\", block: \"start\" });\n }\n }\n function focusRule(ruleId: string) {\n const el = container.querySelector('[data-rule=\"' + ruleId + '\"]');\n if (el) {\n el.open = true;\n setTimeout(() => el.scrollIntoView({ behavior: \"smooth\", block: \"start\" }), 50);\n }\n }\n const handler = (e: any) => {\n const tab = e.target.closest(\"[data-tab]\");\n if (tab) {\n const isGauge = tab.classList.contains(\"rpt-gauge-item\");\n activate(tab.dataset.tab ?? \"\", isGauge);\n return;\n }\n const opp = e.target.closest(\"[data-opp-rule]\");\n if (opp) {\n const cat = opp.dataset.oppCat ?? \"\";\n const rule = opp.dataset.oppRule ?? \"\";\n if (cat) activate(cat, false);\n setTimeout(() => focusRule(rule), 50);\n }\n };\n container._rptHandler = handler;\n container.addEventListener(\"click\", handler);\n}\n\n// ---- Utils ----\n\n/** Get top N rules by total score impact */\nfunction getTopRules(issues: AnalysisIssue[], limit: number): RuleGroup[] {\n const byRule = new Map<string, RuleGroup>();\n for (const issue of issues) {\n const id = issue.rule.definition.id;\n let group = byRule.get(id);\n if (!group) {\n const def = issue.rule.definition;\n group = {\n ruleId: id,\n ruleName: def.name,\n severity: issue.config.severity,\n severityClass: severityDot(issue.config.severity),\n why: def.why,\n impact: def.impact,\n fix: def.fix,\n issues: [],\n totalScore: 0,\n };\n byRule.set(id, group);\n }\n group.issues.push(issue);\n group.totalScore += issue.calculatedScore;\n }\n return [...byRule.values()]\n .sort((a, b) => a.totalScore - b.totalScore)\n .slice(0, limit);\n}\n\nfunction groupIssuesByCategory(issues: AnalysisIssue[]): Map<Category, AnalysisIssue[]> {\n const grouped = new Map<Category, AnalysisIssue[]>();\n for (const category of CATEGORIES) grouped.set(category, []);\n for (const issue of issues) grouped.get(issue.rule.definition.category)!.push(issue);\n return grouped;\n}\n\n/** Group issues by rule within a category, sorted by severity then score */\nfunction groupIssuesByRule(issues: AnalysisIssue[]): RuleGroup[] {\n const byRule = new Map<string, RuleGroup>();\n for (const issue of issues) {\n const id = issue.rule.definition.id;\n let group = byRule.get(id);\n if (!group) {\n const def = issue.rule.definition;\n group = {\n ruleId: id,\n ruleName: def.name,\n severity: issue.config.severity,\n severityClass: severityDot(issue.config.severity),\n why: def.why,\n impact: def.impact,\n fix: def.fix,\n issues: [],\n totalScore: 0,\n };\n byRule.set(id, group);\n }\n group.issues.push(issue);\n group.totalScore += issue.calculatedScore;\n }\n\n const SEVERITY_RANK: Record<string, number> = { blocking: 0, risk: 1, \"missing-info\": 2, suggestion: 3 };\n return [...byRule.values()].sort((a, b) => {\n const sevDiff = (SEVERITY_RANK[a.severity] ?? 4) - (SEVERITY_RANK[b.severity] ?? 4);\n return sevDiff !== 0 ? sevDiff : a.totalScore - b.totalScore;\n });\n}\n\nconst esc = escapeHtml;\n","// Report HTML module — full page generation for CLI\n// Rendering logic lives in render.ts (shared with web/plugin)\n\nimport type { AnalysisFile } from \"../contracts/figma-node.js\";\nimport type { AnalysisResult } from \"../engine/rule-engine.js\";\nimport type { ScoreReport } from \"../engine/scoring.js\";\nimport { escapeHtml } from \"../ui-helpers.js\";\nimport { renderReportBody, initReportInteractions } from \"./render.js\";\nimport type { ReportData } from \"./render.js\";\n\ndeclare const __REPORT_CSS__: string;\nconst reportCss: string = __REPORT_CSS__;\n\nexport type { ReportData } from \"./render.js\";\nexport { renderReportBody, initReportInteractions } from \"./render.js\";\n\nexport interface NodeScreenshot {\n nodeId: string;\n nodePath: string;\n screenshotBase64: string;\n issueCount: number;\n topSeverity: string;\n}\n\nexport interface HtmlReportOptions {\n nodeScreenshots?: NodeScreenshot[];\n figmaToken?: string | undefined;\n}\n\nconst esc = escapeHtml;\n\n/**\n * Generate a complete standalone HTML report page.\n * Used by CLI — opens in browser.\n */\nexport function generateHtmlReport(\n file: AnalysisFile,\n result: AnalysisResult,\n scores: ScoreReport,\n options?: HtmlReportOptions\n): string {\n const figmaToken = options?.figmaToken;\n\n const data: ReportData = {\n fileName: file.name,\n fileKey: file.fileKey,\n scores,\n issues: result.issues,\n nodeCount: result.nodeCount,\n maxDepth: result.maxDepth,\n ...(figmaToken && { figmaToken }),\n };\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>CanICode Report — ${esc(file.name)}</title>\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n <link href=\"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap\" rel=\"stylesheet\">\n <style>\n${reportCss}\n .cli-topbar {\n background: #09090b; color: white;\n border-bottom: 1px solid #27272a;\n }\n .cli-topbar-inner {\n max-width: 960px; margin: 0 auto;\n padding: 12px 24px;\n display: flex; align-items: center; gap: 16px;\n }\n .cli-topbar-logo { font-weight: 600; font-size: 14px; letter-spacing: -0.01em; }\n .cli-topbar-file { color: #a1a1aa; font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .cli-topbar-date { margin-left: auto; color: #71717a; font-size: 12px; }\n .cli-main { max-width: 960px; margin: 0 auto; padding: 0 24px 64px; }\n @media print {\n .cli-topbar { position: static !important; background: white !important; color: var(--fg) !important; }\n .cli-topbar-file { color: var(--fg-muted) !important; }\n }\n </style>\n</head>\n<body>\n\n <!-- Top Bar -->\n <header class=\"cli-topbar\">\n <div class=\"cli-topbar-inner\">\n <span class=\"cli-topbar-logo\">CanICode</span>\n <span class=\"cli-topbar-file\">${esc(file.name)}</span>\n <span class=\"cli-topbar-date no-print\">${new Date().toLocaleDateString()}</span>\n </div>\n </header>\n\n <main class=\"cli-main\">\n${renderReportBody(data)}\n </main>\n\n <script>(${String(initReportInteractions)})(document.querySelector('.cli-main'));</script>\n${figmaToken ? renderFigmaCommentScript(figmaToken) : \"\"}\n</body>\n</html>`;\n}\n\nfunction renderFigmaCommentScript(figmaToken: string): string {\n return ` <script>\n const FIGMA_TOKEN = '${figmaToken}';\n async function postComment(btn) {\n const fileKey = btn.dataset.fileKey;\n const nodeId = btn.dataset.nodeId.replace(/-/g, ':');\n const commentNodeId = nodeId.split(';')[0].replace(/^I/, '');\n const message = btn.dataset.message;\n const commentBody = '[CanICode] ' + message;\n btn.disabled = true;\n btn.textContent = 'Sending...';\n btn.title = '';\n try {\n const res = await fetch('https://api.figma.com/v1/files/' + fileKey + '/comments', {\n method: 'POST',\n headers: { 'X-FIGMA-TOKEN': FIGMA_TOKEN, 'Content-Type': 'application/json' },\n body: JSON.stringify({ message: commentBody, client_meta: { node_id: commentNodeId, node_offset: { x: 0, y: 0 } } }),\n });\n if (!res.ok) {\n const errBody = await res.text().catch(() => '');\n const errMsg = res.status === 400 ? 'Bad request' : res.status === 403 ? 'Token lacks file access' : res.status === 404 ? 'File not found' : res.status === 429 ? 'Rate limited' : 'HTTP ' + res.status;\n throw new Error(errMsg + (errBody ? ': ' + errBody.slice(0, 100) : ''));\n }\n btn.textContent = 'Sent';\n btn.classList.remove('rpt-btn-fail');\n btn.classList.add('rpt-btn-ok');\n } catch (e) {\n btn.textContent = 'Failed';\n btn.title = e.message || String(e);\n btn.classList.remove('rpt-btn-ok');\n btn.classList.add('rpt-btn-fail');\n btn.disabled = false;\n }\n }\n </script>`;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { z } from \"zod\";\nimport { SeveritySchema } from \"../contracts/severity.js\";\nimport type { RuleConfig } from \"../contracts/rule.js\";\nimport { RULE_CONFIGS } from \"./rule-config.js\";\n\nconst VALID_RULE_IDS = new Set(Object.keys(RULE_CONFIGS));\n\nconst RuleOverrideSchema = z.object({\n score: z.number().int().max(0).optional(),\n severity: SeveritySchema.optional(),\n enabled: z.boolean().optional(),\n});\n\nconst ConfigFileSchema = z.object({\n excludeNodeTypes: z.array(z.string()).optional(),\n excludeNodeNames: z.array(z.string()).optional(),\n gridBase: z.number().int().positive().optional(),\n rules: z.record(z.string(), RuleOverrideSchema)\n .superRefine((rules, ctx) => {\n const unknown = Object.keys(rules).filter((id) => !VALID_RULE_IDS.has(id));\n if (unknown.length > 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Unknown rule ID(s): ${unknown.join(\", \")}. Valid IDs: ${[...VALID_RULE_IDS].join(\", \")}`,\n });\n }\n })\n .optional(),\n});\n\nexport type ConfigFile = z.infer<typeof ConfigFileSchema>;\n\nexport async function loadConfigFile(filePath: string): Promise<ConfigFile> {\n const absPath = resolve(filePath);\n const raw = await readFile(absPath, \"utf-8\");\n const parsed: unknown = JSON.parse(raw);\n return ConfigFileSchema.parse(parsed);\n}\n\n/**\n * Merge config overrides into the base rule configs\n */\nexport function mergeConfigs(\n base: Record<string, RuleConfig>,\n overrides: ConfigFile,\n): Record<string, RuleConfig> {\n const merged = { ...base };\n\n // Apply global gridBase to relevant rules\n if (overrides.gridBase !== undefined) {\n for (const [id, config] of Object.entries(merged)) {\n if (config.options && \"gridBase\" in config.options) {\n merged[id] = {\n ...config,\n options: { ...config.options, gridBase: overrides.gridBase },\n };\n }\n }\n }\n\n // Apply per-rule overrides\n if (overrides.rules) {\n for (const [ruleId, override] of Object.entries(overrides.rules)) {\n const existing = merged[ruleId];\n if (existing) {\n merged[ruleId] = {\n ...existing,\n ...(override.score !== undefined && { score: override.score }),\n ...(override.severity !== undefined && { severity: override.severity }),\n ...(override.enabled !== undefined && { enabled: override.enabled }),\n };\n }\n }\n }\n\n return merged;\n}\n","/**\n * Typed event definitions for PostHog analytics.\n * All events are prefixed with `cic_` (CanICode) to distinguish\n * from noise/spam in PostHog dashboards.\n *\n * Only event metadata is tracked — no design data, tokens, or file contents.\n */\n\n/** Event name prefix — use this to filter genuine events in PostHog */\nexport const EVENT_PREFIX = \"cic_\";\n\nexport const EVENTS = {\n // Analysis\n ANALYSIS_STARTED: `${EVENT_PREFIX}analysis_started`,\n ANALYSIS_COMPLETED: `${EVENT_PREFIX}analysis_completed`,\n ANALYSIS_FAILED: `${EVENT_PREFIX}analysis_failed`,\n\n // Report\n REPORT_GENERATED: `${EVENT_PREFIX}report_generated`,\n COMMENT_POSTED: `${EVENT_PREFIX}comment_posted`,\n COMMENT_FAILED: `${EVENT_PREFIX}comment_failed`,\n\n // MCP\n MCP_TOOL_CALLED: `${EVENT_PREFIX}mcp_tool_called`,\n\n // CLI\n CLI_COMMAND: `${EVENT_PREFIX}cli_command`,\n CLI_INIT: `${EVENT_PREFIX}cli_init`,\n} as const;\n\nexport type EventName = (typeof EVENTS)[keyof typeof EVENTS];\n","/**\n * Unified fetch-based monitoring capture for all environments (CLI, MCP, browser, plugin).\n *\n * No external dependencies — uses native `fetch` (Node 18+ / browser).\n * All operations are fire-and-forget; never throws.\n */\n\nimport type { MonitoringConfig } from \"./types.js\";\n\nlet monitoringEnabled = false;\nlet posthogApiKey: string | undefined;\nlet sentryDsn: string | undefined;\nlet distinctId = \"anonymous\";\nlet environment = \"unknown\";\nlet version = \"unknown\";\nlet commonProps: Record<string, unknown> = {};\n\n/** Generate a simple UUID v4 (no crypto dependency needed for monitoring) */\nfunction uuid4(): string {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/** Parse Sentry DSN into components */\nfunction parseSentryDsn(dsn: string): { key: string; host: string; projectId: string } | null {\n try {\n // DSN format: https://{key}@{host}/{projectId}\n const url = new URL(dsn);\n const key = url.username;\n const projectId = url.pathname.slice(1); // remove leading /\n const host = url.protocol + \"//\" + url.host;\n if (!key || !projectId) return null;\n return { key, host, projectId };\n } catch {\n return null;\n }\n}\n\nexport function initCapture(config: MonitoringConfig): void {\n if (config.enabled === false) return;\n if (!config.posthogApiKey && !config.sentryDsn) return;\n\n monitoringEnabled = true;\n posthogApiKey = config.posthogApiKey;\n sentryDsn = config.sentryDsn;\n distinctId = config.distinctId ?? \"anonymous\";\n environment = config.environment ?? \"unknown\";\n version = config.version ?? \"unknown\";\n commonProps = {\n _sdk: \"canicode\",\n _sdk_version: version,\n _env: environment,\n };\n}\n\nexport function captureEvent(event: string, properties?: Record<string, unknown>): void {\n if (!monitoringEnabled || !posthogApiKey) return;\n\n try {\n fetch(\"https://us.i.posthog.com/i/v0/e/\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n api_key: posthogApiKey,\n event,\n distinct_id: distinctId,\n properties: { ...commonProps, ...properties },\n timestamp: new Date().toISOString(),\n }),\n }).catch(() => {});\n } catch {\n // never throw from monitoring\n }\n}\n\nexport function captureError(error: Error, context?: Record<string, unknown>): void {\n if (!monitoringEnabled) return;\n\n // Send to Sentry via envelope API\n if (sentryDsn) {\n const parsed = parseSentryDsn(sentryDsn);\n if (parsed) {\n try {\n const eventId = uuid4();\n const envelope = [\n JSON.stringify({ event_id: eventId, sent_at: new Date().toISOString(), dsn: sentryDsn }),\n JSON.stringify({ type: \"event\", content_type: \"application/json\" }),\n JSON.stringify({\n event_id: eventId,\n exception: { values: [{ type: error.name, value: error.message }] },\n platform: \"node\",\n environment,\n release: `canicode@${version}`,\n timestamp: Date.now() / 1000,\n extra: context,\n }),\n ].join(\"\\n\");\n\n fetch(`${parsed.host}/api/${parsed.projectId}/envelope/`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-sentry-envelope\",\n \"X-Sentry-Auth\": `Sentry sentry_version=7, sentry_key=${parsed.key}`,\n },\n body: envelope,\n }).catch(() => {});\n } catch {\n // never throw from monitoring\n }\n }\n }\n\n // Also send to PostHog as error event\n captureEvent(\"cic_error\", { error: error.message, ...context });\n}\n\nexport function shutdownCapture(): void {\n monitoringEnabled = false;\n posthogApiKey = undefined;\n sentryDsn = undefined;\n distinctId = \"anonymous\";\n environment = \"unknown\";\n version = \"unknown\";\n commonProps = {};\n}\n","/**\n * Shared monitoring module that works across CLI, MCP, and browser environments.\n *\n * Key design principles:\n * - If no API keys are configured, all functions are silent no-ops\n * - All tracking is fire-and-forget (never blocks or throws)\n * - Zero external dependencies — uses native fetch (Node 18+ / browser)\n * - CLI users can opt out via `canicode config --no-telemetry`\n * - No design data, tokens, or file contents are ever sent\n */\n\nexport type { MonitoringConfig } from \"./types.js\";\nexport { EVENTS } from \"./events.js\";\nexport type { EventName } from \"./events.js\";\n\nimport type { MonitoringConfig } from \"./types.js\";\nimport { initCapture, captureEvent, captureError, shutdownCapture } from \"./capture.js\";\n\n/**\n * Initialise monitoring for the current environment.\n * Safe to call multiple times — subsequent calls are ignored.\n */\nexport function initMonitoring(config: MonitoringConfig): void {\n initCapture(config);\n}\n\n/**\n * Track an analytics event. Fire-and-forget; never throws.\n */\nexport function trackEvent(event: string, properties?: Record<string, unknown>): void {\n try {\n captureEvent(event, properties);\n } catch {\n // never throw from monitoring\n }\n}\n\n/**\n * Track an error. Fire-and-forget; never throws.\n */\nexport function trackError(error: Error, context?: Record<string, unknown>): void {\n try {\n captureError(error, context);\n } catch {\n // never throw from monitoring\n }\n}\n\n/**\n * Shut down monitoring. Call before process exit.\n */\nexport function shutdownMonitoring(): void {\n try {\n shutdownCapture();\n } catch {\n // never throw from monitoring\n }\n}\n","/**\n * Monitoring keys injected at build time via tsup `define`.\n * These are replaced with actual values during CI builds.\n * Locally they default to empty strings (monitoring disabled).\n */\n\ndeclare const __POSTHOG_API_KEY__: string;\ndeclare const __SENTRY_DSN__: string;\n\nexport const POSTHOG_API_KEY: string =\n typeof __POSTHOG_API_KEY__ !== \"undefined\" ? __POSTHOG_API_KEY__ : \"\";\nexport const SENTRY_DSN: string =\n typeof __SENTRY_DSN__ !== \"undefined\" ? __SENTRY_DSN__ : \"\";\n","/**\n * Centralized node semantic classification.\n * All \"what is this node?\" logic lives here so rules share the same predicates.\n *\n * Categories:\n * - Container: layout containers (frame, group, component, instance)\n * - Visual: decorative/graphic elements (vector, shape, image)\n * - Interactive: user-interactable elements (button, link, tab, input, toggle)\n * - Overlay: elements that open on top (modal, drawer, dropdown)\n * - Carousel: elements that slide/swipe (carousel, slider, gallery)\n * - Token: style/variable binding checks\n * - Naming: name pattern classification\n */\n\nimport type { AnalysisNode } from \"../contracts/figma-node.js\";\n\n// ── Container classification ─────────────────────────────────────────────────\n\nexport function isContainerNode(node: AnalysisNode): boolean {\n return node.type === \"FRAME\" || node.type === \"GROUP\" || node.type === \"COMPONENT\" || node.type === \"INSTANCE\";\n}\n\nexport function hasAutoLayout(node: AnalysisNode): boolean {\n return node.layoutMode !== undefined && node.layoutMode !== \"NONE\";\n}\n\nexport function hasTextContent(node: AnalysisNode): boolean {\n return node.type === \"TEXT\" || (node.children?.some((c) => c.type === \"TEXT\") ?? false);\n}\n\nexport function hasOverlappingBounds(a: AnalysisNode, b: AnalysisNode): boolean {\n const boxA = a.absoluteBoundingBox;\n const boxB = b.absoluteBoundingBox;\n\n if (!boxA || !boxB) return false;\n\n return !(\n boxA.x + boxA.width <= boxB.x ||\n boxB.x + boxB.width <= boxA.x ||\n boxA.y + boxA.height <= boxB.y ||\n boxB.y + boxB.height <= boxA.y\n );\n}\n\n// ── Visual classification ────────────────────────────────────────────────────\n\nconst VISUAL_LEAF_TYPES = new Set([\n \"VECTOR\", \"BOOLEAN_OPERATION\", \"ELLIPSE\", \"LINE\", \"STAR\", \"REGULAR_POLYGON\", \"RECTANGLE\",\n]);\n\nexport function isVisualLeafType(type: string): boolean {\n return VISUAL_LEAF_TYPES.has(type);\n}\n\nexport function hasImageFill(node: AnalysisNode): boolean {\n if (!Array.isArray(node.fills)) return false;\n return node.fills.some(\n (fill) =>\n typeof fill === \"object\" &&\n fill !== null &&\n (fill as { type?: unknown }).type === \"IMAGE\",\n );\n}\n\nexport function isVisualOnlyNode(node: AnalysisNode): boolean {\n if (VISUAL_LEAF_TYPES.has(node.type)) return true;\n const hasOnlyVisualChildren =\n node.children !== undefined &&\n node.children.length > 0 &&\n node.children.every((c) => VISUAL_LEAF_TYPES.has(c.type));\n // Image fill only counts as visual-only when there are no content children\n if (hasImageFill(node) && (!node.children || node.children.length === 0 || hasOnlyVisualChildren)) {\n return true;\n }\n if (hasOnlyVisualChildren) return true;\n return false;\n}\n\n// ── Interactive classification ───────────────────────────────────────────────\n\nexport type StatefulComponentType = \"button\" | \"link\" | \"tab\" | \"input\" | \"toggle\";\n\n/** Name patterns → interactive type mapping */\nexport const STATEFUL_PATTERNS: Array<{ pattern: RegExp; type: StatefulComponentType }> = [\n { pattern: /\\b(btn|button|cta)\\b/i, type: \"button\" },\n { pattern: /\\b(link|anchor)\\b/i, type: \"link\" },\n { pattern: /\\b(tab|tabs)\\b/i, type: \"tab\" },\n { pattern: /\\b(nav|navigation|menu|navbar)\\b/i, type: \"tab\" },\n { pattern: /\\b(input|text-?field|search-?bar|textarea)\\b/i, type: \"input\" },\n { pattern: /\\b(select|dropdown|combo-?box)\\b/i, type: \"input\" },\n { pattern: /\\b(toggle|switch|checkbox|radio)\\b/i, type: \"toggle\" },\n];\n\nexport function getStatefulComponentType(node: AnalysisNode): StatefulComponentType | null {\n if (!node.name) return null;\n for (const entry of STATEFUL_PATTERNS) {\n if (entry.pattern.test(node.name)) return entry.type;\n }\n return null;\n}\n\nexport function isStatefulComponent(node: AnalysisNode): boolean {\n return getStatefulComponentType(node) !== null;\n}\n\n/**\n * Standard state names across web + mobile platforms.\n * Used by missing-interaction-state (to detect presence) and\n * non-standard-naming (to flag non-standard names).\n *\n * Sources:\n * - CSS: :hover, :active, :focus, :disabled, :enabled — https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/Pseudo-classes\n * - Material Design 3: Hovered, Focused, Pressed, Dragged — https://m3.material.io/foundations/interaction/states\n * - UIKit: highlighted, selected, disabled, focused — https://developer.apple.com/documentation/uikit/uicontrol/state\n */\nexport const STANDARD_STATE_NAMES = new Set([\n // CSS pseudo-classes (web)\n \"default\", \"hover\", \"active\", \"focus\", \"focused\", \"disabled\", \"enabled\",\n // Material Design 3 (Android)\n \"pressed\", \"dragged\",\n // UIKit (iOS)\n \"highlighted\",\n // Common\n \"selected\",\n]);\n\n/**\n * Patterns that look like state names but aren't in the standard set.\n * Maps common non-standard names to their standard equivalent for suggestions.\n */\nexport const STATE_NAME_SUGGESTIONS: Record<string, string> = {\n on: \"active\",\n off: \"default\",\n clicked: \"pressed\",\n tapped: \"pressed\",\n inactive: \"disabled\",\n normal: \"default\",\n rest: \"default\",\n hovered: \"hover\",\n activated: \"active\",\n checked: \"selected\",\n unchecked: \"default\",\n};\n\n/** Pattern to detect state-like variant option names (broad match) */\nexport const STATE_LIKE_PATTERN = /\\b(on|off|clicked|tapped|inactive|normal|rest|hovered|activated|checked|unchecked)\\b/i;\n\n// ── Overlay / Carousel patterns ──────────────────────────────────────────────\n\n/** Elements that open on top of current view */\nexport const OVERLAY_PATTERN = /\\b(dropdown|select|combo-?box|popover|accordion|drawer|modal|bottom-?sheet|sheet|sidebar|panel|dialog|popup|toast)\\b/i;\n\n/** Elements that swipe/slide between items */\nexport const CAROUSEL_PATTERN = /\\b(carousel|slider|swiper|slide-?show|gallery)\\b/i;\n\nexport function isOverlayNode(node: AnalysisNode): boolean {\n return node.name !== undefined && OVERLAY_PATTERN.test(node.name);\n}\n\nexport function isCarouselNode(node: AnalysisNode): boolean {\n return node.name !== undefined && CAROUSEL_PATTERN.test(node.name);\n}\n\n// ── Token classification ─────────────────────────────────────────────────────\n\nexport function hasStyleReference(node: AnalysisNode, styleType: string): boolean {\n return node.styles !== undefined && styleType in node.styles;\n}\n\nexport function hasBoundVariable(node: AnalysisNode, key: string): boolean {\n return node.boundVariables !== undefined && key in node.boundVariables;\n}\n\n// ── Naming patterns ──────────────────────────────────────────────────────────\n\n/** Figma default name patterns (Frame 1, Group 2, etc.) */\nexport const DEFAULT_NAME_PATTERNS = [\n /^Frame\\s*\\d*$/i,\n /^Group\\s*\\d*$/i,\n /^Rectangle\\s*\\d*$/i,\n /^Ellipse\\s*\\d*$/i,\n /^Vector\\s*\\d*$/i,\n /^Line\\s*\\d*$/i,\n /^Text\\s*\\d*$/i,\n /^Image\\s*\\d*$/i,\n /^Component\\s*\\d*$/i,\n /^Instance\\s*\\d*$/i,\n];\n\nexport function isDefaultName(name: string): boolean {\n return DEFAULT_NAME_PATTERNS.some((pattern) => pattern.test(name));\n}\n\n/** Shape-only non-semantic names */\nexport const NON_SEMANTIC_NAMES = [\n \"rectangle\", \"ellipse\", \"vector\", \"line\", \"polygon\",\n \"star\", \"path\", \"shape\", \"image\", \"fill\", \"stroke\",\n];\n\nexport function isNonSemanticName(name: string): boolean {\n return NON_SEMANTIC_NAMES.includes(name.toLowerCase().trim());\n}\n\n// ── Exclusion ────────────────────────────────────────────────────────────────\n\nexport const EXCLUDED_NAME_PATTERN = /(badge|close|dismiss|overlay|float|fab|dot|indicator|corner|decoration|tag|status|notification|icon|ico|image|asset|filter|dim|dimmed|bg|background|logo|avatar|divider|separator|nav|navigation|gnb|header|footer|sidebar|toolbar|modal|dialog|popup|toast|tooltip|dropdown|menu|sticky|spinner|loader|cursor|cta|chatbot|thumb|thumbnail|tabbar|tab-bar|statusbar|status-bar)/i;\n\nexport function isExcludedName(name: string): boolean {\n return EXCLUDED_NAME_PATTERN.test(name);\n}\n","import type { AnalysisNode } from \"../contracts/figma-node.js\";\nimport type { RuleContext } from \"../contracts/rule.js\";\nimport { isVisualLeafType, isVisualOnlyNode, isExcludedName } from \"./node-semantics.js\";\n\n// ============================================\n// Auto-layout exceptions\n// ============================================\n\n/** Frames that don't need auto-layout (only visual-leaf children like icon paths) */\nexport function isAutoLayoutExempt(node: AnalysisNode): boolean {\n if (\n node.children &&\n node.children.length > 0 &&\n node.children.every((c) => isVisualLeafType(c.type))\n ) return true;\n\n return false;\n}\n\n// ============================================\n// Absolute-position exceptions\n// ============================================\n\n/** Nodes that are allowed to use absolute positioning inside auto-layout */\nexport function isAbsolutePositionExempt(node: AnalysisNode): boolean {\n if (isVisualOnlyNode(node)) return true;\n\n // Intentional name patterns (badge, close, overlay, etc.)\n if (isExcludedName(node.name)) return true;\n\n return false;\n}\n\n// ============================================\n// Size-constraint exceptions\n// ============================================\n\n/** Nodes that don't need maxWidth even with FILL sizing */\nexport function isSizeConstraintExempt(node: AnalysisNode, context: RuleContext): boolean {\n // Already has maxWidth\n if (node.maxWidth !== undefined) return true;\n\n // Parent already has maxWidth — parent constrains the stretch\n if (context.parent?.maxWidth !== undefined) return true;\n\n // Root-level frames — they represent the screen itself\n if (context.depth <= 1) return true;\n\n return false;\n}\n\n// ============================================\n// Fixed-size exceptions\n// ============================================\n\n/** Nodes that are allowed to use fixed sizing inside auto-layout */\nexport function isFixedSizeExempt(node: AnalysisNode): boolean {\n // Visual-only nodes (icons, images, shapes) — intentionally fixed\n if (isVisualOnlyNode(node)) return true;\n\n // Excluded names (nav, header, etc.)\n if (isExcludedName(node.name)) return true;\n\n return false;\n}\n","/**\n * Centralized rule violation messages.\n * All message text lives here so CLI, web, plugin, and MCP share the same strings.\n *\n * Each message function returns { message, suggestion, guide? }:\n * - message: what's wrong (node-specific, dynamic)\n * - suggestion: how to fix it (node-specific, dynamic)\n * - guide: exemption hint (optional, when the rule auto-excludes certain cases)\n */\n\n// ── Message return type ─────────────────────────────────────────────────────\n\nexport interface ViolationMsg {\n message: string;\n suggestion: string;\n guide?: string;\n}\n\n// ── Sub-type definitions ─────────────────────────────────────────────────────\n\nexport type RawValueSubType = \"color\" | \"font\" | \"shadow\" | \"opacity\" | \"spacing\";\nexport type NoAutoLayoutSubType = \"overlapping\" | \"nested\" | \"basic\";\nexport type FixedSizeSubType = \"both-axes\" | \"horizontal\";\nexport type MissingComponentSubType = \"unused-component\" | \"name-repetition\" | \"structure-repetition\" | \"style-override\";\n\n// ── raw-value ────────────────────────────────────────────────────────────────\n\nexport const rawValueMsg = {\n color: (name: string, hex: string): ViolationMsg => ({\n message: `\"${name}\" uses raw fill color ${hex} without style or variable`,\n suggestion: `Bind to a color token`,\n }),\n font: (name: string, fontDesc: string): ViolationMsg => ({\n message: `\"${name}\" uses raw font${fontDesc} without text style`,\n suggestion: `Apply a text style`,\n }),\n shadow: (name: string, shadowType: string, details: string): ViolationMsg => ({\n message: `\"${name}\" has ${shadowType}${details} without effect style`,\n suggestion: `Apply an effect style`,\n }),\n opacity: (name: string, pct: number): ViolationMsg => ({\n message: `\"${name}\" uses raw opacity (${pct}%) without a variable binding`,\n suggestion: `Bind opacity to a variable`,\n }),\n spacing: (name: string, label: string, value: number): ViolationMsg => ({\n message: `\"${name}\" uses raw ${label} (${value}px) without a variable binding`,\n suggestion: `Bind spacing to a variable`,\n }),\n};\n\n// ── irregular-spacing ────────────────────────────────────────────────────────\n\nexport type IrregularSpacingSubType = \"padding\" | \"gap\";\n\nexport const irregularSpacingMsg = (name: string, spacing: number, gridBase: number, nearest: number): ViolationMsg => ({\n message: `\"${name}\" has spacing ${spacing}px not on ${gridBase}pt grid`,\n suggestion: `Round to nearest ${gridBase}pt multiple (${nearest}px)`,\n});\n\n// ── no-auto-layout ───────────────────────────────────────────────────────────\n\nexport const noAutoLayoutMsg = {\n overlapping: (name: string): ViolationMsg => ({\n message: `\"${name}\" has overlapping children without Auto Layout`,\n suggestion: `Apply auto-layout to separate overlapping children`,\n guide: `If this is an intentional overlay (e.g., badge on avatar), this can be ignored`,\n }),\n nested: (name: string): ViolationMsg => ({\n message: `\"${name}\" has nested containers without layout hints`,\n suggestion: `Apply auto-layout to organize nested containers`,\n guide: `Icon wrappers containing only vectors are automatically excluded`,\n }),\n basic: (name: string, arrangement: string, directionHint: string): ViolationMsg => ({\n message: `Frame \"${name}\" has no auto-layout${arrangement}`,\n suggestion: directionHint ? `Apply ${directionHint} auto-layout` : `Apply auto-layout`,\n guide: `Single-child wrappers and icon containers are automatically excluded`,\n }),\n};\n\n// ── absolute-position-in-auto-layout ─────────────────────────────────────────\n\nexport const absolutePositionMsg = (name: string, parentName: string): ViolationMsg => ({\n message: `\"${name}\" uses absolute positioning inside Auto Layout parent \"${parentName}\"`,\n suggestion: `Remove absolute positioning or restructure outside the auto-layout parent`,\n guide: `If this is a badge or overlay, name it with \"badge\", \"overlay\", or \"icon\" to auto-exclude`,\n});\n\n// ── fixed-size-in-auto-layout ────────────────────────────────────────────────\n\nexport const fixedSizeMsg = {\n bothAxes: (name: string, width: number, height: number): ViolationMsg => ({\n message: `Container \"${name}\" (${width}×${height}) uses fixed size on both axes inside auto-layout`,\n suggestion: `Set at least one axis to HUG or FILL`,\n }),\n horizontal: (name: string, width: number): ViolationMsg => ({\n message: `\"${name}\" has fixed width (${width}px) inside auto-layout`,\n suggestion: `Set horizontal sizing to FILL`,\n }),\n};\n\n// ── missing-size-constraint ──────────────────────────────────────────────────\n\nexport type MissingSizeConstraintSubType = \"max-width\" | \"min-width\" | \"wrap\" | \"grid\";\n\nexport const missingSizeConstraintMsg = {\n maxWidth: (name: string, currentWidth: string): ViolationMsg => ({\n message: `\"${name}\" uses FILL width (currently ${currentWidth}) without max-width`,\n suggestion: `Add maxWidth to prevent stretching on large screens`,\n }),\n minWidth: (name: string, currentWidth: string): ViolationMsg => ({\n message: `\"${name}\" uses FILL width (currently ${currentWidth}) without min-width`,\n suggestion: `Add minWidth to prevent collapsing on small screens`,\n }),\n wrap: (name: string): ViolationMsg => ({\n message: `\"${name}\" is in a wrap container without min-width`,\n suggestion: `Add minWidth to control when wrapping occurs`,\n }),\n grid: (name: string): ViolationMsg => ({\n message: `\"${name}\" is in a grid layout without size constraints`,\n suggestion: `Add min/max-width for proper column sizing`,\n }),\n};\n\n// ── non-layout-container (was group-usage) ───────────────────────────────────\n\nexport type NonLayoutContainerSubType = \"group\" | \"section\";\n\nexport const nonLayoutContainerMsg = {\n group: (name: string): ViolationMsg => ({\n message: `\"${name}\" is a Group`,\n suggestion: `Convert to Frame and apply auto-layout`,\n }),\n section: (name: string): ViolationMsg => ({\n message: `\"${name}\" is a Section used as layout container`,\n suggestion: `Convert to Frame and apply auto-layout`,\n }),\n};\n\n// ── deep-nesting ─────────────────────────────────────────────────────────────\n\nexport const deepNestingMsg = (name: string, depth: number, maxDepth: number): ViolationMsg => ({\n message: `\"${name}\" is nested ${depth} levels deep within its component (max: ${maxDepth})`,\n suggestion: `Extract into a sub-component to reduce depth`,\n});\n\n// ── missing-component ────────────────────────────────────────────────────────\n\nexport const missingComponentMsg = {\n unusedComponent: (componentName: string, count: number): ViolationMsg => ({\n message: `Component \"${componentName}\" exists but ${count} repeated frames found instead of instances`,\n suggestion: `Replace frames with component instances`,\n }),\n nameRepetition: (name: string, count: number): ViolationMsg => ({\n message: `\"${name}\" appears ${count} times`,\n suggestion: `Extract as a reusable component`,\n }),\n structureRepetition: (name: string, siblingCount: number): ViolationMsg => ({\n message: `\"${name}\" and ${siblingCount} sibling frame(s) share the same internal structure`,\n suggestion: `Extract a shared component from the repeated structure`,\n }),\n styleOverride: (componentName: string, overrides: string[]): ViolationMsg => ({\n message: `\"${componentName}\" instance has style overrides (${overrides.join(\", \")})`,\n suggestion: `Create a new variant for this style combination`,\n }),\n};\n\n// ── detached-instance ────────────────────────────────────────────────────────\n\nexport const detachedInstanceMsg = (name: string, componentName: string): ViolationMsg => ({\n message: `\"${name}\" may be a detached instance of component \"${componentName}\"`,\n suggestion: `Restore as an instance of \"${componentName}\" or create a new variant`,\n});\n\n// ── variant-structure-mismatch ───────────────────────────────────────────────\n\nexport const variantStructureMismatchMsg = (name: string, mismatchCount: number, totalVariants: number): ViolationMsg => ({\n message: `\"${name}\" has ${mismatchCount}/${totalVariants} variants with different child structures`,\n suggestion: `Unify variant structures using visibility toggles for optional elements`,\n});\n\n// ── non-standard-naming ──────────────────────────────────────────────────────\n\nexport type NonStandardNamingSubType = \"state-name\";\n\nexport const nonStandardNamingMsg = {\n stateName: (name: string, nonStandard: string, suggested: string): ViolationMsg => ({\n message: `\"${name}\" has non-standard state name \"${nonStandard}\"`,\n suggestion: `Use \"${suggested}\" for dev-friendly naming`,\n }),\n};\n\n// ── non-semantic-name (merged: default-name + non-semantic-name) ─────────────\n\nexport type NonSemanticNameSubType = \"frame\" | \"group\" | \"vector\" | \"shape\" | \"text\" | \"image\" | \"component\" | \"instance\" | \"shape-name\";\n\nconst DEFAULT_NAME_SUBTYPE_MAP: Record<string, NonSemanticNameSubType> = {\n FRAME: \"frame\",\n GROUP: \"group\",\n RECTANGLE: \"shape\",\n ELLIPSE: \"shape\",\n VECTOR: \"vector\",\n LINE: \"vector\",\n STAR: \"shape\",\n REGULAR_POLYGON: \"shape\",\n TEXT: \"text\",\n IMAGE: \"image\",\n COMPONENT: \"component\",\n COMPONENT_SET: \"component\",\n INSTANCE: \"instance\",\n};\n\nexport function getDefaultNameSubType(nodeType: string): NonSemanticNameSubType {\n return DEFAULT_NAME_SUBTYPE_MAP[nodeType] ?? \"frame\";\n}\n\nconst NON_SEMANTIC_EXAMPLES: Record<string, string> = {\n FRAME: '\"Header\", \"ProductCard\", \"Sidebar\"',\n GROUP: '\"NavItems\", \"ButtonGroup\", \"CardContent\"',\n VECTOR: '\"ArrowIcon\", \"CheckMark\", \"LogoSymbol\"',\n LINE: '\"Divider\", \"Separator\", \"Underline\"',\n RECTANGLE: '\"Background\", \"Divider\", \"Overlay\"',\n ELLIPSE: '\"AvatarShape\", \"StatusDot\", \"Badge\"',\n STAR: '\"RatingIcon\", \"FavoriteIcon\", \"StarBadge\"',\n REGULAR_POLYGON: '\"PlayIcon\", \"WarningIcon\", \"ShapeDecor\"',\n TEXT: '\"PageTitle\", \"Description\", \"Price\"',\n IMAGE: '\"Avatar\", \"ProductPhoto\", \"Banner\"',\n COMPONENT: '\"PrimaryButton\", \"InputField\", \"CardTemplate\"',\n COMPONENT_SET: '\"Button\", \"Input\", \"Card\"',\n INSTANCE: '\"CloseButton\", \"UserAvatar\", \"StarIcon\"',\n};\n\nexport const nonSemanticNameMsg = (type: string, name: string): ViolationMsg => {\n const examples = NON_SEMANTIC_EXAMPLES[type] ?? '\"Header\", \"ProductCard\", \"Icon\"';\n return {\n message: `${type} \"${name}\" is a non-semantic name`,\n suggestion: `Rename to describe its role (e.g., ${examples})`,\n };\n};\n\n// ── missing-interaction-state ─────────────────────────────────────────────────\n\nexport type MissingInteractionStateSubType = \"hover\" | \"disabled\" | \"active\" | \"focus\";\n\nexport const missingInteractionStateMsg = {\n hover: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Hover state variant`,\n suggestion: `Add a State=Hover variant`,\n }),\n disabled: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Disabled state variant`,\n suggestion: `Add a State=Disabled variant`,\n }),\n active: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Active state variant`,\n suggestion: `Add a State=Active variant`,\n }),\n focus: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Focus state variant`,\n suggestion: `Add a State=Focus variant`,\n }),\n};\n\n// ── missing-prototype ─────────────────────────────────────────────────────────\n\nexport type MissingPrototypeSubType = \"button\" | \"navigation\" | \"tab\" | \"overlay\" | \"carousel\" | \"input\" | \"toggle\";\n\nexport const missingPrototypeMsg = {\n button: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a button but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define the click behavior`,\n }),\n navigation: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a navigation link but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define the destination`,\n }),\n tab: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a tab but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define tab switching behavior`,\n }),\n overlay: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like an overlay trigger but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define open/close behavior`,\n }),\n carousel: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a carousel but has no interaction prototype`,\n suggestion: `Add an ON_CLICK or ON_DRAG interaction to define slide navigation`,\n }),\n input: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like an input but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define focus/interaction behavior`,\n }),\n toggle: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a toggle but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define on/off behavior`,\n }),\n};\n\n// ── inconsistent-naming-convention ───────────────────────────────────────────\n\nexport const inconsistentNamingMsg = (name: string, nodeConvention: string, dominantConvention: string, suggested: string): ViolationMsg => ({\n message: `\"${name}\" uses ${nodeConvention} while siblings use ${dominantConvention}`,\n suggestion: `Rename to \"${suggested}\"`,\n guide: `This checks sibling layers at the same level — you don't have to follow the exact suggestion, just keep naming consistent across siblings`,\n});\n","import type { RuleCheckFn, RuleDefinition } from \"../../contracts/rule.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getRuleOption } from \"../rule-config.js\";\nimport { isAutoLayoutExempt, isAbsolutePositionExempt, isSizeConstraintExempt, isFixedSizeExempt } from \"../rule-exceptions.js\";\nimport { noAutoLayoutMsg, absolutePositionMsg, fixedSizeMsg, missingSizeConstraintMsg, nonLayoutContainerMsg, deepNestingMsg } from \"../rule-messages.js\";\nimport { isContainerNode, hasAutoLayout, hasTextContent, hasOverlappingBounds } from \"../node-semantics.js\";\n\n// ============================================\n// no-auto-layout (merged: absorbs ambiguous-structure + missing-layout-hint)\n// ============================================\n\nconst noAutoLayoutDef: RuleDefinition = {\n id: \"no-auto-layout\",\n name: \"No Auto Layout\",\n category: \"pixel-critical\",\n why: \"Without Auto Layout, AI must guess positioning from absolute coordinates instead of reading explicit layout rules\",\n impact: \"Generated code uses hardcoded positions that break on any content or screen size change\",\n fix: \"Apply Auto Layout to create clear, explicit structure — enables AI to generate flexbox/grid instead of absolute positioning\",\n};\n\nconst noAutoLayoutCheck: RuleCheckFn = (node, context) => {\n if (!isContainerNode(node)) return null;\n if (hasAutoLayout(node)) return null;\n if (!node.children || node.children.length === 0) return null;\n\n if (isAutoLayoutExempt(node)) return null;\n\n // Priority 1: Check for overlapping visible children (ambiguous-structure)\n if (node.children.length >= 2) {\n for (let i = 0; i < node.children.length; i++) {\n for (let j = i + 1; j < node.children.length; j++) {\n const childA = node.children[i];\n const childB = node.children[j];\n if (!childA || !childB) continue;\n\n if (hasOverlappingBounds(childA, childB)) {\n if (childA.visible !== false && childB.visible !== false) {\n return {\n ruleId: noAutoLayoutDef.id,\n subType: \"overlapping\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...noAutoLayoutMsg.overlapping(node.name),\n };\n }\n }\n }\n }\n }\n\n // Priority 2: Check for nested containers without layout hints (missing-layout-hint)\n if (node.children.length >= 2) {\n const nestedContainers = node.children.filter((c) => isContainerNode(c));\n if (nestedContainers.length >= 2) {\n const withoutLayout = nestedContainers.filter((c) => !hasAutoLayout(c));\n if (withoutLayout.length >= 2) {\n return {\n ruleId: noAutoLayoutDef.id,\n subType: \"nested\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...noAutoLayoutMsg.nested(node.name),\n };\n }\n }\n }\n\n // Priority 3: Basic no-auto-layout check (FRAME only)\n if (node.type !== \"FRAME\") return null;\n\n const childCount = node.children?.length ?? 0;\n let directionHint = \"\";\n if (node.children && node.children.length >= 2) {\n const boxes = node.children.filter(c => c.absoluteBoundingBox).map(c => c.absoluteBoundingBox!);\n if (boxes.length >= 2) {\n const yRange = Math.max(...boxes.map(b => b.y)) - Math.min(...boxes.map(b => b.y));\n const xRange = Math.max(...boxes.map(b => b.x)) - Math.min(...boxes.map(b => b.x));\n directionHint = yRange > xRange ? \"VERTICAL\" : \"HORIZONTAL\";\n }\n }\n\n const arrangement = directionHint\n ? ` (${childCount} children arranged ${directionHint.toLowerCase()}ly)`\n : childCount > 0 ? ` (${childCount} children)` : \"\";\n\n return {\n ruleId: noAutoLayoutDef.id,\n subType: \"basic\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...noAutoLayoutMsg.basic(node.name, arrangement, directionHint),\n };\n};\n\nexport const noAutoLayout = defineRule({\n definition: noAutoLayoutDef,\n check: noAutoLayoutCheck,\n});\n\n// ============================================\n// absolute-position-in-auto-layout\n// ============================================\n\nconst absolutePositionInAutoLayoutDef: RuleDefinition = {\n id: \"absolute-position-in-auto-layout\",\n name: \"Absolute Position in Auto Layout\",\n category: \"pixel-critical\",\n why: \"Absolute positioning inside Auto Layout contradicts the parent's layout rules — AI sees conflicting instructions\",\n impact: \"AI must decide whether to follow the parent's flexbox or the child's absolute position — often gets it wrong\",\n fix: \"Remove absolute positioning or use proper Auto Layout alignment\",\n};\n\nconst absolutePositionInAutoLayoutCheck: RuleCheckFn = (node, context) => {\n if (!context.parent) return null;\n if (!hasAutoLayout(context.parent)) return null;\n if (node.layoutPositioning !== \"ABSOLUTE\") return null;\n\n if (isAbsolutePositionExempt(node)) return null;\n\n return {\n ruleId: absolutePositionInAutoLayoutDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...absolutePositionMsg(node.name, context.parent.name),\n };\n};\n\nexport const absolutePositionInAutoLayout = defineRule({\n definition: absolutePositionInAutoLayoutDef,\n check: absolutePositionInAutoLayoutCheck,\n});\n\n// ============================================\n// fixed-size-in-auto-layout (merged: absorbs fixed-width-in-responsive-context)\n// ============================================\n\nconst fixedSizeInAutoLayoutDef: RuleDefinition = {\n id: \"fixed-size-in-auto-layout\",\n name: \"Fixed Size in Auto Layout\",\n category: \"responsive-critical\",\n why: \"Fixed sizing inside Auto Layout contradicts the flexible layout intent\",\n impact: \"AI generates a rigid element inside a flex container — the layout won't respond to content changes\",\n fix: \"Use 'Hug' or 'Fill' for at least one axis. Both-axes FIXED → layout completely rigid; horizontal-only FIXED → width won't adapt to parent resize\",\n};\n\nconst fixedSizeInAutoLayoutCheck: RuleCheckFn = (node, context) => {\n if (!context.parent) return null;\n if (!hasAutoLayout(context.parent)) return null;\n if (!isContainerNode(node)) return null;\n if (!node.absoluteBoundingBox) return null;\n\n if (isFixedSizeExempt(node)) return null;\n\n const { width, height } = node.absoluteBoundingBox;\n\n // Check both axes FIXED (stronger case)\n const hFixed =\n node.layoutSizingHorizontal === \"FIXED\" || node.layoutSizingHorizontal === undefined;\n const vFixed =\n node.layoutSizingVertical === \"FIXED\" || node.layoutSizingVertical === undefined;\n\n if (hFixed && vFixed) {\n // Skip if it has its own auto-layout\n if (node.layoutMode && node.layoutMode !== \"NONE\") return null;\n\n return {\n ruleId: fixedSizeInAutoLayoutDef.id,\n subType: \"both-axes\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...fixedSizeMsg.bothAxes(node.name, width, height),\n };\n }\n\n // Check horizontal-only FIXED (lighter case, from fixed-width-in-responsive-context)\n if (hFixed && !vFixed) {\n // Use layoutSizingHorizontal if available (accurate)\n if (node.layoutSizingHorizontal) {\n if (node.layoutSizingHorizontal !== \"FIXED\") return null;\n } else {\n // Fallback: STRETCH means fill, skip\n if (node.layoutAlign === \"STRETCH\") return null;\n if (node.layoutAlign !== \"INHERIT\") return null;\n }\n\n return {\n ruleId: fixedSizeInAutoLayoutDef.id,\n subType: \"horizontal\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...fixedSizeMsg.horizontal(node.name, width),\n };\n }\n\n return null;\n};\n\nexport const fixedSizeInAutoLayout = defineRule({\n definition: fixedSizeInAutoLayoutDef,\n check: fixedSizeInAutoLayoutCheck,\n});\n\n// ============================================\n// missing-size-constraint (merged: missing-min-width + missing-max-width)\n// ============================================\n\nconst missingSizeConstraintDef: RuleDefinition = {\n id: \"missing-size-constraint\",\n name: \"Missing Size Constraint\",\n category: \"responsive-critical\",\n why: \"Without min/max-width, AI has no bounds — generated code may collapse or stretch indefinitely\",\n impact: \"Content becomes unreadable or invisible at extreme screen sizes\",\n fix: \"Set min-width and/or max-width so AI can generate proper size constraints\",\n};\n\nconst missingSizeConstraintCheck: RuleCheckFn = (node, context) => {\n // Only check containers and text-containing nodes\n if (!isContainerNode(node) && !hasTextContent(node)) return null;\n // Skip if not in Auto Layout context\n if (!context.parent || !hasAutoLayout(context.parent)) return null;\n\n const nodePath = context.path.join(\" > \");\n\n // Check 1: wrap parent → FILL children need min-width\n if (context.parent.layoutWrap === \"WRAP\" && node.layoutSizingHorizontal === \"FILL\" && node.minWidth === undefined) {\n return {\n ruleId: missingSizeConstraintDef.id,\n subType: \"wrap\" as const,\n nodeId: node.id,\n nodePath,\n ...missingSizeConstraintMsg.wrap(node.name),\n };\n }\n\n // Check 2: grid parent → FILL children need size constraints\n if (context.parent.layoutMode === \"GRID\" && node.layoutSizingHorizontal === \"FILL\" && node.minWidth === undefined && node.maxWidth === undefined) {\n return {\n ruleId: missingSizeConstraintDef.id,\n subType: \"grid\" as const,\n nodeId: node.id,\n nodePath,\n ...missingSizeConstraintMsg.grid(node.name),\n };\n }\n\n // Check 3: FILL containers need max-width\n if (node.layoutSizingHorizontal === \"FILL\") {\n if (isSizeConstraintExempt(node, context)) return null;\n\n const currentWidth = node.absoluteBoundingBox ? `${node.absoluteBoundingBox.width}px` : \"unknown\";\n return {\n ruleId: missingSizeConstraintDef.id,\n subType: \"max-width\" as const,\n nodeId: node.id,\n nodePath,\n ...missingSizeConstraintMsg.maxWidth(node.name, currentWidth),\n };\n }\n\n return null;\n};\n\nexport const missingSizeConstraint = defineRule({\n definition: missingSizeConstraintDef,\n check: missingSizeConstraintCheck,\n});\n\n// ============================================\n// non-layout-container (was group-usage — now also catches Section)\n// ============================================\n\nconst nonLayoutContainerDef: RuleDefinition = {\n id: \"non-layout-container\",\n name: \"Non-Layout Container\",\n category: \"pixel-critical\",\n why: \"Groups and Sections lack proper layout rules — AI sees children with absolute coordinates but no container logic\",\n impact: \"AI wraps elements in a plain div with no spacing/alignment, producing fragile layouts\",\n fix: \"Convert to Frame with Auto Layout so AI can generate proper flex/grid containers\",\n};\n\nconst nonLayoutContainerCheck: RuleCheckFn = (node, context) => {\n if (node.type === \"GROUP\") {\n return {\n ruleId: nonLayoutContainerDef.id,\n subType: \"group\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonLayoutContainerMsg.group(node.name),\n };\n }\n\n if (node.type === \"SECTION\") {\n return {\n ruleId: nonLayoutContainerDef.id,\n subType: \"section\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonLayoutContainerMsg.section(node.name),\n };\n }\n\n return null;\n};\n\nexport const nonLayoutContainer = defineRule({\n definition: nonLayoutContainerDef,\n check: nonLayoutContainerCheck,\n});\n\n// ============================================\n// deep-nesting\n// ============================================\n\nconst deepNestingDef: RuleDefinition = {\n id: \"deep-nesting\",\n name: \"Deep Nesting\",\n category: \"code-quality\",\n why: \"Deep nesting consumes AI context exponentially — each level adds indentation and structural overhead\",\n impact: \"AI may lose track of parent-child relationships in deeply nested trees, producing wrong layout hierarchy\",\n fix: \"Flatten the structure by extracting deeply nested groups into sub-components\",\n};\n\nconst deepNestingCheck: RuleCheckFn = (node, context, options) => {\n const maxDepth = (options?.[\"maxDepth\"] as number) ?? getRuleOption(\"deep-nesting\", \"maxDepth\", 5);\n\n if (context.componentDepth < maxDepth) return null;\n if (!isContainerNode(node)) return null;\n\n return {\n ruleId: deepNestingDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...deepNestingMsg(node.name, context.componentDepth, maxDepth),\n };\n};\n\nexport const deepNesting = defineRule({\n definition: deepNestingDef,\n check: deepNestingCheck,\n});\n\n","import type { RuleCheckFn, RuleDefinition } from \"../../contracts/rule.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getRuleOption } from \"../rule-config.js\";\nimport { rawValueMsg, irregularSpacingMsg } from \"../rule-messages.js\";\nimport { hasStyleReference, hasBoundVariable } from \"../node-semantics.js\";\n\nfunction isOnGrid(value: number, gridBase: number): boolean {\n return value % gridBase === 0;\n}\n\n// ============================================\n// raw-value (merged: raw-color + raw-font + raw-shadow + raw-opacity + raw-spacing)\n// ============================================\n\nconst rawValueDef: RuleDefinition = {\n id: \"raw-value\",\n name: \"Raw Value\",\n category: \"token-management\",\n why: \"Values without design tokens or variables must be reproduced exactly per node — one typo means a visible difference\",\n impact: \"AI cannot reference a shared token, so each raw value is an independent source of error across large pages\",\n fix: \"Use design tokens or variables (color styles, text styles, effect styles, opacity/spacing variables) so values are referenceable\",\n};\n\nconst rawValueCheck: RuleCheckFn = (node, context) => {\n const nodePath = context.path.join(\" > \");\n\n // Check 1: Raw fill color\n if (node.fills && Array.isArray(node.fills) && node.fills.length > 0) {\n if (!hasStyleReference(node, \"fill\") && !hasBoundVariable(node, \"fills\")) {\n for (const fill of node.fills) {\n const fillObj = fill as Record<string, unknown>;\n if (fillObj[\"type\"] === \"SOLID\" && fillObj[\"color\"]) {\n const c = fillObj[\"color\"] as Record<string, number>;\n const hex = `#${Math.round((c[\"r\"] ?? 0) * 255).toString(16).padStart(2, \"0\")}${Math.round((c[\"g\"] ?? 0) * 255).toString(16).padStart(2, \"0\")}${Math.round((c[\"b\"] ?? 0) * 255).toString(16).padStart(2, \"0\")}`.toUpperCase();\n return {\n ruleId: rawValueDef.id,\n subType: \"color\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.color(node.name, hex),\n };\n }\n }\n }\n }\n\n // Check 2: Raw font (TEXT nodes without text style)\n if (node.type === \"TEXT\") {\n if (\n !hasStyleReference(node, \"text\") &&\n (!hasBoundVariable(node, \"fontFamily\") || !hasBoundVariable(node, \"fontSize\"))\n ) {\n const fontParts: string[] = [];\n const s = node.style;\n if (s) {\n if (s[\"fontFamily\"]) fontParts.push(String(s[\"fontFamily\"]));\n if (s[\"fontSize\"]) fontParts.push(`${s[\"fontSize\"]}px`);\n if (s[\"fontWeight\"]) fontParts.push(String(s[\"fontWeight\"]));\n }\n const fontDesc = fontParts.length > 0 ? ` (${fontParts.join(\" \")})` : \"\";\n return {\n ruleId: rawValueDef.id,\n subType: \"font\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.font(node.name, fontDesc),\n };\n }\n }\n\n // Check 3: Raw shadow (effects without effect style)\n if (node.effects && Array.isArray(node.effects) && node.effects.length > 0) {\n if (!hasStyleReference(node, \"effect\")) {\n for (const effect of node.effects) {\n const effectObj = effect as Record<string, unknown>;\n if (effectObj[\"type\"] === \"DROP_SHADOW\" || effectObj[\"type\"] === \"INNER_SHADOW\") {\n const shadowType = effectObj[\"type\"] === \"DROP_SHADOW\" ? \"drop shadow\" : \"inner shadow\";\n const offset = effectObj[\"offset\"] as Record<string, number> | undefined;\n const radius = effectObj[\"radius\"] as number | undefined;\n const detailParts: string[] = [];\n if (offset) detailParts.push(`offset ${Math.round(offset[\"x\"] ?? 0)},${Math.round(offset[\"y\"] ?? 0)}`);\n if (radius !== undefined) detailParts.push(`blur ${Math.round(radius)}`);\n const details = detailParts.length > 0 ? ` (${detailParts.join(\" \")})` : \"\";\n return {\n ruleId: rawValueDef.id,\n subType: \"shadow\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.shadow(node.name, shadowType, details),\n };\n }\n }\n }\n }\n\n // Check 4: Raw opacity (non-default opacity without variable)\n if (node.opacity !== undefined && node.opacity < 1 && !hasBoundVariable(node, \"opacity\")) {\n return {\n ruleId: rawValueDef.id,\n subType: \"opacity\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.opacity(node.name, Math.round(node.opacity * 100)),\n };\n }\n\n // Check 5: Raw spacing (padding/gap without variable binding)\n const spacingKeys = [\"paddingLeft\", \"paddingRight\", \"paddingTop\", \"paddingBottom\", \"itemSpacing\"] as const;\n for (const key of spacingKeys) {\n const value = node[key];\n if (value !== undefined && value > 0 && !hasBoundVariable(node, key)) {\n const label = key === \"itemSpacing\" ? \"gap\" : key.replace(\"padding\", \"padding-\").toLowerCase();\n return {\n ruleId: rawValueDef.id,\n subType: \"spacing\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.spacing(node.name, label, value),\n };\n }\n }\n\n return null;\n};\n\nexport const rawValue = defineRule({\n definition: rawValueDef,\n check: rawValueCheck,\n});\n\n// ============================================\n// irregular-spacing (merged: inconsistent-spacing + magic-number-spacing)\n// ============================================\n\nconst irregularSpacingDef: RuleDefinition = {\n id: \"irregular-spacing\",\n name: \"Irregular Spacing\",\n category: \"token-management\",\n why: \"Off-grid or arbitrary spacing values force AI to handle many unique values instead of a predictable pattern\",\n impact: \"Higher chance of pixel-level differences when AI substitutes nearby round values\",\n fix: \"Align spacing to the design system grid (e.g., 4pt/8pt increments) for predictable implementation\",\n};\n\nconst irregularSpacingCheck: RuleCheckFn = (node, context, options) => {\n const configuredGridBase = (options?.[\"gridBase\"] as number) ?? getRuleOption(\"irregular-spacing\", \"gridBase\", 4);\n const gridBase = Number.isFinite(configuredGridBase) && configuredGridBase > 0 ? configuredGridBase : 4;\n\n const spacingEntries: Array<{ value: number; subType: \"padding\" | \"gap\" }> = [];\n for (const key of [\"paddingLeft\", \"paddingRight\", \"paddingTop\", \"paddingBottom\"] as const) {\n const v = node[key];\n if (v !== undefined && v > 0) spacingEntries.push({ value: v, subType: \"padding\" });\n }\n if (node.itemSpacing !== undefined && node.itemSpacing > 0) {\n spacingEntries.push({ value: node.itemSpacing, subType: \"gap\" });\n }\n\n // Allow small intentional values\n const commonValues = [1, 2];\n\n for (const entry of spacingEntries) {\n if (commonValues.includes(entry.value)) continue;\n if (!isOnGrid(entry.value, gridBase)) {\n return {\n ruleId: irregularSpacingDef.id,\n subType: entry.subType,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...irregularSpacingMsg(node.name, entry.value, gridBase, Math.round(entry.value / gridBase) * gridBase),\n };\n }\n }\n\n return null;\n};\n\nexport const irregularSpacing = defineRule({\n definition: irregularSpacingDef,\n check: irregularSpacingCheck,\n});\n","import type { RuleCheckFn, RuleDefinition, RuleContext } from \"../../contracts/rule.js\";\nimport { getAnalysisState } from \"../../contracts/rule.js\";\nimport type { AnalysisNode } from \"../../contracts/figma-node.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getRuleOption } from \"../rule-config.js\";\nimport { missingComponentMsg, detachedInstanceMsg, variantStructureMismatchMsg } from \"../rule-messages.js\";\n\n// ============================================\n// Helper functions\n// ============================================\n\n\n/** Style properties to compare between master and instance. */\nconst STYLE_COMPARE_KEYS = [\"fills\", \"strokes\", \"effects\", \"cornerRadius\", \"strokeWeight\", \"individualStrokeWeights\"] as const;\n\n/**\n * Detect style overrides between a component master and an instance.\n * Returns list of property names that differ.\n */\nfunction detectStyleOverrides(master: AnalysisNode, instance: AnalysisNode): string[] {\n const overrides: string[] = [];\n for (const key of STYLE_COMPARE_KEYS) {\n const masterVal = master[key];\n const instanceVal = instance[key];\n // Both undefined/null → no override\n if (masterVal == null && instanceVal == null) continue;\n // One exists, other doesn't → override\n if (masterVal == null || instanceVal == null) {\n overrides.push(key);\n continue;\n }\n // Deep compare via JSON\n if (JSON.stringify(masterVal) !== JSON.stringify(instanceVal)) {\n overrides.push(key);\n }\n }\n return overrides;\n}\n\n/**\n * Collect all frame names in the file for duplicate detection\n */\nfunction collectFrameNames(\n node: AnalysisNode,\n names: Map<string, string[]> = new Map()\n): Map<string, string[]> {\n if (node.type === \"FRAME\" && node.name) {\n const existing = names.get(node.name) ?? [];\n existing.push(node.id);\n names.set(node.name, existing);\n }\n\n if (node.children) {\n for (const child of node.children) {\n collectFrameNames(child, names);\n }\n }\n\n return names;\n}\n\n/**\n * Build a structural fingerprint for a node.\n * The fingerprint encodes type, layoutMode, and child types recursively up to maxDepth.\n */\nfunction buildFingerprint(node: AnalysisNode, depth: number): string {\n if (depth <= 0 || !node.children || node.children.length === 0) {\n return `${node.type}:${node.layoutMode ?? \"NONE\"}`;\n }\n\n const childFingerprints = node.children\n .map((child) => buildFingerprint(child, depth - 1))\n .join(\",\");\n\n return `${node.type}:${node.layoutMode ?? \"NONE\"}:[${childFingerprints}]`;\n}\n\n/**\n * Check if the node is inside an INSTANCE subtree.\n * Walks the full ancestor type chain to detect INSTANCE at any level.\n */\nfunction isInsideInstance(context: {\n ancestorTypes: string[];\n}): boolean {\n return context.ancestorTypes.includes(\"INSTANCE\");\n}\n\n\n\n// ============================================\n// missing-component (unified 4-stage rule)\n// ============================================\n\n/** State keys for per-analysis deduplication via RuleContext.analysisState */\nconst SEEN_STAGE1_KEY = \"missing-component:seenStage1ComponentNames\";\nconst SEEN_STAGE4_KEY = \"missing-component:seenStage4ComponentIds\";\n\nfunction getSeenStage1(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_STAGE1_KEY, () => new Set<string>());\n}\n\nfunction getSeenStage4(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_STAGE4_KEY, () => new Set<string>());\n}\n\nconst missingComponentDef: RuleDefinition = {\n id: \"missing-component\",\n name: \"Missing Component\",\n category: \"code-quality\",\n why: \"Repeated structures, unused components, and divergent instance overrides indicate missing or underutilized components. This inflates AI token consumption and forces manual maintenance.\",\n impact: \"AI code generators reproduce each repeated frame independently instead of emitting a reusable component. Divergent instance overrides produce inconsistent implementations.\",\n fix: \"Create components from repeated structures, use instances instead of duplicated frames, and create variants for instances with significantly different overrides.\",\n};\n\nconst missingComponentCheck: RuleCheckFn = (node, context, options) => {\n // ========================================\n // FRAME stages (1, 2, 3) — ordered by priority\n // ========================================\n if (node.type === \"FRAME\") {\n // Stage 1: Component exists but not used — FRAME name matches a component in metadata AND frame is repeated\n const components = context.file.components;\n const matchingComponent = Object.values(components).find(\n (c) => c.name.toLowerCase() === node.name.toLowerCase()\n );\n\n // Collect frame names once for Stage 1 and Stage 2\n const frameNames = collectFrameNames(context.file.document);\n const sameNameFrames = frameNames.get(node.name);\n const firstFrame = sameNameFrames?.[0];\n\n if (matchingComponent) {\n const seenStage1 = getSeenStage1(context);\n if (\n sameNameFrames &&\n firstFrame !== undefined &&\n sameNameFrames.length >= 2 &&\n !seenStage1.has(node.name.toLowerCase()) &&\n firstFrame === node.id\n ) {\n seenStage1.add(node.name.toLowerCase());\n return {\n ruleId: missingComponentDef.id,\n subType: \"unused-component\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.unusedComponent(matchingComponent.name, sameNameFrames.length),\n };\n }\n }\n\n // Stage 2: Name-based repetition (existing logic)\n const minRepetitions =\n (options?.[\"minRepetitions\"] as number | undefined) ??\n getRuleOption(\"missing-component\", \"minRepetitions\", 3);\n\n if (sameNameFrames && firstFrame !== undefined && sameNameFrames.length >= minRepetitions) {\n if (firstFrame === node.id) {\n return {\n ruleId: missingComponentDef.id,\n subType: \"name-repetition\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.nameRepetition(node.name, sameNameFrames.length),\n };\n }\n }\n\n // Stage 3: Structure-based repetition (absorbed from repeated-frame-structure)\n // Skip if node is inside an INSTANCE subtree\n if (isInsideInstance(context)) return null;\n\n // Skip if parent is COMPONENT_SET\n if (context.parent?.type === \"COMPONENT_SET\") return null;\n\n // Skip if node has no children\n if (!node.children || node.children.length === 0) return null;\n\n const structureMinRepetitions =\n (options?.[\"structureMinRepetitions\"] as number | undefined) ??\n getRuleOption(\"missing-component\", \"structureMinRepetitions\", 2);\n\n const maxFingerprintDepth =\n (options?.[\"maxFingerprintDepth\"] as number | undefined) ??\n getRuleOption(\"missing-component\", \"maxFingerprintDepth\", 3);\n\n // Compute fingerprint for this node\n const fingerprint = buildFingerprint(node, maxFingerprintDepth);\n\n // Access siblings (may be undefined)\n const siblings = context.siblings ?? [];\n\n // Filter siblings to qualifying frames (type === FRAME, not inside INSTANCE, has children)\n const qualifyingSiblings = siblings.filter(\n (s) =>\n s.type === \"FRAME\" &&\n s.children !== undefined &&\n s.children.length > 0\n );\n\n // Count siblings (including self) sharing the same fingerprint\n const matchingNodes = qualifyingSiblings.filter(\n (s) => buildFingerprint(s, maxFingerprintDepth) === fingerprint\n );\n\n // Ensure self is counted (it should be in siblings, but add a guard)\n const selfIsInSiblings = qualifyingSiblings.some((s) => s.id === node.id);\n const count = selfIsInSiblings\n ? matchingNodes.length\n : matchingNodes.length + 1;\n\n if (count >= structureMinRepetitions) {\n // Only emit for the first sibling (by array order) with this fingerprint\n const firstMatch = qualifyingSiblings.find(\n (s) => buildFingerprint(s, maxFingerprintDepth) === fingerprint\n );\n\n // If self is not in siblings list, treat self as first match when no earlier match exists\n const firstMatchId = firstMatch?.id ?? node.id;\n if (firstMatchId === node.id) {\n return {\n ruleId: missingComponentDef.id,\n subType: \"structure-repetition\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.structureRepetition(node.name, count - 1),\n };\n }\n }\n\n return null;\n }\n\n // ========================================\n // Stage 4: Instance style override detection\n // Compares instance styles against component master.\n // Any style override (fills, strokes, effects, cornerRadius) means\n // the designer should use a variant instead.\n // ========================================\n if (node.type === \"INSTANCE\" && node.componentId) {\n const seenStage4 = getSeenStage4(context);\n if (seenStage4.has(node.componentId)) return null;\n\n const componentDefs = context.file.componentDefinitions;\n if (!componentDefs) return null;\n\n const master = componentDefs[node.componentId];\n if (!master) return null;\n\n // Compare style properties between master and instance\n const overrides = detectStyleOverrides(master, node);\n if (overrides.length > 0) {\n // Only mark as seen when we actually flag — allows other instances to be checked\n seenStage4.add(node.componentId);\n const componentMeta = context.file.components[node.componentId];\n const componentName = componentMeta?.name ?? node.name;\n\n return {\n ruleId: missingComponentDef.id,\n subType: \"style-override\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.styleOverride(componentName, overrides),\n };\n }\n return null;\n }\n\n return null;\n};\n\nexport const missingComponent = defineRule({\n definition: missingComponentDef,\n check: missingComponentCheck,\n});\n\n// ============================================\n// detached-instance\n// ============================================\n\nconst detachedInstanceDef: RuleDefinition = {\n id: \"detached-instance\",\n name: \"Detached Instance\",\n category: \"code-quality\",\n why: \"Detached instances lose component relationship — AI sees a one-off frame instead of a reusable component reference\",\n impact: \"AI generates duplicate code instead of reusing the component, inflating output and causing inconsistencies\",\n fix: \"Reset the instance or create a new variant if customization is needed\",\n};\n\nconst detachedInstanceCheck: RuleCheckFn = (node, context) => {\n // A detached instance would be a FRAME that was once an INSTANCE\n // This is hard to detect without historical data\n // Heuristic: Frame with a name that looks like it came from a component\n if (node.type !== \"FRAME\") return null;\n\n // Check if there's a component in the file with a matching name (word boundary)\n const components = context.file.components;\n\n for (const [, component] of Object.entries(components)) {\n const pattern = new RegExp(`\\\\b${component.name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}\\\\b`);\n if (pattern.test(node.name)) {\n // This frame might be a detached instance of this component\n return {\n ruleId: detachedInstanceDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...detachedInstanceMsg(node.name, component.name),\n };\n }\n }\n\n return null;\n};\n\nexport const detachedInstance = defineRule({\n definition: detachedInstanceDef,\n check: detachedInstanceCheck,\n});\n\n// ============================================\n// variant-structure-mismatch\n// ============================================\n\nconst variantStructureMismatchDef: RuleDefinition = {\n id: \"variant-structure-mismatch\",\n name: \"Variant Structure Mismatch\",\n category: \"code-quality\",\n why: \"Variants with different child structures prevent AI from creating a unified component template\",\n impact: \"AI must generate separate implementations for each variant instead of a single parameterized component\",\n fix: \"Ensure all variants share the same child structure, using visibility toggles for optional elements\",\n};\n\nconst variantStructureMismatchCheck: RuleCheckFn = (node, context) => {\n // Only COMPONENT_SET\n if (node.type !== \"COMPONENT_SET\") return null;\n if (!node.children?.length || node.children.length < 2) return null;\n\n // Build fingerprint for each variant child\n const fingerprints = node.children\n .filter(child => child.type === \"COMPONENT\")\n .map(child => buildFingerprint(child, 2));\n\n if (fingerprints.length < 2) return null;\n\n // Compare all fingerprints to the first one\n const base = fingerprints[0];\n const mismatched = fingerprints.filter(fp => fp !== base);\n\n if (mismatched.length === 0) return null;\n\n const mismatchCount = mismatched.length;\n const totalVariants = fingerprints.length;\n\n return {\n ruleId: variantStructureMismatchDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...variantStructureMismatchMsg(node.name, mismatchCount, totalVariants),\n };\n};\n\nexport const variantStructureMismatch = defineRule({\n definition: variantStructureMismatchDef,\n check: variantStructureMismatchCheck,\n});\n\n","import type { RuleCheckFn, RuleDefinition } from \"../../contracts/rule.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getDefaultNameSubType, nonSemanticNameMsg, inconsistentNamingMsg, nonStandardNamingMsg } from \"../rule-messages.js\";\nimport { isExcludedName, isDefaultName, isNonSemanticName, STANDARD_STATE_NAMES, STATE_NAME_SUGGESTIONS, STATE_LIKE_PATTERN } from \"../node-semantics.js\";\n\nfunction detectNamingConvention(name: string): string | null {\n if (/^[a-z]+(-[a-z]+)*$/.test(name)) return \"kebab-case\";\n if (/^[a-z]+(_[a-z]+)*$/.test(name)) return \"snake_case\";\n if (/^[a-z]+([A-Z][a-z]*)*$/.test(name)) return \"camelCase\";\n if (/^[A-Z][a-z]+([A-Z][a-z]*)*$/.test(name)) return \"PascalCase\";\n if (/^[A-Z]+(_[A-Z]+)*$/.test(name)) return \"SCREAMING_SNAKE_CASE\";\n if (/\\s/.test(name)) return \"Title Case\";\n return null;\n}\n\n/** Single capitalized word is compatible with both PascalCase and Title Case */\nfunction isCompatible(nodeConvention: string, dominantConvention: string, name: string): boolean {\n if (!/^[A-Z][a-z]+$/.test(name)) return false;\n const pair = new Set([nodeConvention, dominantConvention]);\n return pair.has(\"PascalCase\") && pair.has(\"Title Case\");\n}\n\n/** Split a name into words regardless of convention */\nfunction splitWords(name: string): string[] {\n // Title Case / space-separated\n if (/\\s/.test(name)) return name.split(/\\s+/);\n // SCREAMING_SNAKE_CASE or snake_case\n if (name.includes(\"_\")) return name.split(\"_\");\n // kebab-case\n if (name.includes(\"-\")) return name.split(\"-\");\n // camelCase / PascalCase — split on uppercase boundaries (including acronym runs)\n return name\n .replace(/([a-z0-9])([A-Z])/g, \"$1\\0$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1\\0$2\")\n .split(\"\\0\");\n}\n\n/** Convert a name to the target convention */\nfunction convertName(name: string, target: string): string {\n const words = splitWords(name);\n switch (target) {\n case \"kebab-case\":\n return words.map(w => w.toLowerCase()).join(\"-\");\n case \"snake_case\":\n return words.map(w => w.toLowerCase()).join(\"_\");\n case \"camelCase\":\n return words.map((w, i) => i === 0 ? w.toLowerCase() : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(\"\");\n case \"PascalCase\":\n return words.map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(\"\");\n case \"SCREAMING_SNAKE_CASE\":\n return words.map(w => w.toUpperCase()).join(\"_\");\n case \"Title Case\":\n return words.map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(\" \");\n default:\n return name;\n }\n}\n\n// ============================================\n// non-semantic-name (merged: default-name + non-semantic-name)\n// ============================================\n\nconst nonSemanticNameDef: RuleDefinition = {\n id: \"non-semantic-name\",\n name: \"Non-Semantic Name\",\n category: \"semantic\",\n why: \"Default or shape names give AI no semantic context — it cannot choose appropriate HTML tags or class names\",\n impact: \"AI generates generic <div> wrappers instead of semantic elements like <header>, <nav>, <article>\",\n fix: \"Rename with a descriptive, purpose-driven name (e.g., 'Header', 'ProductCard', 'Divider')\",\n};\n\nconst nonSemanticNameCheck: RuleCheckFn = (node, context) => {\n if (!node.name) return null;\n if (isExcludedName(node.name)) return null;\n\n // Check 1: Figma default names (Frame 1, Group 2, etc.)\n if (isDefaultName(node.name)) {\n return {\n ruleId: nonSemanticNameDef.id,\n subType: getDefaultNameSubType(node.type),\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonSemanticNameMsg(node.type, node.name),\n };\n }\n\n // Check 2: Shape-only names (rectangle, ellipse, vector, etc.)\n if (isNonSemanticName(node.name)) {\n // Allow shape names for actual shape primitives at leaf level\n if (!node.children || node.children.length === 0) {\n const shapeTypes = [\"RECTANGLE\", \"ELLIPSE\", \"VECTOR\", \"LINE\", \"STAR\", \"REGULAR_POLYGON\"];\n if (shapeTypes.includes(node.type)) return null;\n }\n\n return {\n ruleId: nonSemanticNameDef.id,\n subType: \"shape-name\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonSemanticNameMsg(node.type, node.name),\n };\n }\n\n return null;\n};\n\nexport const nonSemanticName = defineRule({\n definition: nonSemanticNameDef,\n check: nonSemanticNameCheck,\n});\n\n// ============================================\n// inconsistent-naming-convention\n// ============================================\n\nconst inconsistentNamingConventionDef: RuleDefinition = {\n id: \"inconsistent-naming-convention\",\n name: \"Inconsistent Naming Convention\",\n category: \"semantic\",\n why: \"Mixed naming conventions (camelCase + kebab-case + Title Case) at the same level confuse AI pattern recognition\",\n impact: \"AI generates inconsistent class/component names, making the codebase harder to maintain\",\n fix: \"Pick one convention for sibling elements (e.g., kebab-case: 'product-card', or PascalCase: 'ProductCard') — AI maps names to CSS classes and component names, so mixed conventions produce inconsistent code\",\n};\n\nconst inconsistentNamingConventionCheck: RuleCheckFn = (node, context) => {\n if (!context.siblings || context.siblings.length < 2) return null;\n\n // Detect conventions used by siblings\n const conventions = new Map<string, number>();\n let ambiguousPascalCount = 0;\n\n for (const sibling of context.siblings) {\n if (!sibling.name) continue;\n const convention = detectNamingConvention(sibling.name);\n if (convention) {\n conventions.set(convention, (conventions.get(convention) ?? 0) + 1);\n if (convention === \"PascalCase\" && /^[A-Z][a-z]+$/.test(sibling.name)) {\n ambiguousPascalCount++;\n }\n }\n }\n\n // Single capitalized words (Header, Footer) are detected as PascalCase but are\n // equally valid as Title Case. When both conventions appear, discount these\n // ambiguous names so they don't bias the dominant convention toward PascalCase.\n if (conventions.has(\"PascalCase\") && conventions.has(\"Title Case\") && ambiguousPascalCount > 0) {\n const adjusted = (conventions.get(\"PascalCase\") ?? 0) - ambiguousPascalCount;\n if (adjusted <= 0) {\n conventions.delete(\"PascalCase\");\n } else {\n conventions.set(\"PascalCase\", adjusted);\n }\n }\n\n // Skip if we can't detect clear conventions\n if (conventions.size < 2) return null;\n\n // Find the dominant convention\n let dominantConvention = \"\";\n let maxCount = 0;\n for (const [convention, count] of conventions) {\n if (count > maxCount) {\n maxCount = count;\n dominantConvention = convention;\n }\n }\n\n // Check if current node violates the dominant convention\n const nodeConvention = detectNamingConvention(node.name);\n if (nodeConvention && nodeConvention !== dominantConvention && maxCount >= 2) {\n // Single capitalized word is compatible with both PascalCase and Title Case\n if (isCompatible(nodeConvention, dominantConvention, node.name)) return null;\n\n const suggested = convertName(node.name, dominantConvention);\n return {\n ruleId: inconsistentNamingConventionDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...inconsistentNamingMsg(node.name, nodeConvention, dominantConvention, suggested),\n };\n }\n\n return null;\n};\n\nexport const inconsistentNamingConvention = defineRule({\n definition: inconsistentNamingConventionDef,\n check: inconsistentNamingConventionCheck,\n});\n\n// ============================================\n// non-standard-naming\n// ============================================\n\nconst nonStandardNamingDef: RuleDefinition = {\n id: \"non-standard-naming\",\n name: \"Non-Standard Naming\",\n category: \"semantic\",\n why: \"Non-standard state names prevent interaction rules from detecting state variants — AI cannot generate correct :hover/:active/:disabled styles\",\n impact: \"Interaction state detection fails, resulting in static UI with no state transitions\",\n fix: \"Use platform-standard state names: default, hover, active, pressed, selected, highlighted, disabled, enabled, focus, focused, dragged\",\n};\n\nconst nonStandardNamingCheck: RuleCheckFn = (node, context) => {\n // Only check COMPONENT_SET (variant container)\n if (node.type !== \"COMPONENT_SET\") return null;\n if (!node.componentPropertyDefinitions) return null;\n\n for (const prop of Object.values(node.componentPropertyDefinitions)) {\n const p = prop as Record<string, unknown>;\n if (p[\"type\"] !== \"VARIANT\") continue;\n const options = p[\"variantOptions\"];\n if (!Array.isArray(options)) continue;\n\n for (const opt of options) {\n if (typeof opt !== \"string\") continue;\n const lower = opt.toLowerCase().trim();\n\n // Skip if it's a standard name\n if (STANDARD_STATE_NAMES.has(lower)) continue;\n\n // Check if it matches a known non-standard state name\n if (STATE_LIKE_PATTERN.test(opt)) {\n const suggestion = STATE_NAME_SUGGESTIONS[lower];\n if (suggestion) {\n return {\n ruleId: nonStandardNamingDef.id,\n subType: \"state-name\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonStandardNamingMsg.stateName(node.name, opt, suggestion),\n };\n }\n }\n }\n }\n\n return null;\n};\n\nexport const nonStandardNaming = defineRule({\n definition: nonStandardNamingDef,\n check: nonStandardNamingCheck,\n});\n\n","import type { RuleCheckFn, RuleDefinition, RuleContext } from \"../../contracts/rule.js\";\nimport { getAnalysisState } from \"../../contracts/rule.js\";\nimport type { AnalysisNode } from \"../../contracts/figma-node.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport type { MissingInteractionStateSubType, MissingPrototypeSubType } from \"../rule-messages.js\";\nimport { missingInteractionStateMsg, missingPrototypeMsg } from \"../rule-messages.js\";\nimport { getStatefulComponentType, isOverlayNode, isCarouselNode, type StatefulComponentType } from \"../node-semantics.js\";\n\n/** Expected state variants by interactive type */\nconst EXPECTED_STATES: Record<StatefulComponentType, MissingInteractionStateSubType[]> = {\n button: [\"hover\", \"active\", \"disabled\"],\n link: [\"hover\"],\n tab: [\"hover\", \"active\"],\n input: [\"focus\", \"disabled\"],\n toggle: [\"disabled\"],\n};\n\n/** State name patterns — web + mobile platform standard names */\nconst STATE_PATTERNS: Record<MissingInteractionStateSubType, RegExp> = {\n hover: /\\bhover\\b/i,\n disabled: /\\bdisabled\\b/i,\n active: /\\b(active|pressed|selected|highlighted)\\b/i,\n focus: /\\bfocus(ed)?\\b/i,\n};\n\n// ============================================\n// Helpers\n// ============================================\n\n/** Dedup key: emit at most one violation per componentId + subType */\nconst SEEN_KEY = \"missing-interaction-state:seen\";\n\nfunction getSeen(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_KEY, () => new Set<string>());\n}\n\n/**\n * Check if a state variant exists via componentPropertyDefinitions.\n * Looks for VARIANT type properties where variantOptions contain the state name.\n */\nfunction hasStateInVariantProps(node: AnalysisNode, statePattern: RegExp): boolean {\n if (!node.componentPropertyDefinitions) return false;\n for (const prop of Object.values(node.componentPropertyDefinitions)) {\n const p = prop as Record<string, unknown>;\n if (p[\"type\"] !== \"VARIANT\") continue;\n const options = p[\"variantOptions\"];\n if (!Array.isArray(options)) continue;\n if (options.some((opt) => typeof opt === \"string\" && statePattern.test(opt))) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Check if a state variant exists via component master's componentPropertyDefinitions.\n * Falls back to componentDefinitions (fetched masters) when the instance itself\n * doesn't carry the property definitions.\n */\nfunction hasStateInComponentMaster(\n node: AnalysisNode,\n context: RuleContext,\n statePattern: RegExp,\n): boolean {\n if (!node.componentId) return false;\n const defs = context.file.componentDefinitions;\n if (!defs) return false;\n const master = defs[node.componentId];\n if (!master) return false;\n return hasStateInVariantProps(master, statePattern);\n}\n\n// ============================================\n// missing-interaction-state\n// ============================================\n\nconst missingInteractionStateDef: RuleDefinition = {\n id: \"missing-interaction-state\",\n name: \"Missing Interaction State\",\n category: \"interaction\",\n why: \"Interactive components without state variants force AI to guess hover/focus/disabled appearances — or skip them entirely\",\n impact: \"Generated code has no :hover, :focus, or :disabled styles, making the UI feel static and unresponsive\",\n fix: \"Add state variants (Hover, Disabled, Focus, Active) to interactive components in Figma\",\n};\n\nconst missingInteractionStateCheck: RuleCheckFn = (node, context) => {\n // Only check component instances and components\n if (node.type !== \"INSTANCE\" && node.type !== \"COMPONENT\") return null;\n\n const interactiveType = getStatefulComponentType(node);\n if (!interactiveType) return null;\n\n const expectedStates = EXPECTED_STATES[interactiveType];\n if (!expectedStates) return null;\n\n const seen = getSeen(context);\n const nodePath = context.path.join(\" > \");\n\n for (const state of expectedStates) {\n const dedupeKey = `${node.componentId ?? node.id}:${state}`;\n if (seen.has(dedupeKey)) continue;\n\n const pattern = STATE_PATTERNS[state];\n\n // Check variant properties on instance\n if (hasStateInVariantProps(node, pattern)) continue;\n\n // Check variant properties on component master (fetched definitions)\n if (hasStateInComponentMaster(node, context, pattern)) continue;\n\n // Missing state — report first missing one\n seen.add(dedupeKey);\n return {\n ruleId: missingInteractionStateDef.id,\n subType: state,\n nodeId: node.id,\n nodePath,\n ...missingInteractionStateMsg[state](node.name),\n };\n }\n\n return null;\n};\n\nexport const missingInteractionState = defineRule({\n definition: missingInteractionStateDef,\n check: missingInteractionStateCheck,\n});\n\n// ============================================\n// missing-prototype\n// ============================================\n\n/** Interactive types that need click prototype */\nconst PROTOTYPE_TYPES: Record<StatefulComponentType, MissingPrototypeSubType> = {\n button: \"button\",\n link: \"navigation\",\n tab: \"tab\",\n input: \"input\",\n toggle: \"toggle\",\n};\n\nfunction getPrototypeSubType(node: AnalysisNode): MissingPrototypeSubType | null {\n // Check overlay/carousel first — select/dropdown are classified as \"input\" in\n // STATEFUL_PATTERNS but need \"overlay\" subType for prototype checks\n if (isOverlayNode(node)) return \"overlay\";\n if (isCarouselNode(node)) return \"carousel\";\n const interactiveType = getStatefulComponentType(node);\n if (interactiveType) {\n const mapped = PROTOTYPE_TYPES[interactiveType];\n if (mapped) return mapped;\n }\n return null;\n}\n\nfunction hasInteractionTrigger(node: AnalysisNode, triggerType: string): boolean {\n if (!node.interactions || !Array.isArray(node.interactions)) return false;\n return node.interactions.some((interaction) => {\n const i = interaction as { trigger?: { type?: string } };\n return i.trigger?.type === triggerType;\n });\n}\n\n/** Check if node (or its component master) has any of the given trigger types */\nfunction hasAnyInteraction(node: AnalysisNode, context: RuleContext, triggers: string[]): boolean {\n for (const trigger of triggers) {\n if (hasInteractionTrigger(node, trigger)) return true;\n }\n // INSTANCE nodes don't inherit interactions from master — check master fallback\n if (node.componentId && context.file.componentDefinitions) {\n const master = context.file.componentDefinitions[node.componentId];\n if (master) {\n for (const trigger of triggers) {\n if (hasInteractionTrigger(master, trigger)) return true;\n }\n }\n }\n return false;\n}\n\n/** Trigger types to check per subType */\nconst PROTOTYPE_TRIGGERS: Record<string, string[]> = {\n carousel: [\"ON_CLICK\", \"ON_DRAG\"],\n};\n\nconst DEFAULT_TRIGGERS = [\"ON_CLICK\"];\n\nconst missingPrototypeDef: RuleDefinition = {\n id: \"missing-prototype\",\n name: \"Missing Prototype\",\n category: \"interaction\",\n why: \"Interactive elements without prototype interactions give AI no information about navigation or behavior\",\n impact: \"AI cannot generate interaction handlers, routing, or state changes — interactive elements become static\",\n fix: \"Add prototype interactions (ON_CLICK, ON_DRAG) to define navigation targets or state changes\",\n};\n\nconst SEEN_PROTO_KEY = \"missing-prototype:seen\";\n\nfunction getSeenProto(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_PROTO_KEY, () => new Set<string>());\n}\n\nconst missingPrototypeCheck: RuleCheckFn = (node, context) => {\n if (node.type !== \"INSTANCE\" && node.type !== \"COMPONENT\" && node.type !== \"FRAME\") return null;\n\n const subType = getPrototypeSubType(node);\n if (!subType) return null;\n\n // Already has relevant interaction (click, or drag for carousel)\n const triggers = PROTOTYPE_TRIGGERS[subType] ?? DEFAULT_TRIGGERS;\n if (hasAnyInteraction(node, context, triggers)) return null;\n\n // Dedup per componentId + subType\n const seen = getSeenProto(context);\n const dedupeKey = `${node.componentId ?? node.id}:${subType}`;\n if (seen.has(dedupeKey)) return null;\n seen.add(dedupeKey);\n\n return {\n ruleId: missingPrototypeDef.id,\n subType,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingPrototypeMsg[subType](node.name),\n };\n};\n\nexport const missingPrototype = defineRule({\n definition: missingPrototypeDef,\n check: missingPrototypeCheck,\n});\n","#!/usr/bin/env node\nimport { createRequire } from \"node:module\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { config } from \"dotenv\";\nimport { z } from \"zod\";\nimport { writeFile } from \"node:fs\";\nimport { exec } from \"node:child_process\";\nimport { analyzeFile } from \"../core/engine/rule-engine.js\";\nimport { loadFile, isJsonFile, isFixtureDir } from \"../core/engine/loader.js\";\nimport { calculateScores, buildResultJson } from \"../core/engine/scoring.js\";\nimport { generateHtmlReport } from \"../core/report-html/index.js\";\nimport { getReportsDir, ensureReportsDir } from \"../core/engine/config-store.js\";\nimport { getConfigsWithPreset, RULE_CONFIGS, type Preset } from \"../core/rules/rule-config.js\";\nimport { loadConfigFile, mergeConfigs } from \"../core/rules/config-loader.js\";\nimport { ruleRegistry } from \"../core/rules/rule-registry.js\";\nimport type { RuleConfig, RuleId } from \"../core/contracts/rule.js\";\nimport { initMonitoring, trackEvent, trackError, shutdownMonitoring, EVENTS } from \"../core/monitoring/index.js\";\nimport { POSTHOG_API_KEY as BUILTIN_PH_KEY, SENTRY_DSN as BUILTIN_SENTRY_DSN } from \"../core/monitoring/keys.js\";\nimport { getTelemetryEnabled, getPosthogApiKey, getSentryDsn, getDeviceId } from \"../core/engine/config-store.js\";\n\n// Load .env for FIGMA_TOKEN (quiet: suppress dotenv's stdout banner — MCP uses stdout for JSON-RPC)\nconfig({ quiet: true });\n\n// Import rules to register them\nimport \"../core/rules/index.js\";\n\nconst require = createRequire(import.meta.url);\nconst pkg = require(\"../../package.json\") as { version: string };\n\nconst server = new McpServer({\n name: \"canicode\",\n version: pkg.version,\n});\n\nserver.tool(\n \"analyze\",\n `Analyze a Figma design for development-friendliness and AI-friendliness.\n\nProvide a Figma URL or fixture path via the input parameter. Requires FIGMA_TOKEN env var or the token parameter for live Figma URLs.`,\n {\n input: z.string().describe(\"Figma URL or local fixture path. Requires FIGMA_TOKEN for live URLs.\"),\n token: z.string().optional().describe(\"Figma API token (falls back to FIGMA_TOKEN env var)\"),\n preset: z.enum([\"relaxed\", \"dev-friendly\", \"ai-ready\", \"strict\"]).optional().describe(\"Analysis preset\"),\n targetNodeId: z.string().optional().describe(\"Scope analysis to a specific node ID\"),\n configPath: z.string().optional().describe(\"Path to config JSON file for rule overrides\"),\n },\n {\n readOnlyHint: false,\n destructiveHint: false,\n openWorldHint: true,\n title: \"Analyze Figma Design\",\n },\n async ({ input, token, preset, targetNodeId, configPath }) => {\n trackEvent(EVENTS.MCP_TOOL_CALLED, { tool: \"analyze\" });\n try {\n // Fetch via REST API or load from fixture\n const { file, nodeId } = await loadFile(input, token);\n\n const effectiveNodeId = targetNodeId ?? nodeId;\n\n let configs: Record<string, RuleConfig> = preset\n ? { ...getConfigsWithPreset(preset as Preset) }\n : { ...RULE_CONFIGS };\n\n if (configPath) {\n const configFile = await loadConfigFile(configPath);\n configs = mergeConfigs(configs, configFile);\n }\n\n const result = analyzeFile(file, {\n configs: configs as Record<RuleId, RuleConfig>,\n ...(effectiveNodeId ? { targetNodeId: effectiveNodeId } : {}),\n });\n\n const scores = calculateScores(result, configs as Record<RuleId, RuleConfig>);\n\n // Generate HTML report (with Figma token for comment buttons)\n const figmaToken = token ?? process.env[\"FIGMA_TOKEN\"];\n const html = generateHtmlReport(file, result, scores, { figmaToken });\n\n // Save report to disk\n const now = new Date();\n const ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}-${String(now.getHours()).padStart(2, \"0\")}-${String(now.getMinutes()).padStart(2, \"0\")}`;\n ensureReportsDir();\n const reportPath = `${getReportsDir()}/report-${ts}-${file.fileKey}.html`;\n await new Promise<void>((resolve, reject) => {\n writeFile(reportPath, html, \"utf-8\", (err) => {\n if (err) reject(err);\n else resolve();\n });\n });\n\n // Open report in browser\n const openCmd = process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"start\" : \"xdg-open\";\n exec(`${openCmd} \"${reportPath}\"`);\n\n trackEvent(EVENTS.ANALYSIS_COMPLETED, {\n nodeCount: result.nodeCount,\n issueCount: result.issues.length,\n grade: scores.overall.grade,\n percentage: scores.overall.percentage,\n source: isJsonFile(input) || isFixtureDir(input) ? \"fixture\" : \"figma\",\n });\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(buildResultJson(file.name, result, scores, { fileKey: file.fileKey }), null, 2),\n },\n ],\n };\n } catch (error) {\n trackError(\n error instanceof Error ? error : new Error(String(error)),\n { tool: \"analyze\" },\n );\n trackEvent(EVENTS.ANALYSIS_FAILED, {\n error: error instanceof Error ? error.message : String(error),\n });\n return {\n content: [\n {\n type: \"text\" as const,\n text: `Error: ${error instanceof Error ? error.message : String(error)}`,\n },\n ],\n isError: true,\n };\n }\n },\n);\n\nserver.tool(\n \"list-rules\",\n \"List all available analysis rules with their current configuration\",\n {},\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n title: \"List Analysis Rules\",\n },\n async () => {\n const rules = ruleRegistry.getAll().map((rule) => {\n const config =\n RULE_CONFIGS[rule.definition.id as keyof typeof RULE_CONFIGS];\n return {\n id: rule.definition.id,\n name: rule.definition.name,\n category: rule.definition.category,\n severity: config?.severity,\n score: config?.score,\n enabled: config?.enabled,\n why: rule.definition.why,\n };\n });\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(rules, null, 2),\n },\n ],\n };\n },\n);\n\nserver.tool(\n \"version\",\n \"Get the current canicode version. Use this when the user asks what version is installed.\",\n {},\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n title: \"Get Version\",\n },\n async () => ({\n content: [{ type: \"text\" as const, text: `canicode v${pkg.version}` }],\n }),\n);\n\nserver.tool(\n \"docs\",\n `Get documentation for CanICode.\n\nAvailable topics:\n- setup: Installation and token configuration\n- rules: All rule IDs with default scores and severity\n- config: Config overrides (scores, severity, node exclusions, thresholds)\n- visual-compare: Pixel-level comparison between Figma and AI-generated code\n- design-tree: Generate DOM-like design tree from fixture for AI code generation\n- all: Full customization guide\n\nUse this when the user asks about how to use canicode, configuration, rules, visual comparison, or any feature.`,\n {\n topic: z.enum([\"all\", \"setup\", \"rules\", \"config\", \"visual-compare\", \"design-tree\"]).optional()\n .describe(\"Topic to retrieve. Default: all\"),\n },\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n title: \"Get Documentation\",\n },\n async ({ topic }) => {\n const selectedTopic = topic ?? \"all\";\n\n // Inline topics (not from CUSTOMIZATION.md)\n const inlineTopics: Record<string, string> = {\n \"setup\": `# Setup\n\n## CLI\n\\`\\`\\`bash\nnpm install -g canicode\ncanicode init --token figd_xxxxxxxxxxxxx\n\\`\\`\\`\n\nGet your token: Figma → Settings → Security → Personal access tokens → Generate new token\n\n## MCP Server (Claude Code / Cursor / Claude Desktop)\n\\`\\`\\`bash\nclaude mcp add canicode -e FIGMA_TOKEN=figd_xxxxxxxxxxxxx -- npx -y -p canicode canicode-mcp\n\\`\\`\\`\n\nRequires FIGMA_TOKEN for live Figma URL analysis.`,\n\n \"visual-compare\": `# Visual Compare\n\nPixel-level comparison between Figma design and AI-generated code.\n\n## Usage\n\\`\\`\\`bash\ncanicode visual-compare ./index.html --figma-url 'https://www.figma.com/design/ABC/File?node-id=1-234'\n\\`\\`\\`\n\n## Options\n| Option | Default | Description |\n|--------|---------|-------------|\n| --figma-url <url> | (required) | Figma URL with node-id |\n| --token <token> | FIGMA_TOKEN env | Figma API token |\n| --output <dir> | /tmp/canicode-visual-compare | Output directory |\n| --width <px> | (inferred from Figma PNG ÷ scale) | Logical viewport width in CSS px |\n| --height <px> | (inferred from Figma PNG ÷ scale) | Logical viewport height in CSS px |\n| --figma-scale <n> | 2 | Figma export scale (matches @2x fixture PNGs) |\n\nViewport and device pixel ratio are auto-inferred from the Figma PNG dimensions and export scale. Override only when needed.\n\n## Output Files\n/tmp/canicode-visual-compare/\n figma.png — Figma screenshot (at export scale, default @2x)\n code.png — Playwright render of your HTML\n diff.png — Pixel diff (red = different)\n\n## JSON Output (stdout)\n{\n \"similarity\": 87,\n \"diffPixels\": 1340,\n \"totalPixels\": 102400,\n \"width\": 800, \"height\": 600,\n \"figmaScreenshot\": \"...\", \"codeScreenshot\": \"...\", \"diff\": \"...\"\n}\n\n## How It Works\n1. Fetches Figma screenshot via REST API (scale=2)\n2. Reads screenshot dimensions\n3. Renders HTML with Playwright at same viewport size\n4. Compares pixel-by-pixel with pixelmatch (threshold: 0.1)\n\n## Requirements\n- npx playwright install chromium\n- Figma API token with read access`,\n\n \"design-tree\": `# Design Tree\n\nGenerate a DOM-like design tree from a Figma fixture. Converts the node tree to a concise text format with inline CSS styles — 50-100x smaller than raw JSON.\n\n## Usage\n\\`\\`\\`bash\ncanicode design-tree ./fixtures/design\ncanicode design-tree ./fixtures/design --output tree.txt\ncanicode design-tree \"https://www.figma.com/design/ABC/File?node-id=1-234\"\n\\`\\`\\`\n\n## Output Format\nEach node = one line with name, type, dimensions, followed by CSS-ready styles:\n\\`\\`\\`\nHero Form (INSTANCE, 375x960)\n style: display: flex; flex-direction: column; gap: 32px; padding: 160px 24px; background: #F5F5F5\n Title (TEXT, 117x58)\n style: font-family: \"Inter\"; font-weight: 700; font-size: 48px; color: #2C2C2C; text: \"Title\"\n\\`\\`\\`\n\n## Use Cases\n- AI code generation — feed this to an LLM instead of raw 250KB fixture JSON\n- Calibration pipeline — Converter uses this for accurate code reproduction\n- Debugging — quickly see the design structure and styles`,\n };\n\n // Check inline topics first\n if (selectedTopic in inlineTopics) {\n return {\n content: [{ type: \"text\" as const, text: `canicode v${pkg.version}\\n\\n${inlineTopics[selectedTopic]}` }],\n };\n }\n\n // Fall back to CUSTOMIZATION.md for config/rules/all\n const { readFile } = await import(\"node:fs/promises\");\n const { resolve, dirname } = await import(\"node:path\");\n const { fileURLToPath } = await import(\"node:url\");\n\n try {\n const __dirname = dirname(fileURLToPath(import.meta.url));\n const docPath = resolve(__dirname, \"../../docs/CUSTOMIZATION.md\");\n let content: string;\n\n try {\n content = await readFile(docPath, \"utf-8\");\n } catch {\n const altPath = resolve(__dirname, \"../docs/CUSTOMIZATION.md\");\n content = await readFile(altPath, \"utf-8\");\n }\n\n if (selectedTopic !== \"all\") {\n const sections: Record<string, string> = {\n \"config\": \"## Config Overrides\",\n \"rules\": \"### All Rule IDs\",\n };\n const header = sections[selectedTopic];\n if (header) {\n const startIdx = content.indexOf(header);\n if (startIdx !== -1) {\n const nextH2 = content.indexOf(\"\\n## \", startIdx + header.length);\n content = nextH2 !== -1\n ? content.slice(startIdx, nextH2)\n : content.slice(startIdx);\n }\n }\n }\n\n return {\n content: [{ type: \"text\" as const, text: `canicode v${pkg.version}\\n\\n${content}` }],\n };\n } catch {\n return {\n content: [{ type: \"text\" as const, text: \"Documentation not found. See: https://github.com/let-sunny/canicode\" }],\n isError: true,\n };\n }\n },\n);\n\nserver.tool(\n \"visual-compare\",\n `Compare AI-generated code against a Figma design at the pixel level.\n\nTakes an HTML file path and a Figma URL, renders the HTML with Playwright,\nfetches the Figma screenshot, and computes pixel-level similarity using pixelmatch.\n\nReturns similarity percentage (0-100%), diff pixel count, and paths to\nthe Figma screenshot, code screenshot, and diff image.\n\nLogical viewport and device pixel ratio are inferred from the Figma PNG export scale (default 2×) so code.png matches figma.png pixels.\n\nRequires: Playwright with Chromium installed, Figma API token.`,\n {\n codePath: z.string().describe(\"Path to the HTML file to render and compare\"),\n figmaUrl: z.string().describe(\"Figma URL with node-id (e.g., https://www.figma.com/design/ABC/File?node-id=1-234)\"),\n token: z.string().optional().describe(\"Figma API token (falls back to FIGMA_TOKEN env var)\"),\n outputDir: z.string().optional().describe(\"Output directory for screenshots (default: /tmp/canicode-visual-compare)\"),\n figmaExportScale: z.number().int().min(1).max(4).optional().describe(\"Figma export scale (default 2, matches @2x fixture PNGs)\"),\n },\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: true,\n title: \"Visual Compare\",\n },\n async ({ codePath, figmaUrl, token, outputDir, figmaExportScale }) => {\n try {\n const { visualCompare } = await import(\"../core/comparison/visual-compare.js\");\n const figmaToken = token ?? process.env[\"FIGMA_TOKEN\"];\n if (!figmaToken) {\n return {\n content: [{ type: \"text\" as const, text: \"Error: Figma token required. Provide via token parameter or FIGMA_TOKEN env var.\" }],\n isError: true,\n };\n }\n\n const result = await visualCompare({\n figmaUrl,\n figmaToken,\n codePath,\n outputDir,\n ...(figmaExportScale !== undefined ? { figmaExportScale } : {}),\n });\n\n return {\n content: [{\n type: \"text\" as const,\n text: JSON.stringify({\n similarity: result.similarity,\n diffPixels: result.diffPixels,\n totalPixels: result.totalPixels,\n width: result.width,\n height: result.height,\n figmaScreenshot: result.figmaScreenshotPath,\n codeScreenshot: result.codeScreenshotPath,\n diff: result.diffPath,\n }, null, 2),\n }],\n };\n } catch (error) {\n return {\n content: [{ type: \"text\" as const, text: `Error: ${error instanceof Error ? error.message : String(error)}` }],\n isError: true,\n };\n }\n },\n);\n\nasync function main() {\n const monitoringConfig: Parameters<typeof initMonitoring>[0] = {\n environment: \"mcp\",\n version: pkg.version,\n enabled: getTelemetryEnabled(),\n };\n const phKey = getPosthogApiKey() || BUILTIN_PH_KEY;\n if (phKey) monitoringConfig.posthogApiKey = phKey;\n const sDsn = getSentryDsn() || BUILTIN_SENTRY_DSN;\n if (sDsn) monitoringConfig.sentryDsn = sDsn;\n monitoringConfig.distinctId = getDeviceId();\n initMonitoring(monitoringConfig);\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n\nprocess.on(\"beforeExit\", () => {\n shutdownMonitoring();\n});\n\nmain().catch(console.error);\n"]}
1
+ {"version":3,"sources":["../../src/core/comparison/visual-compare-helpers.ts","../../src/core/comparison/visual-compare.ts","../../src/core/contracts/category.ts","../../src/core/contracts/severity.ts","../../src/core/contracts/rule.ts","../../src/core/rules/rule-config.ts","../../src/core/rules/rule-registry.ts","../../src/core/engine/rule-engine.ts","../../src/core/adapters/figma-client.ts","../../src/core/adapters/figma-transformer.ts","../../src/core/adapters/component-resolver.ts","../../src/core/contracts/figma-node.ts","../../src/core/adapters/figma-file-loader.ts","../../src/core/adapters/figma-url-parser.ts","../../src/core/engine/config-store.ts","../../src/core/engine/loader.ts","../../package.json","../../src/core/engine/scoring.ts","../../src/core/ui-constants.ts","../../src/core/ui-helpers.ts","../../src/core/report-html/render.ts","../../src/core/report-html/index.ts","../../src/core/rules/config-loader.ts","../../src/core/monitoring/events.ts","../../src/core/monitoring/capture.ts","../../src/core/monitoring/index.ts","../../src/core/monitoring/keys.ts","../../src/core/rules/node-semantics.ts","../../src/core/rules/rule-exceptions.ts","../../src/core/rules/rule-messages.ts","../../src/core/rules/structure/index.ts","../../src/core/rules/token/index.ts","../../src/core/rules/component/index.ts","../../src/core/rules/naming/index.ts","../../src/core/rules/interaction/index.ts","../../src/mcp/server.ts"],"names":["resolve","statSync","readFileSync","width","height","mkdirSync","dirname","writeFileSync","existsSync","PNG","z","config","BATCH_SIZE","join","response","file","componentDefs","interactionDests","esc","readFile","version","require","visualCompare"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAwBO,SAAS,iBAAiB,QAAA,EAA0B;AACzD,EAAA,OAAO,eAAA,CAAgB,QAAA,CAAS,QAAQ,CAAA,GAAI,CAAA,GAAI,CAAA;AAClD;AAoBO,SAAS,iBAAA,CAAkB,OAAA,EAAiB,MAAA,EAAgB,KAAA,EAAuB;AAExF,EAAA,MAAM,UAAA,GAAa,MAAA,CA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AA,GAAO,cAAa,IAAK,UAAA;AAC/B,mBAA2B,SAAA,GAAY,IAAA;AACvC,EAAA,gBAAA,CAAiB,aAAa,WAAA,EAAY;AAC1C,EAAA,cAAA,CAAe,gBAAgB,CAAA;AAE/B,EAAA,MAAM,SAAA,GAAY,IAAI,oBAAA,EAAqB;AAC3C,EAAA,MAAM,MAAA,CAAO,QAAQ,SAAS,CAAA;AAChC;AAEA,OAAA,CAAQ,EAAA,CAAG,cAAc,MAAM;AAC7B,EAAA,kBAAA,EAAmB;AACrB,CAAC,CAAA;AAED,IAAA,EAAK,CAAE,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA","file":"server.js","sourcesContent":["/**\n * Pure helper functions extracted from visual-compare.ts.\n * These have no side effects beyond file I/O and can be tested directly.\n */\n\nimport { writeFileSync, readFileSync, mkdirSync, statSync } from \"node:fs\";\nimport { resolve, dirname } from \"node:path\";\nimport pixelmatch from \"pixelmatch\";\nimport { PNG } from \"pngjs\";\n\n/** Directory used for caching Figma screenshots. */\nexport const FIGMA_CACHE_DIR = \"/tmp/canicode-figma-cache\";\n\n/**\n * Known @1x screenshot widths from fixture convention.\n * Screenshots at these widths are captured at 1x scale (pixel width = logical width).\n * All other widths are assumed @2x (e.g., 2400px PNG = 1200px logical).\n */\nexport const KNOWN_1X_WIDTHS = [1920, 768];\n\n/**\n * Infer the export scale of a fixture screenshot based on its pixel width.\n * Uses KNOWN_1X_WIDTHS convention: 1920/768 = @1x, others = @2x.\n */\nexport function inferExportScale(pngWidth: number): number {\n return KNOWN_1X_WIDTHS.includes(pngWidth) ? 1 : 2;\n}\n\n/** Cache time-to-live: 1 hour. */\nexport const FIGMA_CACHE_TTL_MS = 60 * 60 * 1000;\n\n/**\n * Tolerance for detecting integer scale factors (@2x, @3x).\n * Broader tolerance because render/rounding errors accumulate at higher scales.\n */\nexport const SCALE_ROUNDING_TOLERANCE = 0.08;\n\n/**\n * Tolerance for detecting 1x (unity) scale.\n * Tighter to avoid false positives — misidentifying a scaled PNG as 1x.\n */\nexport const UNITY_SCALE_TOLERANCE = 0.02;\n\n/**\n * Get the cache path for a given fileKey + nodeId combination.\n */\nexport function getFigmaCachePath(fileKey: string, nodeId: string, scale: number): string {\n // Sanitize nodeId for use as filename (replace : with -)\n const safeNodeId = nodeId.replace(/:/g, \"-\");\n return resolve(FIGMA_CACHE_DIR, `${fileKey}_${safeNodeId}@${scale}x.png`);\n}\n\n/**\n * Check if a cached Figma screenshot exists and is still fresh (within TTL).\n */\nexport function isCacheFresh(cachePath: string): boolean {\n try {\n const stats = statSync(cachePath);\n return Date.now() - stats.mtimeMs < FIGMA_CACHE_TTL_MS;\n } catch {\n // File doesn't exist or was removed between check and stat (TOCTOU safe)\n return false;\n }\n}\n\n/**\n * Infer device pixel ratio so the Playwright screenshot matches Figma PNG pixel dimensions.\n */\nexport function inferDeviceScaleFactor(\n pngW: number,\n pngH: number,\n logicalW: number,\n logicalH: number,\n fallback: number,\n): number {\n if (logicalW <= 0 || logicalH <= 0) return 1;\n const sx = pngW / logicalW;\n const sy = pngH / logicalH;\n const rounded = Math.round((sx + sy) / 2);\n if (rounded >= 2 && Math.abs(sx - rounded) < SCALE_ROUNDING_TOLERANCE && Math.abs(sy - rounded) < SCALE_ROUNDING_TOLERANCE) {\n return rounded;\n }\n if (Math.abs(sx - 1) < UNITY_SCALE_TOLERANCE && Math.abs(sy - 1) < UNITY_SCALE_TOLERANCE) return 1;\n return fallback >= 2 ? fallback : Math.max(1, Math.round(sx));\n}\n\n/**\n * Pad a PNG to target dimensions with a high-contrast fill color (magenta #FF00FF).\n * Unlike resize, padding preserves original pixels 1:1 and guarantees that\n * any size difference is counted as mismatched pixels by pixelmatch.\n *\n * Note: If both images contain magenta in the padded area, those pixels\n * will match — extremely rare in real designs but theoretically possible.\n */\nexport function padPng(png: PNG, targetWidth: number, targetHeight: number): PNG {\n const padded = new PNG({ width: targetWidth, height: targetHeight });\n // Fill entire canvas with magenta (FF00FF) — guaranteed to differ from any real content\n for (let i = 0; i < padded.data.length; i += 4) {\n padded.data[i] = 255; // R\n padded.data[i + 1] = 0; // G\n padded.data[i + 2] = 255; // B\n padded.data[i + 3] = 255; // A\n }\n // Copy original pixels into top-left corner\n for (let y = 0; y < png.height; y++) {\n for (let x = 0; x < png.width; x++) {\n const srcIdx = (y * png.width + x) * 4;\n const dstIdx = (y * targetWidth + x) * 4;\n padded.data[dstIdx] = png.data[srcIdx]!;\n padded.data[dstIdx + 1] = png.data[srcIdx + 1]!;\n padded.data[dstIdx + 2] = png.data[srcIdx + 2]!;\n padded.data[dstIdx + 3] = png.data[srcIdx + 3]!;\n }\n }\n return padded;\n}\n\n/** Options for screenshot comparison. */\nexport interface CompareOptions {\n /** How to handle size mismatches: \"pad\" (magenta fill) or \"crop\" (min dimensions). Default: \"pad\". */\n sizeMismatch?: \"pad\" | \"crop\";\n /** pixelmatch threshold (0-1). Default: 0.1. */\n threshold?: number;\n}\n\n/**\n * Crop a PNG to target dimensions (top-left corner preserved).\n */\nexport function cropPng(png: PNG, targetWidth: number, targetHeight: number): PNG {\n const cropped = new PNG({ width: targetWidth, height: targetHeight });\n for (let y = 0; y < targetHeight; y++) {\n png.data.copy(cropped.data, y * targetWidth * 4, y * png.width * 4, y * png.width * 4 + targetWidth * 4);\n }\n return cropped;\n}\n\n/**\n * Compare two PNG files using pixelmatch.\n */\nexport function compareScreenshots(\n path1: string,\n path2: string,\n diffOutputPath: string,\n options?: CompareOptions,\n): { similarity: number; diffPixels: number; totalPixels: number; width: number; height: number } {\n const sizeMismatch = options?.sizeMismatch ?? \"pad\";\n const threshold = options?.threshold ?? 0.1;\n const raw1 = PNG.sync.read(readFileSync(path1));\n const raw2 = PNG.sync.read(readFileSync(path2));\n\n let img1: PNG = raw1;\n let img2: PNG = raw2;\n\n // Size mismatch — normalize to same dimensions\n if (raw1.width !== raw2.width || raw1.height !== raw2.height) {\n if (sizeMismatch === \"crop\") {\n const width = Math.min(raw1.width, raw2.width);\n const height = Math.min(raw1.height, raw2.height);\n img1 = cropPng(raw1, width, height);\n img2 = cropPng(raw2, width, height);\n } else {\n const width = Math.max(raw1.width, raw2.width);\n const height = Math.max(raw1.height, raw2.height);\n img1 = padPng(raw1, width, height);\n img2 = padPng(raw2, width, height);\n }\n }\n\n const { width, height } = img1;\n const diff = new PNG({ width, height });\n const diffPixels = pixelmatch(img1.data, img2.data, diff.data, width, height, { threshold });\n\n mkdirSync(dirname(diffOutputPath), { recursive: true });\n writeFileSync(diffOutputPath, PNG.sync.write(diff));\n\n const totalPixels = width * height;\n const similarity = diffPixels === 0 ? 100 : Math.floor((1 - diffPixels / totalPixels) * 100);\n\n return { similarity, diffPixels, totalPixels, width, height };\n}\n\n// ── Root width expansion (for responsive comparison) ─────────────────────\n\n/**\n * Replace fixed root-element widths in HTML with fluid values so the layout\n * can expand to fill a wider viewport.\n *\n * Targets the first CSS rule that sets a pixel `width` on the root container\n * (commonly `.root`, `body > div`, etc.) and replaces it with `width: 100%`.\n * Also removes `min-width` pixel constraints.\n *\n * Originally from `src/experiments/ablation/run-condition.ts`.\n */\nexport function expandRootWidth(html: string): string {\n const styleMatch = html.match(/<style[\\s\\S]*?<\\/style>/i);\n if (!styleMatch) return html;\n\n const style = styleMatch[0];\n // Find the first CSS rule block (the root element's rule)\n const firstRuleMatch = style.match(/([^{}]*\\{)([^}]*)\\}/);\n if (!firstRuleMatch) return html;\n\n const rulePrefix = firstRuleMatch[1]!; // e.g. \".root {\"\n const ruleBody = firstRuleMatch[2]!; // e.g. \" width: 375px; min-width: 375px; \"\n\n // Replace width and min-width only inside the first rule\n const newBody = ruleBody\n .replace(/(?<![-\\w])width:\\s*\\d+px/, \"width: 100%\")\n .replace(/min-width:\\s*\\d+px/g, \"min-width: 0\");\n\n const newRule = `${rulePrefix}${newBody}}`;\n const newStyle = style.replace(firstRuleMatch[0], newRule);\n return html.replace(style, newStyle);\n}\n\n// ── Code metrics (shared with ablation helpers) ─────────────────────────\n\n/** Count unique CSS class selectors in an HTML string's <style> block. */\nexport function countCssClasses(html: string): number {\n const styleMatch = html.match(/<style[\\s\\S]*?<\\/style>/i);\n if (!styleMatch) return 0;\n const classes = styleMatch[0].match(/\\.[a-zA-Z][\\w-]*\\s*[{,:]/g);\n return new Set(classes?.map((c) => c.replace(/\\s*[{,:]$/, \"\"))).size;\n}\n\n/** Count unique CSS custom property definitions in an HTML string's <style> block. */\nexport function countCssVariables(html: string): number {\n const styleMatch = html.match(/<style[\\s\\S]*?<\\/style>/i);\n if (!styleMatch) return 0;\n const vars = styleMatch[0].match(/--[\\w-]+\\s*:/g);\n return new Set(vars?.map((v) => v.replace(/\\s*:$/, \"\"))).size;\n}\n\n/** Compute code metrics from an HTML string. */\nexport function computeCodeMetrics(html: string): {\n htmlBytes: number;\n htmlLines: number;\n cssClassCount: number;\n cssVariableCount: number;\n} {\n return {\n htmlBytes: Buffer.byteLength(html, \"utf-8\"),\n htmlLines: html.split(\"\\n\").length,\n cssClassCount: countCssClasses(html),\n cssVariableCount: countCssVariables(html),\n };\n}\n","/**\n * Visual comparison: renders HTML code with Playwright, fetches Figma screenshot,\n * and computes pixel-level similarity using pixelmatch.\n */\n\nimport { writeFileSync, readFileSync, mkdirSync, existsSync, copyFileSync } from \"node:fs\";\nimport { resolve, dirname } from \"node:path\";\nimport { PNG } from \"pngjs\";\nimport {\n FIGMA_CACHE_DIR,\n getFigmaCachePath,\n isCacheFresh,\n inferDeviceScaleFactor,\n inferExportScale,\n compareScreenshots,\n expandRootWidth,\n type CompareOptions,\n} from \"./visual-compare-helpers.js\";\n\n/** Result of a visual comparison between Figma design and rendered code. */\nexport interface VisualCompareResult {\n similarity: number;\n diffPixels: number;\n totalPixels: number;\n width: number;\n height: number;\n figmaScreenshotPath: string;\n codeScreenshotPath: string;\n diffPath: string;\n}\n\n/** Options for the visual comparison pipeline. */\nexport interface VisualCompareOptions {\n figmaUrl: string;\n figmaToken: string;\n codePath: string;\n outputDir?: string | undefined;\n /**\n * Logical CSS viewport (CSS pixels). Omit a dimension to infer from the Figma PNG\n * using `figmaExportScale`. When the whole object is omitted, both dimensions are inferred.\n */\n viewport?: { width?: number; height?: number } | undefined;\n /**\n * Figma Images API `scale` and assumed scale for fixture `figma.png` (e.g. from `save-fixture`).\n * Default 2 matches REST exports and avoids comparing a @2x PNG against a 1× Playwright capture.\n */\n figmaExportScale?: number | undefined;\n /**\n * Path to a local Figma screenshot file. When provided, skips URL-based fetch\n * and uses this file directly as the ground truth. Useful for responsive comparison\n * where multiple fixture screenshots exist at different viewports.\n */\n figmaScreenshotPath?: string | undefined;\n /**\n * When true, replace the root element's fixed pixel width with `width: 100%`\n * before rendering. This allows the layout to expand to fill the viewport,\n * which is needed for responsive comparison (e.g., 375px design rendered at 768px).\n */\n expandRoot?: boolean | undefined;\n}\n\n/**\n * Fetch Figma node screenshot via REST API, with file-based caching.\n * Cache key: fileKey + nodeId. Cache location: /tmp/canicode-figma-cache/. TTL: 1 hour.\n */\nasync function fetchFigmaScreenshot(\n fileKey: string,\n nodeId: string,\n token: string,\n outputPath: string,\n scale: number,\n): Promise<void> {\n const cachePath = getFigmaCachePath(fileKey, nodeId, scale);\n\n // Return cached version if fresh\n if (isCacheFresh(cachePath)) {\n mkdirSync(dirname(outputPath), { recursive: true });\n copyFileSync(cachePath, outputPath);\n return;\n }\n\n const res = await fetch(\n `https://api.figma.com/v1/images/${fileKey}?ids=${nodeId}&format=png&scale=${scale}`,\n { headers: { \"X-Figma-Token\": token } },\n );\n if (!res.ok) throw new Error(`Figma Images API: ${res.status} ${res.statusText}`);\n\n const data = (await res.json()) as { images: Record<string, string | null> };\n const imgUrl = data.images[nodeId];\n if (!imgUrl) throw new Error(`No image returned for node ${nodeId}`);\n\n const imgRes = await fetch(imgUrl);\n if (!imgRes.ok) throw new Error(`Failed to download Figma screenshot: ${imgRes.status}`);\n\n const buffer = Buffer.from(await imgRes.arrayBuffer());\n\n // Write to output path\n mkdirSync(dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, buffer);\n\n // Save to cache\n mkdirSync(FIGMA_CACHE_DIR, { recursive: true });\n writeFileSync(cachePath, buffer);\n}\n\n/**\n * Render HTML file with Playwright and take a screenshot.\n * @param deviceScaleFactor - Pass 2 when the Figma reference is @2x and `viewport` is logical CSS size.\n */\nexport async function renderCodeScreenshot(\n codePath: string,\n outputPath: string,\n logicalViewport: { width: number; height: number },\n deviceScaleFactor: number = 1,\n): Promise<void> {\n // Dynamic import — playwright is an optional dependency\n const { chromium } = await import(\"playwright\");\n const browser = await chromium.launch();\n try {\n const context = await browser.newContext({\n viewport: logicalViewport,\n deviceScaleFactor,\n });\n const page = await context.newPage();\n\n await page.goto(`file://${resolve(codePath)}`, {\n waitUntil: \"networkidle\",\n timeout: 30_000,\n });\n await page.waitForTimeout(1000);\n\n // Capture only the first child element (the design root), not the full body/viewport\n const root = page.locator(\"body > *:first-child\");\n if (await root.count() > 0) {\n await root.screenshot({ path: outputPath });\n } else {\n await page.screenshot({ path: outputPath });\n }\n } finally {\n await browser.close();\n }\n}\n\n/**\n * Run full visual comparison pipeline.\n */\nexport async function visualCompare(options: VisualCompareOptions): Promise<VisualCompareResult> {\n const outputDir = options.outputDir ?? \"/tmp/canicode-visual-compare\";\n const figmaScreenshotPath = resolve(outputDir, \"figma.png\");\n const codeScreenshotPath = resolve(outputDir, \"code.png\");\n const diffPath = resolve(outputDir, \"diff.png\");\n\n // Parse Figma URL\n const urlMatch = options.figmaUrl.match(/\\/design\\/([^/]+)\\//);\n const fileKey = urlMatch?.[1];\n if (!fileKey) throw new Error(\"Invalid Figma URL — could not extract file key\");\n\n const nodeIdMatch = options.figmaUrl.match(/node-id=([^&\\s]+)/);\n const nodeId = nodeIdMatch?.[1]?.replace(/-/g, \":\");\n if (!nodeId) throw new Error(\"Invalid Figma URL — missing node-id\");\n\n // Step 1: Figma screenshot — use local file if provided, otherwise fetch via API\n if (options.figmaScreenshotPath) {\n if (!existsSync(options.figmaScreenshotPath)) {\n throw new Error(`Figma screenshot not found: ${options.figmaScreenshotPath}`);\n }\n mkdirSync(dirname(figmaScreenshotPath), { recursive: true });\n copyFileSync(options.figmaScreenshotPath, figmaScreenshotPath);\n } else if (!existsSync(figmaScreenshotPath)) {\n const fetchScale = options.figmaExportScale ?? 2;\n await fetchFigmaScreenshot(fileKey, nodeId, options.figmaToken, figmaScreenshotPath, fetchScale);\n if (!existsSync(figmaScreenshotPath)) {\n throw new Error(`Figma screenshot was not created at expected path: ${figmaScreenshotPath}`);\n }\n }\n\n // Step 2: Logical viewport + deviceScaleFactor so code.png matches figma.png pixels (@2x, etc.)\n const figmaPng = PNG.sync.read(readFileSync(figmaScreenshotPath));\n // Auto-detect export scale from PNG width when using local screenshot (KNOWN_1X_WIDTHS convention)\n const exportScale = options.figmaExportScale ?? inferExportScale(figmaPng.width);\n const hasViewportOverride = options.viewport !== undefined;\n let logicalW: number;\n let logicalH: number;\n let deviceScaleFactor: number;\n\n if (!hasViewportOverride) {\n logicalW = Math.max(1, Math.round(figmaPng.width / exportScale));\n logicalH = Math.max(1, Math.round(figmaPng.height / exportScale));\n deviceScaleFactor = exportScale;\n } else {\n logicalW =\n options.viewport!.width ?? Math.max(1, Math.round(figmaPng.width / exportScale));\n logicalH =\n options.viewport!.height ?? Math.max(1, Math.round(figmaPng.height / exportScale));\n deviceScaleFactor = inferDeviceScaleFactor(\n figmaPng.width,\n figmaPng.height,\n logicalW,\n logicalH,\n exportScale,\n );\n }\n\n // Step 3: Render code screenshot at matching physical resolution\n let renderPath = options.codePath;\n if (options.expandRoot) {\n const originalHtml = readFileSync(resolve(options.codePath), \"utf-8\");\n const expandedHtml = expandRootWidth(originalHtml);\n renderPath = resolve(outputDir, \"code-expanded.html\");\n writeFileSync(renderPath, expandedHtml);\n }\n await renderCodeScreenshot(\n renderPath,\n codeScreenshotPath,\n { width: logicalW, height: logicalH },\n deviceScaleFactor,\n );\n\n // Validate both screenshots exist before comparing\n if (!existsSync(codeScreenshotPath)) {\n throw new Error(`Code screenshot was not created at expected path: ${codeScreenshotPath}`);\n }\n\n // Compare\n const result = compareScreenshots(figmaScreenshotPath, codeScreenshotPath, diffPath);\n\n return {\n ...result,\n figmaScreenshotPath,\n codeScreenshotPath,\n diffPath,\n };\n}\n\n/** Options for renderAndCompare. */\nexport interface RenderAndCompareOptions {\n /** How to handle size mismatches. Default: \"pad\". */\n sizeMismatch?: CompareOptions[\"sizeMismatch\"];\n /** Output file suffix (e.g. \"baseline\", \"stripped-layout\"). */\n suffix?: string;\n /** pixelmatch threshold. Default: 0.1. */\n threshold?: number;\n /** Replace root element's fixed width with 100% before rendering. */\n expandRoot?: boolean;\n}\n\n/**\n * Render HTML → screenshot, then compare against a Figma screenshot.\n * Handles export scale inference and size normalization.\n *\n * Extracted from ablation helpers to be shared by calibration + experiments.\n */\nexport async function renderAndCompare(\n htmlPath: string,\n figmaScreenshotPath: string,\n outputDir: string,\n options?: RenderAndCompareOptions,\n): Promise<{ similarity: number }> {\n const suffix = options?.suffix ?? \"output\";\n const sizeMismatch = options?.sizeMismatch ?? \"pad\";\n const threshold = options?.threshold;\n\n const figmaImage = PNG.sync.read(readFileSync(figmaScreenshotPath));\n const figmaWidth = figmaImage.width;\n const exportScale = inferExportScale(figmaWidth);\n const logicalW = Math.max(1, Math.round(figmaWidth / exportScale));\n const logicalH = Math.max(1, Math.round(figmaImage.height / exportScale));\n\n let renderHtmlPath = htmlPath;\n if (options?.expandRoot) {\n const originalHtml = readFileSync(resolve(htmlPath), \"utf-8\");\n const expandedHtml = expandRootWidth(originalHtml);\n renderHtmlPath = resolve(outputDir, `code-expanded-${suffix}.html`);\n writeFileSync(renderHtmlPath, expandedHtml);\n }\n const codePngPath = resolve(outputDir, `code-${suffix}.png`);\n await renderCodeScreenshot(renderHtmlPath, codePngPath, { width: logicalW, height: logicalH }, exportScale);\n\n const figmaCopyPath = resolve(outputDir, `figma-${suffix}.png`);\n copyFileSync(figmaScreenshotPath, figmaCopyPath);\n\n const diffPath = resolve(outputDir, `diff-${suffix}.png`);\n const compareOpts: CompareOptions = { sizeMismatch };\n if (threshold !== undefined) compareOpts.threshold = threshold;\n return compareScreenshots(figmaCopyPath, codePngPath, diffPath, compareOpts);\n}\n","import { z } from \"zod\";\n\nexport const CategorySchema = z.enum([\n \"pixel-critical\",\n \"responsive-critical\",\n \"code-quality\",\n \"token-management\",\n \"semantic\",\n \"interaction\",\n]);\n\nexport type Category = z.infer<typeof CategorySchema>;\n\nexport const CATEGORIES = CategorySchema.options;\n\nexport const CATEGORY_LABELS: Record<Category, string> = {\n \"pixel-critical\": \"Pixel Critical\",\n \"responsive-critical\": \"Responsive Critical\",\n \"code-quality\": \"Code Quality\",\n \"token-management\": \"Token Management\",\n \"semantic\": \"Semantic\",\n \"interaction\": \"Interaction\",\n};\n","import { z } from \"zod\";\n\nexport const SeveritySchema = z.enum([\n \"blocking\",\n \"risk\",\n \"missing-info\",\n \"suggestion\",\n]);\n\nexport type Severity = z.infer<typeof SeveritySchema>;\n\nexport const SEVERITY_WEIGHT: Record<Severity, number> = {\n blocking: 10,\n risk: 5,\n \"missing-info\": 2,\n suggestion: 1,\n};\n\nexport const SEVERITY_LABELS: Record<Severity, string> = {\n blocking: \"Blocking\",\n risk: \"Risk\",\n \"missing-info\": \"Missing Info\",\n suggestion: \"Suggestion\",\n};\n","import { z } from \"zod\";\nimport { CategorySchema, type Category } from \"./category.js\";\nimport { SeveritySchema } from \"./severity.js\";\nimport type { AnalysisFile, AnalysisNode } from \"./figma-node.js\";\n\n/**\n * Rule definition - static metadata (does not change)\n */\nexport const RuleDefinitionSchema = z.object({\n id: z.string(),\n name: z.string(),\n category: CategorySchema,\n why: z.string(),\n impact: z.string(),\n fix: z.string(),\n});\n\nexport type RuleDefinition = z.infer<typeof RuleDefinitionSchema>;\n\n/**\n * Rule config - adjustable settings (can be modified via presets)\n */\nexport const RuleConfigSchema = z.object({\n severity: SeveritySchema,\n score: z.number().int().max(0),\n depthWeight: z.number().min(1).max(2).optional(),\n enabled: z.boolean().default(true),\n options: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type RuleConfig = z.infer<typeof RuleConfigSchema>;\n\n/**\n * Context passed to rule check functions\n */\nexport interface RuleContext {\n file: AnalysisFile;\n parent?: AnalysisNode | undefined;\n depth: number;\n /** Depth relative to the nearest COMPONENT/INSTANCE ancestor. Resets at component boundaries. */\n componentDepth: number;\n maxDepth: number;\n path: string[];\n /** Ancestor node types from root to parent (excludes current node). */\n ancestorTypes: string[];\n siblings?: AnalysisNode[] | undefined;\n /** Per-analysis shared state. Created fresh for each analysis run, eliminating module-level mutable state. */\n analysisState: Map<string, unknown>;\n}\n\n/**\n * Get or initialize per-analysis state for a rule.\n * Each key gets its own lazily-initialized state that persists for the duration of one analysis run.\n */\nexport function getAnalysisState<T>(context: RuleContext, key: string, init: () => T): T {\n if (context.analysisState.has(key)) {\n return context.analysisState.get(key) as T;\n }\n const value = init();\n context.analysisState.set(key, value);\n return value;\n}\n\n/**\n * Rule violation result from check function\n */\nexport interface RuleViolation {\n ruleId: string;\n subType?: string;\n nodeId: string;\n nodePath: string;\n message: string;\n suggestion: string;\n guide?: string;\n}\n\n/**\n * Rule check function signature\n */\nexport type RuleCheckFn = (\n node: AnalysisNode,\n context: RuleContext,\n options?: Record<string, unknown>\n) => RuleViolation | null;\n\n/**\n * Complete rule with definition, config, and check function\n */\nexport interface Rule {\n definition: RuleDefinition;\n check: RuleCheckFn;\n}\n\n/**\n * Rule ID type for type safety\n */\nexport type RuleId =\n // Pixel Critical — layout issues that directly affect pixel accuracy (ΔV ≥ 5%)\n | \"no-auto-layout\"\n | \"absolute-position-in-auto-layout\"\n | \"non-layout-container\"\n // Responsive Critical — size issues that break at different viewports (ΔV ≥ 15%)\n | \"fixed-size-in-auto-layout\"\n | \"missing-size-constraint\"\n // Code Quality — structural issues affecting code reuse (ΔV ≈ 0%, CSS classes -8~15)\n | \"missing-component\"\n | \"detached-instance\"\n | \"variant-structure-mismatch\"\n | \"deep-nesting\"\n // Token Management — raw values without design tokens\n | \"raw-value\"\n | \"irregular-spacing\"\n // Interaction — missing state variants and prototype links for interactive components\n | \"missing-interaction-state\"\n | \"missing-prototype\"\n // Semantic — naming issues with negligible pixel impact (ΔV < 2%)\n | \"non-standard-naming\"\n | \"non-semantic-name\"\n | \"inconsistent-naming-convention\";\n\n/**\n * Categories that support depthWeight\n */\nexport const DEPTH_WEIGHT_CATEGORIES: Category[] = [\"pixel-critical\", \"responsive-critical\"];\n\n/**\n * Check if a category supports depth weighting\n */\nexport function supportsDepthWeight(category: Category): boolean {\n return DEPTH_WEIGHT_CATEGORIES.includes(category);\n}\n","import type { Category } from \"../contracts/category.js\";\nimport type { RuleConfig, RuleId } from \"../contracts/rule.js\";\n\n/**\n * Maps each rule ID to its category.\n * Categories are based on ablation experiment data (PR #149, #150):\n * - pixel-critical: ΔV ≥ 5% — layout info removal directly degrades pixel accuracy\n * - responsive-critical: ΔV ≥ 15% at expanded viewport — size info critical for responsive\n * - code-quality: ΔV ≈ 0% but CSS classes -8~15 — affects code structure, not pixels\n * - token-management: raw values without design tokens — wrong input = wrong output\n * - semantic: ΔV < 2%, negligible code difference — naming and semantic issues\n */\nexport const RULE_ID_CATEGORY: Record<RuleId, Category> = {\n // Pixel Critical\n \"no-auto-layout\": \"pixel-critical\",\n \"absolute-position-in-auto-layout\": \"pixel-critical\",\n \"non-layout-container\": \"pixel-critical\",\n // Responsive Critical\n \"fixed-size-in-auto-layout\": \"responsive-critical\",\n \"missing-size-constraint\": \"responsive-critical\",\n // Code Quality\n \"missing-component\": \"code-quality\",\n \"detached-instance\": \"code-quality\",\n \"variant-structure-mismatch\": \"code-quality\",\n \"deep-nesting\": \"code-quality\",\n // Token Management\n \"raw-value\": \"token-management\",\n \"irregular-spacing\": \"token-management\",\n // Interaction\n \"missing-interaction-state\": \"interaction\",\n \"missing-prototype\": \"interaction\",\n // Semantic\n \"non-standard-naming\": \"semantic\",\n \"non-semantic-name\": \"semantic\",\n \"inconsistent-naming-convention\": \"semantic\",\n};\n\n/**\n * Central configuration for all rules.\n * Scores based on ablation experiment + AI implementation interview (#200):\n * - pixel-critical: -10 ~ -7 (layout strip caused ΔV +5.4%)\n * - responsive-critical: -8 ~ -6 (size-constraints ΔV +15.9% at responsive viewports)\n * - code-quality: -7 ~ -3 (CSS classes -8~15, no pixel impact)\n * - token-management: -5 ~ -4 (wrong input = wrong output, irregular spacing actively causes errors)\n * - interaction: -1 (uncalibrated — no metric to validate, kept minimal #210)\n * - semantic: -4 ~ -1 (non-semantic-name upgraded per interview — causes actual implementation errors)\n *\n * Category weights removed (#196) — overall score is simple average of categories.\n */\nexport const RULE_CONFIGS: Record<RuleId, RuleConfig> = {\n // ── Pixel Critical ──\n \"no-auto-layout\": {\n severity: \"blocking\",\n score: -10,\n depthWeight: 1.5,\n enabled: true,\n },\n \"absolute-position-in-auto-layout\": {\n severity: \"blocking\",\n score: -7,\n depthWeight: 1.3,\n enabled: true,\n },\n \"non-layout-container\": {\n severity: \"blocking\",\n score: -8,\n depthWeight: 1.2,\n enabled: true,\n },\n\n // ── Responsive Critical ──\n \"fixed-size-in-auto-layout\": {\n severity: \"risk\",\n score: -6,\n enabled: true,\n },\n \"missing-size-constraint\": {\n severity: \"risk\",\n score: -8,\n enabled: true,\n },\n\n // ── Code Quality ──\n \"missing-component\": {\n severity: \"risk\",\n score: -7,\n enabled: true,\n options: {\n minRepetitions: 2,\n structureMinRepetitions: 2,\n maxFingerprintDepth: 3,\n },\n },\n \"detached-instance\": {\n severity: \"risk\",\n score: -4,\n enabled: true,\n },\n \"variant-structure-mismatch\": {\n severity: \"risk\",\n score: -6,\n enabled: true,\n },\n \"deep-nesting\": {\n severity: \"risk\",\n score: -3,\n enabled: true,\n options: {\n maxDepth: 5,\n },\n },\n\n // ── Token Management ──\n \"raw-value\": {\n severity: \"missing-info\",\n score: -4,\n enabled: true,\n },\n \"irregular-spacing\": {\n severity: \"risk\",\n score: -5,\n enabled: true,\n options: {\n gridBase: 2,\n },\n },\n\n // ── Interaction ──\n \"missing-interaction-state\": {\n severity: \"suggestion\",\n score: -1, // uncalibrated: no metric to validate score (#210), kept at -1 to preserve category visibility\n enabled: true,\n },\n \"missing-prototype\": {\n severity: \"missing-info\",\n score: -3,\n enabled: false, // disabled: interactionDestinations data missing from fixtures (#139)\n },\n\n // ── Semantic ──\n \"non-standard-naming\": {\n severity: \"suggestion\",\n score: -3, // higher than other naming rules: non-standard state names break interaction detection pipeline\n enabled: true,\n },\n \"non-semantic-name\": {\n severity: \"risk\",\n score: -4,\n enabled: true,\n },\n \"inconsistent-naming-convention\": {\n severity: \"suggestion\",\n score: -1,\n enabled: true,\n },\n};\n\n/**\n * Preset types for different analysis modes\n */\nexport type Preset = \"relaxed\" | \"dev-friendly\" | \"ai-ready\" | \"strict\";\n\n/**\n * Get rule configs with preset applied\n */\nexport function getConfigsWithPreset(\n preset: Preset\n): Record<RuleId, RuleConfig> {\n const configs = { ...RULE_CONFIGS };\n\n switch (preset) {\n case \"relaxed\":\n // Disable blocking rules, reduce scores\n for (const [id, config] of Object.entries(configs)) {\n if (config.severity === \"blocking\") {\n configs[id as RuleId] = {\n ...config,\n severity: \"risk\",\n score: Math.round(config.score * 0.5),\n };\n }\n }\n break;\n\n case \"dev-friendly\":\n // Focus on pixel-critical and responsive-critical issues\n for (const [id, config] of Object.entries(configs)) {\n const ruleId = id as RuleId;\n const category = RULE_ID_CATEGORY[ruleId];\n if (category !== \"pixel-critical\" && category !== \"responsive-critical\") {\n configs[ruleId] = { ...config, enabled: false };\n }\n }\n break;\n\n case \"ai-ready\":\n // Boost pixel-critical and token-management rules\n for (const [id, config] of Object.entries(configs)) {\n const ruleId = id as RuleId;\n const category = RULE_ID_CATEGORY[ruleId];\n if (category === \"pixel-critical\" || category === \"token-management\") {\n configs[ruleId] = {\n ...config,\n score: Math.round(config.score * 1.5),\n };\n }\n }\n break;\n\n case \"strict\":\n // Increase scores but respect disabled rules\n for (const [id, config] of Object.entries(configs)) {\n configs[id as RuleId] = {\n ...config,\n score: Math.round(config.score * 1.5),\n };\n }\n break;\n }\n\n return configs;\n}\n\n/**\n * Get option value for a rule with type safety\n */\nexport function getRuleOption<T>(\n ruleId: RuleId,\n optionKey: string,\n defaultValue: T\n): T {\n const config = RULE_CONFIGS[ruleId];\n if (!config.options) return defaultValue;\n const value = config.options[optionKey];\n return (value as T) ?? defaultValue;\n}\n","import type { Rule, RuleConfig, RuleId } from \"../contracts/rule.js\";\nimport type { Category } from \"../contracts/category.js\";\nimport { RULE_CONFIGS } from \"./rule-config.js\";\n\n/**\n * Registry for all rules\n */\nclass RuleRegistry {\n private rules: Map<RuleId, Rule> = new Map();\n\n /**\n * Register a rule\n */\n register(rule: Rule): void {\n this.rules.set(rule.definition.id as RuleId, rule);\n }\n\n /**\n * Get a rule by ID\n */\n get(id: RuleId): Rule | undefined {\n return this.rules.get(id);\n }\n\n /**\n * Get all registered rules\n */\n getAll(): Rule[] {\n return Array.from(this.rules.values());\n }\n\n /**\n * Get rules by category\n */\n getByCategory(category: Category): Rule[] {\n return this.getAll().filter((rule) => rule.definition.category === category);\n }\n\n /**\n * Get enabled rules with their configs\n */\n getEnabled(configs: Record<RuleId, RuleConfig> = RULE_CONFIGS): Rule[] {\n return this.getAll().filter((rule) => {\n const config = configs[rule.definition.id as RuleId];\n return config?.enabled ?? true;\n });\n }\n\n /**\n * Get config for a rule\n */\n getConfig(\n id: RuleId,\n configs: Record<RuleId, RuleConfig> = RULE_CONFIGS\n ): RuleConfig {\n return configs[id];\n }\n\n /**\n * Check if a rule is registered\n */\n has(id: RuleId): boolean {\n return this.rules.has(id);\n }\n\n /**\n * Get count of registered rules\n */\n get size(): number {\n return this.rules.size;\n }\n}\n\n/**\n * Global rule registry instance\n */\nexport const ruleRegistry = new RuleRegistry();\n\n/**\n * Helper to create and register a rule\n */\nexport function defineRule(rule: Rule): Rule {\n ruleRegistry.register(rule);\n return rule;\n}\n","import type { AnalysisFile, AnalysisNode } from \"../contracts/figma-node.js\";\nimport type {\n Rule,\n RuleConfig,\n RuleContext,\n RuleId,\n RuleViolation,\n} from \"../contracts/rule.js\";\nimport { supportsDepthWeight } from \"../contracts/rule.js\";\nimport { ruleRegistry } from \"../rules/rule-registry.js\";\nimport { RULE_CONFIGS } from \"../rules/rule-config.js\";\n\n/**\n * Analysis issue with calculated score and metadata\n */\nexport interface AnalysisIssue {\n violation: RuleViolation;\n rule: Rule;\n config: RuleConfig;\n depth: number;\n maxDepth: number;\n calculatedScore: number;\n}\n\n/**\n * Information about a rule that threw during analysis\n */\nexport interface RuleFailure {\n ruleId: string;\n nodeName: string;\n nodeId: string;\n error: string;\n}\n\n/**\n * Analysis result from the rule engine\n */\nexport interface AnalysisResult {\n file: AnalysisFile;\n issues: AnalysisIssue[];\n failedRules: RuleFailure[];\n maxDepth: number;\n nodeCount: number;\n analyzedAt: string;\n}\n\n/**\n * Options for the rule engine\n */\nexport interface RuleEngineOptions {\n configs?: Record<RuleId, RuleConfig>;\n enabledRules?: RuleId[];\n disabledRules?: RuleId[];\n targetNodeId?: string;\n excludeNodeNames?: string[];\n excludeNodeTypes?: string[];\n}\n\n/**\n * Calculate the maximum depth of a node tree\n */\nfunction calculateMaxDepth(node: AnalysisNode, currentDepth = 0): number {\n if (!node.children || node.children.length === 0) {\n return currentDepth;\n }\n\n let maxChildDepth = currentDepth;\n for (const child of node.children) {\n const childDepth = calculateMaxDepth(child, currentDepth + 1);\n if (childDepth > maxChildDepth) {\n maxChildDepth = childDepth;\n }\n }\n\n return maxChildDepth;\n}\n\n/**\n * Count total nodes in a tree\n */\nfunction countNodes(node: AnalysisNode): number {\n let count = 1;\n if (node.children) {\n for (const child of node.children) {\n count += countNodes(child);\n }\n }\n return count;\n}\n\n/**\n * Find a node by ID in the tree\n */\nfunction findNodeById(node: AnalysisNode, nodeId: string): AnalysisNode | null {\n // Figma node IDs use \":\" separator, URL uses \"-\"\n const normalizedId = nodeId.replace(/-/g, \":\");\n\n if (node.id === normalizedId) {\n return node;\n }\n\n if (node.children) {\n for (const child of node.children) {\n const found = findNodeById(child, nodeId);\n if (found) return found;\n }\n }\n\n return null;\n}\n\n/**\n * Calculate depth weight multiplier for a rule\n * Higher values (closer to 1.5x) at root level, 1.0x at leaf level\n */\nfunction calcDepthWeight(\n depth: number,\n maxDepth: number,\n depthWeight?: number\n): number {\n if (!depthWeight || depthWeight <= 1) return 1;\n if (maxDepth === 0) return depthWeight;\n\n // Linear interpolation: depthWeight at depth 0, 1.0 at maxDepth\n const ratio = depth / maxDepth;\n return depthWeight - (depthWeight - 1) * ratio;\n}\n\n/**\n * Rule engine for analyzing Figma files\n */\nexport class RuleEngine {\n private configs: Record<RuleId, RuleConfig>;\n private enabledRuleIds: Set<RuleId> | null;\n private disabledRuleIds: Set<RuleId>;\n private targetNodeId: string | undefined;\n private excludeNamePattern: RegExp | null;\n private excludeNodeTypes: Set<string> | null;\n\n constructor(options: RuleEngineOptions = {}) {\n this.configs = options.configs ?? RULE_CONFIGS;\n this.enabledRuleIds = options.enabledRules\n ? new Set(options.enabledRules)\n : null;\n this.disabledRuleIds = new Set(options.disabledRules ?? []);\n this.targetNodeId = options.targetNodeId;\n this.excludeNamePattern = options.excludeNodeNames && options.excludeNodeNames.length > 0\n ? new RegExp(`\\\\b(${options.excludeNodeNames.join(\"|\")})\\\\b`, \"i\")\n : null;\n this.excludeNodeTypes = options.excludeNodeTypes && options.excludeNodeTypes.length > 0\n ? new Set(options.excludeNodeTypes)\n : null;\n }\n\n /**\n * Analyze a Figma file and return issues\n */\n analyze(file: AnalysisFile): AnalysisResult {\n // Fresh per-analysis state — eliminates module-level mutable state in rules\n const analysisState = new Map<string, unknown>();\n\n // Find target node if specified\n let rootNode = file.document;\n if (this.targetNodeId) {\n const targetNode = findNodeById(file.document, this.targetNodeId);\n if (!targetNode) {\n throw new Error(`Node not found: ${this.targetNodeId}`);\n }\n rootNode = targetNode;\n }\n\n // Calculate max depth before analysis\n const maxDepth = calculateMaxDepth(rootNode);\n const nodeCount = countNodes(rootNode);\n\n const issues: AnalysisIssue[] = [];\n const failedRules: RuleFailure[] = [];\n const enabledRules = this.getEnabledRules();\n\n // Traverse the tree and run rules on each node\n this.traverseAndCheck(\n rootNode,\n file,\n enabledRules,\n maxDepth,\n issues,\n failedRules,\n 0,\n [],\n [],\n 0,\n analysisState,\n undefined,\n undefined\n );\n\n return {\n file,\n issues,\n failedRules,\n maxDepth,\n nodeCount,\n analyzedAt: new Date().toISOString(),\n };\n }\n\n /**\n * Get rules that should be run based on configuration\n */\n private getEnabledRules(): Rule[] {\n return ruleRegistry.getAll().filter((rule) => {\n const ruleId = rule.definition.id as RuleId;\n\n // Check if explicitly disabled\n if (this.disabledRuleIds.has(ruleId)) return false;\n\n // Check if we have an explicit enable list\n if (this.enabledRuleIds && !this.enabledRuleIds.has(ruleId)) return false;\n\n // Check config enabled status\n const config = this.configs[ruleId];\n return config?.enabled ?? true;\n });\n }\n\n /**\n * Recursively traverse the tree and run rules\n */\n private traverseAndCheck(\n node: AnalysisNode,\n file: AnalysisFile,\n rules: Rule[],\n maxDepth: number,\n issues: AnalysisIssue[],\n failedRules: RuleFailure[],\n depth: number,\n path: string[],\n ancestorTypes: string[],\n componentDepth: number,\n analysisState: Map<string, unknown>,\n parent?: AnalysisNode,\n siblings?: AnalysisNode[]\n ): void {\n const nodePath = [...path, node.name];\n\n // Reset componentDepth at component boundaries\n const isComponentBoundary = node.type === \"COMPONENT\" || node.type === \"COMPONENT_SET\" || node.type === \"INSTANCE\";\n const currentComponentDepth = isComponentBoundary ? 0 : componentDepth;\n\n // Skip nodes matching excluded types or name patterns\n if (this.excludeNodeTypes && this.excludeNodeTypes.has(node.type)) {\n return;\n }\n if (this.excludeNamePattern && this.excludeNamePattern.test(node.name)) {\n return;\n }\n\n // Build context for this node\n const context: RuleContext = {\n file,\n parent,\n depth,\n componentDepth: currentComponentDepth,\n maxDepth,\n path: nodePath,\n ancestorTypes,\n siblings,\n analysisState,\n };\n\n // Run each rule on this node\n for (const rule of rules) {\n const ruleId = rule.definition.id as RuleId;\n const config = this.configs[ruleId];\n const options = config?.options;\n\n try {\n const violation = rule.check(node, context, options);\n\n if (violation) {\n // Calculate score with depth weight if applicable\n let calculatedScore = config.score;\n\n if (\n supportsDepthWeight(rule.definition.category) &&\n config.depthWeight\n ) {\n const weight = calcDepthWeight(depth, maxDepth, config.depthWeight);\n calculatedScore = Math.round(config.score * weight);\n }\n\n issues.push({\n violation,\n rule,\n config,\n depth,\n maxDepth,\n calculatedScore,\n });\n }\n } catch (error) {\n // Track failure and continue — never let one rule break the whole analysis\n failedRules.push({\n ruleId,\n nodeName: node.name,\n nodeId: node.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n // Recurse into children\n if (node.children && node.children.length > 0) {\n const childAncestorTypes = [...ancestorTypes, node.type];\n for (const child of node.children) {\n this.traverseAndCheck(\n child,\n file,\n rules,\n maxDepth,\n issues,\n failedRules,\n depth + 1,\n nodePath,\n childAncestorTypes,\n currentComponentDepth + 1,\n analysisState,\n node,\n node.children\n );\n }\n }\n }\n}\n\n/**\n * Create a rule engine with default configuration\n */\nexport function createRuleEngine(options?: RuleEngineOptions): RuleEngine {\n return new RuleEngine(options);\n}\n\n/**\n * Convenience function to analyze a file with default settings\n */\nexport function analyzeFile(\n file: AnalysisFile,\n options?: RuleEngineOptions\n): AnalysisResult {\n const engine = createRuleEngine(options);\n return engine.analyze(file);\n}\n","import type { GetFileResponse, Node } from \"@figma/rest-api-spec\";\n\nconst FIGMA_API_BASE = \"https://api.figma.com/v1\";\n\nexport interface GetFileNodesResponse {\n name: string;\n lastModified: string;\n version: string;\n nodes: Record<string, {\n document: Node;\n components: GetFileResponse[\"components\"];\n styles: GetFileResponse[\"styles\"];\n }>;\n}\n\nexport interface FigmaClientOptions {\n token: string;\n}\n\nexport class FigmaClient {\n private token: string;\n\n constructor(options: FigmaClientOptions) {\n this.token = options.token;\n }\n\n static fromEnv(): FigmaClient {\n const token = process.env[\"FIGMA_TOKEN\"];\n if (!token) {\n throw new FigmaClientError(\n \"FIGMA_TOKEN environment variable is not set\"\n );\n }\n return new FigmaClient({ token });\n }\n\n async getFile(fileKey: string): Promise<GetFileResponse> {\n const url = `${FIGMA_API_BASE}/files/${fileKey}`;\n const response = await fetch(url, {\n headers: {\n \"X-Figma-Token\": this.token,\n },\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new FigmaClientError(\n `Failed to fetch file: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n return response.json() as Promise<GetFileResponse>;\n }\n\n /**\n * Get rendered images for specific nodes\n * Returns a map of nodeId → image URL\n */\n async getNodeImages(\n fileKey: string,\n nodeIds: string[],\n options?: { format?: \"png\" | \"svg\" | \"jpg\"; scale?: number }\n ): Promise<Record<string, string | null>> {\n const format = options?.format ?? \"png\";\n const scale = options?.scale ?? 2;\n\n // Batch into chunks to avoid 414 URI Too Large\n const BATCH_SIZE = 50;\n const allImages: Record<string, string | null> = {};\n\n for (let i = 0; i < nodeIds.length; i += BATCH_SIZE) {\n const batch = nodeIds.slice(i, i + BATCH_SIZE);\n const ids = batch.join(\",\");\n const url = `${FIGMA_API_BASE}/images/${fileKey}?ids=${encodeURIComponent(ids)}&format=${format}&scale=${scale}`;\n const response = await fetch(url, {\n headers: {\n \"X-Figma-Token\": this.token,\n },\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new FigmaClientError(\n `Failed to fetch images: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n const data = await response.json() as { images: Record<string, string | null> };\n for (const [nodeId, imageUrl] of Object.entries(data.images)) {\n allImages[nodeId] = imageUrl;\n }\n }\n\n return allImages;\n }\n\n /**\n * Get original image fill URLs by imageRef.\n * Returns a mapping of imageRef → download URL for all image fills in the file.\n */\n async getImageFills(fileKey: string): Promise<Record<string, string>> {\n const url = `${FIGMA_API_BASE}/files/${fileKey}/images`;\n const response = await fetch(url, {\n headers: { \"X-Figma-Token\": this.token },\n });\n if (!response.ok) {\n const error = await response.text().catch(() => \"\");\n throw new FigmaClientError(\n `Failed to fetch image fills: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n const data = await response.json() as { meta?: { images?: Record<string, string> } };\n return data.meta?.images ?? {};\n }\n\n /**\n * Download an image URL and return as base64\n */\n async fetchImageAsBase64(imageUrl: string): Promise<string> {\n const response = await fetch(imageUrl);\n if (!response.ok) {\n throw new FigmaClientError(\n `Failed to download image: ${response.status}`,\n response.status\n );\n }\n const buffer = await response.arrayBuffer();\n return Buffer.from(buffer).toString(\"base64\");\n }\n\n async getFileNodes(\n fileKey: string,\n nodeIds: string[]\n ): Promise<GetFileNodesResponse> {\n const ids = nodeIds.join(\",\");\n const url = `${FIGMA_API_BASE}/files/${fileKey}/nodes?ids=${encodeURIComponent(ids)}`;\n const response = await fetch(url, {\n headers: {\n \"X-Figma-Token\": this.token,\n },\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new FigmaClientError(\n `Failed to fetch nodes: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n return response.json() as Promise<GetFileNodesResponse>;\n }\n}\n\nexport class FigmaClientError extends Error {\n constructor(\n message: string,\n public statusCode?: number,\n public responseBody?: unknown\n ) {\n super(message);\n this.name = \"FigmaClientError\";\n }\n}\n","import type { GetFileResponse, Node } from \"@figma/rest-api-spec\";\nimport type { GetFileNodesResponse } from \"./figma-client.js\";\nimport type { AnalysisFile, AnalysisNode } from \"../contracts/figma-node.js\";\n\n/**\n * Transform Figma API response to analysis types\n */\nexport function transformFigmaResponse(\n fileKey: string,\n response: GetFileResponse\n): AnalysisFile {\n return {\n fileKey,\n name: response.name,\n lastModified: response.lastModified,\n version: response.version,\n document: transformNode(response.document),\n components: transformComponents(response.components),\n styles: transformStyles(response.styles),\n };\n}\n\nfunction transformNode(node: Node): AnalysisNode {\n const base: AnalysisNode = {\n id: node.id,\n name: node.name,\n type: node.type as AnalysisNode[\"type\"],\n visible: \"visible\" in node ? (node.visible ?? true) : true,\n };\n\n // Layout properties\n if (\"layoutMode\" in node && node.layoutMode) {\n base.layoutMode = node.layoutMode as AnalysisNode[\"layoutMode\"];\n }\n if (\"layoutAlign\" in node && node.layoutAlign) {\n base.layoutAlign = node.layoutAlign as AnalysisNode[\"layoutAlign\"];\n }\n if (\"layoutPositioning\" in node && node.layoutPositioning) {\n base.layoutPositioning =\n node.layoutPositioning as AnalysisNode[\"layoutPositioning\"];\n }\n if (\"layoutSizingHorizontal\" in node && node.layoutSizingHorizontal) {\n base.layoutSizingHorizontal =\n node.layoutSizingHorizontal as AnalysisNode[\"layoutSizingHorizontal\"];\n }\n if (\"layoutSizingVertical\" in node && node.layoutSizingVertical) {\n base.layoutSizingVertical =\n node.layoutSizingVertical as AnalysisNode[\"layoutSizingVertical\"];\n }\n if (\"primaryAxisAlignItems\" in node) {\n base.primaryAxisAlignItems = node.primaryAxisAlignItems as string;\n }\n if (\"counterAxisAlignItems\" in node) {\n base.counterAxisAlignItems = node.counterAxisAlignItems as string;\n }\n if (\"itemSpacing\" in node) {\n base.itemSpacing = node.itemSpacing as number;\n }\n if (\"paddingLeft\" in node) {\n base.paddingLeft = node.paddingLeft as number;\n }\n if (\"paddingRight\" in node) {\n base.paddingRight = node.paddingRight as number;\n }\n if (\"paddingTop\" in node) {\n base.paddingTop = node.paddingTop as number;\n }\n if (\"paddingBottom\" in node) {\n base.paddingBottom = node.paddingBottom as number;\n }\n\n // Size constraints (responsive)\n if (\"minWidth\" in node && typeof node.minWidth === \"number\") {\n base.minWidth = node.minWidth;\n }\n if (\"maxWidth\" in node && typeof node.maxWidth === \"number\") {\n base.maxWidth = node.maxWidth;\n }\n if (\"minHeight\" in node && typeof node.minHeight === \"number\") {\n base.minHeight = node.minHeight;\n }\n if (\"maxHeight\" in node && typeof node.maxHeight === \"number\") {\n base.maxHeight = node.maxHeight;\n }\n if (\"layoutGrow\" in node && node.layoutGrow !== undefined) {\n base.layoutGrow = node.layoutGrow as 0 | 1;\n }\n if (\"constraints\" in node && node.constraints) {\n base.constraints = node.constraints as AnalysisNode[\"constraints\"];\n }\n\n // Wrap (flex-wrap)\n if (\"layoutWrap\" in node && node.layoutWrap) {\n base.layoutWrap = node.layoutWrap as AnalysisNode[\"layoutWrap\"];\n }\n if (\"counterAxisSpacing\" in node && typeof node.counterAxisSpacing === \"number\") {\n base.counterAxisSpacing = node.counterAxisSpacing;\n }\n if (\"counterAxisAlignContent\" in node && node.counterAxisAlignContent) {\n base.counterAxisAlignContent =\n node.counterAxisAlignContent as AnalysisNode[\"counterAxisAlignContent\"];\n }\n\n // Grid layout (container)\n if (\"gridRowCount\" in node && typeof node.gridRowCount === \"number\") {\n base.gridRowCount = node.gridRowCount;\n }\n if (\"gridColumnCount\" in node && typeof node.gridColumnCount === \"number\") {\n base.gridColumnCount = node.gridColumnCount;\n }\n if (\"gridRowGap\" in node && typeof node.gridRowGap === \"number\") {\n base.gridRowGap = node.gridRowGap;\n }\n if (\"gridColumnGap\" in node && typeof node.gridColumnGap === \"number\") {\n base.gridColumnGap = node.gridColumnGap;\n }\n if (\"gridColumnsSizing\" in node && typeof node.gridColumnsSizing === \"string\") {\n base.gridColumnsSizing = node.gridColumnsSizing;\n }\n if (\"gridRowsSizing\" in node && typeof node.gridRowsSizing === \"string\") {\n base.gridRowsSizing = node.gridRowsSizing;\n }\n\n // Grid layout (child)\n if (\"gridChildHorizontalAlign\" in node && node.gridChildHorizontalAlign) {\n base.gridChildHorizontalAlign =\n node.gridChildHorizontalAlign as AnalysisNode[\"gridChildHorizontalAlign\"];\n }\n if (\"gridChildVerticalAlign\" in node && node.gridChildVerticalAlign) {\n base.gridChildVerticalAlign =\n node.gridChildVerticalAlign as AnalysisNode[\"gridChildVerticalAlign\"];\n }\n if (\"gridRowSpan\" in node && typeof node.gridRowSpan === \"number\") {\n base.gridRowSpan = node.gridRowSpan;\n }\n if (\"gridColumnSpan\" in node && typeof node.gridColumnSpan === \"number\") {\n base.gridColumnSpan = node.gridColumnSpan;\n }\n if (\"gridRowAnchorIndex\" in node && typeof node.gridRowAnchorIndex === \"number\") {\n base.gridRowAnchorIndex = node.gridRowAnchorIndex;\n }\n if (\"gridColumnAnchorIndex\" in node && typeof node.gridColumnAnchorIndex === \"number\") {\n base.gridColumnAnchorIndex = node.gridColumnAnchorIndex;\n }\n\n // Overflow / clip\n if (\"clipsContent\" in node && typeof node.clipsContent === \"boolean\") {\n base.clipsContent = node.clipsContent;\n }\n if (\"overflowDirection\" in node && node.overflowDirection) {\n base.overflowDirection =\n node.overflowDirection as AnalysisNode[\"overflowDirection\"];\n }\n\n // Size/position\n if (\"absoluteBoundingBox\" in node && node.absoluteBoundingBox) {\n base.absoluteBoundingBox = node.absoluteBoundingBox;\n }\n\n // Component properties\n if (\"componentId\" in node) {\n base.componentId = node.componentId as string;\n }\n if (\"componentPropertyDefinitions\" in node) {\n base.componentPropertyDefinitions =\n node.componentPropertyDefinitions as Record<string, unknown>;\n }\n if (\"componentProperties\" in node) {\n base.componentProperties = node.componentProperties as Record<\n string,\n unknown\n >;\n }\n\n // Style properties\n if (\"styles\" in node) {\n base.styles = node.styles as Record<string, string>;\n }\n if (\"fills\" in node) {\n base.fills = node.fills as unknown[];\n }\n if (\"strokes\" in node) {\n base.strokes = node.strokes as unknown[];\n }\n if (\"strokeWeight\" in node && typeof node.strokeWeight === \"number\") {\n base.strokeWeight = node.strokeWeight;\n }\n if (\"individualStrokeWeights\" in node && node.individualStrokeWeights) {\n base.individualStrokeWeights = node.individualStrokeWeights as Record<string, number>;\n }\n if (\"effects\" in node) {\n base.effects = node.effects as unknown[];\n }\n if (\"cornerRadius\" in node && typeof node.cornerRadius === \"number\") {\n base.cornerRadius = node.cornerRadius;\n }\n if (\"opacity\" in node && typeof node.opacity === \"number\" && node.opacity < 1) {\n base.opacity = node.opacity;\n }\n\n // Variable bindings\n if (\"boundVariables\" in node && node.boundVariables) {\n base.boundVariables = node.boundVariables as Record<string, unknown>;\n }\n\n // Text properties\n if (\"characters\" in node) {\n base.characters = node.characters as string;\n }\n if (\"style\" in node) {\n base.style = node.style as Record<string, unknown>;\n }\n if (\"textTruncation\" in node && (node.textTruncation === \"DISABLED\" || node.textTruncation === \"ENDING\")) {\n base.textTruncation = node.textTruncation;\n }\n if (\"maxLines\" in node && typeof node.maxLines === \"number\") {\n base.maxLines = node.maxLines;\n }\n\n // Handoff status\n if (\"devStatus\" in node && node.devStatus) {\n base.devStatus = node.devStatus as AnalysisNode[\"devStatus\"];\n }\n\n // Prototype interactions\n if (\"interactions\" in node && Array.isArray(node.interactions) && node.interactions.length > 0) {\n base.interactions = node.interactions;\n }\n\n // Recursively transform children\n if (\"children\" in node && Array.isArray(node.children)) {\n base.children = node.children.map(transformNode);\n }\n\n return base;\n}\n\n/**\n * Transform Figma /v1/files/{key}/nodes response to analysis types.\n * Returns the first node's subtree as the document.\n */\nexport function transformFileNodesResponse(\n fileKey: string,\n response: GetFileNodesResponse\n): AnalysisFile {\n const entries = Object.values(response.nodes);\n const first = entries[0];\n if (!first)\n throw new Error(\n \"No nodes returned from Figma API — the node-id in the URL may be invalid or deleted. \" +\n \"Try selecting the frame in Figma and copying the link again.\"\n );\n\n return {\n fileKey,\n name: response.name,\n lastModified: response.lastModified,\n version: response.version,\n document: transformNode(first.document),\n components: transformComponents(first.components),\n styles: transformStyles(first.styles),\n };\n}\n\n/**\n * Transform component master nodes from a /v1/files/{key}/nodes response.\n * Each requested node ID is transformed into an AnalysisNode if present.\n */\nexport function transformComponentMasterNodes(\n response: GetFileNodesResponse,\n requestedIds: string[]\n): Record<string, AnalysisNode> {\n const result: Record<string, AnalysisNode> = {};\n for (const id of requestedIds) {\n const entry = response.nodes[id];\n if (entry?.document) {\n result[id] = transformNode(entry.document);\n }\n }\n return result;\n}\n\nfunction transformComponents(\n components: GetFileResponse[\"components\"]\n): AnalysisFile[\"components\"] {\n const result: AnalysisFile[\"components\"] = {};\n for (const [id, component] of Object.entries(components)) {\n result[id] = {\n key: component.key,\n name: component.name,\n description: component.description,\n };\n }\n return result;\n}\n\nfunction transformStyles(\n styles: GetFileResponse[\"styles\"]\n): AnalysisFile[\"styles\"] {\n const result: AnalysisFile[\"styles\"] = {};\n for (const [id, style] of Object.entries(styles)) {\n result[id] = {\n key: style.key,\n name: style.name,\n styleType: style.styleType,\n };\n }\n return result;\n}\n","import type { FigmaClient } from \"./figma-client.js\";\nimport type { AnalysisNode } from \"../contracts/figma-node.js\";\nimport { transformComponentMasterNodes } from \"./figma-transformer.js\";\n\nconst BATCH_SIZE = 50;\n\n/**\n * Recursively collect all unique componentId values from INSTANCE nodes.\n */\nexport function collectComponentIds(node: AnalysisNode): Set<string> {\n const ids = new Set<string>();\n\n function walk(n: AnalysisNode): void {\n if (n.type === \"INSTANCE\" && n.componentId) {\n ids.add(n.componentId);\n }\n if (n.children) {\n for (const child of n.children) {\n walk(child);\n }\n }\n }\n\n walk(node);\n return ids;\n}\n\n/**\n * Recursively collect all unique interaction destination IDs from nodes.\n * These are the node IDs that interactions (e.g., ON_HOVER → CHANGE_TO) point to.\n */\nexport function collectInteractionDestinationIds(node: AnalysisNode): Set<string> {\n const ids = new Set<string>();\n\n function walk(n: AnalysisNode): void {\n if (n.interactions && Array.isArray(n.interactions)) {\n for (const interaction of n.interactions) {\n const i = interaction as {\n trigger?: { type?: string };\n actions?: Array<{ destinationId?: string; navigation?: string }>;\n };\n if (i.trigger?.type === \"ON_HOVER\" && i.actions) {\n for (const action of i.actions) {\n if (action.navigation === \"CHANGE_TO\" && action.destinationId) {\n ids.add(action.destinationId);\n }\n }\n }\n }\n }\n if (n.children) {\n for (const child of n.children) {\n walk(child);\n }\n }\n }\n\n walk(node);\n return ids;\n}\n\n/**\n * Resolve component master node trees via multi-pass fetching.\n *\n * Pass 1: collect component IDs from the document tree, fetch their masters.\n * Pass 2+: collect component IDs from fetched masters that were not in previous passes.\n * Repeats up to maxPasses (default 2).\n *\n * Batches API calls at BATCH_SIZE IDs per request.\n * Skips IDs that return null (e.g. external library components).\n */\nexport async function resolveComponentDefinitions(\n client: FigmaClient,\n fileKey: string,\n document: AnalysisNode,\n maxPasses = 2\n): Promise<Record<string, AnalysisNode>> {\n const allDefinitions: Record<string, AnalysisNode> = {};\n const resolvedIds = new Set<string>();\n\n // Pass 1: collect from the original document\n let pendingIds = collectComponentIds(document);\n\n for (let pass = 0; pass < maxPasses; pass++) {\n // Filter out already-resolved IDs\n const idsToFetch = [...pendingIds].filter((id) => !resolvedIds.has(id));\n if (idsToFetch.length === 0) break;\n\n // Fetch in batches\n for (let i = 0; i < idsToFetch.length; i += BATCH_SIZE) {\n const batch = idsToFetch.slice(i, i + BATCH_SIZE);\n try {\n const response = await client.getFileNodes(fileKey, batch);\n const transformed = transformComponentMasterNodes(response, batch);\n for (const [id, node] of Object.entries(transformed)) {\n allDefinitions[id] = node;\n }\n } catch (err) {\n // Skip failed batches (e.g. external library components)\n console.debug(`[component-resolver] batch fetch failed (${batch.length} ids):`, err);\n }\n }\n\n // Mark all attempted IDs as resolved (even if they failed/returned null)\n for (const id of idsToFetch) {\n resolvedIds.add(id);\n }\n\n // Collect new IDs only from masters fetched in this pass (not all accumulated)\n pendingIds = new Set<string>();\n for (const id of idsToFetch) {\n const node = allDefinitions[id];\n if (node) {\n for (const nestedId of collectComponentIds(node)) {\n if (!resolvedIds.has(nestedId)) {\n pendingIds.add(nestedId);\n }\n }\n }\n }\n }\n\n return allDefinitions;\n}\n\n/**\n * Resolve interaction destination nodes (e.g., hover variants).\n *\n * Collects all destinationId values from interactions in the document,\n * excludes those already in componentDefinitions, and fetches them.\n */\nexport async function resolveInteractionDestinations(\n client: FigmaClient,\n fileKey: string,\n document: AnalysisNode,\n existingDefinitions?: Record<string, AnalysisNode>,\n): Promise<Record<string, AnalysisNode>> {\n const destIds = collectInteractionDestinationIds(document);\n if (destIds.size === 0) return {};\n\n const allDestinations: Record<string, AnalysisNode> = {};\n const idsToFetch: string[] = [];\n\n for (const id of destIds) {\n const existing = existingDefinitions?.[id];\n if (existing) {\n allDestinations[id] = existing;\n } else {\n idsToFetch.push(id);\n }\n }\n\n if (idsToFetch.length === 0) return allDestinations;\n\n for (let i = 0; i < idsToFetch.length; i += BATCH_SIZE) {\n const batch = idsToFetch.slice(i, i + BATCH_SIZE);\n try {\n const response = await client.getFileNodes(fileKey, batch);\n const transformed = transformComponentMasterNodes(response, batch);\n for (const [id, node] of Object.entries(transformed)) {\n allDestinations[id] = node;\n }\n } catch (err) {\n console.debug(`[component-resolver] interaction destination fetch failed (${batch.length} ids):`, err);\n }\n }\n\n return allDestinations;\n}\n","import { z } from \"zod\";\n\n/**\n * Figma node types required for analysis\n * See @figma/rest-api-spec for full API types\n */\n\nexport const AnalysisNodeTypeSchema = z.enum([\n \"DOCUMENT\",\n \"CANVAS\",\n \"FRAME\",\n \"GROUP\",\n \"SECTION\",\n \"COMPONENT\",\n \"COMPONENT_SET\",\n \"INSTANCE\",\n \"RECTANGLE\",\n \"ELLIPSE\",\n \"VECTOR\",\n \"TEXT\",\n \"LINE\",\n \"BOOLEAN_OPERATION\",\n \"STAR\",\n \"REGULAR_POLYGON\",\n \"SLICE\",\n \"STICKY\",\n \"SHAPE_WITH_TEXT\",\n \"CONNECTOR\",\n \"WIDGET\",\n \"EMBED\",\n \"LINK_UNFURL\",\n \"TABLE\",\n \"TABLE_CELL\",\n \"SLOT\",\n]);\n\nexport type AnalysisNodeType = z.infer<typeof AnalysisNodeTypeSchema>;\n\nexport const LayoutModeSchema = z.enum([\"NONE\", \"HORIZONTAL\", \"VERTICAL\", \"GRID\"]);\nexport type LayoutMode = z.infer<typeof LayoutModeSchema>;\n\nexport const LayoutAlignSchema = z.enum([\"MIN\", \"CENTER\", \"MAX\", \"STRETCH\", \"INHERIT\"]);\nexport type LayoutAlign = z.infer<typeof LayoutAlignSchema>;\n\nexport const LayoutPositioningSchema = z.enum([\"AUTO\", \"ABSOLUTE\"]);\nexport type LayoutPositioning = z.infer<typeof LayoutPositioningSchema>;\n\nexport const LayoutConstraintSchema = z.object({\n horizontal: z.enum([\"LEFT\", \"RIGHT\", \"CENTER\", \"LEFT_RIGHT\", \"SCALE\"]),\n vertical: z.enum([\"TOP\", \"BOTTOM\", \"CENTER\", \"TOP_BOTTOM\", \"SCALE\"]),\n});\nexport type LayoutConstraint = z.infer<typeof LayoutConstraintSchema>;\n\nexport const LayoutWrapSchema = z.enum([\"NO_WRAP\", \"WRAP\"]);\nexport type LayoutWrap = z.infer<typeof LayoutWrapSchema>;\n\nexport const OverflowDirectionSchema = z.enum([\n \"HORIZONTAL_SCROLLING\",\n \"VERTICAL_SCROLLING\",\n \"HORIZONTAL_AND_VERTICAL_SCROLLING\",\n \"NONE\",\n]);\nexport type OverflowDirection = z.infer<typeof OverflowDirectionSchema>;\n\nexport const GridChildAlignSchema = z.enum([\"AUTO\", \"MIN\", \"CENTER\", \"MAX\"]);\nexport type GridChildAlign = z.infer<typeof GridChildAlignSchema>;\n\n/**\n * Lightweight FigmaNode type for analysis\n * Contains only properties needed by rules\n */\nconst BaseAnalysisNodeSchema = z.object({\n // Basic identification\n id: z.string(),\n name: z.string(),\n type: AnalysisNodeTypeSchema,\n visible: z.boolean().default(true),\n\n // Layout analysis\n layoutMode: LayoutModeSchema.optional(),\n layoutAlign: LayoutAlignSchema.optional(),\n layoutPositioning: LayoutPositioningSchema.optional(),\n layoutSizingHorizontal: z.enum([\"FIXED\", \"HUG\", \"FILL\"]).optional(),\n layoutSizingVertical: z.enum([\"FIXED\", \"HUG\", \"FILL\"]).optional(),\n primaryAxisAlignItems: z.string().optional(),\n counterAxisAlignItems: z.string().optional(),\n itemSpacing: z.number().optional(),\n paddingLeft: z.number().optional(),\n paddingRight: z.number().optional(),\n paddingTop: z.number().optional(),\n paddingBottom: z.number().optional(),\n\n // Size constraints (responsive)\n minWidth: z.number().optional(),\n maxWidth: z.number().optional(),\n minHeight: z.number().optional(),\n maxHeight: z.number().optional(),\n layoutGrow: z.union([z.literal(0), z.literal(1)]).optional(),\n constraints: LayoutConstraintSchema.optional(),\n\n // Wrap (flex-wrap)\n layoutWrap: LayoutWrapSchema.optional(),\n counterAxisSpacing: z.number().optional(),\n counterAxisAlignContent: z.enum([\"AUTO\", \"SPACE_BETWEEN\"]).optional(),\n\n // Grid layout (container)\n gridRowCount: z.number().optional(),\n gridColumnCount: z.number().optional(),\n gridRowGap: z.number().optional(),\n gridColumnGap: z.number().optional(),\n gridColumnsSizing: z.string().optional(),\n gridRowsSizing: z.string().optional(),\n\n // Grid layout (child)\n gridChildHorizontalAlign: GridChildAlignSchema.optional(),\n gridChildVerticalAlign: GridChildAlignSchema.optional(),\n gridRowSpan: z.number().optional(),\n gridColumnSpan: z.number().optional(),\n gridRowAnchorIndex: z.number().optional(),\n gridColumnAnchorIndex: z.number().optional(),\n\n // Overflow / clip\n clipsContent: z.boolean().optional(),\n overflowDirection: OverflowDirectionSchema.optional(),\n\n // Size/position analysis\n absoluteBoundingBox: z\n .object({\n x: z.number(),\n y: z.number(),\n width: z.number(),\n height: z.number(),\n })\n .nullable()\n .optional(),\n\n // Component analysis\n componentId: z.string().optional(),\n componentPropertyDefinitions: z.record(z.string(), z.unknown()).optional(),\n componentProperties: z.record(z.string(), z.unknown()).optional(),\n\n // Style/token analysis\n styles: z.record(z.string(), z.string()).optional(),\n fills: z.array(z.unknown()).optional(),\n strokes: z.array(z.unknown()).optional(),\n strokeWeight: z.number().optional(),\n individualStrokeWeights: z.record(z.string(), z.number()).optional(),\n effects: z.array(z.unknown()).optional(),\n cornerRadius: z.number().optional(),\n opacity: z.number().optional(),\n\n // Variable binding analysis (design tokens)\n boundVariables: z.record(z.string(), z.unknown()).optional(),\n\n // Text analysis\n characters: z.string().optional(),\n style: z.record(z.string(), z.unknown()).optional(),\n textTruncation: z.enum([\"DISABLED\", \"ENDING\"]).optional(),\n maxLines: z.number().optional(),\n\n // Handoff analysis\n devStatus: z\n .object({\n type: z.enum([\"NONE\", \"READY_FOR_DEV\", \"COMPLETED\"]),\n description: z.string().optional(),\n })\n .optional(),\n\n // Prototype interactions\n interactions: z.array(z.unknown()).optional(),\n\n // Naming analysis metadata\n isAsset: z.boolean().optional(),\n});\n\nexport type AnalysisNode = z.infer<typeof BaseAnalysisNodeSchema> & {\n children?: AnalysisNode[] | undefined;\n};\n\nexport const AnalysisNodeSchema: z.ZodType<AnalysisNode> =\n BaseAnalysisNodeSchema.extend({\n children: z.lazy(() => AnalysisNodeSchema.array().optional()),\n }) as z.ZodType<AnalysisNode>;\n\n/**\n * Figma file metadata for analysis\n */\nexport const AnalysisFileSchema = z.object({\n fileKey: z.string(),\n name: z.string(),\n lastModified: z.string(),\n version: z.string(),\n sourceUrl: z.string().optional(),\n document: AnalysisNodeSchema,\n components: z.record(\n z.string(),\n z.object({\n key: z.string(),\n name: z.string(),\n description: z.string(),\n })\n ),\n componentDefinitions: z.record(z.string(), AnalysisNodeSchema).optional(),\n interactionDestinations: z.record(z.string(), AnalysisNodeSchema).optional(),\n styles: z.record(\n z.string(),\n z.object({\n key: z.string(),\n name: z.string(),\n styleType: z.string(),\n })\n ),\n});\n\nexport type AnalysisFile = z.infer<typeof AnalysisFileSchema>;\n","import { readFile } from \"node:fs/promises\";\nimport { basename, dirname } from \"node:path\";\nimport type { GetFileResponse } from \"@figma/rest-api-spec\";\nimport type { AnalysisFile, AnalysisNode } from \"../contracts/figma-node.js\";\nimport { AnalysisNodeSchema } from \"../contracts/figma-node.js\";\nimport { transformFigmaResponse } from \"./figma-transformer.js\";\n\n/**\n * Extract fileKey from fixture path.\n * - fixtures/name/data.json → name (directory-based fixture)\n * - fixtures/name.json → name (legacy flat fixture)\n */\nfunction extractFileKey(filePath: string): string {\n const fileName = basename(filePath, \".json\");\n if (fileName === \"data\") {\n // Directory-based fixture: use parent directory name\n return basename(dirname(filePath));\n }\n return fileName;\n}\n\n/**\n * Load Figma data from a JSON file\n * For MVP testing and fixture support\n */\nexport async function loadFigmaFileFromJson(\n filePath: string\n): Promise<AnalysisFile> {\n const content = await readFile(filePath, \"utf-8\");\n const data = JSON.parse(content) as GetFileResponse & {\n componentDefinitions?: Record<string, unknown>;\n interactionDestinations?: Record<string, unknown>;\n };\n\n const fileKey = extractFileKey(filePath);\n\n const file = transformFigmaResponse(fileKey, data);\n\n // Preserve componentDefinitions from previously-saved fixtures\n if (data.componentDefinitions) {\n const parsed: Record<string, AnalysisNode> = {};\n for (const [id, raw] of Object.entries(data.componentDefinitions)) {\n const result = AnalysisNodeSchema.safeParse(raw);\n if (result.success) {\n parsed[id] = result.data;\n } else {\n console.debug(`[figma-file-loader] componentDefinitions[${id}] failed validation:`, result.error.issues);\n }\n }\n if (Object.keys(parsed).length > 0) {\n file.componentDefinitions = parsed;\n }\n }\n\n // Preserve interactionDestinations from previously-saved fixtures\n if (data.interactionDestinations) {\n const parsed: Record<string, AnalysisNode> = {};\n for (const [id, raw] of Object.entries(data.interactionDestinations)) {\n const result = AnalysisNodeSchema.safeParse(raw);\n if (result.success) {\n parsed[id] = result.data;\n } else {\n console.debug(`[figma-file-loader] interactionDestinations[${id}] failed validation:`, result.error.issues);\n }\n }\n if (Object.keys(parsed).length > 0) {\n file.interactionDestinations = parsed;\n }\n }\n\n return file;\n}\n\n/**\n * Parse Figma data from a JSON string\n */\nexport function parseFigmaJson(\n json: string,\n fileKey: string\n): AnalysisFile {\n const data = JSON.parse(json) as GetFileResponse;\n return transformFigmaResponse(fileKey, data);\n}\n\nexport class FigmaFileLoadError extends Error {\n constructor(message: string, public filePath?: string) {\n super(message);\n this.name = \"FigmaFileLoadError\";\n }\n}\n","import { z } from \"zod\";\n\nexport const FigmaUrlInfoSchema = z.object({\n fileKey: z.string(),\n nodeId: z.string().optional(),\n fileName: z.string().optional(),\n});\n\nexport type FigmaUrlInfo = z.infer<typeof FigmaUrlInfoSchema>;\n\nconst FIGMA_URL_PATTERNS = [\n // https://www.figma.com/design/FILE_KEY/FILE_NAME?node-id=NODE_ID\n /figma\\.com\\/design\\/([a-zA-Z0-9]+)(?:\\/([^?]+))?(?:\\?.*node-id=([^&]+))?/,\n // https://www.figma.com/file/FILE_KEY/FILE_NAME?node-id=NODE_ID\n /figma\\.com\\/file\\/([a-zA-Z0-9]+)(?:\\/([^?]+))?(?:\\?.*node-id=([^&]+))?/,\n // https://www.figma.com/proto/FILE_KEY/FILE_NAME?node-id=NODE_ID\n /figma\\.com\\/proto\\/([a-zA-Z0-9]+)(?:\\/([^?]+))?(?:\\?.*node-id=([^&]+))?/,\n];\n\nexport function parseFigmaUrl(url: string): FigmaUrlInfo {\n for (const pattern of FIGMA_URL_PATTERNS) {\n const match = url.match(pattern);\n if (match) {\n const [, fileKey, fileName, nodeId] = match;\n if (!fileKey) {\n throw new FigmaUrlParseError(`Invalid Figma URL: missing file key`);\n }\n return {\n fileKey,\n fileName: fileName ? decodeURIComponent(fileName) : undefined,\n nodeId: nodeId ? decodeURIComponent(nodeId) : undefined,\n };\n }\n }\n\n throw new FigmaUrlParseError(\n `Invalid Figma URL format. Expected: https://www.figma.com/design/FILE_KEY/...`\n );\n}\n\nexport class FigmaUrlParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"FigmaUrlParseError\";\n }\n}\n\n/**\n * Extract the commentable node ID from a potentially nested instance path.\n * Instance-internal IDs like \"I3010:7457;1442:7704\" use semicolons to\n * separate path segments. The Figma Comments API only accepts simple IDs\n * (e.g. \"3010:7457\"), so we take the first segment and strip the \"I\" prefix.\n */\nexport function toCommentableNodeId(nodeId: string): string {\n const firstSegment = nodeId.split(\";\")[0]!;\n return firstSegment.replace(/^I/, \"\");\n}\n\nexport function buildFigmaDeepLink(fileKey: string, nodeId: string): string {\n // Strip instance-internal path to top-level node:\n // \"I175:7425;1442:7704\" → \"175:7425\" → \"175-7425\"\n const topNodeId = toCommentableNodeId(nodeId).replace(/:/g, \"-\");\n return `https://www.figma.com/design/${fileKey}?node-id=${topNodeId}`;\n}\n","import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { randomUUID } from \"node:crypto\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nconst AIREADY_DIR = join(homedir(), \".canicode\");\nconst CONFIG_PATH = join(AIREADY_DIR, \"config.json\");\nconst REPORTS_DIR = join(AIREADY_DIR, \"reports\");\n\ninterface AireadyConfig {\n figmaToken?: string;\n telemetry?: boolean;\n posthogApiKey?: string;\n sentryDsn?: string;\n deviceId?: string;\n}\n\nfunction hardenPermissions(path: string, mode: number): void {\n if (process.platform !== \"win32\") {\n chmodSync(path, mode);\n }\n}\n\nfunction ensureDir(dir: string): void {\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n hardenPermissions(dir, 0o700);\n}\n\nexport function readConfig(): AireadyConfig {\n if (!existsSync(CONFIG_PATH)) {\n return {};\n }\n try {\n const raw = readFileSync(CONFIG_PATH, \"utf-8\");\n return JSON.parse(raw) as AireadyConfig;\n } catch {\n return {};\n }\n}\n\nexport function writeConfig(config: AireadyConfig): void {\n ensureDir(AIREADY_DIR);\n writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + \"\\n\", {\n encoding: \"utf-8\",\n mode: 0o600,\n });\n hardenPermissions(CONFIG_PATH, 0o600);\n}\n\nexport function getFigmaToken(): string | undefined {\n // Priority: env var > config file\n return process.env[\"FIGMA_TOKEN\"] ?? readConfig().figmaToken;\n}\n\nexport function setFigmaToken(token: string): void {\n const config = readConfig();\n config.figmaToken = token;\n writeConfig(config);\n}\n\nexport function hasConfig(): boolean {\n return existsSync(CONFIG_PATH);\n}\n\nexport function getConfigPath(): string {\n return CONFIG_PATH;\n}\n\nexport function getReportsDir(): string {\n return REPORTS_DIR;\n}\n\nexport function ensureReportsDir(): void {\n ensureDir(AIREADY_DIR);\n ensureDir(REPORTS_DIR);\n}\n\nexport function getTelemetryEnabled(): boolean {\n return readConfig().telemetry !== false;\n}\n\nexport function setTelemetryEnabled(enabled: boolean): void {\n const config = readConfig();\n config.telemetry = enabled;\n writeConfig(config);\n}\n\nexport function getPosthogApiKey(): string | undefined {\n return process.env[\"POSTHOG_API_KEY\"] ?? readConfig().posthogApiKey;\n}\n\nexport function getSentryDsn(): string | undefined {\n return process.env[\"SENTRY_DSN\"] ?? readConfig().sentryDsn;\n}\n\n/**\n * Get or create a stable anonymous device ID for telemetry.\n * Stored in ~/.canicode/config.json, persists across sessions.\n */\nexport function getDeviceId(): string {\n const config = readConfig();\n if (config.deviceId) return config.deviceId;\n\n const id = randomUUID();\n config.deviceId = id;\n writeConfig(config);\n return id;\n}\n\n/**\n * Initialize canicode: write config + create reports dir\n */\nexport function initAiready(token: string): void {\n setFigmaToken(token);\n ensureReportsDir();\n}\n","import { existsSync, statSync } from \"node:fs\";\nimport { resolve, join } from \"node:path\";\nimport { FigmaClient } from \"../adapters/figma-client.js\";\nimport { resolveComponentDefinitions, resolveInteractionDestinations } from \"../adapters/component-resolver.js\";\nimport { loadFigmaFileFromJson } from \"../adapters/figma-file-loader.js\";\nimport { transformFigmaResponse, transformFileNodesResponse } from \"../adapters/figma-transformer.js\";\nimport { parseFigmaUrl } from \"../adapters/figma-url-parser.js\";\nimport { getFigmaToken } from \"./config-store.js\";\nimport type { AnalysisFile } from \"../contracts/figma-node.js\";\n\nexport interface LoadResult {\n file: AnalysisFile;\n nodeId?: string | undefined;\n}\n\n/** Check if input string is a Figma URL. */\nexport function isFigmaUrl(input: string): boolean {\n return input.includes(\"figma.com/\");\n}\n\n/** Check if input string is a JSON file path. */\nexport function isJsonFile(input: string): boolean {\n return input.endsWith(\".json\");\n}\n\n/**\n * Check if input is a fixture directory (contains data.json).\n */\nexport function isFixtureDir(input: string): boolean {\n const resolved = resolve(input);\n if (!existsSync(resolved)) return false;\n try {\n if (!statSync(resolved).isDirectory()) return false;\n } catch {\n return false;\n }\n return existsSync(join(resolved, \"data.json\"));\n}\n\n/**\n * Resolve fixture input to data.json path.\n * Input: fixtures/name/ or fixtures/name → fixtures/name/data.json\n */\nexport function resolveFixturePath(input: string): string {\n if (isJsonFile(input)) return resolve(input);\n return resolve(join(input, \"data.json\"));\n}\n\n/**\n * Load a Figma file from a URL, JSON file, or fixture directory.\n * Resolves component master node trees for accurate analysis.\n */\nexport async function loadFile(\n input: string,\n token?: string,\n): Promise<LoadResult> {\n if (isJsonFile(input) || isFixtureDir(input)) {\n const filePath = resolveFixturePath(input);\n if (!existsSync(filePath)) {\n throw new Error(`File not found: ${filePath}`);\n }\n console.error(`Loading from JSON: ${filePath}`);\n return { file: await loadFigmaFileFromJson(filePath) };\n }\n\n if (isFigmaUrl(input)) {\n const { fileKey, nodeId } = parseFigmaUrl(input);\n return loadFromApi(fileKey, nodeId, token);\n }\n\n throw new Error(\n `Invalid input: ${input}. Provide a Figma URL or fixture directory path.`\n );\n}\n\nasync function loadFromApi(\n fileKey: string,\n nodeId: string | undefined,\n token?: string\n): Promise<LoadResult> {\n console.error(`Fetching from Figma REST API: ${fileKey}`);\n if (nodeId) {\n console.error(`Target node: ${nodeId}`);\n }\n\n const figmaToken = token ?? getFigmaToken();\n if (!figmaToken) {\n throw new Error(\n \"Figma token required. Run 'canicode init --token YOUR_TOKEN' or set FIGMA_TOKEN env var.\"\n );\n }\n\n const client = new FigmaClient({ token: figmaToken });\n\n if (nodeId) {\n // Fetch only the target node subtree — faster, less rate limit impact\n const response = await client.getFileNodes(fileKey, [nodeId.replace(/-/g, \":\")]);\n const file = transformFileNodesResponse(fileKey, response);\n\n // Resolve component master node trees for accurate analysis\n const componentDefs = await resolveComponentDefinitions(client, fileKey, file.document);\n if (Object.keys(componentDefs).length > 0) {\n file.componentDefinitions = componentDefs;\n }\n\n // Resolve interaction destination nodes (e.g., hover variants)\n const interactionDests = await resolveInteractionDestinations(client, fileKey, file.document, file.componentDefinitions);\n if (Object.keys(interactionDests).length > 0) {\n file.interactionDestinations = interactionDests;\n }\n\n return { file, nodeId };\n }\n\n const response = await client.getFile(fileKey);\n const file = transformFigmaResponse(fileKey, response);\n\n // Full file fetch may still miss component masters from external libraries\n const componentDefs = await resolveComponentDefinitions(client, fileKey, file.document);\n if (Object.keys(componentDefs).length > 0) {\n file.componentDefinitions = componentDefs;\n }\n\n // Resolve interaction destination nodes (e.g., hover variants)\n const interactionDests = await resolveInteractionDestinations(client, fileKey, file.document, file.componentDefinitions);\n if (Object.keys(interactionDests).length > 0) {\n file.interactionDestinations = interactionDests;\n }\n\n return { file, nodeId };\n}\n","{\n \"name\": \"canicode\",\n \"version\": \"0.9.1\",\n \"mcpName\": \"io.github.let-sunny/canicode\",\n \"description\": \"Score your Figma designs with AI-calibrated rules. CLI + MCP server.\",\n \"type\": \"module\",\n \"main\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"bin\": {\n \"canicode\": \"dist/cli/index.js\",\n \"canicode-mcp\": \"dist/mcp/server.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\"\n }\n },\n \"scripts\": {\n \"build\": \"tsup --config tsup.config.ts\",\n \"build:web\": \"bash scripts/build-web.sh\",\n \"dev\": \"tsup --watch\",\n \"test\": \"vitest\",\n \"test:run\": \"vitest run\",\n \"lint\": \"tsc --noEmit\",\n \"build:plugin\": \"bash scripts/build-plugin.sh\",\n \"sync-docs\": \"tsx scripts/sync-rule-docs.ts\",\n \"clean\": \"rm -rf dist\"\n },\n \"files\": [\n \"dist\",\n \"README.md\",\n \"docs/CUSTOMIZATION.md\",\n \".claude/skills/design-to-code/PROMPT.md\"\n ],\n \"keywords\": [\n \"figma\",\n \"design\",\n \"analysis\",\n \"cli\",\n \"mcp\",\n \"readiness\",\n \"ai\"\n ],\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/let-sunny/canicode.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/let-sunny/canicode/issues\"\n },\n \"homepage\": \"https://github.com/let-sunny/canicode\",\n \"author\": \"minseon\",\n \"license\": \"MIT\",\n \"pnpm\": {\n \"overrides\": {\n \"picomatch\": \"4.0.4\",\n \"path-to-regexp\": \"8.4.0\"\n }\n },\n \"packageManager\": \"pnpm@10.32.1\",\n \"engines\": {\n \"node\": \">=22\"\n },\n \"dependencies\": {\n \"@figma/rest-api-spec\": \"^0.36.0\",\n \"@modelcontextprotocol/sdk\": \"^1.27.1\",\n \"cac\": \"^7.0.0\",\n \"dotenv\": \"^17.3.1\",\n \"pixelmatch\": \"^7.1.0\",\n \"pngjs\": \"^7.0.0\",\n \"zod\": \"^4.3.6\"\n },\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.80.0\",\n \"@figma/plugin-typings\": \"^1.123.0\",\n \"@types/node\": \"^25.5.0\",\n \"@types/pngjs\": \"^6.0.5\",\n \"playwright\": \"^1.58.2\",\n \"tsup\": \"^8.5.1\",\n \"tsx\": \"^4.19.0\",\n \"typescript\": \"^5.9.3\",\n \"vitest\": \"^4.1.0\"\n }\n}\n","import type { Category } from \"../contracts/category.js\";\nimport { CATEGORIES, CATEGORY_LABELS } from \"../contracts/category.js\";\nimport type { RuleId, RuleConfig } from \"../contracts/rule.js\";\nimport type { Severity } from \"../contracts/severity.js\";\nimport type { AnalysisResult } from \"./rule-engine.js\";\nimport { RULE_CONFIGS, RULE_ID_CATEGORY } from \"../rules/rule-config.js\";\nimport { version as VERSION } from \"../../../package.json\";\n\n/**\n * Score breakdown for a single category\n */\nexport interface CategoryScoreResult {\n category: Category;\n score: number;\n maxScore: number;\n percentage: number;\n issueCount: number;\n uniqueRuleCount: number;\n weightedIssueCount: number;\n densityScore: number;\n diversityScore: number;\n bySeverity: Record<Severity, number>;\n}\n\n/**\n * Overall score report\n */\nexport interface ScoreReport {\n overall: {\n score: number;\n maxScore: number;\n percentage: number;\n grade: Grade;\n };\n byCategory: Record<Category, CategoryScoreResult>;\n summary: {\n totalIssues: number;\n blocking: number;\n risk: number;\n missingInfo: number;\n suggestion: number;\n nodeCount: number;\n };\n}\n\n/**\n * Grade levels based on percentage\n */\nexport type Grade = \"S\" | \"A+\" | \"A\" | \"B+\" | \"B\" | \"C+\" | \"C\" | \"D\" | \"F\";\n\n/**\n * Density weighting uses per-rule base |score| with sqrt damping (#226).\n *\n * Previously, each issue's |calculatedScore| was summed linearly — a rule\n * triggering N times contributed N× its score. This over-penalized designs\n * with many instances of the same issue (e.g., raw-value ×79 = -316 weight),\n * causing most real files to score Grade D/F with no differentiation.\n *\n * Now: same rule triggered N times contributes |score| × sqrt(N).\n * raw-value ×79 = 4 × sqrt(79) ≈ 36 instead of 316.\n * At low counts sqrt ≈ linear (sqrt(1)=1, sqrt(4)=2), preserving sensitivity.\n * At high counts the curve flattens — 79th occurrence adds ~0.2 vs 1st adding 4.\n *\n * Category weights removed (#196) — overall score is simple average of categories.\n * Category importance is already encoded in rule scores (pixel-critical -10\n * vs semantic -4), so per-category weighting is unnecessary.\n */\n\n/**\n * Compute sum of |score| for all rules in each category from a given config map.\n * Used as denominator for severity-weighted diversity scoring.\n * Must use the same preset-adjusted config map that produced the analysis issues,\n * otherwise diversity ratios will be incorrect.\n */\nfunction computeTotalScorePerCategory(\n configs: Record<RuleId, RuleConfig>\n): Record<Category, number> {\n const totals = Object.fromEntries(\n CATEGORIES.map(c => [c, 0])\n ) as Record<Category, number>;\n\n for (const [id, config] of Object.entries(configs)) {\n const category = RULE_ID_CATEGORY[id as RuleId];\n if (category && config.enabled) {\n totals[category] += Math.abs(config.score);\n }\n }\n\n return totals;\n}\n\n/**\n * Score composition weights (initial intuition, pending calibration validation).\n *\n * Density (0.7): \"how many issues per node\" — measures issue volume relative to design size.\n * Designs with many issues per node are harder to implement accurately.\n *\n * Diversity (0.3): \"how many different rule types triggered\" — measures issue breadth.\n * A design that triggers 1 rule 50 times is easier to fix than one triggering 10 different rules.\n *\n * The 70:30 ratio prioritizes volume over variety. Rationale: a design with a single\n * systemic problem (e.g., all frames missing auto-layout) is still very hard to implement,\n * even though diversity is low. Density captures this; diversity adds a penalty for\n * designs with scattered, unrelated issues.\n *\n * Status: initial values. To be validated via /calibrate-loop against visual-compare results.\n */\nconst DENSITY_WEIGHT = 0.7;\nconst DIVERSITY_WEIGHT = 0.3;\n\n/**\n * Minimum score floor.\n * Even the worst design gets 5% instead of 0%. Rationale: a score of 0 implies\n * \"completely unimplementable\", but any Figma file with visible nodes provides\n * some structural information. The floor also avoids demoralizing UX — seeing 0%\n * feels like the tool failed, not that the design needs improvement.\n */\nconst SCORE_FLOOR = 5;\n\n/**\n * Calculate grade from percentage.\n * Thresholds follow a 5-point interval pattern (95/90/85/80/75/70/65) with a wider\n * gap for D (50-64) and F (<50). This mirrors academic grading conventions where\n * the top tiers are tightly spaced and the failing range is broad.\n */\nfunction calculateGrade(percentage: number): Grade {\n if (percentage >= 95) return \"S\";\n if (percentage >= 90) return \"A+\";\n if (percentage >= 85) return \"A\";\n if (percentage >= 80) return \"B+\";\n if (percentage >= 75) return \"B\";\n if (percentage >= 70) return \"C+\";\n if (percentage >= 65) return \"C\";\n if (percentage >= 50) return \"D\";\n return \"F\";\n}\n\n/**\n * Convert grade to a CSS-safe class name suffix\n * e.g. \"A+\" -> \"Aplus\", \"B+\" -> \"Bplus\", \"C+\" -> \"Cplus\"\n */\nexport function gradeToClassName(grade: Grade): string {\n return grade.replace(\"+\", \"plus\");\n}\n\n/**\n * Clamp a value between min and max\n */\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * Calculate scores from analysis result using density + diversity scoring\n *\n * Density Score = 100 - (weighted issue count / node count) * 100\n * Diversity Score = (1 - weighted triggered rule scores / total category scores) * 100\n * Final Score = density * 0.7 + diversity * 0.3\n *\n * @param result Analysis result with issues\n * @param configs Optional preset-adjusted config map used to produce the issues.\n * If not provided, diversity totals are reconstructed from issue.config values.\n */\nexport function calculateScores(\n result: AnalysisResult,\n configs?: Record<RuleId, RuleConfig>\n): ScoreReport {\n const categoryScores = initializeCategoryScores();\n const nodeCount = result.nodeCount;\n\n // Track unique rules and their base |score| per category\n const uniqueRulesPerCategory = new Map<Category, Set<string>>();\n const ruleScorePerCategory = new Map<Category, Map<string, number>>();\n // Track issue counts per rule per category for sqrt damping (#226)\n const ruleIssueCountPerCategory = new Map<Category, Map<string, number>>();\n for (const category of CATEGORIES) {\n uniqueRulesPerCategory.set(category, new Set());\n ruleScorePerCategory.set(category, new Map());\n ruleIssueCountPerCategory.set(category, new Map());\n }\n\n // Compute totals from the config map.\n // If configs provided: use preset-adjusted totals (recommended when using presets).\n // If not: fall back to static RULE_CONFIGS — only correct when issues were\n // produced with default RULE_CONFIGS, otherwise diversity ratios will be skewed.\n const totalScorePerCategory = computeTotalScorePerCategory(configs ?? RULE_CONFIGS);\n\n // Count issues by severity per category and track unique rules with scores\n for (const issue of result.issues) {\n const category = issue.rule.definition.category;\n const severity = issue.config.severity;\n const ruleId = issue.rule.definition.id;\n\n categoryScores[category].issueCount++;\n categoryScores[category].bySeverity[severity]++;\n uniqueRulesPerCategory.get(category)!.add(ruleId);\n ruleScorePerCategory.get(category)!.set(ruleId, Math.abs(issue.config.score));\n // Accumulate per-rule issue count (using |calculatedScore| as weight unit)\n const ruleCountMap = ruleIssueCountPerCategory.get(category)!;\n ruleCountMap.set(ruleId, (ruleCountMap.get(ruleId) ?? 0) + 1);\n }\n\n // Compute weightedIssueCount with sqrt damping per rule (#226).\n // Same rule triggered N times contributes |score| × sqrt(N) instead of |score| × N.\n // Rationale: 79 raw-value issues represent one systemic problem, not 79× the difficulty.\n // First few occurrences identify the problem; subsequent ones have diminishing impact.\n // At low counts sqrt ≈ linear (sqrt(1)=1, sqrt(4)=2), preserving sensitivity for rare issues.\n for (const category of CATEGORIES) {\n const ruleCountMap = ruleIssueCountPerCategory.get(category)!;\n const ruleScoreMap = ruleScorePerCategory.get(category)!;\n let dampedWeight = 0;\n for (const [ruleId, count] of ruleCountMap) {\n const ruleScore = ruleScoreMap.get(ruleId) ?? 0;\n dampedWeight += ruleScore * Math.sqrt(count);\n }\n categoryScores[category].weightedIssueCount = dampedWeight;\n }\n\n // Calculate percentage for each category based on density + diversity\n for (const category of CATEGORIES) {\n const catScore = categoryScores[category];\n const uniqueRules = uniqueRulesPerCategory.get(category)!;\n\n catScore.uniqueRuleCount = uniqueRules.size;\n\n // Density score: lower density = higher score\n let densityScore = 100;\n if (nodeCount > 0 && catScore.issueCount > 0) {\n const density = catScore.weightedIssueCount / nodeCount;\n densityScore = clamp(Math.round(100 - density * 100), 0, 100);\n }\n catScore.densityScore = densityScore;\n\n // Diversity score: weighted by base rule |score| (config.score, not calculatedScore).\n // Uses base score intentionally — diversity measures \"what types of problems exist\",\n // not \"where they occur\". depthWeight affects density (volume penalty) but not diversity\n // (breadth penalty). A blocking rule (score -10) penalizes diversity more than a\n // suggestion (score -1), so low-severity-only designs correctly get high diversity scores.\n let diversityScore = 100;\n if (catScore.issueCount > 0) {\n const ruleScores = ruleScorePerCategory.get(category)!;\n const weightedTriggered = Array.from(ruleScores.values()).reduce((sum, s) => sum + s, 0);\n const weightedTotal = totalScorePerCategory[category];\n const diversityRatio = weightedTotal > 0 ? weightedTriggered / weightedTotal : 0;\n diversityScore = clamp(Math.round((1 - diversityRatio) * 100), 0, 100);\n }\n catScore.diversityScore = diversityScore;\n\n // Combined score with floor\n const combinedScore = densityScore * DENSITY_WEIGHT + diversityScore * DIVERSITY_WEIGHT;\n catScore.percentage = catScore.issueCount > 0\n ? clamp(Math.round(combinedScore), SCORE_FLOOR, 100)\n : 100;\n\n catScore.score = catScore.percentage;\n catScore.maxScore = 100;\n }\n\n // Calculate overall score as simple average of categories\n // Category importance is already encoded in rule scores (weight baked in),\n // so no per-category weighting is needed.\n let categorySum = 0;\n for (const category of CATEGORIES) {\n categorySum += categoryScores[category].percentage;\n }\n\n const overallPercentage = CATEGORIES.length > 0\n ? Math.round(categorySum / CATEGORIES.length)\n : 100;\n\n // Count issues by severity\n const summary = {\n totalIssues: result.issues.length,\n blocking: 0,\n risk: 0,\n missingInfo: 0,\n suggestion: 0,\n nodeCount,\n };\n\n for (const issue of result.issues) {\n switch (issue.config.severity) {\n case \"blocking\":\n summary.blocking++;\n break;\n case \"risk\":\n summary.risk++;\n break;\n case \"missing-info\":\n summary.missingInfo++;\n break;\n case \"suggestion\":\n summary.suggestion++;\n break;\n }\n }\n\n return {\n overall: {\n score: overallPercentage,\n maxScore: 100,\n percentage: overallPercentage,\n grade: calculateGrade(overallPercentage),\n },\n byCategory: categoryScores,\n summary,\n };\n}\n\n/**\n * Initialize empty category scores\n */\nfunction initializeCategoryScores(): Record<Category, CategoryScoreResult> {\n const scores: Partial<Record<Category, CategoryScoreResult>> = {};\n\n for (const category of CATEGORIES) {\n scores[category] = {\n category,\n score: 100,\n maxScore: 100,\n percentage: 100,\n issueCount: 0,\n uniqueRuleCount: 0,\n weightedIssueCount: 0,\n densityScore: 100,\n diversityScore: 100,\n bySeverity: {\n blocking: 0,\n risk: 0,\n \"missing-info\": 0,\n suggestion: 0,\n },\n };\n }\n\n return scores as Record<Category, CategoryScoreResult>;\n}\n\n/**\n * Format score report as a summary string\n */\nexport function formatScoreSummary(report: ScoreReport): string {\n const lines: string[] = [];\n\n lines.push(`Overall: ${report.overall.grade} (${report.overall.percentage}%)`);\n lines.push(\"\");\n lines.push(\"By Category:\");\n\n for (const category of CATEGORIES) {\n const cat = report.byCategory[category];\n lines.push(` ${category}: ${cat.percentage}% (${cat.issueCount} issues, ${cat.uniqueRuleCount} rules)`);\n }\n\n lines.push(\"\");\n lines.push(\"Issues:\");\n lines.push(` Blocking: ${report.summary.blocking}`);\n lines.push(` Risk: ${report.summary.risk}`);\n lines.push(` Missing Info: ${report.summary.missingInfo}`);\n lines.push(` Suggestion: ${report.summary.suggestion}`);\n lines.push(` Total: ${report.summary.totalIssues}`);\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Get category label for display\n */\nexport function getCategoryLabel(category: Category): string {\n return CATEGORY_LABELS[category];\n}\n\n/**\n * Get severity label for display\n */\nexport function getSeverityLabel(severity: Severity): string {\n const labels: Record<Severity, string> = {\n blocking: \"Blocking\",\n risk: \"Risk\",\n \"missing-info\": \"Missing Info\",\n suggestion: \"Suggestion\",\n };\n return labels[severity];\n}\n\n/**\n * Build a JSON-serializable analysis result summary.\n * Shared by CLI (--json) and MCP server (analyze tool response).\n */\nexport function buildResultJson(\n fileName: string,\n result: AnalysisResult,\n scores: ScoreReport,\n options?: { fileKey?: string },\n): Record<string, unknown> {\n const issuesByRule: Record<string, number> = {};\n for (const issue of result.issues) {\n const id = issue.violation.ruleId;\n issuesByRule[id] = (issuesByRule[id] ?? 0) + 1;\n }\n\n const issues = result.issues.map((issue) => ({\n ruleId: issue.violation.ruleId,\n ...(issue.violation.subType && { subType: issue.violation.subType }),\n severity: issue.config.severity,\n nodeId: issue.violation.nodeId,\n nodePath: issue.violation.nodePath,\n message: issue.violation.message,\n }));\n\n const json: Record<string, unknown> = {\n version: VERSION,\n analyzedAt: result.analyzedAt,\n ...(options?.fileKey && { fileKey: options.fileKey }),\n fileName,\n nodeCount: result.nodeCount,\n maxDepth: result.maxDepth,\n issueCount: result.issues.length,\n scores: {\n overall: scores.overall,\n categories: scores.byCategory,\n },\n issuesByRule,\n issues,\n summary: formatScoreSummary(scores),\n };\n\n if (result.failedRules.length > 0) {\n json[\"failedRules\"] = result.failedRules;\n }\n\n return json;\n}","// Shared UI constants — single source of truth for report-html (Node) and app/shared (browser)\n\nimport type { Category } from \"./contracts/category.js\";\nimport type { Severity } from \"./contracts/severity.js\";\n\n// Re-export category/severity constants that already exist\nexport { CATEGORIES, CATEGORY_LABELS } from \"./contracts/category.js\";\nexport { SEVERITY_LABELS } from \"./contracts/severity.js\";\n\n// Gauge geometry\nexport const GAUGE_R = 54;\nexport const GAUGE_C = Math.round(2 * Math.PI * GAUGE_R); // ~339\n\nexport const CATEGORY_DESCRIPTIONS: Record<Category, string> = {\n \"pixel-critical\":\n \"Auto Layout, absolute positioning, group usage — layout issues that directly affect pixel accuracy\",\n \"responsive-critical\":\n \"Fixed sizing, size constraints, responsive behavior — issues that break at different viewports\",\n \"code-quality\":\n \"Component reuse, detached instances, variant structure, nesting depth\",\n \"token-management\":\n \"Design token binding for colors, fonts, shadows, opacity, spacing grid\",\n \"interaction\":\n \"State variants for interactive components — hover, disabled, active, focus\",\n \"semantic\":\n \"Semantic layer names, naming conventions, default names\",\n};\n\nexport const SEVERITY_ORDER: Severity[] = [\n \"blocking\",\n \"risk\",\n \"missing-info\",\n \"suggestion\",\n];\n","// Shared UI helper functions — single source of truth for report-html (Node) and app/shared (browser)\n// All functions here must be pure (no Node.js or DOM dependencies)\n\nimport type { Severity } from \"./contracts/severity.js\";\nimport { GAUGE_R, GAUGE_C } from \"./ui-constants.js\";\n\n/** Map a percentage score to a color hex string */\nexport function gaugeColor(pct: number): string {\n if (pct >= 75) return \"#22c55e\";\n if (pct >= 50) return \"#f59e0b\";\n return \"#ef4444\";\n}\n\n/** Map a percentage score to a color class name (green/amber/red) */\nexport function scoreClass(pct: number): string {\n if (pct >= 75) return \"green\";\n if (pct >= 50) return \"amber\";\n return \"red\";\n}\n\n/** Escape HTML special characters — works in both Node.js and browser */\nexport function escapeHtml(text: string): string {\n return text\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#039;\");\n}\n\n\n/** Severity to CSS modifier class (used with .rpt-dot, .rpt-issue-score) */\nexport function severityDot(sev: Severity): string {\n const map: Record<Severity, string> = {\n blocking: \"sev-blocking\",\n risk: \"sev-risk\",\n \"missing-info\": \"sev-missing\",\n suggestion: \"sev-suggestion\",\n };\n return map[sev];\n}\n\n/** Severity to CSS modifier class (used with .rpt-issue-score) */\nexport function severityBadge(sev: Severity): string {\n const map: Record<Severity, string> = {\n blocking: \"sev-blocking\",\n risk: \"sev-risk\",\n \"missing-info\": \"sev-missing\",\n suggestion: \"sev-suggestion\",\n };\n return map[sev];\n}\n\n/** Score percentage to CSS modifier class (used with .rpt-badge) */\nexport function scoreBadgeStyle(pct: number): string {\n if (pct >= 75) return \"score-green\";\n if (pct >= 50) return \"score-amber\";\n return \"score-red\";\n}\n\n/** Render a circular gauge SVG string — works in both Node.js and browser */\nexport function renderGaugeSvg(\n pct: number,\n size: number,\n strokeW: number,\n grade?: string\n): string {\n const offset = GAUGE_C * (1 - pct / 100);\n const color = gaugeColor(pct);\n if (grade) {\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 120 120\" class=\"gauge-svg\">\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke-width=\"${strokeW}\" stroke=\"#e4e4e7\" />\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"${strokeW}\" stroke-linecap=\"round\" stroke-dasharray=\"${GAUGE_C}\" stroke-dashoffset=\"${offset}\" transform=\"rotate(-90 60 60)\" class=\"gauge-fill\" />\n <text x=\"60\" y=\"60\" text-anchor=\"middle\" dominant-baseline=\"central\" fill=\"currentColor\" font-size=\"48\" font-weight=\"700\" font-family=\"Inter,-apple-system,sans-serif\">${escapeHtml(grade)}</text>\n </svg>`;\n }\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 120 120\" class=\"gauge-svg\">\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke-width=\"${strokeW}\" stroke=\"#e4e4e7\" />\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"${strokeW}\" stroke-linecap=\"round\" stroke-dasharray=\"${GAUGE_C}\" stroke-dashoffset=\"${offset}\" transform=\"rotate(-90 60 60)\" class=\"gauge-fill\" />\n <text x=\"60\" y=\"62\" text-anchor=\"middle\" dominant-baseline=\"central\" fill=\"currentColor\" font-size=\"28\" font-weight=\"700\" font-family=\"Inter,-apple-system,sans-serif\">${pct}</text>\n </svg>`;\n}\n","/**\n * Pure template functions for report HTML rendering.\n * No Node.js dependencies — usable in browser via CanICode.* globals.\n *\n * Single source of truth for all report UI:\n * - CLI: generateHtmlReport() wraps with <html> shell\n * - Web app: CanICode.renderReportBody() → innerHTML\n * - Figma plugin: CanICode.renderReportBody() → innerHTML\n *\n * Layout: category tabs → rule sections (static info) → node accordion (dynamic info)\n * Styled via self-contained CSS (app/shared/styles.css) — no Tailwind dependency.\n */\n\nimport type { Category } from \"../contracts/category.js\";\nimport type { AnalysisIssue } from \"../engine/rule-engine.js\";\nimport type { ScoreReport } from \"../engine/scoring.js\";\nimport { version as VERSION } from \"../../../package.json\";\nimport { buildFigmaDeepLink } from \"../adapters/figma-url-parser.js\";\nimport {\n CATEGORIES,\n CATEGORY_LABELS,\n} from \"../ui-constants.js\";\nimport {\n escapeHtml,\n severityDot,\n severityBadge,\n renderGaugeSvg,\n} from \"../ui-helpers.js\";\n\n// ---- Data interface ----\n\nexport interface ReportData {\n fileName: string;\n fileKey: string;\n scores: ScoreReport;\n issues: AnalysisIssue[];\n nodeCount: number;\n maxDepth: number;\n figmaToken?: string;\n}\n\n/** Issues grouped by rule within a category */\ninterface RuleGroup {\n ruleId: string;\n ruleName: string;\n severity: string;\n severityClass: string;\n why: string;\n impact: string;\n fix: string;\n issues: AnalysisIssue[];\n totalScore: number;\n}\n\n// ---- Main render ----\n\n/**\n * Render the report body content (everything inside <main>).\n * Does NOT include <html>, <head>, <body> — caller wraps as needed.\n */\nexport function renderReportBody(data: ReportData): string {\n const { scores, issues, fileKey, figmaToken } = data;\n const issuesByCategory = groupIssuesByCategory(issues);\n const ruleOpportunities = getTopRules(issues, 5);\n\n return `\n <!-- Overall Score -->\n <section class=\"rpt-overall\">\n ${renderGaugeSvg(scores.overall.percentage, 200, 10, scores.overall.grade)}\n <div class=\"rpt-score\">\n <span class=\"rpt-score-value\">${scores.overall.percentage}</span>\n <span class=\"rpt-score-max\">/ 100</span>\n </div>\n <p class=\"rpt-score-label\">Overall Score</p>\n </section>\n\n <!-- Category Gauges -->\n <section class=\"card rpt-gauges\">\n <div class=\"rpt-gauges-grid\">\n${CATEGORIES.map((cat) => {\n const cs = scores.byCategory[cat];\n return ` <button type=\"button\" class=\"rpt-gauge-item\" data-tab=\"${cat}\">\n ${renderGaugeSvg(cs.percentage, 100, 7)}\n <span class=\"rpt-gauge-label\">${CATEGORY_LABELS[cat]}</span>\n <span class=\"rpt-gauge-count\">${cs.issueCount} issues</span>\n </button>`;\n }).join(\"\\n\")}\n </div>\n </section>\n\n <!-- Issue Summary -->\n <section class=\"card rpt-summary\">\n <div class=\"rpt-summary-inner\">\n ${renderSummaryDot(\"sev-blocking\", scores.summary.blocking, \"Blocking\")}\n ${renderSummaryDot(\"sev-risk\", scores.summary.risk, \"Risk\")}\n ${renderSummaryDot(\"sev-missing\", scores.summary.missingInfo, \"Missing Info\")}\n ${renderSummaryDot(\"sev-suggestion\", scores.summary.suggestion, \"Suggestion\")}\n <div class=\"rpt-summary-total\">\n <span class=\"rpt-summary-count\">${scores.summary.totalIssues}</span>\n <span class=\"rpt-summary-label\">Total</span>\n </div>\n </div>\n </section>\n\n${ruleOpportunities.length > 0 ? renderOpportunities(ruleOpportunities) : \"\"}\n\n <!-- Category Tabs -->\n <div class=\"rpt-tabs\">\n <div class=\"rpt-tab-list\" role=\"tablist\">\n${CATEGORIES.map((cat, i) => {\n const cs = scores.byCategory[cat];\n return ` <button type=\"button\" role=\"tab\" class=\"rpt-tab${i === 0 ? \" active\" : \"\"}\" data-tab=\"${cat}\" aria-selected=\"${i === 0}\">${CATEGORY_LABELS[cat]} <span class=\"rpt-tab-count\">${cs.issueCount}</span></button>`;\n }).join(\"\\n\")}\n </div>\n\n${CATEGORIES.map((cat, i) => {\n const catIssues = issuesByCategory.get(cat) ?? [];\n const ruleGroups = groupIssuesByRule(catIssues);\n return ` <div class=\"rpt-tab-panel${i === 0 ? \" active\" : \"\"}\" data-panel=\"${cat}\" role=\"tabpanel\">\n${ruleGroups.length === 0\n ? ' <div class=\"rpt-cat-empty\">No issues found</div>'\n : ruleGroups.map(rg => renderRuleSection(rg, fileKey, figmaToken)).join(\"\\n\")\n}\n </div>`;\n }).join(\"\\n\")}\n </div>\n\n <!-- Footer -->\n <footer class=\"rpt-footer\">\n <p class=\"rpt-footer-main\"><strong>CanICode</strong> <span style=\"opacity:0.5\">v${VERSION}</span></p>\n <p class=\"rpt-footer-meta\">${new Date().toLocaleString()} · ${data.nodeCount} nodes · Max depth ${data.maxDepth}</p>\n <p class=\"rpt-footer-links\"><a href=\"https://github.com/let-sunny/canicode/issues\" target=\"_blank\" rel=\"noopener\">Feedback</a> <span style=\"opacity:0.3\">&middot;</span> <a href=\"https://github.com/let-sunny/canicode/discussions/new?category=share-your-figma\" target=\"_blank\" rel=\"noopener\">Share your Figma</a></p>\n </footer>`;\n}\n\n// ---- Components ----\n\nexport function renderSummaryDot(sevClass: string, count: number, label: string): string {\n return `<div class=\"rpt-summary-item\">\n <span class=\"rpt-dot ${sevClass}\"></span>\n <span class=\"rpt-summary-count\">${count}</span>\n <span class=\"rpt-summary-label\">${label}</span>\n </div>`;\n}\n\nexport function renderOpportunities(ruleGroups: RuleGroup[]): string {\n const maxAbs = ruleGroups.reduce((m, rg) => Math.max(m, Math.abs(rg.totalScore)), 1);\n return `\n <!-- Opportunities -->\n <section class=\"card rpt-opps\">\n <div class=\"rpt-opps-header\">\n <h2 class=\"rpt-opps-title\">\n <span class=\"rpt-dot sev-blocking\"></span>\n Opportunities\n </h2>\n <p class=\"rpt-opps-desc\">Top impact rules — fix these first for the biggest improvement.</p>\n </div>\n <div class=\"rpt-opps-list\">\n${ruleGroups.map(rg => {\n const barW = Math.round((Math.abs(rg.totalScore) / maxAbs) * 100);\n const cat = rg.issues[0]?.rule.definition.category ?? \"\";\n return ` <div class=\"rpt-opps-item\" data-opp-rule=\"${esc(rg.ruleId)}\" data-opp-cat=\"${cat}\" style=\"cursor:pointer\">\n <div class=\"rpt-opps-info\">\n <div class=\"rpt-opps-name\">${esc(rg.ruleName)}</div>\n <div class=\"rpt-opps-msg\">${rg.issues.length} issues</div>\n </div>\n <div class=\"rpt-opps-bar-wrap\">\n <div class=\"rpt-opps-bar\">\n <div class=\"rpt-opps-bar-fill\" style=\"width:${barW}%\"></div>\n </div>\n <span class=\"rpt-opps-score\">${rg.totalScore}</span>\n </div>\n </div>`;\n }).join(\"\\n\")}\n </div>\n </section>`;\n}\n\nexport function renderRuleSection(\n rg: RuleGroup,\n fileKey: string,\n figmaToken?: string\n): string {\n const isOpen = rg.severity === \"blocking\" || rg.severity === \"risk\";\n return ` <details class=\"card rpt-rule\" data-rule=\"${esc(rg.ruleId)}\"${isOpen ? \" open\" : \"\"}>\n <summary class=\"rpt-rule-header\">\n <span class=\"rpt-badge score-red\">${rg.totalScore}</span>\n <span class=\"rpt-rule-title\">\n <span class=\"rpt-rule-name\">${esc(rg.ruleName)}</span>\n <span class=\"rpt-rule-meta\">\n <span class=\"rpt-dot-sm ${rg.severityClass}\"></span>\n ${esc(rg.severity)} · ${rg.issues.length} issues\n </span>\n <span class=\"rpt-rule-info\">\n <span class=\"rpt-rule-info-line\"><strong>Why:</strong> ${esc(rg.why)}</span>\n <span class=\"rpt-rule-info-line\"><strong>Impact:</strong> ${esc(rg.impact)}</span>\n <span class=\"rpt-rule-info-line\"><strong>Fix:</strong> ${esc(rg.fix)}</span>\n </span>\n </span>\n <svg class=\"rpt-rule-chevron no-print\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M19 9l-7 7-7-7\"/></svg>\n </summary>\n <div class=\"rpt-rule-issues\">\n${rg.issues.map(issue => renderIssueRow(issue, fileKey, figmaToken)).join(\"\\n\")}\n </div>\n </details>`;\n}\n\nexport function renderIssueRow(\n issue: AnalysisIssue,\n fileKey: string,\n figmaToken?: string\n): string {\n const sev = issue.config.severity;\n const v = issue.violation;\n const link = buildFigmaDeepLink(fileKey, v.nodeId);\n\n return ` <details class=\"rpt-issue\">\n <summary class=\"rpt-issue-header\">\n <span class=\"rpt-issue-msg\">${esc(v.message)}</span>\n <span class=\"rpt-issue-score ${severityBadge(sev)}\">${issue.calculatedScore}</span>\n </summary>\n <div class=\"rpt-issue-body\">\n <div class=\"rpt-issue-suggestion\">${esc(v.suggestion)}</div>${v.guide ? `\n <div class=\"rpt-issue-guide\">${esc(v.guide)}</div>` : \"\"}\n <div class=\"rpt-issue-path\">${esc(v.nodePath)}</div>\n <div class=\"rpt-issue-actions no-print\">\n <a href=\"${link}\" target=\"_blank\" rel=\"noopener\" data-node-id=\"${esc(v.nodeId)}\" class=\"rpt-btn\">Go to node <span>→</span></a>${figmaToken ? `\n <button onclick=\"postComment(this)\" data-file-key=\"${esc(fileKey)}\" data-node-id=\"${esc(v.nodeId)}\" data-message=\"${esc(v.message)} — ${esc(v.suggestion)}\" class=\"rpt-btn\">Comment on Figma</button>` : \"\"}\n </div>\n </div>\n </details>`;\n}\n\n// ---- Interactions ----\n\n/**\n * Initialize tab switching + navigation for a rendered report.\n * Call after inserting renderReportBody() HTML into a container.\n * Uses 'any' to avoid DOM type dependency (this file targets Node.js).\n */\nexport function initReportInteractions(container: any): void {\n // Remove previous handler if re-initialized (e.g., re-analysis)\n if (container._rptHandler) {\n container.removeEventListener(\"click\", container._rptHandler);\n }\n function activate(cat: string, scrollTo: boolean) {\n container.querySelectorAll(\".rpt-tab\").forEach((t: any) => {\n const active = t.dataset.tab === cat;\n t.classList.toggle(\"active\", active);\n t.setAttribute(\"aria-selected\", String(active));\n });\n container.querySelectorAll(\".rpt-tab-panel\").forEach((p: any) => {\n p.classList.toggle(\"active\", p.dataset.panel === cat);\n });\n if (scrollTo) {\n const tabList = container.querySelector(\".rpt-tab-list\");\n if (tabList) tabList.scrollIntoView({ behavior: \"smooth\", block: \"start\" });\n }\n }\n function focusRule(ruleId: string) {\n const el = container.querySelector('[data-rule=\"' + ruleId + '\"]');\n if (el) {\n el.open = true;\n setTimeout(() => el.scrollIntoView({ behavior: \"smooth\", block: \"start\" }), 50);\n }\n }\n const handler = (e: any) => {\n const tab = e.target.closest(\"[data-tab]\");\n if (tab) {\n const isGauge = tab.classList.contains(\"rpt-gauge-item\");\n activate(tab.dataset.tab ?? \"\", isGauge);\n return;\n }\n const opp = e.target.closest(\"[data-opp-rule]\");\n if (opp) {\n const cat = opp.dataset.oppCat ?? \"\";\n const rule = opp.dataset.oppRule ?? \"\";\n if (cat) activate(cat, false);\n setTimeout(() => focusRule(rule), 50);\n }\n };\n container._rptHandler = handler;\n container.addEventListener(\"click\", handler);\n}\n\n// ---- Utils ----\n\n/** Get top N rules by total score impact */\nfunction getTopRules(issues: AnalysisIssue[], limit: number): RuleGroup[] {\n const byRule = new Map<string, RuleGroup>();\n for (const issue of issues) {\n const id = issue.rule.definition.id;\n let group = byRule.get(id);\n if (!group) {\n const def = issue.rule.definition;\n group = {\n ruleId: id,\n ruleName: def.name,\n severity: issue.config.severity,\n severityClass: severityDot(issue.config.severity),\n why: def.why,\n impact: def.impact,\n fix: def.fix,\n issues: [],\n totalScore: 0,\n };\n byRule.set(id, group);\n }\n group.issues.push(issue);\n group.totalScore += issue.calculatedScore;\n }\n return [...byRule.values()]\n .sort((a, b) => a.totalScore - b.totalScore)\n .slice(0, limit);\n}\n\nfunction groupIssuesByCategory(issues: AnalysisIssue[]): Map<Category, AnalysisIssue[]> {\n const grouped = new Map<Category, AnalysisIssue[]>();\n for (const category of CATEGORIES) grouped.set(category, []);\n for (const issue of issues) grouped.get(issue.rule.definition.category)!.push(issue);\n return grouped;\n}\n\n/** Group issues by rule within a category, sorted by severity then score */\nfunction groupIssuesByRule(issues: AnalysisIssue[]): RuleGroup[] {\n const byRule = new Map<string, RuleGroup>();\n for (const issue of issues) {\n const id = issue.rule.definition.id;\n let group = byRule.get(id);\n if (!group) {\n const def = issue.rule.definition;\n group = {\n ruleId: id,\n ruleName: def.name,\n severity: issue.config.severity,\n severityClass: severityDot(issue.config.severity),\n why: def.why,\n impact: def.impact,\n fix: def.fix,\n issues: [],\n totalScore: 0,\n };\n byRule.set(id, group);\n }\n group.issues.push(issue);\n group.totalScore += issue.calculatedScore;\n }\n\n const SEVERITY_RANK: Record<string, number> = { blocking: 0, risk: 1, \"missing-info\": 2, suggestion: 3 };\n return [...byRule.values()].sort((a, b) => {\n const sevDiff = (SEVERITY_RANK[a.severity] ?? 4) - (SEVERITY_RANK[b.severity] ?? 4);\n return sevDiff !== 0 ? sevDiff : a.totalScore - b.totalScore;\n });\n}\n\nconst esc = escapeHtml;\n","// Report HTML module — full page generation for CLI\n// Rendering logic lives in render.ts (shared with web/plugin)\n\nimport type { AnalysisFile } from \"../contracts/figma-node.js\";\nimport type { AnalysisResult } from \"../engine/rule-engine.js\";\nimport type { ScoreReport } from \"../engine/scoring.js\";\nimport { escapeHtml } from \"../ui-helpers.js\";\nimport { renderReportBody, initReportInteractions } from \"./render.js\";\nimport type { ReportData } from \"./render.js\";\n\ndeclare const __REPORT_CSS__: string;\nconst reportCss: string = __REPORT_CSS__;\n\nexport type { ReportData } from \"./render.js\";\nexport { renderReportBody, initReportInteractions } from \"./render.js\";\n\nexport interface NodeScreenshot {\n nodeId: string;\n nodePath: string;\n screenshotBase64: string;\n issueCount: number;\n topSeverity: string;\n}\n\nexport interface HtmlReportOptions {\n nodeScreenshots?: NodeScreenshot[];\n figmaToken?: string | undefined;\n}\n\nconst esc = escapeHtml;\n\n/**\n * Generate a complete standalone HTML report page.\n * Used by CLI — opens in browser.\n */\nexport function generateHtmlReport(\n file: AnalysisFile,\n result: AnalysisResult,\n scores: ScoreReport,\n options?: HtmlReportOptions\n): string {\n const figmaToken = options?.figmaToken;\n\n const data: ReportData = {\n fileName: file.name,\n fileKey: file.fileKey,\n scores,\n issues: result.issues,\n nodeCount: result.nodeCount,\n maxDepth: result.maxDepth,\n ...(figmaToken && { figmaToken }),\n };\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>CanICode Report — ${esc(file.name)}</title>\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n <link href=\"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap\" rel=\"stylesheet\">\n <style>\n${reportCss}\n .cli-topbar {\n background: #09090b; color: white;\n border-bottom: 1px solid #27272a;\n }\n .cli-topbar-inner {\n max-width: 960px; margin: 0 auto;\n padding: 12px 24px;\n display: flex; align-items: center; gap: 16px;\n }\n .cli-topbar-logo { font-weight: 600; font-size: 14px; letter-spacing: -0.01em; }\n .cli-topbar-file { color: #a1a1aa; font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .cli-topbar-date { margin-left: auto; color: #71717a; font-size: 12px; }\n .cli-main { max-width: 960px; margin: 0 auto; padding: 0 24px 64px; }\n @media print {\n .cli-topbar { position: static !important; background: white !important; color: var(--fg) !important; }\n .cli-topbar-file { color: var(--fg-muted) !important; }\n }\n </style>\n</head>\n<body>\n\n <!-- Top Bar -->\n <header class=\"cli-topbar\">\n <div class=\"cli-topbar-inner\">\n <span class=\"cli-topbar-logo\">CanICode</span>\n <span class=\"cli-topbar-file\">${esc(file.name)}</span>\n <span class=\"cli-topbar-date no-print\">${new Date().toLocaleDateString()}</span>\n </div>\n </header>\n\n <main class=\"cli-main\">\n${renderReportBody(data)}\n </main>\n\n <script>(${String(initReportInteractions)})(document.querySelector('.cli-main'));</script>\n${figmaToken ? renderFigmaCommentScript(figmaToken) : \"\"}\n</body>\n</html>`;\n}\n\nfunction renderFigmaCommentScript(figmaToken: string): string {\n return ` <script>\n const FIGMA_TOKEN = '${figmaToken}';\n async function postComment(btn) {\n const fileKey = btn.dataset.fileKey;\n const nodeId = btn.dataset.nodeId.replace(/-/g, ':');\n const commentNodeId = nodeId.split(';')[0].replace(/^I/, '');\n const message = btn.dataset.message;\n const commentBody = '[CanICode] ' + message;\n btn.disabled = true;\n btn.textContent = 'Sending...';\n btn.title = '';\n try {\n const res = await fetch('https://api.figma.com/v1/files/' + fileKey + '/comments', {\n method: 'POST',\n headers: { 'X-FIGMA-TOKEN': FIGMA_TOKEN, 'Content-Type': 'application/json' },\n body: JSON.stringify({ message: commentBody, client_meta: { node_id: commentNodeId, node_offset: { x: 0, y: 0 } } }),\n });\n if (!res.ok) {\n const errBody = await res.text().catch(() => '');\n const errMsg = res.status === 400 ? 'Bad request' : res.status === 403 ? 'Token lacks file access' : res.status === 404 ? 'File not found' : res.status === 429 ? 'Rate limited' : 'HTTP ' + res.status;\n throw new Error(errMsg + (errBody ? ': ' + errBody.slice(0, 100) : ''));\n }\n btn.textContent = 'Sent';\n btn.classList.remove('rpt-btn-fail');\n btn.classList.add('rpt-btn-ok');\n } catch (e) {\n btn.textContent = 'Failed';\n btn.title = e.message || String(e);\n btn.classList.remove('rpt-btn-ok');\n btn.classList.add('rpt-btn-fail');\n btn.disabled = false;\n }\n }\n </script>`;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { z } from \"zod\";\nimport { SeveritySchema } from \"../contracts/severity.js\";\nimport type { RuleConfig } from \"../contracts/rule.js\";\nimport { RULE_CONFIGS } from \"./rule-config.js\";\n\nconst VALID_RULE_IDS = new Set(Object.keys(RULE_CONFIGS));\n\nconst RuleOverrideSchema = z.object({\n score: z.number().int().max(0).optional(),\n severity: SeveritySchema.optional(),\n enabled: z.boolean().optional(),\n});\n\nconst ConfigFileSchema = z.object({\n excludeNodeTypes: z.array(z.string()).optional(),\n excludeNodeNames: z.array(z.string()).optional(),\n gridBase: z.number().int().positive().optional(),\n rules: z.record(z.string(), RuleOverrideSchema)\n .superRefine((rules, ctx) => {\n const unknown = Object.keys(rules).filter((id) => !VALID_RULE_IDS.has(id));\n if (unknown.length > 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Unknown rule ID(s): ${unknown.join(\", \")}. Valid IDs: ${[...VALID_RULE_IDS].join(\", \")}`,\n });\n }\n })\n .optional(),\n});\n\nexport type ConfigFile = z.infer<typeof ConfigFileSchema>;\n\nexport async function loadConfigFile(filePath: string): Promise<ConfigFile> {\n const absPath = resolve(filePath);\n const raw = await readFile(absPath, \"utf-8\");\n const parsed: unknown = JSON.parse(raw);\n return ConfigFileSchema.parse(parsed);\n}\n\n/**\n * Merge config overrides into the base rule configs\n */\nexport function mergeConfigs(\n base: Record<string, RuleConfig>,\n overrides: ConfigFile,\n): Record<string, RuleConfig> {\n const merged = { ...base };\n\n // Apply global gridBase to relevant rules\n if (overrides.gridBase !== undefined) {\n for (const [id, config] of Object.entries(merged)) {\n if (config.options && \"gridBase\" in config.options) {\n merged[id] = {\n ...config,\n options: { ...config.options, gridBase: overrides.gridBase },\n };\n }\n }\n }\n\n // Apply per-rule overrides\n if (overrides.rules) {\n for (const [ruleId, override] of Object.entries(overrides.rules)) {\n const existing = merged[ruleId];\n if (existing) {\n merged[ruleId] = {\n ...existing,\n ...(override.score !== undefined && { score: override.score }),\n ...(override.severity !== undefined && { severity: override.severity }),\n ...(override.enabled !== undefined && { enabled: override.enabled }),\n };\n }\n }\n }\n\n return merged;\n}\n","/**\n * Typed event definitions for PostHog analytics.\n * All events are prefixed with `cic_` (CanICode) to distinguish\n * from noise/spam in PostHog dashboards.\n *\n * Only event metadata is tracked — no design data, tokens, or file contents.\n */\n\n/** Event name prefix — use this to filter genuine events in PostHog */\nexport const EVENT_PREFIX = \"cic_\";\n\nexport const EVENTS = {\n // Analysis\n ANALYSIS_STARTED: `${EVENT_PREFIX}analysis_started`,\n ANALYSIS_COMPLETED: `${EVENT_PREFIX}analysis_completed`,\n ANALYSIS_FAILED: `${EVENT_PREFIX}analysis_failed`,\n\n // Report\n REPORT_GENERATED: `${EVENT_PREFIX}report_generated`,\n COMMENT_POSTED: `${EVENT_PREFIX}comment_posted`,\n COMMENT_FAILED: `${EVENT_PREFIX}comment_failed`,\n\n // MCP\n MCP_TOOL_CALLED: `${EVENT_PREFIX}mcp_tool_called`,\n\n // CLI\n CLI_COMMAND: `${EVENT_PREFIX}cli_command`,\n CLI_INIT: `${EVENT_PREFIX}cli_init`,\n} as const;\n\nexport type EventName = (typeof EVENTS)[keyof typeof EVENTS];\n","/**\n * Unified fetch-based monitoring capture for all environments (CLI, MCP, browser, plugin).\n *\n * No external dependencies — uses native `fetch` (Node 18+ / browser).\n * All operations are fire-and-forget; never throws.\n */\n\nimport type { MonitoringConfig } from \"./types.js\";\n\nlet monitoringEnabled = false;\nlet posthogApiKey: string | undefined;\nlet sentryDsn: string | undefined;\nlet distinctId = \"anonymous\";\nlet environment = \"unknown\";\nlet version = \"unknown\";\nlet commonProps: Record<string, unknown> = {};\n\n/** Generate a simple UUID v4 (no crypto dependency needed for monitoring) */\nfunction uuid4(): string {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/** Parse Sentry DSN into components */\nfunction parseSentryDsn(dsn: string): { key: string; host: string; projectId: string } | null {\n try {\n // DSN format: https://{key}@{host}/{projectId}\n const url = new URL(dsn);\n const key = url.username;\n const projectId = url.pathname.slice(1); // remove leading /\n const host = url.protocol + \"//\" + url.host;\n if (!key || !projectId) return null;\n return { key, host, projectId };\n } catch {\n return null;\n }\n}\n\nexport function initCapture(config: MonitoringConfig): void {\n if (config.enabled === false) return;\n if (!config.posthogApiKey && !config.sentryDsn) return;\n\n monitoringEnabled = true;\n posthogApiKey = config.posthogApiKey;\n sentryDsn = config.sentryDsn;\n distinctId = config.distinctId ?? \"anonymous\";\n environment = config.environment ?? \"unknown\";\n version = config.version ?? \"unknown\";\n commonProps = {\n _sdk: \"canicode\",\n _sdk_version: version,\n _env: environment,\n };\n}\n\nexport function captureEvent(event: string, properties?: Record<string, unknown>): void {\n if (!monitoringEnabled || !posthogApiKey) return;\n\n try {\n fetch(\"https://us.i.posthog.com/i/v0/e/\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n api_key: posthogApiKey,\n event,\n distinct_id: distinctId,\n properties: { ...commonProps, ...properties },\n timestamp: new Date().toISOString(),\n }),\n }).catch(() => {});\n } catch {\n // never throw from monitoring\n }\n}\n\nexport function captureError(error: Error, context?: Record<string, unknown>): void {\n if (!monitoringEnabled) return;\n\n // Send to Sentry via envelope API\n if (sentryDsn) {\n const parsed = parseSentryDsn(sentryDsn);\n if (parsed) {\n try {\n const eventId = uuid4();\n const envelope = [\n JSON.stringify({ event_id: eventId, sent_at: new Date().toISOString(), dsn: sentryDsn }),\n JSON.stringify({ type: \"event\", content_type: \"application/json\" }),\n JSON.stringify({\n event_id: eventId,\n exception: { values: [{ type: error.name, value: error.message }] },\n platform: \"node\",\n environment,\n release: `canicode@${version}`,\n timestamp: Date.now() / 1000,\n extra: context,\n }),\n ].join(\"\\n\");\n\n fetch(`${parsed.host}/api/${parsed.projectId}/envelope/`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-sentry-envelope\",\n \"X-Sentry-Auth\": `Sentry sentry_version=7, sentry_key=${parsed.key}`,\n },\n body: envelope,\n }).catch(() => {});\n } catch {\n // never throw from monitoring\n }\n }\n }\n\n // Also send to PostHog as error event\n captureEvent(\"cic_error\", { error: error.message, ...context });\n}\n\nexport function shutdownCapture(): void {\n monitoringEnabled = false;\n posthogApiKey = undefined;\n sentryDsn = undefined;\n distinctId = \"anonymous\";\n environment = \"unknown\";\n version = \"unknown\";\n commonProps = {};\n}\n","/**\n * Shared monitoring module that works across CLI, MCP, and browser environments.\n *\n * Key design principles:\n * - If no API keys are configured, all functions are silent no-ops\n * - All tracking is fire-and-forget (never blocks or throws)\n * - Zero external dependencies — uses native fetch (Node 18+ / browser)\n * - CLI users can opt out via `canicode config --no-telemetry`\n * - No design data, tokens, or file contents are ever sent\n */\n\nexport type { MonitoringConfig } from \"./types.js\";\nexport { EVENTS } from \"./events.js\";\nexport type { EventName } from \"./events.js\";\n\nimport type { MonitoringConfig } from \"./types.js\";\nimport { initCapture, captureEvent, captureError, shutdownCapture } from \"./capture.js\";\n\n/**\n * Initialise monitoring for the current environment.\n * Safe to call multiple times — subsequent calls are ignored.\n */\nexport function initMonitoring(config: MonitoringConfig): void {\n initCapture(config);\n}\n\n/**\n * Track an analytics event. Fire-and-forget; never throws.\n */\nexport function trackEvent(event: string, properties?: Record<string, unknown>): void {\n try {\n captureEvent(event, properties);\n } catch {\n // never throw from monitoring\n }\n}\n\n/**\n * Track an error. Fire-and-forget; never throws.\n */\nexport function trackError(error: Error, context?: Record<string, unknown>): void {\n try {\n captureError(error, context);\n } catch {\n // never throw from monitoring\n }\n}\n\n/**\n * Shut down monitoring. Call before process exit.\n */\nexport function shutdownMonitoring(): void {\n try {\n shutdownCapture();\n } catch {\n // never throw from monitoring\n }\n}\n","/**\n * Monitoring keys injected at build time via tsup `define`.\n * These are replaced with actual values during CI builds.\n * Locally they default to empty strings (monitoring disabled).\n */\n\ndeclare const __POSTHOG_API_KEY__: string;\ndeclare const __SENTRY_DSN__: string;\n\nexport const POSTHOG_API_KEY: string =\n typeof __POSTHOG_API_KEY__ !== \"undefined\" ? __POSTHOG_API_KEY__ : \"\";\nexport const SENTRY_DSN: string =\n typeof __SENTRY_DSN__ !== \"undefined\" ? __SENTRY_DSN__ : \"\";\n","/**\n * Centralized node semantic classification.\n * All \"what is this node?\" logic lives here so rules share the same predicates.\n *\n * Categories:\n * - Container: layout containers (frame, group, component, instance)\n * - Visual: decorative/graphic elements (vector, shape, image)\n * - Interactive: user-interactable elements (button, link, tab, input, toggle)\n * - Overlay: elements that open on top (modal, drawer, dropdown)\n * - Carousel: elements that slide/swipe (carousel, slider, gallery)\n * - Token: style/variable binding checks\n * - Naming: name pattern classification\n */\n\nimport type { AnalysisNode } from \"../contracts/figma-node.js\";\n\n// ── Container classification ─────────────────────────────────────────────────\n\nexport function isContainerNode(node: AnalysisNode): boolean {\n return node.type === \"FRAME\" || node.type === \"GROUP\" || node.type === \"COMPONENT\" || node.type === \"INSTANCE\";\n}\n\nexport function hasAutoLayout(node: AnalysisNode): boolean {\n return node.layoutMode !== undefined && node.layoutMode !== \"NONE\";\n}\n\nexport function hasTextContent(node: AnalysisNode): boolean {\n return node.type === \"TEXT\" || (node.children?.some((c) => c.type === \"TEXT\") ?? false);\n}\n\nexport function hasOverlappingBounds(a: AnalysisNode, b: AnalysisNode): boolean {\n const boxA = a.absoluteBoundingBox;\n const boxB = b.absoluteBoundingBox;\n\n if (!boxA || !boxB) return false;\n\n return !(\n boxA.x + boxA.width <= boxB.x ||\n boxB.x + boxB.width <= boxA.x ||\n boxA.y + boxA.height <= boxB.y ||\n boxB.y + boxB.height <= boxA.y\n );\n}\n\n// ── Visual classification ────────────────────────────────────────────────────\n\nconst VISUAL_LEAF_TYPES = new Set([\n \"VECTOR\", \"BOOLEAN_OPERATION\", \"ELLIPSE\", \"LINE\", \"STAR\", \"REGULAR_POLYGON\", \"RECTANGLE\",\n]);\n\nexport function isVisualLeafType(type: string): boolean {\n return VISUAL_LEAF_TYPES.has(type);\n}\n\nexport function hasImageFill(node: AnalysisNode): boolean {\n if (!Array.isArray(node.fills)) return false;\n return node.fills.some(\n (fill) =>\n typeof fill === \"object\" &&\n fill !== null &&\n (fill as { type?: unknown }).type === \"IMAGE\",\n );\n}\n\nexport function isVisualOnlyNode(node: AnalysisNode): boolean {\n if (VISUAL_LEAF_TYPES.has(node.type)) return true;\n const hasOnlyVisualChildren =\n node.children !== undefined &&\n node.children.length > 0 &&\n node.children.every((c) => VISUAL_LEAF_TYPES.has(c.type));\n // Image fill only counts as visual-only when there are no content children\n if (hasImageFill(node) && (!node.children || node.children.length === 0 || hasOnlyVisualChildren)) {\n return true;\n }\n if (hasOnlyVisualChildren) return true;\n return false;\n}\n\n// ── Interactive classification ───────────────────────────────────────────────\n\nexport type StatefulComponentType = \"button\" | \"link\" | \"tab\" | \"input\" | \"toggle\";\n\n/** Name patterns → interactive type mapping */\nexport const STATEFUL_PATTERNS: Array<{ pattern: RegExp; type: StatefulComponentType }> = [\n { pattern: /\\b(btn|button|cta)\\b/i, type: \"button\" },\n { pattern: /\\b(link|anchor)\\b/i, type: \"link\" },\n { pattern: /\\b(tab|tabs)\\b/i, type: \"tab\" },\n { pattern: /\\b(nav|navigation|menu|navbar)\\b/i, type: \"tab\" },\n { pattern: /\\b(input|text-?field|search-?bar|textarea)\\b/i, type: \"input\" },\n { pattern: /\\b(select|dropdown|combo-?box)\\b/i, type: \"input\" },\n { pattern: /\\b(toggle|switch|checkbox|radio)\\b/i, type: \"toggle\" },\n];\n\nexport function getStatefulComponentType(node: AnalysisNode): StatefulComponentType | null {\n if (!node.name) return null;\n for (const entry of STATEFUL_PATTERNS) {\n if (entry.pattern.test(node.name)) return entry.type;\n }\n return null;\n}\n\nexport function isStatefulComponent(node: AnalysisNode): boolean {\n return getStatefulComponentType(node) !== null;\n}\n\n/**\n * Standard state names across web + mobile platforms.\n * Used by missing-interaction-state (to detect presence) and\n * non-standard-naming (to flag non-standard names).\n *\n * Sources:\n * - CSS: :hover, :active, :focus, :disabled, :enabled — https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/Pseudo-classes\n * - Material Design 3: Hovered, Focused, Pressed, Dragged — https://m3.material.io/foundations/interaction/states\n * - UIKit: highlighted, selected, disabled, focused — https://developer.apple.com/documentation/uikit/uicontrol/state\n */\nexport const STANDARD_STATE_NAMES = new Set([\n // CSS pseudo-classes (web)\n \"default\", \"hover\", \"active\", \"focus\", \"focused\", \"disabled\", \"enabled\",\n // Material Design 3 (Android)\n \"pressed\", \"dragged\",\n // UIKit (iOS)\n \"highlighted\",\n // Common\n \"selected\",\n]);\n\n/**\n * Patterns that look like state names but aren't in the standard set.\n * Maps common non-standard names to their standard equivalent for suggestions.\n */\nexport const STATE_NAME_SUGGESTIONS: Record<string, string> = {\n on: \"active\",\n off: \"default\",\n clicked: \"pressed\",\n tapped: \"pressed\",\n inactive: \"disabled\",\n normal: \"default\",\n rest: \"default\",\n hovered: \"hover\",\n activated: \"active\",\n checked: \"selected\",\n unchecked: \"default\",\n};\n\n/** Pattern to detect state-like variant option names (broad match) */\nexport const STATE_LIKE_PATTERN = /\\b(on|off|clicked|tapped|inactive|normal|rest|hovered|activated|checked|unchecked)\\b/i;\n\n// ── Overlay / Carousel patterns ──────────────────────────────────────────────\n\n/** Elements that open on top of current view */\nexport const OVERLAY_PATTERN = /\\b(dropdown|select|combo-?box|popover|accordion|drawer|modal|bottom-?sheet|sheet|sidebar|panel|dialog|popup|toast)\\b/i;\n\n/** Elements that swipe/slide between items */\nexport const CAROUSEL_PATTERN = /\\b(carousel|slider|swiper|slide-?show|gallery)\\b/i;\n\nexport function isOverlayNode(node: AnalysisNode): boolean {\n return node.name !== undefined && OVERLAY_PATTERN.test(node.name);\n}\n\nexport function isCarouselNode(node: AnalysisNode): boolean {\n return node.name !== undefined && CAROUSEL_PATTERN.test(node.name);\n}\n\n// ── Token classification ─────────────────────────────────────────────────────\n\nexport function hasStyleReference(node: AnalysisNode, styleType: string): boolean {\n return node.styles !== undefined && styleType in node.styles;\n}\n\nexport function hasBoundVariable(node: AnalysisNode, key: string): boolean {\n return node.boundVariables !== undefined && key in node.boundVariables;\n}\n\n// ── Naming patterns ──────────────────────────────────────────────────────────\n\n/** Figma default name patterns (Frame 1, Group 2, etc.) */\nexport const DEFAULT_NAME_PATTERNS = [\n /^Frame\\s*\\d*$/i,\n /^Group\\s*\\d*$/i,\n /^Rectangle\\s*\\d*$/i,\n /^Ellipse\\s*\\d*$/i,\n /^Vector\\s*\\d*$/i,\n /^Line\\s*\\d*$/i,\n /^Text\\s*\\d*$/i,\n /^Image\\s*\\d*$/i,\n /^Component\\s*\\d*$/i,\n /^Instance\\s*\\d*$/i,\n];\n\nexport function isDefaultName(name: string): boolean {\n return DEFAULT_NAME_PATTERNS.some((pattern) => pattern.test(name));\n}\n\n/** Shape-only non-semantic names */\nexport const NON_SEMANTIC_NAMES = [\n \"rectangle\", \"ellipse\", \"vector\", \"line\", \"polygon\",\n \"star\", \"path\", \"shape\", \"image\", \"fill\", \"stroke\",\n];\n\nexport function isNonSemanticName(name: string): boolean {\n return NON_SEMANTIC_NAMES.includes(name.toLowerCase().trim());\n}\n\n// ── Exclusion ────────────────────────────────────────────────────────────────\n\nexport const EXCLUDED_NAME_PATTERN = /(badge|close|dismiss|overlay|float|fab|dot|indicator|corner|decoration|tag|status|notification|icon|ico|image|asset|filter|dim|dimmed|bg|background|logo|avatar|divider|separator|nav|navigation|gnb|header|footer|sidebar|toolbar|modal|dialog|popup|toast|tooltip|dropdown|menu|sticky|spinner|loader|cursor|cta|chatbot|thumb|thumbnail|tabbar|tab-bar|statusbar|status-bar)/i;\n\nexport function isExcludedName(name: string): boolean {\n return EXCLUDED_NAME_PATTERN.test(name);\n}\n","import type { AnalysisNode } from \"../contracts/figma-node.js\";\nimport type { RuleContext } from \"../contracts/rule.js\";\nimport { isVisualLeafType, isVisualOnlyNode, isExcludedName } from \"./node-semantics.js\";\n\n// ============================================\n// Auto-layout exceptions\n// ============================================\n\n/** Frames that don't need auto-layout (only visual-leaf children like icon paths) */\nexport function isAutoLayoutExempt(node: AnalysisNode): boolean {\n if (\n node.children &&\n node.children.length > 0 &&\n node.children.every((c) => isVisualLeafType(c.type))\n ) return true;\n\n return false;\n}\n\n// ============================================\n// Absolute-position exceptions\n// ============================================\n\n/** Nodes that are allowed to use absolute positioning inside auto-layout */\nexport function isAbsolutePositionExempt(node: AnalysisNode): boolean {\n if (isVisualOnlyNode(node)) return true;\n\n // Intentional name patterns (badge, close, overlay, etc.)\n if (isExcludedName(node.name)) return true;\n\n return false;\n}\n\n// ============================================\n// Size-constraint exceptions\n// ============================================\n\n/** Nodes that don't need maxWidth even with FILL sizing */\nexport function isSizeConstraintExempt(node: AnalysisNode, context: RuleContext): boolean {\n // Already has maxWidth\n if (node.maxWidth !== undefined) return true;\n\n // Parent already has maxWidth — parent constrains the stretch\n if (context.parent?.maxWidth !== undefined) return true;\n\n // Root-level frames — they represent the screen itself\n if (context.depth <= 1) return true;\n\n return false;\n}\n\n// ============================================\n// Fixed-size exceptions\n// ============================================\n\n/** Nodes that are allowed to use fixed sizing inside auto-layout */\nexport function isFixedSizeExempt(node: AnalysisNode): boolean {\n // Visual-only nodes (icons, images, shapes) — intentionally fixed\n if (isVisualOnlyNode(node)) return true;\n\n // Excluded names (nav, header, etc.)\n if (isExcludedName(node.name)) return true;\n\n return false;\n}\n","/**\n * Centralized rule violation messages.\n * All message text lives here so CLI, web, plugin, and MCP share the same strings.\n *\n * Each message function returns { message, suggestion, guide? }:\n * - message: what's wrong (node-specific, dynamic)\n * - suggestion: how to fix it (node-specific, dynamic)\n * - guide: exemption hint (optional, when the rule auto-excludes certain cases)\n */\n\n// ── Message return type ─────────────────────────────────────────────────────\n\nexport interface ViolationMsg {\n message: string;\n suggestion: string;\n guide?: string;\n}\n\n// ── Sub-type definitions ─────────────────────────────────────────────────────\n\nexport type RawValueSubType = \"color\" | \"font\" | \"shadow\" | \"opacity\" | \"spacing\";\nexport type NoAutoLayoutSubType = \"overlapping\" | \"nested\" | \"basic\";\nexport type FixedSizeSubType = \"both-axes\" | \"horizontal\";\nexport type MissingComponentSubType = \"unused-component\" | \"name-repetition\" | \"structure-repetition\" | \"style-override\";\n\n// ── raw-value ────────────────────────────────────────────────────────────────\n\nexport const rawValueMsg = {\n color: (name: string, hex: string): ViolationMsg => ({\n message: `\"${name}\" uses raw fill color ${hex} without style or variable`,\n suggestion: `Bind to a color token`,\n }),\n font: (name: string, fontDesc: string): ViolationMsg => ({\n message: `\"${name}\" uses raw font${fontDesc} without text style`,\n suggestion: `Apply a text style`,\n }),\n shadow: (name: string, shadowType: string, details: string): ViolationMsg => ({\n message: `\"${name}\" has ${shadowType}${details} without effect style`,\n suggestion: `Apply an effect style`,\n }),\n opacity: (name: string, pct: number): ViolationMsg => ({\n message: `\"${name}\" uses raw opacity (${pct}%) without a variable binding`,\n suggestion: `Bind opacity to a variable`,\n }),\n spacing: (name: string, label: string, value: number): ViolationMsg => ({\n message: `\"${name}\" uses raw ${label} (${value}px) without a variable binding`,\n suggestion: `Bind spacing to a variable`,\n }),\n};\n\n// ── irregular-spacing ────────────────────────────────────────────────────────\n\nexport type IrregularSpacingSubType = \"padding\" | \"gap\";\n\nexport const irregularSpacingMsg = (name: string, spacing: number, gridBase: number, nearest: number): ViolationMsg => ({\n message: `\"${name}\" has spacing ${spacing}px not on ${gridBase}pt grid`,\n suggestion: `Round to nearest ${gridBase}pt multiple (${nearest}px)`,\n});\n\n// ── no-auto-layout ───────────────────────────────────────────────────────────\n\nexport const noAutoLayoutMsg = {\n overlapping: (name: string): ViolationMsg => ({\n message: `\"${name}\" has overlapping children without Auto Layout`,\n suggestion: `Apply auto-layout to separate overlapping children`,\n guide: `If this is an intentional overlay (e.g., badge on avatar), this can be ignored`,\n }),\n nested: (name: string): ViolationMsg => ({\n message: `\"${name}\" has nested containers without layout hints`,\n suggestion: `Apply auto-layout to organize nested containers`,\n guide: `Icon wrappers containing only vectors are automatically excluded`,\n }),\n basic: (name: string, arrangement: string, directionHint: string): ViolationMsg => ({\n message: `Frame \"${name}\" has no auto-layout${arrangement}`,\n suggestion: directionHint ? `Apply ${directionHint} auto-layout` : `Apply auto-layout`,\n guide: `Single-child wrappers and icon containers are automatically excluded`,\n }),\n};\n\n// ── absolute-position-in-auto-layout ─────────────────────────────────────────\n\nexport const absolutePositionMsg = (name: string, parentName: string): ViolationMsg => ({\n message: `\"${name}\" uses absolute positioning inside Auto Layout parent \"${parentName}\"`,\n suggestion: `Remove absolute positioning or restructure outside the auto-layout parent`,\n guide: `If this is a badge or overlay, name it with \"badge\", \"overlay\", or \"icon\" to auto-exclude`,\n});\n\n// ── fixed-size-in-auto-layout ────────────────────────────────────────────────\n\nexport const fixedSizeMsg = {\n bothAxes: (name: string, width: number, height: number): ViolationMsg => ({\n message: `Container \"${name}\" (${width}×${height}) uses fixed size on both axes inside auto-layout`,\n suggestion: `Set at least one axis to HUG or FILL`,\n }),\n horizontal: (name: string, width: number): ViolationMsg => ({\n message: `\"${name}\" has fixed width (${width}px) inside auto-layout`,\n suggestion: `Set horizontal sizing to FILL`,\n }),\n};\n\n// ── missing-size-constraint ──────────────────────────────────────────────────\n\nexport type MissingSizeConstraintSubType = \"max-width\" | \"min-width\" | \"wrap\" | \"grid\";\n\nexport const missingSizeConstraintMsg = {\n maxWidth: (name: string, currentWidth: string): ViolationMsg => ({\n message: `\"${name}\" uses FILL width (currently ${currentWidth}) without max-width`,\n suggestion: `Add maxWidth to prevent stretching on large screens`,\n }),\n minWidth: (name: string, currentWidth: string): ViolationMsg => ({\n message: `\"${name}\" uses FILL width (currently ${currentWidth}) without min-width`,\n suggestion: `Add minWidth to prevent collapsing on small screens`,\n }),\n wrap: (name: string): ViolationMsg => ({\n message: `\"${name}\" is in a wrap container without min-width`,\n suggestion: `Add minWidth to control when wrapping occurs`,\n }),\n grid: (name: string): ViolationMsg => ({\n message: `\"${name}\" is in a grid layout without size constraints`,\n suggestion: `Add min/max-width for proper column sizing`,\n }),\n};\n\n// ── non-layout-container (was group-usage) ───────────────────────────────────\n\nexport type NonLayoutContainerSubType = \"group\" | \"section\";\n\nexport const nonLayoutContainerMsg = {\n group: (name: string): ViolationMsg => ({\n message: `\"${name}\" is a Group`,\n suggestion: `Convert to Frame and apply auto-layout`,\n }),\n section: (name: string): ViolationMsg => ({\n message: `\"${name}\" is a Section used as layout container`,\n suggestion: `Convert to Frame and apply auto-layout`,\n }),\n};\n\n// ── deep-nesting ─────────────────────────────────────────────────────────────\n\nexport const deepNestingMsg = (name: string, depth: number, maxDepth: number): ViolationMsg => ({\n message: `\"${name}\" is nested ${depth} levels deep within its component (max: ${maxDepth})`,\n suggestion: `Extract into a sub-component to reduce depth`,\n});\n\n// ── missing-component ────────────────────────────────────────────────────────\n\nexport const missingComponentMsg = {\n unusedComponent: (componentName: string, count: number): ViolationMsg => ({\n message: `Component \"${componentName}\" exists but ${count} repeated frames found instead of instances`,\n suggestion: `Replace frames with component instances`,\n }),\n nameRepetition: (name: string, count: number): ViolationMsg => ({\n message: `\"${name}\" appears ${count} times`,\n suggestion: `Extract as a reusable component`,\n }),\n structureRepetition: (name: string, siblingCount: number): ViolationMsg => ({\n message: `\"${name}\" and ${siblingCount} sibling frame(s) share the same internal structure`,\n suggestion: `Extract a shared component from the repeated structure`,\n }),\n styleOverride: (componentName: string, overrides: string[]): ViolationMsg => ({\n message: `\"${componentName}\" instance has style overrides (${overrides.join(\", \")})`,\n suggestion: `Create a new variant for this style combination`,\n }),\n};\n\n// ── detached-instance ────────────────────────────────────────────────────────\n\nexport const detachedInstanceMsg = (name: string, componentName: string): ViolationMsg => ({\n message: `\"${name}\" may be a detached instance of component \"${componentName}\"`,\n suggestion: `Restore as an instance of \"${componentName}\" or create a new variant`,\n});\n\n// ── variant-structure-mismatch ───────────────────────────────────────────────\n\nexport const variantStructureMismatchMsg = (name: string, mismatchCount: number, totalVariants: number): ViolationMsg => ({\n message: `\"${name}\" has ${mismatchCount}/${totalVariants} variants with different child structures`,\n suggestion: `Unify variant structures using visibility toggles for optional elements`,\n});\n\n// ── non-standard-naming ──────────────────────────────────────────────────────\n\nexport type NonStandardNamingSubType = \"state-name\";\n\nexport const nonStandardNamingMsg = {\n stateName: (name: string, nonStandard: string, suggested: string): ViolationMsg => ({\n message: `\"${name}\" has non-standard state name \"${nonStandard}\"`,\n suggestion: `Use \"${suggested}\" for dev-friendly naming`,\n }),\n};\n\n// ── non-semantic-name (merged: default-name + non-semantic-name) ─────────────\n\nexport type NonSemanticNameSubType = \"frame\" | \"group\" | \"vector\" | \"shape\" | \"text\" | \"image\" | \"component\" | \"instance\" | \"shape-name\";\n\nconst DEFAULT_NAME_SUBTYPE_MAP: Record<string, NonSemanticNameSubType> = {\n FRAME: \"frame\",\n GROUP: \"group\",\n RECTANGLE: \"shape\",\n ELLIPSE: \"shape\",\n VECTOR: \"vector\",\n LINE: \"vector\",\n STAR: \"shape\",\n REGULAR_POLYGON: \"shape\",\n TEXT: \"text\",\n IMAGE: \"image\",\n COMPONENT: \"component\",\n COMPONENT_SET: \"component\",\n INSTANCE: \"instance\",\n};\n\nexport function getDefaultNameSubType(nodeType: string): NonSemanticNameSubType {\n return DEFAULT_NAME_SUBTYPE_MAP[nodeType] ?? \"frame\";\n}\n\nconst NON_SEMANTIC_EXAMPLES: Record<string, string> = {\n FRAME: '\"Header\", \"ProductCard\", \"Sidebar\"',\n GROUP: '\"NavItems\", \"ButtonGroup\", \"CardContent\"',\n VECTOR: '\"ArrowIcon\", \"CheckMark\", \"LogoSymbol\"',\n LINE: '\"Divider\", \"Separator\", \"Underline\"',\n RECTANGLE: '\"Background\", \"Divider\", \"Overlay\"',\n ELLIPSE: '\"AvatarShape\", \"StatusDot\", \"Badge\"',\n STAR: '\"RatingIcon\", \"FavoriteIcon\", \"StarBadge\"',\n REGULAR_POLYGON: '\"PlayIcon\", \"WarningIcon\", \"ShapeDecor\"',\n TEXT: '\"PageTitle\", \"Description\", \"Price\"',\n IMAGE: '\"Avatar\", \"ProductPhoto\", \"Banner\"',\n COMPONENT: '\"PrimaryButton\", \"InputField\", \"CardTemplate\"',\n COMPONENT_SET: '\"Button\", \"Input\", \"Card\"',\n INSTANCE: '\"CloseButton\", \"UserAvatar\", \"StarIcon\"',\n};\n\nexport const nonSemanticNameMsg = (type: string, name: string): ViolationMsg => {\n const examples = NON_SEMANTIC_EXAMPLES[type] ?? '\"Header\", \"ProductCard\", \"Icon\"';\n return {\n message: `${type} \"${name}\" is a non-semantic name`,\n suggestion: `Rename to describe its role (e.g., ${examples})`,\n };\n};\n\n// ── missing-interaction-state ─────────────────────────────────────────────────\n\nexport type MissingInteractionStateSubType = \"hover\" | \"disabled\" | \"active\" | \"focus\";\n\nexport const missingInteractionStateMsg = {\n hover: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Hover state variant`,\n suggestion: `Add a State=Hover variant`,\n }),\n disabled: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Disabled state variant`,\n suggestion: `Add a State=Disabled variant`,\n }),\n active: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Active state variant`,\n suggestion: `Add a State=Active variant`,\n }),\n focus: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Focus state variant`,\n suggestion: `Add a State=Focus variant`,\n }),\n};\n\n// ── missing-prototype ─────────────────────────────────────────────────────────\n\nexport type MissingPrototypeSubType = \"button\" | \"navigation\" | \"tab\" | \"overlay\" | \"carousel\" | \"input\" | \"toggle\";\n\nexport const missingPrototypeMsg = {\n button: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a button but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define the click behavior`,\n }),\n navigation: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a navigation link but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define the destination`,\n }),\n tab: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a tab but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define tab switching behavior`,\n }),\n overlay: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like an overlay trigger but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define open/close behavior`,\n }),\n carousel: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a carousel but has no interaction prototype`,\n suggestion: `Add an ON_CLICK or ON_DRAG interaction to define slide navigation`,\n }),\n input: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like an input but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define focus/interaction behavior`,\n }),\n toggle: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a toggle but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define on/off behavior`,\n }),\n};\n\n// ── inconsistent-naming-convention ───────────────────────────────────────────\n\nexport const inconsistentNamingMsg = (name: string, nodeConvention: string, dominantConvention: string, suggested: string): ViolationMsg => ({\n message: `\"${name}\" uses ${nodeConvention} while siblings use ${dominantConvention}`,\n suggestion: `Rename to \"${suggested}\"`,\n guide: `This checks sibling layers at the same level — you don't have to follow the exact suggestion, just keep naming consistent across siblings`,\n});\n","import type { RuleCheckFn, RuleDefinition } from \"../../contracts/rule.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getRuleOption } from \"../rule-config.js\";\nimport { isAutoLayoutExempt, isAbsolutePositionExempt, isSizeConstraintExempt, isFixedSizeExempt } from \"../rule-exceptions.js\";\nimport { noAutoLayoutMsg, absolutePositionMsg, fixedSizeMsg, missingSizeConstraintMsg, nonLayoutContainerMsg, deepNestingMsg } from \"../rule-messages.js\";\nimport { isContainerNode, hasAutoLayout, hasTextContent, hasOverlappingBounds } from \"../node-semantics.js\";\n\n// ============================================\n// no-auto-layout (merged: absorbs ambiguous-structure + missing-layout-hint)\n// ============================================\n\nconst noAutoLayoutDef: RuleDefinition = {\n id: \"no-auto-layout\",\n name: \"No Auto Layout\",\n category: \"pixel-critical\",\n why: \"Without Auto Layout, AI must guess positioning from absolute coordinates instead of reading explicit layout rules\",\n impact: \"Generated code uses hardcoded positions that break on any content or screen size change\",\n fix: \"Apply Auto Layout to create clear, explicit structure — enables AI to generate flexbox/grid instead of absolute positioning\",\n};\n\nconst noAutoLayoutCheck: RuleCheckFn = (node, context) => {\n if (!isContainerNode(node)) return null;\n if (hasAutoLayout(node)) return null;\n if (!node.children || node.children.length === 0) return null;\n\n if (isAutoLayoutExempt(node)) return null;\n\n // Priority 1: Check for overlapping visible children (ambiguous-structure)\n if (node.children.length >= 2) {\n for (let i = 0; i < node.children.length; i++) {\n for (let j = i + 1; j < node.children.length; j++) {\n const childA = node.children[i];\n const childB = node.children[j];\n if (!childA || !childB) continue;\n\n if (hasOverlappingBounds(childA, childB)) {\n if (childA.visible !== false && childB.visible !== false) {\n return {\n ruleId: noAutoLayoutDef.id,\n subType: \"overlapping\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...noAutoLayoutMsg.overlapping(node.name),\n };\n }\n }\n }\n }\n }\n\n // Priority 2: Check for nested containers without layout hints (missing-layout-hint)\n if (node.children.length >= 2) {\n const nestedContainers = node.children.filter((c) => isContainerNode(c));\n if (nestedContainers.length >= 2) {\n const withoutLayout = nestedContainers.filter((c) => !hasAutoLayout(c));\n if (withoutLayout.length >= 2) {\n return {\n ruleId: noAutoLayoutDef.id,\n subType: \"nested\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...noAutoLayoutMsg.nested(node.name),\n };\n }\n }\n }\n\n // Priority 3: Basic no-auto-layout check (FRAME only)\n if (node.type !== \"FRAME\") return null;\n\n const childCount = node.children?.length ?? 0;\n let directionHint = \"\";\n if (node.children && node.children.length >= 2) {\n const boxes = node.children.filter(c => c.absoluteBoundingBox).map(c => c.absoluteBoundingBox!);\n if (boxes.length >= 2) {\n const yRange = Math.max(...boxes.map(b => b.y)) - Math.min(...boxes.map(b => b.y));\n const xRange = Math.max(...boxes.map(b => b.x)) - Math.min(...boxes.map(b => b.x));\n directionHint = yRange > xRange ? \"VERTICAL\" : \"HORIZONTAL\";\n }\n }\n\n const arrangement = directionHint\n ? ` (${childCount} children arranged ${directionHint.toLowerCase()}ly)`\n : childCount > 0 ? ` (${childCount} children)` : \"\";\n\n return {\n ruleId: noAutoLayoutDef.id,\n subType: \"basic\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...noAutoLayoutMsg.basic(node.name, arrangement, directionHint),\n };\n};\n\nexport const noAutoLayout = defineRule({\n definition: noAutoLayoutDef,\n check: noAutoLayoutCheck,\n});\n\n// ============================================\n// absolute-position-in-auto-layout\n// ============================================\n\nconst absolutePositionInAutoLayoutDef: RuleDefinition = {\n id: \"absolute-position-in-auto-layout\",\n name: \"Absolute Position in Auto Layout\",\n category: \"pixel-critical\",\n why: \"Absolute positioning inside Auto Layout contradicts the parent's layout rules — AI sees conflicting instructions\",\n impact: \"AI must decide whether to follow the parent's flexbox or the child's absolute position — often gets it wrong\",\n fix: \"Remove absolute positioning or use proper Auto Layout alignment\",\n};\n\nconst absolutePositionInAutoLayoutCheck: RuleCheckFn = (node, context) => {\n if (!context.parent) return null;\n if (!hasAutoLayout(context.parent)) return null;\n if (node.layoutPositioning !== \"ABSOLUTE\") return null;\n\n if (isAbsolutePositionExempt(node)) return null;\n\n return {\n ruleId: absolutePositionInAutoLayoutDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...absolutePositionMsg(node.name, context.parent.name),\n };\n};\n\nexport const absolutePositionInAutoLayout = defineRule({\n definition: absolutePositionInAutoLayoutDef,\n check: absolutePositionInAutoLayoutCheck,\n});\n\n// ============================================\n// fixed-size-in-auto-layout (merged: absorbs fixed-width-in-responsive-context)\n// ============================================\n\nconst fixedSizeInAutoLayoutDef: RuleDefinition = {\n id: \"fixed-size-in-auto-layout\",\n name: \"Fixed Size in Auto Layout\",\n category: \"responsive-critical\",\n why: \"Fixed sizing inside Auto Layout contradicts the flexible layout intent\",\n impact: \"AI generates a rigid element inside a flex container — the layout won't respond to content changes\",\n fix: \"Use 'Hug' or 'Fill' for at least one axis. Both-axes FIXED → layout completely rigid; horizontal-only FIXED → width won't adapt to parent resize\",\n};\n\nconst fixedSizeInAutoLayoutCheck: RuleCheckFn = (node, context) => {\n if (!context.parent) return null;\n if (!hasAutoLayout(context.parent)) return null;\n if (!isContainerNode(node)) return null;\n if (!node.absoluteBoundingBox) return null;\n\n if (isFixedSizeExempt(node)) return null;\n\n const { width, height } = node.absoluteBoundingBox;\n\n // Check both axes FIXED (stronger case)\n const hFixed =\n node.layoutSizingHorizontal === \"FIXED\" || node.layoutSizingHorizontal === undefined;\n const vFixed =\n node.layoutSizingVertical === \"FIXED\" || node.layoutSizingVertical === undefined;\n\n if (hFixed && vFixed) {\n // Skip if it has its own auto-layout\n if (node.layoutMode && node.layoutMode !== \"NONE\") return null;\n\n return {\n ruleId: fixedSizeInAutoLayoutDef.id,\n subType: \"both-axes\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...fixedSizeMsg.bothAxes(node.name, width, height),\n };\n }\n\n // Check horizontal-only FIXED (lighter case, from fixed-width-in-responsive-context)\n if (hFixed && !vFixed) {\n // Use layoutSizingHorizontal if available (accurate)\n if (node.layoutSizingHorizontal) {\n if (node.layoutSizingHorizontal !== \"FIXED\") return null;\n } else {\n // Fallback: STRETCH means fill, skip\n if (node.layoutAlign === \"STRETCH\") return null;\n if (node.layoutAlign !== \"INHERIT\") return null;\n }\n\n return {\n ruleId: fixedSizeInAutoLayoutDef.id,\n subType: \"horizontal\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...fixedSizeMsg.horizontal(node.name, width),\n };\n }\n\n return null;\n};\n\nexport const fixedSizeInAutoLayout = defineRule({\n definition: fixedSizeInAutoLayoutDef,\n check: fixedSizeInAutoLayoutCheck,\n});\n\n// ============================================\n// missing-size-constraint (merged: missing-min-width + missing-max-width)\n// ============================================\n\nconst missingSizeConstraintDef: RuleDefinition = {\n id: \"missing-size-constraint\",\n name: \"Missing Size Constraint\",\n category: \"responsive-critical\",\n why: \"Without min/max-width, AI has no bounds — generated code may collapse or stretch indefinitely\",\n impact: \"Content becomes unreadable or invisible at extreme screen sizes\",\n fix: \"Set min-width and/or max-width so AI can generate proper size constraints\",\n};\n\nconst missingSizeConstraintCheck: RuleCheckFn = (node, context) => {\n // Only check containers and text-containing nodes\n if (!isContainerNode(node) && !hasTextContent(node)) return null;\n // Skip if not in Auto Layout context\n if (!context.parent || !hasAutoLayout(context.parent)) return null;\n\n const nodePath = context.path.join(\" > \");\n\n // Check 1: wrap parent → FILL children need min-width\n if (context.parent.layoutWrap === \"WRAP\" && node.layoutSizingHorizontal === \"FILL\" && node.minWidth === undefined) {\n return {\n ruleId: missingSizeConstraintDef.id,\n subType: \"wrap\" as const,\n nodeId: node.id,\n nodePath,\n ...missingSizeConstraintMsg.wrap(node.name),\n };\n }\n\n // Check 2: grid parent → FILL children need size constraints\n if (context.parent.layoutMode === \"GRID\" && node.layoutSizingHorizontal === \"FILL\" && node.minWidth === undefined && node.maxWidth === undefined) {\n return {\n ruleId: missingSizeConstraintDef.id,\n subType: \"grid\" as const,\n nodeId: node.id,\n nodePath,\n ...missingSizeConstraintMsg.grid(node.name),\n };\n }\n\n // Check 3: FILL containers need max-width\n if (node.layoutSizingHorizontal === \"FILL\") {\n if (isSizeConstraintExempt(node, context)) return null;\n\n const currentWidth = node.absoluteBoundingBox ? `${node.absoluteBoundingBox.width}px` : \"unknown\";\n return {\n ruleId: missingSizeConstraintDef.id,\n subType: \"max-width\" as const,\n nodeId: node.id,\n nodePath,\n ...missingSizeConstraintMsg.maxWidth(node.name, currentWidth),\n };\n }\n\n return null;\n};\n\nexport const missingSizeConstraint = defineRule({\n definition: missingSizeConstraintDef,\n check: missingSizeConstraintCheck,\n});\n\n// ============================================\n// non-layout-container (was group-usage — now also catches Section)\n// ============================================\n\nconst nonLayoutContainerDef: RuleDefinition = {\n id: \"non-layout-container\",\n name: \"Non-Layout Container\",\n category: \"pixel-critical\",\n why: \"Groups and Sections lack proper layout rules — AI sees children with absolute coordinates but no container logic\",\n impact: \"AI wraps elements in a plain div with no spacing/alignment, producing fragile layouts\",\n fix: \"Convert to Frame with Auto Layout so AI can generate proper flex/grid containers\",\n};\n\nconst nonLayoutContainerCheck: RuleCheckFn = (node, context) => {\n if (node.type === \"GROUP\") {\n return {\n ruleId: nonLayoutContainerDef.id,\n subType: \"group\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonLayoutContainerMsg.group(node.name),\n };\n }\n\n if (node.type === \"SECTION\") {\n return {\n ruleId: nonLayoutContainerDef.id,\n subType: \"section\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonLayoutContainerMsg.section(node.name),\n };\n }\n\n return null;\n};\n\nexport const nonLayoutContainer = defineRule({\n definition: nonLayoutContainerDef,\n check: nonLayoutContainerCheck,\n});\n\n// ============================================\n// deep-nesting\n// ============================================\n\nconst deepNestingDef: RuleDefinition = {\n id: \"deep-nesting\",\n name: \"Deep Nesting\",\n category: \"code-quality\",\n why: \"Deep nesting consumes AI context exponentially — each level adds indentation and structural overhead\",\n impact: \"AI may lose track of parent-child relationships in deeply nested trees, producing wrong layout hierarchy\",\n fix: \"Flatten the structure by extracting deeply nested groups into sub-components\",\n};\n\nconst deepNestingCheck: RuleCheckFn = (node, context, options) => {\n const maxDepth = (options?.[\"maxDepth\"] as number) ?? getRuleOption(\"deep-nesting\", \"maxDepth\", 5);\n\n if (context.componentDepth < maxDepth) return null;\n if (!isContainerNode(node)) return null;\n\n return {\n ruleId: deepNestingDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...deepNestingMsg(node.name, context.componentDepth, maxDepth),\n };\n};\n\nexport const deepNesting = defineRule({\n definition: deepNestingDef,\n check: deepNestingCheck,\n});\n\n","import type { RuleCheckFn, RuleDefinition } from \"../../contracts/rule.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getRuleOption } from \"../rule-config.js\";\nimport { rawValueMsg, irregularSpacingMsg } from \"../rule-messages.js\";\nimport { hasStyleReference, hasBoundVariable } from \"../node-semantics.js\";\n\nfunction isOnGrid(value: number, gridBase: number): boolean {\n return value % gridBase === 0;\n}\n\n// ============================================\n// raw-value (merged: raw-color + raw-font + raw-shadow + raw-opacity + raw-spacing)\n// ============================================\n\nconst rawValueDef: RuleDefinition = {\n id: \"raw-value\",\n name: \"Raw Value\",\n category: \"token-management\",\n why: \"Values without design tokens or variables must be reproduced exactly per node — one typo means a visible difference\",\n impact: \"AI cannot reference a shared token, so each raw value is an independent source of error across large pages\",\n fix: \"Use design tokens or variables (color styles, text styles, effect styles, opacity/spacing variables) so values are referenceable\",\n};\n\nconst rawValueCheck: RuleCheckFn = (node, context) => {\n const nodePath = context.path.join(\" > \");\n\n // Check 1: Raw fill color\n if (node.fills && Array.isArray(node.fills) && node.fills.length > 0) {\n if (!hasStyleReference(node, \"fill\") && !hasBoundVariable(node, \"fills\")) {\n for (const fill of node.fills) {\n const fillObj = fill as Record<string, unknown>;\n if (fillObj[\"type\"] === \"SOLID\" && fillObj[\"color\"]) {\n const c = fillObj[\"color\"] as Record<string, number>;\n const hex = `#${Math.round((c[\"r\"] ?? 0) * 255).toString(16).padStart(2, \"0\")}${Math.round((c[\"g\"] ?? 0) * 255).toString(16).padStart(2, \"0\")}${Math.round((c[\"b\"] ?? 0) * 255).toString(16).padStart(2, \"0\")}`.toUpperCase();\n return {\n ruleId: rawValueDef.id,\n subType: \"color\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.color(node.name, hex),\n };\n }\n }\n }\n }\n\n // Check 2: Raw font (TEXT nodes without text style)\n if (node.type === \"TEXT\") {\n if (\n !hasStyleReference(node, \"text\") &&\n (!hasBoundVariable(node, \"fontFamily\") || !hasBoundVariable(node, \"fontSize\"))\n ) {\n const fontParts: string[] = [];\n const s = node.style;\n if (s) {\n if (s[\"fontFamily\"]) fontParts.push(String(s[\"fontFamily\"]));\n if (s[\"fontSize\"]) fontParts.push(`${s[\"fontSize\"]}px`);\n if (s[\"fontWeight\"]) fontParts.push(String(s[\"fontWeight\"]));\n }\n const fontDesc = fontParts.length > 0 ? ` (${fontParts.join(\" \")})` : \"\";\n return {\n ruleId: rawValueDef.id,\n subType: \"font\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.font(node.name, fontDesc),\n };\n }\n }\n\n // Check 3: Raw shadow (effects without effect style)\n if (node.effects && Array.isArray(node.effects) && node.effects.length > 0) {\n if (!hasStyleReference(node, \"effect\")) {\n for (const effect of node.effects) {\n const effectObj = effect as Record<string, unknown>;\n if (effectObj[\"type\"] === \"DROP_SHADOW\" || effectObj[\"type\"] === \"INNER_SHADOW\") {\n const shadowType = effectObj[\"type\"] === \"DROP_SHADOW\" ? \"drop shadow\" : \"inner shadow\";\n const offset = effectObj[\"offset\"] as Record<string, number> | undefined;\n const radius = effectObj[\"radius\"] as number | undefined;\n const detailParts: string[] = [];\n if (offset) detailParts.push(`offset ${Math.round(offset[\"x\"] ?? 0)},${Math.round(offset[\"y\"] ?? 0)}`);\n if (radius !== undefined) detailParts.push(`blur ${Math.round(radius)}`);\n const details = detailParts.length > 0 ? ` (${detailParts.join(\" \")})` : \"\";\n return {\n ruleId: rawValueDef.id,\n subType: \"shadow\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.shadow(node.name, shadowType, details),\n };\n }\n }\n }\n }\n\n // Check 4: Raw opacity (non-default opacity without variable)\n if (node.opacity !== undefined && node.opacity < 1 && !hasBoundVariable(node, \"opacity\")) {\n return {\n ruleId: rawValueDef.id,\n subType: \"opacity\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.opacity(node.name, Math.round(node.opacity * 100)),\n };\n }\n\n // Check 5: Raw spacing (padding/gap without variable binding)\n const spacingKeys = [\"paddingLeft\", \"paddingRight\", \"paddingTop\", \"paddingBottom\", \"itemSpacing\"] as const;\n for (const key of spacingKeys) {\n const value = node[key];\n if (value !== undefined && value > 0 && !hasBoundVariable(node, key)) {\n const label = key === \"itemSpacing\" ? \"gap\" : key.replace(\"padding\", \"padding-\").toLowerCase();\n return {\n ruleId: rawValueDef.id,\n subType: \"spacing\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.spacing(node.name, label, value),\n };\n }\n }\n\n return null;\n};\n\nexport const rawValue = defineRule({\n definition: rawValueDef,\n check: rawValueCheck,\n});\n\n// ============================================\n// irregular-spacing (merged: inconsistent-spacing + magic-number-spacing)\n// ============================================\n\nconst irregularSpacingDef: RuleDefinition = {\n id: \"irregular-spacing\",\n name: \"Irregular Spacing\",\n category: \"token-management\",\n why: \"Off-grid or arbitrary spacing values force AI to handle many unique values instead of a predictable pattern\",\n impact: \"Higher chance of pixel-level differences when AI substitutes nearby round values\",\n fix: \"Align spacing to the design system grid (e.g., 4pt/8pt increments) for predictable implementation\",\n};\n\nconst irregularSpacingCheck: RuleCheckFn = (node, context, options) => {\n const configuredGridBase = (options?.[\"gridBase\"] as number) ?? getRuleOption(\"irregular-spacing\", \"gridBase\", 4);\n const gridBase = Number.isFinite(configuredGridBase) && configuredGridBase > 0 ? configuredGridBase : 4;\n\n const spacingEntries: Array<{ value: number; subType: \"padding\" | \"gap\" }> = [];\n for (const key of [\"paddingLeft\", \"paddingRight\", \"paddingTop\", \"paddingBottom\"] as const) {\n const v = node[key];\n if (v !== undefined && v > 0) spacingEntries.push({ value: v, subType: \"padding\" });\n }\n if (node.itemSpacing !== undefined && node.itemSpacing > 0) {\n spacingEntries.push({ value: node.itemSpacing, subType: \"gap\" });\n }\n\n // Allow small intentional values\n const commonValues = [1, 2];\n\n for (const entry of spacingEntries) {\n if (commonValues.includes(entry.value)) continue;\n if (!isOnGrid(entry.value, gridBase)) {\n return {\n ruleId: irregularSpacingDef.id,\n subType: entry.subType,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...irregularSpacingMsg(node.name, entry.value, gridBase, Math.round(entry.value / gridBase) * gridBase),\n };\n }\n }\n\n return null;\n};\n\nexport const irregularSpacing = defineRule({\n definition: irregularSpacingDef,\n check: irregularSpacingCheck,\n});\n","import type { RuleCheckFn, RuleDefinition, RuleContext } from \"../../contracts/rule.js\";\nimport { getAnalysisState } from \"../../contracts/rule.js\";\nimport type { AnalysisNode } from \"../../contracts/figma-node.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getRuleOption } from \"../rule-config.js\";\nimport { missingComponentMsg, detachedInstanceMsg, variantStructureMismatchMsg } from \"../rule-messages.js\";\n\n// ============================================\n// Helper functions\n// ============================================\n\n\n/** Style properties to compare between master and instance. */\nconst STYLE_COMPARE_KEYS = [\"fills\", \"strokes\", \"effects\", \"cornerRadius\", \"strokeWeight\", \"individualStrokeWeights\"] as const;\n\n/**\n * Detect style overrides between a component master and an instance.\n * Returns list of property names that differ.\n */\nfunction detectStyleOverrides(master: AnalysisNode, instance: AnalysisNode): string[] {\n const overrides: string[] = [];\n for (const key of STYLE_COMPARE_KEYS) {\n const masterVal = master[key];\n const instanceVal = instance[key];\n // Both undefined/null → no override\n if (masterVal == null && instanceVal == null) continue;\n // One exists, other doesn't → override\n if (masterVal == null || instanceVal == null) {\n overrides.push(key);\n continue;\n }\n // Deep compare via JSON\n if (JSON.stringify(masterVal) !== JSON.stringify(instanceVal)) {\n overrides.push(key);\n }\n }\n return overrides;\n}\n\n/**\n * Collect all frame names in the file for duplicate detection\n */\nfunction collectFrameNames(\n node: AnalysisNode,\n names: Map<string, string[]> = new Map()\n): Map<string, string[]> {\n if (node.type === \"FRAME\" && node.name) {\n const existing = names.get(node.name) ?? [];\n existing.push(node.id);\n names.set(node.name, existing);\n }\n\n if (node.children) {\n for (const child of node.children) {\n collectFrameNames(child, names);\n }\n }\n\n return names;\n}\n\n/**\n * Build a structural fingerprint for a node.\n * The fingerprint encodes type, layoutMode, and child types recursively up to maxDepth.\n */\nfunction buildFingerprint(node: AnalysisNode, depth: number): string {\n if (depth <= 0 || !node.children || node.children.length === 0) {\n return `${node.type}:${node.layoutMode ?? \"NONE\"}`;\n }\n\n const childFingerprints = node.children\n .map((child) => buildFingerprint(child, depth - 1))\n .join(\",\");\n\n return `${node.type}:${node.layoutMode ?? \"NONE\"}:[${childFingerprints}]`;\n}\n\n/**\n * Check if the node is inside an INSTANCE subtree.\n * Walks the full ancestor type chain to detect INSTANCE at any level.\n */\nfunction isInsideInstance(context: {\n ancestorTypes: string[];\n}): boolean {\n return context.ancestorTypes.includes(\"INSTANCE\");\n}\n\n\n\n// ============================================\n// missing-component (unified 4-stage rule)\n// ============================================\n\n/** State keys for per-analysis deduplication via RuleContext.analysisState */\nconst SEEN_STAGE1_KEY = \"missing-component:seenStage1ComponentNames\";\nconst SEEN_STAGE4_KEY = \"missing-component:seenStage4ComponentIds\";\n\nfunction getSeenStage1(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_STAGE1_KEY, () => new Set<string>());\n}\n\nfunction getSeenStage4(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_STAGE4_KEY, () => new Set<string>());\n}\n\nconst missingComponentDef: RuleDefinition = {\n id: \"missing-component\",\n name: \"Missing Component\",\n category: \"code-quality\",\n why: \"Repeated structures, unused components, and divergent instance overrides indicate missing or underutilized components. This inflates AI token consumption and forces manual maintenance.\",\n impact: \"AI code generators reproduce each repeated frame independently instead of emitting a reusable component. Divergent instance overrides produce inconsistent implementations.\",\n fix: \"Create components from repeated structures, use instances instead of duplicated frames, and create variants for instances with significantly different overrides.\",\n};\n\nconst missingComponentCheck: RuleCheckFn = (node, context, options) => {\n // ========================================\n // FRAME stages (1, 2, 3) — ordered by priority\n // ========================================\n if (node.type === \"FRAME\") {\n // Stage 1: Component exists but not used — FRAME name matches a component in metadata AND frame is repeated\n const components = context.file.components;\n const matchingComponent = Object.values(components).find(\n (c) => c.name.toLowerCase() === node.name.toLowerCase()\n );\n\n // Collect frame names once for Stage 1 and Stage 2\n const frameNames = collectFrameNames(context.file.document);\n const sameNameFrames = frameNames.get(node.name);\n const firstFrame = sameNameFrames?.[0];\n\n if (matchingComponent) {\n const seenStage1 = getSeenStage1(context);\n if (\n sameNameFrames &&\n firstFrame !== undefined &&\n sameNameFrames.length >= 2 &&\n !seenStage1.has(node.name.toLowerCase()) &&\n firstFrame === node.id\n ) {\n seenStage1.add(node.name.toLowerCase());\n return {\n ruleId: missingComponentDef.id,\n subType: \"unused-component\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.unusedComponent(matchingComponent.name, sameNameFrames.length),\n };\n }\n }\n\n // Stage 2: Name-based repetition (existing logic)\n const minRepetitions =\n (options?.[\"minRepetitions\"] as number | undefined) ??\n getRuleOption(\"missing-component\", \"minRepetitions\", 3);\n\n if (sameNameFrames && firstFrame !== undefined && sameNameFrames.length >= minRepetitions) {\n if (firstFrame === node.id) {\n return {\n ruleId: missingComponentDef.id,\n subType: \"name-repetition\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.nameRepetition(node.name, sameNameFrames.length),\n };\n }\n }\n\n // Stage 3: Structure-based repetition (absorbed from repeated-frame-structure)\n // Skip if node is inside an INSTANCE subtree\n if (isInsideInstance(context)) return null;\n\n // Skip if parent is COMPONENT_SET\n if (context.parent?.type === \"COMPONENT_SET\") return null;\n\n // Skip if node has no children\n if (!node.children || node.children.length === 0) return null;\n\n const structureMinRepetitions =\n (options?.[\"structureMinRepetitions\"] as number | undefined) ??\n getRuleOption(\"missing-component\", \"structureMinRepetitions\", 2);\n\n const maxFingerprintDepth =\n (options?.[\"maxFingerprintDepth\"] as number | undefined) ??\n getRuleOption(\"missing-component\", \"maxFingerprintDepth\", 3);\n\n // Compute fingerprint for this node\n const fingerprint = buildFingerprint(node, maxFingerprintDepth);\n\n // Access siblings (may be undefined)\n const siblings = context.siblings ?? [];\n\n // Filter siblings to qualifying frames (type === FRAME, not inside INSTANCE, has children)\n const qualifyingSiblings = siblings.filter(\n (s) =>\n s.type === \"FRAME\" &&\n s.children !== undefined &&\n s.children.length > 0\n );\n\n // Count siblings (including self) sharing the same fingerprint\n const matchingNodes = qualifyingSiblings.filter(\n (s) => buildFingerprint(s, maxFingerprintDepth) === fingerprint\n );\n\n // Ensure self is counted (it should be in siblings, but add a guard)\n const selfIsInSiblings = qualifyingSiblings.some((s) => s.id === node.id);\n const count = selfIsInSiblings\n ? matchingNodes.length\n : matchingNodes.length + 1;\n\n if (count >= structureMinRepetitions) {\n // Only emit for the first sibling (by array order) with this fingerprint\n const firstMatch = qualifyingSiblings.find(\n (s) => buildFingerprint(s, maxFingerprintDepth) === fingerprint\n );\n\n // If self is not in siblings list, treat self as first match when no earlier match exists\n const firstMatchId = firstMatch?.id ?? node.id;\n if (firstMatchId === node.id) {\n return {\n ruleId: missingComponentDef.id,\n subType: \"structure-repetition\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.structureRepetition(node.name, count - 1),\n };\n }\n }\n\n return null;\n }\n\n // ========================================\n // Stage 4: Instance style override detection\n // Compares instance styles against component master.\n // Any style override (fills, strokes, effects, cornerRadius) means\n // the designer should use a variant instead.\n // ========================================\n if (node.type === \"INSTANCE\" && node.componentId) {\n const seenStage4 = getSeenStage4(context);\n if (seenStage4.has(node.componentId)) return null;\n\n const componentDefs = context.file.componentDefinitions;\n if (!componentDefs) return null;\n\n const master = componentDefs[node.componentId];\n if (!master) return null;\n\n // Compare style properties between master and instance\n const overrides = detectStyleOverrides(master, node);\n if (overrides.length > 0) {\n // Only mark as seen when we actually flag — allows other instances to be checked\n seenStage4.add(node.componentId);\n const componentMeta = context.file.components[node.componentId];\n const componentName = componentMeta?.name ?? node.name;\n\n return {\n ruleId: missingComponentDef.id,\n subType: \"style-override\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.styleOverride(componentName, overrides),\n };\n }\n return null;\n }\n\n return null;\n};\n\nexport const missingComponent = defineRule({\n definition: missingComponentDef,\n check: missingComponentCheck,\n});\n\n// ============================================\n// detached-instance\n// ============================================\n\nconst detachedInstanceDef: RuleDefinition = {\n id: \"detached-instance\",\n name: \"Detached Instance\",\n category: \"code-quality\",\n why: \"Detached instances lose component relationship — AI sees a one-off frame instead of a reusable component reference\",\n impact: \"AI generates duplicate code instead of reusing the component, inflating output and causing inconsistencies\",\n fix: \"Reset the instance or create a new variant if customization is needed\",\n};\n\nconst detachedInstanceCheck: RuleCheckFn = (node, context) => {\n // A detached instance would be a FRAME that was once an INSTANCE\n // This is hard to detect without historical data\n // Heuristic: Frame with a name that looks like it came from a component\n if (node.type !== \"FRAME\") return null;\n\n // Check if there's a component in the file with a matching name (word boundary)\n const components = context.file.components;\n\n for (const [, component] of Object.entries(components)) {\n const pattern = new RegExp(`\\\\b${component.name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}\\\\b`);\n if (pattern.test(node.name)) {\n // This frame might be a detached instance of this component\n return {\n ruleId: detachedInstanceDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...detachedInstanceMsg(node.name, component.name),\n };\n }\n }\n\n return null;\n};\n\nexport const detachedInstance = defineRule({\n definition: detachedInstanceDef,\n check: detachedInstanceCheck,\n});\n\n// ============================================\n// variant-structure-mismatch\n// ============================================\n\nconst variantStructureMismatchDef: RuleDefinition = {\n id: \"variant-structure-mismatch\",\n name: \"Variant Structure Mismatch\",\n category: \"code-quality\",\n why: \"Variants with different child structures prevent AI from creating a unified component template\",\n impact: \"AI must generate separate implementations for each variant instead of a single parameterized component\",\n fix: \"Ensure all variants share the same child structure, using visibility toggles for optional elements\",\n};\n\nconst variantStructureMismatchCheck: RuleCheckFn = (node, context) => {\n // Only COMPONENT_SET\n if (node.type !== \"COMPONENT_SET\") return null;\n if (!node.children?.length || node.children.length < 2) return null;\n\n // Build fingerprint for each variant child\n const fingerprints = node.children\n .filter(child => child.type === \"COMPONENT\")\n .map(child => buildFingerprint(child, 2));\n\n if (fingerprints.length < 2) return null;\n\n // Compare all fingerprints to the first one\n const base = fingerprints[0];\n const mismatched = fingerprints.filter(fp => fp !== base);\n\n if (mismatched.length === 0) return null;\n\n const mismatchCount = mismatched.length;\n const totalVariants = fingerprints.length;\n\n return {\n ruleId: variantStructureMismatchDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...variantStructureMismatchMsg(node.name, mismatchCount, totalVariants),\n };\n};\n\nexport const variantStructureMismatch = defineRule({\n definition: variantStructureMismatchDef,\n check: variantStructureMismatchCheck,\n});\n\n","import type { RuleCheckFn, RuleDefinition } from \"../../contracts/rule.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getDefaultNameSubType, nonSemanticNameMsg, inconsistentNamingMsg, nonStandardNamingMsg } from \"../rule-messages.js\";\nimport { isExcludedName, isDefaultName, isNonSemanticName, STANDARD_STATE_NAMES, STATE_NAME_SUGGESTIONS, STATE_LIKE_PATTERN } from \"../node-semantics.js\";\n\nfunction detectNamingConvention(name: string): string | null {\n if (/^[a-z]+(-[a-z]+)*$/.test(name)) return \"kebab-case\";\n if (/^[a-z]+(_[a-z]+)*$/.test(name)) return \"snake_case\";\n if (/^[a-z]+([A-Z][a-z]*)*$/.test(name)) return \"camelCase\";\n if (/^[A-Z][a-z]+([A-Z][a-z]*)*$/.test(name)) return \"PascalCase\";\n if (/^[A-Z]+(_[A-Z]+)*$/.test(name)) return \"SCREAMING_SNAKE_CASE\";\n if (/\\s/.test(name)) return \"Title Case\";\n return null;\n}\n\n/** Single capitalized word is compatible with both PascalCase and Title Case */\nfunction isCompatible(nodeConvention: string, dominantConvention: string, name: string): boolean {\n if (!/^[A-Z][a-z]+$/.test(name)) return false;\n const pair = new Set([nodeConvention, dominantConvention]);\n return pair.has(\"PascalCase\") && pair.has(\"Title Case\");\n}\n\n/** Split a name into words regardless of convention */\nfunction splitWords(name: string): string[] {\n // Title Case / space-separated\n if (/\\s/.test(name)) return name.split(/\\s+/);\n // SCREAMING_SNAKE_CASE or snake_case\n if (name.includes(\"_\")) return name.split(\"_\");\n // kebab-case\n if (name.includes(\"-\")) return name.split(\"-\");\n // camelCase / PascalCase — split on uppercase boundaries (including acronym runs)\n return name\n .replace(/([a-z0-9])([A-Z])/g, \"$1\\0$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1\\0$2\")\n .split(\"\\0\");\n}\n\n/** Convert a name to the target convention */\nfunction convertName(name: string, target: string): string {\n const words = splitWords(name);\n switch (target) {\n case \"kebab-case\":\n return words.map(w => w.toLowerCase()).join(\"-\");\n case \"snake_case\":\n return words.map(w => w.toLowerCase()).join(\"_\");\n case \"camelCase\":\n return words.map((w, i) => i === 0 ? w.toLowerCase() : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(\"\");\n case \"PascalCase\":\n return words.map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(\"\");\n case \"SCREAMING_SNAKE_CASE\":\n return words.map(w => w.toUpperCase()).join(\"_\");\n case \"Title Case\":\n return words.map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(\" \");\n default:\n return name;\n }\n}\n\n// ============================================\n// non-semantic-name (merged: default-name + non-semantic-name)\n// ============================================\n\nconst nonSemanticNameDef: RuleDefinition = {\n id: \"non-semantic-name\",\n name: \"Non-Semantic Name\",\n category: \"semantic\",\n why: \"Default or shape names give AI no semantic context — it cannot choose appropriate HTML tags or class names\",\n impact: \"AI generates generic <div> wrappers instead of semantic elements like <header>, <nav>, <article>\",\n fix: \"Rename with a descriptive, purpose-driven name (e.g., 'Header', 'ProductCard', 'Divider')\",\n};\n\nconst nonSemanticNameCheck: RuleCheckFn = (node, context) => {\n if (!node.name) return null;\n if (isExcludedName(node.name)) return null;\n\n // Check 1: Figma default names (Frame 1, Group 2, etc.)\n if (isDefaultName(node.name)) {\n return {\n ruleId: nonSemanticNameDef.id,\n subType: getDefaultNameSubType(node.type),\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonSemanticNameMsg(node.type, node.name),\n };\n }\n\n // Check 2: Shape-only names (rectangle, ellipse, vector, etc.)\n if (isNonSemanticName(node.name)) {\n // Allow shape names for actual shape primitives at leaf level\n if (!node.children || node.children.length === 0) {\n const shapeTypes = [\"RECTANGLE\", \"ELLIPSE\", \"VECTOR\", \"LINE\", \"STAR\", \"REGULAR_POLYGON\"];\n if (shapeTypes.includes(node.type)) return null;\n }\n\n return {\n ruleId: nonSemanticNameDef.id,\n subType: \"shape-name\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonSemanticNameMsg(node.type, node.name),\n };\n }\n\n return null;\n};\n\nexport const nonSemanticName = defineRule({\n definition: nonSemanticNameDef,\n check: nonSemanticNameCheck,\n});\n\n// ============================================\n// inconsistent-naming-convention\n// ============================================\n\nconst inconsistentNamingConventionDef: RuleDefinition = {\n id: \"inconsistent-naming-convention\",\n name: \"Inconsistent Naming Convention\",\n category: \"semantic\",\n why: \"Mixed naming conventions (camelCase + kebab-case + Title Case) at the same level confuse AI pattern recognition\",\n impact: \"AI generates inconsistent class/component names, making the codebase harder to maintain\",\n fix: \"Pick one convention for sibling elements (e.g., kebab-case: 'product-card', or PascalCase: 'ProductCard') — AI maps names to CSS classes and component names, so mixed conventions produce inconsistent code\",\n};\n\nconst inconsistentNamingConventionCheck: RuleCheckFn = (node, context) => {\n if (!context.siblings || context.siblings.length < 2) return null;\n\n // Detect conventions used by siblings\n const conventions = new Map<string, number>();\n let ambiguousPascalCount = 0;\n\n for (const sibling of context.siblings) {\n if (!sibling.name) continue;\n const convention = detectNamingConvention(sibling.name);\n if (convention) {\n conventions.set(convention, (conventions.get(convention) ?? 0) + 1);\n if (convention === \"PascalCase\" && /^[A-Z][a-z]+$/.test(sibling.name)) {\n ambiguousPascalCount++;\n }\n }\n }\n\n // Single capitalized words (Header, Footer) are detected as PascalCase but are\n // equally valid as Title Case. When both conventions appear, discount these\n // ambiguous names so they don't bias the dominant convention toward PascalCase.\n if (conventions.has(\"PascalCase\") && conventions.has(\"Title Case\") && ambiguousPascalCount > 0) {\n const adjusted = (conventions.get(\"PascalCase\") ?? 0) - ambiguousPascalCount;\n if (adjusted <= 0) {\n conventions.delete(\"PascalCase\");\n } else {\n conventions.set(\"PascalCase\", adjusted);\n }\n }\n\n // Skip if we can't detect clear conventions\n if (conventions.size < 2) return null;\n\n // Find the dominant convention\n let dominantConvention = \"\";\n let maxCount = 0;\n for (const [convention, count] of conventions) {\n if (count > maxCount) {\n maxCount = count;\n dominantConvention = convention;\n }\n }\n\n // Check if current node violates the dominant convention\n const nodeConvention = detectNamingConvention(node.name);\n if (nodeConvention && nodeConvention !== dominantConvention && maxCount >= 2) {\n // Single capitalized word is compatible with both PascalCase and Title Case\n if (isCompatible(nodeConvention, dominantConvention, node.name)) return null;\n\n const suggested = convertName(node.name, dominantConvention);\n return {\n ruleId: inconsistentNamingConventionDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...inconsistentNamingMsg(node.name, nodeConvention, dominantConvention, suggested),\n };\n }\n\n return null;\n};\n\nexport const inconsistentNamingConvention = defineRule({\n definition: inconsistentNamingConventionDef,\n check: inconsistentNamingConventionCheck,\n});\n\n// ============================================\n// non-standard-naming\n// ============================================\n\nconst nonStandardNamingDef: RuleDefinition = {\n id: \"non-standard-naming\",\n name: \"Non-Standard Naming\",\n category: \"semantic\",\n why: \"Non-standard state names prevent interaction rules from detecting state variants — AI cannot generate correct :hover/:active/:disabled styles\",\n impact: \"Interaction state detection fails, resulting in static UI with no state transitions\",\n fix: \"Use platform-standard state names: default, hover, active, pressed, selected, highlighted, disabled, enabled, focus, focused, dragged\",\n};\n\nconst nonStandardNamingCheck: RuleCheckFn = (node, context) => {\n // Only check COMPONENT_SET (variant container)\n if (node.type !== \"COMPONENT_SET\") return null;\n if (!node.componentPropertyDefinitions) return null;\n\n for (const prop of Object.values(node.componentPropertyDefinitions)) {\n const p = prop as Record<string, unknown>;\n if (p[\"type\"] !== \"VARIANT\") continue;\n const options = p[\"variantOptions\"];\n if (!Array.isArray(options)) continue;\n\n for (const opt of options) {\n if (typeof opt !== \"string\") continue;\n const lower = opt.toLowerCase().trim();\n\n // Skip if it's a standard name\n if (STANDARD_STATE_NAMES.has(lower)) continue;\n\n // Check if it matches a known non-standard state name\n if (STATE_LIKE_PATTERN.test(opt)) {\n const suggestion = STATE_NAME_SUGGESTIONS[lower];\n if (suggestion) {\n return {\n ruleId: nonStandardNamingDef.id,\n subType: \"state-name\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonStandardNamingMsg.stateName(node.name, opt, suggestion),\n };\n }\n }\n }\n }\n\n return null;\n};\n\nexport const nonStandardNaming = defineRule({\n definition: nonStandardNamingDef,\n check: nonStandardNamingCheck,\n});\n\n","import type { RuleCheckFn, RuleDefinition, RuleContext } from \"../../contracts/rule.js\";\nimport { getAnalysisState } from \"../../contracts/rule.js\";\nimport type { AnalysisNode } from \"../../contracts/figma-node.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport type { MissingInteractionStateSubType, MissingPrototypeSubType } from \"../rule-messages.js\";\nimport { missingInteractionStateMsg, missingPrototypeMsg } from \"../rule-messages.js\";\nimport { getStatefulComponentType, isOverlayNode, isCarouselNode, type StatefulComponentType } from \"../node-semantics.js\";\n\n/** Expected state variants by interactive type */\nconst EXPECTED_STATES: Record<StatefulComponentType, MissingInteractionStateSubType[]> = {\n button: [\"hover\", \"active\", \"disabled\"],\n link: [\"hover\"],\n tab: [\"hover\", \"active\"],\n input: [\"focus\", \"disabled\"],\n toggle: [\"disabled\"],\n};\n\n/** State name patterns — web + mobile platform standard names */\nconst STATE_PATTERNS: Record<MissingInteractionStateSubType, RegExp> = {\n hover: /\\bhover\\b/i,\n disabled: /\\bdisabled\\b/i,\n active: /\\b(active|pressed|selected|highlighted)\\b/i,\n focus: /\\bfocus(ed)?\\b/i,\n};\n\n// ============================================\n// Helpers\n// ============================================\n\n/** Dedup key: emit at most one violation per componentId + subType */\nconst SEEN_KEY = \"missing-interaction-state:seen\";\n\nfunction getSeen(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_KEY, () => new Set<string>());\n}\n\n/**\n * Check if a state variant exists via componentPropertyDefinitions.\n * Looks for VARIANT type properties where variantOptions contain the state name.\n */\nfunction hasStateInVariantProps(node: AnalysisNode, statePattern: RegExp): boolean {\n if (!node.componentPropertyDefinitions) return false;\n for (const prop of Object.values(node.componentPropertyDefinitions)) {\n const p = prop as Record<string, unknown>;\n if (p[\"type\"] !== \"VARIANT\") continue;\n const options = p[\"variantOptions\"];\n if (!Array.isArray(options)) continue;\n if (options.some((opt) => typeof opt === \"string\" && statePattern.test(opt))) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Check if a state variant exists via component master's componentPropertyDefinitions.\n * Falls back to componentDefinitions (fetched masters) when the instance itself\n * doesn't carry the property definitions.\n */\nfunction hasStateInComponentMaster(\n node: AnalysisNode,\n context: RuleContext,\n statePattern: RegExp,\n): boolean {\n if (!node.componentId) return false;\n const defs = context.file.componentDefinitions;\n if (!defs) return false;\n const master = defs[node.componentId];\n if (!master) return false;\n return hasStateInVariantProps(master, statePattern);\n}\n\n// ============================================\n// missing-interaction-state\n// ============================================\n\nconst missingInteractionStateDef: RuleDefinition = {\n id: \"missing-interaction-state\",\n name: \"Missing Interaction State\",\n category: \"interaction\",\n why: \"Interactive components without state variants force AI to guess hover/focus/disabled appearances — or skip them entirely\",\n impact: \"Generated code has no :hover, :focus, or :disabled styles, making the UI feel static and unresponsive\",\n fix: \"Add state variants (Hover, Disabled, Focus, Active) to interactive components in Figma\",\n};\n\nconst missingInteractionStateCheck: RuleCheckFn = (node, context) => {\n // Only check component instances and components\n if (node.type !== \"INSTANCE\" && node.type !== \"COMPONENT\") return null;\n\n const interactiveType = getStatefulComponentType(node);\n if (!interactiveType) return null;\n\n const expectedStates = EXPECTED_STATES[interactiveType];\n if (!expectedStates) return null;\n\n const seen = getSeen(context);\n const nodePath = context.path.join(\" > \");\n\n for (const state of expectedStates) {\n const dedupeKey = `${node.componentId ?? node.id}:${state}`;\n if (seen.has(dedupeKey)) continue;\n\n const pattern = STATE_PATTERNS[state];\n\n // Check variant properties on instance\n if (hasStateInVariantProps(node, pattern)) continue;\n\n // Check variant properties on component master (fetched definitions)\n if (hasStateInComponentMaster(node, context, pattern)) continue;\n\n // Missing state — report first missing one\n seen.add(dedupeKey);\n return {\n ruleId: missingInteractionStateDef.id,\n subType: state,\n nodeId: node.id,\n nodePath,\n ...missingInteractionStateMsg[state](node.name),\n };\n }\n\n return null;\n};\n\nexport const missingInteractionState = defineRule({\n definition: missingInteractionStateDef,\n check: missingInteractionStateCheck,\n});\n\n// ============================================\n// missing-prototype\n// ============================================\n\n/** Interactive types that need click prototype */\nconst PROTOTYPE_TYPES: Record<StatefulComponentType, MissingPrototypeSubType> = {\n button: \"button\",\n link: \"navigation\",\n tab: \"tab\",\n input: \"input\",\n toggle: \"toggle\",\n};\n\nfunction getPrototypeSubType(node: AnalysisNode): MissingPrototypeSubType | null {\n // Check overlay/carousel first — select/dropdown are classified as \"input\" in\n // STATEFUL_PATTERNS but need \"overlay\" subType for prototype checks\n if (isOverlayNode(node)) return \"overlay\";\n if (isCarouselNode(node)) return \"carousel\";\n const interactiveType = getStatefulComponentType(node);\n if (interactiveType) {\n const mapped = PROTOTYPE_TYPES[interactiveType];\n if (mapped) return mapped;\n }\n return null;\n}\n\nfunction hasInteractionTrigger(node: AnalysisNode, triggerType: string): boolean {\n if (!node.interactions || !Array.isArray(node.interactions)) return false;\n return node.interactions.some((interaction) => {\n const i = interaction as { trigger?: { type?: string } };\n return i.trigger?.type === triggerType;\n });\n}\n\n/** Check if node (or its component master) has any of the given trigger types */\nfunction hasAnyInteraction(node: AnalysisNode, context: RuleContext, triggers: string[]): boolean {\n for (const trigger of triggers) {\n if (hasInteractionTrigger(node, trigger)) return true;\n }\n // INSTANCE nodes don't inherit interactions from master — check master fallback\n if (node.componentId && context.file.componentDefinitions) {\n const master = context.file.componentDefinitions[node.componentId];\n if (master) {\n for (const trigger of triggers) {\n if (hasInteractionTrigger(master, trigger)) return true;\n }\n }\n }\n return false;\n}\n\n/** Trigger types to check per subType */\nconst PROTOTYPE_TRIGGERS: Record<string, string[]> = {\n carousel: [\"ON_CLICK\", \"ON_DRAG\"],\n};\n\nconst DEFAULT_TRIGGERS = [\"ON_CLICK\"];\n\nconst missingPrototypeDef: RuleDefinition = {\n id: \"missing-prototype\",\n name: \"Missing Prototype\",\n category: \"interaction\",\n why: \"Interactive elements without prototype interactions give AI no information about navigation or behavior\",\n impact: \"AI cannot generate interaction handlers, routing, or state changes — interactive elements become static\",\n fix: \"Add prototype interactions (ON_CLICK, ON_DRAG) to define navigation targets or state changes\",\n};\n\nconst SEEN_PROTO_KEY = \"missing-prototype:seen\";\n\nfunction getSeenProto(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_PROTO_KEY, () => new Set<string>());\n}\n\nconst missingPrototypeCheck: RuleCheckFn = (node, context) => {\n if (node.type !== \"INSTANCE\" && node.type !== \"COMPONENT\" && node.type !== \"FRAME\") return null;\n\n const subType = getPrototypeSubType(node);\n if (!subType) return null;\n\n // Already has relevant interaction (click, or drag for carousel)\n const triggers = PROTOTYPE_TRIGGERS[subType] ?? DEFAULT_TRIGGERS;\n if (hasAnyInteraction(node, context, triggers)) return null;\n\n // Dedup per componentId + subType\n const seen = getSeenProto(context);\n const dedupeKey = `${node.componentId ?? node.id}:${subType}`;\n if (seen.has(dedupeKey)) return null;\n seen.add(dedupeKey);\n\n return {\n ruleId: missingPrototypeDef.id,\n subType,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingPrototypeMsg[subType](node.name),\n };\n};\n\nexport const missingPrototype = defineRule({\n definition: missingPrototypeDef,\n check: missingPrototypeCheck,\n});\n","#!/usr/bin/env node\nimport { createRequire } from \"node:module\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { config } from \"dotenv\";\nimport { z } from \"zod\";\nimport { writeFile } from \"node:fs\";\nimport { exec } from \"node:child_process\";\nimport { analyzeFile } from \"../core/engine/rule-engine.js\";\nimport { loadFile, isJsonFile, isFixtureDir } from \"../core/engine/loader.js\";\nimport { calculateScores, buildResultJson } from \"../core/engine/scoring.js\";\nimport { generateHtmlReport } from \"../core/report-html/index.js\";\nimport { getReportsDir, ensureReportsDir } from \"../core/engine/config-store.js\";\nimport { getConfigsWithPreset, RULE_CONFIGS, type Preset } from \"../core/rules/rule-config.js\";\nimport { loadConfigFile, mergeConfigs } from \"../core/rules/config-loader.js\";\nimport { ruleRegistry } from \"../core/rules/rule-registry.js\";\nimport type { RuleConfig, RuleId } from \"../core/contracts/rule.js\";\nimport { initMonitoring, trackEvent, trackError, shutdownMonitoring, EVENTS } from \"../core/monitoring/index.js\";\nimport { POSTHOG_API_KEY as BUILTIN_PH_KEY, SENTRY_DSN as BUILTIN_SENTRY_DSN } from \"../core/monitoring/keys.js\";\nimport { getTelemetryEnabled, getPosthogApiKey, getSentryDsn, getDeviceId } from \"../core/engine/config-store.js\";\n\n// Load .env for FIGMA_TOKEN (quiet: suppress dotenv's stdout banner — MCP uses stdout for JSON-RPC)\nconfig({ quiet: true });\n\n// Import rules to register them\nimport \"../core/rules/index.js\";\n\nconst require = createRequire(import.meta.url);\nconst pkg = require(\"../../package.json\") as { version: string };\n\nconst server = new McpServer({\n name: \"canicode\",\n version: pkg.version,\n});\n\nserver.tool(\n \"analyze\",\n `Analyze a Figma design for development-friendliness and AI-friendliness.\n\nProvide a Figma URL or fixture path via the input parameter. Requires FIGMA_TOKEN env var or the token parameter for live Figma URLs.`,\n {\n input: z.string().describe(\"Figma URL or local fixture path. Requires FIGMA_TOKEN for live URLs.\"),\n token: z.string().optional().describe(\"Figma API token (falls back to FIGMA_TOKEN env var)\"),\n preset: z.enum([\"relaxed\", \"dev-friendly\", \"ai-ready\", \"strict\"]).optional().describe(\"Analysis preset\"),\n targetNodeId: z.string().optional().describe(\"Scope analysis to a specific node ID\"),\n configPath: z.string().optional().describe(\"Path to config JSON file for rule overrides\"),\n },\n {\n readOnlyHint: false,\n destructiveHint: false,\n openWorldHint: true,\n title: \"Analyze Figma Design\",\n },\n async ({ input, token, preset, targetNodeId, configPath }) => {\n trackEvent(EVENTS.MCP_TOOL_CALLED, { tool: \"analyze\" });\n try {\n // Fetch via REST API or load from fixture\n const { file, nodeId } = await loadFile(input, token);\n\n const effectiveNodeId = targetNodeId ?? nodeId;\n\n let configs: Record<string, RuleConfig> = preset\n ? { ...getConfigsWithPreset(preset as Preset) }\n : { ...RULE_CONFIGS };\n\n if (configPath) {\n const configFile = await loadConfigFile(configPath);\n configs = mergeConfigs(configs, configFile);\n }\n\n const result = analyzeFile(file, {\n configs: configs as Record<RuleId, RuleConfig>,\n ...(effectiveNodeId ? { targetNodeId: effectiveNodeId } : {}),\n });\n\n const scores = calculateScores(result, configs as Record<RuleId, RuleConfig>);\n\n // Generate HTML report (with Figma token for comment buttons)\n const figmaToken = token ?? process.env[\"FIGMA_TOKEN\"];\n const html = generateHtmlReport(file, result, scores, { figmaToken });\n\n // Save report to disk\n const now = new Date();\n const ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}-${String(now.getHours()).padStart(2, \"0\")}-${String(now.getMinutes()).padStart(2, \"0\")}`;\n ensureReportsDir();\n const reportPath = `${getReportsDir()}/report-${ts}-${file.fileKey}.html`;\n await new Promise<void>((resolve, reject) => {\n writeFile(reportPath, html, \"utf-8\", (err) => {\n if (err) reject(err);\n else resolve();\n });\n });\n\n // Open report in browser\n const openCmd = process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"start\" : \"xdg-open\";\n exec(`${openCmd} \"${reportPath}\"`);\n\n trackEvent(EVENTS.ANALYSIS_COMPLETED, {\n nodeCount: result.nodeCount,\n issueCount: result.issues.length,\n grade: scores.overall.grade,\n percentage: scores.overall.percentage,\n source: isJsonFile(input) || isFixtureDir(input) ? \"fixture\" : \"figma\",\n });\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(buildResultJson(file.name, result, scores, { fileKey: file.fileKey }), null, 2),\n },\n ],\n };\n } catch (error) {\n trackError(\n error instanceof Error ? error : new Error(String(error)),\n { tool: \"analyze\" },\n );\n trackEvent(EVENTS.ANALYSIS_FAILED, {\n error: error instanceof Error ? error.message : String(error),\n });\n return {\n content: [\n {\n type: \"text\" as const,\n text: `Error: ${error instanceof Error ? error.message : String(error)}`,\n },\n ],\n isError: true,\n };\n }\n },\n);\n\nserver.tool(\n \"list-rules\",\n \"List all available analysis rules with their current configuration\",\n {},\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n title: \"List Analysis Rules\",\n },\n async () => {\n const rules = ruleRegistry.getAll().map((rule) => {\n const config =\n RULE_CONFIGS[rule.definition.id as keyof typeof RULE_CONFIGS];\n return {\n id: rule.definition.id,\n name: rule.definition.name,\n category: rule.definition.category,\n severity: config?.severity,\n score: config?.score,\n enabled: config?.enabled,\n why: rule.definition.why,\n };\n });\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(rules, null, 2),\n },\n ],\n };\n },\n);\n\nserver.tool(\n \"version\",\n \"Get the current canicode version. Use this when the user asks what version is installed.\",\n {},\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n title: \"Get Version\",\n },\n async () => ({\n content: [{ type: \"text\" as const, text: `canicode v${pkg.version}` }],\n }),\n);\n\nserver.tool(\n \"docs\",\n `Get documentation for CanICode.\n\nAvailable topics:\n- setup: Installation and token configuration\n- rules: All rule IDs with default scores and severity\n- config: Config overrides (scores, severity, node exclusions, thresholds)\n- visual-compare: Pixel-level comparison between Figma and AI-generated code\n- design-tree: Generate DOM-like design tree from fixture for AI code generation\n- all: Full customization guide\n\nUse this when the user asks about how to use canicode, configuration, rules, visual comparison, or any feature.`,\n {\n topic: z.enum([\"all\", \"setup\", \"rules\", \"config\", \"visual-compare\", \"design-tree\"]).optional()\n .describe(\"Topic to retrieve. Default: all\"),\n },\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n title: \"Get Documentation\",\n },\n async ({ topic }) => {\n const selectedTopic = topic ?? \"all\";\n\n // Inline topics (not from CUSTOMIZATION.md)\n const inlineTopics: Record<string, string> = {\n \"setup\": `# Setup\n\n## CLI\n\\`\\`\\`bash\nnpm install -g canicode\ncanicode init --token figd_xxxxxxxxxxxxx\n\\`\\`\\`\n\nGet your token: Figma → Settings → Security → Personal access tokens → Generate new token\n\n## MCP Server (Claude Code / Cursor / Claude Desktop)\n\\`\\`\\`bash\nclaude mcp add canicode -e FIGMA_TOKEN=figd_xxxxxxxxxxxxx -- npx -y -p canicode canicode-mcp\n\\`\\`\\`\n\nRequires FIGMA_TOKEN for live Figma URL analysis.`,\n\n \"visual-compare\": `# Visual Compare\n\nPixel-level comparison between Figma design and AI-generated code.\n\n## Usage\n\\`\\`\\`bash\ncanicode visual-compare ./index.html --figma-url 'https://www.figma.com/design/ABC/File?node-id=1-234'\n\\`\\`\\`\n\n## Options\n| Option | Default | Description |\n|--------|---------|-------------|\n| --figma-url <url> | (required) | Figma URL with node-id |\n| --token <token> | FIGMA_TOKEN env | Figma API token |\n| --output <dir> | /tmp/canicode-visual-compare | Output directory |\n| --width <px> | (inferred from Figma PNG ÷ scale) | Logical viewport width in CSS px |\n| --height <px> | (inferred from Figma PNG ÷ scale) | Logical viewport height in CSS px |\n| --figma-scale <n> | 2 | Figma export scale (matches @2x fixture PNGs) |\n\nViewport and device pixel ratio are auto-inferred from the Figma PNG dimensions and export scale. Override only when needed.\n\n## Output Files\n/tmp/canicode-visual-compare/\n figma.png — Figma screenshot (at export scale, default @2x)\n code.png — Playwright render of your HTML\n diff.png — Pixel diff (red = different)\n\n## JSON Output (stdout)\n{\n \"similarity\": 87,\n \"diffPixels\": 1340,\n \"totalPixels\": 102400,\n \"width\": 800, \"height\": 600,\n \"figmaScreenshot\": \"...\", \"codeScreenshot\": \"...\", \"diff\": \"...\"\n}\n\n## How It Works\n1. Fetches Figma screenshot via REST API (scale=2)\n2. Reads screenshot dimensions\n3. Renders HTML with Playwright at same viewport size\n4. Compares pixel-by-pixel with pixelmatch (threshold: 0.1)\n\n## Requirements\n- npx playwright install chromium\n- Figma API token with read access`,\n\n \"design-tree\": `# Design Tree\n\nGenerate a DOM-like design tree from a Figma fixture. Converts the node tree to a concise text format with inline CSS styles — 50-100x smaller than raw JSON.\n\n## Usage\n\\`\\`\\`bash\ncanicode design-tree ./fixtures/design\ncanicode design-tree ./fixtures/design --output tree.txt\ncanicode design-tree \"https://www.figma.com/design/ABC/File?node-id=1-234\"\n\\`\\`\\`\n\n## Output Format\nEach node = one line with name, type, dimensions, followed by CSS-ready styles:\n\\`\\`\\`\nHero Form (INSTANCE, 375x960)\n style: display: flex; flex-direction: column; gap: 32px; padding: 160px 24px; background: #F5F5F5\n Title (TEXT, 117x58)\n style: font-family: \"Inter\"; font-weight: 700; font-size: 48px; color: #2C2C2C; text: \"Title\"\n\\`\\`\\`\n\n## Use Cases\n- AI code generation — feed this to an LLM instead of raw 250KB fixture JSON\n- Calibration pipeline — Converter uses this for accurate code reproduction\n- Debugging — quickly see the design structure and styles`,\n };\n\n // Check inline topics first\n if (selectedTopic in inlineTopics) {\n return {\n content: [{ type: \"text\" as const, text: `canicode v${pkg.version}\\n\\n${inlineTopics[selectedTopic]}` }],\n };\n }\n\n // Fall back to CUSTOMIZATION.md for config/rules/all\n const { readFile } = await import(\"node:fs/promises\");\n const { resolve, dirname } = await import(\"node:path\");\n const { fileURLToPath } = await import(\"node:url\");\n\n try {\n const __dirname = dirname(fileURLToPath(import.meta.url));\n const docPath = resolve(__dirname, \"../../docs/CUSTOMIZATION.md\");\n let content: string;\n\n try {\n content = await readFile(docPath, \"utf-8\");\n } catch {\n const altPath = resolve(__dirname, \"../docs/CUSTOMIZATION.md\");\n content = await readFile(altPath, \"utf-8\");\n }\n\n if (selectedTopic !== \"all\") {\n const sections: Record<string, string> = {\n \"config\": \"## Config Overrides\",\n \"rules\": \"### All Rule IDs\",\n };\n const header = sections[selectedTopic];\n if (header) {\n const startIdx = content.indexOf(header);\n if (startIdx !== -1) {\n const nextH2 = content.indexOf(\"\\n## \", startIdx + header.length);\n content = nextH2 !== -1\n ? content.slice(startIdx, nextH2)\n : content.slice(startIdx);\n }\n }\n }\n\n return {\n content: [{ type: \"text\" as const, text: `canicode v${pkg.version}\\n\\n${content}` }],\n };\n } catch {\n return {\n content: [{ type: \"text\" as const, text: \"Documentation not found. See: https://github.com/let-sunny/canicode\" }],\n isError: true,\n };\n }\n },\n);\n\nserver.tool(\n \"visual-compare\",\n `Compare AI-generated code against a Figma design at the pixel level.\n\nTakes an HTML file path and a Figma URL, renders the HTML with Playwright,\nfetches the Figma screenshot, and computes pixel-level similarity using pixelmatch.\n\nReturns similarity percentage (0-100%), diff pixel count, and paths to\nthe Figma screenshot, code screenshot, and diff image.\n\nLogical viewport and device pixel ratio are inferred from the Figma PNG export scale (default 2×) so code.png matches figma.png pixels.\n\nRequires: Playwright with Chromium installed, Figma API token.`,\n {\n codePath: z.string().describe(\"Path to the HTML file to render and compare\"),\n figmaUrl: z.string().describe(\"Figma URL with node-id (e.g., https://www.figma.com/design/ABC/File?node-id=1-234)\"),\n token: z.string().optional().describe(\"Figma API token (falls back to FIGMA_TOKEN env var)\"),\n outputDir: z.string().optional().describe(\"Output directory for screenshots (default: /tmp/canicode-visual-compare)\"),\n figmaExportScale: z.number().int().min(1).max(4).optional().describe(\"Figma export scale (default 2, matches @2x fixture PNGs)\"),\n },\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: true,\n title: \"Visual Compare\",\n },\n async ({ codePath, figmaUrl, token, outputDir, figmaExportScale }) => {\n try {\n const { visualCompare } = await import(\"../core/comparison/visual-compare.js\");\n const figmaToken = token ?? process.env[\"FIGMA_TOKEN\"];\n if (!figmaToken) {\n return {\n content: [{ type: \"text\" as const, text: \"Error: Figma token required. Provide via token parameter or FIGMA_TOKEN env var.\" }],\n isError: true,\n };\n }\n\n const result = await visualCompare({\n figmaUrl,\n figmaToken,\n codePath,\n outputDir,\n ...(figmaExportScale !== undefined ? { figmaExportScale } : {}),\n });\n\n return {\n content: [{\n type: \"text\" as const,\n text: JSON.stringify({\n similarity: result.similarity,\n diffPixels: result.diffPixels,\n totalPixels: result.totalPixels,\n width: result.width,\n height: result.height,\n figmaScreenshot: result.figmaScreenshotPath,\n codeScreenshot: result.codeScreenshotPath,\n diff: result.diffPath,\n }, null, 2),\n }],\n };\n } catch (error) {\n return {\n content: [{ type: \"text\" as const, text: `Error: ${error instanceof Error ? error.message : String(error)}` }],\n isError: true,\n };\n }\n },\n);\n\nasync function main() {\n const monitoringConfig: Parameters<typeof initMonitoring>[0] = {\n environment: \"mcp\",\n version: pkg.version,\n enabled: getTelemetryEnabled(),\n };\n const phKey = getPosthogApiKey() || BUILTIN_PH_KEY;\n if (phKey) monitoringConfig.posthogApiKey = phKey;\n const sDsn = getSentryDsn() || BUILTIN_SENTRY_DSN;\n if (sDsn) monitoringConfig.sentryDsn = sDsn;\n monitoringConfig.distinctId = getDeviceId();\n initMonitoring(monitoringConfig);\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n\nprocess.on(\"beforeExit\", () => {\n shutdownMonitoring();\n});\n\nmain().catch(console.error);\n"]}