@trishchuk/coolors-mcp 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/.github/ISSUE_TEMPLATE/bug_report.md +20 -8
  2. package/.github/ISSUE_TEMPLATE/feature_request.md +22 -8
  3. package/.github/pull_request_template.md +33 -8
  4. package/.github/workflows/ci.yml +107 -104
  5. package/.github/workflows/deploy-docs.yml +14 -11
  6. package/.github/workflows/release.yml +25 -23
  7. package/README.md +149 -15
  8. package/dist/bin/server.js +997 -256
  9. package/dist/bin/server.js.map +1 -1
  10. package/dist/{chunk-P3ARRKLS.js → chunk-HOMDMKUY.js} +3 -1
  11. package/dist/{chunk-P3ARRKLS.js.map → chunk-HOMDMKUY.js.map} +1 -1
  12. package/dist/{chunk-IQ7NN26V.js → chunk-LHW2ZTOU.js} +14 -2
  13. package/dist/chunk-LHW2ZTOU.js.map +1 -0
  14. package/dist/color/index.js +1 -1
  15. package/dist/coolors-mcp.d.ts +4 -4
  16. package/dist/coolors-mcp.js +1 -1
  17. package/docs/.vitepress/components/ClientGrid.vue +9 -3
  18. package/docs/.vitepress/components/CodeBlock.vue +51 -44
  19. package/docs/.vitepress/components/ConfigModal.vue +151 -67
  20. package/docs/.vitepress/components/DiagramModal.vue +186 -154
  21. package/docs/.vitepress/components/TroubleshootingModal.vue +101 -96
  22. package/docs/.vitepress/config.js +171 -141
  23. package/docs/.vitepress/theme/FundingLayout.vue +65 -54
  24. package/docs/.vitepress/theme/Layout.vue +21 -21
  25. package/docs/.vitepress/theme/components/AdBanner.vue +73 -52
  26. package/docs/.vitepress/theme/components/AdPlaceholder.vue +3 -3
  27. package/docs/.vitepress/theme/components/FundingEffects.vue +77 -53
  28. package/docs/.vitepress/theme/components/FundingHero.vue +78 -63
  29. package/docs/.vitepress/theme/components/SupportSection.vue +106 -89
  30. package/docs/.vitepress/theme/custom-app.css +19 -12
  31. package/docs/.vitepress/theme/custom.css +33 -25
  32. package/docs/.vitepress/theme/index.js +19 -16
  33. package/docs/concepts/accessibility.md +59 -47
  34. package/docs/concepts/color-spaces.md +28 -6
  35. package/docs/concepts/distance-metrics.md +45 -30
  36. package/docs/concepts/hct.md +30 -27
  37. package/docs/concepts/image-analysis.md +52 -21
  38. package/docs/concepts/material-design.md +43 -17
  39. package/docs/concepts/theme-matching.md +64 -40
  40. package/docs/examples/basic-colors.md +92 -108
  41. package/docs/examples/creating-themes.md +104 -108
  42. package/docs/examples/css-refactoring.md +33 -29
  43. package/docs/examples/image-extraction.md +145 -138
  44. package/docs/getting-started.md +45 -34
  45. package/docs/index.md +5 -1
  46. package/docs/installation.md +15 -1
  47. package/docs/tools/accessibility.md +74 -68
  48. package/docs/tools/image-extraction.md +62 -54
  49. package/docs/tools/theme-matching.md +45 -42
  50. package/eslint.config.ts +13 -0
  51. package/jsr.json +1 -1
  52. package/package.json +17 -13
  53. package/src/bin/server.ts +13 -1
  54. package/src/color/__tests__/extract-colors.test.ts +20 -30
  55. package/src/color/apca.ts +105 -0
  56. package/src/color/color-blindness.ts +109 -0
  57. package/src/coolors-mcp.ts +1 -1
  58. package/src/session.ts +10 -2
  59. package/src/theme/matcher.ts +1 -1
  60. package/src/theme/refactor.ts +1 -1
  61. package/src/theme/types.ts +3 -0
  62. package/src/tools/__tests__/cohesion.test.ts +97 -0
  63. package/src/tools/__tests__/color-blindness.test.ts +45 -0
  64. package/src/tools/__tests__/color-conversion.test.ts +38 -0
  65. package/src/tools/__tests__/contrast-checker.test.ts +56 -0
  66. package/src/tools/__tests__/palette-export.test.ts +54 -0
  67. package/src/tools/adjust-color.tool.ts +80 -0
  68. package/src/tools/cohesion.tools.ts +380 -0
  69. package/src/tools/color-blindness.tool.ts +168 -0
  70. package/src/tools/color-conversion.tool.ts +1 -1
  71. package/src/tools/contrast-checker.tool.ts +53 -14
  72. package/src/tools/dislike-analyzer.tool.ts +41 -54
  73. package/src/tools/image-extraction.tools.ts +62 -115
  74. package/src/tools/index.ts +15 -2
  75. package/src/tools/palette-export.tool.ts +174 -0
  76. package/src/tools/palette-with-locks.tool.ts +8 -6
  77. package/src/types.ts +2 -3
  78. package/tsconfig.json +12 -2
  79. package/vitest.config.js +1 -3
  80. package/.claude/settings.local.json +0 -39
  81. package/.env +0 -2
  82. package/.mcp.json +0 -12
  83. package/CLAUDE.md +0 -201
  84. package/DOCUMENTATION.md +0 -274
  85. package/GEMINI.md +0 -54
  86. package/demo/content_based_color.png +0 -0
  87. package/demo/music-player.html +0 -621
  88. package/demo/podcast-player.html +0 -903
  89. package/dist/chunk-IQ7NN26V.js.map +0 -1
  90. package/docs/.vitepress/cache/deps/@braintree_sanitize-url.js +0 -93
  91. package/docs/.vitepress/cache/deps/@braintree_sanitize-url.js.map +0 -7
  92. package/docs/.vitepress/cache/deps/_metadata.json +0 -127
  93. package/docs/.vitepress/cache/deps/chunk-BUSYA2B4.js +0 -9
  94. package/docs/.vitepress/cache/deps/chunk-BUSYA2B4.js.map +0 -7
  95. package/docs/.vitepress/cache/deps/chunk-JD3CXNQ6.js +0 -12683
  96. package/docs/.vitepress/cache/deps/chunk-JD3CXNQ6.js.map +0 -7
  97. package/docs/.vitepress/cache/deps/chunk-SYPOPCWC.js +0 -9719
  98. package/docs/.vitepress/cache/deps/chunk-SYPOPCWC.js.map +0 -7
  99. package/docs/.vitepress/cache/deps/cytoscape-cose-bilkent.js +0 -4710
  100. package/docs/.vitepress/cache/deps/cytoscape-cose-bilkent.js.map +0 -7
  101. package/docs/.vitepress/cache/deps/cytoscape.js +0 -30278
  102. package/docs/.vitepress/cache/deps/cytoscape.js.map +0 -7
  103. package/docs/.vitepress/cache/deps/dayjs.js +0 -285
  104. package/docs/.vitepress/cache/deps/dayjs.js.map +0 -7
  105. package/docs/.vitepress/cache/deps/debug.js +0 -468
  106. package/docs/.vitepress/cache/deps/debug.js.map +0 -7
  107. package/docs/.vitepress/cache/deps/package.json +0 -3
  108. package/docs/.vitepress/cache/deps/prismjs.js +0 -1466
  109. package/docs/.vitepress/cache/deps/prismjs.js.map +0 -7
  110. package/docs/.vitepress/cache/deps/prismjs_components_prism-bash.js +0 -228
  111. package/docs/.vitepress/cache/deps/prismjs_components_prism-bash.js.map +0 -7
  112. package/docs/.vitepress/cache/deps/prismjs_components_prism-javascript.js +0 -142
  113. package/docs/.vitepress/cache/deps/prismjs_components_prism-javascript.js.map +0 -7
  114. package/docs/.vitepress/cache/deps/prismjs_components_prism-json.js +0 -27
  115. package/docs/.vitepress/cache/deps/prismjs_components_prism-json.js.map +0 -7
  116. package/docs/.vitepress/cache/deps/prismjs_components_prism-python.js +0 -65
  117. package/docs/.vitepress/cache/deps/prismjs_components_prism-python.js.map +0 -7
  118. package/docs/.vitepress/cache/deps/prismjs_components_prism-typescript.js +0 -53
  119. package/docs/.vitepress/cache/deps/prismjs_components_prism-typescript.js.map +0 -7
  120. package/docs/.vitepress/cache/deps/prismjs_components_prism-yaml.js +0 -73
  121. package/docs/.vitepress/cache/deps/prismjs_components_prism-yaml.js.map +0 -7
  122. package/docs/.vitepress/cache/deps/vitepress___@vue_devtools-api.js +0 -4507
  123. package/docs/.vitepress/cache/deps/vitepress___@vue_devtools-api.js.map +0 -7
  124. package/docs/.vitepress/cache/deps/vitepress___@vueuse_core.js +0 -584
  125. package/docs/.vitepress/cache/deps/vitepress___@vueuse_core.js.map +0 -7
  126. package/docs/.vitepress/cache/deps/vitepress___@vueuse_integrations_useFocusTrap.js +0 -1146
  127. package/docs/.vitepress/cache/deps/vitepress___@vueuse_integrations_useFocusTrap.js.map +0 -7
  128. package/docs/.vitepress/cache/deps/vitepress___mark__js_src_vanilla__js.js +0 -1667
  129. package/docs/.vitepress/cache/deps/vitepress___mark__js_src_vanilla__js.js.map +0 -7
  130. package/docs/.vitepress/cache/deps/vitepress___minisearch.js +0 -1814
  131. package/docs/.vitepress/cache/deps/vitepress___minisearch.js.map +0 -7
  132. package/docs/.vitepress/cache/deps/vue.js +0 -344
  133. package/docs/.vitepress/cache/deps/vue.js.map +0 -7
  134. package/examples/theme-matching.md +0 -113
  135. package/mcp-config.json +0 -8
  136. package/note.md +0 -35
  137. package/research_results.md +0 -53
  138. package/src/tools/colors.ts +0 -31
  139. package/src/tools/registry.ts +0 -142
  140. package/src/tools/simple-tools.ts +0 -37
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/tools/color-conversion.tool.ts","../../src/tools/color-distance.tool.ts","../../src/tools/colors.ts","../../src/constants.ts","../../src/tools/contrast-checker.tool.ts","../../src/tools/dislike-analyzer.tool.ts","../../src/tools/gradient-generator.tool.ts","../../src/color/utils/math_utils.ts","../../src/color/utils/color_utils.ts","../../src/color/image-utils.ts","../../src/color/quantize/lab_point_provider.ts","../../src/color/quantize/quantizer_wsmeans.ts","../../src/color/quantize/quantizer_map.ts","../../src/color/quantize/quantizer_wu.ts","../../src/color/quantize/quantizer_celebi.ts","../../src/color/score/score.ts","../../src/color/extract-colors.ts","../../src/color/material-theme.ts","../../src/tools/image-extraction.tools.ts","../../src/tools/material-theme.tools.ts","../../src/tools/palette-generator.tool.ts","../../src/tools/palette-with-locks.tool.ts","../../src/tools/theme-matching.tools.ts","../../src/theme/matcher.ts","../../src/theme/parser.ts","../../src/theme/refactor.ts","../../src/bin/server.ts"],"sourcesContent":["/**\n * Color Conversion Tool\n * Convert colors between different formats (hex, rgb, hsl, lab, hct)\n */\n\nimport { z } from \"zod\";\n\nimport {\n parseColor,\n rgbToHct,\n rgbToHex,\n rgbToHsl,\n rgbToLab,\n} from \"../color/index.js\";\n\nexport const colorConversionTool = {\n description:\n \"Convert colors between different formats (hex, rgb, hsl, lab, hct)\",\n execute: async (args: {\n color: string;\n to: \"hct\" | \"hex\" | \"hsl\" | \"lab\" | \"rgb\";\n }) => {\n const rgb = parseColor(args.color);\n if (!rgb) {\n return `Invalid color format: ${args.color}`;\n }\n\n switch (args.to) {\n case \"hct\": {\n const hct = rgbToHct(rgb);\n return `hct(${hct.h.toFixed(1)}, ${hct.c.toFixed(1)}, ${hct.t.toFixed(1)})`;\n }\n case \"hex\":\n return rgbToHex(rgb);\n case \"hsl\": {\n const hsl = rgbToHsl(rgb);\n return `hsl(${Math.round(hsl.h)}, ${Math.round(hsl.s)}%, ${Math.round(hsl.l)}%)`;\n }\n case \"lab\": {\n const lab = rgbToLab(rgb);\n return `lab(${lab.l.toFixed(2)}, ${lab.a.toFixed(2)}, ${lab.b.toFixed(2)})`;\n }\n case \"rgb\":\n return `rgb(${Math.round(rgb.r * 255)}, ${Math.round(rgb.g * 255)}, ${Math.round(rgb.b * 255)})`;\n default:\n return `Invalid format: ${args.to}`;\n }\n },\n name: \"convert_color\",\n parameters: z.object({\n color: z.string().describe(\"Color to convert (hex, rgb(), or hsl())\"),\n to: z.enum([\"hex\", \"rgb\", \"hsl\", \"lab\", \"hct\"]).describe(\"Target format\"),\n }),\n};\n","/**\n * Color Distance Tool\n * Calculate perceptual distance between two colors using various metrics\n */\n\nimport { z } from \"zod\";\n\nimport { colorDistance, parseColor } from \"../color/index.js\";\n\nexport const colorDistanceTool = {\n description:\n \"Calculate perceptual distance between two colors using Delta E 2000\",\n execute: async (args: {\n color1: string;\n color2: string;\n metric?: \"deltaE2000\" | \"deltaE76\" | \"deltaE94\" | \"euclidean\" | \"weighted\";\n }) => {\n const rgb1 = parseColor(args.color1);\n const rgb2 = parseColor(args.color2);\n\n if (!rgb1 || !rgb2) {\n return `Invalid color format: ${!rgb1 ? args.color1 : args.color2}`;\n }\n\n const distance = colorDistance(rgb1, rgb2, {\n metric: args.metric || \"deltaE2000\",\n });\n\n return `Distance between ${args.color1} and ${args.color2}: ${distance.toFixed(2)}`;\n },\n name: \"color_distance\",\n parameters: z.object({\n color1: z.string().describe(\"First color (hex, rgb, or hsl)\"),\n color2: z.string().describe(\"Second color (hex, rgb, or hsl)\"),\n metric: z\n .enum([\"euclidean\", \"deltaE76\", \"deltaE94\", \"deltaE2000\", \"weighted\"])\n .optional()\n .default(\"deltaE2000\")\n .describe(\"Distance metric to use\"),\n }),\n};\n","import { formatHex, formatHsl, formatRgb, parse } from \"culori\";\nimport { z } from \"zod\";\n\nimport { ColorFormat } from \"../constants.js\";\n\nexport const convertColor = {\n description: \"Convert a color from one format to another\",\n execute: async (args: { color: string; to?: ColorFormat }) => {\n const { color, to = ColorFormat.HEX } = args;\n const parsed = parse(color);\n if (!parsed) {\n throw new Error(`Invalid color: ${color}`);\n }\n\n switch (to) {\n case ColorFormat.HEX:\n return formatHex(parsed);\n case ColorFormat.HSL:\n return formatHsl(parsed);\n case ColorFormat.RGB:\n return formatRgb(parsed);\n default:\n throw new Error(`Invalid output format: ${to}`);\n }\n },\n name: \"convertColor\",\n parameters: z.object({\n color: z.string().describe(\"The color to convert\"),\n to: z.nativeEnum(ColorFormat).optional().describe(\"The output format\"),\n }),\n};\n","export enum ColorFormat {\n HEX = \"hex\",\n HSL = \"hsl\",\n RGB = \"rgb\",\n}\n","/**\n * Contrast Checker Tool\n * Check WCAG contrast ratio between two colors\n */\n\nimport { z } from \"zod\";\n\nimport { getContrastRatio, parseColor } from \"../color/index.js\";\n\nexport const contrastCheckerTool = {\n description: \"Check WCAG contrast ratio between two colors\",\n execute: async (args: { background: string; foreground: string }) => {\n const fg = parseColor(args.foreground);\n const bg = parseColor(args.background);\n\n if (!fg || !bg) {\n return `Invalid color format: ${!fg ? args.foreground : args.background}`;\n }\n\n const ratio = getContrastRatio(fg, bg);\n const aa = ratio >= 4.5;\n const aaLarge = ratio >= 3;\n const aaa = ratio >= 7;\n const aaaLarge = ratio >= 4.5;\n\n return `Contrast Ratio: ${ratio.toFixed(2)}:1\nWCAG AA: ${aa ? \"✓ Pass\" : \"✗ Fail\"} (normal text)\nWCAG AA: ${aaLarge ? \"✓ Pass\" : \"✗ Fail\"} (large text)\nWCAG AAA: ${aaa ? \"✓ Pass\" : \"✗ Fail\"} (normal text)\nWCAG AAA: ${aaaLarge ? \"✓ Pass\" : \"✗ Fail\"} (large text)`;\n },\n name: \"check_contrast\",\n parameters: z.object({\n background: z.string().describe(\"Background color\"),\n foreground: z.string().describe(\"Foreground/text color\"),\n }),\n};\n","/**\n * MCP Tools for Dislike Color Analysis\n * Identifies and fixes universally disliked colors based on color psychology research\n */\n\nimport type { Tool } from \"../types.js\";\n\ntype McpTool = Tool<any>;\n\nimport { DislikeAnalyzer } from \"../color/dislike/dislike-analyzer.js\";\nimport { Hct } from \"../color/hct/hct-class.js\";\nimport { parseColor, rgbToArgb } from \"../color/index.js\";\n\n/**\n * Analyze if a color is universally disliked\n */\nexport const analyzeColorLikabilityTool: McpTool = {\n description:\n \"Check if a color is universally disliked (dark yellow-green associated with biological waste) and get a fixed version if needed\",\n execute: async (args: unknown, _context: any) => {\n const { autoFix = true, color } = args as {\n autoFix?: boolean;\n color: string;\n };\n\n try {\n // Parse the input color\n const rgb = parseColor(color);\n if (!rgb) {\n return `Error: Invalid color format: ${color}`;\n }\n\n // Convert to HCT for analysis\n const argb = rgbToArgb(rgb);\n const hct = Hct.fromInt(argb);\n\n // Check if disliked\n const isDisliked = DislikeAnalyzer.isDisliked(hct);\n\n let output = `# Color Likability Analysis\\n\\n`;\n output += `## Input Color: ${color}\\n\\n`;\n output += `### HCT Values\\n`;\n output += `- Hue: ${hct.hue.toFixed(1)}°\\n`;\n output += `- Chroma: ${hct.chroma.toFixed(1)}\\n`;\n output += `- Tone: ${hct.tone.toFixed(1)}\\n\\n`;\n\n output += `### Analysis Result\\n`;\n\n if (isDisliked) {\n output += `⚠️ **This color is universally disliked**\\n\\n`;\n output += `This color falls in the \"bile zone\" - dark yellow-greens that are universally associated with biological waste and rotting food.\\n\\n`;\n output += `**Reason:**\\n`;\n output += `- Hue is in yellow-green range (90-111°): ${Math.round(hct.hue)}°\\n`;\n output += `- Chroma is above threshold (>16): ${Math.round(hct.chroma)}\\n`;\n output += `- Tone is dark (<65): ${Math.round(hct.tone)}\\n\\n`;\n\n if (autoFix) {\n const fixed = DislikeAnalyzer.fixIfDisliked(hct);\n const fixedArgb = fixed.toInt();\n const fixedHex =\n \"#\" +\n [\n (fixedArgb >> 16) & 0xff,\n (fixedArgb >> 8) & 0xff,\n fixedArgb & 0xff,\n ]\n .map((x) => x.toString(16).padStart(2, \"0\"))\n .join(\"\");\n\n output += `### Recommended Fix\\n`;\n output += `**Fixed Color:** ${fixedHex}\\n`;\n output += `- Hue: ${fixed.hue.toFixed(1)}° (preserved)\\n`;\n output += `- Chroma: ${fixed.chroma.toFixed(1)} (preserved)\\n`;\n output += `- Tone: ${fixed.tone.toFixed(1)} (lightened to 70)\\n\\n`;\n output += `The fix preserves the hue and saturation but lightens the color to make it more pleasant.\\n`;\n }\n } else {\n output += `✅ **This color is likable**\\n\\n`;\n output += `This color does not fall in the universally disliked range.\\n`;\n\n // Provide context about why it's liked\n if (Math.round(hct.hue) >= 90 && Math.round(hct.hue) <= 111) {\n if (Math.round(hct.chroma) <= 16) {\n output += `- Although in yellow-green hue range, the low chroma (${Math.round(hct.chroma)}) makes it neutral and acceptable.\\n`;\n } else if (Math.round(hct.tone) >= 65) {\n output += `- Although in yellow-green hue range, the light tone (${Math.round(hct.tone)}) makes it pleasant.\\n`;\n }\n } else {\n output += `- Hue (${Math.round(hct.hue)}°) is outside the problematic yellow-green range.\\n`;\n }\n }\n\n return output;\n } catch (error) {\n return `Error analyzing color: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n inputSchema: {\n properties: {\n autoFix: {\n description:\n \"Automatically return fixed version if disliked (default: true)\",\n type: \"boolean\",\n },\n color: {\n description: \"Color to analyze (hex, rgb, hsl, etc.)\",\n type: \"string\",\n },\n },\n required: [\"color\"],\n type: \"object\",\n },\n name: \"analyze_color_likability\",\n};\n\n/**\n * Fix multiple disliked colors in a batch\n */\nexport const fixDislikedColorsBatchTool: McpTool = {\n description: \"Analyze and fix multiple colors, returning only liked versions\",\n execute: async (args: unknown, _context: any) => {\n const { colors, includeAnalysis = false } = args as {\n colors: string[];\n includeAnalysis?: boolean;\n };\n\n try {\n const results: Array<{\n error?: string;\n fixed?: string;\n hct?: unknown;\n original: string;\n wasDisliked?: boolean;\n }> = [];\n let dislikedCount = 0;\n\n for (const color of colors) {\n const rgb = parseColor(color);\n if (!rgb) {\n results.push({\n error: \"Invalid color format\",\n original: color,\n });\n continue;\n }\n\n const argb = rgbToArgb(rgb);\n const hct = Hct.fromInt(argb);\n const isDisliked = DislikeAnalyzer.isDisliked(hct);\n\n if (isDisliked) {\n dislikedCount++;\n const fixed = DislikeAnalyzer.fixIfDisliked(hct);\n const fixedArgb = fixed.toInt();\n const fixedHex =\n \"#\" +\n [\n (fixedArgb >> 16) & 0xff,\n (fixedArgb >> 8) & 0xff,\n fixedArgb & 0xff,\n ]\n .map((x) => x.toString(16).padStart(2, \"0\"))\n .join(\"\");\n\n results.push({\n fixed: fixedHex,\n hct: includeAnalysis\n ? {\n fixed: { c: fixed.chroma, h: fixed.hue, t: fixed.tone },\n original: { c: hct.chroma, h: hct.hue, t: hct.tone },\n }\n : undefined,\n original: color,\n wasDisliked: true,\n });\n } else {\n results.push({\n fixed: color,\n hct: includeAnalysis\n ? {\n c: hct.chroma,\n h: hct.hue,\n t: hct.tone,\n }\n : undefined,\n original: color,\n wasDisliked: false,\n });\n }\n }\n\n let output = `# Batch Color Likability Analysis\\n\\n`;\n output += `## Summary\\n`;\n output += `- Total colors: ${colors.length}\\n`;\n output += `- Disliked colors found: ${dislikedCount}\\n`;\n output += `- Percentage disliked: ${((dislikedCount / colors.length) * 100).toFixed(1)}%\\n\\n`;\n\n output += `## Results\\n\\n`;\n\n for (const result of results) {\n if (result.error) {\n output += `- **${result.original}**: ❌ ${result.error}\\n`;\n } else if (result.wasDisliked) {\n output += `- **${result.original}** → **${result.fixed}** (fixed)\\n`;\n if (includeAnalysis && result.hct) {\n output += ` - Original HCT: (${result.hct.original.h.toFixed(0)}°, ${result.hct.original.c.toFixed(0)}, ${result.hct.original.t.toFixed(0)})\\n`;\n output += ` - Fixed HCT: (${result.hct.fixed.h.toFixed(0)}°, ${result.hct.fixed.c.toFixed(0)}, ${result.hct.fixed.t.toFixed(0)})\\n`;\n }\n } else {\n output += `- **${result.original}** ✓ (already liked)\\n`;\n if (includeAnalysis && result.hct) {\n output += ` - HCT: (${result.hct.h.toFixed(0)}°, ${result.hct.c.toFixed(0)}, ${result.hct.t.toFixed(0)})\\n`;\n }\n }\n }\n\n if (dislikedCount > 0) {\n output += `\\n## Note\\n`;\n output += `Disliked colors have been automatically fixed by lightening their tone to 70 while preserving hue and chroma. `;\n output += `This makes them more pleasant while maintaining their essential character.\\n`;\n }\n\n return output;\n } catch (error) {\n return `Error processing colors: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n inputSchema: {\n properties: {\n colors: {\n description: \"Array of colors to analyze (hex, rgb, hsl, etc.)\",\n items: {\n type: \"string\",\n },\n type: \"array\",\n },\n includeAnalysis: {\n description:\n \"Include detailed analysis for each color (default: false)\",\n type: \"boolean\",\n },\n },\n required: [\"colors\"],\n type: \"object\",\n },\n name: \"fix_disliked_colors_batch\",\n};\n","import { z } from \"zod\";\n\nimport { Hct } from \"../color/hct/index.js\";\nimport {\n hslToRgb,\n labToRgb,\n parseColor,\n rgbToHex,\n rgbToHsl,\n rgbToLab,\n} from \"../color/index.js\";\nimport { RGB } from \"../color/types.js\";\n\nexport const gradientGeneratorTool = {\n description:\n \"Generate a smooth gradient between colors with multiple interpolation methods\",\n execute: async (args: {\n colors: string[];\n easing?: \"ease-in-out\" | \"ease-in\" | \"ease-out\" | \"linear\";\n format?: \"array\" | \"css-linear\" | \"css-radial\" | \"hex\";\n interpolation?: \"hct\" | \"hsl\" | \"lab\" | \"lch\" | \"rgb\";\n steps: number;\n }) => {\n const {\n colors,\n easing = \"linear\",\n format = \"array\",\n interpolation = \"lab\",\n steps,\n } = args;\n\n if (colors.length < 2) {\n return \"Error: At least 2 colors are required for a gradient\";\n }\n\n // Parse input colors\n const parsedColors: RGB[] = [];\n for (const color of colors) {\n const parsed = parseColor(color);\n if (!parsed) {\n return `Invalid color format: ${color}`;\n }\n parsedColors.push(parsed);\n }\n\n // Apply easing function\n const applyEasing = (t: number): number => {\n switch (easing) {\n case \"ease-in\":\n return t * t;\n case \"ease-in-out\":\n return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;\n case \"ease-out\":\n return t * (2 - t);\n default:\n return t;\n }\n };\n\n // Generate gradient colors\n const gradient: RGB[] = [];\n const segmentSteps = Math.floor(steps / (colors.length - 1));\n const extraSteps = steps % (colors.length - 1);\n\n for (let segment = 0; segment < colors.length - 1; segment++) {\n const start = parsedColors[segment];\n const end = parsedColors[segment + 1];\n const currentSteps = segmentSteps + (segment < extraSteps ? 1 : 0);\n\n for (let step = 0; step < currentSteps; step++) {\n const t = applyEasing(step / currentSteps);\n\n let interpolatedColor: RGB;\n\n switch (interpolation) {\n case \"hct\": {\n // HCT interpolation (Material Design color space)\n const startHct = Hct.fromInt(\n (255 << 24) | (start.r << 16) | (start.g << 8) | start.b,\n );\n const endHct = Hct.fromInt(\n (255 << 24) | (end.r << 16) | (end.g << 8) | end.b,\n );\n\n // Interpolate hue (shortest path)\n let hueDiff = endHct.hue - startHct.hue;\n if (hueDiff > 180) hueDiff -= 360;\n if (hueDiff < -180) hueDiff += 360;\n\n const interpolatedHct = Hct.from(\n (startHct.hue + hueDiff * t + 360) % 360,\n startHct.chroma + (endHct.chroma - startHct.chroma) * t,\n startHct.tone + (endHct.tone - startHct.tone) * t,\n );\n\n const argb = interpolatedHct.toInt();\n interpolatedColor = {\n b: argb & 0xff,\n g: (argb >> 8) & 0xff,\n r: (argb >> 16) & 0xff,\n };\n break;\n }\n\n case \"hsl\": {\n // HSL interpolation\n const startHsl = rgbToHsl(start);\n const endHsl = rgbToHsl(end);\n\n // Handle hue interpolation (shortest path)\n let hueDiff = endHsl.h - startHsl.h;\n if (hueDiff > 180) hueDiff -= 360;\n if (hueDiff < -180) hueDiff += 360;\n\n interpolatedColor = hslToRgb({\n h: (startHsl.h + hueDiff * t + 360) % 360,\n l: startHsl.l + (endHsl.l - startHsl.l) * t,\n s: startHsl.s + (endHsl.s - startHsl.s) * t,\n });\n break;\n }\n\n case \"lab\": {\n // LAB interpolation (perceptually uniform)\n const startLab = rgbToLab(start);\n const endLab = rgbToLab(end);\n\n interpolatedColor = labToRgb({\n a: startLab.a + (endLab.a - startLab.a) * t,\n b: startLab.b + (endLab.b - startLab.b) * t,\n l: startLab.l + (endLab.l - startLab.l) * t,\n });\n break;\n }\n\n case \"lch\": {\n // LCH interpolation (cylindrical LAB)\n const startLab = rgbToLab(start);\n const endLab = rgbToLab(end);\n\n // Convert LAB to LCH\n const startL = startLab.l;\n const startC = Math.sqrt(\n startLab.a * startLab.a + startLab.b * startLab.b,\n );\n const startH = (Math.atan2(startLab.b, startLab.a) * 180) / Math.PI;\n\n const endL = endLab.l;\n const endC = Math.sqrt(endLab.a * endLab.a + endLab.b * endLab.b);\n const endH = (Math.atan2(endLab.b, endLab.a) * 180) / Math.PI;\n\n // Interpolate in LCH\n let hueDiff = endH - startH;\n if (hueDiff > 180) hueDiff -= 360;\n if (hueDiff < -180) hueDiff += 360;\n\n const l = startL + (endL - startL) * t;\n const c = startC + (endC - startC) * t;\n const h = ((startH + hueDiff * t) * Math.PI) / 180;\n\n // Convert back to LAB then RGB\n interpolatedColor = labToRgb({\n a: c * Math.cos(h),\n b: c * Math.sin(h),\n l: l,\n });\n break;\n }\n\n case \"rgb\": {\n // Simple RGB interpolation\n interpolatedColor = {\n b: Math.round(start.b + (end.b - start.b) * t),\n g: Math.round(start.g + (end.g - start.g) * t),\n r: Math.round(start.r + (end.r - start.r) * t),\n };\n break;\n }\n\n default:\n interpolatedColor = start; // Fallback\n }\n\n gradient.push(interpolatedColor);\n }\n }\n\n // Add the last color\n gradient.push(parsedColors[parsedColors.length - 1]);\n\n // Format output\n const hexColors = gradient.map(rgbToHex);\n\n switch (format) {\n case \"css-linear\": {\n const stops = hexColors.map((color, i) => {\n const percent = (i / (hexColors.length - 1)) * 100;\n return `${color} ${percent.toFixed(1)}%`;\n });\n return `linear-gradient(90deg, ${stops.join(\", \")})`;\n }\n\n case \"css-radial\": {\n const stops = hexColors.map((color, i) => {\n const percent = (i / (hexColors.length - 1)) * 100;\n return `${color} ${percent.toFixed(1)}%`;\n });\n return `radial-gradient(circle, ${stops.join(\", \")})`;\n }\n\n case \"hex\":\n return hexColors.join(\", \");\n\n case \"array\":\n default:\n return `Generated gradient with ${steps} steps:\n${hexColors.map((color, i) => `${i + 1}. ${color}`).join(\"\\n\")}\n\nInterpolation: ${interpolation}\nEasing: ${easing}\nInput colors: ${colors.join(\" → \")}`;\n }\n },\n name: \"generate_gradient\",\n parameters: z.object({\n colors: z\n .array(z.string())\n .min(2)\n .describe(\"Colors to create gradient between (minimum 2)\"),\n easing: z\n .enum([\"linear\", \"ease-in\", \"ease-out\", \"ease-in-out\"])\n .default(\"linear\")\n .describe(\"Easing function for gradient transition\"),\n format: z\n .enum([\"hex\", \"css-linear\", \"css-radial\", \"array\"])\n .default(\"array\")\n .describe(\"Output format for the gradient\"),\n interpolation: z\n .enum([\"rgb\", \"hsl\", \"lab\", \"lch\", \"hct\"])\n .default(\"lab\")\n .describe(\n \"Color space for interpolation (lab/lch/hct are perceptually smooth)\",\n ),\n steps: z\n .number()\n .min(3)\n .max(100)\n .describe(\"Number of colors in the gradient\"),\n }),\n};\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// This file is automatically generated. Do not modify it.\n\n/**\n * Utility methods for mathematical operations.\n */\n\n/**\n * Clamps an integer between two floating-point numbers.\n *\n * @return input when min <= input <= max, and either min or max\n * otherwise.\n */\nexport function clampDouble(min: number, max: number, input: number): number {\n if (input < min) {\n return min;\n } else if (input > max) {\n return max;\n }\n\n return input;\n}\n\n/**\n * Clamps an integer between two integers.\n *\n * @return input when min <= input <= max, and either min or max\n * otherwise.\n */\nexport function clampInt(min: number, max: number, input: number): number {\n if (input < min) {\n return min;\n } else if (input > max) {\n return max;\n }\n\n return input;\n}\n\n/**\n * Distance of two points on a circle, represented using degrees.\n */\nexport function differenceDegrees(a: number, b: number): number {\n return 180.0 - Math.abs(Math.abs(a - b) - 180.0);\n}\n\n/**\n * The linear interpolation function.\n *\n * @return start if amount = 0 and stop if amount = 1\n */\nexport function lerp(start: number, stop: number, amount: number): number {\n return (1.0 - amount) * start + amount * stop;\n}\n\n/**\n * Multiplies a 1x3 row vector with a 3x3 matrix.\n */\nexport function matrixMultiply(row: number[], matrix: number[][]): number[] {\n const a =\n row[0] * matrix[0][0] + row[1] * matrix[0][1] + row[2] * matrix[0][2];\n const b =\n row[0] * matrix[1][0] + row[1] * matrix[1][1] + row[2] * matrix[1][2];\n const c =\n row[0] * matrix[2][0] + row[1] * matrix[2][1] + row[2] * matrix[2][2];\n return [a, b, c];\n}\n\n/**\n * Sign of direction change needed to travel from one angle to\n * another.\n *\n * For angles that are 180 degrees apart from each other, both\n * directions have the same travel distance, so either direction is\n * shortest. The value 1.0 is returned in this case.\n *\n * @param from The angle travel starts from, in degrees.\n * @param to The angle travel ends at, in degrees.\n * @return -1 if decreasing from leads to the shortest travel\n * distance, 1 if increasing from leads to the shortest travel\n * distance.\n */\nexport function rotationDirection(from: number, to: number): number {\n const increasingDifference = sanitizeDegreesDouble(to - from);\n return increasingDifference <= 180.0 ? 1.0 : -1.0;\n}\n\n/**\n * Sanitizes a degree measure as a floating-point number.\n *\n * @return a degree measure between 0.0 (inclusive) and 360.0\n * (exclusive).\n */\nexport function sanitizeDegreesDouble(degrees: number): number {\n degrees = degrees % 360.0;\n if (degrees < 0) {\n degrees = degrees + 360.0;\n }\n return degrees;\n}\n\n/**\n * Sanitizes a degree measure as an integer.\n *\n * @return a degree measure between 0 (inclusive) and 360\n * (exclusive).\n */\nexport function sanitizeDegreesInt(degrees: number): number {\n degrees = degrees % 360;\n if (degrees < 0) {\n degrees = degrees + 360;\n }\n return degrees;\n}\n\n/**\n * The signum function.\n *\n * @return 1 if num > 0, -1 if num < 0, and 0 if num = 0\n */\nexport function signum(num: number): number {\n if (num < 0) {\n return -1;\n } else if (num === 0) {\n return 0;\n } else {\n return 1;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// This file is automatically generated. Do not modify it.\n\nimport * as mathUtils from \"./math_utils.js\";\n\n/**\n * Color science utilities.\n *\n * Utility methods for color science constants and color space\n * conversions that aren't HCT or CAM16.\n */\n\nconst SRGB_TO_XYZ = [\n [0.41233895, 0.35762064, 0.18051042],\n [0.2126, 0.7152, 0.0722],\n [0.01932141, 0.11916382, 0.95034478],\n];\n\nconst XYZ_TO_SRGB = [\n [3.2413774792388685, -1.5376652402851851, -0.49885366846268053],\n [-0.9691452513005321, 1.8758853451067872, 0.04156585616912061],\n [0.05562093689691305, -0.20395524564742123, 1.0571799111220335],\n];\n\nconst WHITE_POINT_D65 = [95.047, 100.0, 108.883];\n\n/**\n * Returns the alpha component of a color in ARGB format.\n */\nexport function alphaFromArgb(argb: number): number {\n return (argb >> 24) & 255;\n}\n\n/**\n * Converts a color represented in Lab color space into an ARGB\n * integer.\n */\nexport function argbFromLab(l: number, a: number, b: number): number {\n const whitePoint = WHITE_POINT_D65;\n const fy = (l + 16.0) / 116.0;\n const fx = a / 500.0 + fy;\n const fz = fy - b / 200.0;\n const xNormalized = labInvf(fx);\n const yNormalized = labInvf(fy);\n const zNormalized = labInvf(fz);\n const x = xNormalized * whitePoint[0];\n const y = yNormalized * whitePoint[1];\n const z = zNormalized * whitePoint[2];\n return argbFromXyz(x, y, z);\n}\n\n/**\n * Converts a color from linear RGB components to ARGB format.\n */\nexport function argbFromLinrgb(linrgb: number[]): number {\n const r = delinearized(linrgb[0]);\n const g = delinearized(linrgb[1]);\n const b = delinearized(linrgb[2]);\n return argbFromRgb(r, g, b);\n}\n\n/**\n * Converts an L* value to an ARGB representation.\n *\n * @param lstar L* in L*a*b*\n * @return ARGB representation of grayscale color with lightness\n * matching L*\n */\nexport function argbFromLstar(lstar: number): number {\n const y = yFromLstar(lstar);\n const component = delinearized(y);\n return argbFromRgb(component, component, component);\n}\n\n/**\n * Converts a color from RGB components to ARGB format.\n */\nexport function argbFromRgb(red: number, green: number, blue: number): number {\n return (\n ((255 << 24) |\n ((red & 255) << 16) |\n ((green & 255) << 8) |\n (blue & 255)) >>>\n 0\n );\n}\n\n/**\n * Converts a color from ARGB to XYZ.\n */\nexport function argbFromXyz(x: number, y: number, z: number): number {\n const matrix = XYZ_TO_SRGB;\n const linearR = matrix[0][0] * x + matrix[0][1] * y + matrix[0][2] * z;\n const linearG = matrix[1][0] * x + matrix[1][1] * y + matrix[1][2] * z;\n const linearB = matrix[2][0] * x + matrix[2][1] * y + matrix[2][2] * z;\n const r = delinearized(linearR);\n const g = delinearized(linearG);\n const b = delinearized(linearB);\n return argbFromRgb(r, g, b);\n}\n\n/**\n * Returns the blue component of a color in ARGB format.\n */\nexport function blueFromArgb(argb: number): number {\n return argb & 255;\n}\n\n/**\n * Delinearizes an RGB component.\n *\n * @param rgbComponent 0.0 <= rgb_component <= 100.0, represents\n * linear R/G/B channel\n * @return 0 <= output <= 255, color channel converted to regular\n * RGB space\n */\nexport function delinearized(rgbComponent: number): number {\n const normalized = rgbComponent / 100.0;\n let delinearized = 0.0;\n if (normalized <= 0.0031308) {\n delinearized = normalized * 12.92;\n } else {\n delinearized = 1.055 * Math.pow(normalized, 1.0 / 2.4) - 0.055;\n }\n return mathUtils.clampInt(0, 255, Math.round(delinearized * 255.0));\n}\n\n/**\n * Returns the green component of a color in ARGB format.\n */\nexport function greenFromArgb(argb: number): number {\n return (argb >> 8) & 255;\n}\n\n/**\n * Returns whether a color in ARGB format is opaque.\n */\nexport function isOpaque(argb: number): boolean {\n return alphaFromArgb(argb) >= 255;\n}\n\n/**\n * Converts a color from ARGB representation to L*a*b*\n * representation.\n *\n * @param argb the ARGB representation of a color\n * @return a Lab object representing the color\n */\nexport function labFromArgb(argb: number): number[] {\n const linearR = linearized(redFromArgb(argb));\n const linearG = linearized(greenFromArgb(argb));\n const linearB = linearized(blueFromArgb(argb));\n const matrix = SRGB_TO_XYZ;\n const x =\n matrix[0][0] * linearR + matrix[0][1] * linearG + matrix[0][2] * linearB;\n const y =\n matrix[1][0] * linearR + matrix[1][1] * linearG + matrix[1][2] * linearB;\n const z =\n matrix[2][0] * linearR + matrix[2][1] * linearG + matrix[2][2] * linearB;\n const whitePoint = WHITE_POINT_D65;\n const xNormalized = x / whitePoint[0];\n const yNormalized = y / whitePoint[1];\n const zNormalized = z / whitePoint[2];\n const fx = labF(xNormalized);\n const fy = labF(yNormalized);\n const fz = labF(zNormalized);\n const l = 116.0 * fy - 16;\n const a = 500.0 * (fx - fy);\n const b = 200.0 * (fy - fz);\n return [l, a, b];\n}\n\n/**\n * Linearizes an RGB component.\n *\n * @param rgbComponent 0 <= rgb_component <= 255, represents R/G/B\n * channel\n * @return 0.0 <= output <= 100.0, color channel converted to\n * linear RGB space\n */\nexport function linearized(rgbComponent: number): number {\n const normalized = rgbComponent / 255.0;\n if (normalized <= 0.040449936) {\n return (normalized / 12.92) * 100.0;\n } else {\n return Math.pow((normalized + 0.055) / 1.055, 2.4) * 100.0;\n }\n}\n\n/**\n * Computes the L* value of a color in ARGB representation.\n *\n * @param argb ARGB representation of a color\n * @return L*, from L*a*b*, coordinate of the color\n */\nexport function lstarFromArgb(argb: number): number {\n const y = xyzFromArgb(argb)[1];\n return 116.0 * labF(y / 100.0) - 16.0;\n}\n\n/**\n * Converts a Y value to an L* value.\n *\n * L* in L*a*b* and Y in XYZ measure the same quantity, luminance.\n *\n * L* measures perceptual luminance, a linear scale. Y in XYZ\n * measures relative luminance, a logarithmic scale.\n *\n * @param y Y in XYZ\n * @return L* in L*a*b*\n */\nexport function lstarFromY(y: number): number {\n return labF(y / 100.0) * 116.0 - 16.0;\n}\n\n/**\n * Returns the red component of a color in ARGB format.\n */\nexport function redFromArgb(argb: number): number {\n return (argb >> 16) & 255;\n}\n\n/**\n * Returns the standard white point; white on a sunny day.\n *\n * @return The white point\n */\nexport function whitePointD65(): number[] {\n return WHITE_POINT_D65;\n}\n\n/**\n * Converts a color from XYZ to ARGB.\n */\nexport function xyzFromArgb(argb: number): number[] {\n const r = linearized(redFromArgb(argb));\n const g = linearized(greenFromArgb(argb));\n const b = linearized(blueFromArgb(argb));\n return mathUtils.matrixMultiply([r, g, b], SRGB_TO_XYZ);\n}\n\n/**\n * Converts an L* value to a Y value.\n *\n * L* in L*a*b* and Y in XYZ measure the same quantity, luminance.\n *\n * L* measures perceptual luminance, a linear scale. Y in XYZ\n * measures relative luminance, a logarithmic scale.\n *\n * @param lstar L* in L*a*b*\n * @return Y in XYZ\n */\nexport function yFromLstar(lstar: number): number {\n return 100.0 * labInvf((lstar + 16.0) / 116.0);\n}\n\nfunction labF(t: number): number {\n const e = 216.0 / 24389.0;\n const kappa = 24389.0 / 27.0;\n if (t > e) {\n return Math.pow(t, 1.0 / 3.0);\n } else {\n return (kappa * t + 16) / 116;\n }\n}\n\nfunction labInvf(ft: number): number {\n const e = 216.0 / 24389.0;\n const kappa = 24389.0 / 27.0;\n const ft3 = ft * ft * ft;\n if (ft3 > e) {\n return ft3;\n } else {\n return (116 * ft - 16) / kappa;\n }\n}\n","/**\n * Image processing utilities for color extraction\n */\n\nimport * as utils from \"./utils/color_utils.js\";\n\n/**\n * Filter out near-white and near-black pixels\n * @param pixels - Array of ARGB pixels\n * @returns Filtered array\n */\nexport function filterExtremeTones(pixels: number[]): number[] {\n return pixels.filter((pixel) => {\n const r = utils.redFromArgb(pixel);\n const g = utils.greenFromArgb(pixel);\n const b = utils.blueFromArgb(pixel);\n\n // Calculate luminance (rough approximation)\n const luminance = 0.299 * r + 0.587 * g + 0.114 * b;\n\n // Filter out very dark (< 5%) and very light (> 95%) pixels\n return luminance > 12.75 && luminance < 242.25;\n });\n}\n\n/**\n * Convert image data to ARGB pixel array\n * @param imageData - Canvas ImageData or similar structure\n * @returns Array of ARGB colors as 32-bit integers\n */\nexport function imageDataToPixels(imageData: {\n data: number[] | Uint8ClampedArray;\n height: number;\n width: number;\n}): number[] {\n const pixels: number[] = [];\n const data = imageData.data;\n\n // Process RGBA data (4 bytes per pixel)\n for (let i = 0; i < data.length; i += 4) {\n const r = data[i];\n const g = data[i + 1];\n const b = data[i + 2];\n const a = data[i + 3];\n\n // Skip fully transparent pixels\n if (a < 255 * 0.01) continue;\n\n // Convert to ARGB format\n const argb = utils.argbFromRgb(r, g, b);\n pixels.push(argb);\n }\n\n return pixels;\n}\n\n/**\n * Sample pixels from image for faster processing\n * @param pixels - Full array of pixels\n * @param maxPixels - Maximum number of pixels to sample\n * @returns Sampled array of pixels\n */\nexport function samplePixels(\n pixels: number[],\n maxPixels: number = 10000,\n): number[] {\n if (pixels.length <= maxPixels) {\n return pixels;\n }\n\n const sampled: number[] = [];\n const step = Math.ceil(pixels.length / maxPixels);\n\n for (let i = 0; i < pixels.length; i += step) {\n sampled.push(pixels[i]);\n }\n\n return sampled;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as utils from \"../utils/color_utils.js\";\nimport { PointProvider } from \"./point_provider.js\";\n\n/**\n * Provides conversions needed for K-Means quantization. Converting input to\n * points, and converting the final state of the K-Means algorithm to colors.\n */\nexport class LabPointProvider implements PointProvider {\n /**\n * Standard CIE 1976 delta E formula also takes the square root, unneeded\n * here. This method is used by quantization algorithms to compare distance,\n * and the relative ordering is the same, with or without a square root.\n *\n * This relatively minor optimization is helpful because this method is\n * called at least once for each pixel in an image.\n */\n distance(from: number[], to: number[]): number {\n const dL = from[0] - to[0];\n const dA = from[1] - to[1];\n const dB = from[2] - to[2];\n return dL * dL + dA * dA + dB * dB;\n }\n\n /**\n * Convert a color represented in ARGB to a 3-element array of L*a*b*\n * coordinates of the color.\n */\n fromInt(argb: number): number[] {\n return utils.labFromArgb(argb);\n }\n\n /**\n * Convert a 3-element array to a color represented in ARGB.\n */\n toInt(point: number[]): number {\n return utils.argbFromLab(point[0], point[1], point[2]);\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LabPointProvider } from \"./lab_point_provider.js\";\n\nconst MAX_ITERATIONS = 10;\nconst MIN_MOVEMENT_DISTANCE = 3.0;\n\n/**\n * A wrapper for maintaining a table of distances between K-Means clusters.\n */\nclass DistanceAndIndex {\n distance: number = -1;\n index: number = -1;\n}\n\n/**\n * An image quantizer that improves on the speed of a standard K-Means algorithm\n * by implementing several optimizations, including deduping identical pixels\n * and a triangle inequality rule that reduces the number of comparisons needed\n * to identify which cluster a point should be moved to.\n *\n * Wsmeans stands for Weighted Square Means.\n *\n * This algorithm was designed by M. Emre Celebi, and was found in their 2011\n * paper, Improving the Performance of K-Means for Color Quantization.\n * https://arxiv.org/abs/1101.0395\n */\n// material_color_utilities is designed to have a consistent API across\n// platforms and modular components that can be moved around easily. Using a\n// class as a namespace facilitates this.\n//\n// tslint:disable-next-line:class-as-namespace\nexport class QuantizerWsmeans {\n /**\n * @param inputPixels Colors in ARGB format.\n * @param startingClusters Defines the initial state of the quantizer. Passing\n * an empty array is fine, the implementation will create its own initial\n * state that leads to reproducible results for the same inputs.\n * Passing an array that is the result of Wu quantization leads to higher\n * quality results.\n * @param maxColors The number of colors to divide the image into. A lower\n * number of colors may be returned.\n * @return Colors in ARGB format.\n */\n static quantize(\n inputPixels: number[],\n startingClusters: number[],\n maxColors: number,\n ): Map<number, number> {\n const pixelToCount = new Map<number, number>();\n const points = new Array<number[]>();\n const pixels = new Array<number>();\n const pointProvider = new LabPointProvider();\n let pointCount = 0;\n for (let i = 0; i < inputPixels.length; i++) {\n const inputPixel = inputPixels[i];\n const pixelCount = pixelToCount.get(inputPixel);\n if (pixelCount === undefined) {\n pointCount++;\n points.push(pointProvider.fromInt(inputPixel));\n pixels.push(inputPixel);\n pixelToCount.set(inputPixel, 1);\n } else {\n pixelToCount.set(inputPixel, pixelCount + 1);\n }\n }\n\n const counts = new Array<number>();\n for (let i = 0; i < pointCount; i++) {\n const pixel = pixels[i];\n const count = pixelToCount.get(pixel);\n if (count !== undefined) {\n counts[i] = count;\n }\n }\n\n let clusterCount = Math.min(maxColors, pointCount);\n if (startingClusters.length > 0) {\n clusterCount = Math.min(clusterCount, startingClusters.length);\n }\n\n const clusters = new Array<number[]>();\n for (let i = 0; i < startingClusters.length; i++) {\n clusters.push(pointProvider.fromInt(startingClusters[i]));\n }\n const additionalClustersNeeded = clusterCount - clusters.length;\n if (startingClusters.length === 0 && additionalClustersNeeded > 0) {\n for (let i = 0; i < additionalClustersNeeded; i++) {\n const l = Math.random() * 100.0;\n const a = Math.random() * (100.0 - -100.0 + 1) + -100;\n const b = Math.random() * (100.0 - -100.0 + 1) + -100;\n\n clusters.push([l, a, b]);\n }\n }\n\n const clusterIndices = new Array<number>();\n for (let i = 0; i < pointCount; i++) {\n clusterIndices.push(Math.floor(Math.random() * clusterCount));\n }\n\n const indexMatrix = new Array<number[]>();\n for (let i = 0; i < clusterCount; i++) {\n indexMatrix.push(new Array<number>());\n for (let j = 0; j < clusterCount; j++) {\n indexMatrix[i].push(0);\n }\n }\n\n const distanceToIndexMatrix = new Array<DistanceAndIndex[]>();\n for (let i = 0; i < clusterCount; i++) {\n distanceToIndexMatrix.push(new Array<DistanceAndIndex>());\n for (let j = 0; j < clusterCount; j++) {\n distanceToIndexMatrix[i].push(new DistanceAndIndex());\n }\n }\n\n const pixelCountSums = new Array<number>();\n for (let i = 0; i < clusterCount; i++) {\n pixelCountSums.push(0);\n }\n for (let iteration = 0; iteration < MAX_ITERATIONS; iteration++) {\n for (let i = 0; i < clusterCount; i++) {\n for (let j = i + 1; j < clusterCount; j++) {\n const distance = pointProvider.distance(clusters[i], clusters[j]);\n distanceToIndexMatrix[j][i].distance = distance;\n distanceToIndexMatrix[j][i].index = i;\n distanceToIndexMatrix[i][j].distance = distance;\n distanceToIndexMatrix[i][j].index = j;\n }\n distanceToIndexMatrix[i].sort();\n for (let j = 0; j < clusterCount; j++) {\n indexMatrix[i][j] = distanceToIndexMatrix[i][j].index;\n }\n }\n\n let pointsMoved = 0;\n for (let i = 0; i < pointCount; i++) {\n const point = points[i];\n const previousClusterIndex = clusterIndices[i];\n const previousCluster = clusters[previousClusterIndex];\n const previousDistance = pointProvider.distance(point, previousCluster);\n let minimumDistance = previousDistance;\n let newClusterIndex = -1;\n for (let j = 0; j < clusterCount; j++) {\n if (\n distanceToIndexMatrix[previousClusterIndex][j].distance >=\n 4 * previousDistance\n ) {\n continue;\n }\n const distance = pointProvider.distance(point, clusters[j]);\n if (distance < minimumDistance) {\n minimumDistance = distance;\n newClusterIndex = j;\n }\n }\n if (newClusterIndex !== -1) {\n const distanceChange = Math.abs(\n Math.sqrt(minimumDistance) - Math.sqrt(previousDistance),\n );\n if (distanceChange > MIN_MOVEMENT_DISTANCE) {\n pointsMoved++;\n clusterIndices[i] = newClusterIndex;\n }\n }\n }\n\n if (pointsMoved === 0 && iteration !== 0) {\n break;\n }\n\n const componentASums = new Array<number>(clusterCount).fill(0);\n const componentBSums = new Array<number>(clusterCount).fill(0);\n const componentCSums = new Array<number>(clusterCount).fill(0);\n\n for (let i = 0; i < clusterCount; i++) {\n pixelCountSums[i] = 0;\n }\n for (let i = 0; i < pointCount; i++) {\n const clusterIndex = clusterIndices[i];\n const point = points[i];\n const count = counts[i];\n pixelCountSums[clusterIndex] += count;\n componentASums[clusterIndex] += point[0] * count;\n componentBSums[clusterIndex] += point[1] * count;\n componentCSums[clusterIndex] += point[2] * count;\n }\n\n for (let i = 0; i < clusterCount; i++) {\n const count = pixelCountSums[i];\n if (count === 0) {\n clusters[i] = [0.0, 0.0, 0.0];\n continue;\n }\n const a = componentASums[i] / count;\n const b = componentBSums[i] / count;\n const c = componentCSums[i] / count;\n clusters[i] = [a, b, c];\n }\n }\n\n const argbToPopulation = new Map<number, number>();\n for (let i = 0; i < clusterCount; i++) {\n const count = pixelCountSums[i];\n if (count === 0) {\n continue;\n }\n\n const possibleNewCluster = pointProvider.toInt(clusters[i]);\n // Accumulate population counts when multiple clusters converge to same color\n const existingCount = argbToPopulation.get(possibleNewCluster) || 0;\n argbToPopulation.set(possibleNewCluster, existingCount + count);\n }\n return argbToPopulation;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as utils from \"../utils/color_utils.js\";\n\n/**\n * Quantizes an image into a map, with keys of ARGB colors, and values of the\n * number of times that color appears in the image.\n */\n// material_color_utilities is designed to have a consistent API across\n// platforms and modular components that can be moved around easily. Using a\n// class as a namespace facilitates this.\n//\n// tslint:disable-next-line:class-as-namespace\nexport class QuantizerMap {\n /**\n * @param pixels Colors in ARGB format.\n * @return A Map with keys of ARGB colors, and values of the number of times\n * the color appears in the image.\n */\n static quantize(pixels: number[]): Map<number, number> {\n const countByColor = new Map<number, number>();\n for (let i = 0; i < pixels.length; i++) {\n const pixel = pixels[i];\n const alpha = utils.alphaFromArgb(pixel);\n if (alpha < 255) {\n continue;\n }\n countByColor.set(pixel, (countByColor.get(pixel) ?? 0) + 1);\n }\n return countByColor;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as utils from \"../utils/color_utils.js\";\nimport { QuantizerMap } from \"./quantizer_map.js\";\n\nconst INDEX_BITS = 5;\nconst SIDE_LENGTH = 33; // ((1 << INDEX_INDEX_BITS) + 1)\nconst TOTAL_SIZE = 35937; // SIDE_LENGTH * SIDE_LENGTH * SIDE_LENGTH\n\nconst directions = {\n BLUE: \"blue\",\n GREEN: \"green\",\n RED: \"red\",\n};\n\n/**\n * Keeps track of the state of each box created as the Wu quantization\n * algorithm progresses through dividing the image's pixels as plotted in RGB.\n */\nclass Box {\n constructor(\n public r0: number = 0,\n public r1: number = 0,\n public g0: number = 0,\n public g1: number = 0,\n public b0: number = 0,\n public b1: number = 0,\n public vol: number = 0,\n ) {}\n}\n\n/**\n * Represents final result of Wu algorithm.\n */\nclass CreateBoxesResult {\n /**\n * @param requestedCount how many colors the caller asked to be returned from\n * quantization.\n * @param resultCount the actual number of colors achieved from quantization.\n * May be lower than the requested count.\n */\n constructor(\n public requestedCount: number,\n public resultCount: number,\n ) {}\n}\n\n/**\n * Represents the result of calculating where to cut an existing box in such\n * a way to maximize variance between the two new boxes created by a cut.\n */\nclass MaximizeResult {\n constructor(\n public cutLocation: number,\n public maximum: number,\n ) {}\n}\n\n/**\n * An image quantizer that divides the image's pixels into clusters by\n * recursively cutting an RGB cube, based on the weight of pixels in each area\n * of the cube.\n *\n * The algorithm was described by Xiaolin Wu in Graphic Gems II, published in\n * 1991.\n */\nexport class QuantizerWu {\n constructor(\n private weights: number[] = [],\n private momentsR: number[] = [],\n private momentsG: number[] = [],\n private momentsB: number[] = [],\n private moments: number[] = [],\n private cubes: Box[] = [],\n ) {}\n\n /**\n * @param pixels Colors in ARGB format.\n * @param maxColors The number of colors to divide the image into. A lower\n * number of colors may be returned.\n * @return Colors in ARGB format.\n */\n quantize(pixels: number[], maxColors: number): number[] {\n this.constructHistogram(pixels);\n this.computeMoments();\n const createBoxesResult = this.createBoxes(maxColors);\n const results = this.createResult(createBoxesResult.resultCount);\n return results;\n }\n\n private bottom(cube: Box, direction: string, moment: number[]) {\n switch (direction) {\n case directions.BLUE:\n return (\n -moment[this.getIndex(cube.r1, cube.g1, cube.b0)] +\n moment[this.getIndex(cube.r1, cube.g0, cube.b0)] +\n moment[this.getIndex(cube.r0, cube.g1, cube.b0)] -\n moment[this.getIndex(cube.r0, cube.g0, cube.b0)]\n );\n case directions.GREEN:\n return (\n -moment[this.getIndex(cube.r1, cube.g0, cube.b1)] +\n moment[this.getIndex(cube.r1, cube.g0, cube.b0)] +\n moment[this.getIndex(cube.r0, cube.g0, cube.b1)] -\n moment[this.getIndex(cube.r0, cube.g0, cube.b0)]\n );\n case directions.RED:\n return (\n -moment[this.getIndex(cube.r0, cube.g1, cube.b1)] +\n moment[this.getIndex(cube.r0, cube.g1, cube.b0)] +\n moment[this.getIndex(cube.r0, cube.g0, cube.b1)] -\n moment[this.getIndex(cube.r0, cube.g0, cube.b0)]\n );\n default:\n throw new Error(\"unexpected direction $direction\");\n }\n }\n\n private computeMoments() {\n for (let r = 1; r < SIDE_LENGTH; r++) {\n const area = Array.from<number>({ length: SIDE_LENGTH }).fill(0);\n const areaR = Array.from<number>({ length: SIDE_LENGTH }).fill(0);\n const areaG = Array.from<number>({ length: SIDE_LENGTH }).fill(0);\n const areaB = Array.from<number>({ length: SIDE_LENGTH }).fill(0);\n const area2 = Array.from<number>({ length: SIDE_LENGTH }).fill(0.0);\n for (let g = 1; g < SIDE_LENGTH; g++) {\n let line = 0;\n let lineR = 0;\n let lineG = 0;\n let lineB = 0;\n let line2 = 0.0;\n for (let b = 1; b < SIDE_LENGTH; b++) {\n const index = this.getIndex(r, g, b);\n line += this.weights[index];\n lineR += this.momentsR[index];\n lineG += this.momentsG[index];\n lineB += this.momentsB[index];\n line2 += this.moments[index];\n\n area[b] += line;\n areaR[b] += lineR;\n areaG[b] += lineG;\n areaB[b] += lineB;\n area2[b] += line2;\n\n const previousIndex = this.getIndex(r - 1, g, b);\n this.weights[index] = this.weights[previousIndex] + area[b];\n this.momentsR[index] = this.momentsR[previousIndex] + areaR[b];\n this.momentsG[index] = this.momentsG[previousIndex] + areaG[b];\n this.momentsB[index] = this.momentsB[previousIndex] + areaB[b];\n this.moments[index] = this.moments[previousIndex] + area2[b];\n }\n }\n }\n }\n\n private constructHistogram(pixels: number[]) {\n this.weights = Array.from<number>({ length: TOTAL_SIZE }).fill(0);\n this.momentsR = Array.from<number>({ length: TOTAL_SIZE }).fill(0);\n this.momentsG = Array.from<number>({ length: TOTAL_SIZE }).fill(0);\n this.momentsB = Array.from<number>({ length: TOTAL_SIZE }).fill(0);\n this.moments = Array.from<number>({ length: TOTAL_SIZE }).fill(0);\n\n const countByColor = QuantizerMap.quantize(pixels);\n\n for (const [pixel, count] of countByColor.entries()) {\n const red = utils.redFromArgb(pixel);\n const green = utils.greenFromArgb(pixel);\n const blue = utils.blueFromArgb(pixel);\n\n const bitsToRemove = 8 - INDEX_BITS;\n const iR = (red >> bitsToRemove) + 1;\n const iG = (green >> bitsToRemove) + 1;\n const iB = (blue >> bitsToRemove) + 1;\n const index = this.getIndex(iR, iG, iB);\n\n this.weights[index] = (this.weights[index] ?? 0) + count;\n this.momentsR[index] += count * red;\n this.momentsG[index] += count * green;\n this.momentsB[index] += count * blue;\n this.moments[index] += count * (red * red + green * green + blue * blue);\n }\n }\n\n private createBoxes(maxColors: number): CreateBoxesResult {\n this.cubes = Array.from<number>({ length: maxColors })\n .fill(0)\n .map(() => new Box());\n const volumeVariance = Array.from<number>({ length: maxColors }).fill(0.0);\n this.cubes[0].r0 = 0;\n this.cubes[0].g0 = 0;\n this.cubes[0].b0 = 0;\n\n this.cubes[0].r1 = SIDE_LENGTH - 1;\n this.cubes[0].g1 = SIDE_LENGTH - 1;\n this.cubes[0].b1 = SIDE_LENGTH - 1;\n\n let generatedColorCount = maxColors;\n let next = 0;\n for (let i = 1; i < maxColors; i++) {\n if (this.cut(this.cubes[next], this.cubes[i])) {\n volumeVariance[next] =\n this.cubes[next].vol > 1 ? this.variance(this.cubes[next]) : 0.0;\n volumeVariance[i] =\n this.cubes[i].vol > 1 ? this.variance(this.cubes[i]) : 0.0;\n } else {\n volumeVariance[next] = 0.0;\n i--;\n }\n\n next = 0;\n let temp = volumeVariance[0];\n for (let j = 1; j <= i; j++) {\n if (volumeVariance[j] > temp) {\n temp = volumeVariance[j];\n next = j;\n }\n }\n if (temp <= 0.0) {\n generatedColorCount = i + 1;\n break;\n }\n }\n return new CreateBoxesResult(maxColors, generatedColorCount);\n }\n\n private createResult(colorCount: number): number[] {\n const colors: number[] = [];\n for (let i = 0; i < colorCount; ++i) {\n const cube = this.cubes[i];\n const weight = this.volume(cube, this.weights);\n if (weight > 0) {\n const r = Math.round(this.volume(cube, this.momentsR) / weight);\n const g = Math.round(this.volume(cube, this.momentsG) / weight);\n const b = Math.round(this.volume(cube, this.momentsB) / weight);\n const color =\n (255 << 24) | ((r & 0x0ff) << 16) | ((g & 0x0ff) << 8) | (b & 0x0ff);\n colors.push(color);\n }\n }\n return colors;\n }\n\n private cut(one: Box, two: Box) {\n const wholeR = this.volume(one, this.momentsR);\n const wholeG = this.volume(one, this.momentsG);\n const wholeB = this.volume(one, this.momentsB);\n const wholeW = this.volume(one, this.weights);\n\n const maxRResult = this.maximize(\n one,\n directions.RED,\n one.r0 + 1,\n one.r1,\n wholeR,\n wholeG,\n wholeB,\n wholeW,\n );\n const maxGResult = this.maximize(\n one,\n directions.GREEN,\n one.g0 + 1,\n one.g1,\n wholeR,\n wholeG,\n wholeB,\n wholeW,\n );\n const maxBResult = this.maximize(\n one,\n directions.BLUE,\n one.b0 + 1,\n one.b1,\n wholeR,\n wholeG,\n wholeB,\n wholeW,\n );\n\n let direction;\n const maxR = maxRResult.maximum;\n const maxG = maxGResult.maximum;\n const maxB = maxBResult.maximum;\n if (maxR >= maxG && maxR >= maxB) {\n if (maxRResult.cutLocation < 0) {\n return false;\n }\n direction = directions.RED;\n } else if (maxG >= maxR && maxG >= maxB) {\n direction = directions.GREEN;\n } else {\n direction = directions.BLUE;\n }\n\n two.r1 = one.r1;\n two.g1 = one.g1;\n two.b1 = one.b1;\n\n switch (direction) {\n case directions.BLUE:\n one.b1 = maxBResult.cutLocation;\n two.r0 = one.r0;\n two.g0 = one.g0;\n two.b0 = one.b1;\n break;\n case directions.GREEN:\n one.g1 = maxGResult.cutLocation;\n two.r0 = one.r0;\n two.g0 = one.g1;\n two.b0 = one.b0;\n break;\n case directions.RED:\n one.r1 = maxRResult.cutLocation;\n two.r0 = one.r1;\n two.g0 = one.g0;\n two.b0 = one.b0;\n break;\n default:\n throw new Error(\"unexpected direction \" + direction);\n }\n\n one.vol = (one.r1 - one.r0) * (one.g1 - one.g0) * (one.b1 - one.b0);\n two.vol = (two.r1 - two.r0) * (two.g1 - two.g0) * (two.b1 - two.b0);\n return true;\n }\n\n private getIndex(r: number, g: number, b: number): number {\n return (\n (r << (INDEX_BITS * 2)) +\n (r << (INDEX_BITS + 1)) +\n r +\n (g << INDEX_BITS) +\n g +\n b\n );\n }\n\n private maximize(\n cube: Box,\n direction: string,\n first: number,\n last: number,\n wholeR: number,\n wholeG: number,\n wholeB: number,\n wholeW: number,\n ) {\n const bottomR = this.bottom(cube, direction, this.momentsR);\n const bottomG = this.bottom(cube, direction, this.momentsG);\n const bottomB = this.bottom(cube, direction, this.momentsB);\n const bottomW = this.bottom(cube, direction, this.weights);\n\n let max = 0.0;\n let cut = -1;\n\n let halfR = 0;\n let halfG = 0;\n let halfB = 0;\n let halfW = 0;\n for (let i = first; i < last; i++) {\n halfR = bottomR + this.top(cube, direction, i, this.momentsR);\n halfG = bottomG + this.top(cube, direction, i, this.momentsG);\n halfB = bottomB + this.top(cube, direction, i, this.momentsB);\n halfW = bottomW + this.top(cube, direction, i, this.weights);\n if (halfW === 0) {\n continue;\n }\n\n let tempNumerator = (halfR * halfR + halfG * halfG + halfB * halfB) * 1.0;\n let tempDenominator = halfW * 1.0;\n let temp = tempNumerator / tempDenominator;\n\n halfR = wholeR - halfR;\n halfG = wholeG - halfG;\n halfB = wholeB - halfB;\n halfW = wholeW - halfW;\n if (halfW === 0) {\n continue;\n }\n\n tempNumerator = (halfR * halfR + halfG * halfG + halfB * halfB) * 1.0;\n tempDenominator = halfW * 1.0;\n temp += tempNumerator / tempDenominator;\n\n if (temp > max) {\n max = temp;\n cut = i;\n }\n }\n return new MaximizeResult(cut, max);\n }\n\n private top(\n cube: Box,\n direction: string,\n position: number,\n moment: number[],\n ) {\n switch (direction) {\n case directions.BLUE:\n return (\n moment[this.getIndex(cube.r1, cube.g1, position)] -\n moment[this.getIndex(cube.r1, cube.g0, position)] -\n moment[this.getIndex(cube.r0, cube.g1, position)] +\n moment[this.getIndex(cube.r0, cube.g0, position)]\n );\n case directions.GREEN:\n return (\n moment[this.getIndex(cube.r1, position, cube.b1)] -\n moment[this.getIndex(cube.r1, position, cube.b0)] -\n moment[this.getIndex(cube.r0, position, cube.b1)] +\n moment[this.getIndex(cube.r0, position, cube.b0)]\n );\n case directions.RED:\n return (\n moment[this.getIndex(position, cube.g1, cube.b1)] -\n moment[this.getIndex(position, cube.g1, cube.b0)] -\n moment[this.getIndex(position, cube.g0, cube.b1)] +\n moment[this.getIndex(position, cube.g0, cube.b0)]\n );\n default:\n throw new Error(\"unexpected direction $direction\");\n }\n }\n\n private variance(cube: Box) {\n const dr = this.volume(cube, this.momentsR);\n const dg = this.volume(cube, this.momentsG);\n const db = this.volume(cube, this.momentsB);\n const xx =\n this.moments[this.getIndex(cube.r1, cube.g1, cube.b1)] -\n this.moments[this.getIndex(cube.r1, cube.g1, cube.b0)] -\n this.moments[this.getIndex(cube.r1, cube.g0, cube.b1)] +\n this.moments[this.getIndex(cube.r1, cube.g0, cube.b0)] -\n this.moments[this.getIndex(cube.r0, cube.g1, cube.b1)] +\n this.moments[this.getIndex(cube.r0, cube.g1, cube.b0)] +\n this.moments[this.getIndex(cube.r0, cube.g0, cube.b1)] -\n this.moments[this.getIndex(cube.r0, cube.g0, cube.b0)];\n const hypotenuse = dr * dr + dg * dg + db * db;\n const volume = this.volume(cube, this.weights);\n return xx - hypotenuse / volume;\n }\n\n private volume(cube: Box, moment: number[]) {\n return (\n moment[this.getIndex(cube.r1, cube.g1, cube.b1)] -\n moment[this.getIndex(cube.r1, cube.g1, cube.b0)] -\n moment[this.getIndex(cube.r1, cube.g0, cube.b1)] +\n moment[this.getIndex(cube.r1, cube.g0, cube.b0)] -\n moment[this.getIndex(cube.r0, cube.g1, cube.b1)] +\n moment[this.getIndex(cube.r0, cube.g1, cube.b0)] +\n moment[this.getIndex(cube.r0, cube.g0, cube.b1)] -\n moment[this.getIndex(cube.r0, cube.g0, cube.b0)]\n );\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QuantizerWsmeans } from \"./quantizer_wsmeans.js\";\nimport { QuantizerWu } from \"./quantizer_wu.js\";\n\n/**\n * An image quantizer that improves on the quality of a standard K-Means\n * algorithm by setting the K-Means initial state to the output of a Wu\n * quantizer, instead of random centroids. Improves on speed by several\n * optimizations, as implemented in Wsmeans, or Weighted Square Means, K-Means\n * with those optimizations.\n *\n * This algorithm was designed by M. Emre Celebi, and was found in their 2011\n * paper, Improving the Performance of K-Means for Color Quantization.\n * https://arxiv.org/abs/1101.0395\n */\n// material_color_utilities is designed to have a consistent API across\n// platforms and modular components that can be moved around easily. Using a\n// class as a namespace facilitates this.\n//\n// tslint:disable-next-line:class-as-namespace\nexport class QuantizerCelebi {\n /**\n * @param pixels Colors in ARGB format.\n * @param maxColors The number of colors to divide the image into. A lower\n * number of colors may be returned.\n * @return Map with keys of colors in ARGB format, and values of number of\n * pixels in the original image that correspond to the color in the\n * quantized image.\n */\n static quantize(pixels: number[], maxColors: number): Map<number, number> {\n const wu = new QuantizerWu();\n const wuResult = wu.quantize(pixels, maxColors);\n return QuantizerWsmeans.quantize(pixels, wuResult, maxColors);\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Hct } from \"../hct/index.js\";\nimport * as math from \"../utils/math_utils.js\";\n\n/**\n * Default options for ranking colors based on usage counts.\n * desired: is the max count of the colors returned.\n * fallbackColorARGB: Is the default color that should be used if no\n * other colors are suitable.\n * filter: controls if the resulting colors should be filtered to not include\n * hues that are not used often enough, and colors that are effectively\n * grayscale.\n */\ndeclare interface ScoreOptions {\n desired?: number;\n fallbackColorARGB?: number;\n filter?: boolean;\n}\n\nconst SCORE_OPTION_DEFAULTS = {\n desired: 4, // 4 colors matches what Android wallpaper picker.\n fallbackColorARGB: 0xff4285f4, // Google Blue.\n filter: true, // Avoid unsuitable colors.\n};\n\nfunction compare(\n a: { hct: Hct; score: number },\n b: { hct: Hct; score: number },\n): number {\n if (a.score > b.score) {\n return -1;\n } else if (a.score < b.score) {\n return 1;\n }\n return 0;\n}\n\n/**\n * Given a large set of colors, remove colors that are unsuitable for a UI\n * theme, and rank the rest based on suitability.\n *\n * Enables use of a high cluster count for image quantization, thus ensuring\n * colors aren't muddied, while curating the high cluster count to a much\n * smaller number of appropriate choices.\n */\nexport class Score {\n private static readonly CUTOFF_CHROMA = 5.0;\n private static readonly CUTOFF_EXCITED_PROPORTION = 0.01;\n private static readonly TARGET_CHROMA = 48.0; // A1 Chroma\n private static readonly WEIGHT_CHROMA_ABOVE = 0.3;\n private static readonly WEIGHT_CHROMA_BELOW = 0.1;\n private static readonly WEIGHT_PROPORTION = 0.7;\n\n private constructor() {}\n\n /**\n * Given a map with keys of colors and values of how often the color appears,\n * rank the colors based on suitability for being used for a UI theme.\n *\n * @param colorsToPopulation map with keys of colors and values of how often\n * the color appears, usually from a source image.\n * @param {ScoreOptions} options optional parameters.\n * @return Colors sorted by suitability for a UI theme. The most suitable\n * color is the first item, the least suitable is the last. There will\n * always be at least one color returned. If all the input colors\n * were not suitable for a theme, a default fallback color will be\n * provided, Google Blue.\n */\n static score(\n colorsToPopulation: Map<number, number>,\n options?: ScoreOptions,\n ): number[] {\n const { desired, fallbackColorARGB, filter } = {\n ...SCORE_OPTION_DEFAULTS,\n ...options,\n };\n // Get the HCT color for each Argb value, while finding the per hue count and\n // total count.\n const colorsHct: Hct[] = [];\n const huePopulation = new Array<number>(360).fill(0);\n let populationSum = 0;\n for (const [argb, population] of colorsToPopulation.entries()) {\n const hct = Hct.fromInt(argb);\n colorsHct.push(hct);\n const hue = Math.floor(hct.hue);\n huePopulation[hue] += population;\n populationSum += population;\n }\n\n // Hues with more usage in neighboring 30 degree slice get a larger number.\n const hueExcitedProportions = new Array<number>(360).fill(0.0);\n for (let hue = 0; hue < 360; hue++) {\n const proportion = huePopulation[hue] / populationSum;\n for (let i = hue - 14; i < hue + 16; i++) {\n const neighborHue = math.sanitizeDegreesInt(i);\n hueExcitedProportions[neighborHue] += proportion;\n }\n }\n\n // Scores each HCT color based on usage and chroma, while optionally\n // filtering out values that do not have enough chroma or usage.\n const scoredHct = new Array<{ hct: Hct; score: number }>();\n for (const hct of colorsHct) {\n const hue = math.sanitizeDegreesInt(Math.round(hct.hue));\n const proportion = hueExcitedProportions[hue];\n if (\n filter &&\n (hct.chroma < Score.CUTOFF_CHROMA ||\n proportion <= Score.CUTOFF_EXCITED_PROPORTION)\n ) {\n continue;\n }\n\n const proportionScore = proportion * 100.0 * Score.WEIGHT_PROPORTION;\n const chromaWeight =\n hct.chroma < Score.TARGET_CHROMA\n ? Score.WEIGHT_CHROMA_BELOW\n : Score.WEIGHT_CHROMA_ABOVE;\n const chromaScore = (hct.chroma - Score.TARGET_CHROMA) * chromaWeight;\n const score = proportionScore + chromaScore;\n scoredHct.push({ hct, score });\n }\n // Sorted so that colors with higher scores come first.\n scoredHct.sort(compare);\n\n // Iterates through potential hue differences in degrees in order to select\n // the colors with the largest distribution of hues possible. Starting at\n // 90 degrees(maximum difference for 4 colors) then decreasing down to a\n // 15 degree minimum.\n const chosenColors: Hct[] = [];\n for (\n let differenceDegrees = 90;\n differenceDegrees >= 15;\n differenceDegrees--\n ) {\n chosenColors.length = 0;\n for (const { hct } of scoredHct) {\n const duplicateHue = chosenColors.find((chosenHct) => {\n return (\n math.differenceDegrees(hct.hue, chosenHct.hue) < differenceDegrees\n );\n });\n if (!duplicateHue) {\n chosenColors.push(hct);\n }\n if (chosenColors.length >= desired) break;\n }\n if (chosenColors.length >= desired) break;\n }\n const colors: number[] = [];\n if (chosenColors.length === 0) {\n colors.push(fallbackColorARGB);\n }\n for (const chosenHct of chosenColors) {\n colors.push(chosenHct.toInt());\n }\n return colors;\n }\n}\n","/**\n * Image color extraction using Material Design quantization\n */\n\nimport { DislikeAnalyzer } from \"./dislike/dislike-analyzer.js\";\nimport { Hct } from \"./hct/index.js\";\nimport {\n filterExtremeTones,\n imageDataToPixels,\n samplePixels,\n} from \"./image-utils.js\";\nimport { QuantizerCelebi } from \"./quantize/quantizer_celebi.js\";\nimport { Score } from \"./score/score.js\";\nimport * as utils from \"./utils/color_utils.js\";\n\nexport interface ExtractedColor {\n hct: { c: number; h: number; t: number };\n hex: string;\n percentage: number;\n population: number;\n rgb: { b: number; g: number; r: number };\n}\n\nexport interface ExtractionOptions {\n filter?: boolean;\n fixDislikedColors?: boolean;\n maxColors?: number;\n quality?: \"high\" | \"low\" | \"medium\";\n scoringEnabled?: boolean;\n}\n\nconst QUALITY_SETTINGS = {\n high: { maxPixels: 25000, quantizeColors: 256 },\n low: { maxPixels: 5000, quantizeColors: 64 },\n medium: { maxPixels: 10000, quantizeColors: 128 },\n};\n\n/**\n * Extract dominant colors from image data\n */\nexport function extractColors(\n imageData: {\n data: number[] | Uint8ClampedArray;\n height: number;\n width: number;\n },\n options: ExtractionOptions = {},\n): ExtractedColor[] {\n const {\n filter = true,\n fixDislikedColors = false,\n maxColors = 5,\n quality = \"medium\",\n scoringEnabled = true,\n } = options;\n\n const qualitySettings = QUALITY_SETTINGS[quality];\n\n // Convert image to pixels\n let pixels = imageDataToPixels(imageData);\n\n // Sample for performance\n pixels = samplePixels(pixels, qualitySettings.maxPixels);\n\n // Optionally filter extreme tones\n if (filter) {\n pixels = filterExtremeTones(pixels);\n }\n\n // Quantize colors using Celebi algorithm\n const quantized = QuantizerCelebi.quantize(\n pixels,\n qualitySettings.quantizeColors,\n );\n\n // Score and select best colors\n let selectedColors: number[];\n if (scoringEnabled) {\n selectedColors = Score.score(quantized, {\n desired: maxColors,\n filter: filter,\n });\n } else {\n // Simple selection by population\n const sorted = Array.from(quantized.entries())\n .sort((a, b) => b[1] - a[1])\n .slice(0, maxColors)\n .map((entry) => entry[0]);\n selectedColors = sorted;\n }\n\n // Calculate total population for percentages\n const totalPopulation = Array.from(quantized.values()).reduce(\n (sum, pop) => sum + pop,\n 0,\n );\n\n // Convert to output format\n return selectedColors.map((argb) => {\n let hct = Hct.fromInt(argb);\n\n // Fix disliked colors if requested\n if (fixDislikedColors && DislikeAnalyzer.isDisliked(hct)) {\n hct = DislikeAnalyzer.fixIfDisliked(hct);\n argb = hct.toInt();\n }\n\n const r = utils.redFromArgb(argb);\n const g = utils.greenFromArgb(argb);\n const b = utils.blueFromArgb(argb);\n const population = quantized.get(argb) || 0;\n\n return {\n hct: { c: hct.chroma, h: hct.hue, t: hct.tone },\n hex: rgbToHex(r, g, b),\n percentage: (population / totalPopulation) * 100,\n population,\n rgb: { b, g, r },\n };\n });\n}\n\n/**\n * Extract a color palette suitable for UI themes\n */\nexport function extractThemePalette(imageData: {\n data: number[] | Uint8ClampedArray;\n height: number;\n width: number;\n}): {\n error?: ExtractedColor;\n neutral?: ExtractedColor;\n primary: ExtractedColor;\n secondary?: ExtractedColor;\n tertiary?: ExtractedColor;\n} {\n // Extract with high quality and scoring, fixing disliked colors\n const colors = extractColors(imageData, {\n filter: true,\n fixDislikedColors: true, // Always fix disliked colors for themes\n maxColors: 8,\n quality: \"high\",\n scoringEnabled: true,\n });\n\n if (colors.length === 0) {\n throw new Error(\"No colors could be extracted from image\");\n }\n\n const result: {\n error?: ExtractedColor;\n neutral?: ExtractedColor;\n primary: ExtractedColor;\n secondary?: ExtractedColor;\n tertiary?: ExtractedColor;\n } = {\n primary: colors[0],\n };\n\n // Assign additional colors based on hue differences\n if (colors.length > 1) {\n // Find color with most different hue from primary\n const primaryHue = colors[0].hct.h;\n let maxHueDiff = 0;\n let secondaryIndex = 1;\n\n for (let i = 1; i < Math.min(colors.length, 4); i++) {\n const hueDiff = Math.abs(hueDifference(primaryHue, colors[i].hct.h));\n if (hueDiff > maxHueDiff) {\n maxHueDiff = hueDiff;\n secondaryIndex = i;\n }\n }\n\n result.secondary = colors[secondaryIndex];\n\n // Find tertiary (different from both primary and secondary)\n if (colors.length > 2) {\n const secondaryHue = colors[secondaryIndex].hct.h;\n let bestTertiaryIndex = -1;\n let bestScore = 0;\n\n for (let i = 1; i < colors.length; i++) {\n if (i === secondaryIndex) continue;\n\n const hue = colors[i].hct.h;\n const primaryDiff = Math.abs(hueDifference(primaryHue, hue));\n const secondaryDiff = Math.abs(hueDifference(secondaryHue, hue));\n const score = Math.min(primaryDiff, secondaryDiff);\n\n if (score > bestScore) {\n bestScore = score;\n bestTertiaryIndex = i;\n }\n }\n\n if (bestTertiaryIndex !== -1) {\n result.tertiary = colors[bestTertiaryIndex];\n }\n }\n }\n\n // Find a neutral color (low chroma)\n const neutral = colors.find((c) => c.hct.c < 20);\n if (neutral) {\n result.neutral = neutral;\n }\n\n // Error color (prefer red/orange hue if available, 0-40 or 350-360)\n const errorColor = colors.find((c) => c.hct.h >= 350 || c.hct.h <= 40);\n if (errorColor) {\n result.error = errorColor;\n }\n\n return result;\n}\n\nfunction hueDifference(h1: number, h2: number): number {\n const diff = Math.abs(h1 - h2);\n return diff > 180 ? 360 - diff : diff;\n}\n\nfunction rgbToHex(r: number, g: number, b: number): string {\n return (\n \"#\" +\n [r, g, b].map((x) => Math.round(x).toString(16).padStart(2, \"0\")).join(\"\")\n );\n}\n","/**\n * Material Design Theme Generation\n * Core functionality for Material Design 3 color theme creation\n */\n\nimport { DislikeAnalyzer } from \"./dislike/dislike-analyzer.js\";\nimport { Hct } from \"./hct/hct-class.js\";\nimport {\n corePaletteFromRgb,\n parseColor,\n rgbToArgb,\n rgbToHex,\n} from \"./index.js\";\n\nexport interface MaterialColorScheme {\n background: string;\n error: string;\n errorContainer: string;\n onBackground: string;\n onError: string;\n onErrorContainer: string;\n onPrimary: string;\n onPrimaryContainer: string;\n onSecondary: string;\n onSecondaryContainer: string;\n onSurface: string;\n onSurfaceVariant: string;\n onTertiary: string;\n onTertiaryContainer: string;\n outline: string;\n primary: string;\n primaryContainer: string;\n secondary: string;\n secondaryContainer: string;\n surface: string;\n surfaceVariant: string;\n tertiary: string;\n tertiaryContainer: string;\n}\n\nexport interface MaterialTheme {\n customColors?: Record<string, unknown>;\n schemes: {\n dark: MaterialColorScheme;\n light: MaterialColorScheme;\n };\n sourceColor: string;\n}\n\nexport interface MaterialThemeOptions {\n fixDislikedColors?: boolean;\n includeCustomColors?: boolean;\n isDark?: boolean;\n}\n\n/**\n * Generate a complete Material Design 3 theme from a source color\n */\nexport function generateMaterialTheme(\n sourceColor: string,\n options: MaterialThemeOptions = {},\n): MaterialTheme {\n const { fixDislikedColors = true } = options;\n\n let source = parseColor(sourceColor);\n if (!source) {\n throw new Error(`Invalid color format: ${sourceColor}`);\n }\n\n // Fix source color if it's disliked\n if (fixDislikedColors) {\n const sourceHct = Hct.fromInt(rgbToArgb(source));\n if (DislikeAnalyzer.isDisliked(sourceHct)) {\n const fixedHct = DislikeAnalyzer.fixIfDisliked(sourceHct);\n const fixedArgb = fixedHct.toInt();\n source = {\n b: fixedArgb & 0xff,\n g: (fixedArgb >> 8) & 0xff,\n r: (fixedArgb >> 16) & 0xff,\n };\n }\n }\n\n const corePalette = corePaletteFromRgb(source);\n\n // Generate light theme colors\n const lightScheme: MaterialColorScheme = {\n background: rgbToHex(corePalette.neutral.tone(99)),\n error: rgbToHex(corePalette.error.tone(40)),\n errorContainer: rgbToHex(corePalette.error.tone(90)),\n onBackground: rgbToHex(corePalette.neutral.tone(10)),\n\n onError: rgbToHex(corePalette.error.tone(100)),\n onErrorContainer: rgbToHex(corePalette.error.tone(10)),\n onPrimary: rgbToHex(corePalette.primary.tone(100)),\n onPrimaryContainer: rgbToHex(corePalette.primary.tone(10)),\n\n onSecondary: rgbToHex(corePalette.secondary.tone(100)),\n onSecondaryContainer: rgbToHex(corePalette.secondary.tone(10)),\n onSurface: rgbToHex(corePalette.neutral.tone(10)),\n onSurfaceVariant: rgbToHex(corePalette.neutralVariant.tone(30)),\n\n onTertiary: rgbToHex(corePalette.tertiary.tone(100)),\n onTertiaryContainer: rgbToHex(corePalette.tertiary.tone(10)),\n outline: rgbToHex(corePalette.neutralVariant.tone(50)),\n primary: rgbToHex(corePalette.primary.tone(40)),\n\n primaryContainer: rgbToHex(corePalette.primary.tone(90)),\n secondary: rgbToHex(corePalette.secondary.tone(40)),\n secondaryContainer: rgbToHex(corePalette.secondary.tone(90)),\n surface: rgbToHex(corePalette.neutral.tone(99)),\n\n surfaceVariant: rgbToHex(corePalette.neutralVariant.tone(90)),\n tertiary: rgbToHex(corePalette.tertiary.tone(40)),\n tertiaryContainer: rgbToHex(corePalette.tertiary.tone(90)),\n };\n\n // Generate dark theme colors\n const darkScheme: MaterialColorScheme = {\n background: rgbToHex(corePalette.neutral.tone(10)),\n error: rgbToHex(corePalette.error.tone(80)),\n errorContainer: rgbToHex(corePalette.error.tone(30)),\n onBackground: rgbToHex(corePalette.neutral.tone(90)),\n\n onError: rgbToHex(corePalette.error.tone(20)),\n onErrorContainer: rgbToHex(corePalette.error.tone(90)),\n onPrimary: rgbToHex(corePalette.primary.tone(20)),\n onPrimaryContainer: rgbToHex(corePalette.primary.tone(90)),\n\n onSecondary: rgbToHex(corePalette.secondary.tone(20)),\n onSecondaryContainer: rgbToHex(corePalette.secondary.tone(90)),\n onSurface: rgbToHex(corePalette.neutral.tone(90)),\n onSurfaceVariant: rgbToHex(corePalette.neutralVariant.tone(80)),\n\n onTertiary: rgbToHex(corePalette.tertiary.tone(20)),\n onTertiaryContainer: rgbToHex(corePalette.tertiary.tone(90)),\n outline: rgbToHex(corePalette.neutralVariant.tone(60)),\n primary: rgbToHex(corePalette.primary.tone(80)),\n\n primaryContainer: rgbToHex(corePalette.primary.tone(30)),\n secondary: rgbToHex(corePalette.secondary.tone(80)),\n secondaryContainer: rgbToHex(corePalette.secondary.tone(30)),\n surface: rgbToHex(corePalette.neutral.tone(10)),\n\n surfaceVariant: rgbToHex(corePalette.neutralVariant.tone(30)),\n tertiary: rgbToHex(corePalette.tertiary.tone(80)),\n tertiaryContainer: rgbToHex(corePalette.tertiary.tone(30)),\n };\n\n return {\n schemes: {\n dark: darkScheme,\n light: lightScheme,\n },\n sourceColor,\n };\n}\n","/**\n * MCP tools for image color extraction\n */\n\nimport type { Tool } from \"../types.js\";\n\ntype ImageData = {\n data: number[] | Uint8ClampedArray;\n height: number;\n width: number;\n};\n\ntype McpTool = Tool<unknown>;\n\nimport {\n extractColors,\n ExtractedColor,\n extractThemePalette,\n} from \"../color/extract-colors.js\";\nimport { generateMaterialTheme } from \"../color/material-theme.js\";\n\n/**\n * Extract dominant colors from image data\n */\nexport const extractImageColorsTool: McpTool = {\n description:\n \"Extract dominant colors from an image. Input should be image data as an array of RGBA values.\",\n execute: async (args: unknown, _context: unknown) => {\n const {\n format = \"json\",\n imageData,\n maxColors = 5,\n quality = \"medium\",\n } = args as {\n format?: string;\n imageData: ImageData;\n maxColors?: number;\n quality?: \"high\" | \"low\" | \"medium\";\n };\n\n try {\n // Convert data array to Uint8ClampedArray if needed\n const data =\n imageData.data instanceof Uint8ClampedArray\n ? imageData.data\n : new Uint8ClampedArray(imageData.data);\n\n const processedImageData = {\n data,\n height: imageData.height,\n width: imageData.width,\n };\n\n // Extract colors\n const colors = extractColors(processedImageData, {\n filter: true,\n maxColors,\n quality,\n scoringEnabled: true,\n });\n\n // Format output based on requested format\n switch (format) {\n case \"css\":\n return formatAsCSS(colors);\n\n case \"palette\":\n return formatAsPalette(colors);\n\n case \"json\":\n default:\n return formatAsJSON(colors);\n }\n } catch (error) {\n return `Error extracting colors: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n inputSchema: {\n properties: {\n format: {\n description: \"Output format: json, css, or palette (default: json)\",\n enum: [\"json\", \"css\", \"palette\"],\n type: \"string\",\n },\n imageData: {\n description: \"Image data with RGBA values\",\n properties: {\n data: {\n description: \"Flat array of RGBA values (0-255)\",\n items: { type: \"number\" },\n type: \"array\",\n },\n height: {\n description: \"Image height in pixels\",\n type: \"number\",\n },\n width: {\n description: \"Image width in pixels\",\n type: \"number\",\n },\n },\n required: [\"data\", \"width\", \"height\"],\n type: \"object\",\n },\n maxColors: {\n description: \"Maximum number of colors to extract (default: 5)\",\n maximum: 20,\n minimum: 1,\n type: \"number\",\n },\n quality: {\n description:\n \"Extraction quality: low, medium, or high (default: medium)\",\n enum: [\"low\", \"medium\", \"high\"],\n type: \"string\",\n },\n },\n required: [\"imageData\"],\n type: \"object\",\n },\n name: \"extract_image_colors\",\n};\n\n/**\n * Generate a Material Design theme from an image\n */\nexport const generateThemeFromImageTool: McpTool = {\n description: \"Generate a complete Material Design 3 theme from an image\",\n execute: async (args: unknown, _context: unknown) => {\n const {\n imageData,\n includeCustomColors = true,\n isDark = false,\n } = args as {\n imageData: ImageData;\n includeCustomColors?: boolean;\n isDark?: boolean;\n };\n\n try {\n // Convert data array to Uint8ClampedArray if needed\n const data =\n imageData.data instanceof Uint8ClampedArray\n ? imageData.data\n : new Uint8ClampedArray(imageData.data);\n\n const processedImageData = {\n data,\n height: imageData.height,\n width: imageData.width,\n };\n\n // Extract theme palette\n const palette = extractThemePalette(processedImageData);\n\n // Convert primary color to hex for theme generation\n const sourceColor = palette.primary.hex;\n\n // Generate Material theme\n const theme = generateMaterialTheme(sourceColor, { isDark });\n\n // Add custom colors from extracted palette\n if (includeCustomColors && palette.secondary) {\n theme.customColors = {\n secondary: {\n color: palette.secondary.hex,\n hct: palette.secondary.hct,\n population: palette.secondary.population,\n },\n };\n\n if (palette.tertiary) {\n theme.customColors.tertiary = {\n color: palette.tertiary.hex,\n hct: palette.tertiary.hct,\n population: palette.tertiary.population,\n };\n }\n }\n\n // Format output\n let output = `# Material Design 3 Theme from Image\\n\\n`;\n output += `## Source Colors\\n`;\n output += `- Primary: ${palette.primary.hex} (${palette.primary.percentage.toFixed(1)}%)\\n`;\n\n if (palette.secondary) {\n output += `- Secondary: ${palette.secondary.hex} (${palette.secondary.percentage.toFixed(1)}%)\\n`;\n }\n if (palette.tertiary) {\n output += `- Tertiary: ${palette.tertiary.hex} (${palette.tertiary.percentage.toFixed(1)}%)\\n`;\n }\n\n output += `\\n## Theme Colors (${isDark ? \"Dark\" : \"Light\"} Mode)\\n\\n`;\n output += `### Primary\\n`;\n output += `- primary: ${theme.schemes[isDark ? \"dark\" : \"light\"].primary}\\n`;\n output += `- onPrimary: ${theme.schemes[isDark ? \"dark\" : \"light\"].onPrimary}\\n`;\n output += `- primaryContainer: ${theme.schemes[isDark ? \"dark\" : \"light\"].primaryContainer}\\n`;\n output += `- onPrimaryContainer: ${theme.schemes[isDark ? \"dark\" : \"light\"].onPrimaryContainer}\\n`;\n\n output += `\\n### Surface\\n`;\n output += `- surface: ${theme.schemes[isDark ? \"dark\" : \"light\"].surface}\\n`;\n output += `- onSurface: ${theme.schemes[isDark ? \"dark\" : \"light\"].onSurface}\\n`;\n output += `- surfaceVariant: ${theme.schemes[isDark ? \"dark\" : \"light\"].surfaceVariant}\\n`;\n output += `- onSurfaceVariant: ${theme.schemes[isDark ? \"dark\" : \"light\"].onSurfaceVariant}\\n`;\n\n output += `\\n### Background\\n`;\n output += `- background: ${theme.schemes[isDark ? \"dark\" : \"light\"].background}\\n`;\n output += `- onBackground: ${theme.schemes[isDark ? \"dark\" : \"light\"].onBackground}\\n`;\n\n return output;\n } catch (error) {\n return `Error generating theme: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n inputSchema: {\n properties: {\n imageData: {\n description: \"Image data with RGBA values\",\n properties: {\n data: {\n description: \"Flat array of RGBA values (0-255)\",\n items: { type: \"number\" },\n type: \"array\",\n },\n height: {\n description: \"Image height in pixels\",\n type: \"number\",\n },\n width: {\n description: \"Image width in pixels\",\n type: \"number\",\n },\n },\n required: [\"data\", \"width\", \"height\"],\n type: \"object\",\n },\n includeCustomColors: {\n description: \"Include custom colors from image (default: true)\",\n type: \"boolean\",\n },\n isDark: {\n description: \"Generate dark theme (default: false for light theme)\",\n type: \"boolean\",\n },\n },\n required: [\"imageData\"],\n type: \"object\",\n },\n name: \"generate_theme_from_image\",\n};\n\n// Helper functions for formatting\n\nfunction formatAsCSS(colors: ExtractedColor[]): string {\n let css = \":root {\\n\";\n colors.forEach((color, index) => {\n css += ` --extracted-color-${index + 1}: ${color.hex}; /* ${color.percentage.toFixed(1)}% */\\n`;\n });\n css += \"}\\n\\n\";\n\n css += \"/* Color Details */\\n\";\n colors.forEach((color, index) => {\n css += `/* Color ${index + 1}: ${color.hex}\\n`;\n css += ` RGB: rgb(${color.rgb.r}, ${color.rgb.g}, ${color.rgb.b})\\n`;\n css += ` HCT: hct(${color.hct.h.toFixed(1)}, ${color.hct.c.toFixed(1)}, ${color.hct.t.toFixed(1)})\\n`;\n css += ` Population: ${color.percentage.toFixed(1)}%\\n`;\n css += `*/\\n\\n`;\n });\n\n return css;\n}\n\nfunction formatAsJSON(colors: ExtractedColor[]): string {\n return JSON.stringify(colors, null, 2);\n}\n\nfunction formatAsPalette(colors: ExtractedColor[]): string {\n let output = \"# Extracted Color Palette\\n\\n\";\n\n colors.forEach((color, index) => {\n output += `## Color ${index + 1}\\n`;\n output += `- Hex: ${color.hex}\\n`;\n output += `- RGB: rgb(${color.rgb.r}, ${color.rgb.g}, ${color.rgb.b})\\n`;\n output += `- HCT: H:${color.hct.h.toFixed(1)}° C:${color.hct.c.toFixed(1)} T:${color.hct.t.toFixed(1)}\\n`;\n output += `- Usage: ${color.percentage.toFixed(1)}%\\n\\n`;\n });\n\n return output;\n}\n","/**\n * Material Design Theme Tools\n * Tools for Material Design 3 color theme generation and management\n */\n\nimport { z } from \"zod\";\n\nimport {\n adjustTemperature,\n blend,\n corePaletteFromRgb,\n harmonize,\n parseColor,\n type RGB,\n rgbToHct,\n rgbToHex,\n TonalPalette,\n} from \"../color/index.js\";\n\n/**\n * Generate Material Design 3 Theme\n */\nexport const generateMaterialThemeTool = {\n description:\n \"Generate a complete Material Design 3 color theme from a source color\",\n execute: async (args: {\n includeCustomColors?: boolean;\n sourceColor: string;\n }) => {\n const source = parseColor(args.sourceColor);\n if (!source) {\n return `Invalid color format: ${args.sourceColor}`;\n }\n\n const corePalette = corePaletteFromRgb(source);\n\n // Generate key colors for light theme\n const lightTheme = {\n background: rgbToHex(corePalette.neutral.tone(99)),\n error: rgbToHex(corePalette.error.tone(40)),\n errorContainer: rgbToHex(corePalette.error.tone(90)),\n onBackground: rgbToHex(corePalette.neutral.tone(10)),\n\n onError: rgbToHex(corePalette.error.tone(100)),\n onErrorContainer: rgbToHex(corePalette.error.tone(10)),\n onPrimary: rgbToHex(corePalette.primary.tone(100)),\n onPrimaryContainer: rgbToHex(corePalette.primary.tone(10)),\n\n onSecondary: rgbToHex(corePalette.secondary.tone(100)),\n onSecondaryContainer: rgbToHex(corePalette.secondary.tone(10)),\n onSurface: rgbToHex(corePalette.neutral.tone(10)),\n onSurfaceVariant: rgbToHex(corePalette.neutralVariant.tone(30)),\n\n onTertiary: rgbToHex(corePalette.tertiary.tone(100)),\n onTertiaryContainer: rgbToHex(corePalette.tertiary.tone(10)),\n outline: rgbToHex(corePalette.neutralVariant.tone(50)),\n primary: rgbToHex(corePalette.primary.tone(40)),\n\n primaryContainer: rgbToHex(corePalette.primary.tone(90)),\n secondary: rgbToHex(corePalette.secondary.tone(40)),\n secondaryContainer: rgbToHex(corePalette.secondary.tone(90)),\n surface: rgbToHex(corePalette.neutral.tone(99)),\n\n surfaceVariant: rgbToHex(corePalette.neutralVariant.tone(90)),\n tertiary: rgbToHex(corePalette.tertiary.tone(40)),\n tertiaryContainer: rgbToHex(corePalette.tertiary.tone(90)),\n };\n\n // Generate key colors for dark theme\n const darkTheme = {\n background: rgbToHex(corePalette.neutral.tone(10)),\n error: rgbToHex(corePalette.error.tone(80)),\n errorContainer: rgbToHex(corePalette.error.tone(30)),\n onBackground: rgbToHex(corePalette.neutral.tone(90)),\n\n onError: rgbToHex(corePalette.error.tone(20)),\n onErrorContainer: rgbToHex(corePalette.error.tone(90)),\n onPrimary: rgbToHex(corePalette.primary.tone(20)),\n onPrimaryContainer: rgbToHex(corePalette.primary.tone(90)),\n\n onSecondary: rgbToHex(corePalette.secondary.tone(20)),\n onSecondaryContainer: rgbToHex(corePalette.secondary.tone(90)),\n onSurface: rgbToHex(corePalette.neutral.tone(90)),\n onSurfaceVariant: rgbToHex(corePalette.neutralVariant.tone(80)),\n\n onTertiary: rgbToHex(corePalette.tertiary.tone(20)),\n onTertiaryContainer: rgbToHex(corePalette.tertiary.tone(90)),\n outline: rgbToHex(corePalette.neutralVariant.tone(60)),\n primary: rgbToHex(corePalette.primary.tone(80)),\n\n primaryContainer: rgbToHex(corePalette.primary.tone(30)),\n secondary: rgbToHex(corePalette.secondary.tone(80)),\n secondaryContainer: rgbToHex(corePalette.secondary.tone(30)),\n surface: rgbToHex(corePalette.neutral.tone(10)),\n\n surfaceVariant: rgbToHex(corePalette.neutralVariant.tone(30)),\n tertiary: rgbToHex(corePalette.tertiary.tone(80)),\n tertiaryContainer: rgbToHex(corePalette.tertiary.tone(30)),\n };\n\n let result = `Material Design 3 Theme\nSource Color: ${args.sourceColor}\n\nLIGHT THEME:\n${Object.entries(lightTheme)\n .map(([key, value]) => ` ${key}: ${value}`)\n .join(\"\\n\")}\n\nDARK THEME:\n${Object.entries(darkTheme)\n .map(([key, value]) => ` ${key}: ${value}`)\n .join(\"\\n\")}`;\n\n if (args.includeCustomColors) {\n result += `\\n\\nTONAL PALETTES:\nPrimary: ${[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 99, 100]\n .map((t) => rgbToHex(corePalette.primary.tone(t)))\n .join(\", \")}\nSecondary: ${[40, 80].map((t) => rgbToHex(corePalette.secondary.tone(t))).join(\", \")}\nTertiary: ${[40, 80].map((t) => rgbToHex(corePalette.tertiary.tone(t))).join(\", \")}`;\n }\n\n return result;\n },\n name: \"generate_material_theme\",\n parameters: z.object({\n includeCustomColors: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Include custom color palettes\"),\n sourceColor: z.string().describe(\"Source color for theme generation\"),\n }),\n};\n\n/**\n * Harmonize Colors Tool\n */\nexport const harmonizeColorsTool = {\n description:\n \"Harmonize colors to work better together using Material Design algorithms\",\n execute: async (args: {\n colors: string[];\n factor?: number;\n method?: \"blend\" | \"harmonize\" | \"temperature\";\n }) => {\n const colors = args.colors.map((c) => parseColor(c));\n if (colors.some((c) => c === null)) {\n return \"One or more invalid color formats\";\n }\n\n const validColors = colors as RGB[];\n const method = args.method || \"harmonize\";\n const factor = args.factor || 0.5;\n const results: string[] = [];\n\n switch (method) {\n case \"blend\": {\n // Blend all colors together\n let result = validColors[0];\n for (let i = 1; i < validColors.length; i++) {\n result = blend(result, validColors[i], factor);\n }\n results.push(rgbToHex(result));\n break;\n }\n\n case \"harmonize\": {\n // Harmonize all colors with the first one\n const source = validColors[0];\n results.push(rgbToHex(source)); // Keep source unchanged\n\n for (let i = 1; i < validColors.length; i++) {\n results.push(rgbToHex(harmonize(validColors[i], source, factor)));\n }\n break;\n }\n\n case \"temperature\": {\n // Adjust temperature of all colors\n const amount = (factor - 0.5) * 2; // Convert to -1 to 1\n for (const color of validColors) {\n results.push(rgbToHex(adjustTemperature(color, amount)));\n }\n break;\n }\n }\n\n return `Harmonized Colors (${method}):\nOriginal: ${args.colors.join(\", \")}\nResult: ${results.join(\", \")}`;\n },\n name: \"harmonize_colors\",\n parameters: z.object({\n colors: z\n .array(z.string())\n .min(2)\n .max(10)\n .describe(\"Array of colors to harmonize\"),\n factor: z\n .number()\n .min(0)\n .max(1)\n .optional()\n .default(0.5)\n .describe(\"Harmonization strength (0-1)\"),\n method: z\n .enum([\"blend\", \"harmonize\", \"temperature\"])\n .optional()\n .default(\"harmonize\")\n .describe(\"Harmonization method\"),\n }),\n};\n\n/**\n * Generate Tonal Palette Tool\n */\nexport const generateTonalPaletteTool = {\n description: \"Generate a Material Design tonal palette from a color\",\n execute: async (args: { color: string; tones?: number[] }) => {\n const rgb = parseColor(args.color);\n if (!rgb) {\n return `Invalid color format: ${args.color}`;\n }\n\n const palette = TonalPalette.fromRgb(rgb);\n const tones = args.tones || [\n 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 99, 100,\n ];\n\n const hct = rgbToHct(rgb);\n const colors = tones.map((tone) => ({\n hex: rgbToHex(palette.tone(tone)),\n tone,\n }));\n\n return `Tonal Palette for ${args.color}\nHCT: h=${hct.h.toFixed(1)}°, c=${hct.c.toFixed(1)}, t=${hct.t.toFixed(1)}\n\n${colors.map(({ hex, tone }) => `Tone ${tone}: ${hex}`).join(\"\\n\")}`;\n },\n name: \"generate_tonal_palette\",\n parameters: z.object({\n color: z.string().describe(\"Base color for palette\"),\n tones: z\n .array(z.number())\n .optional()\n .describe(\"Custom tone values (default: Material standard tones)\"),\n }),\n};\n","/**\n * Palette Generator Tool\n * Generate color palettes from a base color\n */\n\nimport { z } from \"zod\";\n\nimport { parseColor, rgbToHex, rgbToHsl } from \"../color/index.js\";\n\nexport const paletteGeneratorTool = {\n description: \"Generate a color palette from a base color\",\n execute: async (args: {\n baseColor: string;\n count?: number;\n type?:\n | \"analogous\"\n | \"complementary\"\n | \"monochromatic\"\n | \"tetradic\"\n | \"triadic\";\n }) => {\n const base = parseColor(args.baseColor);\n if (!base) {\n return `Invalid color format: ${args.baseColor}`;\n }\n\n const type = args.type || \"monochromatic\";\n const count = args.count || 5;\n const hsl = rgbToHsl(base);\n const palette: string[] = [];\n\n switch (type) {\n case \"analogous\": {\n // Colors adjacent on the color wheel\n const step = 30;\n for (let i = 0; i < count; i++) {\n const h = (hsl.h + (i - Math.floor(count / 2)) * step + 360) % 360;\n const color = parseColor(`hsl(${h}, ${hsl.s}%, ${hsl.l}%)`);\n if (color) palette.push(rgbToHex(color));\n }\n break;\n }\n case \"complementary\": {\n // Base color and its complement\n palette.push(rgbToHex(base));\n const complement = parseColor(\n `hsl(${(hsl.h + 180) % 360}, ${hsl.s}%, ${hsl.l}%)`,\n );\n if (complement) palette.push(rgbToHex(complement));\n\n // Add variations\n for (let i = 2; i < count; i++) {\n const l = hsl.l + (i % 2 === 0 ? 20 : -20);\n const h = i < count / 2 ? hsl.h : (hsl.h + 180) % 360;\n const color = parseColor(\n `hsl(${h}, ${hsl.s}%, ${Math.max(10, Math.min(90, l))}%)`,\n );\n if (color) palette.push(rgbToHex(color));\n }\n break;\n }\n case \"monochromatic\": {\n // Generate different lightness values\n const step = 80 / (count - 1);\n for (let i = 0; i < count; i++) {\n const l = 10 + i * step;\n const color = parseColor(`hsl(${hsl.h}, ${hsl.s}%, ${l}%)`);\n if (color) palette.push(rgbToHex(color));\n }\n break;\n }\n case \"tetradic\": {\n // Four colors in rectangle on color wheel\n for (let i = 0; i < Math.min(4, count); i++) {\n const h = (hsl.h + i * 90) % 360;\n const color = parseColor(`hsl(${h}, ${hsl.s}%, ${hsl.l}%)`);\n if (color) palette.push(rgbToHex(color));\n }\n // Add variations for remaining colors\n for (let i = 4; i < count; i++) {\n const baseIdx = i % 4;\n const h = (hsl.h + baseIdx * 90) % 360;\n const l = hsl.l + (i < 8 ? 15 : -15);\n const color = parseColor(\n `hsl(${h}, ${hsl.s}%, ${Math.max(10, Math.min(90, l))}%)`,\n );\n if (color) palette.push(rgbToHex(color));\n }\n break;\n }\n case \"triadic\": {\n // Three colors evenly spaced on color wheel\n for (let i = 0; i < Math.min(3, count); i++) {\n const h = (hsl.h + i * 120) % 360;\n const color = parseColor(`hsl(${h}, ${hsl.s}%, ${hsl.l}%)`);\n if (color) palette.push(rgbToHex(color));\n }\n // Add variations for remaining colors\n for (let i = 3; i < count; i++) {\n const baseIdx = i % 3;\n const h = (hsl.h + baseIdx * 120) % 360;\n const l = hsl.l + (i < 6 ? 20 : -20);\n const color = parseColor(\n `hsl(${h}, ${hsl.s}%, ${Math.max(10, Math.min(90, l))}%)`,\n );\n if (color) palette.push(rgbToHex(color));\n }\n break;\n }\n }\n\n return `Generated ${type} palette:\n${palette.map((color, i) => `${i + 1}. ${color}`).join(\"\\n\")}`;\n },\n name: \"generate_palette\",\n parameters: z.object({\n baseColor: z.string().describe(\"Base color for palette generation\"),\n count: z\n .number()\n .min(3)\n .max(10)\n .default(5)\n .describe(\"Number of colors to generate\"),\n type: z\n .enum([\n \"monochromatic\",\n \"analogous\",\n \"complementary\",\n \"triadic\",\n \"tetradic\",\n ])\n .default(\"monochromatic\")\n .describe(\"Type of color palette\"),\n }),\n};\n","import { z } from \"zod\";\n\nimport {\n colorDistance,\n hslToRgb,\n labToRgb,\n parseColor,\n rgbToHex,\n rgbToHsl,\n rgbToLab,\n} from \"../color/index.js\";\nimport { HSL, RGB } from \"../color/types.js\";\n\nexport const paletteWithLocksTool = {\n description:\n \"Generate a color palette while preserving specific locked colors\",\n execute: async (args: {\n colorSpace?: \"hsl\" | \"lab\";\n lockedColors: string[];\n mode?: \"contrast\" | \"gradient\" | \"harmony\";\n totalColors: number;\n }) => {\n const {\n colorSpace = \"hsl\",\n lockedColors,\n mode = \"harmony\",\n totalColors,\n } = args;\n\n if (lockedColors.length >= totalColors) {\n return `Error: Number of locked colors (${lockedColors.length}) must be less than total colors (${totalColors})`;\n }\n\n // Parse and validate locked colors\n const parsedLocked: RGB[] = [];\n for (const color of lockedColors) {\n const parsed = parseColor(color);\n if (!parsed) {\n return `Invalid color format: ${color}`;\n }\n parsedLocked.push(parsed);\n }\n\n const palette: string[] = [];\n const remainingSlots = totalColors - lockedColors.length;\n\n // Add locked colors to palette\n lockedColors.forEach((color) => palette.push(color));\n\n switch (mode) {\n case \"contrast\": {\n // Generate contrasting colors\n for (let i = 0; i < remainingSlots; i++) {\n let bestColor: null | RGB = null;\n let maxMinDistance = 0;\n\n // Try random colors and pick the one with maximum minimum distance\n for (let attempt = 0; attempt < 100; attempt++) {\n const candidate: RGB = {\n b: Math.floor(Math.random() * 256),\n g: Math.floor(Math.random() * 256),\n r: Math.floor(Math.random() * 256),\n };\n\n let minDistance = Infinity;\n for (const locked of parsedLocked) {\n const dist = colorDistance(candidate, locked, \"deltaE2000\");\n if (dist < minDistance) minDistance = dist;\n }\n\n if (minDistance > maxMinDistance) {\n maxMinDistance = minDistance;\n bestColor = candidate;\n }\n }\n\n if (bestColor) {\n palette.push(rgbToHex(bestColor));\n parsedLocked.push(bestColor);\n }\n }\n break;\n }\n\n case \"gradient\": {\n // Create gradient between locked colors\n if (parsedLocked.length < 2) {\n return \"Gradient mode requires at least 2 locked colors\";\n }\n\n const steps = Math.floor(remainingSlots / (parsedLocked.length - 1));\n\n for (let i = 0; i < parsedLocked.length - 1; i++) {\n const start = parsedLocked[i];\n const end = parsedLocked[i + 1];\n\n for (let step = 1; step <= steps; step++) {\n const t = step / (steps + 1);\n\n if (colorSpace === \"lab\") {\n // Interpolate in LAB space\n const startLab = rgbToLab(start);\n const endLab = rgbToLab(end);\n\n const interpolated = labToRgb({\n a: startLab.a + (endLab.a - startLab.a) * t,\n b: startLab.b + (endLab.b - startLab.b) * t,\n l: startLab.l + (endLab.l - startLab.l) * t,\n });\n\n palette.push(rgbToHex(interpolated));\n } else {\n // Interpolate in HSL space\n const startHsl = rgbToHsl(start);\n const endHsl = rgbToHsl(end);\n\n // Handle hue interpolation (shortest path)\n let hueDiff = endHsl.h - startHsl.h;\n if (hueDiff > 180) hueDiff -= 360;\n if (hueDiff < -180) hueDiff += 360;\n\n const interpolated = hslToRgb({\n h: (startHsl.h + hueDiff * t + 360) % 360,\n l: startHsl.l + (endHsl.l - startHsl.l) * t,\n s: startHsl.s + (endHsl.s - startHsl.s) * t,\n });\n\n palette.push(rgbToHex(interpolated));\n }\n }\n }\n break;\n }\n\n case \"harmony\": {\n // Generate harmonious colors based on locked colors\n const baseHsl = rgbToHsl(parsedLocked[0]);\n const hueStep = 360 / totalColors;\n\n for (let i = 0; i < remainingSlots; i++) {\n let newHue = baseHsl.h;\n let attempts = 0;\n let bestColor: null | RGB = null;\n let maxMinDistance = 0;\n\n // Try different hues to find one that's not too close to locked colors\n while (attempts < 36) {\n newHue = (baseHsl.h + attempts * 10) % 360;\n const candidate = hslToRgb({\n h: newHue,\n l: baseHsl.l + (Math.random() - 0.5) * 20,\n s: baseHsl.s + (Math.random() - 0.5) * 20,\n });\n\n // Check minimum distance to all locked colors\n let minDistance = Infinity;\n for (const locked of parsedLocked) {\n const dist = colorDistance(candidate, locked, \"deltaE2000\");\n if (dist < minDistance) minDistance = dist;\n }\n\n // Keep the candidate with the largest minimum distance\n if (minDistance > maxMinDistance && minDistance > 10) {\n maxMinDistance = minDistance;\n bestColor = candidate;\n }\n\n attempts++;\n }\n\n if (bestColor) {\n palette.push(rgbToHex(bestColor));\n parsedLocked.push(bestColor); // Add to locked for next iteration\n }\n }\n break;\n }\n }\n\n // Sort palette to have locked colors marked\n const result: string[] = [];\n const lockedSet = new Set(lockedColors.map((c) => c.toLowerCase()));\n\n palette.forEach((color) => {\n if (lockedSet.has(color.toLowerCase())) {\n result.push(`${color} (locked)`);\n } else {\n result.push(color);\n }\n });\n\n return `Generated palette with ${lockedColors.length} locked colors:\n${result.map((color, i) => `${i + 1}. ${color}`).join(\"\\n\")}\n\nMode: ${mode}\nColor space: ${colorSpace}\nTotal colors: ${totalColors}`;\n },\n name: \"generate_palette_with_locks\",\n parameters: z.object({\n colorSpace: z\n .enum([\"hsl\", \"lab\"])\n .default(\"hsl\")\n .describe(\"Color space for interpolation (affects gradient smoothness)\"),\n lockedColors: z\n .array(z.string())\n .min(1)\n .describe(\"Colors that must be included in the palette\"),\n mode: z\n .enum([\"harmony\", \"contrast\", \"gradient\"])\n .default(\"harmony\")\n .describe(\n \"Generation mode: harmony (similar), contrast (different), or gradient (smooth transition)\",\n ),\n totalColors: z\n .number()\n .min(2)\n .max(20)\n .describe(\"Total number of colors in the final palette\"),\n }),\n};\n","/**\n * Theme Matching Tools\n * Tools for matching colors to theme variables and refactoring CSS\n */\n\nimport { z } from \"zod\";\n\nimport { corePaletteFromRgb, parseColor, rgbToHex } from \"../color/index.js\";\nimport {\n type ColorContext,\n findBatchMatches,\n findClosestThemeColor,\n generateRefactoringReport,\n parseThemeVariables,\n refactorCss,\n} from \"../theme/index.js\";\n\n/**\n * Match Theme Color Tool\n */\nexport const matchThemeColorTool = {\n description: \"Find the closest matching theme variable for a given color\",\n execute: async (args: {\n color: string;\n context?: ColorContext;\n minConfidence?: number;\n themeCSS: string;\n }) => {\n // Parse theme variables from CSS\n const themeVariables = parseThemeVariables(args.themeCSS);\n\n // Find closest match\n const match = findClosestThemeColor(args.color, themeVariables, {\n contextType: args.context,\n });\n\n if (!match) {\n return \"No matching theme variable found\";\n }\n\n const minConfidence = args.minConfidence ?? 70;\n if (match.confidence < minConfidence) {\n return `Best match below confidence threshold:\nVariable: ${match.variable}\nDistance: ${match.distance.toFixed(2)}\nConfidence: ${match.confidence}%\n\nConsider adding a new theme variable for this color.`;\n }\n\n let result = `Best Match:\nVariable: ${match.variable}\nValue: ${match.value}\nDistance: ${match.distance.toFixed(2)}\nConfidence: ${match.confidence}%`;\n\n if (match.semanticRole) {\n result += `\\nSemantic Role: ${match.semanticRole}`;\n }\n\n if (match.accessibilityInfo) {\n result += `\\n\\nAccessibility:\nContrast with background: ${match.accessibilityInfo.contrastWithBackground.toFixed(2)}\nContrast with foreground: ${match.accessibilityInfo.contrastWithForeground.toFixed(2)}\nMeets AA: ${match.accessibilityInfo.meetsAA ? \"Yes\" : \"No\"}\nMeets AAA: ${match.accessibilityInfo.meetsAAA ? \"Yes\" : \"No\"}`;\n }\n\n if (match.alternatives.length > 0) {\n result += `\\n\\nAlternatives:`;\n for (const alt of match.alternatives) {\n result += `\\n- ${alt.variable} (confidence: ${alt.confidence}%)`;\n }\n }\n\n return result;\n },\n name: \"match_theme_color\",\n parameters: z.object({\n color: z.string().describe(\"Color to match (hex, rgb, hsl)\"),\n context: z\n .enum([\"text\", \"background\", \"border\", \"shadow\", \"accent\", \"decorative\"])\n .optional()\n .describe(\"Usage context for better matching\"),\n minConfidence: z\n .number()\n .min(0)\n .max(100)\n .optional()\n .default(70)\n .describe(\"Minimum confidence threshold (0-100)\"),\n themeCSS: z.string().describe(\"CSS containing theme variables\"),\n }),\n};\n\n/**\n * Refactor CSS with Theme Tool\n */\nexport const refactorCssWithThemeTool = {\n description:\n \"Refactor CSS to use theme variables instead of hardcoded colors\",\n execute: async (args: {\n css: string;\n generateReport?: boolean;\n minConfidence?: number;\n preserveOriginal?: boolean;\n themeCSS: string;\n }) => {\n // Parse theme variables\n const themeVariables = parseThemeVariables(args.themeCSS);\n\n // Refactor CSS\n const result = refactorCss(args.css, themeVariables, {\n addComments: args.preserveOriginal ?? true,\n minConfidence: args.minConfidence ?? 70,\n preserveOriginal: args.preserveOriginal ?? true,\n });\n\n let output = `Refactoring Complete!\n\nStatistics:\n- Total colors found: ${result.statistics.totalColors}\n- Colors replaced: ${result.statistics.replacedColors}\n- Average confidence: ${result.statistics.averageConfidence}%\n- Accessibility issues: ${result.statistics.accessibilityIssues}\n\nRefactored CSS:\n----------------------------------------\n${result.refactored}\n----------------------------------------`;\n\n if (result.warnings.length > 0) {\n output += `\\n\\nWarnings (${result.warnings.length}):`;\n for (const warning of result.warnings.slice(0, 5)) {\n output += `\\n- ${warning.message}`;\n if (warning.suggestion) {\n output += `\\n Suggestion: ${warning.suggestion}`;\n }\n }\n if (result.warnings.length > 5) {\n output += `\\n... and ${result.warnings.length - 5} more warnings`;\n }\n }\n\n if (args.generateReport) {\n output += `\\n\\n${generateRefactoringReport(result)}`;\n }\n\n return output;\n },\n name: \"refactor_css_with_theme\",\n parameters: z.object({\n css: z.string().describe(\"CSS content to refactor\"),\n generateReport: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Generate detailed refactoring report\"),\n minConfidence: z\n .number()\n .min(0)\n .max(100)\n .optional()\n .default(70)\n .describe(\"Minimum confidence for replacements\"),\n preserveOriginal: z\n .boolean()\n .optional()\n .default(true)\n .describe(\"Keep original values as comments\"),\n themeCSS: z.string().describe(\"CSS containing theme variables\"),\n }),\n};\n\n/**\n * Match Theme Colors Batch Tool\n */\nexport const matchThemeColorsBatchTool = {\n description: \"Find theme matches for multiple colors at once\",\n execute: async (args: {\n colors: string[];\n context?: ColorContext;\n themeCSS: string;\n }) => {\n // Parse theme variables\n const themeVariables = parseThemeVariables(args.themeCSS);\n\n // Find matches for all colors\n const matches = findBatchMatches(args.colors, themeVariables, {\n contextType: args.context,\n });\n\n let result = `Theme Color Matches:\\n`;\n let matchCount = 0;\n let totalConfidence = 0;\n\n for (const [color, match] of matches.entries()) {\n if (match) {\n matchCount++;\n totalConfidence += match.confidence;\n result += `\\n${color} → ${match.variable} (${match.confidence}%)`;\n } else {\n result += `\\n${color} → No match found`;\n }\n }\n\n result += `\\n\\nSummary:\n- Matched: ${matchCount}/${args.colors.length}\n- Average confidence: ${matchCount > 0 ? Math.round(totalConfidence / matchCount) : 0}%`;\n\n return result;\n },\n name: \"match_theme_colors_batch\",\n parameters: z.object({\n colors: z\n .array(z.string())\n .min(1)\n .max(50)\n .describe(\"Array of colors to match\"),\n context: z\n .enum([\"text\", \"background\", \"border\", \"shadow\", \"accent\", \"decorative\"])\n .optional()\n .describe(\"Usage context for all colors\"),\n themeCSS: z.string().describe(\"CSS containing theme variables\"),\n }),\n};\n\n/**\n * Generate Theme CSS Tool\n */\nexport const generateThemeCssTool = {\n description:\n \"Generate CSS custom properties for a complete theme from a source color\",\n execute: async (args: {\n includeTones?: number[];\n prefix?: string;\n sourceColor: string;\n }) => {\n const source = parseColor(args.sourceColor);\n if (!source) {\n return `Invalid color format: ${args.sourceColor}`;\n }\n\n const corePalette = corePaletteFromRgb(source);\n const tones = args.includeTones || [\n 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 99, 100,\n ];\n const prefix = args.prefix || \"color\";\n\n let css = `:root {\\n`;\n\n // Generate primary palette\n css += ` /* Primary Colors */\\n`;\n for (const tone of tones) {\n const color = rgbToHex(corePalette.primary.tone(tone));\n css += ` --${prefix}-primary-${tone}: ${color};\\n`;\n }\n\n // Generate secondary palette\n css += `\\n /* Secondary Colors */\\n`;\n for (const tone of tones) {\n const color = rgbToHex(corePalette.secondary.tone(tone));\n css += ` --${prefix}-secondary-${tone}: ${color};\\n`;\n }\n\n // Generate tertiary palette\n css += `\\n /* Tertiary Colors */\\n`;\n for (const tone of tones) {\n const color = rgbToHex(corePalette.tertiary.tone(tone));\n css += ` --${prefix}-tertiary-${tone}: ${color};\\n`;\n }\n\n // Generate error palette\n css += `\\n /* Error Colors */\\n`;\n for (const tone of tones) {\n const color = rgbToHex(corePalette.error.tone(tone));\n css += ` --${prefix}-error-${tone}: ${color};\\n`;\n }\n\n // Generate neutral palette\n css += `\\n /* Neutral Colors */\\n`;\n for (const tone of tones) {\n const color = rgbToHex(corePalette.neutral.tone(tone));\n css += ` --${prefix}-neutral-${tone}: ${color};\\n`;\n }\n\n // Generate neutral variant palette\n css += `\\n /* Neutral Variant Colors */\\n`;\n for (const tone of tones) {\n const color = rgbToHex(corePalette.neutralVariant.tone(tone));\n css += ` --${prefix}-neutral-variant-${tone}: ${color};\\n`;\n }\n\n css += `}\\n\\n`;\n\n // Add semantic mappings\n css += `/* Semantic Color Mappings (Light Theme) */\\n`;\n css += `:root {\\n`;\n css += ` --${prefix}-primary: var(--${prefix}-primary-40);\\n`;\n css += ` --${prefix}-on-primary: var(--${prefix}-primary-100);\\n`;\n css += ` --${prefix}-primary-container: var(--${prefix}-primary-90);\\n`;\n css += ` --${prefix}-on-primary-container: var(--${prefix}-primary-10);\\n`;\n css += ` \\n`;\n css += ` --${prefix}-secondary: var(--${prefix}-secondary-40);\\n`;\n css += ` --${prefix}-on-secondary: var(--${prefix}-secondary-100);\\n`;\n css += ` --${prefix}-secondary-container: var(--${prefix}-secondary-90);\\n`;\n css += ` --${prefix}-on-secondary-container: var(--${prefix}-secondary-10);\\n`;\n css += ` \\n`;\n css += ` --${prefix}-background: var(--${prefix}-neutral-99);\\n`;\n css += ` --${prefix}-on-background: var(--${prefix}-neutral-10);\\n`;\n css += ` --${prefix}-surface: var(--${prefix}-neutral-99);\\n`;\n css += ` --${prefix}-on-surface: var(--${prefix}-neutral-10);\\n`;\n css += `}\\n`;\n\n return css;\n },\n name: \"generate_theme_css\",\n parameters: z.object({\n includeTones: z\n .array(z.number())\n .optional()\n .describe(\n \"Tone values to include (default: 0,10,20,30,40,50,60,70,80,90,95,99,100)\",\n ),\n prefix: z\n .string()\n .optional()\n .default(\"color\")\n .describe(\n \"Prefix for CSS variables (e.g., 'color' → --color-primary-50)\",\n ),\n sourceColor: z.string().describe(\"Source color for theme generation\"),\n }),\n};\n","/**\n * Theme Color Matcher\n * Finds closest theme colors using HCT perceptual distance\n */\n\nimport type { HCT } from \"../color/hct/types.js\";\nimport type {\n ColorContext,\n MatchingOptions,\n SemanticRole,\n ThemeMatch,\n ThemeVariable,\n ThemeVariables,\n} from \"./types.js\";\n\nimport { hexToRgb } from \"../color/conversions.js\";\nimport { rgbToHct } from \"../color/hct/hct-solver.js\";\nimport { getContrastRatio } from \"../color/utils.js\";\n\n/**\n * Default matching weights\n */\nconst DEFAULT_WEIGHTS = {\n accessibility: 0.2,\n perceptual: 0.6,\n semantic: 0.2,\n};\n\n/**\n * Maximum acceptable distances for different contexts\n */\nconst CONTEXT_MAX_DISTANCES: Record<ColorContext, number> = {\n accent: 15, // Moderate for brand consistency\n background: 15, // Moderate flexibility\n border: 20, // More flexibility\n decorative: 30, // Most flexible\n shadow: 25, // Even more flexibility\n text: 10, // Strict for readability\n};\n\n/**\n * Find matches for multiple colors\n */\nexport function findBatchMatches(\n colors: string[],\n themeVariables: ThemeVariables,\n options: MatchingOptions = {},\n): Map<string, null | ThemeMatch> {\n const results = new Map<string, null | ThemeMatch>();\n\n for (const color of colors) {\n results.set(color, findClosestThemeColor(color, themeVariables, options));\n }\n\n return results;\n}\n\n/**\n * Find the closest theme color for a given input color\n */\nexport function findClosestThemeColor(\n inputColor: string,\n themeVariables: ThemeVariables,\n options: MatchingOptions = {},\n): null | ThemeMatch {\n // Parse input color to HCT\n let inputHct: HCT;\n try {\n const rgb = parseColorToRgb(inputColor);\n inputHct = rgbToHct(rgb);\n } catch {\n console.error(`Failed to parse input color: ${inputColor}`);\n return null;\n }\n\n // Flatten theme variables\n const allVariables = flattenThemeVariables(themeVariables);\n if (allVariables.length === 0) {\n return null;\n }\n\n // Calculate distances and scores\n const candidates = allVariables.map((variable) => ({\n distance: calculateHctDistance(inputHct, variable.hct),\n score: 0, // Will be calculated next\n variable,\n }));\n\n // Apply context-based filtering\n const maxDistance =\n options.maxDistance ??\n (options.contextType ? CONTEXT_MAX_DISTANCES[options.contextType] : 30);\n\n const validCandidates = candidates.filter((c) => c.distance <= maxDistance);\n if (validCandidates.length === 0) {\n return null;\n }\n\n // Calculate multi-factor scores\n const weights = options.weights ?? DEFAULT_WEIGHTS;\n for (const candidate of validCandidates) {\n candidate.score = calculateMatchScore(\n inputHct,\n candidate.variable,\n candidate.distance,\n weights,\n options,\n );\n }\n\n // Sort by score (higher is better)\n validCandidates.sort((a, b) => b.score - a.score);\n\n // Get the best match and alternatives\n const best = validCandidates[0];\n const alternatives = validCandidates.slice(1, 4).map((c) => ({\n alternatives: [],\n confidence: calculateConfidence(c.distance, c.score),\n distance: c.distance,\n semanticRole: c.variable.role,\n value: c.variable.value,\n variable: c.variable.name,\n }));\n\n // Calculate accessibility info if needed\n const accessibilityInfo =\n options.contextType === \"text\" || options.contextType === \"background\"\n ? calculateAccessibilityInfo(best.variable.value, themeVariables)\n : undefined;\n\n return {\n accessibilityInfo,\n alternatives,\n confidence: calculateConfidence(best.distance, best.score),\n distance: best.distance,\n semanticRole: best.variable.role,\n value: best.variable.value,\n variable: best.variable.name,\n };\n}\n\n/**\n * Calculate accessibility information\n */\nfunction calculateAccessibilityInfo(\n color: string,\n themeVariables: ThemeVariables,\n): ThemeMatch[\"accessibilityInfo\"] {\n const rgb = parseColorToRgb(color);\n\n // Find typical background and foreground colors\n const backgrounds = findTypicalBackgrounds(themeVariables);\n const foregrounds = findTypicalForegrounds(themeVariables);\n\n let maxContrastBg = 0;\n let maxContrastFg = 0;\n\n for (const bg of backgrounds) {\n const bgRgb = parseColorToRgb(bg.value);\n const contrast = getContrastRatio(rgb, bgRgb);\n maxContrastBg = Math.max(maxContrastBg, contrast);\n }\n\n for (const fg of foregrounds) {\n const fgRgb = parseColorToRgb(fg.value);\n const contrast = getContrastRatio(rgb, fgRgb);\n maxContrastFg = Math.max(maxContrastFg, contrast);\n }\n\n return {\n contrastWithBackground: maxContrastBg,\n contrastWithForeground: maxContrastFg,\n meetsAA: maxContrastBg >= 4.5 || maxContrastFg >= 4.5,\n meetsAAA: maxContrastBg >= 7.0 || maxContrastFg >= 7.0,\n };\n}\n\n/**\n * Calculate confidence score (0-100)\n */\nfunction calculateConfidence(distance: number, score: number): number {\n // For very small distances (exact or near-exact matches), return high confidence\n if (distance < 0.5) return 100;\n if (distance < 1) return 98;\n if (distance < 2) return 95;\n\n // Combine distance and score for confidence\n const distanceConfidence = Math.max(0, 100 - distance * 2);\n const scoreConfidence = score * 100;\n return Math.round((distanceConfidence + scoreConfidence) / 2);\n}\n\n/**\n * Calculate semantic score based on context\n */\nfunction calculateContextSemanticScore(\n context: ColorContext,\n role: SemanticRole | undefined,\n): number {\n if (!role) return 0.5;\n\n switch (context) {\n case \"accent\":\n return role === \"primary\" || role === \"secondary\" ? 1.0 : 0.5;\n case \"background\":\n return role === \"surface\" || role === \"background\" ? 1.0 : 0.3;\n case \"border\":\n // Strongly prefer outline role for border context\n return role === \"outline\" ? 1.0 : role === \"neutral\" ? 0.4 : 0.2;\n case \"decorative\":\n return 0.7; // Any role is acceptable\n case \"shadow\":\n return role === \"shadow\" ? 1.0 : 0.3;\n case \"text\":\n return role === \"neutral\" || role === \"surface\" ? 0.8 : 0.5;\n default:\n return 0.5;\n }\n}\n\n/**\n * Calculate HCT perceptual distance\n */\nfunction calculateHctDistance(color1: HCT, color2: HCT): number {\n // Weight factors for HCT components\n const hueWeight = 1.0;\n const chromaWeight = 1.0;\n const toneWeight = 2.0; // Tone is most important for perception\n\n // Calculate hue difference (circular)\n let hueDiff = Math.abs(color1.h - color2.h);\n if (hueDiff > 180) {\n hueDiff = 360 - hueDiff;\n }\n\n // Normalize hue difference (0-1)\n hueDiff = hueDiff / 180;\n\n // Calculate chroma difference (normalize by max chroma ~120)\n const chromaDiff = Math.abs(color1.c - color2.c) / 120;\n\n // Calculate tone difference (0-100)\n const toneDiff = Math.abs(color1.t - color2.t) / 100;\n\n // Weighted Euclidean distance\n return (\n Math.sqrt(\n Math.pow(hueDiff * hueWeight, 2) +\n Math.pow(chromaDiff * chromaWeight, 2) +\n Math.pow(toneDiff * toneWeight, 2),\n ) * 100\n ); // Scale to 0-100 range\n}\n\n/**\n * Calculate multi-factor match score\n */\nfunction calculateMatchScore(\n inputHct: HCT,\n candidate: ThemeVariable,\n distance: number,\n weights: { accessibility: number; perceptual: number; semantic: number },\n options: MatchingOptions,\n): number {\n // Perceptual score (inverse of distance)\n const perceptualScore = Math.max(0, 100 - distance) / 100;\n\n // Semantic score\n let semanticScore = 0.5; // Neutral if no preference\n if (options.preferredRole && candidate.role) {\n semanticScore = candidate.role === options.preferredRole ? 1.0 : 0.3;\n } else if (options.contextType) {\n semanticScore = calculateContextSemanticScore(\n options.contextType,\n candidate.role,\n );\n }\n\n // Accessibility score (based on tone appropriateness)\n let accessibilityScore = 0.5; // Neutral default\n if (options.contextType === \"text\") {\n // Prefer high contrast (very light or very dark)\n accessibilityScore = candidate.tone < 30 || candidate.tone > 70 ? 1.0 : 0.3;\n } else if (options.contextType === \"background\") {\n // Prefer mid-tones for backgrounds\n accessibilityScore =\n candidate.tone >= 90 || candidate.tone <= 10 ? 1.0 : 0.5;\n }\n\n // Calculate weighted score\n return (\n perceptualScore * weights.perceptual +\n semanticScore * weights.semantic +\n accessibilityScore * weights.accessibility\n );\n}\n\n/**\n * Find typical background colors from theme\n */\nfunction findTypicalBackgrounds(theme: ThemeVariables): ThemeVariable[] {\n const backgrounds: ThemeVariable[] = [];\n\n if (theme.surface) {\n backgrounds.push(\n ...theme.surface.filter((v) => v.tone >= 90 || v.tone <= 10),\n );\n }\n if (theme.background) {\n backgrounds.push(...theme.background);\n }\n if (theme.neutral) {\n backgrounds.push(\n ...theme.neutral.filter((v) => v.tone >= 95 || v.tone <= 5),\n );\n }\n\n return backgrounds;\n}\n\n/**\n * Find typical foreground colors from theme\n */\nfunction findTypicalForegrounds(theme: ThemeVariables): ThemeVariable[] {\n const foregrounds: ThemeVariable[] = [];\n\n if (theme.neutral) {\n foregrounds.push(\n ...theme.neutral.filter(\n (v) => (v.tone >= 20 && v.tone <= 40) || (v.tone >= 60 && v.tone <= 80),\n ),\n );\n }\n if (theme.surface) {\n foregrounds.push(\n ...theme.surface.filter((v) => v.tone >= 10 && v.tone <= 30),\n );\n }\n\n return foregrounds;\n}\n\n/**\n * Flatten theme variables into a single array\n */\nfunction flattenThemeVariables(theme: ThemeVariables): ThemeVariable[] {\n const variables: ThemeVariable[] = [];\n\n // Add standard roles\n if (theme.primary) variables.push(...theme.primary);\n if (theme.secondary) variables.push(...theme.secondary);\n if (theme.tertiary) variables.push(...theme.tertiary);\n if (theme.error) variables.push(...theme.error);\n if (theme.neutral) variables.push(...theme.neutral);\n if (theme.surface) variables.push(...theme.surface);\n if (theme.background) variables.push(...theme.background);\n if (theme.outline) variables.push(...theme.outline);\n if (theme.shadow) variables.push(...theme.shadow);\n\n // Add custom roles\n if (theme.custom) {\n for (const customVars of Object.values(theme.custom)) {\n variables.push(...customVars);\n }\n }\n\n return variables;\n}\n\n/**\n * Parse color string to RGB\n */\nfunction parseColorToRgb(color: string): { b: number; g: number; r: number } {\n // Remove whitespace\n color = color.trim();\n\n // Hex color\n if (color.startsWith(\"#\")) {\n return hexToRgb(color);\n }\n\n // RGB/RGBA\n if (color.startsWith(\"rgb\")) {\n const match = color.match(/rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)/);\n if (match) {\n return {\n b: parseInt(match[3], 10) / 255,\n g: parseInt(match[2], 10) / 255,\n r: parseInt(match[1], 10) / 255,\n };\n }\n }\n\n throw new Error(`Unable to parse color: ${color}`);\n}\n","/**\n * Theme Parser\n * Parses CSS variables and extracts theme colors\n */\n\nimport type { SemanticRole, ThemeVariable, ThemeVariables } from \"./types.js\";\n\nimport { hexToRgb } from \"../color/conversions.js\";\nimport { rgbToHct } from \"../color/hct/hct-solver.js\";\n\n/**\n * Parse CSS content and extract theme variables\n */\nexport function parseThemeVariables(css: string): ThemeVariables {\n const variables: ThemeVariable[] = [];\n\n // Match CSS custom properties\n const varRegex = /--([\\w-]+):\\s*([^;]+);/g;\n let match;\n\n while ((match = varRegex.exec(css)) !== null) {\n const [, name, value] = match;\n const fullName = `--${name}`;\n const trimmedValue = value.trim();\n\n // Check if it's a color value\n if (isColorValue(trimmedValue)) {\n const colorValue = normalizeColorValue(trimmedValue);\n if (colorValue) {\n try {\n const rgb = parseColorToRgb(colorValue);\n const hct = rgbToHct(rgb);\n\n variables.push({\n hct,\n name: fullName,\n role: detectSemanticRole(name),\n tone: hct.t,\n value: colorValue,\n });\n } catch {\n // Skip invalid color values\n console.warn(\n `Failed to parse color variable ${fullName}: ${trimmedValue}`,\n );\n }\n }\n }\n }\n\n // Organize variables by role\n return organizeByRole(variables);\n}\n\n/**\n * Parse CSS variables from an object (e.g., from getComputedStyle)\n */\nexport function parseThemeVariablesFromObject(\n variables: Record<string, string>,\n): ThemeVariables {\n const themeVars: ThemeVariable[] = [];\n\n for (const [name, value] of Object.entries(variables)) {\n if (name.startsWith(\"--\") && isColorValue(value)) {\n const colorValue = normalizeColorValue(value);\n if (colorValue) {\n try {\n const rgb = parseColorToRgb(colorValue);\n const hct = rgbToHct(rgb);\n\n themeVars.push({\n hct,\n name,\n role: detectSemanticRole(name.slice(2)), // Remove -- prefix\n tone: hct.t,\n value: colorValue,\n });\n } catch {\n console.warn(`Failed to parse color variable ${name}: ${value}`);\n }\n }\n }\n }\n\n return organizeByRole(themeVars);\n}\n\n/**\n * Detect semantic role from variable name\n */\nfunction detectSemanticRole(name: string): SemanticRole | undefined {\n const lower = name.toLowerCase();\n\n if (lower.includes(\"primary\")) return \"primary\";\n if (lower.includes(\"secondary\")) return \"secondary\";\n if (lower.includes(\"tertiary\")) return \"tertiary\";\n if (lower.includes(\"error\") || lower.includes(\"danger\")) return \"error\";\n if (lower.includes(\"neutral\") || lower.includes(\"gray\")) return \"neutral\";\n if (lower.includes(\"surface\")) return \"surface\";\n if (lower.includes(\"background\") || lower.includes(\"bg\")) return \"background\";\n if (lower.includes(\"outline\") || lower.includes(\"border\")) return \"outline\";\n if (lower.includes(\"shadow\")) return \"shadow\";\n\n return undefined;\n}\n\n/**\n * HSL to RGB helper\n */\nfunction hslToRgb(\n h: number,\n s: number,\n l: number,\n): { b: number; g: number; r: number } {\n let b, g, r;\n\n if (s === 0) {\n r = g = b = l;\n } else {\n const hue2rgb = (p: number, q: number, t: number) => {\n if (t < 0) t += 1;\n if (t > 1) t -= 1;\n if (t < 1 / 6) return p + (q - p) * 6 * t;\n if (t < 1 / 2) return q;\n if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;\n return p;\n };\n\n const q = l < 0.5 ? l * (1 + s) : l + s - l * s;\n const p = 2 * l - q;\n r = hue2rgb(p, q, h + 1 / 3);\n g = hue2rgb(p, q, h);\n b = hue2rgb(p, q, h - 1 / 3);\n }\n\n return { b, g, r };\n}\n\n/**\n * Check if a value is a color\n */\nfunction isColorValue(value: string): boolean {\n const trimmed = value.trim();\n\n // Hex colors\n if (/^#[0-9a-fA-F]{3,8}$/.test(trimmed)) return true;\n\n // RGB/RGBA\n if (/^rgba?\\(/.test(trimmed)) return true;\n\n // HSL/HSLA\n if (/^hsla?\\(/.test(trimmed)) return true;\n\n // Named colors (basic check)\n if (/^[a-z]+$/i.test(trimmed)) {\n return isNamedColor(trimmed);\n }\n\n return false;\n}\n\n/**\n * Check if string is a named color\n */\nfunction isNamedColor(name: string): boolean {\n const namedColors = [\n \"black\",\n \"white\",\n \"red\",\n \"green\",\n \"blue\",\n \"yellow\",\n \"cyan\",\n \"magenta\",\n \"gray\",\n \"grey\",\n \"orange\",\n \"purple\",\n \"brown\",\n \"pink\",\n \"lime\",\n \"navy\",\n \"teal\",\n \"silver\",\n \"gold\",\n \"indigo\",\n \"violet\",\n \"turquoise\",\n \"coral\",\n ];\n return namedColors.includes(name.toLowerCase());\n}\n\n/**\n * Convert named color to hex (simplified)\n */\nfunction namedColorToHex(name: string): string {\n const colors: Record<string, string> = {\n black: \"#000000\",\n blue: \"#0000ff\",\n brown: \"#a52a2a\",\n coral: \"#ff7f50\",\n cyan: \"#00ffff\",\n gold: \"#ffd700\",\n gray: \"#808080\",\n green: \"#008000\",\n grey: \"#808080\",\n indigo: \"#4b0082\",\n lime: \"#00ff00\",\n magenta: \"#ff00ff\",\n navy: \"#000080\",\n orange: \"#ffa500\",\n pink: \"#ffc0cb\",\n purple: \"#800080\",\n red: \"#ff0000\",\n silver: \"#c0c0c0\",\n teal: \"#008080\",\n turquoise: \"#40e0d0\",\n violet: \"#ee82ee\",\n white: \"#ffffff\",\n yellow: \"#ffff00\",\n };\n return colors[name.toLowerCase()] || \"#000000\";\n}\n\n/**\n * Normalize color value to a standard format\n */\nfunction normalizeColorValue(value: string): null | string {\n const trimmed = value.trim();\n\n // Already in a good format\n if (/^#[0-9a-fA-F]{6}$/.test(trimmed)) {\n return trimmed;\n }\n\n // Short hex\n if (/^#[0-9a-fA-F]{3}$/.test(trimmed)) {\n const [, r, g, b] = trimmed.match(/#(.)(.)(.)/)!;\n return `#${r}${r}${g}${g}${b}${b}`;\n }\n\n // RGB/RGBA\n if (/^rgba?\\(/.test(trimmed)) {\n return parseRgbString(trimmed);\n }\n\n // HSL/HSLA\n if (/^hsla?\\(/.test(trimmed)) {\n return parseHslString(trimmed);\n }\n\n // Named colors\n if (isNamedColor(trimmed)) {\n return namedColorToHex(trimmed);\n }\n\n return null;\n}\n\n/**\n * Organize variables by semantic role\n */\nfunction organizeByRole(variables: ThemeVariable[]): ThemeVariables {\n const organized: ThemeVariables = {\n custom: {},\n };\n\n for (const variable of variables) {\n if (variable.role) {\n const role = variable.role;\n if (!organized[role]) {\n organized[role] = [];\n }\n organized[role].push(variable);\n } else {\n // Extract custom role from name pattern (e.g., --color-brand-50, --accent-warm)\n const colorPattern = variable.name.match(/--(?:color-)?([a-z]+)-\\d+/i);\n const namedPattern = variable.name.match(/--([a-z]+)-[a-z]+/i);\n\n if (colorPattern) {\n const customRole = colorPattern[1].toLowerCase();\n if (!organized.custom![customRole]) {\n organized.custom![customRole] = [];\n }\n organized.custom![customRole].push(variable);\n } else if (namedPattern) {\n const customRole = namedPattern[1].toLowerCase();\n // Only use this pattern if it's a known semantic pattern\n const knownPatterns = [\n \"accent\",\n \"neutral\",\n \"success\",\n \"warning\",\n \"info\",\n ];\n if (knownPatterns.some((p) => customRole.includes(p))) {\n if (!organized.custom![customRole]) {\n organized.custom![customRole] = [];\n }\n organized.custom![customRole].push(variable);\n } else {\n // Unknown pattern, put in uncategorized\n if (!organized.custom![\"uncategorized\"]) {\n organized.custom![\"uncategorized\"] = [];\n }\n organized.custom![\"uncategorized\"].push(variable);\n }\n } else {\n // Uncategorized\n if (!organized.custom![\"uncategorized\"]) {\n organized.custom![\"uncategorized\"] = [];\n }\n organized.custom![\"uncategorized\"].push(variable);\n }\n }\n }\n\n // Sort each role by tone\n for (const role of Object.keys(organized)) {\n if (Array.isArray(organized[role as keyof ThemeVariables])) {\n (organized[role as keyof ThemeVariables] as ThemeVariable[]).sort(\n (a, b) => a.tone - b.tone,\n );\n } else if (role === \"custom\" && organized.custom) {\n for (const customRole of Object.keys(organized.custom)) {\n organized.custom[customRole].sort((a, b) => a.tone - b.tone);\n }\n }\n }\n\n return organized;\n}\n\n/**\n * Parse color to RGB\n */\nfunction parseColorToRgb(color: string): { b: number; g: number; r: number } {\n // Hex color\n if (color.startsWith(\"#\")) {\n return hexToRgb(color);\n }\n\n // RGB string\n if (color.startsWith(\"rgb\")) {\n const match = color.match(/rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)/);\n if (match) {\n return {\n b: parseInt(match[3], 10) / 255,\n g: parseInt(match[2], 10) / 255,\n r: parseInt(match[1], 10) / 255,\n };\n }\n }\n\n throw new Error(`Unable to parse color: ${color}`);\n}\n\n/**\n * Parse HSL/HSLA string to hex\n */\nfunction parseHslString(hsl: string): null | string {\n const match = hsl.match(/hsla?\\((\\d+),\\s*(\\d+)%,\\s*(\\d+)%/);\n if (match) {\n const h = parseInt(match[1], 10) / 360;\n const s = parseInt(match[2], 10) / 100;\n const l = parseInt(match[3], 10) / 100;\n\n // HSL to RGB conversion\n const rgb = hslToRgb(h, s, l);\n const r = Math.round(rgb.r * 255);\n const g = Math.round(rgb.g * 255);\n const b = Math.round(rgb.b * 255);\n\n return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;\n }\n return null;\n}\n\n/**\n * Parse RGB/RGBA string to hex\n */\nfunction parseRgbString(rgb: string): null | string {\n const match = rgb.match(/rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+)/);\n if (match) {\n const r = parseInt(match[1], 10);\n const g = parseInt(match[2], 10);\n const b = parseInt(match[3], 10);\n return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;\n }\n return null;\n}\n","/**\n * CSS Refactoring Utilities\n * Refactor CSS to use theme variables\n */\n\nimport type {\n ColorContext,\n ColorReplacement,\n MatchingOptions,\n RefactoringResult,\n RefactoringWarning,\n ThemeVariables,\n} from \"./types.js\";\n\nimport { findClosestThemeColor } from \"./matcher.js\";\n\n/**\n * CSS property to context mapping\n */\nconst PROPERTY_CONTEXT_MAP: Record<string, ColorContext> = {\n background: \"background\",\n \"background-color\": \"background\",\n border: \"border\",\n \"border-bottom-color\": \"border\",\n \"border-color\": \"border\",\n \"border-left-color\": \"border\",\n \"border-right-color\": \"border\",\n \"border-top-color\": \"border\",\n \"box-shadow\": \"shadow\",\n color: \"text\",\n fill: \"decorative\",\n outline: \"border\",\n \"outline-color\": \"border\",\n \"stop-color\": \"decorative\",\n stroke: \"border\",\n \"text-shadow\": \"shadow\",\n};\n\n/**\n * Generate a refactoring report\n */\nexport function generateRefactoringReport(result: RefactoringResult): string {\n const lines: string[] = [\n \"# CSS Refactoring Report\",\n \"\",\n \"## Summary\",\n `- Total colors found: ${result.statistics.totalColors}`,\n `- Colors replaced: ${result.statistics.replacedColors}`,\n `- Replacement rate: ${Math.round((result.statistics.replacedColors / result.statistics.totalColors) * 100)}%`,\n `- Average confidence: ${result.statistics.averageConfidence}%`,\n `- Accessibility issues: ${result.statistics.accessibilityIssues}`,\n \"\",\n \"## Replacements\",\n ];\n\n // Group replacements by confidence\n const highConfidence = result.replacements.filter((r) => r.confidence >= 90);\n const mediumConfidence = result.replacements.filter(\n (r) => r.confidence >= 70 && r.confidence < 90,\n );\n const lowConfidence = result.replacements.filter((r) => r.confidence < 70);\n\n if (highConfidence.length > 0) {\n lines.push(\"\", \"### High Confidence (≥90%)\");\n for (const replacement of highConfidence) {\n lines.push(\n `- Line ${replacement.line}: ${replacement.originalColor} → ${replacement.cssVariable} (${replacement.confidence}%)`,\n );\n }\n }\n\n if (mediumConfidence.length > 0) {\n lines.push(\"\", \"### Medium Confidence (70-89%)\");\n for (const replacement of mediumConfidence) {\n lines.push(\n `- Line ${replacement.line}: ${replacement.originalColor} → ${replacement.cssVariable} (${replacement.confidence}%)`,\n );\n }\n }\n\n if (lowConfidence.length > 0) {\n lines.push(\"\", \"### Low Confidence (<70%)\");\n for (const replacement of lowConfidence) {\n lines.push(\n `- Line ${replacement.line}: ${replacement.originalColor} → ${replacement.cssVariable} (${replacement.confidence}%)`,\n );\n }\n }\n\n // Add warnings\n if (result.warnings.length > 0) {\n lines.push(\"\", \"## Warnings\");\n\n const warningsByType = result.warnings.reduce(\n (acc, warning) => {\n if (!acc[warning.type]) acc[warning.type] = [];\n acc[warning.type].push(warning);\n return acc;\n },\n {} as Record<string, typeof result.warnings>,\n );\n\n for (const [type, warnings] of Object.entries(warningsByType)) {\n lines.push(\"\", `### ${formatWarningType(type)}`);\n for (const warning of warnings) {\n lines.push(`- ${warning.message}`);\n if (warning.suggestion) {\n lines.push(` Suggestion: ${warning.suggestion}`);\n }\n }\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Refactor a single color value\n */\nexport function refactorColor(\n color: string,\n themeVariables: ThemeVariables,\n context?: ColorContext,\n): {\n alternatives: string[];\n confidence: number;\n variable: null | string;\n} {\n const match = findClosestThemeColor(color, themeVariables, {\n contextType: context,\n });\n\n if (!match) {\n return {\n alternatives: [],\n confidence: 0,\n variable: null,\n };\n }\n\n return {\n alternatives: match.alternatives.map((alt) => alt.variable),\n confidence: match.confidence,\n variable: match.variable,\n };\n}\n\n/**\n * Refactor CSS content to use theme variables\n */\nexport function refactorCss(\n css: string,\n themeVariables: ThemeVariables,\n options: {\n addComments?: boolean;\n minConfidence?: number;\n preserveOriginal?: boolean;\n } = {},\n): RefactoringResult {\n const {\n addComments = true,\n minConfidence = 70,\n preserveOriginal = true,\n } = options;\n\n const replacements: ColorReplacement[] = [];\n const warnings: RefactoringWarning[] = [];\n let refactoredCss = css;\n let totalColors = 0;\n let replacedColors = 0;\n let totalConfidence = 0;\n let accessibilityIssues = 0;\n\n // Process CSS line by line for better tracking\n const lines = css.split(\"\\n\");\n const refactoredLines: string[] = [];\n\n for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {\n const line = lines[lineIndex];\n let refactoredLine = line;\n\n // Detect CSS property\n const propertyMatch = line.match(/^\\s*([a-z-]+):\\s*/i);\n const property = propertyMatch ? propertyMatch[1].toLowerCase() : null;\n const context = property ? PROPERTY_CONTEXT_MAP[property] : undefined;\n\n // Find all color values in the line\n const colorMatches = findColorsInLine(line);\n\n for (const colorMatch of colorMatches) {\n totalColors++;\n const { color, end, start } = colorMatch;\n\n // Find matching theme variable\n const matchOptions: MatchingOptions = {\n contextType: context,\n weights: {\n accessibility:\n context === \"text\" || context === \"background\" ? 0.3 : 0.1,\n perceptual: 0.6,\n semantic: context ? 0.3 : 0.2,\n },\n };\n\n const match = findClosestThemeColor(color, themeVariables, matchOptions);\n\n if (match && match.confidence >= minConfidence) {\n replacedColors++;\n totalConfidence += match.confidence;\n\n // Create replacement\n const replacement: ColorReplacement = {\n column: start,\n confidence: match.confidence,\n context,\n cssVariable: match.variable,\n line: lineIndex + 1,\n originalColor: color,\n property: property || undefined,\n };\n replacements.push(replacement);\n\n // Check accessibility\n if (match.accessibilityInfo && !match.accessibilityInfo.meetsAA) {\n accessibilityIssues++;\n warnings.push({\n location: { column: start, line: lineIndex + 1 },\n message: `Color ${color} replaced with ${match.variable} may have accessibility issues`,\n type: \"accessibility\",\n });\n }\n\n // Apply replacement to line\n let replacementText = `var(${match.variable})`;\n\n if (preserveOriginal && addComments) {\n replacementText = `/* ${color} */ ${replacementText}`;\n }\n\n // Replace in line\n refactoredLine =\n refactoredLine.substring(0, start) +\n replacementText +\n refactoredLine.substring(end);\n } else if (match && match.confidence < minConfidence) {\n warnings.push({\n location: { column: start, line: lineIndex + 1 },\n message: `Low confidence match for ${color}: ${match.variable} (${match.confidence}%)`,\n suggestion: `Consider using ${match.variable} or defining a new theme variable`,\n type: \"low-confidence\",\n });\n } else {\n warnings.push({\n location: { column: start, line: lineIndex + 1 },\n message: `No suitable theme variable found for ${color}`,\n suggestion: \"Consider adding this color to your theme\",\n type: \"no-match\",\n });\n }\n }\n\n refactoredLines.push(refactoredLine);\n }\n\n // Add summary comment at the top if requested\n if (addComments && replacedColors > 0) {\n const summaryComment = `/* CSS Refactored with Theme Variables\n * Total colors found: ${totalColors}\n * Colors replaced: ${replacedColors}\n * Average confidence: ${Math.round(totalConfidence / replacedColors)}%\n * Warnings: ${warnings.length}\n */\\n\\n`;\n refactoredCss = summaryComment + refactoredLines.join(\"\\n\");\n } else {\n refactoredCss = refactoredLines.join(\"\\n\");\n }\n\n return {\n original: css,\n refactored: refactoredCss,\n replacements,\n statistics: {\n accessibilityIssues,\n averageConfidence:\n replacedColors > 0 ? Math.round(totalConfidence / replacedColors) : 0,\n replacedColors,\n totalColors,\n },\n warnings,\n };\n}\n\n/**\n * Find all color values in a line\n */\nfunction findColorsInLine(\n line: string,\n): Array<{ color: string; end: number; start: number }> {\n const colors: Array<{ color: string; end: number; start: number }> = [];\n\n // Check for hex colors\n let match;\n const hexRegex = /#[0-9a-fA-F]{3,8}/g;\n while ((match = hexRegex.exec(line)) !== null) {\n colors.push({\n color: match[0],\n end: match.index + match[0].length,\n start: match.index,\n });\n }\n\n // Check for rgb/rgba - be more precise with the regex\n const rgbRegex = /rgba?\\(\\s*\\d+\\s*,\\s*\\d+\\s*,\\s*\\d+(?:\\s*,\\s*[\\d.]+)?\\s*\\)/g;\n while ((match = rgbRegex.exec(line)) !== null) {\n colors.push({\n color: match[0],\n end: match.index + match[0].length,\n start: match.index,\n });\n }\n\n // Check for hsl/hsla\n const hslRegex = /hsla?\\([^)]+\\)/g;\n while ((match = hslRegex.exec(line)) !== null) {\n colors.push({\n color: match[0],\n end: match.index + match[0].length,\n start: match.index,\n });\n }\n\n // Sort by position to handle overlaps\n colors.sort((a, b) => a.start - b.start);\n\n // Remove duplicates and overlaps\n const uniqueColors: typeof colors = [];\n let lastEnd = -1;\n\n for (const color of colors) {\n if (color.start >= lastEnd) {\n uniqueColors.push(color);\n lastEnd = color.end;\n }\n }\n\n return uniqueColors;\n}\n\n/**\n * Format warning type for display\n */\nfunction formatWarningType(type: string): string {\n const formats: Record<string, string> = {\n accessibility: \"Accessibility Concerns\",\n \"low-confidence\": \"Low Confidence Matches\",\n \"no-match\": \"No Matches Found\",\n \"semantic-mismatch\": \"Semantic Mismatches\",\n };\n return formats[type] || type;\n}\n","#!/usr/bin/env node\n\n/**\n * Coolors MCP Server - Advanced Color Operations & Theme Intelligence\n *\n * A comprehensive Model Context Protocol server providing:\n * - Color space conversions (RGB, HSL, HSV, LAB, XYZ, HCT)\n * - Material Design 3 theme generation with tonal palettes\n * - Intelligent CSS theme matching with multi-factor scoring\n * - Image color extraction using Celebi quantization\n * - WCAG accessibility compliance checking\n * - Universal color preference analysis (dislike detection)\n * - Context-aware color selection for UI components\n *\n * Built on Google's HCT color space for perceptually uniform operations\n * and Material Color Utilities algorithms for professional-grade results.\n */\n\nimport { CoolorsMcp } from \"../coolors-mcp.js\";\nimport * as tools from \"../tools/index.js\";\n\n// Create the MCP server\nconst server = new CoolorsMcp({\n instructions:\n \"Advanced color operations server with Material Design 3 support, CSS theme matching, image extraction, and accessibility compliance. Uses HCT color space for perceptually accurate operations.\",\n name: \"coolors-mcp\",\n version: \"1.0.0\",\n});\n\n// Core color operations: conversion, distance metrics, accessibility\nserver.addTool(tools.colorConversionTool);\nserver.addTool(tools.colorDistanceTool);\nserver.addTool(tools.contrastCheckerTool);\nserver.addTool(tools.paletteGeneratorTool);\nserver.addTool(tools.paletteWithLocksTool);\nserver.addTool(tools.gradientGeneratorTool);\n\n// Material Design 3: theme generation, harmonization, tonal palettes\nserver.addTool(tools.generateMaterialThemeTool);\nserver.addTool(tools.harmonizeColorsTool);\nserver.addTool(tools.generateTonalPaletteTool);\n\n// CSS theme intelligence: matching, refactoring, migration\nserver.addTool(tools.matchThemeColorTool);\nserver.addTool(tools.refactorCssWithThemeTool);\nserver.addTool(tools.matchThemeColorsBatchTool);\nserver.addTool(tools.generateThemeCssTool);\n\n// Image analysis: color extraction, theme generation from photos\nserver.addTool(tools.extractImageColorsTool);\nserver.addTool(tools.generateThemeFromImageTool);\n\n// Color psychology: detect and fix universally disliked colors\nserver.addTool(tools.analyzeColorLikabilityTool);\nserver.addTool(tools.fixDislikedColorsBatchTool);\n\n// Start the server\nserver.start().catch((error) => {\n console.error(\"Failed to start server:\", error);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,SAAS,SAAS;AAUX,IAAM,sBAAsB;AAAA,EACjC,aACE;AAAA,EACF,SAAS,OAAO,SAGV;AACJ,UAAM,MAAM,WAAW,KAAK,KAAK;AACjC,QAAI,CAAC,KAAK;AACR,aAAO,yBAAyB,KAAK,KAAK;AAAA,IAC5C;AAEA,YAAQ,KAAK,IAAI;AAAA,MACf,KAAK,OAAO;AACV,cAAM,MAAM,SAAS,GAAG;AACxB,eAAO,OAAO,IAAI,EAAE,QAAQ,CAAC,CAAC,KAAK,IAAI,EAAE,QAAQ,CAAC,CAAC,KAAK,IAAI,EAAE,QAAQ,CAAC,CAAC;AAAA,MAC1E;AAAA,MACA,KAAK;AACH,eAAO,SAAS,GAAG;AAAA,MACrB,KAAK,OAAO;AACV,cAAM,MAAM,SAAS,GAAG;AACxB,eAAO,OAAO,KAAK,MAAM,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,IAAI,CAAC,CAAC;AAAA,MAC9E;AAAA,MACA,KAAK,OAAO;AACV,cAAM,MAAM,SAAS,GAAG;AACxB,eAAO,OAAO,IAAI,EAAE,QAAQ,CAAC,CAAC,KAAK,IAAI,EAAE,QAAQ,CAAC,CAAC,KAAK,IAAI,EAAE,QAAQ,CAAC,CAAC;AAAA,MAC1E;AAAA,MACA,KAAK;AACH,eAAO,OAAO,KAAK,MAAM,IAAI,IAAI,GAAG,CAAC,KAAK,KAAK,MAAM,IAAI,IAAI,GAAG,CAAC,KAAK,KAAK,MAAM,IAAI,IAAI,GAAG,CAAC;AAAA,MAC/F;AACE,eAAO,mBAAmB,KAAK,EAAE;AAAA,IACrC;AAAA,EACF;AAAA,EACA,MAAM;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0BAA0B;AAC/C,OAAO,QAAc,0BAA0B;AAG/C,OAAO,MAAM,EAAE,MAAM,CAAC,UAAU;AAC9B,UAAQ,MAAM,2BAA2B,KAAK;AAC9C,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["z","z","z","ColorFormat","z","z","z","z","z","z","z","delinearized","z","differenceDegrees","rgbToHex","z","z","z","z","z","z","z","parseColorToRgb","hslToRgb","p","q","parseColorToRgb","z"]}
1
+ {"version":3,"sources":["../../src/tools/adjust-color.tool.ts","../../src/tools/cohesion.tools.ts","../../src/tools/color-blindness.tool.ts","../../src/color/color-blindness.ts","../../src/tools/color-conversion.tool.ts","../../src/tools/color-distance.tool.ts","../../src/tools/contrast-checker.tool.ts","../../src/color/apca.ts","../../src/tools/dislike-analyzer.tool.ts","../../src/tools/gradient-generator.tool.ts","../../src/tools/image-extraction.tools.ts","../../src/color/utils/math_utils.ts","../../src/color/utils/color_utils.ts","../../src/color/image-utils.ts","../../src/color/quantize/lab_point_provider.ts","../../src/color/quantize/quantizer_wsmeans.ts","../../src/color/quantize/quantizer_map.ts","../../src/color/quantize/quantizer_wu.ts","../../src/color/quantize/quantizer_celebi.ts","../../src/color/score/score.ts","../../src/color/extract-colors.ts","../../src/color/material-theme.ts","../../src/tools/material-theme.tools.ts","../../src/tools/palette-export.tool.ts","../../src/tools/palette-generator.tool.ts","../../src/tools/palette-with-locks.tool.ts","../../src/tools/theme-matching.tools.ts","../../src/theme/matcher.ts","../../src/theme/parser.ts","../../src/theme/refactor.ts","../../src/bin/server.ts"],"sourcesContent":["/**\n * Color Adjust / Mix Tool\n * Exposes the lighten/darken/saturate/desaturate/grayscale/invert/mix utilities\n * via MCP.\n */\n\nimport { z } from \"zod\";\n\nimport {\n darken,\n desaturate,\n invertColor,\n lighten,\n mixColors,\n parseColor,\n rgbToHex,\n saturate,\n toGrayscale,\n} from \"../color/index.js\";\n\nconst OPS = [\n \"lighten\",\n \"darken\",\n \"saturate\",\n \"desaturate\",\n \"grayscale\",\n \"invert\",\n \"mix\",\n] as const;\n\nexport const adjustColorTool = {\n description:\n \"Adjust a color: lighten, darken, saturate, desaturate, grayscale, invert, or mix with a second color. Amount is 0-100 (percent) for lighten/darken/saturate/desaturate, 0-1 for mix weight.\",\n execute: async (args: {\n amount?: number;\n color: string;\n operation: (typeof OPS)[number];\n with?: string;\n }) => {\n const rgb = parseColor(args.color);\n if (!rgb) return `Invalid color format: ${args.color}`;\n\n switch (args.operation) {\n case \"darken\":\n return rgbToHex(darken(rgb, args.amount ?? 10));\n case \"desaturate\":\n return rgbToHex(desaturate(rgb, args.amount ?? 10));\n case \"grayscale\":\n return rgbToHex(toGrayscale(rgb));\n case \"invert\":\n return rgbToHex(invertColor(rgb));\n case \"lighten\":\n return rgbToHex(lighten(rgb, args.amount ?? 10));\n case \"mix\": {\n if (!args.with) return \"Error: 'with' is required for mix operation\";\n const other = parseColor(args.with);\n if (!other) return `Invalid color format: ${args.with}`;\n const weight = args.amount ?? 0.5;\n if (weight < 0 || weight > 1) {\n return \"Error: mix amount must be between 0 and 1\";\n }\n return rgbToHex(mixColors(rgb, other, weight));\n }\n case \"saturate\":\n return rgbToHex(saturate(rgb, args.amount ?? 10));\n }\n },\n name: \"adjust_color\",\n parameters: z.object({\n amount: z\n .number()\n .optional()\n .describe(\n \"Amount of change. For lighten/darken/saturate/desaturate: 0-100 (percent). For mix: 0-1 (weight of first color). Default 10 / 0.5.\",\n ),\n color: z.string().describe(\"Color to adjust (hex, rgb, hsl)\"),\n operation: z.enum(OPS).describe(\"Adjustment operation\"),\n with: z.string().optional().describe(\"Second color (only for mix)\"),\n }),\n};\n","/**\n * Visual cohesion tools\n *\n * - generate_tonal_scale: build a Tailwind-style tonal scale (50…950) from a\n * seed color using HCT so steps are perceptually even.\n * - generate_state_colors: derive hover/active/focus/disabled/pressed/selected\n * variants from a base color with consistent tonal deltas.\n * - analyze_palette_consistency: score how visually cohesive a palette is by\n * looking at chroma spread, tonal step uniformity, and hue harmony.\n * - generate_semantic_palette: pick semantic colors (primary/secondary/success/\n * warning/error/info) that harmonize with a brand color via HCT hue rotations.\n */\n\nimport { z } from \"zod\";\n\nimport { argbToRgb, rgbToArgb } from \"../color/conversions.js\";\nimport { Hct } from \"../color/hct/hct-class.js\";\nimport {\n colorDistance,\n parseColor,\n rgbToHex,\n rgbToHsl,\n} from \"../color/index.js\";\n\nconst TONAL_STOPS = [\n 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950,\n] as const;\n\nfunction hctFromColor(input: string): Hct | null {\n const rgb = parseColor(input);\n if (!rgb) return null;\n return Hct.fromInt(rgbToArgb(rgb));\n}\n\nfunction hctToHex(h: number, c: number, t: number): string {\n const hct = Hct.from(h, c, t);\n return rgbToHex(argbToRgb(hct.toInt()));\n}\n\n// --- generate_tonal_scale -----------------------------------------------------\n\nexport const generateTonalScaleTool = {\n description:\n \"Generate a complete tonal scale (Tailwind-style 50/100/.../900/950) from a seed color. Uses Google's HCT color space so each step is perceptually even — ideal for building shadable design-system colors.\",\n execute: async (args: {\n chromaBoost?: number;\n name?: string;\n seed: string;\n stops?: number[];\n }) => {\n const hct = hctFromColor(args.seed);\n if (!hct) return `Invalid color format: ${args.seed}`;\n\n const stops = args.stops?.length ? args.stops : Array.from(TONAL_STOPS);\n const chromaBoost = args.chromaBoost ?? 1;\n const name = (args.name ?? \"color\").toLowerCase();\n\n // Map Tailwind-style stops to HCT tones (50 -> tone 95, 950 -> tone 5).\n const tones = stops.map((s) => Math.max(0, Math.min(100, 100 - s / 10)));\n\n let output = `# Tonal scale for ${args.seed}\\n`;\n output += `Seed HCT: H=${hct.hue.toFixed(1)}° C=${hct.chroma.toFixed(1)} T=${hct.tone.toFixed(1)}\\n\\n`;\n output += `| stop | tone | hex |\\n|---|---|---|\\n`;\n\n const rows: { hex: string; stop: number; tone: number }[] = [];\n for (let i = 0; i < stops.length; i++) {\n const tone = tones[i];\n // Reduce chroma near the extremes (very light / very dark) for legibility.\n const edge = Math.abs(50 - tone) / 50; // 0 at mid, 1 at extremes\n const chroma = hct.chroma * chromaBoost * (1 - 0.35 * edge);\n const hex = hctToHex(hct.hue, chroma, tone);\n rows.push({ hex, stop: stops[i], tone });\n output += `| ${stops[i]} | ${tone.toFixed(0)} | ${hex} |\\n`;\n }\n\n output += `\\n## CSS\\n\\`\\`\\`css\\n:root {\\n`;\n for (const r of rows) output += ` --${name}-${r.stop}: ${r.hex};\\n`;\n output += `}\\n\\`\\`\\`\\n`;\n\n return output;\n },\n name: \"generate_tonal_scale\",\n parameters: z.object({\n chromaBoost: z\n .number()\n .min(0)\n .max(2)\n .optional()\n .default(1)\n .describe(\"Multiplier on seed chroma (1 = preserve, <1 = muted)\"),\n name: z\n .string()\n .optional()\n .describe(\"CSS variable base name (default: 'color')\"),\n seed: z.string().describe(\"Seed color (hex, rgb, hsl)\"),\n stops: z\n .array(z.number().min(0).max(1000))\n .optional()\n .describe(\n \"Custom stops. Default: [50,100,200,300,400,500,600,700,800,900,950].\",\n ),\n }),\n};\n\n// --- generate_state_colors ---------------------------------------------------\n\nexport const generateStateColorsTool = {\n description:\n \"Generate consistent interaction-state colors (hover / active / pressed / focus / disabled / selected) from a base color. Steps are computed in HCT space so they keep equal perceptual weight regardless of base hue.\",\n execute: async (args: { base: string; isDark?: boolean }) => {\n const hct = hctFromColor(args.base);\n if (!hct) return `Invalid color format: ${args.base}`;\n\n const dark = args.isDark ?? false;\n // In dark mode, \"hover\" should lighten; in light mode, it should darken.\n const dir = dark ? +1 : -1;\n\n const states: { hex: string; note: string; state: string; tone: number }[] =\n [\n { hex: \"\", note: \"resting\", state: \"base\", tone: hct.tone },\n {\n hex: \"\",\n note: \"+/- 8 tone\",\n state: \"hover\",\n tone: hct.tone + dir * 8,\n },\n {\n hex: \"\",\n note: \"+/- 16 tone\",\n state: \"active\",\n tone: hct.tone + dir * 16,\n },\n {\n hex: \"\",\n note: \"same as active, alias\",\n state: \"pressed\",\n tone: hct.tone + dir * 16,\n },\n {\n hex: \"\",\n note: \"+/- 4 tone, used as outline\",\n state: \"focus\",\n tone: hct.tone + dir * 4,\n },\n {\n hex: \"\",\n note: \"low chroma, mid tone\",\n state: \"disabled\",\n tone: dark ? 30 : 70,\n },\n {\n hex: \"\",\n note: \"alpha-blend friendly base\",\n state: \"selected\",\n tone: dark ? 25 : 90,\n },\n ];\n\n for (const s of states) {\n const chroma =\n s.state === \"disabled\" ? Math.min(hct.chroma, 6) : hct.chroma;\n const tone = Math.max(0, Math.min(100, s.tone));\n s.hex = hctToHex(hct.hue, chroma, tone);\n s.tone = tone;\n }\n\n let out = `# Interaction states for ${args.base} (${dark ? \"dark\" : \"light\"} mode)\\n\\n`;\n out += `| state | tone | hex | notes |\\n|---|---|---|---|\\n`;\n for (const s of states)\n out += `| ${s.state} | ${s.tone.toFixed(0)} | ${s.hex} | ${s.note} |\\n`;\n\n return out;\n },\n name: \"generate_state_colors\",\n parameters: z.object({\n base: z.string().describe(\"Base/resting color (hex, rgb, hsl)\"),\n isDark: z\n .boolean()\n .optional()\n .default(false)\n .describe(\n \"Whether the base color sits on a dark background. Hover lightens on dark, darkens on light.\",\n ),\n }),\n};\n\n// --- analyze_palette_consistency --------------------------------------------\n\nexport const analyzePaletteConsistencyTool = {\n description:\n \"Score how visually cohesive a palette is. Reports tonal step uniformity, chroma spread, hue distribution, and a single 0-100 cohesion score, plus targeted suggestions for tightening it up.\",\n execute: async (args: { colors: string[] }) => {\n if (args.colors.length < 2) {\n return \"Need at least 2 colors to analyze cohesion.\";\n }\n\n const parsed = args.colors.map((c) => ({ input: c, rgb: parseColor(c) }));\n if (parsed.some((p) => !p.rgb)) {\n const bad = parsed.filter((p) => !p.rgb).map((p) => p.input);\n return `Invalid color format: ${bad.join(\", \")}`;\n }\n\n const hcts = parsed.map((p) => Hct.fromInt(rgbToArgb(p.rgb!)));\n\n const tones = hcts.map((h) => h.tone).sort((a, b) => a - b);\n const chromas = hcts.map((h) => h.chroma);\n const hues = hcts.map((h) => h.hue);\n\n // Tonal step uniformity — std-dev of gaps between sorted tones.\n const gaps: number[] = [];\n for (let i = 1; i < tones.length; i++) gaps.push(tones[i] - tones[i - 1]);\n const avgGap = gaps.reduce((a, b) => a + b, 0) / (gaps.length || 1);\n const gapStd = Math.sqrt(\n gaps.reduce((a, b) => a + (b - avgGap) ** 2, 0) / (gaps.length || 1),\n );\n // Lower std relative to avg = more uniform. Score 100 when std ≈ 0.\n const toneUniformity = Math.max(\n 0,\n 100 - (gapStd / Math.max(1, avgGap)) * 50,\n );\n\n // Chroma cohesion — std-dev of chroma, lower is more cohesive.\n const avgChroma = chromas.reduce((a, b) => a + b, 0) / chromas.length;\n const chromaStd = Math.sqrt(\n chromas.reduce((a, b) => a + (b - avgChroma) ** 2, 0) / chromas.length,\n );\n const chromaCohesion = Math.max(0, 100 - chromaStd * 2);\n\n // Hue harmony — cluster hues; reward palettes whose hues sit within a few\n // recognized harmonic offsets (0, 30, 60, 90, 120, 150, 180 ±15°).\n const targets = [0, 30, 60, 90, 120, 150, 180];\n let harmonyHits = 0;\n for (let i = 0; i < hues.length; i++) {\n for (let j = i + 1; j < hues.length; j++) {\n let d = Math.abs(hues[i] - hues[j]);\n if (d > 180) d = 360 - d;\n if (targets.some((t) => Math.abs(d - t) <= 15)) harmonyHits++;\n }\n }\n const totalPairs = (hues.length * (hues.length - 1)) / 2;\n const hueHarmony = totalPairs ? (harmonyHits / totalPairs) * 100 : 100;\n\n const cohesion =\n 0.4 * toneUniformity + 0.3 * chromaCohesion + 0.3 * hueHarmony;\n\n // Find the most \"off\" color — the one that pushes std the most.\n let outlier = -1;\n let outlierGain = 0;\n for (let i = 0; i < hcts.length; i++) {\n const reduced = hcts.filter((_, k) => k !== i).map((h) => h.chroma);\n const m = reduced.reduce((a, b) => a + b, 0) / reduced.length;\n const std = Math.sqrt(\n reduced.reduce((a, b) => a + (b - m) ** 2, 0) / reduced.length,\n );\n const gain = chromaStd - std;\n if (gain > outlierGain) {\n outlierGain = gain;\n outlier = i;\n }\n }\n\n let out = `# Palette cohesion analysis\\n\\n`;\n out += `Colors: ${args.colors.length}\\n\\n`;\n out += `| metric | score | detail |\\n|---|---|---|\\n`;\n out += `| Tonal step uniformity | ${toneUniformity.toFixed(0)} | gap avg ${avgGap.toFixed(1)} ± ${gapStd.toFixed(1)} |\\n`;\n out += `| Chroma cohesion | ${chromaCohesion.toFixed(0)} | chroma avg ${avgChroma.toFixed(1)} ± ${chromaStd.toFixed(1)} |\\n`;\n out += `| Hue harmony | ${hueHarmony.toFixed(0)} | ${harmonyHits}/${totalPairs} pairs at harmonic angles |\\n`;\n out += `| **Overall cohesion** | **${cohesion.toFixed(0)}** | weighted 0.4 / 0.3 / 0.3 |\\n\\n`;\n\n const suggestions: string[] = [];\n if (toneUniformity < 60)\n suggestions.push(\n `Tone gaps are uneven (std ${gapStd.toFixed(1)}). Snap colors to a fixed scale (e.g. tones 10/30/50/70/90).`,\n );\n if (chromaCohesion < 60)\n suggestions.push(\n `Chroma varies widely (std ${chromaStd.toFixed(1)}). Mute saturated colors or boost flat ones toward chroma ${avgChroma.toFixed(0)}.`,\n );\n if (hueHarmony < 50)\n suggestions.push(\n `Hues don't sit at harmonic angles (30/60/90/120/180°). Try rotating outliers onto the nearest harmonic.`,\n );\n if (outlier >= 0)\n suggestions.push(\n `Likely outlier: ${args.colors[outlier]} (chroma ${hcts[outlier].chroma.toFixed(0)} vs avg ${avgChroma.toFixed(0)}).`,\n );\n\n if (suggestions.length === 0)\n out += `✓ Palette is visually cohesive across all three axes.\\n`;\n else {\n out += `## Suggestions\\n`;\n for (const s of suggestions) out += `- ${s}\\n`;\n }\n\n return out;\n },\n name: \"analyze_palette_consistency\",\n parameters: z.object({\n colors: z.array(z.string()).min(2).describe(\"Palette colors to analyze\"),\n }),\n};\n\n// --- generate_semantic_palette ----------------------------------------------\n\nconst SEMANTIC_OFFSETS: Record<string, number> = {\n // Hue offsets from brand color (in HCT degrees).\n // Secondary/tertiary use harmonic rotations; semantic statuses anchor to\n // conventional hue ranges (red/yellow/blue) but adjust chroma/tone to feel\n // like they belong to the same family.\n primary: 0,\n secondary: -30,\n tertiary: 60,\n};\n\nconst SEMANTIC_ANCHORS: Record<string, { chromaMin: number; hue: number }> = {\n // Anchored hues for status colors. Chroma is clamped down to whatever the\n // brand can muster so the status palette doesn't out-shout the brand.\n error: { chromaMin: 40, hue: 25 }, // red\n info: { chromaMin: 30, hue: 240 }, // blue\n success: { chromaMin: 30, hue: 142 }, // green\n warning: { chromaMin: 50, hue: 80 }, // amber\n};\n\nexport const generateSemanticPaletteTool = {\n description:\n \"From a single brand color, generate a complete visually-cohesive semantic palette: primary, secondary, tertiary, plus success/warning/error/info status colors. Tone and chroma are normalized in HCT space so every color feels like part of the same family.\",\n execute: async (args: { brand: string; isDark?: boolean }) => {\n const hct = hctFromColor(args.brand);\n if (!hct) return `Invalid color format: ${args.brand}`;\n\n const dark = args.isDark ?? false;\n const targetTone = dark ? 80 : 40;\n const familyChroma = Math.max(24, Math.min(hct.chroma, 80));\n\n const entries: { hex: string; hue: number; name: string; tone: number }[] =\n [];\n\n for (const [name, offset] of Object.entries(SEMANTIC_OFFSETS)) {\n const hue = (hct.hue + offset + 360) % 360;\n const hex = hctToHex(hue, familyChroma, targetTone);\n entries.push({ hex, hue, name, tone: targetTone });\n }\n\n for (const [name, anchor] of Object.entries(SEMANTIC_ANCHORS)) {\n const chroma = Math.max(anchor.chromaMin, Math.min(familyChroma, 90));\n const hex = hctToHex(anchor.hue, chroma, targetTone);\n entries.push({ hex, hue: anchor.hue, name, tone: targetTone });\n }\n\n // Quick sanity check: how close are the status hues to the brand? Report\n // the perceptual distance so the user knows what they're getting.\n const brandRgb = parseColor(args.brand)!;\n\n let out = `# Semantic palette derived from ${args.brand}\\n`;\n out += `Mode: ${dark ? \"dark\" : \"light\"} (target tone ${targetTone})\\n`;\n out += `Family chroma: ${familyChroma.toFixed(0)} (brand was ${hct.chroma.toFixed(0)})\\n\\n`;\n out += `| role | hue | hex | ΔE2000 from brand | hsl |\\n|---|---|---|---|---|\\n`;\n for (const e of entries) {\n const rgb = parseColor(e.hex)!;\n const delta = colorDistance(brandRgb, rgb, { metric: \"deltaE2000\" });\n const hsl = rgbToHsl(rgb);\n out += `| ${e.name} | ${e.hue.toFixed(0)}° | ${e.hex} | ${delta.toFixed(1)} | hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%) |\\n`;\n }\n\n out += `\\n## CSS\\n\\`\\`\\`css\\n:root {\\n`;\n for (const e of entries) out += ` --color-${e.name}: ${e.hex};\\n`;\n out += `}\\n\\`\\`\\`\\n`;\n\n return out;\n },\n name: \"generate_semantic_palette\",\n parameters: z.object({\n brand: z.string().describe(\"Brand / seed color (hex, rgb, hsl)\"),\n isDark: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Generate the palette for a dark theme background\"),\n }),\n};\n","/**\n * Color Blindness Simulation Tool\n * Simulate how colors appear to viewers with color vision deficiency (CVD)\n * and audit palette accessibility for common deficiency types.\n */\n\nimport { z } from \"zod\";\n\nimport {\n CVD_PREVALENCE,\n CvdType,\n simulateCvd,\n} from \"../color/color-blindness.js\";\nimport {\n colorDistance,\n getContrastRatio,\n parseColor,\n rgbToHex,\n} from \"../color/index.js\";\n\nconst CVD_TYPES = [\n \"protanopia\",\n \"deuteranopia\",\n \"tritanopia\",\n \"protanomaly\",\n \"deuteranomaly\",\n \"tritanomaly\",\n \"achromatopsia\",\n] as const satisfies readonly CvdType[];\n\nexport const simulateColorBlindnessTool = {\n description:\n \"Simulate how one or more colors appear to viewers with color vision deficiency (protanopia, deuteranopia, tritanopia, their milder anomaly forms, or achromatopsia).\",\n execute: async (args: { colors: string[]; types?: CvdType[] }) => {\n const types = args.types && args.types.length > 0 ? args.types : CVD_TYPES;\n\n const parsed = args.colors.map((c) => ({ input: c, rgb: parseColor(c) }));\n const invalid = parsed.filter((p) => !p.rgb);\n if (invalid.length) {\n return `Invalid color format: ${invalid.map((p) => p.input).join(\", \")}`;\n }\n\n let output = `# Color Blindness Simulation\\n\\n`;\n output += `| Original | ${types.join(\" | \")} |\\n`;\n output += `|${\"---|\".repeat(types.length + 1)}\\n`;\n\n for (const { input, rgb } of parsed) {\n const simulated = types.map((t) => rgbToHex(simulateCvd(rgb!, t)));\n output += `| ${rgbToHex(rgb!)} (${input}) | ${simulated.join(\" | \")} |\\n`;\n }\n\n output += `\\n## Population prevalence\\n`;\n for (const t of types) {\n output += `- **${t}**: ~${CVD_PREVALENCE[t]}% of population\\n`;\n }\n\n return output;\n },\n name: \"simulate_color_blindness\",\n parameters: z.object({\n colors: z\n .array(z.string())\n .min(1)\n .describe(\"Colors to simulate (hex, rgb, hsl)\"),\n types: z\n .array(z.enum(CVD_TYPES))\n .optional()\n .describe(\n \"Deficiency types to simulate. Defaults to all 7 (dichromacy + anomaly + achromatopsia).\",\n ),\n }),\n};\n\nexport const checkPaletteAccessibilityTool = {\n description:\n \"Audit a color palette for color-blind accessibility. For each pair of colors, reports the perceptual distance (Delta E 2000) under each CVD type and flags pairs that become indistinguishable.\",\n execute: async (args: {\n colors: string[];\n indistinguishableThreshold?: number;\n types?: CvdType[];\n }) => {\n const types = args.types && args.types.length > 0 ? args.types : CVD_TYPES;\n const threshold = args.indistinguishableThreshold ?? 10;\n\n const parsed = args.colors.map((c) => ({ input: c, rgb: parseColor(c) }));\n const invalid = parsed.filter((p) => !p.rgb);\n if (invalid.length) {\n return `Invalid color format: ${invalid.map((p) => p.input).join(\", \")}`;\n }\n\n const colors = parsed.map((p) => p.rgb!);\n const labels = parsed.map((p) => rgbToHex(p.rgb!));\n\n let output = `# Palette Accessibility Audit\\n\\n`;\n output += `Indistinguishable threshold: ΔE2000 < ${threshold}\\n\\n`;\n\n const problems: string[] = [];\n\n for (const type of types) {\n const simulated = colors.map((c) => simulateCvd(c, type));\n const collisions: string[] = [];\n\n for (let i = 0; i < simulated.length; i++) {\n for (let j = i + 1; j < simulated.length; j++) {\n const d = colorDistance(simulated[i], simulated[j], {\n metric: \"deltaE2000\",\n });\n if (d < threshold) {\n collisions.push(\n ` - ${labels[i]} ↔ ${labels[j]}: ΔE=${d.toFixed(1)} (sim: ${rgbToHex(\n simulated[i],\n )} vs ${rgbToHex(simulated[j])})`,\n );\n }\n }\n }\n\n output += `## ${type} (~${CVD_PREVALENCE[type]}% of population)\\n`;\n if (collisions.length === 0) {\n output += `✓ All ${colors.length} colors remain distinguishable\\n\\n`;\n } else {\n output += `⚠ ${collisions.length} indistinguishable pair${collisions.length === 1 ? \"\" : \"s\"}:\\n`;\n output += collisions.join(\"\\n\") + \"\\n\\n\";\n problems.push(type);\n }\n }\n\n output += `## Summary\\n`;\n if (problems.length === 0) {\n output += `✓ Palette is accessible across all tested CVD types.\\n`;\n } else {\n output += `⚠ Issues detected in: ${problems.join(\", \")}.\\n`;\n output += `Consider increasing tonal contrast (vary lightness) or chroma; CVD-friendly palettes rely on lightness differences rather than hue alone.\\n`;\n\n // Quick contrast hint: compute mean luminance contrast within the palette\n let worst = Infinity;\n for (let i = 0; i < colors.length; i++) {\n for (let j = i + 1; j < colors.length; j++) {\n const r = getContrastRatio(colors[i], colors[j]);\n if (r < worst) worst = r;\n }\n }\n output += `Lowest WCAG luminance ratio in palette: ${worst.toFixed(2)}:1 (target ≥ 3:1 for adjacent UI swatches).\\n`;\n }\n\n return output;\n },\n name: \"check_palette_accessibility\",\n parameters: z.object({\n colors: z\n .array(z.string())\n .min(2)\n .describe(\"Palette colors to audit (at least 2)\"),\n indistinguishableThreshold: z\n .number()\n .min(1)\n .max(30)\n .optional()\n .default(10)\n .describe(\n \"ΔE2000 below which two simulated colors are considered indistinguishable (default 10)\",\n ),\n types: z\n .array(z.enum(CVD_TYPES))\n .optional()\n .describe(\"CVD types to audit. Defaults to all 7.\"),\n }),\n};\n","/**\n * Color Vision Deficiency (CVD) simulation.\n *\n * Linear-sRGB transformation matrices from Machado, Oliveira, and Fernandes\n * (2009), \"A Physiologically-based Model for Simulation of Color Vision\n * Deficiency\". Severity 1.0 matrices are used for the dichromatic forms\n * (protanopia/deuteranopia/tritanopia); severity 0.6 matrices are used for the\n * milder anomaly forms. Achromatopsia uses ITU-R BT.709 luminance.\n *\n * Pipeline: sRGB → linear sRGB → matrix → sRGB.\n */\n\nimport type { RGB } from \"./types.js\";\n\nexport type CvdType =\n | \"achromatopsia\"\n | \"deuteranomaly\"\n | \"deuteranopia\"\n | \"protanomaly\"\n | \"protanopia\"\n | \"tritanomaly\"\n | \"tritanopia\";\n\n// Confusion-line matrices applied in linear sRGB space (Machado et al. 2009\n// linear approximation, common in libraries like color-blind / colorjs.io).\n// Each matrix maps linear-sRGB to the visible linear-sRGB for the given CVD.\nconst CVD_MATRICES: Record<\n Exclude<CvdType, \"achromatopsia\">,\n [number, number, number, number, number, number, number, number, number]\n> = {\n deuteranomaly: [\n 0.547494, 0.607765, -0.155259, 0.181692, 0.781742, 0.036566, -0.01041,\n 0.027275, 0.983136,\n ],\n deuteranopia: [\n 0.367322, 0.860646, -0.227968, 0.280085, 0.672501, 0.047413, -0.01182,\n 0.04294, 0.968881,\n ],\n // Mild forms (-omaly: severity ~0.6, Machado severity 0.6 table)\n protanomaly: [\n 0.458064, 0.679578, -0.137642, 0.092785, 0.846313, 0.060902, -0.007494,\n -0.016807, 1.024301,\n ],\n // Strong forms (-opia: full dichromacy, severity 1.0)\n protanopia: [\n 0.152286, 1.052583, -0.204868, 0.114503, 0.786281, 0.099216, -0.003882,\n -0.048116, 1.051998,\n ],\n tritanomaly: [\n 1.193214, -0.109812, -0.083402, 0.058694, 0.901185, 0.040121, -0.005978,\n 0.401901, 0.604077,\n ],\n tritanopia: [\n 1.255528, -0.076749, -0.178779, -0.078411, 0.930809, 0.147602, 0.004733,\n 0.691367, 0.3039,\n ],\n};\n\n/**\n * Simulate how a color appears to a viewer with the given color vision\n * deficiency.\n */\nexport function simulateCvd(rgb: RGB, type: CvdType): RGB {\n if (type === \"achromatopsia\") {\n // ITU-R BT.709 luminance (Rec. 709) — perceived brightness.\n const y = 0.2126 * rgb.r + 0.7152 * rgb.g + 0.0722 * rgb.b;\n const g = Math.max(0, Math.min(255, Math.round(y)));\n return { b: g, g, r: g };\n }\n\n const m = CVD_MATRICES[type];\n const r = srgbToLinear(rgb.r);\n const g = srgbToLinear(rgb.g);\n const b = srgbToLinear(rgb.b);\n\n const rOut = m[0] * r + m[1] * g + m[2] * b;\n const gOut = m[3] * r + m[4] * g + m[5] * b;\n const bOut = m[6] * r + m[7] * g + m[8] * b;\n\n return {\n b: linearToSrgb(bOut),\n g: linearToSrgb(gOut),\n r: linearToSrgb(rOut),\n };\n}\n\nfunction linearToSrgb(c: number): number {\n const v = c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;\n return Math.max(0, Math.min(255, Math.round(v * 255)));\n}\n\nfunction srgbToLinear(c: number): number {\n const n = c / 255;\n return n <= 0.04045 ? n / 12.92 : Math.pow((n + 0.055) / 1.055, 2.4);\n}\n\n/**\n * Approximate share of the population affected by each CVD type (worldwide,\n * combining male+female prevalence as reported by Colour Blind Awareness).\n */\nexport const CVD_PREVALENCE: Record<CvdType, number> = {\n achromatopsia: 0.003,\n deuteranomaly: 5.0,\n deuteranopia: 1.0,\n protanomaly: 1.0,\n protanopia: 1.0,\n tritanomaly: 0.01,\n tritanopia: 0.003,\n};\n","/**\n * Color Conversion Tool\n * Convert colors between different formats (hex, rgb, hsl, lab, hct)\n */\n\nimport { z } from \"zod\";\n\nimport {\n parseColor,\n rgbToHct,\n rgbToHex,\n rgbToHsl,\n rgbToLab,\n} from \"../color/index.js\";\n\nexport const colorConversionTool = {\n description:\n \"Convert colors between different formats (hex, rgb, hsl, lab, hct)\",\n execute: async (args: {\n color: string;\n to: \"hct\" | \"hex\" | \"hsl\" | \"lab\" | \"rgb\";\n }) => {\n const rgb = parseColor(args.color);\n if (!rgb) {\n return `Invalid color format: ${args.color}`;\n }\n\n switch (args.to) {\n case \"hct\": {\n const hct = rgbToHct(rgb);\n return `hct(${hct.h.toFixed(1)}, ${hct.c.toFixed(1)}, ${hct.t.toFixed(1)})`;\n }\n case \"hex\":\n return rgbToHex(rgb);\n case \"hsl\": {\n const hsl = rgbToHsl(rgb);\n return `hsl(${Math.round(hsl.h)}, ${Math.round(hsl.s)}%, ${Math.round(hsl.l)}%)`;\n }\n case \"lab\": {\n const lab = rgbToLab(rgb);\n return `lab(${lab.l.toFixed(2)}, ${lab.a.toFixed(2)}, ${lab.b.toFixed(2)})`;\n }\n case \"rgb\":\n return `rgb(${Math.round(rgb.r)}, ${Math.round(rgb.g)}, ${Math.round(rgb.b)})`;\n default:\n return `Invalid format: ${args.to}`;\n }\n },\n name: \"convert_color\",\n parameters: z.object({\n color: z.string().describe(\"Color to convert (hex, rgb(), or hsl())\"),\n to: z.enum([\"hex\", \"rgb\", \"hsl\", \"lab\", \"hct\"]).describe(\"Target format\"),\n }),\n};\n","/**\n * Color Distance Tool\n * Calculate perceptual distance between two colors using various metrics\n */\n\nimport { z } from \"zod\";\n\nimport { colorDistance, parseColor } from \"../color/index.js\";\n\nexport const colorDistanceTool = {\n description:\n \"Calculate perceptual distance between two colors using Delta E 2000\",\n execute: async (args: {\n color1: string;\n color2: string;\n metric?: \"deltaE2000\" | \"deltaE76\" | \"deltaE94\" | \"euclidean\" | \"weighted\";\n }) => {\n const rgb1 = parseColor(args.color1);\n const rgb2 = parseColor(args.color2);\n\n if (!rgb1 || !rgb2) {\n return `Invalid color format: ${!rgb1 ? args.color1 : args.color2}`;\n }\n\n const distance = colorDistance(rgb1, rgb2, {\n metric: args.metric || \"deltaE2000\",\n });\n\n return `Distance between ${args.color1} and ${args.color2}: ${distance.toFixed(2)}`;\n },\n name: \"color_distance\",\n parameters: z.object({\n color1: z.string().describe(\"First color (hex, rgb, or hsl)\"),\n color2: z.string().describe(\"Second color (hex, rgb, or hsl)\"),\n metric: z\n .enum([\"euclidean\", \"deltaE76\", \"deltaE94\", \"deltaE2000\", \"weighted\"])\n .optional()\n .default(\"deltaE2000\")\n .describe(\"Distance metric to use\"),\n }),\n};\n","/**\n * Contrast Checker Tool\n * Check contrast between two colors using WCAG 2.x luminance ratio,\n * APCA (WCAG 3 draft), or both.\n */\n\nimport { z } from \"zod\";\n\nimport { apcaContrast, apcaLevel } from \"../color/apca.js\";\nimport { getContrastRatio, parseColor } from \"../color/index.js\";\n\nexport const contrastCheckerTool = {\n description:\n \"Check contrast between two colors. Supports WCAG 2.x luminance ratio (default), APCA Lc (WCAG 3 draft), or both algorithms side-by-side.\",\n execute: async (args: {\n algorithm?: \"apca\" | \"both\" | \"wcag\";\n background: string;\n foreground: string;\n }) => {\n const fg = parseColor(args.foreground);\n const bg = parseColor(args.background);\n\n if (!fg || !bg) {\n return `Invalid color format: ${!fg ? args.foreground : args.background}`;\n }\n\n const algorithm = args.algorithm ?? \"wcag\";\n\n const wcagBlock = () => {\n const ratio = getContrastRatio(fg, bg);\n const aaLarge = ratio >= 3;\n const aa = ratio >= 4.5;\n const aaaLarge = ratio >= 4.5;\n const aaa = ratio >= 7;\n return `## WCAG 2.x luminance ratio\nContrast Ratio: ${ratio.toFixed(2)}:1\n- AA (normal text): ${aa ? \"✓ Pass\" : \"✗ Fail\"} (need 4.5:1)\n- AA (large text): ${aaLarge ? \"✓ Pass\" : \"✗ Fail\"} (need 3:1)\n- AAA (normal text): ${aaa ? \"✓ Pass\" : \"✗ Fail\"} (need 7:1)\n- AAA (large text): ${aaaLarge ? \"✓ Pass\" : \"✗ Fail\"} (need 4.5:1)`;\n };\n\n const apcaBlock = () => {\n const lc = apcaContrast(fg, bg);\n const level = apcaLevel(lc);\n const polarity =\n lc > 0\n ? \"dark text on light bg\"\n : lc < 0\n ? \"light text on dark bg\"\n : \"no contrast\";\n return `## APCA (WCAG 3 draft)\nLc: ${lc.toFixed(1)} (${polarity})\n- Body text (|Lc| ≥ 75): ${level.body ? \"✓ Pass\" : \"✗ Fail\"}\n- Content text (|Lc| ≥ 60): ${level.content ? \"✓ Pass\" : \"✗ Fail\"}\n- Large text (|Lc| ≥ 45): ${level.large ? \"✓ Pass\" : \"✗ Fail\"}\n- Spot / non-content (|Lc| ≥ 30): ${level.spot ? \"✓ Pass\" : \"✗ Fail\"}`;\n };\n\n if (algorithm === \"wcag\") return wcagBlock();\n if (algorithm === \"apca\") return apcaBlock();\n return `${wcagBlock()}\\n\\n${apcaBlock()}`;\n },\n name: \"check_contrast\",\n parameters: z.object({\n algorithm: z\n .enum([\"wcag\", \"apca\", \"both\"])\n .optional()\n .default(\"wcag\")\n .describe(\n \"Contrast algorithm: 'wcag' (WCAG 2.x ratio), 'apca' (Lc, WCAG 3 draft), or 'both'\",\n ),\n background: z.string().describe(\"Background color\"),\n foreground: z.string().describe(\"Foreground/text color\"),\n }),\n};\n","/**\n * APCA — Accessible Perceptual Contrast Algorithm (WCAG 3 draft)\n *\n * Implementation of APCA W3 0.1.9 / SAPC by Andrew Somers (Myndex).\n * Returns Lc, an absolute contrast value typically in the range [-108, +106].\n * Sign indicates polarity: positive when text is darker than background\n * (\"dark on light\"), negative for light text on dark background. The magnitude\n * (|Lc|) maps to readability thresholds via APCA's \"Bronze Simple Tables\":\n *\n * |Lc| >= 75 body text\n * |Lc| >= 60 content text\n * |Lc| >= 45 large fluent text\n * |Lc| >= 30 non-content / spot text\n * |Lc| < 15 invisible — fails for any text use\n *\n * Reference: https://github.com/Myndex/SAPC-APCA\n */\n\nimport type { RGB } from \"./types.js\";\n\n// APCA constants (W3-0.1.9 4g)\nconst SA98G = {\n blkClmp: 1.414,\n blkThrs: 0.022,\n deltaYmin: 0.0005,\n loBoTclip: -0.6,\n loBoTexp: 0.74,\n loClip: 0.1,\n // Polarity exponents/factors\n normBG: 0.56,\n normTXT: 0.57,\n revBG: 0.62,\n revTXT: 0.65,\n // Soft-clip and scale\n scaleBoW: 1.14,\n scaleWoB: 1.14,\n trailingW: 0.027,\n} as const;\n\nconst sRGBtrc = 2.4;\nconst Rco = 0.2126729;\nconst Gco = 0.7151522;\nconst Bco = 0.072175;\n\n/**\n * Compute APCA Lc for foreground text on background.\n * `text` is the text/foreground color, `bg` is the background color.\n */\nexport function apcaContrast(text: RGB, bg: RGB): number {\n let txtY = apcaY(text);\n let bgY = apcaY(bg);\n\n // Soft black clamp\n if (txtY <= SA98G.blkThrs) {\n txtY += Math.pow(SA98G.blkThrs - txtY, SA98G.blkClmp);\n }\n if (bgY <= SA98G.blkThrs) {\n bgY += Math.pow(SA98G.blkThrs - bgY, SA98G.blkClmp);\n }\n\n if (Math.abs(bgY - txtY) < SA98G.deltaYmin) return 0;\n\n let outputContrast: number;\n\n if (bgY > txtY) {\n // Normal polarity (dark text on light background) — positive Lc\n const SAPC =\n (Math.pow(bgY, SA98G.normBG) - Math.pow(txtY, SA98G.normTXT)) *\n SA98G.scaleBoW;\n outputContrast = SAPC < SA98G.loClip ? 0 : SAPC - SA98G.trailingW;\n } else {\n // Reverse polarity (light text on dark background) — negative Lc\n const SAPC =\n (Math.pow(bgY, SA98G.revBG) - Math.pow(txtY, SA98G.revTXT)) *\n SA98G.scaleWoB;\n outputContrast = SAPC > -SA98G.loClip ? 0 : SAPC + SA98G.trailingW;\n }\n\n return outputContrast * 100;\n}\n\n/**\n * Classify an APCA Lc value against the Bronze Simple level thresholds.\n */\nexport function apcaLevel(lc: number): {\n body: boolean;\n content: boolean;\n large: boolean;\n spot: boolean;\n} {\n const abs = Math.abs(lc);\n return {\n body: abs >= 75,\n content: abs >= 60,\n large: abs >= 45,\n spot: abs >= 30,\n };\n}\n\nfunction apcaY(rgb: RGB): number {\n const r = Math.pow(rgb.r / 255, sRGBtrc);\n const g = Math.pow(rgb.g / 255, sRGBtrc);\n const b = Math.pow(rgb.b / 255, sRGBtrc);\n return Rco * r + Gco * g + Bco * b;\n}\n","/**\n * MCP Tools for Dislike Color Analysis\n * Identifies and fixes universally disliked colors based on color psychology research\n */\n\nimport { z } from \"zod\";\n\nimport { DislikeAnalyzer } from \"../color/dislike/dislike-analyzer.js\";\nimport { Hct } from \"../color/hct/hct-class.js\";\nimport { parseColor, rgbToArgb } from \"../color/index.js\";\n\n/**\n * Analyze if a color is universally disliked\n */\nexport const analyzeColorLikabilityTool = {\n description:\n \"Check if a color is universally disliked (dark yellow-green associated with biological waste) and get a fixed version if needed\",\n execute: async (args: { autoFix?: boolean; color: string }) => {\n const { autoFix = true, color } = args;\n\n try {\n // Parse the input color\n const rgb = parseColor(color);\n if (!rgb) {\n return `Error: Invalid color format: ${color}`;\n }\n\n // Convert to HCT for analysis\n const argb = rgbToArgb(rgb);\n const hct = Hct.fromInt(argb);\n\n // Check if disliked\n const isDisliked = DislikeAnalyzer.isDisliked(hct);\n\n let output = `# Color Likability Analysis\\n\\n`;\n output += `## Input Color: ${color}\\n\\n`;\n output += `### HCT Values\\n`;\n output += `- Hue: ${hct.hue.toFixed(1)}°\\n`;\n output += `- Chroma: ${hct.chroma.toFixed(1)}\\n`;\n output += `- Tone: ${hct.tone.toFixed(1)}\\n\\n`;\n\n output += `### Analysis Result\\n`;\n\n if (isDisliked) {\n output += `⚠️ **This color is universally disliked**\\n\\n`;\n output += `This color falls in the \"bile zone\" - dark yellow-greens that are universally associated with biological waste and rotting food.\\n\\n`;\n output += `**Reason:**\\n`;\n output += `- Hue is in yellow-green range (90-111°): ${Math.round(hct.hue)}°\\n`;\n output += `- Chroma is above threshold (>16): ${Math.round(hct.chroma)}\\n`;\n output += `- Tone is dark (<65): ${Math.round(hct.tone)}\\n\\n`;\n\n if (autoFix) {\n const fixed = DislikeAnalyzer.fixIfDisliked(hct);\n const fixedArgb = fixed.toInt();\n const fixedHex =\n \"#\" +\n [\n (fixedArgb >> 16) & 0xff,\n (fixedArgb >> 8) & 0xff,\n fixedArgb & 0xff,\n ]\n .map((x) => x.toString(16).padStart(2, \"0\"))\n .join(\"\");\n\n output += `### Recommended Fix\\n`;\n output += `**Fixed Color:** ${fixedHex}\\n`;\n output += `- Hue: ${fixed.hue.toFixed(1)}° (preserved)\\n`;\n output += `- Chroma: ${fixed.chroma.toFixed(1)} (preserved)\\n`;\n output += `- Tone: ${fixed.tone.toFixed(1)} (lightened to 70)\\n\\n`;\n output += `The fix preserves the hue and saturation but lightens the color to make it more pleasant.\\n`;\n }\n } else {\n output += `✅ **This color is likable**\\n\\n`;\n output += `This color does not fall in the universally disliked range.\\n`;\n\n // Provide context about why it's liked\n if (Math.round(hct.hue) >= 90 && Math.round(hct.hue) <= 111) {\n if (Math.round(hct.chroma) <= 16) {\n output += `- Although in yellow-green hue range, the low chroma (${Math.round(hct.chroma)}) makes it neutral and acceptable.\\n`;\n } else if (Math.round(hct.tone) >= 65) {\n output += `- Although in yellow-green hue range, the light tone (${Math.round(hct.tone)}) makes it pleasant.\\n`;\n }\n } else {\n output += `- Hue (${Math.round(hct.hue)}°) is outside the problematic yellow-green range.\\n`;\n }\n }\n\n return output;\n } catch (error) {\n return `Error analyzing color: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n name: \"analyze_color_likability\",\n parameters: z.object({\n autoFix: z\n .boolean()\n .optional()\n .default(true)\n .describe(\"Automatically return fixed version if disliked\"),\n color: z.string().describe(\"Color to analyze (hex, rgb, hsl, etc.)\"),\n }),\n};\n\n/**\n * Fix multiple disliked colors in a batch\n */\ntype BatchHct =\n | { c: number; h: number; t: number }\n | {\n fixed: { c: number; h: number; t: number };\n original: { c: number; h: number; t: number };\n };\n\nexport const fixDislikedColorsBatchTool = {\n description: \"Analyze and fix multiple colors, returning only liked versions\",\n execute: async (args: { colors: string[]; includeAnalysis?: boolean }) => {\n const { colors, includeAnalysis = false } = args;\n\n try {\n const results: Array<{\n error?: string;\n fixed?: string;\n hct?: BatchHct;\n original: string;\n wasDisliked?: boolean;\n }> = [];\n let dislikedCount = 0;\n\n for (const color of colors) {\n const rgb = parseColor(color);\n if (!rgb) {\n results.push({\n error: \"Invalid color format\",\n original: color,\n });\n continue;\n }\n\n const argb = rgbToArgb(rgb);\n const hct = Hct.fromInt(argb);\n const isDisliked = DislikeAnalyzer.isDisliked(hct);\n\n if (isDisliked) {\n dislikedCount++;\n const fixed = DislikeAnalyzer.fixIfDisliked(hct);\n const fixedArgb = fixed.toInt();\n const fixedHex =\n \"#\" +\n [\n (fixedArgb >> 16) & 0xff,\n (fixedArgb >> 8) & 0xff,\n fixedArgb & 0xff,\n ]\n .map((x) => x.toString(16).padStart(2, \"0\"))\n .join(\"\");\n\n results.push({\n fixed: fixedHex,\n hct: includeAnalysis\n ? {\n fixed: { c: fixed.chroma, h: fixed.hue, t: fixed.tone },\n original: { c: hct.chroma, h: hct.hue, t: hct.tone },\n }\n : undefined,\n original: color,\n wasDisliked: true,\n });\n } else {\n results.push({\n fixed: color,\n hct: includeAnalysis\n ? {\n c: hct.chroma,\n h: hct.hue,\n t: hct.tone,\n }\n : undefined,\n original: color,\n wasDisliked: false,\n });\n }\n }\n\n let output = `# Batch Color Likability Analysis\\n\\n`;\n output += `## Summary\\n`;\n output += `- Total colors: ${colors.length}\\n`;\n output += `- Disliked colors found: ${dislikedCount}\\n`;\n output += `- Percentage disliked: ${((dislikedCount / colors.length) * 100).toFixed(1)}%\\n\\n`;\n\n output += `## Results\\n\\n`;\n\n for (const result of results) {\n if (result.error) {\n output += `- **${result.original}**: ❌ ${result.error}\\n`;\n } else if (result.wasDisliked) {\n output += `- **${result.original}** → **${result.fixed}** (fixed)\\n`;\n if (includeAnalysis && result.hct && \"original\" in result.hct) {\n const { fixed, original } = result.hct;\n output += ` - Original HCT: (${original.h.toFixed(0)}°, ${original.c.toFixed(0)}, ${original.t.toFixed(0)})\\n`;\n output += ` - Fixed HCT: (${fixed.h.toFixed(0)}°, ${fixed.c.toFixed(0)}, ${fixed.t.toFixed(0)})\\n`;\n }\n } else {\n output += `- **${result.original}** ✓ (already liked)\\n`;\n if (includeAnalysis && result.hct && \"h\" in result.hct) {\n const { c, h, t } = result.hct;\n output += ` - HCT: (${h.toFixed(0)}°, ${c.toFixed(0)}, ${t.toFixed(0)})\\n`;\n }\n }\n }\n\n if (dislikedCount > 0) {\n output += `\\n## Note\\n`;\n output += `Disliked colors have been automatically fixed by lightening their tone to 70 while preserving hue and chroma. `;\n output += `This makes them more pleasant while maintaining their essential character.\\n`;\n }\n\n return output;\n } catch (error) {\n return `Error processing colors: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n name: \"fix_disliked_colors_batch\",\n parameters: z.object({\n colors: z\n .array(z.string())\n .min(1)\n .describe(\"Array of colors to analyze (hex, rgb, hsl, etc.)\"),\n includeAnalysis: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Include detailed analysis for each color\"),\n }),\n};\n","import { z } from \"zod\";\n\nimport { Hct } from \"../color/hct/index.js\";\nimport {\n hslToRgb,\n labToRgb,\n parseColor,\n rgbToHex,\n rgbToHsl,\n rgbToLab,\n} from \"../color/index.js\";\nimport { RGB } from \"../color/types.js\";\n\nexport const gradientGeneratorTool = {\n description:\n \"Generate a smooth gradient between colors with multiple interpolation methods\",\n execute: async (args: {\n colors: string[];\n easing?: \"ease-in-out\" | \"ease-in\" | \"ease-out\" | \"linear\";\n format?: \"array\" | \"css-linear\" | \"css-radial\" | \"hex\";\n interpolation?: \"hct\" | \"hsl\" | \"lab\" | \"lch\" | \"rgb\";\n steps: number;\n }) => {\n const {\n colors,\n easing = \"linear\",\n format = \"array\",\n interpolation = \"lab\",\n steps,\n } = args;\n\n if (colors.length < 2) {\n return \"Error: At least 2 colors are required for a gradient\";\n }\n\n // Parse input colors\n const parsedColors: RGB[] = [];\n for (const color of colors) {\n const parsed = parseColor(color);\n if (!parsed) {\n return `Invalid color format: ${color}`;\n }\n parsedColors.push(parsed);\n }\n\n // Apply easing function\n const applyEasing = (t: number): number => {\n switch (easing) {\n case \"ease-in\":\n return t * t;\n case \"ease-in-out\":\n return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;\n case \"ease-out\":\n return t * (2 - t);\n default:\n return t;\n }\n };\n\n // Generate gradient colors\n const gradient: RGB[] = [];\n const segmentSteps = Math.floor(steps / (colors.length - 1));\n const extraSteps = steps % (colors.length - 1);\n\n for (let segment = 0; segment < colors.length - 1; segment++) {\n const start = parsedColors[segment];\n const end = parsedColors[segment + 1];\n const currentSteps = segmentSteps + (segment < extraSteps ? 1 : 0);\n\n for (let step = 0; step < currentSteps; step++) {\n const t = applyEasing(step / currentSteps);\n\n let interpolatedColor: RGB;\n\n switch (interpolation) {\n case \"hct\": {\n // HCT interpolation (Material Design color space)\n const startHct = Hct.fromInt(\n (255 << 24) | (start.r << 16) | (start.g << 8) | start.b,\n );\n const endHct = Hct.fromInt(\n (255 << 24) | (end.r << 16) | (end.g << 8) | end.b,\n );\n\n // Interpolate hue (shortest path)\n let hueDiff = endHct.hue - startHct.hue;\n if (hueDiff > 180) hueDiff -= 360;\n if (hueDiff < -180) hueDiff += 360;\n\n const interpolatedHct = Hct.from(\n (startHct.hue + hueDiff * t + 360) % 360,\n startHct.chroma + (endHct.chroma - startHct.chroma) * t,\n startHct.tone + (endHct.tone - startHct.tone) * t,\n );\n\n const argb = interpolatedHct.toInt();\n interpolatedColor = {\n b: argb & 0xff,\n g: (argb >> 8) & 0xff,\n r: (argb >> 16) & 0xff,\n };\n break;\n }\n\n case \"hsl\": {\n // HSL interpolation\n const startHsl = rgbToHsl(start);\n const endHsl = rgbToHsl(end);\n\n // Handle hue interpolation (shortest path)\n let hueDiff = endHsl.h - startHsl.h;\n if (hueDiff > 180) hueDiff -= 360;\n if (hueDiff < -180) hueDiff += 360;\n\n interpolatedColor = hslToRgb({\n h: (startHsl.h + hueDiff * t + 360) % 360,\n l: startHsl.l + (endHsl.l - startHsl.l) * t,\n s: startHsl.s + (endHsl.s - startHsl.s) * t,\n });\n break;\n }\n\n case \"lab\": {\n // LAB interpolation (perceptually uniform)\n const startLab = rgbToLab(start);\n const endLab = rgbToLab(end);\n\n interpolatedColor = labToRgb({\n a: startLab.a + (endLab.a - startLab.a) * t,\n b: startLab.b + (endLab.b - startLab.b) * t,\n l: startLab.l + (endLab.l - startLab.l) * t,\n });\n break;\n }\n\n case \"lch\": {\n // LCH interpolation (cylindrical LAB)\n const startLab = rgbToLab(start);\n const endLab = rgbToLab(end);\n\n // Convert LAB to LCH\n const startL = startLab.l;\n const startC = Math.sqrt(\n startLab.a * startLab.a + startLab.b * startLab.b,\n );\n const startH = (Math.atan2(startLab.b, startLab.a) * 180) / Math.PI;\n\n const endL = endLab.l;\n const endC = Math.sqrt(endLab.a * endLab.a + endLab.b * endLab.b);\n const endH = (Math.atan2(endLab.b, endLab.a) * 180) / Math.PI;\n\n // Interpolate in LCH\n let hueDiff = endH - startH;\n if (hueDiff > 180) hueDiff -= 360;\n if (hueDiff < -180) hueDiff += 360;\n\n const l = startL + (endL - startL) * t;\n const c = startC + (endC - startC) * t;\n const h = ((startH + hueDiff * t) * Math.PI) / 180;\n\n // Convert back to LAB then RGB\n interpolatedColor = labToRgb({\n a: c * Math.cos(h),\n b: c * Math.sin(h),\n l: l,\n });\n break;\n }\n\n case \"rgb\": {\n // Simple RGB interpolation\n interpolatedColor = {\n b: Math.round(start.b + (end.b - start.b) * t),\n g: Math.round(start.g + (end.g - start.g) * t),\n r: Math.round(start.r + (end.r - start.r) * t),\n };\n break;\n }\n\n default:\n interpolatedColor = start; // Fallback\n }\n\n gradient.push(interpolatedColor);\n }\n }\n\n // Add the last color\n gradient.push(parsedColors[parsedColors.length - 1]);\n\n // Format output\n const hexColors = gradient.map(rgbToHex);\n\n switch (format) {\n case \"css-linear\": {\n const stops = hexColors.map((color, i) => {\n const percent = (i / (hexColors.length - 1)) * 100;\n return `${color} ${percent.toFixed(1)}%`;\n });\n return `linear-gradient(90deg, ${stops.join(\", \")})`;\n }\n\n case \"css-radial\": {\n const stops = hexColors.map((color, i) => {\n const percent = (i / (hexColors.length - 1)) * 100;\n return `${color} ${percent.toFixed(1)}%`;\n });\n return `radial-gradient(circle, ${stops.join(\", \")})`;\n }\n\n case \"hex\":\n return hexColors.join(\", \");\n\n case \"array\":\n default:\n return `Generated gradient with ${steps} steps:\n${hexColors.map((color, i) => `${i + 1}. ${color}`).join(\"\\n\")}\n\nInterpolation: ${interpolation}\nEasing: ${easing}\nInput colors: ${colors.join(\" → \")}`;\n }\n },\n name: \"generate_gradient\",\n parameters: z.object({\n colors: z\n .array(z.string())\n .min(2)\n .describe(\"Colors to create gradient between (minimum 2)\"),\n easing: z\n .enum([\"linear\", \"ease-in\", \"ease-out\", \"ease-in-out\"])\n .default(\"linear\")\n .describe(\"Easing function for gradient transition\"),\n format: z\n .enum([\"hex\", \"css-linear\", \"css-radial\", \"array\"])\n .default(\"array\")\n .describe(\"Output format for the gradient\"),\n interpolation: z\n .enum([\"rgb\", \"hsl\", \"lab\", \"lch\", \"hct\"])\n .default(\"lab\")\n .describe(\n \"Color space for interpolation (lab/lch/hct are perceptually smooth)\",\n ),\n steps: z\n .number()\n .min(3)\n .max(100)\n .describe(\"Number of colors in the gradient\"),\n }),\n};\n","/**\n * MCP tools for image color extraction\n */\n\nimport { z } from \"zod\";\n\nimport {\n extractColors,\n ExtractedColor,\n extractThemePalette,\n} from \"../color/extract-colors.js\";\nimport { generateMaterialTheme } from \"../color/material-theme.js\";\n\nconst imageDataSchema = z\n .object({\n data: z.array(z.number()).describe(\"Flat array of RGBA values (0-255)\"),\n height: z.number().int().positive().describe(\"Image height in pixels\"),\n width: z.number().int().positive().describe(\"Image width in pixels\"),\n })\n .describe(\"Image data with RGBA values\");\n\ntype ImageDataInput = z.infer<typeof imageDataSchema>;\n\n/**\n * Extract dominant colors from image data\n */\nexport const extractImageColorsTool = {\n description:\n \"Extract dominant colors from an image. Input should be image data as an array of RGBA values.\",\n execute: async (args: {\n format?: \"css\" | \"json\" | \"palette\";\n imageData: ImageDataInput;\n maxColors?: number;\n quality?: \"high\" | \"low\" | \"medium\";\n }) => {\n const {\n format = \"json\",\n imageData,\n maxColors = 5,\n quality = \"medium\",\n } = args;\n\n try {\n const data = new Uint8ClampedArray(imageData.data);\n\n const processedImageData = {\n data,\n height: imageData.height,\n width: imageData.width,\n };\n\n // Extract colors\n const colors = extractColors(processedImageData, {\n filter: true,\n maxColors,\n quality,\n scoringEnabled: true,\n });\n\n // Format output based on requested format\n switch (format) {\n case \"css\":\n return formatAsCSS(colors);\n\n case \"palette\":\n return formatAsPalette(colors);\n\n case \"json\":\n default:\n return formatAsJSON(colors);\n }\n } catch (error) {\n return `Error extracting colors: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n name: \"extract_image_colors\",\n parameters: z.object({\n format: z\n .enum([\"json\", \"css\", \"palette\"])\n .optional()\n .default(\"json\")\n .describe(\"Output format\"),\n imageData: imageDataSchema,\n maxColors: z\n .number()\n .int()\n .min(1)\n .max(20)\n .optional()\n .default(5)\n .describe(\"Maximum number of colors to extract\"),\n quality: z\n .enum([\"low\", \"medium\", \"high\"])\n .optional()\n .default(\"medium\")\n .describe(\"Extraction quality\"),\n }),\n};\n\n/**\n * Generate a Material Design theme from an image\n */\nexport const generateThemeFromImageTool = {\n description: \"Generate a complete Material Design 3 theme from an image\",\n execute: async (args: {\n imageData: ImageDataInput;\n includeCustomColors?: boolean;\n isDark?: boolean;\n }) => {\n const { imageData, includeCustomColors = true, isDark = false } = args;\n\n try {\n const data = new Uint8ClampedArray(imageData.data);\n\n const processedImageData = {\n data,\n height: imageData.height,\n width: imageData.width,\n };\n\n // Extract theme palette\n const palette = extractThemePalette(processedImageData);\n\n // Convert primary color to hex for theme generation\n const sourceColor = palette.primary.hex;\n\n // Generate Material theme\n const theme = generateMaterialTheme(sourceColor, { isDark });\n\n // Add custom colors from extracted palette\n if (includeCustomColors && palette.secondary) {\n theme.customColors = {\n secondary: {\n color: palette.secondary.hex,\n hct: palette.secondary.hct,\n population: palette.secondary.population,\n },\n };\n\n if (palette.tertiary) {\n theme.customColors.tertiary = {\n color: palette.tertiary.hex,\n hct: palette.tertiary.hct,\n population: palette.tertiary.population,\n };\n }\n }\n\n // Format output\n let output = `# Material Design 3 Theme from Image\\n\\n`;\n output += `## Source Colors\\n`;\n output += `- Primary: ${palette.primary.hex} (${palette.primary.percentage.toFixed(1)}%)\\n`;\n\n if (palette.secondary) {\n output += `- Secondary: ${palette.secondary.hex} (${palette.secondary.percentage.toFixed(1)}%)\\n`;\n }\n if (palette.tertiary) {\n output += `- Tertiary: ${palette.tertiary.hex} (${palette.tertiary.percentage.toFixed(1)}%)\\n`;\n }\n\n output += `\\n## Theme Colors (${isDark ? \"Dark\" : \"Light\"} Mode)\\n\\n`;\n output += `### Primary\\n`;\n output += `- primary: ${theme.schemes[isDark ? \"dark\" : \"light\"].primary}\\n`;\n output += `- onPrimary: ${theme.schemes[isDark ? \"dark\" : \"light\"].onPrimary}\\n`;\n output += `- primaryContainer: ${theme.schemes[isDark ? \"dark\" : \"light\"].primaryContainer}\\n`;\n output += `- onPrimaryContainer: ${theme.schemes[isDark ? \"dark\" : \"light\"].onPrimaryContainer}\\n`;\n\n output += `\\n### Surface\\n`;\n output += `- surface: ${theme.schemes[isDark ? \"dark\" : \"light\"].surface}\\n`;\n output += `- onSurface: ${theme.schemes[isDark ? \"dark\" : \"light\"].onSurface}\\n`;\n output += `- surfaceVariant: ${theme.schemes[isDark ? \"dark\" : \"light\"].surfaceVariant}\\n`;\n output += `- onSurfaceVariant: ${theme.schemes[isDark ? \"dark\" : \"light\"].onSurfaceVariant}\\n`;\n\n output += `\\n### Background\\n`;\n output += `- background: ${theme.schemes[isDark ? \"dark\" : \"light\"].background}\\n`;\n output += `- onBackground: ${theme.schemes[isDark ? \"dark\" : \"light\"].onBackground}\\n`;\n\n return output;\n } catch (error) {\n return `Error generating theme: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n name: \"generate_theme_from_image\",\n parameters: z.object({\n imageData: imageDataSchema,\n includeCustomColors: z\n .boolean()\n .optional()\n .default(true)\n .describe(\"Include custom colors from image\"),\n isDark: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Generate dark theme (false for light theme)\"),\n }),\n};\n\n// Helper functions for formatting\n\nfunction formatAsCSS(colors: ExtractedColor[]): string {\n let css = \":root {\\n\";\n colors.forEach((color, index) => {\n css += ` --extracted-color-${index + 1}: ${color.hex}; /* ${color.percentage.toFixed(1)}% */\\n`;\n });\n css += \"}\\n\\n\";\n\n css += \"/* Color Details */\\n\";\n colors.forEach((color, index) => {\n css += `/* Color ${index + 1}: ${color.hex}\\n`;\n css += ` RGB: rgb(${color.rgb.r}, ${color.rgb.g}, ${color.rgb.b})\\n`;\n css += ` HCT: hct(${color.hct.h.toFixed(1)}, ${color.hct.c.toFixed(1)}, ${color.hct.t.toFixed(1)})\\n`;\n css += ` Population: ${color.percentage.toFixed(1)}%\\n`;\n css += `*/\\n\\n`;\n });\n\n return css;\n}\n\nfunction formatAsJSON(colors: ExtractedColor[]): string {\n return JSON.stringify(colors, null, 2);\n}\n\nfunction formatAsPalette(colors: ExtractedColor[]): string {\n let output = \"# Extracted Color Palette\\n\\n\";\n\n colors.forEach((color, index) => {\n output += `## Color ${index + 1}\\n`;\n output += `- Hex: ${color.hex}\\n`;\n output += `- RGB: rgb(${color.rgb.r}, ${color.rgb.g}, ${color.rgb.b})\\n`;\n output += `- HCT: H:${color.hct.h.toFixed(1)}° C:${color.hct.c.toFixed(1)} T:${color.hct.t.toFixed(1)}\\n`;\n output += `- Usage: ${color.percentage.toFixed(1)}%\\n\\n`;\n });\n\n return output;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// This file is automatically generated. Do not modify it.\n\n/**\n * Utility methods for mathematical operations.\n */\n\n/**\n * Clamps an integer between two floating-point numbers.\n *\n * @return input when min <= input <= max, and either min or max\n * otherwise.\n */\nexport function clampDouble(min: number, max: number, input: number): number {\n if (input < min) {\n return min;\n } else if (input > max) {\n return max;\n }\n\n return input;\n}\n\n/**\n * Clamps an integer between two integers.\n *\n * @return input when min <= input <= max, and either min or max\n * otherwise.\n */\nexport function clampInt(min: number, max: number, input: number): number {\n if (input < min) {\n return min;\n } else if (input > max) {\n return max;\n }\n\n return input;\n}\n\n/**\n * Distance of two points on a circle, represented using degrees.\n */\nexport function differenceDegrees(a: number, b: number): number {\n return 180.0 - Math.abs(Math.abs(a - b) - 180.0);\n}\n\n/**\n * The linear interpolation function.\n *\n * @return start if amount = 0 and stop if amount = 1\n */\nexport function lerp(start: number, stop: number, amount: number): number {\n return (1.0 - amount) * start + amount * stop;\n}\n\n/**\n * Multiplies a 1x3 row vector with a 3x3 matrix.\n */\nexport function matrixMultiply(row: number[], matrix: number[][]): number[] {\n const a =\n row[0] * matrix[0][0] + row[1] * matrix[0][1] + row[2] * matrix[0][2];\n const b =\n row[0] * matrix[1][0] + row[1] * matrix[1][1] + row[2] * matrix[1][2];\n const c =\n row[0] * matrix[2][0] + row[1] * matrix[2][1] + row[2] * matrix[2][2];\n return [a, b, c];\n}\n\n/**\n * Sign of direction change needed to travel from one angle to\n * another.\n *\n * For angles that are 180 degrees apart from each other, both\n * directions have the same travel distance, so either direction is\n * shortest. The value 1.0 is returned in this case.\n *\n * @param from The angle travel starts from, in degrees.\n * @param to The angle travel ends at, in degrees.\n * @return -1 if decreasing from leads to the shortest travel\n * distance, 1 if increasing from leads to the shortest travel\n * distance.\n */\nexport function rotationDirection(from: number, to: number): number {\n const increasingDifference = sanitizeDegreesDouble(to - from);\n return increasingDifference <= 180.0 ? 1.0 : -1.0;\n}\n\n/**\n * Sanitizes a degree measure as a floating-point number.\n *\n * @return a degree measure between 0.0 (inclusive) and 360.0\n * (exclusive).\n */\nexport function sanitizeDegreesDouble(degrees: number): number {\n degrees = degrees % 360.0;\n if (degrees < 0) {\n degrees = degrees + 360.0;\n }\n return degrees;\n}\n\n/**\n * Sanitizes a degree measure as an integer.\n *\n * @return a degree measure between 0 (inclusive) and 360\n * (exclusive).\n */\nexport function sanitizeDegreesInt(degrees: number): number {\n degrees = degrees % 360;\n if (degrees < 0) {\n degrees = degrees + 360;\n }\n return degrees;\n}\n\n/**\n * The signum function.\n *\n * @return 1 if num > 0, -1 if num < 0, and 0 if num = 0\n */\nexport function signum(num: number): number {\n if (num < 0) {\n return -1;\n } else if (num === 0) {\n return 0;\n } else {\n return 1;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// This file is automatically generated. Do not modify it.\n\nimport * as mathUtils from \"./math_utils.js\";\n\n/**\n * Color science utilities.\n *\n * Utility methods for color science constants and color space\n * conversions that aren't HCT or CAM16.\n */\n\nconst SRGB_TO_XYZ = [\n [0.41233895, 0.35762064, 0.18051042],\n [0.2126, 0.7152, 0.0722],\n [0.01932141, 0.11916382, 0.95034478],\n];\n\nconst XYZ_TO_SRGB = [\n [3.2413774792388685, -1.5376652402851851, -0.49885366846268053],\n [-0.9691452513005321, 1.8758853451067872, 0.04156585616912061],\n [0.05562093689691305, -0.20395524564742123, 1.0571799111220335],\n];\n\nconst WHITE_POINT_D65 = [95.047, 100.0, 108.883];\n\n/**\n * Returns the alpha component of a color in ARGB format.\n */\nexport function alphaFromArgb(argb: number): number {\n return (argb >> 24) & 255;\n}\n\n/**\n * Converts a color represented in Lab color space into an ARGB\n * integer.\n */\nexport function argbFromLab(l: number, a: number, b: number): number {\n const whitePoint = WHITE_POINT_D65;\n const fy = (l + 16.0) / 116.0;\n const fx = a / 500.0 + fy;\n const fz = fy - b / 200.0;\n const xNormalized = labInvf(fx);\n const yNormalized = labInvf(fy);\n const zNormalized = labInvf(fz);\n const x = xNormalized * whitePoint[0];\n const y = yNormalized * whitePoint[1];\n const z = zNormalized * whitePoint[2];\n return argbFromXyz(x, y, z);\n}\n\n/**\n * Converts a color from linear RGB components to ARGB format.\n */\nexport function argbFromLinrgb(linrgb: number[]): number {\n const r = delinearized(linrgb[0]);\n const g = delinearized(linrgb[1]);\n const b = delinearized(linrgb[2]);\n return argbFromRgb(r, g, b);\n}\n\n/**\n * Converts an L* value to an ARGB representation.\n *\n * @param lstar L* in L*a*b*\n * @return ARGB representation of grayscale color with lightness\n * matching L*\n */\nexport function argbFromLstar(lstar: number): number {\n const y = yFromLstar(lstar);\n const component = delinearized(y);\n return argbFromRgb(component, component, component);\n}\n\n/**\n * Converts a color from RGB components to ARGB format.\n */\nexport function argbFromRgb(red: number, green: number, blue: number): number {\n return (\n ((255 << 24) |\n ((red & 255) << 16) |\n ((green & 255) << 8) |\n (blue & 255)) >>>\n 0\n );\n}\n\n/**\n * Converts a color from ARGB to XYZ.\n */\nexport function argbFromXyz(x: number, y: number, z: number): number {\n const matrix = XYZ_TO_SRGB;\n const linearR = matrix[0][0] * x + matrix[0][1] * y + matrix[0][2] * z;\n const linearG = matrix[1][0] * x + matrix[1][1] * y + matrix[1][2] * z;\n const linearB = matrix[2][0] * x + matrix[2][1] * y + matrix[2][2] * z;\n const r = delinearized(linearR);\n const g = delinearized(linearG);\n const b = delinearized(linearB);\n return argbFromRgb(r, g, b);\n}\n\n/**\n * Returns the blue component of a color in ARGB format.\n */\nexport function blueFromArgb(argb: number): number {\n return argb & 255;\n}\n\n/**\n * Delinearizes an RGB component.\n *\n * @param rgbComponent 0.0 <= rgb_component <= 100.0, represents\n * linear R/G/B channel\n * @return 0 <= output <= 255, color channel converted to regular\n * RGB space\n */\nexport function delinearized(rgbComponent: number): number {\n const normalized = rgbComponent / 100.0;\n let delinearized = 0.0;\n if (normalized <= 0.0031308) {\n delinearized = normalized * 12.92;\n } else {\n delinearized = 1.055 * Math.pow(normalized, 1.0 / 2.4) - 0.055;\n }\n return mathUtils.clampInt(0, 255, Math.round(delinearized * 255.0));\n}\n\n/**\n * Returns the green component of a color in ARGB format.\n */\nexport function greenFromArgb(argb: number): number {\n return (argb >> 8) & 255;\n}\n\n/**\n * Returns whether a color in ARGB format is opaque.\n */\nexport function isOpaque(argb: number): boolean {\n return alphaFromArgb(argb) >= 255;\n}\n\n/**\n * Converts a color from ARGB representation to L*a*b*\n * representation.\n *\n * @param argb the ARGB representation of a color\n * @return a Lab object representing the color\n */\nexport function labFromArgb(argb: number): number[] {\n const linearR = linearized(redFromArgb(argb));\n const linearG = linearized(greenFromArgb(argb));\n const linearB = linearized(blueFromArgb(argb));\n const matrix = SRGB_TO_XYZ;\n const x =\n matrix[0][0] * linearR + matrix[0][1] * linearG + matrix[0][2] * linearB;\n const y =\n matrix[1][0] * linearR + matrix[1][1] * linearG + matrix[1][2] * linearB;\n const z =\n matrix[2][0] * linearR + matrix[2][1] * linearG + matrix[2][2] * linearB;\n const whitePoint = WHITE_POINT_D65;\n const xNormalized = x / whitePoint[0];\n const yNormalized = y / whitePoint[1];\n const zNormalized = z / whitePoint[2];\n const fx = labF(xNormalized);\n const fy = labF(yNormalized);\n const fz = labF(zNormalized);\n const l = 116.0 * fy - 16;\n const a = 500.0 * (fx - fy);\n const b = 200.0 * (fy - fz);\n return [l, a, b];\n}\n\n/**\n * Linearizes an RGB component.\n *\n * @param rgbComponent 0 <= rgb_component <= 255, represents R/G/B\n * channel\n * @return 0.0 <= output <= 100.0, color channel converted to\n * linear RGB space\n */\nexport function linearized(rgbComponent: number): number {\n const normalized = rgbComponent / 255.0;\n if (normalized <= 0.040449936) {\n return (normalized / 12.92) * 100.0;\n } else {\n return Math.pow((normalized + 0.055) / 1.055, 2.4) * 100.0;\n }\n}\n\n/**\n * Computes the L* value of a color in ARGB representation.\n *\n * @param argb ARGB representation of a color\n * @return L*, from L*a*b*, coordinate of the color\n */\nexport function lstarFromArgb(argb: number): number {\n const y = xyzFromArgb(argb)[1];\n return 116.0 * labF(y / 100.0) - 16.0;\n}\n\n/**\n * Converts a Y value to an L* value.\n *\n * L* in L*a*b* and Y in XYZ measure the same quantity, luminance.\n *\n * L* measures perceptual luminance, a linear scale. Y in XYZ\n * measures relative luminance, a logarithmic scale.\n *\n * @param y Y in XYZ\n * @return L* in L*a*b*\n */\nexport function lstarFromY(y: number): number {\n return labF(y / 100.0) * 116.0 - 16.0;\n}\n\n/**\n * Returns the red component of a color in ARGB format.\n */\nexport function redFromArgb(argb: number): number {\n return (argb >> 16) & 255;\n}\n\n/**\n * Returns the standard white point; white on a sunny day.\n *\n * @return The white point\n */\nexport function whitePointD65(): number[] {\n return WHITE_POINT_D65;\n}\n\n/**\n * Converts a color from XYZ to ARGB.\n */\nexport function xyzFromArgb(argb: number): number[] {\n const r = linearized(redFromArgb(argb));\n const g = linearized(greenFromArgb(argb));\n const b = linearized(blueFromArgb(argb));\n return mathUtils.matrixMultiply([r, g, b], SRGB_TO_XYZ);\n}\n\n/**\n * Converts an L* value to a Y value.\n *\n * L* in L*a*b* and Y in XYZ measure the same quantity, luminance.\n *\n * L* measures perceptual luminance, a linear scale. Y in XYZ\n * measures relative luminance, a logarithmic scale.\n *\n * @param lstar L* in L*a*b*\n * @return Y in XYZ\n */\nexport function yFromLstar(lstar: number): number {\n return 100.0 * labInvf((lstar + 16.0) / 116.0);\n}\n\nfunction labF(t: number): number {\n const e = 216.0 / 24389.0;\n const kappa = 24389.0 / 27.0;\n if (t > e) {\n return Math.pow(t, 1.0 / 3.0);\n } else {\n return (kappa * t + 16) / 116;\n }\n}\n\nfunction labInvf(ft: number): number {\n const e = 216.0 / 24389.0;\n const kappa = 24389.0 / 27.0;\n const ft3 = ft * ft * ft;\n if (ft3 > e) {\n return ft3;\n } else {\n return (116 * ft - 16) / kappa;\n }\n}\n","/**\n * Image processing utilities for color extraction\n */\n\nimport * as utils from \"./utils/color_utils.js\";\n\n/**\n * Filter out near-white and near-black pixels\n * @param pixels - Array of ARGB pixels\n * @returns Filtered array\n */\nexport function filterExtremeTones(pixels: number[]): number[] {\n return pixels.filter((pixel) => {\n const r = utils.redFromArgb(pixel);\n const g = utils.greenFromArgb(pixel);\n const b = utils.blueFromArgb(pixel);\n\n // Calculate luminance (rough approximation)\n const luminance = 0.299 * r + 0.587 * g + 0.114 * b;\n\n // Filter out very dark (< 5%) and very light (> 95%) pixels\n return luminance > 12.75 && luminance < 242.25;\n });\n}\n\n/**\n * Convert image data to ARGB pixel array\n * @param imageData - Canvas ImageData or similar structure\n * @returns Array of ARGB colors as 32-bit integers\n */\nexport function imageDataToPixels(imageData: {\n data: number[] | Uint8ClampedArray;\n height: number;\n width: number;\n}): number[] {\n const pixels: number[] = [];\n const data = imageData.data;\n\n // Process RGBA data (4 bytes per pixel)\n for (let i = 0; i < data.length; i += 4) {\n const r = data[i];\n const g = data[i + 1];\n const b = data[i + 2];\n const a = data[i + 3];\n\n // Skip fully transparent pixels\n if (a < 255 * 0.01) continue;\n\n // Convert to ARGB format\n const argb = utils.argbFromRgb(r, g, b);\n pixels.push(argb);\n }\n\n return pixels;\n}\n\n/**\n * Sample pixels from image for faster processing\n * @param pixels - Full array of pixels\n * @param maxPixels - Maximum number of pixels to sample\n * @returns Sampled array of pixels\n */\nexport function samplePixels(\n pixels: number[],\n maxPixels: number = 10000,\n): number[] {\n if (pixels.length <= maxPixels) {\n return pixels;\n }\n\n const sampled: number[] = [];\n const step = Math.ceil(pixels.length / maxPixels);\n\n for (let i = 0; i < pixels.length; i += step) {\n sampled.push(pixels[i]);\n }\n\n return sampled;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as utils from \"../utils/color_utils.js\";\nimport { PointProvider } from \"./point_provider.js\";\n\n/**\n * Provides conversions needed for K-Means quantization. Converting input to\n * points, and converting the final state of the K-Means algorithm to colors.\n */\nexport class LabPointProvider implements PointProvider {\n /**\n * Standard CIE 1976 delta E formula also takes the square root, unneeded\n * here. This method is used by quantization algorithms to compare distance,\n * and the relative ordering is the same, with or without a square root.\n *\n * This relatively minor optimization is helpful because this method is\n * called at least once for each pixel in an image.\n */\n distance(from: number[], to: number[]): number {\n const dL = from[0] - to[0];\n const dA = from[1] - to[1];\n const dB = from[2] - to[2];\n return dL * dL + dA * dA + dB * dB;\n }\n\n /**\n * Convert a color represented in ARGB to a 3-element array of L*a*b*\n * coordinates of the color.\n */\n fromInt(argb: number): number[] {\n return utils.labFromArgb(argb);\n }\n\n /**\n * Convert a 3-element array to a color represented in ARGB.\n */\n toInt(point: number[]): number {\n return utils.argbFromLab(point[0], point[1], point[2]);\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LabPointProvider } from \"./lab_point_provider.js\";\n\nconst MAX_ITERATIONS = 10;\nconst MIN_MOVEMENT_DISTANCE = 3.0;\n\n/**\n * A wrapper for maintaining a table of distances between K-Means clusters.\n */\nclass DistanceAndIndex {\n distance: number = -1;\n index: number = -1;\n}\n\n/**\n * An image quantizer that improves on the speed of a standard K-Means algorithm\n * by implementing several optimizations, including deduping identical pixels\n * and a triangle inequality rule that reduces the number of comparisons needed\n * to identify which cluster a point should be moved to.\n *\n * Wsmeans stands for Weighted Square Means.\n *\n * This algorithm was designed by M. Emre Celebi, and was found in their 2011\n * paper, Improving the Performance of K-Means for Color Quantization.\n * https://arxiv.org/abs/1101.0395\n */\n// material_color_utilities is designed to have a consistent API across\n// platforms and modular components that can be moved around easily. Using a\n// class as a namespace facilitates this.\n//\n// tslint:disable-next-line:class-as-namespace\nexport class QuantizerWsmeans {\n /**\n * @param inputPixels Colors in ARGB format.\n * @param startingClusters Defines the initial state of the quantizer. Passing\n * an empty array is fine, the implementation will create its own initial\n * state that leads to reproducible results for the same inputs.\n * Passing an array that is the result of Wu quantization leads to higher\n * quality results.\n * @param maxColors The number of colors to divide the image into. A lower\n * number of colors may be returned.\n * @return Colors in ARGB format.\n */\n static quantize(\n inputPixels: number[],\n startingClusters: number[],\n maxColors: number,\n ): Map<number, number> {\n const pixelToCount = new Map<number, number>();\n const points = new Array<number[]>();\n const pixels = new Array<number>();\n const pointProvider = new LabPointProvider();\n let pointCount = 0;\n for (let i = 0; i < inputPixels.length; i++) {\n const inputPixel = inputPixels[i];\n const pixelCount = pixelToCount.get(inputPixel);\n if (pixelCount === undefined) {\n pointCount++;\n points.push(pointProvider.fromInt(inputPixel));\n pixels.push(inputPixel);\n pixelToCount.set(inputPixel, 1);\n } else {\n pixelToCount.set(inputPixel, pixelCount + 1);\n }\n }\n\n const counts = new Array<number>();\n for (let i = 0; i < pointCount; i++) {\n const pixel = pixels[i];\n const count = pixelToCount.get(pixel);\n if (count !== undefined) {\n counts[i] = count;\n }\n }\n\n let clusterCount = Math.min(maxColors, pointCount);\n if (startingClusters.length > 0) {\n clusterCount = Math.min(clusterCount, startingClusters.length);\n }\n\n const clusters = new Array<number[]>();\n for (let i = 0; i < startingClusters.length; i++) {\n clusters.push(pointProvider.fromInt(startingClusters[i]));\n }\n const additionalClustersNeeded = clusterCount - clusters.length;\n if (startingClusters.length === 0 && additionalClustersNeeded > 0) {\n for (let i = 0; i < additionalClustersNeeded; i++) {\n const l = Math.random() * 100.0;\n const a = Math.random() * (100.0 - -100.0 + 1) + -100;\n const b = Math.random() * (100.0 - -100.0 + 1) + -100;\n\n clusters.push([l, a, b]);\n }\n }\n\n const clusterIndices = new Array<number>();\n for (let i = 0; i < pointCount; i++) {\n clusterIndices.push(Math.floor(Math.random() * clusterCount));\n }\n\n const indexMatrix = new Array<number[]>();\n for (let i = 0; i < clusterCount; i++) {\n indexMatrix.push(new Array<number>());\n for (let j = 0; j < clusterCount; j++) {\n indexMatrix[i].push(0);\n }\n }\n\n const distanceToIndexMatrix = new Array<DistanceAndIndex[]>();\n for (let i = 0; i < clusterCount; i++) {\n distanceToIndexMatrix.push(new Array<DistanceAndIndex>());\n for (let j = 0; j < clusterCount; j++) {\n distanceToIndexMatrix[i].push(new DistanceAndIndex());\n }\n }\n\n const pixelCountSums = new Array<number>();\n for (let i = 0; i < clusterCount; i++) {\n pixelCountSums.push(0);\n }\n for (let iteration = 0; iteration < MAX_ITERATIONS; iteration++) {\n for (let i = 0; i < clusterCount; i++) {\n for (let j = i + 1; j < clusterCount; j++) {\n const distance = pointProvider.distance(clusters[i], clusters[j]);\n distanceToIndexMatrix[j][i].distance = distance;\n distanceToIndexMatrix[j][i].index = i;\n distanceToIndexMatrix[i][j].distance = distance;\n distanceToIndexMatrix[i][j].index = j;\n }\n distanceToIndexMatrix[i].sort();\n for (let j = 0; j < clusterCount; j++) {\n indexMatrix[i][j] = distanceToIndexMatrix[i][j].index;\n }\n }\n\n let pointsMoved = 0;\n for (let i = 0; i < pointCount; i++) {\n const point = points[i];\n const previousClusterIndex = clusterIndices[i];\n const previousCluster = clusters[previousClusterIndex];\n const previousDistance = pointProvider.distance(point, previousCluster);\n let minimumDistance = previousDistance;\n let newClusterIndex = -1;\n for (let j = 0; j < clusterCount; j++) {\n if (\n distanceToIndexMatrix[previousClusterIndex][j].distance >=\n 4 * previousDistance\n ) {\n continue;\n }\n const distance = pointProvider.distance(point, clusters[j]);\n if (distance < minimumDistance) {\n minimumDistance = distance;\n newClusterIndex = j;\n }\n }\n if (newClusterIndex !== -1) {\n const distanceChange = Math.abs(\n Math.sqrt(minimumDistance) - Math.sqrt(previousDistance),\n );\n if (distanceChange > MIN_MOVEMENT_DISTANCE) {\n pointsMoved++;\n clusterIndices[i] = newClusterIndex;\n }\n }\n }\n\n if (pointsMoved === 0 && iteration !== 0) {\n break;\n }\n\n const componentASums = new Array<number>(clusterCount).fill(0);\n const componentBSums = new Array<number>(clusterCount).fill(0);\n const componentCSums = new Array<number>(clusterCount).fill(0);\n\n for (let i = 0; i < clusterCount; i++) {\n pixelCountSums[i] = 0;\n }\n for (let i = 0; i < pointCount; i++) {\n const clusterIndex = clusterIndices[i];\n const point = points[i];\n const count = counts[i];\n pixelCountSums[clusterIndex] += count;\n componentASums[clusterIndex] += point[0] * count;\n componentBSums[clusterIndex] += point[1] * count;\n componentCSums[clusterIndex] += point[2] * count;\n }\n\n for (let i = 0; i < clusterCount; i++) {\n const count = pixelCountSums[i];\n if (count === 0) {\n clusters[i] = [0.0, 0.0, 0.0];\n continue;\n }\n const a = componentASums[i] / count;\n const b = componentBSums[i] / count;\n const c = componentCSums[i] / count;\n clusters[i] = [a, b, c];\n }\n }\n\n const argbToPopulation = new Map<number, number>();\n for (let i = 0; i < clusterCount; i++) {\n const count = pixelCountSums[i];\n if (count === 0) {\n continue;\n }\n\n const possibleNewCluster = pointProvider.toInt(clusters[i]);\n // Accumulate population counts when multiple clusters converge to same color\n const existingCount = argbToPopulation.get(possibleNewCluster) || 0;\n argbToPopulation.set(possibleNewCluster, existingCount + count);\n }\n return argbToPopulation;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as utils from \"../utils/color_utils.js\";\n\n/**\n * Quantizes an image into a map, with keys of ARGB colors, and values of the\n * number of times that color appears in the image.\n */\n// material_color_utilities is designed to have a consistent API across\n// platforms and modular components that can be moved around easily. Using a\n// class as a namespace facilitates this.\n//\n// tslint:disable-next-line:class-as-namespace\nexport class QuantizerMap {\n /**\n * @param pixels Colors in ARGB format.\n * @return A Map with keys of ARGB colors, and values of the number of times\n * the color appears in the image.\n */\n static quantize(pixels: number[]): Map<number, number> {\n const countByColor = new Map<number, number>();\n for (let i = 0; i < pixels.length; i++) {\n const pixel = pixels[i];\n const alpha = utils.alphaFromArgb(pixel);\n if (alpha < 255) {\n continue;\n }\n countByColor.set(pixel, (countByColor.get(pixel) ?? 0) + 1);\n }\n return countByColor;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as utils from \"../utils/color_utils.js\";\nimport { QuantizerMap } from \"./quantizer_map.js\";\n\nconst INDEX_BITS = 5;\nconst SIDE_LENGTH = 33; // ((1 << INDEX_INDEX_BITS) + 1)\nconst TOTAL_SIZE = 35937; // SIDE_LENGTH * SIDE_LENGTH * SIDE_LENGTH\n\nconst directions = {\n BLUE: \"blue\",\n GREEN: \"green\",\n RED: \"red\",\n};\n\n/**\n * Keeps track of the state of each box created as the Wu quantization\n * algorithm progresses through dividing the image's pixels as plotted in RGB.\n */\nclass Box {\n constructor(\n public r0: number = 0,\n public r1: number = 0,\n public g0: number = 0,\n public g1: number = 0,\n public b0: number = 0,\n public b1: number = 0,\n public vol: number = 0,\n ) {}\n}\n\n/**\n * Represents final result of Wu algorithm.\n */\nclass CreateBoxesResult {\n /**\n * @param requestedCount how many colors the caller asked to be returned from\n * quantization.\n * @param resultCount the actual number of colors achieved from quantization.\n * May be lower than the requested count.\n */\n constructor(\n public requestedCount: number,\n public resultCount: number,\n ) {}\n}\n\n/**\n * Represents the result of calculating where to cut an existing box in such\n * a way to maximize variance between the two new boxes created by a cut.\n */\nclass MaximizeResult {\n constructor(\n public cutLocation: number,\n public maximum: number,\n ) {}\n}\n\n/**\n * An image quantizer that divides the image's pixels into clusters by\n * recursively cutting an RGB cube, based on the weight of pixels in each area\n * of the cube.\n *\n * The algorithm was described by Xiaolin Wu in Graphic Gems II, published in\n * 1991.\n */\nexport class QuantizerWu {\n constructor(\n private weights: number[] = [],\n private momentsR: number[] = [],\n private momentsG: number[] = [],\n private momentsB: number[] = [],\n private moments: number[] = [],\n private cubes: Box[] = [],\n ) {}\n\n /**\n * @param pixels Colors in ARGB format.\n * @param maxColors The number of colors to divide the image into. A lower\n * number of colors may be returned.\n * @return Colors in ARGB format.\n */\n quantize(pixels: number[], maxColors: number): number[] {\n this.constructHistogram(pixels);\n this.computeMoments();\n const createBoxesResult = this.createBoxes(maxColors);\n const results = this.createResult(createBoxesResult.resultCount);\n return results;\n }\n\n private bottom(cube: Box, direction: string, moment: number[]) {\n switch (direction) {\n case directions.BLUE:\n return (\n -moment[this.getIndex(cube.r1, cube.g1, cube.b0)] +\n moment[this.getIndex(cube.r1, cube.g0, cube.b0)] +\n moment[this.getIndex(cube.r0, cube.g1, cube.b0)] -\n moment[this.getIndex(cube.r0, cube.g0, cube.b0)]\n );\n case directions.GREEN:\n return (\n -moment[this.getIndex(cube.r1, cube.g0, cube.b1)] +\n moment[this.getIndex(cube.r1, cube.g0, cube.b0)] +\n moment[this.getIndex(cube.r0, cube.g0, cube.b1)] -\n moment[this.getIndex(cube.r0, cube.g0, cube.b0)]\n );\n case directions.RED:\n return (\n -moment[this.getIndex(cube.r0, cube.g1, cube.b1)] +\n moment[this.getIndex(cube.r0, cube.g1, cube.b0)] +\n moment[this.getIndex(cube.r0, cube.g0, cube.b1)] -\n moment[this.getIndex(cube.r0, cube.g0, cube.b0)]\n );\n default:\n throw new Error(\"unexpected direction $direction\");\n }\n }\n\n private computeMoments() {\n for (let r = 1; r < SIDE_LENGTH; r++) {\n const area = Array.from<number>({ length: SIDE_LENGTH }).fill(0);\n const areaR = Array.from<number>({ length: SIDE_LENGTH }).fill(0);\n const areaG = Array.from<number>({ length: SIDE_LENGTH }).fill(0);\n const areaB = Array.from<number>({ length: SIDE_LENGTH }).fill(0);\n const area2 = Array.from<number>({ length: SIDE_LENGTH }).fill(0.0);\n for (let g = 1; g < SIDE_LENGTH; g++) {\n let line = 0;\n let lineR = 0;\n let lineG = 0;\n let lineB = 0;\n let line2 = 0.0;\n for (let b = 1; b < SIDE_LENGTH; b++) {\n const index = this.getIndex(r, g, b);\n line += this.weights[index];\n lineR += this.momentsR[index];\n lineG += this.momentsG[index];\n lineB += this.momentsB[index];\n line2 += this.moments[index];\n\n area[b] += line;\n areaR[b] += lineR;\n areaG[b] += lineG;\n areaB[b] += lineB;\n area2[b] += line2;\n\n const previousIndex = this.getIndex(r - 1, g, b);\n this.weights[index] = this.weights[previousIndex] + area[b];\n this.momentsR[index] = this.momentsR[previousIndex] + areaR[b];\n this.momentsG[index] = this.momentsG[previousIndex] + areaG[b];\n this.momentsB[index] = this.momentsB[previousIndex] + areaB[b];\n this.moments[index] = this.moments[previousIndex] + area2[b];\n }\n }\n }\n }\n\n private constructHistogram(pixels: number[]) {\n this.weights = Array.from<number>({ length: TOTAL_SIZE }).fill(0);\n this.momentsR = Array.from<number>({ length: TOTAL_SIZE }).fill(0);\n this.momentsG = Array.from<number>({ length: TOTAL_SIZE }).fill(0);\n this.momentsB = Array.from<number>({ length: TOTAL_SIZE }).fill(0);\n this.moments = Array.from<number>({ length: TOTAL_SIZE }).fill(0);\n\n const countByColor = QuantizerMap.quantize(pixels);\n\n for (const [pixel, count] of countByColor.entries()) {\n const red = utils.redFromArgb(pixel);\n const green = utils.greenFromArgb(pixel);\n const blue = utils.blueFromArgb(pixel);\n\n const bitsToRemove = 8 - INDEX_BITS;\n const iR = (red >> bitsToRemove) + 1;\n const iG = (green >> bitsToRemove) + 1;\n const iB = (blue >> bitsToRemove) + 1;\n const index = this.getIndex(iR, iG, iB);\n\n this.weights[index] = (this.weights[index] ?? 0) + count;\n this.momentsR[index] += count * red;\n this.momentsG[index] += count * green;\n this.momentsB[index] += count * blue;\n this.moments[index] += count * (red * red + green * green + blue * blue);\n }\n }\n\n private createBoxes(maxColors: number): CreateBoxesResult {\n this.cubes = Array.from<number>({ length: maxColors })\n .fill(0)\n .map(() => new Box());\n const volumeVariance = Array.from<number>({ length: maxColors }).fill(0.0);\n this.cubes[0].r0 = 0;\n this.cubes[0].g0 = 0;\n this.cubes[0].b0 = 0;\n\n this.cubes[0].r1 = SIDE_LENGTH - 1;\n this.cubes[0].g1 = SIDE_LENGTH - 1;\n this.cubes[0].b1 = SIDE_LENGTH - 1;\n\n let generatedColorCount = maxColors;\n let next = 0;\n for (let i = 1; i < maxColors; i++) {\n if (this.cut(this.cubes[next], this.cubes[i])) {\n volumeVariance[next] =\n this.cubes[next].vol > 1 ? this.variance(this.cubes[next]) : 0.0;\n volumeVariance[i] =\n this.cubes[i].vol > 1 ? this.variance(this.cubes[i]) : 0.0;\n } else {\n volumeVariance[next] = 0.0;\n i--;\n }\n\n next = 0;\n let temp = volumeVariance[0];\n for (let j = 1; j <= i; j++) {\n if (volumeVariance[j] > temp) {\n temp = volumeVariance[j];\n next = j;\n }\n }\n if (temp <= 0.0) {\n generatedColorCount = i + 1;\n break;\n }\n }\n return new CreateBoxesResult(maxColors, generatedColorCount);\n }\n\n private createResult(colorCount: number): number[] {\n const colors: number[] = [];\n for (let i = 0; i < colorCount; ++i) {\n const cube = this.cubes[i];\n const weight = this.volume(cube, this.weights);\n if (weight > 0) {\n const r = Math.round(this.volume(cube, this.momentsR) / weight);\n const g = Math.round(this.volume(cube, this.momentsG) / weight);\n const b = Math.round(this.volume(cube, this.momentsB) / weight);\n const color =\n (255 << 24) | ((r & 0x0ff) << 16) | ((g & 0x0ff) << 8) | (b & 0x0ff);\n colors.push(color);\n }\n }\n return colors;\n }\n\n private cut(one: Box, two: Box) {\n const wholeR = this.volume(one, this.momentsR);\n const wholeG = this.volume(one, this.momentsG);\n const wholeB = this.volume(one, this.momentsB);\n const wholeW = this.volume(one, this.weights);\n\n const maxRResult = this.maximize(\n one,\n directions.RED,\n one.r0 + 1,\n one.r1,\n wholeR,\n wholeG,\n wholeB,\n wholeW,\n );\n const maxGResult = this.maximize(\n one,\n directions.GREEN,\n one.g0 + 1,\n one.g1,\n wholeR,\n wholeG,\n wholeB,\n wholeW,\n );\n const maxBResult = this.maximize(\n one,\n directions.BLUE,\n one.b0 + 1,\n one.b1,\n wholeR,\n wholeG,\n wholeB,\n wholeW,\n );\n\n let direction;\n const maxR = maxRResult.maximum;\n const maxG = maxGResult.maximum;\n const maxB = maxBResult.maximum;\n if (maxR >= maxG && maxR >= maxB) {\n if (maxRResult.cutLocation < 0) {\n return false;\n }\n direction = directions.RED;\n } else if (maxG >= maxR && maxG >= maxB) {\n direction = directions.GREEN;\n } else {\n direction = directions.BLUE;\n }\n\n two.r1 = one.r1;\n two.g1 = one.g1;\n two.b1 = one.b1;\n\n switch (direction) {\n case directions.BLUE:\n one.b1 = maxBResult.cutLocation;\n two.r0 = one.r0;\n two.g0 = one.g0;\n two.b0 = one.b1;\n break;\n case directions.GREEN:\n one.g1 = maxGResult.cutLocation;\n two.r0 = one.r0;\n two.g0 = one.g1;\n two.b0 = one.b0;\n break;\n case directions.RED:\n one.r1 = maxRResult.cutLocation;\n two.r0 = one.r1;\n two.g0 = one.g0;\n two.b0 = one.b0;\n break;\n default:\n throw new Error(\"unexpected direction \" + direction);\n }\n\n one.vol = (one.r1 - one.r0) * (one.g1 - one.g0) * (one.b1 - one.b0);\n two.vol = (two.r1 - two.r0) * (two.g1 - two.g0) * (two.b1 - two.b0);\n return true;\n }\n\n private getIndex(r: number, g: number, b: number): number {\n return (\n (r << (INDEX_BITS * 2)) +\n (r << (INDEX_BITS + 1)) +\n r +\n (g << INDEX_BITS) +\n g +\n b\n );\n }\n\n private maximize(\n cube: Box,\n direction: string,\n first: number,\n last: number,\n wholeR: number,\n wholeG: number,\n wholeB: number,\n wholeW: number,\n ) {\n const bottomR = this.bottom(cube, direction, this.momentsR);\n const bottomG = this.bottom(cube, direction, this.momentsG);\n const bottomB = this.bottom(cube, direction, this.momentsB);\n const bottomW = this.bottom(cube, direction, this.weights);\n\n let max = 0.0;\n let cut = -1;\n\n let halfR = 0;\n let halfG = 0;\n let halfB = 0;\n let halfW = 0;\n for (let i = first; i < last; i++) {\n halfR = bottomR + this.top(cube, direction, i, this.momentsR);\n halfG = bottomG + this.top(cube, direction, i, this.momentsG);\n halfB = bottomB + this.top(cube, direction, i, this.momentsB);\n halfW = bottomW + this.top(cube, direction, i, this.weights);\n if (halfW === 0) {\n continue;\n }\n\n let tempNumerator = (halfR * halfR + halfG * halfG + halfB * halfB) * 1.0;\n let tempDenominator = halfW * 1.0;\n let temp = tempNumerator / tempDenominator;\n\n halfR = wholeR - halfR;\n halfG = wholeG - halfG;\n halfB = wholeB - halfB;\n halfW = wholeW - halfW;\n if (halfW === 0) {\n continue;\n }\n\n tempNumerator = (halfR * halfR + halfG * halfG + halfB * halfB) * 1.0;\n tempDenominator = halfW * 1.0;\n temp += tempNumerator / tempDenominator;\n\n if (temp > max) {\n max = temp;\n cut = i;\n }\n }\n return new MaximizeResult(cut, max);\n }\n\n private top(\n cube: Box,\n direction: string,\n position: number,\n moment: number[],\n ) {\n switch (direction) {\n case directions.BLUE:\n return (\n moment[this.getIndex(cube.r1, cube.g1, position)] -\n moment[this.getIndex(cube.r1, cube.g0, position)] -\n moment[this.getIndex(cube.r0, cube.g1, position)] +\n moment[this.getIndex(cube.r0, cube.g0, position)]\n );\n case directions.GREEN:\n return (\n moment[this.getIndex(cube.r1, position, cube.b1)] -\n moment[this.getIndex(cube.r1, position, cube.b0)] -\n moment[this.getIndex(cube.r0, position, cube.b1)] +\n moment[this.getIndex(cube.r0, position, cube.b0)]\n );\n case directions.RED:\n return (\n moment[this.getIndex(position, cube.g1, cube.b1)] -\n moment[this.getIndex(position, cube.g1, cube.b0)] -\n moment[this.getIndex(position, cube.g0, cube.b1)] +\n moment[this.getIndex(position, cube.g0, cube.b0)]\n );\n default:\n throw new Error(\"unexpected direction $direction\");\n }\n }\n\n private variance(cube: Box) {\n const dr = this.volume(cube, this.momentsR);\n const dg = this.volume(cube, this.momentsG);\n const db = this.volume(cube, this.momentsB);\n const xx =\n this.moments[this.getIndex(cube.r1, cube.g1, cube.b1)] -\n this.moments[this.getIndex(cube.r1, cube.g1, cube.b0)] -\n this.moments[this.getIndex(cube.r1, cube.g0, cube.b1)] +\n this.moments[this.getIndex(cube.r1, cube.g0, cube.b0)] -\n this.moments[this.getIndex(cube.r0, cube.g1, cube.b1)] +\n this.moments[this.getIndex(cube.r0, cube.g1, cube.b0)] +\n this.moments[this.getIndex(cube.r0, cube.g0, cube.b1)] -\n this.moments[this.getIndex(cube.r0, cube.g0, cube.b0)];\n const hypotenuse = dr * dr + dg * dg + db * db;\n const volume = this.volume(cube, this.weights);\n return xx - hypotenuse / volume;\n }\n\n private volume(cube: Box, moment: number[]) {\n return (\n moment[this.getIndex(cube.r1, cube.g1, cube.b1)] -\n moment[this.getIndex(cube.r1, cube.g1, cube.b0)] -\n moment[this.getIndex(cube.r1, cube.g0, cube.b1)] +\n moment[this.getIndex(cube.r1, cube.g0, cube.b0)] -\n moment[this.getIndex(cube.r0, cube.g1, cube.b1)] +\n moment[this.getIndex(cube.r0, cube.g1, cube.b0)] +\n moment[this.getIndex(cube.r0, cube.g0, cube.b1)] -\n moment[this.getIndex(cube.r0, cube.g0, cube.b0)]\n );\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QuantizerWsmeans } from \"./quantizer_wsmeans.js\";\nimport { QuantizerWu } from \"./quantizer_wu.js\";\n\n/**\n * An image quantizer that improves on the quality of a standard K-Means\n * algorithm by setting the K-Means initial state to the output of a Wu\n * quantizer, instead of random centroids. Improves on speed by several\n * optimizations, as implemented in Wsmeans, or Weighted Square Means, K-Means\n * with those optimizations.\n *\n * This algorithm was designed by M. Emre Celebi, and was found in their 2011\n * paper, Improving the Performance of K-Means for Color Quantization.\n * https://arxiv.org/abs/1101.0395\n */\n// material_color_utilities is designed to have a consistent API across\n// platforms and modular components that can be moved around easily. Using a\n// class as a namespace facilitates this.\n//\n// tslint:disable-next-line:class-as-namespace\nexport class QuantizerCelebi {\n /**\n * @param pixels Colors in ARGB format.\n * @param maxColors The number of colors to divide the image into. A lower\n * number of colors may be returned.\n * @return Map with keys of colors in ARGB format, and values of number of\n * pixels in the original image that correspond to the color in the\n * quantized image.\n */\n static quantize(pixels: number[], maxColors: number): Map<number, number> {\n const wu = new QuantizerWu();\n const wuResult = wu.quantize(pixels, maxColors);\n return QuantizerWsmeans.quantize(pixels, wuResult, maxColors);\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Hct } from \"../hct/index.js\";\nimport * as math from \"../utils/math_utils.js\";\n\n/**\n * Default options for ranking colors based on usage counts.\n * desired: is the max count of the colors returned.\n * fallbackColorARGB: Is the default color that should be used if no\n * other colors are suitable.\n * filter: controls if the resulting colors should be filtered to not include\n * hues that are not used often enough, and colors that are effectively\n * grayscale.\n */\ndeclare interface ScoreOptions {\n desired?: number;\n fallbackColorARGB?: number;\n filter?: boolean;\n}\n\nconst SCORE_OPTION_DEFAULTS = {\n desired: 4, // 4 colors matches what Android wallpaper picker.\n fallbackColorARGB: 0xff4285f4, // Google Blue.\n filter: true, // Avoid unsuitable colors.\n};\n\nfunction compare(\n a: { hct: Hct; score: number },\n b: { hct: Hct; score: number },\n): number {\n if (a.score > b.score) {\n return -1;\n } else if (a.score < b.score) {\n return 1;\n }\n return 0;\n}\n\n/**\n * Given a large set of colors, remove colors that are unsuitable for a UI\n * theme, and rank the rest based on suitability.\n *\n * Enables use of a high cluster count for image quantization, thus ensuring\n * colors aren't muddied, while curating the high cluster count to a much\n * smaller number of appropriate choices.\n */\nexport class Score {\n private static readonly CUTOFF_CHROMA = 5.0;\n private static readonly CUTOFF_EXCITED_PROPORTION = 0.01;\n private static readonly TARGET_CHROMA = 48.0; // A1 Chroma\n private static readonly WEIGHT_CHROMA_ABOVE = 0.3;\n private static readonly WEIGHT_CHROMA_BELOW = 0.1;\n private static readonly WEIGHT_PROPORTION = 0.7;\n\n private constructor() {}\n\n /**\n * Given a map with keys of colors and values of how often the color appears,\n * rank the colors based on suitability for being used for a UI theme.\n *\n * @param colorsToPopulation map with keys of colors and values of how often\n * the color appears, usually from a source image.\n * @param {ScoreOptions} options optional parameters.\n * @return Colors sorted by suitability for a UI theme. The most suitable\n * color is the first item, the least suitable is the last. There will\n * always be at least one color returned. If all the input colors\n * were not suitable for a theme, a default fallback color will be\n * provided, Google Blue.\n */\n static score(\n colorsToPopulation: Map<number, number>,\n options?: ScoreOptions,\n ): number[] {\n const { desired, fallbackColorARGB, filter } = {\n ...SCORE_OPTION_DEFAULTS,\n ...options,\n };\n // Get the HCT color for each Argb value, while finding the per hue count and\n // total count.\n const colorsHct: Hct[] = [];\n const huePopulation = new Array<number>(360).fill(0);\n let populationSum = 0;\n for (const [argb, population] of colorsToPopulation.entries()) {\n const hct = Hct.fromInt(argb);\n colorsHct.push(hct);\n const hue = Math.floor(hct.hue);\n huePopulation[hue] += population;\n populationSum += population;\n }\n\n // Hues with more usage in neighboring 30 degree slice get a larger number.\n const hueExcitedProportions = new Array<number>(360).fill(0.0);\n for (let hue = 0; hue < 360; hue++) {\n const proportion = huePopulation[hue] / populationSum;\n for (let i = hue - 14; i < hue + 16; i++) {\n const neighborHue = math.sanitizeDegreesInt(i);\n hueExcitedProportions[neighborHue] += proportion;\n }\n }\n\n // Scores each HCT color based on usage and chroma, while optionally\n // filtering out values that do not have enough chroma or usage.\n const scoredHct = new Array<{ hct: Hct; score: number }>();\n for (const hct of colorsHct) {\n const hue = math.sanitizeDegreesInt(Math.round(hct.hue));\n const proportion = hueExcitedProportions[hue];\n if (\n filter &&\n (hct.chroma < Score.CUTOFF_CHROMA ||\n proportion <= Score.CUTOFF_EXCITED_PROPORTION)\n ) {\n continue;\n }\n\n const proportionScore = proportion * 100.0 * Score.WEIGHT_PROPORTION;\n const chromaWeight =\n hct.chroma < Score.TARGET_CHROMA\n ? Score.WEIGHT_CHROMA_BELOW\n : Score.WEIGHT_CHROMA_ABOVE;\n const chromaScore = (hct.chroma - Score.TARGET_CHROMA) * chromaWeight;\n const score = proportionScore + chromaScore;\n scoredHct.push({ hct, score });\n }\n // Sorted so that colors with higher scores come first.\n scoredHct.sort(compare);\n\n // Iterates through potential hue differences in degrees in order to select\n // the colors with the largest distribution of hues possible. Starting at\n // 90 degrees(maximum difference for 4 colors) then decreasing down to a\n // 15 degree minimum.\n const chosenColors: Hct[] = [];\n for (\n let differenceDegrees = 90;\n differenceDegrees >= 15;\n differenceDegrees--\n ) {\n chosenColors.length = 0;\n for (const { hct } of scoredHct) {\n const duplicateHue = chosenColors.find((chosenHct) => {\n return (\n math.differenceDegrees(hct.hue, chosenHct.hue) < differenceDegrees\n );\n });\n if (!duplicateHue) {\n chosenColors.push(hct);\n }\n if (chosenColors.length >= desired) break;\n }\n if (chosenColors.length >= desired) break;\n }\n const colors: number[] = [];\n if (chosenColors.length === 0) {\n colors.push(fallbackColorARGB);\n }\n for (const chosenHct of chosenColors) {\n colors.push(chosenHct.toInt());\n }\n return colors;\n }\n}\n","/**\n * Image color extraction using Material Design quantization\n */\n\nimport { DislikeAnalyzer } from \"./dislike/dislike-analyzer.js\";\nimport { Hct } from \"./hct/index.js\";\nimport {\n filterExtremeTones,\n imageDataToPixels,\n samplePixels,\n} from \"./image-utils.js\";\nimport { QuantizerCelebi } from \"./quantize/quantizer_celebi.js\";\nimport { Score } from \"./score/score.js\";\nimport * as utils from \"./utils/color_utils.js\";\n\nexport interface ExtractedColor {\n hct: { c: number; h: number; t: number };\n hex: string;\n percentage: number;\n population: number;\n rgb: { b: number; g: number; r: number };\n}\n\nexport interface ExtractionOptions {\n filter?: boolean;\n fixDislikedColors?: boolean;\n maxColors?: number;\n quality?: \"high\" | \"low\" | \"medium\";\n scoringEnabled?: boolean;\n}\n\nconst QUALITY_SETTINGS = {\n high: { maxPixels: 25000, quantizeColors: 256 },\n low: { maxPixels: 5000, quantizeColors: 64 },\n medium: { maxPixels: 10000, quantizeColors: 128 },\n};\n\n/**\n * Extract dominant colors from image data\n */\nexport function extractColors(\n imageData: {\n data: number[] | Uint8ClampedArray;\n height: number;\n width: number;\n },\n options: ExtractionOptions = {},\n): ExtractedColor[] {\n const {\n filter = true,\n fixDislikedColors = false,\n maxColors = 5,\n quality = \"medium\",\n scoringEnabled = true,\n } = options;\n\n const qualitySettings = QUALITY_SETTINGS[quality];\n\n // Convert image to pixels\n let pixels = imageDataToPixels(imageData);\n\n // Sample for performance\n pixels = samplePixels(pixels, qualitySettings.maxPixels);\n\n // Optionally filter extreme tones\n if (filter) {\n pixels = filterExtremeTones(pixels);\n }\n\n // Quantize colors using Celebi algorithm\n const quantized = QuantizerCelebi.quantize(\n pixels,\n qualitySettings.quantizeColors,\n );\n\n // Score and select best colors\n let selectedColors: number[];\n if (scoringEnabled) {\n selectedColors = Score.score(quantized, {\n desired: maxColors,\n filter: filter,\n });\n } else {\n // Simple selection by population\n const sorted = Array.from(quantized.entries())\n .sort((a, b) => b[1] - a[1])\n .slice(0, maxColors)\n .map((entry) => entry[0]);\n selectedColors = sorted;\n }\n\n // Calculate total population for percentages\n const totalPopulation = Array.from(quantized.values()).reduce(\n (sum, pop) => sum + pop,\n 0,\n );\n\n // Convert to output format\n return selectedColors.map((argb) => {\n let hct = Hct.fromInt(argb);\n\n // Fix disliked colors if requested\n if (fixDislikedColors && DislikeAnalyzer.isDisliked(hct)) {\n hct = DislikeAnalyzer.fixIfDisliked(hct);\n argb = hct.toInt();\n }\n\n const r = utils.redFromArgb(argb);\n const g = utils.greenFromArgb(argb);\n const b = utils.blueFromArgb(argb);\n const population = quantized.get(argb) || 0;\n\n return {\n hct: { c: hct.chroma, h: hct.hue, t: hct.tone },\n hex: rgbToHex(r, g, b),\n percentage: (population / totalPopulation) * 100,\n population,\n rgb: { b, g, r },\n };\n });\n}\n\n/**\n * Extract a color palette suitable for UI themes\n */\nexport function extractThemePalette(imageData: {\n data: number[] | Uint8ClampedArray;\n height: number;\n width: number;\n}): {\n error?: ExtractedColor;\n neutral?: ExtractedColor;\n primary: ExtractedColor;\n secondary?: ExtractedColor;\n tertiary?: ExtractedColor;\n} {\n // Extract with high quality and scoring, fixing disliked colors\n const colors = extractColors(imageData, {\n filter: true,\n fixDislikedColors: true, // Always fix disliked colors for themes\n maxColors: 8,\n quality: \"high\",\n scoringEnabled: true,\n });\n\n if (colors.length === 0) {\n throw new Error(\"No colors could be extracted from image\");\n }\n\n const result: {\n error?: ExtractedColor;\n neutral?: ExtractedColor;\n primary: ExtractedColor;\n secondary?: ExtractedColor;\n tertiary?: ExtractedColor;\n } = {\n primary: colors[0],\n };\n\n // Assign additional colors based on hue differences\n if (colors.length > 1) {\n // Find color with most different hue from primary\n const primaryHue = colors[0].hct.h;\n let maxHueDiff = 0;\n let secondaryIndex = 1;\n\n for (let i = 1; i < Math.min(colors.length, 4); i++) {\n const hueDiff = Math.abs(hueDifference(primaryHue, colors[i].hct.h));\n if (hueDiff > maxHueDiff) {\n maxHueDiff = hueDiff;\n secondaryIndex = i;\n }\n }\n\n result.secondary = colors[secondaryIndex];\n\n // Find tertiary (different from both primary and secondary)\n if (colors.length > 2) {\n const secondaryHue = colors[secondaryIndex].hct.h;\n let bestTertiaryIndex = -1;\n let bestScore = 0;\n\n for (let i = 1; i < colors.length; i++) {\n if (i === secondaryIndex) continue;\n\n const hue = colors[i].hct.h;\n const primaryDiff = Math.abs(hueDifference(primaryHue, hue));\n const secondaryDiff = Math.abs(hueDifference(secondaryHue, hue));\n const score = Math.min(primaryDiff, secondaryDiff);\n\n if (score > bestScore) {\n bestScore = score;\n bestTertiaryIndex = i;\n }\n }\n\n if (bestTertiaryIndex !== -1) {\n result.tertiary = colors[bestTertiaryIndex];\n }\n }\n }\n\n // Find a neutral color (low chroma)\n const neutral = colors.find((c) => c.hct.c < 20);\n if (neutral) {\n result.neutral = neutral;\n }\n\n // Error color (prefer red/orange hue if available, 0-40 or 350-360)\n const errorColor = colors.find((c) => c.hct.h >= 350 || c.hct.h <= 40);\n if (errorColor) {\n result.error = errorColor;\n }\n\n return result;\n}\n\nfunction hueDifference(h1: number, h2: number): number {\n const diff = Math.abs(h1 - h2);\n return diff > 180 ? 360 - diff : diff;\n}\n\nfunction rgbToHex(r: number, g: number, b: number): string {\n return (\n \"#\" +\n [r, g, b].map((x) => Math.round(x).toString(16).padStart(2, \"0\")).join(\"\")\n );\n}\n","/**\n * Material Design Theme Generation\n * Core functionality for Material Design 3 color theme creation\n */\n\nimport { DislikeAnalyzer } from \"./dislike/dislike-analyzer.js\";\nimport { Hct } from \"./hct/hct-class.js\";\nimport {\n corePaletteFromRgb,\n parseColor,\n rgbToArgb,\n rgbToHex,\n} from \"./index.js\";\n\nexport interface MaterialColorScheme {\n background: string;\n error: string;\n errorContainer: string;\n onBackground: string;\n onError: string;\n onErrorContainer: string;\n onPrimary: string;\n onPrimaryContainer: string;\n onSecondary: string;\n onSecondaryContainer: string;\n onSurface: string;\n onSurfaceVariant: string;\n onTertiary: string;\n onTertiaryContainer: string;\n outline: string;\n primary: string;\n primaryContainer: string;\n secondary: string;\n secondaryContainer: string;\n surface: string;\n surfaceVariant: string;\n tertiary: string;\n tertiaryContainer: string;\n}\n\nexport interface MaterialTheme {\n customColors?: Record<string, unknown>;\n schemes: {\n dark: MaterialColorScheme;\n light: MaterialColorScheme;\n };\n sourceColor: string;\n}\n\nexport interface MaterialThemeOptions {\n fixDislikedColors?: boolean;\n includeCustomColors?: boolean;\n isDark?: boolean;\n}\n\n/**\n * Generate a complete Material Design 3 theme from a source color\n */\nexport function generateMaterialTheme(\n sourceColor: string,\n options: MaterialThemeOptions = {},\n): MaterialTheme {\n const { fixDislikedColors = true } = options;\n\n let source = parseColor(sourceColor);\n if (!source) {\n throw new Error(`Invalid color format: ${sourceColor}`);\n }\n\n // Fix source color if it's disliked\n if (fixDislikedColors) {\n const sourceHct = Hct.fromInt(rgbToArgb(source));\n if (DislikeAnalyzer.isDisliked(sourceHct)) {\n const fixedHct = DislikeAnalyzer.fixIfDisliked(sourceHct);\n const fixedArgb = fixedHct.toInt();\n source = {\n b: fixedArgb & 0xff,\n g: (fixedArgb >> 8) & 0xff,\n r: (fixedArgb >> 16) & 0xff,\n };\n }\n }\n\n const corePalette = corePaletteFromRgb(source);\n\n // Generate light theme colors\n const lightScheme: MaterialColorScheme = {\n background: rgbToHex(corePalette.neutral.tone(99)),\n error: rgbToHex(corePalette.error.tone(40)),\n errorContainer: rgbToHex(corePalette.error.tone(90)),\n onBackground: rgbToHex(corePalette.neutral.tone(10)),\n\n onError: rgbToHex(corePalette.error.tone(100)),\n onErrorContainer: rgbToHex(corePalette.error.tone(10)),\n onPrimary: rgbToHex(corePalette.primary.tone(100)),\n onPrimaryContainer: rgbToHex(corePalette.primary.tone(10)),\n\n onSecondary: rgbToHex(corePalette.secondary.tone(100)),\n onSecondaryContainer: rgbToHex(corePalette.secondary.tone(10)),\n onSurface: rgbToHex(corePalette.neutral.tone(10)),\n onSurfaceVariant: rgbToHex(corePalette.neutralVariant.tone(30)),\n\n onTertiary: rgbToHex(corePalette.tertiary.tone(100)),\n onTertiaryContainer: rgbToHex(corePalette.tertiary.tone(10)),\n outline: rgbToHex(corePalette.neutralVariant.tone(50)),\n primary: rgbToHex(corePalette.primary.tone(40)),\n\n primaryContainer: rgbToHex(corePalette.primary.tone(90)),\n secondary: rgbToHex(corePalette.secondary.tone(40)),\n secondaryContainer: rgbToHex(corePalette.secondary.tone(90)),\n surface: rgbToHex(corePalette.neutral.tone(99)),\n\n surfaceVariant: rgbToHex(corePalette.neutralVariant.tone(90)),\n tertiary: rgbToHex(corePalette.tertiary.tone(40)),\n tertiaryContainer: rgbToHex(corePalette.tertiary.tone(90)),\n };\n\n // Generate dark theme colors\n const darkScheme: MaterialColorScheme = {\n background: rgbToHex(corePalette.neutral.tone(10)),\n error: rgbToHex(corePalette.error.tone(80)),\n errorContainer: rgbToHex(corePalette.error.tone(30)),\n onBackground: rgbToHex(corePalette.neutral.tone(90)),\n\n onError: rgbToHex(corePalette.error.tone(20)),\n onErrorContainer: rgbToHex(corePalette.error.tone(90)),\n onPrimary: rgbToHex(corePalette.primary.tone(20)),\n onPrimaryContainer: rgbToHex(corePalette.primary.tone(90)),\n\n onSecondary: rgbToHex(corePalette.secondary.tone(20)),\n onSecondaryContainer: rgbToHex(corePalette.secondary.tone(90)),\n onSurface: rgbToHex(corePalette.neutral.tone(90)),\n onSurfaceVariant: rgbToHex(corePalette.neutralVariant.tone(80)),\n\n onTertiary: rgbToHex(corePalette.tertiary.tone(20)),\n onTertiaryContainer: rgbToHex(corePalette.tertiary.tone(90)),\n outline: rgbToHex(corePalette.neutralVariant.tone(60)),\n primary: rgbToHex(corePalette.primary.tone(80)),\n\n primaryContainer: rgbToHex(corePalette.primary.tone(30)),\n secondary: rgbToHex(corePalette.secondary.tone(80)),\n secondaryContainer: rgbToHex(corePalette.secondary.tone(30)),\n surface: rgbToHex(corePalette.neutral.tone(10)),\n\n surfaceVariant: rgbToHex(corePalette.neutralVariant.tone(30)),\n tertiary: rgbToHex(corePalette.tertiary.tone(80)),\n tertiaryContainer: rgbToHex(corePalette.tertiary.tone(30)),\n };\n\n return {\n schemes: {\n dark: darkScheme,\n light: lightScheme,\n },\n sourceColor,\n };\n}\n","/**\n * Material Design Theme Tools\n * Tools for Material Design 3 color theme generation and management\n */\n\nimport { z } from \"zod\";\n\nimport {\n adjustTemperature,\n blend,\n corePaletteFromRgb,\n harmonize,\n parseColor,\n type RGB,\n rgbToHct,\n rgbToHex,\n TonalPalette,\n} from \"../color/index.js\";\n\n/**\n * Generate Material Design 3 Theme\n */\nexport const generateMaterialThemeTool = {\n description:\n \"Generate a complete Material Design 3 color theme from a source color\",\n execute: async (args: {\n includeCustomColors?: boolean;\n sourceColor: string;\n }) => {\n const source = parseColor(args.sourceColor);\n if (!source) {\n return `Invalid color format: ${args.sourceColor}`;\n }\n\n const corePalette = corePaletteFromRgb(source);\n\n // Generate key colors for light theme\n const lightTheme = {\n background: rgbToHex(corePalette.neutral.tone(99)),\n error: rgbToHex(corePalette.error.tone(40)),\n errorContainer: rgbToHex(corePalette.error.tone(90)),\n onBackground: rgbToHex(corePalette.neutral.tone(10)),\n\n onError: rgbToHex(corePalette.error.tone(100)),\n onErrorContainer: rgbToHex(corePalette.error.tone(10)),\n onPrimary: rgbToHex(corePalette.primary.tone(100)),\n onPrimaryContainer: rgbToHex(corePalette.primary.tone(10)),\n\n onSecondary: rgbToHex(corePalette.secondary.tone(100)),\n onSecondaryContainer: rgbToHex(corePalette.secondary.tone(10)),\n onSurface: rgbToHex(corePalette.neutral.tone(10)),\n onSurfaceVariant: rgbToHex(corePalette.neutralVariant.tone(30)),\n\n onTertiary: rgbToHex(corePalette.tertiary.tone(100)),\n onTertiaryContainer: rgbToHex(corePalette.tertiary.tone(10)),\n outline: rgbToHex(corePalette.neutralVariant.tone(50)),\n primary: rgbToHex(corePalette.primary.tone(40)),\n\n primaryContainer: rgbToHex(corePalette.primary.tone(90)),\n secondary: rgbToHex(corePalette.secondary.tone(40)),\n secondaryContainer: rgbToHex(corePalette.secondary.tone(90)),\n surface: rgbToHex(corePalette.neutral.tone(99)),\n\n surfaceVariant: rgbToHex(corePalette.neutralVariant.tone(90)),\n tertiary: rgbToHex(corePalette.tertiary.tone(40)),\n tertiaryContainer: rgbToHex(corePalette.tertiary.tone(90)),\n };\n\n // Generate key colors for dark theme\n const darkTheme = {\n background: rgbToHex(corePalette.neutral.tone(10)),\n error: rgbToHex(corePalette.error.tone(80)),\n errorContainer: rgbToHex(corePalette.error.tone(30)),\n onBackground: rgbToHex(corePalette.neutral.tone(90)),\n\n onError: rgbToHex(corePalette.error.tone(20)),\n onErrorContainer: rgbToHex(corePalette.error.tone(90)),\n onPrimary: rgbToHex(corePalette.primary.tone(20)),\n onPrimaryContainer: rgbToHex(corePalette.primary.tone(90)),\n\n onSecondary: rgbToHex(corePalette.secondary.tone(20)),\n onSecondaryContainer: rgbToHex(corePalette.secondary.tone(90)),\n onSurface: rgbToHex(corePalette.neutral.tone(90)),\n onSurfaceVariant: rgbToHex(corePalette.neutralVariant.tone(80)),\n\n onTertiary: rgbToHex(corePalette.tertiary.tone(20)),\n onTertiaryContainer: rgbToHex(corePalette.tertiary.tone(90)),\n outline: rgbToHex(corePalette.neutralVariant.tone(60)),\n primary: rgbToHex(corePalette.primary.tone(80)),\n\n primaryContainer: rgbToHex(corePalette.primary.tone(30)),\n secondary: rgbToHex(corePalette.secondary.tone(80)),\n secondaryContainer: rgbToHex(corePalette.secondary.tone(30)),\n surface: rgbToHex(corePalette.neutral.tone(10)),\n\n surfaceVariant: rgbToHex(corePalette.neutralVariant.tone(30)),\n tertiary: rgbToHex(corePalette.tertiary.tone(80)),\n tertiaryContainer: rgbToHex(corePalette.tertiary.tone(30)),\n };\n\n let result = `Material Design 3 Theme\nSource Color: ${args.sourceColor}\n\nLIGHT THEME:\n${Object.entries(lightTheme)\n .map(([key, value]) => ` ${key}: ${value}`)\n .join(\"\\n\")}\n\nDARK THEME:\n${Object.entries(darkTheme)\n .map(([key, value]) => ` ${key}: ${value}`)\n .join(\"\\n\")}`;\n\n if (args.includeCustomColors) {\n result += `\\n\\nTONAL PALETTES:\nPrimary: ${[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 99, 100]\n .map((t) => rgbToHex(corePalette.primary.tone(t)))\n .join(\", \")}\nSecondary: ${[40, 80].map((t) => rgbToHex(corePalette.secondary.tone(t))).join(\", \")}\nTertiary: ${[40, 80].map((t) => rgbToHex(corePalette.tertiary.tone(t))).join(\", \")}`;\n }\n\n return result;\n },\n name: \"generate_material_theme\",\n parameters: z.object({\n includeCustomColors: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Include custom color palettes\"),\n sourceColor: z.string().describe(\"Source color for theme generation\"),\n }),\n};\n\n/**\n * Harmonize Colors Tool\n */\nexport const harmonizeColorsTool = {\n description:\n \"Harmonize colors to work better together using Material Design algorithms\",\n execute: async (args: {\n colors: string[];\n factor?: number;\n method?: \"blend\" | \"harmonize\" | \"temperature\";\n }) => {\n const colors = args.colors.map((c) => parseColor(c));\n if (colors.some((c) => c === null)) {\n return \"One or more invalid color formats\";\n }\n\n const validColors = colors as RGB[];\n const method = args.method || \"harmonize\";\n const factor = args.factor || 0.5;\n const results: string[] = [];\n\n switch (method) {\n case \"blend\": {\n // Blend all colors together\n let result = validColors[0];\n for (let i = 1; i < validColors.length; i++) {\n result = blend(result, validColors[i], factor);\n }\n results.push(rgbToHex(result));\n break;\n }\n\n case \"harmonize\": {\n // Harmonize all colors with the first one\n const source = validColors[0];\n results.push(rgbToHex(source)); // Keep source unchanged\n\n for (let i = 1; i < validColors.length; i++) {\n results.push(rgbToHex(harmonize(validColors[i], source, factor)));\n }\n break;\n }\n\n case \"temperature\": {\n // Adjust temperature of all colors\n const amount = (factor - 0.5) * 2; // Convert to -1 to 1\n for (const color of validColors) {\n results.push(rgbToHex(adjustTemperature(color, amount)));\n }\n break;\n }\n }\n\n return `Harmonized Colors (${method}):\nOriginal: ${args.colors.join(\", \")}\nResult: ${results.join(\", \")}`;\n },\n name: \"harmonize_colors\",\n parameters: z.object({\n colors: z\n .array(z.string())\n .min(2)\n .max(10)\n .describe(\"Array of colors to harmonize\"),\n factor: z\n .number()\n .min(0)\n .max(1)\n .optional()\n .default(0.5)\n .describe(\"Harmonization strength (0-1)\"),\n method: z\n .enum([\"blend\", \"harmonize\", \"temperature\"])\n .optional()\n .default(\"harmonize\")\n .describe(\"Harmonization method\"),\n }),\n};\n\n/**\n * Generate Tonal Palette Tool\n */\nexport const generateTonalPaletteTool = {\n description: \"Generate a Material Design tonal palette from a color\",\n execute: async (args: { color: string; tones?: number[] }) => {\n const rgb = parseColor(args.color);\n if (!rgb) {\n return `Invalid color format: ${args.color}`;\n }\n\n const palette = TonalPalette.fromRgb(rgb);\n const tones = args.tones || [\n 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 99, 100,\n ];\n\n const hct = rgbToHct(rgb);\n const colors = tones.map((tone) => ({\n hex: rgbToHex(palette.tone(tone)),\n tone,\n }));\n\n return `Tonal Palette for ${args.color}\nHCT: h=${hct.h.toFixed(1)}°, c=${hct.c.toFixed(1)}, t=${hct.t.toFixed(1)}\n\n${colors.map(({ hex, tone }) => `Tone ${tone}: ${hex}`).join(\"\\n\")}`;\n },\n name: \"generate_tonal_palette\",\n parameters: z.object({\n color: z.string().describe(\"Base color for palette\"),\n tones: z\n .array(z.number())\n .optional()\n .describe(\"Custom tone values (default: Material standard tones)\"),\n }),\n};\n","/**\n * Palette Export Tool\n * Convert a palette of colors into commonly used design-system formats:\n * CSS custom properties, SCSS variables, Tailwind config, or W3C design tokens.\n */\n\nimport { z } from \"zod\";\n\nimport { parseColor, rgbToHex, rgbToHsl } from \"../color/index.js\";\n\nconst FORMATS = [\"css\", \"scss\", \"tailwind\", \"tokens\", \"json\"] as const;\n\ntype ExportFormat = (typeof FORMATS)[number];\n\ninterface NamedColor {\n hex: string;\n name: string;\n}\n\nfunction asCss(items: NamedColor[]): string {\n const body = items.map(({ hex, name }) => ` --${name}: ${hex};`).join(\"\\n\");\n return `:root {\\n${body}\\n}\\n`;\n}\n\nfunction asJson(items: NamedColor[]): string {\n const obj: Record<string, { hex: string; hsl: string; rgb: string }> = {};\n for (const { hex, name } of items) {\n const rgb = parseColor(hex)!;\n const hsl = rgbToHsl(rgb);\n obj[name] = {\n hex,\n hsl: `hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%)`,\n rgb: `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`,\n };\n }\n return JSON.stringify(obj, null, 2) + \"\\n\";\n}\n\nfunction asScss(items: NamedColor[]): string {\n return items.map(({ hex, name }) => `$${name}: ${hex};`).join(\"\\n\") + \"\\n\";\n}\n\nfunction asTailwind(items: NamedColor[], prefix?: string): string {\n const key = prefix ?? \"palette\";\n const lines = items\n .map(({ hex, name }) => {\n // Drop the prefix from the entry name if it was prefixed\n const entry =\n prefix && name.startsWith(`${prefix}-`)\n ? name.slice(prefix.length + 1)\n : name;\n return ` \"${entry}\": \"${hex}\",`;\n })\n .join(\"\\n\");\n return `// tailwind.config.js\nmodule.exports = {\n theme: {\n extend: {\n colors: {\n \"${key}\": {\n${lines}\n },\n },\n },\n },\n};\n`;\n}\n\nfunction asTokens(items: NamedColor[], prefix?: string): string {\n // W3C Design Tokens Community Group format (draft).\n const group = prefix ?? \"color\";\n const obj: Record<string, unknown> = {\n [group]: Object.fromEntries(\n items.map(({ hex, name }) => {\n const entry =\n prefix && name.startsWith(`${prefix}-`)\n ? name.slice(prefix.length + 1)\n : name;\n return [entry, { $type: \"color\", $value: hex }];\n }),\n ),\n };\n return JSON.stringify(obj, null, 2) + \"\\n\";\n}\n\nfunction defaultName(index: number): string {\n // Tailwind-style 50/100…900 scale up to 10 colors, then numeric.\n const scale = [\n \"50\",\n \"100\",\n \"200\",\n \"300\",\n \"400\",\n \"500\",\n \"600\",\n \"700\",\n \"800\",\n \"900\",\n ];\n return scale[index] ?? String((index + 1) * 100);\n}\n\nfunction resolveNames(\n colors: string[],\n names?: string[],\n prefix?: string,\n): NamedColor[] {\n return colors.map((c, i) => {\n const parsed = parseColor(c);\n if (!parsed) throw new Error(`Invalid color: ${c}`);\n const hex = rgbToHex(parsed);\n const raw = names?.[i] ?? defaultName(i);\n const slug = raw.toLowerCase().replace(/[^a-z0-9-]+/g, \"-\");\n const name = prefix ? `${prefix}-${slug}` : slug;\n return { hex, name };\n });\n}\n\nexport const exportPaletteTool = {\n description:\n \"Export a list of colors as CSS custom properties, SCSS variables, a Tailwind config snippet, W3C design tokens, or JSON.\",\n execute: async (args: {\n colors: string[];\n format: ExportFormat;\n names?: string[];\n prefix?: string;\n }) => {\n const { colors, format, names, prefix } = args;\n\n if (names && names.length !== colors.length) {\n return `Error: names array length (${names.length}) must match colors length (${colors.length}).`;\n }\n\n let items: NamedColor[];\n try {\n items = resolveNames(colors, names, prefix);\n } catch (e) {\n return e instanceof Error ? e.message : String(e);\n }\n\n switch (format) {\n case \"css\":\n return asCss(items);\n case \"json\":\n return asJson(items);\n case \"scss\":\n return asScss(items);\n case \"tailwind\":\n return asTailwind(items, prefix);\n case \"tokens\":\n return asTokens(items, prefix);\n }\n },\n name: \"export_palette\",\n parameters: z.object({\n colors: z.array(z.string()).min(1).describe(\"Palette colors\"),\n format: z\n .enum(FORMATS)\n .describe(\n \"Output format: css (custom properties), scss (variables), tailwind (config), tokens (W3C design tokens), json\",\n ),\n names: z\n .array(z.string())\n .optional()\n .describe(\n \"Optional names for each color. Length must match colors. Defaults to a 50/100…900 scale.\",\n ),\n prefix: z\n .string()\n .optional()\n .describe(\"Optional prefix for variable/token names (e.g. 'brand')\"),\n }),\n};\n","/**\n * Palette Generator Tool\n * Generate color palettes from a base color\n */\n\nimport { z } from \"zod\";\n\nimport { parseColor, rgbToHex, rgbToHsl } from \"../color/index.js\";\n\nexport const paletteGeneratorTool = {\n description: \"Generate a color palette from a base color\",\n execute: async (args: {\n baseColor: string;\n count?: number;\n type?:\n | \"analogous\"\n | \"complementary\"\n | \"monochromatic\"\n | \"tetradic\"\n | \"triadic\";\n }) => {\n const base = parseColor(args.baseColor);\n if (!base) {\n return `Invalid color format: ${args.baseColor}`;\n }\n\n const type = args.type || \"monochromatic\";\n const count = args.count || 5;\n const hsl = rgbToHsl(base);\n const palette: string[] = [];\n\n switch (type) {\n case \"analogous\": {\n // Colors adjacent on the color wheel\n const step = 30;\n for (let i = 0; i < count; i++) {\n const h = (hsl.h + (i - Math.floor(count / 2)) * step + 360) % 360;\n const color = parseColor(`hsl(${h}, ${hsl.s}%, ${hsl.l}%)`);\n if (color) palette.push(rgbToHex(color));\n }\n break;\n }\n case \"complementary\": {\n // Base color and its complement\n palette.push(rgbToHex(base));\n const complement = parseColor(\n `hsl(${(hsl.h + 180) % 360}, ${hsl.s}%, ${hsl.l}%)`,\n );\n if (complement) palette.push(rgbToHex(complement));\n\n // Add variations\n for (let i = 2; i < count; i++) {\n const l = hsl.l + (i % 2 === 0 ? 20 : -20);\n const h = i < count / 2 ? hsl.h : (hsl.h + 180) % 360;\n const color = parseColor(\n `hsl(${h}, ${hsl.s}%, ${Math.max(10, Math.min(90, l))}%)`,\n );\n if (color) palette.push(rgbToHex(color));\n }\n break;\n }\n case \"monochromatic\": {\n // Generate different lightness values\n const step = 80 / (count - 1);\n for (let i = 0; i < count; i++) {\n const l = 10 + i * step;\n const color = parseColor(`hsl(${hsl.h}, ${hsl.s}%, ${l}%)`);\n if (color) palette.push(rgbToHex(color));\n }\n break;\n }\n case \"tetradic\": {\n // Four colors in rectangle on color wheel\n for (let i = 0; i < Math.min(4, count); i++) {\n const h = (hsl.h + i * 90) % 360;\n const color = parseColor(`hsl(${h}, ${hsl.s}%, ${hsl.l}%)`);\n if (color) palette.push(rgbToHex(color));\n }\n // Add variations for remaining colors\n for (let i = 4; i < count; i++) {\n const baseIdx = i % 4;\n const h = (hsl.h + baseIdx * 90) % 360;\n const l = hsl.l + (i < 8 ? 15 : -15);\n const color = parseColor(\n `hsl(${h}, ${hsl.s}%, ${Math.max(10, Math.min(90, l))}%)`,\n );\n if (color) palette.push(rgbToHex(color));\n }\n break;\n }\n case \"triadic\": {\n // Three colors evenly spaced on color wheel\n for (let i = 0; i < Math.min(3, count); i++) {\n const h = (hsl.h + i * 120) % 360;\n const color = parseColor(`hsl(${h}, ${hsl.s}%, ${hsl.l}%)`);\n if (color) palette.push(rgbToHex(color));\n }\n // Add variations for remaining colors\n for (let i = 3; i < count; i++) {\n const baseIdx = i % 3;\n const h = (hsl.h + baseIdx * 120) % 360;\n const l = hsl.l + (i < 6 ? 20 : -20);\n const color = parseColor(\n `hsl(${h}, ${hsl.s}%, ${Math.max(10, Math.min(90, l))}%)`,\n );\n if (color) palette.push(rgbToHex(color));\n }\n break;\n }\n }\n\n return `Generated ${type} palette:\n${palette.map((color, i) => `${i + 1}. ${color}`).join(\"\\n\")}`;\n },\n name: \"generate_palette\",\n parameters: z.object({\n baseColor: z.string().describe(\"Base color for palette generation\"),\n count: z\n .number()\n .min(3)\n .max(10)\n .default(5)\n .describe(\"Number of colors to generate\"),\n type: z\n .enum([\n \"monochromatic\",\n \"analogous\",\n \"complementary\",\n \"triadic\",\n \"tetradic\",\n ])\n .default(\"monochromatic\")\n .describe(\"Type of color palette\"),\n }),\n};\n","import { z } from \"zod\";\n\nimport {\n colorDistance,\n hslToRgb,\n labToRgb,\n parseColor,\n rgbToHex,\n rgbToHsl,\n rgbToLab,\n} from \"../color/index.js\";\nimport { RGB } from \"../color/types.js\";\n\nexport const paletteWithLocksTool = {\n description:\n \"Generate a color palette while preserving specific locked colors\",\n execute: async (args: {\n colorSpace?: \"hsl\" | \"lab\";\n lockedColors: string[];\n mode?: \"contrast\" | \"gradient\" | \"harmony\";\n totalColors: number;\n }) => {\n const {\n colorSpace = \"hsl\",\n lockedColors,\n mode = \"harmony\",\n totalColors,\n } = args;\n\n if (lockedColors.length >= totalColors) {\n return `Error: Number of locked colors (${lockedColors.length}) must be less than total colors (${totalColors})`;\n }\n\n // Parse and validate locked colors\n const parsedLocked: RGB[] = [];\n for (const color of lockedColors) {\n const parsed = parseColor(color);\n if (!parsed) {\n return `Invalid color format: ${color}`;\n }\n parsedLocked.push(parsed);\n }\n\n const palette: string[] = [];\n const remainingSlots = totalColors - lockedColors.length;\n\n // Add locked colors to palette\n lockedColors.forEach((color) => palette.push(color));\n\n switch (mode) {\n case \"contrast\": {\n // Generate contrasting colors\n for (let i = 0; i < remainingSlots; i++) {\n let bestColor: null | RGB = null;\n let maxMinDistance = 0;\n\n // Try random colors and pick the one with maximum minimum distance\n for (let attempt = 0; attempt < 100; attempt++) {\n const candidate: RGB = {\n b: Math.floor(Math.random() * 256),\n g: Math.floor(Math.random() * 256),\n r: Math.floor(Math.random() * 256),\n };\n\n let minDistance = Infinity;\n for (const locked of parsedLocked) {\n const dist = colorDistance(candidate, locked, {\n metric: \"deltaE2000\",\n });\n if (dist < minDistance) minDistance = dist;\n }\n\n if (minDistance > maxMinDistance) {\n maxMinDistance = minDistance;\n bestColor = candidate;\n }\n }\n\n if (bestColor) {\n palette.push(rgbToHex(bestColor));\n parsedLocked.push(bestColor);\n }\n }\n break;\n }\n\n case \"gradient\": {\n // Create gradient between locked colors\n if (parsedLocked.length < 2) {\n return \"Gradient mode requires at least 2 locked colors\";\n }\n\n const steps = Math.floor(remainingSlots / (parsedLocked.length - 1));\n\n for (let i = 0; i < parsedLocked.length - 1; i++) {\n const start = parsedLocked[i];\n const end = parsedLocked[i + 1];\n\n for (let step = 1; step <= steps; step++) {\n const t = step / (steps + 1);\n\n if (colorSpace === \"lab\") {\n // Interpolate in LAB space\n const startLab = rgbToLab(start);\n const endLab = rgbToLab(end);\n\n const interpolated = labToRgb({\n a: startLab.a + (endLab.a - startLab.a) * t,\n b: startLab.b + (endLab.b - startLab.b) * t,\n l: startLab.l + (endLab.l - startLab.l) * t,\n });\n\n palette.push(rgbToHex(interpolated));\n } else {\n // Interpolate in HSL space\n const startHsl = rgbToHsl(start);\n const endHsl = rgbToHsl(end);\n\n // Handle hue interpolation (shortest path)\n let hueDiff = endHsl.h - startHsl.h;\n if (hueDiff > 180) hueDiff -= 360;\n if (hueDiff < -180) hueDiff += 360;\n\n const interpolated = hslToRgb({\n h: (startHsl.h + hueDiff * t + 360) % 360,\n l: startHsl.l + (endHsl.l - startHsl.l) * t,\n s: startHsl.s + (endHsl.s - startHsl.s) * t,\n });\n\n palette.push(rgbToHex(interpolated));\n }\n }\n }\n break;\n }\n\n case \"harmony\": {\n // Generate harmonious colors based on locked colors\n const baseHsl = rgbToHsl(parsedLocked[0]);\n\n for (let i = 0; i < remainingSlots; i++) {\n let attempts = 0;\n let bestColor: null | RGB = null;\n let maxMinDistance = 0;\n\n // Try different hues to find one that's not too close to locked colors\n while (attempts < 36) {\n const newHue = (baseHsl.h + attempts * 10) % 360;\n const candidate = hslToRgb({\n h: newHue,\n l: baseHsl.l + (Math.random() - 0.5) * 20,\n s: baseHsl.s + (Math.random() - 0.5) * 20,\n });\n\n // Check minimum distance to all locked colors\n let minDistance = Infinity;\n for (const locked of parsedLocked) {\n const dist = colorDistance(candidate, locked, {\n metric: \"deltaE2000\",\n });\n if (dist < minDistance) minDistance = dist;\n }\n\n // Keep the candidate with the largest minimum distance\n if (minDistance > maxMinDistance && minDistance > 10) {\n maxMinDistance = minDistance;\n bestColor = candidate;\n }\n\n attempts++;\n }\n\n if (bestColor) {\n palette.push(rgbToHex(bestColor));\n parsedLocked.push(bestColor); // Add to locked for next iteration\n }\n }\n break;\n }\n }\n\n // Sort palette to have locked colors marked\n const result: string[] = [];\n const lockedSet = new Set(lockedColors.map((c) => c.toLowerCase()));\n\n palette.forEach((color) => {\n if (lockedSet.has(color.toLowerCase())) {\n result.push(`${color} (locked)`);\n } else {\n result.push(color);\n }\n });\n\n return `Generated palette with ${lockedColors.length} locked colors:\n${result.map((color, i) => `${i + 1}. ${color}`).join(\"\\n\")}\n\nMode: ${mode}\nColor space: ${colorSpace}\nTotal colors: ${totalColors}`;\n },\n name: \"generate_palette_with_locks\",\n parameters: z.object({\n colorSpace: z\n .enum([\"hsl\", \"lab\"])\n .default(\"hsl\")\n .describe(\"Color space for interpolation (affects gradient smoothness)\"),\n lockedColors: z\n .array(z.string())\n .min(1)\n .describe(\"Colors that must be included in the palette\"),\n mode: z\n .enum([\"harmony\", \"contrast\", \"gradient\"])\n .default(\"harmony\")\n .describe(\n \"Generation mode: harmony (similar), contrast (different), or gradient (smooth transition)\",\n ),\n totalColors: z\n .number()\n .min(2)\n .max(20)\n .describe(\"Total number of colors in the final palette\"),\n }),\n};\n","/**\n * Theme Matching Tools\n * Tools for matching colors to theme variables and refactoring CSS\n */\n\nimport { z } from \"zod\";\n\nimport { corePaletteFromRgb, parseColor, rgbToHex } from \"../color/index.js\";\nimport {\n type ColorContext,\n findBatchMatches,\n findClosestThemeColor,\n generateRefactoringReport,\n parseThemeVariables,\n refactorCss,\n} from \"../theme/index.js\";\n\n/**\n * Match Theme Color Tool\n */\nexport const matchThemeColorTool = {\n description: \"Find the closest matching theme variable for a given color\",\n execute: async (args: {\n color: string;\n context?: ColorContext;\n minConfidence?: number;\n themeCSS: string;\n }) => {\n // Parse theme variables from CSS\n const themeVariables = parseThemeVariables(args.themeCSS);\n\n // Find closest match\n const match = findClosestThemeColor(args.color, themeVariables, {\n contextType: args.context,\n });\n\n if (!match) {\n return \"No matching theme variable found\";\n }\n\n const minConfidence = args.minConfidence ?? 70;\n if (match.confidence < minConfidence) {\n return `Best match below confidence threshold:\nVariable: ${match.variable}\nDistance: ${match.distance.toFixed(2)}\nConfidence: ${match.confidence}%\n\nConsider adding a new theme variable for this color.`;\n }\n\n let result = `Best Match:\nVariable: ${match.variable}\nValue: ${match.value}\nDistance: ${match.distance.toFixed(2)}\nConfidence: ${match.confidence}%`;\n\n if (match.semanticRole) {\n result += `\\nSemantic Role: ${match.semanticRole}`;\n }\n\n if (match.accessibilityInfo) {\n result += `\\n\\nAccessibility:\nContrast with background: ${match.accessibilityInfo.contrastWithBackground.toFixed(2)}\nContrast with foreground: ${match.accessibilityInfo.contrastWithForeground.toFixed(2)}\nMeets AA: ${match.accessibilityInfo.meetsAA ? \"Yes\" : \"No\"}\nMeets AAA: ${match.accessibilityInfo.meetsAAA ? \"Yes\" : \"No\"}`;\n }\n\n if (match.alternatives.length > 0) {\n result += `\\n\\nAlternatives:`;\n for (const alt of match.alternatives) {\n result += `\\n- ${alt.variable} (confidence: ${alt.confidence}%)`;\n }\n }\n\n return result;\n },\n name: \"match_theme_color\",\n parameters: z.object({\n color: z.string().describe(\"Color to match (hex, rgb, hsl)\"),\n context: z\n .enum([\"text\", \"background\", \"border\", \"shadow\", \"accent\", \"decorative\"])\n .optional()\n .describe(\"Usage context for better matching\"),\n minConfidence: z\n .number()\n .min(0)\n .max(100)\n .optional()\n .default(70)\n .describe(\"Minimum confidence threshold (0-100)\"),\n themeCSS: z.string().describe(\"CSS containing theme variables\"),\n }),\n};\n\n/**\n * Refactor CSS with Theme Tool\n */\nexport const refactorCssWithThemeTool = {\n description:\n \"Refactor CSS to use theme variables instead of hardcoded colors\",\n execute: async (args: {\n css: string;\n generateReport?: boolean;\n minConfidence?: number;\n preserveOriginal?: boolean;\n themeCSS: string;\n }) => {\n // Parse theme variables\n const themeVariables = parseThemeVariables(args.themeCSS);\n\n // Refactor CSS\n const result = refactorCss(args.css, themeVariables, {\n addComments: args.preserveOriginal ?? true,\n minConfidence: args.minConfidence ?? 70,\n preserveOriginal: args.preserveOriginal ?? true,\n });\n\n let output = `Refactoring Complete!\n\nStatistics:\n- Total colors found: ${result.statistics.totalColors}\n- Colors replaced: ${result.statistics.replacedColors}\n- Average confidence: ${result.statistics.averageConfidence}%\n- Accessibility issues: ${result.statistics.accessibilityIssues}\n\nRefactored CSS:\n----------------------------------------\n${result.refactored}\n----------------------------------------`;\n\n if (result.warnings.length > 0) {\n output += `\\n\\nWarnings (${result.warnings.length}):`;\n for (const warning of result.warnings.slice(0, 5)) {\n output += `\\n- ${warning.message}`;\n if (warning.suggestion) {\n output += `\\n Suggestion: ${warning.suggestion}`;\n }\n }\n if (result.warnings.length > 5) {\n output += `\\n... and ${result.warnings.length - 5} more warnings`;\n }\n }\n\n if (args.generateReport) {\n output += `\\n\\n${generateRefactoringReport(result)}`;\n }\n\n return output;\n },\n name: \"refactor_css_with_theme\",\n parameters: z.object({\n css: z.string().describe(\"CSS content to refactor\"),\n generateReport: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Generate detailed refactoring report\"),\n minConfidence: z\n .number()\n .min(0)\n .max(100)\n .optional()\n .default(70)\n .describe(\"Minimum confidence for replacements\"),\n preserveOriginal: z\n .boolean()\n .optional()\n .default(true)\n .describe(\"Keep original values as comments\"),\n themeCSS: z.string().describe(\"CSS containing theme variables\"),\n }),\n};\n\n/**\n * Match Theme Colors Batch Tool\n */\nexport const matchThemeColorsBatchTool = {\n description: \"Find theme matches for multiple colors at once\",\n execute: async (args: {\n colors: string[];\n context?: ColorContext;\n themeCSS: string;\n }) => {\n // Parse theme variables\n const themeVariables = parseThemeVariables(args.themeCSS);\n\n // Find matches for all colors\n const matches = findBatchMatches(args.colors, themeVariables, {\n contextType: args.context,\n });\n\n let result = `Theme Color Matches:\\n`;\n let matchCount = 0;\n let totalConfidence = 0;\n\n for (const [color, match] of matches.entries()) {\n if (match) {\n matchCount++;\n totalConfidence += match.confidence;\n result += `\\n${color} → ${match.variable} (${match.confidence}%)`;\n } else {\n result += `\\n${color} → No match found`;\n }\n }\n\n result += `\\n\\nSummary:\n- Matched: ${matchCount}/${args.colors.length}\n- Average confidence: ${matchCount > 0 ? Math.round(totalConfidence / matchCount) : 0}%`;\n\n return result;\n },\n name: \"match_theme_colors_batch\",\n parameters: z.object({\n colors: z\n .array(z.string())\n .min(1)\n .max(50)\n .describe(\"Array of colors to match\"),\n context: z\n .enum([\"text\", \"background\", \"border\", \"shadow\", \"accent\", \"decorative\"])\n .optional()\n .describe(\"Usage context for all colors\"),\n themeCSS: z.string().describe(\"CSS containing theme variables\"),\n }),\n};\n\n/**\n * Generate Theme CSS Tool\n */\nexport const generateThemeCssTool = {\n description:\n \"Generate CSS custom properties for a complete theme from a source color\",\n execute: async (args: {\n includeTones?: number[];\n prefix?: string;\n sourceColor: string;\n }) => {\n const source = parseColor(args.sourceColor);\n if (!source) {\n return `Invalid color format: ${args.sourceColor}`;\n }\n\n const corePalette = corePaletteFromRgb(source);\n const tones = args.includeTones || [\n 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 99, 100,\n ];\n const prefix = args.prefix || \"color\";\n\n let css = `:root {\\n`;\n\n // Generate primary palette\n css += ` /* Primary Colors */\\n`;\n for (const tone of tones) {\n const color = rgbToHex(corePalette.primary.tone(tone));\n css += ` --${prefix}-primary-${tone}: ${color};\\n`;\n }\n\n // Generate secondary palette\n css += `\\n /* Secondary Colors */\\n`;\n for (const tone of tones) {\n const color = rgbToHex(corePalette.secondary.tone(tone));\n css += ` --${prefix}-secondary-${tone}: ${color};\\n`;\n }\n\n // Generate tertiary palette\n css += `\\n /* Tertiary Colors */\\n`;\n for (const tone of tones) {\n const color = rgbToHex(corePalette.tertiary.tone(tone));\n css += ` --${prefix}-tertiary-${tone}: ${color};\\n`;\n }\n\n // Generate error palette\n css += `\\n /* Error Colors */\\n`;\n for (const tone of tones) {\n const color = rgbToHex(corePalette.error.tone(tone));\n css += ` --${prefix}-error-${tone}: ${color};\\n`;\n }\n\n // Generate neutral palette\n css += `\\n /* Neutral Colors */\\n`;\n for (const tone of tones) {\n const color = rgbToHex(corePalette.neutral.tone(tone));\n css += ` --${prefix}-neutral-${tone}: ${color};\\n`;\n }\n\n // Generate neutral variant palette\n css += `\\n /* Neutral Variant Colors */\\n`;\n for (const tone of tones) {\n const color = rgbToHex(corePalette.neutralVariant.tone(tone));\n css += ` --${prefix}-neutral-variant-${tone}: ${color};\\n`;\n }\n\n css += `}\\n\\n`;\n\n // Add semantic mappings\n css += `/* Semantic Color Mappings (Light Theme) */\\n`;\n css += `:root {\\n`;\n css += ` --${prefix}-primary: var(--${prefix}-primary-40);\\n`;\n css += ` --${prefix}-on-primary: var(--${prefix}-primary-100);\\n`;\n css += ` --${prefix}-primary-container: var(--${prefix}-primary-90);\\n`;\n css += ` --${prefix}-on-primary-container: var(--${prefix}-primary-10);\\n`;\n css += ` \\n`;\n css += ` --${prefix}-secondary: var(--${prefix}-secondary-40);\\n`;\n css += ` --${prefix}-on-secondary: var(--${prefix}-secondary-100);\\n`;\n css += ` --${prefix}-secondary-container: var(--${prefix}-secondary-90);\\n`;\n css += ` --${prefix}-on-secondary-container: var(--${prefix}-secondary-10);\\n`;\n css += ` \\n`;\n css += ` --${prefix}-background: var(--${prefix}-neutral-99);\\n`;\n css += ` --${prefix}-on-background: var(--${prefix}-neutral-10);\\n`;\n css += ` --${prefix}-surface: var(--${prefix}-neutral-99);\\n`;\n css += ` --${prefix}-on-surface: var(--${prefix}-neutral-10);\\n`;\n css += `}\\n`;\n\n return css;\n },\n name: \"generate_theme_css\",\n parameters: z.object({\n includeTones: z\n .array(z.number())\n .optional()\n .describe(\n \"Tone values to include (default: 0,10,20,30,40,50,60,70,80,90,95,99,100)\",\n ),\n prefix: z\n .string()\n .optional()\n .default(\"color\")\n .describe(\n \"Prefix for CSS variables (e.g., 'color' → --color-primary-50)\",\n ),\n sourceColor: z.string().describe(\"Source color for theme generation\"),\n }),\n};\n","/**\n * Theme Color Matcher\n * Finds closest theme colors using HCT perceptual distance\n */\n\nimport type { HCT } from \"../color/hct/types.js\";\nimport type {\n ColorContext,\n MatchingOptions,\n SemanticRole,\n ThemeMatch,\n ThemeVariable,\n ThemeVariables,\n} from \"./types.js\";\n\nimport { hexToRgb } from \"../color/conversions.js\";\nimport { rgbToHct } from \"../color/hct/hct-solver.js\";\nimport { getContrastRatio } from \"../color/utils.js\";\n\n/**\n * Default matching weights\n */\nconst DEFAULT_WEIGHTS = {\n accessibility: 0.2,\n perceptual: 0.6,\n semantic: 0.2,\n};\n\n/**\n * Maximum acceptable distances for different contexts\n */\nconst CONTEXT_MAX_DISTANCES: Record<ColorContext, number> = {\n accent: 15, // Moderate for brand consistency\n background: 15, // Moderate flexibility\n border: 20, // More flexibility\n decorative: 30, // Most flexible\n shadow: 25, // Even more flexibility\n text: 10, // Strict for readability\n};\n\n/**\n * Find matches for multiple colors\n */\nexport function findBatchMatches(\n colors: string[],\n themeVariables: ThemeVariables,\n options: MatchingOptions = {},\n): Map<string, null | ThemeMatch> {\n const results = new Map<string, null | ThemeMatch>();\n\n for (const color of colors) {\n results.set(color, findClosestThemeColor(color, themeVariables, options));\n }\n\n return results;\n}\n\n/**\n * Find the closest theme color for a given input color\n */\nexport function findClosestThemeColor(\n inputColor: string,\n themeVariables: ThemeVariables,\n options: MatchingOptions = {},\n): null | ThemeMatch {\n // Parse input color to HCT\n let inputHct: HCT;\n try {\n const rgb = parseColorToRgb(inputColor);\n inputHct = rgbToHct(rgb);\n } catch {\n console.error(`Failed to parse input color: ${inputColor}`);\n return null;\n }\n\n // Flatten theme variables\n const allVariables = flattenThemeVariables(themeVariables);\n if (allVariables.length === 0) {\n return null;\n }\n\n // Calculate distances and scores\n const candidates = allVariables.map((variable) => ({\n distance: calculateHctDistance(inputHct, variable.hct),\n score: 0, // Will be calculated next\n variable,\n }));\n\n // Apply context-based filtering\n const maxDistance =\n options.maxDistance ??\n (options.contextType ? CONTEXT_MAX_DISTANCES[options.contextType] : 30);\n\n const validCandidates = candidates.filter((c) => c.distance <= maxDistance);\n if (validCandidates.length === 0) {\n return null;\n }\n\n // Calculate multi-factor scores\n const weights = options.weights ?? DEFAULT_WEIGHTS;\n for (const candidate of validCandidates) {\n candidate.score = calculateMatchScore(\n inputHct,\n candidate.variable,\n candidate.distance,\n weights,\n options,\n );\n }\n\n // Sort by score (higher is better)\n validCandidates.sort((a, b) => b.score - a.score);\n\n // Get the best match and alternatives\n const best = validCandidates[0];\n const alternatives = validCandidates.slice(1, 4).map((c) => ({\n alternatives: [],\n confidence: calculateConfidence(c.distance, c.score),\n distance: c.distance,\n semanticRole: c.variable.role,\n value: c.variable.value,\n variable: c.variable.name,\n }));\n\n // Calculate accessibility info if needed\n const accessibilityInfo =\n options.contextType === \"text\" || options.contextType === \"background\"\n ? calculateAccessibilityInfo(best.variable.value, themeVariables)\n : undefined;\n\n return {\n accessibilityInfo,\n alternatives,\n confidence: calculateConfidence(best.distance, best.score),\n distance: best.distance,\n semanticRole: best.variable.role,\n value: best.variable.value,\n variable: best.variable.name,\n };\n}\n\n/**\n * Calculate accessibility information\n */\nfunction calculateAccessibilityInfo(\n color: string,\n themeVariables: ThemeVariables,\n): ThemeMatch[\"accessibilityInfo\"] {\n const rgb = parseColorToRgb(color);\n\n // Find typical background and foreground colors\n const backgrounds = findTypicalBackgrounds(themeVariables);\n const foregrounds = findTypicalForegrounds(themeVariables);\n\n let maxContrastBg = 0;\n let maxContrastFg = 0;\n\n for (const bg of backgrounds) {\n const bgRgb = parseColorToRgb(bg.value);\n const contrast = getContrastRatio(rgb, bgRgb);\n maxContrastBg = Math.max(maxContrastBg, contrast);\n }\n\n for (const fg of foregrounds) {\n const fgRgb = parseColorToRgb(fg.value);\n const contrast = getContrastRatio(rgb, fgRgb);\n maxContrastFg = Math.max(maxContrastFg, contrast);\n }\n\n return {\n contrastWithBackground: maxContrastBg,\n contrastWithForeground: maxContrastFg,\n meetsAA: maxContrastBg >= 4.5 || maxContrastFg >= 4.5,\n meetsAAA: maxContrastBg >= 7.0 || maxContrastFg >= 7.0,\n };\n}\n\n/**\n * Calculate confidence score (0-100)\n */\nfunction calculateConfidence(distance: number, score: number): number {\n // For very small distances (exact or near-exact matches), return high confidence\n if (distance < 0.5) return 100;\n if (distance < 1) return 98;\n if (distance < 2) return 95;\n\n // Combine distance and score for confidence\n const distanceConfidence = Math.max(0, 100 - distance * 2);\n const scoreConfidence = score * 100;\n return Math.round((distanceConfidence + scoreConfidence) / 2);\n}\n\n/**\n * Calculate semantic score based on context\n */\nfunction calculateContextSemanticScore(\n context: ColorContext,\n role: SemanticRole | undefined,\n): number {\n if (!role) return 0.5;\n\n switch (context) {\n case \"accent\":\n return role === \"primary\" || role === \"secondary\" ? 1.0 : 0.5;\n case \"background\":\n return role === \"surface\" || role === \"background\" ? 1.0 : 0.3;\n case \"border\":\n // Strongly prefer outline role for border context\n return role === \"outline\" ? 1.0 : role === \"neutral\" ? 0.4 : 0.2;\n case \"decorative\":\n return 0.7; // Any role is acceptable\n case \"shadow\":\n return role === \"shadow\" ? 1.0 : 0.3;\n case \"text\":\n return role === \"neutral\" || role === \"surface\" ? 0.8 : 0.5;\n default:\n return 0.5;\n }\n}\n\n/**\n * Calculate HCT perceptual distance\n */\nfunction calculateHctDistance(color1: HCT, color2: HCT): number {\n // Weight factors for HCT components\n const hueWeight = 1.0;\n const chromaWeight = 1.0;\n const toneWeight = 2.0; // Tone is most important for perception\n\n // Calculate hue difference (circular)\n let hueDiff = Math.abs(color1.h - color2.h);\n if (hueDiff > 180) {\n hueDiff = 360 - hueDiff;\n }\n\n // Normalize hue difference (0-1)\n hueDiff = hueDiff / 180;\n\n // Calculate chroma difference (normalize by max chroma ~120)\n const chromaDiff = Math.abs(color1.c - color2.c) / 120;\n\n // Calculate tone difference (0-100)\n const toneDiff = Math.abs(color1.t - color2.t) / 100;\n\n // Weighted Euclidean distance\n return (\n Math.sqrt(\n Math.pow(hueDiff * hueWeight, 2) +\n Math.pow(chromaDiff * chromaWeight, 2) +\n Math.pow(toneDiff * toneWeight, 2),\n ) * 100\n ); // Scale to 0-100 range\n}\n\n/**\n * Calculate multi-factor match score\n */\nfunction calculateMatchScore(\n _inputHct: HCT,\n candidate: ThemeVariable,\n distance: number,\n weights: { accessibility: number; perceptual: number; semantic: number },\n options: MatchingOptions,\n): number {\n // Perceptual score (inverse of distance)\n const perceptualScore = Math.max(0, 100 - distance) / 100;\n\n // Semantic score\n let semanticScore = 0.5; // Neutral if no preference\n if (options.preferredRole && candidate.role) {\n semanticScore = candidate.role === options.preferredRole ? 1.0 : 0.3;\n } else if (options.contextType) {\n semanticScore = calculateContextSemanticScore(\n options.contextType,\n candidate.role,\n );\n }\n\n // Accessibility score (based on tone appropriateness)\n let accessibilityScore = 0.5; // Neutral default\n if (options.contextType === \"text\") {\n // Prefer high contrast (very light or very dark)\n accessibilityScore = candidate.tone < 30 || candidate.tone > 70 ? 1.0 : 0.3;\n } else if (options.contextType === \"background\") {\n // Prefer mid-tones for backgrounds\n accessibilityScore =\n candidate.tone >= 90 || candidate.tone <= 10 ? 1.0 : 0.5;\n }\n\n // Calculate weighted score\n return (\n perceptualScore * weights.perceptual +\n semanticScore * weights.semantic +\n accessibilityScore * weights.accessibility\n );\n}\n\n/**\n * Find typical background colors from theme\n */\nfunction findTypicalBackgrounds(theme: ThemeVariables): ThemeVariable[] {\n const backgrounds: ThemeVariable[] = [];\n\n if (theme.surface) {\n backgrounds.push(\n ...theme.surface.filter((v) => v.tone >= 90 || v.tone <= 10),\n );\n }\n if (theme.background) {\n backgrounds.push(...theme.background);\n }\n if (theme.neutral) {\n backgrounds.push(\n ...theme.neutral.filter((v) => v.tone >= 95 || v.tone <= 5),\n );\n }\n\n return backgrounds;\n}\n\n/**\n * Find typical foreground colors from theme\n */\nfunction findTypicalForegrounds(theme: ThemeVariables): ThemeVariable[] {\n const foregrounds: ThemeVariable[] = [];\n\n if (theme.neutral) {\n foregrounds.push(\n ...theme.neutral.filter(\n (v) => (v.tone >= 20 && v.tone <= 40) || (v.tone >= 60 && v.tone <= 80),\n ),\n );\n }\n if (theme.surface) {\n foregrounds.push(\n ...theme.surface.filter((v) => v.tone >= 10 && v.tone <= 30),\n );\n }\n\n return foregrounds;\n}\n\n/**\n * Flatten theme variables into a single array\n */\nfunction flattenThemeVariables(theme: ThemeVariables): ThemeVariable[] {\n const variables: ThemeVariable[] = [];\n\n // Add standard roles\n if (theme.primary) variables.push(...theme.primary);\n if (theme.secondary) variables.push(...theme.secondary);\n if (theme.tertiary) variables.push(...theme.tertiary);\n if (theme.error) variables.push(...theme.error);\n if (theme.neutral) variables.push(...theme.neutral);\n if (theme.surface) variables.push(...theme.surface);\n if (theme.background) variables.push(...theme.background);\n if (theme.outline) variables.push(...theme.outline);\n if (theme.shadow) variables.push(...theme.shadow);\n\n // Add custom roles\n if (theme.custom) {\n for (const customVars of Object.values(theme.custom)) {\n variables.push(...customVars);\n }\n }\n\n return variables;\n}\n\n/**\n * Parse color string to RGB\n */\nfunction parseColorToRgb(color: string): { b: number; g: number; r: number } {\n // Remove whitespace\n color = color.trim();\n\n // Hex color\n if (color.startsWith(\"#\")) {\n return hexToRgb(color);\n }\n\n // RGB/RGBA\n if (color.startsWith(\"rgb\")) {\n const match = color.match(/rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)/);\n if (match) {\n return {\n b: parseInt(match[3], 10) / 255,\n g: parseInt(match[2], 10) / 255,\n r: parseInt(match[1], 10) / 255,\n };\n }\n }\n\n throw new Error(`Unable to parse color: ${color}`);\n}\n","/**\n * Theme Parser\n * Parses CSS variables and extracts theme colors\n */\n\nimport type { SemanticRole, ThemeVariable, ThemeVariables } from \"./types.js\";\n\nimport { hexToRgb } from \"../color/conversions.js\";\nimport { rgbToHct } from \"../color/hct/hct-solver.js\";\n\n/**\n * Parse CSS content and extract theme variables\n */\nexport function parseThemeVariables(css: string): ThemeVariables {\n const variables: ThemeVariable[] = [];\n\n // Match CSS custom properties\n const varRegex = /--([\\w-]+):\\s*([^;]+);/g;\n let match;\n\n while ((match = varRegex.exec(css)) !== null) {\n const [, name, value] = match;\n const fullName = `--${name}`;\n const trimmedValue = value.trim();\n\n // Check if it's a color value\n if (isColorValue(trimmedValue)) {\n const colorValue = normalizeColorValue(trimmedValue);\n if (colorValue) {\n try {\n const rgb = parseColorToRgb(colorValue);\n const hct = rgbToHct(rgb);\n\n variables.push({\n hct,\n name: fullName,\n role: detectSemanticRole(name),\n tone: hct.t,\n value: colorValue,\n });\n } catch {\n // Skip invalid color values\n console.warn(\n `Failed to parse color variable ${fullName}: ${trimmedValue}`,\n );\n }\n }\n }\n }\n\n // Organize variables by role\n return organizeByRole(variables);\n}\n\n/**\n * Parse CSS variables from an object (e.g., from getComputedStyle)\n */\nexport function parseThemeVariablesFromObject(\n variables: Record<string, string>,\n): ThemeVariables {\n const themeVars: ThemeVariable[] = [];\n\n for (const [name, value] of Object.entries(variables)) {\n if (name.startsWith(\"--\") && isColorValue(value)) {\n const colorValue = normalizeColorValue(value);\n if (colorValue) {\n try {\n const rgb = parseColorToRgb(colorValue);\n const hct = rgbToHct(rgb);\n\n themeVars.push({\n hct,\n name,\n role: detectSemanticRole(name.slice(2)), // Remove -- prefix\n tone: hct.t,\n value: colorValue,\n });\n } catch {\n console.warn(`Failed to parse color variable ${name}: ${value}`);\n }\n }\n }\n }\n\n return organizeByRole(themeVars);\n}\n\n/**\n * Detect semantic role from variable name\n */\nfunction detectSemanticRole(name: string): SemanticRole | undefined {\n const lower = name.toLowerCase();\n\n if (lower.includes(\"primary\")) return \"primary\";\n if (lower.includes(\"secondary\")) return \"secondary\";\n if (lower.includes(\"tertiary\")) return \"tertiary\";\n if (lower.includes(\"error\") || lower.includes(\"danger\")) return \"error\";\n if (lower.includes(\"neutral\") || lower.includes(\"gray\")) return \"neutral\";\n if (lower.includes(\"surface\")) return \"surface\";\n if (lower.includes(\"background\") || lower.includes(\"bg\")) return \"background\";\n if (lower.includes(\"outline\") || lower.includes(\"border\")) return \"outline\";\n if (lower.includes(\"shadow\")) return \"shadow\";\n\n return undefined;\n}\n\n/**\n * HSL to RGB helper\n */\nfunction hslToRgb(\n h: number,\n s: number,\n l: number,\n): { b: number; g: number; r: number } {\n let b, g, r;\n\n if (s === 0) {\n r = g = b = l;\n } else {\n const hue2rgb = (p: number, q: number, t: number) => {\n if (t < 0) t += 1;\n if (t > 1) t -= 1;\n if (t < 1 / 6) return p + (q - p) * 6 * t;\n if (t < 1 / 2) return q;\n if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;\n return p;\n };\n\n const q = l < 0.5 ? l * (1 + s) : l + s - l * s;\n const p = 2 * l - q;\n r = hue2rgb(p, q, h + 1 / 3);\n g = hue2rgb(p, q, h);\n b = hue2rgb(p, q, h - 1 / 3);\n }\n\n return { b, g, r };\n}\n\n/**\n * Check if a value is a color\n */\nfunction isColorValue(value: string): boolean {\n const trimmed = value.trim();\n\n // Hex colors\n if (/^#[0-9a-fA-F]{3,8}$/.test(trimmed)) return true;\n\n // RGB/RGBA\n if (/^rgba?\\(/.test(trimmed)) return true;\n\n // HSL/HSLA\n if (/^hsla?\\(/.test(trimmed)) return true;\n\n // Named colors (basic check)\n if (/^[a-z]+$/i.test(trimmed)) {\n return isNamedColor(trimmed);\n }\n\n return false;\n}\n\n/**\n * Check if string is a named color\n */\nfunction isNamedColor(name: string): boolean {\n const namedColors = [\n \"black\",\n \"white\",\n \"red\",\n \"green\",\n \"blue\",\n \"yellow\",\n \"cyan\",\n \"magenta\",\n \"gray\",\n \"grey\",\n \"orange\",\n \"purple\",\n \"brown\",\n \"pink\",\n \"lime\",\n \"navy\",\n \"teal\",\n \"silver\",\n \"gold\",\n \"indigo\",\n \"violet\",\n \"turquoise\",\n \"coral\",\n ];\n return namedColors.includes(name.toLowerCase());\n}\n\n/**\n * Convert named color to hex (simplified)\n */\nfunction namedColorToHex(name: string): string {\n const colors: Record<string, string> = {\n black: \"#000000\",\n blue: \"#0000ff\",\n brown: \"#a52a2a\",\n coral: \"#ff7f50\",\n cyan: \"#00ffff\",\n gold: \"#ffd700\",\n gray: \"#808080\",\n green: \"#008000\",\n grey: \"#808080\",\n indigo: \"#4b0082\",\n lime: \"#00ff00\",\n magenta: \"#ff00ff\",\n navy: \"#000080\",\n orange: \"#ffa500\",\n pink: \"#ffc0cb\",\n purple: \"#800080\",\n red: \"#ff0000\",\n silver: \"#c0c0c0\",\n teal: \"#008080\",\n turquoise: \"#40e0d0\",\n violet: \"#ee82ee\",\n white: \"#ffffff\",\n yellow: \"#ffff00\",\n };\n return colors[name.toLowerCase()] || \"#000000\";\n}\n\n/**\n * Normalize color value to a standard format\n */\nfunction normalizeColorValue(value: string): null | string {\n const trimmed = value.trim();\n\n // Already in a good format\n if (/^#[0-9a-fA-F]{6}$/.test(trimmed)) {\n return trimmed;\n }\n\n // Short hex\n if (/^#[0-9a-fA-F]{3}$/.test(trimmed)) {\n const [, r, g, b] = trimmed.match(/#(.)(.)(.)/)!;\n return `#${r}${r}${g}${g}${b}${b}`;\n }\n\n // RGB/RGBA\n if (/^rgba?\\(/.test(trimmed)) {\n return parseRgbString(trimmed);\n }\n\n // HSL/HSLA\n if (/^hsla?\\(/.test(trimmed)) {\n return parseHslString(trimmed);\n }\n\n // Named colors\n if (isNamedColor(trimmed)) {\n return namedColorToHex(trimmed);\n }\n\n return null;\n}\n\n/**\n * Organize variables by semantic role\n */\nfunction organizeByRole(variables: ThemeVariable[]): ThemeVariables {\n const organized: ThemeVariables = {\n custom: {},\n };\n\n for (const variable of variables) {\n if (variable.role) {\n const role = variable.role;\n if (!organized[role]) {\n organized[role] = [];\n }\n organized[role].push(variable);\n } else {\n // Extract custom role from name pattern (e.g., --color-brand-50, --accent-warm)\n const colorPattern = variable.name.match(/--(?:color-)?([a-z]+)-\\d+/i);\n const namedPattern = variable.name.match(/--([a-z]+)-[a-z]+/i);\n\n if (colorPattern) {\n const customRole = colorPattern[1].toLowerCase();\n if (!organized.custom![customRole]) {\n organized.custom![customRole] = [];\n }\n organized.custom![customRole].push(variable);\n } else if (namedPattern) {\n const customRole = namedPattern[1].toLowerCase();\n // Only use this pattern if it's a known semantic pattern\n const knownPatterns = [\n \"accent\",\n \"neutral\",\n \"success\",\n \"warning\",\n \"info\",\n ];\n if (knownPatterns.some((p) => customRole.includes(p))) {\n if (!organized.custom![customRole]) {\n organized.custom![customRole] = [];\n }\n organized.custom![customRole].push(variable);\n } else {\n // Unknown pattern, put in uncategorized\n if (!organized.custom![\"uncategorized\"]) {\n organized.custom![\"uncategorized\"] = [];\n }\n organized.custom![\"uncategorized\"].push(variable);\n }\n } else {\n // Uncategorized\n if (!organized.custom![\"uncategorized\"]) {\n organized.custom![\"uncategorized\"] = [];\n }\n organized.custom![\"uncategorized\"].push(variable);\n }\n }\n }\n\n // Sort each role by tone\n for (const role of Object.keys(organized)) {\n if (Array.isArray(organized[role as keyof ThemeVariables])) {\n (organized[role as keyof ThemeVariables] as ThemeVariable[]).sort(\n (a, b) => a.tone - b.tone,\n );\n } else if (role === \"custom\" && organized.custom) {\n for (const customRole of Object.keys(organized.custom)) {\n organized.custom[customRole].sort((a, b) => a.tone - b.tone);\n }\n }\n }\n\n return organized;\n}\n\n/**\n * Parse color to RGB\n */\nfunction parseColorToRgb(color: string): { b: number; g: number; r: number } {\n // Hex color\n if (color.startsWith(\"#\")) {\n return hexToRgb(color);\n }\n\n // RGB string\n if (color.startsWith(\"rgb\")) {\n const match = color.match(/rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)/);\n if (match) {\n return {\n b: parseInt(match[3], 10) / 255,\n g: parseInt(match[2], 10) / 255,\n r: parseInt(match[1], 10) / 255,\n };\n }\n }\n\n throw new Error(`Unable to parse color: ${color}`);\n}\n\n/**\n * Parse HSL/HSLA string to hex\n */\nfunction parseHslString(hsl: string): null | string {\n const match = hsl.match(/hsla?\\((\\d+),\\s*(\\d+)%,\\s*(\\d+)%/);\n if (match) {\n const h = parseInt(match[1], 10) / 360;\n const s = parseInt(match[2], 10) / 100;\n const l = parseInt(match[3], 10) / 100;\n\n // HSL to RGB conversion\n const rgb = hslToRgb(h, s, l);\n const r = Math.round(rgb.r * 255);\n const g = Math.round(rgb.g * 255);\n const b = Math.round(rgb.b * 255);\n\n return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;\n }\n return null;\n}\n\n/**\n * Parse RGB/RGBA string to hex\n */\nfunction parseRgbString(rgb: string): null | string {\n const match = rgb.match(/rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+)/);\n if (match) {\n const r = parseInt(match[1], 10);\n const g = parseInt(match[2], 10);\n const b = parseInt(match[3], 10);\n return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;\n }\n return null;\n}\n","/**\n * CSS Refactoring Utilities\n * Refactor CSS to use theme variables\n */\n\nimport type {\n ColorContext,\n ColorReplacement,\n MatchingOptions,\n RefactoringResult,\n RefactoringWarning,\n ThemeVariables,\n} from \"./types.js\";\n\nimport { findClosestThemeColor } from \"./matcher.js\";\n\n/**\n * CSS property to context mapping\n */\nconst PROPERTY_CONTEXT_MAP: Record<string, ColorContext> = {\n background: \"background\",\n \"background-color\": \"background\",\n border: \"border\",\n \"border-bottom-color\": \"border\",\n \"border-color\": \"border\",\n \"border-left-color\": \"border\",\n \"border-right-color\": \"border\",\n \"border-top-color\": \"border\",\n \"box-shadow\": \"shadow\",\n color: \"text\",\n fill: \"decorative\",\n outline: \"border\",\n \"outline-color\": \"border\",\n \"stop-color\": \"decorative\",\n stroke: \"border\",\n \"text-shadow\": \"shadow\",\n};\n\n/**\n * Generate a refactoring report\n */\nexport function generateRefactoringReport(result: RefactoringResult): string {\n const lines: string[] = [\n \"# CSS Refactoring Report\",\n \"\",\n \"## Summary\",\n `- Total colors found: ${result.statistics.totalColors}`,\n `- Colors replaced: ${result.statistics.replacedColors}`,\n `- Replacement rate: ${Math.round((result.statistics.replacedColors / result.statistics.totalColors) * 100)}%`,\n `- Average confidence: ${result.statistics.averageConfidence}%`,\n `- Accessibility issues: ${result.statistics.accessibilityIssues}`,\n \"\",\n \"## Replacements\",\n ];\n\n // Group replacements by confidence\n const highConfidence = result.replacements.filter((r) => r.confidence >= 90);\n const mediumConfidence = result.replacements.filter(\n (r) => r.confidence >= 70 && r.confidence < 90,\n );\n const lowConfidence = result.replacements.filter((r) => r.confidence < 70);\n\n if (highConfidence.length > 0) {\n lines.push(\"\", \"### High Confidence (≥90%)\");\n for (const replacement of highConfidence) {\n lines.push(\n `- Line ${replacement.line}: ${replacement.originalColor} → ${replacement.cssVariable} (${replacement.confidence}%)`,\n );\n }\n }\n\n if (mediumConfidence.length > 0) {\n lines.push(\"\", \"### Medium Confidence (70-89%)\");\n for (const replacement of mediumConfidence) {\n lines.push(\n `- Line ${replacement.line}: ${replacement.originalColor} → ${replacement.cssVariable} (${replacement.confidence}%)`,\n );\n }\n }\n\n if (lowConfidence.length > 0) {\n lines.push(\"\", \"### Low Confidence (<70%)\");\n for (const replacement of lowConfidence) {\n lines.push(\n `- Line ${replacement.line}: ${replacement.originalColor} → ${replacement.cssVariable} (${replacement.confidence}%)`,\n );\n }\n }\n\n // Add warnings\n if (result.warnings.length > 0) {\n lines.push(\"\", \"## Warnings\");\n\n const warningsByType = result.warnings.reduce(\n (acc, warning) => {\n if (!acc[warning.type]) acc[warning.type] = [];\n acc[warning.type].push(warning);\n return acc;\n },\n {} as Record<string, typeof result.warnings>,\n );\n\n for (const [type, warnings] of Object.entries(warningsByType)) {\n lines.push(\"\", `### ${formatWarningType(type)}`);\n for (const warning of warnings) {\n lines.push(`- ${warning.message}`);\n if (warning.suggestion) {\n lines.push(` Suggestion: ${warning.suggestion}`);\n }\n }\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Refactor a single color value\n */\nexport function refactorColor(\n color: string,\n themeVariables: ThemeVariables,\n context?: ColorContext,\n): {\n alternatives: string[];\n confidence: number;\n variable: null | string;\n} {\n const match = findClosestThemeColor(color, themeVariables, {\n contextType: context,\n });\n\n if (!match) {\n return {\n alternatives: [],\n confidence: 0,\n variable: null,\n };\n }\n\n return {\n alternatives: match.alternatives.map((alt) => alt.variable),\n confidence: match.confidence,\n variable: match.variable,\n };\n}\n\n/**\n * Refactor CSS content to use theme variables\n */\nexport function refactorCss(\n css: string,\n themeVariables: ThemeVariables,\n options: {\n addComments?: boolean;\n minConfidence?: number;\n preserveOriginal?: boolean;\n } = {},\n): RefactoringResult {\n const {\n addComments = true,\n minConfidence = 70,\n preserveOriginal = true,\n } = options;\n\n const replacements: ColorReplacement[] = [];\n const warnings: RefactoringWarning[] = [];\n let refactoredCss: string;\n let totalColors = 0;\n let replacedColors = 0;\n let totalConfidence = 0;\n let accessibilityIssues = 0;\n\n // Process CSS line by line for better tracking\n const lines = css.split(\"\\n\");\n const refactoredLines: string[] = [];\n\n for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {\n const line = lines[lineIndex];\n let refactoredLine = line;\n\n // Detect CSS property\n const propertyMatch = line.match(/^\\s*([a-z-]+):\\s*/i);\n const property = propertyMatch ? propertyMatch[1].toLowerCase() : null;\n const context = property ? PROPERTY_CONTEXT_MAP[property] : undefined;\n\n // Find all color values in the line\n const colorMatches = findColorsInLine(line);\n\n for (const colorMatch of colorMatches) {\n totalColors++;\n const { color, end, start } = colorMatch;\n\n // Find matching theme variable\n const matchOptions: MatchingOptions = {\n contextType: context,\n weights: {\n accessibility:\n context === \"text\" || context === \"background\" ? 0.3 : 0.1,\n perceptual: 0.6,\n semantic: context ? 0.3 : 0.2,\n },\n };\n\n const match = findClosestThemeColor(color, themeVariables, matchOptions);\n\n if (match && match.confidence >= minConfidence) {\n replacedColors++;\n totalConfidence += match.confidence;\n\n // Create replacement\n const replacement: ColorReplacement = {\n column: start,\n confidence: match.confidence,\n context,\n cssVariable: match.variable,\n line: lineIndex + 1,\n originalColor: color,\n property: property || undefined,\n };\n replacements.push(replacement);\n\n // Check accessibility\n if (match.accessibilityInfo && !match.accessibilityInfo.meetsAA) {\n accessibilityIssues++;\n warnings.push({\n location: { column: start, line: lineIndex + 1 },\n message: `Color ${color} replaced with ${match.variable} may have accessibility issues`,\n type: \"accessibility\",\n });\n }\n\n // Apply replacement to line\n let replacementText = `var(${match.variable})`;\n\n if (preserveOriginal && addComments) {\n replacementText = `/* ${color} */ ${replacementText}`;\n }\n\n // Replace in line\n refactoredLine =\n refactoredLine.substring(0, start) +\n replacementText +\n refactoredLine.substring(end);\n } else if (match && match.confidence < minConfidence) {\n warnings.push({\n location: { column: start, line: lineIndex + 1 },\n message: `Low confidence match for ${color}: ${match.variable} (${match.confidence}%)`,\n suggestion: `Consider using ${match.variable} or defining a new theme variable`,\n type: \"low-confidence\",\n });\n } else {\n warnings.push({\n location: { column: start, line: lineIndex + 1 },\n message: `No suitable theme variable found for ${color}`,\n suggestion: \"Consider adding this color to your theme\",\n type: \"no-match\",\n });\n }\n }\n\n refactoredLines.push(refactoredLine);\n }\n\n // Add summary comment at the top if requested\n if (addComments && replacedColors > 0) {\n const summaryComment = `/* CSS Refactored with Theme Variables\n * Total colors found: ${totalColors}\n * Colors replaced: ${replacedColors}\n * Average confidence: ${Math.round(totalConfidence / replacedColors)}%\n * Warnings: ${warnings.length}\n */\\n\\n`;\n refactoredCss = summaryComment + refactoredLines.join(\"\\n\");\n } else {\n refactoredCss = refactoredLines.join(\"\\n\");\n }\n\n return {\n original: css,\n refactored: refactoredCss,\n replacements,\n statistics: {\n accessibilityIssues,\n averageConfidence:\n replacedColors > 0 ? Math.round(totalConfidence / replacedColors) : 0,\n replacedColors,\n totalColors,\n },\n warnings,\n };\n}\n\n/**\n * Find all color values in a line\n */\nfunction findColorsInLine(\n line: string,\n): Array<{ color: string; end: number; start: number }> {\n const colors: Array<{ color: string; end: number; start: number }> = [];\n\n // Check for hex colors\n let match;\n const hexRegex = /#[0-9a-fA-F]{3,8}/g;\n while ((match = hexRegex.exec(line)) !== null) {\n colors.push({\n color: match[0],\n end: match.index + match[0].length,\n start: match.index,\n });\n }\n\n // Check for rgb/rgba - be more precise with the regex\n const rgbRegex = /rgba?\\(\\s*\\d+\\s*,\\s*\\d+\\s*,\\s*\\d+(?:\\s*,\\s*[\\d.]+)?\\s*\\)/g;\n while ((match = rgbRegex.exec(line)) !== null) {\n colors.push({\n color: match[0],\n end: match.index + match[0].length,\n start: match.index,\n });\n }\n\n // Check for hsl/hsla\n const hslRegex = /hsla?\\([^)]+\\)/g;\n while ((match = hslRegex.exec(line)) !== null) {\n colors.push({\n color: match[0],\n end: match.index + match[0].length,\n start: match.index,\n });\n }\n\n // Sort by position to handle overlaps\n colors.sort((a, b) => a.start - b.start);\n\n // Remove duplicates and overlaps\n const uniqueColors: typeof colors = [];\n let lastEnd = -1;\n\n for (const color of colors) {\n if (color.start >= lastEnd) {\n uniqueColors.push(color);\n lastEnd = color.end;\n }\n }\n\n return uniqueColors;\n}\n\n/**\n * Format warning type for display\n */\nfunction formatWarningType(type: string): string {\n const formats: Record<string, string> = {\n accessibility: \"Accessibility Concerns\",\n \"low-confidence\": \"Low Confidence Matches\",\n \"no-match\": \"No Matches Found\",\n \"semantic-mismatch\": \"Semantic Mismatches\",\n };\n return formats[type] || type;\n}\n","#!/usr/bin/env node\n\n/**\n * Coolors MCP Server - Advanced Color Operations & Theme Intelligence\n *\n * A comprehensive Model Context Protocol server providing:\n * - Color space conversions (RGB, HSL, HSV, LAB, XYZ, HCT)\n * - Material Design 3 theme generation with tonal palettes\n * - Intelligent CSS theme matching with multi-factor scoring\n * - Image color extraction using Celebi quantization\n * - WCAG accessibility compliance checking\n * - Universal color preference analysis (dislike detection)\n * - Context-aware color selection for UI components\n *\n * Built on Google's HCT color space for perceptually uniform operations\n * and Material Color Utilities algorithms for professional-grade results.\n */\n\nimport { CoolorsMcp } from \"../coolors-mcp.js\";\nimport * as tools from \"../tools/index.js\";\n\n// Create the MCP server\nconst server = new CoolorsMcp({\n instructions:\n \"Advanced color operations server with Material Design 3 support, CSS theme matching, image extraction, and accessibility compliance. Uses HCT color space for perceptually accurate operations.\",\n name: \"coolors-mcp\",\n version: \"1.1.0\",\n});\n\n// Core color operations: conversion, distance metrics, accessibility\nserver.addTool(tools.colorConversionTool);\nserver.addTool(tools.colorDistanceTool);\nserver.addTool(tools.contrastCheckerTool);\nserver.addTool(tools.adjustColorTool);\nserver.addTool(tools.paletteGeneratorTool);\nserver.addTool(tools.paletteWithLocksTool);\nserver.addTool(tools.gradientGeneratorTool);\nserver.addTool(tools.exportPaletteTool);\n\n// Color-blindness simulation & accessibility audit\nserver.addTool(tools.simulateColorBlindnessTool);\nserver.addTool(tools.checkPaletteAccessibilityTool);\n\n// Visual cohesion: tonal scales, state colors, palette consistency, semantics\nserver.addTool(tools.generateTonalScaleTool);\nserver.addTool(tools.generateStateColorsTool);\nserver.addTool(tools.analyzePaletteConsistencyTool);\nserver.addTool(tools.generateSemanticPaletteTool);\n\n// Material Design 3: theme generation, harmonization, tonal palettes\nserver.addTool(tools.generateMaterialThemeTool);\nserver.addTool(tools.harmonizeColorsTool);\nserver.addTool(tools.generateTonalPaletteTool);\n\n// CSS theme intelligence: matching, refactoring, migration\nserver.addTool(tools.matchThemeColorTool);\nserver.addTool(tools.refactorCssWithThemeTool);\nserver.addTool(tools.matchThemeColorsBatchTool);\nserver.addTool(tools.generateThemeCssTool);\n\n// Image analysis: color extraction, theme generation from photos\nserver.addTool(tools.extractImageColorsTool);\nserver.addTool(tools.generateThemeFromImageTool);\n\n// Color psychology: detect and fix universally disliked colors\nserver.addTool(tools.analyzeColorLikabilityTool);\nserver.addTool(tools.fixDislikedColorsBatchTool);\n\n// Start the server\nserver.start().catch((error) => {\n console.error(\"Failed to start server:\", error);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,SAAS,SAAS;AAclB,IAAM,MAAM;AAAA,EACV;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,kBAAkB;AAAA,EAC7B,aACE;AAAA,EACF,SAAS,OAAO,SAKV;AACJ,UAAM,MAAM,WAAW,KAAK,KAAK;AACjC,QAAI,CAAC,IAAK,QAAO,yBAAyB,KAAK,KAAK;AAEpD,Y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ChB,CAAC;","names":["z","z","z","g","z","z","z","z","z","z","z","z","z","z","z","z","z","z","delinearized","z","differenceDegrees","rgbToHex","z","z","z","z","z","z","z","z","z","z","parseColorToRgb","hslToRgb","p","q","parseColorToRgb","z"]}