@pairdraw/core 0.20.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (539) hide show
  1. package/dist/canvas/noise/render.js +1 -1
  2. package/dist/canvas/noise/render.js.map +1 -1
  3. package/dist/canvas/noise/shader.d.ts +6 -3
  4. package/dist/canvas/noise/shader.d.ts.map +1 -1
  5. package/dist/canvas/noise/shader.js +12 -7
  6. package/dist/canvas/noise/shader.js.map +1 -1
  7. package/dist/canvas/noise/tile.d.ts.map +1 -1
  8. package/dist/canvas/noise/tile.js +2 -1
  9. package/dist/canvas/noise/tile.js.map +1 -1
  10. package/dist/canvas/renderer/colors.d.ts +20 -5
  11. package/dist/canvas/renderer/colors.d.ts.map +1 -1
  12. package/dist/canvas/renderer/colors.js +48 -42
  13. package/dist/canvas/renderer/colors.js.map +1 -1
  14. package/dist/canvas/renderer/document-surface.d.ts +25 -0
  15. package/dist/canvas/renderer/document-surface.d.ts.map +1 -0
  16. package/dist/canvas/renderer/document-surface.js +46 -0
  17. package/dist/canvas/renderer/document-surface.js.map +1 -0
  18. package/dist/canvas/renderer/fonts.d.ts.map +1 -1
  19. package/dist/canvas/renderer/fonts.js +6 -4
  20. package/dist/canvas/renderer/fonts.js.map +1 -1
  21. package/dist/canvas/renderer/lifecycle.js +4 -3
  22. package/dist/canvas/renderer/lifecycle.js.map +1 -1
  23. package/dist/canvas/renderer/methods.d.ts.map +1 -1
  24. package/dist/canvas/renderer/methods.js +1 -0
  25. package/dist/canvas/renderer/methods.js.map +1 -1
  26. package/dist/canvas/renderer/pipeline.d.ts.map +1 -1
  27. package/dist/canvas/renderer/pipeline.js +23 -2
  28. package/dist/canvas/renderer/pipeline.js.map +1 -1
  29. package/dist/canvas/renderer/retained-backing.d.ts.map +1 -1
  30. package/dist/canvas/renderer/retained-backing.js +2 -1
  31. package/dist/canvas/renderer/retained-backing.js.map +1 -1
  32. package/dist/canvas/renderer/tiles/surface-pool.d.ts.map +1 -1
  33. package/dist/canvas/renderer/tiles/surface-pool.js +2 -7
  34. package/dist/canvas/renderer/tiles/surface-pool.js.map +1 -1
  35. package/dist/canvas/renderer.d.ts +20 -2
  36. package/dist/canvas/renderer.d.ts.map +1 -1
  37. package/dist/canvas/renderer.js +28 -4
  38. package/dist/canvas/renderer.js.map +1 -1
  39. package/dist/canvas/scene.d.ts.map +1 -1
  40. package/dist/canvas/scene.js +4 -3
  41. package/dist/canvas/scene.js.map +1 -1
  42. package/dist/canvas/shaders/compile.d.ts +3 -1
  43. package/dist/canvas/shaders/compile.d.ts.map +1 -1
  44. package/dist/canvas/shaders/compile.js +12 -3
  45. package/dist/canvas/shaders/compile.js.map +1 -1
  46. package/dist/canvas/shaders/draw.d.ts.map +1 -1
  47. package/dist/canvas/shaders/draw.js +10 -3
  48. package/dist/canvas/shaders/draw.js.map +1 -1
  49. package/dist/canvas/shaders/effect.d.ts.map +1 -1
  50. package/dist/canvas/shaders/effect.js +8 -17
  51. package/dist/canvas/shaders/effect.js.map +1 -1
  52. package/dist/canvas/shadows/shape.d.ts.map +1 -1
  53. package/dist/canvas/shadows/shape.js +4 -2
  54. package/dist/canvas/shadows/shape.js.map +1 -1
  55. package/dist/canvas/shadows.d.ts.map +1 -1
  56. package/dist/canvas/shadows.js +4 -2
  57. package/dist/canvas/shadows.js.map +1 -1
  58. package/dist/canvas/text/decorations.d.ts +2 -2
  59. package/dist/canvas/text/decorations.d.ts.map +1 -1
  60. package/dist/canvas/text/decorations.js +5 -5
  61. package/dist/canvas/text/decorations.js.map +1 -1
  62. package/dist/canvas/text/index.js +1 -1
  63. package/dist/canvas/text/index.js.map +1 -1
  64. package/dist/canvas/text/paragraph/index.d.ts +2 -2
  65. package/dist/canvas/text/paragraph/index.d.ts.map +1 -1
  66. package/dist/canvas/text/paragraph/index.js +16 -5
  67. package/dist/canvas/text/paragraph/index.js.map +1 -1
  68. package/dist/canvas/text/renderer.d.ts +2 -1
  69. package/dist/canvas/text/renderer.d.ts.map +1 -1
  70. package/dist/canvas/text/shape.js +4 -4
  71. package/dist/canvas/text/shape.js.map +1 -1
  72. package/dist/canvas/texture.d.ts.map +1 -1
  73. package/dist/canvas/texture.js +2 -1
  74. package/dist/canvas/texture.js.map +1 -1
  75. package/dist/design-memory/rules.js +1 -1
  76. package/dist/editor/clipboard/assets.d.ts.map +1 -1
  77. package/dist/editor/clipboard/assets.js +2 -2
  78. package/dist/editor/clipboard/assets.js.map +1 -1
  79. package/dist/editor/clipboard/component-matches.d.ts +13 -0
  80. package/dist/editor/clipboard/component-matches.d.ts.map +1 -0
  81. package/dist/editor/clipboard/component-matches.js +50 -0
  82. package/dist/editor/clipboard/component-matches.js.map +1 -0
  83. package/dist/editor/clipboard/dependencies.d.ts +7 -0
  84. package/dist/editor/clipboard/dependencies.d.ts.map +1 -1
  85. package/dist/editor/clipboard/dependencies.js +5 -0
  86. package/dist/editor/clipboard/dependencies.js.map +1 -1
  87. package/dist/editor/clipboard/export.js +2 -2
  88. package/dist/editor/clipboard/export.js.map +1 -1
  89. package/dist/editor/clipboard.d.ts.map +1 -1
  90. package/dist/editor/clipboard.js +48 -19
  91. package/dist/editor/clipboard.js.map +1 -1
  92. package/dist/editor/components/properties.d.ts.map +1 -1
  93. package/dist/editor/components/properties.js +3 -3
  94. package/dist/editor/components/properties.js.map +1 -1
  95. package/dist/editor/eyedropper.d.ts +1 -1
  96. package/dist/editor/eyedropper.d.ts.map +1 -1
  97. package/dist/editor/eyedropper.js +6 -3
  98. package/dist/editor/eyedropper.js.map +1 -1
  99. package/dist/editor/history/atomic-tool.d.ts.map +1 -1
  100. package/dist/editor/history/atomic-tool.js +3 -2
  101. package/dist/editor/history/atomic-tool.js.map +1 -1
  102. package/dist/editor/shapes/pencil.js +1 -1
  103. package/dist/editor/structure/state.d.ts.map +1 -1
  104. package/dist/editor/structure/state.js +2 -2
  105. package/dist/editor/structure/state.js.map +1 -1
  106. package/dist/editor/text.d.ts.map +1 -1
  107. package/dist/editor/text.js +2 -2
  108. package/dist/editor/text.js.map +1 -1
  109. package/dist/editor/variables.js +3 -3
  110. package/dist/editor/variables.js.map +1 -1
  111. package/dist/figma-api/fresh-read.d.ts +15 -0
  112. package/dist/figma-api/fresh-read.d.ts.map +1 -0
  113. package/dist/figma-api/fresh-read.js +54 -0
  114. package/dist/figma-api/fresh-read.js.map +1 -0
  115. package/dist/figma-api/graph-ref.d.ts +9 -0
  116. package/dist/figma-api/graph-ref.d.ts.map +1 -0
  117. package/dist/figma-api/graph-ref.js +14 -0
  118. package/dist/figma-api/graph-ref.js.map +1 -0
  119. package/dist/figma-api/index.d.ts +6 -1
  120. package/dist/figma-api/index.d.ts.map +1 -1
  121. package/dist/figma-api/index.js +12 -5
  122. package/dist/figma-api/index.js.map +1 -1
  123. package/dist/figma-api/pending-layout.d.ts +3 -3
  124. package/dist/figma-api/pending-layout.d.ts.map +1 -1
  125. package/dist/figma-api/pending-layout.js +7 -3
  126. package/dist/figma-api/pending-layout.js.map +1 -1
  127. package/dist/figma-api/pending-sync.d.ts +1 -1
  128. package/dist/figma-api/pending-sync.d.ts.map +1 -1
  129. package/dist/figma-api/pending-sync.js +3 -1
  130. package/dist/figma-api/pending-sync.js.map +1 -1
  131. package/dist/figma-api/proxy.d.ts.map +1 -1
  132. package/dist/figma-api/proxy.js +3 -2
  133. package/dist/figma-api/proxy.js.map +1 -1
  134. package/dist/figma-api/reactions.d.ts +20 -4
  135. package/dist/figma-api/reactions.d.ts.map +1 -1
  136. package/dist/figma-api/reactions.js +49 -3
  137. package/dist/figma-api/reactions.js.map +1 -1
  138. package/dist/figma-api/variables/index.d.ts.map +1 -1
  139. package/dist/figma-api/variables/index.js +2 -2
  140. package/dist/figma-api/variables/index.js.map +1 -1
  141. package/dist/io/formats/design-tokens/css/known.js +1 -1
  142. package/dist/io/formats/design-tokens/css/known.js.map +1 -1
  143. package/dist/io/formats/design-tokens/css/read.d.ts +3 -1
  144. package/dist/io/formats/design-tokens/css/read.d.ts.map +1 -1
  145. package/dist/io/formats/design-tokens/css/read.js +11 -5
  146. package/dist/io/formats/design-tokens/css/read.js.map +1 -1
  147. package/dist/io/formats/design-tokens/css/sync.d.ts.map +1 -1
  148. package/dist/io/formats/design-tokens/css/sync.js +17 -4
  149. package/dist/io/formats/design-tokens/css/sync.js.map +1 -1
  150. package/dist/io/formats/design-tokens/css/values.d.ts +6 -5
  151. package/dist/io/formats/design-tokens/css/values.d.ts.map +1 -1
  152. package/dist/io/formats/design-tokens/css/values.js +24 -8
  153. package/dist/io/formats/design-tokens/css/values.js.map +1 -1
  154. package/dist/io/formats/design-tokens/decode.d.ts +7 -6
  155. package/dist/io/formats/design-tokens/decode.d.ts.map +1 -1
  156. package/dist/io/formats/design-tokens/decode.js +13 -12
  157. package/dist/io/formats/design-tokens/decode.js.map +1 -1
  158. package/dist/io/formats/design-tokens/export.js +3 -3
  159. package/dist/io/formats/design-tokens/export.js.map +1 -1
  160. package/dist/io/formats/design-tokens/plan/index.d.ts.map +1 -1
  161. package/dist/io/formats/design-tokens/plan/index.js +4 -3
  162. package/dist/io/formats/design-tokens/plan/index.js.map +1 -1
  163. package/dist/io/formats/design-tokens/plan/styles.d.ts.map +1 -1
  164. package/dist/io/formats/design-tokens/plan/styles.js +9 -9
  165. package/dist/io/formats/design-tokens/plan/styles.js.map +1 -1
  166. package/dist/io/formats/design-tokens/styles.d.ts +4 -4
  167. package/dist/io/formats/design-tokens/styles.d.ts.map +1 -1
  168. package/dist/io/formats/design-tokens/styles.js +7 -7
  169. package/dist/io/formats/design-tokens/styles.js.map +1 -1
  170. package/dist/io/formats/design-tokens/sync/drift.js +2 -2
  171. package/dist/io/formats/design-tokens/sync/drift.js.map +1 -1
  172. package/dist/io/formats/design-tokens/values.d.ts +10 -5
  173. package/dist/io/formats/design-tokens/values.d.ts.map +1 -1
  174. package/dist/io/formats/design-tokens/values.js +13 -7
  175. package/dist/io/formats/design-tokens/values.js.map +1 -1
  176. package/dist/io/formats/drawio/label.js +1 -1
  177. package/dist/io/formats/drawio/paint.js +1 -1
  178. package/dist/io/formats/drawio/warnings.d.ts +17 -2
  179. package/dist/io/formats/drawio/warnings.d.ts.map +1 -1
  180. package/dist/io/formats/drawio/warnings.js +15 -8
  181. package/dist/io/formats/drawio/warnings.js.map +1 -1
  182. package/dist/io/formats/fig/export/index.d.ts.map +1 -1
  183. package/dist/io/formats/fig/export/index.js +15 -3
  184. package/dist/io/formats/fig/export/index.js.map +1 -1
  185. package/dist/io/formats/fig/export/patch/index.d.ts.map +1 -1
  186. package/dist/io/formats/fig/export/patch/index.js +2 -1
  187. package/dist/io/formats/fig/export/patch/index.js.map +1 -1
  188. package/dist/io/formats/fig/export/setup.d.ts +7 -2
  189. package/dist/io/formats/fig/export/setup.d.ts.map +1 -1
  190. package/dist/io/formats/fig/export/setup.js +12 -13
  191. package/dist/io/formats/fig/export/setup.js.map +1 -1
  192. package/dist/io/formats/fig/export/variables.d.ts.map +1 -1
  193. package/dist/io/formats/fig/export/variables.js +9 -7
  194. package/dist/io/formats/fig/export/variables.js.map +1 -1
  195. package/dist/io/formats/html/index.d.ts +1 -0
  196. package/dist/io/formats/html/index.d.ts.map +1 -1
  197. package/dist/io/formats/html/index.js +5 -3
  198. package/dist/io/formats/html/index.js.map +1 -1
  199. package/dist/io/formats/html/vectors.js +1 -0
  200. package/dist/io/formats/html/vectors.js.map +1 -1
  201. package/dist/io/formats/mermaid/layers.js +2 -2
  202. package/dist/io/formats/mermaid/layers.js.map +1 -1
  203. package/dist/io/formats/mermaid/styles.js +1 -1
  204. package/dist/io/formats/pdf/export.d.ts.map +1 -1
  205. package/dist/io/formats/pdf/export.js +1 -0
  206. package/dist/io/formats/pdf/export.js.map +1 -1
  207. package/dist/io/formats/pdf/prepare.d.ts +4 -4
  208. package/dist/io/formats/pdf/prepare.d.ts.map +1 -1
  209. package/dist/io/formats/pdf/prepare.js +2 -2
  210. package/dist/io/formats/pdf/prepare.js.map +1 -1
  211. package/dist/io/formats/pen/index.d.ts.map +1 -1
  212. package/dist/io/formats/pen/index.js +13 -2
  213. package/dist/io/formats/pen/index.js.map +1 -1
  214. package/dist/io/formats/pptx/style.js +1 -1
  215. package/dist/io/formats/raster/render.d.ts +1 -1
  216. package/dist/io/formats/raster/render.d.ts.map +1 -1
  217. package/dist/io/formats/raster/render.js +9 -4
  218. package/dist/io/formats/raster/render.js.map +1 -1
  219. package/dist/io/formats/svg/defs.d.ts +6 -3
  220. package/dist/io/formats/svg/defs.d.ts.map +1 -1
  221. package/dist/io/formats/svg/defs.js +12 -11
  222. package/dist/io/formats/svg/defs.js.map +1 -1
  223. package/dist/io/formats/svg/effects.js +2 -2
  224. package/dist/io/formats/svg/effects.js.map +1 -1
  225. package/dist/io/formats/svg/export.d.ts +5 -2
  226. package/dist/io/formats/svg/export.d.ts.map +1 -1
  227. package/dist/io/formats/svg/export.js +4 -2
  228. package/dist/io/formats/svg/export.js.map +1 -1
  229. package/dist/io/formats/svg/filter.d.ts +4 -1
  230. package/dist/io/formats/svg/filter.d.ts.map +1 -1
  231. package/dist/io/formats/svg/filter.js +6 -2
  232. package/dist/io/formats/svg/filter.js.map +1 -1
  233. package/dist/io/formats/svg/grain.js +1 -1
  234. package/dist/io/formats/svg/grain.js.map +1 -1
  235. package/dist/io/formats/svg/import.d.ts +4 -2
  236. package/dist/io/formats/svg/import.d.ts.map +1 -1
  237. package/dist/io/formats/svg/import.js +2 -1
  238. package/dist/io/formats/svg/import.js.map +1 -1
  239. package/dist/io/formats/svg/text/export.d.ts.map +1 -1
  240. package/dist/io/formats/svg/text/export.js +8 -8
  241. package/dist/io/formats/svg/text/export.js.map +1 -1
  242. package/dist/io/formats/svg/text/layout.js +2 -2
  243. package/dist/io/formats/svg/text/layout.js.map +1 -1
  244. package/dist/io/formats.d.ts.map +1 -1
  245. package/dist/io/formats.js +11 -4
  246. package/dist/io/formats.js.map +1 -1
  247. package/dist/io/index.d.ts +2 -2
  248. package/dist/io/subgraph.d.ts.map +1 -1
  249. package/dist/io/subgraph.js +1 -1
  250. package/dist/io/subgraph.js.map +1 -1
  251. package/dist/io/types.d.ts +12 -3
  252. package/dist/io/types.d.ts.map +1 -1
  253. package/dist/kiwi/fig/session/options.d.ts +3 -0
  254. package/dist/kiwi/fig/session/options.d.ts.map +1 -1
  255. package/dist/kiwi/fig/session/options.js +4 -0
  256. package/dist/kiwi/fig/session/options.js.map +1 -1
  257. package/dist/layout/yoga-helpers.d.ts +2 -1
  258. package/dist/layout/yoga-helpers.d.ts.map +1 -1
  259. package/dist/layout/yoga-helpers.js +7 -1
  260. package/dist/layout/yoga-helpers.js.map +1 -1
  261. package/dist/layout.js +24 -1
  262. package/dist/layout.js.map +1 -1
  263. package/dist/lint/fixes.js +1 -1
  264. package/dist/lint/linter.js +2 -2
  265. package/dist/lint/linter.js.map +1 -1
  266. package/dist/pairdraw-api/comments.d.ts +4 -1
  267. package/dist/pairdraw-api/comments.d.ts.map +1 -1
  268. package/dist/pairdraw-api/comments.js +5 -0
  269. package/dist/pairdraw-api/comments.js.map +1 -1
  270. package/dist/pairdraw-api/index.d.ts +3 -3
  271. package/dist/pairdraw-api/index.d.ts.map +1 -1
  272. package/dist/pairdraw-api/index.js +5 -5
  273. package/dist/pairdraw-api/index.js.map +1 -1
  274. package/dist/pairdraw-api/nodes.d.ts +1 -1
  275. package/dist/prototype/scene.js +1 -1
  276. package/dist/rpc/analyze-commands.js +1 -1
  277. package/dist/rpc/read-commands.d.ts +2 -2
  278. package/dist/rpc/read-commands.js +3 -3
  279. package/dist/rpc/read-commands.js.map +1 -1
  280. package/dist/rpc/variables-command.js +2 -2
  281. package/dist/rpc/variables-command.js.map +1 -1
  282. package/dist/text/font/provider.d.ts +15 -0
  283. package/dist/text/font/provider.d.ts.map +1 -0
  284. package/dist/text/font/provider.js +18 -0
  285. package/dist/text/font/provider.js.map +1 -0
  286. package/dist/text/font/readiness.d.ts +32 -0
  287. package/dist/text/font/readiness.d.ts.map +1 -0
  288. package/dist/text/font/{status.js → readiness.js} +8 -4
  289. package/dist/text/font/readiness.js.map +1 -0
  290. package/dist/text/index.d.ts +4 -3
  291. package/dist/text/index.js +4 -3
  292. package/dist/text/prepare.d.ts +9 -4
  293. package/dist/text/prepare.d.ts.map +1 -1
  294. package/dist/text/prepare.js +9 -4
  295. package/dist/text/prepare.js.map +1 -1
  296. package/dist/tools/analyze/colors.js +1 -1
  297. package/dist/tools/analyze/responsive/index.js +7 -18
  298. package/dist/tools/analyze/responsive/index.js.map +1 -1
  299. package/dist/tools/analyze/responsive/widths.d.ts +27 -0
  300. package/dist/tools/analyze/responsive/widths.d.ts.map +1 -0
  301. package/dist/tools/analyze/responsive/widths.js +49 -0
  302. package/dist/tools/analyze/responsive/widths.js.map +1 -0
  303. package/dist/tools/analyze.d.ts +2 -1
  304. package/dist/tools/analyze.js +2 -1
  305. package/dist/tools/codegen/tokens.d.ts.map +1 -1
  306. package/dist/tools/codegen/tokens.js +2 -2
  307. package/dist/tools/codegen/tokens.js.map +1 -1
  308. package/dist/tools/comments.d.ts.map +1 -1
  309. package/dist/tools/comments.js +2 -2
  310. package/dist/tools/comments.js.map +1 -1
  311. package/dist/tools/component-catalog.d.ts.map +1 -1
  312. package/dist/tools/component-catalog.js +5 -3
  313. package/dist/tools/component-catalog.js.map +1 -1
  314. package/dist/tools/create/basic.js +1 -1
  315. package/dist/tools/create/behaviours.js +1 -1
  316. package/dist/tools/create/html.d.ts.map +1 -1
  317. package/dist/tools/create/html.js +1 -3
  318. package/dist/tools/create/html.js.map +1 -1
  319. package/dist/tools/create/icons.js +2 -2
  320. package/dist/tools/create/icons.js.map +1 -1
  321. package/dist/tools/create/mermaid.js +1 -1
  322. package/dist/tools/create/render.js +1 -1
  323. package/dist/tools/create/svg.js +5 -2
  324. package/dist/tools/create/svg.js.map +1 -1
  325. package/dist/tools/create/vector.js +3 -3
  326. package/dist/tools/create/vector.js.map +1 -1
  327. package/dist/tools/css/shorthand.d.ts +20 -0
  328. package/dist/tools/css/shorthand.d.ts.map +1 -0
  329. package/dist/tools/css/shorthand.js +54 -0
  330. package/dist/tools/css/shorthand.js.map +1 -0
  331. package/dist/tools/describe/index.js +2 -2
  332. package/dist/tools/describe/index.js.map +1 -1
  333. package/dist/tools/describe/issues.js +1 -1
  334. package/dist/tools/html-host.d.ts.map +1 -1
  335. package/dist/tools/html-host.js +5 -3
  336. package/dist/tools/html-host.js.map +1 -1
  337. package/dist/tools/image-ai/apply.d.ts.map +1 -1
  338. package/dist/tools/image-ai/apply.js +1 -3
  339. package/dist/tools/image-ai/apply.js.map +1 -1
  340. package/dist/tools/image-ai/generate.js +1 -1
  341. package/dist/tools/image-ai/service.d.ts.map +1 -1
  342. package/dist/tools/image-ai/service.js +5 -3
  343. package/dist/tools/image-ai/service.js.map +1 -1
  344. package/dist/tools/index.d.ts +2 -1
  345. package/dist/tools/index.js +2 -1
  346. package/dist/tools/modify/effects.js +1 -1
  347. package/dist/tools/modify/effects.js.map +1 -1
  348. package/dist/tools/modify/geometry.d.ts.map +1 -1
  349. package/dist/tools/modify/geometry.js +14 -3
  350. package/dist/tools/modify/geometry.js.map +1 -1
  351. package/dist/tools/modify/layout.d.ts.map +1 -1
  352. package/dist/tools/modify/layout.js +35 -8
  353. package/dist/tools/modify/layout.js.map +1 -1
  354. package/dist/tools/modify/matching.d.ts.map +1 -1
  355. package/dist/tools/modify/matching.js +10 -10
  356. package/dist/tools/modify/matching.js.map +1 -1
  357. package/dist/tools/modify/paint.d.ts.map +1 -1
  358. package/dist/tools/modify/paint.js +57 -5
  359. package/dist/tools/modify/paint.js.map +1 -1
  360. package/dist/tools/modify/reactions.d.ts.map +1 -1
  361. package/dist/tools/modify/reactions.js +2 -2
  362. package/dist/tools/modify/reactions.js.map +1 -1
  363. package/dist/tools/modify/text.d.ts.map +1 -1
  364. package/dist/tools/modify/text.js +3 -3
  365. package/dist/tools/modify/text.js.map +1 -1
  366. package/dist/tools/prompts/codegen.js +1 -1
  367. package/dist/tools/prompts/codegen.js.map +1 -1
  368. package/dist/tools/read/css.d.ts +14 -0
  369. package/dist/tools/read/css.d.ts.map +1 -0
  370. package/dist/tools/read/css.js +306 -0
  371. package/dist/tools/read/css.js.map +1 -0
  372. package/dist/tools/read/libraries.js +1 -1
  373. package/dist/tools/read/reactions.js +1 -1
  374. package/dist/tools/read/reactions.js.map +1 -1
  375. package/dist/tools/read/space.d.ts.map +1 -1
  376. package/dist/tools/read/space.js +0 -2
  377. package/dist/tools/read/space.js.map +1 -1
  378. package/dist/tools/read.d.ts +2 -1
  379. package/dist/tools/read.js +2 -1
  380. package/dist/tools/registry/core.d.ts +1 -1
  381. package/dist/tools/registry/core.js +3 -1
  382. package/dist/tools/registry/core.js.map +1 -1
  383. package/dist/tools/schema.d.ts +6 -4
  384. package/dist/tools/schema.d.ts.map +1 -1
  385. package/dist/tools/schema.js +9 -5
  386. package/dist/tools/schema.js.map +1 -1
  387. package/dist/tools/script/host.d.ts.map +1 -1
  388. package/dist/tools/script/host.js +5 -3
  389. package/dist/tools/script/host.js.map +1 -1
  390. package/dist/tools/variables/collections.js +1 -1
  391. package/dist/tools/variables/collections.js.map +1 -1
  392. package/dist/tools/variables/values.d.ts.map +1 -1
  393. package/dist/tools/variables/values.js +4 -4
  394. package/dist/tools/variables/values.js.map +1 -1
  395. package/dist/tools/vector/vectorize.d.ts.map +1 -1
  396. package/dist/tools/vector/vectorize.js +6 -4
  397. package/dist/tools/vector/vectorize.js.map +1 -1
  398. package/dist/tools/video-host.d.ts.map +1 -1
  399. package/dist/tools/video-host.js +5 -3
  400. package/dist/tools/video-host.js.map +1 -1
  401. package/dist/vector/vectorize/svg/gradients.d.ts +2 -2
  402. package/dist/vector/vectorize/svg/gradients.d.ts.map +1 -1
  403. package/dist/vector/vectorize/svg/gradients.js +5 -5
  404. package/dist/vector/vectorize/svg/gradients.js.map +1 -1
  405. package/dist/vector/vectorize/svg/to-vectors.d.ts +3 -1
  406. package/dist/vector/vectorize/svg/to-vectors.d.ts.map +1 -1
  407. package/dist/vector/vectorize/svg/to-vectors.js +13 -12
  408. package/dist/vector/vectorize/svg/to-vectors.js.map +1 -1
  409. package/package.json +9 -9
  410. package/src/canvas/noise/render.ts +1 -1
  411. package/src/canvas/noise/shader.ts +13 -5
  412. package/src/canvas/noise/tile.ts +2 -1
  413. package/src/canvas/renderer/colors.ts +76 -50
  414. package/src/canvas/renderer/document-surface.ts +53 -0
  415. package/src/canvas/renderer/fonts.ts +6 -4
  416. package/src/canvas/renderer/lifecycle.ts +4 -4
  417. package/src/canvas/renderer/methods.ts +1 -0
  418. package/src/canvas/renderer/pipeline.ts +21 -3
  419. package/src/canvas/renderer/retained-backing.ts +2 -1
  420. package/src/canvas/renderer/tiles/surface-pool.ts +9 -7
  421. package/src/canvas/renderer.ts +36 -11
  422. package/src/canvas/scene.ts +4 -3
  423. package/src/canvas/shaders/compile.ts +14 -3
  424. package/src/canvas/shaders/draw.ts +11 -4
  425. package/src/canvas/shaders/effect.ts +8 -19
  426. package/src/canvas/shadows/shape.ts +4 -2
  427. package/src/canvas/shadows.ts +5 -2
  428. package/src/canvas/text/decorations.ts +15 -5
  429. package/src/canvas/text/index.ts +9 -1
  430. package/src/canvas/text/paragraph/index.ts +16 -6
  431. package/src/canvas/text/renderer.ts +2 -1
  432. package/src/canvas/text/shape.ts +4 -4
  433. package/src/canvas/texture.ts +2 -1
  434. package/src/editor/clipboard/assets.ts +6 -2
  435. package/src/editor/clipboard/component-matches.ts +65 -0
  436. package/src/editor/clipboard/dependencies.ts +22 -1
  437. package/src/editor/clipboard/export.ts +2 -2
  438. package/src/editor/clipboard.ts +74 -20
  439. package/src/editor/components/properties.ts +3 -2
  440. package/src/editor/eyedropper.ts +14 -4
  441. package/src/editor/history/atomic-tool.ts +3 -2
  442. package/src/editor/structure/state.ts +2 -1
  443. package/src/editor/text.ts +2 -1
  444. package/src/editor/variables.ts +3 -3
  445. package/src/figma-api/fresh-read.ts +57 -0
  446. package/src/figma-api/graph-ref.ts +13 -0
  447. package/src/figma-api/index.ts +12 -4
  448. package/src/figma-api/pending-layout.ts +7 -3
  449. package/src/figma-api/pending-sync.ts +4 -1
  450. package/src/figma-api/proxy.ts +2 -1
  451. package/src/figma-api/reactions.ts +91 -10
  452. package/src/figma-api/variables/index.ts +5 -4
  453. package/src/io/formats/design-tokens/css/known.ts +1 -1
  454. package/src/io/formats/design-tokens/css/read.ts +20 -7
  455. package/src/io/formats/design-tokens/css/sync.ts +9 -4
  456. package/src/io/formats/design-tokens/css/values.ts +37 -9
  457. package/src/io/formats/design-tokens/decode.ts +17 -12
  458. package/src/io/formats/design-tokens/export.ts +3 -3
  459. package/src/io/formats/design-tokens/plan/index.ts +6 -5
  460. package/src/io/formats/design-tokens/plan/styles.ts +37 -10
  461. package/src/io/formats/design-tokens/styles.ts +10 -7
  462. package/src/io/formats/design-tokens/sync/drift.ts +6 -4
  463. package/src/io/formats/design-tokens/values.ts +15 -8
  464. package/src/io/formats/drawio/warnings.ts +28 -9
  465. package/src/io/formats/fig/export/index.ts +36 -3
  466. package/src/io/formats/fig/export/patch/index.ts +4 -1
  467. package/src/io/formats/fig/export/setup.ts +25 -15
  468. package/src/io/formats/fig/export/variables.ts +17 -6
  469. package/src/io/formats/html/index.ts +9 -3
  470. package/src/io/formats/html/vectors.ts +1 -0
  471. package/src/io/formats/mermaid/layers.ts +2 -2
  472. package/src/io/formats/pdf/export.ts +1 -0
  473. package/src/io/formats/pdf/prepare.ts +6 -6
  474. package/src/io/formats/pen/index.ts +15 -4
  475. package/src/io/formats/raster/render.ts +12 -4
  476. package/src/io/formats/svg/defs.ts +26 -14
  477. package/src/io/formats/svg/effects.ts +2 -2
  478. package/src/io/formats/svg/export.ts +17 -3
  479. package/src/io/formats/svg/filter.ts +12 -2
  480. package/src/io/formats/svg/grain.ts +1 -1
  481. package/src/io/formats/svg/import.ts +6 -3
  482. package/src/io/formats/svg/text/export.ts +10 -8
  483. package/src/io/formats/svg/text/layout.ts +2 -2
  484. package/src/io/formats.ts +18 -5
  485. package/src/io/index.ts +1 -0
  486. package/src/io/subgraph.ts +4 -1
  487. package/src/io/types.ts +10 -0
  488. package/src/kiwi/fig/session/options.ts +4 -1
  489. package/src/layout/yoga-helpers.ts +8 -0
  490. package/src/layout.ts +47 -1
  491. package/src/lint/linter.ts +1 -1
  492. package/src/pairdraw-api/comments.ts +6 -0
  493. package/src/pairdraw-api/index.ts +7 -9
  494. package/src/rpc/read-commands.ts +4 -4
  495. package/src/rpc/variables-command.ts +2 -2
  496. package/src/text/font/provider.ts +26 -0
  497. package/src/text/font/{status.ts → readiness.ts} +13 -9
  498. package/src/text/index.ts +2 -1
  499. package/src/text/prepare.ts +9 -4
  500. package/src/tools/analyze/responsive/index.ts +8 -15
  501. package/src/tools/analyze/responsive/widths.ts +63 -0
  502. package/src/tools/analyze.ts +2 -0
  503. package/src/tools/codegen/tokens.ts +4 -2
  504. package/src/tools/comments.ts +6 -4
  505. package/src/tools/component-catalog.ts +5 -3
  506. package/src/tools/create/html.ts +0 -3
  507. package/src/tools/create/icons.ts +1 -1
  508. package/src/tools/create/svg.ts +4 -1
  509. package/src/tools/create/vector.ts +2 -2
  510. package/src/tools/css/shorthand.ts +64 -0
  511. package/src/tools/describe/index.ts +2 -8
  512. package/src/tools/html-host.ts +5 -3
  513. package/src/tools/image-ai/apply.ts +0 -2
  514. package/src/tools/image-ai/service.ts +5 -3
  515. package/src/tools/index.ts +2 -0
  516. package/src/tools/modify/effects.ts +1 -1
  517. package/src/tools/modify/geometry.ts +16 -3
  518. package/src/tools/modify/layout.ts +47 -13
  519. package/src/tools/modify/matching.ts +14 -11
  520. package/src/tools/modify/paint.ts +85 -5
  521. package/src/tools/modify/reactions.ts +3 -2
  522. package/src/tools/modify/text.ts +15 -11
  523. package/src/tools/prompts/codegen.md +2 -1
  524. package/src/tools/read/css.ts +365 -0
  525. package/src/tools/read/reactions.ts +3 -2
  526. package/src/tools/read/space.ts +0 -2
  527. package/src/tools/read.ts +1 -0
  528. package/src/tools/registry/core.ts +3 -2
  529. package/src/tools/schema.ts +14 -5
  530. package/src/tools/script/host.ts +6 -3
  531. package/src/tools/variables/collections.ts +1 -1
  532. package/src/tools/variables/values.ts +16 -5
  533. package/src/tools/vector/vectorize.ts +10 -4
  534. package/src/tools/video-host.ts +5 -3
  535. package/src/vector/vectorize/svg/gradients.ts +8 -5
  536. package/src/vector/vectorize/svg/to-vectors.ts +48 -14
  537. package/dist/text/font/status.d.ts +0 -28
  538. package/dist/text/font/status.d.ts.map +0 -1
  539. package/dist/text/font/status.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"schema.js","names":[],"sources":["../../src/tools/schema.ts"],"sourcesContent":["/**\n * Tool definition schema.\n *\n * Native Valibot inputs and execution capabilities are owned by each tool.\n * Adapters consume these contracts rather than maintaining transport-specific schemas.\n */\n\nimport * as v from 'valibot'\n\nimport type { SceneNode } from '@pairdraw/scene-graph'\nimport { tryParseColor } from '@pairdraw/scene-graph/color'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport type { FigmaAPI, FigmaNodeProxy } from '#core/figma-api'\nimport type { FigmaFontNameInput } from '#core/figma-api/fonts/names'\n\nexport type ToolCapability =\n | 'document:read'\n | 'document:write'\n | 'filesystem:read'\n | 'filesystem:write'\n | 'network:access'\n | 'code:execute'\n | 'settings:read'\n | 'settings:write'\n\nexport type ToolExecution =\n | { kind: 'sync'; mutation: 'none' | 'view' | 'properties' | 'document' }\n | {\n kind: 'async'\n mutation: 'none' | 'view' | 'document'\n /**\n * The call can run for a long time even when it only reads, such as recording a video, so\n * bridges give it the deadline they give an edit.\n */\n long?: boolean\n }\n\nexport type ToolInterface = 'mcp' | 'ai' | 'webmcp'\nexport type ToolExposure = Partial<Record<ToolInterface, boolean>>\n\ninterface ToolMetadata {\n name: string\n description: string\n execution: ToolExecution\n /** Interface inclusion defaults to true; execution support and user permissions remain separate. */\n exposure: ToolExposure\n capabilities: readonly ToolCapability[]\n availability: 'default' | 'eval'\n /**\n * What a call's values come from, for the document's design memory:\n * - `imported`: outside content, such as a web page, an SVG, a photo or a library component,\n * whose colors and type are its own, so the memory warns about them rather than refusing;\n * - `copied`: the layers the call names, which it copies or converts with their values, such\n * as a clone, a group or a boolean, so values those layers already had are not new.\n * - `merged`: layers the call joins into one, which may take a paint from any of them, such as\n * flatten and boolean operations; a value is only theirs when every named layer had it.\n */\n content?: 'imported' | 'copied' | 'merged'\n}\n\nexport interface ToolDef extends ToolMetadata {\n input: v.StrictObjectSchema<v.ObjectEntries, undefined>\n /** Derived from execution metadata, never declared independently by a tool. */\n readonly mutates: boolean\n /**\n * Loads the fonts the call's text edits need, as a Figma plugin loads them before it edits\n * text; rejects when one cannot load. Every executor awaits it before `execute`, so a\n * synchronous tool still edits in one step.\n */\n loadFonts: (figma: FigmaAPI, args: Record<string, unknown>) => Promise<void>\n /** `signal` aborts a caller's cancelled request, which a long export checks while it runs. */\n execute: (figma: FigmaAPI, args: Record<string, unknown>, signal?: AbortSignal) => unknown\n /**\n * The synchronous answer of a read whose `execute` may load a page first, or `undefined`\n * when answering would load. Hosts that cannot wait refuse on `undefined` before any load.\n */\n executeSync?: (figma: FigmaAPI, args: Record<string, unknown>) => unknown\n}\n\ntype ToolDefinitionMetadata = Omit<ToolMetadata, 'exposure' | 'capabilities' | 'availability'> &\n Partial<Pick<ToolMetadata, 'exposure' | 'capabilities' | 'availability'>>\n\nexport function defineTool<P extends v.ObjectEntries, R>(\n def: ToolDefinitionMetadata & {\n input: v.StrictObjectSchema<P, undefined>\n execution: ToolExecution & (R extends PromiseLike<unknown> ? { kind: 'async' } : unknown)\n /** The fonts a call's text edits need loaded first; text edits refuse unloaded fonts. */\n fonts?: (\n figma: FigmaAPI,\n args: v.InferOutput<v.StrictObjectSchema<P, undefined>>\n ) => FigmaFontNameInput[]\n execute: (\n figma: FigmaAPI,\n args: v.InferOutput<v.StrictObjectSchema<P, undefined>>,\n signal?: AbortSignal\n ) => R\n executeSync?: (\n figma: FigmaAPI,\n args: v.InferOutput<v.StrictObjectSchema<P, undefined>>\n ) => unknown\n }\n): ToolDef {\n const { fonts } = def\n return {\n ...def,\n exposure: def.exposure ?? {},\n capabilities: def.capabilities ?? [\n toolChangesDocument(def) ? 'document:write' : 'document:read'\n ],\n availability: def.availability ?? 'default',\n get mutates() {\n return def.execution.mutation !== 'none'\n },\n async loadFonts(figma, args) {\n if (!fonts) return\n // Wrong arguments are for `execute` to report.\n const parsed = v.safeParse(def.input, args)\n if (!parsed.success) return\n for (const font of fonts(figma, parsed.output)) await figma.loadFontAsync(font)\n },\n execute: (figma, args, signal) =>\n def.execute(figma, parseToolArgs(def.name, def.input, args), signal),\n executeSync: def.executeSync\n ? (figma, args) => def.executeSync?.(figma, parseToolArgs(def.name, def.input, args))\n : undefined\n }\n}\n\n/**\n * Every tool run goes through here, so a wrong call from AI chat, the CLI, WebMCP, and MCP names\n * the tool and lists each problem with its argument. An unknown or missing argument names the\n * arguments the tool takes, and a picklist names the values it accepts, read from the schema, so\n * the caller does not have to guess. Inputs are strict objects, so a misspelled or mis-nested\n * argument fails here instead of being dropped.\n */\nexport function parseToolArgs<S extends v.GenericSchema>(\n name: string,\n schema: S,\n args: unknown\n): v.InferOutput<S> {\n const result = v.safeParse(schema, args)\n if (result.success) return result.output\n throw new Error(formatToolArgumentError(name, schema, result.issues))\n}\n\n/** One refusal for every surface: the tool, then each problem with where it is. */\nfunction formatToolArgumentError(\n name: string,\n schema: v.GenericSchema,\n issues: readonly v.BaseIssue<unknown>[]\n): string {\n const problems = issues\n .flatMap((issue) => branchIssues(schema, issue))\n .map(({ keys, issue }) => {\n const place = keys.length > 0 ? `\\n → at ${placeOf(keys)}` : ''\n return `× ${formatToolArgIssue(schema, keys, issue)}${place}`\n })\n return `Invalid arguments for ${name}:\\n${problems.join('\\n')}`\n}\n\n/** The parts of a Valibot schema this module reads to name what a call should have sent. */\ntype SchemaParts = {\n readonly entries?: v.ObjectEntries\n readonly item?: v.GenericSchema\n readonly wrapped?: v.GenericSchema\n readonly options?: readonly unknown[]\n}\n\nfunction schemaParts(schema: unknown): SchemaParts {\n return typeof schema === 'object' && schema !== null ? schema : {}\n}\n\n/** The schema a wrapper such as `optional` or `pipe` holds, down to the one with the rules. */\nfunction unwrappedSchema(schema: v.GenericSchema): v.GenericSchema {\n let current = schema\n for (;;) {\n const wrapped = schemaParts(current).wrapped\n if (!wrapped) return current\n current = wrapped\n }\n}\n\ntype ArgumentKey = string | number\n\nfunction issueKeys(issue: v.BaseIssue<unknown>): ArgumentKey[] {\n const keys: ArgumentKey[] = []\n for (const item of issue.path ?? []) {\n if (!('key' in item)) continue\n if (typeof item.key === 'string' || typeof item.key === 'number') keys.push(item.key)\n }\n return keys\n}\n\n/** `operations[0].props`: an index reads as part of its array, a name follows a dot. */\nfunction placeOf(keys: readonly ArgumentKey[]): string {\n return keys.reduce<string>((place, key) => {\n if (typeof key === 'number') return `${place}[${key}]`\n return place ? `${place}.${key}` : key\n }, '')\n}\n\n/**\n * `v.union` reports one issue for every branch, which reads as \"Expected Object but received\n * Object\". Re-check the value against each branch and keep the one that got furthest: the branch\n * whose own problems name the field the caller has to fix.\n */\nfunction branchIssues(\n schema: v.GenericSchema,\n issue: v.BaseIssue<unknown>\n): { keys: ArgumentKey[]; issue: v.BaseIssue<unknown> }[] {\n const keys = issueKeys(issue)\n if (issue.type !== 'union') return [{ keys, issue }]\n const union = schemaAtPath(schema, keys)\n const options = union ? schemaParts(union).options : undefined\n if (!options || options.length === 0) return [{ keys, issue }]\n let best: readonly v.BaseIssue<unknown>[] | null = null\n for (const option of options) {\n const parsed = v.safeParse(option as v.GenericSchema, issue.input)\n if (parsed.success) continue\n if (!best || parsed.issues.length < best.length) best = parsed.issues\n }\n if (!best || best.length === 0) return [{ keys, issue }]\n return best.map((nested) => ({ keys: [...keys, ...issueKeys(nested)], issue: nested }))\n}\n\nfunction schemaAtPath(root: v.GenericSchema, keys: readonly ArgumentKey[]): v.GenericSchema | null {\n let current = unwrappedSchema(root)\n for (const key of keys) {\n const parts = schemaParts(current)\n const name = String(key)\n const next = parts.entries && name in parts.entries ? parts.entries[name] : parts.item\n if (!next) return null\n current = unwrappedSchema(next)\n }\n return current\n}\n\nfunction formatToolArgIssue(\n schema: v.GenericSchema,\n keys: readonly ArgumentKey[],\n issue: v.BaseIssue<unknown>\n): string {\n const key = keys.at(-1)\n if (key !== undefined && (issue.type === 'object' || issue.type === 'strict_object')) {\n if (issue.expected === 'never') {\n const parent = schemaAtPath(schema, keys.slice(0, -1))\n const accepted = parent ? Object.keys(schemaParts(parent).entries ?? {}) : []\n return accepted.length > 0\n ? `Unknown argument \"${key}\". Accepted: ${accepted.join(', ')}`\n : `Unknown argument \"${key}\"`\n }\n if (issue.received === 'undefined') return `Missing required argument \"${key}\"`\n }\n if (issue.type === 'picklist' && key !== undefined) {\n const resolved = schemaAtPath(schema, keys)\n const options = resolved ? schemaParts(resolved).options : undefined\n if (options && options.length > 0) {\n const accepted = options.map((option) => JSON.stringify(option)).join(', ')\n return `Invalid value ${issue.received} for argument \"${key}\". Accepted: ${accepted}`\n }\n }\n return issue.message\n}\n\nexport function toolChangesDocument(def: Pick<ToolDef, 'execution'>): boolean {\n return def.execution.mutation === 'properties' || def.execution.mutation === 'document'\n}\n\nexport function isToolExposed(def: Pick<ToolDef, 'exposure'>, target: ToolInterface): boolean {\n return def.exposure[target] !== false\n}\n\nexport function isAtomicTool(def: ToolDef): boolean {\n return def.execution.kind === 'sync' && def.execution.mutation === 'properties'\n}\n\nexport class NodeNotFoundError extends Error {\n constructor(id: string) {\n super(`Node not found: ${id}`)\n this.name = 'NodeNotFoundError'\n }\n}\n\nexport function requireNode(figma: FigmaAPI, id: string): ReturnType<FigmaAPI['getNodeById']> {\n const node = figma.getNodeById(id)\n if (!node) throw new NodeNotFoundError(id)\n return node\n}\n\nexport function requireNodes(figma: FigmaAPI, ids: ReadonlyArray<string>): FigmaNodeProxy[] | null {\n const nodes: FigmaNodeProxy[] = []\n for (const id of ids) {\n const node = figma.getNodeById(id)\n if (!node) return null\n nodes.push(node)\n }\n return nodes\n}\n\n/** A tool's answer when the operation it wraps throws: the error's message for the caller. */\nexport function toolFailure(error: unknown): { error: string } {\n return { error: error instanceof Error ? error.message : String(error) }\n}\n\nexport function nodeNotFound(id: string): { error: string } {\n return { error: `Node \"${id}\" not found` }\n}\n\nexport function getRawNodeOrError(\n figma: FigmaAPI,\n id: string\n): { node: SceneNode } | { error: string } {\n const node = figma.graph.getNode(id)\n return node ? { node } : nodeNotFound(id)\n}\n\nexport function nodeToResult(node: FigmaNodeProxy, maxDepth?: number): Record<string, unknown> {\n return node.toJSON(maxDepth)\n}\n\nexport function nodeSummary(node: FigmaNodeProxy): { id: string; name: string; type: string } {\n return { id: node.id, name: node.name, type: node.type }\n}\n\n/**\n * A tool colour, refusing text that would otherwise land as black: `set_fill { color: \"#GGG\" }`\n * used to paint black and report success. Read through `tryParseColor`, since a published schema\n * cannot express what the parser accepts.\n */\nexport function parseToolColor(value: string): Color | { error: string } {\n return (\n tryParseColor(value) ?? {\n error: `\"${value}\" is not a color; use a hex value, a color name, or a color function`\n }\n )\n}\n\n/**\n * A colour the caller may leave out. Missing stays missing; text that is not a colour is the\n * same refusal `parseToolColor` gives, so each tool does not repeat that check.\n */\nexport function parseOptionalToolColor(\n value: string | undefined\n): { color: Color | undefined } | { error: string } {\n if (value === undefined) return { color: undefined }\n const parsed = parseToolColor(value)\n if ('error' in parsed) return parsed\n return { color: parsed }\n}\n\nexport const nodeIdInputSchema = v.pipe(v.string(), v.description('Node ID'))\nexport const nodeInputSchema = v.strictObject({ id: nodeIdInputSchema })\nexport const nodeComparisonInputSchema = v.strictObject({\n from: v.pipe(v.string(), v.description('Source node ID')),\n to: v.pipe(v.string(), v.description('Target node ID'))\n})\n\nexport function nodeTraversalInput(depthDescription: string) {\n return v.strictObject({\n id: nodeIdInputSchema,\n depth: v.optional(toolNumber(v.pipe(v.number(), v.description(depthDescription))))\n })\n}\nexport const positionInputs = {\n x: toolNumber(v.pipe(v.number(), v.description('X position in the parent, or on the page'))),\n y: toolNumber(v.pipe(v.number(), v.description('Y position in the parent, or on the page')))\n}\n\n/** Reuse a native number schema for both numeric and numeric-string agent inputs. */\nexport function toolNumber(schema: v.GenericSchema<number, number> = v.number()) {\n // JSON Schema numbers are finite. Express that with representable bounds as well as at runtime.\n const finite = v.pipe(schema, v.minValue(-Number.MAX_VALUE), v.maxValue(Number.MAX_VALUE))\n return v.union([\n finite,\n v.pipe(\n v.string(),\n v.regex(/\\S/, 'Expected a nonblank numeric string'),\n v.description(v.getDescription(schema) ?? 'Numeric value'),\n v.transform(Number),\n finite\n )\n ])\n}\n"],"mappings":";;;;;;;;;AAmFA,SAAgB,WACd,KAkBS;CACT,MAAM,EAAE,UAAU;CAClB,OAAO;EACL,GAAG;EACH,UAAU,IAAI,YAAY,CAAC;EAC3B,cAAc,IAAI,gBAAgB,CAChC,oBAAoB,GAAG,IAAI,mBAAmB,eAChD;EACA,cAAc,IAAI,gBAAgB;EAClC,IAAI,UAAU;GACZ,OAAO,IAAI,UAAU,aAAa;EACpC;EACA,MAAM,UAAU,OAAO,MAAM;GAC3B,IAAI,CAAC,OAAO;GAEZ,MAAM,SAAS,EAAE,UAAU,IAAI,OAAO,IAAI;GAC1C,IAAI,CAAC,OAAO,SAAS;GACrB,KAAK,MAAM,QAAQ,MAAM,OAAO,OAAO,MAAM,GAAG,MAAM,MAAM,cAAc,IAAI;EAChF;EACA,UAAU,OAAO,MAAM,WACrB,IAAI,QAAQ,OAAO,cAAc,IAAI,MAAM,IAAI,OAAO,IAAI,GAAG,MAAM;EACrE,aAAa,IAAI,eACZ,OAAO,SAAS,IAAI,cAAc,OAAO,cAAc,IAAI,MAAM,IAAI,OAAO,IAAI,CAAC,IAClF,KAAA;CACN;AACF;;;;;;;;AASA,SAAgB,cACd,MACA,QACA,MACkB;CAClB,MAAM,SAAS,EAAE,UAAU,QAAQ,IAAI;CACvC,IAAI,OAAO,SAAS,OAAO,OAAO;CAClC,MAAM,IAAI,MAAM,wBAAwB,MAAM,QAAQ,OAAO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3F,GAAG,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,0CAA0C,CAAC,CAAC;AAC7F;;AAGA,SAAgB,WAAW,SAA0C,EAAE,OAAO,GAAG;CAE/E,MAAM,SAAS,EAAE,KAAK,QAAQ,EAAE,SAAS,CAAC,OAAO,SAAS,GAAG,EAAE,SAAS,OAAO,SAAS,CAAC;CACzF,OAAO,EAAE,MAAM,CACb,QACA,EAAE,KACA,EAAE,OAAO,GACT,EAAE,MAAM,MAAM,oCAAoC,GAClD,EAAE,YAAY,EAAE,eAAe,MAAM,KAAK,eAAe,GACzD,EAAE,UAAU,MAAM,GAClB,MACF,CACF,CAAC;AACH"}
