@pairdraw/kiwi 0.0.0-stage → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +28 -0
  3. package/README.md +112 -2
  4. package/dist/chunks/fig/codec.js +1371 -0
  5. package/dist/chunks/fig/codec.js.map +1 -0
  6. package/dist/fig/codec.d.ts +477 -0
  7. package/dist/fig/codec.js +2 -0
  8. package/dist/fig/container.d.ts +48 -0
  9. package/dist/fig/container.js +2 -0
  10. package/dist/fig/guid.d.ts +13 -0
  11. package/dist/fig/guid.js +31 -0
  12. package/dist/fig/guid.js.map +1 -0
  13. package/dist/fig/parse.d.ts +33 -0
  14. package/dist/fig/parse.js +83 -0
  15. package/dist/fig/parse.js.map +1 -0
  16. package/dist/fig.d.ts +185 -0
  17. package/dist/fig.js +117 -0
  18. package/dist/fig.js.map +1 -0
  19. package/dist/index.d.ts +182 -0
  20. package/dist/page-manifest.d.ts +16 -0
  21. package/dist/schema-runtime.d.ts +2 -0
  22. package/dist/schema-runtime.js +2 -0
  23. package/dist/types.d.ts +26 -0
  24. package/package.json +64 -4
  25. package/src/fig/codec.ts +536 -0
  26. package/src/fig/container.ts +180 -0
  27. package/src/fig/guid.ts +24 -0
  28. package/src/fig/index.ts +5 -0
  29. package/src/fig/page-manifest.ts +149 -0
  30. package/src/fig/parse.ts +136 -0
  31. package/src/fig/protocol.ts +237 -0
  32. package/src/fig/schema/fig.kiwi +5628 -0
  33. package/src/fig/schema.ts +7 -0
  34. package/src/fig/types.ts +25 -0
  35. package/src/fig/variable-bindings.ts +11 -0
  36. package/src/global.d.ts +4 -0
  37. package/src/schema-runtime/bb.ts +284 -0
  38. package/src/schema-runtime/binary.ts +102 -0
  39. package/src/schema-runtime/index.ts +25 -0
  40. package/src/schema-runtime/interpreter.ts +465 -0
  41. package/src/schema-runtime/parser.ts +287 -0
  42. package/src/schema-runtime/schema.ts +24 -0
  43. package/src/schema-runtime/util.ts +10 -0
  44. package/src/schema-runtime/validate.ts +88 -0
