@moondraft/import 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (337) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/LICENSE +34 -0
  3. package/README.md +36 -2
  4. package/SOURCE.md +394 -0
  5. package/dist/adapter/convert.d.ts +144 -0
  6. package/dist/adapter/convert.js +2811 -0
  7. package/dist/adapter/figma-descriptions.d.ts +7 -0
  8. package/dist/adapter/figma-descriptions.js +34 -0
  9. package/dist/adapter/figma-grids.d.ts +12 -0
  10. package/dist/adapter/figma-grids.js +175 -0
  11. package/dist/adapter/figma-handoff.d.ts +12 -0
  12. package/dist/adapter/figma-handoff.js +167 -0
  13. package/dist/adapter/figma-hyperlinks.d.ts +13 -0
  14. package/dist/adapter/figma-hyperlinks.js +77 -0
  15. package/dist/adapter/figma.d.ts +12 -0
  16. package/dist/adapter/figma.js +40 -0
  17. package/dist/adapter/file-components.d.ts +20 -0
  18. package/dist/adapter/file-components.js +352 -0
  19. package/dist/adapter/file-resources.d.ts +29 -0
  20. package/dist/adapter/file-resources.js +851 -0
  21. package/dist/adapter/image-crop.d.ts +18 -0
  22. package/dist/adapter/image-crop.js +30 -0
  23. package/dist/adapter/index.d.ts +6 -0
  24. package/dist/adapter/index.js +9 -0
  25. package/dist/adapter/link.d.ts +49 -0
  26. package/dist/adapter/link.js +892 -0
  27. package/dist/adapter/payload.d.ts +31 -0
  28. package/dist/adapter/payload.js +78 -0
  29. package/dist/adapter/shapes.d.ts +31 -0
  30. package/dist/adapter/shapes.js +75 -0
  31. package/dist/adapter/variables.d.ts +45 -0
  32. package/dist/adapter/variables.js +106 -0
  33. package/dist/figma-file.d.ts +38 -0
  34. package/dist/figma-file.js +97 -0
  35. package/dist/figma-worker.d.ts +11 -0
  36. package/dist/figma-worker.js +12 -0
  37. package/dist/figma.d.ts +26 -0
  38. package/dist/figma.js +230 -0
  39. package/dist/index.d.ts +29 -0
  40. package/dist/index.js +50 -0
  41. package/dist/report.d.ts +42 -0
  42. package/dist/report.js +142 -0
  43. package/dist/serialize.d.ts +7 -0
  44. package/dist/serialize.js +79 -0
  45. package/dist/svg.d.ts +33 -0
  46. package/dist/svg.js +44 -0
  47. package/dist/syntax.d.ts +8 -0
  48. package/dist/syntax.js +19 -0
  49. package/dist/taco/figma-import/clipboard.d.ts +25 -0
  50. package/dist/taco/figma-import/clipboard.js +87 -0
  51. package/dist/taco/figma-import/clipboardSize.d.ts +31 -0
  52. package/dist/taco/figma-import/clipboardSize.js +107 -0
  53. package/dist/taco/figma-import/container/compression.d.ts +9 -0
  54. package/dist/taco/figma-import/container/compression.js +174 -0
  55. package/dist/taco/figma-import/container/error.d.ts +15 -0
  56. package/dist/taco/figma-import/container/error.js +19 -0
  57. package/dist/taco/figma-import/container/kiwiContainer.d.ts +41 -0
  58. package/dist/taco/figma-import/container/kiwiContainer.js +61 -0
  59. package/dist/taco/figma-import/container/limits.d.ts +22 -0
  60. package/dist/taco/figma-import/container/limits.js +22 -0
  61. package/dist/taco/figma-import/container/zip.d.ts +14 -0
  62. package/dist/taco/figma-import/container/zip.js +154 -0
  63. package/dist/taco/figma-import/figFile.d.ts +34 -0
  64. package/dist/taco/figma-import/figFile.js +91 -0
  65. package/dist/taco/figma-import/figFileDocument.d.ts +25 -0
  66. package/dist/taco/figma-import/figFileDocument.js +100 -0
  67. package/dist/taco/figma-import/import/blobs.d.ts +10 -0
  68. package/dist/taco/figma-import/import/blobs.js +23 -0
  69. package/dist/taco/figma-import/import/carry.d.ts +24 -0
  70. package/dist/taco/figma-import/import/carry.js +66 -0
  71. package/dist/taco/figma-import/import/componentProps.d.ts +90 -0
  72. package/dist/taco/figma-import/import/componentProps.js +329 -0
  73. package/dist/taco/figma-import/import/componentSets.d.ts +85 -0
  74. package/dist/taco/figma-import/import/componentSets.js +647 -0
  75. package/dist/taco/figma-import/import/converters/effects.d.ts +31 -0
  76. package/dist/taco/figma-import/import/converters/effects.js +127 -0
  77. package/dist/taco/figma-import/import/converters/ellipse.d.ts +7 -0
  78. package/dist/taco/figma-import/import/converters/ellipse.js +54 -0
  79. package/dist/taco/figma-import/import/converters/exportSettings.d.ts +4 -0
  80. package/dist/taco/figma-import/import/converters/exportSettings.js +49 -0
  81. package/dist/taco/figma-import/import/converters/frame.d.ts +21 -0
  82. package/dist/taco/figma-import/import/converters/frame.js +63 -0
  83. package/dist/taco/figma-import/import/converters/gradient.d.ts +74 -0
  84. package/dist/taco/figma-import/import/converters/gradient.js +108 -0
  85. package/dist/taco/figma-import/import/converters/group.d.ts +19 -0
  86. package/dist/taco/figma-import/import/converters/group.js +30 -0
  87. package/dist/taco/figma-import/import/converters/image.d.ts +13 -0
  88. package/dist/taco/figma-import/import/converters/image.js +94 -0
  89. package/dist/taco/figma-import/import/converters/layout.d.ts +33 -0
  90. package/dist/taco/figma-import/import/converters/layout.js +187 -0
  91. package/dist/taco/figma-import/import/converters/line.d.ts +11 -0
  92. package/dist/taco/figma-import/import/converters/line.js +40 -0
  93. package/dist/taco/figma-import/import/converters/rectangle.d.ts +3 -0
  94. package/dist/taco/figma-import/import/converters/rectangle.js +11 -0
  95. package/dist/taco/figma-import/import/converters/section.d.ts +8 -0
  96. package/dist/taco/figma-import/import/converters/section.js +29 -0
  97. package/dist/taco/figma-import/import/converters/shared.d.ts +71 -0
  98. package/dist/taco/figma-import/import/converters/shared.js +372 -0
  99. package/dist/taco/figma-import/import/converters/text.d.ts +54 -0
  100. package/dist/taco/figma-import/import/converters/text.js +707 -0
  101. package/dist/taco/figma-import/import/converters/vector.d.ts +105 -0
  102. package/dist/taco/figma-import/import/converters/vector.js +609 -0
  103. package/dist/taco/figma-import/import/converters/vectorNetwork.d.ts +114 -0
  104. package/dist/taco/figma-import/import/converters/vectorNetwork.js +503 -0
  105. package/dist/taco/figma-import/import/fields.d.ts +15 -0
  106. package/dist/taco/figma-import/import/fields.js +29 -0
  107. package/dist/taco/figma-import/import/instances.d.ts +184 -0
  108. package/dist/taco/figma-import/import/instances.js +1530 -0
  109. package/dist/taco/figma-import/import/nestingCycles.d.ts +86 -0
  110. package/dist/taco/figma-import/import/nestingCycles.js +488 -0
  111. package/dist/taco/figma-import/import/slots.d.ts +56 -0
  112. package/dist/taco/figma-import/import/slots.js +96 -0
  113. package/dist/taco/figma-import/import/styles.d.ts +48 -0
  114. package/dist/taco/figma-import/import/styles.js +48 -0
  115. package/dist/taco/figma-import/import/tree.d.ts +66 -0
  116. package/dist/taco/figma-import/import/tree.js +194 -0
  117. package/dist/taco/figma-import/import/types.d.ts +232 -0
  118. package/dist/taco/figma-import/import/types.js +33 -0
  119. package/dist/taco/figma-import/import/variables.d.ts +137 -0
  120. package/dist/taco/figma-import/import/variables.js +769 -0
  121. package/dist/taco/figma-import/import/variantTrees.d.ts +20 -0
  122. package/dist/taco/figma-import/import/variantTrees.js +520 -0
  123. package/dist/taco/figma-import/import/walk.d.ts +207 -0
  124. package/dist/taco/figma-import/import/walk.js +1464 -0
  125. package/dist/taco/figma-import/index.d.ts +22 -0
  126. package/dist/taco/figma-import/index.js +13 -0
  127. package/dist/taco/figma-import/kiwi/byteReader.d.ts +37 -0
  128. package/dist/taco/figma-import/kiwi/byteReader.js +151 -0
  129. package/dist/taco/figma-import/kiwi/error.d.ts +14 -0
  130. package/dist/taco/figma-import/kiwi/error.js +29 -0
  131. package/dist/taco/figma-import/kiwi/limits.d.ts +18 -0
  132. package/dist/taco/figma-import/kiwi/limits.js +18 -0
  133. package/dist/taco/figma-import/kiwi/message.d.ts +12 -0
  134. package/dist/taco/figma-import/kiwi/message.js +147 -0
  135. package/dist/taco/figma-import/kiwi/schema.d.ts +42 -0
  136. package/dist/taco/figma-import/kiwi/schema.js +206 -0
  137. package/dist/taco/figma-import/kiwi/types.d.ts +46 -0
  138. package/dist/taco/figma-import/kiwi/types.js +18 -0
  139. package/dist/taco/model/agent-hidden-fields.d.ts +20 -0
  140. package/dist/taco/model/agent-hidden-fields.js +29 -0
  141. package/dist/taco/model/asset-users.d.ts +23 -0
  142. package/dist/taco/model/asset-users.js +128 -0
  143. package/dist/taco/model/auto-layout-lines.d.ts +32 -0
  144. package/dist/taco/model/auto-layout-lines.js +70 -0
  145. package/dist/taco/model/codec.d.ts +444 -0
  146. package/dist/taco/model/codec.js +5665 -0
  147. package/dist/taco/model/color.d.ts +11 -0
  148. package/dist/taco/model/color.js +61 -0
  149. package/dist/taco/model/comment-operations.d.ts +102 -0
  150. package/dist/taco/model/comment-operations.js +227 -0
  151. package/dist/taco/model/component-evaluation.d.ts +96 -0
  152. package/dist/taco/model/component-evaluation.js +555 -0
  153. package/dist/taco/model/component-expressions.d.ts +242 -0
  154. package/dist/taco/model/component-expressions.js +1082 -0
  155. package/dist/taco/model/component-properties.d.ts +111 -0
  156. package/dist/taco/model/component-properties.js +339 -0
  157. package/dist/taco/model/component-samples.d.ts +83 -0
  158. package/dist/taco/model/component-samples.js +290 -0
  159. package/dist/taco/model/component-validity.d.ts +85 -0
  160. package/dist/taco/model/component-validity.js +397 -0
  161. package/dist/taco/model/components.d.ts +155 -0
  162. package/dist/taco/model/components.js +505 -0
  163. package/dist/taco/model/connector-ends.d.ts +20 -0
  164. package/dist/taco/model/connector-ends.js +188 -0
  165. package/dist/taco/model/connector-geometry.d.ts +74 -0
  166. package/dist/taco/model/connector-geometry.js +293 -0
  167. package/dist/taco/model/corner-radii.d.ts +26 -0
  168. package/dist/taco/model/corner-radii.js +47 -0
  169. package/dist/taco/model/derivations.d.ts +81 -0
  170. package/dist/taco/model/derivations.js +151 -0
  171. package/dist/taco/model/export-settings.d.ts +53 -0
  172. package/dist/taco/model/export-settings.js +156 -0
  173. package/dist/taco/model/expressions/ast.d.ts +153 -0
  174. package/dist/taco/model/expressions/ast.js +6 -0
  175. package/dist/taco/model/expressions/cache.d.ts +23 -0
  176. package/dist/taco/model/expressions/cache.js +43 -0
  177. package/dist/taco/model/expressions/check.d.ts +72 -0
  178. package/dist/taco/model/expressions/check.js +517 -0
  179. package/dist/taco/model/expressions/completion.d.ts +61 -0
  180. package/dist/taco/model/expressions/completion.js +421 -0
  181. package/dist/taco/model/expressions/evaluate.d.ts +32 -0
  182. package/dist/taco/model/expressions/evaluate.js +519 -0
  183. package/dist/taco/model/expressions/forms.d.ts +84 -0
  184. package/dist/taco/model/expressions/forms.js +200 -0
  185. package/dist/taco/model/expressions/index.d.ts +14 -0
  186. package/dist/taco/model/expressions/index.js +17 -0
  187. package/dist/taco/model/expressions/lexer.d.ts +42 -0
  188. package/dist/taco/model/expressions/lexer.js +213 -0
  189. package/dist/taco/model/expressions/library.d.ts +33 -0
  190. package/dist/taco/model/expressions/library.js +117 -0
  191. package/dist/taco/model/expressions/names.d.ts +43 -0
  192. package/dist/taco/model/expressions/names.js +99 -0
  193. package/dist/taco/model/expressions/parser.d.ts +15 -0
  194. package/dist/taco/model/expressions/parser.js +438 -0
  195. package/dist/taco/model/expressions/rename.d.ts +34 -0
  196. package/dist/taco/model/expressions/rename.js +46 -0
  197. package/dist/taco/model/expressions/source.d.ts +15 -0
  198. package/dist/taco/model/expressions/source.js +161 -0
  199. package/dist/taco/model/expressions/types.d.ts +119 -0
  200. package/dist/taco/model/expressions/types.js +102 -0
  201. package/dist/taco/model/expressions/values.d.ts +97 -0
  202. package/dist/taco/model/expressions/values.js +160 -0
  203. package/dist/taco/model/geometry-limits.d.ts +16 -0
  204. package/dist/taco/model/geometry-limits.js +67 -0
  205. package/dist/taco/model/geometry.d.ts +47 -0
  206. package/dist/taco/model/geometry.js +193 -0
  207. package/dist/taco/model/group-bounds.d.ts +38 -0
  208. package/dist/taco/model/group-bounds.js +144 -0
  209. package/dist/taco/model/id-table.d.ts +37 -0
  210. package/dist/taco/model/id-table.js +80 -0
  211. package/dist/taco/model/index.d.ts +25 -0
  212. package/dist/taco/model/index.js +27 -0
  213. package/dist/taco/model/instance-resolver.d.ts +376 -0
  214. package/dist/taco/model/instance-resolver.js +1778 -0
  215. package/dist/taco/model/layer-syntax.d.ts +340 -0
  216. package/dist/taco/model/layer-syntax.js +3506 -0
  217. package/dist/taco/model/layout/constraints.d.ts +84 -0
  218. package/dist/taco/model/layout/constraints.js +445 -0
  219. package/dist/taco/model/layout/frame-layout.d.ts +46 -0
  220. package/dist/taco/model/layout/frame-layout.js +618 -0
  221. package/dist/taco/model/layout/node-sizing.d.ts +163 -0
  222. package/dist/taco/model/layout/node-sizing.js +486 -0
  223. package/dist/taco/model/legacy-connector-caps.d.ts +15 -0
  224. package/dist/taco/model/legacy-connector-caps.js +70 -0
  225. package/dist/taco/model/linear-call.d.ts +48 -0
  226. package/dist/taco/model/linear-call.js +58 -0
  227. package/dist/taco/model/new-nodes.d.ts +145 -0
  228. package/dist/taco/model/new-nodes.js +277 -0
  229. package/dist/taco/model/node-builder.d.ts +449 -0
  230. package/dist/taco/model/node-builder.js +2294 -0
  231. package/dist/taco/model/node-table-watch.d.ts +36 -0
  232. package/dist/taco/model/node-table-watch.js +63 -0
  233. package/dist/taco/model/node-transform.d.ts +39 -0
  234. package/dist/taco/model/node-transform.js +79 -0
  235. package/dist/taco/model/node-users-index.d.ts +10 -0
  236. package/dist/taco/model/node-users-index.js +82 -0
  237. package/dist/taco/model/operation-references.d.ts +80 -0
  238. package/dist/taco/model/operation-references.js +399 -0
  239. package/dist/taco/model/operations.d.ts +610 -0
  240. package/dist/taco/model/operations.js +2882 -0
  241. package/dist/taco/model/overlay-table.d.ts +71 -0
  242. package/dist/taco/model/overlay-table.js +171 -0
  243. package/dist/taco/model/override-remap.d.ts +69 -0
  244. package/dist/taco/model/override-remap.js +230 -0
  245. package/dist/taco/model/parent-table.d.ts +53 -0
  246. package/dist/taco/model/parent-table.js +193 -0
  247. package/dist/taco/model/problem-collector.d.ts +27 -0
  248. package/dist/taco/model/problem-collector.js +101 -0
  249. package/dist/taco/model/sha256.d.ts +10 -0
  250. package/dist/taco/model/sha256.js +79 -0
  251. package/dist/taco/model/shape-geometry.d.ts +96 -0
  252. package/dist/taco/model/shape-geometry.js +368 -0
  253. package/dist/taco/model/shared-node-table.d.ts +97 -0
  254. package/dist/taco/model/shared-node-table.js +546 -0
  255. package/dist/taco/model/slots.d.ts +113 -0
  256. package/dist/taco/model/slots.js +281 -0
  257. package/dist/taco/model/stroke-settings.d.ts +37 -0
  258. package/dist/taco/model/stroke-settings.js +90 -0
  259. package/dist/taco/model/svg-path-import.d.ts +89 -0
  260. package/dist/taco/model/svg-path-import.js +219 -0
  261. package/dist/taco/model/text-measurement.d.ts +142 -0
  262. package/dist/taco/model/text-measurement.js +846 -0
  263. package/dist/taco/model/text-reads.d.ts +66 -0
  264. package/dist/taco/model/text-reads.js +128 -0
  265. package/dist/taco/model/text-sizer.d.ts +358 -0
  266. package/dist/taco/model/text-sizer.js +996 -0
  267. package/dist/taco/model/theme-users.d.ts +59 -0
  268. package/dist/taco/model/theme-users.js +312 -0
  269. package/dist/taco/model/thumbnail.d.ts +15 -0
  270. package/dist/taco/model/thumbnail.js +34 -0
  271. package/dist/taco/model/types.d.ts +2369 -0
  272. package/dist/taco/model/types.js +366 -0
  273. package/dist/taco/model/unknown-property.d.ts +5 -0
  274. package/dist/taco/model/unknown-property.js +7 -0
  275. package/dist/taco/model/validated-documents.d.ts +22 -0
  276. package/dist/taco/model/validated-documents.js +22 -0
  277. package/dist/taco/model/variable-modes.d.ts +61 -0
  278. package/dist/taco/model/variable-modes.js +438 -0
  279. package/dist/taco/model/variable-references.d.ts +54 -0
  280. package/dist/taco/model/variable-references.js +183 -0
  281. package/dist/taco/model/variables.d.ts +24 -0
  282. package/dist/taco/model/variables.js +151 -0
  283. package/dist/taco/model/vector-network.d.ts +34 -0
  284. package/dist/taco/model/vector-network.js +411 -0
  285. package/dist/taco/svg-import/import-svg.d.ts +36 -0
  286. package/dist/taco/svg-import/import-svg.js +729 -0
  287. package/dist/taco/svg-import/index.d.ts +3 -0
  288. package/dist/taco/svg-import/index.js +3 -0
  289. package/dist/taco/svg-import/limits/limits.d.ts +79 -0
  290. package/dist/taco/svg-import/limits/limits.js +160 -0
  291. package/dist/taco/svg-import/paint/gradients.d.ts +64 -0
  292. package/dist/taco/svg-import/paint/gradients.js +429 -0
  293. package/dist/taco/svg-import/paint/paint.d.ts +32 -0
  294. package/dist/taco/svg-import/paint/paint.js +162 -0
  295. package/dist/taco/svg-import/paths/paths.d.ts +58 -0
  296. package/dist/taco/svg-import/paths/paths.js +205 -0
  297. package/dist/taco/svg-import/public-types.d.ts +279 -0
  298. package/dist/taco/svg-import/public-types.js +56 -0
  299. package/dist/taco/svg-import/report/report.d.ts +44 -0
  300. package/dist/taco/svg-import/report/report.js +79 -0
  301. package/dist/taco/svg-import/reuse/reuse.d.ts +99 -0
  302. package/dist/taco/svg-import/reuse/reuse.js +840 -0
  303. package/dist/taco/svg-import/shapes/shapes.d.ts +35 -0
  304. package/dist/taco/svg-import/shapes/shapes.js +386 -0
  305. package/dist/taco/svg-import/structure/effects.d.ts +26 -0
  306. package/dist/taco/svg-import/structure/effects.js +618 -0
  307. package/dist/taco/svg-import/structure/image.d.ts +24 -0
  308. package/dist/taco/svg-import/structure/image.js +495 -0
  309. package/dist/taco/svg-import/structure/walk.d.ts +85 -0
  310. package/dist/taco/svg-import/structure/walk.js +544 -0
  311. package/dist/taco/svg-import/style/color.d.ts +40 -0
  312. package/dist/taco/svg-import/style/color.js +275 -0
  313. package/dist/taco/svg-import/style/computed.d.ts +214 -0
  314. package/dist/taco/svg-import/style/computed.js +1534 -0
  315. package/dist/taco/svg-import/style/css.d.ts +127 -0
  316. package/dist/taco/svg-import/style/css.js +541 -0
  317. package/dist/taco/svg-import/style/media.d.ts +25 -0
  318. package/dist/taco/svg-import/style/media.js +307 -0
  319. package/dist/taco/svg-import/style/properties.d.ts +43 -0
  320. package/dist/taco/svg-import/style/properties.js +135 -0
  321. package/dist/taco/svg-import/style/selector-reach.d.ts +30 -0
  322. package/dist/taco/svg-import/style/selector-reach.js +169 -0
  323. package/dist/taco/svg-import/style/selector-validity.d.ts +14 -0
  324. package/dist/taco/svg-import/style/selector-validity.js +307 -0
  325. package/dist/taco/svg-import/text/text.d.ts +29 -0
  326. package/dist/taco/svg-import/text/text.js +545 -0
  327. package/dist/taco/svg-import/transform/matrix.d.ts +111 -0
  328. package/dist/taco/svg-import/transform/matrix.js +229 -0
  329. package/dist/taco/svg-import/tree/element-data.d.ts +52 -0
  330. package/dist/taco/svg-import/tree/element-data.js +155 -0
  331. package/dist/taco/svg-import/tree/elements.d.ts +36 -0
  332. package/dist/taco/svg-import/tree/elements.js +121 -0
  333. package/dist/taco/svg-import/units/length.d.ts +43 -0
  334. package/dist/taco/svg-import/units/length.js +125 -0
  335. package/dist/taco/svg-import/units/viewbox.d.ts +35 -0
  336. package/dist/taco/svg-import/units/viewbox.js +77 -0
  337. package/package.json +55 -4