1
+ {"version":3,"file":"schema.js","names":[],"sources":["../../src/tools/schema.ts"],"sourcesContent":["/**\n * Tool definition schema.\n *\n * Native Valibot inputs and execution capabilities are owned by each tool.\n * Adapters consume these contracts rather than maintaining transport-specific schemas.\n */\n\nimport * as v from 'valibot'\n\nimport type { DocumentColorSpace, SceneNode } from '@pairdraw/scene-graph'\nimport { tryParseColor } from '@pairdraw/scene-graph/color'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport type { FigmaAPI, FigmaNodeProxy } from '#core/figma-api'\nimport type { FigmaFontNameInput } from '#core/figma-api/fonts/names'\n\nexport type ToolCapability =\n | 'document:read'\n | 'document:write'\n | 'filesystem:read'\n | 'filesystem:write'\n | 'network:access'\n | 'code:execute'\n | 'settings:read'\n | 'settings:write'\n\nexport type ToolExecution =\n | { kind: 'sync'; mutation: 'none' | 'view' | 'properties' | 'document' }\n | {\n kind: 'async'\n mutation: 'none' | 'view' | 'document'\n /**\n * The call can run for a long time even when it only reads, such as recording a video, so\n * bridges give it the deadline they give an edit.\n */\n long?: boolean\n }\n\nexport type ToolInterface = 'mcp' | 'ai' | 'webmcp'\nexport type ToolExposure = Partial<Record<ToolInterface, boolean>>\n\ninterface ToolMetadata {\n name: string\n description: string\n execution: ToolExecution\n /** Interface inclusion defaults to true; execution support and user permissions remain separate. */\n exposure: ToolExposure\n capabilities: readonly ToolCapability[]\n availability: 'default' | 'eval'\n /**\n * What a call's values come from, for the document's design memory:\n * - `imported`: outside content, such as a web page, an SVG, a photo or a library component,\n * whose colors and type are its own, so the memory warns about them rather than refusing;\n * - `copied`: the layers the call names, which it copies or converts with their values, such\n * as a clone, a group or a boolean, so values those layers already had are not new.\n * - `merged`: layers the call joins into one, which may take a paint from any of them, such as\n * flatten and boolean operations; a value is only theirs when every named layer had it.\n */\n content?: 'imported' | 'copied' | 'merged'\n}\n\nexport interface ToolDef extends ToolMetadata {\n input: v.StrictObjectSchema<v.ObjectEntries, undefined>\n /** Derived from execution metadata, never declared independently by a tool. */\n readonly mutates: boolean\n /**\n * Loads the fonts the call's text edits need, as a Figma plugin loads them before it edits\n * text; rejects when one cannot load. Every executor awaits it before `execute`, so a\n * synchronous tool still edits in one step.\n */\n loadFonts: (figma: FigmaAPI, args: Record<string, unknown>) => Promise<void>\n /** `signal` aborts a caller's cancelled request, which a long export checks while it runs. */\n execute: (figma: FigmaAPI, args: Record<string, unknown>, signal?: AbortSignal) => unknown\n /**\n * The synchronous answer of a read whose `execute` may load a page first, or `undefined`\n * when answering would load. Hosts that cannot wait refuse on `undefined` before any load.\n */\n executeSync?: (figma: FigmaAPI, args: Record<string, unknown>) => unknown\n}\n\ntype ToolDefinitionMetadata = Omit<ToolMetadata, 'exposure' | 'capabilities' | 'availability'> &\n Partial<Pick<ToolMetadata, 'exposure' | 'capabilities' | 'availability'>>\n\nexport function defineTool<P extends v.ObjectEntries, R>(\n def: ToolDefinitionMetadata & {\n input: v.StrictObjectSchema<P, undefined>\n execution: ToolExecution & (R extends PromiseLike<unknown> ? { kind: 'async' } : unknown)\n /** The fonts a call's text edits need loaded first; text edits refuse unloaded fonts. */\n fonts?: (\n figma: FigmaAPI,\n args: v.InferOutput<v.StrictObjectSchema<P, undefined>>\n ) => FigmaFontNameInput[]\n execute: (\n figma: FigmaAPI,\n args: v.InferOutput<v.StrictObjectSchema<P, undefined>>,\n signal?: AbortSignal\n ) => R\n executeSync?: (\n figma: FigmaAPI,\n args: v.InferOutput<v.StrictObjectSchema<P, undefined>>\n ) => unknown\n }\n): ToolDef {\n const { fonts } = def\n return {\n ...def,\n exposure: def.exposure ?? {},\n capabilities: def.capabilities ?? [\n toolChangesDocument(def) ? 'document:write' : 'document:read'\n ],\n availability: def.availability ?? 'default',\n get mutates() {\n return def.execution.mutation !== 'none'\n },\n async loadFonts(figma, args) {\n if (!fonts) return\n // Wrong arguments are for `execute` to report.\n const parsed = v.safeParse(def.input, args)\n if (!parsed.success) return\n for (const font of fonts(figma, parsed.output)) await figma.loadFontAsync(font)\n },\n execute: (figma, args, signal) =>\n def.execute(figma, parseToolArgs(def.name, def.input, args), signal),\n executeSync: def.executeSync\n ? (figma, args) => def.executeSync?.(figma, parseToolArgs(def.name, def.input, args))\n : undefined\n }\n}\n\n/**\n * Every tool run goes through here, so a wrong call from AI chat, the CLI, WebMCP, and MCP names\n * the tool and lists each problem with its argument. An unknown or missing argument names the\n * arguments the tool takes, and a picklist names the values it accepts, read from the schema, so\n * the caller does not have to guess. Inputs are strict objects, so a misspelled or mis-nested\n * argument fails here instead of being dropped.\n */\nexport function parseToolArgs<S extends v.GenericSchema>(\n name: string,\n schema: S,\n args: unknown\n): v.InferOutput<S> {\n const result = v.safeParse(schema, args)\n if (result.success) return result.output\n throw new Error(formatToolArgumentError(name, schema, result.issues))\n}\n\n/** One refusal for every surface: the tool, then each problem with where it is. */\nfunction formatToolArgumentError(\n name: string,\n schema: v.GenericSchema,\n issues: readonly v.BaseIssue<unknown>[]\n): string {\n const problems = issues\n .flatMap((issue) => branchIssues(schema, issue))\n .map(({ keys, issue }) => {\n const place = keys.length > 0 ? `\\n → at ${placeOf(keys)}` : ''\n return `× ${formatToolArgIssue(schema, keys, issue)}${place}`\n })\n return `Invalid arguments for ${name}:\\n${problems.join('\\n')}`\n}\n\n/** The parts of a Valibot schema this module reads to name what a call should have sent. */\ntype SchemaParts = {\n readonly entries?: v.ObjectEntries\n readonly item?: v.GenericSchema\n readonly wrapped?: v.GenericSchema\n readonly options?: readonly unknown[]\n}\n\nfunction schemaParts(schema: unknown): SchemaParts {\n return typeof schema === 'object' && schema !== null ? schema : {}\n}\n\n/** The schema a wrapper such as `optional` or `pipe` holds, down to the one with the rules. */\nfunction unwrappedSchema(schema: v.GenericSchema): v.GenericSchema {\n let current = schema\n for (;;) {\n const wrapped = schemaParts(current).wrapped\n if (!wrapped) return current\n current = wrapped\n }\n}\n\ntype ArgumentKey = string | number\n\nfunction issueKeys(issue: v.BaseIssue<unknown>): ArgumentKey[] {\n const keys: ArgumentKey[] = []\n for (const item of issue.path ?? []) {\n if (!('key' in item)) continue\n if (typeof item.key === 'string' || typeof item.key === 'number') keys.push(item.key)\n }\n return keys\n}\n\n/** `operations[0].props`: an index reads as part of its array, a name follows a dot. */\nfunction placeOf(keys: readonly ArgumentKey[]): string {\n return keys.reduce<string>((place, key) => {\n if (typeof key === 'number') return `${place}[${key}]`\n return place ? `${place}.${key}` : key\n }, '')\n}\n\n/**\n * `v.union` reports one issue for every branch, which reads as \"Expected Object but received\n * Object\". Re-check the value against each branch and keep the one that got furthest: the branch\n * whose own problems name the field the caller has to fix.\n */\nfunction branchIssues(\n schema: v.GenericSchema,\n issue: v.BaseIssue<unknown>\n): { keys: ArgumentKey[]; issue: v.BaseIssue<unknown> }[] {\n const keys = issueKeys(issue)\n if (issue.type !== 'union') return [{ keys, issue }]\n const union = schemaAtPath(schema, keys)\n const options = union ? schemaParts(union).options : undefined\n if (!options || options.length === 0) return [{ keys, issue }]\n let best: readonly v.BaseIssue<unknown>[] | null = null\n for (const option of options) {\n const parsed = v.safeParse(option as v.GenericSchema, issue.input)\n if (parsed.success) continue\n if (!best || parsed.issues.length < best.length) best = parsed.issues\n }\n if (!best || best.length === 0) return [{ keys, issue }]\n return best.map((nested) => ({ keys: [...keys, ...issueKeys(nested)], issue: nested }))\n}\n\nfunction schemaAtPath(root: v.GenericSchema, keys: readonly ArgumentKey[]): v.GenericSchema | null {\n let current = unwrappedSchema(root)\n for (const key of keys) {\n const parts = schemaParts(current)\n const name = String(key)\n const next = parts.entries && name in parts.entries ? parts.entries[name] : parts.item\n if (!next) return null\n current = unwrappedSchema(next)\n }\n return current\n}\n\nfunction formatToolArgIssue(\n schema: v.GenericSchema,\n keys: readonly ArgumentKey[],\n issue: v.BaseIssue<unknown>\n): string {\n const key = keys.at(-1)\n if (key !== undefined && (issue.type === 'object' || issue.type === 'strict_object')) {\n if (issue.expected === 'never') {\n const parent = schemaAtPath(schema, keys.slice(0, -1))\n const accepted = parent ? Object.keys(schemaParts(parent).entries ?? {}) : []\n return accepted.length > 0\n ? `Unknown argument \"${key}\". Accepted: ${accepted.join(', ')}`\n : `Unknown argument \"${key}\"`\n }\n if (issue.received === 'undefined') return `Missing required argument \"${key}\"`\n }\n if (issue.type === 'picklist' && key !== undefined) {\n const resolved = schemaAtPath(schema, keys)\n const options = resolved ? schemaParts(resolved).options : undefined\n if (options && options.length > 0) {\n const accepted = options.map((option) => JSON.stringify(option)).join(', ')\n return `Invalid value ${issue.received} for argument \"${key}\". Accepted: ${accepted}`\n }\n }\n return issue.message\n}\n\nexport function toolChangesDocument(def: Pick<ToolDef, 'execution'>): boolean {\n return def.execution.mutation === 'properties' || def.execution.mutation === 'document'\n}\n\nexport function isToolExposed(def: Pick<ToolDef, 'exposure'>, target: ToolInterface): boolean {\n return def.exposure[target] !== false\n}\n\nexport function isAtomicTool(def: ToolDef): boolean {\n return def.execution.kind === 'sync' && def.execution.mutation === 'properties'\n}\n\nexport class NodeNotFoundError extends Error {\n constructor(id: string) {\n super(`Node not found: ${id}`)\n this.name = 'NodeNotFoundError'\n }\n}\n\nexport function requireNode(figma: FigmaAPI, id: string): ReturnType<FigmaAPI['getNodeById']> {\n const node = figma.getNodeById(id)\n if (!node) throw new NodeNotFoundError(id)\n return node\n}\n\nexport function requireNodes(figma: FigmaAPI, ids: ReadonlyArray<string>): FigmaNodeProxy[] | null {\n const nodes: FigmaNodeProxy[] = []\n for (const id of ids) {\n const node = figma.getNodeById(id)\n if (!node) return null\n nodes.push(node)\n }\n return nodes\n}\n\n/** A tool's answer when the operation it wraps throws: the error's message for the caller. */\nexport function toolFailure(error: unknown): { error: string } {\n return { error: error instanceof Error ? error.message : String(error) }\n}\n\nexport function nodeNotFound(id: string): { error: string } {\n return { error: `Node \"${id}\" not found` }\n}\n\nexport function getRawNodeOrError(\n figma: FigmaAPI,\n id: string\n): { node: SceneNode } | { error: string } {\n const node = figma.graph.getNode(id)\n return node ? { node } : nodeNotFound(id)\n}\n\nexport function nodeToResult(node: FigmaNodeProxy, maxDepth?: number): Record<string, unknown> {\n return node.toJSON(maxDepth)\n}\n\nexport function nodeSummary(node: FigmaNodeProxy): { id: string; name: string; type: string } {\n return { id: node.id, name: node.name, type: node.type }\n}\n\n/**\n * A tool colour, refusing text that would otherwise land as black: `set_fill { color: \"#GGG\" }`\n * used to paint black and report success. Read through `tryParseColor`, since a published schema\n * cannot express what the parser accepts.\n */\nexport function parseToolColor(\n value: string,\n profile: DocumentColorSpace = 'srgb'\n): Color | { error: string } {\n return (\n tryParseColor(value, profile) ?? {\n error: `\"${value}\" is not a color; use a hex value, a color name, or a color function`\n }\n )\n}\n\n/**\n * A colour the caller may leave out. Missing stays missing; text that is not a colour is the\n * same refusal `parseToolColor` gives, so each tool does not repeat that check.\n */\nexport function parseOptionalToolColor(\n value: string | undefined,\n profile: DocumentColorSpace = 'srgb'\n): { color: Color | undefined } | { error: string } {\n if (value === undefined) return { color: undefined }\n const parsed = parseToolColor(value, profile)\n if ('error' in parsed) return parsed\n return { color: parsed }\n}\n\nexport const nodeIdInputSchema = v.pipe(v.string(), v.description('Node ID'))\nexport const nodeInputSchema = v.strictObject({ id: nodeIdInputSchema })\nexport const nodeComparisonInputSchema = v.strictObject({\n from: v.pipe(v.string(), v.description('Source node ID')),\n to: v.pipe(v.string(), v.description('Target node ID'))\n})\n\nexport function nodeTraversalInput(depthDescription: string) {\n return v.strictObject({\n id: nodeIdInputSchema,\n depth: v.optional(toolNumber(v.pipe(v.number(), v.description(depthDescription))))\n })\n}\nexport const positionInputs = {\n x: toolNumber(v.pipe(v.number(), v.description('X position in the parent, or on the page'))),\n y: toolNumber(v.pipe(v.number(), v.description('Y position in the parent, or on the page')))\n}\n\n/** Reuse a native number schema for both numeric and numeric-string agent inputs. */\nexport function toolNumber(schema: v.GenericSchema<number, number> = v.number()) {\n // JSON Schema numbers are finite. Express that with representable bounds as well as at runtime.\n const finite = v.pipe(schema, v.minValue(-Number.MAX_VALUE), v.maxValue(Number.MAX_VALUE))\n return v.union([\n finite,\n v.pipe(\n v.string(),\n v.regex(/\\S/, 'Expected a nonblank numeric string'),\n v.description(v.getDescription(schema) ?? 'Numeric value'),\n v.transform(Number),\n finite\n )\n ])\n}\n\n/** `ids`: several node IDs in one call; the description names what they point at. */\nexport function nodeIdsField(description: string) {\n return v.optional(v.pipe(v.array(v.string()), v.minLength(1), v.description(description)))\n}\n"],"mappings":";;;;;;;;;AAmFA,SAAgB,WACd,KAkBS;CACT,MAAM,EAAE,UAAU;CAClB,OAAO;EACL,GAAG;EACH,UAAU,IAAI,YAAY,CAAC;EAC3B,cAAc,IAAI,gBAAgB,CAChC,oBAAoB,GAAG,IAAI,mBAAmB,eAChD;EACA,cAAc,IAAI,gBAAgB;EAClC,IAAI,UAAU;GACZ,OAAO,IAAI,UAAU,aAAa;EACpC;EACA,MAAM,UAAU,OAAO,MAAM;GAC3B,IAAI,CAAC,OAAO;GAEZ,MAAM,SAAS,EAAE,UAAU,IAAI,OAAO,IAAI;GAC1C,IAAI,CAAC,OAAO,SAAS;GACrB,KAAK,MAAM,QAAQ,MAAM,OAAO,OAAO,MAAM,GAAG,MAAM,MAAM,cAAc,IAAI;EAChF;EACA,UAAU,OAAO,MAAM,WACrB,IAAI,QAAQ,OAAO,cAAc,IAAI,MAAM,IAAI,OAAO,IAAI,GAAG,MAAM;EACr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E,YAAY,gBAAgB,CAAC;AACxD,CAAC;AAED,SAAgB,mBAAmB,kBAA0B;CAC3D,OAAO,EAAE,aAAa;EACpB,IAAI;EACJ,OAAO,EAAE,SAAS,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,gBAAgB,CAAC,CAAC,CAAC;CACnF,CAAC;AACH;AACA,MAAa,iBAAiB;CAC5B,GAAG,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,0CAA0C,CAAC,CAAC;CAC3F,GAAG,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,0CAA0C,CAAC,CAAC;AAC7F;;AAGA,SAAgB,WAAW,SAA0C,EAAE,OAAO,GAAG;CAE/E,MAAM,SAAS,EAAE,KAAK,QAAQ,EAAE,SAAS,CAAC,OAAO,SAAS,GAAG,EAAE,SAAS,OAAO,SAAS,CAAC;CACzF,OAAO,EAAE,MAAM,CACb,QACA,EAAE,KACA,EAAE,OAAO,GACT,EAAE,MAAM,MAAM,oCAAoC,GAClD,EAAE,YAAY,EAAE,eAAe,MAAM,KAAK,eAAe,GACzD,EAAE,UAAU,MAAM,GAClB,MACF,CACF,CAAC;AACH;;AAGA,SAAgB,aAAa,aAAqB;CAChD,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,GAAG,EAAE,UAAU,CAAC,GAAG,EAAE,YAAY,WAAW,CAAC,CAAC;AAC3F"}
@@ -1 +1 @@
1
- {"version":3,"file":"host.d.ts","names":[],"sources":["../../../src/tools/script/host.ts"],"mappings":";;;;;;UAKiB;;EAEf,OAAO;IACL;IACA;IACA;IACA;MACE;IAAU;IAAY;IAAa;;;EAEvC,UAAU,YAAY;;EAEtB,IAAI,aAAa;IAAU;IAAY;IAAa;IAAgB;;;;iBAMtD,uBAAuB,eAAe,MAAM;iBAO5C,kBAAkB,gBAAgB"}
1
+ {"version":3,"file":"host.d.ts","names":[],"sources":["../../../src/tools/script/host.ts"],"mappings":";;;;;;UAOiB;;EAEf,OAAO;IACL;IACA;IACA;IACA;MACE;IAAU;IAAY;IAAa;;;EAEvC,UAAU,YAAY;;EAEtB,IAAI,aAAa;IAAU;IAAY;IAAa;IAAgB;;;;iBAMtD,uBAAuB,eAAe,MAAM;iBAQ5C,kBAAkB,gBAAgB"}
@@ -1,14 +1,16 @@
1
+ import { underlyingGraph } from "../../figma-api/graph-ref.js";
1
2
  //#region src/tools/script/host.ts