@@ -0,0 +1,24 @@
1
+ import type { GUID } from './types'
2
+
3
+ /**
4
+ * Kiwi's all-ones GUID names no node: a cleared style reference, a slot's own content, or a
5
+ * layer without an override key.
6
+ */
7
+ export const UNSET_GUID: Readonly<GUID> = { sessionID: 0xffffffff, localID: 0xffffffff }
8
+
9
+ export function isUnsetGuid(guid: GUID): boolean {
10
+ return guid.sessionID === UNSET_GUID.sessionID && guid.localID === UNSET_GUID.localID
11
+ }
12
+
13
+ export function guidToString(guid: GUID): string {
14
+ return `${guid.sessionID}:${guid.localID}`
15
+ }
16
+
17
+ export function stringToGuid(str: string): GUID {
18
+ const match = str.match(/^(?:VariableID:|VariableCollectionId:)?(\d+):(\d+)$/)
19
+ if (match) {
20
+ return { sessionID: Number.parseInt(match[1], 10), localID: Number.parseInt(match[2], 10) }
21
+ }
22
+ const [session, local] = str.split(':')
23
+ return { sessionID: Number.parseInt(session, 10), localID: Number.parseInt(local, 10) }
24
+ }
@@ -0,0 +1,5 @@
1
+ export { default as figmaSchema } from './schema'
2
+ export * from './page-manifest'
3
+ export * from './protocol'
4
+ export * from './types'
5
+ export * from './variable-bindings'
@@ -0,0 +1,149 @@
1
+ import { ByteBuffer } from '../schema-runtime/bb'
2
+ import type { CompiledDefinition, CompiledSchema } from '../schema-runtime/interpreter'
3
+
4
+ export interface FigPageManifestEntry {
5
+ sourceId: string
6
+ name: string
7
+ position: string | null
8
+ internalOnly: boolean
9
+ }
10
+
11
+ interface PageCandidate extends FigPageManifestEntry {
12
+ parentId: string | null
13
+ phase: string | null
14
+ type: string | null
15
+ }
16
+
17
+ function enumName(bb: ByteBuffer, definition: CompiledDefinition | null): string | null {
18
+ const value = bb.readVarUint()
19
+ return definition?.kind === 'ENUM' ? (definition.names[value] ?? null) : null
20
+ }
21
+
22
+ function scanNodeChange(
23
+ bb: ByteBuffer,
24
+ schema: CompiledSchema,
25
+ nodeChange: CompiledDefinition
26
+ ): PageCandidate | null {
27
+ let sourceSessionId: number | null = null
28
+ let sourceLocalId: number | null = null
29
+ let parentSessionId: number | null = null
30
+ let parentLocalId: number | null = null
31
+ let positionOffset: number | null = null
32
+ let phase: string | null = null
33
+ let type: string | null = null
34
+ let name: string | null = null
35
+ let internalOnly = false
36
+
37
+ for (let fieldId = bb.readVarUint(); fieldId !== 0; fieldId = bb.readVarUint()) {
38
+ const field = nodeChange.byId[fieldId]
39
+ if (!field) throw new Error(`Invalid field ${fieldId} in Kiwi NodeChange`)
40
+ switch (field.name) {
41
+ case 'guid':
42
+ sourceSessionId = bb.readVarUint()
43
+ sourceLocalId = bb.readVarUint()
44
+ break
45
+ case 'parentIndex':
46
+ parentSessionId = bb.readVarUint()
47
+ parentLocalId = bb.readVarUint()
48
+ positionOffset = bb.offset
49
+ bb.skipString()
50
+ break
51
+ case 'phase':
52
+ phase = enumName(bb, field.definition)
53
+ break
54
+ case 'type':
55
+ type = enumName(bb, field.definition)
56
+ break
57
+ case 'name':
58
+ if (type === 'DOCUMENT' || type === 'CANVAS') name = bb.readString()
59
+ else bb.skipString()
60
+ break
61
+ case 'internalOnly':
62
+ internalOnly = !!bb.readByte()
63
+ break
64
+ default:
65
+ schema.skip(field, bb)
66
+ }
67
+ }
68
+
69
+ if (
70
+ (type !== 'DOCUMENT' && type !== 'CANVAS') ||
71
+ sourceSessionId === null ||
72
+ sourceLocalId === null
73
+ ) {
74
+ return null
75
+ }
76
+ let position: string | null = null
77
+ if (positionOffset !== null) {
78
+ const endOffset = bb.offset
79
+ bb.offset = positionOffset
80
+ position = bb.readString()
81
+ bb.offset = endOffset
82
+ }
83
+ const parentId =
84
+ parentSessionId === null || parentLocalId === null
85
+ ? null
86
+ : `${parentSessionId}:${parentLocalId}`
87
+ return {
88
+ sourceId: `${sourceSessionId}:${sourceLocalId}`,
89
+ parentId,
90
+ position,
91
+ phase,
92
+ type,
93
+ name: name ?? 'Page',
94
+ internalOnly
95
+ }
96
+ }
97
+
98
+ /**
99
+ * Scans encoded Kiwi bytes without materializing NodeChange objects. Kiwi messages are not
100
+ * length-prefixed, so every value is visited, but only document/page fields are allocated.
101
+ */
102
+ export function extractFigPageManifest(
103
+ schema: CompiledSchema,
104
+ data: Uint8Array
105
+ ): FigPageManifestEntry[] {
106
+ const message = schema.definition('Message')
107
+ const nodeChange = schema.definition('NodeChange')
108
+ if (message.kind !== 'MESSAGE' || nodeChange.kind !== 'MESSAGE') return []
109
+
110
+ const bb = new ByteBuffer(data)
111
+ const candidates: PageCandidate[] = []
112
+ for (let fieldId = bb.readVarUint(); fieldId !== 0; fieldId = bb.readVarUint()) {
113
+ const field = message.byId[fieldId]
114
+ if (!field) throw new Error(`Invalid field ${fieldId} in Kiwi Message`)
115
+ if (field.name !== 'nodeChanges' || !field.isArray) {
116
+ schema.skip(field, bb)
117
+ continue
118
+ }
119
+ for (let length = bb.readVarUint(); length > 0; length--) {
120
+ const candidate = scanNodeChange(bb, schema, nodeChange)
121
+ if (candidate) candidates.push(candidate)
122
+ }
123
+ break
124
+ }
125
+
126
+ const documentId = candidates.find(
127
+ (candidate) => candidate.type === 'DOCUMENT' && candidate.phase !== 'REMOVED'
128
+ )?.sourceId
129
+ return candidates
130
+ .filter(
131
+ (candidate) =>
132
+ candidate.type === 'CANVAS' &&
133
+ candidate.phase !== 'REMOVED' &&
134
+ (!documentId || candidate.parentId === documentId)
135
+ )
136
+ .sort((a, b) => {
137
+ const aPosition = a.position ?? ''
138
+ const bPosition = b.position ?? ''
139
+ if (aPosition < bPosition) return -1
140
+ if (aPosition > bPosition) return 1
141
+ return 0
142
+ })
143
+ .map(({ sourceId, name, position, internalOnly }) => ({
144
+ sourceId,
145
+ name,
146
+ position,
147
+ internalOnly
148
+ }))
149
+ }
@@ -0,0 +1,136 @@
1
+ import { inflateSync } from 'fflate'
2
+
3
+ import {
4
+ decodeBinarySchema,
5
+ compileSchema,
6
+ ByteBuffer,
7
+ type HeaderFields,
8
+ type RuntimeMessage
9
+ } from '../schema-runtime'
10
+ import type { NodeChange } from './codec'
11
+ import { decompressFigKiwiData, figFileKind, type FigFileKind } from './container'
12
+ import { extractFigPageManifest, type FigPageManifestEntry } from './page-manifest'
13
+
14
+ /**
15
+ * Deduplicates pluginData/pluginRelaunchData entries on raw NodeChange objects.
16
+ * Some .fig files have millions of identical entries where only a small
17
+ * fraction are unique by full triple.
18
+ * Full-triple key (id+key+value) preserves multi-entry subsystems like OkHCL.
19
+ */
20
+ export function deduplicateNodeChangePluginData(nodeChanges: NodeChange[]): void {
21
+ for (const nc of nodeChanges) {
22
+ if (nc.pluginData && nc.pluginData.length > 1) {
23
+ const map = new Map<string, (typeof nc.pluginData)[number]>()
24
+ for (const entry of nc.pluginData) {
25
+ map.set(`${entry.pluginID}\0${entry.key}\0${entry.value}`, entry)
26
+ }
27
+ if (map.size < nc.pluginData.length) {
28
+ nc.pluginData = [...map.values()]
29
+ }
30
+ }
31
+ if (nc.pluginRelaunchData && nc.pluginRelaunchData.length > 1) {
32
+ const map = new Map<string, (typeof nc.pluginRelaunchData)[number]>()
33
+ for (const entry of nc.pluginRelaunchData) {
34
+ map.set(`${entry.pluginID}\0${entry.command}\0${entry.message}\0${entry.isDeleted}`, entry)
35
+ }
36
+ if (map.size < nc.pluginRelaunchData.length) {
37
+ nc.pluginRelaunchData = [...map.values()]
38
+ }
39
+ }
40
+ }
41
+ }
42
+
43
+ interface FigKiwiPayload {
44
+ schemaDeflated: Uint8Array
45
+ dataRaw: Uint8Array
46
+ version: number
47
+ kind: FigFileKind
48
+ }
49
+
50
+ export function parseFigKiwiContainer(data: Uint8Array): FigKiwiPayload | null {
51
+ const kind = figFileKind(data)
52
+ if (!kind) return null
53
+
54
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength)
55
+ const version = view.getUint32(8, true)
56
+ let offset = 12
57
+
58
+ const chunks: Uint8Array[] = []
59
+ while (offset < data.length) {
60
+ if (offset + 4 > data.length) break
61
+ const len = view.getUint32(offset, true)
62
+ offset += 4
63
+ if (offset + len > data.length) {
64
+ throw new Error(
65
+ `Corrupted .fig file: chunk at offset ${offset - 4} declares length ${len} but only ${data.length - offset} bytes remain`
66
+ )
67
+ }
68
+ chunks.push(data.slice(offset, offset + len))
69
+ offset += len
70
+ }
71
+ if (chunks.length < 2) return null
72
+
73
+ return { schemaDeflated: chunks[0], dataRaw: decompressFigKiwiData(chunks[1]), version, kind }
74
+ }
75
+
76
+ function isRuntimeMessage(value: unknown): value is RuntimeMessage {
77
+ return (
78
+ typeof value === 'object' &&
79
+ value !== null &&
80
+ !Array.isArray(value) &&
81
+ !(value instanceof Uint8Array)
82
+ )
83
+ }
84
+
85
+ export interface FigKiwiDecodeResult {
86
+ nodeChanges: NodeChange[]
87
+ blobs: Uint8Array[]
88
+ figKiwiVersion: number
89
+ /** Deflated kiwi schema bytes from the original file (for roundtrip fidelity). */
90
+ figSchemaDeflated: Uint8Array
91
+ /** A design file or a FigJam board, by the canvas's header. */
92
+ kind: FigFileKind
93
+ }
94
+
95
+ /** Decode one raw `fig-kiwi` canvas payload. Outer `.fig` archive handling lives in `@pairdraw/fig`. */
96
+ export function decodeFigKiwiCanvas(
97
+ data: Uint8Array,
98
+ onPages?: (pages: FigPageManifestEntry[]) => void,
99
+ headers?: HeaderFields
100
+ ): FigKiwiDecodeResult {
101
+ const payload = parseFigKiwiContainer(data)
102
+ if (!payload) throw new Error('Invalid fig-kiwi container')
103
+
104
+ const schemaBytes = inflateSync(payload.schemaDeflated)
105
+ const compiled = compileSchema(decodeBinarySchema(new ByteBuffer(schemaBytes)), headers)
106
+ if (onPages) {
107
+ try {
108
+ const pages = extractFigPageManifest(compiled.schema, payload.dataRaw)
109
+ if (pages.length > 0) onPages(pages)
110
+ } catch (error) {
111
+ console.warn('Failed to scan FIG page manifest; continuing with full decode:', error)
112
+ }
113
+ }
114
+ if (!compiled.decodeMessage) throw new Error('The fig-kiwi schema has no Message')
115
+ const message = compiled.decodeMessage(payload.dataRaw)
116
+
117
+ const records = message.nodeChanges
118
+ if (!Array.isArray(records) || records.length === 0) {
119
+ throw new Error('No nodes found in .fig file')
120
+ }
121
+ const nodeChanges = records as NodeChange[]
122
+ deduplicateNodeChangePluginData(nodeChanges)
123
+
124
+ const blobs: Uint8Array[] = (Array.isArray(message.blobs) ? message.blobs : []).map((blob) => {
125
+ const bytes = isRuntimeMessage(blob) ? blob.bytes : undefined
126
+ return bytes instanceof Uint8Array ? bytes : new Uint8Array(Object.values(bytes ?? {}))
127
+ })
128
+
129
+ return {
130
+ nodeChanges,
131
+ blobs,
132
+ figKiwiVersion: payload.version,
133
+ figSchemaDeflated: payload.schemaDeflated,
134
+ kind: payload.kind
135
+ }
136
+ }
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Figma Multiplayer Protocol
3
+ *
4
+ * This module handles the low-level WebSocket communication with Figma's
5
+ * multiplayer server. The protocol uses:
6
+ *
7
+ * - Kiwi binary serialization (schema-based, like Protocol Buffers)
8
+ * - Zstd compression for all messages
9
+ * - Session-based authentication via cookies
10
+ *
11
+ * Message types (from Figma's schema):
12
+ * 0 = JOIN_START - Server sends session info
13
+ * 1 = NODE_CHANGES - Create/update/delete nodes
14
+ * 2 = USER_CHANGES - User presence updates
15
+ * 3 = JOIN_END - Initial sync complete
16
+ * 4 = SIGNAL - Various metadata (reconnect info, etc.)
17
+ * 5 = STYLE - Style updates
18
+ * ...and more
19
+ *
20
+ * Wire format:
21
+ * All messages are Zstd-compressed Kiwi-encoded binary data.
22
+ * Zstd magic bytes: 0x28 0xB5 0x2F 0xFD
23
+ */
24
+
25
+ export const MESSAGE_TYPES = {
26
+ JOIN_START: 0,
27
+ NODE_CHANGES: 1,
28
+ USER_CHANGES: 2,
29
+ JOIN_END: 3,
30
+ SIGNAL: 4,
31
+ STYLE: 5,
32
+ STYLE_SET: 6,
33
+ JOIN_START_SKIP_RELOAD: 7,
34
+ NOTIFY_SHOULD_UPGRADE: 8,
35
+ UPGRADE_DONE: 9,
36
+ UPGRADE_REFRESH: 10,
37
+ SCENE_GRAPH_QUERY: 11,
38
+ SCENE_GRAPH_REPLY: 12,
39
+ DIFF: 13,
40
+ CLIENT_BROADCAST: 14
41
+ } as const
42
+
43
+ export const NODE_TYPES = {
44
+ NONE: 0,
45
+ DOCUMENT: 1,
46
+ CANVAS: 2,
47
+ GROUP: 3,
48
+ FRAME: 4,
49
+ BOOLEAN_OPERATION: 5,
50
+ VECTOR: 6,
51
+ STAR: 7,
52
+ LINE: 8,
53
+ ELLIPSE: 9,
54
+ RECTANGLE: 10,
55
+ REGULAR_POLYGON: 11,
56
+ ROUNDED_RECTANGLE: 12,
57
+ TEXT: 13,
58
+ SLICE: 14,
59
+ SYMBOL: 15,
60
+ INSTANCE: 16,
61
+ STICKY: 17,
62
+ SHAPE_WITH_TEXT: 18,
63
+ CONNECTOR: 19,
64
+ CODE_BLOCK: 20,
65
+ WIDGET: 21,
66
+ STAMP: 22,
67
+ MEDIA: 23,
68
+ HIGHLIGHT: 24,
69
+ SECTION: 25,
70
+ SECTION_OVERLAY: 26,
71
+ WASHI_TAPE: 27,
72
+ VARIABLE: 28
73
+ } as const
74
+
75
+ export const NODE_PHASES = {
76
+ CREATED: 0,
77
+ REMOVED: 1
78
+ } as const
79
+
80
+ export const BLEND_MODES = {
81
+ PASS_THROUGH: 0,
82
+ NORMAL: 1,
83
+ DARKEN: 2,
84
+ MULTIPLY: 3,
85
+ LINEAR_BURN: 4,
86
+ COLOR_BURN: 5,
87
+ LIGHTEN: 6,
88
+ SCREEN: 7,
89
+ LINEAR_DODGE: 8,
90
+ COLOR_DODGE: 9,
91
+ OVERLAY: 10,
92
+ SOFT_LIGHT: 11,
93
+ HARD_LIGHT: 12,
94
+ DIFFERENCE: 13,
95
+ EXCLUSION: 14,
96
+ HUE: 15,
97
+ SATURATION: 16,
98
+ COLOR: 17,
99
+ LUMINOSITY: 18
100
+ } as const
101
+
102
+ export const PAINT_TYPES = {
103
+ SOLID: 0,
104
+ GRADIENT_LINEAR: 1,
105
+ GRADIENT_RADIAL: 2,
106
+ GRADIENT_ANGULAR: 3,
107
+ GRADIENT_DIAMOND: 4,
108
+ IMAGE: 5,
109
+ EMOJI: 6,
110
+ VIDEO: 7
111
+ } as const
112
+
113
+ /**
114
+ * Zstd magic bytes
115
+ */
116
+ export const ZSTD_MAGIC = new Uint8Array([0x28, 0xb5, 0x2f, 0xfd])
117
+
118
+ // ============================================================================
119
+ // Kiwi Binary Format Constants
120
+ // ============================================================================
121
+
122
+ /**
123
+ * Kiwi uses field numbers to identify message fields.
124
+ * Field 1 with value = message type indicates the message kind.
125
+ */
126
+ export const KIWI = {
127
+ /** First byte of valid Kiwi messages (field number 1) */
128
+ MESSAGE_MARKER: 1,
129
+
130
+ /** Field number for sessionID in JOIN_START message */
131
+ SESSION_ID_FIELD: 2,
132
+
133
+ /** Varint continuation bit (MSB set = more bytes follow) */
134
+ VARINT_CONTINUE_BIT: 0x80,
135
+
136
+ /** Varint value mask (lower 7 bits contain data) */
137
+ VARINT_VALUE_MASK: 0x7f,
138
+
139
+ /** Bits per varint byte */
140
+ VARINT_BITS_PER_BYTE: 7
141
+ } as const
142
+
143
+ /**
144
+ * Valid session ID range (based on observed Figma behavior)
145
+ */
146
+ export const SESSION_ID = {
147
+ MIN: 10000,
148
+ MAX: 1000000
149
+ } as const
150
+
151
+ /**
152
+ * Parse a varint from a Uint8Array at given position
153
+ * Returns [value, newPosition]
154
+ */
155
+ export function parseVarint(data: Uint8Array, pos: number): [number, number] {
156
+ let value = 0
157
+ let shift = 0
158
+
159
+ while (pos < data.length) {
160
+ const byte = data[pos]
161
+ pos++
162
+ value |= (byte & KIWI.VARINT_VALUE_MASK) << shift
163
+
164
+ if (!(byte & KIWI.VARINT_CONTINUE_BIT)) {
165
+ break
166
+ }
167
+ shift += KIWI.VARINT_BITS_PER_BYTE
168
+ }
169
+
170
+ return [value, pos]
171
+ }
172
+
173
+ /**
174
+ * Check if data is a valid Kiwi message
175
+ */
176
+ export function isKiwiMessage(data: Uint8Array): boolean {
177
+ return data.length >= 2 && data[0] === KIWI.MESSAGE_MARKER
178
+ }
179
+
180
+ /**
181
+ * Get message type from Kiwi message
182
+ */
183
+ export function getKiwiMessageType(data: Uint8Array): number | null {
184
+ if (!isKiwiMessage(data)) return null
185
+ return data.at(1) ?? null
186
+ }
187
+
188
+ /**
189
+ * fig-wire header magic (first 8 bytes of some messages)
190
+ */
191
+ export const FIG_WIRE_MAGIC = 'fig-wire'
192
+
193
+ /**
194
+ * Check if data is Zstd-compressed
195
+ */
196
+ export function isZstdCompressed(data: Uint8Array): boolean {
197
+ return (
198
+ data.length >= 4 && data[0] === 0x28 && data[1] === 0xb5 && data[2] === 0x2f && data[3] === 0xfd
199
+ )
200
+ }
201
+
202
+ /**
203
+ * Check if data has fig-wire header
204
+ */
205
+ export function hasFigWireHeader(data: Uint8Array): boolean {
206
+ if (data.length < 8) return false
207
+ const header = new TextDecoder().decode(data.slice(0, 8))
208
+ return header === FIG_WIRE_MAGIC
209
+ }
210
+
211
+ /**
212
+ * Skip fig-wire header and find zstd data
213
+ * Header format: "fig-wire" (8 bytes) + version (4 bytes LE) + zstd data
214
+ */
215
+ export function skipFigWireHeader(data: Uint8Array): Uint8Array {
216
+ if (!hasFigWireHeader(data)) return data
217
+ // Skip 8 bytes header + 4 bytes version
218
+ return data.slice(12)
219
+ }
220
+
221
+ /**
222
+ * Current multiplayer protocol version
223
+ */
224
+ export const PROTOCOL_VERSION = 151
225
+
226
+ /**
227
+ * Build WebSocket URL for Figma multiplayer
228
+ */
229
+ export function buildMultiplayerURL(fileKey: string, trackingId?: string): string {
230
+ const params = new URLSearchParams({
231
+ role: 'editor',
232
+ version: String(PROTOCOL_VERSION),
233
+ recentReload: '0',
234
+ tracking_session_id: trackingId || `ws-${Date.now()}`
235
+ })
236
+ return `wss://www.figma.com/api/multiplayer/${fileKey}?${params}`
237
+ }