figme-mcp 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +447 -0
  3. package/dist/cache.d.ts +29 -0
  4. package/dist/cache.js +68 -0
  5. package/dist/fig/bytebuffer.d.ts +31 -0
  6. package/dist/fig/bytebuffer.js +98 -0
  7. package/dist/fig/container.d.ts +32 -0
  8. package/dist/fig/container.js +80 -0
  9. package/dist/fig/imagemeta.d.ts +17 -0
  10. package/dist/fig/imagemeta.js +96 -0
  11. package/dist/fig/invariants.d.ts +10 -0
  12. package/dist/fig/invariants.js +63 -0
  13. package/dist/fig/kiwi.d.ts +38 -0
  14. package/dist/fig/kiwi.js +144 -0
  15. package/dist/fig/parse.d.ts +37 -0
  16. package/dist/fig/parse.js +91 -0
  17. package/dist/fig/zip.d.ts +23 -0
  18. package/dist/fig/zip.js +95 -0
  19. package/dist/mcp/create.d.ts +12 -0
  20. package/dist/mcp/create.js +48 -0
  21. package/dist/mcp/respond.d.ts +76 -0
  22. package/dist/mcp/respond.js +124 -0
  23. package/dist/mcp/server.d.ts +3 -0
  24. package/dist/mcp/server.js +22 -0
  25. package/dist/mcp/tools/blob.d.ts +7 -0
  26. package/dist/mcp/tools/blob.js +55 -0
  27. package/dist/mcp/tools/components.d.ts +7 -0
  28. package/dist/mcp/tools/components.js +54 -0
  29. package/dist/mcp/tools/context.d.ts +24 -0
  30. package/dist/mcp/tools/context.js +48 -0
  31. package/dist/mcp/tools/find.d.ts +7 -0
  32. package/dist/mcp/tools/find.js +97 -0
  33. package/dist/mcp/tools/image.d.ts +6 -0
  34. package/dist/mcp/tools/image.js +100 -0
  35. package/dist/mcp/tools/instance.d.ts +7 -0
  36. package/dist/mcp/tools/instance.js +44 -0
  37. package/dist/mcp/tools/node.d.ts +7 -0
  38. package/dist/mcp/tools/node.js +49 -0
  39. package/dist/mcp/tools/overview.d.ts +7 -0
  40. package/dist/mcp/tools/overview.js +45 -0
  41. package/dist/mcp/tools/render.d.ts +6 -0
  42. package/dist/mcp/tools/render.js +128 -0
  43. package/dist/mcp/tools/style.d.ts +7 -0
  44. package/dist/mcp/tools/style.js +38 -0
  45. package/dist/mcp/tools/text.d.ts +7 -0
  46. package/dist/mcp/tools/text.js +89 -0
  47. package/dist/mcp/tools/tree.d.ts +7 -0
  48. package/dist/mcp/tools/tree.js +100 -0
  49. package/dist/mcp/tools/variables.d.ts +7 -0
  50. package/dist/mcp/tools/variables.js +71 -0
  51. package/dist/model/access.d.ts +28 -0
  52. package/dist/model/access.js +106 -0
  53. package/dist/model/components.d.ts +72 -0
  54. package/dist/model/components.js +157 -0
  55. package/dist/model/index.d.ts +73 -0
  56. package/dist/model/index.js +192 -0
  57. package/dist/model/instance.d.ts +87 -0
  58. package/dist/model/instance.js +208 -0
  59. package/dist/model/summarize.d.ts +83 -0
  60. package/dist/model/summarize.js +541 -0
  61. package/dist/model/text.d.ts +29 -0
  62. package/dist/model/text.js +61 -0
  63. package/dist/model/tree.d.ts +47 -0
  64. package/dist/model/tree.js +89 -0
  65. package/dist/model/variables.d.ts +50 -0
  66. package/dist/model/variables.js +141 -0
  67. package/dist/render/bounds.d.ts +64 -0
  68. package/dist/render/bounds.js +173 -0
  69. package/dist/render/color.d.ts +20 -0
  70. package/dist/render/color.js +41 -0
  71. package/dist/render/effects.d.ts +34 -0
  72. package/dist/render/effects.js +196 -0
  73. package/dist/render/export.d.ts +51 -0
  74. package/dist/render/export.js +573 -0
  75. package/dist/render/index.d.ts +42 -0
  76. package/dist/render/index.js +94 -0
  77. package/dist/render/instance.d.ts +12 -0
  78. package/dist/render/instance.js +72 -0
  79. package/dist/render/matrix.d.ts +46 -0
  80. package/dist/render/matrix.js +94 -0
  81. package/dist/render/node.d.ts +41 -0
  82. package/dist/render/node.js +95 -0
  83. package/dist/render/paint.d.ts +27 -0
  84. package/dist/render/paint.js +301 -0
  85. package/dist/render/path.d.ts +42 -0
  86. package/dist/render/path.js +156 -0
  87. package/dist/render/raster.d.ts +31 -0
  88. package/dist/render/raster.js +69 -0
  89. package/dist/render/report.d.ts +72 -0
  90. package/dist/render/report.js +106 -0
  91. package/dist/render/style.d.ts +31 -0
  92. package/dist/render/style.js +67 -0
  93. package/dist/render/svg.d.ts +60 -0
  94. package/dist/render/svg.js +150 -0
  95. package/dist/render/text.d.ts +50 -0
  96. package/dist/render/text.js +90 -0
  97. package/package.json +47 -0