2
3
  const hosts = /* @__PURE__ */ new WeakMap();
3
4
  /** Lets the `script` tool run for the documents of `owner`, a document's graph. */
4
5
  function registerScriptToolHost(owner, host) {
5
- hosts.set(owner, host);
6
+ const target = underlyingGraph(owner);
7
+ hosts.set(target, host);
6
8
  return () => {
7
- if (hosts.get(owner) === host) hosts.delete(owner);
9
+ if (hosts.get(target) === host) hosts.delete(target);
8
10
  };
9
11
  }
10
12
  function getScriptToolHost(owner) {
11
- return hosts.get(owner);
13
+ return hosts.get(underlyingGraph(owner));
12
14
  }
13
15
  //#endregion
14
16
  export { getScriptToolHost, registerScriptToolHost };
@@ -1 +1 @@
1
- {"version":3,"file":"host.js","names":[],"sources":["../../../src/tools/script/host.ts"],"sourcesContent":["/**\n * What the `script` tool needs from the host: the sandbox and the node that carries its program\n * live in the app, so the app registers the runner for the documents it shows. A headless host\n * without a sandbox registers nothing, and the tool reports that it is unavailable.\n */\nexport interface ScriptToolHost {\n /** Places a code layer, writes its program, and runs it once there. */\n create(placement: {\n source: string\n x?: number\n y?: number\n parentId?: string\n }): Promise<{ id: string; ok: boolean; error?: string }>\n /** Replaces the program of an existing code layer, as an undo step. */\n setSource(id: string, source: string): void\n /** Runs the code layer again without editing it. */\n run(id: string): Promise<{ id: string; ok: boolean; error?: string; layers?: number }>\n}\n\nconst hosts = new WeakMap<object, ScriptToolHost>()\n\n/** Lets the `script` tool run for the documents of `owner`, a document's graph. */\nexport function registerScriptToolHost(owner: object, host: ScriptToolHost): () => void {\n hosts.set(owner, host)\n return () => {\n if (hosts.get(owner) === host) hosts.delete(owner)\n }\n}\n\nexport function getScriptToolHost(owner: object): ScriptToolHost | undefined {\n return hosts.get(owner)\n}\n"],"mappings":";AAmBA,MAAM,wBAAQ,IAAI,QAAgC;;AAGlD,SAAgB,uBAAuB,OAAe,MAAkC;CACtF,MAAM,IAAI,OAAO,IAAI;CACrB,aAAa;EACX,IAAI,MAAM,IAAI,KAAK,MAAM,MAAM,MAAM,OAAO,KAAK;CACnD;AACF;AAEA,SAAgB,kBAAkB,OAA2C;CAC3E,OAAO,MAAM,IAAI,KAAK;AACxB"}
1
+ {"version":3,"file":"host.js","names":[],"sources":["../../../src/tools/script/host.ts"],"sourcesContent":["import { underlyingGraph } from '#core/figma-api/graph-ref'\n\n/**\n * What the `script` tool needs from the host: the sandbox and the node that carries its program\n * live in the app, so the app registers the runner for the documents it shows. A headless host\n * without a sandbox registers nothing, and the tool reports that it is unavailable.\n */\nexport interface ScriptToolHost {\n /** Places a code layer, writes its program, and runs it once there. */\n create(placement: {\n source: string\n x?: number\n y?: number\n parentId?: string\n }): Promise<{ id: string; ok: boolean; error?: string }>\n /** Replaces the program of an existing code layer, as an undo step. */\n setSource(id: string, source: string): void\n /** Runs the code layer again without editing it. */\n run(id: string): Promise<{ id: string; ok: boolean; error?: string; layers?: number }>\n}\n\nconst hosts = new WeakMap<object, ScriptToolHost>()\n\n/** Lets the `script` tool run for the documents of `owner`, a document's graph. */\nexport function registerScriptToolHost(owner: object, host: ScriptToolHost): () => void {\n const target = underlyingGraph(owner)\n hosts.set(target, host)\n return () => {\n if (hosts.get(target) === host) hosts.delete(target)\n }\n}\n\nexport function getScriptToolHost(owner: object): ScriptToolHost | undefined {\n return hosts.get(underlyingGraph(owner))\n}\n"],"mappings":";;AAqBA,MAAM,wBAAQ,IAAI,QAAgC;;AAGlD,SAAgB,uBAAuB,OAAe,MAAkC;CACtF,MAAM,SAAS,gBAAgB,KAAK;CACpC,MAAM,IAAI,QAAQ,IAAI;CACtB,aAAa;EACX,IAAI,MAAM,IAAI,MAAM,MAAM,MAAM,MAAM,OAAO,MAAM;CACrD;AACF;AAEA,SAAgB,kBAAkB,OAA2C;CAC3E,OAAO,MAAM,IAAI,gBAAgB,KAAK,CAAC;AACzC"}
@@ -10,7 +10,7 @@ const listCollections = defineTool({
10
10
  },
11
11
  input: v.strictObject({}),
12
12
  execute: (figma) => {
13
- const collections = [...figma.graph.variableCollections.values()];
13
+ const collections = figma.graph.getLiveCollections();
14
14
  return {
15
15
  count: collections.length,
16
16
  collections
@@ -1 +1 @@
1
- {"version":3,"file":"collections.js","names":[],"sources":["../../../src/tools/variables/collections.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport { defineTool } from '#core/tools/schema'\n\nexport const listCollections = defineTool({\n name: 'list_collections',\n description: 'List all variable collections.',\n execution: { kind: 'sync', mutation: 'none' },\n input: v.strictObject({}),\n execute: (figma) => {\n const collections = [...figma.graph.variableCollections.values()]\n return { count: collections.length, collections }\n }\n})\n\nexport const getCollection = defineTool({\n name: 'get_collection',\n description: 'Get a variable collection by ID.',\n execution: { kind: 'sync', mutation: 'none' },\n exposure: { webmcp: false },\n input: v.strictObject({\n id: v.pipe(v.string(), v.description('Collection ID'))\n }),\n execute: (figma, { id }) => {\n const collection = figma.graph.variableCollections.get(id)\n if (!collection) return { error: `Collection \"${id}\" not found` }\n return {\n ...collection,\n activeModeId: figma.graph.getActiveModeId(id)\n }\n }\n})\n\nexport const createCollection = defineTool({\n name: 'create_collection',\n\n description: 'Create a new variable collection.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n name: v.pipe(v.string(), v.description('Collection name'))\n }),\n execute: (figma, { name }) => {\n return figma.graph.variableCollections.get(figma.variables.createVariableCollection(name).id)\n }\n})\n\nexport const deleteCollection = defineTool({\n name: 'delete_collection',\n\n description: 'Delete a variable collection and all its variables.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n id: v.pipe(v.string(), v.description('Collection ID'))\n }),\n execute: (figma, { id }) => {\n const collection = figma.variables.getVariableCollectionById(id)\n if (!collection) return { error: `Collection \"${id}\" not found` }\n collection.remove()\n return { deleted: id }\n }\n})\n"],"mappings":";;;AAIA,MAAa,kBAAkB,WAAW;CACxC,MAAM;CACN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAO;CAC5C,OAAO,EAAE,aAAa,CAAC,CAAC;CACxB,UAAU,UAAU;EAClB,MAAM,cAAc,CAAC,GAAG,MAAM,MAAM,oBAAoB,OAAO,CAAC;EAChE,OAAO;GAAE,OAAO,YAAY;GAAQ;EAAY;CAClD;AACF,CAAC;AAED,MAAa,gBAAgB,WAAW;CACtC,MAAM;CACN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAO;CAC5C,UAAU,EAAE,QAAQ,MAAM;CAC1B,OAAO,EAAE,aAAa,EACpB,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,eAAe,CAAC,EACvD,CAAC;CACD,UAAU,OAAO,EAAE,SAAS;EAC1B,MAAM,aAAa,MAAM,MAAM,oBAAoB,IAAI,EAAE;EACzD,IAAI,CAAC,YAAY,OAAO,EAAE,OAAO,eAAe,GAAG,aAAa;EAChE,OAAO;GACL,GAAG;GACH,cAAc,MAAM,MAAM,gBAAgB,EAAE;EAC9C;CACF;AACF,CAAC;AAED,MAAa,mBAAmB,WAAW;CACzC,MAAM;CAEN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAW;CAChD,OAAO,EAAE,aAAa,EACpB,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,iBAAiB,CAAC,EAC3D,CAAC;CACD,UAAU,OAAO,EAAE,WAAW;EAC5B,OAAO,MAAM,MAAM,oBAAoB,IAAI,MAAM,UAAU,yBAAyB,IAAI,CAAC,CAAC,EAAE;CAC9F;AACF,CAAC;AAED,MAAa,mBAAmB,WAAW;CACzC,MAAM;CAEN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAW;CAChD,OAAO,EAAE,aAAa,EACpB,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,eAAe,CAAC,EACvD,CAAC;CACD,UAAU,OAAO,EAAE,SAAS;EAC1B,MAAM,aAAa,MAAM,UAAU,0BAA0B,EAAE;EAC/D,IAAI,CAAC,YAAY,OAAO,EAAE,OAAO,eAAe,GAAG,aAAa;EAChE,WAAW,OAAO;EAClB,OAAO,EAAE,SAAS,GAAG;CACvB;AACF,CAAC"}
1
+ {"version":3,"file":"collections.js","names":[],"sources":["../../../src/tools/variables/collections.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport { defineTool } from '#core/tools/schema'\n\nexport const listCollections = defineTool({\n name: 'list_collections',\n description: 'List all variable collections.',\n execution: { kind: 'sync', mutation: 'none' },\n input: v.strictObject({}),\n execute: (figma) => {\n const collections = figma.graph.getLiveCollections()\n return { count: collections.length, collections }\n }\n})\n\nexport const getCollection = defineTool({\n name: 'get_collection',\n description: 'Get a variable collection by ID.',\n execution: { kind: 'sync', mutation: 'none' },\n exposure: { webmcp: false },\n input: v.strictObject({\n id: v.pipe(v.string(), v.description('Collection ID'))\n }),\n execute: (figma, { id }) => {\n const collection = figma.graph.variableCollections.get(id)\n if (!collection) return { error: `Collection \"${id}\" not found` }\n return {\n ...collection,\n activeModeId: figma.graph.getActiveModeId(id)\n }\n }\n})\n\nexport const createCollection = defineTool({\n name: 'create_collection',\n\n description: 'Create a new variable collection.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n name: v.pipe(v.string(), v.description('Collection name'))\n }),\n execute: (figma, { name }) => {\n return figma.graph.variableCollections.get(figma.variables.createVariableCollection(name).id)\n }\n})\n\nexport const deleteCollection = defineTool({\n name: 'delete_collection',\n\n description: 'Delete a variable collection and all its variables.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n id: v.pipe(v.string(), v.description('Collection ID'))\n }),\n execute: (figma, { id }) => {\n const collection = figma.variables.getVariableCollectionById(id)\n if (!collection) return { error: `Collection \"${id}\" not found` }\n collection.remove()\n return { deleted: id }\n }\n})\n"],"mappings":";;;AAIA,MAAa,kBAAkB,WAAW;CACxC,MAAM;CACN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAO;CAC5C,OAAO,EAAE,aAAa,CAAC,CAAC;CACxB,UAAU,UAAU;EAClB,MAAM,cAAc,MAAM,MAAM,mBAAmB;EACnD,OAAO;GAAE,OAAO,YAAY;GAAQ;EAAY;CAClD;AACF,CAAC;AAED,MAAa,gBAAgB,WAAW;CACtC,MAAM;CACN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAO;CAC5C,UAAU,EAAE,QAAQ,MAAM;CAC1B,OAAO,EAAE,aAAa,EACpB,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,eAAe,CAAC,EACvD,CAAC;CACD,UAAU,OAAO,EAAE,SAAS;EAC1B,MAAM,aAAa,MAAM,MAAM,oBAAoB,IAAI,EAAE;EACzD,IAAI,CAAC,YAAY,OAAO,EAAE,OAAO,eAAe,GAAG,aAAa;EAChE,OAAO;GACL,GAAG;GACH,cAAc,MAAM,MAAM,gBAAgB,EAAE;EAC9C;CACF;AACF,CAAC;AAED,MAAa,mBAAmB,WAAW;CACzC,MAAM;CAEN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAW;CAChD,OAAO,EAAE,aAAa,EACpB,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,iBAAiB,CAAC,EAC3D,CAAC;CACD,UAAU,OAAO,EAAE,WAAW;EAC5B,OAAO,MAAM,MAAM,oBAAoB,IAAI,MAAM,UAAU,yBAAyB,IAAI,CAAC,CAAC,EAAE;CAC9F;AACF,CAAC;AAED,MAAa,mBAAmB,WAAW;CACzC,MAAM;CAEN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAW;CAChD,OAAO,EAAE,aAAa,EACpB,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,eAAe,CAAC,EACvD,CAAC;CACD,UAAU,OAAO,EAAE,SAAS;EAC1B,MAAM,aAAa,MAAM,UAAU,0BAA0B,EAAE;EAC/D,IAAI,CAAC,YAAY,OAAO,EAAE,OAAO,eAAe,GAAG,aAAa;EAChE,WAAW,OAAO;EAClB,OAAO,EAAE,SAAS,GAAG;CACvB;AACF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"values.d.ts","names":[],"sources":["../../../src/tools/variables/values.ts"],"mappings":";;cAuBa,gBAAA;cAgCA,aAAA;cAqBA,gBAAA"}
1
+ {"version":3,"file":"values.d.ts","names":[],"sources":["../../../src/tools/variables/values.ts"],"mappings":";;cA2Ba,gBAAA;cAmCA,aAAA;cAyBA,gBAAA"}
@@ -6,8 +6,8 @@ import * as v from "valibot";
6
6
  function figmaValue(value) {
7
7
  return typeof value === "object" ? { ...value } : value;
8
8
  }
9
- function parseVariableValue(type, value) {
10
- if (type === "COLOR") return tryParseColor(value);
9
+ function parseVariableValue(type, value, profile) {
10
+ if (type === "COLOR") return tryParseColor(value, profile);
11
11
  if (type === "FLOAT") return Number(value);
12
12
  if (type === "BOOLEAN") return value === "true";
13
13
  return value;
@@ -32,7 +32,7 @@ const createVariable = defineTool({
32
32
  }),
33
33
  execute: (figma, args) => {
34
34
  const type = args.type;
35
- const value = args.value === void 0 ? void 0 : parseVariableValue(type, args.value);
35
+ const value = args.value === void 0 ? void 0 : parseVariableValue(type, args.value, figma.graph.documentColorSpace);
36
36
  if (value === null) return { error: `"${args.value}" is not a ${type} value` };
37
37
  if (typeof value === "number" && !Number.isFinite(value)) return { error: `"${args.value}" is not a number` };
38
38
  const variable = figma.variables.createVariable(args.name, args.collection_id, type);
@@ -55,7 +55,7 @@ const setVariable = defineTool({
55
55
  execute: (figma, args) => {
56
56
  const variable = figma.variables.getVariableById(args.id);
57
57
  if (!variable) return { error: `Variable "${args.id}" not found` };
58
- const parsedValue = parseVariableValue(variable.resolvedType, args.value);
58
+ const parsedValue = parseVariableValue(variable.resolvedType, args.value, figma.graph.documentColorSpace);
59
59
  if (parsedValue === null) return { error: `"${args.value}" is not a ${variable.resolvedType} value` };
60
60
  variable.setValueForMode(args.mode, figmaValue(parsedValue));
61
61
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"values.js","names":[],"sources":["../../../src/tools/variables/values.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport type { VariableType } from '@pairdraw/scene-graph'\nimport { tryParseColor } from '@pairdraw/scene-graph/color'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport type { FigmaVariableValue } from '#core/figma-api'\nimport { defineTool } from '#core/tools/schema'\n\n/** A parsed value as `setValueForMode` takes it; a colour gets a copy of its own. */\nfunction figmaValue(value: ToolValue): FigmaVariableValue {\n return typeof value === 'object' ? { ...value } : value\n}\n\ntype ToolValue = Color | number | string | boolean\n\nfunction parseVariableValue(type: VariableType, value: string): ToolValue | null {\n if (type === 'COLOR') return tryParseColor(value)\n if (type === 'FLOAT') return Number(value)\n if (type === 'BOOLEAN') return value === 'true'\n return value\n}\n\nexport const createVariable = defineTool({\n name: 'create_variable',\n\n description: 'Create a new variable in a collection.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n name: v.pipe(v.string(), v.description('Variable name')),\n type: v.pipe(\n v.picklist(['COLOR', 'FLOAT', 'STRING', 'BOOLEAN']),\n v.description('Variable type')\n ),\n collection_id: v.pipe(v.string(), v.description('Collection ID')),\n value: v.optional(\n v.pipe(v.string(), v.description('Initial value (hex for COLOR, number for FLOAT, etc.)'))\n )\n }),\n execute: (figma, args) => {\n const type = args.type\n // The value is checked first, so a value the variable cannot hold creates nothing.\n const value = args.value === undefined ? undefined : parseVariableValue(type, args.value)\n if (value === null) return { error: `\"${args.value}\" is not a ${type} value` }\n if (typeof value === 'number' && !Number.isFinite(value))\n return { error: `\"${args.value}\" is not a number` }\n const variable = figma.variables.createVariable(args.name, args.collection_id, type)\n if (value !== undefined) {\n for (const modeId of Object.keys(variable.valuesByMode))\n variable.setValueForMode(modeId, figmaValue(value))\n }\n return figma.graph.variables.get(variable.id)\n }\n})\n\nexport const setVariable = defineTool({\n name: 'set_variable',\n\n description: 'Set the value of a variable for a specific mode.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: v.pipe(v.string(), v.description('Variable ID')),\n mode: v.pipe(v.string(), v.description('Mode ID')),\n value: v.pipe(v.string(), v.description('Value (hex for COLOR, number for FLOAT, etc.)'))\n }),\n execute: (figma, args) => {\n const variable = figma.variables.getVariableById(args.id)\n if (!variable) return { error: `Variable \"${args.id}\" not found` }\n const parsedValue = parseVariableValue(variable.resolvedType, args.value)\n if (parsedValue === null)\n return { error: `\"${args.value}\" is not a ${variable.resolvedType} value` }\n variable.setValueForMode(args.mode, figmaValue(parsedValue))\n return { id: args.id, mode: args.mode, value: parsedValue }\n }\n})\n\nexport const deleteVariable = defineTool({\n name: 'delete_variable',\n\n description: 'Delete a variable.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n id: v.pipe(v.string(), v.description('Variable ID'))\n }),\n execute: (figma, { id }) => {\n const variable = figma.variables.getVariableById(id)\n if (!variable) return { error: `Variable \"${id}\" not found` }\n variable.remove()\n return { deleted: id }\n }\n})\n"],"mappings":";;;;;AAUA,SAAS,WAAW,OAAsC;CACxD,OAAO,OAAO,UAAU,WAAW,EAAE,GAAG,MAAM,IAAI;AACpD;AAIA,SAAS,mBAAmB,MAAoB,OAAiC;CAC/E,IAAI,SAAS,SAAS,OAAO,cAAc,KAAK;CAChD,IAAI,SAAS,SAAS,OAAO,OAAO,KAAK;CACzC,IAAI,SAAS,WAAW,OAAO,UAAU;CACzC,OAAO;AACT;AAEA,MAAa,iBAAiB,WAAW;CACvC,MAAM;CAEN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAW;CAChD,OAAO,EAAE,aAAa;EAC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OAAO,SAAS;EACxB,MAAM,WAAW,MAAM,UAAU,gBAAgB,KAAK,EAAE;EACxD,IAAI,CAAC,UAAU,OAAO,EAAE,OAAO,aAAa,KAAK,GAAG,aAAa;EACjE,MAAM,cAAc,mBAAmB,SAAS,cAAc,KAAK,KAAK;EACxE,IAAI,gBAAgB,MAClB,OAAO,EAAE,OAAO,IAAI,KAAK,MAAM,aAAa,SAAS,aAAa,QAAQ;EAC5E,SAAS,gBAAgB,KAAK,MAAM,WAAW,WAAW,CAAC;EAC3D,OAAO;GAAE,IAAI,KAAK;GAAI,MAAM,KAAK;GAAM,OAAO;EAAY;CAC5D;AACF,CAAC;AAED,MAAa,iBAAiB,WAAW;CACvC,MAAM;CAEN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAW;CAChD,OAAO,EAAE,aAAa,EACpB,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,aAAa,CAAC,EACrD,CAAC;CACD,UAAU,OAAO,EAAE,SAAS;EAC1B,MAAM,WAAW,MAAM,UAAU,gBAAgB,EAAE;EACnD,IAAI,CAAC,UAAU,OAAO,EAAE,OAAO,aAAa,GAAG,aAAa;EAC5D,SAAS,OAAO;EAChB,OAAO,EAAE,SAAS,GAAG;CACvB;AACF,CAAC"}
1
+ {"version":3,"file":"values.js","names":[],"sources":["../../../src/tools/variables/values.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport type { DocumentColorSpace, VariableType } from '@pairdraw/scene-graph'\nimport { tryParseColor } from '@pairdraw/scene-graph/color'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport type { FigmaVariableValue } from '#core/figma-api'\nimport { defineTool } from '#core/tools/schema'\n\n/** A parsed value as `setValueForMode` takes it; a colour gets a copy of its own. */\nfunction figmaValue(value: ToolValue): FigmaVariableValue {\n return typeof value === 'object' ? { ...value } : value\n}\n\ntype ToolValue = Color | number | string | boolean\n\nfunction parseVariableValue(\n type: VariableType,\n value: string,\n profile: DocumentColorSpace\n): ToolValue | null {\n if (type === 'COLOR') return tryParseColor(value, profile)\n if (type === 'FLOAT') return Number(value)\n if (type === 'BOOLEAN') return value === 'true'\n return value\n}\n\nexport const createVariable = defineTool({\n name: 'create_variable',\n\n description: 'Create a new variable in a collection.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n name: v.pipe(v.string(), v.description('Variable name')),\n type: v.pipe(\n v.picklist(['COLOR', 'FLOAT', 'STRING', 'BOOLEAN']),\n v.description('Variable type')\n ),\n collection_id: v.pipe(v.string(), v.description('Collection ID')),\n value: v.optional(\n v.pipe(v.string(), v.description('Initial value (hex for COLOR, number for FLOAT, etc.)'))\n )\n }),\n execute: (figma, args) => {\n const type = args.type\n // The value is checked first, so a value the variable cannot hold creates nothing.\n const value =\n args.value === undefined\n ? undefined\n : parseVariableValue(type, args.value, figma.graph.documentColorSpace)\n if (value === null) return { error: `\"${args.value}\" is not a ${type} value` }\n if (typeof value === 'number' && !Number.isFinite(value))\n return { error: `\"${args.value}\" is not a number` }\n const variable = figma.variables.createVariable(args.name, args.collection_id, type)\n if (value !== undefined) {\n for (const modeId of Object.keys(variable.valuesByMode))\n variable.setValueForMode(modeId, figmaValue(value))\n }\n return figma.graph.variables.get(variable.id)\n }\n})\n\nexport const setVariable = defineTool({\n name: 'set_variable',\n\n description: 'Set the value of a variable for a specific mode.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: v.pipe(v.string(), v.description('Variable ID')),\n mode: v.pipe(v.string(), v.description('Mode ID')),\n value: v.pipe(v.string(), v.description('Value (hex for COLOR, number for FLOAT, etc.)'))\n }),\n execute: (figma, args) => {\n const variable = figma.variables.getVariableById(args.id)\n if (!variable) return { error: `Variable \"${args.id}\" not found` }\n const parsedValue = parseVariableValue(\n variable.resolvedType,\n args.value,\n figma.graph.documentColorSpace\n )\n if (parsedValue === null)\n return { error: `\"${args.value}\" is not a ${variable.resolvedType} value` }\n variable.setValueForMode(args.mode, figmaValue(parsedValue))\n return { id: args.id, mode: args.mode, value: parsedValue }\n }\n})\n\nexport const deleteVariable = defineTool({\n name: 'delete_variable',\n\n description: 'Delete a variable.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n id: v.pipe(v.string(), v.description('Variable ID'))\n }),\n execute: (figma, { id }) => {\n const variable = figma.variables.getVariableById(id)\n if (!variable) return { error: `Variable \"${id}\" not found` }\n variable.remove()\n return { deleted: id }\n }\n})\n"],"mappings":";;;;;AAUA,SAAS,WAAW,OAAsC;CACxD,OAAO,OAAO,UAAU,WAAW,EAAE,GAAG,MAAM,IAAI;AACpD;AAIA,SAAS,mBACP,MACA,OACA,SACkB;CAClB,IAAI,SAAS,SAAS,OAAO,cAAc,OAAO,OAAO;CACzD,IAAI,SAAS,SAAS,OAAO,OAAO,KAAK;CACzC,IAAI,SAAS,WAAW,OAAO,UAAU;CACzC,OAAO;AACT;AAEA,MAAa,iBAAiB,WAAW;CACvC,MAAM;CAEN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAW;CAChD,OAAO,EAAE,aAAa;EACpB,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,eAAe,CAAC;EACvD,MAAM,EAAE,KACN,EAAE,SAAS;GAAC;GAAS;GAAS;GAAU;EAAS,CAAC,GAClD,EAAE,YAAY,eAAe,CAC/B;EACA,eAAe,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,eAAe,CAAC;EAChE,OAAO,EAAE,SACP,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,uDAAuD,CAAC,CAC3F;CACF,CAAC;CACD,UAAU,OAAO,SAAS;EACxB,MAAM,OAAO,KAAK;EAElB,MAAM,QACJ,KAAK,UAAU,KAAA,IACX,KAAA,IACA,mBAAmB,MAAM,KAAK,OAAO,MAAM,MAAM,kBAAkB;EACzE,IAAI,UAAU,MAAM,OAAO,EAAE,OAAO,IAAI,KAAK,MAAM,aAAa,KAAK,QAAQ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pB,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,aAAa,CAAC,EACrD,CAAC;CACD,UAAU,OAAO,EAAE,SAAS;EAC1B,MAAM,WAAW,MAAM,UAAU,gBAAgB,EAAE;EACnD,IAAI,CAAC,UAAU,OAAO,EAAE,OAAO,aAAa,GAAG,aAAa;EAC5D,SAAS,OAAO;EAChB,OAAO,EAAE,SAAS,GAAG;CACvB;AACF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"vectorize.d.ts","names":[],"sources":["../../../src/tools/vector/vectorize.ts"],"mappings":";;;UAUiB;EACf;EACA,OAAO;;;;;;UAOQ;EACf,UAAU,SAAS,wBAAwB;;;iBAM7B,wBAAwB,eAAe,YAAY;iBAOnD,mBAAmB,gBAAgB;cAItC,gBAAA"}
1
+ {"version":3,"file":"vectorize.d.ts","names":[],"sources":["../../../src/tools/vector/vectorize.ts"],"mappings":";;;UAWiB;EACf;EACA,OAAO;;;;;;UAOQ;EACf,UAAU,SAAS,wBAAwB;;;iBAM7B,wBAAwB,eAAe,YAAY;iBAQnD,mBAAmB,gBAAgB;cAItC,gBAAA"}
@@ -1,19 +1,21 @@
1
1
  import { createVectorFrameBeside } from "../../vector/vectorize/beside.js";
2
2
  import { vectorizableImageFill } from "../../vector/vectorize/image.js";
3
3
  import { svgToVectorPaths } from "../../vector/vectorize/svg/to-vectors.js";
4
+ import { underlyingGraph } from "../../figma-api/graph-ref.js";
4
5
  import { defineTool, nodeIdInputSchema, nodeNotFound, toolFailure } from "../schema.js";
5
6
  import * as v from "valibot";
6
7
  //#region src/tools/vector/vectorize.ts
7
8
  const vectorizers = /* @__PURE__ */ new WeakMap();
8
9
  /** Lets `vectorize_image` run for the documents of `owner`, a document's graph. */
9
10
  function registerImageVectorizer(owner, vectorizer) {
10
- vectorizers.set(owner, vectorizer);
11
+ const target = underlyingGraph(owner);
12
+ vectorizers.set(target, vectorizer);
11
13
  return () => {
12
- if (vectorizers.get(owner) === vectorizer) vectorizers.delete(owner);
14
+ if (vectorizers.get(target) === vectorizer) vectorizers.delete(target);
13
15
  };
14
16
  }
15
17
  function getImageVectorizer(owner) {
16
- return vectorizers.get(owner);
18
+ return vectorizers.get(underlyingGraph(owner));
17
19
  }
18
20
  const vectorizeImage = defineTool({
19
21
  name: "vectorize_image",
@@ -49,7 +51,7 @@ const vectorizeImage = defineTool({
49
51
  const vectorized = svgToVectorPaths(svg, {
50
52
  width: current.width,
51
53
  height: current.height
52
- });
54
+ }, { profile: graph.documentColorSpace });
53
55
  if (!vectorized?.paths.length) return { error: "The vectorize service returned no paths" };
54
56
  const frameId = createVectorFrameBeside(graph, id, vectorized);
55
57
  const frame = frameId ? graph.getNode(frameId) : void 0;
@@ -1 +1 @@
1
- {"version":3,"file":"vectorize.js","names":[],"sources":["../../../src/tools/vector/vectorize.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport { defineTool, nodeIdInputSchema, nodeNotFound, toolFailure } from '#core/tools/schema'\nimport {\n createVectorFrameBeside,\n svgToVectorPaths,\n vectorizableImageFill\n} from '#core/vector/vectorize'\n\n/** An image to vectorize: its hash in the document and its encoded bytes. */\nexport interface ImageVectorizeRequest {\n imageHash: string\n bytes: Uint8Array\n}\n\n/**\n * The vectorize service a host set up, such as the app with the user's provider key. It answers\n * with SVG markup, or rejects with a message the agent can pass on to the user.\n */\nexport interface ImageVectorizer {\n vectorize(request: ImageVectorizeRequest): Promise<string>\n}\n\nconst vectorizers = new WeakMap<object, ImageVectorizer>()\n\n/** Lets `vectorize_image` run for the documents of `owner`, a document's graph. */\nexport function registerImageVectorizer(owner: object, vectorizer: ImageVectorizer): () => void {\n vectorizers.set(owner, vectorizer)\n return () => {\n if (vectorizers.get(owner) === vectorizer) vectorizers.delete(owner)\n }\n}\n\nexport function getImageVectorizer(owner: object): ImageVectorizer | undefined {\n return vectorizers.get(owner)\n}\n\nexport const vectorizeImage = defineTool({\n name: 'vectorize_image',\n description:\n 'Convert the image a layer shows (its topmost visible image fill, on a layer of any kind) into editable vector paths with the vectorize service the user set up in Settings. The original layer stays; the paths go in a new frame beside it, whose id is returned. It sends the image to that service with the user’s own key and can take a few minutes, so call it only when the user asks for vectors from an image.',\n execution: { kind: 'async', mutation: 'document' },\n content: 'imported',\n capabilities: ['document:write', 'network:access'],\n input: v.strictObject({\n id: v.pipe(nodeIdInputSchema, v.description('Layer whose image fill to vectorize'))\n }),\n execute: async (figma, { id }) => {\n const graph = figma.graph\n const node = graph.getNode(id)\n if (!node) return nodeNotFound(id)\n const fill = vectorizableImageFill(node)\n if (!fill) return { error: `\"${node.name}\" has no visible image fill to vectorize` }\n const vectorizer = getImageVectorizer(graph)\n if (!vectorizer) {\n return {\n error:\n 'Vectorizing runs in the app, with the vectorize service and key set up in its Settings; it is not available here.'\n }\n }\n const bytes = graph.images.get(fill.imageHash)\n if (!bytes) return { error: `The image data of \"${node.name}\" is missing` }\n\n let svg: string\n try {\n svg = await vectorizer.vectorize({ imageHash: fill.imageHash, bytes })\n } catch (error) {\n return toolFailure(error)\n }\n\n // The service may outlast the layer or its image: another edit can change either meanwhile.\n const current = graph.getNode(id)\n if (!current || vectorizableImageFill(current)?.imageHash !== fill.imageHash) {\n return { error: `The image of \"${node.name}\" changed before vectorizing finished` }\n }\n const vectorized = svgToVectorPaths(svg, { width: current.width, height: current.height })\n if (!vectorized?.paths.length) return { error: 'The vectorize service returned no paths' }\n const frameId = createVectorFrameBeside(graph, id, vectorized)\n const frame = frameId ? graph.getNode(frameId) : undefined\n if (!frame) return { error: `Could not add the vectors beside \"${current.name}\"` }\n return {\n id: frame.id,\n name: frame.name,\n type: frame.type,\n source_id: id,\n paths: frame.childIds.length\n }\n }\n})\n"],"mappings":";;;;;;AAuBA,MAAM,8BAAc,IAAI,QAAiC;;AAGzD,SAAgB,wBAAwB,OAAe,YAAyC;CAC9F,YAAY,IAAI,OAAO,UAAU;CACjC,aAAa;EACX,IAAI,YAAY,IAAI,KAAK,MAAM,YAAY,YAAY,OAAO,KAAK;CACr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C7D,MAAM,QAAQ,UAAU,MAAM,QAAQ,OAAO,IAAI,KAAA;EACjD,IAAI,CAAC,OAAO,OAAO,EAAE,OAAO,qCAAqC,QAAQ,KAAK,GAAG;EACjF,OAAO;GACL,IAAI,MAAM;GACV,MAAM,MAAM;GACZ,MAAM,MAAM;GACZ,WAAW;GACX,OAAO,MAAM,SAAS;EACxB;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"vectorize.js","names":[],"sources":["../../../src/tools/vector/vectorize.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport { underlyingGraph } from '#core/figma-api/graph-ref'\nimport { defineTool, nodeIdInputSchema, nodeNotFound, toolFailure } from '#core/tools/schema'\nimport {\n createVectorFrameBeside,\n svgToVectorPaths,\n vectorizableImageFill\n} from '#core/vector/vectorize'\n\n/** An image to vectorize: its hash in the document and its encoded bytes. */\nexport interface ImageVectorizeRequest {\n imageHash: string\n bytes: Uint8Array\n}\n\n/**\n * The vectorize service a host set up, such as the app with the user's provider key. It answers\n * with SVG markup, or rejects with a message the agent can pass on to the user.\n */\nexport interface ImageVectorizer {\n vectorize(request: ImageVectorizeRequest): Promise<string>\n}\n\nconst vectorizers = new WeakMap<object, ImageVectorizer>()\n\n/** Lets `vectorize_image` run for the documents of `owner`, a document's graph. */\nexport function registerImageVectorizer(owner: object, vectorizer: ImageVectorizer): () => void {\n const target = underlyingGraph(owner)\n vectorizers.set(target, vectorizer)\n return () => {\n if (vectorizers.get(target) === vectorizer) vectorizers.delete(target)\n }\n}\n\nexport function getImageVectorizer(owner: object): ImageVectorizer | undefined {\n return vectorizers.get(underlyingGraph(owner))\n}\n\nexport const vectorizeImage = defineTool({\n name: 'vectorize_image',\n description:\n 'Convert the image a layer shows (its topmost visible image fill, on a layer of any kind) into editable vector paths with the vectorize service the user set up in Settings. The original layer stays; the paths go in a new frame beside it, whose id is returned. It sends the image to that service with the user’s own key and can take a few minutes, so call it only when the user asks for vectors from an image.',\n execution: { kind: 'async', mutation: 'document' },\n content: 'imported',\n capabilities: ['document:write', 'network:access'],\n input: v.strictObject({\n id: v.pipe(nodeIdInputSchema, v.description('Layer whose image fill to vectorize'))\n }),\n execute: async (figma, { id }) => {\n const graph = figma.graph\n const node = graph.getNode(id)\n if (!node) return nodeNotFound(id)\n const fill = vectorizableImageFill(node)\n if (!fill) return { error: `\"${node.name}\" has no visible image fill to vectorize` }\n const vectorizer = getImageVectorizer(graph)\n if (!vectorizer) {\n return {\n error:\n 'Vectorizing runs in the app, with the vectorize service and key set up in its Settings; it is not available here.'\n }\n }\n const bytes = graph.images.get(fill.imageHash)\n if (!bytes) return { error: `The image data of \"${node.name}\" is missing` }\n\n let svg: string\n try {\n svg = await vectorizer.vectorize({ imageHash: fill.imageHash, bytes })\n } catch (error) {\n return toolFailure(error)\n }\n\n // The service may outlast the layer or its image: another edit can change either meanwhile.\n const current = graph.getNode(id)\n if (!current || vectorizableImageFill(current)?.imageHash !== fill.imageHash) {\n return { error: `The image of \"${node.name}\" changed before vectorizing finished` }\n }\n const vectorized = svgToVectorPaths(\n svg,\n { width: current.width, height: current.height },\n { profile: graph.documentColorSpace }\n )\n if (!vectorized?.paths.length) return { error: 'The vectorize service returned no paths' }\n const frameId = createVectorFrameBeside(graph, id, vectorized)\n const frame = frameId ? graph.getNode(frameId) : undefined\n if (!frame) return { error: `Could not add the vectors beside \"${current.name}\"` }\n return {\n id: frame.id,\n name: frame.name,\n type: frame.type,\n source_id: id,\n paths: frame.childIds.length\n }\n }\n})\n"],"mappings":";;;;;;;AAwBA,MAAM,8BAAc,IAAI,QAAiC;;AAGzD,SAAgB,wBAAwB,OAAe,YAAyC;CAC9F,MAAM,SAAS,gBAAgB,KAAK;CACpC,YAAY,IAAI,QAAQ,UAAU;CAClC,aAAa;EACX,IAAI,YAAY,IAAI,MAAM,MAAM,YAAY,YAAY,OAAO,MAAM;CACvE;AACF;AAEA,SAAgB,mBAAmB,OAA4C;CAC7E,OAAO,YAAY,IAAI,gBAAgB,KAAK,CAAC;AAC/C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IAAI,KAAA;EACjD,IAAI,CAAC,OAAO,OAAO,EAAE,OAAO,qCAAqC,QAAQ,KAAK,GAAG;EACjF,OAAO;GACL,IAAI,MAAM;GACV,MAAM,MAAM;GACZ,MAAM,MAAM;GACZ,WAAW;GACX,OAAO,MAAM,SAAS;EACxB;CACF;AACF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"video-host.d.ts","names":[],"sources":["../../src/tools/video-host.ts"],"mappings":";;;;;;;iBAQgB,qBAAqB,eAAe,SAAS;iBAO7C,gBAAgB,gBAAgB"}
1
+ {"version":3,"file":"video-host.d.ts","names":[],"sources":["../../src/tools/video-host.ts"],"mappings":";;;;;;;iBASgB,qBAAqB,eAAe,SAAS;iBAQ7C,gBAAgB,gBAAgB"}
@@ -1,3 +1,4 @@
1
+ import { underlyingGraph } from "../figma-api/graph-ref.js";
1
2
  //#region src/tools/video-host.ts
2
3
  const encoders = /* @__PURE__ */ new WeakMap();
3
4
  /**
@@ -5,13 +6,14 @@ const encoders = /* @__PURE__ */ new WeakMap();
5
6
  * WebCodecs cannot encode in that host, as the CLI does with ffmpeg. The app needs none.
6
7
  */
7
8
  function registerVideoEncoder(owner, encoder) {
8
- encoders.set(owner, encoder);
9
+ const target = underlyingGraph(owner);
10
+ encoders.set(target, encoder);
9
11
  return () => {
10
- if (encoders.get(owner) === encoder) encoders.delete(owner);
12
+ if (encoders.get(target) === encoder) encoders.delete(target);
11
13
  };
12
14
  }
13
15
  function getVideoEncoder(owner) {
14
- return encoders.get(owner);
16
+ return encoders.get(underlyingGraph(owner));
15
17
  }
16
18
  //#endregion
17
19
  export { getVideoEncoder, registerVideoEncoder };
@@ -1 +1 @@
1
- {"version":3,"file":"video-host.js","names":[],"sources":["../../src/tools/video-host.ts"],"sourcesContent":["import type { VideoHostEncoder } from '#core/io/formats/video'\n\nconst encoders = new WeakMap<object, VideoHostEncoder>()\n\n/**\n * Lets `export_video` encode, for the documents of `owner` (a document's graph), the formats\n * WebCodecs cannot encode in that host, as the CLI does with ffmpeg. The app needs none.\n */\nexport function registerVideoEncoder(owner: object, encoder: VideoHostEncoder): () => void {\n encoders.set(owner, encoder)\n return () => {\n if (encoders.get(owner) === encoder) encoders.delete(owner)\n }\n}\n\nexport function getVideoEncoder(owner: object): VideoHostEncoder | undefined {\n return encoders.get(owner)\n}\n"],"mappings":";AAEA,MAAM,2BAAW,IAAI,QAAkC;;;;;AAMvD,SAAgB,qBAAqB,OAAe,SAAuC;CACzF,SAAS,IAAI,OAAO,OAAO;CAC3B,aAAa;EACX,IAAI,SAAS,IAAI,KAAK,MAAM,SAAS,SAAS,OAAO,KAAK;CAC5D;AACF;AAEA,SAAgB,gBAAgB,OAA6C;CAC3E,OAAO,SAAS,IAAI,KAAK;AAC3B"}
1
+ {"version":3,"file":"video-host.js","names":[],"sources":["../../src/tools/video-host.ts"],"sourcesContent":["import { underlyingGraph } from '#core/figma-api/graph-ref'\nimport type { VideoHostEncoder } from '#core/io/formats/video'\n\nconst encoders = new WeakMap<object, VideoHostEncoder>()\n\n/**\n * Lets `export_video` encode, for the documents of `owner` (a document's graph), the formats\n * WebCodecs cannot encode in that host, as the CLI does with ffmpeg. The app needs none.\n */\nexport function registerVideoEncoder(owner: object, encoder: VideoHostEncoder): () => void {\n const target = underlyingGraph(owner)\n encoders.set(target, encoder)\n return () => {\n if (encoders.get(target) === encoder) encoders.delete(target)\n }\n}\n\nexport function getVideoEncoder(owner: object): VideoHostEncoder | undefined {\n return encoders.get(underlyingGraph(owner))\n}\n"],"mappings":";;AAGA,MAAM,2BAAW,IAAI,QAAkC;;;;;AAMvD,SAAgB,qBAAqB,OAAe,SAAuC;CACzF,MAAM,SAAS,gBAAgB,KAAK;CACpC,SAAS,IAAI,QAAQ,OAAO;CAC5B,aAAa;EACX,IAAI,SAAS,IAAI,MAAM,MAAM,SAAS,SAAS,OAAO,MAAM;CAC9D;AACF;AAEA,SAAgB,gBAAgB,OAA6C;CAC3E,OAAO,SAAS,IAAI,gBAAgB,KAAK,CAAC;AAC5C"}
@@ -1,5 +1,5 @@
1
1
  import { SVGViewportMapping } from "./transform.js";
2
- import { Fill } from "@pairdraw/scene-graph";
2
+ import { DocumentColorSpace, Fill } from "@pairdraw/scene-graph";
3
3
  import { Color, Rect } from "@pairdraw/scene-graph/primitives";
4
4
  //#region src/vector/vectorize/svg/gradients.d.ts
5
5
  interface RawStop {
@@ -24,7 +24,7 @@ interface ParsedGradient {
24
24
  * (no hand-rolled markup parsing). Returns an empty map on parse failure so a
25
25
  * malformed SVG simply falls back to solid fills.
26
26
  */
27
- declare function parseSVGGradients(svg: string): Map<string, ParsedGradient>;
27
+ declare function parseSVGGradients(svg: string, profile?: DocumentColorSpace): Map<string, ParsedGradient>;
28
28
  /**
29
29
  * Build a scene-graph gradient Fill for `fill="url(#id)"`, with its transform
30
30
  * expressed in the path's normalized bounding-box space (`nodeBounds` in the same
@@ -1 +1 @@
1
- {"version":3,"file":"gradients.d.ts","names":[],"sources":["../../../../src/vector/vectorize/svg/gradients.ts"],"mappings":";;;;UAuBU;EACR;EACA,OAAO;;UAGC;EACR;EACA;EACA;EACA,OAAO;EAEP;EACA;EACA;EACA;EAEA;EACA;EACA;;;;;;;iBAyCc,kBAAkB,cAAc,YAAY;;;;;;iBAoD5C,oBACd,wBACA,WAAW,YAAY,iBACvB,iCACA,UAAU,oBACV,YAAY,OACX"}
1
+ {"version":3,"file":"gradients.d.ts","names":[],"sources":["../../../../src/vector/vectorize/svg/gradients.ts"],"mappings":";;;;UAuBU;EACR;EACA,OAAO;;UAGC;EACR;EACA;EACA;EACA,OAAO;EAEP;EACA;EACA;EACA;EAEA;EACA;EACA;;;;;;;iBAyCc,kBACd,aACA,UAAS,qBACR,YAAY;;;;;;iBAoDC,oBACd,wBACA,WAAW,YAAY,iBACvB,iCACA,UAAU,oBACV,YAAY,OACX"}
@@ -1,7 +1,7 @@
1
1
  import { parseSVGDocument } from "../../../io/formats/svg/document.js";
2
2
  import { mapSVGPointToViewport, transformSVGPoint } from "./transform.js";
3
- import { ellipticalGradientTransform, linearGradientTransformFromAxes } from "@pairdraw/scene-graph/gradient";
4
3
  import { parseColor } from "@pairdraw/scene-graph/color";
4
+ import { ellipticalGradientTransform, linearGradientTransformFromAxes } from "@pairdraw/scene-graph/gradient";
5
5
  //#region src/vector/vectorize/svg/gradients.ts
6
6
  /** Coordinate value: bare number (userSpaceOnUse) or percent/fraction (objectBoundingBox). */
7
7
  function coord(value, fallback) {
@@ -11,12 +11,12 @@ function coord(value, fallback) {
11
11
  const n = Number.parseFloat(trimmed);
12
12
  return Number.isFinite(n) ? n : fallback;
13
13
  }
14
- function readStops(gradient) {
14
+ function readStops(gradient, profile) {
15
15
  const stops = [];
16
16
  const stopEls = Array.from(gradient.getElementsByTagName("stop"));
17
17
  for (const [i, stop] of stopEls.entries()) {
18
18
  const offset = coord(stop.getAttribute("offset"), i === 0 ? 0 : 1);
19
- const color = parseColor(stop.getAttribute("stop-color") ?? "#000000");
19
+ const color = parseColor(stop.getAttribute("stop-color") ?? "#000000", profile);
20
20
  const opacity = stop.getAttribute("stop-opacity");
21
21
  if (opacity != null) {
22
22
  const a = Number.parseFloat(opacity);
@@ -34,7 +34,7 @@ function readStops(gradient) {
34
34
  * (no hand-rolled markup parsing). Returns an empty map on parse failure so a
35
35
  * malformed SVG simply falls back to solid fills.
36
36
  */
37
- function parseSVGGradients(svg) {
37
+ function parseSVGGradients(svg, profile = "srgb") {
38
38
  const map = /* @__PURE__ */ new Map();
39
39
  const doc = parseSVGDocument(svg);
40
40
  if (!doc) return map;
@@ -48,7 +48,7 @@ function parseSVGGradients(svg) {
48
48
  kind,
49
49
  units,
50
50
  transform: el.getAttribute("gradientTransform"),
51
- stops: readStops(el),
51
+ stops: readStops(el, profile),
52
52
  x1: coord(el.getAttribute("x1"), 0),
53
53
  y1: coord(el.getAttribute("y1"), 0),
54
54
  x2: coord(el.getAttribute("x2"), units === "objectBoundingBox" ? 1 : 0),
@@ -1 +1 @@
1
- {"version":3,"file":"gradients.js","names":[],"sources":["../../../../src/vector/vectorize/svg/gradients.ts"],"sourcesContent":["/**\n * Parse SVG <linearGradient>/<radialGradient> defs and resolve `fill=\"url(#id)\"`\n * references into scene-graph gradient fills.\n *\n * Raster vectorizers (Recraft, fal) emit shaded regions as gradients rather than\n * flat colors. Without this, those paths fall back to the default solid color\n * (black). Gradient geometry is given in userSpaceOnUse viewBox coordinates; we\n * map the endpoints through the same transform pipeline as the path data, then\n * normalize into each node's bounding box and build the transform in Figma's convention\n * (see geometry/gradient).\n */\nimport type { Fill, GradientStop } from '@pairdraw/scene-graph'\nimport { parseColor } from '@pairdraw/scene-graph/color'\nimport {\n ellipticalGradientTransform,\n linearGradientTransformFromAxes\n} from '@pairdraw/scene-graph/gradient'\nimport type { Color, Rect, Vector } from '@pairdraw/scene-graph/primitives'\n\nimport { parseSVGDocument } from '#core/io/formats/svg/document'\n\nimport { mapSVGPointToViewport, transformSVGPoint, type SVGViewportMapping } from './transform'\n\ninterface RawStop {\n offset: number\n color: Color\n}\n\ninterface ParsedGradient {\n kind: 'linear' | 'radial'\n units: 'userSpaceOnUse' | 'objectBoundingBox'\n transform: string | null\n stops: RawStop[]\n // linear\n x1: number\n y1: number\n x2: number\n y2: number\n // radial\n cx: number\n cy: number\n r: number\n}\n\n/** Minimal structural view of the parsed XML nodes we read (DOM-compatible). */\ninterface SVGQueryable {\n getElementsByTagName(name: string): ArrayLike<SVGElementLike>\n}\ninterface SVGElementLike extends SVGQueryable {\n getAttribute(name: string): string | null\n}\n\n/** Coordinate value: bare number (userSpaceOnUse) or percent/fraction (objectBoundingBox). */\nfunction coord(value: string | null, fallback: number): number {\n if (value == null) return fallback\n const trimmed = value.trim()\n if (trimmed.endsWith('%')) return Number.parseFloat(trimmed) / 100\n const n = Number.parseFloat(trimmed)\n return Number.isFinite(n) ? n : fallback\n}\n\nfunction readStops(gradient: SVGElementLike): RawStop[] {\n const stops: RawStop[] = []\n const stopEls = Array.from(gradient.getElementsByTagName('stop'))\n for (const [i, stop] of stopEls.entries()) {\n const offset = coord(stop.getAttribute('offset'), i === 0 ? 0 : 1)\n const color = parseColor(stop.getAttribute('stop-color') ?? '#000000')\n const opacity = stop.getAttribute('stop-opacity')\n if (opacity != null) {\n const a = Number.parseFloat(opacity)\n if (Number.isFinite(a)) color.a = a\n }\n stops.push({ offset: Math.min(1, Math.max(0, offset)), color })\n }\n return stops.sort((a, b) => a.offset - b.offset)\n}\n\n/**\n * Parse every gradient def in the SVG into a lookup by id, via an XML/DOM parse\n * (no hand-rolled markup parsing). Returns an empty map on parse failure so a\n * malformed SVG simply falls back to solid fills.\n */\nexport function parseSVGGradients(svg: string): Map<string, ParsedGradient> {\n const map = new Map<string, ParsedGradient>()\n const doc: SVGQueryable | null = parseSVGDocument(svg)\n if (!doc) return map\n\n for (const kind of ['linear', 'radial'] as const) {\n const els = Array.from(doc.getElementsByTagName(`${kind}Gradient`))\n for (const el of els) {\n const id = el.getAttribute('id')\n if (!id) continue\n // SVG default gradientUnits is objectBoundingBox; vectorizers (Recraft/fal)\n // set userSpaceOnUse explicitly.\n const units =\n el.getAttribute('gradientUnits') === 'userSpaceOnUse'\n ? 'userSpaceOnUse'\n : 'objectBoundingBox'\n map.set(id, {\n kind,\n units,\n transform: el.getAttribute('gradientTransform'),\n stops: readStops(el),\n x1: coord(el.getAttribute('x1'), 0),\n y1: coord(el.getAttribute('y1'), 0),\n x2: coord(el.getAttribute('x2'), units === 'objectBoundingBox' ? 1 : 0),\n y2: coord(el.getAttribute('y2'), 0),\n cx: coord(el.getAttribute('cx'), 0.5),\n cy: coord(el.getAttribute('cy'), 0.5),\n r: coord(el.getAttribute('r'), 0.5)\n })\n }\n }\n return map\n}\n\nfunction gradientIdFromFill(fill: string | null): string | null {\n const value = fill?.trim()\n if (!value?.startsWith('url(') || !value.endsWith(')')) return null\n const reference = value.slice(4, -1).trim()\n if (!reference.startsWith('#')) return null\n const id = reference.slice(1).trim()\n return id && !id.includes(' ') ? id : null\n}\n\nfunction gradientStops(stops: RawStop[]): GradientStop[] {\n return stops.map((s) => ({ color: s.color, position: s.offset }))\n}\n\n/**\n * Build a scene-graph gradient Fill for `fill=\"url(#id)\"`, with its transform\n * expressed in the path's normalized bounding-box space (`nodeBounds` in the same\n * bounds-pixel space as the parsed network).\n */\nexport function resolveGradientFill(\n fillRef: string | null,\n gradients: Map<string, ParsedGradient>,\n elementTransform: string | null,\n viewport: SVGViewportMapping,\n nodeBounds: Rect\n): Fill | null {\n const id = gradientIdFromFill(fillRef)\n if (!id) return null\n const grad = gradients.get(id)\n if (!grad || grad.stops.length === 0) return null\n if (nodeBounds.width <= 0 || nodeBounds.height <= 0) return null\n\n const toLocal = (px: number, py: number): Vector => {\n let mapped: Vector\n if (grad.units === 'objectBoundingBox') {\n // The gradient's own transform works in bounding-box units here.\n const box = transformSVGPoint(px, py, grad.transform)\n mapped = {\n x: nodeBounds.x + box.x * nodeBounds.width,\n y: nodeBounds.y + box.y * nodeBounds.height\n }\n } else {\n mapped = mapSVGPointToViewport(px, py, elementTransform, grad.transform, viewport)\n }\n return {\n x: (mapped.x - nodeBounds.x) / nodeBounds.width,\n y: (mapped.y - nodeBounds.y) / nodeBounds.height\n }\n }\n\n const baseColor = grad.stops[0].color\n const stops = gradientStops(grad.stops)\n\n if (grad.kind === 'radial') {\n const center = toLocal(grad.cx, grad.cy)\n const edgeX = toLocal(grad.cx + grad.r, grad.cy)\n const edgeY = toLocal(grad.cx, grad.cy + grad.r)\n const transform = ellipticalGradientTransform(center, edgeX, edgeY)\n return {\n type: 'GRADIENT_RADIAL',\n color: baseColor,\n opacity: 1,\n visible: true,\n gradientStops: stops,\n gradientTransform: transform\n }\n }\n\n const start = toLocal(grad.x1, grad.y1)\n const end = toLocal(grad.x2, grad.y2)\n // SVG bands run square to the line in the gradient's own units; mapping a square step through\n // the same transforms keeps them where SVG draws them.\n const acrossEnd = toLocal(grad.x1 - (grad.y2 - grad.y1), grad.y1 + (grad.x2 - grad.x1))\n const transform = linearGradientTransformFromAxes(start, end, {\n x: acrossEnd.x - start.x,\n y: acrossEnd.y - start.y\n })\n return {\n type: 'GRADIENT_LINEAR',\n color: baseColor,\n opacity: 1,\n visible: true,\n gradientStops: stops,\n gradientTransform: transform\n }\n}\n"],"mappings":";;;;;;AAqDA,SAAS,MAAM,OAAsB,UAA0B;CAC7D,IAAI,SAAS,MAAM,OAAO;CAC1B,MAAM,UAAU,MAAM,KAAK;CAC3B,IAAI,QAAQ,SAAS,GAAG,GAAG,OAAO,OAAO,WAAW,OAAO,IAAI;CAC/D,MAAM,IAAI,OAAO,WAAW,OAAO;CACnC,OAAO,OAAO,SAAS,CAAC,IAAI,IAAI;AAClC;AAEA,SAAS,UAAU,UAAqC;CACtD,MAAM,QAAmB,CAAC;CAC1B,MAAM,UAAU,MAAM,KAAK,SAAS,qBAAqB,MAAM,CAAC;CAChE,KAAK,MAAM,CAAC,GAAG,SAAS,QAAQ,QAAQ,GAAG;EACzC,MAAM,SAAS,MAAM,KAAK,aAAa,QAAQ,GAAG,MAAM,IAAI,IAAI,CAAC;EACjE,MAAM,QAAQ,WAAW,KAAK,aAAa,YAAY,KAAK,SAAS;EACrE,MAAM,UAAU,KAAK,aAAa,cAAc;EAChD,IAAI,WAAW,MAAM;GACnB,MAAM,IAAI,OAAO,WAAW,OAAO;GACnC,IAAI,OAAO,SAAS,CAAC,GAAG,MAAM,IAAI;EACpC;EACA,MAAM,KAAK;GAAE,QAAQ,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,MAAM,CAAC;GAAG;EAAM,CAAC;CAChE;CACA,OAAO,MAAM,MAAM,GAAG,MAAM,EAAE,SAAS,EAAE,MAAM;AACjD;;;;;;AAOA,SAAgB,kBAAkB,KAA0C;CAC1E,MAAM,sBAAM,IAAI,IAA4B;CAC5C,MAAM,MAA2B,iBAAiB,GAAG;CACrD,IAAI,CAAC,KAAK,OAAO;CAEjB,KAAK,MAAM,QAAQ,CAAC,UAAU,QAAQ,GAAY;EAChD,MAAM,MAAM,MAAM,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EACT,SAAS;EACT,eAAe;EACf,mBAVgB,gCAAgC,OAAO,KAAK;GAC5D,GAAG,UAAU,IAAI,MAAM;GACvB,GAAG,UAAU,IAAI,MAAM;EACzB,CAO6B;CAC7B;AACF"}
1
+ {"version":3,"file":"gradients.js","names":[],"sources":["../../../../src/vector/vectorize/svg/gradients.ts"],"sourcesContent":["/**\n * Parse SVG <linearGradient>/<radialGradient> defs and resolve `fill=\"url(#id)\"`\n * references into scene-graph gradient fills.\n *\n * Raster vectorizers (Recraft, fal) emit shaded regions as gradients rather than\n * flat colors. Without this, those paths fall back to the default solid color\n * (black). Gradient geometry is given in userSpaceOnUse viewBox coordinates; we\n * map the endpoints through the same transform pipeline as the path data, then\n * normalize into each node's bounding box and build the transform in Figma's convention\n * (see geometry/gradient).\n */\nimport type { DocumentColorSpace, Fill, GradientStop } from '@pairdraw/scene-graph'\nimport { parseColor } from '@pairdraw/scene-graph/color'\nimport {\n ellipticalGradientTransform,\n linearGradientTransformFromAxes\n} from '@pairdraw/scene-graph/gradient'\nimport type { Color, Rect, Vector } from '@pairdraw/scene-graph/primitives'\n\nimport { parseSVGDocument } from '#core/io/formats/svg/document'\n\nimport { mapSVGPointToViewport, transformSVGPoint, type SVGViewportMapping } from './transform'\n\ninterface RawStop {\n offset: number\n color: Color\n}\n\ninterface ParsedGradient {\n kind: 'linear' | 'radial'\n units: 'userSpaceOnUse' | 'objectBoundingBox'\n transform: string | null\n stops: RawStop[]\n // linear\n x1: number\n y1: number\n x2: number\n y2: number\n // radial\n cx: number\n cy: number\n r: number\n}\n\n/** Minimal structural view of the parsed XML nodes we read (DOM-compatible). */\ninterface SVGQueryable {\n getElementsByTagName(name: string): ArrayLike<SVGElementLike>\n}\ninterface SVGElementLike extends SVGQueryable {\n getAttribute(name: string): string | null\n}\n\n/** Coordinate value: bare number (userSpaceOnUse) or percent/fraction (objectBoundingBox). */\nfunction coord(value: string | null, fallback: number): number {\n if (value == null) return fallback\n const trimmed = value.trim()\n if (trimmed.endsWith('%')) return Number.parseFloat(trimmed) / 100\n const n = Number.parseFloat(trimmed)\n return Number.isFinite(n) ? n : fallback\n}\n\nfunction readStops(gradient: SVGElementLike, profile: DocumentColorSpace): RawStop[] {\n const stops: RawStop[] = []\n const stopEls = Array.from(gradient.getElementsByTagName('stop'))\n for (const [i, stop] of stopEls.entries()) {\n const offset = coord(stop.getAttribute('offset'), i === 0 ? 0 : 1)\n const color = parseColor(stop.getAttribute('stop-color') ?? '#000000', profile)\n const opacity = stop.getAttribute('stop-opacity')\n if (opacity != null) {\n const a = Number.parseFloat(opacity)\n if (Number.isFinite(a)) color.a = a\n }\n stops.push({ offset: Math.min(1, Math.max(0, offset)), color })\n }\n return stops.sort((a, b) => a.offset - b.offset)\n}\n\n/**\n * Parse every gradient def in the SVG into a lookup by id, via an XML/DOM parse\n * (no hand-rolled markup parsing). Returns an empty map on parse failure so a\n * malformed SVG simply falls back to solid fills.\n */\nexport function parseSVGGradients(\n svg: string,\n profile: DocumentColorSpace = 'srgb'\n): Map<string, ParsedGradient> {\n const map = new Map<string, ParsedGradient>()\n const doc: SVGQueryable | null = parseSVGDocument(svg)\n if (!doc) return map\n\n for (const kind of ['linear', 'radial'] as const) {\n const els = Array.from(doc.getElementsByTagName(`${kind}Gradient`))\n for (const el of els) {\n const id = el.getAttribute('id')\n if (!id) continue\n // SVG default gradientUnits is objectBoundingBox; vectorizers (Recraft/fal)\n // set userSpaceOnUse explicitly.\n const units =\n el.getAttribute('gradientUnits') === 'userSpaceOnUse'\n ? 'userSpaceOnUse'\n : 'objectBoundingBox'\n map.set(id, {\n kind,\n units,\n transform: el.getAttribute('gradientTransform'),\n stops: readStops(el, profile),\n x1: coord(el.getAttribute('x1'), 0),\n y1: coord(el.getAttribute('y1'), 0),\n x2: coord(el.getAttribute('x2'), units === 'objectBoundingBox' ? 1 : 0),\n y2: coord(el.getAttribute('y2'), 0),\n cx: coord(el.getAttribute('cx'), 0.5),\n cy: coord(el.getAttribute('cy'), 0.5),\n r: coord(el.getAttribute('r'), 0.5)\n })\n }\n }\n return map\n}\n\nfunction gradientIdFromFill(fill: string | null): string | null {\n const value = fill?.trim()\n if (!value?.startsWith('url(') || !value.endsWith(')')) return null\n const reference = value.slice(4, -1).trim()\n if (!reference.startsWith('#')) return null\n const id = reference.slice(1).trim()\n return id && !id.includes(' ') ? id : null\n}\n\nfunction gradientStops(stops: RawStop[]): GradientStop[] {\n return stops.map((s) => ({ color: s.color, position: s.offset }))\n}\n\n/**\n * Build a scene-graph gradient Fill for `fill=\"url(#id)\"`, with its transform\n * expressed in the path's normalized bounding-box space (`nodeBounds` in the same\n * bounds-pixel space as the parsed network).\n */\nexport function resolveGradientFill(\n fillRef: string | null,\n gradients: Map<string, ParsedGradient>,\n elementTransform: string | null,\n viewport: SVGViewportMapping,\n nodeBounds: Rect\n): Fill | null {\n const id = gradientIdFromFill(fillRef)\n if (!id) return null\n const grad = gradients.get(id)\n if (!grad || grad.stops.length === 0) return null\n if (nodeBounds.width <= 0 || nodeBounds.height <= 0) return null\n\n const toLocal = (px: number, py: number): Vector => {\n let mapped: Vector\n if (grad.units === 'objectBoundingBox') {\n // The gradient's own transform works in bounding-box units here.\n const box = transformSVGPoint(px, py, grad.transform)\n mapped = {\n x: nodeBounds.x + box.x * nodeBounds.width,\n y: nodeBounds.y + box.y * nodeBounds.height\n }\n } else {\n mapped = mapSVGPointToViewport(px, py, elementTransform, grad.transform, viewport)\n }\n return {\n x: (mapped.x - nodeBounds.x) / nodeBounds.width,\n y: (mapped.y - nodeBounds.y) / nodeBounds.height\n }\n }\n\n const baseColor = grad.stops[0].color\n const stops = gradientStops(grad.stops)\n\n if (grad.kind === 'radial') {\n const center = toLocal(grad.cx, grad.cy)\n const edgeX = toLocal(grad.cx + grad.r, grad.cy)\n const edgeY = toLocal(grad.cx, grad.cy + grad.r)\n const transform = ellipticalGradientTransform(center, edgeX, edgeY)\n return {\n type: 'GRADIENT_RADIAL',\n color: baseColor,\n opacity: 1,\n visible: true,\n gradientStops: stops,\n gradientTransform: transform\n }\n }\n\n const start = toLocal(grad.x1, grad.y1)\n const end = toLocal(grad.x2, grad.y2)\n // SVG bands run square to the line in the gradient's own units; mapping a square step through\n // the same transforms keeps them where SVG draws them.\n const acrossEnd = toLocal(grad.x1 - (grad.y2 - grad.y1), grad.y1 + (grad.x2 - grad.x1))\n const transform = linearGradientTransformFromAxes(start, end, {\n x: acrossEnd.x - start.x,\n y: acrossEnd.y - start.y\n })\n return {\n type: 'GRADIENT_LINEAR',\n color: baseColor,\n opacity: 1,\n visible: true,\n gradientStops: stops,\n gradientTransform: transform\n }\n}\n"],"mappings":";;;;;;AAqDA,SAAS,MAAM,OAAsB,UAA0B;CAC7D,IAAI,SAAS,MAAM,OAAO;CAC1B,MAAM,UAAU,MAAM,KAAK;CAC3B,IAAI,QAAQ,SAAS,GAAG,GAAG,OAAO,OAAO,WAAW,OAAO,IAAI;CAC/D,MAAM,IAAI,OAAO,WAAW,OAAO;CACnC,OAAO,OAAO,SAAS,CAAC,IAAI,IAAI;AAClC;AAEA,SAAS,UAAU,UAA0B,SAAwC;CACnF,MAAM,QAAmB,CAAC;CAC1B,MAAM,UAAU,MAAM,KAAK,SAAS,qBAAqB,MAAM,CAAC;CAChE,KAAK,MAAM,CAAC,GAAG,SAAS,QAAQ,QAAQ,GAAG;EACzC,MAAM,SAAS,MAAM,KAAK,aAAa,QAAQ,GAAG,MAAM,IAAI,IAAI,CAAC;EACjE,MAAM,QAAQ,WAAW,KAAK,aAAa,YAAY,KAAK,WAAW,OAAO;EAC9E,MAAM,UAAU,KAAK,aAAa,cAAc;EAChD,IAAI,WAAW,MAAM;GACnB,MAAM,IAAI,OAAO,WAAW,OAAO;GACnC,IAAI,OAAO,SAAS,CAAC,GAAG,MAAM,IAAI;EACpC;EACA,MAAM,KAAK;GAAE,QAAQ,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,MAAM,CAAC;GAAG;EAAM,CAAC;CAChE;CACA,OAAO,MAAM,MAAM,GAAG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OhC;EAC7B;CACF;CAEA,MAAM,QAAQ,QAAQ,KAAK,IAAI,KAAK,EAAE;CACtC,MAAM,MAAM,QAAQ,KAAK,IAAI,KAAK,EAAE;CAGpC,MAAM,YAAY,QAAQ,KAAK,MAAM,KAAK,KAAK,KAAK,KAAK,KAAK,MAAM,KAAK,KAAK,KAAK,GAAG;CAKtF,OAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,SAAS;EACT,eAAe;EACf,mBAVgB,gCAAgC,OAAO,KAAK;GAC5D,GAAG,UAAU,IAAI,MAAM;GACvB,GAAG,UAAU,IAAI,MAAM;EACzB,CAO6B;CAC7B;AACF"}
@@ -1,6 +1,6 @@
1
1
  import { SVGElementLayer, SVGTextPiece, SVGTextRun } from "../../../icons/types.js";
2
2
  import { Mat3 } from "@pairdraw/scene-graph/matrix";
3
- import { Fill, Stroke, VectorNetwork } from "@pairdraw/scene-graph";
3
+ import { DocumentColorSpace, Fill, Stroke, VectorNetwork } from "@pairdraw/scene-graph";
4
4
  import { Rect, Size } from "@pairdraw/scene-graph/primitives";
5
5
  //#region src/vector/vectorize/svg/to-vectors.d.ts
6
6
  interface VectorizedClip {
@@ -45,6 +45,8 @@ interface SVGVectorizeResult {
45
45
  declare function svgToVectorPaths(svgText: string, bounds: Size, options?: {
46
46
  defaultColor?: string;
47
47
  preserveAspectRatio?: boolean;
48
+ /** The profile a color that names its own space is read into. */
49
+ profile?: DocumentColorSpace;
48
50
  }): SVGVectorizeResult | null;
49
51
  //#endregion
50
52
  export { SVGVectorizeResult, VectorizedClip, VectorizedPath, VectorizedText, VectorizedTextPiece, svgToVectorPaths };
@@ -1 +1 @@
1
- {"version":3,"file":"to-vectors.d.ts","names":[],"sources":["../../../../src/vector/vectorize/svg/to-vectors.ts"],"mappings":";;;;;UA0EiB;;EAEf;;EAEA;;EAEA,QAAQ;IAAQ,SAAS;IAAe;;;UAGzB;EACf,eAAe;EACf,OAAO;EACP,SAAS;;EAET,QAAQ;EACR,UAAU;;;KAIA,sBAAsB,KAAK;EACrC,MAAM,MAAM;IAAe,OAAO;;;UAGnB;EACf,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,UAAU;;EAEV;;UAGe;EACf,OAAO;EACP,OAAO;;EAEP,eAAe;;iBAGD,iBACd,iBACA,QAAQ,MACR;EAAY;EAAuB;IAClC"}
1
+ {"version":3,"file":"to-vectors.d.ts","names":[],"sources":["../../../../src/vector/vectorize/svg/to-vectors.ts"],"mappings":";;;;;UA+FiB;;EAEf;;EAEA;;EAEA,QAAQ;IAAQ,SAAS;IAAe;;;UAGzB;EACf,eAAe;EACf,OAAO;EACP,SAAS;;EAET,QAAQ;EACR,UAAU;;;KAIA,sBAAsB,KAAK;EACrC,MAAM,MAAM;IAAe,OAAO;;;UAGnB;EACf,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,UAAU;;EAEV;;UAGe;EACf,OAAO;EACP,OAAO;;EAEP,eAAe;;iBAGD,iBACd,iBACA,QAAQ,MACR;EACE;EACA;;EAEA,UAAU;IAEX"}
@@ -5,8 +5,8 @@ import { parseSVGSize, parseSVGViewBox } from "../../../io/formats/svg/metadata.
5
5
  import { applySVGTransformToPath, mapSVGPathToViewport, resolveSVGViewportMapping } from "./transform.js";
6
6
  import { parseSVGGradients, resolveGradientFill } from "./gradients.js";
7
7
  import { computeBounds } from "@pairdraw/scene-graph/geometry";
8
- import { parseSVGPath } from "@pairdraw/scene-graph/parse-path";
9
8
  import { parseColor } from "@pairdraw/scene-graph/color";
9
+ import { parseSVGPath } from "@pairdraw/scene-graph/parse-path";
10
10
  import svgpath from "svgpath";
11
11
  //#region src/vector/vectorize/svg/to-vectors.ts
12
12
  /**
@@ -31,24 +31,24 @@ function unionPathBounds(paths) {
31
31
  const rects = paths.map((path) => computeAccurateBounds(path.vectorNetwork)).filter((bounds) => bounds.width > 0 && bounds.height > 0);
32
32
  return computeBounds(rects);
33
33
  }
34
- function resolveFill(path, defaultColor) {
34
+ function resolveFill(path, defaultColor, profile) {
35
35
  if (path.fill && path.fill !== "none") return [{
36
36
  type: "SOLID",
37
- color: path.fill === "currentColor" ? parseColor(defaultColor) : parseColor(path.fill),
37
+ color: path.fill === "currentColor" ? parseColor(defaultColor, profile) : parseColor(path.fill, profile),
38
38
  opacity: path.fillOpacity,
39
39
  visible: true
40
40
  }];
41
41
  if (path.fill === null && !path.stroke) return [{
42
42
  type: "SOLID",
43
- color: parseColor(defaultColor),
43
+ color: parseColor(defaultColor, profile),
44
44
  opacity: 1,
45
45
  visible: true
46
46
  }];
47
47
  return [];
48
48
  }
49
- function resolveStrokes(path, defaultColor, strokeScale = 1) {
49
+ function resolveStrokes(path, defaultColor, strokeScale = 1, profile = "srgb") {
50
50
  if (!path.stroke || path.stroke === "none") return [];
51
- const color = path.stroke === "currentColor" ? parseColor(defaultColor) : parseColor(path.stroke);
51
+ const color = path.stroke === "currentColor" ? parseColor(defaultColor, profile) : parseColor(path.stroke, profile);
52
52
  return [{
53
53
  ...createPathStroke(color, path.strokeWidth * strokeScale, path.strokeCap, path.strokeJoin),
54
54
  opacity: path.strokeOpacity
@@ -60,7 +60,8 @@ function svgToVectorPaths(svgText, bounds, options) {
60
60
  const space = parseSVGCoordinateSpace(svgText);
61
61
  if (space.width <= 0 || space.height <= 0) return null;
62
62
  const defaultColor = options?.defaultColor ?? "#000000";
63
- const gradients = parseSVGGradients(svgText);
63
+ const profile = options?.profile ?? "srgb";
64
+ const gradients = parseSVGGradients(svgText, profile);
64
65
  const viewport = resolveSVGViewportMapping(svgText, space, bounds, options?.preserveAspectRatio ?? false);
65
66
  const strokeScale = Math.min(viewport.scaleX, viewport.scaleY);
66
67
  const vectorized = [];
@@ -70,8 +71,8 @@ function svgToVectorPaths(svgText, bounds, options) {
70
71
  const transform = path.transform ?? null;
71
72
  const pathData = applySVGTransformToPath(path.d, transform);
72
73
  const scaledD = mapSVGPathToViewport(pathData, viewport);
73
- const solidFills = resolveFill(path, defaultColor);
74
- const strokes = resolveStrokes(path, defaultColor, strokeScale);
74
+ const solidFills = resolveFill(path, defaultColor, profile);
75
+ const strokes = resolveStrokes(path, defaultColor, strokeScale, profile);
75
76
  const network = parseSVGPath(scaledD, fillRule, { includeOpenRegions: solidFills.length > 0 && strokes.length === 0 });
76
77
  const pathBounds = computeAccurateBounds(network);
77
78
  const gradientFill = gradients.size > 0 ? resolveGradientFill(path.fill, gradients, transform, viewport, computeAccurateBounds(network)) : null;
@@ -94,7 +95,7 @@ function svgToVectorPaths(svgText, bounds, options) {
94
95
  ...piece,
95
96
  runs: piece.runs.map((run) => ({
96
97
  ...run,
97
- fills: resolveTextFill(run, defaultColor)
98
+ fills: resolveTextFill(run, defaultColor, profile)
98
99
  }))
99
100
  })),
100
101
  matrix: transformMatrix(text.transform, viewport),
@@ -163,10 +164,10 @@ function transformMatrix(transform, viewport) {
163
164
  1
164
165
  ];
165
166
  }
166
- function resolveTextFill(run, defaultColor) {
167
+ function resolveTextFill(run, defaultColor, profile) {
167
168
  return [{
168
169
  type: "SOLID",
169
- color: run.fill === null || run.fill === "currentColor" ? parseColor(defaultColor) : parseColor(run.fill),
170
+ color: run.fill === null || run.fill === "currentColor" ? parseColor(defaultColor, profile) : parseColor(run.fill, profile),
170
171
  opacity: run.fillOpacity,
171
172
  visible: true
172
173
  }];