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,98 @@
1
+ /**
2
+ * Kiwi primitive decoders (fig-reading-solution.md §4).
3
+ *
4
+ * Direct port of class `BB` in tools/fig2json.mjs, which was validated byte-for-byte against
5
+ * the official `kiwi-schema` package. Do not "improve" these — every later stage desynchronizes
6
+ * within a few fields if a primitive is off by one byte.
7
+ */
8
+ // Scratch buffers for the float32 bit-reinterpretation in varFloat(); module-scoped so the hot
9
+ // decode loop never allocates.
10
+ const F32_INT = new Int32Array(1);
11
+ const F32 = new Float32Array(F32_INT.buffer);
12
+ export class ByteBuffer {
13
+ b;
14
+ i;
15
+ constructor(buf, offset = 0) {
16
+ this.b = buf;
17
+ this.i = offset;
18
+ }
19
+ get remaining() {
20
+ return this.b.length - this.i;
21
+ }
22
+ byte() {
23
+ if (this.i >= this.b.length)
24
+ throw new Error(`read past end at ${this.i}`);
25
+ return this.b[this.i++];
26
+ }
27
+ bytes(n) {
28
+ if (this.i + n > this.b.length)
29
+ throw new Error(`read past end at ${this.i}+${n}`);
30
+ const s = this.b.subarray(this.i, this.i + n);
31
+ this.i += n;
32
+ return s;
33
+ }
34
+ /** Unsigned LEB128, max 5 bytes (32-bit) — mirrors kiwi readVarUint. */
35
+ varUint() {
36
+ let value = 0;
37
+ let shift = 0;
38
+ let b;
39
+ do {
40
+ b = this.byte();
41
+ value |= (b & 127) << shift;
42
+ shift += 7;
43
+ } while (b & 128 && shift < 35);
44
+ return value >>> 0;
45
+ }
46
+ /** Zigzag-encoded signed 32-bit — mirrors kiwi readVarInt. */
47
+ varInt() {
48
+ const v = this.varUint() | 0;
49
+ return v & 1 ? ~(v >>> 1) : v >>> 1;
50
+ }
51
+ /** Unsigned LEB128 up to 9 bytes; the 9th byte contributes all 8 bits. */
52
+ varUint64() {
53
+ let value = 0n;
54
+ let shift = 0n;
55
+ for (;;) {
56
+ const b = this.byte();
57
+ if (shift === 56n) {
58
+ value |= BigInt(b) << 56n;
59
+ break;
60
+ }
61
+ value |= BigInt(b & 127) << shift;
62
+ if (!(b & 128))
63
+ break;
64
+ shift += 7n;
65
+ }
66
+ return value;
67
+ }
68
+ varInt64() {
69
+ const v = this.varUint64();
70
+ return v & 1n ? ~(v >> 1n) : v >> 1n;
71
+ }
72
+ /**
73
+ * Kiwi float32: a single 0x00 byte means 0.0, otherwise 4 bytes bit-rotated so the exponent
74
+ * lands in the first byte (better entropy for compression) — mirrors kiwi readVarFloat.
75
+ * Values decode as float32, so 0.2 legitimately reads back as 0.20000000298023224.
76
+ */
77
+ varFloat() {
78
+ const first = this.byte();
79
+ if (first === 0)
80
+ return 0;
81
+ const b2 = this.byte();
82
+ const b3 = this.byte();
83
+ const b4 = this.byte();
84
+ let bits = first | (b2 << 8) | (b3 << 16) | (b4 << 24);
85
+ bits = (bits << 23) | (bits >>> 9);
86
+ F32_INT[0] = bits;
87
+ return F32[0];
88
+ }
89
+ /** UTF-8 bytes up to (not including) the next NUL; the cursor advances past the NUL. */
90
+ string() {
91
+ const end = this.b.indexOf(0, this.i);
92
+ if (end < 0)
93
+ throw new Error(`unterminated string at ${this.i}`);
94
+ const s = this.b.toString('utf8', this.i, end);
95
+ this.i = end + 1;
96
+ return s;
97
+ }
98
+ }
@@ -0,0 +1,32 @@
1
+ import { ZipArchive } from './zip.js';
2
+ export declare const FIG_KIWI_MAGIC = "fig-kiwi";
3
+ export type Codec = 'zstd' | 'deflate-raw' | 'zlib' | 'stored';
4
+ export interface ChunkInfo {
5
+ readonly index: number;
6
+ readonly compressedSize: number;
7
+ readonly size: number;
8
+ readonly codec: Codec;
9
+ }
10
+ export interface FigStream {
11
+ readonly version: number;
12
+ readonly chunks: readonly Buffer[];
13
+ }
14
+ export interface Container {
15
+ readonly kind: 'zip' | 'bare';
16
+ readonly zip: ZipArchive | undefined;
17
+ /** The raw `fig-kiwi` stream (`canvas.fig` inside a ZIP, or the whole file). */
18
+ readonly stream: Buffer;
19
+ }
20
+ /** Stage A: sniff the container and produce the fig-kiwi stream. Never trusts the extension. */
21
+ export declare function openContainer(buf: Buffer): Container;
22
+ /** Stage B: validate the header and walk the length-prefixed chunks; must land exactly on EOF. */
23
+ export declare function readFigStream(buf: Buffer): FigStream;
24
+ /**
25
+ * Stage C: decompress one chunk, sniffing the codec. Codecs differ BETWEEN chunks of the same
26
+ * file (the sample is deflate for chunk 0 and zstd for chunk 1), so never reuse a decision.
27
+ */
28
+ export declare function decompressChunk(chunk: Buffer): {
29
+ data: Buffer;
30
+ codec: Codec;
31
+ };
32
+ //# sourceMappingURL=container.d.ts.map
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Container sniffing, chunk framing and per-chunk decompression
3
+ * (fig-reading-solution.md §1–§3).
4
+ *
5
+ * Every sniff point fails loudly with the observed magic bytes: a future container or codec
6
+ * change should be a five-minute diagnosis, not a mystery.
7
+ */
8
+ import * as zlib from 'node:zlib';
9
+ import { ZipArchive, looksLikeZip } from './zip.js';
10
+ export const FIG_KIWI_MAGIC = 'fig-kiwi';
11
+ const ZSTD_MAGIC = 0xfd2fb528;
12
+ function hexDump(buf, n = 16) {
13
+ return [...buf.subarray(0, n)].map((b) => b.toString(16).padStart(2, '0')).join(' ');
14
+ }
15
+ /** Stage A: sniff the container and produce the fig-kiwi stream. Never trusts the extension. */
16
+ export function openContainer(buf) {
17
+ if (looksLikeZip(buf)) {
18
+ const zip = new ZipArchive(buf);
19
+ const stream = zip.read('canvas.fig');
20
+ if (!stream) {
21
+ throw new Error(`.fig ZIP has no canvas.fig entry (entries: ${zip.names().slice(0, 10).join(', ')}${zip.size > 10 ? ', …' : ''})`);
22
+ }
23
+ return { kind: 'zip', zip, stream };
24
+ }
25
+ if (buf.length >= 8 && buf.toString('latin1', 0, 8) === FIG_KIWI_MAGIC) {
26
+ return { kind: 'bare', zip: undefined, stream: buf };
27
+ }
28
+ throw new Error(`not a readable .fig: expected ZIP (50 4b 03 04) or "fig-kiwi" magic, got ${hexDump(buf)}`);
29
+ }
30
+ /** Stage B: validate the header and walk the length-prefixed chunks; must land exactly on EOF. */
31
+ export function readFigStream(buf) {
32
+ if (buf.length < 12 || buf.toString('latin1', 0, 8) !== FIG_KIWI_MAGIC) {
33
+ throw new Error(`bad fig-kiwi magic: ${hexDump(buf)}`);
34
+ }
35
+ const version = buf.readUInt32LE(8);
36
+ const chunks = [];
37
+ let off = 12;
38
+ while (off < buf.length) {
39
+ if (off + 4 > buf.length) {
40
+ throw new Error(`truncated chunk length prefix at offset ${off} (file ends at ${buf.length})`);
41
+ }
42
+ const size = buf.readUInt32LE(off);
43
+ off += 4;
44
+ if (off + size > buf.length) {
45
+ throw new Error(`chunk ${chunks.length} overruns file: needs ${size} bytes at ${off}, only ${buf.length - off} left`);
46
+ }
47
+ chunks.push(buf.subarray(off, off + size));
48
+ off += size;
49
+ }
50
+ if (off !== buf.length)
51
+ throw new Error(`chunk walk ended at ${off}, file length ${buf.length}`);
52
+ if (chunks.length < 2)
53
+ throw new Error(`expected >= 2 chunks (schema, data), got ${chunks.length}`);
54
+ return { version, chunks };
55
+ }
56
+ /**
57
+ * Stage C: decompress one chunk, sniffing the codec. Codecs differ BETWEEN chunks of the same
58
+ * file (the sample is deflate for chunk 0 and zstd for chunk 1), so never reuse a decision.
59
+ */
60
+ export function decompressChunk(chunk) {
61
+ if (chunk.length >= 4 && chunk.readUInt32LE(0) === ZSTD_MAGIC) {
62
+ return { data: zlib.zstdDecompressSync(chunk), codec: 'zstd' };
63
+ }
64
+ try {
65
+ return { data: zlib.inflateRawSync(chunk), codec: 'deflate-raw' };
66
+ }
67
+ catch {
68
+ /* not raw deflate */
69
+ }
70
+ try {
71
+ return { data: zlib.inflateSync(chunk), codec: 'zlib' };
72
+ }
73
+ catch {
74
+ /* not zlib */
75
+ }
76
+ // "Stored" is the last resort, and only plausible for a chunk that is not obviously garbage.
77
+ if (chunk.length === 0)
78
+ throw new Error('empty chunk');
79
+ return { data: chunk, codec: 'stored' };
80
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Content-type and dimension sniffing for the bitmaps stored under `images/` in a .fig ZIP
3
+ * (fig-reading-solution.md §9.11 — the bytes are the original PNG/JPEG/GIF/WebP).
4
+ *
5
+ * Byte-level and format-agnostic, so it lives in Layer 1. Dimensions are read from the header
6
+ * only; nothing is decoded.
7
+ */
8
+ export interface ImageMeta {
9
+ mime: string;
10
+ extension: string;
11
+ byteLength: number;
12
+ width?: number;
13
+ height?: number;
14
+ }
15
+ /** Identify image bytes by magic number; unknown content becomes application/octet-stream. */
16
+ export declare function sniffImage(buf: Buffer): ImageMeta;
17
+ //# sourceMappingURL=imagemeta.d.ts.map
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Content-type and dimension sniffing for the bitmaps stored under `images/` in a .fig ZIP
3
+ * (fig-reading-solution.md §9.11 — the bytes are the original PNG/JPEG/GIF/WebP).
4
+ *
5
+ * Byte-level and format-agnostic, so it lives in Layer 1. Dimensions are read from the header
6
+ * only; nothing is decoded.
7
+ */
8
+ function startsWith(buf, bytes, offset = 0) {
9
+ if (buf.length < offset + bytes.length)
10
+ return false;
11
+ for (let i = 0; i < bytes.length; i++)
12
+ if (buf[offset + i] !== bytes[i])
13
+ return false;
14
+ return true;
15
+ }
16
+ /** JPEG dimensions live in the first SOFn marker; walk the segment chain to find it. */
17
+ function jpegSize(buf) {
18
+ let i = 2;
19
+ while (i + 9 < buf.length) {
20
+ if (buf[i] !== 0xff) {
21
+ i++;
22
+ continue;
23
+ }
24
+ const marker = buf[i + 1];
25
+ // SOF0..SOF15, excluding DHT (c4), JPG (c8) and DAC (cc).
26
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
27
+ return { height: buf.readUInt16BE(i + 5), width: buf.readUInt16BE(i + 7) };
28
+ }
29
+ if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
30
+ i += 2;
31
+ continue;
32
+ }
33
+ if (i + 4 > buf.length)
34
+ break;
35
+ i += 2 + buf.readUInt16BE(i + 2);
36
+ }
37
+ return undefined;
38
+ }
39
+ function webpSize(buf) {
40
+ const fourcc = buf.toString('latin1', 12, 16);
41
+ if (fourcc === 'VP8X' && buf.length >= 30) {
42
+ return {
43
+ width: (buf.readUIntLE(24, 3) & 0xffffff) + 1,
44
+ height: (buf.readUIntLE(27, 3) & 0xffffff) + 1,
45
+ };
46
+ }
47
+ if (fourcc === 'VP8 ' && buf.length >= 30) {
48
+ return { width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff };
49
+ }
50
+ if (fourcc === 'VP8L' && buf.length >= 25) {
51
+ const bits = buf.readUInt32LE(21);
52
+ return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
53
+ }
54
+ return undefined;
55
+ }
56
+ /** Identify image bytes by magic number; unknown content becomes application/octet-stream. */
57
+ export function sniffImage(buf) {
58
+ const byteLength = buf.length;
59
+ if (startsWith(buf, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) {
60
+ // IHDR is always the first chunk: width/height are big-endian u32 at 16 and 20.
61
+ const dims = buf.length >= 24 ? { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) } : {};
62
+ return { mime: 'image/png', extension: 'png', byteLength, ...dims };
63
+ }
64
+ if (startsWith(buf, [0xff, 0xd8, 0xff])) {
65
+ return { mime: 'image/jpeg', extension: 'jpg', byteLength, ...(jpegSize(buf) ?? {}) };
66
+ }
67
+ if (startsWith(buf, [0x47, 0x49, 0x46, 0x38])) {
68
+ const dims = buf.length >= 10 ? { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) } : {};
69
+ return { mime: 'image/gif', extension: 'gif', byteLength, ...dims };
70
+ }
71
+ if (startsWith(buf, [0x52, 0x49, 0x46, 0x46]) && buf.toString('latin1', 8, 12) === 'WEBP') {
72
+ return { mime: 'image/webp', extension: 'webp', byteLength, ...(webpSize(buf) ?? {}) };
73
+ }
74
+ if (startsWith(buf, [0x42, 0x4d]) && buf.length >= 26) {
75
+ return {
76
+ mime: 'image/bmp',
77
+ extension: 'bmp',
78
+ byteLength,
79
+ width: buf.readInt32LE(18),
80
+ height: Math.abs(buf.readInt32LE(22)),
81
+ };
82
+ }
83
+ if (buf.length >= 12 && buf.toString('latin1', 4, 8) === 'ftyp') {
84
+ const brand = buf.toString('latin1', 8, 12);
85
+ if (brand.startsWith('avif'))
86
+ return { mime: 'image/avif', extension: 'avif', byteLength };
87
+ if (brand.startsWith('heic') || brand.startsWith('mif1')) {
88
+ return { mime: 'image/heic', extension: 'heic', byteLength };
89
+ }
90
+ }
91
+ const head = buf.toString('utf8', 0, Math.min(256, buf.length)).trimStart();
92
+ if (head.startsWith('<svg') || (head.startsWith('<?xml') && head.includes('<svg'))) {
93
+ return { mime: 'image/svg+xml', extension: 'svg', byteLength };
94
+ }
95
+ return { mime: 'application/octet-stream', extension: 'bin', byteLength };
96
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Post-parse validation (fig-reading-solution.md §7).
3
+ *
4
+ * Policy: structural corruption throws (already handled by the exact-consumption asserts in
5
+ * container/kiwi); everything else is reported as a warning so a slightly unusual file still
6
+ * yields a fully usable document.
7
+ */
8
+ import type { ParsedFig } from './parse.js';
9
+ export declare function checkInvariants(fig: ParsedFig): string[];
10
+ //# sourceMappingURL=invariants.d.ts.map
@@ -0,0 +1,63 @@
1
+ export function checkInvariants(fig) {
2
+ const warnings = [];
3
+ const type = fig.message['type'];
4
+ if (type !== 'NODE_CHANGES') {
5
+ warnings.push(`message.type is ${JSON.stringify(type)}, expected "NODE_CHANGES"`);
6
+ }
7
+ if (!Array.isArray(fig.message['nodeChanges'])) {
8
+ throw new Error('decoded message has no nodeChanges array — not a document snapshot');
9
+ }
10
+ // Exactly one DOCUMENT root, and no node whose parent is missing.
11
+ const keys = new Set();
12
+ let documents = 0;
13
+ for (const nc of fig.nodeChanges) {
14
+ const guid = nc['guid'];
15
+ if (guid)
16
+ keys.add(`${guid.sessionID}:${guid.localID}`);
17
+ if (nc['type'] === 'DOCUMENT')
18
+ documents++;
19
+ }
20
+ if (documents !== 1)
21
+ warnings.push(`expected exactly 1 DOCUMENT node, found ${documents}`);
22
+ let orphans = 0;
23
+ for (const nc of fig.nodeChanges) {
24
+ if (nc['type'] === 'DOCUMENT')
25
+ continue;
26
+ const pi = nc['parentIndex'];
27
+ const pg = pi?.guid;
28
+ if (!pg || !keys.has(`${pg.sessionID}:${pg.localID}`))
29
+ orphans++;
30
+ }
31
+ if (orphans > 0)
32
+ warnings.push(`${orphans} node(s) have no resolvable parent`);
33
+ // Every image fill must resolve to an images/<sha1> entry; a miss is "unavailable", not fatal.
34
+ if (fig.zip) {
35
+ const present = new Set(fig.zip
36
+ .names()
37
+ .filter((n) => n.startsWith('images/') && n.length > 'images/'.length)
38
+ .map((n) => n.slice('images/'.length)));
39
+ const missing = new Set();
40
+ let referenced = 0;
41
+ for (const nc of fig.nodeChanges) {
42
+ for (const key of ['fillPaints', 'strokePaints']) {
43
+ const paints = nc[key];
44
+ if (!Array.isArray(paints))
45
+ continue;
46
+ for (const paint of paints) {
47
+ const hash = paint['image']?.['hash'];
48
+ if (!(hash instanceof Uint8Array))
49
+ continue;
50
+ referenced++;
51
+ const hex = Buffer.from(hash).toString('hex');
52
+ if (!present.has(hex))
53
+ missing.add(hex);
54
+ }
55
+ }
56
+ }
57
+ if (missing.size > 0) {
58
+ warnings.push(`${missing.size} image hash(es) referenced by paints are not in images/ ` +
59
+ `(first: ${[...missing][0]}; ${referenced} paint references total)`);
60
+ }
61
+ }
62
+ return warnings;
63
+ }
@@ -0,0 +1,38 @@
1
+ export declare const BUILTINS: readonly ['bool', 'byte', 'int', 'uint', 'float', 'string', 'int64', 'uint64'];
2
+ declare const KINDS: readonly ['ENUM', 'STRUCT', 'MESSAGE'];
3
+ export type DefKind = (typeof KINDS)[number];
4
+ export interface KiwiField {
5
+ readonly name: string;
6
+ /** >= 0: index into the definition table; < 0: builtin, index = ~type. */
7
+ readonly type: number;
8
+ readonly isArray: boolean;
9
+ /** MESSAGE: wire field id. ENUM: the enum member's numeric value. STRUCT: unused. */
10
+ readonly value: number;
11
+ }
12
+ export interface KiwiDefinition {
13
+ readonly name: string;
14
+ readonly kind: DefKind;
15
+ readonly fields: readonly KiwiField[];
16
+ /** MESSAGE only: field id → field. Built once at decode time. */
17
+ fieldById?: Map<number, KiwiField>;
18
+ /** ENUM only: numeric value → member name. Built once at decode time. */
19
+ enumByValue?: Map<number, string>;
20
+ }
21
+ export type KiwiSchema = readonly KiwiDefinition[];
22
+ /** Anything a decoded Kiwi value can be. `byte[]` fields decode to plain Uint8Array. */
23
+ export type KiwiValue = boolean | number | bigint | string | Uint8Array | KiwiValue[] | KiwiObject;
24
+ export interface KiwiObject {
25
+ [key: string]: KiwiValue | undefined;
26
+ }
27
+ /** Decode chunk 0 (decompressed) — the binary schema. */
28
+ export declare function decodeBinarySchema(buf: Buffer): KiwiDefinition[];
29
+ /** Render a decoded schema as Kiwi source text — the authoritative field reference. */
30
+ export declare function schemaToText(defs: KiwiSchema): string;
31
+ export interface KiwiDecoder {
32
+ /** Decode `buf` as the definition named `rootName`; asserts exact byte consumption. */
33
+ decode(rootName: string, buf: Buffer): KiwiObject;
34
+ readonly definitions: KiwiSchema;
35
+ }
36
+ export declare function makeDecoder(defs: KiwiSchema): KiwiDecoder;
37
+ export {};
38
+ //# sourceMappingURL=kiwi.d.ts.map
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Kiwi binary-schema decoding and schema-driven data decoding
3
+ * (fig-reading-solution.md §5 and §6).
4
+ *
5
+ * The schema ships inside the .fig file, so nothing here hardcodes a field id or a type name.
6
+ * That is precisely what makes the reader survive Figma's unannounced schema changes.
7
+ */
8
+ import { ByteBuffer } from './bytebuffer.js';
9
+ export const BUILTINS = ['bool', 'byte', 'int', 'uint', 'float', 'string', 'int64', 'uint64'];
10
+ const KINDS = ['ENUM', 'STRUCT', 'MESSAGE'];
11
+ /** ~type for the `byte` builtin — the one array type with raw length-prefixed bytes. */
12
+ const BYTE_TYPE = ~BUILTINS.indexOf('byte');
13
+ /** Decode chunk 0 (decompressed) — the binary schema. */
14
+ export function decodeBinarySchema(buf) {
15
+ const bb = new ByteBuffer(buf);
16
+ const count = bb.varUint();
17
+ const defs = [];
18
+ for (let i = 0; i < count; i++) {
19
+ const name = bb.string();
20
+ const kindByte = bb.byte();
21
+ const kind = KINDS[kindByte];
22
+ if (!kind)
23
+ throw new Error(`schema: definition "${name}" has unknown kind byte ${kindByte}`);
24
+ const fieldCount = bb.varUint();
25
+ const fields = [];
26
+ for (let j = 0; j < fieldCount; j++) {
27
+ fields.push({
28
+ name: bb.string(),
29
+ type: bb.varInt(),
30
+ isArray: !!(bb.byte() & 1),
31
+ value: bb.varUint(),
32
+ });
33
+ }
34
+ defs.push({ name, kind, fields });
35
+ }
36
+ if (bb.remaining !== 0)
37
+ throw new Error(`schema: ${bb.remaining} trailing bytes`);
38
+ return defs;
39
+ }
40
+ /** Render a decoded schema as Kiwi source text — the authoritative field reference. */
41
+ export function schemaToText(defs) {
42
+ const typeName = (t) => (t < 0 ? BUILTINS[~t] : (defs[t]?.name ?? `#${t}`));
43
+ const out = [];
44
+ for (const d of defs) {
45
+ out.push(`${d.kind.toLowerCase()} ${d.name} {`);
46
+ for (const f of d.fields) {
47
+ out.push(d.kind === 'ENUM'
48
+ ? ` ${f.name} = ${f.value};`
49
+ : ` ${typeName(f.type)}${f.isArray ? '[]' : ''} ${f.name} = ${f.value};`);
50
+ }
51
+ out.push('}', '');
52
+ }
53
+ return out.join('\n');
54
+ }
55
+ export function makeDecoder(defs) {
56
+ const byName = new Map();
57
+ for (const d of defs) {
58
+ byName.set(d.name, d);
59
+ if (d.kind === 'MESSAGE')
60
+ d.fieldById = new Map(d.fields.map((f) => [f.value, f]));
61
+ else if (d.kind === 'ENUM')
62
+ d.enumByValue = new Map(d.fields.map((f) => [f.value, f.name]));
63
+ }
64
+ function decodeType(bb, type) {
65
+ if (type < 0) {
66
+ switch (BUILTINS[~type]) {
67
+ case 'bool':
68
+ return bb.byte() !== 0;
69
+ case 'byte':
70
+ return bb.byte();
71
+ case 'int':
72
+ return bb.varInt();
73
+ case 'uint':
74
+ return bb.varUint();
75
+ case 'float':
76
+ return bb.varFloat();
77
+ case 'string':
78
+ return bb.string();
79
+ case 'int64':
80
+ return bb.varInt64();
81
+ case 'uint64':
82
+ return bb.varUint64();
83
+ default:
84
+ throw new Error(`unknown builtin type ${type} at byte ${bb.i}`);
85
+ }
86
+ }
87
+ const def = defs[type];
88
+ if (!def)
89
+ throw new Error(`type index ${type} out of range at byte ${bb.i}`);
90
+ if (def.kind === 'ENUM') {
91
+ const v = bb.varUint();
92
+ // New enum members appear over time; surface the raw number rather than throwing.
93
+ return def.enumByValue?.get(v) ?? v;
94
+ }
95
+ return decodeDef(bb, def);
96
+ }
97
+ function readField(bb, f) {
98
+ if (f.isArray) {
99
+ const len = bb.varUint();
100
+ // byte[] is a length prefix followed by raw bytes. Copy into a plain Uint8Array: a Buffer
101
+ // view would (a) pin the whole decompressed chunk and (b) hijack JSON.stringify through
102
+ // Buffer#toJSON before any replacer runs.
103
+ if (f.type === BYTE_TYPE)
104
+ return new Uint8Array(bb.bytes(len));
105
+ const arr = new Array(len);
106
+ for (let k = 0; k < len; k++)
107
+ arr[k] = decodeType(bb, f.type);
108
+ return arr;
109
+ }
110
+ return decodeType(bb, f.type);
111
+ }
112
+ function decodeDef(bb, def) {
113
+ const obj = {};
114
+ if (def.kind === 'STRUCT') {
115
+ // Structs are positional: every field, in schema order, no tags, no terminator.
116
+ for (const f of def.fields)
117
+ obj[f.name] = readField(bb, f);
118
+ return obj;
119
+ }
120
+ for (;;) {
121
+ // Messages are (varuint field-id, value)* terminated by id 0; unset fields are absent.
122
+ const tag = bb.varUint();
123
+ if (tag === 0)
124
+ return obj;
125
+ const f = def.fieldById?.get(tag);
126
+ if (!f)
127
+ throw new Error(`unknown field id ${tag} in ${def.name} at byte ${bb.i}`);
128
+ obj[f.name] = readField(bb, f);
129
+ }
130
+ }
131
+ return {
132
+ definitions: defs,
133
+ decode(rootName, buf) {
134
+ const def = byName.get(rootName);
135
+ if (!def)
136
+ throw new Error(`no definition named ${rootName}`);
137
+ const bb = new ByteBuffer(buf);
138
+ const result = decodeDef(bb, def);
139
+ if (bb.remaining !== 0)
140
+ throw new Error(`data: ${bb.remaining} trailing bytes`);
141
+ return result;
142
+ },
143
+ };
144
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * parseFig — the whole Stage A→D pipeline in one call (fig-reading-solution.md §0).
3
+ *
4
+ * Layer 1 boundary: this module knows bytes, chunks and Kiwi. It knows nothing about frames,
5
+ * paints or auto-layout — that lives in ../model.
6
+ */
7
+ import { type ChunkInfo } from './container.js';
8
+ import { type KiwiDefinition, type KiwiObject } from './kiwi.js';
9
+ import type { ZipArchive } from './zip.js';
10
+ /** A decoded `NodeChange`: an open record, because the schema grows constantly. */
11
+ export type NodeChange = KiwiObject;
12
+ export interface FigMeta {
13
+ readonly file_name?: string;
14
+ readonly exported_at?: string;
15
+ readonly [key: string]: unknown;
16
+ }
17
+ export interface ParsedFig {
18
+ readonly container: 'zip' | 'bare';
19
+ /** ZIP entries (images/, thumbnail.png, meta.json); undefined for bare streams. */
20
+ readonly zip: ZipArchive | undefined;
21
+ readonly meta: FigMeta | undefined;
22
+ readonly version: number;
23
+ readonly chunks: readonly ChunkInfo[];
24
+ readonly schema: readonly KiwiDefinition[];
25
+ readonly message: KiwiObject;
26
+ readonly nodeChanges: readonly NodeChange[];
27
+ readonly blobs: readonly KiwiObject[];
28
+ /** Non-fatal observations (unresolved images, odd counts). Structural corruption throws. */
29
+ readonly warnings: readonly string[];
30
+ readonly parseMs: number;
31
+ }
32
+ export interface ParseOptions {
33
+ /** Skip §7 invariant checks (used by micro-benchmarks; on by default). */
34
+ readonly checkInvariants?: boolean;
35
+ }
36
+ export declare function parseFig(buf: Buffer, opts?: ParseOptions): ParsedFig;
37
+ //# sourceMappingURL=parse.d.ts.map