@@ -0,0 +1,541 @@
1
+ import { nodeImageHashes } from './index.js';
2
+ import { breadcrumb, guidKey } from './tree.js';
3
+ import { assetRefString, bool, bytes, colorHex, compact, hex, jsonSafe, num, obj, objArr, r2, str, } from './access.js';
4
+ import { describeVariableData } from './variables.js';
5
+ export function summarize(t, opts = {}) {
6
+ const size = obj(t.node, 'size');
7
+ const w = num(size, 'x');
8
+ const h = num(size, 'y');
9
+ return compact({
10
+ guid: t.key,
11
+ type: str(t.node, 'type') ?? 'UNKNOWN',
12
+ name: str(t.node, 'name'),
13
+ size: w !== undefined && h !== undefined ? `${r2(w)}x${r2(h)}` : undefined,
14
+ children: t.children.length || undefined,
15
+ page: opts.page && t.page ? str(t.page.node, 'name') : undefined,
16
+ });
17
+ }
18
+ /** `[FRAME] 134x40 "Frame 39" (2:1339) x3` — ~4x denser than the JSON summary. */
19
+ export function outlineLine(t, depth) {
20
+ const s = summarize(t);
21
+ const parts = [`${' '.repeat(depth)}[${s.type}]`];
22
+ if (s.size)
23
+ parts.push(s.size);
24
+ parts.push(JSON.stringify(s.name ?? ''));
25
+ parts.push(`(${s.guid})`);
26
+ if (s.children)
27
+ parts.push(`x${s.children}`);
28
+ return parts.join(' ');
29
+ }
30
+ // --------------------------------------------------------------------------- geometry
31
+ function rotationDegrees(m) {
32
+ const m00 = num(m, 'm00');
33
+ const m10 = num(m, 'm10');
34
+ if (m00 === undefined || m10 === undefined)
35
+ return undefined;
36
+ const deg = (Math.atan2(m10, m00) * 180) / Math.PI;
37
+ return Math.abs(deg) < 0.01 ? undefined : r2(deg);
38
+ }
39
+ /** Origin of the node in its page's coordinate space (§9.3: compose transforms down the tree). */
40
+ export function absoluteOrigin(t) {
41
+ let x = 0;
42
+ let y = 0;
43
+ let seen = false;
44
+ for (let cur = t; cur; cur = cur.parent) {
45
+ const type = str(cur.node, 'type');
46
+ if (type === 'CANVAS' || type === 'DOCUMENT')
47
+ break;
48
+ const m = obj(cur.node, 'transform');
49
+ if (!m)
50
+ continue;
51
+ seen = true;
52
+ const nx = (num(m, 'm00') ?? 1) * x + (num(m, 'm01') ?? 0) * y + (num(m, 'm02') ?? 0);
53
+ const ny = (num(m, 'm10') ?? 0) * x + (num(m, 'm11') ?? 1) * y + (num(m, 'm12') ?? 0);
54
+ x = nx;
55
+ y = ny;
56
+ }
57
+ return seen ? { x: r2(x), y: r2(y) } : undefined;
58
+ }
59
+ function geometryOf(t) {
60
+ const node = t.node;
61
+ const size = obj(node, 'size');
62
+ const m = obj(node, 'transform');
63
+ const abs = absoluteOrigin(t);
64
+ const g = compact({
65
+ width: r2(num(size, 'x')),
66
+ height: r2(num(size, 'y')),
67
+ x: r2(num(m, 'm02')),
68
+ y: r2(num(m, 'm12')),
69
+ absoluteX: abs?.x,
70
+ absoluteY: abs?.y,
71
+ rotation: rotationDegrees(m),
72
+ });
73
+ return Object.keys(g).length ? g : undefined;
74
+ }
75
+ function cornerRadiusOf(node) {
76
+ const uniform = num(node, 'cornerRadius');
77
+ if (!bool(node, 'rectangleCornerRadiiIndependent'))
78
+ return r2(uniform);
79
+ const corners = [
80
+ num(node, 'rectangleTopLeftCornerRadius') ?? uniform ?? 0,
81
+ num(node, 'rectangleTopRightCornerRadius') ?? uniform ?? 0,
82
+ num(node, 'rectangleBottomRightCornerRadius') ?? uniform ?? 0,
83
+ num(node, 'rectangleBottomLeftCornerRadius') ?? uniform ?? 0,
84
+ ].map((v) => r2(v));
85
+ return corners.every((v) => v === corners[0]) ? corners[0] : corners;
86
+ }
87
+ // --------------------------------------------------------------------------- paints & effects
88
+ export function paintView(idx, p) {
89
+ const image = obj(p, 'image');
90
+ const stops = objArr(p, 'stops').map((s) => compact({ at: r2(num(s, 'position')), color: colorHex(obj(s, 'color')) }));
91
+ const w = num(p, 'originalImageWidth');
92
+ const h = num(p, 'originalImageHeight');
93
+ return compact({
94
+ type: str(p, 'type'),
95
+ color: colorHex(obj(p, 'color')),
96
+ opacity: num(p, 'opacity') === 1 ? undefined : r2(num(p, 'opacity')),
97
+ visible: bool(p, 'visible') === false ? false : undefined,
98
+ blendMode: str(p, 'blendMode') === 'NORMAL' ? undefined : str(p, 'blendMode'),
99
+ stops: stops.length ? stops : undefined,
100
+ imageHash: hex(bytes(image, 'hash')),
101
+ imageName: str(image, 'name'),
102
+ imageScaleMode: str(p, 'imageScaleMode'),
103
+ imageSize: w !== undefined && h !== undefined ? `${w}x${h}` : undefined,
104
+ colorVar: describeVariableData(idx, obj(p, 'colorVar')),
105
+ opacityVar: describeVariableData(idx, obj(p, 'opacityVar')),
106
+ imageVar: describeVariableData(idx, obj(p, 'imageVar')),
107
+ });
108
+ }
109
+ export function effectView(idx, e) {
110
+ const offset = obj(e, 'offset');
111
+ const hasOffset = offset !== undefined && (num(offset, 'x') !== 0 || num(offset, 'y') !== 0);
112
+ return compact({
113
+ type: str(e, 'type'),
114
+ color: colorHex(obj(e, 'color')),
115
+ offset: hasOffset ? { x: r2(num(offset, 'x')), y: r2(num(offset, 'y')) } : undefined,
116
+ radius: r2(num(e, 'radius')),
117
+ spread: num(e, 'spread') ? r2(num(e, 'spread')) : undefined,
118
+ visible: bool(e, 'visible') === false ? false : undefined,
119
+ blendMode: str(e, 'blendMode') === 'NORMAL' ? undefined : str(e, 'blendMode'),
120
+ showShadowBehindNode: bool(e, 'showShadowBehindNode') || undefined,
121
+ colorVar: describeVariableData(idx, obj(e, 'colorVar')),
122
+ radiusVar: describeVariableData(idx, obj(e, 'radiusVar')),
123
+ });
124
+ }
125
+ /**
126
+ * Figma stores the left/top pair in `stackHorizontalPadding`/`stackVerticalPadding` and only
127
+ * writes `stackPaddingRight`/`stackPaddingBottom` when the box is asymmetric (§9.5).
128
+ */
129
+ export function paddingOf(node) {
130
+ const uniform = num(node, 'stackPadding');
131
+ const left = num(node, 'stackHorizontalPadding') ?? uniform;
132
+ const top = num(node, 'stackVerticalPadding') ?? uniform;
133
+ const right = num(node, 'stackPaddingRight') ?? left;
134
+ const bottom = num(node, 'stackPaddingBottom') ?? top;
135
+ if (left === undefined && top === undefined && right === undefined && bottom === undefined) {
136
+ return undefined;
137
+ }
138
+ return {
139
+ top: r2(top ?? 0),
140
+ right: r2(right ?? 0),
141
+ bottom: r2(bottom ?? 0),
142
+ left: r2(left ?? 0),
143
+ };
144
+ }
145
+ function autoLayoutOf(node) {
146
+ const mode = str(node, 'stackMode');
147
+ if (!mode || mode === 'NONE')
148
+ return undefined;
149
+ return compact({
150
+ mode,
151
+ spacing: r2(num(node, 'stackSpacing')),
152
+ counterSpacing: r2(num(node, 'stackCounterSpacing')),
153
+ padding: paddingOf(node),
154
+ primaryAlign: str(node, 'stackPrimaryAlignItems'),
155
+ counterAlign: str(node, 'stackCounterAlignItems'),
156
+ counterAlignContent: str(node, 'stackCounterAlignContent'),
157
+ primarySizing: str(node, 'stackPrimarySizing'),
158
+ width: str(node, 'stackWidth'),
159
+ height: str(node, 'stackHeight'),
160
+ wrap: str(node, 'stackWrap'),
161
+ reverseZIndex: bool(node, 'stackReverseZIndex') || undefined,
162
+ });
163
+ }
164
+ function layoutChildOf(node) {
165
+ const margin = compact({
166
+ top: r2(num(node, 'stackChildMarginTop')),
167
+ right: r2(num(node, 'stackChildMarginRight')),
168
+ bottom: r2(num(node, 'stackChildMarginBottom')),
169
+ left: r2(num(node, 'stackChildMarginLeft')),
170
+ });
171
+ return orUndefined(compact({
172
+ grow: num(node, 'stackChildPrimaryGrow'),
173
+ alignSelf: str(node, 'stackChildAlignSelf'),
174
+ positioning: str(node, 'stackPositioning'),
175
+ margin: Object.keys(margin).length ? margin : undefined,
176
+ }));
177
+ }
178
+ // --------------------------------------------------------------------------- text
179
+ /** `{value, units}` rendered compactly: `"1.5"` (RAW multiplier), `"13px"`, `"150%"`. */
180
+ export function lengthString(o) {
181
+ if (!o)
182
+ return undefined;
183
+ const v = num(o, 'value');
184
+ if (v === undefined)
185
+ return undefined;
186
+ switch (str(o, 'units')) {
187
+ case 'PIXELS':
188
+ return `${r2(v)}px`;
189
+ case 'PERCENT':
190
+ return `${r2(v)}%`;
191
+ default:
192
+ return String(r2(v));
193
+ }
194
+ }
195
+ const CHARACTERS_PREVIEW = 400;
196
+ export function textBasics(node) {
197
+ const textData = obj(node, 'textData');
198
+ const font = obj(node, 'fontName');
199
+ const characters = str(textData, 'characters');
200
+ if (!textData && !font && characters === undefined)
201
+ return undefined;
202
+ const truncated = characters !== undefined && characters.length > CHARACTERS_PREVIEW;
203
+ const overrides = objArr(textData, 'styleOverrideTable').length;
204
+ return orUndefined(compact({
205
+ characters: truncated ? `${characters.slice(0, CHARACTERS_PREVIEW)}...` : characters,
206
+ characterCount: truncated ? characters.length : undefined,
207
+ charactersTruncated: truncated || undefined,
208
+ font: font ? `${str(font, 'family') ?? ''} ${str(font, 'style') ?? ''}`.trim() : undefined,
209
+ fontSize: r2(num(node, 'fontSize')),
210
+ lineHeight: lengthString(obj(node, 'lineHeight')),
211
+ letterSpacing: lengthString(obj(node, 'letterSpacing')),
212
+ paragraphSpacing: r2(num(node, 'paragraphSpacing')),
213
+ align: str(node, 'textAlignHorizontal'),
214
+ verticalAlign: str(node, 'textAlignVertical'),
215
+ textCase: str(node, 'textCase'),
216
+ textDecoration: str(node, 'textDecoration'),
217
+ autoResize: str(node, 'textAutoResize'),
218
+ styleOverrides: overrides || undefined,
219
+ }));
220
+ }
221
+ // --------------------------------------------------------------------------- refs
222
+ const STYLE_REF_FIELDS = {
223
+ styleIdForFill: 'fill',
224
+ styleIdForStrokeFill: 'stroke',
225
+ styleIdForText: 'text',
226
+ styleIdForEffect: 'effect',
227
+ styleIdForGrid: 'grid',
228
+ };
229
+ /**
230
+ * Shared-style references.
231
+ *
232
+ * A style definition is stored as an ordinary (hidden) node parked on a canvas, carrying the
233
+ * publishable `key` that `styleIdFor*.assetRef.key` points at — text styles are TEXT nodes, fill
234
+ * styles are ROUNDED_RECTANGLE nodes. So a style used from the same file resolves to a real node
235
+ * and, with `resolve`, to the values it defines. Styles from other libraries stay opaque refs.
236
+ */
237
+ export function styleRefsOf(idx, node, opts = {}) {
238
+ const out = {};
239
+ for (const [field, label] of Object.entries(STYLE_REF_FIELDS)) {
240
+ const ref = obj(node, field);
241
+ if (!ref)
242
+ continue;
243
+ const local = idx.resolveAssetRef(ref);
244
+ const guid = guidKey(obj(ref, 'guid'));
245
+ out[label] = compact({
246
+ name: local ? str(local.node, 'name') : undefined,
247
+ guid: local?.key ?? guid,
248
+ assetRef: assetRefString(ref),
249
+ defines: opts.resolve && local ? styleDefinition(idx, label, local.node) : undefined,
250
+ });
251
+ }
252
+ return orUndefined(out);
253
+ }
254
+ /** The values a locally-defined style carries: typography for text, paints for fill/stroke. */
255
+ function styleDefinition(idx, label, definition) {
256
+ if (label === 'text')
257
+ return orUndefined(typography(idx, definition));
258
+ if (label === 'effect') {
259
+ const effects = objArr(definition, 'effects').map((e) => effectView(idx, e));
260
+ return effects.length ? { effects } : undefined;
261
+ }
262
+ const paints = objArr(definition, label === 'stroke' ? 'strokePaints' : 'fillPaints');
263
+ const views = paints.map((p) => paintView(idx, p));
264
+ return views.length ? { paints: views } : undefined;
265
+ }
266
+ /** Every `*Var` binding set directly on the node, plus its variable-consumption maps. */
267
+ export function variableBindingsOf(idx, node) {
268
+ const out = {};
269
+ for (const [key, value] of Object.entries(node)) {
270
+ if (!key.endsWith('Var'))
271
+ continue;
272
+ if (!value || typeof value !== 'object' || Array.isArray(value) || value instanceof Uint8Array) {
273
+ continue;
274
+ }
275
+ const described = describeVariableData(idx, value);
276
+ if (described !== undefined)
277
+ out[key] = described;
278
+ }
279
+ for (const map of ['variableConsumptionMap', 'parameterConsumptionMap']) {
280
+ for (const entry of objArr(obj(node, map), 'entries')) {
281
+ const field = str(entry, 'variableField');
282
+ const described = describeVariableData(idx, obj(entry, 'variableData'));
283
+ if (field && described !== undefined)
284
+ out[field] = described;
285
+ }
286
+ }
287
+ return orUndefined(out);
288
+ }
289
+ function componentOf(idx, t) {
290
+ const node = t.node;
291
+ const type = str(node, 'type');
292
+ if (type === 'INSTANCE') {
293
+ const symbolData = obj(node, 'symbolData');
294
+ const symbolId = guidKey(obj(symbolData, 'symbolID'));
295
+ const symbol = symbolId ? idx.node(symbolId) : undefined;
296
+ return compact({
297
+ role: 'INSTANCE',
298
+ symbol: symbolId,
299
+ symbolName: symbol ? str(symbol.node, 'name') : undefined,
300
+ symbolInFile: symbolId !== undefined && symbol === undefined ? false : undefined,
301
+ overrides: objArr(symbolData, 'symbolOverrides').length || undefined,
302
+ propAssignments: objArr(node, 'componentPropAssignments').length || undefined,
303
+ });
304
+ }
305
+ if (type === 'SYMBOL') {
306
+ const propDefs = objArr(node, 'componentPropDefs');
307
+ return compact({
308
+ role: 'SYMBOL',
309
+ description: str(node, 'symbolDescription'),
310
+ key: str(node, 'componentKey'),
311
+ propDefs: propDefs.length
312
+ ? propDefs.map((d) => compact({ name: str(d, 'name'), type: str(d, 'type') }))
313
+ : undefined,
314
+ instances: idx.instanceCounts.get(t.key) ?? 0,
315
+ });
316
+ }
317
+ return undefined;
318
+ }
319
+ function prototypeOf(node) {
320
+ return orUndefined(compact({
321
+ startNode: guidKey(obj(node, 'prototypeStartNodeID')),
322
+ transitionNode: guidKey(obj(node, 'transitionNodeID')),
323
+ interactions: objArr(node, 'prototypeInteractions').length || undefined,
324
+ backgroundColor: colorHex(obj(node, 'prototypeBackgroundColor')),
325
+ }));
326
+ }
327
+ function blobIndexes(paths) {
328
+ const out = [];
329
+ for (const p of paths) {
330
+ const i = num(p, 'commandsBlob');
331
+ if (i !== undefined)
332
+ out.push(i);
333
+ }
334
+ return out.length ? out : undefined;
335
+ }
336
+ function vectorOf(node) {
337
+ const vectorData = obj(node, 'vectorData');
338
+ const normalized = obj(vectorData, 'normalizedSize');
339
+ return orUndefined(compact({
340
+ networkBlob: num(vectorData, 'vectorNetworkBlob'),
341
+ normalizedSize: normalized
342
+ ? `${r2(num(normalized, 'x'))}x${r2(num(normalized, 'y'))}`
343
+ : undefined,
344
+ fillBlobs: blobIndexes(objArr(node, 'fillGeometry')),
345
+ strokeBlobs: blobIndexes(objArr(node, 'strokeGeometry')),
346
+ }));
347
+ }
348
+ function orUndefined(o) {
349
+ return Object.keys(o).length ? o : undefined;
350
+ }
351
+ export function nodeDetail(idx, t, opts = {}) {
352
+ const node = t.node;
353
+ const maxChildren = opts.maxChildren ?? 100;
354
+ const fills = objArr(node, 'fillPaints').map((p) => paintView(idx, p));
355
+ const strokes = objArr(node, 'strokePaints').map((p) => paintView(idx, p));
356
+ const effects = objArr(node, 'effects').map((e) => effectView(idx, e));
357
+ const images = nodeImageHashes(node);
358
+ const dashPattern = node['dashPattern'];
359
+ return compact({
360
+ guid: t.key,
361
+ type: str(node, 'type') ?? 'UNKNOWN',
362
+ name: str(node, 'name'),
363
+ page: t.page ? str(t.page.node, 'name') : undefined,
364
+ path: breadcrumb(t) || undefined,
365
+ parent: t.parent?.key,
366
+ childrenCount: t.children.length || undefined,
367
+ depth: t.depth,
368
+ visible: bool(node, 'visible') === false ? false : undefined,
369
+ locked: bool(node, 'locked') || undefined,
370
+ opacity: num(node, 'opacity') === 1 ? undefined : r2(num(node, 'opacity')),
371
+ blendMode: str(node, 'blendMode') === 'NORMAL' ? undefined : str(node, 'blendMode'),
372
+ mask: bool(node, 'mask') || undefined,
373
+ geometry: geometryOf(t),
374
+ constraints: orUndefined(compact({
375
+ horizontal: str(node, 'horizontalConstraint'),
376
+ vertical: str(node, 'verticalConstraint'),
377
+ })),
378
+ cornerRadius: cornerRadiusOf(node),
379
+ fills: fills.length ? fills : undefined,
380
+ strokes: strokes.length ? strokes : undefined,
381
+ strokeWeight: num(node, 'strokeWeight') ? r2(num(node, 'strokeWeight')) : undefined,
382
+ strokeAlign: strokes.length ? str(node, 'strokeAlign') : undefined,
383
+ strokeCap: str(node, 'strokeCap'),
384
+ strokeJoin: strokes.length ? str(node, 'strokeJoin') : undefined,
385
+ dashPattern: Array.isArray(dashPattern) && dashPattern.length
386
+ ? dashPattern.map((v) => r2(v))
387
+ : undefined,
388
+ effects: effects.length ? effects : undefined,
389
+ autoLayout: autoLayoutOf(node),
390
+ layout: layoutChildOf(node),
391
+ text: textBasics(node),
392
+ component: componentOf(idx, t),
393
+ styles: styleRefsOf(idx, node),
394
+ variables: variableBindingsOf(idx, node),
395
+ prototype: prototypeOf(node),
396
+ vector: vectorOf(node),
397
+ images: images.length ? images : undefined,
398
+ children: opts.children === false ? undefined : t.children.slice(0, maxChildren).map((c) => summarize(c)),
399
+ childrenTruncated: opts.children !== false && t.children.length > maxChildren ? true : undefined,
400
+ });
401
+ }
402
+ // --------------------------------------------------------------------------- style block
403
+ /**
404
+ * Typography of a node — or of a partial style-override record from a text run — reporting only
405
+ * the fields it actually sets, so a run's block shows exactly what differs from the base style.
406
+ */
407
+ export function typography(idx, node, opts = {}) {
408
+ const font = obj(node, 'fontName');
409
+ const fills = objArr(node, 'fillPaints');
410
+ const solid = fills.find((p) => str(p, 'type') === 'SOLID');
411
+ return compact({
412
+ font: font ? `${str(font, 'family') ?? ''} ${str(font, 'style') ?? ''}`.trim() : undefined,
413
+ fontPostScript: str(font, 'postscript'),
414
+ fontSize: r2(num(node, 'fontSize')),
415
+ lineHeight: lengthString(obj(node, 'lineHeight')),
416
+ letterSpacing: lengthString(obj(node, 'letterSpacing')),
417
+ paragraphSpacing: r2(num(node, 'paragraphSpacing')),
418
+ textCase: str(node, 'textCase'),
419
+ textDecoration: str(node, 'textDecoration'),
420
+ align: str(node, 'textAlignHorizontal'),
421
+ verticalAlign: str(node, 'textAlignVertical'),
422
+ color: solid ? colorHex(obj(solid, 'color')) : undefined,
423
+ fills: fills.length && !solid ? fills.map((p) => paintView(idx, p)) : undefined,
424
+ // Runs express most overrides as a shared-style ref, so keep them here by default; the
425
+ // caller turns them off when it already reports the node's style refs separately.
426
+ styles: opts.includeStyleRefs === false ? undefined : styleRefsOf(idx, node),
427
+ });
428
+ }
429
+ // Figma's layout vocabulary in CSS terms. Figma's "primary axis" is the flex main axis and its
430
+ // "counter axis" is the cross axis, so StackJustify maps to justify-content and StackAlign /
431
+ // StackCounterAlign map to align-items / align-self.
432
+ const JUSTIFY = {
433
+ MIN: 'flex-start',
434
+ CENTER: 'center',
435
+ MAX: 'flex-end',
436
+ SPACE_EVENLY: 'space-between',
437
+ SPACE_BETWEEN: 'space-between',
438
+ SPACE_AROUND: 'space-around',
439
+ SPACE_EVENLY_CSS: 'space-evenly',
440
+ };
441
+ const ALIGN = {
442
+ MIN: 'flex-start',
443
+ CENTER: 'center',
444
+ MAX: 'flex-end',
445
+ STRETCH: 'stretch',
446
+ BASELINE: 'baseline',
447
+ AUTO: 'auto',
448
+ };
449
+ const SIZING = {
450
+ FIXED: 'fixed',
451
+ RESIZE_TO_FIT: 'hug',
452
+ RESIZE_TO_FIT_WITH_IMPLICIT_SIZE: 'hug',
453
+ };
454
+ function cssPadding(p) {
455
+ if (p.top === p.right && p.right === p.bottom && p.bottom === p.left)
456
+ return `${p.top}px`;
457
+ if (p.top === p.bottom && p.left === p.right)
458
+ return `${p.top}px ${p.right}px`;
459
+ return `${p.top}px ${p.right}px ${p.bottom}px ${p.left}px`;
460
+ }
461
+ /**
462
+ * The resolved, code-generation-oriented style of one node: paints as hex, radii, typography and
463
+ * auto-layout expressed in CSS-flexbox terms. Shared-style and variable references are named
464
+ * whenever the target is defined in this same file.
465
+ */
466
+ export function styleBlock(idx, t) {
467
+ const node = t.node;
468
+ const size = obj(node, 'size');
469
+ const mode = str(node, 'stackMode');
470
+ const padding = paddingOf(node);
471
+ const layout = mode && mode !== 'NONE'
472
+ ? compact({
473
+ display: 'flex',
474
+ direction: mode === 'VERTICAL' ? 'column' : mode === 'GRID' ? 'grid' : 'row',
475
+ gap: r2(num(node, 'stackSpacing')),
476
+ rowGap: r2(num(node, 'stackCounterSpacing')),
477
+ padding: padding ? cssPadding(padding) : undefined,
478
+ paddingBox: padding,
479
+ justifyContent: JUSTIFY[str(node, 'stackPrimaryAlignItems') ?? ''],
480
+ alignItems: ALIGN[str(node, 'stackCounterAlignItems') ?? ''],
481
+ alignContent: str(node, 'stackCounterAlignContent') === 'SPACE_BETWEEN' ? 'space-between' : undefined,
482
+ flexWrap: str(node, 'stackWrap') === 'WRAP' ? 'wrap' : undefined,
483
+ primarySizing: SIZING[str(node, 'stackPrimarySizing') ?? ''],
484
+ widthSizing: SIZING[str(node, 'stackWidth') ?? ''],
485
+ heightSizing: SIZING[str(node, 'stackHeight') ?? ''],
486
+ })
487
+ : undefined;
488
+ const inParent = orUndefined(compact({
489
+ flexGrow: num(node, 'stackChildPrimaryGrow'),
490
+ alignSelf: ALIGN[str(node, 'stackChildAlignSelf') ?? ''],
491
+ position: str(node, 'stackPositioning') === 'ABSOLUTE' ? 'absolute' : undefined,
492
+ margin: orUndefined(compact({
493
+ top: r2(num(node, 'stackChildMarginTop')),
494
+ right: r2(num(node, 'stackChildMarginRight')),
495
+ bottom: r2(num(node, 'stackChildMarginBottom')),
496
+ left: r2(num(node, 'stackChildMarginLeft')),
497
+ })),
498
+ }));
499
+ const fills = objArr(node, 'fillPaints').map((p) => paintView(idx, p));
500
+ const strokes = objArr(node, 'strokePaints').map((p) => paintView(idx, p));
501
+ const effects = objArr(node, 'effects').map((e) => effectView(idx, e));
502
+ const type = str(node, 'type');
503
+ const dashPattern = node['dashPattern'];
504
+ return compact({
505
+ guid: t.key,
506
+ type,
507
+ name: str(node, 'name'),
508
+ width: r2(num(size, 'x')),
509
+ height: r2(num(size, 'y')),
510
+ opacity: num(node, 'opacity') === 1 ? undefined : r2(num(node, 'opacity')),
511
+ blendMode: str(node, 'blendMode') === 'NORMAL' ? undefined : str(node, 'blendMode'),
512
+ cornerRadius: cornerRadiusOf(node),
513
+ fills: fills.length ? fills : undefined,
514
+ strokes: strokes.length ? strokes : undefined,
515
+ strokeWeight: num(node, 'strokeWeight') ? r2(num(node, 'strokeWeight')) : undefined,
516
+ strokeAlign: strokes.length ? str(node, 'strokeAlign') : undefined,
517
+ dashPattern: Array.isArray(dashPattern) && dashPattern.length
518
+ ? dashPattern.map((v) => r2(v))
519
+ : undefined,
520
+ effects: effects.length ? effects : undefined,
521
+ layout,
522
+ inParentLayout: inParent,
523
+ typography: type === 'TEXT' ? orUndefined(typography(idx, node, { includeStyleRefs: false })) : undefined,
524
+ constraints: orUndefined(compact({
525
+ horizontal: str(node, 'horizontalConstraint'),
526
+ vertical: str(node, 'verticalConstraint'),
527
+ })),
528
+ styles: styleRefsOf(idx, node, { resolve: true }),
529
+ variables: variableBindingsOf(idx, node),
530
+ });
531
+ }
532
+ /** The decoded NodeChange verbatim, JSON-safe (BigInt -> string, bytes -> hex). */
533
+ export function nodeRaw(t) {
534
+ const out = { guid: t.key };
535
+ for (const [k, v] of Object.entries(t.node)) {
536
+ if (k === 'guid')
537
+ continue;
538
+ out[k] = jsonSafe(v);
539
+ }
540
+ return out;
541
+ }
@@ -0,0 +1,29 @@
1
+ import type { FileIndex } from './index.js';
2
+ import type { TreeNode } from './tree.js';
3
+ export interface TextRun {
4
+ /** UTF-16 code-unit offsets: `characters.slice(start, end)`. */
5
+ start: number;
6
+ end: number;
7
+ text: string;
8
+ /** 0 = the node's base style. */
9
+ styleID: number;
10
+ /** Only the fields this run overrides; absent when the run uses the base style. */
11
+ style?: Record<string, unknown>;
12
+ }
13
+ export interface TextView {
14
+ characters: string;
15
+ characterCount: number;
16
+ /** Node-level typography that every run inherits. */
17
+ baseStyle?: Record<string, unknown>;
18
+ runs?: TextRun[];
19
+ /** True when `characterStyleIDs` is present and mentions any non-zero id. */
20
+ hasStyledRuns: boolean;
21
+ }
22
+ /** The four fields a copy inventory actually needs, ~6x cheaper than the full typography. */
23
+ export declare function compactStyle(style: Record<string, unknown> | undefined): Record<string, unknown> | undefined;
24
+ /**
25
+ * Group `characterStyleIDs` into maximal runs of equal id. Consecutive characters sharing an id
26
+ * become one run, so a 4000-character node with two styles costs two entries, not 4000.
27
+ */
28
+ export declare function textView(idx: FileIndex, t: TreeNode, includeRuns: boolean): TextView | undefined;
29
+ //# sourceMappingURL=text.d.ts.map
@@ -0,0 +1,61 @@
1
+ import { compact, num, obj, objArr, str } from './access.js';
2
+ import { typography } from './summarize.js';
3
+ /** The four fields a copy inventory actually needs, ~6x cheaper than the full typography. */
4
+ export function compactStyle(style) {
5
+ if (!style)
6
+ return undefined;
7
+ return compact({
8
+ font: style['font'],
9
+ size: style['fontSize'],
10
+ lineHeight: style['lineHeight'],
11
+ color: style['color'],
12
+ });
13
+ }
14
+ /**
15
+ * Group `characterStyleIDs` into maximal runs of equal id. Consecutive characters sharing an id
16
+ * become one run, so a 4000-character node with two styles costs two entries, not 4000.
17
+ */
18
+ export function textView(idx, t, includeRuns) {
19
+ const textData = obj(t.node, 'textData');
20
+ const characters = str(textData, 'characters');
21
+ if (characters === undefined)
22
+ return undefined;
23
+ const ids = textData?.['characterStyleIDs'] ?? [];
24
+ const hasStyledRuns = ids.some((id) => id !== 0);
25
+ const view = {
26
+ characters,
27
+ characterCount: characters.length,
28
+ baseStyle: orUndefined(typography(idx, t.node)),
29
+ hasStyledRuns,
30
+ };
31
+ if (!includeRuns)
32
+ return view;
33
+ const overrides = new Map();
34
+ for (const entry of objArr(textData, 'styleOverrideTable')) {
35
+ const id = num(entry, 'styleID');
36
+ if (id !== undefined)
37
+ overrides.set(id, entry);
38
+ }
39
+ const runs = [];
40
+ let start = 0;
41
+ const idAt = (i) => ids[i] ?? 0;
42
+ for (let i = 1; i <= characters.length; i++) {
43
+ if (i < characters.length && idAt(i) === idAt(start))
44
+ continue;
45
+ const styleID = idAt(start);
46
+ const override = overrides.get(styleID);
47
+ runs.push(compact({
48
+ start,
49
+ end: i,
50
+ text: characters.slice(start, i),
51
+ styleID,
52
+ style: override ? orUndefined(typography(idx, override)) : undefined,
53
+ }));
54
+ start = i;
55
+ }
56
+ view.runs = runs;
57
+ return view;
58
+ }
59
+ function orUndefined(o) {
60
+ return Object.keys(o).length ? o : undefined;
61
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Layer-tree reconstruction (fig-reading-solution.md §8).
3
+ *
4
+ * `message.nodeChanges` is flat; every node carries `parentIndex.{guid, position}`. Siblings are
5
+ * ordered by a fractional-index string that MUST be compared by raw UTF-16 code units — numeric
6
+ * or locale-aware comparison scrambles layer order.
7
+ */
8
+ import type { NodeChange } from '../fig/parse.js';
9
+ import type { KiwiObject } from '../fig/kiwi.js';
10
+ export interface Guid {
11
+ readonly sessionID?: number;
12
+ readonly localID?: number;
13
+ }
14
+ /** Canonical guid string used at every API boundary: `"2:1339"`. */
15
+ export declare function guidKey(g: Guid | undefined): string | undefined;
16
+ export declare function readGuid(obj: KiwiObject | undefined, field: string): string | undefined;
17
+ export interface TreeNode {
18
+ readonly key: string;
19
+ readonly node: NodeChange;
20
+ readonly children: TreeNode[];
21
+ parent: TreeNode | undefined;
22
+ /** DFS pre-order position; stable for a given parse, and the basis of every cursor. */
23
+ order: number;
24
+ depth: number;
25
+ /** Nearest CANVAS ancestor (the page a node lives on); undefined for DOCUMENT and pages. */
26
+ page: TreeNode | undefined;
27
+ }
28
+ /**
29
+ * The identity that instance override paths (`symbolData.symbolOverrides[].guidPath.guids` and
30
+ * `derivedSymbolData[].guidPath.guids`) use for a component descendant: its `overrideKey` when
31
+ * it has one — a node created by copying a component keeps the original's — else its own guid.
32
+ *
33
+ * Measured on the sample: 8 893 of 10 480 symbol descendants carry an explicit key; the other
34
+ * 1 587 are addressed by guid, by 30 061 of the file's 303 833 records.
35
+ */
36
+ export declare function overrideIdentity(t: TreeNode): string;
37
+ export interface Tree {
38
+ readonly root: TreeNode | undefined;
39
+ readonly byKey: ReadonlyMap<string, TreeNode>;
40
+ /** DFS pre-order list; index === TreeNode.order. */
41
+ readonly ordered: readonly TreeNode[];
42
+ readonly orphans: readonly TreeNode[];
43
+ }
44
+ export declare function buildTree(nodeChanges: readonly NodeChange[]): Tree;
45
+ /** Names from the node up to (excluding) the DOCUMENT, root-first — a readable breadcrumb. */
46
+ export declare function breadcrumb(t: TreeNode, separator?: string): string;
47
+ //# sourceMappingURL=tree.d.ts.map