@sarjallab09/figma-intelligence 1.0.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 (286) hide show
  1. package/LICENSE +26 -0
  2. package/README.md +327 -0
  3. package/bin/cli.js +859 -0
  4. package/design-bridge/.env.example +5 -0
  5. package/design-bridge/bridge.js +196 -0
  6. package/design-bridge/lib/assets.js +367 -0
  7. package/design-bridge/lib/prompt.js +85 -0
  8. package/design-bridge/lib/server.js +66 -0
  9. package/design-bridge/lib/stitch.js +37 -0
  10. package/design-bridge/lib/tokens.js +82 -0
  11. package/design-bridge/package-lock.json +579 -0
  12. package/design-bridge/package.json +19 -0
  13. package/figma-bridge-plugin/README.md +97 -0
  14. package/figma-bridge-plugin/anthropic-chat-runner.js +192 -0
  15. package/figma-bridge-plugin/bridge-relay.js +2363 -0
  16. package/figma-bridge-plugin/chat-runner.js +459 -0
  17. package/figma-bridge-plugin/code.js +1528 -0
  18. package/figma-bridge-plugin/codex-runner.js +505 -0
  19. package/figma-bridge-plugin/component-schemas.js +110 -0
  20. package/figma-bridge-plugin/content-context.js +869 -0
  21. package/figma-bridge-plugin/create-button.js +216 -0
  22. package/figma-bridge-plugin/gemini-cli-runner.js +291 -0
  23. package/figma-bridge-plugin/gemini-runner.js +187 -0
  24. package/figma-bridge-plugin/html-to-figma.js +927 -0
  25. package/figma-bridge-plugin/knowledge-hub/.gitkeep +0 -0
  26. package/figma-bridge-plugin/knowledge-hub/uspec-references/anatomy-spec.md +159 -0
  27. package/figma-bridge-plugin/knowledge-hub/uspec-references/api-spec.md +162 -0
  28. package/figma-bridge-plugin/knowledge-hub/uspec-references/color-spec.md +148 -0
  29. package/figma-bridge-plugin/knowledge-hub/uspec-references/full-spec-template.md +314 -0
  30. package/figma-bridge-plugin/knowledge-hub/uspec-references/property-spec.md +175 -0
  31. package/figma-bridge-plugin/knowledge-hub/uspec-references/screen-reader-spec.md +180 -0
  32. package/figma-bridge-plugin/knowledge-hub/uspec-references/structure-spec.md +165 -0
  33. package/figma-bridge-plugin/manifest.json +21 -0
  34. package/figma-bridge-plugin/package-lock.json +1936 -0
  35. package/figma-bridge-plugin/package.json +20 -0
  36. package/figma-bridge-plugin/perplexity-runner.js +188 -0
  37. package/figma-bridge-plugin/references/SKILL.md +178 -0
  38. package/figma-bridge-plugin/references/anatomy-spec.md +159 -0
  39. package/figma-bridge-plugin/references/api-spec.md +162 -0
  40. package/figma-bridge-plugin/references/color-spec.md +148 -0
  41. package/figma-bridge-plugin/references/full-spec-template.md +314 -0
  42. package/figma-bridge-plugin/references/property-spec.md +175 -0
  43. package/figma-bridge-plugin/references/screen-reader-spec.md +180 -0
  44. package/figma-bridge-plugin/references/structure-spec.md +165 -0
  45. package/figma-bridge-plugin/shared-prompt-config.js +604 -0
  46. package/figma-bridge-plugin/spec-helpers/build-table.js +269 -0
  47. package/figma-bridge-plugin/spec-helpers/classify-elements.js +189 -0
  48. package/figma-bridge-plugin/spec-helpers/index.js +35 -0
  49. package/figma-bridge-plugin/spec-helpers/parse-figma-link.js +49 -0
  50. package/figma-bridge-plugin/spec-helpers/position-markers.js +158 -0
  51. package/figma-bridge-plugin/stitch-auth.js +322 -0
  52. package/figma-bridge-plugin/stitch-runner.js +1427 -0
  53. package/figma-bridge-plugin/token-resolver.js +107 -0
  54. package/figma-bridge-plugin/ui.html +4467 -0
  55. package/figma-intelligence-layer/.env.example +39 -0
  56. package/figma-intelligence-layer/docs/local-image-generation.md +60 -0
  57. package/figma-intelligence-layer/examples/comfyui-workflow-template.example.json +101 -0
  58. package/figma-intelligence-layer/jest.config.js +14 -0
  59. package/figma-intelligence-layer/mcp-config.json +19 -0
  60. package/figma-intelligence-layer/package-lock.json +5892 -0
  61. package/figma-intelligence-layer/package.json +48 -0
  62. package/figma-intelligence-layer/scripts/setup-comfyui-local.sh +67 -0
  63. package/figma-intelligence-layer/scripts/start-comfyui.sh +33 -0
  64. package/figma-intelligence-layer/src/index.ts +2233 -0
  65. package/figma-intelligence-layer/src/shared/auto-layout-validator.ts +404 -0
  66. package/figma-intelligence-layer/src/shared/cache.ts +187 -0
  67. package/figma-intelligence-layer/src/shared/color-operations.ts +533 -0
  68. package/figma-intelligence-layer/src/shared/color-utils.ts +138 -0
  69. package/figma-intelligence-layer/src/shared/component-script-builder.ts +413 -0
  70. package/figma-intelligence-layer/src/shared/component-templates.ts +2767 -0
  71. package/figma-intelligence-layer/src/shared/concept-taxonomy.ts +694 -0
  72. package/figma-intelligence-layer/src/shared/decision-log.ts +128 -0
  73. package/figma-intelligence-layer/src/shared/design-system-context.ts +568 -0
  74. package/figma-intelligence-layer/src/shared/design-system-intelligence.ts +131 -0
  75. package/figma-intelligence-layer/src/shared/design-system-matcher.ts +184 -0
  76. package/figma-intelligence-layer/src/shared/design-system-normalizers.ts +196 -0
  77. package/figma-intelligence-layer/src/shared/design-system-tokens.ts +295 -0
  78. package/figma-intelligence-layer/src/shared/dtcg-validator.ts +530 -0
  79. package/figma-intelligence-layer/src/shared/enrichment-pipeline.ts +671 -0
  80. package/figma-intelligence-layer/src/shared/figma-bridge.ts +1408 -0
  81. package/figma-intelligence-layer/src/shared/font-config.ts +126 -0
  82. package/figma-intelligence-layer/src/shared/icon-catalog.ts +360 -0
  83. package/figma-intelligence-layer/src/shared/icon-fetch.ts +80 -0
  84. package/figma-intelligence-layer/src/shared/prototype-script-builder.ts +162 -0
  85. package/figma-intelligence-layer/src/shared/response-compression.ts +440 -0
  86. package/figma-intelligence-layer/src/shared/semantic-token-catalog.ts +324 -0
  87. package/figma-intelligence-layer/src/shared/token-binder.ts +505 -0
  88. package/figma-intelligence-layer/src/shared/token-math.ts +427 -0
  89. package/figma-intelligence-layer/src/shared/token-naming.ts +468 -0
  90. package/figma-intelligence-layer/src/shared/token-utils.ts +420 -0
  91. package/figma-intelligence-layer/src/shared/types.ts +346 -0
  92. package/figma-intelligence-layer/src/shared/typography-presets.ts +94 -0
  93. package/figma-intelligence-layer/src/shared/unsplash.ts +165 -0
  94. package/figma-intelligence-layer/src/shared/vision-client.ts +607 -0
  95. package/figma-intelligence-layer/src/shared/vision-provider-anthropic.ts +334 -0
  96. package/figma-intelligence-layer/src/shared/vision-provider-openai.ts +446 -0
  97. package/figma-intelligence-layer/src/tools/phase1-vision/a11y-audit/a11y-annotate-handler.ts +782 -0
  98. package/figma-intelligence-layer/src/tools/phase1-vision/a11y-audit/a11y-annotate-renderer.ts +496 -0
  99. package/figma-intelligence-layer/src/tools/phase1-vision/a11y-audit/a11y-annotation-kit.ts +230 -0
  100. package/figma-intelligence-layer/src/tools/phase1-vision/a11y-audit/colorblind-sim.ts +66 -0
  101. package/figma-intelligence-layer/src/tools/phase1-vision/a11y-audit/index.ts +810 -0
  102. package/figma-intelligence-layer/src/tools/phase1-vision/a11y-audit/keyboard-sr-order-analyzer.ts +1191 -0
  103. package/figma-intelligence-layer/src/tools/phase1-vision/a11y-audit/keyboard-sr-order-figma-page.ts +1346 -0
  104. package/figma-intelligence-layer/src/tools/phase1-vision/a11y-audit/keyboard-sr-order-handler.ts +148 -0
  105. package/figma-intelligence-layer/src/tools/phase1-vision/a11y-audit/vpat-figma-page.ts +499 -0
  106. package/figma-intelligence-layer/src/tools/phase1-vision/a11y-audit/vpat-report.ts +910 -0
  107. package/figma-intelligence-layer/src/tools/phase1-vision/a11y-audit/wcag-checker.ts +989 -0
  108. package/figma-intelligence-layer/src/tools/phase1-vision/a11y-audit/wcag-criteria.ts +1160 -0
  109. package/figma-intelligence-layer/src/tools/phase1-vision/design-from-ref/index.ts +424 -0
  110. package/figma-intelligence-layer/src/tools/phase1-vision/screen-cloner/component-recognizer.ts +38 -0
  111. package/figma-intelligence-layer/src/tools/phase1-vision/screen-cloner/ds-matcher.ts +111 -0
  112. package/figma-intelligence-layer/src/tools/phase1-vision/screen-cloner/font-matcher.ts +114 -0
  113. package/figma-intelligence-layer/src/tools/phase1-vision/screen-cloner/icon-resolver.ts +103 -0
  114. package/figma-intelligence-layer/src/tools/phase1-vision/screen-cloner/index.ts +1060 -0
  115. package/figma-intelligence-layer/src/tools/phase1-vision/screen-cloner/layout-segmenter.ts +18 -0
  116. package/figma-intelligence-layer/src/tools/phase1-vision/screen-cloner/token-inferencer.ts +39 -0
  117. package/figma-intelligence-layer/src/tools/phase1-vision/screen-cloner/vision-pipeline.ts +58 -0
  118. package/figma-intelligence-layer/src/tools/phase1-vision/sketch-to-design/index.ts +298 -0
  119. package/figma-intelligence-layer/src/tools/phase1-vision/visual-audit/index.ts +197 -0
  120. package/figma-intelligence-layer/src/tools/phase2-accuracy/component-audit/index.ts +494 -0
  121. package/figma-intelligence-layer/src/tools/phase2-accuracy/intent-translator/index.ts +356 -0
  122. package/figma-intelligence-layer/src/tools/phase2-accuracy/layout-intelligence/container-patterns.ts +123 -0
  123. package/figma-intelligence-layer/src/tools/phase2-accuracy/layout-intelligence/index.ts +663 -0
  124. package/figma-intelligence-layer/src/tools/phase2-accuracy/lint-rules/built-in-rules.yaml +56 -0
  125. package/figma-intelligence-layer/src/tools/phase2-accuracy/lint-rules/index.ts +614 -0
  126. package/figma-intelligence-layer/src/tools/phase2-accuracy/lint-rules/rule-engine.ts +113 -0
  127. package/figma-intelligence-layer/src/tools/phase2-accuracy/theme-generator/color-theory.ts +178 -0
  128. package/figma-intelligence-layer/src/tools/phase2-accuracy/theme-generator/index.ts +470 -0
  129. package/figma-intelligence-layer/src/tools/phase2-accuracy/variant-expander/index.ts +429 -0
  130. package/figma-intelligence-layer/src/tools/phase2-accuracy/variant-expander/token-override-maps.ts +226 -0
  131. package/figma-intelligence-layer/src/tools/phase3-generation/ai-image-insert/index.ts +535 -0
  132. package/figma-intelligence-layer/src/tools/phase3-generation/component-archaeologist/index.ts +660 -0
  133. package/figma-intelligence-layer/src/tools/phase3-generation/component-archaeologist/pattern-fingerprints.ts +209 -0
  134. package/figma-intelligence-layer/src/tools/phase3-generation/composition-builder/index.ts +540 -0
  135. package/figma-intelligence-layer/src/tools/phase3-generation/figma-animated-build.ts +391 -0
  136. package/figma-intelligence-layer/src/tools/phase3-generation/page-architect/index.ts +2019 -0
  137. package/figma-intelligence-layer/src/tools/phase3-generation/page-architect/screen-templates.ts +131 -0
  138. package/figma-intelligence-layer/src/tools/phase3-generation/prototype-map/index.ts +381 -0
  139. package/figma-intelligence-layer/src/tools/phase3-generation/prototype-wire/index.ts +565 -0
  140. package/figma-intelligence-layer/src/tools/phase3-generation/swarm-build/index.ts +764 -0
  141. package/figma-intelligence-layer/src/tools/phase3-generation/system-drift/index.ts +535 -0
  142. package/figma-intelligence-layer/src/tools/phase3-generation/unsplash-search/index.ts +84 -0
  143. package/figma-intelligence-layer/src/tools/phase3-generation/url-to-frame/index.ts +401 -0
  144. package/figma-intelligence-layer/src/tools/phase4-sync/animation-specifier/code-generators/css-animations.ts +68 -0
  145. package/figma-intelligence-layer/src/tools/phase4-sync/animation-specifier/code-generators/framer-motion.ts +78 -0
  146. package/figma-intelligence-layer/src/tools/phase4-sync/animation-specifier/code-generators/swift-animations.ts +93 -0
  147. package/figma-intelligence-layer/src/tools/phase4-sync/animation-specifier/index.ts +596 -0
  148. package/figma-intelligence-layer/src/tools/phase4-sync/ci-check/index.ts +462 -0
  149. package/figma-intelligence-layer/src/tools/phase4-sync/export-tokens/index.ts +1470 -0
  150. package/figma-intelligence-layer/src/tools/phase4-sync/generate-component-code/index.ts +829 -0
  151. package/figma-intelligence-layer/src/tools/phase4-sync/handoff-spec/index.ts +702 -0
  152. package/figma-intelligence-layer/src/tools/phase4-sync/icon-library-sync/index.ts +483 -0
  153. package/figma-intelligence-layer/src/tools/phase4-sync/sync-from-code/index.ts +501 -0
  154. package/figma-intelligence-layer/src/tools/phase4-sync/sync-from-code/storybook-parser.ts +106 -0
  155. package/figma-intelligence-layer/src/tools/phase4-sync/watch-docs/index.ts +676 -0
  156. package/figma-intelligence-layer/src/tools/phase4-sync/webhook-listener/index.ts +560 -0
  157. package/figma-intelligence-layer/src/tools/phase5-governance/apg-doc/index.ts +1043 -0
  158. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/component-detection.ts +620 -0
  159. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/extractors/anatomy.ts +331 -0
  160. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/extractors/color-tokens.ts +77 -0
  161. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/extractors/properties.ts +54 -0
  162. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/extractors/snapshot.ts +287 -0
  163. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/extractors/spacing.ts +71 -0
  164. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/extractors/states.ts +43 -0
  165. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/extractors/typography.ts +71 -0
  166. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/index.ts +221 -0
  167. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/_default.ts +166 -0
  168. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/accordion.ts +232 -0
  169. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/alert.ts +234 -0
  170. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/avatar-group.ts +270 -0
  171. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/avatar.ts +249 -0
  172. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/badge.ts +231 -0
  173. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/banner.ts +293 -0
  174. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/breadcrumb.ts +240 -0
  175. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/button.ts +243 -0
  176. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/calendar.ts +307 -0
  177. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/card.ts +143 -0
  178. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/checkbox.ts +227 -0
  179. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/chip.ts +233 -0
  180. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/combobox.ts +282 -0
  181. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/datepicker.ts +276 -0
  182. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/divider.ts +223 -0
  183. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/drawer.ts +255 -0
  184. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/dropdown-menu.ts +289 -0
  185. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/empty-state.ts +261 -0
  186. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/file-uploader.ts +290 -0
  187. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/form.ts +265 -0
  188. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/grid.ts +238 -0
  189. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/icon.ts +255 -0
  190. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/index.ts +128 -0
  191. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/inline-edit.ts +286 -0
  192. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/inline-message.ts +255 -0
  193. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/input.ts +330 -0
  194. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/link.ts +247 -0
  195. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/list.ts +250 -0
  196. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/menu.ts +247 -0
  197. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/modal.ts +144 -0
  198. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/navbar.ts +264 -0
  199. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/navigation.ts +251 -0
  200. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/number-input.ts +261 -0
  201. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/pagination.ts +248 -0
  202. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/popover.ts +270 -0
  203. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/progress.ts +251 -0
  204. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/radio.ts +142 -0
  205. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/range-slider.ts +282 -0
  206. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/rating.ts +250 -0
  207. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/search.ts +258 -0
  208. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/segmented-control.ts +265 -0
  209. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/select.ts +319 -0
  210. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/skeleton.ts +256 -0
  211. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/slider.ts +232 -0
  212. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/spinner.ts +239 -0
  213. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/status-dot.ts +252 -0
  214. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/stepper.ts +270 -0
  215. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/table.ts +244 -0
  216. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/tabs.ts +143 -0
  217. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/tag.ts +243 -0
  218. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/textarea.ts +259 -0
  219. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/time-picker.ts +293 -0
  220. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/toast.ts +144 -0
  221. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/toggle.ts +289 -0
  222. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/toolbar.ts +267 -0
  223. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/tooltip.ts +232 -0
  224. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/treeview.ts +257 -0
  225. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/knowledge/typography.ts +319 -0
  226. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/legacy-compat.ts +121 -0
  227. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/renderers/anatomy-diagram.ts +430 -0
  228. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/renderers/figma-page.ts +312 -0
  229. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/renderers/json.ts +129 -0
  230. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/renderers/markdown.ts +78 -0
  231. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/renderers/visual-doc.ts +2333 -0
  232. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/sections/accessibility.ts +100 -0
  233. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/sections/anatomy.ts +32 -0
  234. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/sections/color-tokens.ts +59 -0
  235. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/sections/content-guidance.ts +18 -0
  236. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/sections/design-tokens.ts +53 -0
  237. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/sections/interaction-rules.ts +19 -0
  238. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/sections/overview.ts +91 -0
  239. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/sections/properties-api.ts +71 -0
  240. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/sections/qa-criteria.ts +19 -0
  241. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/sections/related-components.ts +110 -0
  242. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/sections/responsive.ts +19 -0
  243. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/sections/size-specs.ts +67 -0
  244. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/sections/spacing-structure.ts +58 -0
  245. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/sections/state-specs.ts +79 -0
  246. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/sections/states.ts +50 -0
  247. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/sections/type-hierarchy.ts +33 -0
  248. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/sections/typography.ts +55 -0
  249. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/sections/usage-guidelines.ts +73 -0
  250. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/sections/variants.ts +81 -0
  251. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec/types.ts +409 -0
  252. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec-sheet/index.ts +198 -0
  253. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec-sheet/renderer.ts +701 -0
  254. package/figma-intelligence-layer/src/tools/phase5-governance/component-spec-sheet/types.ts +88 -0
  255. package/figma-intelligence-layer/src/tools/phase5-governance/decision-log/index.ts +135 -0
  256. package/figma-intelligence-layer/src/tools/phase5-governance/design-decision-log/index.ts +491 -0
  257. package/figma-intelligence-layer/src/tools/phase5-governance/ds-primitives/index.ts +416 -0
  258. package/figma-intelligence-layer/src/tools/phase5-governance/ds-scaffolder/index.ts +722 -0
  259. package/figma-intelligence-layer/src/tools/phase5-governance/ds-variables/index.ts +449 -0
  260. package/figma-intelligence-layer/src/tools/phase5-governance/health-report/index.ts +393 -0
  261. package/figma-intelligence-layer/src/tools/phase5-governance/taxonomy-docs/index.ts +406 -0
  262. package/figma-intelligence-layer/src/tools/phase5-governance/taxonomy-docs/renderers/figma-page.ts +292 -0
  263. package/figma-intelligence-layer/src/tools/phase5-governance/taxonomy-docs/renderers/json.ts +24 -0
  264. package/figma-intelligence-layer/src/tools/phase5-governance/taxonomy-docs/renderers/markdown.ts +172 -0
  265. package/figma-intelligence-layer/src/tools/phase5-governance/taxonomy-docs/renderers/naming-guide.ts +409 -0
  266. package/figma-intelligence-layer/src/tools/phase5-governance/token-analytics/index.ts +594 -0
  267. package/figma-intelligence-layer/src/tools/phase5-governance/token-docs/index.ts +710 -0
  268. package/figma-intelligence-layer/src/tools/phase5-governance/token-migrate/index.ts +458 -0
  269. package/figma-intelligence-layer/src/tools/phase5-governance/token-naming/index.ts +134 -0
  270. package/figma-intelligence-layer/tests/apg-doc.test.ts +101 -0
  271. package/figma-intelligence-layer/tests/design-system-context.test.ts +152 -0
  272. package/figma-intelligence-layer/tests/design-system-matcher.test.ts +144 -0
  273. package/figma-intelligence-layer/tests/figma-bridge.test.ts +83 -0
  274. package/figma-intelligence-layer/tests/generate-image-and-insert.test.ts +56 -0
  275. package/figma-intelligence-layer/tests/screen-cloner-regression.test.ts +69 -0
  276. package/figma-intelligence-layer/tests/smoke.test.ts +174 -0
  277. package/figma-intelligence-layer/tests/spec-generator.test.ts +127 -0
  278. package/figma-intelligence-layer/tests/token-migrate.test.ts +21 -0
  279. package/figma-intelligence-layer/tests/token-naming.test.ts +30 -0
  280. package/figma-intelligence-layer/tsconfig.json +19 -0
  281. package/package.json +35 -0
  282. package/scripts/clean-existing-chunks.js +179 -0
  283. package/scripts/connect-ai-tool.js +490 -0
  284. package/scripts/convert-hub-pdfs.js +425 -0
  285. package/scripts/figma-mcp-status.js +349 -0
  286. package/scripts/register-codex-mcp.js +96 -0
