@iflow-mcp/artemsvit-figma-mcp-pro 3.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/version.ts","../src/services/figma-api.ts","../src/config/base.ts","../src/config/rules.ts","../src/processors/context-processor.ts","../src/config/frameworks/react.ts","../src/config/frameworks/vue.ts","../src/config/frameworks/angular.ts","../src/config/frameworks/svelte.ts","../src/config/frameworks/html.ts","../src/config/frameworks/swiftui.ts","../src/config/frameworks/uikit.ts","../src/config/frameworks/electron.ts","../src/config/frameworks/tauri.ts","../src/config/frameworks/nwjs.ts","../src/config/frameworks/index.ts"],"sourcesContent":["import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport {\n CallToolRequestSchema,\n ErrorCode,\n ListToolsRequestSchema,\n McpError,\n} from '@modelcontextprotocol/sdk/types.js';\nimport { z } from 'zod';\nimport { Command } from 'commander';\nimport dotenv from 'dotenv';\nimport chalk from 'chalk';\nimport path from 'path';\nimport fs from 'fs/promises';\nimport { VERSION } from './version.js';\n\n// Load environment variables\ndotenv.config();\n\n// Import our services\nimport { FigmaApiService, FigmaApiConfig } from './services/figma-api.js';\nimport { ContextProcessor, ProcessingContext } from './processors/context-processor.js';\nimport { ContextRules } from './config/rules.js';\nimport { getFrameworkRules } from './config/frameworks/index.js';\n\n// Tool schemas\nconst ShowFrameworksSchema = z.object({});\n\nconst GetFigmaDataSchema = z.object({\n fileKey: z.string().optional().describe('The Figma file key (optional if url provided)'),\n url: z.string().optional().describe('Full Figma URL with file and node selection (alternative to fileKey + nodeId)'),\n nodeId: z.string().optional().describe('Specific node ID to fetch (optional, extracted from url if provided)'),\n depth: z.number().min(1).max(10).default(5).describe('Maximum depth to traverse'),\n framework: z.enum(['react', 'vue', 'angular', 'svelte', 'html', 'swiftui', 'uikit', 'electron', 'tauri', 'nwjs']).describe('Target framework - REQUIRED (use select_framework first)'),\n includeImages: z.boolean().default(false).describe('Whether to include image URLs'),\n selectionOnly: z.boolean().default(false).describe('DEPRECATED: No longer needed. Select more specific elements in Figma if getting unintended content.'),\n customRules: z.record(z.any()).optional().describe('Custom processing rules')\n}).refine(data => data.fileKey || data.url, {\n message: \"Either fileKey or url must be provided\"\n});\n\nconst DownloadFigmaImagesSchema = z.object({\n fileKey: z.string().optional().describe('The Figma file key (optional if url provided)'),\n url: z.string().optional().describe('Full Figma URL with file and node selection - will scan selected area for ALL export assets'),\n nodeId: z.string().optional().describe('Specific node ID to scan for export assets (optional, extracted from url if provided)'),\n localPath: z.string().describe('Local directory path to save images (will be created if it does not exist)'),\n scale: z.number().min(0.5).max(4).default(2).optional().describe('Fallback export scale for images if no export settings found'),\n format: z.enum(['jpg', 'png', 'svg', 'pdf']).default('svg').optional().describe('Fallback image format if no export settings found')\n}).refine(data => data.fileKey || data.url, {\n message: \"Either fileKey or url must be provided\"\n});\n\nconst ProcessDesignCommentsSchema = z.object({\n url: z.string().describe('Figma URL to scan for comments (full URL from browser)'),\n framework: z.enum(['react', 'vue', 'angular', 'svelte', 'html']).describe('Target framework for code suggestions')\n});\n\nconst CheckReferenceSchema = z.object({\n assetsPath: z.string().describe('Path to assets folder containing reference.png file'),\n framework: z.enum(['react', 'vue', 'angular', 'svelte', 'html']).optional().describe('Target framework for development context (optional)')\n});\n\n\n\n// Server configuration\ninterface ServerConfig {\n figmaApiKey: string;\n port?: number | undefined;\n debug?: boolean;\n customRules?: Partial<ContextRules>;\n}\n\nclass CustomFigmaMcpServer {\n private server: Server;\n private figmaApi: FigmaApiService;\n private contextProcessor: ContextProcessor;\n private config: ServerConfig;\n\n // Centralized workflow constants\n private static readonly WORKFLOW_SEQUENCE = 'show_frameworks → Design data → Comments → Assets download → Reference analysis → Code generation';\n\n constructor(config: ServerConfig) {\n this.config = config;\n \n // Initialize Figma API service\n const apiConfig: FigmaApiConfig = {\n apiKey: config.figmaApiKey,\n cacheConfig: {\n ttl: parseInt(process.env.CACHE_TTL || '300'),\n maxSize: parseInt(process.env.CACHE_MAX_SIZE || '1000')\n },\n rateLimitConfig: {\n requestsPerMinute: parseInt(process.env.RATE_LIMIT_REQUESTS_PER_MINUTE || '60'),\n burstSize: parseInt(process.env.RATE_LIMIT_BURST_SIZE || '10')\n }\n };\n \n this.figmaApi = new FigmaApiService(apiConfig);\n this.contextProcessor = new ContextProcessor(config.customRules);\n \n // Initialize MCP server\n this.server = new Server(\n {\n name: 'figma-mcp-pro',\n version: VERSION,\n },\n {\n capabilities: {\n tools: {},\n },\n }\n );\n\n this.setupToolHandlers();\n this.setupErrorHandling();\n }\n\n // Helper methods to reduce duplication\n private parseFigmaUrl(url: string): { fileKey: string; nodeId?: string } {\n try {\n const urlObj = new URL(url);\n \n // Extract fileKey from URL path like /design/ZVnXdidh7cqIeJuI8e4c6g/...\n const pathParts = urlObj.pathname.split('/');\n const designIndex = pathParts.findIndex(part => part === 'design' || part === 'file');\n \n if (designIndex === -1 || designIndex >= pathParts.length - 1) {\n throw new Error('Invalid Figma URL: could not extract file key');\n }\n \n const extractedFileKey = pathParts[designIndex + 1];\n if (!extractedFileKey) {\n throw new Error('Invalid Figma URL: file key not found after design path');\n }\n \n // Extract nodeId from query params like ?node-id=1530-166\n const nodeIdParam = urlObj.searchParams.get('node-id');\n \n return {\n fileKey: extractedFileKey,\n nodeId: nodeIdParam || undefined\n };\n } catch (error) {\n throw new McpError(\n ErrorCode.InvalidParams,\n `Invalid Figma URL: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n private generateWorkflowStatus(stepComplete: string, nextStep?: string): any {\n return {\n [`${stepComplete}_COMPLETE`]: `${stepComplete} completed successfully`,\n ...(nextStep && { NEXT_STEP: nextStep }),\n COMPLETE_WORKFLOW: CustomFigmaMcpServer.WORKFLOW_SEQUENCE\n };\n }\n\n private log(...args: any[]): void {\n if (this.config.debug) {\n console.error(chalk.blue(...args)); // Use stderr for logging to avoid interfering with MCP JSON\n }\n }\n\n private logError(...args: any[]): void {\n console.error(chalk.red(...args)); // Always log errors to stderr\n }\n\n private setupToolHandlers(): void {\n // List available tools\n this.server.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: [\n {\n name: 'show_frameworks',\n description: 'STEP 1: Show available frameworks to user. Call with empty object {}. Shows options, then STOP and wait for user to tell you their choice. DO NOT make further tool calls until user provides their framework preference.',\n inputSchema: {\n type: 'object',\n properties: {},\n required: [],\n additionalProperties: false\n },\n },\n {\n name: 'get_figma_data',\n description: 'STEP 2: Get well-structured, AI-optimized Figma design data with framework-specific optimizations. Analyzes layout, components, coordinates, visual effects (shadows, borders), design tokens. PURE DESIGN DATA ONLY - no comments. Use AFTER user chooses framework. Can accept full Figma URL to automatically extract file and node selection. If getting unintended content, select a more specific element in Figma.',\n inputSchema: {\n type: 'object',\n properties: {\n fileKey: {\n type: 'string',\n description: 'The Figma file key (optional if url provided)'\n },\n url: {\n type: 'string',\n description: 'Full Figma URL with file and node selection (alternative to fileKey + nodeId)'\n },\n nodeId: {\n type: 'string',\n description: 'Specific node ID to fetch (optional, extracted from url if provided)'\n },\n depth: {\n type: 'number',\n minimum: 1,\n maximum: 10,\n default: 5,\n description: 'Maximum depth to traverse'\n },\n framework: {\n type: 'string',\n enum: ['react', 'vue', 'angular', 'svelte', 'html', 'swiftui', 'uikit', 'electron', 'tauri', 'nwjs'],\n default: 'html',\n description: 'Target framework for optimized CSS and component generation (default: html)'\n },\n includeImages: {\n type: 'boolean',\n default: false,\n description: 'Whether to include image URLs'\n },\n selectionOnly: {\n type: 'boolean',\n default: false,\n description: 'DEPRECATED: This parameter is no longer needed. The API correctly fetches only the selected node and its contents. If you are getting unintended content, select a more specific element in Figma (the exact frame/component, not a parent container).'\n },\n customRules: {\n type: 'object',\n description: 'Custom processing rules'\n }\n },\n required: []\n },\n },\n {\n name: 'process_design_comments',\n description: 'STEP 3: Process designer comments with smart coordinate matching. Use AFTER get_figma_data when you want to analyze designer instructions. Converts comments into actionable AI prompts for implementation.',\n inputSchema: {\n type: 'object',\n properties: {\n url: {\n type: 'string',\n description: 'Figma URL to scan for comments (full URL from browser)'\n },\n framework: {\n type: 'string',\n enum: ['react', 'vue', 'angular', 'svelte', 'html', 'swiftui', 'uikit', 'electron', 'tauri', 'nwjs'],\n description: 'Target framework for code suggestions'\n }\n },\n required: ['url', 'framework']\n },\n },\n {\n name: 'download_design_assets',\n description: 'STEP 4: Automatically scan selected area for ALL export-ready assets and download them with reference.png. Takes Figma URL, finds all nodes with export settings in selected area, downloads them with Figma export settings, plus creates reference.png of whole selection.',\n inputSchema: {\n type: 'object',\n properties: {\n fileKey: {\n type: 'string',\n description: 'The Figma file key (optional if url provided)'\n },\n url: {\n type: 'string',\n description: 'Full Figma URL with file and node selection - will scan selected area for ALL export assets'\n },\n nodeId: {\n type: 'string',\n description: 'Specific node ID to scan for export assets (optional, extracted from url if provided)'\n },\n localPath: {\n type: 'string',\n description: 'Local directory path to save images (will be created if it does not exist). Images will be saved with filenames based on the actual node names from Figma.'\n },\n scale: {\n type: 'number',\n minimum: 0.5,\n maximum: 4,\n default: 2,\n description: 'Fallback export scale for images if no export settings found'\n },\n format: {\n type: 'string',\n enum: ['jpg', 'png', 'svg', 'pdf'],\n default: 'svg',\n description: 'Fallback image format if no export settings found'\n }\n },\n required: ['localPath']\n },\n },\n {\n name: 'check_reference',\n description: 'STEP 5: Analyze reference.png file for design understanding. Provides design context, layout analysis, component structure guidance, and framework-specific development recommendations before starting code implementation.',\n inputSchema: {\n type: 'object',\n properties: {\n assetsPath: {\n type: 'string',\n description: 'Path to assets folder containing reference.png file'\n },\n framework: {\n type: 'string',\n enum: ['react', 'vue', 'angular', 'svelte', 'html', 'swiftui', 'uikit', 'electron', 'tauri', 'nwjs'],\n description: 'Target framework for development context (optional)'\n }\n },\n required: ['assetsPath']\n },\n }\n ],\n };\n });\n\n // Handle tool calls\n this.server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n\n try {\n switch (name) {\n case 'show_frameworks':\n return await this.handleShowFrameworks(args);\n case 'get_figma_data':\n return await this.handleGetFigmaData(args);\n case 'process_design_comments':\n return await this.handleProcessDesignComments(args);\n case 'download_design_assets':\n return await this.handleDownloadDesignAssets(args);\n case 'check_reference':\n return await this.handleCheckReference(args);\n default:\n throw new McpError(\n ErrorCode.MethodNotFound,\n `Unknown tool: ${name}`\n );\n }\n } catch (error) {\n if (error instanceof McpError) {\n throw error;\n }\n \n this.logError(`Error in tool ${name}:`, error);\n throw new McpError(\n ErrorCode.InternalError,\n `Tool execution failed: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n });\n }\n\n private async handleShowFrameworks(args: any) {\n this.log(`[Figma MCP] Showing available frameworks, received args:`, JSON.stringify(args));\n this.log(`[Figma MCP] Args type:`, typeof args);\n \n try {\n // Handle both undefined and empty object cases\n ShowFrameworksSchema.parse(args || {});\n } catch (error) {\n this.logError(`[Figma MCP] Schema validation error for args:`, args);\n this.logError(`[Figma MCP] Schema validation error:`, error);\n throw new McpError(\n ErrorCode.InvalidParams,\n `Invalid parameters: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n\n // Framework options\n const frameworks = [\n { id: 1, name: 'React', desc: 'Modern web framework with TypeScript and hooks' },\n { id: 2, name: 'Vue', desc: 'Progressive framework with Composition API' },\n { id: 3, name: 'Angular', desc: 'Full-featured framework with TypeScript' },\n { id: 4, name: 'Svelte', desc: 'Compile-time framework with reactive updates' },\n { id: 5, name: 'HTML/CSS/JS', desc: 'Vanilla web technologies, no framework' },\n { id: 6, name: 'SwiftUI', desc: 'Apple\\'s declarative UI for iOS/macOS apps' },\n { id: 7, name: 'UIKit', desc: 'Traditional Apple framework for iOS development' },\n { id: 8, name: 'Electron', desc: 'Cross-platform desktop apps with web tech' },\n { id: 9, name: 'Tauri', desc: 'Lightweight desktop apps with Rust backend' },\n { id: 10, name: 'NW.js', desc: 'Desktop apps with Node.js and Chromium' }\n ];\n\n const frameworkText = `Choose your framework:\n\n${frameworks.map(f => `${f.id}. ${f.name} - ${f.desc}`).join('\\n')}\n\nType your choice (1-10):`;\n\n return {\n content: [\n {\n type: 'text',\n text: frameworkText\n },\n {\n type: 'text', \n text: `\n\n🚨 **CRITICAL AI INSTRUCTION**: \n- Stop here - DO NOT make any more tool calls\n- Show framework options to user, short and clearly formatted, and wait for user to respond with framework number (1-10)\n- Do NOT proceed to get_figma_data until user chooses\n- STEP 1 COMPLETE - User must select framework first`\n }\n ]\n };\n }\n\n private async handleGetFigmaData(args: any) {\n this.log(`[Figma MCP] Received args:`, JSON.stringify(args, null, 2));\n \n let parsed;\n try {\n parsed = GetFigmaDataSchema.parse(args);\n } catch (error) {\n this.logError(`[Figma MCP] Schema validation error:`, error);\n throw new McpError(\n ErrorCode.InvalidParams,\n `Invalid parameters: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n \n const { framework, customRules, selectionOnly } = parsed;\n const depth = parsed.depth || 5;\n\n // Extract fileKey and nodeId from URL if provided, otherwise use direct parameters\n let fileKey: string;\n let nodeId: string | undefined;\n\n if (parsed.url) {\n this.log(`[Figma MCP] Parsing URL: ${parsed.url}`);\n const urlData = this.parseFigmaUrl(parsed.url);\n fileKey = urlData.fileKey;\n nodeId = urlData.nodeId;\n this.log(`[Figma MCP] Extracted from URL - fileKey: ${fileKey}, nodeId: ${nodeId}`);\n } else {\n // Use direct parameters\n if (!parsed.fileKey) {\n throw new McpError(\n ErrorCode.InvalidParams,\n 'fileKey is required when url is not provided'\n );\n }\n fileKey = parsed.fileKey;\n nodeId = parsed.nodeId;\n this.log(`[Figma MCP] Using direct parameters - fileKey: ${fileKey}, nodeId: ${nodeId}`);\n }\n\n // Convert node ID format from URL format (1530-166) to API format (1530:166)\n const apiNodeId = nodeId ? nodeId.replace(/-/g, ':') : undefined;\n\n // Load framework-specific rules\n const frameworkRules = getFrameworkRules(framework);\n this.log(`[Figma MCP] Using ${framework} framework with rules:`, frameworkRules);\n\n this.log(`[Figma MCP] Fetching data for file: ${fileKey} (depth: ${depth})`);\n if (apiNodeId) {\n this.log(`[Figma MCP] Target node: ${apiNodeId} (converted from: ${parsed.nodeId})`);\n this.log(`[Figma MCP] 📖 HOW FIGMA SELECTION WORKS:`);\n this.log(`[Figma MCP] ✅ When you select a node in Figma, you get that node + ALL its contents`);\n this.log(`[Figma MCP] ✅ This is correct - if you select a frame, you get the frame + all components inside`);\n this.log(`[Figma MCP] ❌ If you're getting OTHER screens you didn't select, you selected a parent container`);\n this.log(`[Figma MCP] 💡 Solution: In Figma, select the SPECIFIC frame/component, not the page or parent`);\n }\n \n try {\n // Update processor rules with framework-specific rules and custom overrides\n const mergedRules = customRules ? { ...frameworkRules, ...customRules } : frameworkRules;\n this.contextProcessor.updateRules(mergedRules);\n\n let figmaData;\n let isSpecificNode = false;\n \n if (apiNodeId) {\n // Fetch specific node with depth - this is what user selected\n this.log(`[Figma MCP] Fetching specific node: ${apiNodeId}`);\n \n // Always use full depth to get complete content of selected node\n // The selectionOnly flag will be handled during processing, not during API fetch\n this.log(`[Figma MCP] Using depth ${depth} to get complete content of selected node`);\n if (selectionOnly) {\n this.log(`[Figma MCP] Selection-only mode: Will filter out sibling content during processing`);\n }\n \n try {\n const nodeResponse = await this.figmaApi.getFileNodes(fileKey, [apiNodeId], {\n depth: depth,\n use_absolute_bounds: true\n });\n this.log(`[Figma MCP] Node response received, keys:`, Object.keys(nodeResponse.nodes));\n const nodeWrapper = nodeResponse.nodes[apiNodeId];\n if (!nodeWrapper) {\n throw new Error(`Node ${apiNodeId} not found in file ${fileKey}. Available nodes: ${Object.keys(nodeResponse.nodes).join(', ')}`);\n }\n figmaData = nodeWrapper.document;\n isSpecificNode = true;\n } catch (apiError) {\n this.logError(`[Figma MCP] API error fetching node ${apiNodeId}:`, apiError);\n throw apiError;\n }\n } else {\n // Fetch entire file with depth - fallback when no specific selection\n this.log(`[Figma MCP] Fetching entire document (no specific selection)`);\n try {\n const fileResponse = await this.figmaApi.getFile(fileKey, {\n depth: depth,\n use_absolute_bounds: true\n });\n this.log(`[Figma MCP] File response received for document:`, fileResponse.document?.name);\n figmaData = fileResponse.document;\n } catch (apiError) {\n this.logError(`[Figma MCP] API error fetching file ${fileKey}:`, apiError);\n throw apiError;\n }\n }\n\n // Debug: Log the structure we received\n this.log(`[Figma MCP] Raw data structure (${isSpecificNode ? 'SPECIFIC SELECTION' : 'FULL DOCUMENT'}):`);\n this.log(`- Node ID: ${figmaData.id}`);\n this.log(`- Node Name: ${figmaData.name}`);\n this.log(`- Node Type: ${figmaData.type}`);\n this.log(`- Has Children: ${figmaData.children ? figmaData.children.length : 0}`);\n \n if (figmaData.children && figmaData.children.length > 0) {\n const maxChildren = isSpecificNode ? Math.min(10, figmaData.children.length) : Math.min(5, figmaData.children.length);\n this.log(`[Figma MCP] Showing ${maxChildren} of ${figmaData.children.length} children:`);\n for (let i = 0; i < maxChildren; i++) {\n const child = figmaData.children[i];\n if (child) {\n this.log(` - Child ${i}: \"${child.name}\" (${child.type}) - Children: ${child.children ? child.children.length : 0}`);\n if (child.absoluteBoundingBox) {\n this.log(` Bounds: ${Math.round(child.absoluteBoundingBox.x)}, ${Math.round(child.absoluteBoundingBox.y)} (${Math.round(child.absoluteBoundingBox.width)}x${Math.round(child.absoluteBoundingBox.height)})`);\n }\n }\n }\n if (figmaData.children.length > maxChildren) {\n this.log(` - ... and ${figmaData.children.length - maxChildren} more children`);\n }\n }\n \n // Additional guidance for users about selection scope\n if (isSpecificNode && figmaData.children && figmaData.children.length > 1) {\n this.log(`[Figma MCP] ✅ SELECTION ANALYSIS: You selected \"${figmaData.name}\" (${figmaData.type}) which contains ${figmaData.children.length} child elements.`);\n this.log(`[Figma MCP] 📋 This is the correct behavior - you get the selected element AND all its contents.`);\n this.log(`[Figma MCP] 💡 If you're seeing content from OTHER screens you didn't select:`);\n this.log(`[Figma MCP] - You may have selected a parent container (like a page or large frame)`);\n this.log(`[Figma MCP] - In Figma, select the SPECIFIC frame/component you want, not its parent`);\n this.log(`[Figma MCP] - Look for the exact screen/component in the layers panel and select that`);\n } else if (isSpecificNode) {\n this.log(`[Figma MCP] ✅ SELECTION ANALYSIS: You selected \"${figmaData.name}\" (${figmaData.type}) - single element with no children.`);\n }\n\n // Process the data with context enhancement\n const processingContext: ProcessingContext = {\n fileKey,\n depth: 0,\n siblingIndex: 0,\n totalSiblings: 1,\n framework\n };\n\n let enhancedData = await this.contextProcessor.processNode(figmaData, processingContext);\n\n // Get processing stats\n const stats = this.contextProcessor.getStats();\n \n // Note: Image fetching removed - exportable images are detected in data structure\n // Use download_figma_images tool for actual image downloads\n\n this.log(`[Figma MCP] Successfully processed ${stats.nodesProcessed} nodes`);\n\n // Generate optimized data for AI (removing redundant information)\n const optimizedData = this.contextProcessor.optimizeForAI(enhancedData);\n\n // Create clean metadata (design data only)\n const debugInfo: any = {\n framework: framework,\n frameworkRules: frameworkRules,\n source: isSpecificNode ? 'selection' : 'document',\n processed: stats.nodesProcessed,\n selectedNode: isSpecificNode ? { id: figmaData.id, name: figmaData.name, type: figmaData.type, childCount: figmaData.children?.length || 0 } : null,\n IMPORTANT_NEXT_STEPS: {\n STEP_3: 'REQUIRED: Use process_design_comments tool to check for designer comments',\n STEP_4: 'Use download_design_assets tool to get images and visual reference',\n STEP_5: 'Use check_reference tool to analyze reference.png before development',\n COMPLETE_WORKFLOW: CustomFigmaMcpServer.WORKFLOW_SEQUENCE,\n CURRENT_STATUS: 'STEP 2 COMPLETE - Design data extracted successfully'\n }\n };\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n // Essential metadata FIRST - so AI sees guidance immediately\n metadata: debugInfo,\n \n // Primary data: AI-optimized and clean \n data: optimizedData\n }, null, 2)\n }\n ]\n };\n\n } catch (error) {\n this.logError(`[Figma MCP] Error fetching data:`, error);\n throw new McpError(\n ErrorCode.InternalError,\n `Failed to fetch Figma data: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n\n\n private async handleProcessDesignComments(args: any) {\n this.log(`[Figma MCP] Processing design comments:`, JSON.stringify(args, null, 2));\n \n let parsed;\n try {\n parsed = ProcessDesignCommentsSchema.parse(args);\n } catch (error) {\n this.logError(`[Figma MCP] Schema validation error:`, error);\n throw new McpError(\n ErrorCode.InvalidParams,\n `Invalid parameters: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n \n const { url, framework } = parsed;\n\n // Parse Figma URL to extract fileKey and nodeId\n const urlData = this.parseFigmaUrl(url);\n const fileKey = urlData.fileKey;\n const nodeId = urlData.nodeId;\n \n this.log(`[Figma MCP] Parsed URL - fileKey: ${fileKey}, nodeId: ${nodeId}, framework: ${framework}`);\n\n try {\n // Fetch comments from Figma API\n this.log(`[Figma MCP] Fetching comments for file: ${fileKey}`);\n const commentsResponse = await this.figmaApi.getComments(fileKey);\n let relevantComments = commentsResponse.comments;\n \n // If specific node is selected, filter comments to only those related to the selection\n if (nodeId) {\n const apiNodeId = nodeId.replace(/-/g, ':');\n this.log(`[Figma MCP] Filtering comments for specific node: ${apiNodeId} (from ${nodeId})`);\n \n // Get the bounds of the selected node for coordinate-based filtering\n let selectedNodeBounds = null;\n try {\n const nodeResponse = await this.figmaApi.getFileNodes(fileKey, [apiNodeId], { depth: 1 });\n const selectedNode = nodeResponse.nodes[apiNodeId]?.document;\n if (selectedNode?.absoluteBoundingBox) {\n selectedNodeBounds = selectedNode.absoluteBoundingBox;\n this.log(`[Figma MCP] Selected node bounds:`, selectedNodeBounds);\n }\n } catch (boundsError) {\n this.log(`[Figma MCP] Could not get node bounds for filtering:`, boundsError);\n }\n \n // Filter comments that are related to the selected node\n const originalCount = relevantComments.length;\n relevantComments = relevantComments.filter(comment => {\n // Check if comment is directly on the selected node\n if (comment.client_meta?.node_id === apiNodeId) {\n this.log(`[Figma MCP] Comment directly on selected node: \"${comment.message}\"`);\n return true;\n }\n \n // Check if comment coordinates are within selected node bounds\n if (selectedNodeBounds) {\n const commentAny = comment as any; // Type cast to access coordinate properties\n const commentX = comment.client_meta?.node_offset?.x || (comment.client_meta as any)?.x || commentAny.x;\n const commentY = comment.client_meta?.node_offset?.y || (comment.client_meta as any)?.y || commentAny.y;\n \n if (commentX !== undefined && commentY !== undefined) {\n const isWithinBounds = commentX >= selectedNodeBounds.x && \n commentX <= selectedNodeBounds.x + selectedNodeBounds.width &&\n commentY >= selectedNodeBounds.y && \n commentY <= selectedNodeBounds.y + selectedNodeBounds.height;\n \n if (isWithinBounds) {\n this.log(`[Figma MCP] Comment within node bounds: \"${comment.message}\" at (${commentX}, ${commentY})`);\n return true;\n }\n }\n }\n \n return false; // Exclude comments not related to the selected node\n });\n \n this.log(`[Figma MCP] Comment filtering: ${originalCount} total → ${relevantComments.length} relevant to selected node`);\n }\n \n this.log(`[Figma MCP] Found ${relevantComments.length} comments to process${nodeId ? ' for selected node' : ' in file'}`);\n\n if (relevantComments.length === 0) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n message: nodeId ? 'No comments found for the selected node/section' : 'No comments found in this design',\n comments: [],\n aiPrompts: [],\n nodeSelection: nodeId ? `Checked for comments on node: ${nodeId}` : 'Checked entire file',\n WORKFLOW_STATUS: this.generateWorkflowStatus('STEP_3', 'STEP 4: Use download_design_assets tool to get images and reference.png')\n }, null, 2)\n }\n ]\n };\n }\n\n // Get design data to extract elements with bounds\n this.log(`[Figma MCP] Fetching design data for element analysis`);\n const figmaDataArgs: any = {\n fileKey,\n framework,\n includeComments: false,\n depth: 5\n };\n \n if (nodeId) {\n figmaDataArgs.nodeId = nodeId;\n }\n\n const figmaDataResult = await this.handleGetFigmaData(figmaDataArgs);\n const analysisData = figmaDataResult?.content?.[0]?.text ? JSON.parse(figmaDataResult.content[0].text) : {};\n \n // Extract all elements with bounds from analysis data\n const elementsWithBounds = this.extractElementsWithBounds(analysisData.data);\n this.log(`[Figma MCP] Extracted ${elementsWithBounds.length} elements with bounds for matching`);\n\n // Process each comment and create clean implementation instructions\n const implementations = [];\n \n this.log(`[Figma MCP] Debug - Relevant comments structure:`, JSON.stringify(relevantComments, null, 2));\n this.log(`[Figma MCP] Debug - Elements with bounds:`, elementsWithBounds.length);\n\n for (const comment of relevantComments) {\n this.log(`[Figma MCP] Debug - Processing comment:`, JSON.stringify(comment, null, 2));\n \n // Extract coordinates from comment structure\n let coordinates = null;\n if (comment.client_meta?.node_offset) {\n coordinates = {\n x: comment.client_meta.node_offset.x,\n y: comment.client_meta.node_offset.y\n };\n this.log(`[Figma MCP] Found coordinates: (${coordinates.x}, ${coordinates.y})`);\n } else {\n this.log(`[Figma MCP] No coordinates in client_meta.node_offset`);\n this.log(`[Figma MCP] Available client_meta:`, comment.client_meta || 'null');\n }\n \n // Find target element if coordinates available\n let targetElement = null;\n if (coordinates) {\n // Find element containing or near the comment\n const candidateElements = elementsWithBounds.filter(element => {\n const bounds = element.bounds;\n const isInside = coordinates.x >= bounds.x && \n coordinates.x <= bounds.x + bounds.width &&\n coordinates.y >= bounds.y && \n coordinates.y <= bounds.y + bounds.height;\n \n if (!isInside) {\n // Check if comment is near the element (within 100px)\n const centerX = bounds.x + bounds.width / 2;\n const centerY = bounds.y + bounds.height / 2;\n const distance = Math.sqrt(Math.pow(coordinates.x - centerX, 2) + Math.pow(coordinates.y - centerY, 2));\n return distance <= 100;\n }\n return true;\n });\n \n if (candidateElements.length > 0) {\n // Sort by proximity and take closest\n candidateElements.sort((a, b) => {\n const distA = Math.sqrt(\n Math.pow(coordinates.x - (a.bounds.x + a.bounds.width / 2), 2) + \n Math.pow(coordinates.y - (a.bounds.y + a.bounds.height / 2), 2)\n );\n const distB = Math.sqrt(\n Math.pow(coordinates.x - (b.bounds.x + b.bounds.width / 2), 2) + \n Math.pow(coordinates.y - (b.bounds.y + b.bounds.height / 2), 2)\n );\n return distA - distB;\n });\n targetElement = candidateElements[0]?.name;\n this.log(`[Figma MCP] Matched comment to element: ${targetElement}`);\n }\n }\n \n // Create clean implementation instruction\n const implementation = {\n instruction: comment.message,\n targetElement: targetElement || \"Apply to relevant design element\",\n coordinates: coordinates\n };\n \n implementations.push(implementation);\n this.log(`[Figma MCP] Added implementation: \"${comment.message}\" → ${targetElement || 'General'}`);\n }\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n implementations: implementations,\n framework: framework,\n nodeContext: nodeId ? `Comments for node: ${nodeId}` : 'Comments for entire file',\n WORKFLOW_STATUS: this.generateWorkflowStatus('STEP_3', 'STEP 4: Use download_design_assets tool to get images and reference.png')\n }, null, 2)\n }\n ]\n };\n\n } catch (error) {\n this.logError(`[Figma MCP] Error processing comments:`, error);\n throw new McpError(\n ErrorCode.InternalError,\n `Failed to process design comments: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n /**\n * Extract all elements with bounds from analysis data recursively\n */\n private extractElementsWithBounds(data: any): Array<{\n id: string;\n name: string;\n type: string;\n bounds: { x: number; y: number; width: number; height: number };\n path: string;\n }> {\n const elements: Array<{\n id: string;\n name: string;\n type: string;\n bounds: { x: number; y: number; width: number; height: number };\n path: string;\n }> = [];\n\n const traverse = (node: any, path: string = '') => {\n const fullPath = path ? `${path} > ${node.name}` : node.name;\n \n // Try multiple possible bounds field names\n let bounds = null;\n if (node.bounds) {\n bounds = node.bounds;\n } else if (node.absoluteBoundingBox) {\n bounds = {\n x: node.absoluteBoundingBox.x,\n y: node.absoluteBoundingBox.y,\n width: node.absoluteBoundingBox.width,\n height: node.absoluteBoundingBox.height\n };\n } else if (node.relativeTransform && node.size) {\n // Calculate bounds from transform and size\n bounds = {\n x: node.relativeTransform[0][2] || 0,\n y: node.relativeTransform[1][2] || 0,\n width: node.size.x || 0,\n height: node.size.y || 0\n };\n }\n \n if (bounds && node.id && node.name && node.type) {\n elements.push({\n id: node.id,\n name: node.name,\n type: node.type,\n bounds: bounds,\n path: fullPath\n });\n \n this.log(`[DEBUG] Added element: ${node.name} (${node.type}) at (${bounds.x}, ${bounds.y}) size ${bounds.width}x${bounds.height}`);\n } else {\n this.log(`[DEBUG] Skipped element: ${node.name || 'unnamed'} - missing bounds or required fields`);\n this.log(`[DEBUG] Available node fields:`, Object.keys(node));\n }\n\n if (node.children && Array.isArray(node.children)) {\n for (const child of node.children) {\n traverse(child, fullPath);\n }\n }\n };\n\n traverse(data);\n return elements;\n }\n\n /**\n * Setup project assets directory and copy from Cursor fallback location\n * This handles the Cursor IDE working directory bug by copying assets from the fallback location\n */\n\n private async handleCheckReference(args: any) {\n this.log(`[Figma MCP] Checking reference image:`, JSON.stringify(args, null, 2));\n \n let parsed;\n try {\n parsed = CheckReferenceSchema.parse(args);\n } catch (error) {\n this.logError(`[Figma MCP] Schema validation error:`, error);\n throw new McpError(\n ErrorCode.InvalidParams,\n `Invalid parameters: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n \n const { assetsPath, framework: _framework } = parsed;\n\n try {\n // Simple path resolution\n const resolvedPath = path.isAbsolute(assetsPath) \n ? assetsPath \n : path.resolve(process.cwd(), assetsPath);\n \n const referencePath = path.join(resolvedPath, 'reference.png');\n \n this.log(`[Figma MCP] Looking for reference.png at: ${referencePath}`);\n \n // Simple check - does reference.png exist?\n try {\n const fileStats = await fs.stat(referencePath);\n \n if (!fileStats.isFile() || fileStats.size === 0) {\n throw new Error('File exists but is invalid');\n }\n \n const fileSizeKB = Math.round(fileStats.size / 1024);\n const relativePath = path.relative(process.cwd(), referencePath);\n \n this.log(`[Figma MCP] ✅ Reference found: ${referencePath} (${fileSizeKB}KB)`);\n \n // Success - ready for next step\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n status: 'success',\n message: 'reference.png found and verified',\n reference: {\n path: relativePath,\n size: `${fileSizeKB} KB`,\n verified: true\n },\n instruction: 'Analyze reference.png with all collected design data to understand layout, components, and visual context before code implementation',\n STEP_5_COMPLETE: true,\n NEXT_ACTION: 'Implement code using reference.png analysis + design data + downloaded assets',\n READY_FOR_DEVELOPMENT: true\n }, null, 2)\n }\n ]\n };\n \n } catch (statError) {\n // File doesn't exist - need to run download_design_assets first\n this.log(`[Figma MCP] ❌ reference.png not found at: ${referencePath}`);\n \n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n status: 'error',\n message: 'reference.png not found in assets folder',\n expectedPath: referencePath,\n REQUIRED_ACTION: 'Run download_design_assets first to create reference.png',\n STEP_4_MISSING: 'download_design_assets must be completed before check_reference',\n NEXT_STEP: 'Call download_design_assets with your Figma URL to create reference.png'\n }, null, 2)\n }\n ]\n };\n }\n\n } catch (error) {\n this.logError(`[Figma MCP] Error checking reference:`, error);\n throw new McpError(\n ErrorCode.InternalError,\n `Failed to check reference: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n\n\n private async handleDownloadDesignAssets(args: any) {\n const parsed = DownloadFigmaImagesSchema.parse(args);\n const { localPath } = parsed;\n\n // Add comprehensive debug logging for path resolution\n this.log(`[Figma MCP] 🔍 DEBUG: Download request analysis:`);\n this.log(`[Figma MCP] 📁 Requested localPath: \"${localPath}\"`);\n this.log(`[Figma MCP] 🌍 Environment context:`);\n this.log(`[Figma MCP] - process.cwd(): \"${process.cwd()}\"`);\n this.log(`[Figma MCP] - PWD: \"${process.env.PWD || 'undefined'}\"`);\n this.log(`[Figma MCP] - INIT_CWD: \"${process.env.INIT_CWD || 'undefined'}\"`);\n this.log(`[Figma MCP] - PROJECT_ROOT: \"${process.env.PROJECT_ROOT || 'undefined'}\"`);\n this.log(`[Figma MCP] - WORKSPACE_ROOT: \"${process.env.WORKSPACE_ROOT || 'undefined'}\"`);\n\n // Extract fileKey and nodeId from URL if provided, otherwise use direct parameters\n let fileKey: string;\n let nodeId: string | undefined;\n\n if (parsed.url) {\n this.log(`[Figma MCP] Parsing URL: ${parsed.url}`);\n const urlData = this.parseFigmaUrl(parsed.url);\n fileKey = urlData.fileKey;\n nodeId = urlData.nodeId;\n this.log(`[Figma MCP] Extracted from URL - fileKey: ${fileKey}, nodeId: ${nodeId}`);\n } else {\n // Use direct parameters\n if (!parsed.fileKey) {\n throw new McpError(\n ErrorCode.InvalidParams,\n 'fileKey is required when url is not provided'\n );\n }\n fileKey = parsed.fileKey;\n nodeId = parsed.nodeId;\n this.log(`[Figma MCP] Using direct parameters - fileKey: ${fileKey}, nodeId: ${nodeId}`);\n }\n\n // Convert node ID format from URL format (1530-166) to API format (1530:166)\n const apiNodeId = nodeId ? nodeId.replace(/-/g, ':') : undefined;\n\n this.log(`[Figma MCP] Scanning for export assets in ${apiNodeId ? `selected area: ${apiNodeId}` : 'entire file'}`);\n\n try {\n // Step 1: Get the selected area data to scan for export assets\n let targetNode;\n if (apiNodeId) {\n this.log(`[Figma MCP] Fetching selected node: ${apiNodeId}`);\n const nodeResponse = await this.figmaApi.getFileNodes(fileKey, [apiNodeId], {\n depth: 10, // Deep scan to find all export assets\n use_absolute_bounds: true\n });\n const nodeWrapper = nodeResponse.nodes[apiNodeId];\n if (!nodeWrapper) {\n throw new Error(`Node ${apiNodeId} not found in file ${fileKey}`);\n }\n targetNode = nodeWrapper.document;\n } else {\n this.log(`[Figma MCP] Fetching entire document for export scan`);\n const fileResponse = await this.figmaApi.getFile(fileKey, {\n depth: 10, // Deep scan to find all export assets\n use_absolute_bounds: true\n });\n targetNode = fileResponse.document;\n }\n\n // Step 2: Recursively scan for all nodes with export settings\n const exportableNodes = this.findNodesWithExportSettings(targetNode);\n this.log(`[Figma MCP] Found ${exportableNodes.length} nodes with export settings`);\n\n if (exportableNodes.length === 0) {\n this.log(`[Figma MCP] No export settings found in selected area`);\n \n // Still create reference.png of the selected area\n let referenceResult = null;\n try {\n this.log(`[Figma MCP] Creating visual reference of selected area...`);\n referenceResult = await this.createVisualReference(fileKey, apiNodeId ? [apiNodeId] : [], localPath);\n } catch (referenceError) {\n this.logError(`[Figma MCP] Failed to create reference:`, referenceError);\n }\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n downloads: [],\n summary: { total: 0, successful: 0, failed: 0 },\n reference: referenceResult,\n message: 'No export settings found in selected area. Only reference.png created.',\n instructions: this.generateDownloadInstructions([], referenceResult)\n }, null, 2)\n }\n ]\n };\n }\n\n // Step 3: Download all exportable assets with their Figma export settings\n this.log(`[Figma MCP] 🔥 DEBUG: About to download ${exportableNodes.length} export-ready assets...`);\n this.log(`[Figma MCP] 📁 Target localPath: \"${localPath}\"`);\n \n const downloadResult = await this.figmaApi.downloadImagesWithExportSettings(\n fileKey,\n exportableNodes,\n localPath,\n { skipWorkspaceEnforcement: true, overwriteExisting: true }\n );\n\n this.log(`[Figma MCP] 🔥 DEBUG: Export download completed!`);\n this.log(`[Figma MCP] 📊 Summary: ${downloadResult.summary.successful} successful, ${downloadResult.summary.failed} failed`);\n this.log(`[Figma MCP] 📁 Workspace enforcement result:`, downloadResult.workspaceEnforcement || 'No enforcement info');\n \n // Debug: Log actual file locations\n if (downloadResult.downloaded.length > 0) {\n this.log(`[Figma MCP] 🔍 DEBUG: Actual download locations:`);\n downloadResult.downloaded.forEach((download, index) => {\n this.log(`[Figma MCP] ${index + 1}. ${download.nodeName} → ${download.filePath} (success: ${download.success})`);\n });\n }\n\n // Step 4: Create visual context reference of the selected area\n let referenceResult = null;\n try {\n this.log(`[Figma MCP] Creating visual reference of selected area...`);\n referenceResult = await this.createVisualReference(fileKey, apiNodeId ? [apiNodeId] : [], localPath);\n \n if (referenceResult?.success) {\n this.log(`[Figma MCP] ✅ Reference created at: ${referenceResult.filePath}`);\n } else {\n this.log(`[Figma MCP] ⚠️ Reference creation failed:`, referenceResult?.error);\n }\n } catch (referenceError) {\n this.logError(`[Figma MCP] Failed to create reference:`, referenceError);\n // Don't fail the entire download if reference creation fails\n }\n\n // Step 5: Verify where files actually ended up\n this.log(`[Figma MCP] 🔍 DEBUG: Final verification of file locations:`);\n \n for (const download of downloadResult.downloaded) {\n if (download.success) {\n try {\n const stat = await fs.stat(download.filePath);\n const relativePath = path.relative(process.cwd(), download.filePath);\n this.log(`[Figma MCP] ✅ Verified: ${download.nodeName}`);\n this.log(`[Figma MCP] 📁 Absolute: ${download.filePath}`);\n this.log(`[Figma MCP] 📂 Relative: ${relativePath}`);\n this.log(`[Figma MCP] 📦 Size: ${Math.round(stat.size / 1024)}KB`);\n } catch (verifyError) {\n this.log(`[Figma MCP] ❌ NOT FOUND: ${download.nodeName} at ${download.filePath}`);\n }\n }\n }\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n downloads: downloadResult.downloaded,\n summary: downloadResult.summary,\n reference: referenceResult,\n workspaceEnforcement: downloadResult.workspaceEnforcement,\n debug: {\n requestedPath: localPath,\n resolvedWorkspace: downloadResult.workspaceEnforcement?.finalLocation || 'No workspace info',\n actualPaths: downloadResult.downloaded.map(d => ({ \n name: d.nodeName, \n path: d.filePath, \n success: d.success \n }))\n },\n exportSettings: {\n found: exportableNodes.length,\n downloaded: downloadResult.summary.successful,\n scope: apiNodeId ? `Selected area: ${nodeId}` : 'Entire file'\n },\n message: downloadResult.summary.total === 0 \n ? 'No export assets found to download.'\n : `Downloaded ${downloadResult.summary.successful} export-ready assets with Figma export settings, plus reference.png of selected area.`,\n instructions: this.generateDownloadInstructions(downloadResult.downloaded, referenceResult)\n }, null, 2)\n }\n ]\n };\n\n } catch (error) {\n this.logError(`[Figma MCP] Error downloading assets:`, error);\n throw new McpError(\n ErrorCode.InternalError,\n `Failed to download assets: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n\n\n /**\n * Find all nodes with Figma export settings configured\n */\n private findNodesWithExportSettings(node: any): any[] {\n const exportableNodes: any[] = [];\n \n const scanNode = (currentNode: any) => {\n // Check if this node has export settings\n if (currentNode.exportSettings && Array.isArray(currentNode.exportSettings) && currentNode.exportSettings.length > 0) {\n this.log(`[Figma MCP] Found export settings on node: ${currentNode.name} (${currentNode.type}) - ${currentNode.exportSettings.length} settings`);\n exportableNodes.push(currentNode);\n }\n \n // Recursively check children\n if (currentNode.children && Array.isArray(currentNode.children)) {\n currentNode.children.forEach((child: any) => {\n scanNode(child);\n });\n }\n };\n \n if (node) {\n scanNode(node);\n }\n \n this.log(`[Figma MCP] Export scan complete: found ${exportableNodes.length} nodes with export settings`);\n return exportableNodes;\n }\n\n\n\n /**\n * Create visual context reference by finding and downloading the parent context\n */\n private async createVisualReference(fileKey: string, selectedNodeIds: string[], localPath: string): Promise<{\n success: boolean;\n filePath?: string;\n contextType: 'parent-frame' | 'page' | 'document';\n contextName?: string;\n error?: string;\n }> {\n try {\n // Strategy: Find the common parent or page context for visual reference\n let referenceNodeId: string | null = null;\n let contextType: 'parent-frame' | 'page' | 'document' = 'document';\n let contextName = 'Visual Context';\n\n // Strategy: Use the actual selected node(s) for context, not parent/page\n if (selectedNodeIds.length === 1 && selectedNodeIds[0]) {\n // Single selection: use the selected node itself as reference\n const firstNodeId = selectedNodeIds[0];\n try {\n const nodeResponse = await this.figmaApi.getFileNodes(fileKey, [firstNodeId], { depth: 2 });\n const selectedNode = nodeResponse.nodes[firstNodeId]?.document;\n \n if (selectedNode) {\n referenceNodeId = selectedNode.id;\n contextType = selectedNode.type === 'CANVAS' ? 'page' : 'parent-frame';\n contextName = selectedNode.name;\n this.log(`[Figma MCP] Using selected node as reference: ${contextName} (${selectedNode.type})`);\n } else {\n this.log(`[Figma MCP] Selected node not found, trying page fallback`);\n }\n } catch (nodeError) {\n this.log(`[Figma MCP] Could not get selected node details:`, nodeError);\n }\n } else if (selectedNodeIds.length > 1 && selectedNodeIds[0]) {\n // Multiple selections: try to find common parent or use first node\n referenceNodeId = selectedNodeIds[0]; // Use first selection as context\n contextType = 'parent-frame';\n contextName = 'Multiple Selection Context';\n this.log(`[Figma MCP] Multiple selections, using first node as reference context`);\n }\n\n // Last resort fallback: Use first page as reference\n if (!referenceNodeId) {\n this.log(`[Figma MCP] No specific selection context, falling back to page`);\n try {\n const fileResponse = await this.figmaApi.getFile(fileKey, { depth: 2 });\n if (fileResponse.document?.children?.[0]) {\n referenceNodeId = fileResponse.document.children[0].id;\n contextType = 'page';\n contextName = fileResponse.document.children[0].name;\n }\n } catch (fileError) {\n return {\n success: false,\n contextType: 'document',\n error: 'Could not access file for reference context'\n };\n }\n }\n\n if (!referenceNodeId) {\n return {\n success: false,\n contextType: 'document',\n error: 'Could not determine reference context'\n };\n }\n\n this.log(`[Figma MCP] Creating reference from ${contextType}: \"${contextName}\" (${referenceNodeId})`);\n\n // Download the reference as PNG with 1x scale as requested\n const referenceDownload = await this.figmaApi.downloadImages(\n fileKey,\n [referenceNodeId],\n localPath,\n {\n scale: 1, // Use 1x scale as requested by user\n format: 'png',\n skipWorkspaceEnforcement: true\n }\n );\n\n if (referenceDownload.summary.successful === 0) {\n return {\n success: false,\n contextType,\n contextName,\n error: 'Failed to download reference image'\n };\n }\n\n // Force rename to reference.png with robust fallback handling\n const originalFile = referenceDownload.downloaded[0];\n if (originalFile && originalFile.success) {\n const referenceFilePath = path.join(localPath, 'reference.png');\n \n this.log(`[Figma MCP] 🔄 Converting \"${path.basename(originalFile.filePath)}\" → \"reference.png\"`);\n \n try {\n // Check if original file exists first\n await fs.access(originalFile.filePath);\n \n // Method 1: Try direct rename (fastest, works if same filesystem)\n await fs.rename(originalFile.filePath, referenceFilePath);\n this.log(`[Figma MCP] ✅ Successfully renamed to reference.png via fs.rename`);\n \n return {\n success: true,\n filePath: referenceFilePath,\n contextType,\n contextName\n };\n } catch (renameError) {\n this.log(`[Figma MCP] ⚠️ Direct rename failed (${renameError}), trying copy + delete...`);\n \n try {\n // Check if original file still exists\n await fs.access(originalFile.filePath);\n \n // Method 2: Copy + delete (works across filesystems, handles Cursor restrictions)\n await fs.copyFile(originalFile.filePath, referenceFilePath);\n \n // Verify the copy succeeded before deleting original\n const copyStats = await fs.stat(referenceFilePath);\n if (copyStats.size > 0) {\n // Delete original only after successful copy\n try {\n await fs.unlink(originalFile.filePath);\n this.log(`[Figma MCP] ✅ Successfully created reference.png via copy + delete`);\n } catch (deleteError) {\n this.log(`[Figma MCP] ⚠️ Copy succeeded but original file deletion failed: ${deleteError}`);\n // Continue anyway - we have reference.png\n }\n \n return {\n success: true,\n filePath: referenceFilePath,\n contextType,\n contextName\n };\n } else {\n throw new Error('Copy resulted in empty file');\n }\n } catch (copyError) {\n this.logError(`[Figma MCP] ❌ Both rename and copy failed:`, copyError);\n \n // Method 3: Create a symbolic link to reference.png\n try {\n // Check if original file still exists\n await fs.access(originalFile.filePath);\n \n // Create a hard link (works better than symlink for cross-platform)\n await fs.link(originalFile.filePath, referenceFilePath);\n this.log(`[Figma MCP] ✅ Successfully created reference.png via hard link`);\n \n return {\n success: true,\n filePath: referenceFilePath,\n contextType,\n contextName\n };\n } catch (linkError) {\n this.logError(`[Figma MCP] ❌ Hard link creation failed:`, linkError);\n \n // Method 4: Last resort - use the original file as reference but log the issue\n this.log(`[Figma MCP] 🔧 Using original file as reference: ${path.basename(originalFile.filePath)}`);\n \n return {\n success: true,\n filePath: originalFile.filePath, // Use original path\n contextType,\n contextName,\n error: `Warning: Could not rename to reference.png, using original filename: ${path.basename(originalFile.filePath)}`\n };\n }\n }\n }\n }\n\n return {\n success: false,\n contextType,\n contextName,\n error: 'Reference download was not successful'\n };\n\n } catch (error) {\n this.logError(`[Figma MCP] Error creating visual reference:`, error);\n return {\n success: false,\n contextType: 'document',\n error: error instanceof Error ? error.message : String(error)\n };\n }\n }\n\n /**\n * Generate instructions for using downloaded assets and reference (Universal IDE compatibility)\n */\n private generateDownloadInstructions(downloads: any[], referenceResult: any): string[] {\n const instructions: string[] = [];\n const workingDir = process.cwd();\n \n if (downloads.length > 0) {\n instructions.push(`📁 Asset Files Downloaded:`);\n downloads.forEach(download => {\n if (download.success) {\n // Show both filename and relative path for universal IDE compatibility\n const filename = download.filePath.split('/').pop() || 'unknown';\n const relativePath = download.relativePath || `./${filename}`;\n const fileSize = download.fileSize ? ` (${Math.round(download.fileSize / 1024)}KB)` : '';\n const verified = download.verified !== false ? '✅' : '⚠️';\n \n instructions.push(` ${verified} ${download.nodeName}`);\n instructions.push(` 📁 File: ${filename}${fileSize}`);\n instructions.push(` 📂 Path: ${relativePath}`);\n if (download.verified === false) {\n instructions.push(` ⚠️ File verification failed - check directory structure`);\n }\n } else {\n instructions.push(` ❌ ${download.nodeId || download.nodeName} → Failed: ${download.error}`);\n }\n });\n instructions.push('');\n }\n\n if (referenceResult?.success) {\n const referenceRelativePath = referenceResult.filePath ? \n path.relative(workingDir, referenceResult.filePath) : './reference.png';\n \n instructions.push(`🎯 Visual Context Reference:`);\n instructions.push(` 📄 reference.png → Shows ${referenceResult.contextType} context: \"${referenceResult.contextName}\"`);\n instructions.push(` 📂 Path: ${referenceRelativePath.startsWith('.') ? referenceRelativePath : `./${referenceRelativePath}`}`);\n instructions.push(` 💡 Use this reference to understand how downloaded assets fit in the overall design`);\n instructions.push(` 🔍 Open reference.png to see layout, positioning, and relationship between elements`);\n instructions.push('');\n }\n\n instructions.push(`🔄 NEXT STEP - CRITICAL FOR AI WORKFLOW:`);\n instructions.push(` ⚡ Use check_reference tool to analyze reference.png before development`);\n instructions.push(` 📂 Pass the assets folder path to check_reference tool`);\n instructions.push(` 🎯 This provides design understanding and framework-specific guidance`);\n instructions.push(` ✅ STEP 4 COMPLETE - Assets downloaded, proceed to STEP 5: check_reference`);\n instructions.push(``);\n instructions.push(`🛠️ Universal IDE Development Workflow:`);\n instructions.push(` 1. Assets are saved using relative paths (./assets/...) for cross-IDE compatibility`);\n instructions.push(` 2. reference.png shows the complete design context and layout`);\n instructions.push(` 3. Use individual asset files for implementation`);\n instructions.push(` 4. All paths are verified after download to ensure availability`);\n instructions.push(` 5. Files work consistently across Cursor, Windsurf, TRAE, and other IDEs`);\n\n return instructions;\n }\n\n\n\n\n\n private setupErrorHandling(): void {\n this.server.onerror = (error) => {\n this.logError('[Figma MCP] Server error:', error);\n };\n\n process.on('SIGINT', async () => {\n this.logError('\\n[Figma MCP] Shutting down server...');\n await this.server.close();\n process.exit(0);\n });\n }\n\n async start(): Promise<void> {\n const transport = new StdioServerTransport();\n await this.server.connect(transport);\n \n this.log('[Figma MCP] Debug mode enabled');\n this.logError('[Figma MCP] Server started successfully');\n }\n}\n\n// CLI setup\nconst program = new Command();\n\nprogram\n .name('figma-mcp-pro')\n .description('Professional Figma MCP Server with enhanced AI context processing')\n .version(VERSION)\n .requiredOption('--figma-api-key <key>', 'Figma API key', process.env.FIGMA_API_KEY)\n .option('--port <port>', 'Server port', process.env.PORT)\n .option('--debug', 'Enable debug mode', process.env.DEBUG === 'true')\n .option('--stdio', 'Use stdio transport (default)', true)\n .action(async (options) => {\n if (!options.figmaApiKey) {\n console.error('Error: Figma API key is required');\n console.error('Set FIGMA_API_KEY environment variable or use --figma-api-key option');\n process.exit(1);\n }\n\n try {\n const server = new CustomFigmaMcpServer({\n figmaApiKey: options.figmaApiKey,\n port: options.port ? parseInt(options.port) : undefined,\n debug: options.debug\n });\n\n await server.start();\n } catch (error) {\n console.error('Failed to start server:', error);\n process.exit(1);\n }\n });\n\n// Handle unhandled rejections\nprocess.on('unhandledRejection', (reason: any, promise: Promise<any>) => {\n console.error('Unhandled Rejection at:', promise, 'reason:', reason);\n process.exit(1);\n});\n\nprocess.on('uncaughtException', (error: Error) => {\n console.error('Uncaught Exception:', error);\n process.exit(1);\n});\n\n// Start the CLI\nprogram.parse();","import { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\n\n// Get the directory of the current module\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n// Read version from package.json as the single source of truth\nfunction getVersion(): string {\n try {\n const packageJsonPath = join(__dirname, '..', 'package.json');\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8'));\n return packageJson.version;\n } catch (error) {\n console.error('Error reading version from package.json:', error);\n return '0.0.0'; // Fallback version\n }\n}\n\nexport const VERSION = getVersion(); ","import axios, { AxiosInstance, AxiosResponse } from 'axios';\nimport NodeCache from 'node-cache';\nimport pRetry from 'p-retry';\nimport pLimit from 'p-limit';\nimport fs from 'fs/promises';\nimport * as fsSync from 'fs';\nimport path from 'path';\nimport os from 'os';\nimport {\n FigmaFileResponse,\n FigmaNodeResponse,\n FigmaImageResponse,\n FigmaError,\n FigmaNode,\n FigmaExportSetting,\n FigmaCommentsResponse\n} from '../types/figma.js';\n\nexport interface FigmaApiConfig {\n apiKey: string;\n baseUrl?: string;\n timeout?: number;\n retryAttempts?: number;\n retryDelay?: number;\n cacheConfig?: {\n ttl: number;\n maxSize: number;\n };\n rateLimitConfig?: {\n requestsPerMinute: number;\n burstSize: number;\n };\n}\n\nexport interface FigmaApiOptions {\n version?: string;\n ids?: string[];\n depth?: number;\n geometry?: 'paths' | 'vector';\n plugin_data?: string;\n branch_data?: boolean;\n use_absolute_bounds?: boolean;\n}\n\nexport class FigmaApiError extends Error {\n constructor(\n message: string,\n public status?: number,\n public code?: string,\n public details?: any\n ) {\n super(message);\n this.name = 'FigmaApiError';\n }\n}\n\nexport class FigmaApiService {\n private client: AxiosInstance;\n private cache: NodeCache;\n private rateLimiter: ReturnType<typeof pLimit>;\n private config: Required<FigmaApiConfig>;\n\n constructor(config: FigmaApiConfig) {\n this.config = {\n baseUrl: 'https://api.figma.com/v1',\n timeout: 30000,\n retryAttempts: 3,\n retryDelay: 1000,\n cacheConfig: {\n ttl: 300, // 5 minutes\n maxSize: 1000\n },\n rateLimitConfig: {\n requestsPerMinute: 60,\n burstSize: 10\n },\n ...config\n };\n\n this.client = axios.create({\n baseURL: this.config.baseUrl,\n timeout: this.config.timeout,\n headers: {\n 'X-Figma-Token': this.config.apiKey,\n 'Content-Type': 'application/json',\n 'User-Agent': 'Custom-Figma-MCP-Server/1.0.0'\n }\n });\n\n this.cache = new NodeCache({\n stdTTL: this.config.cacheConfig.ttl,\n maxKeys: this.config.cacheConfig.maxSize,\n useClones: false\n });\n\n // Rate limiter: allow burst of requests, then throttle\n this.rateLimiter = pLimit(this.config.rateLimitConfig.burstSize);\n\n this.setupInterceptors();\n }\n\n private setupInterceptors(): void {\n // Request interceptor for logging and rate limiting\n this.client.interceptors.request.use(\n (config) => {\n console.error(`[Figma API] ${config.method?.toUpperCase()} ${config.url}`);\n return config;\n },\n (error) => {\n console.error('[Figma API] Request error:', error);\n return Promise.reject(error);\n }\n );\n\n // Response interceptor for error handling\n this.client.interceptors.response.use(\n (response) => {\n console.error(`[Figma API] Response ${response.status} for ${response.config.url}`);\n return response;\n },\n (error) => {\n if (error.response) {\n const { status, data } = error.response;\n const figmaError = data as FigmaError;\n \n throw new FigmaApiError(\n figmaError.err || `HTTP ${status} error`,\n status,\n figmaError.err,\n data\n );\n } else if (error.request) {\n throw new FigmaApiError(\n 'Network error: No response received',\n 0,\n 'NETWORK_ERROR',\n error.request\n );\n } else {\n throw new FigmaApiError(\n `Request setup error: ${error.message}`,\n 0,\n 'REQUEST_ERROR',\n error\n );\n }\n }\n );\n }\n\n private async makeRequest<T>(\n endpoint: string,\n options: FigmaApiOptions = {},\n useCache = true\n ): Promise<T> {\n const cacheKey = `${endpoint}:${JSON.stringify(options)}`;\n \n // Check cache first\n if (useCache) {\n const cached = this.cache.get<T>(cacheKey);\n if (cached) {\n console.error(`[Figma API] Cache hit for ${endpoint}`);\n return cached;\n }\n }\n\n // Rate limit the request\n return this.rateLimiter(async () => {\n const response = await pRetry(\n async () => {\n const response: AxiosResponse<T> = await this.client.get(endpoint, {\n params: this.buildParams(options)\n });\n return response;\n },\n {\n retries: this.config.retryAttempts,\n minTimeout: this.config.retryDelay,\n factor: 2,\n onFailedAttempt: (error) => {\n console.warn(\n `[Figma API] Attempt ${error.attemptNumber} failed for ${endpoint}. ${error.retriesLeft} retries left.`\n );\n }\n }\n );\n\n const data = response.data;\n \n // Cache successful responses\n if (useCache) {\n this.cache.set(cacheKey, data);\n }\n\n return data;\n });\n }\n\n private buildParams(options: FigmaApiOptions): Record<string, string> {\n const params: Record<string, string> = {};\n\n if (options.version) params.version = options.version;\n if (options.ids) params.ids = options.ids.join(',');\n if (options.depth !== undefined) params.depth = options.depth.toString();\n if (options.geometry) params.geometry = options.geometry;\n if (options.plugin_data) params.plugin_data = options.plugin_data;\n if (options.branch_data) params.branch_data = 'true';\n if (options.use_absolute_bounds) params.use_absolute_bounds = 'true';\n\n return params;\n }\n\n /**\n * Get a Figma file by its key\n */\n async getFile(fileKey: string, options: FigmaApiOptions = {}): Promise<FigmaFileResponse> {\n if (!fileKey || typeof fileKey !== 'string') {\n throw new FigmaApiError('File key is required and must be a string');\n }\n\n try {\n return await this.makeRequest<FigmaFileResponse>(`/files/${fileKey}`, options);\n } catch (error) {\n if (error instanceof FigmaApiError) {\n throw error;\n }\n throw new FigmaApiError(`Failed to get file ${fileKey}: ${error}`);\n }\n }\n\n /**\n * Get specific nodes from a Figma file\n */\n async getFileNodes(\n fileKey: string,\n nodeIds: string[],\n options: FigmaApiOptions = {}\n ): Promise<FigmaNodeResponse> {\n if (!fileKey || typeof fileKey !== 'string') {\n throw new FigmaApiError('File key is required and must be a string');\n }\n\n if (!nodeIds || !Array.isArray(nodeIds) || nodeIds.length === 0) {\n throw new FigmaApiError('Node IDs are required and must be a non-empty array');\n }\n\n try {\n return await this.makeRequest<FigmaNodeResponse>(\n `/files/${fileKey}/nodes`,\n { ...options, ids: nodeIds }\n );\n } catch (error) {\n if (error instanceof FigmaApiError) {\n throw error;\n }\n throw new FigmaApiError(`Failed to get nodes from file ${fileKey}: ${error}`);\n }\n }\n\n /**\n * Get images for specific nodes\n */\n async getImages(\n fileKey: string,\n nodeIds: string[],\n options: {\n scale?: number;\n format?: 'jpg' | 'png' | 'svg' | 'pdf';\n svg_include_id?: boolean;\n svg_simplify_stroke?: boolean;\n use_absolute_bounds?: boolean;\n version?: string;\n } = {}\n ): Promise<FigmaImageResponse> {\n if (!fileKey || typeof fileKey !== 'string') {\n throw new FigmaApiError('File key is required and must be a string');\n }\n\n if (!nodeIds || !Array.isArray(nodeIds) || nodeIds.length === 0) {\n throw new FigmaApiError('Node IDs are required and must be a non-empty array');\n }\n\n try {\n const params: Record<string, string> = {\n ids: nodeIds.join(','),\n format: options.format || 'png'\n };\n\n if (options.scale) params.scale = options.scale.toString();\n if (options.svg_include_id) params.svg_include_id = 'true';\n if (options.svg_simplify_stroke) params.svg_simplify_stroke = 'true';\n if (options.use_absolute_bounds) params.use_absolute_bounds = 'true';\n if (options.version) params.version = options.version;\n\n const response: AxiosResponse<FigmaImageResponse> = await this.client.get(\n `/images/${fileKey}`,\n { params }\n );\n\n return response.data;\n } catch (error) {\n if (error instanceof FigmaApiError) {\n throw error;\n }\n throw new FigmaApiError(`Failed to get images from file ${fileKey}: ${error}`);\n }\n }\n\n\n\n\n\n\n\n\n\n /**\n * Get cache statistics\n */\n getCacheStats(): {\n keys: number;\n hits: number;\n misses: number;\n size: number;\n } {\n const stats = this.cache.getStats();\n return {\n keys: stats.keys,\n hits: stats.hits,\n misses: stats.misses,\n size: stats.ksize + stats.vsize\n };\n }\n\n /**\n * Clear cache\n */\n clearCache(): void {\n this.cache.flushAll();\n console.error('[Figma API] Cache cleared');\n }\n\n /**\n * Update API key\n */\n updateApiKey(apiKey: string): void {\n if (!apiKey || typeof apiKey !== 'string') {\n throw new FigmaApiError('API key is required and must be a string');\n }\n\n this.config.apiKey = apiKey;\n this.client.defaults.headers['X-Figma-Token'] = apiKey;\n console.error('[Figma API] API key updated');\n }\n\n\n\n\n\n /**\n * Robust IDE-aware path resolution for universal compatibility\n */\n private static resolvePath(inputPath: string): string {\n // Normalize input path - remove encoding issues\n const normalizedPath = inputPath.trim().replace(/[^\\x20-\\x7E]/g, '');\n \n console.error(`[Figma API] Input path: \"${inputPath}\" -> normalized: \"${normalizedPath}\"`);\n \n // Handle absolute paths - if it's already absolute and valid, use as-is (but validate safety)\n if (path.isAbsolute(normalizedPath) && !this.isSystemRoot(normalizedPath) && normalizedPath.length > 1) {\n // Still validate it's not a dangerous system path using cross-platform logic\n if (!this.isDangerousPath(normalizedPath)) {\n console.error(`[Figma API] Using safe absolute path: ${normalizedPath}`);\n return normalizedPath;\n } else {\n console.error(`[Figma API] ⚠️ Absolute path is dangerous, switching to relative: ${normalizedPath}`);\n // Fall through to relative path handling\n }\n }\n \n // ENHANCED CURSOR IDE FIX: Use comprehensive workspace detection\n const workspaceInfo = this.getActualWorkspaceDirectory();\n \n console.error(`[Figma API] Using workspace directory: ${workspaceInfo.workspaceDir} (${workspaceInfo.confidence} confidence from ${workspaceInfo.source})`);\n \n // CRITICAL CURSOR BUG PREVENTION: If workspace directory is still dangerous, force safe fallback\n if (this.isDangerousPath(workspaceInfo.workspaceDir) || this.isSystemRoot(workspaceInfo.workspaceDir)) {\n console.error(`[Figma API] 🚨 CRITICAL: Workspace directory is dangerous/root: ${workspaceInfo.workspaceDir}`);\n const userHome = os.homedir();\n const safeFallbackWorkspace = path.join(userHome, 'figma-mcp-workspace');\n console.error(`[Figma API] 🛡️ Using bulletproof safe workspace: ${safeFallbackWorkspace}`);\n \n // Override workspace info with safe fallback\n workspaceInfo.workspaceDir = safeFallbackWorkspace;\n workspaceInfo.confidence = 'low';\n workspaceInfo.source = 'Emergency Safe Fallback';\n }\n \n // Clean the path for consistent relative path handling\n let cleanPath = normalizedPath;\n \n // Handle various relative path formats consistently\n if (cleanPath.startsWith('./')) {\n cleanPath = cleanPath.substring(2); // Remove './'\n } else if (cleanPath.startsWith('../')) {\n // Handle parent directory references\n cleanPath = cleanPath; // Keep as-is, path.resolve will handle it\n } else if (cleanPath.startsWith('/')) {\n // Remove leading slash to make it relative\n cleanPath = cleanPath.substring(1);\n }\n \n // Ensure we have a valid path\n if (!cleanPath || cleanPath === '.' || cleanPath === '') {\n cleanPath = 'figma-assets'; // Default directory name\n }\n \n // Use path.resolve with workspace directory as base for consistent cross-platform path resolution\n const resolvedPath = path.resolve(workspaceInfo.workspaceDir, cleanPath);\n \n // FINAL BULLETPROOF SAFETY CHECK - Absolutely prevent any dangerous path resolution\n if (this.isDangerousPath(resolvedPath) || this.isSystemRoot(path.dirname(resolvedPath))) {\n console.error(`[Figma API] 🚨 EMERGENCY BLOCK: Resolved path is still dangerous: ${resolvedPath}`);\n console.error(`[Figma API] 🚨 This indicates a severe Cursor IDE workspace detection failure`);\n \n // Force ultra-safe fallback that cannot possibly be system root\n const userHome = os.homedir();\n const emergencyPath = path.resolve(userHome, 'figma-emergency-downloads', cleanPath);\n console.error(`[Figma API] 🛡️ Using emergency safe path: ${emergencyPath}`);\n \n // Triple-check the emergency path is safe (this should never fail)\n if (this.isDangerousPath(emergencyPath)) {\n console.error(`[Figma API] 💥 CRITICAL SYSTEM ERROR: Even emergency path is dangerous!`);\n throw new FigmaApiError(`System error: Cannot create safe download path. Emergency path ${emergencyPath} is dangerous. Please check your system configuration.`);\n }\n \n return emergencyPath;\n }\n \n console.error(`[Figma API] ✅ Path resolution: \"${normalizedPath}\" -> \"${resolvedPath}\"`);\n console.error(`[Figma API] Environment: workspace=\"${workspaceInfo.workspaceDir}\", PWD=\"${process.env.PWD}\", resolved=\"${resolvedPath}\"`);\n \n return resolvedPath;\n }\n\n\n\n /**\n * Enhanced project directory detection by looking for common project markers\n * Specifically optimized for Cursor IDE environment\n */\n private static findProjectDirectoryByMarkers(): string[] {\n const candidates: string[] = [];\n \n // Enhanced project markers with scoring for better detection\n const projectMarkers = [\n { file: 'package.json', score: 10 },\n { file: '.git', score: 8 },\n { file: 'tsconfig.json', score: 7 },\n { file: 'yarn.lock', score: 6 },\n { file: 'package-lock.json', score: 6 },\n { file: 'pnpm-lock.yaml', score: 6 },\n { file: 'node_modules', score: 5 },\n { file: 'src', score: 4 },\n { file: 'dist', score: 3 },\n { file: 'README.md', score: 2 },\n { file: '.gitignore', score: 3 },\n { file: 'index.js', score: 2 },\n { file: 'index.ts', score: 2 }\n ];\n \n // Multiple starting points for comprehensive search\n const startingPoints: string[] = [];\n \n // Add environment-based starting points\n if (process.env.PWD && !this.isSystemRoot(process.env.PWD)) {\n startingPoints.push(process.env.PWD);\n }\n if (process.env.INIT_CWD && !this.isSystemRoot(process.env.INIT_CWD)) {\n startingPoints.push(process.env.INIT_CWD);\n }\n \n // Add process.cwd() if it's not system root\n if (!this.isSystemRoot(process.cwd())) {\n startingPoints.push(process.cwd());\n }\n \n // Fallback to user directories\n const userDirs = [\n path.join(os.homedir(), 'Desktop'),\n path.join(os.homedir(), 'Documents'),\n path.join(os.homedir(), 'Projects'),\n path.join(os.homedir(), 'Development'),\n path.join(os.homedir(), 'Code'),\n os.homedir()\n ];\n startingPoints.push(...userDirs);\n \n // Remove duplicates\n const uniqueStartingPoints = [...new Set(startingPoints)];\n \n console.error(`[Figma API] 🔍 Project marker search starting from ${uniqueStartingPoints.length} locations`);\n \n for (const startDir of uniqueStartingPoints) {\n try {\n console.error(`[Figma API] 🔍 Searching from: ${startDir}`);\n \n // Search upward for project markers\n let currentDir = startDir;\n const maxLevels = 8; // Prevent infinite loops\n \n for (let level = 0; level < maxLevels; level++) {\n let totalScore = 0;\n \n for (const marker of projectMarkers) {\n const markerPath = path.join(currentDir, marker.file);\n try {\n fsSync.accessSync(markerPath);\n totalScore += marker.score;\n \n // Special handling for key markers\n if (marker.file === 'package.json') {\n try {\n const packageContent = fsSync.readFileSync(markerPath, 'utf8');\n const packageJson = JSON.parse(packageContent);\n if (packageJson.name && !packageJson.name.startsWith('figma-mcp-workspace')) {\n totalScore += 5; // Bonus for real projects\n }\n } catch {\n // Invalid package.json, but still counts\n }\n }\n } catch {\n // Marker not found\n }\n }\n \n // If we found enough markers, consider this a project directory\n if (totalScore >= 10 && !candidates.includes(currentDir)) {\n candidates.push(currentDir);\n console.error(`[Figma API] ✅ Project found with score ${totalScore}: ${currentDir}`);\n }\n \n const parentDir = path.dirname(currentDir);\n if (parentDir === currentDir) break; // Reached root\n currentDir = parentDir;\n }\n \n // Also search one level down in the starting directory\n if (startDir !== os.homedir()) { // Don't search all of home directory\n try {\n const entries = fsSync.readdirSync(startDir, { withFileTypes: true });\n for (const entry of entries.slice(0, 20)) { // Limit to first 20 entries\n if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules') {\n const subDir = path.join(startDir, entry.name);\n \n let totalScore = 0;\n for (const marker of projectMarkers) {\n const markerPath = path.join(subDir, marker.file);\n try {\n fsSync.accessSync(markerPath);\n totalScore += marker.score;\n } catch {\n // Marker not found\n }\n }\n \n if (totalScore >= 10 && !candidates.includes(subDir)) {\n candidates.push(subDir);\n console.error(`[Figma API] ✅ Project found (subdirectory) with score ${totalScore}: ${subDir}`);\n }\n }\n }\n } catch {\n // Directory not readable\n }\n }\n } catch (error) {\n console.error(`[Figma API] ⚠️ Error searching from ${startDir}:`, error);\n }\n }\n \n console.error(`[Figma API] 📊 Project marker search found ${candidates.length} candidates`);\n return candidates;\n }\n\n /**\n * Check if a directory looks like a valid project directory\n */\n private static isValidProjectDirectory(dir: string): boolean {\n const projectIndicators = [\n 'package.json',\n 'tsconfig.json',\n '.git',\n 'src',\n 'node_modules'\n ];\n \n let indicatorCount = 0;\n for (const indicator of projectIndicators) {\n try {\n fsSync.accessSync(path.join(dir, indicator));\n indicatorCount++;\n } catch {\n // Indicator not found\n }\n }\n \n // Consider it a project directory if it has at least 2 indicators\n return indicatorCount >= 2;\n }\n\n /**\n * Create directory with enhanced verification and universal IDE compatibility\n */\n private static async createDirectorySafely(resolvedPath: string, originalPath: string): Promise<void> {\n // Validate the resolved path\n if (!resolvedPath || resolvedPath.length === 0) {\n throw new Error('Invalid or empty path after resolution');\n }\n \n // Enhanced safety check: prevent creating directories at dangerous locations (cross-platform)\n if (this.isDangerousPath(resolvedPath)) {\n console.error(`[Figma API] SAFETY BLOCK: Refusing to create directory at dangerous location: ${resolvedPath}`);\n throw new FigmaApiError(`Blocked dangerous directory creation at: ${resolvedPath}. Original path: ${originalPath}`);\n }\n \n console.error(`[Figma API] Creating directory: \"${originalPath}\" -> \"${resolvedPath}\"`);\n \n try {\n // Create directory with full permissions for universal compatibility\n await fs.mkdir(resolvedPath, { recursive: true, mode: 0o755 });\n \n // Verify directory was created and is accessible\n const stats = await fs.stat(resolvedPath);\n if (!stats.isDirectory()) {\n throw new Error('Path exists but is not a directory');\n }\n \n // Test write permissions by creating a temporary file\n const testFile = path.join(resolvedPath, '.figma-test-write');\n try {\n await fs.writeFile(testFile, 'test');\n await fs.unlink(testFile); // Clean up test file\n } catch (writeError) {\n throw new Error(`Directory exists but is not writable: ${writeError instanceof Error ? writeError.message : String(writeError)}`);\n }\n \n console.error(`[Figma API] ✅ Directory verified: ${resolvedPath}`);\n \n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n console.error(`[Figma API] ❌ Directory creation failed:`, { \n originalPath, \n resolvedPath,\n cwd: process.cwd(),\n environment: {\n PWD: process.env.PWD,\n INIT_CWD: process.env.INIT_CWD,\n PROJECT_ROOT: process.env.PROJECT_ROOT,\n WORKSPACE_ROOT: process.env.WORKSPACE_ROOT\n },\n error: errorMessage \n });\n throw new FigmaApiError(`Failed to create/verify directory: ${errorMessage}`);\n }\n }\n\n /**\n * Verify that assets exist in the expected location (universal IDE compatibility)\n */\n private static async verifyAssetsLocation(expectedPaths: string[]): Promise<{\n verified: Array<{ path: string; exists: boolean; size?: number; relativePath?: string }>;\n summary: { total: number; found: number; missing: number };\n }> {\n const verified: Array<{ path: string; exists: boolean; size?: number; relativePath?: string }> = [];\n \n for (const expectedPath of expectedPaths) {\n try {\n const stat = await fs.stat(expectedPath);\n const relativePath = path.relative(process.cwd(), expectedPath);\n verified.push({\n path: expectedPath,\n exists: true,\n size: stat.size,\n relativePath: relativePath.startsWith('..') ? expectedPath : relativePath\n });\n } catch (error) {\n verified.push({\n path: expectedPath,\n exists: false\n });\n }\n }\n \n const summary = {\n total: verified.length,\n found: verified.filter(v => v.exists).length,\n missing: verified.filter(v => !v.exists).length\n };\n \n return { verified, summary };\n }\n\n /**\n * Advanced asset recovery system for IDE compatibility issues\n * Searches common alternative download locations and recovers assets to project folder\n */\n private static async findAndRecoverMissingAssets(\n expectedResults: Array<{ nodeId: string; nodeName: string; filePath: string; success: boolean }>,\n targetDirectory: string\n ): Promise<{\n recovered: Array<{ nodeId: string; nodeName: string; oldPath: string; newPath: string; success: boolean }>;\n summary: { total: number; found: number; recovered: number; failed: number };\n }> {\n const recovered: Array<{ nodeId: string; nodeName: string; oldPath: string; newPath: string; success: boolean }> = [];\n const missingAssets = expectedResults.filter(r => r.success); // Only check supposedly successful downloads\n \n console.error(`[Figma API] 🔍 Searching for ${missingAssets.length} potentially misplaced assets...`);\n \n // Common alternative locations where files might have been downloaded (cross-platform)\n const searchLocations = this.getAssetSearchLocations();\n \n // Remove duplicates and ensure target directory isn't in search list\n const uniqueSearchLocations = [...new Set(searchLocations)].filter(loc => loc !== targetDirectory);\n \n // Also search recursively in some key directories\n const recursiveSearchDirs = [\n path.join(os.homedir(), 'figma-workspace'),\n os.homedir()\n ];\n \n for (const asset of missingAssets) {\n const expectedPath = asset.filePath;\n const filename = path.basename(expectedPath);\n \n // First verify it's actually missing from expected location\n try {\n await fs.access(expectedPath);\n // File exists where expected, no recovery needed\n continue;\n } catch {\n // File is missing, proceed with search\n }\n \n console.error(`[Figma API] 🔍 Searching for missing file: ${filename}`);\n \n let foundPath: string | null = null;\n \n // First, search direct locations\n for (const searchLoc of uniqueSearchLocations) {\n try {\n const candidatePath = path.join(searchLoc, filename);\n await fs.access(candidatePath);\n \n // Found the file! Verify it's a reasonable size (not empty)\n const stat = await fs.stat(candidatePath);\n if (stat.size > 0) {\n foundPath = candidatePath;\n console.error(`[Figma API] ✅ Found ${filename} at: ${candidatePath} (${(stat.size / 1024).toFixed(1)}KB)`);\n break;\n }\n } catch {\n // File not found in this location, continue searching\n }\n }\n \n // If not found in direct locations, search recursively in key directories\n if (!foundPath) {\n foundPath = await this.searchFileRecursively(filename, recursiveSearchDirs);\n }\n \n if (foundPath) {\n // Attempt to move the file to the correct location\n try {\n // Ensure target directory exists\n await FigmaApiService.createDirectorySafely(targetDirectory, targetDirectory);\n \n // Move the file\n await fs.rename(foundPath, expectedPath);\n \n recovered.push({\n nodeId: asset.nodeId,\n nodeName: asset.nodeName,\n oldPath: foundPath,\n newPath: expectedPath,\n success: true\n });\n \n console.error(`[Figma API] ✅ Recovered ${filename}: ${foundPath} → ${expectedPath}`);\n \n } catch (moveError) {\n // If move fails, try copy and delete\n try {\n await fs.copyFile(foundPath, expectedPath);\n await fs.unlink(foundPath);\n \n recovered.push({\n nodeId: asset.nodeId,\n nodeName: asset.nodeName,\n oldPath: foundPath,\n newPath: expectedPath,\n success: true\n });\n \n console.error(`[Figma API] ✅ Recovered ${filename} via copy: ${foundPath} → ${expectedPath}`);\n \n } catch (copyError) {\n recovered.push({\n nodeId: asset.nodeId,\n nodeName: asset.nodeName,\n oldPath: foundPath,\n newPath: expectedPath,\n success: false\n });\n \n console.error(`[Figma API] ❌ Failed to recover ${filename}:`, copyError);\n }\n }\n } else {\n console.error(`[Figma API] ❌ Could not locate missing file: ${filename}`);\n }\n }\n \n const summary = {\n total: missingAssets.length,\n found: recovered.length,\n recovered: recovered.filter(r => r.success).length,\n failed: recovered.filter(r => !r.success).length\n };\n \n if (summary.recovered > 0) {\n console.error(`[Figma API] 🎉 Recovery completed: ${summary.recovered}/${summary.total} assets recovered to project folder`);\n } else if (summary.total > 0) {\n console.error(`[Figma API] ⚠️ No assets recovered - files may have been downloaded to an unknown location`);\n }\n \n return { recovered, summary };\n }\n\n /**\n * Search for a file recursively in given directories (limited depth)\n */\n private static async searchFileRecursively(filename: string, searchDirs: string[], maxDepth: number = 3): Promise<string | null> {\n for (const searchDir of searchDirs) {\n try {\n const found = await this.searchInDirectory(searchDir, filename, maxDepth);\n if (found) {\n return found;\n }\n } catch (error) {\n console.error(`[Figma API] Error searching in ${searchDir}:`, error);\n }\n }\n return null;\n }\n\n /**\n * Search for a file in a specific directory with depth limit\n */\n private static async searchInDirectory(dir: string, filename: string, maxDepth: number, currentDepth: number = 0): Promise<string | null> {\n if (currentDepth >= maxDepth) {\n return null;\n }\n \n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n \n // First, check if the file is directly in this directory\n for (const entry of entries) {\n if (entry.isFile() && entry.name === filename) {\n const filePath = path.join(dir, entry.name);\n const stat = await fs.stat(filePath);\n if (stat.size > 0) {\n return filePath;\n }\n }\n }\n \n // Then, search subdirectories\n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules') {\n const subDir = path.join(dir, entry.name);\n const found = await this.searchInDirectory(subDir, filename, maxDepth, currentDepth + 1);\n if (found) {\n return found;\n }\n }\n }\n } catch (error) {\n // Directory not accessible, skip\n }\n \n return null;\n }\n\n /**\n * Download images for specific nodes directly (without requiring export settings)\n */\n async downloadImages(\n fileKey: string,\n nodeIds: string[],\n localPath: string,\n options: {\n scale?: number;\n format?: 'jpg' | 'png' | 'svg' | 'pdf';\n skipWorkspaceEnforcement?: boolean;\n } = {}\n ): Promise<{\n downloaded: Array<{\n nodeId: string;\n nodeName: string;\n filePath: string;\n success: boolean;\n error?: string;\n }>;\n summary: {\n total: number;\n successful: number;\n failed: number;\n };\n workspaceEnforcement?: {\n finalLocation: string;\n moved: number;\n workspaceSource: string;\n confidence: 'high' | 'medium' | 'low';\n } | null;\n }> {\n // Resolve and ensure local directory exists\n const resolvedPath = FigmaApiService.resolvePath(localPath);\n await FigmaApiService.createDirectorySafely(resolvedPath, localPath);\n\n const results: Array<{\n nodeId: string;\n nodeName: string;\n filePath: string;\n success: boolean;\n error?: string;\n }> = [];\n\n // INTELLIGENT ASSET DEDUPLICATION: Handle both filename and content duplicates\n const usedFilenames = new Set<string>();\n const filenameCounters = new Map<string, number>();\n const contentHashes = new Map<string, { filename: string; nodeId: string; nodeName: string }>();\n\n // Pre-populate with existing files in target directory\n try {\n const existingFiles = await fs.readdir(resolvedPath);\n existingFiles.forEach(file => {\n usedFilenames.add(file);\n console.error(`[Figma API] 📁 Existing file detected: ${file}`);\n });\n } catch (error) {\n // Directory doesn't exist yet or can't read it - that's fine\n console.error(`[Figma API] 📁 Target directory empty or doesn't exist yet`);\n }\n\n /**\n * Generate content hash for asset deduplication (simplified for downloadImages)\n */\n const generateContentHash = (node: FigmaNode, format: string, scale: number): string => {\n const hashComponents = [\n node.type,\n format,\n scale.toString(),\n JSON.stringify(node.fills || []),\n JSON.stringify(node.strokes || []),\n JSON.stringify(node.effects || []),\n node.cornerRadius || 0,\n node.strokeWeight || 0,\n node.type === 'TEXT' ? node.characters || '' : '',\n node.absoluteBoundingBox ? `${Math.round(node.absoluteBoundingBox.width)}x${Math.round(node.absoluteBoundingBox.height)}` : ''\n ];\n \n return hashComponents.join('|').replace(/[^a-zA-Z0-9]/g, '').substring(0, 16);\n };\n\n /**\n * Check if asset should be treated as reusable (icons, logos, etc.)\n */\n const isReusableAsset = (node: FigmaNode, sanitizedName: string): boolean => {\n const name = sanitizedName.toLowerCase();\n \n // Check for common icon naming patterns\n const iconPatterns = [\n 'akar-icons-',\n 'dashicons-',\n 'ci-',\n 'uis-',\n 'mdi-',\n 'ant-design-',\n 'feather-',\n 'heroicons-',\n 'lucide-',\n 'tabler-',\n 'phosphor-',\n 'icon-',\n 'ico-'\n ];\n \n const isIcon = iconPatterns.some(pattern => name.includes(pattern));\n \n // Also check for small size (typical for icons)\n const size = node.absoluteBoundingBox;\n const isSmallSize = size ? (size.width <= 100 && size.height <= 100) : false;\n \n // Check if it's an SVG type node (vector graphics)\n const isVectorType = node.type === 'VECTOR' || node.type === 'BOOLEAN_OPERATION' || node.type === 'COMPONENT';\n \n // Consider it reusable if it matches icon patterns OR is a small vector graphic\n const shouldDeduplicate = isIcon || (isSmallSize && isVectorType);\n \n if (shouldDeduplicate) {\n console.error(`[Figma API] 🔗 Detected reusable asset: \"${name}\" (icon: ${isIcon}, small: ${isSmallSize}, vector: ${isVectorType})`);\n }\n \n return shouldDeduplicate;\n };\n\n /**\n * Enhanced filename generation with content-based deduplication\n */\n const generateUniqueFilename = (node: FigmaNode, baseName: string, extension: string, format: string, scale: number): string => {\n // Always add scale to filename for consistency with export settings\n const baseNameWithScale = scale === 1 ? `${baseName}-x1` : `${baseName}-x${scale}`;\n const baseFilename = `${baseNameWithScale}.${extension}`;\n \n // Check if this is a reusable asset type\n if (isReusableAsset(node, baseName)) {\n // Generate content hash for deduplication\n const contentHash = generateContentHash(node, format, scale);\n \n // Check if we already have an asset with identical content\n if (contentHashes.has(contentHash)) {\n const existingAsset = contentHashes.get(contentHash)!;\n console.error(`[Figma API] 🔗 Content duplicate detected: \"${baseName}\" → reusing \"${existingAsset.filename}\" (same as ${existingAsset.nodeName})`);\n return existingAsset.filename;\n }\n \n // New unique content - register it for future deduplication\n contentHashes.set(contentHash, { filename: baseFilename, nodeId: node.id, nodeName: baseName });\n }\n \n // Standard filename uniqueness check\n if (!usedFilenames.has(baseFilename)) {\n usedFilenames.add(baseFilename);\n return baseFilename;\n }\n \n // Generate incremental filename for true duplicates\n const counter = filenameCounters.get(baseNameWithScale) || 1;\n let uniqueFilename: string;\n let currentCounter = counter + 1;\n \n do {\n uniqueFilename = `${baseNameWithScale}-${currentCounter}.${extension}`;\n currentCounter++;\n } while (usedFilenames.has(uniqueFilename));\n \n // Update counter and mark as used\n filenameCounters.set(baseNameWithScale, currentCounter - 1);\n usedFilenames.add(uniqueFilename);\n \n console.error(`[Figma API] 🔄 Filename duplicate resolved: \"${baseFilename}\" → \"${uniqueFilename}\"`);\n return uniqueFilename;\n };\n\n try {\n // First, get the nodes to get their names\n const nodeResponse = await this.getFileNodes(fileKey, nodeIds, {\n depth: 1,\n use_absolute_bounds: true\n });\n\n // Get image URLs for all nodes\n const format = (options.format || 'png').toLowerCase();\n let scale = options.scale || 1;\n \n // SVG only supports 1x scale according to Figma documentation\n if (format === 'svg') {\n scale = 1;\n }\n \n const imageResponse = await this.getImages(fileKey, nodeIds, {\n format: format as 'jpg' | 'png' | 'svg' | 'pdf',\n scale: scale,\n use_absolute_bounds: true\n });\n\n // Download each image\n for (const nodeId of nodeIds) {\n const nodeWrapper = nodeResponse.nodes[nodeId];\n const imageUrl = imageResponse.images[nodeId];\n \n if (!nodeWrapper) {\n results.push({\n nodeId,\n nodeName: 'Unknown',\n filePath: '',\n success: false,\n error: `Node ${nodeId} not found`\n });\n continue;\n }\n\n if (!imageUrl) {\n results.push({\n nodeId,\n nodeName: nodeWrapper.document?.name || 'Unknown',\n filePath: '',\n success: false,\n error: 'No image URL returned from Figma API'\n });\n continue;\n }\n\n // Use the actual node name as filename (preserve original name)\n const nodeName = nodeWrapper.document?.name || `node-${nodeId}`;\n // Sanitize filename to remove/replace problematic characters\n const sanitizedNodeName = nodeName\n .replace(/[/\\\\:*?\"<>|]/g, '-') // Replace problematic characters with dash\n .replace(/\\s+/g, ' ') // Normalize spaces\n .trim();\n const extension = format;\n \n // Generate unique filename to prevent overwrites\n const filename = generateUniqueFilename(nodeWrapper.document!, sanitizedNodeName, extension, format, scale);\n const filePath = path.join(resolvedPath, filename);\n\n // Debug logging to understand the filename issue\n console.error(`[Figma API] Debug - Node ID: ${nodeId}, Node Name: \"${nodeName}\", Filename: \"${filename}\"`);\n\n try {\n // Download the image\n const downloadResponse = await axios.get(imageUrl, {\n responseType: 'arraybuffer',\n timeout: 30000,\n headers: {\n 'User-Agent': 'Custom-Figma-MCP-Server/1.0.0'\n }\n });\n\n // Write to file\n await fs.writeFile(filePath, Buffer.from(downloadResponse.data));\n\n results.push({\n nodeId,\n nodeName: sanitizedNodeName,\n filePath,\n success: true\n });\n\n console.error(`[Figma API] Downloaded: ${filename} (${(downloadResponse.data.byteLength / 1024).toFixed(1)}KB)`);\n\n } catch (downloadError) {\n results.push({\n nodeId,\n nodeName: sanitizedNodeName,\n filePath: filePath,\n success: false,\n error: `Download failed: ${downloadError instanceof Error ? downloadError.message : String(downloadError)}`\n });\n console.error(`[Figma API] Failed to download ${filename}:`, downloadError);\n }\n }\n\n } catch (error) {\n // Mark all as failed if we can't get the basic data\n for (const nodeId of nodeIds) {\n results.push({\n nodeId,\n nodeName: 'Unknown',\n filePath: '',\n success: false,\n error: `Failed to fetch node data: ${error instanceof Error ? error.message : String(error)}`\n });\n }\n }\n\n // Calculate summary\n const summary = {\n total: results.length,\n successful: results.filter(r => r.success).length,\n failed: results.filter(r => !r.success).length\n };\n\n console.error(`[Figma API] Download completed: ${summary.successful}/${summary.total} successful`);\n\n // WORKSPACE ENFORCEMENT: Ensure all assets end up in the actual IDE workspace (can be skipped)\n let workspaceEnforcement = null;\n if (summary.successful > 0 && !options.skipWorkspaceEnforcement) {\n try {\n workspaceEnforcement = await FigmaApiService.enforceWorkspaceLocation(results, localPath);\n console.error(`[Figma API] 🎯 Workspace enforcement: ${workspaceEnforcement.summary.moved} moved, ${workspaceEnforcement.summary.alreadyCorrect} already correct`);\n } catch (enforcementError) {\n console.error(`[Figma API] ⚠️ Workspace enforcement failed, falling back to recovery:`, enforcementError);\n \n // Fallback to original recovery system\n const expectedPaths = results.filter(r => r.success).map(r => r.filePath);\n if (expectedPaths.length > 0) {\n const verification = await FigmaApiService.verifyAssetsLocation(expectedPaths);\n \n if (verification.summary.missing > 0) {\n console.error(`[Figma API] ⚠️ ${verification.summary.missing} assets missing from expected location, attempting recovery...`);\n \n const recovery = await FigmaApiService.findAndRecoverMissingAssets(results, resolvedPath);\n \n if (recovery.summary.recovered > 0) {\n console.error(`[Figma API] 🎉 Successfully recovered ${recovery.summary.recovered} assets to project directory!`);\n \n for (const recoveredAsset of recovery.recovered) {\n const resultIndex = results.findIndex(r => r.nodeId === recoveredAsset.nodeId);\n if (resultIndex !== -1 && recoveredAsset.success && results[resultIndex]) {\n results[resultIndex].filePath = recoveredAsset.newPath;\n results[resultIndex].success = true;\n }\n }\n }\n }\n }\n }\n }\n\n return { \n downloaded: results, \n summary,\n workspaceEnforcement: workspaceEnforcement ? {\n finalLocation: workspaceEnforcement.finalLocation,\n moved: workspaceEnforcement.summary.moved,\n workspaceSource: workspaceEnforcement.workspaceInfo.source,\n confidence: workspaceEnforcement.workspaceInfo.confidence\n } : null\n };\n }\n\n /**\n * Download images to local directory based on export settings\n */\n async downloadImagesWithExportSettings(\n fileKey: string,\n nodes: FigmaNode[],\n localPath: string,\n options: {\n skipWorkspaceEnforcement?: boolean;\n overwriteExisting?: boolean; // New option to control existing file behavior\n } = {}\n ): Promise<{\n downloaded: Array<{\n nodeId: string;\n nodeName: string;\n filePath: string;\n exportSetting: FigmaExportSetting;\n success: boolean;\n error?: string;\n }>;\n summary: {\n total: number;\n successful: number;\n failed: number;\n skipped: number;\n };\n workspaceEnforcement?: {\n finalLocation: string;\n moved: number;\n workspaceSource: string;\n confidence: 'high' | 'medium' | 'low';\n } | null;\n }> {\n // Resolve and ensure local directory exists\n const resolvedPath = FigmaApiService.resolvePath(localPath);\n await FigmaApiService.createDirectorySafely(resolvedPath, localPath);\n\n const results: Array<{\n nodeId: string;\n nodeName: string;\n filePath: string;\n exportSetting: FigmaExportSetting;\n success: boolean;\n error?: string;\n }> = [];\n\n // INTELLIGENT ASSET DEDUPLICATION: Handle both filename and content duplicates\n const usedFilenames = new Set<string>();\n const filenameCounters = new Map<string, number>();\n const contentHashes = new Map<string, { filename: string; nodeId: string; nodeName: string }>();\n\n // Handle existing files based on overwriteExisting option\n const existingFiles = new Set<string>();\n try {\n const files = await fs.readdir(resolvedPath);\n files.forEach(file => existingFiles.add(file));\n \n if (options.overwriteExisting) {\n console.error(`[Figma API] 🔄 Overwrite mode: Will replace ${files.length} existing files if needed`);\n // Don't add existing files to usedFilenames - allow overwrites\n } else {\n // Add existing files to usedFilenames to prevent overwrites (current behavior)\n files.forEach(file => {\n usedFilenames.add(file);\n console.error(`[Figma API] 📁 Existing file detected: ${file} (will increment if duplicate)`);\n });\n }\n } catch (error) {\n // Directory doesn't exist yet or can't read it - that's fine\n console.error(`[Figma API] 📁 Target directory empty or doesn't exist yet`);\n }\n\n /**\n * Generate content hash for asset deduplication\n */\n const generateContentHash = (node: FigmaNode, exportSetting: FigmaExportSetting): string => {\n const hashComponents = [\n node.type,\n // Don't include node.id for icons - we want to deduplicate identical icons regardless of their node ID\n // node.id, // REMOVED - this was preventing icon deduplication\n node.name, // Keep node name for uniqueness\n exportSetting.format,\n exportSetting.constraint?.type || 'none',\n exportSetting.constraint?.value || 1,\n exportSetting.suffix || '',\n JSON.stringify(node.fills || []),\n JSON.stringify(node.strokes || []),\n JSON.stringify(node.effects || []),\n node.cornerRadius || 0,\n node.strokeWeight || 0,\n node.type === 'TEXT' ? node.characters || '' : '',\n node.absoluteBoundingBox ? `${Math.round(node.absoluteBoundingBox.width)}x${Math.round(node.absoluteBoundingBox.height)}` : '',\n // Add more specific properties for better differentiation\n node.blendMode || '',\n node.opacity || 1,\n JSON.stringify(node.strokeDashes || [])\n ];\n \n // Create a more robust hash that focuses on visual content, not node identity\n const hashString = hashComponents.join('|');\n return hashString.replace(/[^a-zA-Z0-9]/g, '').substring(0, 32); // Increased length for better uniqueness\n };\n\n /**\n * Check if asset should be treated as reusable (icons, logos, etc.)\n */\n const isReusableAsset = (node: FigmaNode, sanitizedName: string): boolean => {\n const name = sanitizedName.toLowerCase();\n \n // Check for common icon naming patterns\n const iconPatterns = [\n 'akar-icons-',\n 'dashicons-',\n 'ci-',\n 'uis-',\n 'mdi-',\n 'ant-design-',\n 'feather-',\n 'heroicons-',\n 'lucide-',\n 'tabler-',\n 'phosphor-',\n 'icon-',\n 'ico-'\n ];\n \n const isIcon = iconPatterns.some(pattern => name.includes(pattern));\n \n // Also check for small size (typical for icons)\n const size = node.absoluteBoundingBox;\n const isSmallSize = size ? (size.width <= 100 && size.height <= 100) : false;\n \n // Check if it's an SVG type node (vector graphics)\n const isVectorType = node.type === 'VECTOR' || node.type === 'BOOLEAN_OPERATION' || node.type === 'COMPONENT';\n \n // Consider it reusable if it matches icon patterns OR is a small vector graphic\n const shouldDeduplicate = isIcon || (isSmallSize && isVectorType);\n \n if (shouldDeduplicate) {\n console.error(`[Figma API] 🔗 Detected reusable asset: \"${name}\" (icon: ${isIcon}, small: ${isSmallSize}, vector: ${isVectorType})`);\n }\n \n return shouldDeduplicate;\n };\n\n /**\n * Enhanced filename generation with content-based deduplication\n */\n const generateUniqueFilename = (node: FigmaNode, baseName: string, extension: string, exportSetting: FigmaExportSetting): string => {\n const baseFilename = `${baseName}.${extension}`;\n \n // Check if this is a reusable asset type (icons, etc.)\n if (isReusableAsset(node, baseName)) {\n // Generate content hash for deduplication\n const contentHash = generateContentHash(node, exportSetting);\n \n // Check if we already have an asset with identical content\n if (contentHashes.has(contentHash)) {\n const existingAsset = contentHashes.get(contentHash)!;\n console.error(`[Figma API] 🔗 Content duplicate detected: \"${baseName}\" → reusing \"${existingAsset.filename}\" (same as ${existingAsset.nodeName})`);\n return existingAsset.filename;\n }\n \n // New unique content - register it for future deduplication\n contentHashes.set(contentHash, { filename: baseFilename, nodeId: node.id, nodeName: baseName });\n console.error(`[Figma API] 🆕 New unique icon registered: \"${baseName}\" with hash ${contentHash.substring(0, 8)}...`);\n }\n \n // Standard filename uniqueness check\n if (!usedFilenames.has(baseFilename)) {\n usedFilenames.add(baseFilename);\n return baseFilename;\n }\n \n // Generate incremental filename for true duplicates (different content but same name)\n const counter = filenameCounters.get(baseName) || 0;\n let uniqueFilename: string;\n let currentCounter = counter + 1;\n \n do {\n uniqueFilename = `${baseName}-${currentCounter}.${extension}`;\n currentCounter++;\n } while (usedFilenames.has(uniqueFilename));\n \n // Update counter and mark as used\n filenameCounters.set(baseName, currentCounter - 1);\n usedFilenames.add(uniqueFilename);\n \n console.error(`[Figma API] 🔄 Filename duplicate resolved: \"${baseFilename}\" → \"${uniqueFilename}\"`);\n return uniqueFilename;\n };\n\n // Find all nodes with export settings\n const nodesToExport: Array<{ node: FigmaNode; exportSetting: FigmaExportSetting }> = [];\n \n const findExportableNodes = (node: FigmaNode) => {\n // Enhanced debugging for icon detection\n const nodeName = node.name.toLowerCase();\n const isIconName = ['uis:', 'dashicons:', 'ci:', 'icon', 'svg'].some(keyword => nodeName.includes(keyword));\n \n if (isIconName) {\n console.error(`[Figma API] 🔍 DEBUG: Found potential icon \"${node.name}\" (${node.type})`);\n console.error(`[Figma API] 📋 Export settings: ${node.exportSettings ? node.exportSettings.length : 0} found`);\n if (node.exportSettings && node.exportSettings.length > 0) {\n node.exportSettings.forEach((setting, index) => {\n const scale = setting.constraint?.type === 'SCALE' ? setting.constraint.value : 1;\n console.error(`[Figma API] 📄 Setting ${index}: format=${setting.format}, scale=${scale}x, suffix=${setting.suffix || 'none'}`);\n });\n } else {\n console.error(`[Figma API] ⚠️ No export settings found for icon \"${node.name}\"`);\n }\n }\n \n if (node.exportSettings && node.exportSettings.length > 0) {\n // Add each export setting as a separate export task\n for (const exportSetting of node.exportSettings) {\n nodesToExport.push({ node, exportSetting });\n console.error(`[Figma API] ✅ Added to export queue: \"${node.name}\" as ${exportSetting.format}`);\n }\n }\n \n // Recursively check children\n if (node.children) {\n for (const child of node.children) {\n findExportableNodes(child);\n }\n }\n };\n\n // Find all exportable nodes\n console.error(`[Figma API] 🔍 Scanning ${nodes.length} root nodes for export settings...`);\n for (const node of nodes) {\n console.error(`[Figma API] 📁 Scanning node: \"${node.name}\" (${node.type})`);\n findExportableNodes(node);\n }\n\n if (nodesToExport.length === 0) {\n console.error(`[Figma API] ❌ No nodes with export settings found!`);\n console.error(`[Figma API] 💡 Make sure your icons have export settings configured in Figma:`);\n console.error(`[Figma API] 1. Select the icon in Figma`);\n console.error(`[Figma API] 2. In the right panel, scroll to \"Export\" section`);\n console.error(`[Figma API] 3. Click \"+\" to add export settings`);\n console.error(`[Figma API] 4. Choose SVG format for icons`);\n return {\n downloaded: [],\n summary: { total: 0, successful: 0, failed: 0, skipped: 0 }\n };\n }\n\n console.error(`[Figma API] ✅ Found ${nodesToExport.length} export tasks from ${nodes.length} nodes`);\n\n // Group exports by format and scale to batch API calls efficiently\n const exportGroups = new Map<string, Array<{ node: FigmaNode; exportSetting: FigmaExportSetting }>>();\n \n for (const item of nodesToExport) {\n const { exportSetting } = item;\n let scale = 1;\n \n // Extract scale from constraint according to Figma API documentation\n if (exportSetting.constraint) {\n if (exportSetting.constraint.type === 'SCALE') {\n scale = exportSetting.constraint.value;\n }\n // For WIDTH/HEIGHT constraints, we'll use scale 1 and let Figma handle the sizing\n // The API will respect the width/height values from the constraint\n }\n \n // SVG only supports 1x scale according to Figma documentation\n const format = exportSetting.format.toLowerCase();\n if (format === 'svg') {\n scale = 1;\n }\n \n const groupKey = `${format}_${scale}`;\n \n if (!exportGroups.has(groupKey)) {\n exportGroups.set(groupKey, []);\n }\n exportGroups.get(groupKey)!.push(item);\n }\n\n console.error(`[Figma API] Grouped exports into ${exportGroups.size} batches by format/scale`);\n\n // Process each group\n for (const [groupKey, groupItems] of exportGroups) {\n const [format, scaleStr] = groupKey.split('_');\n const scale = parseFloat(scaleStr || '1');\n \n console.error(`[Figma API] Processing group: ${format} at ${scale}x scale (${groupItems.length} items)`);\n \n // Process in smaller batches to avoid API limits\n const batchSize = 10;\n for (let i = 0; i < groupItems.length; i += batchSize) {\n const batch = groupItems.slice(i, i + batchSize);\n const nodeIds = batch.map(item => item.node.id);\n \n try {\n // Get image URLs for this batch with the specific format and scale\n const imageResponse = await this.getImages(fileKey, nodeIds, {\n format: format as 'jpg' | 'png' | 'svg' | 'pdf',\n scale: scale,\n use_absolute_bounds: true\n });\n\n // Download each image in the batch\n for (const { node, exportSetting } of batch) {\n const imageUrl = imageResponse.images[node.id];\n \n if (!imageUrl) {\n results.push({\n nodeId: node.id,\n nodeName: node.name.replace(/[/\\\\:*?\"<>|]/g, '-').replace(/\\s+/g, ' ').trim(),\n filePath: '',\n exportSetting,\n success: false,\n error: 'No image URL returned from Figma API'\n });\n continue;\n }\n\n // Generate filename based on export settings with proper sanitization\n const rawNodeName = node.name;\n // Sanitize filename to remove/replace problematic characters\n const sanitizedNodeName = rawNodeName\n .replace(/[/\\\\:*?\"<>|]/g, '-') // Replace problematic characters with dash\n .replace(/\\s+/g, ' ') // Normalize spaces\n .trim();\n \n const suffix = exportSetting.suffix || '';\n const extension = exportSetting.format.toLowerCase();\n \n // Build base filename with proper suffix and scale handling\n let baseFilename: string;\n if (suffix) {\n // If there's a custom suffix, use it as-is\n baseFilename = `${sanitizedNodeName}${suffix}`;\n } else {\n // Always add scale to filename for clarity and consistency\n if (scale === 1) {\n baseFilename = `${sanitizedNodeName}-x1`;\n } else {\n baseFilename = `${sanitizedNodeName}-x${scale}`;\n }\n }\n \n // Generate unique filename to prevent overwrites\n const filename = generateUniqueFilename(node, baseFilename, extension, exportSetting);\n const filePath = path.join(resolvedPath, filename);\n\n try {\n // Download the image\n const downloadResponse = await axios.get(imageUrl, {\n responseType: 'arraybuffer',\n timeout: 30000,\n headers: {\n 'User-Agent': 'Custom-Figma-MCP-Server/1.0.0'\n }\n });\n\n // Write to file\n await fs.writeFile(filePath, downloadResponse.data);\n\n results.push({\n nodeId: node.id,\n nodeName: sanitizedNodeName,\n filePath,\n exportSetting,\n success: true\n });\n\n console.error(`[Figma API] Downloaded: ${filename} (${(downloadResponse.data.byteLength / 1024).toFixed(1)}KB)`);\n\n } catch (downloadError) {\n results.push({\n nodeId: node.id,\n nodeName: sanitizedNodeName,\n filePath: filePath,\n exportSetting,\n success: false,\n error: `Download failed: ${downloadError instanceof Error ? downloadError.message : String(downloadError)}`\n });\n console.error(`[Figma API] Failed to download ${filename}:`, downloadError);\n }\n }\n\n } catch (batchError) {\n // Mark all items in this batch as failed\n console.error(`[Figma API] Batch failed for group ${groupKey}:`, batchError);\n for (const { node, exportSetting } of batch) {\n results.push({\n nodeId: node.id,\n nodeName: node.name.replace(/[/\\\\:*?\"<>|]/g, '-').replace(/\\s+/g, ' ').trim(),\n filePath: '',\n exportSetting,\n success: false,\n error: `Batch API call failed: ${batchError instanceof Error ? batchError.message : String(batchError)}`\n });\n }\n }\n \n // Add a small delay between batches to be respectful to the API\n if (i + batchSize < groupItems.length) {\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n }\n }\n\n const summary = {\n total: results.length,\n successful: results.filter(r => r.success).length,\n failed: results.filter(r => !r.success).length,\n skipped: 0 // We process all nodes with export settings\n };\n\n console.error(`[Figma API] Download completed: ${summary.successful}/${summary.total} successful`);\n\n // WORKSPACE ENFORCEMENT: Ensure all export assets end up in the actual IDE workspace (can be skipped)\n let workspaceEnforcement = null;\n if (summary.successful > 0 && !options.skipWorkspaceEnforcement) {\n console.error(`[Figma API] 🔄 Starting workspace enforcement for ${summary.successful} successful downloads...`);\n try {\n workspaceEnforcement = await FigmaApiService.enforceWorkspaceLocation(results, localPath);\n console.error(`[Figma API] 🎯 Export workspace enforcement completed successfully!`);\n console.error(`[Figma API] ✅ ${workspaceEnforcement.summary.alreadyCorrect} already in correct location`);\n console.error(`[Figma API] 📦 ${workspaceEnforcement.summary.moved} moved to workspace`);\n console.error(`[Figma API] ❌ ${workspaceEnforcement.summary.failed} failed to move`);\n console.error(`[Figma API] 📁 Final location: ${workspaceEnforcement.finalLocation}`);\n } catch (enforcementError) {\n console.error(`[Figma API] ❌ Export workspace enforcement failed completely:`, enforcementError);\n console.error(`[Figma API] 🔄 Falling back to legacy recovery system...`);\n \n // Fallback to original recovery system\n const expectedPaths = results.filter(r => r.success).map(r => r.filePath);\n if (expectedPaths.length > 0) {\n console.error(`[Figma API] 🔍 Verifying ${expectedPaths.length} expected paths...`);\n const verification = await FigmaApiService.verifyAssetsLocation(expectedPaths);\n \n console.error(`[Figma API] 📊 Verification results: ${verification.summary.found} found, ${verification.summary.missing} missing`);\n \n if (verification.summary.missing > 0) {\n console.error(`[Figma API] ⚠️ ${verification.summary.missing} export assets missing from expected location, attempting recovery...`);\n \n const recovery = await FigmaApiService.findAndRecoverMissingAssets(results, resolvedPath);\n \n console.error(`[Figma API] 📊 Recovery results: ${recovery.summary.recovered}/${recovery.summary.total} recovered`);\n \n if (recovery.summary.recovered > 0) {\n console.error(`[Figma API] 🎉 Successfully recovered ${recovery.summary.recovered} export assets to project directory!`);\n \n for (const recoveredAsset of recovery.recovered) {\n const resultIndex = results.findIndex(r => r.nodeId === recoveredAsset.nodeId);\n if (resultIndex !== -1 && recoveredAsset.success && results[resultIndex]) {\n results[resultIndex].filePath = recoveredAsset.newPath;\n results[resultIndex].success = true;\n console.error(`[Figma API] 📦 Updated result path: ${recoveredAsset.oldPath} → ${recoveredAsset.newPath}`);\n }\n }\n } else {\n console.error(`[Figma API] ⚠️ Recovery system could not locate missing assets`);\n }\n } else {\n console.error(`[Figma API] ✅ All assets verified at expected locations`);\n }\n }\n }\n } else {\n console.error(`[Figma API] ⏭️ Skipping workspace enforcement - no successful downloads`);\n }\n\n return { \n downloaded: results, \n summary,\n workspaceEnforcement: workspaceEnforcement ? {\n finalLocation: workspaceEnforcement.finalLocation,\n moved: workspaceEnforcement.summary.moved,\n workspaceSource: workspaceEnforcement.workspaceInfo.source,\n confidence: workspaceEnforcement.workspaceInfo.confidence\n } : null\n };\n }\n\n /**\n * Get comments for a Figma file\n */\n async getComments(fileKey: string): Promise<FigmaCommentsResponse> {\n if (!fileKey || typeof fileKey !== 'string') {\n throw new FigmaApiError('File key is required and must be a string');\n }\n\n try {\n return await this.makeRequest<FigmaCommentsResponse>(`/files/${fileKey}/comments`);\n } catch (error) {\n if (error instanceof FigmaApiError) {\n throw error;\n }\n throw new FigmaApiError(`Failed to get comments from file ${fileKey}: ${error}`);\n }\n }\n\n\n\n /**\n * Get OS-specific dangerous paths that should never be used for asset downloads\n */\n private static getDangerousPaths(): string[] {\n const platform = os.platform();\n \n switch (platform) {\n case 'win32':\n // Windows dangerous paths\n return [\n 'C:\\\\',\n 'C:\\\\Windows',\n 'C:\\\\Program Files',\n 'C:\\\\Program Files (x86)',\n 'C:\\\\System32',\n 'C:\\\\Users\\\\Public',\n 'D:\\\\',\n 'E:\\\\',\n // Also check for drive letters generically\n ...Array.from({ length: 26 }, (_, i) => String.fromCharCode(65 + i) + ':\\\\')\n ];\n \n case 'darwin':\n // macOS dangerous paths\n return [\n '/',\n '/System',\n '/Library',\n '/usr',\n '/bin',\n '/sbin',\n '/etc',\n '/var',\n '/tmp',\n '/Applications',\n '/private'\n ];\n \n default:\n // Linux and other Unix-like systems\n return [\n '/',\n '/bin',\n '/usr',\n '/etc',\n '/root',\n '/var',\n '/sys',\n '/proc',\n '/boot',\n '/dev',\n '/lib',\n '/sbin',\n '/tmp'\n ];\n }\n }\n\n /**\n * Check if a path is considered dangerous/system path for the current OS\n */\n private static isDangerousPath(checkPath: string): boolean {\n const dangerousPaths = this.getDangerousPaths();\n const normalizedCheckPath = path.normalize(checkPath);\n \n return dangerousPaths.some(dangerous => {\n const normalizedDangerous = path.normalize(dangerous);\n return normalizedCheckPath === normalizedDangerous || \n normalizedCheckPath.startsWith(normalizedDangerous + path.sep);\n });\n }\n\n /**\n * Check if current working directory indicates a system root (cross-platform)\n */\n private static isSystemRoot(dir: string): boolean {\n const normalizedDir = path.normalize(dir);\n const platform = os.platform();\n \n switch (platform) {\n case 'win32':\n // Windows: Check for drive root (C:\\, D:\\, etc.)\n return /^[A-Z]:\\\\?$/i.test(normalizedDir);\n \n default:\n // Unix-like systems: Check for root directory\n return normalizedDir === path.sep || normalizedDir.length <= 1;\n }\n }\n\n /**\n * Get OS-appropriate search locations for missing assets\n */\n private static getAssetSearchLocations(): string[] {\n const platform = os.platform();\n const homeDir = os.homedir();\n const cwd = process.cwd();\n \n const commonLocations = [\n homeDir,\n path.join(homeDir, 'figma-workspace'),\n path.join(homeDir, 'figma-workspace', 'assets'),\n cwd,\n path.join(cwd, '..'),\n path.join(cwd, 'assets'),\n path.join(cwd, 'figma-assets')\n ];\n \n switch (platform) {\n case 'win32':\n return [\n ...commonLocations,\n path.join(homeDir, 'Downloads'),\n path.join(homeDir, 'Desktop'),\n path.join(homeDir, 'Documents'),\n 'C:\\\\temp',\n 'C:\\\\tmp',\n // Don't search system roots on Windows\n ];\n \n case 'darwin':\n return [\n ...commonLocations,\n path.join(homeDir, 'Downloads'),\n path.join(homeDir, 'Desktop'),\n path.join(homeDir, 'Documents'),\n '/tmp',\n // macOS specific locations\n path.join(homeDir, 'Library', 'Application Support'),\n ];\n \n default:\n // Linux and other Unix-like systems\n return [\n ...commonLocations,\n path.join(homeDir, 'Downloads'),\n path.join(homeDir, 'Desktop'),\n path.join(homeDir, 'Documents'),\n '/tmp',\n // Only add root if we're not running as root user\n ...(process.getuid && process.getuid() !== 0 ? ['/'] : []),\n '/assets',\n '/figma-assets'\n ];\n }\n }\n\n /**\n * Enhanced workspace detection specifically designed for Cursor IDE compatibility\n * This addresses the known Cursor bug where process.cwd() returns wrong directories\n */\n private static getActualWorkspaceDirectory(): { workspaceDir: string; confidence: 'high' | 'medium' | 'low'; source: string } {\n console.error(`[Figma API] 🎯 Enhanced workspace detection starting...`);\n console.error(`[Figma API] 📊 Initial context: process.cwd()=\"${process.cwd()}\", PWD=\"${process.env.PWD}\"`);\n \n const candidates: Array<{ dir: string; confidence: 'high' | 'medium' | 'low'; source: string }> = [];\n \n // Detect if we're in Cursor IDE environment\n const isCursorIDE = \n process.env.CURSOR_USER_DATA_DIR ||\n process.env.CURSOR_CONFIG_DIR ||\n process.env.VSCODE_IPC_HOOK_CLI ||\n process.argv.some(arg => arg.includes('cursor')) ||\n !!process.env.CURSOR_DEBUG;\n \n if (isCursorIDE) {\n console.error(`[Figma API] 🎯 Cursor IDE detected - applying enhanced detection`);\n }\n \n // HIGHEST PRIORITY: Cursor-specific workspace variables\n const cursorSpecificSources = [\n { env: 'WORKSPACE_FOLDER_PATHS', label: 'Cursor Workspace Folders', priority: 'ultra-high' },\n { env: 'CURSOR_WORKSPACE_ROOT', label: 'Cursor Workspace Root', priority: 'high' },\n { env: 'VSCODE_WORKSPACE_ROOT', label: 'VS Code Workspace Root', priority: 'high' }\n ];\n \n for (const source of cursorSpecificSources) {\n const envValue = process.env[source.env];\n if (envValue) {\n // Handle multiple workspace paths (WORKSPACE_FOLDER_PATHS can contain multiple paths)\n const workspacePaths = envValue.includes(';') ? envValue.split(';') : [envValue];\n \n for (const dir of workspacePaths) {\n const cleanDir = dir.trim();\n if (cleanDir && !this.isSystemRoot(cleanDir)) {\n try {\n fsSync.accessSync(cleanDir);\n if (this.isValidProjectDirectory(cleanDir)) {\n const confidence = source.priority === 'ultra-high' ? 'high' : 'high';\n candidates.push({ dir: cleanDir, confidence, source: source.label });\n console.error(`[Figma API] ✅ Found ${source.label}: ${cleanDir}`);\n }\n } catch {\n console.error(`[Figma API] ⚠️ ${source.label} not accessible: ${cleanDir}`);\n }\n }\n }\n }\n }\n \n // High confidence candidates - standard workspace detection\n const highConfidenceSources = [\n { env: 'PROJECT_ROOT', label: 'Project Root' },\n { env: 'WORKSPACE_ROOT', label: 'Workspace Root' },\n { env: 'npm_config_prefix', label: 'NPM Project Root' },\n { env: 'INIT_CWD', label: 'Initial Working Directory' }\n ];\n \n for (const source of highConfidenceSources) {\n const dir = process.env[source.env];\n if (dir && !this.isSystemRoot(dir)) {\n try {\n fsSync.accessSync(dir);\n if (this.isValidProjectDirectory(dir)) {\n candidates.push({ dir, confidence: 'high', source: source.label });\n console.error(`[Figma API] ✅ Found ${source.label}: ${dir}`);\n }\n } catch {\n console.error(`[Figma API] ⚠️ ${source.label} not accessible: ${dir}`);\n }\n }\n }\n \n // Medium confidence - process working directory sources\n const mediumConfidenceSources = [\n { env: 'PWD', label: 'Shell Working Directory' },\n { env: 'OLDPWD', label: 'Previous Working Directory' }\n ];\n \n for (const source of mediumConfidenceSources) {\n const dir = process.env[source.env];\n if (dir && !this.isSystemRoot(dir)) {\n try {\n fsSync.accessSync(dir);\n if (this.isValidProjectDirectory(dir)) {\n candidates.push({ dir, confidence: 'medium', source: source.label });\n console.error(`[Figma API] ✅ Found ${source.label}: ${dir}`);\n }\n } catch {\n console.error(`[Figma API] ⚠️ ${source.label} not accessible: ${dir}`);\n }\n }\n }\n \n // Project marker-based detection (medium confidence) - enhanced for Cursor\n console.error(`[Figma API] 🔍 Searching for project markers...`);\n const markerBasedDirs = this.findProjectDirectoryByMarkers();\n for (const dir of markerBasedDirs) {\n if (!candidates.some(c => c.dir === dir)) {\n candidates.push({ dir, confidence: 'medium', source: 'Project Markers' });\n console.error(`[Figma API] ✅ Found via project markers: ${dir}`);\n }\n }\n \n // Special handling for Cursor: if process.cwd() is system root, skip it entirely\n const processCwd = process.cwd();\n if (isCursorIDE && this.isSystemRoot(processCwd)) {\n console.error(`[Figma API] 🚨 Cursor bug detected: process.cwd() is system root (${processCwd}), ignoring`);\n } else if (!this.isSystemRoot(processCwd) && this.isValidProjectDirectory(processCwd)) {\n if (!candidates.some(c => c.dir === processCwd)) {\n candidates.push({ dir: processCwd, confidence: 'low', source: 'Process Working Directory' });\n console.error(`[Figma API] ✅ Valid process.cwd(): ${processCwd}`);\n }\n } else {\n console.error(`[Figma API] ❌ Invalid process.cwd(): ${processCwd}`);\n }\n \n // Sort by confidence and prefer high confidence results\n candidates.sort((a, b) => {\n const confidenceOrder = { 'high': 3, 'medium': 2, 'low': 1 };\n return confidenceOrder[b.confidence] - confidenceOrder[a.confidence];\n });\n \n console.error(`[Figma API] 🔍 Workspace detection found ${candidates.length} candidates:`);\n candidates.forEach((candidate, index) => {\n console.error(`[Figma API] ${index + 1}. ${candidate.dir} (${candidate.confidence} confidence, ${candidate.source})`);\n });\n \n // Return the best candidate or intelligent fallback\n if (candidates.length > 0) {\n const best = candidates[0]!; // Safe because we checked length > 0\n console.error(`[Figma API] ✅ Selected workspace: ${best.dir} (${best.confidence} confidence)`);\n return { workspaceDir: best.dir, confidence: best.confidence, source: best.source };\n }\n \n // For Cursor IDE: try to find the actual project directory in common locations\n if (isCursorIDE) {\n console.error(`[Figma API] 🎯 Cursor IDE fallback: searching common project locations`);\n \n const commonProjectLocations = [\n path.join(os.homedir(), 'Desktop'),\n path.join(os.homedir(), 'Documents'),\n path.join(os.homedir(), 'Projects'),\n path.join(os.homedir(), 'Development'),\n path.join(os.homedir(), 'Code'),\n os.homedir()\n ];\n \n for (const baseDir of commonProjectLocations) {\n try {\n const entries = fsSync.readdirSync(baseDir, { withFileTypes: true });\n for (const entry of entries.slice(0, 10)) { // Limit search to first 10 entries\n if (entry.isDirectory()) {\n const projectCandidate = path.join(baseDir, entry.name);\n if (this.isValidProjectDirectory(projectCandidate)) {\n console.error(`[Figma API] 🎯 Found potential Cursor project: ${projectCandidate}`);\n return { workspaceDir: projectCandidate, confidence: 'medium', source: 'Cursor Project Search' };\n }\n }\n }\n } catch {\n // Directory not accessible\n }\n }\n }\n \n // Last resort fallback - but create a proper project structure\n const fallback = path.join(os.homedir(), 'figma-mcp-workspace');\n console.error(`[Figma API] 🔧 No valid workspace found, using enhanced fallback: ${fallback}`);\n \n // Try to create the fallback directory structure\n try {\n fsSync.mkdirSync(fallback, { recursive: true });\n // Create a package.json to make it look like a proper project\n const packageJsonPath = path.join(fallback, 'package.json');\n if (!fsSync.existsSync(packageJsonPath)) {\n fsSync.writeFileSync(packageJsonPath, JSON.stringify({\n name: 'figma-mcp-workspace',\n version: '1.0.0',\n description: 'Workspace for Figma MCP assets',\n private: true\n }, null, 2));\n }\n console.error(`[Figma API] ✅ Created fallback workspace with package.json`);\n } catch (error) {\n console.error(`[Figma API] ⚠️ Could not enhance fallback workspace:`, error);\n }\n \n return { workspaceDir: fallback, confidence: 'low', source: 'Enhanced Fallback' };\n }\n\n /**\n * Enforce assets are in the actual IDE workspace - move them if needed\n */\n private static async enforceWorkspaceLocation(\n downloadResults: Array<{ nodeId: string; nodeName: string; filePath: string; success: boolean; error?: string }>,\n requestedPath: string\n ): Promise<{\n finalLocation: string;\n moved: Array<{ nodeId: string; nodeName: string; oldPath: string; newPath: string; success: boolean }>;\n summary: { total: number; alreadyCorrect: number; moved: number; failed: number };\n workspaceInfo: { dir: string; confidence: 'high' | 'medium' | 'low'; source: string };\n }> {\n console.error(`[Figma API] 🎯 Enforcing workspace location for assets...`);\n console.error(`[Figma API] 📥 Input: ${downloadResults.length} download results, requested path: \"${requestedPath}\"`);\n \n // Get the actual workspace directory\n const workspaceInfo = this.getActualWorkspaceDirectory();\n console.error(`[Figma API] 🏠 Detected workspace: \"${workspaceInfo.workspaceDir}\" (${workspaceInfo.confidence} confidence from ${workspaceInfo.source})`);\n \n // Determine the final target directory in the workspace\n const requestedBasename = path.basename(requestedPath);\n const workspaceTargetDir = path.resolve(workspaceInfo.workspaceDir, requestedBasename);\n \n console.error(`[Figma API] 📁 Target workspace location: ${workspaceTargetDir}`);\n console.error(`[Figma API] 🔄 Assets to process: ${downloadResults.filter(r => r.success).length} successful downloads`);\n \n const moved: Array<{ nodeId: string; nodeName: string; oldPath: string; newPath: string; success: boolean }> = [];\n const successfulDownloads = downloadResults.filter(r => r.success);\n \n let alreadyCorrect = 0;\n let movedCount = 0;\n let failed = 0;\n \n for (const result of successfulDownloads) {\n const currentPath = result.filePath;\n const filename = path.basename(currentPath);\n const targetPath = path.join(workspaceTargetDir, filename);\n \n console.error(`[Figma API] 🔍 Processing asset: ${result.nodeName}`);\n console.error(`[Figma API] 📁 Current path: ${currentPath}`);\n console.error(`[Figma API] 🎯 Target path: ${targetPath}`);\n console.error(`[Figma API] 📋 Filename: ${filename}`);\n \n // Check if file is already in the correct workspace location\n if (path.normalize(currentPath) === path.normalize(targetPath)) {\n console.error(`[Figma API] ✅ Already in workspace: ${filename}`);\n alreadyCorrect++;\n continue;\n }\n \n // Check if file actually exists at current location\n try {\n await fs.access(currentPath);\n } catch {\n console.error(`[Figma API] ⚠️ File not found at reported location: ${currentPath}`);\n \n // Try to find it using our search system\n const searchLocations = this.getAssetSearchLocations();\n let foundPath: string | null = null;\n \n for (const searchLoc of searchLocations) {\n try {\n const candidatePath = path.join(searchLoc, filename);\n await fs.access(candidatePath);\n const stat = await fs.stat(candidatePath);\n if (stat.size > 0) {\n foundPath = candidatePath;\n console.error(`[Figma API] 🔍 Found ${filename} at: ${candidatePath}`);\n break;\n }\n } catch {\n // Continue searching\n }\n }\n \n if (!foundPath) {\n console.error(`[Figma API] ❌ Could not locate ${filename} for workspace enforcement`);\n moved.push({\n nodeId: result.nodeId,\n nodeName: result.nodeName,\n oldPath: currentPath,\n newPath: targetPath,\n success: false\n });\n failed++;\n continue;\n }\n \n // Update current path to found location\n result.filePath = foundPath;\n }\n \n // Ensure target directory exists\n try {\n await this.createDirectorySafely(workspaceTargetDir, requestedPath);\n } catch (dirError) {\n console.error(`[Figma API] ❌ Failed to create workspace directory: ${dirError}`);\n moved.push({\n nodeId: result.nodeId,\n nodeName: result.nodeName,\n oldPath: result.filePath,\n newPath: targetPath,\n success: false\n });\n failed++;\n continue;\n }\n \n // Move/copy the file to workspace with robust cross-filesystem support\n try {\n const originalPath = result.filePath; // Save original path before moving\n \n console.error(`[Figma API] 🔄 Attempting to move: ${filename}`);\n console.error(`[Figma API] 📤 From: ${originalPath}`);\n console.error(`[Figma API] 📥 To: ${targetPath}`);\n \n // Check source file exists and get stats\n let sourceStats;\n try {\n sourceStats = await fs.stat(originalPath);\n console.error(`[Figma API] 📊 Source file: ${Math.round(sourceStats.size / 1024)}KB`);\n } catch (statError) {\n throw new Error(`Source file does not exist: ${originalPath}`);\n }\n \n // Ensure target directory exists\n const targetDir = path.dirname(targetPath);\n try {\n await fs.mkdir(targetDir, { recursive: true });\n } catch (mkdirError) {\n console.error(`[Figma API] ⚠️ Target directory creation failed:`, mkdirError);\n }\n \n let moveSuccess = false;\n let moveMethod = '';\n \n // Method 1: Try atomic rename (fastest, works on same filesystem)\n try {\n await fs.rename(originalPath, targetPath);\n moveSuccess = true;\n moveMethod = 'atomic rename';\n console.error(`[Figma API] ✅ Success via atomic rename: ${filename}`);\n } catch (renameError) {\n console.error(`[Figma API] ⚠️ Atomic rename failed (likely cross-filesystem):`, renameError instanceof Error ? renameError.message : String(renameError));\n \n // Method 2: Copy + verify + delete (cross-filesystem safe)\n try {\n console.error(`[Figma API] 🔄 Trying copy + delete method...`);\n \n // Copy the file\n await fs.copyFile(originalPath, targetPath);\n \n // Verify the copy was successful\n const targetStats = await fs.stat(targetPath);\n if (targetStats.size !== sourceStats.size) {\n throw new Error(`Copy verification failed: size mismatch (${sourceStats.size} vs ${targetStats.size})`);\n }\n \n console.error(`[Figma API] ✅ Copy verified: ${Math.round(targetStats.size / 1024)}KB`);\n \n // Only delete original after successful copy verification\n await fs.unlink(originalPath);\n \n moveSuccess = true;\n moveMethod = 'copy + delete';\n console.error(`[Figma API] ✅ Success via copy + delete: ${filename}`);\n \n } catch (copyError) {\n console.error(`[Figma API] ❌ Copy + delete failed:`, copyError instanceof Error ? copyError.message : String(copyError));\n \n // Method 3: Last resort - streaming copy (handles large files and permission issues)\n try {\n console.error(`[Figma API] 🔄 Trying streaming copy method...`);\n \n const readStream = (await import('fs')).createReadStream(originalPath);\n const writeStream = (await import('fs')).createWriteStream(targetPath);\n \n await new Promise<void>((resolve, reject) => {\n readStream.pipe(writeStream);\n writeStream.on('finish', () => resolve());\n writeStream.on('error', reject);\n readStream.on('error', reject);\n });\n \n // Verify streaming copy\n const streamTargetStats = await fs.stat(targetPath);\n if (streamTargetStats.size !== sourceStats.size) {\n throw new Error(`Streaming copy verification failed: size mismatch`);\n }\n \n // Delete original\n await fs.unlink(originalPath);\n \n moveSuccess = true;\n moveMethod = 'streaming copy';\n console.error(`[Figma API] ✅ Success via streaming copy: ${filename}`);\n \n } catch (streamError) {\n const streamErrorMsg = streamError instanceof Error ? streamError.message : String(streamError);\n console.error(`[Figma API] ❌ All move methods failed for ${filename}:`, streamErrorMsg);\n throw new Error(`All move methods failed: ${streamErrorMsg}`);\n }\n }\n }\n \n if (moveSuccess) {\n // Final verification\n try {\n const finalStats = await fs.stat(targetPath);\n console.error(`[Figma API] 🎉 Move completed via ${moveMethod}: ${filename} (${Math.round(finalStats.size / 1024)}KB)`);\n \n // Update the result with new path\n result.filePath = targetPath;\n \n moved.push({\n nodeId: result.nodeId,\n nodeName: result.nodeName,\n oldPath: originalPath,\n newPath: targetPath,\n success: true\n });\n movedCount++;\n \n } catch (verifyError) {\n throw new Error(`Move appeared successful but target file verification failed: ${verifyError instanceof Error ? verifyError.message : String(verifyError)}`);\n }\n } else {\n throw new Error('Unknown move failure - none of the methods succeeded');\n }\n\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error);\n console.error(`[Figma API] ❌ Failed to move ${filename} to workspace: ${errorMsg}`);\n console.error(`[Figma API] 🔍 This usually indicates a filesystem or permission issue`);\n \n moved.push({\n nodeId: result.nodeId,\n nodeName: result.nodeName,\n oldPath: result.filePath,\n newPath: targetPath,\n success: false\n });\n failed++;\n }\n }\n \n const summary = {\n total: successfulDownloads.length,\n alreadyCorrect,\n moved: movedCount,\n failed\n };\n \n console.error(`[Figma API] 🎯 Workspace enforcement completed:`);\n console.error(`[Figma API] 📊 ${summary.alreadyCorrect} already correct, ${summary.moved} moved, ${summary.failed} failed`);\n console.error(`[Figma API] 📁 Final location: ${workspaceTargetDir}`);\n \n return {\n finalLocation: workspaceTargetDir,\n moved,\n summary,\n workspaceInfo: { dir: workspaceInfo.workspaceDir, confidence: workspaceInfo.confidence, source: workspaceInfo.source }\n };\n }\n} ","export interface BaseRule {\n rule: string;\n description: string;\n priority: 'critical' | 'high' | 'medium' | 'low';\n checks: string[];\n}\n\nexport interface FrameworkConfig {\n name: string;\n type: 'web' | 'mobile' | 'desktop';\n language: 'typescript' | 'javascript' | 'swift' | 'rust' | 'mixed';\n features: string[];\n rules: Record<string, BaseRule>;\n}\n\n// Common optimization flags\nexport const COMMON_OPTIMIZATIONS = {\n WEB_BASE: {\n enableCSSGeneration: true,\n enableSemanticAnalysis: true,\n enableAccessibilityInfo: true,\n enableResponsiveBreakpoints: true,\n enableDesignTokens: true,\n enableComponentVariants: true,\n enableInteractionStates: true,\n simplifyComplexPaths: true,\n optimizeForCodeGeneration: true\n },\n MOBILE_BASE: {\n enableCSSGeneration: false,\n enableSemanticAnalysis: true,\n enableAccessibilityInfo: true,\n enableResponsiveBreakpoints: true,\n enableDesignTokens: true,\n enableComponentVariants: true,\n enableInteractionStates: true,\n simplifyComplexPaths: true,\n optimizeForCodeGeneration: true,\n generateAdaptiveLayouts: true,\n generateDarkModeSupport: true\n },\n DESKTOP_BASE: {\n enableCSSGeneration: true,\n enableSemanticAnalysis: true,\n enableAccessibilityInfo: true,\n enableResponsiveBreakpoints: false,\n enableDesignTokens: true,\n enableComponentVariants: true,\n enableInteractionStates: true,\n simplifyComplexPaths: true,\n optimizeForCodeGeneration: true,\n generateMenus: true,\n generateNotifications: true\n }\n};\n\n// Common rule patterns\nexport const BASE_RULES = {\n MODERN_PATTERNS: {\n rule: \"Use modern framework patterns\",\n description: \"Follow current best practices for the framework\",\n priority: \"critical\" as const,\n checks: [\"Modern syntax\", \"Best practices\", \"Performance optimized\"]\n },\n TYPESCRIPT: {\n rule: \"TypeScript-first development\", \n description: \"Use TypeScript for type safety and better IDE support\",\n priority: \"critical\" as const,\n checks: [\"Proper typing\", \"Interface definitions\", \"Type safety\"]\n },\n ACCESSIBILITY: {\n rule: \"Accessibility-first approach\",\n description: \"Ensure components are accessible by default\",\n priority: \"high\" as const,\n checks: [\"ARIA labels\", \"Keyboard navigation\", \"Screen reader support\"]\n },\n PERFORMANCE: {\n rule: \"Optimize for performance\",\n description: \"Implement performance best practices\",\n priority: \"high\" as const,\n checks: [\"Optimized rendering\", \"Memory efficient\", \"Fast interactions\"]\n },\n TESTING: {\n rule: \"Comprehensive testing strategy\",\n description: \"Test components and functionality thoroughly\",\n priority: \"medium\" as const,\n checks: [\"Unit tests\", \"Integration tests\", \"User interaction tests\"]\n }\n};\n\nexport const NAMING_CONVENTIONS = {\n PASCAL_CASE: 'PascalCase' as const,\n CAMEL_CASE: 'camelCase' as const,\n KEBAB_CASE: 'kebab-case' as const,\n SNAKE_CASE: 'snake_case' as const\n}; ","import { FigmaNodeType } from '../types/figma.js';\nimport { COMMON_OPTIMIZATIONS, NAMING_CONVENTIONS, BaseRule } from './base.js';\n\n// Base framework optimization interface\ninterface BaseFrameworkOptimization {\n useTypeScript?: boolean;\n componentNamingConvention?: string;\n implementationRules?: Record<string, BaseRule>;\n}\n\n// Framework-specific interfaces extending base\ninterface WebFrameworkOptimization extends BaseFrameworkOptimization {\n generateJSX?: boolean;\n useStyledComponents?: boolean;\n useTailwindCSS?: boolean;\n generateHooks?: boolean;\n generatePropTypes?: boolean;\n generateStorybook?: boolean;\n generateSFC?: boolean;\n useCompositionAPI?: boolean;\n useScoped?: boolean;\n generateProps?: boolean;\n generateComponent?: boolean;\n useStandalone?: boolean;\n generateModule?: boolean;\n useSignals?: boolean;\n generateSvelteComponent?: boolean;\n useStores?: boolean;\n generateSemanticHTML?: boolean;\n useCSS?: boolean;\n generateAccessibleMarkup?: boolean;\n useModernCSS?: boolean;\n}\n\ninterface MobileFrameworkOptimization extends BaseFrameworkOptimization {\n generateViews?: boolean;\n useViewBuilder?: boolean;\n generateModifiers?: boolean;\n useObservableObject?: boolean;\n useStateManagement?: boolean;\n generatePreviewProvider?: boolean;\n useEnvironmentObjects?: boolean;\n generateSFSymbols?: boolean;\n useNativeColors?: boolean;\n generateAdaptiveLayouts?: boolean;\n useAsyncImage?: boolean;\n generateNavigationViews?: boolean;\n useToolbarModifiers?: boolean;\n generateAnimations?: boolean;\n useGeometryReader?: boolean;\n generateDarkModeSupport?: boolean;\n useTabViews?: boolean;\n generateListViews?: boolean;\n useScrollViews?: boolean;\n generateFormViews?: boolean;\n generateViewControllers?: boolean;\n useStoryboards?: boolean;\n useProgrammaticLayout?: boolean;\n useAutoLayout?: boolean;\n generateXIBFiles?: boolean;\n useStackViews?: boolean;\n generateConstraints?: boolean;\n useSwiftUIInterop?: boolean;\n generateDelegatePatterns?: boolean;\n useModernConcurrency?: boolean;\n generateAccessibilitySupport?: boolean;\n}\n\ninterface DesktopFrameworkOptimization extends BaseFrameworkOptimization {\n generateMainProcess?: boolean;\n generateRendererProcess?: boolean;\n useIPC?: boolean;\n useWebSecurity?: boolean;\n generateMenus?: boolean;\n useNativeDialogs?: boolean;\n generateUpdater?: boolean;\n useContextIsolation?: boolean;\n generateNotifications?: boolean;\n useCrashReporter?: boolean;\n generateTrayIcon?: boolean;\n useProtocolHandlers?: boolean;\n generateRustBackend?: boolean;\n generateWebFrontend?: boolean;\n useSystemWebView?: boolean;\n generateCommands?: boolean;\n useEventSystem?: boolean;\n generatePlugins?: boolean;\n useSidecar?: boolean;\n useFilesystem?: boolean;\n useSystemTray?: boolean;\n generateNodeBackend?: boolean;\n useChromiumAPI?: boolean;\n useNativeModules?: boolean;\n generateManifest?: boolean;\n useClipboard?: boolean;\n generateFileAccess?: boolean;\n useShell?: boolean;\n generateScreenCapture?: boolean;\n useTrayIcon?: boolean;\n}\n\n// Unified framework optimization type\nexport type FrameworkOptimization = WebFrameworkOptimization & MobileFrameworkOptimization & DesktopFrameworkOptimization;\n\n// Main context rules interface\nexport interface ContextRules {\n maxDepth: number;\n includeHiddenNodes: boolean;\n includeLockedNodes: boolean;\n \n nodeTypeFilters: {\n include: FigmaNodeType[];\n exclude: FigmaNodeType[];\n prioritize: FigmaNodeType[];\n };\n \n aiOptimization: {\n enableCSSGeneration: boolean;\n enableSemanticAnalysis: boolean;\n enableAccessibilityInfo: boolean;\n enableResponsiveBreakpoints: boolean;\n enableDesignTokens: boolean;\n enableComponentVariants: boolean;\n enableInteractionStates: boolean;\n simplifyComplexPaths: boolean;\n optimizeForCodeGeneration: boolean;\n };\n \n contentEnhancement: {\n extractTextContent: boolean;\n analyzeImageContent: boolean;\n detectUIPatterns: boolean;\n identifyComponentHierarchy: boolean;\n extractLayoutConstraints: boolean;\n analyzeColorPalettes: boolean;\n extractTypographyStyles: boolean;\n detectSpacingPatterns: boolean;\n };\n \n contextReduction: {\n removeRedundantProperties: boolean;\n simplifyNestedStructures: boolean;\n aggregateSimilarNodes: boolean;\n removeEmptyContainers: boolean;\n limitTextLength: number;\n compressLargeArrays: boolean;\n };\n \n frameworkOptimizations: Partial<{\n react: FrameworkOptimization;\n vue: FrameworkOptimization;\n angular: FrameworkOptimization;\n svelte: FrameworkOptimization;\n html: FrameworkOptimization;\n swiftui: FrameworkOptimization;\n uikit: FrameworkOptimization;\n electron: FrameworkOptimization;\n tauri: FrameworkOptimization;\n nwjs: FrameworkOptimization;\n }>;\n \n customRules: CustomRule[];\n}\n\nexport interface CustomRule {\n name: string;\n description: string;\n condition: RuleCondition;\n action: RuleAction;\n priority: number;\n enabled: boolean;\n}\n\nexport interface RuleCondition {\n nodeType?: FigmaNodeType | FigmaNodeType[];\n nodeName?: string | RegExp;\n hasChildren?: boolean;\n hasText?: boolean;\n hasImages?: boolean;\n isComponent?: boolean;\n isInstance?: boolean;\n hasAutoLayout?: boolean;\n customCondition?: (node: any) => boolean;\n}\n\nexport interface RuleAction {\n type: 'enhance' | 'transform' | 'filter' | 'aggregate' | 'custom';\n parameters: Record<string, any>;\n customAction?: (node: any, context: any) => any;\n}\n\n// Base framework configurations\nconst WEB_FRAMEWORK_BASE: Partial<WebFrameworkOptimization> = {\n useTypeScript: true,\n componentNamingConvention: NAMING_CONVENTIONS.PASCAL_CASE,\n useTailwindCSS: true\n};\n\nconst MOBILE_FRAMEWORK_BASE: Partial<MobileFrameworkOptimization> = {\n useTypeScript: true,\n componentNamingConvention: NAMING_CONVENTIONS.PASCAL_CASE,\n generateAccessibilitySupport: true\n};\n\nconst DESKTOP_FRAMEWORK_BASE: Partial<DesktopFrameworkOptimization> = {\n generateMenus: true,\n generateNotifications: true\n};\n\n// Default rules configuration using base optimizations\nexport const DEFAULT_RULES: ContextRules = {\n maxDepth: 10,\n includeHiddenNodes: false,\n includeLockedNodes: true,\n \n nodeTypeFilters: {\n include: [\n 'DOCUMENT', 'CANVAS', 'FRAME', 'GROUP', 'TEXT', 'RECTANGLE', 'ELLIPSE', \n 'VECTOR', 'COMPONENT', 'INSTANCE', 'BOOLEAN_OPERATION', 'STAR', 'LINE', 'REGULAR_POLYGON'\n ],\n exclude: ['SLICE', 'STICKY'],\n prioritize: ['DOCUMENT', 'CANVAS', 'FRAME', 'COMPONENT', 'INSTANCE', 'TEXT']\n },\n \n aiOptimization: COMMON_OPTIMIZATIONS.WEB_BASE,\n \n contentEnhancement: {\n extractTextContent: true,\n analyzeImageContent: false,\n detectUIPatterns: true,\n identifyComponentHierarchy: true,\n extractLayoutConstraints: true,\n analyzeColorPalettes: true,\n extractTypographyStyles: true,\n detectSpacingPatterns: true\n },\n \n contextReduction: {\n removeRedundantProperties: true,\n simplifyNestedStructures: true,\n aggregateSimilarNodes: false,\n removeEmptyContainers: true,\n limitTextLength: 1000,\n compressLargeArrays: true\n },\n \n frameworkOptimizations: {\n react: { ...WEB_FRAMEWORK_BASE, generateJSX: true, generateHooks: true },\n vue: { ...WEB_FRAMEWORK_BASE, generateSFC: true, useCompositionAPI: true },\n angular: { ...WEB_FRAMEWORK_BASE, generateComponent: true, useStandalone: true, useSignals: true },\n svelte: { ...WEB_FRAMEWORK_BASE, generateSvelteComponent: true },\n html: { ...WEB_FRAMEWORK_BASE, generateSemanticHTML: true, useCSS: true, generateAccessibleMarkup: true, useModernCSS: true },\n swiftui: { ...MOBILE_FRAMEWORK_BASE, generateViews: true, useViewBuilder: true, generateModifiers: true, useStateManagement: true, generateAdaptiveLayouts: true, generateDarkModeSupport: true },\n uikit: { ...MOBILE_FRAMEWORK_BASE, generateViewControllers: true, useProgrammaticLayout: true, useAutoLayout: true },\n electron: { ...DESKTOP_FRAMEWORK_BASE, componentNamingConvention: NAMING_CONVENTIONS.CAMEL_CASE, generateMainProcess: true, generateRendererProcess: true, useIPC: true, useContextIsolation: true },\n tauri: { ...DESKTOP_FRAMEWORK_BASE, componentNamingConvention: NAMING_CONVENTIONS.SNAKE_CASE, generateRustBackend: true, generateWebFrontend: true, useSystemWebView: true },\n nwjs: { ...DESKTOP_FRAMEWORK_BASE, componentNamingConvention: NAMING_CONVENTIONS.CAMEL_CASE, generateNodeBackend: true, generateWebFrontend: true, useChromiumAPI: true }\n },\n \n customRules: []\n};\n\n// Utility functions\nexport const getEnvironmentRules = (): Partial<ContextRules> => {\n const isDev = process.env.NODE_ENV === 'development';\n return {\n maxDepth: isDev ? 15 : 10,\n aiOptimization: {\n ...COMMON_OPTIMIZATIONS.WEB_BASE,\n enableComponentVariants: isDev,\n enableInteractionStates: isDev\n }\n };\n};\n\nexport const validateRules = (rules: ContextRules): string[] => {\n const errors: string[] = [];\n if (rules.maxDepth < 1 || rules.maxDepth > 20) {\n errors.push('maxDepth must be between 1 and 20');\n }\n if (rules.contextReduction.limitTextLength < 0) {\n errors.push('limitTextLength must be non-negative');\n }\n return errors;\n};\n\nexport const mergeRules = (base: ContextRules, override: Partial<ContextRules>): ContextRules => {\n return {\n ...base,\n ...override,\n aiOptimization: { ...base.aiOptimization, ...override.aiOptimization },\n contentEnhancement: { ...base.contentEnhancement, ...override.contentEnhancement },\n contextReduction: { ...base.contextReduction, ...override.contextReduction },\n frameworkOptimizations: { ...base.frameworkOptimizations, ...override.frameworkOptimizations }\n };\n}; ","import {\n FigmaNode,\n EnhancedFigmaNode,\n CSSProperties,\n SemanticRole,\n AccessibilityInfo,\n DesignToken,\n ComponentVariant,\n InteractionState,\n LayoutContext,\n ComponentRelationships,\n FigmaColor,\n FigmaTypeStyle,\n FigmaComment,\n CommentInstruction,\n EnhancedFigmaNodeWithComments\n} from '../types/figma.js';\nimport {\n ContextRules,\n RuleCondition,\n RuleAction,\n DEFAULT_RULES,\n mergeRules,\n getEnvironmentRules\n} from '../config/rules.js';\n\nexport interface ProcessingContext {\n fileKey: string;\n fileName?: string;\n parentNode?: EnhancedFigmaNode;\n depth: number;\n siblingIndex: number;\n totalSiblings: number;\n framework?: 'react' | 'vue' | 'angular' | 'svelte' | 'html' | 'swiftui' | 'uikit' | 'electron' | 'tauri' | 'nwjs' | undefined;\n designSystem?: DesignSystemContext;\n}\n\nexport interface DesignSystemContext {\n colors: Map<string, string>;\n typography: Map<string, FigmaTypeStyle>;\n spacing: Map<string, number>;\n components: Map<string, ComponentVariant[]>;\n breakpoints: Map<string, number>;\n}\n\nexport interface ProcessingStats {\n nodesProcessed: number;\n nodesEnhanced: number;\n rulesApplied: number;\n processingTime: number;\n errors: string[];\n warnings: string[];\n}\n\nexport class ContextProcessor {\n private rules: ContextRules;\n private stats: ProcessingStats = {\n nodesProcessed: 0,\n nodesEnhanced: 0,\n rulesApplied: 0,\n processingTime: 0,\n errors: [],\n warnings: []\n };\n\n constructor(customRules?: Partial<ContextRules>) {\n const envRules = getEnvironmentRules();\n this.rules = mergeRules(DEFAULT_RULES, { ...envRules, ...customRules });\n }\n\n /**\n * Process a Figma node tree and enhance it with AI-optimized context\n */\n async processNode(\n node: FigmaNode,\n context: ProcessingContext\n ): Promise<EnhancedFigmaNode> {\n const startTime = Date.now();\n this.stats.nodesProcessed++;\n\n try {\n // Check depth limit\n if (context.depth > this.rules.maxDepth) {\n this.stats.warnings.push(`Max depth exceeded for node ${node.id}`);\n return this.createMinimalNode(node);\n }\n\n // Apply node type filters\n if (!this.shouldIncludeNode(node)) {\n return this.createMinimalNode(node);\n }\n\n // Create enhanced node\n const enhancedNode: EnhancedFigmaNode = {\n ...node,\n cssProperties: {},\n semanticRole: undefined,\n accessibilityInfo: {},\n designTokens: [],\n componentVariants: [],\n interactionStates: [],\n layoutContext: this.createLayoutContext(node, context),\n // Add component relationships\n componentRelationships: this.createComponentRelationships(node, context)\n };\n\n // Apply AI optimizations\n if (this.rules.aiOptimization.enableCSSGeneration) {\n enhancedNode.cssProperties = this.generateCSSProperties(node, context);\n }\n\n if (this.rules.aiOptimization.enableSemanticAnalysis) {\n enhancedNode.semanticRole = this.analyzeSemanticRole(node, context);\n }\n\n if (this.rules.aiOptimization.enableAccessibilityInfo) {\n enhancedNode.accessibilityInfo = this.generateAccessibilityInfo(node, context);\n }\n\n if (this.rules.aiOptimization.enableDesignTokens) {\n enhancedNode.designTokens = this.extractDesignTokens(node, context);\n }\n\n if (this.rules.aiOptimization.enableComponentVariants) {\n enhancedNode.componentVariants = this.detectComponentVariants(node, context);\n }\n\n if (this.rules.aiOptimization.enableInteractionStates) {\n enhancedNode.interactionStates = this.generateInteractionStates(node, context);\n }\n\n // Apply custom rules\n await this.applyCustomRules(enhancedNode, context);\n\n // Process children recursively\n if (node.children && context.depth < this.rules.maxDepth) {\n enhancedNode.children = await Promise.all(\n node.children.map((child, index) =>\n this.processNode(child, {\n ...context,\n parentNode: enhancedNode,\n depth: context.depth + 1,\n siblingIndex: index,\n totalSiblings: node.children?.length || 0\n })\n )\n );\n }\n\n // Apply context reduction\n this.applyContextReduction(enhancedNode);\n\n this.stats.nodesEnhanced++;\n return enhancedNode;\n\n } catch (error) {\n this.stats.errors.push(`Error processing node ${node.id}: ${error}`);\n return this.createMinimalNode(node);\n } finally {\n this.stats.processingTime += Date.now() - startTime;\n }\n }\n\n private shouldIncludeNode(node: FigmaNode): boolean {\n // Check visibility\n if (!this.rules.includeHiddenNodes && node.visible === false) {\n return false;\n }\n\n // Check locked status\n if (!this.rules.includeLockedNodes && node.locked === true) {\n return false;\n }\n\n // Check node type filters\n const { include, exclude } = this.rules.nodeTypeFilters;\n \n if (exclude.includes(node.type)) {\n return false;\n }\n\n if (include.length > 0 && !include.includes(node.type)) {\n return false;\n }\n\n return true;\n }\n\n private createMinimalNode(node: FigmaNode): EnhancedFigmaNode {\n return {\n id: node.id,\n name: node.name,\n type: node.type,\n visible: node.visible,\n locked: node.locked\n };\n }\n\n private createLayoutContext(node: FigmaNode, context: ProcessingContext): LayoutContext {\n const position = context.totalSiblings === 1 ? 'only' :\n context.siblingIndex === 0 ? 'first' :\n context.siblingIndex === context.totalSiblings - 1 ? 'last' : 'middle';\n\n return {\n parentType: context.parentNode?.type || 'DOCUMENT',\n siblingCount: context.totalSiblings,\n position,\n gridArea: this.detectGridArea(node, context),\n flexOrder: this.detectFlexOrder(node, context)\n };\n }\n\n private createComponentRelationships(node: FigmaNode, context: ProcessingContext): ComponentRelationships {\n const relationships: ComponentRelationships = {};\n\n // Parent information\n if (context.parentNode) {\n relationships.parent = {\n id: context.parentNode.id,\n name: context.parentNode.name,\n type: context.parentNode.type\n };\n }\n\n // Children information (simplified for AI)\n if (node.children && node.children.length > 0) {\n relationships.children = node.children.slice(0, 10).map(child => ({\n id: child.id,\n name: child.name,\n type: child.type,\n role: this.detectChildRole(child, node)\n }));\n }\n\n // Sibling information (limited to avoid bloat)\n if (context.parentNode?.children && context.totalSiblings > 1) {\n const siblings = context.parentNode.children\n .filter(sibling => sibling.id !== node.id)\n .slice(0, 5)\n .map(sibling => ({\n id: sibling.id,\n name: sibling.name,\n type: sibling.type\n }));\n \n if (siblings.length > 0) {\n relationships.siblings = siblings;\n }\n }\n\n // Component instance information\n if (node.componentId || node.type === 'INSTANCE') {\n relationships.componentInstance = {\n componentId: node.componentId,\n overrides: node.componentProperties\n };\n }\n\n // Export settings\n if (node.exportSettings && node.exportSettings.length > 0) {\n relationships.exportable = {\n hasExportSettings: true,\n formats: node.exportSettings.map(setting => setting.format.toLowerCase()),\n category: this.detectExportCategory(node)\n };\n }\n\n return relationships;\n }\n\n private detectChildRole(child: FigmaNode, _parent: FigmaNode): string | undefined {\n const childName = child.name.toLowerCase();\n \n // Detect common child roles\n if (child.type === 'TEXT') {\n if (childName.includes('title') || childName.includes('heading')) return 'title';\n if (childName.includes('description') || childName.includes('body')) return 'description';\n if (childName.includes('label')) return 'label';\n if (childName.includes('caption')) return 'caption';\n }\n \n if (this.isButton(child, childName)) return 'action';\n if (this.isImage(child, childName)) return 'visual';\n if (child.type === 'FRAME' && childName.includes('content')) return 'content';\n \n return undefined;\n }\n\n private detectExportCategory(node: FigmaNode): 'icon' | 'image' | 'logo' | 'asset' {\n const name = node.name.toLowerCase();\n \n if (name.includes('icon')) return 'icon';\n if (name.includes('logo')) return 'logo';\n if (name.includes('image') || name.includes('photo')) return 'image';\n \n // Size-based detection\n if (node.absoluteBoundingBox) {\n const { width, height } = node.absoluteBoundingBox;\n if (width <= 32 && height <= 32) return 'icon';\n if (width > 200 || height > 200) return 'image';\n }\n \n return 'asset';\n }\n\n private generateCSSProperties(node: FigmaNode, _context: ProcessingContext): CSSProperties {\n const css: CSSProperties = {};\n\n // Layout properties\n if (node.absoluteBoundingBox) {\n css.width = `${node.absoluteBoundingBox.width}px`;\n css.height = `${node.absoluteBoundingBox.height}px`;\n }\n\n // Auto layout properties\n if (node.layoutMode) {\n css.display = 'flex';\n css.flexDirection = node.layoutMode === 'HORIZONTAL' ? 'row' : 'column';\n \n if (node.primaryAxisAlignItems) {\n css.justifyContent = this.mapAxisAlign(node.primaryAxisAlignItems);\n }\n \n if (node.counterAxisAlignItems) {\n css.alignItems = this.mapAxisAlign(node.counterAxisAlignItems);\n }\n \n if (node.itemSpacing) {\n css.gap = `${node.itemSpacing}px`;\n }\n }\n\n // Padding\n if (node.paddingLeft || node.paddingRight || node.paddingTop || node.paddingBottom) {\n const top = node.paddingTop || 0;\n const right = node.paddingRight || 0;\n const bottom = node.paddingBottom || 0;\n const left = node.paddingLeft || 0;\n css.padding = `${top}px ${right}px ${bottom}px ${left}px`;\n }\n\n // Background (enhanced with gradient support)\n if (node.fills && node.fills.length > 0) {\n const fill = node.fills[0];\n if (fill && fill.visible !== false) {\n if (fill.type === 'SOLID' && fill.color) {\n css.backgroundColor = this.colorToCSS(fill.color);\n } else if (fill.type.startsWith('GRADIENT_') && fill.gradientStops) {\n css.background = this.generateGradientCSS(fill);\n } else if (fill.type === 'IMAGE' && fill.imageRef) {\n css.backgroundImage = `url(${fill.imageRef})`;\n if (fill.scaleMode) {\n css.backgroundSize = this.mapScaleMode(fill.scaleMode);\n }\n }\n }\n }\n\n // Border radius - support individual corners and cornerSmoothing\n if (node.cornerRadius !== undefined) {\n css.borderRadius = `${node.cornerRadius}px`;\n } else if (node.rectangleCornerRadii) {\n // Support for individual corner radii\n const [topLeft, topRight, bottomRight, bottomLeft] = node.rectangleCornerRadii;\n css.borderRadius = `${topLeft}px ${topRight}px ${bottomRight}px ${bottomLeft}px`;\n }\n\n // Strokes (borders)\n if (node.strokes && node.strokes.length > 0) {\n const stroke = node.strokes[0]; // Use first stroke\n if (stroke && stroke.type === 'SOLID' && stroke.color) {\n const strokeWeight = node.strokeWeight || 1;\n const strokeColor = this.colorToCSS(stroke.color);\n \n // Handle stroke alignment\n if (node.strokeAlign === 'INSIDE') {\n // Use box-shadow inset to simulate inside stroke\n css.boxShadow = `inset 0 0 0 ${strokeWeight}px ${strokeColor}`;\n } else if (node.strokeAlign === 'OUTSIDE') {\n // Use box-shadow to simulate outside stroke\n css.boxShadow = `0 0 0 ${strokeWeight}px ${strokeColor}`;\n } else {\n // CENTER (default) - use regular border\n css.border = `${strokeWeight}px solid ${strokeColor}`;\n }\n }\n }\n\n // Individual strokes per side\n if (node.individualStrokeWeights) {\n const { top, right, bottom, left } = node.individualStrokeWeights;\n if (node.strokes && node.strokes.length > 0) {\n const stroke = node.strokes[0];\n if (stroke && stroke.type === 'SOLID' && stroke.color) {\n const strokeColor = this.colorToCSS(stroke.color);\n css.borderTop = top > 0 ? `${top}px solid ${strokeColor}` : 'none';\n css.borderRight = right > 0 ? `${right}px solid ${strokeColor}` : 'none';\n css.borderBottom = bottom > 0 ? `${bottom}px solid ${strokeColor}` : 'none';\n css.borderLeft = left > 0 ? `${left}px solid ${strokeColor}` : 'none';\n }\n }\n }\n\n // Stroke dashes\n if (node.strokeDashes && node.strokeDashes.length > 0) {\n css.borderStyle = 'dashed';\n // Note: CSS doesn't support custom dash patterns like Figma\n }\n\n // Opacity\n if (node.opacity !== undefined && node.opacity < 1) {\n css.opacity = node.opacity.toString();\n }\n \n // Blend mode\n if (node.blendMode && node.blendMode !== 'NORMAL' && node.blendMode !== 'PASS_THROUGH') {\n css.mixBlendMode = node.blendMode.toLowerCase().replace('_', '-');\n }\n \n // Layout sizing (for auto layout children)\n if (node.layoutSizingHorizontal === 'FILL') {\n css.flexGrow = '1';\n }\n if (node.layoutSizingVertical === 'FILL') {\n css.alignSelf = 'stretch';\n }\n \n // Layout alignment\n if (node.layoutAlign) {\n switch (node.layoutAlign) {\n case 'MIN':\n css.alignSelf = 'flex-start';\n break;\n case 'CENTER':\n css.alignSelf = 'center';\n break;\n case 'MAX':\n css.alignSelf = 'flex-end';\n break;\n case 'STRETCH':\n css.alignSelf = 'stretch';\n break;\n }\n }\n\n // Text properties\n if (node.type === 'TEXT' && node.style) {\n css.fontSize = `${node.style.fontSize}px`;\n css.fontFamily = node.style.fontFamily;\n css.lineHeight = `${node.style.lineHeightPx}px`;\n css.letterSpacing = `${node.style.letterSpacing}px`;\n \n // Add missing typography properties\n if (node.style.fontPostScriptName) {\n css.fontFamily = `\"${node.style.fontPostScriptName}\", ${css.fontFamily}`;\n }\n \n // Text decoration\n if (node.style.textDecoration && node.style.textDecoration !== 'NONE') {\n css.textDecoration = node.style.textDecoration.toLowerCase().replace('_', '-');\n }\n \n // Text transform\n if (node.style.textCase && node.style.textCase !== 'ORIGINAL') {\n switch (node.style.textCase) {\n case 'UPPER':\n css.textTransform = 'uppercase';\n break;\n case 'LOWER':\n css.textTransform = 'lowercase';\n break;\n case 'TITLE':\n css.textTransform = 'capitalize';\n break;\n case 'SMALL_CAPS':\n case 'SMALL_CAPS_FORCED':\n css.fontVariant = 'small-caps';\n break;\n }\n }\n \n // Paragraph spacing\n if (node.style.paragraphSpacing) {\n css.marginBottom = `${node.style.paragraphSpacing}px`;\n }\n \n // Paragraph indent\n if (node.style.paragraphIndent) {\n css.textIndent = `${node.style.paragraphIndent}px`;\n }\n \n if (node.style.fills && node.style.fills.length > 0) {\n const textFill = node.style.fills[0];\n if (textFill && textFill.type === 'SOLID' && textFill.color) {\n css.color = this.colorToCSS(textFill.color);\n }\n }\n }\n\n // Effects (shadows and blurs)\n if (node.effects && node.effects.length > 0) {\n const dropShadows: string[] = [];\n const innerShadows: string[] = [];\n let layerBlur: number | undefined;\n let backgroundBlur: number | undefined;\n \n // Process all effects\n node.effects.forEach(effect => {\n if (effect.visible === false) return; // Skip invisible effects\n \n switch (effect.type) {\n case 'DROP_SHADOW':\n const x = effect.offset?.x || 0;\n const y = effect.offset?.y || 0;\n const blur = effect.radius || 0;\n const spread = effect.spread || 0;\n const color = effect.color ? this.colorToCSS(effect.color) : 'rgba(0,0,0,0.25)';\n dropShadows.push(`${x}px ${y}px ${blur}px ${spread}px ${color}`);\n break;\n \n case 'INNER_SHADOW':\n const ix = effect.offset?.x || 0;\n const iy = effect.offset?.y || 0;\n const iblur = effect.radius || 0;\n const ispread = effect.spread || 0;\n const icolor = effect.color ? this.colorToCSS(effect.color) : 'rgba(0,0,0,0.25)';\n innerShadows.push(`inset ${ix}px ${iy}px ${iblur}px ${ispread}px ${icolor}`);\n break;\n \n case 'LAYER_BLUR':\n layerBlur = effect.radius || 0;\n break;\n \n case 'BACKGROUND_BLUR':\n backgroundBlur = effect.radius || 0;\n break;\n }\n });\n \n // Combine all shadows into box-shadow\n const allShadows = [...innerShadows, ...dropShadows];\n if (allShadows.length > 0) {\n // Check if we already have stroke shadows\n if (css.boxShadow) {\n css.boxShadow = `${css.boxShadow}, ${allShadows.join(', ')}`;\n } else {\n css.boxShadow = allShadows.join(', ');\n }\n }\n \n // Apply blur effects\n if (layerBlur !== undefined || backgroundBlur !== undefined) {\n const filters: string[] = [];\n if (layerBlur !== undefined) {\n filters.push(`blur(${layerBlur}px)`);\n }\n if (backgroundBlur !== undefined) {\n // backdrop-filter for background blur\n css.backdropFilter = `blur(${backgroundBlur}px)`;\n }\n if (filters.length > 0) {\n css.filter = filters.join(' ');\n }\n }\n }\n\n return css;\n }\n\n private analyzeSemanticRole(node: FigmaNode, context: ProcessingContext): SemanticRole | undefined {\n const name = node.name.toLowerCase();\n \n // Enhanced button detection with states\n if (this.isButton(node, name)) {\n return { \n type: 'button', \n purpose: 'interactive',\n variant: this.detectButtonVariant(node, name),\n state: this.detectComponentState(node, name)\n };\n }\n \n // Enhanced input detection with field types\n if (this.isInput(node, name)) {\n return { \n type: 'input', \n purpose: 'data-entry',\n inputType: this.detectInputType(node, name),\n required: name.includes('required') || name.includes('*')\n };\n }\n \n // Navigation and menu detection\n if (this.isNavigation(node, name, context)) {\n return { \n type: 'navigation', \n purpose: 'navigation',\n level: this.detectNavigationLevel(node, context)\n };\n }\n \n // Enhanced text content with semantic hierarchy\n if (node.type === 'TEXT') {\n const hierarchy = this.detectTextHierarchy(node);\n const contentType = this.detectContentType(node, name);\n return { \n type: 'text', \n hierarchy,\n contentType,\n textAlign: this.detectTextAlignment(node)\n };\n }\n \n // List detection\n if (this.isList(node, name, context)) {\n return {\n type: 'list',\n purpose: 'content',\n listType: this.detectListType(node, name),\n itemCount: this.countListItems(node)\n };\n }\n \n // Grid detection\n if (this.isGrid(node, name, context)) {\n return {\n type: 'grid',\n purpose: 'layout',\n gridStructure: this.analyzeGridStructure(node),\n responsive: this.detectResponsiveBehavior(node)\n };\n }\n \n // Card component detection\n if (this.isCard(node, name, context)) {\n return {\n type: 'card',\n purpose: 'content',\n cardType: this.detectCardType(node, name),\n hasActions: this.hasCardActions(node)\n };\n }\n \n // Container with layout analysis\n if (node.type === 'FRAME' && node.children && node.children.length > 0) {\n const layoutPattern = this.detectLayoutPattern(node);\n return { \n type: 'container', \n purpose: 'layout',\n layoutPattern,\n semantic: this.detectContainerSemantic(node, name)\n };\n }\n \n // Image with enhanced detection\n if (this.isImage(node, name)) {\n return {\n type: 'image',\n purpose: 'visual',\n imageType: this.detectImageType(node, name),\n hasCaption: this.hasImageCaption(node, context)\n };\n }\n \n return undefined;\n }\n\n // Enhanced helper methods for semantic analysis\n private isButton(node: FigmaNode, name: string): boolean {\n return name.includes('button') || \n name.includes('btn') || \n name.includes('cta') ||\n (node.type === 'FRAME' && this.hasButtonCharacteristics(node));\n }\n\n private hasButtonCharacteristics(node: FigmaNode): boolean {\n // Check for button-like styling: rounded corners, solid background, centered text\n const hasRoundedCorners = Boolean(node.cornerRadius && node.cornerRadius > 0);\n const hasSolidBackground = Boolean(node.fills && node.fills.some(fill => fill.type === 'SOLID'));\n const hasClickableSize = Boolean(node.absoluteBoundingBox && \n node.absoluteBoundingBox.width >= 60 && node.absoluteBoundingBox.height >= 32);\n const hasTextChild = Boolean(node.children && node.children.some(child => child.type === 'TEXT'));\n \n return hasRoundedCorners && hasSolidBackground && hasClickableSize && hasTextChild;\n }\n\n private detectButtonVariant(_node: FigmaNode, name: string): string {\n if (name.includes('primary')) return 'primary';\n if (name.includes('secondary')) return 'secondary';\n if (name.includes('outline')) return 'outline';\n if (name.includes('ghost')) return 'ghost';\n if (name.includes('link')) return 'link';\n return 'default';\n }\n\n private detectComponentState(_node: FigmaNode, name: string): string {\n if (name.includes('disabled')) return 'disabled';\n if (name.includes('hover')) return 'hover';\n if (name.includes('active')) return 'active';\n if (name.includes('focus')) return 'focus';\n return 'default';\n }\n\n private isInput(_node: FigmaNode, name: string): boolean {\n return name.includes('input') || \n name.includes('field') || \n name.includes('textbox') ||\n name.includes('textarea') ||\n name.includes('select') ||\n name.includes('dropdown');\n }\n\n private detectInputType(_node: FigmaNode, name: string): string {\n if (name.includes('email')) return 'email';\n if (name.includes('password')) return 'password';\n if (name.includes('search')) return 'search';\n if (name.includes('number')) return 'number';\n if (name.includes('tel') || name.includes('phone')) return 'tel';\n if (name.includes('url')) return 'url';\n if (name.includes('date')) return 'date';\n if (name.includes('textarea')) return 'textarea';\n if (name.includes('select') || name.includes('dropdown')) return 'select';\n return 'text';\n }\n\n private isNavigation(node: FigmaNode, name: string, context: ProcessingContext): boolean {\n return name.includes('nav') || \n name.includes('menu') || \n name.includes('header') ||\n name.includes('breadcrumb') ||\n (this.hasNavigationPattern(node) && context.depth <= 2);\n }\n\n private hasNavigationPattern(node: FigmaNode): boolean {\n // Check for horizontal list of links/buttons\n if (node.layoutMode === 'HORIZONTAL' && node.children) {\n const hasMultipleItems = node.children.length >= 2;\n const hasUniformItems = this.hasUniformChildren(node);\n return hasMultipleItems && hasUniformItems;\n }\n return false;\n }\n\n private detectNavigationLevel(_node: FigmaNode, context: ProcessingContext): number {\n if (context.depth === 0) return 1; // Primary navigation\n if (context.depth === 1) return 2; // Secondary navigation\n return 3; // Tertiary navigation\n }\n\n private isList(node: FigmaNode, name: string, _context: ProcessingContext): boolean {\n if (name.includes('list') || name.includes('items')) return true;\n \n // Auto-detect list pattern\n if (node.children && node.children.length >= 2) {\n const hasRepeatingPattern = this.hasRepeatingPattern(node);\n const isVerticalLayout = node.layoutMode === 'VERTICAL' || \n (node.layoutMode === undefined && this.hasVerticalArrangement(node));\n return hasRepeatingPattern && isVerticalLayout;\n }\n return false;\n }\n\n private detectListType(node: FigmaNode, name: string): string {\n if (name.includes('ordered') || name.includes('numbered')) return 'ordered';\n if (name.includes('unordered') || name.includes('bullet')) return 'unordered';\n if (name.includes('description') || name.includes('definition')) return 'description';\n \n // Auto-detect based on content\n if (node.children && node.children.length > 0) {\n const firstChild = node.children[0];\n if (firstChild && this.hasNumbering(firstChild)) return 'ordered';\n if (firstChild && this.hasBulletPoints(firstChild)) return 'unordered';\n }\n return 'unordered';\n }\n\n private countListItems(node: FigmaNode): number {\n if (!node.children) return 0;\n // Count direct children that represent list items\n return node.children.filter(child => \n child.type === 'FRAME' || child.type === 'TEXT'\n ).length;\n }\n\n private isGrid(node: FigmaNode, name: string, _context: ProcessingContext): boolean {\n if (name.includes('grid') || name.includes('gallery')) return true;\n \n // Auto-detect grid pattern\n if (node.children && node.children.length >= 4) {\n const gridStructure = this.analyzeGridStructure(node);\n return gridStructure.columns > 1 && gridStructure.rows > 1;\n }\n return false;\n }\n\n private analyzeGridStructure(node: FigmaNode): { columns: number; rows: number; gap: number } {\n if (!node.children || node.children.length === 0) {\n return { columns: 1, rows: 1, gap: 0 };\n }\n\n // Sort children by position\n const children = [...node.children].sort((a, b) => {\n const aBox = a.absoluteBoundingBox;\n const bBox = b.absoluteBoundingBox;\n if (!aBox || !bBox) return 0;\n \n // Sort by Y first, then by X\n if (Math.abs(aBox.y - bBox.y) < 10) {\n return aBox.x - bBox.x;\n }\n return aBox.y - bBox.y;\n });\n\n // Detect grid dimensions\n if (children.length === 0) return { columns: 1, rows: 1, gap: 0 };\n \n const firstChild = children[0];\n if (!firstChild || !firstChild.absoluteBoundingBox) return { columns: 1, rows: 1, gap: 0 };\n \n // Count items in first row (same Y position)\n const firstRowY = firstChild.absoluteBoundingBox.y;\n const firstRowItems = children.filter(child => \n child.absoluteBoundingBox && \n Math.abs(child.absoluteBoundingBox.y - firstRowY) < 10\n );\n \n const columns = firstRowItems.length;\n const rows = Math.ceil(children.length / columns);\n \n // Calculate gap\n let gap = 0;\n if (firstRowItems.length > 1) {\n const first = firstRowItems[0]?.absoluteBoundingBox;\n const second = firstRowItems[1]?.absoluteBoundingBox;\n if (first && second) {\n gap = second.x - (first.x + first.width);\n }\n }\n \n return { columns, rows, gap: Math.max(0, gap) };\n }\n\n private isCard(node: FigmaNode, name: string, _context: ProcessingContext): boolean {\n if (name.includes('card') || name.includes('tile')) return true;\n \n // Auto-detect card pattern\n return this.hasCardCharacteristics(node);\n }\n\n private hasCardCharacteristics(node: FigmaNode): boolean {\n // Check for card-like styling and content structure\n const hasBackground = Boolean(node.fills && node.fills.length > 0);\n const hasBorder = Boolean(node.strokes && node.strokes.length > 0);\n const hasShadow = Boolean(node.effects && node.effects.some(effect => \n effect.type === 'DROP_SHADOW' && effect.visible !== false\n ));\n const hasStructuredContent = Boolean(node.children && node.children.length >= 2);\n const hasRoundedCorners = Boolean(node.cornerRadius && node.cornerRadius > 0);\n \n return (hasBackground || hasBorder || hasShadow) && \n hasStructuredContent && \n hasRoundedCorners;\n }\n\n private detectCardType(_node: FigmaNode, name: string): string {\n if (name.includes('product')) return 'product';\n if (name.includes('profile') || name.includes('user')) return 'profile';\n if (name.includes('article') || name.includes('blog')) return 'article';\n if (name.includes('feature')) return 'feature';\n return 'content';\n }\n\n private hasCardActions(node: FigmaNode): boolean {\n if (!node.children) return false;\n \n return node.children.some(child => \n this.isButton(child, child.name.toLowerCase()) ||\n child.name.toLowerCase().includes('action') ||\n child.name.toLowerCase().includes('link')\n );\n }\n\n private detectLayoutPattern(node: FigmaNode): string {\n if (!node.children || node.children.length === 0) return 'empty';\n \n // Check for specific layout patterns\n if (node.layoutMode === 'HORIZONTAL') {\n if (this.hasUniformChildren(node)) return 'horizontal-list';\n if (this.hasSidebarPattern(node)) return 'sidebar';\n return 'horizontal-flow';\n }\n \n if (node.layoutMode === 'VERTICAL') {\n if (this.hasHeaderBodyFooterPattern(node)) return 'header-body-footer';\n if (this.hasUniformChildren(node)) return 'vertical-list';\n return 'vertical-flow';\n }\n \n // Auto layout not defined, analyze positioning\n if (this.hasGridPattern(node)) return 'grid';\n if (this.hasAbsolutePositioning(node)) return 'absolute';\n if (this.hasStackingPattern(node)) return 'stack';\n \n return 'free-form';\n }\n\n private detectContainerSemantic(_node: FigmaNode, name: string): string {\n if (name.includes('header')) return 'header';\n if (name.includes('footer')) return 'footer';\n if (name.includes('sidebar')) return 'aside';\n if (name.includes('main') || name.includes('content')) return 'main';\n if (name.includes('section')) return 'section';\n if (name.includes('article')) return 'article';\n if (name.includes('nav')) return 'nav';\n return 'div';\n }\n\n private isImage(node: FigmaNode, name: string): boolean {\n const hasImageFill = node.fills && node.fills.some(fill => fill.type === 'IMAGE');\n const isImageType = node.type === 'RECTANGLE' || node.type === 'ELLIPSE';\n const hasImageName = name.includes('image') || name.includes('photo') || \n name.includes('picture') || name.includes('avatar');\n \n return hasImageFill || (isImageType && hasImageName);\n }\n\n private detectImageType(_node: FigmaNode, name: string): string {\n if (name.includes('avatar') || name.includes('profile')) return 'avatar';\n if (name.includes('logo')) return 'logo';\n if (name.includes('icon')) return 'icon';\n if (name.includes('hero') || name.includes('banner')) return 'hero';\n if (name.includes('thumbnail')) return 'thumbnail';\n return 'content';\n }\n\n private hasImageCaption(_node: FigmaNode, context: ProcessingContext): boolean {\n // Check if there's a text element near this image\n if (!context.parentNode?.children) return false;\n \n const nodeIndex = context.siblingIndex;\n const siblings = context.parentNode.children;\n \n // Check next sibling for caption\n if (nodeIndex + 1 < siblings.length) {\n const nextSibling = siblings[nodeIndex + 1];\n if (!nextSibling) return false;\n \n return nextSibling.type === 'TEXT' && \n nextSibling.name.toLowerCase().includes('caption');\n }\n \n return false;\n }\n\n // Enhanced text hierarchy detection\n private detectTextHierarchy(node: FigmaNode): number {\n if (node.type !== 'TEXT' || !node.style) {\n return 0;\n }\n \n const fontSize = node.style.fontSize;\n // @ts-ignore - fontWeight not in type definition but exists in API\n const fontWeight = node.style.fontWeight || 400;\n const name = node.name.toLowerCase();\n \n // Check explicit heading indicators first\n if (name.includes('h1') || name.includes('heading 1')) return 1;\n if (name.includes('h2') || name.includes('heading 2')) return 2;\n if (name.includes('h3') || name.includes('heading 3')) return 3;\n if (name.includes('h4') || name.includes('heading 4')) return 4;\n if (name.includes('h5') || name.includes('heading 5')) return 5;\n if (name.includes('h6') || name.includes('heading 6')) return 6;\n \n // Semantic name-based detection\n if (name.includes('title') || name.includes('headline')) {\n if (fontSize >= 32) return 1;\n if (fontSize >= 24) return 2;\n return 3;\n }\n \n if (name.includes('subtitle') || name.includes('subheading')) {\n if (fontSize >= 20) return 3;\n return 4;\n }\n \n // Font size and weight based detection\n if (fontSize >= 36 || (fontSize >= 28 && fontWeight >= 600)) return 1;\n if (fontSize >= 28 || (fontSize >= 24 && fontWeight >= 600)) return 2;\n if (fontSize >= 24 || (fontSize >= 20 && fontWeight >= 600)) return 3;\n if (fontSize >= 20 || (fontSize >= 18 && fontWeight >= 600)) return 4;\n if (fontSize >= 18 || (fontSize >= 16 && fontWeight >= 600)) return 5;\n if (fontSize >= 16 && fontWeight >= 600) return 6;\n \n return 0; // Body text\n }\n\n private detectContentType(_node: FigmaNode, name: string): string {\n if (name.includes('title') || name.includes('heading') || name.includes('headline')) return 'title';\n if (name.includes('subtitle') || name.includes('subheading')) return 'subtitle';\n if (name.includes('label')) return 'label';\n if (name.includes('caption')) return 'caption';\n if (name.includes('description') || name.includes('body')) return 'body';\n if (name.includes('quote') || name.includes('blockquote')) return 'quote';\n if (name.includes('code')) return 'code';\n if (name.includes('link')) return 'link';\n if (name.includes('date') || name.includes('time')) return 'datetime';\n if (name.includes('price') || name.includes('cost')) return 'price';\n if (name.includes('tag')) return 'tag';\n return 'text';\n }\n\n private detectTextAlignment(node: FigmaNode): string {\n if (node.type !== 'TEXT' || !node.style) return 'left';\n \n // @ts-ignore - textAlignHorizontal not in type definition but exists in API\n const textAlign = node.style.textAlignHorizontal;\n if (textAlign === 'CENTER') return 'center';\n if (textAlign === 'RIGHT') return 'right';\n if (textAlign === 'JUSTIFIED') return 'justify';\n return 'left';\n }\n\n private generateAccessibilityInfo(node: FigmaNode, context: ProcessingContext): AccessibilityInfo {\n const info: AccessibilityInfo = {};\n \n // Generate aria-label from node name\n if (node.name && !node.name.startsWith('Rectangle') && !node.name.startsWith('Ellipse')) {\n info.ariaLabel = node.name;\n }\n \n // Set focusable for interactive elements\n const semanticRole = this.analyzeSemanticRole(node, context);\n if (semanticRole?.type === 'button' || semanticRole?.type === 'input') {\n info.focusable = true;\n info.tabIndex = 0;\n }\n \n // Set appropriate ARIA roles\n switch (semanticRole?.type) {\n case 'button':\n info.ariaRole = 'button';\n break;\n case 'input':\n info.ariaRole = 'textbox';\n break;\n case 'navigation':\n info.ariaRole = 'navigation';\n break;\n case 'image':\n info.ariaRole = 'img';\n info.altText = node.name;\n break;\n }\n \n return info;\n }\n\n private extractDesignTokens(node: FigmaNode, _context: ProcessingContext): DesignToken[] {\n const tokens: DesignToken[] = [];\n \n // Color tokens\n if (node.fills && node.fills.length > 0) {\n node.fills.forEach((fill, index) => {\n if (fill.type === 'SOLID' && fill.color) {\n tokens.push({\n name: `${node.name}-fill-${index}`,\n value: this.colorToCSS(fill.color),\n type: 'color',\n category: 'background'\n });\n }\n });\n }\n \n // Typography tokens\n if (node.type === 'TEXT' && node.style) {\n tokens.push({\n name: `${node.name}-font-size`,\n value: `${node.style.fontSize}px`,\n type: 'typography',\n category: 'font-size'\n });\n \n tokens.push({\n name: `${node.name}-line-height`,\n value: `${node.style.lineHeightPx}px`,\n type: 'typography',\n category: 'line-height'\n });\n }\n \n // Spacing tokens\n if (node.paddingLeft || node.paddingRight || node.paddingTop || node.paddingBottom) {\n const padding = [\n node.paddingTop || 0,\n node.paddingRight || 0,\n node.paddingBottom || 0,\n node.paddingLeft || 0\n ];\n \n tokens.push({\n name: `${node.name}-padding`,\n value: padding.map(p => `${p}px`).join(' '),\n type: 'spacing',\n category: 'padding'\n });\n }\n \n // Shadow tokens\n if (node.effects && node.effects.length > 0) {\n const dropShadows = node.effects.filter(e => e.type === 'DROP_SHADOW' && e.visible !== false);\n const innerShadows = node.effects.filter(e => e.type === 'INNER_SHADOW' && e.visible !== false);\n \n dropShadows.forEach((shadow, index) => {\n const x = shadow.offset?.x || 0;\n const y = shadow.offset?.y || 0;\n const blur = shadow.radius || 0;\n const spread = shadow.spread || 0;\n const color = shadow.color ? this.colorToCSS(shadow.color) : 'rgba(0,0,0,0.25)';\n \n tokens.push({\n name: `${node.name}-drop-shadow-${index}`,\n value: `${x}px ${y}px ${blur}px ${spread}px ${color}`,\n type: 'shadow',\n category: 'drop-shadow'\n });\n });\n \n innerShadows.forEach((shadow, index) => {\n const x = shadow.offset?.x || 0;\n const y = shadow.offset?.y || 0;\n const blur = shadow.radius || 0;\n const spread = shadow.spread || 0;\n const color = shadow.color ? this.colorToCSS(shadow.color) : 'rgba(0,0,0,0.25)';\n \n tokens.push({\n name: `${node.name}-inner-shadow-${index}`,\n value: `inset ${x}px ${y}px ${blur}px ${spread}px ${color}`,\n type: 'shadow',\n category: 'inner-shadow'\n });\n });\n }\n \n // Border tokens\n if (node.strokes && node.strokes.length > 0 && node.strokeWeight) {\n const stroke = node.strokes[0];\n if (stroke && stroke.type === 'SOLID' && stroke.color) {\n tokens.push({\n name: `${node.name}-border`,\n value: `${node.strokeWeight}px solid ${this.colorToCSS(stroke.color)}`,\n type: 'border',\n category: 'stroke'\n });\n }\n }\n \n // Border radius tokens\n if (node.cornerRadius !== undefined) {\n tokens.push({\n name: `${node.name}-border-radius`,\n value: `${node.cornerRadius}px`,\n type: 'border',\n category: 'radius'\n });\n }\n \n return tokens;\n }\n\n private detectComponentVariants(node: FigmaNode, _context: ProcessingContext): ComponentVariant[] {\n const variants: ComponentVariant[] = [];\n \n if (node.type === 'COMPONENT' || node.type === 'INSTANCE') {\n // Default variant\n variants.push({\n name: 'default',\n properties: {},\n state: 'default'\n });\n \n // Detect hover state based on naming\n if (node.name.toLowerCase().includes('hover')) {\n variants.push({\n name: 'hover',\n properties: { state: 'hover' },\n state: 'hover'\n });\n }\n \n // Detect disabled state\n if (node.name.toLowerCase().includes('disabled')) {\n variants.push({\n name: 'disabled',\n properties: { state: 'disabled' },\n state: 'disabled'\n });\n }\n }\n \n return variants;\n }\n\n private generateInteractionStates(node: FigmaNode, context: ProcessingContext): InteractionState[] {\n const states: InteractionState[] = [];\n \n const semanticRole = this.analyzeSemanticRole(node, context);\n \n if (semanticRole?.type === 'button') {\n states.push({\n trigger: 'hover',\n changes: { opacity: '0.8' },\n animation: { duration: '0.2s', easing: 'ease-in-out' }\n });\n \n states.push({\n trigger: 'click',\n changes: { transform: 'scale(0.95)' },\n animation: { duration: '0.1s', easing: 'ease-in-out' }\n });\n }\n \n if (semanticRole?.type === 'input') {\n states.push({\n trigger: 'focus',\n changes: {\n borderColor: '#007AFF',\n boxShadow: '0 0 0 2px rgba(0, 122, 255, 0.2)'\n },\n animation: { duration: '0.2s', easing: 'ease-in-out' }\n });\n }\n \n return states;\n }\n\n private async applyCustomRules(node: EnhancedFigmaNode, context: ProcessingContext): Promise<void> {\n const applicableRules = this.rules.customRules\n .filter(rule => rule.enabled)\n .filter(rule => this.evaluateRuleCondition(rule.condition, node, context))\n .sort((a, b) => b.priority - a.priority);\n\n for (const rule of applicableRules) {\n try {\n await this.applyRuleAction(rule.action, node, context);\n this.stats.rulesApplied++;\n } catch (error) {\n this.stats.errors.push(`Error applying rule \"${rule.name}\": ${error}`);\n }\n }\n }\n\n private evaluateRuleCondition(condition: RuleCondition, node: EnhancedFigmaNode, _context: ProcessingContext): boolean {\n // Check node type\n if (condition.nodeType) {\n const types = Array.isArray(condition.nodeType) ? condition.nodeType : [condition.nodeType];\n if (!types.includes(node.type)) {\n return false;\n }\n }\n \n // Check node name\n if (condition.nodeName) {\n if (condition.nodeName instanceof RegExp) {\n if (!condition.nodeName.test(node.name)) {\n return false;\n }\n } else {\n if (!node.name.toLowerCase().includes(condition.nodeName.toLowerCase())) {\n return false;\n }\n }\n }\n \n // Check has children\n if (condition.hasChildren !== undefined) {\n const hasChildren = node.children && node.children.length > 0;\n if (condition.hasChildren !== hasChildren) {\n return false;\n }\n }\n \n // Check has text\n if (condition.hasText !== undefined) {\n const hasText = node.type === 'TEXT' || \n (node.children && node.children.some(child => child.type === 'TEXT'));\n if (condition.hasText !== hasText) {\n return false;\n }\n }\n \n // Check is component\n if (condition.isComponent !== undefined) {\n const isComponent = node.type === 'COMPONENT' || node.type === 'INSTANCE';\n if (condition.isComponent !== isComponent) {\n return false;\n }\n }\n \n // Check has auto layout\n if (condition.hasAutoLayout !== undefined) {\n const hasAutoLayout = node.layoutMode !== undefined && node.layoutMode !== 'NONE';\n if (condition.hasAutoLayout !== hasAutoLayout) {\n return false;\n }\n }\n \n // Custom condition\n if (condition.customCondition) {\n return condition.customCondition(node);\n }\n \n return true;\n }\n\n private async applyRuleAction(action: RuleAction, node: EnhancedFigmaNode, context: ProcessingContext): Promise<void> {\n switch (action.type) {\n case 'enhance':\n Object.assign(node, action.parameters);\n break;\n case 'transform':\n // Apply transformations based on parameters\n break;\n case 'custom':\n if (action.customAction) {\n await action.customAction(node, context);\n }\n break;\n }\n }\n\n private applyContextReduction(node: EnhancedFigmaNode): void {\n if (!this.rules.contextReduction.removeRedundantProperties) {\n return;\n }\n\n // Remove empty arrays and objects\n Object.keys(node).forEach(key => {\n const value = (node as any)[key];\n if (Array.isArray(value) && value.length === 0) {\n delete (node as any)[key];\n } else if (typeof value === 'object' && value !== null && Object.keys(value).length === 0) {\n delete (node as any)[key];\n }\n });\n\n // Limit text length\n if (node.characters && node.characters.length > this.rules.contextReduction.limitTextLength) {\n node.characters = node.characters.substring(0, this.rules.contextReduction.limitTextLength) + '...';\n }\n }\n\n // Helper methods\n private colorToCSS(color: FigmaColor): string {\n const r = Math.round(color.r * 255);\n const g = Math.round(color.g * 255);\n const b = Math.round(color.b * 255);\n const a = color.a;\n \n if (a === 1) {\n return `rgb(${r}, ${g}, ${b})`;\n } else {\n return `rgba(${r}, ${g}, ${b}, ${a})`;\n }\n }\n\n private mapAxisAlign(align: string): string {\n switch (align) {\n case 'MIN': return 'flex-start';\n case 'CENTER': return 'center';\n case 'MAX': return 'flex-end';\n case 'SPACE_BETWEEN': return 'space-between';\n default: return 'flex-start';\n }\n }\n\n private detectGridArea(_node: FigmaNode, _context: ProcessingContext): string | undefined {\n // Implementation for detecting CSS Grid area\n return undefined;\n }\n\n private detectFlexOrder(_node: FigmaNode, _context: ProcessingContext): number | undefined {\n // Implementation for detecting flex order\n return undefined;\n }\n\n /**\n * Get processing statistics\n */\n getStats(): ProcessingStats {\n return { ...this.stats };\n }\n\n /**\n * Reset processing statistics\n */\n resetStats(): void {\n this.stats = {\n nodesProcessed: 0,\n nodesEnhanced: 0,\n rulesApplied: 0,\n processingTime: 0,\n errors: [],\n warnings: []\n };\n }\n\n /**\n * Update rules configuration\n */\n updateRules(newRules: Partial<ContextRules>): void {\n this.rules = mergeRules(this.rules, newRules);\n }\n\n /**\n * Process comments and associate them with nodes using coordinate matching\n * Uses bottom-up approach to find the most specific element for each comment\n */\n processCommentsForNode(\n node: EnhancedFigmaNode, \n comments: FigmaComment[]\n ): EnhancedFigmaNodeWithComments {\n // Extract simplified comment instructions with coordinates\n const simplifiedInstructions = this.extractSimplifiedInstructions(comments);\n \n console.error(`[Context Processor] Processing comments for node: ${node.name} (${node.id})`);\n console.error(` Available instructions: ${simplifiedInstructions.length}`);\n \n // COMPREHENSIVE COORDINATE DEBUG: Show all element bounds vs comment coordinates\n if (simplifiedInstructions.length > 0) {\n console.error(`[Context Processor] COORDINATE ANALYSIS:`);\n simplifiedInstructions.forEach((inst, instIndex) => {\n console.error(` Comment ${instIndex}: \"${inst.instruction}\" at (${inst.coordinates.x}, ${inst.coordinates.y})`);\n this.debugElementCoordinates(node, inst.coordinates, ` `);\n });\n }\n \n // Process children first (bottom-up approach) - this is crucial for specificity\n const processedChildren: EnhancedFigmaNodeWithComments[] = [];\n const usedInstructions = new Set<number>(); // Track which instructions have been used\n \n if (node.children) {\n console.error(` Processing ${node.children.length} children first...`);\n for (const child of node.children) {\n const processedChild = this.processCommentsForNode(child as EnhancedFigmaNode, comments);\n processedChildren.push(processedChild);\n \n // Mark instructions used by children - be more aggressive about tracking\n if (processedChild.aiInstructions && processedChild.aiInstructions.length > 0) {\n console.error(` Child ${child.name} claimed ${processedChild.aiInstructions.length} instructions`);\n processedChild.aiInstructions.forEach(inst => {\n const index = simplifiedInstructions.findIndex(si => \n si.instruction === inst.instruction && \n si.coordinates &&\n si.coordinates.x === inst.coordinates!.x && \n si.coordinates.y === inst.coordinates!.y\n );\n if (index >= 0) {\n usedInstructions.add(index);\n console.error(` Marked instruction ${index} as used: \"${inst.instruction}\"`);\n }\n });\n }\n \n // Also recursively mark instructions from grandchildren\n this.markUsedInstructionsRecursively(processedChild, simplifiedInstructions, usedInstructions);\n }\n }\n\n console.error(` Instructions used by children: ${usedInstructions.size}`);\n \n // Only match instructions to this node if they haven't been used by children\n const availableInstructions = simplifiedInstructions.filter((_, index) => !usedInstructions.has(index));\n console.error(` Available instructions for this node: ${availableInstructions.length}`);\n \n // Use ONLY coordinate-based matching - no semantic override\n // Children have already claimed their instructions, now parent gets remaining ones that coordinate-match\n const matchedInstructions = this.matchInstructionsToNode(node, availableInstructions);\n\n // Create enhanced node with comments\n const enhancedNodeWithComments: EnhancedFigmaNodeWithComments = {\n ...node,\n children: processedChildren.length > 0 ? processedChildren : undefined\n };\n\n // Only attach instructions if there are any for this specific node\n if (matchedInstructions.length > 0) {\n console.error(` Attaching ${matchedInstructions.length} instructions to ${node.name}`);\n enhancedNodeWithComments.aiInstructions = matchedInstructions;\n enhancedNodeWithComments.commentInstructions = matchedInstructions;\n }\n\n return enhancedNodeWithComments;\n }\n\n /**\n * Recursively mark instructions as used from all descendants\n */\n private markUsedInstructionsRecursively(\n node: EnhancedFigmaNodeWithComments,\n simplifiedInstructions: Array<{ instruction: string; coordinates: { x: number; y: number }; nodeId?: string }>,\n usedInstructions: Set<number>\n ): void {\n // Mark this node's instructions\n if (node.aiInstructions) {\n node.aiInstructions.forEach(inst => {\n const index = simplifiedInstructions.findIndex(si => \n si.instruction === inst.instruction && \n si.coordinates &&\n si.coordinates.x === inst.coordinates!.x && \n si.coordinates.y === inst.coordinates!.y\n );\n if (index >= 0) {\n usedInstructions.add(index);\n }\n });\n }\n \n // Recursively mark children's instructions\n if (node.children) {\n node.children.forEach(child => {\n this.markUsedInstructionsRecursively(child as EnhancedFigmaNodeWithComments, simplifiedInstructions, usedInstructions);\n });\n }\n }\n\n /**\n * Extract only essential data from comments: instruction + coordinates\n */\n private extractSimplifiedInstructions(comments: FigmaComment[]): Array<{\n instruction: string;\n coordinates: { x: number; y: number };\n nodeId?: string;\n }> {\n console.error(`[Context Processor] FULL COMMENT DATA DEBUG:`);\n comments.forEach((comment, index) => {\n console.error(` Comment ${index}:`);\n console.error(` message: \"${comment.message}\"`);\n console.error(` client_meta:`, JSON.stringify(comment.client_meta, null, 2));\n if (comment.client_meta?.node_offset) {\n console.error(` coordinates: (${comment.client_meta.node_offset.x}, ${comment.client_meta.node_offset.y})`);\n }\n if (comment.client_meta?.node_id) {\n console.error(` target_node_id: ${comment.client_meta.node_id}`);\n }\n });\n\n const instructions = comments\n .filter(comment => comment.message && comment.client_meta?.node_offset)\n .map(comment => ({\n instruction: comment.message,\n coordinates: {\n x: comment.client_meta!.node_offset!.x,\n y: comment.client_meta!.node_offset!.y\n },\n nodeId: comment.client_meta?.node_id\n }));\n\n // Enhanced debug logging for comment coordinates\n console.error(`[Context Processor] Extracted ${instructions.length} instructions with coordinates:`);\n instructions.forEach((inst, index) => {\n console.error(` ${index}: \"${inst.instruction}\" at (${inst.coordinates.x}, ${inst.coordinates.y}) node_id: ${inst.nodeId || 'none'}`);\n });\n\n return instructions;\n }\n\n /**\n * Match instructions to nodes using precise coordinate matching with specificity priority\n */\n private matchInstructionsToNode(\n node: EnhancedFigmaNode, \n instructions: Array<{ instruction: string; coordinates: { x: number; y: number }; nodeId?: string }>\n ): CommentInstruction[] {\n const matchedInstructions: CommentInstruction[] = [];\n\n // Debug logging for this node\n console.error(`[Context Processor] Matching instructions for node: ${node.name} (${node.id})`);\n if (node.absoluteBoundingBox) {\n const bounds = node.absoluteBoundingBox;\n console.error(` Node bounds: x=${bounds.x}, y=${bounds.y}, width=${bounds.width}, height=${bounds.height}`);\n console.error(` Bounds range: x=${bounds.x} to ${bounds.x + bounds.width}, y=${bounds.y} to ${bounds.y + bounds.height}`);\n } else {\n console.error(` Node has no absoluteBoundingBox`);\n }\n\n // Direct node ID match (highest priority)\n const directMatches = instructions.filter(inst => inst.nodeId === node.id);\n console.error(` Direct ID matches: ${directMatches.length}`);\n \n // Precise coordinate-based matching - prioritize smaller, more specific elements\n let coordinateMatches: typeof instructions = [];\n if (node.absoluteBoundingBox && instructions.length > directMatches.length) {\n const bounds = node.absoluteBoundingBox;\n const nodeArea = bounds.width * bounds.height; // Calculate area for specificity\n \n coordinateMatches = instructions.filter(inst => \n !inst.nodeId || inst.nodeId !== node.id // Don't double-count direct matches\n ).filter(inst => {\n const { x, y } = inst.coordinates;\n \n // STRICT coordinate matching only - no fuzzy tolerance for precision\n const exactMatch = x >= bounds.x && \n x <= bounds.x + bounds.width &&\n y >= bounds.y && \n y <= bounds.y + bounds.height;\n \n if (exactMatch) {\n console.error(` EXACT COORDINATE MATCH: \"${inst.instruction}\" at (${x}, ${y}) in node area ${nodeArea}px²`);\n return true;\n }\n \n console.error(` NO MATCH: \"${inst.instruction}\" at (${x}, ${y}) outside bounds`);\n return false;\n });\n }\n console.error(` Precise coordinate matches: ${coordinateMatches.length}`);\n\n // Convert to CommentInstruction format with specificity-based confidence\n [...directMatches, ...coordinateMatches].forEach(match => {\n const instructionType = this.categorizeInstruction(match.instruction);\n let confidence = 1.0;\n \n // Adjust confidence based on match type and node specificity\n if (match.nodeId === node.id) {\n confidence = 1.0; // Direct node ID match\n } else if (node.absoluteBoundingBox) {\n const bounds = node.absoluteBoundingBox;\n const nodeArea = bounds.width * bounds.height;\n \n // Higher confidence for smaller, more specific elements\n // Elements smaller than 10,000px² (100x100) get higher confidence\n if (nodeArea < 10000) {\n confidence = 0.95; // High confidence for small, specific elements like logos/icons\n } else if (nodeArea < 50000) {\n confidence = 0.85; // Medium confidence for medium elements like buttons\n } else {\n confidence = 0.7; // Lower confidence for large containers\n }\n \n console.error(` Assigned confidence ${confidence} based on node area ${nodeArea}px²`);\n } else {\n confidence = 0.5; // Low confidence for nodes without bounds\n }\n \n matchedInstructions.push({\n type: instructionType,\n instruction: match.instruction,\n author: 'Designer',\n timestamp: new Date().toISOString(),\n confidence,\n coordinates: match.coordinates\n });\n });\n\n console.error(` Total matched instructions: ${matchedInstructions.length}`);\n return matchedInstructions;\n }\n\n /**\n * Debug helper: Recursively show all element bounds compared to comment coordinates\n */\n private debugElementCoordinates(node: EnhancedFigmaNode, commentCoords: { x: number; y: number }, indent: string): void {\n if (node.absoluteBoundingBox) {\n const bounds = node.absoluteBoundingBox;\n const isInside = commentCoords.x >= bounds.x && \n commentCoords.x <= bounds.x + bounds.width &&\n commentCoords.y >= bounds.y && \n commentCoords.y <= bounds.y + bounds.height;\n const area = bounds.width * bounds.height;\n \n console.error(`${indent}${node.name} (${node.type}): bounds(${bounds.x},${bounds.y}) to (${bounds.x + bounds.width},${bounds.y + bounds.height}) area=${area}px² ${isInside ? '✓ CONTAINS' : '✗ outside'}`);\n } else {\n console.error(`${indent}${node.name} (${node.type}): NO BOUNDS`);\n }\n \n // Recursively check children\n if (node.children) {\n node.children.forEach(child => {\n this.debugElementCoordinates(child as EnhancedFigmaNode, commentCoords, indent + ' ');\n });\n }\n }\n\n /**\n * Simplified instruction categorization\n */\n private categorizeInstruction(instruction: string): 'animation' | 'interaction' | 'behavior' | 'general' {\n const text = instruction.toLowerCase();\n \n if (text.includes('hover') || text.includes('click') || text.includes('tap') || text.includes('focus')) {\n return 'interaction';\n }\n \n if (text.includes('animate') || text.includes('animation') || text.includes('transition') || \n text.includes('fade') || text.includes('slide') || text.includes('bounce')) {\n return 'animation';\n }\n \n if (text.includes('show') || text.includes('hide') || text.includes('toggle') || \n text.includes('enable') || text.includes('disable')) {\n return 'behavior';\n }\n \n return 'general';\n }\n\n /**\n * Extract all node IDs from a node tree for comment filtering\n */\n extractAllNodeIds(node: FigmaNode): string[] {\n const nodeIds = [node.id];\n \n if (node.children) {\n node.children.forEach(child => {\n nodeIds.push(...this.extractAllNodeIds(child));\n });\n }\n \n return nodeIds;\n }\n\n /**\n * Generate optimized data structure for AI code generation\n * Removes redundant and non-valuable information, focuses on development needs\n */\n optimizeForAI(node: EnhancedFigmaNodeWithComments): any {\n const optimized: any = {\n // Core identification\n id: node.id,\n name: node.name,\n type: node.type,\n };\n\n // Only include valuable properties\n if (node.visible === false) optimized.visible = false; // Only if hidden\n if (node.children && node.children.length > 0) {\n optimized.children = node.children.map(child => \n this.optimizeForAI(child as EnhancedFigmaNodeWithComments)\n );\n }\n\n // AI-friendly positioning (simplified)\n if (node.absoluteBoundingBox) {\n optimized.bounds = {\n x: node.absoluteBoundingBox.x,\n y: node.absoluteBoundingBox.y,\n width: node.absoluteBoundingBox.width,\n height: node.absoluteBoundingBox.height\n };\n }\n\n // Essential CSS properties only\n if (node.cssProperties && Object.keys(node.cssProperties).length > 0) {\n optimized.css = this.cleanCSSProperties(node.cssProperties);\n }\n\n // Detect and mark exportable images/icons\n const imageInfo = this.detectExportableImage(node);\n if (imageInfo) {\n optimized.image = imageInfo;\n // Override type to be more specific\n if (imageInfo.category === 'icon') optimized.type = 'ICON';\n if (imageInfo.category === 'image') optimized.type = 'IMAGE';\n }\n\n // Semantic information for AI\n if (node.semanticRole) {\n optimized.role = node.semanticRole;\n }\n\n // Accessibility information\n if (node.accessibilityInfo && Object.keys(node.accessibilityInfo).length > 0) {\n optimized.accessibility = node.accessibilityInfo;\n }\n\n // Design tokens (valuable for design systems)\n if (node.designTokens && node.designTokens.length > 0) {\n optimized.tokens = node.designTokens.map(token => ({\n name: token.name,\n value: token.value,\n type: token.type\n }));\n }\n\n // Interaction states (valuable for components)\n if (node.interactionStates && node.interactionStates.length > 0) {\n optimized.interactions = node.interactionStates;\n }\n\n // Text content (essential)\n if (node.type === 'TEXT' && node.characters) {\n optimized.text = node.characters;\n \n // Simplified text styling (no complex overrides)\n if (node.style) {\n optimized.textStyle = {\n fontFamily: node.style.fontFamily,\n fontSize: node.style.fontSize,\n lineHeight: node.style.lineHeightPx\n };\n }\n }\n\n // Layout information (essential for containers)\n if (node.layoutMode) {\n optimized.layout = {\n mode: node.layoutMode,\n direction: node.layoutMode === 'HORIZONTAL' ? 'row' : 'column',\n gap: node.itemSpacing,\n padding: this.simplifyPadding(node)\n };\n }\n\n // Component relationships (valuable for understanding structure)\n if (node.componentRelationships) {\n const relationships: any = {};\n \n if (node.componentRelationships.parent) {\n relationships.parent = {\n name: node.componentRelationships.parent.name,\n type: node.componentRelationships.parent.type\n };\n }\n \n if (node.componentRelationships.children && node.componentRelationships.children.length > 0) {\n relationships.children = node.componentRelationships.children.map(child => ({\n name: child.name,\n type: child.type,\n role: child.role\n }));\n }\n \n if (node.componentRelationships.componentInstance) {\n relationships.component = node.componentRelationships.componentInstance;\n }\n \n if (node.componentRelationships.exportable?.hasExportSettings) {\n relationships.exportable = node.componentRelationships.exportable;\n }\n \n if (Object.keys(relationships).length > 0) {\n optimized.relationships = relationships;\n }\n }\n\n // AI Instructions (the most valuable!)\n if (node.aiInstructions && node.aiInstructions.length > 0) {\n optimized.instructions = node.aiInstructions.map(inst => ({\n type: inst.type,\n instruction: inst.instruction,\n confidence: inst.confidence\n }));\n }\n\n return optimized;\n }\n\n /**\n * Clean CSS properties - remove redundant and keep only development-relevant ones\n */\n private cleanCSSProperties(css: any): any {\n const essential = ['width', 'height', 'padding', 'margin', 'gap', \n 'backgroundColor', 'color', 'fontSize', 'fontFamily', \n 'borderRadius', 'border', 'boxShadow', 'display', \n 'flexDirection', 'justifyContent', 'alignItems'];\n \n const cleaned: any = {};\n essential.forEach(prop => {\n if (css[prop] && css[prop] !== '0px' && css[prop] !== 'none') {\n cleaned[prop] = css[prop];\n }\n });\n \n return Object.keys(cleaned).length > 0 ? cleaned : undefined;\n }\n\n /**\n * Simplify padding to a single property\n */\n private simplifyPadding(node: any): string | undefined {\n if (!node.paddingTop && !node.paddingRight && !node.paddingBottom && !node.paddingLeft) {\n return undefined;\n }\n \n const top = node.paddingTop || 0;\n const right = node.paddingRight || 0;\n const bottom = node.paddingBottom || 0;\n const left = node.paddingLeft || 0;\n \n // Check if all sides are equal\n if (top === right && right === bottom && bottom === left) {\n return `${top}px`;\n }\n \n return `${top}px ${right}px ${bottom}px ${left}px`;\n }\n\n /**\n * Detect ONLY nodes with explicit Figma export settings - no heuristics\n * Following Figma API specification: only export what's marked for export\n */\n private detectExportableImage(node: any): { category: 'icon' | 'image' | 'logo'; formats: string[]; isExportable: boolean } | null {\n // ONLY detect nodes with explicit export settings configured in Figma\n const hasExportSettings = node.exportSettings && node.exportSettings.length > 0;\n \n if (!hasExportSettings) {\n return null; // No export settings = not exportable\n }\n \n // Extract actual export formats and scales from Figma export settings\n const formats: string[] = [];\n for (const setting of node.exportSettings) {\n const format = setting.format.toLowerCase();\n let scale = 1;\n \n // Extract scale from constraint according to Figma API\n if (setting.constraint) {\n if (setting.constraint.type === 'SCALE') {\n scale = setting.constraint.value;\n }\n }\n \n // Format with scale info (e.g., \"svg\", \"png@2x\")\n if (format === 'svg' || scale === 1) {\n formats.push(format);\n } else {\n formats.push(`${format}@${scale}x`);\n }\n }\n \n // Determine category based on actual content, not guessing\n let category: 'icon' | 'image' | 'logo' = 'icon';\n \n // Check for actual image fills (photos/raster images)\n const hasImageFill = node.fills && node.fills.some((fill: any) => \n fill.type === 'IMAGE' && fill.imageRef\n );\n \n if (hasImageFill) {\n category = 'image';\n } else {\n // For vector content, check naming for logos vs icons\n const name = node.name.toLowerCase();\n if (name.includes('logo') || name.includes('brand')) {\n category = 'logo';\n } else {\n category = 'icon';\n }\n }\n \n return {\n category,\n formats: [...new Set(formats)], // Remove duplicates\n isExportable: true\n };\n }\n\n // Helper methods for pattern detection\n private hasUniformChildren(node: FigmaNode): boolean {\n if (!node.children || node.children.length < 2) return false;\n \n const firstChild = node.children[0];\n if (!firstChild) return false;\n \n const firstType = firstChild.type;\n const firstSize = firstChild.absoluteBoundingBox;\n \n return node.children.every(child => {\n const childSize = child.absoluteBoundingBox;\n const sameType = child.type === firstType;\n const similarSize = firstSize && childSize && \n Math.abs(firstSize.width - childSize.width) < 20 &&\n Math.abs(firstSize.height - childSize.height) < 20;\n return sameType && similarSize;\n });\n }\n\n private hasRepeatingPattern(node: FigmaNode): boolean {\n if (!node.children || node.children.length < 2) return false;\n \n // Check if children have similar structure\n const firstChild = node.children[0];\n if (!firstChild) return false;\n \n const pattern = this.analyzeNodeStructure(firstChild);\n \n return node.children.slice(1).every(child => \n this.matchesStructurePattern(child, pattern)\n );\n }\n\n private hasVerticalArrangement(node: FigmaNode): boolean {\n if (!node.children || node.children.length < 2) return false;\n \n const sorted = [...node.children].sort((a, b) => {\n const aBox = a.absoluteBoundingBox;\n const bBox = b.absoluteBoundingBox;\n if (!aBox || !bBox) return 0;\n return aBox.y - bBox.y;\n });\n \n // Check if items are arranged vertically with minimal horizontal overlap\n for (let i = 1; i < sorted.length; i++) {\n const prevNode = sorted[i - 1];\n const currNode = sorted[i];\n const prev = prevNode?.absoluteBoundingBox;\n const curr = currNode?.absoluteBoundingBox;\n if (!prev || !curr) continue;\n \n // Items should be below each other, not side by side\n if (curr.y <= prev.y + prev.height * 0.5) return false;\n }\n \n return true;\n }\n\n private hasNumbering(node: FigmaNode): boolean {\n if (node.type !== 'TEXT' || !node.characters) return false;\n \n const text = node.characters.trim();\n const numberPatterns = [\n /^\\d+\\./, // 1. 2. 3.\n /^\\d+\\)/, // 1) 2) 3)\n /^\\(\\d+\\)/, // (1) (2) (3)\n /^[ivx]+\\./i, // i. ii. iii.\n /^[a-z]\\./ // a. b. c.\n ];\n \n return numberPatterns.some(pattern => pattern.test(text));\n }\n\n private hasBulletPoints(node: FigmaNode): boolean {\n if (node.type !== 'TEXT' || !node.characters) return false;\n \n const text = node.characters.trim();\n const bulletPatterns = [\n /^•/, /^·/, /^‣/, /^⁃/, // Unicode bullets\n /^-/, /^\\*/, /^\\+/ // ASCII bullets\n ];\n \n return bulletPatterns.some(pattern => pattern.test(text));\n }\n\n private hasSidebarPattern(node: FigmaNode): boolean {\n if (!node.children || node.children.length !== 2) return false;\n \n const first = node.children[0];\n const second = node.children[1];\n if (!first || !second) return false;\n \n const firstBox = first.absoluteBoundingBox;\n const secondBox = second.absoluteBoundingBox;\n \n if (!firstBox || !secondBox) return false;\n \n // One child should be significantly narrower (sidebar)\n const firstIsNarrow = firstBox.width < secondBox.width * 0.5;\n const secondIsNarrow = secondBox.width < firstBox.width * 0.5;\n \n return firstIsNarrow || secondIsNarrow;\n }\n\n private hasHeaderBodyFooterPattern(node: FigmaNode): boolean {\n if (!node.children || node.children.length < 3) return false;\n \n // Sort by Y position\n const sorted = [...node.children].sort((a, b) => {\n const aBox = a.absoluteBoundingBox;\n const bBox = b.absoluteBoundingBox;\n if (!aBox || !bBox) return 0;\n return aBox.y - bBox.y;\n });\n \n // Check if first and last are smaller than middle sections\n const heights = sorted.map(child => child.absoluteBoundingBox?.height || 0);\n if (heights.length < 3) return false;\n \n const [headerHeight, ...bodyAndFooter] = heights;\n const footerHeight = bodyAndFooter[bodyAndFooter.length - 1];\n const bodyHeights = bodyAndFooter.slice(0, -1);\n const maxBodyHeight = Math.max(...bodyHeights);\n \n return (headerHeight || 0) < maxBodyHeight && (footerHeight || 0) < maxBodyHeight;\n }\n\n private hasGridPattern(node: FigmaNode): boolean {\n if (!node.children || node.children.length < 4) return false;\n \n const structure = this.analyzeGridStructure(node);\n return structure.columns > 1 && structure.rows > 1;\n }\n\n private hasAbsolutePositioning(node: FigmaNode): boolean {\n if (!node.children || node.children.length === 0) return false;\n \n // Check if children overlap significantly (indicating absolute positioning)\n const boxes = node.children\n .map(child => child.absoluteBoundingBox)\n .filter(box => box !== undefined);\n \n if (boxes.length < 2) return false;\n \n for (let i = 0; i < boxes.length; i++) {\n for (let j = i + 1; j < boxes.length; j++) {\n const box1 = boxes[i]!;\n const box2 = boxes[j]!;\n \n const overlapX = Math.max(0, Math.min(box1.x + box1.width, box2.x + box2.width) - Math.max(box1.x, box2.x));\n const overlapY = Math.max(0, Math.min(box1.y + box1.height, box2.y + box2.height) - Math.max(box1.y, box2.y));\n const overlapArea = overlapX * overlapY;\n \n const box1Area = box1.width * box1.height;\n const box2Area = box2.width * box2.height;\n const minArea = Math.min(box1Area, box2Area);\n \n // Significant overlap indicates absolute positioning\n if (overlapArea > minArea * 0.25) {\n return true;\n }\n }\n }\n \n return false;\n }\n\n private hasStackingPattern(node: FigmaNode): boolean {\n if (!node.children || node.children.length < 2) return false;\n \n // Check if elements are stacked with similar positions (like z-index stacking)\n const centerPoints = node.children.map(child => {\n const box = child.absoluteBoundingBox;\n return box ? {\n x: box.x + box.width / 2,\n y: box.y + box.height / 2\n } : null;\n }).filter(point => point !== null);\n \n if (centerPoints.length < 2) return false;\n \n // Check if center points are close together\n const [first, ...rest] = centerPoints;\n const threshold = 50; // pixels\n \n return rest.every(point => \n Math.abs(point!.x - first!.x) < threshold &&\n Math.abs(point!.y - first!.y) < threshold\n );\n }\n\n private analyzeNodeStructure(node: FigmaNode): any {\n return {\n type: node.type,\n hasText: node.type === 'TEXT' || (node.children && node.children.some(child => child.type === 'TEXT')),\n hasImage: node.fills && node.fills.some(fill => fill.type === 'IMAGE'),\n childCount: node.children ? node.children.length : 0,\n hasBackground: node.fills && node.fills.length > 0,\n hasCornerRadius: node.cornerRadius && node.cornerRadius > 0\n };\n }\n\n private matchesStructurePattern(node: FigmaNode, pattern: any): boolean {\n const structure = this.analyzeNodeStructure(node);\n \n return structure.type === pattern.type &&\n structure.hasText === pattern.hasText &&\n structure.hasImage === pattern.hasImage &&\n Math.abs(structure.childCount - pattern.childCount) <= 1 &&\n structure.hasBackground === pattern.hasBackground;\n }\n\n private detectResponsiveBehavior(node: FigmaNode): boolean {\n // Analyze layout properties to detect responsive behavior intentions\n if (!node.children || node.children.length === 0) return false;\n \n // Check for auto layout (indicates responsive design)\n const hasAutoLayout = node.layoutMode !== undefined && node.layoutMode !== 'NONE';\n \n // Check for flexible sizing\n const hasFlexibleSizing = node.children.some(child => \n child.layoutSizingHorizontal === 'FILL' || \n child.layoutSizingVertical === 'FILL' ||\n (child.layoutGrow !== undefined && child.layoutGrow > 0)\n );\n \n // Check for constraints that suggest responsive behavior\n const hasResponsiveConstraints = node.children.some(child =>\n child.constraints?.horizontal === 'LEFT_RIGHT' ||\n child.constraints?.horizontal === 'SCALE' ||\n child.constraints?.vertical === 'TOP_BOTTOM' ||\n child.constraints?.vertical === 'SCALE'\n );\n \n return hasAutoLayout || hasFlexibleSizing || hasResponsiveConstraints;\n }\n\n private generateGradientCSS(fill: any): string {\n if (!fill.gradientStops || fill.gradientStops.length === 0) {\n return '';\n }\n\n const stops = fill.gradientStops\n .map((stop: any) => `${this.colorToCSS(stop.color)} ${Math.round(stop.position * 100)}%`)\n .join(', ');\n\n switch (fill.type) {\n case 'GRADIENT_LINEAR':\n // Calculate angle from gradient handle positions if available\n let angle = '180deg'; // Default to top-to-bottom\n if (fill.gradientHandlePositions && fill.gradientHandlePositions.length >= 2) {\n const start = fill.gradientHandlePositions[0];\n const end = fill.gradientHandlePositions[1];\n if (start && end) {\n const deltaX = end.x - start.x;\n const deltaY = end.y - start.y;\n const angleRad = Math.atan2(deltaY, deltaX);\n angle = `${Math.round((angleRad * 180) / Math.PI + 90)}deg`;\n }\n }\n return `linear-gradient(${angle}, ${stops})`;\n \n case 'GRADIENT_RADIAL':\n return `radial-gradient(circle, ${stops})`;\n \n case 'GRADIENT_ANGULAR':\n return `conic-gradient(${stops})`;\n \n case 'GRADIENT_DIAMOND':\n return `radial-gradient(ellipse, ${stops})`;\n \n default:\n return `linear-gradient(${stops})`;\n }\n }\n\n private mapScaleMode(scaleMode: string): string {\n switch (scaleMode) {\n case 'FILL':\n return 'cover';\n case 'FIT':\n return 'contain';\n case 'TILE':\n return 'repeat';\n case 'STRETCH':\n return '100% 100%';\n default:\n return 'cover';\n }\n }\n} ","import type { ContextRules } from '../rules.js';\nimport { COMMON_OPTIMIZATIONS, BASE_RULES, NAMING_CONVENTIONS } from '../base.js';\n\nexport const reactRules: Partial<ContextRules> = {\n aiOptimization: {\n ...COMMON_OPTIMIZATIONS.WEB_BASE,\n enableComponentVariants: true,\n enableInteractionStates: true\n },\n \n frameworkOptimizations: {\n react: {\n generateJSX: true,\n useStyledComponents: false,\n useTailwindCSS: true,\n generateHooks: true,\n generatePropTypes: false,\n useTypeScript: true,\n componentNamingConvention: NAMING_CONVENTIONS.PASCAL_CASE,\n generateStorybook: false,\n implementationRules: {\n modernPatterns: {\n ...BASE_RULES.MODERN_PATTERNS,\n rule: \"Function components with hooks\",\n checks: [\"useState/useEffect\", \"Custom hooks\", \"No class components\"]\n },\n typeScript: {\n ...BASE_RULES.TYPESCRIPT,\n checks: [\"Interface props\", \"Typed state\", \"Event handlers typed\"]\n },\n performance: {\n ...BASE_RULES.PERFORMANCE,\n rule: \"React.memo + useCallback optimization\",\n checks: [\"React.memo wrapping\", \"useCallback functions\", \"useMemo calculations\"]\n },\n stateManagement: {\n rule: \"Context API for global state\",\n description: \"React Context + useReducer for complex state\",\n priority: \"medium\" as const,\n checks: [\"Context providers\", \"useReducer complex state\", \"Custom hooks\"]\n },\n accessibility: {\n ...BASE_RULES.ACCESSIBILITY,\n checks: [\"ARIA labels\", \"useId hook\", \"Keyboard support\", \"Screen readers\"]\n },\n testing: {\n ...BASE_RULES.TESTING,\n rule: \"React Testing Library approach\",\n checks: [\"User-focused tests\", \"Accessibility queries\", \"Async testing\"]\n },\n react19: {\n rule: \"React 19 features\",\n description: \"Server Components + useOptimistic\",\n priority: \"medium\" as const,\n checks: [\"Server Components\", \"use() hook\", \"useOptimistic UI\"]\n }\n }\n }\n }\n}; ","import type { ContextRules } from '../rules.js';\nimport { COMMON_OPTIMIZATIONS, BASE_RULES, NAMING_CONVENTIONS } from '../base.js';\n\nexport const vueRules: Partial<ContextRules> = {\n aiOptimization: {\n ...COMMON_OPTIMIZATIONS.WEB_BASE,\n enableComponentVariants: true,\n enableInteractionStates: true\n },\n \n frameworkOptimizations: {\n vue: {\n generateSFC: true,\n useCompositionAPI: true,\n useScoped: true,\n generateProps: true,\n useTypeScript: true,\n componentNamingConvention: NAMING_CONVENTIONS.PASCAL_CASE,\n implementationRules: {\n modernPatterns: {\n ...BASE_RULES.MODERN_PATTERNS,\n rule: \"Composition API with script setup\",\n checks: [\"<script setup>\", \"Composables\", \"Reactive refs\"]\n },\n typeScript: {\n ...BASE_RULES.TYPESCRIPT,\n checks: [\"defineProps types\", \"defineEmits types\", \"Reactive types\"]\n },\n performance: {\n ...BASE_RULES.PERFORMANCE,\n rule: \"Reactivity optimization\",\n checks: [\"computed values\", \"watch effects\", \"shallowRef\"]\n },\n stateManagement: {\n rule: \"Pinia for state management\",\n description: \"Pinia stores with composition API\",\n priority: \"medium\" as const,\n checks: [\"Pinia stores\", \"Store composition\", \"Action methods\"]\n },\n accessibility: BASE_RULES.ACCESSIBILITY,\n testing: {\n ...BASE_RULES.TESTING,\n rule: \"Vue Test Utils approach\",\n checks: [\"Component mounting\", \"Props testing\", \"Event testing\"]\n }\n }\n }\n }\n}; ","import type { ContextRules } from '../rules.js';\nimport { COMMON_OPTIMIZATIONS, BASE_RULES, NAMING_CONVENTIONS } from '../base.js';\n\nexport const angularRules: Partial<ContextRules> = {\n aiOptimization: {\n ...COMMON_OPTIMIZATIONS.WEB_BASE,\n enableComponentVariants: true,\n enableInteractionStates: true\n },\n \n frameworkOptimizations: {\n angular: {\n generateComponent: true,\n useStandalone: true,\n generateModule: false,\n useSignals: true,\n useTypeScript: true,\n componentNamingConvention: NAMING_CONVENTIONS.PASCAL_CASE,\n implementationRules: {\n modernPatterns: {\n ...BASE_RULES.MODERN_PATTERNS,\n rule: \"Standalone components with signals\",\n checks: [\"Standalone components\", \"Signals API\", \"Control flow syntax\"]\n },\n typeScript: BASE_RULES.TYPESCRIPT,\n performance: {\n ...BASE_RULES.PERFORMANCE,\n rule: \"OnPush strategy and signals\",\n checks: [\"OnPush change detection\", \"Signals\", \"TrackBy functions\"]\n },\n stateManagement: {\n rule: \"NgRx with signals\",\n description: \"NgRx store with signals integration\",\n priority: \"medium\" as const,\n checks: [\"NgRx store\", \"Effects\", \"Signal store\"]\n },\n accessibility: BASE_RULES.ACCESSIBILITY,\n testing: {\n ...BASE_RULES.TESTING,\n rule: \"Angular testing utilities\",\n checks: [\"TestBed setup\", \"Component testing\", \"Service testing\"]\n }\n }\n }\n }\n}; ","import type { ContextRules } from '../rules.js';\nimport { COMMON_OPTIMIZATIONS, BASE_RULES, NAMING_CONVENTIONS } from '../base.js';\n\nexport const svelteRules: Partial<ContextRules> = {\n aiOptimization: {\n ...COMMON_OPTIMIZATIONS.WEB_BASE,\n enableComponentVariants: true,\n enableInteractionStates: true\n },\n \n frameworkOptimizations: {\n svelte: {\n generateSvelteComponent: true,\n useTypeScript: true,\n useStores: false,\n componentNamingConvention: NAMING_CONVENTIONS.PASCAL_CASE,\n implementationRules: {\n modernPatterns: {\n ...BASE_RULES.MODERN_PATTERNS,\n rule: \"Svelte 5+ with runes\",\n checks: [\"$state runes\", \"Reactive declarations\", \"Component composition\"]\n },\n typeScript: BASE_RULES.TYPESCRIPT,\n performance: {\n ...BASE_RULES.PERFORMANCE,\n rule: \"Svelte compilation optimization\",\n checks: [\"Reactive updates\", \"Tree shaking\", \"Bundle optimization\"]\n },\n stateManagement: {\n rule: \"Svelte stores and context\",\n description: \"Writable stores and context API\",\n priority: \"medium\" as const,\n checks: [\"Writable stores\", \"Context API\", \"Reactive stores\"]\n },\n accessibility: BASE_RULES.ACCESSIBILITY,\n testing: {\n ...BASE_RULES.TESTING,\n rule: \"Svelte testing library\",\n checks: [\"Component testing\", \"Store testing\", \"User interactions\"]\n }\n }\n }\n }\n}; ","import type { ContextRules } from '../rules.js';\nimport { COMMON_OPTIMIZATIONS } from '../base.js';\n\n// HTML-specific rule templates\nconst CRITICAL_ACCURACY = {\n priority: \"critical\" as const,\n rule: \"Exact Figma fidelity\"\n};\n\nconst HIGH_MODERN = {\n priority: \"high\" as const,\n rule: \"Modern CSS patterns\"\n};\n\nconst MEDIUM_ENHANCEMENT = {\n priority: \"medium\" as const,\n rule: \"UI enhancements\"\n};\n\nexport const htmlRules: Partial<ContextRules> = {\n aiOptimization: {\n ...COMMON_OPTIMIZATIONS.WEB_BASE,\n enableComponentVariants: false,\n enableInteractionStates: true,\n enableDesignTokens: true\n },\n \n frameworkOptimizations: {\n html: {\n generateSemanticHTML: true,\n useCSS: true,\n useTailwindCSS: true,\n generateAccessibleMarkup: true,\n useModernCSS: true,\n implementationRules: {\n // CRITICAL: Figma Fidelity\n metadataFidelity: {\n ...CRITICAL_ACCURACY,\n description: \"Apply exact Figma values: padding, margins, fonts, colors, dimensions\",\n checks: [\"Exact padding\", \"Exact margins\", \"Exact font-sizes\", \"Exact colors\", \"Exact dimensions\"]\n },\n typographyPrecision: {\n ...CRITICAL_ACCURACY,\n description: \"Exact typography with CSS variables\",\n checks: [\"Exact font-size\", \"Exact line-height\", \"Exact letter-spacing\", \"CSS variables\"]\n },\n colorAccuracy: {\n ...CRITICAL_ACCURACY,\n description: \"Exact colors with CSS custom properties\",\n checks: [\"Exact hex/rgba\", \"CSS variables\", \"Consistent system\"]\n },\n\n // CRITICAL: CSS Variables System\n cssVariables: {\n ...CRITICAL_ACCURACY,\n rule: \"CSS custom properties system\",\n description: \"Systematic design tokens with semantic naming\",\n checks: [\n \"Color tokens: --color-primary, --text-primary, --bg-surface\",\n \"Typography: --font-size-*, --line-height-*\", \n \"Spacing: --space-xs/sm/md/lg, --radius-sm/md/lg\",\n \"Effects: --shadow-sm/md/lg, semantic naming\"\n ]\n },\n\n // HIGH: Layout & Structure \n flexibleContainers: {\n ...HIGH_MODERN,\n description: \"Flexible layouts: children 100% width, containers max-width\",\n checks: [\"Children 100% width\", \"Container max-width\", \"Flex: 1 patterns\"]\n },\n semanticHTML: {\n ...HIGH_MODERN,\n description: \"Semantic HTML5 + BEM methodology\",\n checks: [\"<section>/<article>/<header>\", \"BEM: block__element--modifier\", \"Accessibility\"]\n },\n responsiveDefault: {\n ...HIGH_MODERN,\n description: \"Mobile-first responsive with CSS variables\",\n checks: [\"Mobile-first\", \"Breakpoint variables\", \"Responsive tokens\"]\n },\n modernCSS: {\n ...HIGH_MODERN,\n description: \"CSS Grid, Flexbox, logical properties, container queries\",\n checks: [\"CSS Grid 2D\", \"Flexbox 1D\", \"Logical properties\", \"Container queries\"]\n },\n marginConflicts: {\n ...HIGH_MODERN,\n description: \"Clean spacing: zero margins on flex children, container gaps\",\n checks: [\"Zero flex margins\", \"Container gaps\", \"Clean spacing\"]\n },\n noInlineStyles: {\n ...HIGH_MODERN,\n description: \"External CSS only, class-based styling\",\n checks: [\"External CSS\", \"Class names\", \"No inline styles\", \"Maintainable\"]\n },\n\n // MEDIUM: Enhancements\n borderTechnique: {\n ...MEDIUM_ENHANCEMENT,\n description: \"box-shadow: 0 0 0 1px for pixel-perfect borders\",\n checks: [\"Box-shadow borders\", \"Consistent rendering\", \"Pixel-perfect\"]\n },\n animationIntegration: {\n ...MEDIUM_ENHANCEMENT,\n description: \"Hover effects and transitions with CSS variables\",\n checks: [\"CSS variable transitions\", \"Hover effects\", \"Consistent timing\"]\n },\n\n // CRITICAL: Validation\n validationChecklist: {\n ...CRITICAL_ACCURACY,\n rule: \"Quality assurance checklist\",\n description: \"Verify fidelity, responsiveness, and modern practices\",\n checks: [\n \"✓ Dimensions match Figma exactly\",\n \"✓ Colors use CSS variables with exact values\", \n \"✓ Typography exact + CSS variables in :root\",\n \"✓ Responsive: mobile/tablet/desktop\",\n \"✓ Container containment, no overflow\",\n \"✓ Semantic HTML + accessibility\",\n \"✓ Hover/animations work + external CSS\",\n \"✓ BEM methodology + modern CSS features\"\n ]\n }\n }\n }\n }\n}; ","import type { ContextRules } from '../rules.js';\nimport { COMMON_OPTIMIZATIONS, BASE_RULES, NAMING_CONVENTIONS } from '../base.js';\n\nexport const swiftuiRules: Partial<ContextRules> = {\n aiOptimization: {\n ...COMMON_OPTIMIZATIONS.MOBILE_BASE,\n enableCSSGeneration: false\n },\n \n frameworkOptimizations: {\n swiftui: {\n generateViews: true,\n useViewBuilder: true,\n generateModifiers: true,\n useObservableObject: true,\n useStateManagement: true,\n generatePreviewProvider: true,\n useEnvironmentObjects: false,\n componentNamingConvention: NAMING_CONVENTIONS.PASCAL_CASE,\n generateSFSymbols: true,\n useNativeColors: true,\n generateAdaptiveLayouts: true,\n useAsyncImage: true,\n generateNavigationViews: true,\n useToolbarModifiers: true,\n generateAnimations: true,\n useGeometryReader: false,\n generateDarkModeSupport: true,\n useTabViews: true,\n generateListViews: true,\n useScrollViews: true,\n generateFormViews: true,\n implementationRules: {\n modernPatterns: {\n ...BASE_RULES.MODERN_PATTERNS,\n rule: \"SwiftUI 5.0+ patterns\",\n checks: [\"@State/@Observable\", \"ViewBuilder\", \"Modifiers\"]\n },\n stateManagement: {\n rule: \"SwiftUI state management\",\n description: \"@State, @Binding, @Observable for state\",\n priority: \"critical\" as const,\n checks: [\"@State local\", \"@Binding shared\", \"@Observable data\"]\n },\n layout: {\n rule: \"Adaptive layout system\",\n description: \"HStack/VStack, LazyGrid, adaptive sizing\",\n priority: \"high\" as const,\n checks: [\"Flexible layouts\", \"Device adaptation\", \"Safe areas\"]\n },\n navigation: {\n rule: \"Modern navigation patterns\",\n description: \"NavigationStack, TabView, Sheet presentation\",\n priority: \"high\" as const,\n checks: [\"NavigationStack\", \"Programmatic navigation\", \"Modal presentation\"]\n },\n accessibility: {\n ...BASE_RULES.ACCESSIBILITY,\n checks: [\"VoiceOver support\", \"Dynamic Type\", \"Accessibility modifiers\"]\n },\n performance: {\n ...BASE_RULES.PERFORMANCE,\n rule: \"SwiftUI performance optimization\",\n checks: [\"LazyLoading\", \"Identity tracking\", \"View updates\"]\n },\n testing: {\n ...BASE_RULES.TESTING,\n rule: \"SwiftUI testing strategy\",\n checks: [\"Preview testing\", \"UI tests\", \"Unit tests\"]\n }\n }\n }\n }\n}; ","import type { ContextRules } from '../rules.js';\nimport { COMMON_OPTIMIZATIONS, BASE_RULES, NAMING_CONVENTIONS } from '../base.js';\n\nexport const uikitRules: Partial<ContextRules> = {\n aiOptimization: {\n ...COMMON_OPTIMIZATIONS.MOBILE_BASE,\n enableCSSGeneration: false\n },\n \n frameworkOptimizations: {\n uikit: {\n generateViewControllers: true,\n useStoryboards: false,\n useProgrammaticLayout: true,\n useAutoLayout: true,\n generateXIBFiles: false,\n useStackViews: true,\n generateConstraints: true,\n useSwiftUIInterop: true,\n componentNamingConvention: NAMING_CONVENTIONS.PASCAL_CASE,\n generateDelegatePatterns: true,\n useModernConcurrency: true,\n generateAccessibilitySupport: true,\n implementationRules: {\n modernPatterns: {\n ...BASE_RULES.MODERN_PATTERNS,\n rule: \"Modern UIKit with Swift concurrency\",\n checks: [\"async/await\", \"@MainActor\", \"Structured concurrency\"]\n },\n programmaticLayout: {\n rule: \"Programmatic Auto Layout\",\n description: \"NSLayoutConstraint and UIStackView patterns\",\n priority: \"critical\" as const,\n checks: [\"Auto Layout\", \"UIStackView\", \"Constraint activation\"]\n },\n swiftuiInterop: {\n rule: \"SwiftUI-UIKit integration\",\n description: \"UIHostingController and UIViewRepresentable\",\n priority: \"high\" as const,\n checks: [\"UIHostingController\", \"UIViewRepresentable\", \"Coordinator pattern\"]\n },\n delegatePatterns: {\n rule: \"Modern delegate patterns\",\n description: \"Protocol-oriented delegates with weak references\",\n priority: \"high\" as const,\n checks: [\"Weak delegates\", \"Protocol design\", \"Table view patterns\"]\n },\n accessibility: {\n ...BASE_RULES.ACCESSIBILITY,\n checks: [\"VoiceOver\", \"Dynamic Type\", \"Accessibility traits\", \"Custom actions\"]\n },\n performance: {\n ...BASE_RULES.PERFORMANCE,\n rule: \"UIKit performance optimization\",\n checks: [\"Table prefetching\", \"Image caching\", \"Memory management\"]\n },\n testing: {\n ...BASE_RULES.TESTING,\n rule: \"UIKit testing strategy\",\n checks: [\"XCTest\", \"UI testing\", \"Mock delegates\"]\n }\n }\n }\n }\n}; ","import type { ContextRules } from '../rules.js';\nimport { COMMON_OPTIMIZATIONS, BASE_RULES, NAMING_CONVENTIONS } from '../base.js';\n\nexport const electronRules: Partial<ContextRules> = {\n aiOptimization: {\n ...COMMON_OPTIMIZATIONS.DESKTOP_BASE,\n enableCSSGeneration: true,\n enableResponsiveBreakpoints: true\n },\n \n frameworkOptimizations: {\n electron: {\n generateMainProcess: true,\n generateRendererProcess: true,\n useIPC: true,\n useWebSecurity: true,\n generateMenus: true,\n useNativeDialogs: true,\n generateUpdater: true,\n useContextIsolation: true,\n componentNamingConvention: NAMING_CONVENTIONS.CAMEL_CASE,\n generateNotifications: true,\n useCrashReporter: false,\n generateTrayIcon: false,\n useProtocolHandlers: false,\n implementationRules: {\n modernPatterns: {\n ...BASE_RULES.MODERN_PATTERNS,\n rule: \"Main/Renderer process separation\",\n checks: [\"Context isolation\", \"Preload scripts\", \"Secure IPC\"]\n },\n security: {\n rule: \"Electron security best practices\",\n description: \"Context isolation, CSP, and secure defaults\",\n priority: \"critical\" as const,\n checks: [\"Context isolation\", \"Node integration disabled\", \"CSP headers\"]\n },\n ipcCommunication: {\n rule: \"Secure IPC patterns\",\n description: \"Type-safe IPC with proper validation\",\n priority: \"high\" as const,\n checks: [\"Typed IPC channels\", \"Input validation\", \"Error handling\"]\n },\n nativeIntegration: {\n rule: \"Native OS integration\",\n description: \"Menus, notifications, and system dialogs\",\n priority: \"medium\" as const,\n checks: [\"Application menus\", \"System notifications\", \"File dialogs\"]\n },\n performance: {\n ...BASE_RULES.PERFORMANCE,\n checks: [\"Memory management\", \"Process optimization\", \"Resource loading\"]\n },\n testing: {\n ...BASE_RULES.TESTING,\n rule: \"Electron testing strategy\",\n checks: [\"Spectron tests\", \"Unit tests\", \"Main process tests\"]\n }\n }\n }\n }\n}; ","import type { ContextRules } from '../rules.js';\nimport { COMMON_OPTIMIZATIONS, BASE_RULES, NAMING_CONVENTIONS } from '../base.js';\n\nexport const tauriRules: Partial<ContextRules> = {\n aiOptimization: {\n ...COMMON_OPTIMIZATIONS.DESKTOP_BASE,\n enableCSSGeneration: true,\n enableResponsiveBreakpoints: false\n },\n \n frameworkOptimizations: {\n tauri: {\n generateRustBackend: true,\n generateWebFrontend: true,\n useSystemWebView: true,\n generateCommands: true,\n useEventSystem: true,\n generatePlugins: false,\n useSidecar: false,\n componentNamingConvention: NAMING_CONVENTIONS.SNAKE_CASE,\n generateUpdater: true,\n useFilesystem: true,\n generateNotifications: true,\n useSystemTray: false,\n generateMenus: true,\n implementationRules: {\n modernPatterns: {\n ...BASE_RULES.MODERN_PATTERNS,\n rule: \"Rust backend with web frontend\",\n checks: [\"Tauri commands\", \"System WebView\", \"Rust/JS interop\"]\n },\n security: {\n rule: \"WebView security configuration\",\n description: \"Secure WebView with CSP and allowlist\",\n priority: \"critical\" as const,\n checks: [\"Content Security Policy\", \"API allowlist\", \"Secure contexts\"]\n },\n communication: {\n rule: \"Frontend-backend communication\",\n description: \"Tauri invoke API and event system\",\n priority: \"high\" as const,\n checks: [\"Invoke API\", \"Event system\", \"Type-safe commands\"]\n },\n nativeIntegration: {\n rule: \"Native OS integration\",\n description: \"Tauri plugins for OS functionality\",\n priority: \"medium\" as const,\n checks: [\"Filesystem access\", \"Notifications\", \"System integration\"]\n },\n performance: {\n ...BASE_RULES.PERFORMANCE,\n rule: \"Bundle optimization\",\n checks: [\"System WebView\", \"Rust performance\", \"Small bundles\"]\n },\n testing: {\n ...BASE_RULES.TESTING,\n rule: \"Tauri testing strategy\",\n checks: [\"Rust unit tests\", \"WebView tests\", \"Integration tests\"]\n }\n }\n }\n }\n}; ","import type { ContextRules } from '../rules.js';\nimport { COMMON_OPTIMIZATIONS, BASE_RULES, NAMING_CONVENTIONS } from '../base.js';\n\nexport const nwjsRules: Partial<ContextRules> = {\n aiOptimization: {\n ...COMMON_OPTIMIZATIONS.DESKTOP_BASE,\n enableCSSGeneration: true,\n enableResponsiveBreakpoints: false\n },\n \n frameworkOptimizations: {\n nwjs: {\n generateNodeBackend: true,\n generateWebFrontend: true,\n useChromiumAPI: true,\n generateMenus: true,\n useNativeModules: true,\n generateManifest: true,\n useClipboard: true,\n componentNamingConvention: NAMING_CONVENTIONS.CAMEL_CASE,\n generateFileAccess: true,\n useShell: true,\n generateScreenCapture: false,\n useTrayIcon: false,\n implementationRules: {\n modernPatterns: {\n ...BASE_RULES.MODERN_PATTERNS,\n rule: \"Unified Node.js and DOM context\",\n checks: [\"Node.js modules in browser\", \"Direct file system access\", \"Chromium APIs\"]\n },\n manifestConfiguration: {\n rule: \"Package.json manifest configuration\",\n description: \"App properties and window settings\",\n priority: \"critical\" as const,\n checks: [\"package.json setup\", \"Window configuration\", \"App permissions\"]\n },\n nodeIntegration: {\n rule: \"Node.js API integration\",\n description: \"Direct Node.js module access in web pages\",\n priority: \"high\" as const,\n checks: [\"require() in browser\", \"File system APIs\", \"OS modules\"]\n },\n chromiumFeatures: {\n rule: \"Chromium-specific features\",\n description: \"Native browser capabilities and DevTools\",\n priority: \"high\" as const,\n checks: [\"DevTools access\", \"Window management\", \"Native dialogs\"]\n },\n nativeIntegration: {\n rule: \"Native system integration\",\n description: \"Menus, clipboard, and shell access\",\n priority: \"medium\" as const,\n checks: [\"Native menus\", \"Clipboard API\", \"Shell commands\"]\n },\n performance: {\n ...BASE_RULES.PERFORMANCE,\n rule: \"NW.js performance optimization\",\n checks: [\"Package optimization\", \"Memory management\", \"Startup performance\"]\n },\n testing: {\n ...BASE_RULES.TESTING,\n rule: \"NW.js testing strategy\",\n checks: [\"Node.js testing\", \"Browser testing\", \"Integration tests\"]\n }\n }\n }\n }\n}; ","import { reactRules } from './react.js';\nimport { vueRules } from './vue.js';\nimport { angularRules } from './angular.js';\nimport { svelteRules } from './svelte.js';\nimport { htmlRules } from './html.js';\nimport { swiftuiRules } from './swiftui.js';\nimport { uikitRules } from './uikit.js';\nimport { electronRules } from './electron.js';\nimport { tauriRules } from './tauri.js';\nimport { nwjsRules } from './nwjs.js';\nimport type { ContextRules } from '../rules.js';\n\nexport type Framework = 'react' | 'vue' | 'angular' | 'svelte' | 'html' | 'swiftui' | 'uikit' | 'electron' | 'tauri' | 'nwjs';\n\nexport const frameworks: Record<Framework, Partial<ContextRules>> = {\n react: reactRules,\n vue: vueRules,\n angular: angularRules,\n svelte: svelteRules,\n html: htmlRules,\n swiftui: swiftuiRules,\n uikit: uikitRules,\n electron: electronRules,\n tauri: tauriRules,\n nwjs: nwjsRules\n} as const;\n\nexport const frameworkDescriptions = {\n react: {\n name: 'React',\n description: 'Modern React with TypeScript, functional components, and hooks',\n features: ['Components', 'TypeScript', 'Hooks', 'CSS Modules']\n },\n vue: {\n name: 'Vue 3',\n description: 'Vue 3 with Composition API and TypeScript',\n features: ['Components', 'Composition API', 'TypeScript', 'Scoped Styles']\n },\n angular: {\n name: 'Angular',\n description: 'Angular with TypeScript and component architecture',\n features: ['Components', 'TypeScript', 'Services', 'Angular CLI']\n },\n svelte: {\n name: 'Svelte',\n description: 'Svelte with TypeScript and reactive statements',\n features: ['Components', 'TypeScript', 'Reactive', 'Scoped Styles']\n },\n html: {\n name: 'HTML/CSS/JS',\n description: 'Vanilla HTML, CSS, and JavaScript - no framework',\n features: ['Semantic HTML', 'Pure CSS', 'Vanilla JS', 'Accessibility']\n },\n swiftui: {\n name: 'SwiftUI',\n description: 'Apple\\'s declarative UI framework for iOS, macOS, watchOS, tvOS',\n features: ['Declarative', 'Swift', 'Cross-Apple Platform', 'Live Previews']\n },\n uikit: {\n name: 'UIKit',\n description: 'Traditional Apple UI framework with programmatic and Storyboard support',\n features: ['Imperative', 'Objective-C/Swift', 'Mature', 'SwiftUI Interop']\n },\n electron: {\n name: 'Electron',\n description: 'Cross-platform desktop apps with web technologies',\n features: ['Chromium', 'Node.js', 'Cross-Platform', 'Large Ecosystem']\n },\n tauri: {\n name: 'Tauri',\n description: 'Lightweight desktop apps with Rust backend and web frontend',\n features: ['System WebView', 'Rust Backend', 'Small Bundles', 'Secure']\n },\n nwjs: {\n name: 'NW.js',\n description: 'Node.js and Chromium combined for desktop applications',\n features: ['Node.js', 'Chromium', 'Direct DOM Access', 'Cross-Platform']\n }\n} as const;\n\nexport function getFrameworkRules(framework: Framework) {\n return frameworks[framework];\n}\n\nexport function getAvailableFrameworks() {\n return Object.keys(frameworks) as Framework[];\n}\n\nexport function isValidFramework(framework: string): framework is Framework {\n return framework in frameworks;\n} "],"mappings":";;;AAAA,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS;AAClB,SAAS,eAAe;AACxB,OAAO,YAAY;AACnB,OAAO,WAAW;AAClB,OAAOA,WAAU;AACjB,OAAOC,SAAQ;;;ACbf,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,SAAS,YAAY;AAG9B,IAAM,aAAa,cAAc,YAAY,GAAG;AAChD,IAAM,YAAY,QAAQ,UAAU;AAGpC,SAAS,aAAqB;AAC5B,MAAI;AACF,UAAM,kBAAkB,KAAK,WAAW,MAAM,cAAc;AAC5D,UAAM,cAAc,KAAK,MAAM,aAAa,iBAAiB,MAAM,CAAC;AACpE,WAAO,YAAY;AAAA,EACrB,SAAS,OAAO;AACd,YAAQ,MAAM,4CAA4C,KAAK;AAC/D,WAAO;AAAA,EACT;AACF;AAEO,IAAM,UAAU,WAAW;;;ACpBlC,OAAO,WAA6C;AACpD,OAAO,eAAe;AACtB,OAAO,YAAY;AACnB,OAAO,YAAY;AACnB,OAAO,QAAQ;AACf,YAAY,YAAY;AACxB,OAAO,UAAU;AACjB,OAAO,QAAQ;AAqCR,IAAM,gBAAN,cAA4B,MAAM;AAAA,EACvC,YACE,SACO,QACA,MACA,SACP;AACA,UAAM,OAAO;AAJN;AACA;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,kBAA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