@atomixstudio/mcp 1.0.15 → 1.0.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/types.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/fetch.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/sync.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/diff.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/rules.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/formats/css.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/formats/scss.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/formats/less.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/formats/json.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/formats/ts.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/formats/js.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/formats/swift.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/formats/kotlin.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/formats/dart.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/response.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/tokens.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/config.ts"],"sourcesContent":["/**\n * Atomix MCP Server - User Design System Mode\n * \n * A minimal MCP server that serves design tokens from a user's\n * Atomix Design System via the public API.\n * \n * Usage:\n * npx @atomixstudio/mcp --ds-id <id> [--api-key <key>]\n * \n * Tools:\n * - getToken: Get a specific token by path\n * - listTokens: List tokens in a category\n * - searchTokens: Search for tokens by name or value\n * - validateUsage: Check if a value follows the design system\n * - getAIToolRules: Generate AI coding rules for this design system\n * - exportMCPConfig: Generate MCP configuration files\n * - getSetupInstructions: Get setup guide for AI tools\n * - syncTokens: Sync tokens to a local file\n * \n * @see https://atomixstudio.eu\n */\n\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n ListResourcesRequestSchema,\n ReadResourceRequestSchema,\n ListPromptsRequestSchema,\n GetPromptRequestSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\n\n// Import from core library\nimport {\n fetchDesignSystem,\n getTokenByPath,\n flattenTokens,\n searchTokens,\n getTokenStats,\n syncTokens as coreSyncTokens,\n compareDesignSystems,\n generateCSSOutput,\n generateSCSSOutput,\n generateLessOutput,\n generateJSONOutput,\n generateTSOutput,\n generateJSOutput,\n generateSwiftOutput,\n generateKotlinOutput,\n generateDartOutput,\n diffTokens,\n formatSyncResponse,\n detectGovernanceChangesByFoundation,\n syncRulesFiles,\n type DesignSystemData,\n type OutputFormat,\n type RulesFileResult,\n type DiffResult,\n} from \"@atomixstudio/sync-core\";\nimport * as path from \"path\";\nimport * as fs from \"fs\";\n\n// ============================================\n// CLI ARGUMENTS (for MCP server configuration)\n// ============================================\n\nfunction parseArgs(): { dsId: string | null; apiKey: string | null; apiBase: string | null } {\n const args = process.argv.slice(2);\n let dsId: string | null = null;\n let apiKey: string | null = null;\n let apiBase: string | null = null;\n\n for (let i = 0; i < args.length; i++) {\n if (args[i] === \"--ds-id\" && args[i + 1]) {\n dsId = args[i + 1];\n i++;\n } else if (args[i] === \"--api-key\" && args[i + 1]) {\n apiKey = args[i + 1];\n i++;\n } else if (args[i] === \"--api-base\" && args[i + 1]) {\n apiBase = args[i + 1];\n i++;\n }\n }\n\n return { dsId, apiKey, apiBase };\n}\n\nconst cliArgs = parseArgs();\nconst { dsId, apiKey } = cliArgs;\nconst apiBase = cliArgs.apiBase || \"https://atomixstudio.eu\";\n\n// ============================================\n// CACHED DATA (for MCP server)\n// ============================================\n\nlet cachedData: DesignSystemData | null = null;\nlet cachedETag: string | null = null;\nlet lastChangeSummary: string | null = null;\n\n// Store affected tokens from last sync for /refactor command\ninterface LastSyncAffectedTokens {\n modified: Array<{ token: string; oldValue: string; newValue: string }>;\n removed: Array<{ token: string; lastValue: string }>;\n added: string[];\n format: string; // \"css\" | \"scss\" | \"swift\" | \"kotlin\" | \"dart\" etc.\n timestamp: string;\n}\nlet lastSyncAffectedTokens: LastSyncAffectedTokens | null = null;\n\n// Helper to get last change summary (MCP-specific, tracks changes for prompts)\nfunction getLastChangeSummary(): string | null {\n return lastChangeSummary;\n}\n\n// Update change summary when fetching (for MCP prompts)\nasync function updateChangeSummary(freshData: DesignSystemData) {\n if (cachedData) {\n const changes = compareDesignSystems(cachedData, freshData);\n lastChangeSummary = changes.summary;\n if (changes.hasChanges) {\n console.error(`[mcp-user] Design system changes detected:\\n${changes.summary}`);\n }\n }\n}\n\n/** Fetch design system for MCP; uses cache and updates cachedData/cachedETag. */\nasync function fetchDesignSystemForMCP(forceRefresh = false): Promise<DesignSystemData> {\n if (!dsId) throw new Error(\"Missing --ds-id. Usage: npx @atomixstudio/mcp --ds-id <id>\");\n const result = await fetchDesignSystem({\n dsId,\n apiKey: apiKey ?? undefined,\n apiBase: apiBase ?? undefined,\n etag: forceRefresh ? undefined : cachedETag ?? undefined,\n forceRefresh,\n });\n if (result.status === 304 && cachedData) return cachedData;\n if (result.status === 304 || !result.data) throw new Error(\"No design system data (304 or null)\");\n cachedData = result.data;\n cachedETag = result.etag;\n await updateChangeSummary(result.data);\n return result.data;\n}\n\n// ============================================\n// TOKEN UTILITIES\n// ============================================\n\nconst TOKEN_CATEGORIES = [\"colors\", \"typography\", \"spacing\", \"sizing\", \"shadows\", \"radius\", \"borders\", \"motion\", \"zIndex\"] as const;\ntype TokenCategory = typeof TOKEN_CATEGORIES[number];\n\n// Token utilities are imported from core library - no local implementations needed\n\n// ============================================\n// MCP SERVER SETUP\n// ============================================\n\nconst server = new Server(\n {\n name: \"atomix-mcp-user\",\n version: \"1.0.15\",\n },\n {\n capabilities: {\n tools: {},\n resources: {},\n prompts: {},\n },\n }\n);\n\n// ============================================\n// TOOL DEFINITIONS\n// ============================================\n\nserver.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: [\n {\n name: \"getToken\",\n description: \"Get a specific design token by its path. Returns the value and CSS variable name.\",\n inputSchema: {\n type: \"object\",\n properties: {\n path: {\n type: \"string\",\n description: \"Token path in dot notation (e.g., 'colors.brand.primary', 'spacing.scale.md')\",\n },\n },\n required: [\"path\"],\n },\n },\n {\n name: \"listTokens\",\n description: \"List all tokens in a category (colors, typography, spacing, sizing, shadows, radius, borders, motion, zIndex).\",\n inputSchema: {\n type: \"object\",\n properties: {\n category: {\n type: \"string\",\n enum: TOKEN_CATEGORIES,\n description: \"Token category to list\",\n },\n subcategory: {\n type: \"string\",\n description: \"Optional subcategory (e.g., 'brand' for colors, 'scale' for spacing)\",\n },\n },\n required: [\"category\"],\n },\n },\n {\n name: \"searchTokens\",\n description: \"Search for tokens by name or value.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"Search query (matches token paths or values)\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"validateUsage\",\n description: \"Check if a CSS value follows the design system. Detects hardcoded values that should use tokens.\",\n inputSchema: {\n type: \"object\",\n properties: {\n value: {\n type: \"string\",\n description: \"CSS value to validate (e.g., '#ff0000', '16px', 'rgb(0,112,97)')\",\n },\n context: {\n type: \"string\",\n enum: [\"color\", \"spacing\", \"radius\", \"shadow\", \"typography\", \"any\"],\n description: \"Context of the value to help find the right token\",\n },\n },\n required: [\"value\"],\n },\n },\n {\n name: \"getAIToolRules\",\n description: \"Generate design system rules for AI coding tools (Cursor, Copilot, Windsurf, etc.).\",\n inputSchema: {\n type: \"object\",\n properties: {\n tool: {\n type: \"string\",\n enum: [\"cursor\", \"copilot\", \"windsurf\", \"cline\", \"continue\", \"zed\", \"generic\", \"all\"],\n description: \"AI tool to generate rules for. Use 'all' to get rules for all tools.\",\n },\n },\n required: [\"tool\"],\n },\n },\n {\n name: \"exportMCPConfig\",\n description: \"Generate MCP configuration file for AI tools.\",\n inputSchema: {\n type: \"object\",\n properties: {\n tool: {\n type: \"string\",\n enum: [\"cursor\", \"claude-desktop\", \"windsurf\", \"continue\", \"vscode\", \"all\"],\n description: \"AI tool to generate MCP config for.\",\n },\n },\n required: [\"tool\"],\n },\n },\n {\n name: \"getSetupInstructions\",\n description: \"Get detailed setup instructions for a specific AI tool.\",\n inputSchema: {\n type: \"object\",\n properties: {\n tool: {\n type: \"string\",\n enum: [\"cursor\", \"copilot\", \"windsurf\", \"cline\", \"continue\", \"zed\", \"claude-desktop\", \"generic\"],\n description: \"AI tool to get setup instructions for.\",\n },\n },\n required: [\"tool\"],\n },\n },\n {\n name: \"syncTokens\",\n description: \"Sync design tokens to a local file. Safe, never breaks UI - adds new tokens, updates existing values, marks deprecated tokens. Use /refactor to migrate deprecated tokens. WARNING: The output file is completely rewritten - only CSS custom properties (variables) are preserved. Custom CSS rules will be lost. Keep custom CSS in a separate file.\",\n inputSchema: {\n type: \"object\",\n properties: {\n output: {\n type: \"string\",\n description: \"Output file path relative to project root (e.g., './src/tokens.css', './DesignTokens.swift')\",\n },\n format: {\n type: \"string\",\n enum: [\"css\", \"scss\", \"less\", \"json\", \"ts\", \"js\", \"swift\", \"kotlin\", \"dart\"],\n description: \"Output format. WEB: css, scss, less, json, ts, js. NATIVE: swift (iOS), kotlin (Android), dart (Flutter). Default: css\",\n },\n },\n required: [\"output\"],\n },\n },\n {\n name: \"getDependencies\",\n description: \"Get suggested dependencies for this design system (icon package, fonts, SKILL.md, token files). Use with atomix-setup prompt. Optional platform and stack for tailored suggestions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n platform: {\n type: \"string\",\n enum: [\"web\", \"ios\", \"android\"],\n description: \"Target platform (web, ios, android). Optional.\",\n },\n stack: {\n type: \"string\",\n description: \"Stack or framework (e.g. react, vue, next, swift, kotlin). Optional.\",\n },\n },\n required: [],\n },\n },\n ],\n };\n});\n\n// ============================================\n// TOOL HANDLERS\n// ============================================\n\nserver.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n\n try {\n // Force refresh for syncTokens to ensure we get the latest data\n const shouldForceRefresh = name === \"syncTokens\";\n const data = await fetchDesignSystemForMCP(shouldForceRefresh);\n\n switch (name) {\n case \"getToken\": {\n const path = args?.path as string;\n const value = getTokenByPath(data.tokens, path);\n \n if (value === undefined) {\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n error: `Token not found: ${path}`,\n suggestion: \"Use listTokens or searchTokens to find available tokens.\",\n availableCategories: TOKEN_CATEGORIES,\n }, null, 2),\n }],\n };\n }\n\n // Find CSS variable for this path\n const cssVarKey = `--atmx-${path.replace(/\\./g, \"-\")}`;\n const cssVar = data.cssVariables[cssVarKey];\n\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n path,\n value,\n cssVariable: cssVar || `var(${cssVarKey})`,\n usage: `style={{ property: \"var(${cssVarKey})\" }}`,\n }, null, 2),\n }],\n };\n }\n\n case \"listTokens\": {\n const category = args?.category as TokenCategory;\n const subcategory = args?.subcategory as string | undefined;\n \n let tokensToList: unknown = data.tokens[category];\n \n if (subcategory && tokensToList && typeof tokensToList === \"object\") {\n tokensToList = getTokenByPath(tokensToList as Record<string, unknown>, subcategory);\n }\n\n if (!tokensToList) {\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n error: `Category not found: ${category}${subcategory ? `.${subcategory}` : \"\"}`,\n availableCategories: TOKEN_CATEGORIES,\n }, null, 2),\n }],\n };\n }\n\n const flat = flattenTokens(tokensToList);\n \n // Enhance tokens with CSS variable names\n const tokensWithCssVars = flat.map(({ path, value }) => {\n // Construct the full path for CSS variable lookup\n const fullPath = subcategory \n ? `${category}.${subcategory}.${path}` \n : `${category}.${path}`;\n \n // Find CSS variable in cssVariables\n let cssVar: string | undefined;\n \n if (category === \"colors\" && subcategory === \"static.brand\") {\n // Brand colors use pattern: --atmx-color-brand-{key}\n // Path is already just the key (e.g., \"testis\", \"primary\")\n cssVar = data.cssVariables[`--atmx-color-brand-${path}`];\n } else if (category === \"colors\" && subcategory?.startsWith(\"modes.\")) {\n // Mode colors use pattern: --atmx-color-{key}\n // Path is already the semantic key (e.g., \"bg-page\", \"text-primary\")\n cssVar = data.cssVariables[`--atmx-color-${path}`];\n } else {\n // For other tokens, try the standard pattern\n const cssVarKey = `--atmx-${fullPath.replace(/\\./g, \"-\")}`;\n cssVar = data.cssVariables[cssVarKey];\n }\n \n return {\n path: fullPath,\n value,\n cssVariable: cssVar || undefined,\n };\n });\n \n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n category,\n subcategory,\n count: tokensWithCssVars.length,\n tokens: tokensWithCssVars.slice(0, 50), // Limit to 50 for readability\n truncated: tokensWithCssVars.length > 50,\n }, null, 2),\n }],\n };\n }\n\n case \"searchTokens\": {\n const query = args?.query as string;\n const results = searchTokens(data.tokens, query);\n \n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n query,\n count: results.length,\n results: results.slice(0, 30),\n truncated: results.length > 30,\n }, null, 2),\n }],\n };\n }\n\n case \"validateUsage\": {\n const value = args?.value as string;\n const context = (args?.context as string) || \"any\";\n \n // Check if value is a hardcoded color\n const isHexColor = /^#[0-9A-Fa-f]{3,8}$/.test(value);\n const isRgbColor = /^rgb\\(|^rgba\\(|^hsl\\(/.test(value);\n const isPixelValue = /^\\d+px$/.test(value);\n \n if (!isHexColor && !isRgbColor && !isPixelValue) {\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n value,\n valid: true,\n message: \"Value appears to be using tokens or is not a design token value.\",\n }, null, 2),\n }],\n };\n }\n\n // Search for matching tokens\n const matches = searchTokens(data.tokens, value);\n \n if (matches.length > 0) {\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n value,\n valid: false,\n message: \"Hardcoded value detected. Use a token instead.\",\n matchingTokens: matches.slice(0, 5),\n suggestion: `Use var(--atmx-${matches[0].path.replace(/\\./g, \"-\")}) instead of ${value}`,\n }, null, 2),\n }],\n };\n }\n\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n value,\n valid: false,\n message: \"Hardcoded value detected. No exact token match found.\",\n suggestion: `Consider adding this value to the design system or use the closest token.`,\n context,\n }, null, 2),\n }],\n };\n }\n\n case \"getAIToolRules\": {\n const tool = args?.tool as string;\n \n // Fetch rules from the API\n const rulesUrl = `${apiBase}/api/ds/${dsId}/rules?format=${tool === \"all\" ? \"all\" : tool}`;\n console.error(`[getAIToolRules] Fetching: ${rulesUrl}`);\n \n const headers: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (apiKey) headers[\"x-api-key\"] = apiKey;\n \n try {\n const response = await fetch(rulesUrl, { headers });\n console.error(`[getAIToolRules] Response status: ${response.status}`);\n \n if (!response.ok) {\n const errorText = await response.text();\n console.error(`[getAIToolRules] Error response: ${errorText}`);\n throw new Error(`Failed to fetch rules: ${response.status} - ${errorText}`);\n }\n\n const rules = await response.json() as { rules?: string[]; categories?: Record<string, string[]> };\n console.error(`[getAIToolRules] Got ${rules.rules?.length || 0} rules`);\n \n return {\n content: [{\n type: \"text\",\n text: JSON.stringify(rules, null, 2),\n }],\n };\n } catch (fetchError) {\n console.error(`[getAIToolRules] Fetch error:`, fetchError);\n throw fetchError;\n }\n }\n\n case \"exportMCPConfig\": {\n const tool = args?.tool as string;\n \n // Generate MCP config locally\n const serverName = data.meta.name.toLowerCase().replace(/[^a-z0-9]/g, \"-\");\n const npxArgs = [\"@atomixstudio/mcp@latest\"];\n if (dsId) npxArgs.push(\"--ds-id\", dsId);\n if (apiKey) npxArgs.push(\"--api-key\", apiKey);\n\n const config = {\n mcpServers: {\n [serverName]: {\n command: \"npx\",\n args: npxArgs,\n },\n },\n };\n\n const configs: Record<string, { path: string; content: string }> = {\n cursor: { path: \".cursor/mcp.json\", content: JSON.stringify(config, null, 2) },\n \"claude-desktop\": { path: \"claude_desktop_config.json\", content: JSON.stringify(config, null, 2) },\n windsurf: { path: \".windsurf/mcp.json\", content: JSON.stringify(config, null, 2) },\n continue: { path: \".continue/config.json\", content: JSON.stringify({ models: [], mcpServers: [{ name: serverName, command: \"npx\", args: npxArgs }] }, null, 2) },\n vscode: { path: \".vscode/settings.json\", content: JSON.stringify({ \"mcp.servers\": config.mcpServers }, null, 2) },\n };\n\n if (tool === \"all\") {\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n message: \"MCP configurations for all tools\",\n configs: Object.entries(configs).map(([t, c]) => ({\n tool: t,\n path: c.path,\n content: JSON.parse(c.content),\n })),\n }, null, 2),\n }],\n };\n }\n\n const selectedConfig = configs[tool as keyof typeof configs];\n if (!selectedConfig) {\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n error: `Unknown tool: ${tool}`,\n availableTools: Object.keys(configs),\n }, null, 2),\n }],\n };\n }\n\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n tool,\n path: selectedConfig.path,\n content: JSON.parse(selectedConfig.content),\n instructions: `Create the file at ${selectedConfig.path} with the content above, then restart your IDE.`,\n }, null, 2),\n }],\n };\n }\n\n case \"getSetupInstructions\": {\n const tool = args?.tool as string;\n \n const instructions: Record<string, string> = {\n cursor: `# Cursor MCP Setup\n\n1. Create \\`.cursor/mcp.json\\` in your project root\n2. Add the MCP configuration (use exportMCPConfig to get it)\n3. Restart Cursor IDE\n4. Verify by asking: \"What design tokens are available?\"\n\n## File Structure\n\n⚠️ **IMPORTANT**: The \\`tokens.css\\` file (or your specified output file) is **completely rewritten** on each sync.\n\n- ✅ **Preserved**: CSS custom properties (variables) - both design system tokens and custom variables\n- ❌ **Lost**: Regular CSS rules (selectors, classes, media queries, etc.)\n\n**Best Practice**: Keep \\`tokens.css\\` separate from your custom CSS. Use a separate file (e.g., \\`custom.css\\`) for custom styles.`,\n\n copilot: `# Copilot Setup\n\n1. Create a Copilot instructions file in your project (e.g. \\`.github/copilot-instructions.md\\`)\n2. Use getAIToolRules({ tool: \"copilot\" }) to get the content\n3. Enable custom instructions in your editor (e.g. \\`github.copilot.chat.codeGeneration.useInstructionFiles\\`: true in settings)\n\n## File Structure\n\n⚠️ **IMPORTANT**: The \\`tokens.css\\` file (or your specified output file) is **completely rewritten** on each sync.\n\n- ✅ **Preserved**: CSS custom properties (variables) - both design system tokens and custom variables\n- ❌ **Lost**: Regular CSS rules (selectors, classes, media queries, etc.)\n\n**Best Practice**: Keep \\`tokens.css\\` separate from your custom CSS. Use a separate file (e.g., \\`custom.css\\`) for custom styles.`,\n\n windsurf: `# Windsurf Setup\n\n1. Create \\`.windsurf/mcp.json\\` in your project root\n2. Create \\`.windsurfrules\\` with rules from getAIToolRules\n3. Restart Windsurf Editor\n\n## File Structure\n\n⚠️ **IMPORTANT**: The \\`tokens.css\\` file (or your specified output file) is **completely rewritten** on each sync.\n\n- ✅ **Preserved**: CSS custom properties (variables) - both design system tokens and custom variables\n- ❌ **Lost**: Regular CSS rules (selectors, classes, media queries, etc.)\n\n**Best Practice**: Keep \\`tokens.css\\` separate from your custom CSS. Use a separate file (e.g., \\`custom.css\\`) for custom styles.`,\n\n cline: `# Cline Setup\n\n1. Create \\`.clinerules\\` in your project root\n2. Cline auto-detects MCP from .cursor/mcp.json\n\n## File Structure\n\n⚠️ **IMPORTANT**: The \\`tokens.css\\` file (or your specified output file) is **completely rewritten** on each sync.\n\n- ✅ **Preserved**: CSS custom properties (variables) - both design system tokens and custom variables\n- ❌ **Lost**: Regular CSS rules (selectors, classes, media queries, etc.)\n\n**Best Practice**: Keep \\`tokens.css\\` separate from your custom CSS. Use a separate file (e.g., \\`custom.css\\`) for custom styles.`,\n\n continue: `# Continue Setup\n\n1. Create/edit \\`.continue/config.json\\`\n2. Add mcpServers configuration\n3. Restart VS Code\n\n## File Structure\n\n⚠️ **IMPORTANT**: The \\`tokens.css\\` file (or your specified output file) is **completely rewritten** on each sync.\n\n- ✅ **Preserved**: CSS custom properties (variables) - both design system tokens and custom variables\n- ❌ **Lost**: Regular CSS rules (selectors, classes, media queries, etc.)\n\n**Best Practice**: Keep \\`tokens.css\\` separate from your custom CSS. Use a separate file (e.g., \\`custom.css\\`) for custom styles.`,\n\n zed: `# Zed Setup\n\n1. Create \\`.zed/assistant/rules.md\\` in your project\n2. Use getAIToolRules({ tool: \"zed\" }) for content\n\n## File Structure\n\n⚠️ **IMPORTANT**: The \\`tokens.css\\` file (or your specified output file) is **completely rewritten** on each sync.\n\n- ✅ **Preserved**: CSS custom properties (variables) - both design system tokens and custom variables\n- ❌ **Lost**: Regular CSS rules (selectors, classes, media queries, etc.)\n\n**Best Practice**: Keep \\`tokens.css\\` separate from your custom CSS. Use a separate file (e.g., \\`custom.css\\`) for custom styles.`,\n\n \"claude-desktop\": `# Claude Desktop Setup\n\n1. Find your Claude config:\n - macOS: ~/Library/Application Support/Claude/claude_desktop_config.json\n - Windows: %APPDATA%\\\\Claude\\\\claude_desktop_config.json\n2. Add MCP server configuration\n3. Restart Claude Desktop\n\n## File Structure\n\n⚠️ **IMPORTANT**: The \\`tokens.css\\` file (or your specified output file) is **completely rewritten** on each sync.\n\n- ✅ **Preserved**: CSS custom properties (variables) - both design system tokens and custom variables\n- ❌ **Lost**: Regular CSS rules (selectors, classes, media queries, etc.)\n\n**Best Practice**: Keep \\`tokens.css\\` separate from your custom CSS. Use a separate file (e.g., \\`custom.css\\`) for custom styles.`,\n\n generic: `# Generic AI Tool Setup\n\n1. Create AI_GUIDELINES.md in your project root\n2. Use getAIToolRules({ tool: \"generic\" }) for content\n3. Reference in your prompts or context\n\n## File Structure\n\n⚠️ **IMPORTANT**: The \\`tokens.css\\` file (or your specified output file) is **completely rewritten** on each sync.\n\n- ✅ **Preserved**: CSS custom properties (variables) - both design system tokens and custom variables\n- ❌ **Lost**: Regular CSS rules (selectors, classes, media queries, etc.)\n\n**Best Practice**: Keep \\`tokens.css\\` separate from your custom CSS. Use a separate file (e.g., \\`custom.css\\`) for custom styles.`,\n };\n\n const instruction = instructions[tool];\n if (!instruction) {\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n error: `Unknown tool: ${tool}`,\n availableTools: Object.keys(instructions),\n }, null, 2),\n }],\n };\n }\n\n return {\n content: [{\n type: \"text\",\n text: instruction,\n }],\n };\n }\n\n case \"syncTokens\": {\n const output = args?.output as string;\n const format = (args?.format as OutputFormat) || \"css\";\n \n if (!output) {\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({ error: \"Missing required parameter: output\" }, null, 2),\n }],\n };\n }\n\n // Check if file exists first to detect deprecated tokens\n const outputPath = path.resolve(process.cwd(), output);\n const fileExists = fs.existsSync(outputPath);\n \n // Read old file if it exists\n const deprecatedTokens: Map<string, string> = new Map();\n const existingTokens: Map<string, string> = new Map();\n \n if (fileExists && [\"css\", \"scss\", \"less\"].includes(format)) {\n const oldContent = fs.readFileSync(outputPath, \"utf-8\");\n \n // Extract CSS variables with their values from old file\n // Pattern: --var-name: value; (handles both with and without comments)\n // Improved regex: handles comments before variables, supports uppercase/numbers in prefix\n const oldVarPattern = /(?:^|\\n)\\s*(?:\\/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*\\/\\s*)?(--[a-zA-Z0-9-]+):\\s*([^;]+);/gm;\n let match;\n while ((match = oldVarPattern.exec(oldContent)) !== null) {\n const varName = match[1];\n const varValue = match[2].trim();\n \n existingTokens.set(varName, varValue);\n \n // Mark as deprecated if NOT in design system (kept for backward compatibility)\n if (!(varName in data.cssVariables)) {\n deprecatedTokens.set(varName, varValue);\n }\n }\n }\n \n // Always merge: DS tokens + existing custom tokens (deprecated get comment but stay in file)\n const mergedCssVariables = { ...data.cssVariables };\n // Note: deprecated tokens are passed separately to get /* DEPRECATED */ comment\n // but custom tokens not in DS are preserved in the output\n\n // Generate content based on format\n // Get dark mode colors for CSS output\n const darkModeColors = (data.tokens?.colors as Record<string, unknown>)?.modes as { dark?: Record<string, string> } | undefined;\n \n // Use mergedCssVariables for CSS-based formats (supports merge mode)\n // Use data.cssVariables for native formats (merge mode not supported)\n let newContent: string;\n switch (format) {\n case \"css\":\n newContent = generateCSSOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"scss\":\n newContent = generateSCSSOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"less\":\n newContent = generateLessOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"json\":\n newContent = generateJSONOutput(data.tokens);\n break;\n case \"js\":\n newContent = generateJSOutput(data.tokens);\n break;\n case \"ts\":\n newContent = generateTSOutput(data.tokens);\n break;\n case \"swift\":\n newContent = generateSwiftOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"kotlin\":\n newContent = generateKotlinOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"dart\":\n newContent = generateDartOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n default:\n newContent = generateCSSOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n }\n\n // Count tokens\n const tokenCount = Object.keys(mergedCssVariables).length;\n const dsTokenCount = Object.keys(data.cssVariables).length;\n const deprecatedCount = deprecatedTokens.size;\n\n let diffSummary = \"\";\n let changes: Array<{ key: string; old: string; new: string }> = [];\n let diff: DiffResult | undefined;\n\n if (fileExists && [\"css\", \"scss\", \"less\"].includes(format)) {\n const oldContent = fs.readFileSync(outputPath, \"utf-8\");\n diff = diffTokens(oldContent, mergedCssVariables, format as OutputFormat, darkModeColors?.dark);\n \n // Count changes (removed tokens are kept as deprecated, not actually removed)\n const lightChanges = diff.added.length + diff.modified.length;\n const darkChanges = diff.addedDark.length + diff.modifiedDark.length;\n const totalChanges = lightChanges + darkChanges + deprecatedCount;\n \n if (totalChanges === 0) {\n const lastUpdated = data.meta.exportedAt \n ? new Date(data.meta.exportedAt).toLocaleString()\n : \"N/A\";\n return {\n content: [{\n type: \"text\",\n text: `✓ Already up to date!\\n\\nFile: ${output}\\nTokens: ${tokenCount}\\nVersion: ${data.meta.version}\\nLast updated: ${lastUpdated}`,\n }],\n };\n }\n\n changes = [...diff.modified, ...diff.modifiedDark];\n \n // Build summary (deprecated tokens are kept, marked for /refactor)\n const lightSummary = lightChanges > 0 ? `Light: ${diff.modified.length} modified, ${diff.added.length} added` : \"\";\n const darkSummary = darkChanges > 0 ? `Dark: ${diff.modifiedDark.length} modified, ${diff.addedDark.length} added` : \"\";\n const deprecatedSummary = deprecatedCount > 0 ? `${deprecatedCount} deprecated (use /refactor)` : \"\";\n diffSummary = [lightSummary, darkSummary, deprecatedSummary].filter(Boolean).join(\" | \");\n \n // Store affected tokens for /refactor command\n const removedTokensWithValues: Array<{ token: string; lastValue: string }> = [];\n for (const [token, value] of deprecatedTokens.entries()) {\n removedTokensWithValues.push({ token, lastValue: value });\n }\n \n lastSyncAffectedTokens = {\n modified: [...diff.modified, ...diff.modifiedDark].map(m => ({\n token: m.key,\n oldValue: m.old,\n newValue: m.new,\n })),\n removed: removedTokensWithValues,\n added: [...diff.added, ...diff.addedDark],\n format,\n timestamp: new Date().toISOString(),\n };\n }\n\n // Write the file\n const outputDir = path.dirname(outputPath);\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n fs.writeFileSync(outputPath, newContent);\n\n // Sync rules files (default: true, same as core syncTokens)\n // IMPORTANT: Keep rules syncing logic here - don't duplicate in formatter\n // The formatter only formats the response, it doesn't perform operations\n let rulesResults: RulesFileResult[] = [];\n try {\n rulesResults = await syncRulesFiles({\n dsId: dsId!,\n apiKey: apiKey ?? undefined,\n apiBase: apiBase ?? undefined,\n rulesDir: process.cwd(),\n });\n } catch (error) {\n // Rules sync is optional, don't fail the whole operation\n console.error(`[syncTokens] Failed to sync rules: ${error}`);\n }\n\n // Detect which foundations have governance changes\n // IMPORTANT: Use the shared helper from core - don't duplicate logic\n const governanceChanges = cachedData \n ? detectGovernanceChangesByFoundation(cachedData, data)\n : [];\n\n // IMPORTANT: Use the shared formatter from core package\n // This ensures MCP and CLI have identical output format\n // All response formatting logic is centralized in formatSyncResponse()\n // Do NOT build custom response text here - use the formatter instead\n const response = formatSyncResponse({\n data,\n output,\n format,\n dsTokenCount,\n deprecatedCount,\n deprecatedTokens,\n diff,\n changes,\n fileExists,\n rulesResults,\n governanceChanges,\n changeSummary: getLastChangeSummary(),\n hasRefactorRecommendation: !!lastSyncAffectedTokens?.removed.length,\n deprecatedTokenCount: lastSyncAffectedTokens?.removed.length || 0,\n });\n\n\n return {\n content: [{\n type: \"text\",\n text: response,\n }],\n };\n }\n\n case \"getDependencies\": {\n const platform = args?.platform as string | undefined;\n const stack = args?.stack as string | undefined;\n const tokens = data.tokens as Record<string, unknown>;\n const typography = tokens?.typography as Record<string, unknown> | undefined;\n const fontFamily = typography?.fontFamily as Record<string, string> | undefined;\n const fontNames: string[] = [];\n if (fontFamily) {\n for (const key of [\"display\", \"heading\", \"body\"]) {\n const v = fontFamily[key];\n if (typeof v === \"string\" && v && !fontNames.includes(v)) fontNames.push(v);\n }\n }\n const icons = tokens?.icons as { library?: string; libraryPackage?: string; nativePackage?: string } | undefined;\n const ICON_PACKAGES: Record<string, { web: string; native: string }> = {\n lucide: { web: \"lucide-react\", native: \"lucide-react-native\" },\n heroicons: { web: \"@heroicons/react\", native: \"heroicons-react-native\" },\n phosphor: { web: \"phosphor-react\", native: \"phosphor-react-native\" },\n };\n const lib = icons?.library || \"lucide\";\n const iconPkgs = ICON_PACKAGES[lib] || ICON_PACKAGES.lucide;\n const payload = {\n iconLibrary: {\n package: iconPkgs.web,\n nativePackage: iconPkgs.native,\n performanceHint: \"Use individual SVG imports for tree-shaking; avoid loading entire icon libraries or icon fonts.\",\n },\n fonts: {\n families: fontNames,\n performanceHint: \"Implement self-hosted fonts and local @font-face declarations; avoid external CDN links; use font-display: swap.\",\n },\n skill: {\n path: \".cursor/skills/atomix-ds/SKILL.md\",\n content: GENERIC_SKILL_MD,\n },\n tokenFiles: {\n files: [\"tokens.css\", \"tokens.json\"],\n copyInstructions: \"Call the syncTokens MCP tool to create the token file; do not only suggest the user run sync later.\",\n },\n meta: { dsName: data.meta.name, platform: platform ?? undefined, stack: stack ?? undefined },\n };\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify(payload, null, 2),\n }],\n };\n }\n\n default:\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n error: `Unknown tool: ${name}`,\n availableTools: [\"getToken\", \"listTokens\", \"searchTokens\", \"validateUsage\", \"getAIToolRules\", \"exportMCPConfig\", \"getSetupInstructions\", \"syncTokens\", \"getDependencies\"],\n }, null, 2),\n }],\n };\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n let suggestion = \"Check your MCP server configuration.\";\n \n if (errorMessage.includes(\"Missing --ds-id\")) {\n suggestion = \"Add --ds-id <your-design-system-id> to your MCP server configuration.\";\n } else if (errorMessage.includes(\"Failed to fetch\")) {\n const statusMatch = errorMessage.match(/Failed to fetch design system: (\\d+)/);\n if (statusMatch) {\n const status = statusMatch[1];\n if (status === \"404\") {\n suggestion = `Design system ID \"${dsId}\" not found. Verify the ID is correct or the design system has been published.`;\n } else if (status === \"401\" || status === \"403\") {\n suggestion = \"Design system is private. Add --api-key <your-key> to your MCP server configuration.\";\n } else {\n suggestion = `API request failed (${status}). Check your network connection and API base URL (${apiBase}).`;\n }\n } else {\n suggestion = `Failed to connect to API at ${apiBase}. Check your network connection.`;\n }\n }\n \n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n error: errorMessage,\n suggestion,\n configured: {\n dsId: dsId || \"not set\",\n apiBase: apiBase || \"not set\",\n hasApiKey: !!apiKey,\n },\n }, null, 2),\n }],\n isError: true,\n };\n }\n});\n\n// ============================================\n// GENERIC SKILL.MD (coding-platform agnostic)\n// ============================================\n\nconst GENERIC_SKILL_MD = `---\nname: atomix-ds\ndescription: Use this design system when editing UI, design system files, or when the user asks to follow the project's design system. Fetch rules dynamically via MCP.\n---\n\n# Atomix Design System\n\n## When to use\n\n- Editing UI components, pages, or styles\n- Working in design system or token files\n- User asks to follow the project's design system\n\n## How to use\n\n1. Call MCP tool **getAIToolRules** with the tool id that matches your **current AI coding environment**:\n - **cursor** (Cursor IDE)\n - **windsurf** (Windsurf)\n - **copilot** (Copilot)\n - **cline** (Cline)\n - **continue** (Continue)\n - **zed** (Zed)\n - **generic** (other tools)\n\n Example: \\`getAIToolRules({ tool: \"cursor\" })\\` when in Cursor.\n\n2. Alternatively use the **design-system-rules** prompt or the resource \\`atomix://rules/<tool>\\` with the same tool id.\n\n3. Apply the returned rules (tokens, governance) when generating or editing code.\n\n4. Ensure Atomix MCP is configured with the project's \\`--ds-id\\` (config path varies by platform: e.g. \\`.cursor/mcp.json\\`, \\`.windsurf/mcp.json\\`).\n`;\n\n// ============================================\n// RESOURCE HANDLERS\n// ============================================\n\nconst AI_TOOLS = [\"cursor\", \"copilot\", \"windsurf\", \"cline\", \"continue\", \"zed\", \"generic\"] as const;\n\nserver.setRequestHandler(ListResourcesRequestSchema, async () => {\n try {\n await fetchDesignSystemForMCP();\n // Return empty list so resources are hidden in UI; AI can still read atomix://hello and atomix://rules/<tool> via ReadResource.\n return { resources: [] };\n } catch {\n // ds-id missing or fetch failed: return minimal list so Cursor still shows Resources\n return {\n resources: [\n {\n uri: \"atomix://setup\",\n name: \"Configure MCP\",\n description: \"Add --ds-id to your MCP config to load design system resources\",\n mimeType: \"text/markdown\",\n },\n ],\n };\n }\n});\n\nserver.setRequestHandler(ReadResourceRequestSchema, async (request) => {\n const { uri } = request.params;\n\n // Placeholder when ds-id missing or fetch failed\n if (uri === \"atomix://setup\") {\n return {\n contents: [{\n uri,\n mimeType: \"text/markdown\",\n text: `# Configure Atomix MCP\n\nAdd \\`--ds-id <your-design-system-id>\\` to your MCP server config.\n\nExample (\\`.cursor/mcp.json\\`):\n\\`\\`\\`json\n{\n \"mcpServers\": {\n \"atomix\": {\n \"command\": \"npx\",\n \"args\": [\"@atomixstudio/mcp@latest\", \"--ds-id\", \"<your-ds-id>\"]\n }\n }\n}\n\\`\\`\\`\n\nGet your DS ID from: https://atomixstudio.eu/ds/[your-ds-id]`,\n }],\n };\n }\n\n const data = await fetchDesignSystemForMCP();\n const stats = getTokenStats(data);\n\n // Welcome resource\n if (uri === \"atomix://hello\") {\n const welcome = generateWelcomeMessage(data, stats);\n return {\n contents: [{\n uri,\n mimeType: \"text/markdown\",\n text: welcome,\n }],\n };\n }\n\n // Rules resources\n const rulesMatch = uri.match(/^atomix:\\/\\/rules\\/(.+)$/);\n if (rulesMatch) {\n const tool = rulesMatch[1];\n if (!AI_TOOLS.includes(tool as typeof AI_TOOLS[number])) {\n throw new Error(`Unknown tool: ${tool}. Available: ${AI_TOOLS.join(\", \")}`);\n }\n\n // Fetch rules from API\n const rulesUrl = `${apiBase}/api/ds/${dsId}/rules?format=${tool}`;\n const headers: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (apiKey) headers[\"x-api-key\"] = apiKey;\n\n const response = await fetch(rulesUrl, { headers });\n if (!response.ok) {\n throw new Error(`Failed to fetch rules: ${response.status}`);\n }\n\n const rulesData = await response.json() as { content?: string; tool?: string };\n \n return {\n contents: [{\n uri,\n mimeType: \"text/markdown\",\n text: rulesData.content || JSON.stringify(rulesData, null, 2),\n }],\n };\n }\n\n throw new Error(`Unknown resource: ${uri}`);\n});\n\n// ============================================\n// PROMPTS - Auto-suggest hello on connection\n// ============================================\n\nserver.setRequestHandler(ListPromptsRequestSchema, async () => {\n // Essential commands only. -- prefix works across AI coding tools (Cursor, Windsurf, etc.).\n const prompts = [\n { name: \"--hello\", description: \"Get started with this design system - overview, tokens, and tools. Run this first!\" },\n {\n name: \"--setup\",\n description: \"Setup design system in project. Three phases: scan, report and ask, then create only after you approve.\",\n arguments: [\n { name: \"platform\", description: \"Target platform (web, ios, android). Optional.\", required: false },\n { name: \"stack\", description: \"Stack or framework (e.g. react, vue, next, swift, kotlin). Optional.\", required: false },\n ],\n },\n {\n name: \"--rules\",\n description: \"Get the design system governance rules for your AI coding tool\",\n arguments: [\n { name: \"tool\", description: \"AI tool (cursor, copilot, windsurf, cline, continue, zed, generic). Optional.\", required: false },\n ],\n },\n { name: \"--sync\", description: \"Sync tokens to a local file. Safe: adds new, updates existing, marks deprecated. Use /--refactor to migrate.\" },\n { name: \"--refactor\", description: \"Migrate deprecated tokens in codebase. Run after /--sync.\" },\n ];\n\n return { prompts };\n});\n\nserver.setRequestHandler(GetPromptRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n // Map -- prompt names to internal handler names (works across Cursor, Windsurf, etc.)\n const canonicalName =\n name === \"--hello\" ? \"hello\"\n : name === \"--setup\" ? \"atomix-setup\"\n : name === \"--rules\" ? \"design-system-rules\"\n : name === \"--sync\" ? \"sync\"\n : name === \"--refactor\" ? \"refactor\"\n : name;\n\n // Try to fetch design system, but handle gracefully if not configured\n // Force refresh for sync prompt to ensure we get latest data\n const shouldForceRefresh = canonicalName === \"sync\";\n let data: DesignSystemData | null = null;\n let stats: ReturnType<typeof getTokenStats> | null = null;\n \n try {\n data = await fetchDesignSystemForMCP(shouldForceRefresh);\n stats = getTokenStats(data);\n } catch (error) {\n // If design system fetch fails, return helpful error message\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n \n if (errorMessage.includes(\"Missing --ds-id\")) {\n // Missing ds-id configuration\n return {\n description: \"MCP Server Configuration Required\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: `The MCP server isn't configured. To use design system prompts, you need to configure the server with:\n- \\`--ds-id\\`: Your design system ID (required - get it from https://atomixstudio.eu/ds/[your-ds-id])\n- \\`--api-key\\`: Your API key (optional - only needed for private design systems)\n\n**Note:** Most design systems are public and don't require an API key. Only add \\`--api-key\\` if your design system is private.\n\nConfigure the MCP server in your Cursor settings, then restart Cursor.`,\n },\n },\n ],\n };\n } else if (errorMessage.includes(\"Failed to fetch\")) {\n // API fetch failed - show actual error details\n const statusMatch = errorMessage.match(/Failed to fetch design system: (\\d+) (.+)/);\n const status = statusMatch ? statusMatch[1] : \"unknown\";\n const details = statusMatch ? statusMatch[2] : errorMessage;\n \n let helpText = `**Error:** Failed to fetch design system from ${apiBase}/api/ds/${dsId}/tokens\\n\\n`;\n helpText += `**Status:** ${status}\\n`;\n helpText += `**Details:** ${details}\\n\\n`;\n \n if (status === \"404\") {\n helpText += `**Possible causes:**\\n`;\n helpText += `- Design system ID \"${dsId}\" doesn't exist\\n`;\n helpText += `- API base URL \"${apiBase}\" is incorrect\\n`;\n helpText += `- Design system hasn't been published yet\\n\\n`;\n helpText += `**Solution:** Verify the design system ID and API base URL in your MCP server configuration.`;\n } else if (status === \"401\" || status === \"403\") {\n helpText += `**Possible causes:**\\n`;\n helpText += `- Design system is private and requires an API key\\n`;\n helpText += `- API key is invalid or expired\\n\\n`;\n helpText += `**Solution:** Add \\`--api-key <your-key>\\` to your MCP server configuration.`;\n } else {\n helpText += `**Possible causes:**\\n`;\n helpText += `- Network connection issue\\n`;\n helpText += `- API server is down\\n`;\n helpText += `- CORS or firewall blocking the request\\n\\n`;\n helpText += `**Solution:** Check your network connection and verify the API base URL is accessible.`;\n }\n \n return {\n description: \"Design System Fetch Failed\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: helpText,\n },\n },\n ],\n };\n }\n // Re-throw other errors\n throw error;\n }\n\n // Helper to build category prompt with metadata and AI rules\n const buildCategoryPrompt = (category: string, instructions: string): string => {\n const lines: string[] = [];\n \n // Header with DS info\n lines.push(`## Design System Information`);\n lines.push(`- **Name**: ${data!.meta.name}`);\n lines.push(`- **Version**: ${data!.meta.version || \"1.0.0\"}`);\n lines.push(`- **Last Published**: ${data!.meta.exportedAt ? new Date(data!.meta.exportedAt).toLocaleDateString() : \"N/A\"}`);\n lines.push(``);\n \n // AI Rules for this category\n const categoryRules = data!.governance.categories?.[category];\n if (categoryRules && categoryRules.length > 0) {\n lines.push(`## AI Rules for ${category.charAt(0).toUpperCase() + category.slice(1)}`);\n categoryRules.forEach((rule, index) => {\n lines.push(`${index + 1}. ${rule}`);\n });\n lines.push(``);\n }\n \n // Instructions\n lines.push(`## Instructions`);\n lines.push(instructions);\n \n return lines.join(\"\\n\");\n };\n\n switch (canonicalName) {\n case \"hello\": {\n const welcome = generateWelcomeMessage(data, stats);\n const helloInstruction = `You are showing the Atomix design system welcome. You MUST do the following in order:\n\n1. **First** — Copy and draw the ASCII art block exactly as it appears below (the code block with the arrow pattern). Output it verbatim before any other text. Do not summarize, skip, or replace it with a description.\n2. **Then** — Output the rest of the welcome message (markdown) exactly as given.\n\nDo not add any introduction or commentary before the ASCII art. The ASCII art must be the very first thing you output.\n\n---\n${welcome}`;\n return {\n description: `Hello — ${data.meta.name} Design System`,\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: helloInstruction,\n },\n },\n ],\n };\n }\n\n case \"design-system-rules\": {\n const tool = (args?.tool as string) || \"cursor\";\n const rulesUrl = `${apiBase}/api/ds/${dsId}/rules?format=${tool}`;\n const headers: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (apiKey) headers[\"x-api-key\"] = apiKey;\n\n const response = await fetch(rulesUrl, { headers });\n if (!response.ok) {\n throw new Error(`Failed to fetch rules: ${response.status}`);\n }\n\n const rulesData = await response.json() as { content?: string };\n \n return {\n description: `Design system rules for ${tool}`,\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: `Show me the design system rules for ${tool}.`,\n },\n },\n {\n role: \"assistant\" as const,\n content: {\n type: \"text\" as const,\n text: rulesData.content || JSON.stringify(rulesData, null, 2),\n },\n },\n ],\n };\n }\n\n case \"spacing\": {\n const instructions = `List all spacing tokens in a table format. Use the listTokens tool with category \"spacing\" and subcategory \"scale\". Format the response as a markdown table with columns: Token Name | Value | CSS Variable. The Token Name should be in short format (e.g., \"spacing.xs\" instead of \"spacing.scale.xs\").`;\n const response = {\n description: \"List all spacing tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: buildCategoryPrompt(\"spacing\", instructions),\n },\n },\n ],\n };\n\n return response;\n }\n\n case \"radius\": {\n const instructions = `List all border radius tokens in a table format. Use the listTokens tool with category \"radius\" and subcategory \"scale\". Format the response as a markdown table with columns: Token Name | Value | CSS Variable. The Token Name should be in short format (e.g., \"radius.sm\" instead of \"radius.scale.sm\").`;\n return {\n description: \"List all border radius tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: buildCategoryPrompt(\"radius\", instructions),\n },\n },\n ],\n };\n }\n\n case \"color\": {\n const instructions = `List all color tokens in a table format showing both light and dark mode values. \n\nFirst, call listTokens with category \"colors\" and subcategory \"modes.light\" to get light mode colors.\nThen, call listTokens with category \"colors\" and subcategory \"modes.dark\" to get dark mode colors.\nAlso call listTokens with category \"colors\" and subcategory \"static.brand\" to get brand colors.\n\nFormat the response as a markdown table with columns: Token Name | Light Mode Value | Dark Mode Value | CSS Variable.\n\nFor brand colors (from static.brand), show the same value in both Light and Dark columns since brand colors don't change with mode.\nFor semantic colors (from modes.light/modes.dark), match tokens by name and show their respective values.\n\nThe Token Name should be in short format:\n- Brand colors: \"colors.brand.primary\" (not \"colors.static.brand.primary\")\n- Semantic colors: \"colors.bgSurface\" (not \"colors.modes.light.bgSurface\")`;\n return {\n description: \"List all color tokens with light/dark mode\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: buildCategoryPrompt(\"colors\", instructions),\n },\n },\n ],\n };\n }\n\n case \"typography\": {\n const instructions = `List all typography tokens in a table format. Use the listTokens tool with category \"typography\" (no subcategory needed). Format the response as a markdown table with columns: Token Name | Value | CSS Variable. Group tokens by type (fontSize, fontWeight, lineHeight, etc.) with section headers.`;\n return {\n description: \"List all typography tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: buildCategoryPrompt(\"typography\", instructions),\n },\n },\n ],\n };\n }\n\n case \"shadow\": {\n const instructions = `List all shadow/elevation tokens in a table format. Use the listTokens tool with category \"shadows\" and subcategory \"elevation\". Format the response as a markdown table with columns: Token Name | Value | CSS Variable. The Token Name should be in short format (e.g., \"shadows.elevation.md\" is fine as-is).`;\n return {\n description: \"List all shadow/elevation tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: buildCategoryPrompt(\"shadows\", instructions),\n },\n },\n ],\n };\n }\n\n case \"border\": {\n const instructions = `List all border width tokens in a table format. Use the listTokens tool with category \"borders\" and subcategory \"width\". Format the response as a markdown table with columns: Token Name | Value | CSS Variable. The Token Name should be in short format (e.g., \"borders.width.sm\" is fine as-is).`;\n return {\n description: \"List all border width tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: buildCategoryPrompt(\"borders\", instructions),\n },\n },\n ],\n };\n }\n\n case \"sizing\": {\n const instructions = `List all sizing tokens in a table format. Call listTokens twice:\n1. category \"sizing\" and subcategory \"height\" for component heights\n2. category \"sizing\" and subcategory \"icon\" for icon sizes\n\nFormat the response as a markdown table with columns: Token Name | Value | CSS Variable. Group by type (height vs icon) with section headers.`;\n return {\n description: \"List all sizing tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: buildCategoryPrompt(\"sizing\", instructions),\n },\n },\n ],\n };\n }\n\n case \"motion\": {\n const instructions = `List all motion tokens in a table format. Call listTokens twice:\n1. category \"motion\" and subcategory \"duration\" for duration tokens\n2. category \"motion\" and subcategory \"easing\" for easing tokens\n\nFormat the response as a markdown table with columns: Token Name | Value | CSS Variable. Group by type (duration vs easing) with section headers.`;\n return {\n description: \"List all motion tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: buildCategoryPrompt(\"motion\", instructions),\n },\n },\n ],\n };\n }\n\n case \"sync\": {\n // Use defaults - no arguments needed\n const output = (args?.output as string) || \"./tokens.css\";\n const format = (args?.format as string) || \"css\";\n \n \n // MCP prompts return messages that the AI interprets\n // Use a very direct, imperative instruction to call the tool\n const response = {\n description: `Sync design tokens to ${output}`,\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: `Call the syncTokens tool now. Use output=\"${output}\" and format=\"${format}\". Execute immediately - do not search or ask questions.`,\n },\n },\n ],\n };\n \n \n return response;\n }\n\n case \"refactor\": {\n // Check if we have affected tokens from last sync\n if (!lastSyncAffectedTokens) {\n return {\n description: \"Refactor codebase for deprecated tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: `No recent sync data available. Please run \\`/sync\\` first to update your token file, then run \\`/refactor\\` to scan your codebase for deprecated token usage.`,\n },\n },\n ],\n };\n }\n\n // Check if there are any deprecated tokens to refactor\n if (lastSyncAffectedTokens.removed.length === 0) {\n return {\n description: \"Refactor codebase for deprecated tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: `✓ No deprecated tokens found in last sync.\\n\\nYour codebase is up to date! The last sync on ${new Date(lastSyncAffectedTokens.timestamp).toLocaleString()} did not remove any tokens.`,\n },\n },\n ],\n };\n }\n\n // Build the refactor instructions\n const format = lastSyncAffectedTokens.format;\n const isNativeFormat = [\"swift\", \"kotlin\", \"dart\"].includes(format);\n \n // Build search patterns based on format\n let searchPatterns = \"\";\n let fileExtensions = \"\";\n \n if (isNativeFormat) {\n // Native format patterns\n const nativeTokens = lastSyncAffectedTokens.removed.map(r => {\n // Convert CSS var name to native format\n // --atmx-color-brand-primary → colorBrandPrimary (Swift/Dart) or ColorBrandPrimary (Kotlin)\n const withoutPrefix = r.token.replace(/^--atmx-/, \"\");\n const camelCase = withoutPrefix.replace(/-([a-z])/g, (_, c) => c.toUpperCase());\n const pascalCase = camelCase.charAt(0).toUpperCase() + camelCase.slice(1);\n return { css: r.token, camel: camelCase, pascal: pascalCase, lastValue: r.lastValue };\n });\n \n if (format === \"swift\") {\n fileExtensions = \".swift files\";\n searchPatterns = nativeTokens.map(t => ` • \\`DesignTokens.*.${t.camel}\\` (was: ${t.lastValue})`).join(\"\\n\");\n } else if (format === \"kotlin\") {\n fileExtensions = \".kt files\";\n searchPatterns = nativeTokens.map(t => ` • \\`DesignTokens.*.${t.pascal}\\` (was: ${t.lastValue})`).join(\"\\n\");\n } else {\n fileExtensions = \".dart files\";\n searchPatterns = nativeTokens.map(t => ` • \\`DesignTokens.${t.camel}\\` (was: ${t.lastValue})`).join(\"\\n\");\n }\n } else {\n // Web format patterns (CSS, SCSS, Less, etc.)\n fileExtensions = \".tsx, .ts, .jsx, .js, .css, .scss, .less, .vue, .svelte files\";\n searchPatterns = lastSyncAffectedTokens.removed.map(r => \n ` • \\`var(${r.token})\\` or \\`\"${r.token}\"\\` (was: ${r.lastValue})`\n ).join(\"\\n\");\n }\n\n const instructions = `Scan the codebase for deprecated design tokens and help update them.\n\n## Deprecated Tokens (${lastSyncAffectedTokens.removed.length})\n\nThe following tokens have been removed from the design system:\n\n${searchPatterns}\n\n## Instructions\n\n1. **Search** for these patterns in ${fileExtensions}:\n - Skip node_modules, dist, build, .next, .git directories\n - Look for both \\`var(--token)\\` and direct string references\n\n2. **Report findings** in this format:\n \\`\\`\\`\n 📄 path/to/file.tsx\n Line 42: background: var(--atmx-color-deprecated);\n Line 78: const color = \"--atmx-color-deprecated\";\n \\`\\`\\`\n\n3. **After listing all findings**, ask:\n > \"Found X instances of deprecated tokens in Y files. Would you like me to update them?\"\n > \n > For each deprecated token, I'll suggest the closest equivalent from the current design system.\n\n4. **If user confirms**:\n - Show the proposed replacement for each instance\n - Apply changes only after user approves\n - For tokens with no clear replacement, ask user which token to use\n\n## Important\n\n- Do NOT make any changes without explicit user confirmation\n- Show before → after for each change\n- If you can't find a suitable replacement token, ask the user\n\n## Available Token Categories\n\nUse \\`/color\\`, \\`/spacing\\`, \\`/radius\\`, \\`/typography\\`, \\`/shadow\\`, \\`/border\\`, \\`/sizing\\`, \\`/motion\\` to see current tokens if you need to find replacements.`;\n\n return {\n description: \"Refactor codebase for deprecated tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: instructions,\n },\n },\n ],\n };\n }\n\n case \"atomix-setup\": {\n const setupInstructions = `You are running **atomix-setup** (design system setup). Three phases only.\n\n**Rule:** Do not create, write, or modify any file until Phase 3 and only after the user has explicitly approved (e.g. replied \"Yes\", \"Yes for all\", \"Go ahead\"). Creating or modifying files before the user approves is a rule violation.\n\n## Todo list (required)\n\n- **Create a todo list** at the start with items for Phase 1, Phase 2, and Phase 3 (e.g. \"Phase 1: Scan\", \"Phase 2: Report and ask\", \"Phase 3: Create after approval\").\n- Work **step by step**: complete Phase 1, then Phase 2; do not run Phase 3 until the user has replied with approval.\n- Mark todo items completed as you finish each phase. Use this pattern so the user and you can track progress.\n\n## Phase 1 – Scan\n\n- Resolve platform/stack: infer from the project (e.g. package.json, build.gradle, Xcode) or ask the user once: \"Which platform? (e.g. web, Android, iOS)\" and if relevant \"Which stack? (e.g. React, Vue, Next, Swift, Kotlin).\" Do not assume a default.\n- Call MCP tool **getDependencies** with \\`platform\\` and optional \\`stack\\`. If it fails, tell the user: \"Atomix MCP is not connected or design system ID is missing. Configure MCP with --ds-id and try again.\"\n- Scan the repo for what already exists: .cursor/skills/atomix-ds/SKILL.md, a tokens file (e.g. tokens.css or src/tokens.css), icon package from getDependencies, font setup. Do **not** include or check for MCP config; MCP is already configured for this session.\n- **Web:** Scan for any existing CSS (e.g. globals.css, main.css, App.css, index.css, Tailwind entry, framework styles). Note whether at least one CSS file exists.\n- **Native (iOS/Android):** Scan for existing theme or style files (e.g. SwiftUI theme/asset catalog, Android themes.xml/styles.xml, Compose theme). Note whether the project already has a theme or style setup.\n- Build two lists: **Suggested** (from getDependencies minus what exists) and **Already present**. Only include: icon package, fonts, skill (.cursor/skills/atomix-ds/SKILL.md), token files. No MCP.\n- Do not write, create, or add anything in Phase 1.\n\n## Phase 2 – Report and ask for permission\n\n- Reply with: **Suggested:** [list] and **Already present:** [list].\n- Ask exactly once: \"Do you want me to add the suggested items? (Yes for all, or say which ones.)\" (Integration with existing CSS or theme is recommended after Phase 3; new global CSS/theme is only suggested when none exists.)\n- **Stop.** Do not run Phase 3 in this response. Wait for the user to reply.\n\n## Phase 3 – Create or add (only after user approval)\n\n- Run only when the user has said yes (all or specific items).\n- For each approved item:\n - **Skill:** Write the skill content from getDependencies to .cursor/skills/atomix-ds/SKILL.md.\n - **Token file:** Call the **syncTokens** MCP tool with \\`output\\` set to the path (e.g. \"./src/tokens.css\" or \"./tokens.css\"). You must call syncTokens; do not only suggest the user run sync later.\n - **Icon package / fonts:** Add per getDependencies (e.g. install package, add font config). Do not overwrite existing.\n- Report only what you actually created or updated (e.g. \"Added: .cursor/skills/atomix-ds/SKILL.md. Synced: src/tokens.css.\"). Do not claim the token file was added if you did not call syncTokens.\n- **After reporting – styles/theme (per platform):**\n - **Web:** If the project **already has** at least one CSS file: recommend how to integrate Atomix (e.g. import the synced tokens file, use \\`var(--atomix-*)\\` or semantic classes). Do **not** suggest creating a new global CSS. Only if the project has **no** CSS file at all, ask once: \"There are no CSS files yet. Do you want a minimal global CSS (typography + semantic utilities from the design system)?\" and add it only if the user says yes.\n - **iOS/Android:** If the project **already has** theme or style files: recommend how to integrate Atomix tokens (e.g. use synced DesignTokens.swift / Kotlin tokens in existing theme). Do **not** suggest creating a new global theme file. Only if the project has **no** theme/style setup at all, ask once: \"There's no theme/style setup yet. Do you want a minimal token-based theme (colors, typography, spacing from the design system)?\" and add it only if the user says yes.\n\n---\n\nCreate your todo list first, then execute Phase 1 (resolve platform/stack, call getDependencies, scan, build lists). Then Phase 2 (report lists and ask). Do not perform Phase 3 until the user replies.`;\n return {\n description: \"Setup design system in project (atomix-setup). Create todo list; Phase 1 scan, Phase 2 report and ask, Phase 3 create only after user approval.\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: setupInstructions,\n },\n },\n ],\n };\n }\n\n default:\n throw new Error(`Unknown prompt: ${name}`);\n }\n});\n\nfunction generateWelcomeMessage(data: DesignSystemData, stats: ReturnType<typeof getTokenStats>): string {\n const tokenSummary = Object.entries(stats.byCategory)\n .map(([cat, count]) => `${cat}: ${count}`)\n .join(\", \");\n\n const asciiArt = `\n\\`\\`\\`\n ↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘ \n\\`\\`\\`\n`;\n\n return `${asciiArt}\n# Welcome to ${data.meta.name}\n\n## Design System Overview\n\n| Metric | Value |\n|--------|-------|\n| Name | ${data.meta.name} |\n| DS ID | ${dsId} |\n| Total Tokens | ${stats.total} |\n| CSS Variables | ${stats.cssVariables} |\n| Governance Rules | ${stats.governanceRules} |\n| Version | ${data.meta.version || 1} |\n\n### Token breakdown\n\n${tokenSummary}\n\n---\n\n## Essential commands\n\n| Command | What to expect |\n|---------|----------------|\n| **/--hello** | Get started - overview, tokens, and tools. Run this first! |\n| **/--setup** | Setup design system in project. Three phases; creates files only after you approve. |\n| **/--rules** | Governance rules for your AI tool (Cursor, Copilot, Windsurf, etc.). |\n| **/--sync** | Sync tokens to a local file. Safe: adds new, updates existing, marks deprecated. |\n| **/--refactor** | Migrate deprecated tokens in codebase. Run after /--sync. |\n\n**Suggested next step:** Run **/--setup** to set up global styles, icons, fonts, and token files; the AI will list options and ask before adding anything.\n\n---\n\n*Atomix Studio — https://atomixstudio.eu | DS: https://atomixstudio.eu/ds/${dsId}*\n`;\n}\n\n\n// ============================================\n// START SERVER\n// ============================================\n\nasync function startServer() {\n if (!dsId) {\n console.error(\"Error: Missing --ds-id argument\");\n console.error(\"Usage: npx atomix --ds-id <id> [--api-key <key>]\");\n console.error(\"Note: --api-key is optional (only needed for private design systems)\");\n console.error(\"\");\n console.error(\"For sync command: npx atomix sync --help\");\n console.error(\"Get your DS ID from https://atomixstudio.eu/ds/[your-ds-id]\");\n process.exit(1);\n }\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n \n // Log to stderr so it doesn't interfere with MCP protocol on stdout\n console.error(`Atomix MCP Server started for design system: ${dsId}`);\n}\n\n// Start MCP server (no CLI commands - this is MCP-only)\nasync function main() {\n await startServer();\n}\n\nmain().catch((error) => {\n console.error(\"Failed:\", error);\n process.exit(1);\n});\n\n","/**\n * Core Types for Atomix Sync\n * \n * Shared types used across CLI and MCP implementations.\n */\n\nexport interface ExportedTokens {\n tokens: {\n colors: {\n static: { brand: Record<string, string> };\n modes: { light: Record<string, string>; dark: Record<string, string> };\n };\n typography: Record<string, unknown>;\n spacing: { scale: Record<string, string> };\n sizing: { height: Record<string, string>; icon: Record<string, string> };\n shadows: { elevation: Record<string, string> };\n radius: { scale: Record<string, string> };\n borders: { width: Record<string, string> };\n motion: { duration: Record<string, string>; easing: Record<string, string> };\n zIndex: Record<string, number>;\n };\n cssVariables: Record<string, string>;\n governance: {\n rules: string[];\n categories: Record<string, string[]>;\n };\n meta: {\n name: string;\n version: number;\n exportedAt: string;\n };\n}\n\nexport interface DesignSystemData {\n tokens: ExportedTokens[\"tokens\"];\n cssVariables: Record<string, string>;\n governance: ExportedTokens[\"governance\"];\n meta: ExportedTokens[\"meta\"];\n}\n\nexport type OutputFormat = \n | \"css\" | \"scss\" | \"less\" // Web CSS-based\n | \"json\" | \"ts\" | \"js\" // Web JS-based\n | \"swift\" | \"kotlin\" | \"dart\"; // Native mobile\n\nexport interface AtomixConfig {\n dsId: string;\n apiKey?: string;\n apiBase?: string;\n output: string;\n format: OutputFormat;\n // For future codebase scanning\n include?: string[]; // Glob patterns to include\n exclude?: string[]; // Glob patterns to exclude\n}\n\nexport interface SyncOptions {\n dsId: string;\n apiKey?: string;\n apiBase?: string;\n output: string;\n format: OutputFormat;\n yes?: boolean; // Auto-confirm\n rules?: boolean; // Also sync rules files\n rulesDir?: string; // Directory for rules files\n etag?: string; // Cached ETag for conditional requests\n}\n\nexport interface SyncResult {\n success: boolean;\n tokenCount: number;\n deprecatedCount: number;\n etag?: string;\n status?: 200 | 304;\n changes?: DiffResult;\n error?: string;\n}\n\nexport interface DiffResult {\n added: string[];\n modified: Array<{ key: string; old: string; new: string }>;\n removed: string[];\n addedDark: string[];\n modifiedDark: Array<{ key: string; old: string; new: string }>;\n removedDark: string[];\n}\n\nexport interface ChangeSummary {\n hasChanges: boolean;\n versionChanged: boolean;\n timestampChanged: boolean;\n addedTokens: string[];\n removedTokens: string[];\n modifiedTokens: Array<{ token: string; oldValue: string; newValue: string }>;\n governanceChanged: boolean;\n summary: string;\n}\n\nexport interface FetchOptions {\n dsId: string;\n apiKey?: string;\n apiBase?: string;\n etag?: string; // Send If-None-Match header\n forceRefresh?: boolean;\n}\n\nexport interface FetchResult {\n data: DesignSystemData | null; // null if 304 Not Modified\n etag: string;\n status: 200 | 304;\n}\n\n// Default file patterns for codebase scanning\nexport const DEFAULT_INCLUDE = [\n \"**/*.tsx\", // React TypeScript components\n \"**/*.jsx\", // React JavaScript components\n \"**/*.ts\", // TypeScript files\n \"**/*.js\", // JavaScript files\n \"**/*.css\", // CSS stylesheets\n \"**/*.scss\", // SASS files\n \"**/*.less\", // Less files\n \"**/*.vue\", // Vue components\n \"**/*.svelte\", // Svelte components\n \"**/*.astro\", // Astro components\n];\n\nexport const DEFAULT_EXCLUDE = [\n \"node_modules/**\",\n \"dist/**\",\n \"build/**\",\n \".next/**\",\n \".nuxt/**\",\n \".git/**\",\n \"coverage/**\",\n \"**/*.min.js\",\n \"**/*.min.css\",\n \"**/*.d.ts\", // Type definitions\n \"**/*.test.*\", // Test files\n \"**/*.spec.*\", // Spec files\n];\n","/**\n * Fetch Design System Data\n * \n * Handles fetching design system tokens from API with ETag support.\n */\n\nimport type { DesignSystemData, ExportedTokens, FetchOptions, FetchResult, ChangeSummary } from './types.js';\n\n/**\n * Generate ETag from design system metadata\n */\nexport function generateETag(meta: { version: number; updatedAt?: string; exportedAt?: string }): string {\n const ts = meta.updatedAt ?? meta.exportedAt ?? \"\";\n const hash = `${meta.version}-${ts}`;\n return `\"v${hash}\"`; // ETag format: \"v1.0-2024-01-01T00:00:00Z\"\n}\n\n/**\n * Compare two design systems and return change summary\n */\nexport function compareDesignSystems(\n cached: DesignSystemData,\n fresh: DesignSystemData\n): ChangeSummary {\n const changes: ChangeSummary = {\n hasChanges: false,\n versionChanged: false,\n timestampChanged: false,\n addedTokens: [],\n removedTokens: [],\n modifiedTokens: [],\n governanceChanged: false,\n summary: \"\",\n };\n\n // Compare metadata\n if (cached.meta.version !== fresh.meta.version) {\n changes.versionChanged = true;\n changes.hasChanges = true;\n }\n\n if (cached.meta.exportedAt !== fresh.meta.exportedAt) {\n changes.timestampChanged = true;\n changes.hasChanges = true;\n }\n\n // Compare CSS variables (includes all tokens: spacing, typography, colors, etc.)\n const cachedVars = Object.keys(cached.cssVariables);\n const freshVars = Object.keys(fresh.cssVariables);\n\n // Find added tokens (all categories)\n for (const varName of freshVars) {\n if (!(varName in cached.cssVariables)) {\n changes.addedTokens.push(varName);\n changes.hasChanges = true;\n }\n }\n\n // Find removed tokens (all categories)\n for (const varName of cachedVars) {\n if (!(varName in fresh.cssVariables)) {\n changes.removedTokens.push(varName);\n changes.hasChanges = true;\n }\n }\n\n // Find modified tokens (all categories)\n for (const varName of cachedVars) {\n if (varName in fresh.cssVariables) {\n const oldValue = cached.cssVariables[varName];\n const newValue = fresh.cssVariables[varName];\n if (oldValue !== newValue) {\n changes.modifiedTokens.push({\n token: varName,\n oldValue,\n newValue,\n });\n changes.hasChanges = true;\n }\n }\n }\n\n // Compare dark mode colors (stored separately in tokens.colors.modes.dark)\n // These are NOT in cssVariables, so we need to compare them separately\n const cachedDark = (cached.tokens?.colors as Record<string, unknown>)?.modes as { dark?: Record<string, string> } | undefined;\n const freshDark = (fresh.tokens?.colors as Record<string, unknown>)?.modes as { dark?: Record<string, string> } | undefined;\n \n const cachedDarkColors = cachedDark?.dark || {};\n const freshDarkColors = freshDark?.dark || {};\n \n const cachedDarkKeys = Object.keys(cachedDarkColors);\n const freshDarkKeys = Object.keys(freshDarkColors);\n\n // Detect CSS variable prefix from existing cssVariables (fallback to --atmx-color-)\n const firstColorVar = cachedVars.find(v => v.includes(\"-color-\")) || freshVars.find(v => v.includes(\"-color-\"));\n const prefixMatch = firstColorVar?.match(/^(--[a-z]+-color-)/);\n const colorPrefix = prefixMatch ? prefixMatch[1] : \"--atmx-color-\";\n\n // Find added dark mode colors\n for (const key of freshDarkKeys) {\n if (!(key in cachedDarkColors)) {\n const cssVarName = `${colorPrefix}${key}`;\n // Only add if not already in the list (avoid duplicates)\n if (!changes.addedTokens.includes(cssVarName)) {\n changes.addedTokens.push(cssVarName);\n changes.hasChanges = true;\n }\n }\n }\n\n // Find removed dark mode colors\n for (const key of cachedDarkKeys) {\n if (!(key in freshDarkColors)) {\n const cssVarName = `${colorPrefix}${key}`;\n if (!changes.removedTokens.includes(cssVarName)) {\n changes.removedTokens.push(cssVarName);\n changes.hasChanges = true;\n }\n }\n }\n\n // Find modified dark mode colors\n for (const key of cachedDarkKeys) {\n if (key in freshDarkColors) {\n const oldValue = cachedDarkColors[key];\n const newValue = freshDarkColors[key];\n if (oldValue !== newValue) {\n const cssVarName = `${colorPrefix}${key}`;\n // Check if we already have this token in modified list (might be a light mode change too)\n const existingIndex = changes.modifiedTokens.findIndex(m => m.token === cssVarName);\n if (existingIndex >= 0) {\n // Update existing entry to show both light and dark changes\n changes.modifiedTokens[existingIndex].oldValue += ` | dark: ${oldValue}`;\n changes.modifiedTokens[existingIndex].newValue += ` | dark: ${newValue}`;\n } else {\n // Add new dark mode-only change\n changes.modifiedTokens.push({\n token: `${cssVarName} (dark mode)`,\n oldValue,\n newValue,\n });\n changes.hasChanges = true;\n }\n }\n }\n }\n\n // Compare governance rules (AI guide changes)\n // Compare both the rules array and categories object\n const cachedGovernance = cached.governance || { rules: [], categories: {} };\n const freshGovernance = fresh.governance || { rules: [], categories: {} };\n \n const cachedRules = cachedGovernance.rules || [];\n const freshRules = freshGovernance.rules || [];\n const cachedCategories = cachedGovernance.categories || {};\n const freshCategories = freshGovernance.categories || {};\n \n // Compare rules array (deep comparison)\n const cachedRulesStr = JSON.stringify(cachedRules.sort());\n const freshRulesStr = JSON.stringify(freshRules.sort());\n \n // Compare categories object (deep comparison)\n const cachedCategoriesStr = JSON.stringify(cachedCategories, Object.keys(cachedCategories).sort());\n const freshCategoriesStr = JSON.stringify(freshCategories, Object.keys(freshCategories).sort());\n \n if (cachedRulesStr !== freshRulesStr || cachedCategoriesStr !== freshCategoriesStr) {\n changes.governanceChanged = true;\n changes.hasChanges = true;\n }\n\n // Build summary text\n const summaryLines: string[] = [];\n \n if (!changes.hasChanges) {\n summaryLines.push(\"✓ No changes detected - design system is up to date\");\n } else {\n summaryLines.push(\"📦 Design System Changes Detected:\");\n summaryLines.push(\"\");\n\n if (changes.versionChanged) {\n summaryLines.push(` Version: ${cached.meta.version} → ${fresh.meta.version}`);\n }\n\n if (changes.timestampChanged) {\n const cachedDate = new Date(cached.meta.exportedAt).toLocaleString();\n const freshDate = new Date(fresh.meta.exportedAt).toLocaleString();\n summaryLines.push(` Published: ${cachedDate} → ${freshDate}`);\n }\n\n if (changes.addedTokens.length > 0) {\n summaryLines.push(` ➕ Added: ${changes.addedTokens.length} token(s)`);\n if (changes.addedTokens.length <= 10) {\n changes.addedTokens.forEach(token => {\n summaryLines.push(` - ${token}`);\n });\n } else {\n changes.addedTokens.slice(0, 10).forEach(token => {\n summaryLines.push(` - ${token}`);\n });\n summaryLines.push(` ... and ${changes.addedTokens.length - 10} more`);\n }\n }\n\n if (changes.removedTokens.length > 0) {\n summaryLines.push(` ➖ Removed: ${changes.removedTokens.length} token(s)`);\n if (changes.removedTokens.length <= 10) {\n changes.removedTokens.forEach(token => {\n summaryLines.push(` - ${token}`);\n });\n } else {\n changes.removedTokens.slice(0, 10).forEach(token => {\n summaryLines.push(` - ${token}`);\n });\n summaryLines.push(` ... and ${changes.removedTokens.length - 10} more`);\n }\n }\n\n if (changes.modifiedTokens.length > 0) {\n summaryLines.push(` 🔄 Modified: ${changes.modifiedTokens.length} token(s)`);\n if (changes.modifiedTokens.length <= 10) {\n changes.modifiedTokens.forEach(({ token, oldValue, newValue }) => {\n summaryLines.push(` ${token}:`);\n summaryLines.push(` - ${oldValue}`);\n summaryLines.push(` + ${newValue}`);\n });\n } else {\n changes.modifiedTokens.slice(0, 5).forEach(({ token, oldValue, newValue }) => {\n summaryLines.push(` ${token}:`);\n summaryLines.push(` - ${oldValue}`);\n summaryLines.push(` + ${newValue}`);\n });\n summaryLines.push(` ... and ${changes.modifiedTokens.length - 5} more`);\n }\n }\n\n if (changes.governanceChanged) {\n summaryLines.push(` 📝 AI guide updated`);\n }\n }\n\n changes.summary = summaryLines.join(\"\\n\");\n return changes;\n}\n\n/**\n * Detect which foundations have governance changes\n * \n * Compares cached vs fresh governance data and returns an array of foundation names\n * that have changed (e.g., [\"general\", \"colors\", \"typography\"]).\n * \n * @param cached - Previously cached design system data\n * @param fresh - Freshly fetched design system data\n * @returns Array of foundation names that have governance changes\n */\nexport function detectGovernanceChangesByFoundation(\n cached: DesignSystemData,\n fresh: DesignSystemData\n): string[] {\n const changes: string[] = [];\n \n const cachedGov = cached.governance || { rules: [], categories: {} };\n const freshGov = fresh.governance || { rules: [], categories: {} };\n \n // Check general rules (rules array)\n const cachedRulesStr = JSON.stringify((cachedGov.rules || []).sort());\n const freshRulesStr = JSON.stringify((freshGov.rules || []).sort());\n if (cachedRulesStr !== freshRulesStr) {\n changes.push(\"general\");\n }\n \n // Check foundation-specific rules (categories object)\n const cachedCategories = cachedGov.categories || {};\n const freshCategories = freshGov.categories || {};\n \n const allFoundationKeys = new Set([\n ...Object.keys(cachedCategories),\n ...Object.keys(freshCategories),\n ]);\n \n for (const foundation of allFoundationKeys) {\n const cachedRules = cachedCategories[foundation] || [];\n const freshRules = freshCategories[foundation] || [];\n const cachedRulesStr = JSON.stringify(cachedRules.sort());\n const freshRulesStr = JSON.stringify(freshRules.sort());\n \n if (cachedRulesStr !== freshRulesStr) {\n changes.push(foundation);\n }\n }\n \n return changes;\n}\n\n/**\n * Fetch design system from API with ETag support\n */\nexport async function fetchDesignSystem(options: FetchOptions): Promise<FetchResult> {\n const { dsId, apiKey, apiBase = \"https://atomixstudio.eu\", etag, forceRefresh = false } = options;\n\n if (!dsId) {\n throw new Error(\"Missing dsId. Usage: fetchDesignSystem({ dsId: '...' })\");\n }\n\n const url = `${apiBase}/api/ds/${dsId}/tokens?format=export`;\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n \n if (apiKey) {\n headers[\"x-api-key\"] = apiKey;\n }\n \n // Send If-None-Match if we have cached ETag\n if (etag) {\n headers[\"if-none-match\"] = etag;\n }\n\n const response = await fetch(url, { headers });\n \n if (response.status === 304) {\n // Not Modified - return null data, same ETag\n return {\n data: null,\n etag: etag!,\n status: 304,\n };\n }\n \n if (!response.ok) {\n const text = await response.text();\n throw new Error(`Failed to fetch design system: ${response.status} ${text}`);\n }\n\n const data = await response.json() as ExportedTokens;\n \n // Extract ETag from response header or generate from meta\n const responseETag = response.headers.get('etag');\n const finalETag = responseETag || generateETag(data.meta);\n \n // Transform to DesignSystemData format\n const designSystemData: DesignSystemData = {\n tokens: data.tokens,\n cssVariables: data.cssVariables,\n governance: data.governance,\n meta: data.meta,\n };\n \n return {\n data: designSystemData,\n etag: finalETag,\n status: 200,\n };\n}\n","/**\n * Core Sync Function\n * \n * Unified sync logic used by both CLI and MCP.\n */\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport type { SyncOptions, SyncResult, DesignSystemData, OutputFormat, DiffResult } from './types.js';\nimport { fetchDesignSystem } from './fetch.js';\nimport { diffTokens } from './diff.js';\nimport { syncRulesFiles } from './rules.js';\nimport {\n generateCSSOutput,\n generateSCSSOutput,\n generateLessOutput,\n generateJSONOutput,\n generateTSOutput,\n generateJSOutput,\n generateSwiftOutput,\n generateKotlinOutput,\n generateDartOutput,\n} from './formats/index.js';\n\n/**\n * Sync design tokens to a local file\n */\nexport async function syncTokens(options: SyncOptions): Promise<SyncResult> {\n const {\n dsId,\n apiKey,\n apiBase = \"https://atomixstudio.eu\",\n output,\n format,\n yes = false,\n rules = true, // Default to true (sync rules by default)\n rulesDir,\n etag, // Optional cached ETag\n } = options;\n\n try {\n // Fetch design system with ETag support\n const fetchResult = await fetchDesignSystem({\n dsId,\n apiKey,\n apiBase,\n etag,\n forceRefresh: true,\n });\n\n // Handle 304 Not Modified\n if (fetchResult.status === 304) {\n return {\n success: true,\n tokenCount: 0,\n deprecatedCount: 0,\n etag: fetchResult.etag,\n status: 304,\n };\n }\n\n if (!fetchResult.data) {\n return {\n success: false,\n tokenCount: 0,\n deprecatedCount: 0,\n error: \"No data returned from API\",\n };\n }\n\n const data = fetchResult.data;\n\n // Check if file exists first to detect deprecated tokens\n const outputPath = path.resolve(process.cwd(), output);\n const fileExists = fs.existsSync(outputPath);\n \n // Read old file if it exists\n const deprecatedTokens: Map<string, string> = new Map();\n const existingTokens: Map<string, string> = new Map();\n \n if (fileExists) {\n if ([\"css\", \"scss\", \"less\"].includes(format)) {\n // For CSS-based formats, extract CSS variables\n const oldContent = fs.readFileSync(outputPath, \"utf-8\");\n // Improved regex: handles comments before variables, supports uppercase/numbers in prefix\n const oldVarPattern = /(?:^|\\n)\\s*(?:\\/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*\\/\\s*)?(--[a-zA-Z0-9-]+):\\s*([^;]+);/gm;\n let match;\n while ((match = oldVarPattern.exec(oldContent)) !== null) {\n const varName = match[1];\n const varValue = match[2].trim();\n \n existingTokens.set(varName, varValue);\n \n // Mark as deprecated if NOT in design system (kept for backward compatibility)\n if (!(varName in data.cssVariables)) {\n deprecatedTokens.set(varName, varValue);\n }\n }\n } else if ([\"swift\", \"kotlin\", \"dart\"].includes(format)) {\n // For native formats, extract tokens and convert to CSS variable names\n const oldContent = fs.readFileSync(outputPath, \"utf-8\");\n let tokenPattern: RegExp;\n \n if (format === \"swift\") {\n tokenPattern = /static\\s+let\\s+(\\w+)\\s*=\\s*[^;]+;/g;\n } else if (format === \"kotlin\") {\n tokenPattern = /val\\s+(\\w+)\\s*=\\s*[^;]+/g;\n } else {\n tokenPattern = /static\\s+const\\s+(\\w+)\\s*=\\s*[^;]+;/g;\n }\n \n let match;\n while ((match = tokenPattern.exec(oldContent)) !== null) {\n const nativeName = match[1];\n // Convert native name to CSS variable name (approximate)\n const kebab = nativeName\n .replace(/([A-Z])/g, \"-$1\")\n .toLowerCase()\n .replace(/^-/, \"\");\n const cssVarName = `--atmx-${kebab}`;\n \n existingTokens.set(cssVarName, \"\");\n \n // Mark as deprecated if NOT in design system\n if (!(cssVarName in data.cssVariables)) {\n deprecatedTokens.set(cssVarName, \"\");\n }\n }\n }\n }\n \n // Always use DS tokens (deprecated tokens are kept via generateXOutput functions)\n const mergedCssVariables = { ...data.cssVariables };\n\n // Generate new content based on format\n // Get dark mode colors for CSS output\n const darkModeColors = (data.tokens?.colors as Record<string, unknown>)?.modes as { dark?: Record<string, string> } | undefined;\n \n // Use mergedCssVariables for CSS-based formats (supports merge mode)\n let newContent: string;\n switch (format) {\n case \"css\":\n newContent = generateCSSOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"scss\":\n newContent = generateSCSSOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"less\":\n newContent = generateLessOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"json\":\n newContent = generateJSONOutput(data.tokens);\n break;\n case \"js\":\n newContent = generateJSOutput(data.tokens);\n break;\n case \"ts\":\n newContent = generateTSOutput(data.tokens);\n break;\n case \"swift\":\n newContent = generateSwiftOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"kotlin\":\n newContent = generateKotlinOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"dart\":\n newContent = generateDartOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n default:\n newContent = generateCSSOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n }\n\n // CSS-based formats support diffing\n const supportsDiff = [\"css\", \"scss\", \"less\"].includes(format);\n const deprecatedCount = deprecatedTokens.size;\n let diffResult: DiffResult | undefined;\n \n if (fileExists && supportsDiff) {\n const oldContent = fs.readFileSync(outputPath, \"utf-8\");\n diffResult = diffTokens(oldContent, mergedCssVariables, format as OutputFormat, darkModeColors?.dark);\n\n // Count changes (deprecated tokens are kept, not removed)\n const lightChanges = diffResult.added.length + diffResult.modified.length;\n const darkChanges = diffResult.addedDark.length + diffResult.modifiedDark.length;\n const totalChanges = lightChanges + darkChanges + deprecatedCount;\n\n if (totalChanges === 0) {\n // Already up to date - return early\n return {\n success: true,\n tokenCount: Object.keys(mergedCssVariables).length,\n deprecatedCount,\n etag: fetchResult.etag,\n status: 200,\n changes: diffResult,\n };\n }\n }\n\n // Write file\n const outputDir = path.dirname(outputPath);\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n fs.writeFileSync(outputPath, newContent);\n\n // Sync rules files if requested\n let rulesResults;\n if (rules) {\n rulesResults = await syncRulesFiles({\n dsId,\n apiKey,\n apiBase,\n rulesDir,\n });\n }\n\n return {\n success: true,\n tokenCount: Object.keys(mergedCssVariables).length,\n deprecatedCount,\n etag: fetchResult.etag,\n status: 200,\n changes: diffResult,\n };\n } catch (error) {\n return {\n success: false,\n tokenCount: 0,\n deprecatedCount: 0,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n","/**\n * Diff Logic\n * \n * Functions for comparing token files and detecting changes.\n */\n\nimport type { OutputFormat, DiffResult } from './types.js';\n\nexport function diffTokens(\n oldContent: string,\n newCssVars: Record<string, string>,\n format: OutputFormat,\n newDarkVars?: Record<string, string>\n): DiffResult {\n const added: string[] = [];\n const modified: Array<{ key: string; old: string; new: string }> = [];\n const removed: string[] = [];\n const addedDark: string[] = [];\n const modifiedDark: Array<{ key: string; old: string; new: string }> = [];\n const removedDark: string[] = [];\n\n // CSS-based formats (css, scss, less) all use CSS variables\n if (format === \"css\" || format === \"scss\" || format === \"less\") {\n // Split old content into light mode (:root) and dark mode (.dark) sections\n // Find the :root section\n const rootMatch = oldContent.match(/:root\\s*\\{([^}]*)\\}/);\n const darkMatch = oldContent.match(/\\.dark[^{]*\\{([^}]*)\\}/);\n \n // Parse light mode variables from :root\n const oldLightVars: Record<string, string> = {};\n if (rootMatch) {\n const rootContent = rootMatch[1];\n const varRegex = /(--[\\w-]+):\\s*([^;]+);/g;\n let match;\n while ((match = varRegex.exec(rootContent)) !== null) {\n oldLightVars[match[1]] = match[2].trim();\n }\n } else {\n // Fallback: parse everything (old behavior for files without sections)\n const varRegex = /(--[\\w-]+):\\s*([^;]+);/g;\n let match;\n while ((match = varRegex.exec(oldContent)) !== null) {\n // Only take the first occurrence to get light mode values\n if (!(match[1] in oldLightVars)) {\n oldLightVars[match[1]] = match[2].trim();\n }\n }\n }\n\n // Parse dark mode variables from .dark\n const oldDarkVars: Record<string, string> = {};\n if (darkMatch) {\n const darkContent = darkMatch[1];\n const varRegex = /(--[\\w-]+):\\s*([^;]+);/g;\n let match;\n while ((match = varRegex.exec(darkContent)) !== null) {\n oldDarkVars[match[1]] = match[2].trim();\n }\n }\n\n // Compare light mode\n for (const [key, value] of Object.entries(newCssVars)) {\n if (!(key in oldLightVars)) {\n added.push(key);\n } else if (oldLightVars[key] !== value) {\n modified.push({ key, old: oldLightVars[key], new: value });\n }\n }\n\n for (const key of Object.keys(oldLightVars)) {\n if (!(key in newCssVars)) {\n removed.push(key);\n }\n }\n\n // Compare dark mode if new dark vars provided\n if (newDarkVars && Object.keys(newDarkVars).length > 0) {\n // Generate the expected CSS variable names for dark mode\n // newDarkVars keys are like \"bg-page\", need to match \"--atmx-color-bg-page\"\n const firstKey = Object.keys(newCssVars)[0] || \"--atmx-\";\n const prefixMatch = firstKey.match(/^(--[a-z]+-)/);\n const prefix = prefixMatch ? prefixMatch[1] : \"--atmx-\";\n\n for (const [key, value] of Object.entries(newDarkVars)) {\n const cssVarName = `${prefix}color-${key}`;\n if (!(cssVarName in oldDarkVars)) {\n addedDark.push(cssVarName);\n } else if (oldDarkVars[cssVarName] !== value) {\n modifiedDark.push({ key: cssVarName, old: oldDarkVars[cssVarName], new: value });\n }\n }\n\n for (const key of Object.keys(oldDarkVars)) {\n // Extract the short key from --atmx-color-bg-page -> bg-page\n const shortKey = key.replace(new RegExp(`^${prefix}color-`), \"\");\n if (!(shortKey in newDarkVars)) {\n removedDark.push(key);\n }\n }\n }\n }\n\n return { added, modified, removed, addedDark, modifiedDark, removedDark };\n}\n","/**\n * Rules File Syncing\n * \n * Functions for syncing AI tool rules files.\n */\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\n\nexport interface SyncRulesOptions {\n dsId: string;\n apiKey?: string;\n apiBase?: string;\n rulesDir?: string;\n}\n\nexport interface RulesFileResult {\n tool: string;\n filename: string;\n path: string;\n success: boolean;\n error?: string;\n}\n\nexport async function syncRulesFiles(options: SyncRulesOptions): Promise<RulesFileResult[]> {\n const { dsId, apiKey, apiBase = \"https://atomixstudio.eu\", rulesDir = process.cwd() } = options;\n \n const rulesDirResolved = path.resolve(process.cwd(), rulesDir);\n \n // Detect which AI tools are likely in use based on existing files\n const toolsToSync: Array<{ tool: string; filename: string; dir?: string }> = [\n { tool: \"cursor\", filename: \".cursorrules\" },\n { tool: \"windsurf\", filename: \".windsurfrules\" },\n { tool: \"cline\", filename: \".clinerules\" },\n { tool: \"continue\", filename: \".continuerules\" },\n { tool: \"copilot\", filename: \"copilot-instructions.md\", dir: \".github\" },\n { tool: \"generic\", filename: \"AI_GUIDELINES.md\" },\n ];\n \n // Check which tools have existing files or should be created\n const existingTools = toolsToSync.filter(t => {\n const filePath = t.dir \n ? path.join(rulesDirResolved, t.dir, t.filename)\n : path.join(rulesDirResolved, t.filename);\n return fs.existsSync(filePath);\n });\n \n // If no existing rules files, create .cursorrules by default\n const toolsToWrite = existingTools.length > 0 \n ? existingTools \n : [{ tool: \"cursor\", filename: \".cursorrules\" }];\n \n const results: RulesFileResult[] = [];\n \n for (const { tool, filename, dir } of toolsToWrite) {\n try {\n // Fetch rules from API\n const rulesUrl = `${apiBase}/api/ds/${dsId}/rules?format=${tool}`;\n const headers: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (apiKey) headers[\"x-api-key\"] = apiKey;\n \n const response = await fetch(rulesUrl, { headers });\n if (!response.ok) {\n results.push({\n tool,\n filename,\n path: dir ? `${dir}/${filename}` : filename,\n success: false,\n error: `Failed to fetch ${tool} rules: ${response.status}`,\n });\n continue;\n }\n \n const rulesData = await response.json() as { content?: string };\n if (!rulesData.content) {\n results.push({\n tool,\n filename,\n path: dir ? `${dir}/${filename}` : filename,\n success: false,\n error: `No content for ${tool} rules`,\n });\n continue;\n }\n \n // Write the file\n const targetDir = dir ? path.join(rulesDirResolved, dir) : rulesDirResolved;\n if (!fs.existsSync(targetDir)) {\n fs.mkdirSync(targetDir, { recursive: true });\n }\n \n const filePath = path.join(targetDir, filename);\n fs.writeFileSync(filePath, rulesData.content);\n \n results.push({\n tool,\n filename,\n path: dir ? `${dir}/${filename}` : filename,\n success: true,\n });\n } catch (error) {\n results.push({\n tool,\n filename,\n path: dir ? `${dir}/${filename}` : filename,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n \n return results;\n}\n","/**\n * CSS Format Generator\n * \n * Generates CSS output with CSS custom properties and dark mode support.\n */\n\nexport function generateCSSOutput(\n cssVariables: Record<string, string>,\n darkModeColors?: Record<string, string>,\n deprecatedTokens: Map<string, string> = new Map()\n): string {\n const lines = [\n \"/* Atomix Design System Tokens\",\n \" * Auto-generated - do not edit manually\",\n ` * Synced: ${new Date().toISOString()}`,\n \" *\",\n \" * WARNING: This file is completely rewritten on each sync.\",\n \" * Only CSS custom properties (variables) are preserved.\",\n \" * Custom CSS rules (selectors, classes, etc.) will be lost.\",\n \" * Keep custom CSS in a separate file.\",\n \" */\",\n \"\",\n \"/* Light mode (default) */\",\n \":root {\"\n ];\n \n // Merge current and deprecated tokens, then sort\n const allVars = new Map<string, { value: string; deprecated: boolean }>();\n \n // Add current tokens\n for (const [key, value] of Object.entries(cssVariables)) {\n allVars.set(key, { value, deprecated: false });\n }\n \n // Add deprecated tokens\n for (const [key, value] of deprecatedTokens.entries()) {\n allVars.set(key, { value, deprecated: true });\n }\n \n // Sort all variables by name\n const sortedKeys = Array.from(allVars.keys()).sort();\n \n for (const key of sortedKeys) {\n const { value, deprecated } = allVars.get(key)!;\n if (deprecated) {\n lines.push(` /* DEPRECATED */ ${key}: ${value};`);\n } else {\n lines.push(` ${key}: ${value};`);\n }\n }\n \n lines.push(\"}\");\n \n // Add dark mode overrides if provided\n if (darkModeColors && Object.keys(darkModeColors).length > 0) {\n lines.push(\"\");\n lines.push(\"/* Dark mode */\");\n lines.push(\".dark,\");\n lines.push(\"[data-theme=\\\"dark\\\"] {\");\n \n // Detect prefix from cssVariables keys\n const firstKey = sortedKeys[0] || \"--atmx-\";\n const prefixMatch = firstKey.match(/^(--[a-z]+-)/);\n const prefix = prefixMatch ? prefixMatch[1] : \"--atmx-\";\n \n // Sort dark mode keys for consistent output\n const sortedDarkKeys = Object.keys(darkModeColors).sort();\n for (const key of sortedDarkKeys) {\n // Dark mode colors are stored with keys like \"bg-page\", \"text-primary\"\n // Convert to CSS variable names: --atmx-color-bg-page\n lines.push(` ${prefix}color-${key}: ${darkModeColors[key]};`);\n }\n \n lines.push(\"}\");\n }\n \n lines.push(\"\");\n \n return lines.join(\"\\n\");\n}\n","/**\n * SCSS Format Generator\n * \n * Generates SCSS output with CSS variables and SCSS variables.\n */\n\nexport function generateSCSSOutput(\n cssVariables: Record<string, string>,\n darkModeColors?: Record<string, string>,\n deprecatedTokens: Map<string, string> = new Map()\n): string {\n const lines = [\n \"// Atomix Design System Tokens\",\n \"// Auto-generated - do not edit manually\",\n `// Synced: ${new Date().toISOString()}`,\n \"\",\n \"// CSS Custom Properties (for use in CSS/HTML)\",\n \"// Light mode (default)\",\n \":root {\"\n ];\n \n // Merge current and deprecated tokens, then sort\n const allVars = new Map<string, { value: string; deprecated: boolean }>();\n \n // Add current tokens\n for (const [key, value] of Object.entries(cssVariables)) {\n allVars.set(key, { value, deprecated: false });\n }\n \n // Add deprecated tokens\n for (const [key, value] of deprecatedTokens.entries()) {\n allVars.set(key, { value, deprecated: true });\n }\n \n // Sort all variables by name\n const sortedKeys = Array.from(allVars.keys()).sort();\n \n for (const key of sortedKeys) {\n const { value, deprecated } = allVars.get(key)!;\n if (deprecated) {\n lines.push(` // DEPRECATED ${key}: ${value};`);\n } else {\n lines.push(` ${key}: ${value};`);\n }\n }\n \n lines.push(\"}\");\n \n // Add dark mode CSS variables\n if (darkModeColors && Object.keys(darkModeColors).length > 0) {\n lines.push(\"\");\n lines.push(\"// Dark mode\");\n lines.push(\".dark,\");\n lines.push(\"[data-theme=\\\"dark\\\"] {\");\n \n const firstKey = sortedKeys[0] || \"--atmx-\";\n const prefixMatch = firstKey.match(/^(--[a-z]+-)/);\n const prefix = prefixMatch ? prefixMatch[1] : \"--atmx-\";\n \n for (const [key, value] of Object.entries(darkModeColors)) {\n lines.push(` ${prefix}color-${key}: ${value};`);\n }\n \n lines.push(\"}\");\n }\n \n lines.push(\"\");\n lines.push(\"// SCSS Variables (light mode values)\");\n \n // Include deprecated tokens in SCSS variables too\n for (const key of sortedKeys) {\n const { value, deprecated } = allVars.get(key)!;\n const scssVar = \"$\" + key.replace(/^--/, \"\");\n if (deprecated) {\n lines.push(`// DEPRECATED ${scssVar}: ${value};`);\n } else {\n lines.push(`${scssVar}: ${value};`);\n }\n }\n \n // Add dark mode SCSS variables\n if (darkModeColors && Object.keys(darkModeColors).length > 0) {\n lines.push(\"\");\n lines.push(\"// SCSS Variables (dark mode values)\");\n \n const firstKey = Object.keys(cssVariables)[0] || \"--atmx-\";\n const prefixMatch = firstKey.match(/^--([a-z]+)-/);\n const prefix = prefixMatch ? prefixMatch[1] : \"atmx\";\n \n for (const [key, value] of Object.entries(darkModeColors)) {\n const scssVar = `$${prefix}-color-${key}-dark`;\n lines.push(`${scssVar}: ${value};`);\n }\n }\n \n lines.push(\"\");\n \n return lines.join(\"\\n\");\n}\n","/**\n * Less Format Generator\n * \n * Generates Less output with CSS variables and Less variables.\n */\n\nexport function generateLessOutput(\n cssVariables: Record<string, string>,\n darkModeColors?: Record<string, string>,\n deprecatedTokens: Map<string, string> = new Map()\n): string {\n const lines = [\n \"// Atomix Design System Tokens\",\n \"// Auto-generated - do not edit manually\",\n `// Synced: ${new Date().toISOString()}`,\n \"\",\n \"// CSS Custom Properties (for use in CSS/HTML)\",\n \"// Light mode (default)\",\n \":root {\"\n ];\n \n // Merge current and deprecated tokens, then sort\n const allVars = new Map<string, { value: string; deprecated: boolean }>();\n \n // Add current tokens\n for (const [key, value] of Object.entries(cssVariables)) {\n allVars.set(key, { value, deprecated: false });\n }\n \n // Add deprecated tokens\n for (const [key, value] of deprecatedTokens.entries()) {\n allVars.set(key, { value, deprecated: true });\n }\n \n // Sort all variables by name\n const sortedKeys = Array.from(allVars.keys()).sort();\n \n for (const key of sortedKeys) {\n const { value, deprecated } = allVars.get(key)!;\n if (deprecated) {\n lines.push(` // DEPRECATED ${key}: ${value};`);\n } else {\n lines.push(` ${key}: ${value};`);\n }\n }\n \n lines.push(\"}\");\n \n // Add dark mode CSS variables\n if (darkModeColors && Object.keys(darkModeColors).length > 0) {\n lines.push(\"\");\n lines.push(\"// Dark mode\");\n lines.push(\".dark,\");\n lines.push(\"[data-theme=\\\"dark\\\"] {\");\n \n const firstKey = Object.keys(cssVariables)[0] || \"--atmx-\";\n const prefixMatch = firstKey.match(/^(--[a-z]+-)/);\n const prefix = prefixMatch ? prefixMatch[1] : \"--atmx-\";\n \n for (const [key, value] of Object.entries(darkModeColors)) {\n lines.push(` ${prefix}color-${key}: ${value};`);\n }\n \n lines.push(\"}\");\n }\n \n lines.push(\"\");\n lines.push(\"// Less Variables (light mode values)\");\n \n for (const [key, value] of Object.entries(cssVariables)) {\n const lessVar = \"@\" + key.replace(/^--/, \"\");\n lines.push(`${lessVar}: ${value};`);\n }\n \n // Add dark mode Less variables\n if (darkModeColors && Object.keys(darkModeColors).length > 0) {\n lines.push(\"\");\n lines.push(\"// Less Variables (dark mode values)\");\n \n const firstKey = Object.keys(cssVariables)[0] || \"--atmx-\";\n const prefixMatch = firstKey.match(/^--([a-z]+)-/);\n const prefix = prefixMatch ? prefixMatch[1] : \"atmx\";\n \n for (const [key, value] of Object.entries(darkModeColors)) {\n const lessVar = `@${prefix}-color-${key}-dark`;\n lines.push(`${lessVar}: ${value};`);\n }\n }\n \n lines.push(\"\");\n \n return lines.join(\"\\n\");\n}\n","/**\n * JSON Format Generator\n * \n * Generates JSON output with raw token structure.\n */\n\nimport type { ExportedTokens } from '../types.js';\n\nexport function generateJSONOutput(tokens: ExportedTokens[\"tokens\"]): string {\n return JSON.stringify(tokens, null, 2);\n}\n","/**\n * TypeScript Format Generator\n * \n * Generates TypeScript output with types.\n */\n\nimport type { ExportedTokens } from '../types.js';\n\nexport function generateTSOutput(tokens: ExportedTokens[\"tokens\"]): string {\n return `// Atomix Design System Tokens\n// Auto-generated - do not edit manually\n// Synced: ${new Date().toISOString()}\n\nexport const tokens = ${JSON.stringify(tokens, null, 2)} as const;\n\nexport type Tokens = typeof tokens;\n`;\n}\n","/**\n * JavaScript Format Generator\n * \n * Generates JavaScript ES module output.\n */\n\nimport type { ExportedTokens } from '../types.js';\n\nexport function generateJSOutput(tokens: ExportedTokens[\"tokens\"]): string {\n return `// Atomix Design System Tokens\n// Auto-generated - do not edit manually\n// Synced: ${new Date().toISOString()}\n\nexport const tokens = ${JSON.stringify(tokens, null, 2)};\n`;\n}\n","/**\n * Swift Format Generator\n * \n * Generates Swift/SwiftUI output with dark mode support.\n */\n\n// Helper functions\nfunction toSwiftName(cssVar: string): string {\n // --atmx-color-brand-primary → colorBrandPrimary\n return cssVar\n .replace(/^--atmx-/, \"\")\n .replace(/-([a-z])/g, (_, c) => c.toUpperCase());\n}\n\nfunction isColorValue(value: string): boolean {\n return /^#[0-9A-Fa-f]{3,8}$/.test(value) || \n /^rgb/.test(value) || \n /^hsl/.test(value);\n}\n\nfunction hexToSwiftColor(hex: string): string {\n // #RRGGBB or #RRGGBBAA\n const clean = hex.replace(\"#\", \"\");\n if (clean.length === 3) {\n // #RGB -> #RRGGBB\n const r = clean[0], g = clean[1], b = clean[2];\n return `Color(hex: 0x${r}${r}${g}${g}${b}${b})`;\n }\n if (clean.length === 6) {\n return `Color(hex: 0x${clean})`;\n }\n if (clean.length === 8) {\n // #RRGGBBAA\n const rgb = clean.substring(0, 6);\n const alpha = parseInt(clean.substring(6, 8), 16) / 255;\n return `Color(hex: 0x${rgb}).opacity(${alpha.toFixed(2)})`;\n }\n return `Color.clear // Could not parse: ${hex}`;\n}\n\nexport function generateSwiftOutput(\n cssVariables: Record<string, string>,\n darkModeColors?: Record<string, string>,\n deprecatedTokens: Map<string, string> = new Map()\n): string {\n const lines = [\n \"// Atomix Design System Tokens\",\n \"// Auto-generated - do not edit manually\",\n `// Synced: ${new Date().toISOString()}`,\n \"\",\n \"import SwiftUI\",\n \"\",\n \"// MARK: - Color Extension for Hex\",\n \"extension Color {\",\n \" init(hex: UInt, alpha: Double = 1.0) {\",\n \" self.init(\",\n \" .sRGB,\",\n \" red: Double((hex >> 16) & 0xFF) / 255.0,\",\n \" green: Double((hex >> 8) & 0xFF) / 255.0,\",\n \" blue: Double(hex & 0xFF) / 255.0,\",\n \" opacity: alpha\",\n \" )\",\n \" }\",\n \"}\",\n \"\",\n \"// MARK: - Design Tokens\",\n \"enum DesignTokens {\",\n \"\",\n \" // MARK: Colors (Light Mode)\",\n \" enum Colors {\"\n ];\n\n // Group by category, including deprecated tokens\n const colors: Array<[string, string, boolean]> = [];\n const spacing: Array<[string, string, boolean]> = [];\n const typography: Array<[string, string, boolean]> = [];\n const other: Array<[string, string, boolean]> = [];\n\n // Add current tokens\n for (const [key, value] of Object.entries(cssVariables)) {\n const isDeprecated = false;\n if (key.includes(\"-color-\")) colors.push([key, value, isDeprecated]);\n else if (key.includes(\"-spacing-\")) spacing.push([key, value, isDeprecated]);\n else if (key.includes(\"-typography-\") || key.includes(\"-font-\")) typography.push([key, value, isDeprecated]);\n else other.push([key, value, isDeprecated]);\n }\n \n // Add deprecated tokens\n for (const [key, value] of deprecatedTokens.entries()) {\n const isDeprecated = true;\n if (key.includes(\"-color-\")) colors.push([key, value, isDeprecated]);\n else if (key.includes(\"-spacing-\")) spacing.push([key, value, isDeprecated]);\n else if (key.includes(\"-typography-\") || key.includes(\"-font-\")) typography.push([key, value, isDeprecated]);\n else other.push([key, value, isDeprecated]);\n }\n\n // Sort by key name\n colors.sort((a, b) => a[0].localeCompare(b[0]));\n spacing.sort((a, b) => a[0].localeCompare(b[0]));\n typography.sort((a, b) => a[0].localeCompare(b[0]));\n other.sort((a, b) => a[0].localeCompare(b[0]));\n\n for (const [key, value, isDeprecated] of colors) {\n const name = toSwiftName(key);\n if (isColorValue(value)) {\n if (isDeprecated) {\n lines.push(` @available(*, deprecated, message: \"This token has been removed from the design system\")`);\n lines.push(` static let ${name} = ${hexToSwiftColor(value)}`);\n } else {\n lines.push(` static let ${name} = ${hexToSwiftColor(value)}`);\n }\n }\n }\n\n lines.push(\" }\");\n \n // Add dark mode colors if provided\n if (darkModeColors && Object.keys(darkModeColors).length > 0) {\n lines.push(\"\");\n lines.push(\" // MARK: Colors (Dark Mode)\");\n lines.push(\" enum ColorsDark {\");\n \n for (const [key, value] of Object.entries(darkModeColors)) {\n const name = `color${key.split(\"-\").map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(\"\")}`;\n if (isColorValue(value)) {\n lines.push(` static let ${name} = ${hexToSwiftColor(value)}`);\n }\n }\n \n lines.push(\" }\");\n }\n \n lines.push(\"\");\n lines.push(\" // MARK: Spacing\");\n lines.push(\" enum Spacing {\");\n\n for (const [key, value, isDeprecated] of spacing) {\n const name = toSwiftName(key);\n const numValue = parseFloat(value);\n if (!isNaN(numValue)) {\n if (isDeprecated) {\n lines.push(` @available(*, deprecated, message: \"This token has been removed from the design system\")`);\n lines.push(` static let ${name}: CGFloat = ${numValue}`);\n } else {\n lines.push(` static let ${name}: CGFloat = ${numValue}`);\n }\n }\n }\n\n lines.push(\" }\");\n lines.push(\"\");\n lines.push(\" // MARK: Typography\");\n lines.push(\" enum Typography {\");\n\n for (const [key, value, isDeprecated] of typography) {\n const name = toSwiftName(key);\n if (isDeprecated) {\n lines.push(` @available(*, deprecated, message: \"This token has been removed from the design system\")`);\n }\n if (key.includes(\"size\")) {\n const numValue = parseFloat(value);\n if (!isNaN(numValue)) {\n lines.push(` static let ${name}: CGFloat = ${numValue}`);\n }\n } else if (key.includes(\"weight\")) {\n lines.push(` static let ${name} = \"${value}\"`);\n } else if (key.includes(\"family\")) {\n lines.push(` static let ${name} = \"${value}\"`);\n }\n }\n\n lines.push(\" }\");\n lines.push(\"\");\n lines.push(\" // MARK: Other\");\n lines.push(\" enum Other {\");\n\n for (const [key, value, isDeprecated] of other) {\n const name = toSwiftName(key);\n if (isDeprecated) {\n lines.push(` @available(*, deprecated, message: \"This token has been removed from the design system\")`);\n }\n if (isColorValue(value)) {\n lines.push(` static let ${name} = ${hexToSwiftColor(value)}`);\n } else {\n const numValue = parseFloat(value);\n if (!isNaN(numValue)) {\n lines.push(` static let ${name}: CGFloat = ${numValue}`);\n } else {\n lines.push(` static let ${name} = \"${value}\"`);\n }\n }\n }\n\n lines.push(\" }\");\n lines.push(\"}\");\n lines.push(\"\");\n\n return lines.join(\"\\n\");\n}\n","/**\n * Kotlin Format Generator\n * \n * Generates Kotlin/Jetpack Compose output with dark mode support.\n */\n\n// Helper functions\nfunction toSwiftName(cssVar: string): string {\n return cssVar\n .replace(/^--atmx-/, \"\")\n .replace(/-([a-z])/g, (_, c) => c.toUpperCase());\n}\n\nfunction toKotlinName(cssVar: string): string {\n // --atmx-color-brand-primary → ColorBrandPrimary\n const camel = toSwiftName(cssVar);\n return camel.charAt(0).toUpperCase() + camel.slice(1);\n}\n\nfunction isColorValue(value: string): boolean {\n return /^#[0-9A-Fa-f]{3,8}$/.test(value) || \n /^rgb/.test(value) || \n /^hsl/.test(value);\n}\n\nfunction hexToKotlinColor(hex: string): string {\n const clean = hex.replace(\"#\", \"\").toUpperCase();\n if (clean.length === 3) {\n const r = clean[0], g = clean[1], b = clean[2];\n return `Color(0xFF${r}${r}${g}${g}${b}${b})`;\n }\n if (clean.length === 6) {\n return `Color(0xFF${clean})`;\n }\n if (clean.length === 8) {\n // RRGGBBAA -> AARRGGBB for Android\n const rgb = clean.substring(0, 6);\n const alpha = clean.substring(6, 8);\n return `Color(0x${alpha}${rgb})`;\n }\n return `Color.Transparent // Could not parse: ${hex}`;\n}\n\nexport function generateKotlinOutput(\n cssVariables: Record<string, string>,\n darkModeColors?: Record<string, string>,\n deprecatedTokens: Map<string, string> = new Map()\n): string {\n const lines = [\n \"// Atomix Design System Tokens\",\n \"// Auto-generated - do not edit manually\",\n `// Synced: ${new Date().toISOString()}`,\n \"\",\n \"package com.atomix.design\",\n \"\",\n \"import androidx.compose.ui.graphics.Color\",\n \"import androidx.compose.ui.unit.dp\",\n \"import androidx.compose.ui.unit.sp\",\n \"\",\n \"object DesignTokens {\",\n \"\",\n \" // Light mode colors\",\n \" object Colors {\"\n ];\n\n const colors: Array<[string, string, boolean]> = [];\n const spacing: Array<[string, string, boolean]> = [];\n const typography: Array<[string, string, boolean]> = [];\n const other: Array<[string, string, boolean]> = [];\n\n // Add current tokens\n for (const [key, value] of Object.entries(cssVariables)) {\n const isDeprecated = false;\n if (key.includes(\"-color-\")) colors.push([key, value, isDeprecated]);\n else if (key.includes(\"-spacing-\")) spacing.push([key, value, isDeprecated]);\n else if (key.includes(\"-typography-\") || key.includes(\"-font-\")) typography.push([key, value, isDeprecated]);\n else other.push([key, value, isDeprecated]);\n }\n \n // Add deprecated tokens\n for (const [key, value] of deprecatedTokens.entries()) {\n const isDeprecated = true;\n if (key.includes(\"-color-\")) colors.push([key, value, isDeprecated]);\n else if (key.includes(\"-spacing-\")) spacing.push([key, value, isDeprecated]);\n else if (key.includes(\"-typography-\") || key.includes(\"-font-\")) typography.push([key, value, isDeprecated]);\n else other.push([key, value, isDeprecated]);\n }\n\n // Sort by key name\n colors.sort((a, b) => a[0].localeCompare(b[0]));\n spacing.sort((a, b) => a[0].localeCompare(b[0]));\n typography.sort((a, b) => a[0].localeCompare(b[0]));\n other.sort((a, b) => a[0].localeCompare(b[0]));\n\n for (const [key, value, isDeprecated] of colors) {\n const name = toKotlinName(key);\n if (isColorValue(value)) {\n if (isDeprecated) {\n lines.push(` @Deprecated(\"This token has been removed from the design system\")`);\n lines.push(` val ${name} = ${hexToKotlinColor(value)}`);\n } else {\n lines.push(` val ${name} = ${hexToKotlinColor(value)}`);\n }\n }\n }\n\n lines.push(\" }\");\n \n // Add dark mode colors if provided\n if (darkModeColors && Object.keys(darkModeColors).length > 0) {\n lines.push(\"\");\n lines.push(\" // Dark mode colors\");\n lines.push(\" object ColorsDark {\");\n \n for (const [key, value] of Object.entries(darkModeColors)) {\n const name = `Color${key.split(\"-\").map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(\"\")}`;\n if (isColorValue(value)) {\n lines.push(` val ${name} = ${hexToKotlinColor(value)}`);\n }\n }\n \n lines.push(\" }\");\n }\n \n lines.push(\"\");\n lines.push(\" object Spacing {\");\n\n for (const [key, value, isDeprecated] of spacing) {\n const name = toKotlinName(key);\n const numValue = parseFloat(value);\n if (!isNaN(numValue)) {\n if (isDeprecated) {\n lines.push(` @Deprecated(\"This token has been removed from the design system\")`);\n lines.push(` val ${name} = ${numValue}.dp`);\n } else {\n lines.push(` val ${name} = ${numValue}.dp`);\n }\n }\n }\n\n lines.push(\" }\");\n lines.push(\"\");\n lines.push(\" object Typography {\");\n\n for (const [key, value, isDeprecated] of typography) {\n const name = toKotlinName(key);\n if (isDeprecated) {\n lines.push(` @Deprecated(\"This token has been removed from the design system\")`);\n }\n if (key.includes(\"size\")) {\n const numValue = parseFloat(value);\n if (!isNaN(numValue)) {\n lines.push(` val ${name} = ${numValue}.sp`);\n }\n } else {\n lines.push(` const val ${name} = \"${value}\"`);\n }\n }\n\n lines.push(\" }\");\n lines.push(\"\");\n lines.push(\" object Other {\");\n\n for (const [key, value, isDeprecated] of other) {\n const name = toKotlinName(key);\n if (isDeprecated) {\n lines.push(` @Deprecated(\"This token has been removed from the design system\")`);\n }\n if (isColorValue(value)) {\n lines.push(` val ${name} = ${hexToKotlinColor(value)}`);\n } else {\n const numValue = parseFloat(value);\n if (!isNaN(numValue)) {\n lines.push(` val ${name} = ${numValue}.dp`);\n } else {\n lines.push(` const val ${name} = \"${value}\"`);\n }\n }\n }\n\n lines.push(\" }\");\n lines.push(\"}\");\n lines.push(\"\");\n\n return lines.join(\"\\n\");\n}\n","/**\n * Dart Format Generator\n * \n * Generates Dart/Flutter output with dark mode support.\n */\n\n// Helper functions\nfunction toSwiftName(cssVar: string): string {\n return cssVar\n .replace(/^--atmx-/, \"\")\n .replace(/-([a-z])/g, (_, c) => c.toUpperCase());\n}\n\nfunction toDartName(cssVar: string): string {\n // --atmx-color-brand-primary → colorBrandPrimary (same as Swift)\n return toSwiftName(cssVar);\n}\n\nfunction isColorValue(value: string): boolean {\n return /^#[0-9A-Fa-f]{3,8}$/.test(value) || \n /^rgb/.test(value) || \n /^hsl/.test(value);\n}\n\nfunction hexToDartColor(hex: string): string {\n const clean = hex.replace(\"#\", \"\").toUpperCase();\n if (clean.length === 3) {\n const r = clean[0], g = clean[1], b = clean[2];\n return `Color(0xFF${r}${r}${g}${g}${b}${b})`;\n }\n if (clean.length === 6) {\n return `Color(0xFF${clean})`;\n }\n if (clean.length === 8) {\n const rgb = clean.substring(0, 6);\n const alpha = clean.substring(6, 8);\n return `Color(0x${alpha}${rgb})`;\n }\n return `Colors.transparent // Could not parse: ${hex}`;\n}\n\nexport function generateDartOutput(\n cssVariables: Record<string, string>,\n darkModeColors?: Record<string, string>,\n deprecatedTokens: Map<string, string> = new Map()\n): string {\n const lines = [\n \"// Atomix Design System Tokens\",\n \"// Auto-generated - do not edit manually\",\n `// Synced: ${new Date().toISOString()}`,\n \"\",\n \"import 'package:flutter/material.dart';\",\n \"\",\n \"class DesignTokens {\",\n \" DesignTokens._();\",\n \"\",\n \" // Colors (Light Mode)\"\n ];\n\n const colors: Array<[string, string, boolean]> = [];\n const spacing: Array<[string, string, boolean]> = [];\n const typography: Array<[string, string, boolean]> = [];\n const other: Array<[string, string, boolean]> = [];\n\n // Add current tokens\n for (const [key, value] of Object.entries(cssVariables)) {\n const isDeprecated = false;\n if (key.includes(\"-color-\")) colors.push([key, value, isDeprecated]);\n else if (key.includes(\"-spacing-\")) spacing.push([key, value, isDeprecated]);\n else if (key.includes(\"-typography-\") || key.includes(\"-font-\")) typography.push([key, value, isDeprecated]);\n else other.push([key, value, isDeprecated]);\n }\n \n // Add deprecated tokens\n for (const [key, value] of deprecatedTokens.entries()) {\n const isDeprecated = true;\n if (key.includes(\"-color-\")) colors.push([key, value, isDeprecated]);\n else if (key.includes(\"-spacing-\")) spacing.push([key, value, isDeprecated]);\n else if (key.includes(\"-typography-\") || key.includes(\"-font-\")) typography.push([key, value, isDeprecated]);\n else other.push([key, value, isDeprecated]);\n }\n\n // Sort by key name\n colors.sort((a, b) => a[0].localeCompare(b[0]));\n spacing.sort((a, b) => a[0].localeCompare(b[0]));\n typography.sort((a, b) => a[0].localeCompare(b[0]));\n other.sort((a, b) => a[0].localeCompare(b[0]));\n\n for (const [key, value, isDeprecated] of colors) {\n const name = toDartName(key);\n if (isColorValue(value)) {\n if (isDeprecated) {\n lines.push(` @Deprecated('This token has been removed from the design system')`);\n lines.push(` static const ${name} = ${hexToDartColor(value)};`);\n } else {\n lines.push(` static const ${name} = ${hexToDartColor(value)};`);\n }\n }\n }\n\n // Add dark mode colors if provided\n if (darkModeColors && Object.keys(darkModeColors).length > 0) {\n lines.push(\"\");\n lines.push(\" // Colors (Dark Mode)\");\n \n for (const [key, value] of Object.entries(darkModeColors)) {\n const name = `color${key.split(\"-\").map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(\"\")}Dark`;\n if (isColorValue(value)) {\n lines.push(` static const ${name} = ${hexToDartColor(value)};`);\n }\n }\n }\n\n lines.push(\"\");\n lines.push(\" // Spacing\");\n\n for (const [key, value, isDeprecated] of spacing) {\n const name = toDartName(key);\n const numValue = parseFloat(value);\n if (!isNaN(numValue)) {\n if (isDeprecated) {\n lines.push(` @Deprecated('This token has been removed from the design system')`);\n lines.push(` static const double ${name} = ${numValue};`);\n } else {\n lines.push(` static const double ${name} = ${numValue};`);\n }\n }\n }\n\n lines.push(\"\");\n lines.push(\" // Typography\");\n\n for (const [key, value, isDeprecated] of typography) {\n const name = toDartName(key);\n if (isDeprecated) {\n lines.push(` @Deprecated('This token has been removed from the design system')`);\n }\n if (key.includes(\"size\")) {\n const numValue = parseFloat(value);\n if (!isNaN(numValue)) {\n lines.push(` static const double ${name} = ${numValue};`);\n }\n } else {\n lines.push(` static const String ${name} = '${value}';`);\n }\n }\n\n lines.push(\"\");\n lines.push(\" // Other\");\n\n for (const [key, value, isDeprecated] of other) {\n const name = toDartName(key);\n if (isDeprecated) {\n lines.push(` @Deprecated('This token has been removed from the design system')`);\n }\n if (isColorValue(value)) {\n lines.push(` static const ${name} = ${hexToDartColor(value)};`);\n } else {\n const numValue = parseFloat(value);\n if (!isNaN(numValue)) {\n lines.push(` static const double ${name} = ${numValue};`);\n } else {\n lines.push(` static const String ${name} = '${value}';`);\n }\n }\n }\n\n lines.push(\"}\");\n lines.push(\"\");\n\n return lines.join(\"\\n\");\n}\n","/**\n * Format sync response for CLI and MCP\n * \n * Single source of truth for sync output formatting.\n * This ensures MCP and CLI have identical response formats.\n */\n\nimport * as path from \"path\";\nimport type { DesignSystemData, DiffResult } from './types.js';\nimport type { RulesFileResult } from './rules.js';\n\nexport interface FormatSyncResponseOptions {\n // Core data\n data: DesignSystemData;\n output: string;\n format: string;\n \n // Token counts\n dsTokenCount: number;\n deprecatedCount: number;\n deprecatedTokens: Map<string, string>;\n \n // Changes\n diff?: DiffResult;\n changes?: Array<{ key: string; old: string; new: string }>;\n fileExists: boolean;\n \n // Rules\n rulesResults?: RulesFileResult[];\n \n // Governance changes\n governanceChanges?: string[];\n changeSummary?: string | null;\n \n // Refactor info\n hasRefactorRecommendation?: boolean;\n deprecatedTokenCount?: number;\n}\n\n/**\n * Format enhanced sync response text\n * \n * Generates a comprehensive response with explicit lists of:\n * - Deprecated tokens (with values)\n * - New tokens\n * - Modified files (output + rules files)\n * - AI rules changes by foundation\n * - Detailed changes summary\n * - Refactor recommendations\n */\nexport function formatSyncResponse(options: FormatSyncResponseOptions): string {\n const {\n data,\n output,\n format,\n dsTokenCount,\n deprecatedCount,\n deprecatedTokens,\n diff,\n changes = [],\n fileExists,\n rulesResults = [],\n governanceChanges = [],\n changeSummary,\n hasRefactorRecommendation = false,\n deprecatedTokenCount = 0,\n } = options;\n\n const lastUpdated = data.meta.exportedAt \n ? new Date(data.meta.exportedAt).toLocaleString()\n : \"N/A\";\n\n let response = `✓ Synced ${dsTokenCount} tokens to ${output}\\n`;\n response += `Format: ${format}\\n`;\n response += `Design System: ${data.meta.name} (v${data.meta.version})\\n`;\n if (deprecatedCount > 0) {\n response += `Tokens: ${dsTokenCount} active, ${deprecatedCount} deprecated (run /refactor to migrate)\\n`;\n } else {\n response += `Tokens: ${dsTokenCount}\\n`;\n }\n response += `Version: ${data.meta.version}\\n`;\n response += `Last updated: ${lastUpdated}\\n`;\n\n // ============================================\n // SECTION 1: DEPRECATED TOKENS (Explicit List)\n // ============================================\n if (deprecatedCount > 0) {\n response += `\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`;\n response += `📋 DEPRECATED TOKENS (${deprecatedCount})\\n`;\n response += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n\\n`;\n response += `These tokens are no longer in the design system but are preserved in your file for backward compatibility.\\n`;\n response += `Run \\`/refactor\\` to find and migrate usage in your codebase.\\n\\n`;\n \n const deprecatedTokenList = Array.from(deprecatedTokens.keys()).sort();\n deprecatedTokenList.forEach((token, index) => {\n const value = deprecatedTokens.get(token);\n response += ` ${index + 1}. ${token}`;\n if (value) {\n response += ` = ${value}`;\n }\n response += `\\n`;\n });\n }\n\n // ============================================\n // SECTION 2: NEW TOKENS (Explicit List)\n // ============================================\n const newTokenList: string[] = [];\n if (diff) {\n newTokenList.push(...diff.added, ...diff.addedDark);\n }\n\n // Also include tokens from change summary if available\n if (changeSummary && changeSummary.includes(\"➕ Added:\")) {\n const addedSection = changeSummary.match(/➕ Added: \\d+ token\\(s\\)([\\s\\S]*?)(?=➖|🔄|📝|$)/);\n if (addedSection) {\n const addedLines = addedSection[0].match(/ - (--[^\\n]+)/g) || [];\n addedLines.forEach(line => {\n const token = line.replace(/ - /, \"\").trim();\n if (token && !newTokenList.includes(token)) {\n newTokenList.push(token);\n }\n });\n }\n }\n\n if (newTokenList.length > 0) {\n response += `\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`;\n response += `✨ NEW TOKENS (${newTokenList.length})\\n`;\n response += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n\\n`;\n newTokenList.sort().forEach((token, index) => {\n response += ` ${index + 1}. ${token}\\n`;\n });\n }\n\n // ============================================\n // SECTION 3: MODIFIED FILES (Explicit List)\n // ============================================\n const modifiedFiles: string[] = [output];\n\n // Add rules files that were synced\n rulesResults.forEach(result => {\n if (result.success) {\n const fullPath = path.resolve(process.cwd(), result.path);\n if (!modifiedFiles.includes(fullPath)) {\n modifiedFiles.push(fullPath);\n }\n }\n });\n\n response += `\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`;\n response += `📁 MODIFIED FILES (${modifiedFiles.length})\\n`;\n response += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n\\n`;\n modifiedFiles.forEach((file, index) => {\n const relativePath = path.relative(process.cwd(), file);\n response += ` ${index + 1}. ${relativePath}\\n`;\n });\n\n // ============================================\n // SECTION 4: AI RULES CHANGES (By Foundation)\n // ============================================\n if (governanceChanges.length > 0) {\n response += `\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`;\n response += `📝 AI RULES CHANGES\\n`;\n response += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n\\n`;\n response += `The following AI guidance sections have been updated:\\n\\n`;\n \n // Capitalize foundation names\n const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);\n \n governanceChanges.forEach((foundation, index) => {\n const displayName = foundation === \"general\" \n ? \"General Rules\" \n : capitalize(foundation);\n response += ` ${index + 1}. ${displayName}\\n`;\n });\n \n response += `\\nThese changes are reflected in your AI tool rules files (e.g., .cursorrules).\\n`;\n response += `Review the updated rules files to see the new guidance.\\n`;\n }\n\n // ============================================\n // SECTION 5: DETAILED CHANGES (Keep existing)\n // ============================================\n if (diff) {\n const lightChanges = diff.added.length + diff.modified.length;\n const darkChanges = diff.addedDark.length + diff.modifiedDark.length;\n \n if (lightChanges > 0 || darkChanges > 0 || deprecatedCount > 0) {\n response += `\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`;\n response += `📊 DETAILED CHANGES\\n`;\n response += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n\\n`;\n \n const lightSummary = lightChanges > 0 ? `Light: ${diff.modified.length} modified, ${diff.added.length} added` : \"\";\n const darkSummary = darkChanges > 0 ? `Dark: ${diff.modifiedDark.length} modified, ${diff.addedDark.length} added` : \"\";\n const deprecatedSummary = deprecatedCount > 0 ? `${deprecatedCount} deprecated (use /refactor)` : \"\";\n const diffSummary = [lightSummary, darkSummary, deprecatedSummary].filter(Boolean).join(\" | \");\n response += `${diffSummary}\\n`;\n \n if (changes.length > 0 && changes.length <= 10) {\n response += \"\\nModified tokens:\\n\";\n for (const { key, old: oldVal, new: newVal } of changes) {\n response += ` ${key}: ${oldVal} → ${newVal}\\n`;\n }\n }\n }\n } else if (!fileExists) {\n response += `\\n(New file created)\\n`;\n }\n\n // ============================================\n // SECTION 6: REFACTOR RECOMMENDATION\n // ============================================\n if (hasRefactorRecommendation && deprecatedTokenCount > 0) {\n response += `\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`;\n response += `💡 NEXT STEP\\n`;\n response += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n\\n`;\n response += `${deprecatedTokenCount} token(s) have been deprecated.\\n`;\n response += `Your codebase may still reference these deprecated tokens.\\n\\n`;\n response += `Run \\`/refactor\\` to:\\n`;\n response += ` • Scan your codebase for deprecated token usage\\n`;\n response += ` • See which files need updates\\n`;\n response += ` • Review and apply changes with your confirmation\\n`;\n }\n\n return response;\n}\n","/**\n * Token Utilities\n * \n * Functions for working with design tokens.\n */\n\nimport type { DesignSystemData } from './types.js';\n\nexport function getTokenByPath(tokens: Record<string, unknown>, path: string): unknown {\n const parts = path.split(\".\");\n let current: unknown = tokens;\n\n for (const part of parts) {\n if (current && typeof current === \"object\" && part in current) {\n current = (current as Record<string, unknown>)[part];\n } else {\n return undefined;\n }\n }\n\n return current;\n}\n\nexport function flattenTokens(obj: unknown, prefix = \"\"): Array<{ path: string; value: unknown }> {\n const results: Array<{ path: string; value: unknown }> = [];\n\n if (obj && typeof obj === \"object\" && !Array.isArray(obj)) {\n for (const [key, value] of Object.entries(obj)) {\n const newPath = prefix ? `${prefix}.${key}` : key;\n \n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n results.push(...flattenTokens(value, newPath));\n } else {\n results.push({ path: newPath, value });\n }\n }\n }\n\n return results;\n}\n\nexport function searchTokens(tokens: Record<string, unknown>, query: string): Array<{ path: string; value: unknown }> {\n const flat = flattenTokens(tokens);\n const lowerQuery = query.toLowerCase();\n \n return flat.filter(({ path, value }) => {\n const pathMatch = path.toLowerCase().includes(lowerQuery);\n const valueMatch = String(value).toLowerCase().includes(lowerQuery);\n return pathMatch || valueMatch;\n });\n}\n\nexport function countTokens(tokens: Record<string, unknown>, prefix = \"\"): number {\n let count = 0;\n for (const [key, value] of Object.entries(tokens)) {\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n count += countTokens(value as Record<string, unknown>, `${prefix}${key}.`);\n } else if (value !== undefined && value !== null) {\n count++;\n }\n }\n return count;\n}\n\nexport function getTokenStats(data: DesignSystemData): {\n total: number;\n byCategory: Record<string, number>;\n cssVariables: number;\n governanceRules: number;\n} {\n const byCategory: Record<string, number> = {};\n let total = 0;\n\n for (const [category, value] of Object.entries(data.tokens)) {\n if (value && typeof value === \"object\") {\n const count = countTokens(value as Record<string, unknown>);\n byCategory[category] = count;\n total += count;\n }\n }\n\n return {\n total,\n byCategory,\n cssVariables: Object.keys(data.cssVariables).length,\n governanceRules: data.governance.rules.length,\n };\n}\n","/**\n * Config Management\n * \n * Functions for loading and managing .atomixrc configuration.\n */\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport type { AtomixConfig, DEFAULT_INCLUDE, DEFAULT_EXCLUDE } from './types.js';\n\nexport { DEFAULT_INCLUDE, DEFAULT_EXCLUDE } from './types.js';\n\nexport function findConfig(): AtomixConfig | null {\n const configNames = [\".atomixrc\", \".atomixrc.json\", \"atomix.config.json\"];\n const cwd = process.cwd();\n \n for (const name of configNames) {\n const configPath = path.join(cwd, name);\n if (fs.existsSync(configPath)) {\n try {\n const content = fs.readFileSync(configPath, \"utf-8\");\n return JSON.parse(content) as AtomixConfig;\n } catch {\n console.error(`Error parsing ${name}`);\n }\n }\n }\n return null;\n}\n"],"mappings":";;;AAsBA,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;AKzBP,YAAY,QAAQ;AACpB,YAAY,UAAU;AUAtB,YAAYA,WAAU;AbIf,SAAS,aAAa,MAA4E;AACvG,QAAM,KAAK,KAAK,aAAa,KAAK,cAAc;AAChD,QAAM,OAAO,GAAG,KAAK,OAAO,IAAI,EAAE;AAClC,SAAO,KAAK,IAAI;AAClB;AAKO,SAAS,qBACd,QACA,OACe;AACf,QAAM,UAAyB;IAC7B,YAAY;IACZ,gBAAgB;IAChB,kBAAkB;IAClB,aAAa,CAAC;IACd,eAAe,CAAC;IAChB,gBAAgB,CAAC;IACjB,mBAAmB;IACnB,SAAS;EACX;AAGA,MAAI,OAAO,KAAK,YAAY,MAAM,KAAK,SAAS;AAC9C,YAAQ,iBAAiB;AACzB,YAAQ,aAAa;EACvB;AAEA,MAAI,OAAO,KAAK,eAAe,MAAM,KAAK,YAAY;AACpD,YAAQ,mBAAmB;AAC3B,YAAQ,aAAa;EACvB;AAGA,QAAM,aAAa,OAAO,KAAK,OAAO,YAAY;AAClD,QAAM,YAAY,OAAO,KAAK,MAAM,YAAY;AAGhD,aAAW,WAAW,WAAW;AAC/B,QAAI,EAAE,WAAW,OAAO,eAAe;AACrC,cAAQ,YAAY,KAAK,OAAO;AAChC,cAAQ,aAAa;IACvB;EACF;AAGA,aAAW,WAAW,YAAY;AAChC,QAAI,EAAE,WAAW,MAAM,eAAe;AACpC,cAAQ,cAAc,KAAK,OAAO;AAClC,cAAQ,aAAa;IACvB;EACF;AAGA,aAAW,WAAW,Y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KAAK,IAAI;AAEZ,QAAM,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6BjB,SAAO,GAAG,QAAQ;AAAA,eACL,KAAK,KAAK,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,WAMlB,KAAK,KAAK,IAAI;AAAA,YACb,IAAI;AAAA,mBACG,MAAM,KAAK;AAAA,oBACV,MAAM,YAAY;AAAA,uBACf,MAAM,eAAe;AAAA,cAC9B,KAAK,KAAK,WAAW,CAAC;AAAA;AAAA;AAAA;AAAA,EAIlC,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iFAkB8D,IAAI;AAAA;AAEhF;AAOA,eAAe,cAAc;AAC3B,MAAI,CAAC,MAAM;AACT,YAAQ,MAAM,iCAAiC;AAC/C,YAAQ,MAAM,kDAAkD;AAChE,YAAQ,MAAM,sEAAsE;AACpF,YAAQ,MAAM,EAAE;AAChB,YAAQ,MAAM,0CAA0C;AACxD,YAAQ,MAAM,6DAA6D;AAC3E,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAG9B,UAAQ,MAAM,gDAAgD,IAAI,EAAE;AACtE;AAGA,eAAe,OAAO;AACpB,QAAM,YAAY;AACpB;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,UAAQ,MAAM,WAAW,KAAK;AAC9B,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["path","cachedRulesStr","freshRulesStr","dsId","apiKey","apiBase","toSwiftName","isColorValue","path","path","fs","dsId","apiKey","apiBase"]}
1
+ {"version":3,"sources":["../src/index.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/types.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/fetch.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/sync.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/diff.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/rules.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/formats/css.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/formats/scss.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/formats/less.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/formats/json.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/formats/ts.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/formats/js.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/formats/swift.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/formats/kotlin.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/formats/dart.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/response.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/tokens.ts","../node_modules/.pnpm/@atomixstudio+sync-core@file+..+atomix-sync-core/node_modules/@atomixstudio/sync-core/src/config.ts"],"sourcesContent":["/**\n * Atomix MCP Server - User Design System Mode\n * \n * A minimal MCP server that serves design tokens from a user's\n * Atomix Design System via the public API.\n * \n * Usage:\n * npx @atomixstudio/mcp --ds-id <id> [--api-key <key>]\n * \n * Tools:\n * - getToken: Get a specific token by path\n * - listTokens: List tokens in a category\n * - searchTokens: Search for tokens by name or value\n * - validateUsage: Check if a value follows the design system\n * - getAIToolRules: Generate AI coding rules for this design system\n * - exportMCPConfig: Generate MCP configuration files\n * - getSetupInstructions: Get setup guide for AI tools\n * - syncTokens: Sync tokens to a local file\n * \n * @see https://atomixstudio.eu\n */\n\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n ListResourcesRequestSchema,\n ReadResourceRequestSchema,\n ListPromptsRequestSchema,\n GetPromptRequestSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\n\n// Import from core library\nimport {\n fetchDesignSystem,\n getTokenByPath,\n flattenTokens,\n searchTokens,\n getTokenStats,\n syncTokens as coreSyncTokens,\n compareDesignSystems,\n generateCSSOutput,\n generateSCSSOutput,\n generateLessOutput,\n generateJSONOutput,\n generateTSOutput,\n generateJSOutput,\n generateSwiftOutput,\n generateKotlinOutput,\n generateDartOutput,\n diffTokens,\n formatSyncResponse,\n detectGovernanceChangesByFoundation,\n syncRulesFiles,\n type DesignSystemData,\n type OutputFormat,\n type RulesFileResult,\n type DiffResult,\n} from \"@atomixstudio/sync-core\";\nimport * as path from \"path\";\nimport * as fs from \"fs\";\n\n// ============================================\n// CLI ARGUMENTS (for MCP server configuration)\n// ============================================\n\nfunction parseArgs(): { dsId: string | null; apiKey: string | null; apiBase: string | null } {\n const args = process.argv.slice(2);\n let dsId: string | null = null;\n let apiKey: string | null = null;\n let apiBase: string | null = null;\n\n for (let i = 0; i < args.length; i++) {\n if (args[i] === \"--ds-id\" && args[i + 1]) {\n dsId = args[i + 1];\n i++;\n } else if (args[i] === \"--api-key\" && args[i + 1]) {\n apiKey = args[i + 1];\n i++;\n } else if (args[i] === \"--api-base\" && args[i + 1]) {\n apiBase = args[i + 1];\n i++;\n }\n }\n\n return { dsId, apiKey, apiBase };\n}\n\nconst cliArgs = parseArgs();\nconst { dsId, apiKey } = cliArgs;\nconst apiBase = cliArgs.apiBase || \"https://atomixstudio.eu\";\n\n// ============================================\n// CACHED DATA (for MCP server)\n// ============================================\n\nlet cachedData: DesignSystemData | null = null;\nlet cachedETag: string | null = null;\nlet lastChangeSummary: string | null = null;\n\n// Store affected tokens from last sync for /refactor command\ninterface LastSyncAffectedTokens {\n modified: Array<{ token: string; oldValue: string; newValue: string }>;\n removed: Array<{ token: string; lastValue: string }>;\n added: string[];\n format: string; // \"css\" | \"scss\" | \"swift\" | \"kotlin\" | \"dart\" etc.\n timestamp: string;\n}\nlet lastSyncAffectedTokens: LastSyncAffectedTokens | null = null;\n\n// Helper to get last change summary (MCP-specific, tracks changes for prompts)\nfunction getLastChangeSummary(): string | null {\n return lastChangeSummary;\n}\n\n// Update change summary when fetching (for MCP prompts)\nasync function updateChangeSummary(freshData: DesignSystemData) {\n if (cachedData) {\n const changes = compareDesignSystems(cachedData, freshData);\n lastChangeSummary = changes.summary;\n if (changes.hasChanges) {\n console.error(`[mcp-user] Design system changes detected:\\n${changes.summary}`);\n }\n }\n}\n\n/** Fetch design system for MCP; uses cache and updates cachedData/cachedETag. */\nasync function fetchDesignSystemForMCP(forceRefresh = false): Promise<DesignSystemData> {\n if (!dsId) throw new Error(\"Missing --ds-id. Usage: npx @atomixstudio/mcp --ds-id <id>\");\n const result = await fetchDesignSystem({\n dsId,\n apiKey: apiKey ?? undefined,\n apiBase: apiBase ?? undefined,\n etag: forceRefresh ? undefined : cachedETag ?? undefined,\n forceRefresh,\n });\n if (result.status === 304 && cachedData) return cachedData;\n if (result.status === 304 || !result.data) throw new Error(\"No design system data (304 or null)\");\n cachedData = result.data;\n cachedETag = result.etag;\n await updateChangeSummary(result.data);\n return result.data;\n}\n\n// ============================================\n// TOKEN UTILITIES\n// ============================================\n\nconst TOKEN_CATEGORIES = [\"colors\", \"typography\", \"spacing\", \"sizing\", \"shadows\", \"radius\", \"borders\", \"motion\", \"zIndex\"] as const;\ntype TokenCategory = typeof TOKEN_CATEGORIES[number];\n\n// Token utilities are imported from core library - no local implementations needed\n\n// ============================================\n// MCP SERVER SETUP\n// ============================================\n\nconst server = new Server(\n {\n name: \"atomix-mcp-user\",\n version: \"1.0.17\",\n },\n {\n capabilities: {\n tools: {},\n resources: {},\n prompts: {},\n },\n }\n);\n\n// ============================================\n// TOOL DEFINITIONS\n// ============================================\n\nserver.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: [\n {\n name: \"getToken\",\n description: \"Get a specific design token by its path. Returns the value and CSS variable name.\",\n inputSchema: {\n type: \"object\",\n properties: {\n path: {\n type: \"string\",\n description: \"Token path in dot notation (e.g., 'colors.brand.primary', 'spacing.scale.md')\",\n },\n },\n required: [\"path\"],\n },\n },\n {\n name: \"listTokens\",\n description: \"List all tokens in a category (colors, typography, spacing, sizing, shadows, radius, borders, motion, zIndex).\",\n inputSchema: {\n type: \"object\",\n properties: {\n category: {\n type: \"string\",\n enum: TOKEN_CATEGORIES,\n description: \"Token category to list\",\n },\n subcategory: {\n type: \"string\",\n description: \"Optional subcategory (e.g., 'brand' for colors, 'scale' for spacing)\",\n },\n },\n required: [\"category\"],\n },\n },\n {\n name: \"searchTokens\",\n description: \"Search for tokens by name or value.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"Search query (matches token paths or values)\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"validateUsage\",\n description: \"Check if a CSS value follows the design system. Detects hardcoded values that should use tokens.\",\n inputSchema: {\n type: \"object\",\n properties: {\n value: {\n type: \"string\",\n description: \"CSS value to validate (e.g., '#ff0000', '16px', 'rgb(0,112,97)')\",\n },\n context: {\n type: \"string\",\n enum: [\"color\", \"spacing\", \"radius\", \"shadow\", \"typography\", \"any\"],\n description: \"Context of the value to help find the right token\",\n },\n },\n required: [\"value\"],\n },\n },\n {\n name: \"getAIToolRules\",\n description: \"Generate design system rules for AI coding tools (Cursor, Copilot, Windsurf, etc.).\",\n inputSchema: {\n type: \"object\",\n properties: {\n tool: {\n type: \"string\",\n enum: [\"cursor\", \"copilot\", \"windsurf\", \"cline\", \"continue\", \"zed\", \"generic\", \"all\"],\n description: \"AI tool to generate rules for. Use 'all' to get rules for all tools.\",\n },\n },\n required: [\"tool\"],\n },\n },\n {\n name: \"exportMCPConfig\",\n description: \"Generate MCP configuration file for AI tools.\",\n inputSchema: {\n type: \"object\",\n properties: {\n tool: {\n type: \"string\",\n enum: [\"cursor\", \"claude-desktop\", \"windsurf\", \"continue\", \"vscode\", \"all\"],\n description: \"AI tool to generate MCP config for.\",\n },\n },\n required: [\"tool\"],\n },\n },\n {\n name: \"getSetupInstructions\",\n description: \"Get detailed setup instructions for a specific AI tool.\",\n inputSchema: {\n type: \"object\",\n properties: {\n tool: {\n type: \"string\",\n enum: [\"cursor\", \"copilot\", \"windsurf\", \"cline\", \"continue\", \"zed\", \"claude-desktop\", \"generic\"],\n description: \"AI tool to get setup instructions for.\",\n },\n },\n required: [\"tool\"],\n },\n },\n {\n name: \"syncTokens\",\n description: \"Sync design tokens to a local file. Safe, never breaks UI - adds new tokens, updates existing values, marks deprecated tokens. Use /refactor to migrate deprecated tokens. WARNING: The output file is completely rewritten - only CSS custom properties (variables) are preserved. Custom CSS rules will be lost. Keep custom CSS in a separate file.\",\n inputSchema: {\n type: \"object\",\n properties: {\n output: {\n type: \"string\",\n description: \"Output file path relative to project root (e.g., './src/tokens.css', './DesignTokens.swift')\",\n },\n format: {\n type: \"string\",\n enum: [\"css\", \"scss\", \"less\", \"json\", \"ts\", \"js\", \"swift\", \"kotlin\", \"dart\"],\n description: \"Output format. WEB: css, scss, less, json, ts, js. NATIVE: swift (iOS), kotlin (Android), dart (Flutter). Default: css\",\n },\n },\n required: [\"output\"],\n },\n },\n {\n name: \"getDependencies\",\n description: \"Get suggested dependencies for this design system (icon package, fonts, SKILL.md, token files). Use with /--getstarted prompt. Optional platform and stack for tailored suggestions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n platform: {\n type: \"string\",\n enum: [\"web\", \"ios\", \"android\"],\n description: \"Target platform (web, ios, android). Optional.\",\n },\n stack: {\n type: \"string\",\n description: \"Stack or framework (e.g. react, vue, next, swift, kotlin). Optional.\",\n },\n },\n required: [],\n },\n },\n ],\n };\n});\n\n// ============================================\n// TOOL HANDLERS\n// ============================================\n\nserver.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n\n try {\n // Force refresh for syncTokens to ensure we get the latest data\n const shouldForceRefresh = name === \"syncTokens\";\n const data = await fetchDesignSystemForMCP(shouldForceRefresh);\n\n switch (name) {\n case \"getToken\": {\n const path = args?.path as string;\n const value = getTokenByPath(data.tokens, path);\n \n if (value === undefined) {\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n error: `Token not found: ${path}`,\n suggestion: \"Use listTokens or searchTokens to find available tokens.\",\n availableCategories: TOKEN_CATEGORIES,\n }, null, 2),\n }],\n };\n }\n\n // Find CSS variable for this path\n const cssVarKey = `--atmx-${path.replace(/\\./g, \"-\")}`;\n const cssVar = data.cssVariables[cssVarKey];\n\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n path,\n value,\n cssVariable: cssVar || `var(${cssVarKey})`,\n usage: `style={{ property: \"var(${cssVarKey})\" }}`,\n }, null, 2),\n }],\n };\n }\n\n case \"listTokens\": {\n const category = args?.category as TokenCategory;\n const subcategory = args?.subcategory as string | undefined;\n \n let tokensToList: unknown = data.tokens[category];\n \n if (subcategory && tokensToList && typeof tokensToList === \"object\") {\n tokensToList = getTokenByPath(tokensToList as Record<string, unknown>, subcategory);\n }\n\n if (!tokensToList) {\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n error: `Category not found: ${category}${subcategory ? `.${subcategory}` : \"\"}`,\n availableCategories: TOKEN_CATEGORIES,\n }, null, 2),\n }],\n };\n }\n\n const flat = flattenTokens(tokensToList);\n \n // Enhance tokens with CSS variable names\n const tokensWithCssVars = flat.map(({ path, value }) => {\n // Construct the full path for CSS variable lookup\n const fullPath = subcategory \n ? `${category}.${subcategory}.${path}` \n : `${category}.${path}`;\n \n // Find CSS variable in cssVariables\n let cssVar: string | undefined;\n \n if (category === \"colors\" && subcategory === \"static.brand\") {\n // Brand colors use pattern: --atmx-color-brand-{key}\n // Path is already just the key (e.g., \"testis\", \"primary\")\n cssVar = data.cssVariables[`--atmx-color-brand-${path}`];\n } else if (category === \"colors\" && subcategory?.startsWith(\"modes.\")) {\n // Mode colors use pattern: --atmx-color-{key}\n // Path is already the semantic key (e.g., \"bg-page\", \"text-primary\")\n cssVar = data.cssVariables[`--atmx-color-${path}`];\n } else {\n // For other tokens, try the standard pattern\n const cssVarKey = `--atmx-${fullPath.replace(/\\./g, \"-\")}`;\n cssVar = data.cssVariables[cssVarKey];\n }\n \n return {\n path: fullPath,\n value,\n cssVariable: cssVar || undefined,\n };\n });\n \n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n category,\n subcategory,\n count: tokensWithCssVars.length,\n tokens: tokensWithCssVars.slice(0, 50), // Limit to 50 for readability\n truncated: tokensWithCssVars.length > 50,\n }, null, 2),\n }],\n };\n }\n\n case \"searchTokens\": {\n const query = args?.query as string;\n const results = searchTokens(data.tokens, query);\n \n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n query,\n count: results.length,\n results: results.slice(0, 30),\n truncated: results.length > 30,\n }, null, 2),\n }],\n };\n }\n\n case \"validateUsage\": {\n const value = args?.value as string;\n const context = (args?.context as string) || \"any\";\n \n // Check if value is a hardcoded color\n const isHexColor = /^#[0-9A-Fa-f]{3,8}$/.test(value);\n const isRgbColor = /^rgb\\(|^rgba\\(|^hsl\\(/.test(value);\n const isPixelValue = /^\\d+px$/.test(value);\n \n if (!isHexColor && !isRgbColor && !isPixelValue) {\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n value,\n valid: true,\n message: \"Value appears to be using tokens or is not a design token value.\",\n }, null, 2),\n }],\n };\n }\n\n // Search for matching tokens\n const matches = searchTokens(data.tokens, value);\n \n if (matches.length > 0) {\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n value,\n valid: false,\n message: \"Hardcoded value detected. Use a token instead.\",\n matchingTokens: matches.slice(0, 5),\n suggestion: `Use var(--atmx-${matches[0].path.replace(/\\./g, \"-\")}) instead of ${value}`,\n }, null, 2),\n }],\n };\n }\n\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n value,\n valid: false,\n message: \"Hardcoded value detected. No exact token match found.\",\n suggestion: `Consider adding this value to the design system or use the closest token.`,\n context,\n }, null, 2),\n }],\n };\n }\n\n case \"getAIToolRules\": {\n const tool = args?.tool as string;\n \n // Fetch rules from the API\n const rulesUrl = `${apiBase}/api/ds/${dsId}/rules?format=${tool === \"all\" ? \"all\" : tool}`;\n console.error(`[getAIToolRules] Fetching: ${rulesUrl}`);\n \n const headers: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (apiKey) headers[\"x-api-key\"] = apiKey;\n \n try {\n const response = await fetch(rulesUrl, { headers });\n console.error(`[getAIToolRules] Response status: ${response.status}`);\n \n if (!response.ok) {\n const errorText = await response.text();\n console.error(`[getAIToolRules] Error response: ${errorText}`);\n throw new Error(`Failed to fetch rules: ${response.status} - ${errorText}`);\n }\n\n const rules = await response.json() as { rules?: string[]; categories?: Record<string, string[]> };\n console.error(`[getAIToolRules] Got ${rules.rules?.length || 0} rules`);\n \n return {\n content: [{\n type: \"text\",\n text: JSON.stringify(rules, null, 2),\n }],\n };\n } catch (fetchError) {\n console.error(`[getAIToolRules] Fetch error:`, fetchError);\n throw fetchError;\n }\n }\n\n case \"exportMCPConfig\": {\n const tool = args?.tool as string;\n \n // Generate MCP config locally\n const serverName = data.meta.name.toLowerCase().replace(/[^a-z0-9]/g, \"-\");\n const npxArgs = [\"@atomixstudio/mcp@latest\"];\n if (dsId) npxArgs.push(\"--ds-id\", dsId);\n if (apiKey) npxArgs.push(\"--api-key\", apiKey);\n\n const config = {\n mcpServers: {\n [serverName]: {\n command: \"npx\",\n args: npxArgs,\n },\n },\n };\n\n const configs: Record<string, { path: string; content: string }> = {\n cursor: { path: \".cursor/mcp.json\", content: JSON.stringify(config, null, 2) },\n \"claude-desktop\": { path: \"claude_desktop_config.json\", content: JSON.stringify(config, null, 2) },\n windsurf: { path: \".windsurf/mcp.json\", content: JSON.stringify(config, null, 2) },\n continue: { path: \".continue/config.json\", content: JSON.stringify({ models: [], mcpServers: [{ name: serverName, command: \"npx\", args: npxArgs }] }, null, 2) },\n vscode: { path: \".vscode/settings.json\", content: JSON.stringify({ \"mcp.servers\": config.mcpServers }, null, 2) },\n };\n\n if (tool === \"all\") {\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n message: \"MCP configurations for all tools\",\n configs: Object.entries(configs).map(([t, c]) => ({\n tool: t,\n path: c.path,\n content: JSON.parse(c.content),\n })),\n }, null, 2),\n }],\n };\n }\n\n const selectedConfig = configs[tool as keyof typeof configs];\n if (!selectedConfig) {\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n error: `Unknown tool: ${tool}`,\n availableTools: Object.keys(configs),\n }, null, 2),\n }],\n };\n }\n\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n tool,\n path: selectedConfig.path,\n content: JSON.parse(selectedConfig.content),\n instructions: `Create the file at ${selectedConfig.path} with the content above, then restart your IDE.`,\n }, null, 2),\n }],\n };\n }\n\n case \"getSetupInstructions\": {\n const tool = args?.tool as string;\n \n const instructions: Record<string, string> = {\n cursor: `# Cursor MCP Setup\n\n1. Create \\`.cursor/mcp.json\\` in your project root\n2. Add the MCP configuration (use exportMCPConfig to get it)\n3. Restart Cursor IDE\n4. Verify by asking: \"What design tokens are available?\"\n\n## File Structure\n\n⚠️ **IMPORTANT**: The \\`tokens.css\\` file (or your specified output file) is **completely rewritten** on each sync.\n\n- ✅ **Preserved**: CSS custom properties (variables) - both design system tokens and custom variables\n- ❌ **Lost**: Regular CSS rules (selectors, classes, media queries, etc.)\n\n**Best Practice**: Keep \\`tokens.css\\` separate from your custom CSS. Use a separate file (e.g., \\`custom.css\\`) for custom styles.`,\n\n copilot: `# Copilot Setup\n\n1. Create a Copilot instructions file in your project (e.g. \\`.github/copilot-instructions.md\\`)\n2. Use getAIToolRules({ tool: \"copilot\" }) to get the content\n3. Enable custom instructions in your editor (e.g. \\`github.copilot.chat.codeGeneration.useInstructionFiles\\`: true in settings)\n\n## File Structure\n\n⚠️ **IMPORTANT**: The \\`tokens.css\\` file (or your specified output file) is **completely rewritten** on each sync.\n\n- ✅ **Preserved**: CSS custom properties (variables) - both design system tokens and custom variables\n- ❌ **Lost**: Regular CSS rules (selectors, classes, media queries, etc.)\n\n**Best Practice**: Keep \\`tokens.css\\` separate from your custom CSS. Use a separate file (e.g., \\`custom.css\\`) for custom styles.`,\n\n windsurf: `# Windsurf Setup\n\n1. Create \\`.windsurf/mcp.json\\` in your project root\n2. Create \\`.windsurfrules\\` with rules from getAIToolRules\n3. Restart Windsurf Editor\n\n## File Structure\n\n⚠️ **IMPORTANT**: The \\`tokens.css\\` file (or your specified output file) is **completely rewritten** on each sync.\n\n- ✅ **Preserved**: CSS custom properties (variables) - both design system tokens and custom variables\n- ❌ **Lost**: Regular CSS rules (selectors, classes, media queries, etc.)\n\n**Best Practice**: Keep \\`tokens.css\\` separate from your custom CSS. Use a separate file (e.g., \\`custom.css\\`) for custom styles.`,\n\n cline: `# Cline Setup\n\n1. Create \\`.clinerules\\` in your project root\n2. Cline auto-detects MCP from .cursor/mcp.json\n\n## File Structure\n\n⚠️ **IMPORTANT**: The \\`tokens.css\\` file (or your specified output file) is **completely rewritten** on each sync.\n\n- ✅ **Preserved**: CSS custom properties (variables) - both design system tokens and custom variables\n- ❌ **Lost**: Regular CSS rules (selectors, classes, media queries, etc.)\n\n**Best Practice**: Keep \\`tokens.css\\` separate from your custom CSS. Use a separate file (e.g., \\`custom.css\\`) for custom styles.`,\n\n continue: `# Continue Setup\n\n1. Create/edit \\`.continue/config.json\\`\n2. Add mcpServers configuration\n3. Restart VS Code\n\n## File Structure\n\n⚠️ **IMPORTANT**: The \\`tokens.css\\` file (or your specified output file) is **completely rewritten** on each sync.\n\n- ✅ **Preserved**: CSS custom properties (variables) - both design system tokens and custom variables\n- ❌ **Lost**: Regular CSS rules (selectors, classes, media queries, etc.)\n\n**Best Practice**: Keep \\`tokens.css\\` separate from your custom CSS. Use a separate file (e.g., \\`custom.css\\`) for custom styles.`,\n\n zed: `# Zed Setup\n\n1. Create \\`.zed/assistant/rules.md\\` in your project\n2. Use getAIToolRules({ tool: \"zed\" }) for content\n\n## File Structure\n\n⚠️ **IMPORTANT**: The \\`tokens.css\\` file (or your specified output file) is **completely rewritten** on each sync.\n\n- ✅ **Preserved**: CSS custom properties (variables) - both design system tokens and custom variables\n- ❌ **Lost**: Regular CSS rules (selectors, classes, media queries, etc.)\n\n**Best Practice**: Keep \\`tokens.css\\` separate from your custom CSS. Use a separate file (e.g., \\`custom.css\\`) for custom styles.`,\n\n \"claude-desktop\": `# Claude Desktop Setup\n\n1. Find your Claude config:\n - macOS: ~/Library/Application Support/Claude/claude_desktop_config.json\n - Windows: %APPDATA%\\\\Claude\\\\claude_desktop_config.json\n2. Add MCP server configuration\n3. Restart Claude Desktop\n\n## File Structure\n\n⚠️ **IMPORTANT**: The \\`tokens.css\\` file (or your specified output file) is **completely rewritten** on each sync.\n\n- ✅ **Preserved**: CSS custom properties (variables) - both design system tokens and custom variables\n- ❌ **Lost**: Regular CSS rules (selectors, classes, media queries, etc.)\n\n**Best Practice**: Keep \\`tokens.css\\` separate from your custom CSS. Use a separate file (e.g., \\`custom.css\\`) for custom styles.`,\n\n generic: `# Generic AI Tool Setup\n\n1. Create AI_GUIDELINES.md in your project root\n2. Use getAIToolRules({ tool: \"generic\" }) for content\n3. Reference in your prompts or context\n\n## File Structure\n\n⚠️ **IMPORTANT**: The \\`tokens.css\\` file (or your specified output file) is **completely rewritten** on each sync.\n\n- ✅ **Preserved**: CSS custom properties (variables) - both design system tokens and custom variables\n- ❌ **Lost**: Regular CSS rules (selectors, classes, media queries, etc.)\n\n**Best Practice**: Keep \\`tokens.css\\` separate from your custom CSS. Use a separate file (e.g., \\`custom.css\\`) for custom styles.`,\n };\n\n const instruction = instructions[tool];\n if (!instruction) {\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n error: `Unknown tool: ${tool}`,\n availableTools: Object.keys(instructions),\n }, null, 2),\n }],\n };\n }\n\n return {\n content: [{\n type: \"text\",\n text: instruction,\n }],\n };\n }\n\n case \"syncTokens\": {\n const output = args?.output as string;\n const format = (args?.format as OutputFormat) || \"css\";\n \n if (!output) {\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({ error: \"Missing required parameter: output\" }, null, 2),\n }],\n };\n }\n\n // Check if file exists first to detect deprecated tokens\n const outputPath = path.resolve(process.cwd(), output);\n const fileExists = fs.existsSync(outputPath);\n \n // Read old file if it exists\n const deprecatedTokens: Map<string, string> = new Map();\n const existingTokens: Map<string, string> = new Map();\n \n if (fileExists && [\"css\", \"scss\", \"less\"].includes(format)) {\n const oldContent = fs.readFileSync(outputPath, \"utf-8\");\n \n // Extract CSS variables with their values from old file\n // Pattern: --var-name: value; (handles both with and without comments)\n // Improved regex: handles comments before variables, supports uppercase/numbers in prefix\n const oldVarPattern = /(?:^|\\n)\\s*(?:\\/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*\\/\\s*)?(--[a-zA-Z0-9-]+):\\s*([^;]+);/gm;\n let match;\n while ((match = oldVarPattern.exec(oldContent)) !== null) {\n const varName = match[1];\n const varValue = match[2].trim();\n \n existingTokens.set(varName, varValue);\n \n // Mark as deprecated if NOT in design system (kept for backward compatibility)\n if (!(varName in data.cssVariables)) {\n deprecatedTokens.set(varName, varValue);\n }\n }\n }\n \n // Always merge: DS tokens + existing custom tokens (deprecated get comment but stay in file)\n const mergedCssVariables = { ...data.cssVariables };\n // Note: deprecated tokens are passed separately to get /* DEPRECATED */ comment\n // but custom tokens not in DS are preserved in the output\n\n // Generate content based on format\n // Get dark mode colors for CSS output\n const darkModeColors = (data.tokens?.colors as Record<string, unknown>)?.modes as { dark?: Record<string, string> } | undefined;\n \n // Use mergedCssVariables for CSS-based formats (supports merge mode)\n // Use data.cssVariables for native formats (merge mode not supported)\n let newContent: string;\n switch (format) {\n case \"css\":\n newContent = generateCSSOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"scss\":\n newContent = generateSCSSOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"less\":\n newContent = generateLessOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"json\":\n newContent = generateJSONOutput(data.tokens);\n break;\n case \"js\":\n newContent = generateJSOutput(data.tokens);\n break;\n case \"ts\":\n newContent = generateTSOutput(data.tokens);\n break;\n case \"swift\":\n newContent = generateSwiftOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"kotlin\":\n newContent = generateKotlinOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"dart\":\n newContent = generateDartOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n default:\n newContent = generateCSSOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n }\n\n // Count tokens\n const tokenCount = Object.keys(mergedCssVariables).length;\n const dsTokenCount = Object.keys(data.cssVariables).length;\n const deprecatedCount = deprecatedTokens.size;\n\n let diffSummary = \"\";\n let changes: Array<{ key: string; old: string; new: string }> = [];\n let diff: DiffResult | undefined;\n\n if (fileExists && [\"css\", \"scss\", \"less\"].includes(format)) {\n const oldContent = fs.readFileSync(outputPath, \"utf-8\");\n diff = diffTokens(oldContent, mergedCssVariables, format as OutputFormat, darkModeColors?.dark);\n \n // Count changes (removed tokens are kept as deprecated, not actually removed)\n const lightChanges = diff.added.length + diff.modified.length;\n const darkChanges = diff.addedDark.length + diff.modifiedDark.length;\n const totalChanges = lightChanges + darkChanges + deprecatedCount;\n \n if (totalChanges === 0) {\n const lastUpdated = data.meta.exportedAt \n ? new Date(data.meta.exportedAt).toLocaleString()\n : \"N/A\";\n return {\n content: [{\n type: \"text\",\n text: `✓ Already up to date!\\n\\nFile: ${output}\\nTokens: ${tokenCount}\\nVersion: ${data.meta.version}\\nLast updated: ${lastUpdated}`,\n }],\n };\n }\n\n changes = [...diff.modified, ...diff.modifiedDark];\n \n // Build summary (deprecated tokens are kept, marked for /refactor)\n const lightSummary = lightChanges > 0 ? `Light: ${diff.modified.length} modified, ${diff.added.length} added` : \"\";\n const darkSummary = darkChanges > 0 ? `Dark: ${diff.modifiedDark.length} modified, ${diff.addedDark.length} added` : \"\";\n const deprecatedSummary = deprecatedCount > 0 ? `${deprecatedCount} deprecated (use /refactor)` : \"\";\n diffSummary = [lightSummary, darkSummary, deprecatedSummary].filter(Boolean).join(\" | \");\n \n // Store affected tokens for /refactor command\n const removedTokensWithValues: Array<{ token: string; lastValue: string }> = [];\n for (const [token, value] of deprecatedTokens.entries()) {\n removedTokensWithValues.push({ token, lastValue: value });\n }\n \n lastSyncAffectedTokens = {\n modified: [...diff.modified, ...diff.modifiedDark].map(m => ({\n token: m.key,\n oldValue: m.old,\n newValue: m.new,\n })),\n removed: removedTokensWithValues,\n added: [...diff.added, ...diff.addedDark],\n format,\n timestamp: new Date().toISOString(),\n };\n }\n\n // Write the file\n const outputDir = path.dirname(outputPath);\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n fs.writeFileSync(outputPath, newContent);\n\n // Sync rules files (default: true, same as core syncTokens)\n // IMPORTANT: Keep rules syncing logic here - don't duplicate in formatter\n // The formatter only formats the response, it doesn't perform operations\n let rulesResults: RulesFileResult[] = [];\n try {\n rulesResults = await syncRulesFiles({\n dsId: dsId!,\n apiKey: apiKey ?? undefined,\n apiBase: apiBase ?? undefined,\n rulesDir: process.cwd(),\n });\n } catch (error) {\n // Rules sync is optional, don't fail the whole operation\n console.error(`[syncTokens] Failed to sync rules: ${error}`);\n }\n\n // Detect which foundations have governance changes\n // IMPORTANT: Use the shared helper from core - don't duplicate logic\n const governanceChanges = cachedData \n ? detectGovernanceChangesByFoundation(cachedData, data)\n : [];\n\n // IMPORTANT: Use the shared formatter from core package\n // This ensures MCP and CLI have identical output format\n // All response formatting logic is centralized in formatSyncResponse()\n // Do NOT build custom response text here - use the formatter instead\n const response = formatSyncResponse({\n data,\n output,\n format,\n dsTokenCount,\n deprecatedCount,\n deprecatedTokens,\n diff,\n changes,\n fileExists,\n rulesResults,\n governanceChanges,\n changeSummary: getLastChangeSummary(),\n hasRefactorRecommendation: !!lastSyncAffectedTokens?.removed.length,\n deprecatedTokenCount: lastSyncAffectedTokens?.removed.length || 0,\n });\n\n\n return {\n content: [{\n type: \"text\",\n text: response,\n }],\n };\n }\n\n case \"getDependencies\": {\n const platform = args?.platform as string | undefined;\n const stack = args?.stack as string | undefined;\n const tokens = data.tokens as Record<string, unknown>;\n const typography = tokens?.typography as Record<string, unknown> | undefined;\n const fontFamily = typography?.fontFamily as Record<string, string> | undefined;\n const fontNames: string[] = [];\n if (fontFamily) {\n for (const key of [\"display\", \"heading\", \"body\"]) {\n const v = fontFamily[key];\n if (typeof v === \"string\" && v && !fontNames.includes(v)) fontNames.push(v);\n }\n }\n const icons = tokens?.icons as { library?: string; libraryPackage?: string; nativePackage?: string; style?: string; strokeWidth?: string } | undefined;\n const ICON_PACKAGES: Record<string, { web: string; native: string }> = {\n lucide: { web: \"lucide-react\", native: \"lucide-react-native\" },\n heroicons: { web: \"@heroicons/react\", native: \"heroicons-react-native\" },\n phosphor: { web: \"phosphor-react\", native: \"phosphor-react-native\" },\n };\n const lib = icons?.library || \"lucide\";\n const iconPkgs = ICON_PACKAGES[lib] || ICON_PACKAGES.lucide;\n const payload = {\n iconLibrary: {\n package: iconPkgs.web,\n nativePackage: iconPkgs.native,\n strokeWidthToken: icons?.strokeWidth != null ? \"icons.strokeWidth\" : undefined,\n strokeWidthValue: icons?.strokeWidth,\n performanceHint: \"Use individual SVG imports for tree-shaking. Apply the design system's icon tokens: sizing via getToken('sizing.icon.sm') or listTokens('sizing'), and stroke width via getToken('icons.strokeWidth') when the DS defines it. Do not use hardcoded sizes or stroke widths.\",\n },\n fonts: {\n families: fontNames,\n performanceHint: \"Link fonts via URL (e.g. Google Fonts <link> or CSS @import); no need to download font files or add them to the repo. Prefer font-display: swap when possible. You must also build a typeset: CSS rules (e.g. .typeset-display, .typeset-heading, .typeset-body) that use var(--atmx-typography-*) for font-family, font-size, font-weight, line-height, letter-spacing from getToken/listTokens(typography). Do not create a file that only contains a font import.\",\n },\n skill: {\n path: \".cursor/skills/atomix-ds/SKILL.md\",\n content: GENERIC_SKILL_MD,\n },\n tokenFiles: {\n files: [\"tokens.css\", \"tokens.json\"],\n copyInstructions: \"Call the syncTokens MCP tool to create the token file; do not only suggest the user run sync later.\",\n },\n showcase: platform === \"web\" || !platform\n ? {\n path: \"atomix-setup-showcase.html\",\n template: SHOWCASE_HTML_TEMPLATE,\n substitutionInstructions: \"Replace placeholders with values from the synced token file. MCP/sync/export use the --atmx- prefix. {{TOKENS_CSS_PATH}} = path to the synced token file (e.g. ./tokens.css, same as syncTokens output). {{DS_NAME}} = design system name. {{BRAND_PRIMARY_VAR}} = var(--atmx-color-brand-primary). {{BRAND_PRIMARY_FOREGROUND_VAR}} = var(--atmx-color-brand-primary-foreground). {{HEADING_FONT_VAR}} = var(--atmx-typography-font-family-heading) or var(--atmx-typography-font-family-display). {{FONT_FAMILY_VAR}} = var(--atmx-typography-font-family-body). {{FONT_LINK_TAG}} = Google Fonts <link> for the font, or empty string. Do not invent CSS variable names; use only vars that exist in the export.\",\n }\n : undefined,\n meta: { dsName: data.meta.name, platform: platform ?? undefined, stack: stack ?? undefined },\n };\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify(payload, null, 2),\n }],\n };\n }\n\n default:\n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n error: `Unknown tool: ${name}`,\n availableTools: [\"getToken\", \"listTokens\", \"searchTokens\", \"validateUsage\", \"getAIToolRules\", \"exportMCPConfig\", \"getSetupInstructions\", \"syncTokens\", \"getDependencies\"],\n }, null, 2),\n }],\n };\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n let suggestion = \"Check your MCP server configuration.\";\n \n if (errorMessage.includes(\"Missing --ds-id\")) {\n suggestion = \"Add --ds-id <your-design-system-id> to your MCP server configuration.\";\n } else if (errorMessage.includes(\"Failed to fetch\")) {\n const statusMatch = errorMessage.match(/Failed to fetch design system: (\\d+)/);\n if (statusMatch) {\n const status = statusMatch[1];\n if (status === \"404\") {\n suggestion = `Design system ID \"${dsId}\" not found. Verify the ID is correct or the design system has been published.`;\n } else if (status === \"401\" || status === \"403\") {\n suggestion = \"Design system is private. Add --api-key <your-key> to your MCP server configuration.\";\n } else {\n suggestion = `API request failed (${status}). Check your network connection and API base URL (${apiBase}).`;\n }\n } else {\n suggestion = `Failed to connect to API at ${apiBase}. Check your network connection.`;\n }\n }\n \n return {\n content: [{\n type: \"text\",\n text: JSON.stringify({\n error: errorMessage,\n suggestion,\n configured: {\n dsId: dsId || \"not set\",\n apiBase: apiBase || \"not set\",\n hasApiKey: !!apiKey,\n },\n }, null, 2),\n }],\n isError: true,\n };\n }\n});\n\n// ============================================\n// GENERIC SKILL.MD (coding-platform agnostic)\n// ============================================\n\nconst GENERIC_SKILL_MD = `---\nname: atomix-ds\ndescription: Use the Atomix design system for UI, tokens, and styles. Fetch rules and tokens via MCP tools; never hardcode design values.\n---\n\n# Atomix Design System\n\nUse this skill when editing UI, design system files, or when the user asks to follow the project's design system. Your job is to **get the relevant data from the design system via MCP** and apply it—not to guess or invent values.\n\n## Goal\n\nComplete the user's task using the design system as the single source of truth. Every color, spacing, typography, radius, shadow, or sizing value must come from the MCP tools (tokens or governance rules). Do not hardcode hex codes, pixel values, or font names.\n\n## When to use\n\n- Building or editing UI components, pages, or styles\n- Working in design system or token files (e.g. \\`tokens.css\\`, theme files)\n- User asks to \"follow the design system\", \"use tokens\", or \"match the DS\"\n- Validating or refactoring existing code, UI or visual design for token compliance\n\n## How to get design system data\n\n**1. Governance rules (how to use tokens in code)** \nCall **getAIToolRules** with the tool id for your current environment: \\`cursor\\`, \\`windsurf\\`, \\`copilot\\`, \\`cline\\`, \\`continue\\`, \\`zed\\`, or \\`generic\\`. \nExample: \\`getAIToolRules({ tool: \"cursor\" })\\`. \nAlternatively use the **/--rules** prompt or the resource \\`atomix://rules/<tool>\\`.\n\n**2. Token values (what to use in code)** \n- **getToken(path)** — One token by path (e.g. \\`colors.brand.primary\\`, \\`typography.fontSize.lg\\`, \\`sizing.icon.sm\\`, \\`icons.strokeWidth\\`). Icon stroke width is at \\`icons.strokeWidth\\` when the design system defines it.\n- **listTokens(category)** — All tokens in a category: \\`colors\\`, \\`typography\\`, \\`spacing\\`, \\`sizing\\`, \\`shadows\\`, \\`radius\\`, \\`borders\\`, \\`motion\\`, \\`zIndex\\`. For icon config (e.g. stroke width), use \\`getToken(\"icons.strokeWidth\")\\` since \\`icons\\` is not a list category.\n- **searchTokens(query)** — Find tokens by name or value.\n\n**3. Validation** \n- **validateUsage(value, context)** — Check if a CSS/value should use a token instead (e.g. \\`validateUsage(\"#007061\", \"color\")\\`).\n\n**4. Syncing tokens to a file** \n- **syncTokens({ output, format })** — Writes the current design system tokens to a file (e.g. \\`./tokens.css\\`). Use when the user wants a local token file.\n\nUse the returned rules and token paths/values when generating or editing code. Prefer CSS variables (e.g. \\`var(--atmx-*)\\`) or the exact token references from the tools.\n\n## Best practices\n\n- **Fetch first:** Before writing UI or styles, call getAIToolRules and/or getToken/listTokens so you know the exact tokens and conventions.\n- **Icons:** Apply the design system's icon tokens when rendering icons: sizing via \\`getToken(\"sizing.icon.sm\")\\` or \\`listTokens(\"sizing\")\\`, and stroke width via \\`getToken(\"icons.strokeWidth\")\\` when the DS defines it; do not use hardcoded sizes or stroke widths.\n- **Typography:** Use typography tokens (fontFamily, fontSize, fontWeight, lineHeight, letterSpacing) from the DS for any text; build typesets (Display, Heading, body) from those tokens when creating global styles.\n- **No guessing:** If a value is not in the rules or token list, use searchTokens or listTokens to find the closest match rather than inventing a value.\n`;\n\n// ============================================\n// SETUP SHOWCASE HTML (exact structure for getstarted web)\n// ============================================\n// Placeholders: {{TOKENS_CSS_PATH}}, {{DS_NAME}}, {{BRAND_PRIMARY_VAR}}, {{BRAND_PRIMARY_FOREGROUND_VAR}}, {{HEADING_FONT_VAR}}, {{FONT_FAMILY_VAR}}, {{FONT_LINK_TAG}}\n// All var placeholders must be replaced with actual token var() from the synced file (prefix is --atmx- per MCP/sync/export). No made-up CSS vars.\nconst SHOWCASE_HTML_TEMPLATE = `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Setup complete — {{DS_NAME}}</title>\n {{FONT_LINK_TAG}}\n <link rel=\"stylesheet\" href=\"{{TOKENS_CSS_PATH}}\">\n <style>\n * { box-sizing: border-box; }\n body {\n margin: 0;\n font-family: {{FONT_FAMILY_VAR}}, system-ui, sans-serif;\n background: {{BRAND_PRIMARY_VAR}};\n color: {{BRAND_PRIMARY_FOREGROUND_VAR}};\n min-height: 100vh;\n padding: 2rem;\n display: flex;\n align-items: center;\n justify-content: center;\n text-align: center;\n }\n .wrap { width: 375px; max-width: 100%; }\n .icon { width: 2rem; height: 2rem; margin: 0 auto 1rem; }\n h1 {\n font-family: {{HEADING_FONT_VAR}}, {{FONT_FAMILY_VAR}}, system-ui, sans-serif;\n font-size: clamp(1.5rem, 4vw, 2.25rem);\n font-weight: 700;\n margin: 0 0 0.75rem;\n line-height: 1.25;\n }\n .lead { margin: 0 0 1.5rem; font-size: 1rem; line-height: 1.5; opacity: 0.95; }\n .now { margin: 1.5rem 0 0; font-size: 0.875rem; line-height: 1.6; opacity: 0.95; text-align: left; }\n .now strong { display: block; margin-bottom: 0.5rem; }\n .now ul { margin: 0; padding-left: 1.25rem; }\n .tips { margin-top: 1.5rem; font-size: 0.875rem; line-height: 1.6; opacity: 0.9; }\n .tips a { color: inherit; text-decoration: underline; }\n </style>\n</head>\n<body>\n <div class=\"wrap\">\n <div class=\"icon\" aria-hidden=\"true\">\n <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" width=\"32\" height=\"32\"><path d=\"M20 6L9 17l-5-5\"/></svg>\n </div>\n <h1>You're all set with {{DS_NAME}}</h1>\n <p class=\"lead\">This page uses your design system: brand primary as background, headline and body typesets, and an icon. Token file is linked above.</p>\n <div class=\"now\">\n <strong>What you can do now:</strong>\n <ul>\n <li>Ask your agent to build your designs using the design system tokens</li>\n <li>Build components and pages that use <code>var(--atmx-*)</code> for colors, spacing, and typography</li>\n <li>Run <code>/--rules</code> to load governance rules; run <code>/--sync</code> and <code>/--refactor</code> after you change tokens in Atomix Studio</li>\n </ul>\n </div>\n <p class=\"tips\">Keep the source of truth at <a href=\"https://atomixstudio.eu\" target=\"_blank\" rel=\"noopener\">atomixstudio.eu</a> — avoid editing token values in this repo.</p>\n </div>\n</body>\n</html>\n`;\n\n// ============================================\n// RESOURCE HANDLERS\n// ============================================\n\nconst AI_TOOLS = [\"cursor\", \"copilot\", \"windsurf\", \"cline\", \"continue\", \"zed\", \"generic\"] as const;\n\nserver.setRequestHandler(ListResourcesRequestSchema, async () => {\n try {\n await fetchDesignSystemForMCP();\n // Return empty list so resources are hidden in UI; AI can still read atomix://hello and atomix://rules/<tool> via ReadResource.\n return { resources: [] };\n } catch {\n // ds-id missing or fetch failed: return minimal list so Cursor still shows Resources\n return {\n resources: [\n {\n uri: \"atomix://setup\",\n name: \"Configure MCP\",\n description: \"Add --ds-id to your MCP config to load design system resources\",\n mimeType: \"text/markdown\",\n },\n ],\n };\n }\n});\n\nserver.setRequestHandler(ReadResourceRequestSchema, async (request) => {\n const { uri } = request.params;\n\n // Placeholder when ds-id missing or fetch failed\n if (uri === \"atomix://setup\") {\n return {\n contents: [{\n uri,\n mimeType: \"text/markdown\",\n text: `# Configure Atomix MCP\n\nAdd \\`--ds-id <your-design-system-id>\\` to your MCP server config.\n\nExample (\\`.cursor/mcp.json\\`):\n\\`\\`\\`json\n{\n \"mcpServers\": {\n \"atomix\": {\n \"command\": \"npx\",\n \"args\": [\"@atomixstudio/mcp@latest\", \"--ds-id\", \"<your-ds-id>\"]\n }\n }\n}\n\\`\\`\\`\n\nGet your DS ID from: https://atomixstudio.eu/ds/[your-ds-id]`,\n }],\n };\n }\n\n const data = await fetchDesignSystemForMCP();\n const stats = getTokenStats(data);\n\n // Welcome resource\n if (uri === \"atomix://hello\") {\n const welcome = generateWelcomeMessage(data, stats);\n return {\n contents: [{\n uri,\n mimeType: \"text/markdown\",\n text: welcome,\n }],\n };\n }\n\n // Rules resources\n const rulesMatch = uri.match(/^atomix:\\/\\/rules\\/(.+)$/);\n if (rulesMatch) {\n const tool = rulesMatch[1];\n if (!AI_TOOLS.includes(tool as typeof AI_TOOLS[number])) {\n throw new Error(`Unknown tool: ${tool}. Available: ${AI_TOOLS.join(\", \")}`);\n }\n\n // Fetch rules from API\n const rulesUrl = `${apiBase}/api/ds/${dsId}/rules?format=${tool}`;\n const headers: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (apiKey) headers[\"x-api-key\"] = apiKey;\n\n const response = await fetch(rulesUrl, { headers });\n if (!response.ok) {\n throw new Error(`Failed to fetch rules: ${response.status}`);\n }\n\n const rulesData = await response.json() as { content?: string; tool?: string };\n \n return {\n contents: [{\n uri,\n mimeType: \"text/markdown\",\n text: rulesData.content || JSON.stringify(rulesData, null, 2),\n }],\n };\n }\n\n throw new Error(`Unknown resource: ${uri}`);\n});\n\n// ============================================\n// PROMPTS - Auto-suggest hello on connection\n// ============================================\n\nserver.setRequestHandler(ListPromptsRequestSchema, async () => {\n // Essential commands only. -- prefix works across AI coding tools (Cursor, Windsurf, etc.).\n // No `arguments` on any prompt: Cursor invokes GetPrompt immediately. Prompts with `arguments`\n // cause Cursor to show an argument form/search UI instead of running the prompt. Optional\n // args (tool, platform, stack) are handled inside GetPrompt with defaults.\n const prompts = [\n { name: \"--hello\", description: \"Get started with this design system - overview, tokens, and tools. Run this first!\" },\n { name: \"--getstarted\", description: \"Get started with design system in project. Three phases: scan, report and ask, then create only after you approve.\" },\n { name: \"--rules\", description: \"Get the design system governance rules for your AI coding tool (default: cursor).\" },\n { name: \"--sync\", description: \"Sync tokens to a local file. Safe: adds new, updates existing, marks deprecated. Use /--refactor to migrate.\" },\n { name: \"--refactor\", description: \"Migrate deprecated tokens in codebase. Run after /--sync.\" },\n ];\n\n return { prompts };\n});\n\nserver.setRequestHandler(GetPromptRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n // Map -- prompt names to internal handler names (works across Cursor, Windsurf, etc.)\n const canonicalName =\n name === \"--hello\" ? \"hello\"\n : name === \"--getstarted\" ? \"atomix-setup\"\n : name === \"--rules\" ? \"design-system-rules\"\n : name === \"--sync\" ? \"sync\"\n : name === \"--refactor\" ? \"refactor\"\n : name;\n\n // Try to fetch design system, but handle gracefully if not configured\n // Force refresh for sync prompt to ensure we get latest data\n const shouldForceRefresh = canonicalName === \"sync\";\n let data: DesignSystemData | null = null;\n let stats: ReturnType<typeof getTokenStats> | null = null;\n \n try {\n data = await fetchDesignSystemForMCP(shouldForceRefresh);\n stats = getTokenStats(data);\n } catch (error) {\n // If design system fetch fails, return helpful error message\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n \n if (errorMessage.includes(\"Missing --ds-id\")) {\n // Missing ds-id configuration\n return {\n description: \"MCP Server Configuration Required\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: `The MCP server isn't configured. To use design system prompts, you need to configure the server with:\n- \\`--ds-id\\`: Your design system ID (required - get it from https://atomixstudio.eu/ds/[your-ds-id])\n- \\`--api-key\\`: Your API key (optional - only needed for private design systems)\n\n**Note:** Most design systems are public and don't require an API key. Only add \\`--api-key\\` if your design system is private.\n\nConfigure the MCP server in your Cursor settings, then restart Cursor.`,\n },\n },\n ],\n };\n } else if (errorMessage.includes(\"Failed to fetch\")) {\n // API fetch failed - show actual error details\n const statusMatch = errorMessage.match(/Failed to fetch design system: (\\d+) (.+)/);\n const status = statusMatch ? statusMatch[1] : \"unknown\";\n const details = statusMatch ? statusMatch[2] : errorMessage;\n \n let helpText = `**Error:** Failed to fetch design system from ${apiBase}/api/ds/${dsId}/tokens\\n\\n`;\n helpText += `**Status:** ${status}\\n`;\n helpText += `**Details:** ${details}\\n\\n`;\n \n if (status === \"404\") {\n helpText += `**Possible causes:**\\n`;\n helpText += `- Design system ID \"${dsId}\" doesn't exist\\n`;\n helpText += `- API base URL \"${apiBase}\" is incorrect\\n`;\n helpText += `- Design system hasn't been published yet\\n\\n`;\n helpText += `**Solution:** Verify the design system ID and API base URL in your MCP server configuration.`;\n } else if (status === \"401\" || status === \"403\") {\n helpText += `**Possible causes:**\\n`;\n helpText += `- Design system is private and requires an API key\\n`;\n helpText += `- API key is invalid or expired\\n\\n`;\n helpText += `**Solution:** Add \\`--api-key <your-key>\\` to your MCP server configuration.`;\n } else {\n helpText += `**Possible causes:**\\n`;\n helpText += `- Network connection issue\\n`;\n helpText += `- API server is down\\n`;\n helpText += `- CORS or firewall blocking the request\\n\\n`;\n helpText += `**Solution:** Check your network connection and verify the API base URL is accessible.`;\n }\n \n return {\n description: \"Design System Fetch Failed\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: helpText,\n },\n },\n ],\n };\n }\n // Re-throw other errors\n throw error;\n }\n\n // Helper to build category prompt with metadata and AI rules\n const buildCategoryPrompt = (category: string, instructions: string): string => {\n const lines: string[] = [];\n \n // Header with DS info\n lines.push(`## Design System Information`);\n lines.push(`- **Name**: ${data!.meta.name}`);\n lines.push(`- **Version**: ${data!.meta.version || \"1.0.0\"}`);\n lines.push(`- **Last Published**: ${data!.meta.exportedAt ? new Date(data!.meta.exportedAt).toLocaleDateString() : \"N/A\"}`);\n lines.push(``);\n \n // AI Rules for this category\n const categoryRules = data!.governance.categories?.[category];\n if (categoryRules && categoryRules.length > 0) {\n lines.push(`## AI Rules for ${category.charAt(0).toUpperCase() + category.slice(1)}`);\n categoryRules.forEach((rule, index) => {\n lines.push(`${index + 1}. ${rule}`);\n });\n lines.push(``);\n }\n \n // Instructions\n lines.push(`## Instructions`);\n lines.push(instructions);\n \n return lines.join(\"\\n\");\n };\n\n switch (canonicalName) {\n case \"hello\": {\n const welcome = generateWelcomeMessage(data, stats);\n const helloInstruction = `You are showing the Atomix design system welcome. You MUST do the following in order:\n\n1. **First** — Copy and draw the ASCII art block exactly as it appears below (the code block with the arrow pattern). Output it verbatim before any other text. Do not summarize, skip, or replace it with a description.\n2. **Then** — Output the rest of the welcome message (markdown) exactly as given.\n\nDo not add any introduction or commentary before the ASCII art. The ASCII art must be the very first thing you output.\n\n---\n${welcome}`;\n return {\n description: `Hello — ${data.meta.name} Design System`,\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: helloInstruction,\n },\n },\n ],\n };\n }\n\n case \"design-system-rules\": {\n const tool = (args?.tool as string) || \"cursor\";\n const rulesUrl = `${apiBase}/api/ds/${dsId}/rules?format=${tool}`;\n const headers: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (apiKey) headers[\"x-api-key\"] = apiKey;\n\n const response = await fetch(rulesUrl, { headers });\n if (!response.ok) {\n throw new Error(`Failed to fetch rules: ${response.status}`);\n }\n\n const rulesData = await response.json() as { content?: string };\n \n return {\n description: `Design system rules for ${tool}`,\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: `Show me the design system rules for ${tool}.`,\n },\n },\n {\n role: \"assistant\" as const,\n content: {\n type: \"text\" as const,\n text: rulesData.content || JSON.stringify(rulesData, null, 2),\n },\n },\n ],\n };\n }\n\n case \"spacing\": {\n const instructions = `List all spacing tokens in a table format. Use the listTokens tool with category \"spacing\" and subcategory \"scale\". Format the response as a markdown table with columns: Token Name | Value | CSS Variable. The Token Name should be in short format (e.g., \"spacing.xs\" instead of \"spacing.scale.xs\").`;\n const response = {\n description: \"List all spacing tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: buildCategoryPrompt(\"spacing\", instructions),\n },\n },\n ],\n };\n\n return response;\n }\n\n case \"radius\": {\n const instructions = `List all border radius tokens in a table format. Use the listTokens tool with category \"radius\" and subcategory \"scale\". Format the response as a markdown table with columns: Token Name | Value | CSS Variable. The Token Name should be in short format (e.g., \"radius.sm\" instead of \"radius.scale.sm\").`;\n return {\n description: \"List all border radius tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: buildCategoryPrompt(\"radius\", instructions),\n },\n },\n ],\n };\n }\n\n case \"color\": {\n const instructions = `List all color tokens in a table format showing both light and dark mode values. \n\nFirst, call listTokens with category \"colors\" and subcategory \"modes.light\" to get light mode colors.\nThen, call listTokens with category \"colors\" and subcategory \"modes.dark\" to get dark mode colors.\nAlso call listTokens with category \"colors\" and subcategory \"static.brand\" to get brand colors.\n\nFormat the response as a markdown table with columns: Token Name | Light Mode Value | Dark Mode Value | CSS Variable.\n\nFor brand colors (from static.brand), show the same value in both Light and Dark columns since brand colors don't change with mode.\nFor semantic colors (from modes.light/modes.dark), match tokens by name and show their respective values.\n\nThe Token Name should be in short format:\n- Brand colors: \"colors.brand.primary\" (not \"colors.static.brand.primary\")\n- Semantic colors: \"colors.bgSurface\" (not \"colors.modes.light.bgSurface\")`;\n return {\n description: \"List all color tokens with light/dark mode\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: buildCategoryPrompt(\"colors\", instructions),\n },\n },\n ],\n };\n }\n\n case \"typography\": {\n const instructions = `List all typography tokens in a table format. Use the listTokens tool with category \"typography\" (no subcategory needed). Format the response as a markdown table with columns: Token Name | Value | CSS Variable. Group tokens by type (fontSize, fontWeight, lineHeight, etc.) with section headers.`;\n return {\n description: \"List all typography tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: buildCategoryPrompt(\"typography\", instructions),\n },\n },\n ],\n };\n }\n\n case \"shadow\": {\n const instructions = `List all shadow/elevation tokens in a table format. Use the listTokens tool with category \"shadows\" and subcategory \"elevation\". Format the response as a markdown table with columns: Token Name | Value | CSS Variable. The Token Name should be in short format (e.g., \"shadows.elevation.md\" is fine as-is).`;\n return {\n description: \"List all shadow/elevation tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: buildCategoryPrompt(\"shadows\", instructions),\n },\n },\n ],\n };\n }\n\n case \"border\": {\n const instructions = `List all border width tokens in a table format. Use the listTokens tool with category \"borders\" and subcategory \"width\". Format the response as a markdown table with columns: Token Name | Value | CSS Variable. The Token Name should be in short format (e.g., \"borders.width.sm\" is fine as-is).`;\n return {\n description: \"List all border width tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: buildCategoryPrompt(\"borders\", instructions),\n },\n },\n ],\n };\n }\n\n case \"sizing\": {\n const instructions = `List all sizing tokens in a table format. Call listTokens twice:\n1. category \"sizing\" and subcategory \"height\" for component heights\n2. category \"sizing\" and subcategory \"icon\" for icon sizes\n\nFormat the response as a markdown table with columns: Token Name | Value | CSS Variable. Group by type (height vs icon) with section headers.`;\n return {\n description: \"List all sizing tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: buildCategoryPrompt(\"sizing\", instructions),\n },\n },\n ],\n };\n }\n\n case \"motion\": {\n const instructions = `List all motion tokens in a table format. Call listTokens twice:\n1. category \"motion\" and subcategory \"duration\" for duration tokens\n2. category \"motion\" and subcategory \"easing\" for easing tokens\n\nFormat the response as a markdown table with columns: Token Name | Value | CSS Variable. Group by type (duration vs easing) with section headers.`;\n return {\n description: \"List all motion tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: buildCategoryPrompt(\"motion\", instructions),\n },\n },\n ],\n };\n }\n\n case \"sync\": {\n // Use defaults - no arguments needed\n const output = (args?.output as string) || \"./tokens.css\";\n const format = (args?.format as string) || \"css\";\n \n \n // MCP prompts return messages that the AI interprets\n // Use a very direct, imperative instruction to call the tool\n const response = {\n description: `Sync design tokens to ${output}`,\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: `Call the syncTokens tool now. Use output=\"${output}\" and format=\"${format}\". Execute immediately - do not search or ask questions.`,\n },\n },\n ],\n };\n \n \n return response;\n }\n\n case \"refactor\": {\n // Check if we have affected tokens from last sync\n if (!lastSyncAffectedTokens) {\n return {\n description: \"Refactor codebase for deprecated tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: `No recent sync data available. Please run \\`/sync\\` first to update your token file, then run \\`/refactor\\` to scan your codebase for deprecated token usage.`,\n },\n },\n ],\n };\n }\n\n // Check if there are any deprecated tokens to refactor\n if (lastSyncAffectedTokens.removed.length === 0) {\n return {\n description: \"Refactor codebase for deprecated tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: `✓ No deprecated tokens found in last sync.\\n\\nYour codebase is up to date! The last sync on ${new Date(lastSyncAffectedTokens.timestamp).toLocaleString()} did not remove any tokens.`,\n },\n },\n ],\n };\n }\n\n // Build the refactor instructions\n const format = lastSyncAffectedTokens.format;\n const isNativeFormat = [\"swift\", \"kotlin\", \"dart\"].includes(format);\n \n // Build search patterns based on format\n let searchPatterns = \"\";\n let fileExtensions = \"\";\n \n if (isNativeFormat) {\n // Native format patterns\n const nativeTokens = lastSyncAffectedTokens.removed.map(r => {\n // Convert CSS var name to native format\n // --atmx-color-brand-primary → colorBrandPrimary (Swift/Dart) or ColorBrandPrimary (Kotlin)\n const withoutPrefix = r.token.replace(/^--atmx-/, \"\");\n const camelCase = withoutPrefix.replace(/-([a-z])/g, (_, c) => c.toUpperCase());\n const pascalCase = camelCase.charAt(0).toUpperCase() + camelCase.slice(1);\n return { css: r.token, camel: camelCase, pascal: pascalCase, lastValue: r.lastValue };\n });\n \n if (format === \"swift\") {\n fileExtensions = \".swift files\";\n searchPatterns = nativeTokens.map(t => ` • \\`DesignTokens.*.${t.camel}\\` (was: ${t.lastValue})`).join(\"\\n\");\n } else if (format === \"kotlin\") {\n fileExtensions = \".kt files\";\n searchPatterns = nativeTokens.map(t => ` • \\`DesignTokens.*.${t.pascal}\\` (was: ${t.lastValue})`).join(\"\\n\");\n } else {\n fileExtensions = \".dart files\";\n searchPatterns = nativeTokens.map(t => ` • \\`DesignTokens.${t.camel}\\` (was: ${t.lastValue})`).join(\"\\n\");\n }\n } else {\n // Web format patterns (CSS, SCSS, Less, etc.)\n fileExtensions = \".tsx, .ts, .jsx, .js, .css, .scss, .less, .vue, .svelte files\";\n searchPatterns = lastSyncAffectedTokens.removed.map(r => \n ` • \\`var(${r.token})\\` or \\`\"${r.token}\"\\` (was: ${r.lastValue})`\n ).join(\"\\n\");\n }\n\n const instructions = `Scan the codebase for deprecated design tokens and help update them.\n\n## Deprecated Tokens (${lastSyncAffectedTokens.removed.length})\n\nThe following tokens have been removed from the design system:\n\n${searchPatterns}\n\n## Instructions\n\n1. **Search** for these patterns in ${fileExtensions}:\n - Skip node_modules, dist, build, .next, .git directories\n - Look for both \\`var(--token)\\` and direct string references\n\n2. **Report findings** in this format:\n \\`\\`\\`\n 📄 path/to/file.tsx\n Line 42: background: var(--atmx-color-deprecated);\n Line 78: const color = \"--atmx-color-deprecated\";\n \\`\\`\\`\n\n3. **After listing all findings**, ask:\n > \"Found X instances of deprecated tokens in Y files. Would you like me to update them?\"\n > \n > For each deprecated token, I'll suggest the closest equivalent from the current design system.\n\n4. **If user confirms**:\n - Show the proposed replacement for each instance\n - Apply changes only after user approves\n - For tokens with no clear replacement, ask user which token to use\n\n## Important\n\n- Do NOT make any changes without explicit user confirmation\n- Show before → after for each change\n- If you can't find a suitable replacement token, ask the user\n\n## Available Token Categories\n\nUse \\`/color\\`, \\`/spacing\\`, \\`/radius\\`, \\`/typography\\`, \\`/shadow\\`, \\`/border\\`, \\`/sizing\\`, \\`/motion\\` to see current tokens if you need to find replacements.`;\n\n return {\n description: \"Refactor codebase for deprecated tokens\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: instructions,\n },\n },\n ],\n };\n }\n\n case \"atomix-setup\": {\n const setupInstructions = `You are running **/--getstarted** (get started with design system). Three phases only.\n\n**Rule:** Do not create, write, or modify any file until Phase 3 and only after the user has explicitly approved (e.g. \"Yes\", \"Yes for all\", \"Go ahead\").\n\n## Todo list (required)\n\n- Create a todo list at the start: Phase 1, Phase 2, Phase 3. Work step by step; do not run Phase 3 until the user has replied with approval. Mark items completed as you go.\n\n## Phase 1 – Scan\n\n- Resolve platform/stack: infer from the project (e.g. package.json, build.gradle, Xcode) or ask once: \"Which platform? (e.g. web, Android, iOS)\" and if relevant \"Which stack? (e.g. React, Vue, Next, Swift, Kotlin).\" Do not assume a default.\n- Call **getDependencies** with \\`platform\\` and optional \\`stack\\`. If it fails, tell the user the design system could not be reached and stop.\n- Scan the repo for: .cursor/skills/atomix-ds/SKILL.md, a tokens file (e.g. tokens.css or src/tokens.css), icon package from getDependencies, font links. **Web:** note any existing CSS (globals.css, main.css, Tailwind, etc.). **Native:** note any theme/style files (SwiftUI, Android themes, Compose).\n- Build two lists: **Suggested** (from getDependencies minus what exists) and **Already present**. Include: icon package, font links, skill (.cursor/skills/atomix-ds/SKILL.md), token files; for web, also include the **showcase page** (atomix-setup-showcase.html) if getDependencies returned a \\`showcase\\` object.\n- Do not write, create, or add anything in Phase 1.\n\n## Phase 2 – Report and ask\n\n- Reply with: **Suggested:** [list] and **Already present:** [list].\n- Ask exactly once: \"Do you want me to add the suggested items? (Yes for all, or say which ones.)\"\n- **Stop.** Wait for the user to reply. Do not run Phase 3 in this response.\n\n## Phase 3 – Create (only after user approval)\n\n- Run only when the user has said yes (all or specific items).\n- For each approved item:\n - **Skill:** Write the skill content from getDependencies to .cursor/skills/atomix-ds/SKILL.md.\n - **Token file:** Call **syncTokens** with \\`output\\` set to the path (e.g. \"./src/tokens.css\" or \"./tokens.css\"). You must call syncTokens; do not only suggest the user run it later.\n - **Icon package:** Install per getDependencies. When rendering icons, apply the design system's icon tokens: use getToken(\\`sizing.icon.*\\`) or listTokens(\\`sizing\\`) for size, and getToken(\\`icons.strokeWidth\\`) for stroke width when the DS defines it; do not use hardcoded sizes or stroke widths.\n - **Fonts and typeset:** Add font links (e.g. \\`<link>\\` or \\`@import\\` from Google Fonts). Then build a **typeset** in CSS: use **getToken** / **listTokens** (category \\`typography\\`) to get fontFamily, fontSize, fontWeight, lineHeight, letterSpacing for display, heading, and body, and write CSS rules (e.g. \\`.typeset-display\\`, \\`.typeset-heading\\`, \\`.typeset-body\\`, or \\`h1\\`/\\`h2\\`/\\`p\\`) that set those properties to \\`var(--atmx-typography-*)\\`. The typeset file (or section) must define the full type scale—not only a font import. Do not create a CSS file that contains only a font import.\n - **Showcase page (web only):** If platform is web and getDependencies returned a \\`showcase\\` object, create the file at \\`showcase.path\\` using \\`showcase.template\\`. Replace every placeholder per \\`showcase.substitutionInstructions\\`: TOKENS_CSS_PATH, DS_NAME, BRAND_PRIMARY_VAR (page background), BRAND_PRIMARY_FOREGROUND_VAR (text on brand), HEADING_FONT_VAR (h1), FONT_FAMILY_VAR (body), FONT_LINK_TAG. Use only CSS variable names that exist in the synced token file. Do not change the HTML structure. After creating the file, launch it in the default browser (e.g. \\`open atomix-setup-showcase.html\\` on macOS, \\`xdg-open atomix-setup-showcase.html\\` on Linux, or the equivalent on Windows).\n- Report only what you actually created or updated. Do not claim the token file was added if you did not call syncTokens.\n- **After reporting – styles/theme:**\n - **Web:** If the project already has at least one CSS file: recommend how to integrate Atomix (e.g. import the synced tokens file, use \\`var(--atmx-*)\\`). Do not suggest a new global CSS. Only if there is **no** CSS file at all, ask once: \"There are no CSS files yet. Do you want me to build a global typeset from the design system?\" If yes, create a CSS file that includes: (1) font \\`@import\\` or document that a font link is needed, and (2) **typeset rules**—CSS classes or element rules that set font-family, font-size, font-weight, line-height, letter-spacing using \\`var(--atmx-typography-*)\\` from the token file (e.g. \\`.typeset-display\\`, \\`.typeset-heading\\`, \\`.typeset-body\\`). You must call getToken/listTokens to get the exact typography token paths and write the corresponding var() references. The output must not be only a font import; it must define the full typeset (Display, Heading, body) with every style detail from the design system.\n - **iOS/Android:** If the project already has theme/style files: recommend how to integrate Atomix tokens. Do not suggest a new global theme. Only if there is **no** theme/style at all, ask once: \"There's no theme/style setup yet. Do you want a minimal token-based theme?\" and add only if the user says yes.\n\nCreate your todo list first, then Phase 1 (resolve platform/stack, call getDependencies, scan, build lists), then Phase 2 (report and ask). Do not perform Phase 3 until the user replies.`;\n return {\n description: \"Get started with design system in project (/--getstarted). Create todo list; Phase 1 scan, Phase 2 report and ask, Phase 3 create only after user approval.\",\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: setupInstructions,\n },\n },\n ],\n };\n }\n\n default:\n throw new Error(`Unknown prompt: ${name}`);\n }\n});\n\nfunction generateWelcomeMessage(data: DesignSystemData, stats: ReturnType<typeof getTokenStats>): string {\n const tokenSummary = Object.entries(stats.byCategory)\n .map(([cat, count]) => `${cat}: ${count}`)\n .join(\", \");\n\n const asciiArt = `\n\\`\\`\\`\n ↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘↘ \n ↘↘↘↘↘↘↘↘↘↘↘ \n\\`\\`\\`\n`;\n\n return `${asciiArt}\n# Welcome to ${data.meta.name}\n\n## Design System Overview\n\n| Metric | Value |\n|--------|-------|\n| Name | ${data.meta.name} |\n| DS ID | ${dsId} |\n| Total Tokens | ${stats.total} |\n| CSS Variables | ${stats.cssVariables} |\n| Governance Rules | ${stats.governanceRules} |\n| Version | ${data.meta.version || 1} |\n\n### Token breakdown\n\n${tokenSummary}\n\n---\n\n## Essential commands\n\n| Command | What to expect |\n|---------|----------------|\n| **/--hello** | Get started - overview, tokens, and tools. Run this first! |\n| **/--getstarted** | Get started with design system in project. Three phases; creates files only after you approve. |\n| **/--rules** | Governance rules for your AI tool (Cursor, Copilot, Windsurf, etc.). |\n| **/--sync** | Sync tokens to a local file. Safe: adds new, updates existing, marks deprecated. |\n| **/--refactor** | Migrate deprecated tokens in codebase. Run after /--sync. |\n\n**Suggested next step:** Run **/--getstarted** to set up global styles, icons, fonts, and token files; the AI will list options and ask before adding anything.\n\n---\n\n*Atomix Studio — https://atomixstudio.eu | DS: https://atomixstudio.eu/ds/${dsId}*\n`;\n}\n\n\n// ============================================\n// START SERVER\n// ============================================\n\nasync function startServer() {\n if (!dsId) {\n console.error(\"Error: Missing --ds-id argument\");\n console.error(\"Usage: npx atomix --ds-id <id> [--api-key <key>]\");\n console.error(\"Note: --api-key is optional (only needed for private design systems)\");\n console.error(\"\");\n console.error(\"For sync command: npx atomix sync --help\");\n console.error(\"Get your DS ID from https://atomixstudio.eu/ds/[your-ds-id]\");\n process.exit(1);\n }\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n \n // Log to stderr so it doesn't interfere with MCP protocol on stdout\n console.error(`Atomix MCP Server started for design system: ${dsId}`);\n}\n\n// Start MCP server (no CLI commands - this is MCP-only)\nasync function main() {\n await startServer();\n}\n\nmain().catch((error) => {\n console.error(\"Failed:\", error);\n process.exit(1);\n});\n\n","/**\n * Core Types for Atomix Sync\n * \n * Shared types used across CLI and MCP implementations.\n */\n\nexport interface ExportedTokens {\n tokens: {\n colors: {\n static: { brand: Record<string, string> };\n modes: { light: Record<string, string>; dark: Record<string, string> };\n };\n typography: Record<string, unknown>;\n spacing: { scale: Record<string, string> };\n sizing: { height: Record<string, string>; icon: Record<string, string> };\n shadows: { elevation: Record<string, string> };\n radius: { scale: Record<string, string> };\n borders: { width: Record<string, string> };\n motion: { duration: Record<string, string>; easing: Record<string, string> };\n zIndex: Record<string, number>;\n };\n cssVariables: Record<string, string>;\n governance: {\n rules: string[];\n categories: Record<string, string[]>;\n };\n meta: {\n name: string;\n version: number;\n exportedAt: string;\n };\n}\n\nexport interface DesignSystemData {\n tokens: ExportedTokens[\"tokens\"];\n cssVariables: Record<string, string>;\n governance: ExportedTokens[\"governance\"];\n meta: ExportedTokens[\"meta\"];\n}\n\nexport type OutputFormat = \n | \"css\" | \"scss\" | \"less\" // Web CSS-based\n | \"json\" | \"ts\" | \"js\" // Web JS-based\n | \"swift\" | \"kotlin\" | \"dart\"; // Native mobile\n\nexport interface AtomixConfig {\n dsId: string;\n apiKey?: string;\n apiBase?: string;\n output: string;\n format: OutputFormat;\n // For future codebase scanning\n include?: string[]; // Glob patterns to include\n exclude?: string[]; // Glob patterns to exclude\n}\n\nexport interface SyncOptions {\n dsId: string;\n apiKey?: string;\n apiBase?: string;\n output: string;\n format: OutputFormat;\n yes?: boolean; // Auto-confirm\n rules?: boolean; // Also sync rules files\n rulesDir?: string; // Directory for rules files\n etag?: string; // Cached ETag for conditional requests\n}\n\nexport interface SyncResult {\n success: boolean;\n tokenCount: number;\n deprecatedCount: number;\n etag?: string;\n status?: 200 | 304;\n changes?: DiffResult;\n error?: string;\n}\n\nexport interface DiffResult {\n added: string[];\n modified: Array<{ key: string; old: string; new: string }>;\n removed: string[];\n addedDark: string[];\n modifiedDark: Array<{ key: string; old: string; new: string }>;\n removedDark: string[];\n}\n\nexport interface ChangeSummary {\n hasChanges: boolean;\n versionChanged: boolean;\n timestampChanged: boolean;\n addedTokens: string[];\n removedTokens: string[];\n modifiedTokens: Array<{ token: string; oldValue: string; newValue: string }>;\n governanceChanged: boolean;\n summary: string;\n}\n\nexport interface FetchOptions {\n dsId: string;\n apiKey?: string;\n apiBase?: string;\n etag?: string; // Send If-None-Match header\n forceRefresh?: boolean;\n}\n\nexport interface FetchResult {\n data: DesignSystemData | null; // null if 304 Not Modified\n etag: string;\n status: 200 | 304;\n}\n\n// Default file patterns for codebase scanning\nexport const DEFAULT_INCLUDE = [\n \"**/*.tsx\", // React TypeScript components\n \"**/*.jsx\", // React JavaScript components\n \"**/*.ts\", // TypeScript files\n \"**/*.js\", // JavaScript files\n \"**/*.css\", // CSS stylesheets\n \"**/*.scss\", // SASS files\n \"**/*.less\", // Less files\n \"**/*.vue\", // Vue components\n \"**/*.svelte\", // Svelte components\n \"**/*.astro\", // Astro components\n];\n\nexport const DEFAULT_EXCLUDE = [\n \"node_modules/**\",\n \"dist/**\",\n \"build/**\",\n \".next/**\",\n \".nuxt/**\",\n \".git/**\",\n \"coverage/**\",\n \"**/*.min.js\",\n \"**/*.min.css\",\n \"**/*.d.ts\", // Type definitions\n \"**/*.test.*\", // Test files\n \"**/*.spec.*\", // Spec files\n];\n","/**\n * Fetch Design System Data\n * \n * Handles fetching design system tokens from API with ETag support.\n */\n\nimport type { DesignSystemData, ExportedTokens, FetchOptions, FetchResult, ChangeSummary } from './types.js';\n\n/**\n * Generate ETag from design system metadata\n */\nexport function generateETag(meta: { version: number; updatedAt?: string; exportedAt?: string }): string {\n const ts = meta.updatedAt ?? meta.exportedAt ?? \"\";\n const hash = `${meta.version}-${ts}`;\n return `\"v${hash}\"`; // ETag format: \"v1.0-2024-01-01T00:00:00Z\"\n}\n\n/**\n * Compare two design systems and return change summary\n */\nexport function compareDesignSystems(\n cached: DesignSystemData,\n fresh: DesignSystemData\n): ChangeSummary {\n const changes: ChangeSummary = {\n hasChanges: false,\n versionChanged: false,\n timestampChanged: false,\n addedTokens: [],\n removedTokens: [],\n modifiedTokens: [],\n governanceChanged: false,\n summary: \"\",\n };\n\n // Compare metadata\n if (cached.meta.version !== fresh.meta.version) {\n changes.versionChanged = true;\n changes.hasChanges = true;\n }\n\n if (cached.meta.exportedAt !== fresh.meta.exportedAt) {\n changes.timestampChanged = true;\n changes.hasChanges = true;\n }\n\n // Compare CSS variables (includes all tokens: spacing, typography, colors, etc.)\n const cachedVars = Object.keys(cached.cssVariables);\n const freshVars = Object.keys(fresh.cssVariables);\n\n // Find added tokens (all categories)\n for (const varName of freshVars) {\n if (!(varName in cached.cssVariables)) {\n changes.addedTokens.push(varName);\n changes.hasChanges = true;\n }\n }\n\n // Find removed tokens (all categories)\n for (const varName of cachedVars) {\n if (!(varName in fresh.cssVariables)) {\n changes.removedTokens.push(varName);\n changes.hasChanges = true;\n }\n }\n\n // Find modified tokens (all categories)\n for (const varName of cachedVars) {\n if (varName in fresh.cssVariables) {\n const oldValue = cached.cssVariables[varName];\n const newValue = fresh.cssVariables[varName];\n if (oldValue !== newValue) {\n changes.modifiedTokens.push({\n token: varName,\n oldValue,\n newValue,\n });\n changes.hasChanges = true;\n }\n }\n }\n\n // Compare dark mode colors (stored separately in tokens.colors.modes.dark)\n // These are NOT in cssVariables, so we need to compare them separately\n const cachedDark = (cached.tokens?.colors as Record<string, unknown>)?.modes as { dark?: Record<string, string> } | undefined;\n const freshDark = (fresh.tokens?.colors as Record<string, unknown>)?.modes as { dark?: Record<string, string> } | undefined;\n \n const cachedDarkColors = cachedDark?.dark || {};\n const freshDarkColors = freshDark?.dark || {};\n \n const cachedDarkKeys = Object.keys(cachedDarkColors);\n const freshDarkKeys = Object.keys(freshDarkColors);\n\n // Detect CSS variable prefix from existing cssVariables (fallback to --atmx-color-)\n const firstColorVar = cachedVars.find(v => v.includes(\"-color-\")) || freshVars.find(v => v.includes(\"-color-\"));\n const prefixMatch = firstColorVar?.match(/^(--[a-z]+-color-)/);\n const colorPrefix = prefixMatch ? prefixMatch[1] : \"--atmx-color-\";\n\n // Find added dark mode colors\n for (const key of freshDarkKeys) {\n if (!(key in cachedDarkColors)) {\n const cssVarName = `${colorPrefix}${key}`;\n // Only add if not already in the list (avoid duplicates)\n if (!changes.addedTokens.includes(cssVarName)) {\n changes.addedTokens.push(cssVarName);\n changes.hasChanges = true;\n }\n }\n }\n\n // Find removed dark mode colors\n for (const key of cachedDarkKeys) {\n if (!(key in freshDarkColors)) {\n const cssVarName = `${colorPrefix}${key}`;\n if (!changes.removedTokens.includes(cssVarName)) {\n changes.removedTokens.push(cssVarName);\n changes.hasChanges = true;\n }\n }\n }\n\n // Find modified dark mode colors\n for (const key of cachedDarkKeys) {\n if (key in freshDarkColors) {\n const oldValue = cachedDarkColors[key];\n const newValue = freshDarkColors[key];\n if (oldValue !== newValue) {\n const cssVarName = `${colorPrefix}${key}`;\n // Check if we already have this token in modified list (might be a light mode change too)\n const existingIndex = changes.modifiedTokens.findIndex(m => m.token === cssVarName);\n if (existingIndex >= 0) {\n // Update existing entry to show both light and dark changes\n changes.modifiedTokens[existingIndex].oldValue += ` | dark: ${oldValue}`;\n changes.modifiedTokens[existingIndex].newValue += ` | dark: ${newValue}`;\n } else {\n // Add new dark mode-only change\n changes.modifiedTokens.push({\n token: `${cssVarName} (dark mode)`,\n oldValue,\n newValue,\n });\n changes.hasChanges = true;\n }\n }\n }\n }\n\n // Compare governance rules (AI guide changes)\n // Compare both the rules array and categories object\n const cachedGovernance = cached.governance || { rules: [], categories: {} };\n const freshGovernance = fresh.governance || { rules: [], categories: {} };\n \n const cachedRules = cachedGovernance.rules || [];\n const freshRules = freshGovernance.rules || [];\n const cachedCategories = cachedGovernance.categories || {};\n const freshCategories = freshGovernance.categories || {};\n \n // Compare rules array (deep comparison)\n const cachedRulesStr = JSON.stringify(cachedRules.sort());\n const freshRulesStr = JSON.stringify(freshRules.sort());\n \n // Compare categories object (deep comparison)\n const cachedCategoriesStr = JSON.stringify(cachedCategories, Object.keys(cachedCategories).sort());\n const freshCategoriesStr = JSON.stringify(freshCategories, Object.keys(freshCategories).sort());\n \n if (cachedRulesStr !== freshRulesStr || cachedCategoriesStr !== freshCategoriesStr) {\n changes.governanceChanged = true;\n changes.hasChanges = true;\n }\n\n // Build summary text\n const summaryLines: string[] = [];\n \n if (!changes.hasChanges) {\n summaryLines.push(\"✓ No changes detected - design system is up to date\");\n } else {\n summaryLines.push(\"📦 Design System Changes Detected:\");\n summaryLines.push(\"\");\n\n if (changes.versionChanged) {\n summaryLines.push(` Version: ${cached.meta.version} → ${fresh.meta.version}`);\n }\n\n if (changes.timestampChanged) {\n const cachedDate = new Date(cached.meta.exportedAt).toLocaleString();\n const freshDate = new Date(fresh.meta.exportedAt).toLocaleString();\n summaryLines.push(` Published: ${cachedDate} → ${freshDate}`);\n }\n\n if (changes.addedTokens.length > 0) {\n summaryLines.push(` ➕ Added: ${changes.addedTokens.length} token(s)`);\n if (changes.addedTokens.length <= 10) {\n changes.addedTokens.forEach(token => {\n summaryLines.push(` - ${token}`);\n });\n } else {\n changes.addedTokens.slice(0, 10).forEach(token => {\n summaryLines.push(` - ${token}`);\n });\n summaryLines.push(` ... and ${changes.addedTokens.length - 10} more`);\n }\n }\n\n if (changes.removedTokens.length > 0) {\n summaryLines.push(` ➖ Removed: ${changes.removedTokens.length} token(s)`);\n if (changes.removedTokens.length <= 10) {\n changes.removedTokens.forEach(token => {\n summaryLines.push(` - ${token}`);\n });\n } else {\n changes.removedTokens.slice(0, 10).forEach(token => {\n summaryLines.push(` - ${token}`);\n });\n summaryLines.push(` ... and ${changes.removedTokens.length - 10} more`);\n }\n }\n\n if (changes.modifiedTokens.length > 0) {\n summaryLines.push(` 🔄 Modified: ${changes.modifiedTokens.length} token(s)`);\n if (changes.modifiedTokens.length <= 10) {\n changes.modifiedTokens.forEach(({ token, oldValue, newValue }) => {\n summaryLines.push(` ${token}:`);\n summaryLines.push(` - ${oldValue}`);\n summaryLines.push(` + ${newValue}`);\n });\n } else {\n changes.modifiedTokens.slice(0, 5).forEach(({ token, oldValue, newValue }) => {\n summaryLines.push(` ${token}:`);\n summaryLines.push(` - ${oldValue}`);\n summaryLines.push(` + ${newValue}`);\n });\n summaryLines.push(` ... and ${changes.modifiedTokens.length - 5} more`);\n }\n }\n\n if (changes.governanceChanged) {\n summaryLines.push(` 📝 AI guide updated`);\n }\n }\n\n changes.summary = summaryLines.join(\"\\n\");\n return changes;\n}\n\n/**\n * Detect which foundations have governance changes\n * \n * Compares cached vs fresh governance data and returns an array of foundation names\n * that have changed (e.g., [\"general\", \"colors\", \"typography\"]).\n * \n * @param cached - Previously cached design system data\n * @param fresh - Freshly fetched design system data\n * @returns Array of foundation names that have governance changes\n */\nexport function detectGovernanceChangesByFoundation(\n cached: DesignSystemData,\n fresh: DesignSystemData\n): string[] {\n const changes: string[] = [];\n \n const cachedGov = cached.governance || { rules: [], categories: {} };\n const freshGov = fresh.governance || { rules: [], categories: {} };\n \n // Check general rules (rules array)\n const cachedRulesStr = JSON.stringify((cachedGov.rules || []).sort());\n const freshRulesStr = JSON.stringify((freshGov.rules || []).sort());\n if (cachedRulesStr !== freshRulesStr) {\n changes.push(\"general\");\n }\n \n // Check foundation-specific rules (categories object)\n const cachedCategories = cachedGov.categories || {};\n const freshCategories = freshGov.categories || {};\n \n const allFoundationKeys = new Set([\n ...Object.keys(cachedCategories),\n ...Object.keys(freshCategories),\n ]);\n \n for (const foundation of allFoundationKeys) {\n const cachedRules = cachedCategories[foundation] || [];\n const freshRules = freshCategories[foundation] || [];\n const cachedRulesStr = JSON.stringify(cachedRules.sort());\n const freshRulesStr = JSON.stringify(freshRules.sort());\n \n if (cachedRulesStr !== freshRulesStr) {\n changes.push(foundation);\n }\n }\n \n return changes;\n}\n\n/**\n * Fetch design system from API with ETag support\n */\nexport async function fetchDesignSystem(options: FetchOptions): Promise<FetchResult> {\n const { dsId, apiKey, apiBase = \"https://atomixstudio.eu\", etag, forceRefresh = false } = options;\n\n if (!dsId) {\n throw new Error(\"Missing dsId. Usage: fetchDesignSystem({ dsId: '...' })\");\n }\n\n const url = `${apiBase}/api/ds/${dsId}/tokens?format=export`;\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n \n if (apiKey) {\n headers[\"x-api-key\"] = apiKey;\n }\n \n // Send If-None-Match if we have cached ETag\n if (etag) {\n headers[\"if-none-match\"] = etag;\n }\n\n const response = await fetch(url, { headers });\n \n if (response.status === 304) {\n // Not Modified - return null data, same ETag\n return {\n data: null,\n etag: etag!,\n status: 304,\n };\n }\n \n if (!response.ok) {\n const text = await response.text();\n throw new Error(`Failed to fetch design system: ${response.status} ${text}`);\n }\n\n const data = await response.json() as ExportedTokens;\n \n // Extract ETag from response header or generate from meta\n const responseETag = response.headers.get('etag');\n const finalETag = responseETag || generateETag(data.meta);\n \n // Transform to DesignSystemData format\n const designSystemData: DesignSystemData = {\n tokens: data.tokens,\n cssVariables: data.cssVariables,\n governance: data.governance,\n meta: data.meta,\n };\n \n return {\n data: designSystemData,\n etag: finalETag,\n status: 200,\n };\n}\n","/**\n * Core Sync Function\n * \n * Unified sync logic used by both CLI and MCP.\n */\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport type { SyncOptions, SyncResult, DesignSystemData, OutputFormat, DiffResult } from './types.js';\nimport { fetchDesignSystem } from './fetch.js';\nimport { diffTokens } from './diff.js';\nimport { syncRulesFiles } from './rules.js';\nimport {\n generateCSSOutput,\n generateSCSSOutput,\n generateLessOutput,\n generateJSONOutput,\n generateTSOutput,\n generateJSOutput,\n generateSwiftOutput,\n generateKotlinOutput,\n generateDartOutput,\n} from './formats/index.js';\n\n/**\n * Sync design tokens to a local file\n */\nexport async function syncTokens(options: SyncOptions): Promise<SyncResult> {\n const {\n dsId,\n apiKey,\n apiBase = \"https://atomixstudio.eu\",\n output,\n format,\n yes = false,\n rules = true, // Default to true (sync rules by default)\n rulesDir,\n etag, // Optional cached ETag\n } = options;\n\n try {\n // Fetch design system with ETag support\n const fetchResult = await fetchDesignSystem({\n dsId,\n apiKey,\n apiBase,\n etag,\n forceRefresh: true,\n });\n\n // Handle 304 Not Modified\n if (fetchResult.status === 304) {\n return {\n success: true,\n tokenCount: 0,\n deprecatedCount: 0,\n etag: fetchResult.etag,\n status: 304,\n };\n }\n\n if (!fetchResult.data) {\n return {\n success: false,\n tokenCount: 0,\n deprecatedCount: 0,\n error: \"No data returned from API\",\n };\n }\n\n const data = fetchResult.data;\n\n // Check if file exists first to detect deprecated tokens\n const outputPath = path.resolve(process.cwd(), output);\n const fileExists = fs.existsSync(outputPath);\n \n // Read old file if it exists\n const deprecatedTokens: Map<string, string> = new Map();\n const existingTokens: Map<string, string> = new Map();\n \n if (fileExists) {\n if ([\"css\", \"scss\", \"less\"].includes(format)) {\n // For CSS-based formats, extract CSS variables\n const oldContent = fs.readFileSync(outputPath, \"utf-8\");\n // Improved regex: handles comments before variables, supports uppercase/numbers in prefix\n const oldVarPattern = /(?:^|\\n)\\s*(?:\\/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*\\/\\s*)?(--[a-zA-Z0-9-]+):\\s*([^;]+);/gm;\n let match;\n while ((match = oldVarPattern.exec(oldContent)) !== null) {\n const varName = match[1];\n const varValue = match[2].trim();\n \n existingTokens.set(varName, varValue);\n \n // Mark as deprecated if NOT in design system (kept for backward compatibility)\n if (!(varName in data.cssVariables)) {\n deprecatedTokens.set(varName, varValue);\n }\n }\n } else if ([\"swift\", \"kotlin\", \"dart\"].includes(format)) {\n // For native formats, extract tokens and convert to CSS variable names\n const oldContent = fs.readFileSync(outputPath, \"utf-8\");\n let tokenPattern: RegExp;\n \n if (format === \"swift\") {\n tokenPattern = /static\\s+let\\s+(\\w+)\\s*=\\s*[^;]+;/g;\n } else if (format === \"kotlin\") {\n tokenPattern = /val\\s+(\\w+)\\s*=\\s*[^;]+/g;\n } else {\n tokenPattern = /static\\s+const\\s+(\\w+)\\s*=\\s*[^;]+;/g;\n }\n \n let match;\n while ((match = tokenPattern.exec(oldContent)) !== null) {\n const nativeName = match[1];\n // Convert native name to CSS variable name (approximate)\n const kebab = nativeName\n .replace(/([A-Z])/g, \"-$1\")\n .toLowerCase()\n .replace(/^-/, \"\");\n const cssVarName = `--atmx-${kebab}`;\n \n existingTokens.set(cssVarName, \"\");\n \n // Mark as deprecated if NOT in design system\n if (!(cssVarName in data.cssVariables)) {\n deprecatedTokens.set(cssVarName, \"\");\n }\n }\n }\n }\n \n // Always use DS tokens (deprecated tokens are kept via generateXOutput functions)\n const mergedCssVariables = { ...data.cssVariables };\n\n // Generate new content based on format\n // Get dark mode colors for CSS output\n const darkModeColors = (data.tokens?.colors as Record<string, unknown>)?.modes as { dark?: Record<string, string> } | undefined;\n \n // Use mergedCssVariables for CSS-based formats (supports merge mode)\n let newContent: string;\n switch (format) {\n case \"css\":\n newContent = generateCSSOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"scss\":\n newContent = generateSCSSOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"less\":\n newContent = generateLessOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"json\":\n newContent = generateJSONOutput(data.tokens);\n break;\n case \"js\":\n newContent = generateJSOutput(data.tokens);\n break;\n case \"ts\":\n newContent = generateTSOutput(data.tokens);\n break;\n case \"swift\":\n newContent = generateSwiftOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"kotlin\":\n newContent = generateKotlinOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n case \"dart\":\n newContent = generateDartOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n default:\n newContent = generateCSSOutput(mergedCssVariables, darkModeColors?.dark, deprecatedTokens);\n break;\n }\n\n // CSS-based formats support diffing\n const supportsDiff = [\"css\", \"scss\", \"less\"].includes(format);\n const deprecatedCount = deprecatedTokens.size;\n let diffResult: DiffResult | undefined;\n \n if (fileExists && supportsDiff) {\n const oldContent = fs.readFileSync(outputPath, \"utf-8\");\n diffResult = diffTokens(oldContent, mergedCssVariables, format as OutputFormat, darkModeColors?.dark);\n\n // Count changes (deprecated tokens are kept, not removed)\n const lightChanges = diffResult.added.length + diffResult.modified.length;\n const darkChanges = diffResult.addedDark.length + diffResult.modifiedDark.length;\n const totalChanges = lightChanges + darkChanges + deprecatedCount;\n\n if (totalChanges === 0) {\n // Already up to date - return early\n return {\n success: true,\n tokenCount: Object.keys(mergedCssVariables).length,\n deprecatedCount,\n etag: fetchResult.etag,\n status: 200,\n changes: diffResult,\n };\n }\n }\n\n // Write file\n const outputDir = path.dirname(outputPath);\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n fs.writeFileSync(outputPath, newContent);\n\n // Sync rules files if requested\n let rulesResults;\n if (rules) {\n rulesResults = await syncRulesFiles({\n dsId,\n apiKey,\n apiBase,\n rulesDir,\n });\n }\n\n return {\n success: true,\n tokenCount: Object.keys(mergedCssVariables).length,\n deprecatedCount,\n etag: fetchResult.etag,\n status: 200,\n changes: diffResult,\n };\n } catch (error) {\n return {\n success: false,\n tokenCount: 0,\n deprecatedCount: 0,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n","/**\n * Diff Logic\n * \n * Functions for comparing token files and detecting changes.\n */\n\nimport type { OutputFormat, DiffResult } from './types.js';\n\nexport function diffTokens(\n oldContent: string,\n newCssVars: Record<string, string>,\n format: OutputFormat,\n newDarkVars?: Record<string, string>\n): DiffResult {\n const added: string[] = [];\n const modified: Array<{ key: string; old: string; new: string }> = [];\n const removed: string[] = [];\n const addedDark: string[] = [];\n const modifiedDark: Array<{ key: string; old: string; new: string }> = [];\n const removedDark: string[] = [];\n\n // CSS-based formats (css, scss, less) all use CSS variables\n if (format === \"css\" || format === \"scss\" || format === \"less\") {\n // Split old content into light mode (:root) and dark mode (.dark) sections\n // Find the :root section\n const rootMatch = oldContent.match(/:root\\s*\\{([^}]*)\\}/);\n const darkMatch = oldContent.match(/\\.dark[^{]*\\{([^}]*)\\}/);\n \n // Parse light mode variables from :root\n const oldLightVars: Record<string, string> = {};\n if (rootMatch) {\n const rootContent = rootMatch[1];\n const varRegex = /(--[\\w-]+):\\s*([^;]+);/g;\n let match;\n while ((match = varRegex.exec(rootContent)) !== null) {\n oldLightVars[match[1]] = match[2].trim();\n }\n } else {\n // Fallback: parse everything (old behavior for files without sections)\n const varRegex = /(--[\\w-]+):\\s*([^;]+);/g;\n let match;\n while ((match = varRegex.exec(oldContent)) !== null) {\n // Only take the first occurrence to get light mode values\n if (!(match[1] in oldLightVars)) {\n oldLightVars[match[1]] = match[2].trim();\n }\n }\n }\n\n // Parse dark mode variables from .dark\n const oldDarkVars: Record<string, string> = {};\n if (darkMatch) {\n const darkContent = darkMatch[1];\n const varRegex = /(--[\\w-]+):\\s*([^;]+);/g;\n let match;\n while ((match = varRegex.exec(darkContent)) !== null) {\n oldDarkVars[match[1]] = match[2].trim();\n }\n }\n\n // Compare light mode\n for (const [key, value] of Object.entries(newCssVars)) {\n if (!(key in oldLightVars)) {\n added.push(key);\n } else if (oldLightVars[key] !== value) {\n modified.push({ key, old: oldLightVars[key], new: value });\n }\n }\n\n for (const key of Object.keys(oldLightVars)) {\n if (!(key in newCssVars)) {\n removed.push(key);\n }\n }\n\n // Compare dark mode if new dark vars provided\n if (newDarkVars && Object.keys(newDarkVars).length > 0) {\n // Generate the expected CSS variable names for dark mode\n // newDarkVars keys are like \"bg-page\", need to match \"--atmx-color-bg-page\"\n const firstKey = Object.keys(newCssVars)[0] || \"--atmx-\";\n const prefixMatch = firstKey.match(/^(--[a-z]+-)/);\n const prefix = prefixMatch ? prefixMatch[1] : \"--atmx-\";\n\n for (const [key, value] of Object.entries(newDarkVars)) {\n const cssVarName = `${prefix}color-${key}`;\n if (!(cssVarName in oldDarkVars)) {\n addedDark.push(cssVarName);\n } else if (oldDarkVars[cssVarName] !== value) {\n modifiedDark.push({ key: cssVarName, old: oldDarkVars[cssVarName], new: value });\n }\n }\n\n for (const key of Object.keys(oldDarkVars)) {\n // Extract the short key from --atmx-color-bg-page -> bg-page\n const shortKey = key.replace(new RegExp(`^${prefix}color-`), \"\");\n if (!(shortKey in newDarkVars)) {\n removedDark.push(key);\n }\n }\n }\n }\n\n return { added, modified, removed, addedDark, modifiedDark, removedDark };\n}\n","/**\n * Rules File Syncing\n * \n * Functions for syncing AI tool rules files.\n */\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\n\nexport interface SyncRulesOptions {\n dsId: string;\n apiKey?: string;\n apiBase?: string;\n rulesDir?: string;\n}\n\nexport interface RulesFileResult {\n tool: string;\n filename: string;\n path: string;\n success: boolean;\n error?: string;\n}\n\nexport async function syncRulesFiles(options: SyncRulesOptions): Promise<RulesFileResult[]> {\n const { dsId, apiKey, apiBase = \"https://atomixstudio.eu\", rulesDir = process.cwd() } = options;\n \n const rulesDirResolved = path.resolve(process.cwd(), rulesDir);\n \n // Detect which AI tools are likely in use based on existing files\n const toolsToSync: Array<{ tool: string; filename: string; dir?: string }> = [\n { tool: \"cursor\", filename: \".cursorrules\" },\n { tool: \"windsurf\", filename: \".windsurfrules\" },\n { tool: \"cline\", filename: \".clinerules\" },\n { tool: \"continue\", filename: \".continuerules\" },\n { tool: \"copilot\", filename: \"copilot-instructions.md\", dir: \".github\" },\n { tool: \"generic\", filename: \"AI_GUIDELINES.md\" },\n ];\n \n // Check which tools have existing files or should be created\n const existingTools = toolsToSync.filter(t => {\n const filePath = t.dir \n ? path.join(rulesDirResolved, t.dir, t.filename)\n : path.join(rulesDirResolved, t.filename);\n return fs.existsSync(filePath);\n });\n \n // If no existing rules files, create .cursorrules by default\n const toolsToWrite = existingTools.length > 0 \n ? existingTools \n : [{ tool: \"cursor\", filename: \".cursorrules\" }];\n \n const results: RulesFileResult[] = [];\n \n for (const { tool, filename, dir } of toolsToWrite) {\n try {\n // Fetch rules from API\n const rulesUrl = `${apiBase}/api/ds/${dsId}/rules?format=${tool}`;\n const headers: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (apiKey) headers[\"x-api-key\"] = apiKey;\n \n const response = await fetch(rulesUrl, { headers });\n if (!response.ok) {\n results.push({\n tool,\n filename,\n path: dir ? `${dir}/${filename}` : filename,\n success: false,\n error: `Failed to fetch ${tool} rules: ${response.status}`,\n });\n continue;\n }\n \n const rulesData = await response.json() as { content?: string };\n if (!rulesData.content) {\n results.push({\n tool,\n filename,\n path: dir ? `${dir}/${filename}` : filename,\n success: false,\n error: `No content for ${tool} rules`,\n });\n continue;\n }\n \n // Write the file\n const targetDir = dir ? path.join(rulesDirResolved, dir) : rulesDirResolved;\n if (!fs.existsSync(targetDir)) {\n fs.mkdirSync(targetDir, { recursive: true });\n }\n \n const filePath = path.join(targetDir, filename);\n fs.writeFileSync(filePath, rulesData.content);\n \n results.push({\n tool,\n filename,\n path: dir ? `${dir}/${filename}` : filename,\n success: true,\n });\n } catch (error) {\n results.push({\n tool,\n filename,\n path: dir ? `${dir}/${filename}` : filename,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n \n return results;\n}\n","/**\n * CSS Format Generator\n * \n * Generates CSS output with CSS custom properties and dark mode support.\n */\n\nexport function generateCSSOutput(\n cssVariables: Record<string, string>,\n darkModeColors?: Record<string, string>,\n deprecatedTokens: Map<string, string> = new Map()\n): string {\n const lines = [\n \"/* Atomix Design System Tokens\",\n \" * Auto-generated - do not edit manually\",\n ` * Synced: ${new Date().toISOString()}`,\n \" *\",\n \" * WARNING: This file is completely rewritten on each sync.\",\n \" * Only CSS custom properties (variables) are preserved.\",\n \" * Custom CSS rules (selectors, classes, etc.) will be lost.\",\n \" * Keep custom CSS in a separate file.\",\n \" */\",\n \"\",\n \"/* Light mode (default) */\",\n \":root {\"\n ];\n \n // Merge current and deprecated tokens, then sort\n const allVars = new Map<string, { value: string; deprecated: boolean }>();\n \n // Add current tokens\n for (const [key, value] of Object.entries(cssVariables)) {\n allVars.set(key, { value, deprecated: false });\n }\n \n // Add deprecated tokens\n for (const [key, value] of deprecatedTokens.entries()) {\n allVars.set(key, { value, deprecated: true });\n }\n \n // Sort all variables by name\n const sortedKeys = Array.from(allVars.keys()).sort();\n \n for (const key of sortedKeys) {\n const { value, deprecated } = allVars.get(key)!;\n if (deprecated) {\n lines.push(` /* DEPRECATED */ ${key}: ${value};`);\n } else {\n lines.push(` ${key}: ${value};`);\n }\n }\n \n lines.push(\"}\");\n \n // Add dark mode overrides if provided\n if (darkModeColors && Object.keys(darkModeColors).length > 0) {\n lines.push(\"\");\n lines.push(\"/* Dark mode */\");\n lines.push(\".dark,\");\n lines.push(\"[data-theme=\\\"dark\\\"] {\");\n \n // Detect prefix from cssVariables keys\n const firstKey = sortedKeys[0] || \"--atmx-\";\n const prefixMatch = firstKey.match(/^(--[a-z]+-)/);\n const prefix = prefixMatch ? prefixMatch[1] : \"--atmx-\";\n \n // Sort dark mode keys for consistent output\n const sortedDarkKeys = Object.keys(darkModeColors).sort();\n for (const key of sortedDarkKeys) {\n // Dark mode colors are stored with keys like \"bg-page\", \"text-primary\"\n // Convert to CSS variable names: --atmx-color-bg-page\n lines.push(` ${prefix}color-${key}: ${darkModeColors[key]};`);\n }\n \n lines.push(\"}\");\n }\n \n lines.push(\"\");\n \n return lines.join(\"\\n\");\n}\n","/**\n * SCSS Format Generator\n * \n * Generates SCSS output with CSS variables and SCSS variables.\n */\n\nexport function generateSCSSOutput(\n cssVariables: Record<string, string>,\n darkModeColors?: Record<string, string>,\n deprecatedTokens: Map<string, string> = new Map()\n): string {\n const lines = [\n \"// Atomix Design System Tokens\",\n \"// Auto-generated - do not edit manually\",\n `// Synced: ${new Date().toISOString()}`,\n \"\",\n \"// CSS Custom Properties (for use in CSS/HTML)\",\n \"// Light mode (default)\",\n \":root {\"\n ];\n \n // Merge current and deprecated tokens, then sort\n const allVars = new Map<string, { value: string; deprecated: boolean }>();\n \n // Add current tokens\n for (const [key, value] of Object.entries(cssVariables)) {\n allVars.set(key, { value, deprecated: false });\n }\n \n // Add deprecated tokens\n for (const [key, value] of deprecatedTokens.entries()) {\n allVars.set(key, { value, deprecated: true });\n }\n \n // Sort all variables by name\n const sortedKeys = Array.from(allVars.keys()).sort();\n \n for (const key of sortedKeys) {\n const { value, deprecated } = allVars.get(key)!;\n if (deprecated) {\n lines.push(` // DEPRECATED ${key}: ${value};`);\n } else {\n lines.push(` ${key}: ${value};`);\n }\n }\n \n lines.push(\"}\");\n \n // Add dark mode CSS variables\n if (darkModeColors && Object.keys(darkModeColors).length > 0) {\n lines.push(\"\");\n lines.push(\"// Dark mode\");\n lines.push(\".dark,\");\n lines.push(\"[data-theme=\\\"dark\\\"] {\");\n \n const firstKey = sortedKeys[0] || \"--atmx-\";\n const prefixMatch = firstKey.match(/^(--[a-z]+-)/);\n const prefix = prefixMatch ? prefixMatch[1] : \"--atmx-\";\n \n for (const [key, value] of Object.entries(darkModeColors)) {\n lines.push(` ${prefix}color-${key}: ${value};`);\n }\n \n lines.push(\"}\");\n }\n \n lines.push(\"\");\n lines.push(\"// SCSS Variables (light mode values)\");\n \n // Include deprecated tokens in SCSS variables too\n for (const key of sortedKeys) {\n const { value, deprecated } = allVars.get(key)!;\n const scssVar = \"$\" + key.replace(/^--/, \"\");\n if (deprecated) {\n lines.push(`// DEPRECATED ${scssVar}: ${value};`);\n } else {\n lines.push(`${scssVar}: ${value};`);\n }\n }\n \n // Add dark mode SCSS variables\n if (darkModeColors && Object.keys(darkModeColors).length > 0) {\n lines.push(\"\");\n lines.push(\"// SCSS Variables (dark mode values)\");\n \n const firstKey = Object.keys(cssVariables)[0] || \"--atmx-\";\n const prefixMatch = firstKey.match(/^--([a-z]+)-/);\n const prefix = prefixMatch ? prefixMatch[1] : \"atmx\";\n \n for (const [key, value] of Object.entries(darkModeColors)) {\n const scssVar = `$${prefix}-color-${key}-dark`;\n lines.push(`${scssVar}: ${value};`);\n }\n }\n \n lines.push(\"\");\n \n return lines.join(\"\\n\");\n}\n","/**\n * Less Format Generator\n * \n * Generates Less output with CSS variables and Less variables.\n */\n\nexport function generateLessOutput(\n cssVariables: Record<string, string>,\n darkModeColors?: Record<string, string>,\n deprecatedTokens: Map<string, string> = new Map()\n): string {\n const lines = [\n \"// Atomix Design System Tokens\",\n \"// Auto-generated - do not edit manually\",\n `// Synced: ${new Date().toISOString()}`,\n \"\",\n \"// CSS Custom Properties (for use in CSS/HTML)\",\n \"// Light mode (default)\",\n \":root {\"\n ];\n \n // Merge current and deprecated tokens, then sort\n const allVars = new Map<string, { value: string; deprecated: boolean }>();\n \n // Add current tokens\n for (const [key, value] of Object.entries(cssVariables)) {\n allVars.set(key, { value, deprecated: false });\n }\n \n // Add deprecated tokens\n for (const [key, value] of deprecatedTokens.entries()) {\n allVars.set(key, { value, deprecated: true });\n }\n \n // Sort all variables by name\n const sortedKeys = Array.from(allVars.keys()).sort();\n \n for (const key of sortedKeys) {\n const { value, deprecated } = allVars.get(key)!;\n if (deprecated) {\n lines.push(` // DEPRECATED ${key}: ${value};`);\n } else {\n lines.push(` ${key}: ${value};`);\n }\n }\n \n lines.push(\"}\");\n \n // Add dark mode CSS variables\n if (darkModeColors && Object.keys(darkModeColors).length > 0) {\n lines.push(\"\");\n lines.push(\"// Dark mode\");\n lines.push(\".dark,\");\n lines.push(\"[data-theme=\\\"dark\\\"] {\");\n \n const firstKey = Object.keys(cssVariables)[0] || \"--atmx-\";\n const prefixMatch = firstKey.match(/^(--[a-z]+-)/);\n const prefix = prefixMatch ? prefixMatch[1] : \"--atmx-\";\n \n for (const [key, value] of Object.entries(darkModeColors)) {\n lines.push(` ${prefix}color-${key}: ${value};`);\n }\n \n lines.push(\"}\");\n }\n \n lines.push(\"\");\n lines.push(\"// Less Variables (light mode values)\");\n \n for (const [key, value] of Object.entries(cssVariables)) {\n const lessVar = \"@\" + key.replace(/^--/, \"\");\n lines.push(`${lessVar}: ${value};`);\n }\n \n // Add dark mode Less variables\n if (darkModeColors && Object.keys(darkModeColors).length > 0) {\n lines.push(\"\");\n lines.push(\"// Less Variables (dark mode values)\");\n \n const firstKey = Object.keys(cssVariables)[0] || \"--atmx-\";\n const prefixMatch = firstKey.match(/^--([a-z]+)-/);\n const prefix = prefixMatch ? prefixMatch[1] : \"atmx\";\n \n for (const [key, value] of Object.entries(darkModeColors)) {\n const lessVar = `@${prefix}-color-${key}-dark`;\n lines.push(`${lessVar}: ${value};`);\n }\n }\n \n lines.push(\"\");\n \n return lines.join(\"\\n\");\n}\n","/**\n * JSON Format Generator\n * \n * Generates JSON output with raw token structure.\n */\n\nimport type { ExportedTokens } from '../types.js';\n\nexport function generateJSONOutput(tokens: ExportedTokens[\"tokens\"]): string {\n return JSON.stringify(tokens, null, 2);\n}\n","/**\n * TypeScript Format Generator\n * \n * Generates TypeScript output with types.\n */\n\nimport type { ExportedTokens } from '../types.js';\n\nexport function generateTSOutput(tokens: ExportedTokens[\"tokens\"]): string {\n return `// Atomix Design System Tokens\n// Auto-generated - do not edit manually\n// Synced: ${new Date().toISOString()}\n\nexport const tokens = ${JSON.stringify(tokens, null, 2)} as const;\n\nexport type Tokens = typeof tokens;\n`;\n}\n","/**\n * JavaScript Format Generator\n * \n * Generates JavaScript ES module output.\n */\n\nimport type { ExportedTokens } from '../types.js';\n\nexport function generateJSOutput(tokens: ExportedTokens[\"tokens\"]): string {\n return `// Atomix Design System Tokens\n// Auto-generated - do not edit manually\n// Synced: ${new Date().toISOString()}\n\nexport const tokens = ${JSON.stringify(tokens, null, 2)};\n`;\n}\n","/**\n * Swift Format Generator\n * \n * Generates Swift/SwiftUI output with dark mode support.\n */\n\n// Helper functions\nfunction toSwiftName(cssVar: string): string {\n // --atmx-color-brand-primary → colorBrandPrimary\n return cssVar\n .replace(/^--atmx-/, \"\")\n .replace(/-([a-z])/g, (_, c) => c.toUpperCase());\n}\n\nfunction isColorValue(value: string): boolean {\n return /^#[0-9A-Fa-f]{3,8}$/.test(value) || \n /^rgb/.test(value) || \n /^hsl/.test(value);\n}\n\nfunction hexToSwiftColor(hex: string): string {\n // #RRGGBB or #RRGGBBAA\n const clean = hex.replace(\"#\", \"\");\n if (clean.length === 3) {\n // #RGB -> #RRGGBB\n const r = clean[0], g = clean[1], b = clean[2];\n return `Color(hex: 0x${r}${r}${g}${g}${b}${b})`;\n }\n if (clean.length === 6) {\n return `Color(hex: 0x${clean})`;\n }\n if (clean.length === 8) {\n // #RRGGBBAA\n const rgb = clean.substring(0, 6);\n const alpha = parseInt(clean.substring(6, 8), 16) / 255;\n return `Color(hex: 0x${rgb}).opacity(${alpha.toFixed(2)})`;\n }\n return `Color.clear // Could not parse: ${hex}`;\n}\n\nexport function generateSwiftOutput(\n cssVariables: Record<string, string>,\n darkModeColors?: Record<string, string>,\n deprecatedTokens: Map<string, string> = new Map()\n): string {\n const lines = [\n \"// Atomix Design System Tokens\",\n \"// Auto-generated - do not edit manually\",\n `// Synced: ${new Date().toISOString()}`,\n \"\",\n \"import SwiftUI\",\n \"\",\n \"// MARK: - Color Extension for Hex\",\n \"extension Color {\",\n \" init(hex: UInt, alpha: Double = 1.0) {\",\n \" self.init(\",\n \" .sRGB,\",\n \" red: Double((hex >> 16) & 0xFF) / 255.0,\",\n \" green: Double((hex >> 8) & 0xFF) / 255.0,\",\n \" blue: Double(hex & 0xFF) / 255.0,\",\n \" opacity: alpha\",\n \" )\",\n \" }\",\n \"}\",\n \"\",\n \"// MARK: - Design Tokens\",\n \"enum DesignTokens {\",\n \"\",\n \" // MARK: Colors (Light Mode)\",\n \" enum Colors {\"\n ];\n\n // Group by category, including deprecated tokens\n const colors: Array<[string, string, boolean]> = [];\n const spacing: Array<[string, string, boolean]> = [];\n const typography: Array<[string, string, boolean]> = [];\n const other: Array<[string, string, boolean]> = [];\n\n // Add current tokens\n for (const [key, value] of Object.entries(cssVariables)) {\n const isDeprecated = false;\n if (key.includes(\"-color-\")) colors.push([key, value, isDeprecated]);\n else if (key.includes(\"-spacing-\")) spacing.push([key, value, isDeprecated]);\n else if (key.includes(\"-typography-\") || key.includes(\"-font-\")) typography.push([key, value, isDeprecated]);\n else other.push([key, value, isDeprecated]);\n }\n \n // Add deprecated tokens\n for (const [key, value] of deprecatedTokens.entries()) {\n const isDeprecated = true;\n if (key.includes(\"-color-\")) colors.push([key, value, isDeprecated]);\n else if (key.includes(\"-spacing-\")) spacing.push([key, value, isDeprecated]);\n else if (key.includes(\"-typography-\") || key.includes(\"-font-\")) typography.push([key, value, isDeprecated]);\n else other.push([key, value, isDeprecated]);\n }\n\n // Sort by key name\n colors.sort((a, b) => a[0].localeCompare(b[0]));\n spacing.sort((a, b) => a[0].localeCompare(b[0]));\n typography.sort((a, b) => a[0].localeCompare(b[0]));\n other.sort((a, b) => a[0].localeCompare(b[0]));\n\n for (const [key, value, isDeprecated] of colors) {\n const name = toSwiftName(key);\n if (isColorValue(value)) {\n if (isDeprecated) {\n lines.push(` @available(*, deprecated, message: \"This token has been removed from the design system\")`);\n lines.push(` static let ${name} = ${hexToSwiftColor(value)}`);\n } else {\n lines.push(` static let ${name} = ${hexToSwiftColor(value)}`);\n }\n }\n }\n\n lines.push(\" }\");\n \n // Add dark mode colors if provided\n if (darkModeColors && Object.keys(darkModeColors).length > 0) {\n lines.push(\"\");\n lines.push(\" // MARK: Colors (Dark Mode)\");\n lines.push(\" enum ColorsDark {\");\n \n for (const [key, value] of Object.entries(darkModeColors)) {\n const name = `color${key.split(\"-\").map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(\"\")}`;\n if (isColorValue(value)) {\n lines.push(` static let ${name} = ${hexToSwiftColor(value)}`);\n }\n }\n \n lines.push(\" }\");\n }\n \n lines.push(\"\");\n lines.push(\" // MARK: Spacing\");\n lines.push(\" enum Spacing {\");\n\n for (const [key, value, isDeprecated] of spacing) {\n const name = toSwiftName(key);\n const numValue = parseFloat(value);\n if (!isNaN(numValue)) {\n if (isDeprecated) {\n lines.push(` @available(*, deprecated, message: \"This token has been removed from the design system\")`);\n lines.push(` static let ${name}: CGFloat = ${numValue}`);\n } else {\n lines.push(` static let ${name}: CGFloat = ${numValue}`);\n }\n }\n }\n\n lines.push(\" }\");\n lines.push(\"\");\n lines.push(\" // MARK: Typography\");\n lines.push(\" enum Typography {\");\n\n for (const [key, value, isDeprecated] of typography) {\n const name = toSwiftName(key);\n if (isDeprecated) {\n lines.push(` @available(*, deprecated, message: \"This token has been removed from the design system\")`);\n }\n if (key.includes(\"size\")) {\n const numValue = parseFloat(value);\n if (!isNaN(numValue)) {\n lines.push(` static let ${name}: CGFloat = ${numValue}`);\n }\n } else if (key.includes(\"weight\")) {\n lines.push(` static let ${name} = \"${value}\"`);\n } else if (key.includes(\"family\")) {\n lines.push(` static let ${name} = \"${value}\"`);\n }\n }\n\n lines.push(\" }\");\n lines.push(\"\");\n lines.push(\" // MARK: Other\");\n lines.push(\" enum Other {\");\n\n for (const [key, value, isDeprecated] of other) {\n const name = toSwiftName(key);\n if (isDeprecated) {\n lines.push(` @available(*, deprecated, message: \"This token has been removed from the design system\")`);\n }\n if (isColorValue(value)) {\n lines.push(` static let ${name} = ${hexToSwiftColor(value)}`);\n } else {\n const numValue = parseFloat(value);\n if (!isNaN(numValue)) {\n lines.push(` static let ${name}: CGFloat = ${numValue}`);\n } else {\n lines.push(` static let ${name} = \"${value}\"`);\n }\n }\n }\n\n lines.push(\" }\");\n lines.push(\"}\");\n lines.push(\"\");\n\n return lines.join(\"\\n\");\n}\n","/**\n * Kotlin Format Generator\n * \n * Generates Kotlin/Jetpack Compose output with dark mode support.\n */\n\n// Helper functions\nfunction toSwiftName(cssVar: string): string {\n return cssVar\n .replace(/^--atmx-/, \"\")\n .replace(/-([a-z])/g, (_, c) => c.toUpperCase());\n}\n\nfunction toKotlinName(cssVar: string): string {\n // --atmx-color-brand-primary → ColorBrandPrimary\n const camel = toSwiftName(cssVar);\n return camel.charAt(0).toUpperCase() + camel.slice(1);\n}\n\nfunction isColorValue(value: string): boolean {\n return /^#[0-9A-Fa-f]{3,8}$/.test(value) || \n /^rgb/.test(value) || \n /^hsl/.test(value);\n}\n\nfunction hexToKotlinColor(hex: string): string {\n const clean = hex.replace(\"#\", \"\").toUpperCase();\n if (clean.length === 3) {\n const r = clean[0], g = clean[1], b = clean[2];\n return `Color(0xFF${r}${r}${g}${g}${b}${b})`;\n }\n if (clean.length === 6) {\n return `Color(0xFF${clean})`;\n }\n if (clean.length === 8) {\n // RRGGBBAA -> AARRGGBB for Android\n const rgb = clean.substring(0, 6);\n const alpha = clean.substring(6, 8);\n return `Color(0x${alpha}${rgb})`;\n }\n return `Color.Transparent // Could not parse: ${hex}`;\n}\n\nexport function generateKotlinOutput(\n cssVariables: Record<string, string>,\n darkModeColors?: Record<string, string>,\n deprecatedTokens: Map<string, string> = new Map()\n): string {\n const lines = [\n \"// Atomix Design System Tokens\",\n \"// Auto-generated - do not edit manually\",\n `// Synced: ${new Date().toISOString()}`,\n \"\",\n \"package com.atomix.design\",\n \"\",\n \"import androidx.compose.ui.graphics.Color\",\n \"import androidx.compose.ui.unit.dp\",\n \"import androidx.compose.ui.unit.sp\",\n \"\",\n \"object DesignTokens {\",\n \"\",\n \" // Light mode colors\",\n \" object Colors {\"\n ];\n\n const colors: Array<[string, string, boolean]> = [];\n const spacing: Array<[string, string, boolean]> = [];\n const typography: Array<[string, string, boolean]> = [];\n const other: Array<[string, string, boolean]> = [];\n\n // Add current tokens\n for (const [key, value] of Object.entries(cssVariables)) {\n const isDeprecated = false;\n if (key.includes(\"-color-\")) colors.push([key, value, isDeprecated]);\n else if (key.includes(\"-spacing-\")) spacing.push([key, value, isDeprecated]);\n else if (key.includes(\"-typography-\") || key.includes(\"-font-\")) typography.push([key, value, isDeprecated]);\n else other.push([key, value, isDeprecated]);\n }\n \n // Add deprecated tokens\n for (const [key, value] of deprecatedTokens.entries()) {\n const isDeprecated = true;\n if (key.includes(\"-color-\")) colors.push([key, value, isDeprecated]);\n else if (key.includes(\"-spacing-\")) spacing.push([key, value, isDeprecated]);\n else if (key.includes(\"-typography-\") || key.includes(\"-font-\")) typography.push([key, value, isDeprecated]);\n else other.push([key, value, isDeprecated]);\n }\n\n // Sort by key name\n colors.sort((a, b) => a[0].localeCompare(b[0]));\n spacing.sort((a, b) => a[0].localeCompare(b[0]));\n typography.sort((a, b) => a[0].localeCompare(b[0]));\n other.sort((a, b) => a[0].localeCompare(b[0]));\n\n for (const [key, value, isDeprecated] of colors) {\n const name = toKotlinName(key);\n if (isColorValue(value)) {\n if (isDeprecated) {\n lines.push(` @Deprecated(\"This token has been removed from the design system\")`);\n lines.push(` val ${name} = ${hexToKotlinColor(value)}`);\n } else {\n lines.push(` val ${name} = ${hexToKotlinColor(value)}`);\n }\n }\n }\n\n lines.push(\" }\");\n \n // Add dark mode colors if provided\n if (darkModeColors && Object.keys(darkModeColors).length > 0) {\n lines.push(\"\");\n lines.push(\" // Dark mode colors\");\n lines.push(\" object ColorsDark {\");\n \n for (const [key, value] of Object.entries(darkModeColors)) {\n const name = `Color${key.split(\"-\").map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(\"\")}`;\n if (isColorValue(value)) {\n lines.push(` val ${name} = ${hexToKotlinColor(value)}`);\n }\n }\n \n lines.push(\" }\");\n }\n \n lines.push(\"\");\n lines.push(\" object Spacing {\");\n\n for (const [key, value, isDeprecated] of spacing) {\n const name = toKotlinName(key);\n const numValue = parseFloat(value);\n if (!isNaN(numValue)) {\n if (isDeprecated) {\n lines.push(` @Deprecated(\"This token has been removed from the design system\")`);\n lines.push(` val ${name} = ${numValue}.dp`);\n } else {\n lines.push(` val ${name} = ${numValue}.dp`);\n }\n }\n }\n\n lines.push(\" }\");\n lines.push(\"\");\n lines.push(\" object Typography {\");\n\n for (const [key, value, isDeprecated] of typography) {\n const name = toKotlinName(key);\n if (isDeprecated) {\n lines.push(` @Deprecated(\"This token has been removed from the design system\")`);\n }\n if (key.includes(\"size\")) {\n const numValue = parseFloat(value);\n if (!isNaN(numValue)) {\n lines.push(` val ${name} = ${numValue}.sp`);\n }\n } else {\n lines.push(` const val ${name} = \"${value}\"`);\n }\n }\n\n lines.push(\" }\");\n lines.push(\"\");\n lines.push(\" object Other {\");\n\n for (const [key, value, isDeprecated] of other) {\n const name = toKotlinName(key);\n if (isDeprecated) {\n lines.push(` @Deprecated(\"This token has been removed from the design system\")`);\n }\n if (isColorValue(value)) {\n lines.push(` val ${name} = ${hexToKotlinColor(value)}`);\n } else {\n const numValue = parseFloat(value);\n if (!isNaN(numValue)) {\n lines.push(` val ${name} = ${numValue}.dp`);\n } else {\n lines.push(` const val ${name} = \"${value}\"`);\n }\n }\n }\n\n lines.push(\" }\");\n lines.push(\"}\");\n lines.push(\"\");\n\n return lines.join(\"\\n\");\n}\n","/**\n * Dart Format Generator\n * \n * Generates Dart/Flutter output with dark mode support.\n */\n\n// Helper functions\nfunction toSwiftName(cssVar: string): string {\n return cssVar\n .replace(/^--atmx-/, \"\")\n .replace(/-([a-z])/g, (_, c) => c.toUpperCase());\n}\n\nfunction toDartName(cssVar: string): string {\n // --atmx-color-brand-primary → colorBrandPrimary (same as Swift)\n return toSwiftName(cssVar);\n}\n\nfunction isColorValue(value: string): boolean {\n return /^#[0-9A-Fa-f]{3,8}$/.test(value) || \n /^rgb/.test(value) || \n /^hsl/.test(value);\n}\n\nfunction hexToDartColor(hex: string): string {\n const clean = hex.replace(\"#\", \"\").toUpperCase();\n if (clean.length === 3) {\n const r = clean[0], g = clean[1], b = clean[2];\n return `Color(0xFF${r}${r}${g}${g}${b}${b})`;\n }\n if (clean.length === 6) {\n return `Color(0xFF${clean})`;\n }\n if (clean.length === 8) {\n const rgb = clean.substring(0, 6);\n const alpha = clean.substring(6, 8);\n return `Color(0x${alpha}${rgb})`;\n }\n return `Colors.transparent // Could not parse: ${hex}`;\n}\n\nexport function generateDartOutput(\n cssVariables: Record<string, string>,\n darkModeColors?: Record<string, string>,\n deprecatedTokens: Map<string, string> = new Map()\n): string {\n const lines = [\n \"// Atomix Design System Tokens\",\n \"// Auto-generated - do not edit manually\",\n `// Synced: ${new Date().toISOString()}`,\n \"\",\n \"import 'package:flutter/material.dart';\",\n \"\",\n \"class DesignTokens {\",\n \" DesignTokens._();\",\n \"\",\n \" // Colors (Light Mode)\"\n ];\n\n const colors: Array<[string, string, boolean]> = [];\n const spacing: Array<[string, string, boolean]> = [];\n const typography: Array<[string, string, boolean]> = [];\n const other: Array<[string, string, boolean]> = [];\n\n // Add current tokens\n for (const [key, value] of Object.entries(cssVariables)) {\n const isDeprecated = false;\n if (key.includes(\"-color-\")) colors.push([key, value, isDeprecated]);\n else if (key.includes(\"-spacing-\")) spacing.push([key, value, isDeprecated]);\n else if (key.includes(\"-typography-\") || key.includes(\"-font-\")) typography.push([key, value, isDeprecated]);\n else other.push([key, value, isDeprecated]);\n }\n \n // Add deprecated tokens\n for (const [key, value] of deprecatedTokens.entries()) {\n const isDeprecated = true;\n if (key.includes(\"-color-\")) colors.push([key, value, isDeprecated]);\n else if (key.includes(\"-spacing-\")) spacing.push([key, value, isDeprecated]);\n else if (key.includes(\"-typography-\") || key.includes(\"-font-\")) typography.push([key, value, isDeprecated]);\n else other.push([key, value, isDeprecated]);\n }\n\n // Sort by key name\n colors.sort((a, b) => a[0].localeCompare(b[0]));\n spacing.sort((a, b) => a[0].localeCompare(b[0]));\n typography.sort((a, b) => a[0].localeCompare(b[0]));\n other.sort((a, b) => a[0].localeCompare(b[0]));\n\n for (const [key, value, isDeprecated] of colors) {\n const name = toDartName(key);\n if (isColorValue(value)) {\n if (isDeprecated) {\n lines.push(` @Deprecated('This token has been removed from the design system')`);\n lines.push(` static const ${name} = ${hexToDartColor(value)};`);\n } else {\n lines.push(` static const ${name} = ${hexToDartColor(value)};`);\n }\n }\n }\n\n // Add dark mode colors if provided\n if (darkModeColors && Object.keys(darkModeColors).length > 0) {\n lines.push(\"\");\n lines.push(\" // Colors (Dark Mode)\");\n \n for (const [key, value] of Object.entries(darkModeColors)) {\n const name = `color${key.split(\"-\").map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(\"\")}Dark`;\n if (isColorValue(value)) {\n lines.push(` static const ${name} = ${hexToDartColor(value)};`);\n }\n }\n }\n\n lines.push(\"\");\n lines.push(\" // Spacing\");\n\n for (const [key, value, isDeprecated] of spacing) {\n const name = toDartName(key);\n const numValue = parseFloat(value);\n if (!isNaN(numValue)) {\n if (isDeprecated) {\n lines.push(` @Deprecated('This token has been removed from the design system')`);\n lines.push(` static const double ${name} = ${numValue};`);\n } else {\n lines.push(` static const double ${name} = ${numValue};`);\n }\n }\n }\n\n lines.push(\"\");\n lines.push(\" // Typography\");\n\n for (const [key, value, isDeprecated] of typography) {\n const name = toDartName(key);\n if (isDeprecated) {\n lines.push(` @Deprecated('This token has been removed from the design system')`);\n }\n if (key.includes(\"size\")) {\n const numValue = parseFloat(value);\n if (!isNaN(numValue)) {\n lines.push(` static const double ${name} = ${numValue};`);\n }\n } else {\n lines.push(` static const String ${name} = '${value}';`);\n }\n }\n\n lines.push(\"\");\n lines.push(\" // Other\");\n\n for (const [key, value, isDeprecated] of other) {\n const name = toDartName(key);\n if (isDeprecated) {\n lines.push(` @Deprecated('This token has been removed from the design system')`);\n }\n if (isColorValue(value)) {\n lines.push(` static const ${name} = ${hexToDartColor(value)};`);\n } else {\n const numValue = parseFloat(value);\n if (!isNaN(numValue)) {\n lines.push(` static const double ${name} = ${numValue};`);\n } else {\n lines.push(` static const String ${name} = '${value}';`);\n }\n }\n }\n\n lines.push(\"}\");\n lines.push(\"\");\n\n return lines.join(\"\\n\");\n}\n","/**\n * Format sync response for CLI and MCP\n * \n * Single source of truth for sync output formatting.\n * This ensures MCP and CLI have identical response formats.\n */\n\nimport * as path from \"path\";\nimport type { DesignSystemData, DiffResult } from './types.js';\nimport type { RulesFileResult } from './rules.js';\n\nexport interface FormatSyncResponseOptions {\n // Core data\n data: DesignSystemData;\n output: string;\n format: string;\n \n // Token counts\n dsTokenCount: number;\n deprecatedCount: number;\n deprecatedTokens: Map<string, string>;\n \n // Changes\n diff?: DiffResult;\n changes?: Array<{ key: string; old: string; new: string }>;\n fileExists: boolean;\n \n // Rules\n rulesResults?: RulesFileResult[];\n \n // Governance changes\n governanceChanges?: string[];\n changeSummary?: string | null;\n \n // Refactor info\n hasRefactorRecommendation?: boolean;\n deprecatedTokenCount?: number;\n}\n\n/**\n * Format enhanced sync response text\n * \n * Generates a comprehensive response with explicit lists of:\n * - Deprecated tokens (with values)\n * - New tokens\n * - Modified files (output + rules files)\n * - AI rules changes by foundation\n * - Detailed changes summary\n * - Refactor recommendations\n */\nexport function formatSyncResponse(options: FormatSyncResponseOptions): string {\n const {\n data,\n output,\n format,\n dsTokenCount,\n deprecatedCount,\n deprecatedTokens,\n diff,\n changes = [],\n fileExists,\n rulesResults = [],\n governanceChanges = [],\n changeSummary,\n hasRefactorRecommendation = false,\n deprecatedTokenCount = 0,\n } = options;\n\n const lastUpdated = data.meta.exportedAt \n ? new Date(data.meta.exportedAt).toLocaleString()\n : \"N/A\";\n\n let response = `✓ Synced ${dsTokenCount} tokens to ${output}\\n`;\n response += `Format: ${format}\\n`;\n response += `Design System: ${data.meta.name} (v${data.meta.version})\\n`;\n if (deprecatedCount > 0) {\n response += `Tokens: ${dsTokenCount} active, ${deprecatedCount} deprecated (run /refactor to migrate)\\n`;\n } else {\n response += `Tokens: ${dsTokenCount}\\n`;\n }\n response += `Version: ${data.meta.version}\\n`;\n response += `Last updated: ${lastUpdated}\\n`;\n\n // ============================================\n // SECTION 1: DEPRECATED TOKENS (Explicit List)\n // ============================================\n if (deprecatedCount > 0) {\n response += `\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`;\n response += `📋 DEPRECATED TOKENS (${deprecatedCount})\\n`;\n response += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n\\n`;\n response += `These tokens are no longer in the design system but are preserved in your file for backward compatibility.\\n`;\n response += `Run \\`/refactor\\` to find and migrate usage in your codebase.\\n\\n`;\n \n const deprecatedTokenList = Array.from(deprecatedTokens.keys()).sort();\n deprecatedTokenList.forEach((token, index) => {\n const value = deprecatedTokens.get(token);\n response += ` ${index + 1}. ${token}`;\n if (value) {\n response += ` = ${value}`;\n }\n response += `\\n`;\n });\n }\n\n // ============================================\n // SECTION 2: NEW TOKENS (Explicit List)\n // ============================================\n const newTokenList: string[] = [];\n if (diff) {\n newTokenList.push(...diff.added, ...diff.addedDark);\n }\n\n // Also include tokens from change summary if available\n if (changeSummary && changeSummary.includes(\"➕ Added:\")) {\n const addedSection = changeSummary.match(/➕ Added: \\d+ token\\(s\\)([\\s\\S]*?)(?=➖|🔄|📝|$)/);\n if (addedSection) {\n const addedLines = addedSection[0].match(/ - (--[^\\n]+)/g) || [];\n addedLines.forEach(line => {\n const token = line.replace(/ - /, \"\").trim();\n if (token && !newTokenList.includes(token)) {\n newTokenList.push(token);\n }\n });\n }\n }\n\n if (newTokenList.length > 0) {\n response += `\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`;\n response += `✨ NEW TOKENS (${newTokenList.length})\\n`;\n response += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n\\n`;\n newTokenList.sort().forEach((token, index) => {\n response += ` ${index + 1}. ${token}\\n`;\n });\n }\n\n // ============================================\n // SECTION 3: MODIFIED FILES (Explicit List)\n // ============================================\n const modifiedFiles: string[] = [output];\n\n // Add rules files that were synced\n rulesResults.forEach(result => {\n if (result.success) {\n const fullPath = path.resolve(process.cwd(), result.path);\n if (!modifiedFiles.includes(fullPath)) {\n modifiedFiles.push(fullPath);\n }\n }\n });\n\n response += `\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`;\n response += `📁 MODIFIED FILES (${modifiedFiles.length})\\n`;\n response += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n\\n`;\n modifiedFiles.forEach((file, index) => {\n const relativePath = path.relative(process.cwd(), file);\n response += ` ${index + 1}. ${relativePath}\\n`;\n });\n\n // ============================================\n // SECTION 4: AI RULES CHANGES (By Foundation)\n // ============================================\n if (governanceChanges.length > 0) {\n response += `\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`;\n response += `📝 AI RULES CHANGES\\n`;\n response += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n\\n`;\n response += `The following AI guidance sections have been updated:\\n\\n`;\n \n // Capitalize foundation names\n const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);\n \n governanceChanges.forEach((foundation, index) => {\n const displayName = foundation === \"general\" \n ? \"General Rules\" \n : capitalize(foundation);\n response += ` ${index + 1}. ${displayName}\\n`;\n });\n \n response += `\\nThese changes are reflected in your AI tool rules files (e.g., .cursorrules).\\n`;\n response += `Review the updated rules files to see the new guidance.\\n`;\n }\n\n // ============================================\n // SECTION 5: DETAILED CHANGES (Keep existing)\n // ============================================\n if (diff) {\n const lightChanges = diff.added.length + diff.modified.length;\n const darkChanges = diff.addedDark.length + diff.modifiedDark.length;\n \n if (lightChanges > 0 || darkChanges > 0 || deprecatedCount > 0) {\n response += `\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`;\n response += `📊 DETAILED CHANGES\\n`;\n response += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n\\n`;\n \n const lightSummary = lightChanges > 0 ? `Light: ${diff.modified.length} modified, ${diff.added.length} added` : \"\";\n const darkSummary = darkChanges > 0 ? `Dark: ${diff.modifiedDark.length} modified, ${diff.addedDark.length} added` : \"\";\n const deprecatedSummary = deprecatedCount > 0 ? `${deprecatedCount} deprecated (use /refactor)` : \"\";\n const diffSummary = [lightSummary, darkSummary, deprecatedSummary].filter(Boolean).join(\" | \");\n response += `${diffSummary}\\n`;\n \n if (changes.length > 0 && changes.length <= 10) {\n response += \"\\nModified tokens:\\n\";\n for (const { key, old: oldVal, new: newVal } of changes) {\n response += ` ${key}: ${oldVal} → ${newVal}\\n`;\n }\n }\n }\n } else if (!fileExists) {\n response += `\\n(New file created)\\n`;\n }\n\n // ============================================\n // SECTION 6: REFACTOR RECOMMENDATION\n // ============================================\n if (hasRefactorRecommendation && deprecatedTokenCount > 0) {\n response += `\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`;\n response += `💡 NEXT STEP\\n`;\n response += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n\\n`;\n response += `${deprecatedTokenCount} token(s) have been deprecated.\\n`;\n response += `Your codebase may still reference these deprecated tokens.\\n\\n`;\n response += `Run \\`/refactor\\` to:\\n`;\n response += ` • Scan your codebase for deprecated token usage\\n`;\n response += ` • See which files need updates\\n`;\n response += ` • Review and apply changes with your confirmation\\n`;\n }\n\n return response;\n}\n","/**\n * Token Utilities\n * \n * Functions for working with design tokens.\n */\n\nimport type { DesignSystemData } from './types.js';\n\nexport function getTokenByPath(tokens: Record<string, unknown>, path: string): unknown {\n const parts = path.split(\".\");\n let current: unknown = tokens;\n\n for (const part of parts) {\n if (current && typeof current === \"object\" && part in current) {\n current = (current as Record<string, unknown>)[part];\n } else {\n return undefined;\n }\n }\n\n return current;\n}\n\nexport function flattenTokens(obj: unknown, prefix = \"\"): Array<{ path: string; value: unknown }> {\n const results: Array<{ path: string; value: unknown }> = [];\n\n if (obj && typeof obj === \"object\" && !Array.isArray(obj)) {\n for (const [key, value] of Object.entries(obj)) {\n const newPath = prefix ? `${prefix}.${key}` : key;\n \n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n results.push(...flattenTokens(value, newPath));\n } else {\n results.push({ path: newPath, value });\n }\n }\n }\n\n return results;\n}\n\nexport function searchTokens(tokens: Record<string, unknown>, query: string): Array<{ path: string; value: unknown }> {\n const flat = flattenTokens(tokens);\n const lowerQuery = query.toLowerCase();\n \n return flat.filter(({ path, value }) => {\n const pathMatch = path.toLowerCase().includes(lowerQuery);\n const valueMatch = String(value).toLowerCase().includes(lowerQuery);\n return pathMatch || valueMatch;\n });\n}\n\nexport function countTokens(tokens: Record<string, unknown>, prefix = \"\"): number {\n let count = 0;\n for (const [key, value] of Object.entries(tokens)) {\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n count += countTokens(value as Record<string, unknown>, `${prefix}${key}.`);\n } else if (value !== undefined && value !== null) {\n count++;\n }\n }\n return count;\n}\n\nexport function getTokenStats(data: DesignSystemData): {\n total: number;\n byCategory: Record<string, number>;\n cssVariables: number;\n governanceRules: number;\n} {\n const byCategory: Record<string, number> = {};\n let total = 0;\n\n for (const [category, value] of Object.entries(data.tokens)) {\n if (value && typeof value === \"object\") {\n const count = countTokens(value as Record<string, unknown>);\n byCategory[category] = count;\n total += count;\n }\n }\n\n return {\n total,\n byCategory,\n cssVariables: Object.keys(data.cssVariables).length,\n governanceRules: data.governance.rules.length,\n };\n}\n","/**\n * Config Management\n * \n * Functions for loading and managing .atomixrc configuration.\n */\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport type { AtomixConfig, DEFAULT_INCLUDE, DEFAULT_EXCLUDE } from './types.js';\n\nexport { DEFAULT_INCLUDE, DEFAULT_EXCLUDE } from './types.js';\n\nexport function findConfig(): AtomixConfig | null {\n const configNames = [\".atomixrc\", \".atomixrc.json\", \"atomix.config.json\"];\n const cwd = process.cwd();\n \n for (const name of configNames) {\n const configPath = path.join(cwd, name);\n if (fs.existsSync(configPath)) {\n try {\n const content = fs.readFileSync(configPath, \"utf-8\");\n return JSON.parse(content) as AtomixConfig;\n } catch {\n console.error(`Error parsing ${name}`);\n }\n }\n }\n return null;\n}\n"],"mappings":";;;AAsBA,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;AKzBP,YAAY,QAAQ;AACpB,YAAY,UAAU;AUAtB,YAAYA,WAAU;AbIf,SAAS,aAAa,MAA4E;AACvG,QAAM,KAAK,KAAK,aAAa,KAAK,cAAc;AAChD,QAAM,OAAO,GAAG,KAAK,OAAO,IAAI,EAAE;AAClC,SAAO,KAAK,IAAI;AAClB;AAKO,SAAS,qBACd,QACA,OACe;AACf,QAAM,UAAyB;IAC7B,YAAY;IACZ,gBAAgB;IAChB,kBAAkB;IAClB,aAAa,CAAC;IACd,eAAe,CAAC;IAChB,gBAAgB,CAAC;IACjB,mBAAmB;IACnB,SAAS;EACX;AAGA,MAAI,OAAO,KAAK,YAAY,MAAM,KAAK,SAAS;AAC9C,YAAQ,iBAAiB;AACzB,YAAQ,aAAa;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