@@ -0,0 +1,663 @@
1
+ // ─────────────────────────────────────────────────────────────────────────────
2
+ // Layout Intelligence
3
+ // Analyses a Figma node's container type and recommends (or applies) optimal
4
+ // Auto-Layout settings drawn from a built-in container → settings lookup table.
5
+ // All spacing values are snapped to the nearest spacing token.
6
+ // ─────────────────────────────────────────────────────────────────────────────
7
+
8
+ import { getBridge } from "../../../shared/figma-bridge.js";
9
+ import { decisionLog } from "../../../shared/decision-log.js";
10
+ import { snapToSpacingToken } from "../../../shared/token-utils.js";
11
+ import { FigmaNode } from "../../../shared/types.js";
12
+ import { generateValidatorScript, generateDocumentRepairScript, generateDocumentRepairCall } from "../../../shared/auto-layout-validator.js";
13
+
14
+ // ─── Public types ─────────────────────────────────────────────────────────────
15
+
16
+ export interface LayoutIntelligenceArgs {
17
+ nodeId: string;
18
+ applyChanges: boolean;
19
+ spacingTokenSet?: string;
20
+ responsiveHints?: boolean;
21
+ reportDiff?: boolean;
22
+ recursive?: boolean;
23
+ }
24
+
25
+ export type ContainerKind =
26
+ | "navigation bar"
27
+ | "card"
28
+ | "form"
29
+ | "button"
30
+ | "grid"
31
+ | "list item"
32
+ | "modal"
33
+ | "section"
34
+ | "document_page"
35
+ | "header_block"
36
+ | "section_block"
37
+ | "toc_row"
38
+ | "paragraph_group"
39
+ | "divider"
40
+ | "footer_block"
41
+ | "table_block";
42
+
43
+ export interface AutoLayoutSpec {
44
+ direction: "HORIZONTAL" | "VERTICAL" | "WRAP";
45
+ primaryAxisSizingMode: "FIXED" | "AUTO"; // width
46
+ counterAxisSizingMode: "FIXED" | "AUTO"; // height
47
+ paddingToken: string;
48
+ gapToken: string;
49
+ paddingValue: number; // resolved px
50
+ gapValue: number; // resolved px
51
+ }
52
+
53
+ export interface PropertyDiff {
54
+ property: string;
55
+ before: string | number | undefined;
56
+ after: string | number;
57
+ tokenName?: string;
58
+ }
59
+
60
+ export interface LayoutIntelligenceResult {
61
+ nodeId: string;
62
+ nodeName: string;
63
+ detectedKind: ContainerKind | "unknown";
64
+ spec: AutoLayoutSpec;
65
+ diff: PropertyDiff[];
66
+ applied: boolean;
67
+ responsiveHints?: string[];
68
+ logEntryId: string;
69
+ validationFixes?: number;
70
+ }
71
+
72
+ // ─── Spacing token name → px value ───────────────────────────────────────────
73
+
74
+ const SPACE: Record<string, number> = {
75
+ "--space-xs": 4,
76
+ "--space-sm": 8,
77
+ "--space-md": 16,
78
+ "--space-lg": 24,
79
+ "--space-xl": 32,
80
+ "--space-2xl": 48,
81
+ "--space-3xl": 56,
82
+ "--space-4xl": 64,
83
+ };
84
+
85
+ // ─── Container → Auto-Layout mapping table ────────────────────────────────────
86
+ // direction / primaryAxis (W) / counterAxis (H) / padding token / gap token
87
+
88
+ const CONTAINER_SPECS: Record<ContainerKind, AutoLayoutSpec> = {
89
+ "navigation bar": {
90
+ direction: "HORIZONTAL",
91
+ primaryAxisSizingMode: "AUTO", // Fill W
92
+ counterAxisSizingMode: "AUTO", // Hug H
93
+ paddingToken: "--space-md",
94
+ gapToken: "--space-md",
95
+ paddingValue: SPACE["--space-md"],
96
+ gapValue: SPACE["--space-md"],
97
+ },
98
+ card: {
99
+ direction: "VERTICAL",
100
+ primaryAxisSizingMode: "AUTO", // Fill W
101
+ counterAxisSizingMode: "AUTO", // Hug H
102
+ paddingToken: "--space-lg",
103
+ gapToken: "--space-lg",
104
+ paddingValue: SPACE["--space-lg"],
105
+ gapValue: SPACE["--space-lg"],
106
+ },
107
+ form: {
108
+ direction: "VERTICAL",
109
+ primaryAxisSizingMode: "AUTO",
110
+ counterAxisSizingMode: "AUTO",
111
+ paddingToken: "--space-md",
112
+ gapToken: "--space-md",
113
+ paddingValue: SPACE["--space-md"],
114
+ gapValue: SPACE["--space-md"],
115
+ },
116
+ button: {
117
+ direction: "HORIZONTAL",
118
+ primaryAxisSizingMode: "AUTO", // Hug W
119
+ counterAxisSizingMode: "AUTO", // Hug H
120
+ paddingToken: "--space-sm",
121
+ gapToken: "--space-sm",
122
+ paddingValue: SPACE["--space-sm"],
123
+ gapValue: SPACE["--space-sm"],
124
+ },
125
+ grid: {
126
+ direction: "WRAP",
127
+ primaryAxisSizingMode: "AUTO",
128
+ counterAxisSizingMode: "AUTO",
129
+ paddingToken: "--space-md",
130
+ gapToken: "--space-md",
131
+ paddingValue: SPACE["--space-md"],
132
+ gapValue: SPACE["--space-md"],
133
+ },
134
+ "list item": {
135
+ direction: "HORIZONTAL",
136
+ primaryAxisSizingMode: "AUTO",
137
+ counterAxisSizingMode: "AUTO",
138
+ paddingToken: "--space-sm",
139
+ gapToken: "--space-sm",
140
+ paddingValue: SPACE["--space-sm"],
141
+ gapValue: SPACE["--space-sm"],
142
+ },
143
+ modal: {
144
+ direction: "VERTICAL",
145
+ primaryAxisSizingMode: "FIXED", // Fixed W
146
+ counterAxisSizingMode: "AUTO", // Hug H
147
+ paddingToken: "--space-xl",
148
+ gapToken: "--space-xl",
149
+ paddingValue: SPACE["--space-xl"],
150
+ gapValue: SPACE["--space-xl"],
151
+ },
152
+ section: {
153
+ direction: "VERTICAL",
154
+ primaryAxisSizingMode: "AUTO",
155
+ counterAxisSizingMode: "AUTO",
156
+ paddingToken: "--space-2xl",
157
+ gapToken: "--space-2xl",
158
+ paddingValue: SPACE["--space-2xl"],
159
+ gapValue: SPACE["--space-2xl"],
160
+ },
161
+
162
+ // ─── Document layout primitives ───────────────────────────────────────────
163
+ document_page: {
164
+ direction: "VERTICAL",
165
+ primaryAxisSizingMode: "AUTO", // Hug H (page grows with content)
166
+ counterAxisSizingMode: "FIXED", // Fixed W (document width)
167
+ paddingToken: "--space-3xl",
168
+ gapToken: "--space-2xl",
169
+ paddingValue: SPACE["--space-3xl"],
170
+ gapValue: SPACE["--space-2xl"],
171
+ },
172
+ header_block: {
173
+ direction: "VERTICAL",
174
+ primaryAxisSizingMode: "AUTO",
175
+ counterAxisSizingMode: "AUTO",
176
+ paddingToken: "--space-xs",
177
+ gapToken: "--space-sm",
178
+ paddingValue: 0,
179
+ gapValue: SPACE["--space-sm"],
180
+ },
181
+ section_block: {
182
+ direction: "VERTICAL",
183
+ primaryAxisSizingMode: "AUTO",
184
+ counterAxisSizingMode: "AUTO",
185
+ paddingToken: "--space-xs",
186
+ gapToken: "--space-lg",
187
+ paddingValue: 0,
188
+ gapValue: SPACE["--space-lg"],
189
+ },
190
+ toc_row: {
191
+ direction: "HORIZONTAL",
192
+ primaryAxisSizingMode: "AUTO",
193
+ counterAxisSizingMode: "AUTO",
194
+ paddingToken: "--space-xs",
195
+ gapToken: "--space-sm",
196
+ paddingValue: 0,
197
+ gapValue: SPACE["--space-sm"],
198
+ },
199
+ paragraph_group: {
200
+ direction: "VERTICAL",
201
+ primaryAxisSizingMode: "AUTO",
202
+ counterAxisSizingMode: "AUTO",
203
+ paddingToken: "--space-xs",
204
+ gapToken: "--space-sm",
205
+ paddingValue: 0,
206
+ gapValue: SPACE["--space-sm"],
207
+ },
208
+ divider: {
209
+ direction: "HORIZONTAL",
210
+ primaryAxisSizingMode: "FIXED",
211
+ counterAxisSizingMode: "FIXED",
212
+ paddingToken: "--space-xs",
213
+ gapToken: "--space-xs",
214
+ paddingValue: 0,
215
+ gapValue: 0,
216
+ },
217
+ footer_block: {
218
+ direction: "HORIZONTAL",
219
+ primaryAxisSizingMode: "AUTO",
220
+ counterAxisSizingMode: "AUTO",
221
+ paddingToken: "--space-xs",
222
+ gapToken: "--space-md",
223
+ paddingValue: 0,
224
+ gapValue: SPACE["--space-md"],
225
+ },
226
+ table_block: {
227
+ direction: "VERTICAL",
228
+ primaryAxisSizingMode: "AUTO",
229
+ counterAxisSizingMode: "AUTO",
230
+ paddingToken: "--space-xs",
231
+ gapToken: "--space-xs",
232
+ paddingValue: 0,
233
+ gapValue: 0,
234
+ },
235
+ };
236
+
237
+ // ─── Container-kind detection heuristics ─────────────────────────────────────
238
+
239
+ function detectContainerKind(node: FigmaNode): ContainerKind | "unknown" {
240
+ const name = node.name.toLowerCase();
241
+ const childCount = node.children?.length ?? 0;
242
+ const w = node.absoluteBoundingBox?.width ?? 0;
243
+ const h = node.absoluteBoundingBox?.height ?? 0;
244
+ const aspectRatio = h > 0 ? w / h : 1;
245
+
246
+ // Document layout primitives (highest priority — checked first)
247
+ if (/doc(ument)?[\s_-]?page|spec[\s_-]?page|guide(line)?[\s_-]?page/.test(name)) return "document_page";
248
+ if (/header[\s_-]?block|doc[\s_-]?header|page[\s_-]?title[\s_-]?block/.test(name)) return "header_block";
249
+ if (/section[\s_-]?block|content[\s_-]?section/.test(name)) return "section_block";
250
+ if (/toc[\s_-]?row|table[\s_-]?of[\s_-]?contents/.test(name)) return "toc_row";
251
+ if (/paragraph[\s_-]?group|body[\s_-]?text[\s_-]?block|text[\s_-]?block/.test(name)) return "paragraph_group";
252
+ if (/\bdivider\b|\bseparator\b|\bhr\b/.test(name)) return "divider";
253
+ if (/footer[\s_-]?block|doc[\s_-]?footer/.test(name)) return "footer_block";
254
+ if (/table[\s_-]?block|spec[\s_-]?table|data[\s_-]?table/.test(name)) return "table_block";
255
+
256
+ // Name-based detection for UI containers
257
+ if (/nav(igation)?\s*(bar)?|navbar|top\s*bar|header\s*bar/.test(name)) return "navigation bar";
258
+ if (/\bmodal\b|\bdialog\b|\bdrawer\b|\bpopup\b/.test(name)) return "modal";
259
+ if (/\bcard\b|\btile\b|\bpanel\b/.test(name)) return "card";
260
+ if (/\bform\b|\binput\s*group\b/.test(name)) return "form";
261
+ if (/\bbtn\b|\bbutton\b|\bcta\b/.test(name)) return "button";
262
+ if (/\bgrid\b|\bmasonry\b|\bgallery\b/.test(name)) return "grid";
263
+ if (/\blist\s*item\b|\brow\b|\bcell\b/.test(name)) return "list item";
264
+ if (/\bsection\b|\bhero\b|\bfooter\b|\bpage\b/.test(name)) return "section";
265
+
266
+ // Geometry-based fallback: document page (wide, vertical, many children)
267
+ if (w >= 1000 && w <= 1400 && node.layoutMode === "VERTICAL" && childCount > 5) return "document_page";
268
+
269
+ // Geometry-based fallback for UI containers
270
+ if (w > 0 && h <= 80 && aspectRatio > 5) return "navigation bar"; // very wide & short
271
+ if (w <= 120 && h <= 60 && childCount <= 3) return "button"; // small & few children
272
+ if (childCount > 6 && node.layoutMode === "NONE") return "grid"; // many children, no layout
273
+ if (h > 300 && w < 600 && childCount > 2) return "modal"; // tall-ish popup sized box
274
+ if (childCount > 0 && node.layoutMode === "VERTICAL") return "card";
275
+ if (aspectRatio > 4 && childCount <= 5) return "list item";
276
+
277
+ return "unknown";
278
+ }
279
+
280
+ // ─── Diff builder ─────────────────────────────────────────────────────────────
281
+
282
+ function buildDiff(node: FigmaNode, spec: AutoLayoutSpec): PropertyDiff[] {
283
+ const diffs: PropertyDiff[] = [];
284
+
285
+ const currentLayoutMode = node.layoutMode ?? "NONE";
286
+ const targetLayoutMode = spec.direction === "WRAP" ? "HORIZONTAL" : spec.direction;
287
+
288
+ if (currentLayoutMode !== targetLayoutMode) {
289
+ diffs.push({ property: "layoutMode", before: currentLayoutMode, after: targetLayoutMode });
290
+ }
291
+
292
+ // WRAP is represented via layoutWrap which we handle separately
293
+ if (spec.direction === "WRAP") {
294
+ diffs.push({ property: "layoutWrap", before: "NO_WRAP", after: "WRAP" });
295
+ }
296
+
297
+ const spacingFields: Array<keyof FigmaNode> = [
298
+ "paddingLeft",
299
+ "paddingRight",
300
+ "paddingTop",
301
+ "paddingBottom",
302
+ ];
303
+
304
+ for (const field of spacingFields) {
305
+ const current = node[field] as number | undefined;
306
+ const snapped = snapToSpacingToken(spec.paddingValue);
307
+ if (current !== snapped.tokenValue) {
308
+ diffs.push({
309
+ property: field,
310
+ before: current,
311
+ after: snapped.tokenValue,
312
+ tokenName: snapped.tokenName,
313
+ });
314
+ }
315
+ }
316
+
317
+ const currentGap = node.itemSpacing ?? 0;
318
+ const snappedGap = snapToSpacingToken(spec.gapValue);
319
+ if (currentGap !== snappedGap.tokenValue) {
320
+ diffs.push({
321
+ property: "itemSpacing",
322
+ before: currentGap,
323
+ after: snappedGap.tokenValue,
324
+ tokenName: snappedGap.tokenName,
325
+ });
326
+ }
327
+
328
+ if (node.primaryAxisSizingMode !== spec.primaryAxisSizingMode) {
329
+ diffs.push({
330
+ property: "primaryAxisSizingMode",
331
+ before: node.primaryAxisSizingMode,
332
+ after: spec.primaryAxisSizingMode,
333
+ });
334
+ }
335
+
336
+ if (node.counterAxisSizingMode !== spec.counterAxisSizingMode) {
337
+ diffs.push({
338
+ property: "counterAxisSizingMode",
339
+ before: node.counterAxisSizingMode,
340
+ after: spec.counterAxisSizingMode,
341
+ });
342
+ }
343
+
344
+ return diffs;
345
+ }
346
+
347
+ // ─── Figma script builder ─────────────────────────────────────────────────────
348
+
349
+ function buildApplyScript(nodeId: string, spec: AutoLayoutSpec, paddingPx: number, gapPx: number): string {
350
+ const layoutMode = spec.direction === "WRAP" ? "HORIZONTAL" : spec.direction;
351
+ const wrapLine = spec.direction === "WRAP"
352
+ ? `node.layoutWrap = 'WRAP';`
353
+ : `node.layoutWrap = 'NO_WRAP';`;
354
+
355
+ return `
356
+ const node = await figma.getNodeByIdAsync(${JSON.stringify(nodeId)});
357
+ if (!node) throw new Error('Node not found: ${nodeId}');
358
+ if (!('layoutMode' in node)) throw new Error('Node does not support Auto Layout');
359
+ node.layoutMode = ${JSON.stringify(layoutMode)};
360
+ ${wrapLine}
361
+ node.primaryAxisSizingMode = ${JSON.stringify(spec.primaryAxisSizingMode)};
362
+ node.counterAxisSizingMode = ${JSON.stringify(spec.counterAxisSizingMode)};
363
+ node.paddingLeft = ${paddingPx};
364
+ node.paddingRight = ${paddingPx};
365
+ node.paddingTop = ${paddingPx};
366
+ node.paddingBottom = ${paddingPx};
367
+ node.itemSpacing = ${gapPx};
368
+
369
+ // ── Deep recursive FILL enforcement ──
370
+ function isAL(n) { return n.layoutMode === 'HORIZONTAL' || n.layoutMode === 'VERTICAL'; }
371
+ function isDocContainer(name) {
372
+ return /section|header|footer|table|paragraph|toc|block|overview|anatomy|content|divider/i.test(name);
373
+ }
374
+ function enforceChildFill(parent, depth) {
375
+ if (depth > 20 || !('children' in parent)) return;
376
+ const dir = parent.layoutMode;
377
+ const parentIsAL = isAL(parent);
378
+ if (!parentIsAL) return;
379
+
380
+ for (const child of parent.children) {
381
+ if (!('layoutAlign' in child)) continue;
382
+ const cName = (child.name || '').toLowerCase();
383
+ const cType = child.type;
384
+
385
+ // Skip small fixed elements (icons ≤48px) unless they're semantic containers
386
+ const isSmallFixed = child.width && child.height && child.width <= 48 && child.height <= 48;
387
+ if (isSmallFixed && !isDocContainer(cName) &&
388
+ !/input|field|button|btn|bar|card|container|wrapper|form/.test(cName)) {
389
+ continue;
390
+ }
391
+
392
+ if (dir === 'VERTICAL') {
393
+ // VERTICAL parent → children fill width
394
+ if (cType === 'FRAME' || cType === 'COMPONENT' || cType === 'INSTANCE' ||
395
+ cType === 'RECTANGLE' || cType === 'GROUP' || cType === 'TEXT') {
396
+ child.layoutAlign = 'STRETCH';
397
+ if ('layoutSizingHorizontal' in child) child.layoutSizingHorizontal = 'FILL';
398
+ }
399
+ } else if (dir === 'HORIZONTAL') {
400
+ // HORIZONTAL parent → grow content children, fill height on frames
401
+ if (cType === 'FRAME' || cType === 'COMPONENT' || cType === 'INSTANCE') {
402
+ if (/input|field|search|content|main|body|spacer/.test(cName) || isDocContainer(cName)) {
403
+ child.layoutGrow = 1;
404
+ }
405
+ }
406
+ }
407
+
408
+ // Recurse into child frames
409
+ if ('children' in child && isAL(child)) {
410
+ enforceChildFill(child, depth + 1);
411
+ }
412
+ }
413
+ }
414
+ enforceChildFill(node, 0);
415
+
416
+ return { success: true };
417
+ `.trim();
418
+ }
419
+
420
+ // ─── Responsive hints ─────────────────────────────────────────────────────────
421
+
422
+ function generateResponsiveHints(kind: ContainerKind | "unknown", spec: AutoLayoutSpec): string[] {
423
+ const hints: string[] = [];
424
+
425
+ if (kind === "navigation bar") {
426
+ hints.push("On mobile (<768px): switch to VERTICAL and collapse secondary items into a hamburger menu.");
427
+ hints.push("Ensure flex-shrink is applied to label text so icons stay visible at small widths.");
428
+ } else if (kind === "card") {
429
+ hints.push("In a responsive grid, let cards stretch to Fill-W; avoid Fixed widths.");
430
+ hints.push("Increase padding to --space-xl on desktop for breathing room.");
431
+ } else if (kind === "modal") {
432
+ hints.push("On mobile: set width to Fill-W and reduce padding to --space-md.");
433
+ hints.push("Use max-height: 90vh with scrollable content area to prevent overflow.");
434
+ } else if (kind === "grid") {
435
+ hints.push("Use Constraints → Scale on children so grid items resize proportionally.");
436
+ hints.push("Reduce gap to --space-sm on mobile breakpoints.");
437
+ } else if (kind === "form") {
438
+ hints.push("Stack label + input vertically on mobile; use horizontal layout on desktop.");
439
+ } else if (kind === "section") {
440
+ hints.push("Reduce padding from --space-2xl to --space-xl on tablet and --space-lg on mobile.");
441
+ } else if (kind === "document_page") {
442
+ hints.push("On mobile: reduce page width to 100vw, padding to --space-lg, section gap to --space-xl.");
443
+ hints.push("Consider collapsible TOC on narrow viewports.");
444
+ } else if (kind === "section_block" || kind === "paragraph_group") {
445
+ hints.push("Keep FILL width at all breakpoints for readable line lengths.");
446
+ }
447
+
448
+ if (spec.direction === "HORIZONTAL") {
449
+ hints.push("If children need to wrap at narrow viewports, enable layoutWrap = WRAP.");
450
+ }
451
+
452
+ return hints;
453
+ }
454
+
455
+ // ─── Document container kinds (used to auto-enable recursive validation) ─────
456
+
457
+ const DOCUMENT_KINDS: Set<ContainerKind | "unknown"> = new Set([
458
+ "document_page", "header_block", "section_block", "toc_row",
459
+ "paragraph_group", "divider", "footer_block", "table_block",
460
+ ]);
461
+
462
+ function isDocumentKind(kind: ContainerKind | "unknown"): boolean {
463
+ return DOCUMENT_KINDS.has(kind);
464
+ }
465
+
466
+ // ─── Recursive spec application for nested document containers ───────────────
467
+
468
+ function buildRecursiveSpecScript(nodeId: string): string {
469
+ // Serialize the detection patterns and specs as inline JS so they run inside
470
+ // the Figma Plugin API context (bridge.execute).
471
+ return `
472
+ (async () => {
473
+ const root = await figma.getNodeByIdAsync(${JSON.stringify(nodeId)});
474
+ if (!root) throw new Error('Node not found');
475
+
476
+ const SPECS = {
477
+ document_page: { dir: 'VERTICAL', pw: 'AUTO', cw: 'FIXED', pad: 56, gap: 48 },
478
+ header_block: { dir: 'VERTICAL', pw: 'AUTO', cw: 'AUTO', pad: 0, gap: 8 },
479
+ section_block: { dir: 'VERTICAL', pw: 'AUTO', cw: 'AUTO', pad: 0, gap: 24 },
480
+ toc_row: { dir: 'HORIZONTAL', pw: 'AUTO', cw: 'AUTO', pad: 0, gap: 8 },
481
+ paragraph_group: { dir: 'VERTICAL', pw: 'AUTO', cw: 'AUTO', pad: 0, gap: 8 },
482
+ divider: { dir: 'HORIZONTAL', pw: 'FIXED', cw: 'FIXED', pad: 0, gap: 0 },
483
+ footer_block: { dir: 'HORIZONTAL', pw: 'AUTO', cw: 'AUTO', pad: 0, gap: 16 },
484
+ table_block: { dir: 'VERTICAL', pw: 'AUTO', cw: 'AUTO', pad: 0, gap: 0 },
485
+ };
486
+
487
+ const DETECT = [
488
+ [/doc(ument)?[\\s_-]?page|spec[\\s_-]?page|guide(line)?[\\s_-]?page/i, 'document_page'],
489
+ [/header[\\s_-]?block|doc[\\s_-]?header|page[\\s_-]?title[\\s_-]?block/i, 'header_block'],
490
+ [/section[\\s_-]?block|content[\\s_-]?section/i, 'section_block'],
491
+ [/toc[\\s_-]?row|table[\\s_-]?of[\\s_-]?contents/i, 'toc_row'],
492
+ [/paragraph[\\s_-]?group|body[\\s_-]?text[\\s_-]?block|text[\\s_-]?block/i, 'paragraph_group'],
493
+ [/\\bdivider\\b|\\bseparator\\b|\\bhr\\b/i, 'divider'],
494
+ [/footer[\\s_-]?block|doc[\\s_-]?footer/i, 'footer_block'],
495
+ [/table[\\s_-]?block|spec[\\s_-]?table|data[\\s_-]?table/i, 'table_block'],
496
+ ];
497
+
498
+ function detectKind(node) {
499
+ const n = (node.name || '').toLowerCase();
500
+ for (const [re, kind] of DETECT) {
501
+ if (re.test(n)) return kind;
502
+ }
503
+ return null;
504
+ }
505
+
506
+ function isAL(n) { return n.layoutMode === 'HORIZONTAL' || n.layoutMode === 'VERTICAL'; }
507
+
508
+ let applied = 0;
509
+
510
+ function applySpec(node, spec) {
511
+ if (!('layoutMode' in node)) return;
512
+ node.layoutMode = spec.dir;
513
+ node.layoutWrap = 'NO_WRAP';
514
+ node.primaryAxisSizingMode = spec.pw;
515
+ node.counterAxisSizingMode = spec.cw;
516
+ node.paddingLeft = spec.pad;
517
+ node.paddingRight = spec.pad;
518
+ node.paddingTop = spec.pad;
519
+ node.paddingBottom = spec.pad;
520
+ node.itemSpacing = spec.gap;
521
+ applied++;
522
+ }
523
+
524
+ function walkAndApply(node, depth) {
525
+ if (depth > 20 || !('children' in node)) return;
526
+ for (const child of node.children) {
527
+ const kind = detectKind(child);
528
+ if (kind && SPECS[kind]) {
529
+ applySpec(child, SPECS[kind]);
530
+ }
531
+
532
+ // Enforce FILL on children of VERTICAL auto-layout containers
533
+ if (isAL(node) && node.layoutMode === 'VERTICAL' && 'layoutAlign' in child) {
534
+ const cType = child.type;
535
+ if (cType === 'FRAME' || cType === 'COMPONENT' || cType === 'INSTANCE' ||
536
+ cType === 'RECTANGLE' || cType === 'GROUP' || cType === 'TEXT') {
537
+ // Skip small icons
538
+ const isSmall = child.width && child.height && child.width <= 48 && child.height <= 48;
539
+ if (!isSmall) {
540
+ child.layoutAlign = 'STRETCH';
541
+ if ('layoutSizingHorizontal' in child) child.layoutSizingHorizontal = 'FILL';
542
+ }
543
+ }
544
+ }
545
+
546
+ walkAndApply(child, depth + 1);
547
+ }
548
+ }
549
+
550
+ // Don't re-apply to root (already done by buildApplyScript), only children
551
+ walkAndApply(root, 0);
552
+ return { applied: applied };
553
+ })();
554
+ `.trim();
555
+ }
556
+
557
+ // ─── Main handler ─────────────────────────────────────────────────────────────
558
+
559
+ export async function layoutIntelligenceHandler(
560
+ args: LayoutIntelligenceArgs
561
+ ): Promise<LayoutIntelligenceResult> {
562
+ const {
563
+ nodeId,
564
+ applyChanges,
565
+ spacingTokenSet, // reserved for future token-set override
566
+ responsiveHints = false,
567
+ reportDiff = true,
568
+ } = args;
569
+
570
+ if (!nodeId) throw new Error("layoutIntelligence: `nodeId` is required.");
571
+
572
+ const bridge = await getBridge();
573
+
574
+ // 1. Fetch the node tree
575
+ const node = await bridge.getNode(nodeId);
576
+
577
+ // 2. Detect container type
578
+ const detectedKind = detectContainerKind(node);
579
+
580
+ // 3. Resolve spec (fall back to "card" for unknown containers)
581
+ const resolvedKind: ContainerKind = detectedKind === "unknown" ? "card" : detectedKind;
582
+ const spec = CONTAINER_SPECS[resolvedKind];
583
+
584
+ // Override spacing if spacingTokenSet is provided and matches a known token
585
+ if (spacingTokenSet && SPACE[spacingTokenSet] !== undefined) {
586
+ spec.paddingValue = SPACE[spacingTokenSet];
587
+ spec.paddingToken = spacingTokenSet;
588
+ }
589
+
590
+ // 4. Snap spacing values
591
+ const snappedPadding = snapToSpacingToken(spec.paddingValue);
592
+ const snappedGap = snapToSpacingToken(spec.gapValue);
593
+
594
+ // 5. Build diff
595
+ const diff = reportDiff ? buildDiff(node, spec) : [];
596
+
597
+ // 6. Apply if requested
598
+ let applied = false;
599
+ if (applyChanges) {
600
+ const script = buildApplyScript(nodeId, spec, snappedPadding.tokenValue as number, snappedGap.tokenValue as number);
601
+ const execResult = await bridge.execute(script);
602
+ if (!execResult.success) {
603
+ throw new Error(`layoutIntelligence: Failed to apply changes — ${execResult.error}`);
604
+ }
605
+ applied = true;
606
+
607
+ // 6b. For document containers: recursively apply specs to nested children
608
+ if (isDocumentKind(detectedKind)) {
609
+ const recursiveScript = buildRecursiveSpecScript(nodeId);
610
+ await bridge.execute(recursiveScript);
611
+ }
612
+ }
613
+
614
+ // 7. Log the decision
615
+ const logEntry = await decisionLog.log({
616
+ tool: "layout-intelligence",
617
+ nodeIds: [nodeId],
618
+ rationale: `Detected container kind "${detectedKind}" on node "${node.name}". Recommended spec: ${spec.direction}, padding=${snappedPadding.tokenName}, gap=${snappedGap.tokenName}. Applied: ${applied}. Diff properties changed: ${diff.length}.`,
619
+ tokens: [snappedPadding.tokenName, snappedGap.tokenName],
620
+ reversible: applied,
621
+ metadata: { detectedKind, resolvedKind, spec, diffCount: diff.length },
622
+ });
623
+
624
+ // 8. Auto-layout validation + document repair
625
+ // Auto-enabled for document containers; also runs when recursive=true
626
+ const shouldValidate = args.recursive || isDocumentKind(detectedKind);
627
+ let validationFixes = 0;
628
+ if (shouldValidate && applied) {
629
+ const validatorScript = `
630
+ (async () => {
631
+ ${generateValidatorScript()}
632
+ ${generateDocumentRepairScript()}
633
+ const node = await figma.getNodeByIdAsync(${JSON.stringify(nodeId)});
634
+ if (!node) throw new Error('Node not found: ${nodeId}');
635
+ const valResult = validateAutoLayout(node);
636
+ ${generateDocumentRepairCall('node')}
637
+ const totalFixes = valResult.fixes + (_docRepair ? _docRepair.repairs : 0);
638
+ return { fixes: totalFixes, valDetails: valResult.details, repairDetails: _docRepair ? _docRepair.details : [] };
639
+ })();
640
+ `.trim();
641
+ const valResult = await bridge.execute(validatorScript);
642
+ if (valResult.success && valResult.result) {
643
+ validationFixes = (valResult.result as { fixes: number }).fixes;
644
+ }
645
+ }
646
+
647
+ const result: LayoutIntelligenceResult = {
648
+ nodeId,
649
+ nodeName: node.name,
650
+ detectedKind,
651
+ spec,
652
+ diff,
653
+ applied,
654
+ logEntryId: logEntry.id,
655
+ ...(shouldValidate ? { validationFixes } : {}),
656
+ };
657
+
658
+ if (responsiveHints) {
659
+ result.responsiveHints = generateResponsiveHints(detectedKind, spec);
660
+ }
661
+
662
+ return result;
663
+ }