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,301 @@
1
+ import { bool, bytes, hex, num, obj, objArr, str } from '../model/access.js';
2
+ import { sniffImage } from '../fig/imagemeta.js';
3
+ import { alphaOf, hexOf } from './color.js';
4
+ import { fromFigma, invert, isIdentity, multiply, scale as scaleMat } from './matrix.js';
5
+ import { esc, fmt, toAttr } from './svg.js';
6
+ import { feat } from './report.js';
7
+ /** resvg decodes these; anything else is reported and drawn as nothing. */
8
+ const EMBEDDABLE = new Set(['image/png', 'image/jpeg', 'image/gif']);
9
+ function paintOpacity(paint) {
10
+ const o = num(paint, 'opacity');
11
+ return o === undefined ? 1 : o;
12
+ }
13
+ function opacityAttr(alpha) {
14
+ return alpha >= 1 ? {} : { 'fill-opacity': alpha };
15
+ }
16
+ function stopsOf(paint, opacity) {
17
+ return objArr(paint, 'stops')
18
+ .map((s) => {
19
+ const color = obj(s, 'color');
20
+ return {
21
+ offset: Math.max(0, Math.min(1, num(s, 'position') ?? 0)),
22
+ color: hexOf(color),
23
+ alpha: alphaOf(color) * opacity,
24
+ };
25
+ })
26
+ .sort((a, b) => a.offset - b.offset);
27
+ }
28
+ function stopMarkup(stops) {
29
+ return stops
30
+ .map((s) => `<stop offset="${fmt(s.offset)}" stop-color="${esc(s.color)}"` +
31
+ (s.alpha >= 1 ? '' : ` stop-opacity="${fmt(s.alpha)}"`) +
32
+ '/>')
33
+ .join('');
34
+ }
35
+ /** Mean of the stop colours — what an unsupported gradient type is approximated with. */
36
+ function averageStop(stops) {
37
+ if (stops.length === 0)
38
+ return undefined;
39
+ let r = 0;
40
+ let g = 0;
41
+ let b = 0;
42
+ let a = 0;
43
+ for (const s of stops) {
44
+ r += parseInt(s.color.slice(1, 3), 16);
45
+ g += parseInt(s.color.slice(3, 5), 16);
46
+ b += parseInt(s.color.slice(5, 7), 16);
47
+ a += s.alpha;
48
+ }
49
+ const n = stops.length;
50
+ const ch = (v) => Math.round(v / n).toString(16).padStart(2, '0');
51
+ return { fill: `#${ch(r)}${ch(g)}${ch(b)}`, ...opacityAttr(a / n) };
52
+ }
53
+ function round4(m) {
54
+ return [m.a, m.b, m.c, m.d, m.e, m.f].map((v) => Math.round(v * 10_000) / 10_000).join(',');
55
+ }
56
+ /**
57
+ * F7 — `paint.transform` maps the node's normalized 0..1 box TO gradient space, where a linear
58
+ * gradient runs from (0, 0.5) to (1, 0.5) and a radial one is centred at (0.5, 0.5) with radius
59
+ * 0.5. The exporter therefore needs the INVERSE, composed with `scale(w, h)`.
60
+ */
61
+ function gradientAttrs(paint, box, env, guid, type) {
62
+ const opacity = paintOpacity(paint);
63
+ const stops = stopsOf(paint, opacity);
64
+ if (stops.length === 0)
65
+ return undefined;
66
+ if (type === 'GRADIENT_ANGULAR' || type === 'GRADIENT_DIAMOND') {
67
+ // Drawn as the average colour so the shape is visible rather than missing.
68
+ env.report.approximated(feat.paint(type), guid);
69
+ return averageStop(stops);
70
+ }
71
+ const inv = invert(fromFigma(obj(paint, 'transform')));
72
+ if (!inv) {
73
+ env.report.approximated('gradient-singular', guid);
74
+ const first = stops[0];
75
+ return { fill: first.color, ...opacityAttr(first.alpha) };
76
+ }
77
+ const g = multiply(scaleMat(box.w, box.h), inv);
78
+ const linear = type === 'GRADIENT_LINEAR';
79
+ const key = `grad:${type}:${round4(g)}:${stops.map((s) => `${s.offset}/${s.color}/${s.alpha}`).join(',')}`;
80
+ const id = env.out.def(key, (defId) => linear
81
+ ? `<linearGradient id="${defId}" gradientUnits="userSpaceOnUse" x1="0" y1="0.5" x2="1" y2="0.5" ` +
82
+ `gradientTransform="${toAttr(g)}">${stopMarkup(stops)}</linearGradient>`
83
+ : `<radialGradient id="${defId}" gradientUnits="userSpaceOnUse" cx="0.5" cy="0.5" r="0.5" ` +
84
+ `gradientTransform="${toAttr(g)}">${stopMarkup(stops)}</radialGradient>`);
85
+ return { fill: `url(#${id})` };
86
+ }
87
+ // ---------------------------------------------------------------------------------- images
88
+ /** Image bytes: ZIP entry `images/<40-hex>`, else the blob named by `image.dataBlob` (F6). */
89
+ function imageBytes(env, image) {
90
+ const hash = hex(bytes(image, 'hash'));
91
+ if (hash) {
92
+ const fromZip = env.entry.fig.zip?.read(`images/${hash}`);
93
+ if (fromZip)
94
+ return fromZip;
95
+ }
96
+ const blobIndex = num(image, 'dataBlob');
97
+ if (blobIndex !== undefined) {
98
+ const raw = bytes(env.entry.fig.blobs[blobIndex], 'bytes');
99
+ if (raw)
100
+ return Buffer.from(raw);
101
+ }
102
+ return undefined;
103
+ }
104
+ /** One data URI per distinct image, built at most once per render. */
105
+ function dataUri(env, image, guid) {
106
+ const hash = hex(bytes(image, 'hash')) ?? `blob:${num(image, 'dataBlob') ?? '?'}`;
107
+ const cached = env.images.get(hash);
108
+ if (cached !== undefined) {
109
+ if (cached === null)
110
+ return undefined;
111
+ return cached;
112
+ }
113
+ const raw = imageBytes(env, image);
114
+ if (!raw) {
115
+ env.report.unsupported('image-missing', guid);
116
+ env.images.set(hash, null);
117
+ return undefined;
118
+ }
119
+ const meta = sniffImage(raw);
120
+ if (!EMBEDDABLE.has(meta.mime)) {
121
+ env.report.unsupported(feat.imageFormat(meta.mime), guid);
122
+ env.images.set(hash, null);
123
+ return undefined;
124
+ }
125
+ const uri = `data:${meta.mime};base64,${raw.toString('base64')}`;
126
+ env.images.set(hash, uri);
127
+ return uri;
128
+ }
129
+ function intrinsicSize(paint, env, image) {
130
+ const w = num(paint, 'originalImageWidth');
131
+ const h = num(paint, 'originalImageHeight');
132
+ if (w && h)
133
+ return { w, h };
134
+ const raw = imageBytes(env, image);
135
+ const meta = raw ? sniffImage(raw) : undefined;
136
+ return { w: meta?.width ?? 1, h: meta?.height ?? 1 };
137
+ }
138
+ /**
139
+ * §4.7.3. The four scale modes map onto `preserveAspectRatio`, so the renderer does the fitting
140
+ * arithmetic: FILL = `slice`, FIT = `meet`, STRETCH = `none`, TILE = a pattern the size of one
141
+ * tile. Figma's "crop" is a non-identity `paint.transform` on a STRETCH paint (the schema has no
142
+ * separate `imageTransform` field — the plan's §4.7.3 named it wrongly).
143
+ */
144
+ function imageAttrs(paint, box, env, guid) {
145
+ const image = obj(paint, 'image');
146
+ if (!image) {
147
+ env.report.unsupported('image-missing', guid);
148
+ return undefined;
149
+ }
150
+ const uri = dataUri(env, image, guid);
151
+ if (!uri)
152
+ return undefined;
153
+ if (box.w <= 0 || box.h <= 0)
154
+ return undefined;
155
+ const mode = str(paint, 'imageScaleMode') ?? 'STRETCH';
156
+ env.report.seen(feat.imageMode(mode));
157
+ const opacity = paintOpacity(paint);
158
+ const rotation = num(paint, 'rotation') ?? 0;
159
+ const tileScale = num(paint, 'scale') ?? 1;
160
+ const transform = fromFigma(obj(paint, 'transform'));
161
+ const intrinsic = intrinsicSize(paint, env, image);
162
+ if (objArr(paint, 'paintFilter').length > 0 || obj(paint, 'filterColorAdjust')) {
163
+ env.report.approximated('image-filters', guid);
164
+ }
165
+ // Pattern tile geometry: one tile covers the whole box except for TILE.
166
+ let tileW = box.w;
167
+ let tileH = box.h;
168
+ let inner;
169
+ const href = ` xlink:href="${esc(uri)}"`;
170
+ const op = opacity >= 1 ? '' : ` opacity="${fmt(opacity)}"`;
171
+ if (mode === 'TILE') {
172
+ tileW = Math.max(1e-3, intrinsic.w * tileScale);
173
+ tileH = Math.max(1e-3, intrinsic.h * tileScale);
174
+ inner = `<image width="${fmt(tileW)}" height="${fmt(tileH)}" preserveAspectRatio="none"${op}${href}/>`;
175
+ }
176
+ else if (mode === 'FILL') {
177
+ inner = `<image width="${fmt(box.w)}" height="${fmt(box.h)}" preserveAspectRatio="xMidYMid slice"${op}${href}/>`;
178
+ }
179
+ else if (mode === 'FIT') {
180
+ inner = `<image width="${fmt(box.w)}" height="${fmt(box.h)}" preserveAspectRatio="xMidYMid meet"${op}${href}/>`;
181
+ }
182
+ else if (isIdentity(transform)) {
183
+ inner = `<image width="${fmt(box.w)}" height="${fmt(box.h)}" preserveAspectRatio="none"${op}${href}/>`;
184
+ }
185
+ else {
186
+ // Figma "crop". Candidate A of §4.7.3; fixture cf-image-crop decides between A and B.
187
+ const inv = invert(transform);
188
+ if (!inv) {
189
+ inner = `<image width="${fmt(box.w)}" height="${fmt(box.h)}" preserveAspectRatio="none"${op}${href}/>`;
190
+ }
191
+ else {
192
+ env.report.approximated('image-crop', guid);
193
+ const m = multiply(multiply(scaleMat(box.w, box.h), inv), scaleMat(1 / intrinsic.w, 1 / intrinsic.h));
194
+ inner =
195
+ `<image width="${fmt(intrinsic.w)}" height="${fmt(intrinsic.h)}" preserveAspectRatio="none"` +
196
+ `${op} transform="${toAttr(m)}"${href}/>`;
197
+ }
198
+ }
199
+ if (rotation !== 0) {
200
+ // Multiples of 90 swap the tile's aspect; anything else is an approximation either way.
201
+ env.report.approximated('image-rotation', guid);
202
+ inner =
203
+ `<g transform="translate(${fmt(tileW / 2)} ${fmt(tileH / 2)}) rotate(${fmt(rotation)}) ` +
204
+ `translate(${fmt(-tileW / 2)} ${fmt(-tileH / 2)})">${inner}</g>`;
205
+ }
206
+ const hash = hex(bytes(image, 'hash')) ?? 'blob';
207
+ const key = `img:${hash}:${mode}:${fmt(tileW)}x${fmt(tileH)}:${fmt(box.w)}x${fmt(box.h)}:${fmt(rotation)}:${fmt(opacity)}:${round4(transform)}`;
208
+ const id = env.out.def(key, (defId) => `<pattern id="${defId}" patternUnits="userSpaceOnUse" x="0" y="0" ` +
209
+ `width="${fmt(tileW)}" height="${fmt(tileH)}">${inner}</pattern>`);
210
+ return { fill: `url(#${id})` };
211
+ }
212
+ // ----------------------------------------------------------------------------------- entry
213
+ /**
214
+ * Attributes for one paint, or `undefined` when it draws nothing.
215
+ * Records the paint type in the report vocabulary either way.
216
+ */
217
+ export function paintAttrs(paint, box, env, guid) {
218
+ const type = str(paint, 'type') ?? 'SOLID';
219
+ env.report.seen(feat.paint(type));
220
+ if (bool(paint, 'visible') === false)
221
+ return undefined;
222
+ const opacity = paintOpacity(paint);
223
+ if (opacity <= 0)
224
+ return undefined;
225
+ // An OUTLINE mask only cares where the geometry is, not what colour it is.
226
+ if (env.whiteout)
227
+ return { fill: '#ffffff' };
228
+ const attrs = paintFill(paint, box, env, guid, type);
229
+ if (!attrs)
230
+ return undefined;
231
+ // §4.11 — a paint may carry its own blend mode, which lands on the element it paints.
232
+ const blend = paintBlendStyle(paint, env, guid);
233
+ return blend ? { ...attrs, style: blend } : attrs;
234
+ }
235
+ /** Paint-level `blendMode`, mapped the same way as the node-level one. */
236
+ function paintBlendStyle(paint, env, guid) {
237
+ const mode = str(paint, 'blendMode') ?? 'NORMAL';
238
+ if (mode === 'NORMAL' || mode === 'PASS_THROUGH')
239
+ return undefined;
240
+ env.report.seen(feat.blend(mode));
241
+ const exact = PAINT_BLEND_CSS[mode];
242
+ if (exact)
243
+ return `mix-blend-mode:${exact}`;
244
+ const near = PAINT_BLEND_APPROXIMATE[mode];
245
+ if (near) {
246
+ env.report.approximated(feat.blend(mode), guid);
247
+ return `mix-blend-mode:${near}`;
248
+ }
249
+ env.report.unsupported(feat.blend(mode), guid);
250
+ return undefined;
251
+ }
252
+ const PAINT_BLEND_CSS = {
253
+ DARKEN: 'darken',
254
+ MULTIPLY: 'multiply',
255
+ COLOR_BURN: 'color-burn',
256
+ LIGHTEN: 'lighten',
257
+ SCREEN: 'screen',
258
+ COLOR_DODGE: 'color-dodge',
259
+ OVERLAY: 'overlay',
260
+ SOFT_LIGHT: 'soft-light',
261
+ HARD_LIGHT: 'hard-light',
262
+ DIFFERENCE: 'difference',
263
+ EXCLUSION: 'exclusion',
264
+ HUE: 'hue',
265
+ SATURATION: 'saturation',
266
+ COLOR: 'color',
267
+ LUMINOSITY: 'luminosity',
268
+ };
269
+ const PAINT_BLEND_APPROXIMATE = {
270
+ LINEAR_DODGE: 'screen',
271
+ LINEAR_BURN: 'multiply',
272
+ };
273
+ function paintFill(paint, box, env, guid, type) {
274
+ const opacity = paintOpacity(paint);
275
+ switch (type) {
276
+ case 'SOLID': {
277
+ const alpha = alphaOf(obj(paint, 'color')) * opacity;
278
+ if (alpha <= 0)
279
+ return undefined;
280
+ return { fill: hexOf(obj(paint, 'color')), ...opacityAttr(alpha) };
281
+ }
282
+ case 'GRADIENT_LINEAR':
283
+ case 'GRADIENT_RADIAL':
284
+ case 'GRADIENT_ANGULAR':
285
+ case 'GRADIENT_DIAMOND':
286
+ return gradientAttrs(paint, box, env, guid, type);
287
+ case 'IMAGE':
288
+ return imageAttrs(paint, box, env, guid);
289
+ case 'VIDEO': {
290
+ // Draw the poster frame when the file kept one; otherwise nothing.
291
+ env.report.approximated(feat.paint(type), guid);
292
+ const poster = obj(paint, 'imageThumbnail') ?? obj(paint, 'image');
293
+ if (!poster)
294
+ return undefined;
295
+ return imageAttrs({ ...paint, image: poster, imageScaleMode: 'FILL' }, box, env, guid);
296
+ }
297
+ default:
298
+ env.report.unsupported(feat.paint(type), guid);
299
+ return undefined;
300
+ }
301
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Path command blobs (plan §4.2, fact F4).
3
+ *
4
+ * A blob is a flat sequence of commands: one opcode byte followed by little-endian float32
5
+ * arguments. Verified on all 7 292 non-empty fill, stroke and glyph blobs of the sample file:
6
+ *
7
+ * 0 close (0 floats) 1 moveTo (x y) 2 lineTo (x y) 3 quadTo (cx cy x y)
8
+ * 4 cubicTo (c1x c1y c2x c2y x y)
9
+ *
10
+ * An empty blob is a valid empty path ("no fill area", e.g. a zero-height line).
11
+ */
12
+ import type { Box, Mat } from './matrix.js';
13
+ export type PathOp = 'Z' | 'M' | 'L' | 'Q' | 'C';
14
+ export interface PathCommand {
15
+ readonly op: PathOp;
16
+ readonly args: readonly number[];
17
+ }
18
+ export declare function decodeCommands(raw: Uint8Array): PathCommand[];
19
+ /**
20
+ * SVG `d` string. `m`, when given, is applied to every coordinate pair before formatting.
21
+ *
22
+ * Commands before the first `moveto` are dropped. SVG requires path data to begin with a
23
+ * moveto, and **4 287 of the 4 288 glyph outline blobs in the sample begin with a `close`**
24
+ * (fill and stroke blobs never do). Emitting that leading `Z` makes the whole path invalid and
25
+ * resvg discards it without a word — every piece of text renders blank.
26
+ */
27
+ export declare function toPathData(cmds: readonly PathCommand[], m?: Mat): string;
28
+ /**
29
+ * Conservative bounds: control points are included, so a curve's box may be slightly larger
30
+ * than the ink. That is the safe direction — a render region is never too small.
31
+ */
32
+ export declare function pathBounds(cmds: readonly PathCommand[], m?: Mat): Box | undefined;
33
+ /** Round every coordinate to `decimals` places — used by the golden tests, not by the exporter. */
34
+ export declare function roundCommands(cmds: readonly PathCommand[], decimals: number): PathCommand[];
35
+ /**
36
+ * A rounded rectangle, for §4.14: files written by other tools may carry no `fillGeometry`.
37
+ * Radii are clamped so adjacent corners cannot overlap.
38
+ */
39
+ export declare function roundedRectCommands(w: number, h: number, radii?: readonly [number, number, number, number]): PathCommand[];
40
+ /** An ellipse inscribed in `w × h`, as four cubic arcs. */
41
+ export declare function ellipseCommands(w: number, h: number): PathCommand[];
42
+ //# sourceMappingURL=path.d.ts.map
@@ -0,0 +1,156 @@
1
+ import { apply } from './matrix.js';
2
+ import { fmt } from './svg.js';
3
+ const ARG_COUNT = { 0: 0, 1: 2, 2: 2, 3: 4, 4: 6 };
4
+ const OPS = ['Z', 'M', 'L', 'Q', 'C'];
5
+ export function decodeCommands(raw) {
6
+ const out = [];
7
+ if (raw.length === 0)
8
+ return out;
9
+ const dv = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
10
+ let i = 0;
11
+ while (i < raw.length) {
12
+ const op = raw[i];
13
+ const n = ARG_COUNT[op];
14
+ if (n === undefined) {
15
+ throw new Error(`unknown path opcode ${op} at byte ${i} of ${raw.length}`);
16
+ }
17
+ if (i + 1 + 4 * n > raw.length) {
18
+ throw new Error(`truncated path command ${op} at byte ${i} of ${raw.length}`);
19
+ }
20
+ const args = [];
21
+ for (let k = 0; k < n; k++)
22
+ args.push(dv.getFloat32(i + 1 + 4 * k, true));
23
+ out.push({ op: OPS[op], args });
24
+ i += 1 + 4 * n;
25
+ }
26
+ return out;
27
+ }
28
+ /**
29
+ * SVG `d` string. `m`, when given, is applied to every coordinate pair before formatting.
30
+ *
31
+ * Commands before the first `moveto` are dropped. SVG requires path data to begin with a
32
+ * moveto, and **4 287 of the 4 288 glyph outline blobs in the sample begin with a `close`**
33
+ * (fill and stroke blobs never do). Emitting that leading `Z` makes the whole path invalid and
34
+ * resvg discards it without a word — every piece of text renders blank.
35
+ */
36
+ export function toPathData(cmds, m) {
37
+ const parts = [];
38
+ let started = false;
39
+ for (const cmd of cmds) {
40
+ if (!started) {
41
+ if (cmd.op !== 'M')
42
+ continue;
43
+ started = true;
44
+ }
45
+ if (cmd.op === 'Z') {
46
+ parts.push('Z');
47
+ continue;
48
+ }
49
+ const nums = [];
50
+ for (let k = 0; k + 1 < cmd.args.length; k += 2) {
51
+ const x = cmd.args[k];
52
+ const y = cmd.args[k + 1];
53
+ if (m) {
54
+ const [px, py] = apply(m, x, y);
55
+ nums.push(fmt(px), fmt(py));
56
+ }
57
+ else {
58
+ nums.push(fmt(x), fmt(y));
59
+ }
60
+ }
61
+ parts.push(`${cmd.op}${nums.join(',')}`);
62
+ }
63
+ return parts.join(' ');
64
+ }
65
+ /**
66
+ * Conservative bounds: control points are included, so a curve's box may be slightly larger
67
+ * than the ink. That is the safe direction — a render region is never too small.
68
+ */
69
+ export function pathBounds(cmds, m) {
70
+ let minX = Infinity;
71
+ let minY = Infinity;
72
+ let maxX = -Infinity;
73
+ let maxY = -Infinity;
74
+ let seen = false;
75
+ for (const cmd of cmds) {
76
+ for (let k = 0; k + 1 < cmd.args.length; k += 2) {
77
+ const rx = cmd.args[k];
78
+ const ry = cmd.args[k + 1];
79
+ const [x, y] = m ? apply(m, rx, ry) : [rx, ry];
80
+ if (!Number.isFinite(x) || !Number.isFinite(y))
81
+ continue;
82
+ seen = true;
83
+ if (x < minX)
84
+ minX = x;
85
+ if (y < minY)
86
+ minY = y;
87
+ if (x > maxX)
88
+ maxX = x;
89
+ if (y > maxY)
90
+ maxY = y;
91
+ }
92
+ }
93
+ if (!seen)
94
+ return undefined;
95
+ return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };
96
+ }
97
+ /** Round every coordinate to `decimals` places — used by the golden tests, not by the exporter. */
98
+ export function roundCommands(cmds, decimals) {
99
+ const factor = 10 ** decimals;
100
+ return cmds.map((c) => ({ op: c.op, args: c.args.map((v) => Math.round(v * factor) / factor) }));
101
+ }
102
+ /** Control-point ratio that turns four cubics into a circle to within 0.02 %. */
103
+ const KAPPA = 0.5522847498307936;
104
+ /**
105
+ * A rounded rectangle, for §4.14: files written by other tools may carry no `fillGeometry`.
106
+ * Radii are clamped so adjacent corners cannot overlap.
107
+ */
108
+ export function roundedRectCommands(w, h, radii = [0, 0, 0, 0]) {
109
+ if (!(w > 0) || !(h > 0))
110
+ return [];
111
+ const limit = Math.min(w, h) / 2;
112
+ const [tl, tr, br, bl] = radii.map((r) => Math.max(0, Math.min(r, limit)));
113
+ const arc = (fromX, fromY, toX, toY, cx, cy) => ({
114
+ op: 'C',
115
+ args: [
116
+ fromX + (cx - fromX) * KAPPA,
117
+ fromY + (cy - fromY) * KAPPA,
118
+ toX + (cx - toX) * KAPPA,
119
+ toY + (cy - toY) * KAPPA,
120
+ toX,
121
+ toY,
122
+ ],
123
+ });
124
+ const out = [{ op: 'M', args: [tl, 0] }];
125
+ out.push({ op: 'L', args: [w - tr, 0] });
126
+ if (tr > 0)
127
+ out.push(arc(w - tr, 0, w, tr, w, 0));
128
+ out.push({ op: 'L', args: [w, h - br] });
129
+ if (br > 0)
130
+ out.push(arc(w, h - br, w - br, h, w, h));
131
+ out.push({ op: 'L', args: [bl, h] });
132
+ if (bl > 0)
133
+ out.push(arc(bl, h, 0, h - bl, 0, h));
134
+ out.push({ op: 'L', args: [0, tl] });
135
+ if (tl > 0)
136
+ out.push(arc(0, tl, tl, 0, 0, 0));
137
+ out.push({ op: 'Z', args: [] });
138
+ return out;
139
+ }
140
+ /** An ellipse inscribed in `w × h`, as four cubic arcs. */
141
+ export function ellipseCommands(w, h) {
142
+ if (!(w > 0) || !(h > 0))
143
+ return [];
144
+ const rx = w / 2;
145
+ const ry = h / 2;
146
+ const ox = rx * KAPPA;
147
+ const oy = ry * KAPPA;
148
+ return [
149
+ { op: 'M', args: [rx, 0] },
150
+ { op: 'C', args: [rx + ox, 0, w, ry - oy, w, ry] },
151
+ { op: 'C', args: [w, ry + oy, rx + ox, h, rx, h] },
152
+ { op: 'C', args: [rx - ox, h, 0, ry + oy, 0, ry] },
153
+ { op: 'C', args: [0, ry - oy, rx - ox, 0, rx, 0] },
154
+ { op: 'Z', args: [] },
155
+ ];
156
+ }
@@ -0,0 +1,31 @@
1
+ interface RenderedImage {
2
+ asPng(): Uint8Array;
3
+ readonly width: number;
4
+ readonly height: number;
5
+ free(): void;
6
+ }
7
+ interface ResvgInstance {
8
+ render(): RenderedImage;
9
+ free(): void;
10
+ }
11
+ interface ResvgModule {
12
+ initWasm(input: Uint8Array): Promise<void>;
13
+ Resvg: new (svg: string, opts?: Record<string, unknown>) => ResvgInstance;
14
+ }
15
+ /** Resolves to `undefined` when the optional package is not installed. Never throws. */
16
+ export declare function rasterizer(): Promise<ResvgModule | undefined>;
17
+ export interface RasterResult {
18
+ readonly png: Uint8Array;
19
+ readonly width: number;
20
+ readonly height: number;
21
+ }
22
+ /**
23
+ * `undefined` means "no rasterizer installed". A malformed SVG throws a plain Error from resvg
24
+ * ("SVG data parsing failed …"); callers report that as `svg-rejected` rather than crashing.
25
+ *
26
+ * There is deliberately no `pixels` field: resvg's pixel buffer is PREMULTIPLIED (Appendix E,
27
+ * R5), so comparing it against `pngjs` output would be silently wrong. Always decode `png`.
28
+ */
29
+ export declare function rasterize(svg: string, scale: number, background?: string): Promise<RasterResult | undefined>;
30
+ export {};
31
+ //# sourceMappingURL=raster.d.ts.map
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Optional rasterizer wrapper (plan §5) around `@resvg/resvg-wasm`.
3
+ *
4
+ * The package is an OPTIONAL dependency: `rasterizer()` resolves to `undefined` when it is not
5
+ * installed and never throws, so the server, every existing tool and the SVG output keep
6
+ * working without it.
7
+ *
8
+ * Behaviour here is measured, not assumed — see Appendix E of the plan.
9
+ */
10
+ import * as fs from 'node:fs';
11
+ import { createRequire } from 'node:module';
12
+ const require = createRequire(import.meta.url);
13
+ let loading;
14
+ /** Resolves to `undefined` when the optional package is not installed. Never throws. */
15
+ export function rasterizer() {
16
+ if (!loading) {
17
+ loading = (async () => {
18
+ let mod;
19
+ try {
20
+ // A variable keeps tsc from resolving the module at build time, so the project still
21
+ // compiles when the optional dependency is absent.
22
+ const name = '@resvg/resvg-wasm';
23
+ mod = (await import(name));
24
+ }
25
+ catch {
26
+ return undefined; // not installed — the only genuinely absent case
27
+ }
28
+ try {
29
+ const wasm = fs.readFileSync(require.resolve('@resvg/resvg-wasm/index_bg.wasm'));
30
+ await mod.initWasm(wasm);
31
+ }
32
+ catch (err) {
33
+ // initWasm() throws "Already initialized. The initWasm() function can be used only
34
+ // once." when another copy of this module has already run it (two dist copies, a test
35
+ // harness, a second server in-process). That is success, not failure.
36
+ const message = err instanceof Error ? err.message : String(err);
37
+ if (!/already initialized/i.test(message))
38
+ return undefined;
39
+ }
40
+ return mod;
41
+ })();
42
+ }
43
+ return loading;
44
+ }
45
+ /**
46
+ * `undefined` means "no rasterizer installed". A malformed SVG throws a plain Error from resvg
47
+ * ("SVG data parsing failed …"); callers report that as `svg-rejected` rather than crashing.
48
+ *
49
+ * There is deliberately no `pixels` field: resvg's pixel buffer is PREMULTIPLIED (Appendix E,
50
+ * R5), so comparing it against `pngjs` output would be silently wrong. Always decode `png`.
51
+ */
52
+ export async function rasterize(svg, scale, background) {
53
+ const mod = await rasterizer();
54
+ if (!mod)
55
+ return undefined;
56
+ const resvg = new mod.Resvg(svg, {
57
+ fitTo: { mode: 'zoom', value: scale },
58
+ background,
59
+ font: { loadSystemFonts: false },
60
+ });
61
+ const img = resvg.render();
62
+ try {
63
+ return { png: img.asPng(), width: img.width, height: img.height };
64
+ }
65
+ finally {
66
+ img.free();
67
+ resvg.free();
68
+ }
69
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The render report (plan §4.12) — what was drawn, what was approximated, what was skipped.
3
+ *
4
+ * This is not a courtesy log. `featuresPresent` is the join key between the exporter, the
5
+ * coverage matrix and the gallery of the visual tester, so the vocabulary (Appendix D) is
6
+ * fixed: never invent a feature string at a call site, add it to `FEATURES` first.
7
+ */
8
+ import type { Box } from './matrix.js';
9
+ export interface FeatureEntry {
10
+ readonly feature: string;
11
+ readonly count: number;
12
+ readonly examples: string[];
13
+ }
14
+ export interface RenderReport {
15
+ root: {
16
+ guid: string;
17
+ name?: string;
18
+ type: string;
19
+ };
20
+ nodesVisited: number;
21
+ nodesDrawn: number;
22
+ bounds: Box;
23
+ width: number;
24
+ height: number;
25
+ scale: number;
26
+ /** Not drawn at all. */
27
+ unsupported: FeatureEntry[];
28
+ /** Drawn, but not exactly the way Figma would. */
29
+ approximated: FeatureEntry[];
30
+ /** Every vocabulary key seen in the subtree, drawn or not — used by the coverage matrix. */
31
+ featuresPresent: string[];
32
+ svgBytes: number;
33
+ renderMs: number;
34
+ rasterMs?: number;
35
+ note?: string;
36
+ }
37
+ /**
38
+ * Appendix D. Parameterised keys are formed with the helpers below so a typo cannot silently
39
+ * create a new feature that the coverage matrix will never recognise.
40
+ */
41
+ export declare const FEATURES: readonly ['image-missing', 'image-crop', 'image-rotation', 'image-filters', 'gradient-singular', 'emoji', 'glyph-rotation', 'text-without-outlines', 'text-property-without-outlines', 'text-stroke', 'text-decoration', 'text-truncation', 'stroke-dashed', 'stroke-without-geometry', 'vector-without-geometry', 'geometry:corrupt', 'geometry:synthesised', 'mask-hidden', 'oversize', 'svg-rejected', 'instance-unresolved', 'instance-recursive', 'instance-property', 'instance-swap', 'node-failed'];
42
+ /** Prefixes of the parameterised keys built by `feat` below. */
43
+ export declare const FEATURE_PREFIXES: readonly ['node-type:', 'paint:', 'effect:', 'blend:', 'mask:', 'stroke-align:', 'image-mode:', 'image-format:'];
44
+ /** True when `feature` is part of the frozen vocabulary; used to guard against typos. */
45
+ export declare function isKnownFeature(feature: string): boolean;
46
+ export declare const feat: {
47
+ nodeType: (type: string) => string;
48
+ paint: (type: string) => string;
49
+ effect: (type: string) => string;
50
+ blend: (mode: string) => string;
51
+ mask: (type: string) => string;
52
+ strokeAlign: (align: string) => string;
53
+ imageMode: (mode: string) => string;
54
+ imageFormat: (mime: string) => string;
55
+ };
56
+ export declare class ReportBuilder {
57
+ nodesVisited: number;
58
+ nodesDrawn: number;
59
+ private readonly unsupportedBuckets;
60
+ private readonly approximatedBuckets;
61
+ private readonly present;
62
+ private static bump;
63
+ /** Not drawn at all. Always also record it as present. */
64
+ unsupported(feature: string, guid?: string): void;
65
+ /** Drawn, but not exactly like Figma. */
66
+ approximated(feature: string, guid?: string): void;
67
+ /** Record a feature as occurring in the subtree, whether or not it was drawn exactly. */
68
+ seen(feature: string): void;
69
+ private static entries;
70
+ finish(base: Omit<RenderReport, 'unsupported' | 'approximated' | 'featuresPresent' | 'nodesVisited' | 'nodesDrawn'>): RenderReport;
71
+ }
72
+ //# sourceMappingURL=report.d.ts.map