@@ -0,0 +1,851 @@
1
+ import * as editorSchema from '@moondraft/editor/schema';
2
+ import { STYLES, VARIABLES } from '@moondraft/editor/schema';
3
+ import { textColor } from '../taco/figma-import/import/converters/text.js';
4
+ import { styleAtOf, supportsRunPaint } from './link.js';
5
+ import { guidText, isObject } from '../taco/figma-import/import/fields.js';
6
+ import { isDetachedStyle, STYLE_REFERENCE_FIELDS } from '../taco/figma-import/import/styles.js';
7
+ import { layerPathKey, parseLayerPath } from '../taco/model/index.js';
8
+ import { rgba, runStyle } from './convert.js';
9
+ import { keepDescription } from './figma-descriptions.js';
10
+ // Editor 0.3.0's closed variable schema predates both metadata fields.
11
+ const scopeNames = 'VARIABLE_SCOPES' in editorSchema ? new Set(editorSchema.VARIABLE_SCOPES) : undefined;
12
+ const syntaxPlatforms = new Map([['WEB', 'web'], ['ANDROID', 'android'], ['iOS', 'ios']]);
13
+ function keepVariableMetadata(node, record, report) {
14
+ const { variableScopes, codeSyntax } = node.change;
15
+ const leftOut = (what) => report.push({ kind: 'left-out', what, count: 1 });
16
+ if (!scopeNames) {
17
+ if (Array.isArray(variableScopes) || codeSyntax !== undefined)
18
+ leftOut('variable metadata requires a newer editor');
19
+ return;
20
+ }
21
+ if (Array.isArray(variableScopes)) {
22
+ record.scopes = [];
23
+ for (const raw of variableScopes) {
24
+ const scope = raw === 'STROKE' ? 'STROKE_COLOR' : raw;
25
+ if (typeof scope === 'string' && scopeNames.has(scope))
26
+ record.scopes.push(scope);
27
+ else
28
+ leftOut('unsupported variable scope');
29
+ }
30
+ }
31
+ if (codeSyntax === undefined)
32
+ return;
33
+ if (!isObject(codeSyntax) || codeSyntax.entries !== undefined && !Array.isArray(codeSyntax.entries)) {
34
+ leftOut('unsupported variable code syntax');
35
+ return;
36
+ }
37
+ record.codeSyntax = {};
38
+ for (const entry of codeSyntax.entries ?? []) {
39
+ if (isObject(entry) && typeof entry.platform === 'string' && typeof entry.value === 'string') {
40
+ const platform = syntaxPlatforms.get(entry.platform);
41
+ if (platform) {
42
+ record.codeSyntax[platform] = entry.value;
43
+ continue;
44
+ }
45
+ }
46
+ leftOut('unsupported variable code syntax entry');
47
+ }
48
+ }
49
+ function fileVariables(result, shared, identity, report) {
50
+ const variables = result.sources.variables;
51
+ for (const [id, c] of Object.entries(result.variableCollections)) {
52
+ shared.push({ ...identity(variables.sources.get(id)), id, parent: VARIABLES, kind: 'collection', name: c.name,
53
+ modes: c.modeOrder.map(id => ({ id, name: c.modes[id].name })), defaultMode: c.defaultModeId });
54
+ for (const [varId, v] of Object.entries(c.variables)) {
55
+ const node = variables.sources.get(varId);
56
+ const values = Object.fromEntries(Object.entries(v.values).map(([mode, value]) => [mode, v.type === 'color' ? rgba(value) : value]));
57
+ for (const [mode, alias] of variables.aliases.get(varId) ?? [])
58
+ values[mode] = { alias };
59
+ const record = { ...identity(node), id: varId, parent: id, name: v.name, kind: 'variable', type: v.type, values };
60
+ keepDescription(node, record, report);
61
+ keepVariableMetadata(node, record, report);
62
+ shared.push(record);
63
+ }
64
+ }
65
+ }
66
+ const corners = ['rectangleTopLeftCornerRadius', 'rectangleTopRightCornerRadius', 'rectangleBottomRightCornerRadius', 'rectangleBottomLeftCornerRadius'];
67
+ const strokeSides = ['Top', 'Right', 'Bottom', 'Left'].map(side => ({
68
+ field: 'border' + side + 'Weight', binding: 'BORDER_' + side.toUpperCase() + '_WEIGHT',
69
+ }));
70
+ const isStrokeSideBinding = (field) => strokeSides.some(side => side.binding === field);
71
+ const strokeSideBindings = (change) => (change.variableConsumptionMap?.entries ?? []).filter((entry) => isStrokeSideBinding(entry.variableField));
72
+ const hasUniformStroke = (change) => change.borderStrokeWeightsIndependent === false ||
73
+ change.strokeWeight !== undefined && !change.borderStrokeWeightsIndependent;
74
+ const fields = {
75
+ WIDTH: 'w', HEIGHT: 'h', STROKE_WEIGHT: 'strokeWidth', OPACITY: 'opacity', VISIBLE: 'visible', TEXT_DATA: 'content',
76
+ STACK_SPACING: 'layoutData.layout.gap', STACK_COUNTER_SPACING: 'layoutData.layout.wrapGap',
77
+ CORNER_RADIUS: 'radius', RECTANGLE_TOP_LEFT_CORNER_RADIUS: 'radius.0', RECTANGLE_TOP_RIGHT_CORNER_RADIUS: 'radius.1',
78
+ RECTANGLE_BOTTOM_RIGHT_CORNER_RADIUS: 'radius.2', RECTANGLE_BOTTOM_LEFT_CORNER_RADIUS: 'radius.3',
79
+ ...Object.fromEntries(['left', 'top', 'right', 'bottom'].map(side => ['STACK_PADDING_' + side.toUpperCase(), 'layoutData.layout.padding.' + side])),
80
+ };
81
+ function paintsAndEffects(change, m, bind, indices) {
82
+ for (const [key, prefix] of [['fillPaints', 'look.fills'], ['strokePaints', 'look.stroke.paint']]) {
83
+ const paints = change[key] ?? [];
84
+ if (!paints.length)
85
+ continue;
86
+ if (key === 'fillPaints' && m.fill && paints.some(p => p.colorVar)) {
87
+ (m.look ??= {}).fills = [{ k: 'solid', c: m.fill, o: 1 }];
88
+ delete m.fill;
89
+ }
90
+ if (key === 'strokePaints' && m.stroke && m.look?.stroke && paints.some(p => p.colorVar))
91
+ m.look.stroke.paint ??= { k: 'solid', c: m.stroke, o: 1 };
92
+ const order = indices.paintIndices.get(paints) ?? paints.map((_, i) => i);
93
+ const byIndex = new Map(order.map((index, i) => [index, i]));
94
+ const firstStroke = order.find(i => paints[i]?.visible !== false);
95
+ const glyphPaint = key === 'fillPaints' && m.kind === 'text' ? textColor(paints).paint : undefined;
96
+ paints.forEach((paint, i) => {
97
+ const fill = key === 'fillPaints';
98
+ const index = byIndex.get(i);
99
+ const output = fill ? index !== undefined && m.look?.fills?.[index] : i === firstStroke && m.look?.stroke?.paint;
100
+ const path = fill ? prefix + '.' + index : prefix;
101
+ if (paint.colorVar && paint !== glyphPaint)
102
+ bind(output?.k === 'solid' ? path + '.c' : undefined, paint.colorVar, 'color');
103
+ if (paint.opacityVar)
104
+ bind(undefined, paint.opacityVar, 'number');
105
+ if (!paint.stopsVar)
106
+ return;
107
+ // The reader sorts the stops and samples a new endpoint for stops beyond the paint's range.
108
+ const sorted = (paint.stops ?? []).map((stop, source) => ({ at: stop.position, source }))
109
+ .sort((a, b) => a.at - b.at);
110
+ const inside = sorted.filter((stop) => stop.at >= 0 && stop.at <= 1);
111
+ const first = Number(sorted[0]?.at < 0);
112
+ const locations = new Map(inside.map((stop, i) => [stop.source, first + i]));
113
+ for (const [j, stop] of paint.stopsVar.entries())
114
+ if (stop.colorVar) {
115
+ const k = locations.get(j);
116
+ if (k === undefined || !output?.stops?.[k])
117
+ bind(undefined, stop.colorVar, 'color');
118
+ else {
119
+ bind(path + '.stops.' + k + '.1', stop.colorVar, 'color');
120
+ if (sorted.length === 1 && output.stops.length === 2)
121
+ bind(path + '.stops.1.1', stop.colorVar, 'color');
122
+ }
123
+ }
124
+ });
125
+ }
126
+ for (const effect of change.effects ?? []) {
127
+ const blur = ['FOREGROUND_BLUR', 'BACKGROUND_BLUR'].includes(effect.type);
128
+ const prefix = m.kind === 'text' ? undefined : indices.effectFields.get(effect);
129
+ if (prefix && blur)
130
+ (m.look ??= {})[prefix.slice(5)] ??= { radius: 0 };
131
+ for (const [field, suffix] of Object.entries({ colorVar: 'c', radiusVar: blur ? 'radius' : 'blur', spreadVar: 'spread', offsetXVar: 'x', offsetYVar: 'y' })) {
132
+ if (effect[field])
133
+ bind(prefix && (!blur || suffix === 'radius') ? prefix + '.' + suffix : undefined, effect[field], field === 'colorVar' ? 'color' : 'number');
134
+ }
135
+ }
136
+ }
137
+ function radiusBindings(change) {
138
+ const bindings = new Map();
139
+ for (const e of change.variableConsumptionMap?.entries ?? []) {
140
+ const path = fields[e.variableField];
141
+ if (path?.startsWith('radius'))
142
+ bindings.set(path, e.variableData);
143
+ }
144
+ return bindings;
145
+ }
146
+ // Apply one Figma layer's authored radii to the four corners it inherits.
147
+ function radiiOf(change, inherited) {
148
+ const bindings = radiusBindings(change);
149
+ return corners.map((field, i) => {
150
+ const base = inherited?.[i];
151
+ const own = change.rectangleCornerRadiiIndependent !== false ? change[field] : undefined;
152
+ const value = Math.max(0, own ?? change.cornerRadius ?? base?.value ?? 0);
153
+ const corner = bindings.get('radius.' + i);
154
+ if (corner)
155
+ return { value, binding: { data: corner, specific: true } };
156
+ const overall = bindings.get('radius');
157
+ if (overall && !base?.binding?.specific)
158
+ return { value, binding: { data: overall, specific: false } };
159
+ if (!overall && (own !== undefined || change.cornerRadius !== undefined))
160
+ return { value };
161
+ return base?.binding ? { value, binding: base.binding } : { value };
162
+ });
163
+ }
164
+ /** Finds instance roots that need their own radius bindings. Native instance roots take bindings from their main.
165
+ * @param result - File definitions and original instance fields.
166
+ * @returns The effective corners for each root that must remain an expanded frame.
167
+ * @internal
168
+ */
169
+ export function expandedRadiusRoots(result) {
170
+ const roots = new Map(Object.entries(result.componentIds).map(([guid, component]) => [component, result.sources.tree.nodes.get(guid)]));
171
+ const nested = new Map();
172
+ const hasRadius = (c) => c.cornerRadius !== undefined || corners.some(field => field in c) || radiusBindings(c).size > 0;
173
+ for (const overrides of result.sources.occurrenceFields.values())
174
+ for (const [path, change] of overrides) {
175
+ if (!hasRadius(change))
176
+ continue;
177
+ const target = parseLayerPath(path).at(-1);
178
+ const changes = nested.get(target);
179
+ if (changes)
180
+ changes.push(change);
181
+ else
182
+ nested.set(target, [change]);
183
+ }
184
+ const expanded = new Map();
185
+ const needsFrame = (main, own) => own.some(c => c.binding) && own.some((c, i) => JSON.stringify(c.binding?.data) !== JSON.stringify(main[i].binding?.data) || !c.binding && c.value !== main[i].value);
186
+ for (const { node, figma } of result.sources.imported) {
187
+ if (node.type !== 'instance' || figma.type !== 'INSTANCE')
188
+ continue;
189
+ const overrides = nested.get(node.id);
190
+ if (!overrides && !hasRadius(figma.change))
191
+ continue;
192
+ const main = radiiOf(roots.get(node.componentId).change), own = radiiOf(figma.change, main);
193
+ if (needsFrame(main, own) || overrides?.some(change => needsFrame(own, radiiOf(change, own))))
194
+ expanded.set(node.id, own);
195
+ }
196
+ return expanded;
197
+ }
198
+ function layerFields(change, m, bind) {
199
+ const entries = change.variableConsumptionMap?.entries ?? [];
200
+ for (const { variableField, variableData } of entries) {
201
+ if (isStrokeSideBinding(variableField))
202
+ continue; // Installed per side.
203
+ if (variableField === 'FONT_SIZE' && m.styles)
204
+ continue; // Installed per range below.
205
+ if (variableField === 'TEXT_DATA' && variableData === undefined)
206
+ continue; // An empty entry names no variable.
207
+ let path = Object.hasOwn(fields, variableField) ? fields[variableField] : undefined;
208
+ if (path?.startsWith('radius') && ['frame', 'rect'].includes(m.kind))
209
+ continue; // Installed per effective corner.
210
+ if (path?.startsWith('radius') || (path === 'w' || path === 'h') && (m[path] === undefined || m.autoResize === 2 || path === 'h' && m.autoResize === 1)
211
+ || path?.startsWith('layoutData.layout.') && (!m.layoutData?.layout || m.layoutData.layout.kind === 'absolute' || m.component && m.component !== m.id)
212
+ || path === 'content' && m.kind !== 'text'
213
+ || path === 'strokeWidth' && (!m.stroke || m.component && m.component !== m.id)
214
+ || path && m.bind?.[path])
215
+ path = undefined;
216
+ bind(path, variableData, path === 'visible' ? 'boolean' : path === 'content' ? 'string' : 'number');
217
+ }
218
+ }
219
+ // Linking compares painted instances with their mains. A mode difference in that comparison is derived:
220
+ // leaving it as an authored paint override would mask the binding when the mode changes again.
221
+ function inheritedLiterals(entry, template, change, expanded, rootBindings) {
222
+ const sources = Object.keys(template.vars ?? {});
223
+ const inherited = (key) => sources.some(path => path === key || path.startsWith(key + '.'));
224
+ const formatting = [
225
+ ['look.fills', 'fillStyle', 'fillPaints', 'styleIdForFill'],
226
+ ['look.stroke.paint', 'strokeStyle', 'strokePaints', 'styleIdForStrokeFill'],
227
+ ['look.shadows', 'effectStyle', 'effects', 'styleIdForEffect'],
228
+ ['look.layerBlur', 'effectStyle', 'effects', 'styleIdForEffect'],
229
+ ['look.backgroundBlur', 'effectStyle', 'effects', 'styleIdForEffect'],
230
+ ];
231
+ for (const [key, style, list, ref] of formatting) {
232
+ if (!template[style] && !inherited(key))
233
+ continue;
234
+ if (!(list in change || ref in change))
235
+ delete entry[key];
236
+ else if (!(key in entry) && list in change && !(ref in change)) {
237
+ const bound = sources.filter(path => path.startsWith(key + '.'));
238
+ if (bound.length && rootBindings && bound.every(path => rootBindings.has(path)))
239
+ continue;
240
+ // The link pass omits equal literals. An authored value still masks the main's source.
241
+ if (key === 'look.fills')
242
+ entry[key] = expanded.look?.fills ?? (expanded.fill ? [{ k: 'solid', c: expanded.fill }] : []);
243
+ else if (key === 'look.stroke.paint' && expanded.stroke)
244
+ entry[key] = expanded.look?.stroke?.paint ?? { k: 'solid', c: expanded.stroke };
245
+ else if (key !== 'look.stroke.paint')
246
+ entry[key] = expanded.look?.[key.slice(5)] ?? (key === 'look.shadows' ? [] : { radius: 0 });
247
+ }
248
+ }
249
+ for (const [key, field] of [['visible', 'visible'], ['opacity', 'opacity'], ['content', 'textData']]) {
250
+ if (rootBindings || !inherited(key))
251
+ continue;
252
+ const authored = key === 'content' ? change.textData?.characters !== undefined : field in change;
253
+ if (!authored)
254
+ delete entry[key];
255
+ else if (!(key in entry))
256
+ entry[key] = key === 'content' ? expanded.content : change[field];
257
+ }
258
+ }
259
+ // A style alias supplies its colour in the user's mode. All other paint fields, including
260
+ // the unit-box gradient geometry, must match the paint converted on that user's box.
261
+ function sameStyleValue(style, literal) {
262
+ if (style === literal)
263
+ return true;
264
+ if (typeof style === 'number' && typeof literal === 'number')
265
+ return Math.fround(style) === Math.fround(literal);
266
+ if (style?.alias)
267
+ return literal !== undefined;
268
+ if (!style || !literal || typeof style !== 'object' || typeof literal !== 'object')
269
+ return false;
270
+ if (Array.isArray(style) && style.length !== literal.length)
271
+ return false;
272
+ return Object.keys({ ...style, ...literal }).every(k => k === 'o' ? (style.o ?? 1) === (literal.o ?? 1) : sameStyleValue(style[k], literal[k]));
273
+ }
274
+ /** Writes the shared resources, layer references and mode choices of a saved file.
275
+ * @param result - Reader output retaining the source relationships.
276
+ * @param doc - Converted layers to associate with their definitions.
277
+ * @param occurrences - Original override fields at their native instance paths.
278
+ * @param expanded - Converted instance literals before the linker removes equal fields.
279
+ * @param expandedRadii - Effective corners of instance roots kept as frames.
280
+ * @param report - Receives unsupported bindings and style uses.
281
+ * @param fileId - Stable Figma file key or digest for unpublished resources.
282
+ * @returns Nothing.
283
+ */
284
+ export function fileResources(result, doc, occurrences, expanded, expandedRadii, report, fileId) {
285
+ const { tree, variables, imported, styleLayers, textStyleUses } = result.sources;
286
+ const shared = [];
287
+ const identity = node => ({ name: node.name, key: String(node.change.key || `figma-${fileId()}-${node.id}`) });
288
+ fileVariables(result, shared, identity, report);
289
+ const bySource = new Map(doc.models.map((m) => [m.sourceId, m]));
290
+ const layerSource = new Map(imported.map(({ figma, node }) => [node.id, { figma, node }]));
291
+ const definitions = new Map();
292
+ const byKey = new Map();
293
+ const styleModels = new Set();
294
+ const styleUsers = new Map();
295
+ const records = new Map(doc.models.map(m => [m.id, m]));
296
+ function style(node, record) {
297
+ keepDescription(node, record, report);
298
+ definitions.set(node.id, record);
299
+ byKey.set(record.type + '/' + record.key, record);
300
+ shared.push(record);
301
+ }
302
+ const textDefinitions = new Map();
303
+ for (const [node, use] of textStyleUses) {
304
+ const { id, style: text } = use.shared;
305
+ const { color, ...value } = runStyle(text);
306
+ textDefinitions.set(id, value);
307
+ styleUsers.set(id, []);
308
+ const fields = node.change.variableConsumptionMap?.entries ?? [];
309
+ for (const e of fields)
310
+ if (e.variableField !== 'FONT_SIZE')
311
+ report.push({ kind: 'left-out', what: 'variable binding', count: 1, ids: [id] });
312
+ const entry = fields.find((e) => e.variableField === 'FONT_SIZE');
313
+ const size = entry && variables.positiveLengthOf(entry.variableData, node.id);
314
+ if (entry && !size)
315
+ report.push({ kind: 'left-out', what: 'variable binding', count: 1, ids: [id] });
316
+ style(node, { ...identity(node), id, parent: STYLES, kind: 'style', type: 'text',
317
+ value: size ? { ...value, size: { alias: size } } : value });
318
+ }
319
+ function variableAt(path, data, type, id) {
320
+ const variable = variables.variableOf(data, id);
321
+ const length = path && /^(?:w|h|strokeWidth|look\.stroke\.sides\.[0-3]|opacity|radius(?:\.[0-3])?|look\.(?:layerBlur|backgroundBlur)\.radius|look\.shadows\.\d+\.blur)$/.test(path);
322
+ if (path && 'id' in variable && variable.type === type && (type !== 'number' || (path === 'opacity') === !!variable.opacity)
323
+ && (!length || variables.valuesMatch(variable.id, n => typeof n === 'number' && n >= 0 && (path !== 'opacity' || n <= 1))))
324
+ return variable.id;
325
+ report.push({ kind: 'left-out', what: 'variable binding', count: 1, ids: [id] });
326
+ }
327
+ const binding = (m, target) => (path, data, type) => {
328
+ const variable = variableAt(path, data, type, m.id);
329
+ if (variable)
330
+ target(path, variable);
331
+ };
332
+ for (const [guid, layer] of styleLayers) {
333
+ const node = tree.nodes.get(guid), model = bySource.get(layer.id);
334
+ styleModels.add(model.id);
335
+ styleUsers.set(layer.id, []);
336
+ paintsAndEffects(node.change, model, binding(layer, (path, alias) => {
337
+ const parts = path.split('.'), last = parts.pop();
338
+ parts.reduce((v, part) => v[part], model)[last] = { alias };
339
+ }), result.sources);
340
+ const base = { ...identity(node), id: layer.id, parent: STYLES, kind: 'style' };
341
+ if (node.change.styleType === 'FILL')
342
+ style(node, { ...base, type: 'paint', value: model.look?.fills ?? (model.fill ? [{ k: 'solid', c: model.fill, o: 1 }] : []) });
343
+ else
344
+ style(node, { ...base, type: 'effect', value: { shadows: [], ...model.look } });
345
+ }
346
+ doc.models = doc.models.filter(m => !styleModels.has(m.id));
347
+ const textStyles = new Map(shared.flatMap(r => r.kind === 'style' && r.type === 'text' ? [[r.id, r]] : []));
348
+ function palette(entry, id, occurrence = false) {
349
+ if (!entry.styles)
350
+ return;
351
+ // Expanded palettes may be shared by several linked records. Strip reader metadata on a copy.
352
+ entry.styles = entry.styles.map((source, i) => {
353
+ const { fileFontSize, fileTextColor, filePlainTextColor, fileFillStyle, filePlainFillStyle, ...s } = source;
354
+ const { textStyle, color, paintOpacity, link: _link, figmaHyperlink: _pending, ...local } = s;
355
+ const style = definitions.get(fileFillStyle ?? filePlainFillStyle);
356
+ if (style) {
357
+ styleUsers.get(style.id)?.push(id);
358
+ if (!occurrence) {
359
+ if (filePlainFillStyle)
360
+ lost('instance text paint style kept as plain colour', id);
361
+ else if (supportsRunPaint && style.type === 'paint' && style.value.length === 1 && style.value[0]?.k === 'solid') {
362
+ s.fillStyle = style.id;
363
+ // The style owns both the colour (possibly an alias) and the paint opacity.
364
+ const paint = style.value[0];
365
+ if (Array.isArray(paint.c))
366
+ s.color = paint.c;
367
+ const opacity = paint.visible === false ? 0 : paint.o ?? 1;
368
+ if (opacity !== 1)
369
+ s.paintOpacity = opacity;
370
+ else
371
+ delete s.paintOpacity;
372
+ }
373
+ else
374
+ lost('style reference', id);
375
+ }
376
+ }
377
+ if (!s.fillStyle && fileTextColor !== undefined && !occurrence && (supportsRunPaint || !style)) {
378
+ if (fileTextColor)
379
+ (entry.vars ??= {})[`styles.${i}.color`] = fileTextColor;
380
+ else
381
+ lost('variable binding', id);
382
+ }
383
+ // If linking kept the instance expanded, its explicitly bound paint still becomes a literal.
384
+ if (!occurrence && !filePlainFillStyle && filePlainTextColor !== undefined)
385
+ lost('instance text colour binding kept as plain colour', id);
386
+ if ((occurrence || filePlainTextColor !== undefined || style && !supportsRunPaint) && paintOpacity !== undefined) {
387
+ s.color = [color[0], color[1], color[2], color[3] * paintOpacity];
388
+ delete s.paintOpacity;
389
+ }
390
+ if (textStyle)
391
+ styleUsers.get(textStyle)?.push(id);
392
+ const styleSize = textStyles.get(textStyle)?.value.size;
393
+ const inherited = typeof styleSize === 'object' && styleSize.alias === fileFontSize;
394
+ if (textStyle && (JSON.stringify(local) !== JSON.stringify(textDefinitions.get(textStyle)) || (fileFontSize || fileFontSize === null && typeof styleSize === 'object') && !inherited)) {
395
+ delete s.textStyle;
396
+ report.push({ kind: 'approximated', what: 'text style with local formatting', count: 1, ids: [id] });
397
+ }
398
+ if (fileFontSize === null)
399
+ report.push({ kind: 'left-out', what: 'variable binding', count: 1, ids: [id] });
400
+ else if (fileFontSize && !(inherited && s.textStyle))
401
+ (entry.vars ??= {})['styles.' + i + '.size'] = fileFontSize;
402
+ return s;
403
+ });
404
+ }
405
+ const lost = (what, id) => report.push({ kind: 'left-out', what, count: 1, ids: [id] });
406
+ const isInstance = (m) => m.component && m.component !== m.id;
407
+ const slots = [
408
+ ['styleIdForFill', 'fillStyle', 'paint', 'fillPaints'],
409
+ ['styleIdForStrokeFill', 'strokeStyle', 'paint', 'strokePaints'],
410
+ ['styleIdForEffect', 'effectStyle', 'effect', 'effects'],
411
+ ];
412
+ // A virtual layer takes the main's formatting beneath any explicitly authored paints or effects.
413
+ function appearance(base, entry) {
414
+ const m = { ...base, look: { ...base.look, ...(base.look?.stroke && { stroke: { ...base.look.stroke } }) } };
415
+ if (entry?.['look.fills']) {
416
+ m.look.fills = entry['look.fills'];
417
+ delete m.fill;
418
+ }
419
+ if (entry?.['look.stroke.paint'] && m.look.stroke)
420
+ m.look.stroke.paint = entry['look.stroke.paint'];
421
+ for (const field of ['shadows', 'backgroundBlur', 'layerBlur'])
422
+ if (entry?.['look.' + field])
423
+ m.look[field] = entry['look.' + field];
424
+ return m;
425
+ }
426
+ function installRadius(change, m, root, entry, id, virtual) {
427
+ const expanded = expandedRadii.get(m.sourceId);
428
+ const local = radiusBindings(change);
429
+ const literal = change.cornerRadius !== undefined || corners.some(field => field in change);
430
+ const override = virtual || isInstance(m);
431
+ if ((!expanded || virtual) && !literal && !local.size) {
432
+ if (override && Object.keys(root.vars ?? {}).some(path => path.startsWith('radius.')))
433
+ delete entry.radius;
434
+ return;
435
+ }
436
+ let inherited = override ? expanded ?? radiiOf(layerSource.get(root.sourceId).figma.change) : undefined;
437
+ if (virtual) {
438
+ const parts = id.split(';');
439
+ for (let i = parts.length - 2; i > 0; i--) {
440
+ const inner = occurrences.get(parts[i])?.get(parts.slice(i + 1).join(';'));
441
+ if (inner)
442
+ inherited = radiiOf(inner, inherited);
443
+ }
444
+ }
445
+ const effective = expanded && !virtual ? expanded : radiiOf(change, inherited);
446
+ const values = effective.map(c => c.value);
447
+ const stored = values.every(v => v === values[0]) ? values[0] : values;
448
+ if (isInstance(m)) {
449
+ if (effective.some(c => c.binding))
450
+ delete entry.radius; // A linked root inherits its main's sources.
451
+ else
452
+ entry.radius = stored;
453
+ return;
454
+ }
455
+ const resolved = new Map();
456
+ for (const c of effective)
457
+ if (c.binding && !resolved.has(c.binding.data))
458
+ resolved.set(c.binding.data, variableAt('radius', c.binding.data, 'number', id));
459
+ // A literal masks the entire tuple, so reinstate the unaffected corners' bindings beside it.
460
+ const writeLiteral = !!expanded || override && literal || [...resolved.values()].includes(undefined);
461
+ if (writeLiteral)
462
+ entry.radius = stored;
463
+ else if (override)
464
+ delete entry.radius;
465
+ effective.forEach((c, i) => {
466
+ if (!c.binding || !writeLiteral && inherited?.[i]?.binding === c.binding)
467
+ return;
468
+ const variable = resolved.get(c.binding.data);
469
+ if (variable)
470
+ (entry.vars ??= {})['radius.' + i] = variable;
471
+ });
472
+ }
473
+ function installStrokeSides(change, root, entry, id, instance, virtual) {
474
+ const override = instance || virtual;
475
+ const bindings = new Map(strokeSideBindings(change).map(({ variableField, variableData }) => [variableField, variableData]));
476
+ const key = 'look.stroke.sides';
477
+ const target = ['frame', 'rect'].includes(root.kind) && root.stroke && !root.boolean;
478
+ if (!target && bindings.size === 4) {
479
+ const [first, ...rest] = bindings.values();
480
+ // Shapes without independent widths can still use one common source for the whole stroke.
481
+ if (first !== undefined && rest.every(value => JSON.stringify(value) === JSON.stringify(first))) {
482
+ const variable = variableAt(!instance && root.stroke ? 'strokeWidth' : undefined, first, 'number', id);
483
+ if (variable)
484
+ (entry.vars ??= {}).strokeWidth = variable;
485
+ return;
486
+ }
487
+ }
488
+ const uniform = hasUniformStroke(change);
489
+ const base = root.look?.stroke?.sides ?? Array(4).fill(root.strokeWidth ?? 0);
490
+ const literals = strokeSides.map((side, i) => {
491
+ const value = change[side.field];
492
+ // An INSTANCE record also repeats its root's stored widths, including inherited values.
493
+ const cleared = bindings.has(side.binding) && bindings.get(side.binding) === undefined;
494
+ return override && !virtual && !uniform && !cleared && value === base[i] ? undefined : value;
495
+ });
496
+ const authored = uniform || literals.some(v => v !== undefined) || [...bindings.values()].includes(undefined);
497
+ if (!bindings.size && !(override && target && authored && (entry[key] || root.look?.stroke?.sides)))
498
+ return;
499
+ if (override && target && authored) {
500
+ const previous = entry[key] ?? base;
501
+ entry[key] = literals.map((v, i) => Math.max(0, (uniform ? change.strokeWeight : v) ?? previous[i]));
502
+ }
503
+ for (const [i, side] of strokeSides.entries()) {
504
+ const path = key + '.' + i;
505
+ if (bindings.has(side.binding)) {
506
+ const data = bindings.get(side.binding);
507
+ const variable = data === undefined ? undefined : variableAt(target ? path : undefined, data, 'number', id);
508
+ if (variable)
509
+ (entry.vars ??= {})[path] = variable;
510
+ else if (override && target)
511
+ (entry.vars ??= {})[path] = null;
512
+ }
513
+ else if (override && target && (uniform || literals[i] !== undefined)) {
514
+ (entry.vars ??= {})[path] ??= null;
515
+ }
516
+ }
517
+ }
518
+ // Only frames and pages store mode choices. Other layers have no children, so a choice there changes only the
519
+ // layer's own bindings: through its variables, its styles' aliases and the aliases those variables follow.
520
+ let sharedById;
521
+ // Choices left unreported on a main's layer, by layer id: an instance override can still bind that layer.
522
+ const unused = new Map();
523
+ const occurrenceModes = new Map();
524
+ function consultsCollection(layer, collection) {
525
+ sharedById ??= new Map(shared.map(r => [r.id, r]));
526
+ const queue = [], seen = new Set();
527
+ const aliases = (value) => {
528
+ if (!value || typeof value !== 'object')
529
+ return;
530
+ if (typeof value.alias === 'string')
531
+ queue.push(value.alias);
532
+ for (const inner of Object.values(value))
533
+ aliases(inner);
534
+ };
535
+ for (const ref of Object.values(layer.vars ?? {}))
536
+ if (typeof ref === 'string')
537
+ queue.push(ref);
538
+ for (const slot of Object.keys(styled))
539
+ if (typeof layer[slot] === 'string')
540
+ queue.push(layer[slot]);
541
+ for (const run of layer.styles ?? []) {
542
+ if (run.textStyle)
543
+ queue.push(run.textStyle);
544
+ if (run.fillStyle)
545
+ queue.push(run.fillStyle);
546
+ }
547
+ while (queue.length) {
548
+ const id = queue.pop();
549
+ if (seen.has(id))
550
+ continue;
551
+ seen.add(id);
552
+ const record = sharedById.get(id);
553
+ if (record?.kind === 'variable') {
554
+ if (record.parent === collection)
555
+ return true;
556
+ aliases(record.values);
557
+ }
558
+ else if (record?.kind === 'style')
559
+ aliases(record.value);
560
+ }
561
+ return false;
562
+ }
563
+ // Occurrence entries that name a style, masked once every entry holds its own bindings.
564
+ const masked = [];
565
+ const styled = {
566
+ fillStyle: ['look.fills'],
567
+ strokeStyle: ['look.stroke.paint'],
568
+ effectStyle: ['look.shadows', 'look.layerBlur', 'look.backgroundBlur'],
569
+ };
570
+ function* occurrenceSources(id, outermost) {
571
+ const parts = id.split(';');
572
+ const layer = records.get(parts.at(-1));
573
+ if (layer && isInstance(layer)) {
574
+ yield records.get(layer.component);
575
+ yield layer;
576
+ yield layer.overrides?.[''];
577
+ }
578
+ else
579
+ yield layer;
580
+ for (let i = parts.length - 2; i >= (outermost ? 0 : 1); i--)
581
+ yield records.get(parts[i])?.overrides?.[parts.slice(i + 1).join(';')];
582
+ }
583
+ /** Variable paths bound on a virtual layer beneath its outermost instance: its main layer, then inner instances.
584
+ * A mask at an inner level still counts, so the outer mask holds if that inner style is later detached. */
585
+ function inheritedBindings(id) {
586
+ const paths = new Set();
587
+ for (const source of occurrenceSources(id, false))
588
+ for (const [path, ref] of Object.entries(source?.vars ?? {}))
589
+ if (ref)
590
+ paths.add(path);
591
+ return paths;
592
+ }
593
+ function install(change, m, into, id, virtual = false) {
594
+ const instance = isInstance(m);
595
+ const root = instance ? records.get(m.component) : m;
596
+ const rootBindings = instance ? new Set() : undefined;
597
+ const paint = instance ? appearance(root, m.overrides?.['']) : virtual ? appearance(m, into) : m;
598
+ const lists = { fillPaints: change.fillPaints, strokePaints: change.strokePaints, effects: change.effects };
599
+ for (const [field, slot, type, list] of slots) {
600
+ const ref = change[field];
601
+ if (!ref || m.kind === 'text' && slot === 'fillStyle')
602
+ continue;
603
+ let style = ref.guid ? definitions.get(guidText(ref.guid, field)) : undefined;
604
+ if (style?.type !== type)
605
+ style = byKey.get(type + '/' + ref.assetRef?.key);
606
+ const fills = paint.look?.fills ?? (paint.fill ? [{ k: 'solid', c: paint.fill, o: 1 }] : []);
607
+ const stroke = paint.look?.stroke?.paint ?? (paint.stroke && { k: 'solid', c: paint.stroke, o: 1 });
608
+ const effects = style?.type === 'effect' && {
609
+ shadows: paint.look?.shadows ?? [],
610
+ layerBlur: paint.look?.layerBlur ?? (style.value.layerBlur && { radius: 0 }),
611
+ backgroundBlur: paint.look?.backgroundBlur ?? (style.value.backgroundBlur && { radius: 0 }),
612
+ };
613
+ if (style && !isDetachedStyle(ref))
614
+ styleUsers.get(style.id)?.push(id);
615
+ const differs = style?.type === 'paint' && !sameStyleValue(style.value, slot === 'fillStyle' ? fills : stroke ? [stroke] : [])
616
+ || style?.type === 'effect' && !sameStyleValue(style.value, effects);
617
+ if (isDetachedStyle(ref) || !style || differs) {
618
+ if (differs)
619
+ lost('style reference', id);
620
+ if (virtual && !instance && m[slot]) {
621
+ into[slot] = null;
622
+ if (slot === 'fillStyle')
623
+ into['look.fills'] = fills;
624
+ else if (slot === 'strokeStyle' && paint.look.stroke)
625
+ into['look.stroke.paint'] = stroke;
626
+ else if (slot === 'effectStyle') {
627
+ into['look.shadows'] = paint.look.shadows ?? [];
628
+ into['look.layerBlur'] = paint.look.layerBlur ?? { radius: 0 };
629
+ into['look.backgroundBlur'] = paint.look.backgroundBlur ?? { radius: 0 };
630
+ }
631
+ }
632
+ continue;
633
+ }
634
+ if (m.kind === 'text' || instance && root[slot] !== style.id
635
+ || slot === 'strokeStyle' && (!paint.look?.stroke || style.type !== 'paint' || style.value.length !== 1)) {
636
+ lost('style reference', id);
637
+ }
638
+ else {
639
+ if (!instance) {
640
+ into[slot] = style.id;
641
+ if (virtual)
642
+ masked.push([into, id, slot]);
643
+ }
644
+ delete lists[list]; // Variable-backed paints in a named style are authored on its definition.
645
+ }
646
+ }
647
+ const rootEntry = instance && !virtual ? m.overrides?.[''] ?? {} : into;
648
+ if (['frame', 'rect'].includes(m.kind))
649
+ installRadius(change, m, root, rootEntry, id, virtual);
650
+ installStrokeSides(change, root, rootEntry, id, instance, virtual);
651
+ const bind = binding({ id }, (path, variable) => {
652
+ if (virtual && (['w', 'h'].includes(path) || path.startsWith('layoutData.'))
653
+ || instance && (path.startsWith('look.') || path === 'strokeWidth')) {
654
+ if (root.vars?.[path] !== variable)
655
+ lost('variable binding', id);
656
+ else
657
+ rootBindings?.add(path);
658
+ return;
659
+ }
660
+ (into.vars ??= {})[path] = variable;
661
+ if (virtual && path.startsWith('look.fills.') && !root.look?.fills)
662
+ into['look.fills'] = paint.look.fills;
663
+ if (virtual && path.startsWith('look.stroke.paint.') && !root.look?.stroke?.paint)
664
+ into['look.stroke.paint'] = paint.look.stroke.paint;
665
+ });
666
+ if (virtual && m.kind === 'text' && !m.bind?.content && change.variableConsumptionMap?.entries?.some((entry) => entry.variableField === 'TEXT_DATA' && entry.variableData === undefined)) {
667
+ // A field-only occurrence entry clears the inherited binding even when the linker found identical text.
668
+ (into.vars ??= {}).content = null;
669
+ into.content ??= expanded.get(id)?.content ?? m.content;
670
+ }
671
+ layerFields(change, m, bind);
672
+ paintsAndEffects(lists, paint, bind, result.sources);
673
+ for (const range of change.textData?.styleOverrideTable ?? []) {
674
+ const glyphPaint = textColor(range.fillPaints ?? []).paint;
675
+ for (const field of range.variableConsumptionMap?.entries ?? [])
676
+ if (field.variableField !== 'FONT_SIZE')
677
+ lost('variable binding', id);
678
+ for (const fill of range.fillPaints ?? []) {
679
+ if (fill.colorVar && fill !== glyphPaint)
680
+ lost('variable binding', id);
681
+ if (fill.opacityVar)
682
+ lost('variable binding', id);
683
+ for (const stop of fill.stopsVar ?? [])
684
+ if (stop.colorVar)
685
+ lost('variable binding', id);
686
+ }
687
+ }
688
+ if (rootBindings && !virtual) {
689
+ inheritedLiterals(rootEntry, root, change, expanded.get(id), rootBindings);
690
+ if (Object.keys(rootEntry).length)
691
+ (m.overrides ??= {})[''] = rootEntry;
692
+ }
693
+ const chosen = new Set();
694
+ if (change.variableModeBySetMap)
695
+ for (const choice of change.variableModeBySetMap.entries ?? []) {
696
+ const mode = variables.modeOf(choice, id);
697
+ if (typeof mode === 'string')
698
+ lost('variable mode', id);
699
+ else if (['page', 'frame'].includes(m.kind))
700
+ (into.modes ??= {})[mode.collectionId] = mode.modeId;
701
+ else if (virtual)
702
+ chosen.add(mode.collectionId);
703
+ else if (consultsCollection(m, mode.collectionId))
704
+ lost('variable mode', id);
705
+ else
706
+ unused.set(m.id, (unused.get(m.id) ?? new Set()).add(mode.collectionId));
707
+ }
708
+ if (virtual) {
709
+ for (const collection of unused.get(m.id) ?? [])
710
+ chosen.add(collection);
711
+ if (chosen.size)
712
+ occurrenceModes.set(id, chosen);
713
+ }
714
+ }
715
+ // Instance appearance comes from its main, which may live on a later page.
716
+ const layers = doc.models;
717
+ const mainLayers = new Map(layers.filter(m => m.component === m.id).map(m => [m.sourceId, m]));
718
+ const mains = new Map(result.components.map(c => [c.id, mainLayers.get(c.rootId)]));
719
+ function expandedFields(m, change) {
720
+ const source = layerSource.get(m.sourceId);
721
+ if (expandedRadii.has(m.sourceId) && source.node.type === 'instance') {
722
+ const main = mains.get(source.node.componentId);
723
+ const original = layerSource.get(main.sourceId).figma.change;
724
+ change = { ...change };
725
+ // The linked root would inherit its main's formatting. Keep those same literals and sources on the frame.
726
+ for (const [ref, slot, , list] of slots) {
727
+ if (ref in change || list in change)
728
+ continue;
729
+ if (ref in original)
730
+ change[ref] = original[ref];
731
+ if (list in original)
732
+ change[list] = original[list];
733
+ const keys = slot === 'fillStyle' ? ['fill'] : slot === 'strokeStyle' ? ['stroke', 'strokeWidth'] : [];
734
+ const look = slot === 'fillStyle' ? ['fills'] : slot === 'strokeStyle' ? ['stroke'] : ['shadows', 'layerBlur', 'backgroundBlur'];
735
+ for (const key of keys)
736
+ if (main[key] !== undefined)
737
+ m[key] = main[key];
738
+ for (const key of look)
739
+ if (main.look?.[key] !== undefined)
740
+ (m.look ??= {})[key] = structuredClone(main.look[key]);
741
+ }
742
+ if (m.stroke) {
743
+ const own = change.variableConsumptionMap?.entries ?? [];
744
+ const uniform = hasUniformStroke(change);
745
+ const base = main.look?.stroke?.sides ?? Array(4).fill(main.strokeWidth ?? 0);
746
+ const literals = strokeSides.map(({ field }) => uniform ? change.strokeWeight : change[field]);
747
+ const inherited = strokeSideBindings(original).filter(({ variableField }) => !uniform && !own.some((entry) => entry.variableField === variableField) &&
748
+ !strokeSides.some(({ binding }, i) => binding === variableField && literals[i] !== undefined && literals[i] !== base[i]));
749
+ if (inherited.length)
750
+ change.variableConsumptionMap = { ...change.variableConsumptionMap, entries: [...inherited, ...own] };
751
+ if (literals.some(v => v !== undefined)) {
752
+ const stroke = { position: 0, ...m.look?.stroke };
753
+ const previous = stroke.sides ?? base;
754
+ stroke.sides = literals.map((value, i) => Math.max(0, value ?? previous[i]));
755
+ (m.look ??= {}).stroke = stroke;
756
+ }
757
+ }
758
+ }
759
+ const path = [m.sourceId];
760
+ for (let parent = records.get(m.parent); parent; parent = records.get(parent.parent)) {
761
+ if (expandedRadii.has(parent.sourceId)) {
762
+ const own = result.sources.occurrenceFields.get(parent.sourceId)?.get(layerPathKey(path));
763
+ if (own) {
764
+ change = { ...change, ...own };
765
+ for (const [ref, list] of STYLE_REFERENCE_FIELDS)
766
+ if (list in own && !(ref in own))
767
+ delete change[ref];
768
+ }
769
+ }
770
+ if (layerSource.get(parent.sourceId)?.node.type === 'instance')
771
+ path.unshift(parent.sourceId);
772
+ }
773
+ return change;
774
+ }
775
+ for (const m of [...layers.filter(m => !isInstance(m)), ...layers.filter(isInstance)]) {
776
+ palette(m, m.id);
777
+ const source = layerSource.get(m.sourceId);
778
+ if (source)
779
+ install(expandedRadii.size ? expandedFields(m, source.figma.change) : source.figma.change, m, m, m.id);
780
+ }
781
+ for (const m of layers) {
782
+ const authored = occurrences.get(m.id);
783
+ const paths = new Set([...Object.keys(m.overrides ?? {}), ...authored?.keys() ?? []]);
784
+ for (const path of paths) {
785
+ const id = m.id + ';' + path, entry = m.overrides?.[path] ?? {};
786
+ const change = authored?.get(path);
787
+ const target = path ? records.get(path.split(';').at(-1)) : m;
788
+ if (target?.kind === 'text' && change) {
789
+ const textData = change.textData;
790
+ const painted = [change, ...(textData?.styleOverrideTable ?? [])].filter(fields => fields.fillPaints !== undefined || fields.styleIdForFill !== undefined);
791
+ // Even an explicitly painted run that looks identical to its main is a plain override.
792
+ const layer = expanded.get(id);
793
+ if (painted.length && layer?.styles) {
794
+ // The linker packs a full text body for a paint difference. Only authored wording owns the characters.
795
+ if (textData?.characters !== undefined)
796
+ entry.content = layer.content;
797
+ else
798
+ delete entry.content;
799
+ entry.styles ??= layer.styles;
800
+ entry.styleAt ??= styleAtOf(layer);
801
+ for (const fields of painted) {
802
+ const style = fields.styleIdForFill && result.sources.styleNodeFor(fields.styleIdForFill, 'FILL');
803
+ const fills = style?.change.fillPaints ?? fields.fillPaints ?? [];
804
+ if (style || target.styles?.some((s) => s.fillStyle))
805
+ lost('instance text paint style kept as plain colour', id);
806
+ else if (textColor(fills).paint?.colorVar)
807
+ lost('instance text colour binding kept as plain colour', id);
808
+ }
809
+ }
810
+ }
811
+ palette(entry, id, true);
812
+ if (path && target && !isInstance(target)) {
813
+ inheritedLiterals(entry, target, change ?? {}, expanded.get(id));
814
+ if (!change && Object.keys(target.vars ?? {}).some(key => key.startsWith('radius.')))
815
+ delete entry.radius;
816
+ }
817
+ if (change && target)
818
+ install(change, target, path ? entry : m, path ? id : m.id, !!path);
819
+ if (Object.keys(entry).length)
820
+ (m.overrides ??= {})[path] = entry;
821
+ else if (m.overrides)
822
+ delete m.overrides[path];
823
+ }
824
+ }
825
+ // A style override replaces the slot as Figma does: bindings the occurrence inherits there no longer apply.
826
+ for (const [entry, id, slot] of masked)
827
+ for (const path of inheritedBindings(id))
828
+ if (styled[slot].some(p => path.startsWith(p + '.')) && !Object.hasOwn(entry.vars ?? {}, path))
829
+ (entry.vars ??= {})[path] = null;
830
+ for (const [id, choices] of occurrenceModes) {
831
+ let layer = {};
832
+ for (const source of occurrenceSources(id, true))
833
+ if (source)
834
+ layer = { ...layer, ...source, vars: { ...layer.vars, ...source.vars } };
835
+ for (const collection of choices)
836
+ if (consultsCollection(layer, collection))
837
+ lost('variable mode', id);
838
+ }
839
+ // A definition can be unused. Diagnostics for its bindings select only actual layer users.
840
+ for (const entry of report) {
841
+ if (!entry.ids?.some(id => styleUsers.has(id)))
842
+ continue;
843
+ const users = entry.ids.flatMap(id => styleUsers.get(id) ?? [id]);
844
+ if (users.length)
845
+ entry.ids = users;
846
+ else
847
+ delete entry.ids;
848
+ }
849
+ if (shared.length)
850
+ doc.shared = shared;
851
+ }