Skip to content

AI-native design editor. Open-source Figma alternative.

perf(kiwi): compile schemas into tables and decompress .fig data with WebAssembly zstd (#1336)

Danila Poyarkov60fed3f7b619
diff --git a/bun.lock b/bun.lock
index 992160f95..ac04cec4a 100644
--- a/bun.lock
+++ b/bun.lock
@@ -71,7 +71,6 @@
"es-toolkit": "^1.52.0",
"fflate": "^0.8.3",
"fuse.js": "^7.5.0",
- "fzstd": "^0.1.1",
"hast-util-to-html": "^9.0.5",
"idb": "^8.0.3",
"js-base64": "^3.9.3",
@@ -273,7 +272,6 @@
"es-toolkit": "^1.52.0",
"fflate": "^0.8.3",
"fontoxpath": "^3.34.0",
- "fzstd": "^0.1.1",
"js-base64": "^3.9.3",
"jsep": "^1.4.0",
"jsondiffpatch": "^0.7.6",
@@ -479,7 +477,6 @@
"dependencies": {
"@hpcc-js/wasm-zstd": "^1.16.2",
"fflate": "^0.8.3",
- "fzstd": "^0.1.1",
},
"devDependencies": {
"@types/bun": "^1.3.14",
@@ -3347,8 +3344,6 @@
"fuse.js": ["[email protected]", "", {}, "sha512-sQtrEfA+ez/3G0cCZecF70oqpCRttCexYUG4mUrtWL49ULUzUyxokt5kyqwtKzj1270RaKih+hcP3qLcumccow=="],
- "fzstd": ["[email protected]", "", {}, "sha512-dkuVSOKKwh3eas5VkJy1AW1vFpet8TA/fGmVA5krThl8YcOVE/8ZIoEA1+U1vEn5ckxxhLirSdY837azmbaNHA=="],
-
"gaxios": ["[email protected]", "", { "dependencies": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", "node-fetch": "^3.3.2" } }, "sha512-kB3rzJV7d9juLZh8/56QTXCwQfxyhdOMdyYk1HdQKFtF8TJTDTZQJtixWIwXdE9Jji91mC41DUNpjleo4L4eAQ=="],
"gcp-metadata": ["[email protected]", "", { "dependencies": { "gaxios": "^7.0.0", "google-logging-utils": "^1.0.0", "json-bigint": "^1.0.0" } }, "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg=="],
diff --git a/changes/1336/performance.md b/changes/1336/performance.md
new file mode 100644
index 000000000..1d4ddae52
--- /dev/null
+++ b/changes/1336/performance.md
@@ -0,0 +1,2 @@
+- Opening a `.fig` reads its record index up to 1.7× faster, with the Kiwi schema compiled once into tables.
+- `.fig` data decompresses with the same Zstd that saves it, about 3× faster than before in browsers and the desktop app.
diff --git a/package.json b/package.json
index 9a2e2ed57..df9c43994 100644
--- a/package.json
+++ b/package.json
@@ -185,7 +185,6 @@
"es-toolkit": "^1.52.0",
"fflate": "^0.8.3",
"fuse.js": "^7.5.0",
- "fzstd": "^0.1.1",
"hast-util-to-html": "^9.0.5",
"idb": "^8.0.3",
"js-base64": "^3.9.3",
diff --git a/packages/core/package.json b/packages/core/package.json
index 3baadb0a0..440f09bf0 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -200,7 +200,6 @@
"es-toolkit": "^1.52.0",
"fflate": "^0.8.3",
"fontoxpath": "^3.34.0",
- "fzstd": "^0.1.1",
"js-base64": "^3.9.3",
"jsep": "^1.4.0",
"jsondiffpatch": "^0.7.6",
diff --git a/packages/core/src/io/formats/fig/read.ts b/packages/core/src/io/formats/fig/read.ts
index 09254497d..5f03a350e 100644
--- a/packages/core/src/io/formats/fig/read.ts
+++ b/packages/core/src/io/formats/fig/read.ts
@@ -1,4 +1,5 @@
import type { FigPageManifestEntry } from '@open-pencil/kiwi/fig'
+import { loadFigDataDecompressor } from '@open-pencil/kiwi/fig/container'
import type { SceneGraph } from '@open-pencil/scene-graph'
import { IS_BROWSER } from '#core/constants'
@@ -45,10 +46,13 @@ function parseFigFileSync(buffer: ArrayBuffer, options: ParseFigFileOptions = {}
return reader.graph
}
-export function parseFigFileViaWorker(
+export async function parseFigFileViaWorker(
buffer: ArrayBuffer,
options: ParseFigFileOptions
): Promise<SceneGraph> {
+ options.signal?.throwIfAborted()
+ // The worker loads its own; this thread patches the archive on save, which reads it again.
+ await loadFigDataDecompressor()
return new Promise((resolve, reject) => {
options.signal?.throwIfAborted()
const worker = createFigSessionWorker()
@@ -125,6 +129,10 @@ export async function parseFigFile(
buffer: ArrayBuffer,
options: ParseFigFileOptions = {}
): Promise<SceneGraph> {
+ options.signal?.throwIfAborted()
+ // Loaded here even when a worker opens the file: recovering its pages later reads the archive
+ // again on this thread.
+ await loadFigDataDecompressor()
options.signal?.throwIfAborted()
if (typeof Worker !== 'undefined' && IS_BROWSER) {
try {
diff --git a/packages/core/src/kiwi/fig/session/worker.ts b/packages/core/src/kiwi/fig/session/worker.ts
index c1809bbc8..79b025d28 100644
--- a/packages/core/src/kiwi/fig/session/worker.ts
+++ b/packages/core/src/kiwi/fig/session/worker.ts
@@ -1,3 +1,5 @@
+import { loadFigDataDecompressor } from '@open-pencil/kiwi/fig/container'
+
import { serializeSceneGraph } from '#core/kiwi/fig/parse/transfer'
import { createFigArchiveOperations } from '#core/kiwi/fig/session/archive/access'
import type {
@@ -101,7 +103,7 @@ function handleRequest(request: FigSessionRequest): void {
}
}
-self.onmessage = (event: MessageEvent<FigSessionOpenRequest>) => {
+self.onmessage = async (event: MessageEvent<FigSessionOpenRequest>) => {
const request = event.data
port = request.port
port.onmessage = (message: MessageEvent<FigSessionRequest>) => handleRequest(message.data)
@@ -109,6 +111,7 @@ self.onmessage = (event: MessageEvent<FigSessionOpenRequest>) => {
// The worker copies the archive itself, so the main thread sends the file once.
const archiveBytes = request.buffer.slice(0)
try {
+ await loadFigDataDecompressor()
const opened = openReaderSession(request.buffer, request.options?.populate)
const archiveInfo = opened.session.archiveRecordInfo()
archive = createFigArchiveOperations(archiveBytes, () => archiveInfo)
diff --git a/packages/core/tests/helpers/test-utils.ts b/packages/core/tests/helpers/test-utils.ts
index 5c1e57754..ce5d62813 100644
--- a/packages/core/tests/helpers/test-utils.ts
+++ b/packages/core/tests/helpers/test-utils.ts
@@ -1,11 +1,11 @@
import { describe } from 'bun:test'
-// Tests that don't run are not useful, but it may be desirable to run only a short subset of tests.
-// Set BUN_HEAVY_TESTS to false to skip tests marked as heavy, and set it to true to run them.
-// By default, all tests are run.
-export const runsHeavyTests = process.env.BUN_HEAVY_TESTS
- ? ['1', 't', 'true'].includes(process.env.BUN_HEAVY_TESTS.trim().toLowerCase())
- : true
+// Heavy tests parse the large fixtures, gigabytes each, and run only when BUN_HEAVY_TESTS is
+// true, which the unit test runner sets while giving each heavy file its own process. A bare
+// `bun test` over a directory skips them, so it cannot hold several such graphs in one process.
+export const runsHeavyTests = ['1', 't', 'true'].includes(
+ (process.env.BUN_HEAVY_TESTS ?? '').trim().toLowerCase()
+)
export const heavy = describe.if(runsHeavyTests)
diff --git a/packages/core/tests/io/formats/fig/roundtrip/exhaustive.test.ts b/packages/core/tests/io/formats/fig/roundtrip/exhaustive.test.ts
index 6f8eeb448..459d7d8f6 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/exhaustive.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/exhaustive.test.ts
@@ -1,9 +1,10 @@
-import { beforeAll, afterAll, describe, expect, test, spyOn, setDefaultTimeout } from 'bun:test'
+import { beforeAll, afterAll, expect, test, spyOn, setDefaultTimeout } from 'bun:test'
import {
expectSaveLoadedOnlyInternalPages,
snapshotNodes
} from '#core-tests/helpers/fig/save-contract'
+import { heavy } from '#core-tests/helpers/test-utils'
import { unzipSync } from 'fflate'
import {
@@ -406,7 +407,7 @@ function deepCompareRaw(
function verifyFixture(spec: FixtureSpec): void {
const name = (spec.file.split('/').pop() ?? '').replace('.fig', '')
- describe(`roundtrip: ${name}`, () => {
+ heavy(`roundtrip: ${name}`, () => {
let g0!: Map<string, SceneNode>
let g0Graph!: SceneGraph
let g0Bytes!: ArrayBuffer
diff --git a/packages/core/tests/io/formats/fig/roundtrip/glyph-blob.test.ts b/packages/core/tests/io/formats/fig/roundtrip/glyph-blob.test.ts
index 2f613d518..b7769e217 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/glyph-blob.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/glyph-blob.test.ts
@@ -1,11 +1,11 @@
-import { beforeAll, describe, expect, test } from 'bun:test'
+import { beforeAll, expect, test } from 'bun:test'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { expectDefined } from '#core-tests/helpers/assert'
import { FIXTURES } from '#core-tests/helpers/fig/fixtures'
import { corePackagePath } from '#core-tests/helpers/paths'
-import { HEAVY_TEST_TIMEOUT_MS } from '#core-tests/helpers/test-utils'
+import { heavy, HEAVY_TEST_TIMEOUT_MS } from '#core-tests/helpers/test-utils'
import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
import { fontManager } from '@open-pencil/core/text'
@@ -44,7 +44,7 @@ function loadInterFonts() {
}
}
-describe('roundtrip: text glyph blobs', () => {
+heavy('roundtrip: text glyph blobs', () => {
beforeAll(
async () => {
await initCodec()
diff --git a/packages/docs/development/tech-stack.md b/packages/docs/development/tech-stack.md
index db2c8d171..879b1cb0c 100644
--- a/packages/docs/development/tech-stack.md
+++ b/packages/docs/development/tech-stack.md
@@ -34,7 +34,7 @@
"reka-ui": "^2.10.3",
"tailwindcss": "^4.3.3",
"culori": "^4.0.2",
- "fzstd": "^0.1.1",
+ "@hpcc-js/wasm-zstd": "^1.16.2",
"fflate": "^0.8.3",
"@trystero-p2p/mqtt": "^0.26.0",
"yjs": "^13.6.32",
diff --git a/packages/docs/development/testing.md b/packages/docs/development/testing.md
index 92cb4879c..bcec63756 100644
--- a/packages/docs/development/testing.md
+++ b/packages/docs/development/testing.md
@@ -97,6 +97,8 @@ Two environment faults look exactly like a code regression, and both have cost r
Browser suites resolve `@open-pencil/*` through each package's built `dist`, which Vite then pre-bundles. Rebuilding a package does not invalidate that cache, so a Playwright run can execute code from before your change — including throwing on a field you just added. If a browser run contradicts the source you are reading, delete `node_modules/.vite` and run again before believing it.
+Heavy tests, the ones that parse the large fixtures or a populated `gold-preview.fig` more than once, run only with `BUN_HEAVY_TESTS=true`. The unit test runner sets it and gives each heavy file its own Bun process, because one such graph takes gigabytes and a process keeps every graph a test module holds until it exits: a bare `bun test` over `packages/core/tests/io/formats/fig` with heavy tests enabled has reached 37 GB. A bare `bun test` and `test:unit:quick` therefore skip them; `bun run test:unit` runs them, and `bun run test:unit:heavy` or `bun tools/dev/unit-tests/src/run.ts <group> --heavy-only` runs the heavy files alone.
+
Heavier `.fig` suites are sensitive to machine load. A full run alongside other work has reported failures that vanish on a quiet re-run, with the same suite taking three times as long. Re-run a failing heavy test alone before concluding anything, and compare against the same test on `master` under the same load rather than against a remembered baseline. Raising its timeout is still never the fix.
## Server ownership and worktrees
diff --git a/packages/docs/reference/file-format.md b/packages/docs/reference/file-format.md
index bbe33fc0e..7d29dfee1 100644
--- a/packages/docs/reference/file-format.md
+++ b/packages/docs/reference/file-format.md
@@ -62,7 +62,7 @@ Figma's schema uses non-contiguous field IDs (e.g. 1, 2, 5, 10 with gaps). The k
### Compression
-The schema chunk is deflated and the message chunk is Zstd-compressed; Figma also reads a deflated message chunk, as older files have. Decompression uses the `fzstd` library.
+The schema chunk is deflated and the message chunk is Zstd-compressed; Figma also reads a deflated message chunk, as older files have. Decompression uses the same Zstd as export: Bun's own under Bun, the WebAssembly build elsewhere.
Export writes the message chunk with Zstd at a level set per document, stored as `figCompression` in the document node's `open-pencil` plugin data: `fast` (level 3, as Figma saves), `smaller` (9), or `smallest` (19). Figma opens every Zstd level, but only frames that declare their decompressed size, which all three encoders write. Reading costs the same at every level; on a 45 MB message, level 9 takes about five times and level 19 about 150 times as long to write as level 3.
diff --git a/packages/fig/AGENTS.md b/packages/fig/AGENTS.md
index d42059e40..1cf42d61c 100644
--- a/packages/fig/AGENTS.md
+++ b/packages/fig/AGENTS.md
@@ -3,10 +3,12 @@
`@open-pencil/kiwi` owns Kiwi schema, runtime, codecs, containers, and parse helpers without SceneGraph knowledge. `@open-pencil/fig` owns complete `.fig` archive parsing, SceneGraph conversion, metadata policy, component/instance interpretation, and the Figma clipboard format. Core owns format-neutral orchestration, runtime fonts and workers, and thumbnails.
- Keep Kiwi runtime changes minimal; put project policy in wrappers, not in the runtime.
+- A schema is compiled once into tables, `compileSchema(schema).schema`, and decoding, skipping, encoding, the page manifest scan, and record patching all read fields through them; do not add another type switch or name lookup over Kiwi values (`packages/kiwi/tests/compiled-schema.test.ts`).
- Figma clipboard envelope encoding, decoding, and bounds belong to `@open-pencil/fig/clipboard`; converting those records to a SceneGraph is `materializeFigFragment` in `packages/fig/src/document/fragment.ts`, which Core drives from `packages/core/src/clipboard/fig-import.ts`. Core prepares runtime fonts and text and owns editor placement and history; browser and Tauri adapters own system clipboard I/O. Do not add platform clipboard APIs here.
- One reader serves every `.fig` path — parse, worker, page population, session recovery, export, and paste — through the document sessions in `packages/fig/src/document/`. Read what it could not resolve with `readerDiagnostics(graph)` from `packages/core/src/kiwi/fig/session/document-state.ts`; do not add a second import path.
- A generated frame's `.fig` record carries its sublayers as `nodeGenerationData` and their derived geometry. Each generated type registers a `GeneratedFrameCodec` that reads and writes them in `packages/fig/src/node-change/generated/codecs.ts`; the import and export dispatch through it and never test node types (`packages/fig/tests/node-change/generated/codecs.test.ts`).
- `.fig` document data is written with Zstd at the document's `figCompression` level: `build_fig_file` in `desktop/` on Tauri, `loadFigDataCompressor` from `@open-pencil/kiwi/fig/container` elsewhere, which is Bun's Zstd or a WebAssembly build. Figma rejects a Zstd frame that does not declare its decompressed size, so every encoder must write it (`packages/kiwi/tests/container.test.ts`).
+- Reading uses the same Zstd through the synchronous `decompressFigKiwiData`, which needs `loadFigDataDecompressor` awaited once per thread outside Bun: `parseFigFile` and the session worker do that, so page recovery and archive patches on either thread never wait (`packages/kiwi/tests/container.test.ts`).
- Saving a document opened from a `.fig` writes only the fields its edits changed, merged into the archive's records, and copies the rest as bytes (`packages/core/src/io/formats/fig/export/patch/`, `patchFigMessage` in `packages/fig/src/record-patch/`); the full export remains for documents with no archive. A change is what the archive tracker sees outside page loads and outside `applyDerivedLayoutDuring`, which wraps layout derived from the file or its fonts; layout an edit causes counts, and the tracker keeps each edited layer as it was so the fields are found by comparing records (`packages/core/tests/io/formats/fig/export/patch/`).
- Changes to `.fig` behavior require round-trip validation in Figma. `packages/docs/development/roadmap.md` tracks raw metadata coverage and the code map for import/export mapping and schema files.
- Measure a reader change over a whole archive, not one frame: capture before and after with `visual-oracles compare digest --file F --out baseline.json` then `--baseline baseline.json`, and account for every node it reports. `compare interpreted-document` checks one frame against live Figma and will report no change while a rule breaks pages it does not cover.
diff --git a/packages/fig/src/record-patch/index.ts b/packages/fig/src/record-patch/index.ts
index de6f99f33..6c2226716 100644
--- a/packages/fig/src/record-patch/index.ts
+++ b/packages/fig/src/record-patch/index.ts
@@ -6,9 +6,10 @@ import { guidToString } from '@open-pencil/kiwi/fig/guid'
import {
ByteBuffer,
compileSchema,
- createSchemaSkipper,
decodeBinarySchema,
- type SchemaSkipper
+ type CompiledDefinition,
+ type RuntimeCodec,
+ type RuntimeMessage
} from '@open-pencil/kiwi/schema-runtime'
import { orderKeyBetween } from '@open-pencil/scene-graph/order-keys'
@@ -293,7 +294,6 @@ export function patchFigRecords(
return mergeRecords(archive.map(entryOf), patch, (record) => record).map((entry) => entry.value)
}
-type KiwiCodec = ReturnType<typeof compileSchema>
type RecordHead = Omit<RecordEntry<Uint8Array>, 'value'> & {
guid?: GUID
/** Read only when asked for: what an instance shows, for finding where components are used. */
@@ -311,26 +311,14 @@ interface ScannedMessage {
hasBlobs: boolean
}
-function fieldType(type: string | null): string {
- if (type === null) throw new Error('Kiwi field without a type')
- return type
-}
-
-function decoderOf(codec: KiwiCodec, type: string): (bb: ByteBuffer) => unknown {
- const decoder = codec[`decode${type}`]
- if (typeof decoder !== 'function') throw new Error(`No Kiwi decoder for ${type}`)
- return decoder as (bb: ByteBuffer) => unknown
-}
-
/** Reads a record's identity, place and type, and moves past everything else in it. */
function scanRecord(
- codec: KiwiCodec,
- skipper: SchemaSkipper,
- type: string,
+ codec: RuntimeCodec,
+ record: CompiledDefinition,
bb: ByteBuffer,
readSymbolData: boolean
): RecordHead {
- const fields = skipper.fieldsById(type)
+ const { schema } = codec
const head: RecordHead = {
id: undefined,
parent: undefined,
@@ -338,56 +326,57 @@ function scanRecord(
parentIndex: undefined
}
for (let id = bb.readVarUint(); id !== 0; id = bb.readVarUint()) {
- const field = fields.get(id)
+ const field = record.byId[id]
if (!field) throw new Error('Attempted to parse invalid message')
const name = field.isArray ? '' : field.name
if (name === 'guid') {
- head.guid = decoderOf(codec, fieldType(field.type))(bb) as GUID
+ head.guid = schema.read(field, bb) as GUID
head.id = key(head.guid)
} else if (name === 'parentIndex') {
- const parentIndex = decoderOf(codec, fieldType(field.type))(bb) as NodeChange['parentIndex']
+ const parentIndex = schema.read(field, bb) as NodeChange['parentIndex']
head.parentIndex = parentIndex
head.parent = key(parentIndex?.guid)
} else if (name === 'type') {
- const names = codec[fieldType(field.type)] as Record<number, string> | undefined
- head.type = names?.[bb.readVarUint()]
- } else if (name === 'symbolData' && readSymbolData)
- head.symbolData = decoderOf(codec, fieldType(field.type))(bb)
- else skipper.skipField(field, bb)
+ head.type = field.definition?.names[bb.readVarUint()]
+ } else if (name === 'symbolData' && readSymbolData) head.symbolData = schema.read(field, bb)
+ else schema.skip(field, bb)
}
return head
}
function scanMessage(
- codec: KiwiCodec,
- skipper: SchemaSkipper,
+ codec: RuntimeCodec,
data: Uint8Array,
readSymbolData = false
): ScannedMessage {
- const fields = skipper.fieldsById('Message')
+ const { schema } = codec
+ const fields = schema.definition('Message').byId
const bb = new ByteBuffer(data)
const scanned: ScannedMessage = { parts: [], records: [], blobs: [], hasBlobs: false }
for (;;) {
const start = bb.offset
const id = bb.readVarUint()
if (id === 0) break
- const field = fields.get(id)
+ const field = fields[id]
if (!field) throw new Error('Attempted to parse invalid message')
- const type = fieldType(field.type)
const isRecords = field.name === 'nodeChanges' && field.isArray
const isBlobs = field.name === 'blobs' && field.isArray
if (!isRecords && !isBlobs) {
- skipper.skipField(field, bb)
+ schema.skip(field, bb)
scanned.parts.push({ kind: 'bytes', bytes: data.subarray(start, bb.offset) })
continue
}
+ const definition = field.definition
+ if (!definition) throw new Error(`Kiwi ${field.name} holds no messages`)
+ const type = definition.name
+ const element = { ...field, isArray: false }
for (let count = bb.readVarUint(); count > 0; count--) {
const begin = bb.offset
if (isRecords) {
- const head = scanRecord(codec, skipper, type, bb, readSymbolData)
+ const head = scanRecord(codec, definition, bb, readSymbolData)
scanned.records.push({ ...head, value: data.subarray(begin, bb.offset) })
} else {
- skipper.skipValue(type, bb)
+ schema.skip(element, bb)
scanned.blobs.push(data.subarray(begin, bb.offset))
}
}
@@ -398,9 +387,8 @@ function scanMessage(
return scanned
}
-function archiveCodec(schemaDeflated: Uint8Array) {
- const schema = decodeBinarySchema(new ByteBuffer(inflateSync(schemaDeflated)))
- return { codec: compileSchema(schema), skipper: createSchemaSkipper(schema) }
+function archiveCodec(schemaDeflated: Uint8Array): RuntimeCodec {
+ return compileSchema(decodeBinarySchema(new ByteBuffer(inflateSync(schemaDeflated))))
}
function varUint(value: number): Uint8Array {
@@ -409,12 +397,10 @@ function varUint(value: number): Uint8Array {
return bb.toUint8Array().slice()
}
-function encoded(codec: KiwiCodec, type: string, value: unknown): Uint8Array {
- const encoder = codec[`encode${type}`]
- if (typeof encoder !== 'function') throw new Error(`No Kiwi encoder for ${type}`)
- const bytes = (encoder as (message: unknown) => Uint8Array | undefined)(value)
- if (!bytes) throw new Error(`Encoding ${type} produced nothing`)
- return bytes.slice()
+function encoded(codec: RuntimeCodec, type: string, value: unknown): Uint8Array {
+ const bb = new ByteBuffer()
+ codec.schema.encode(codec.schema.definition(type), value as RuntimeMessage, bb)
+ return bb.toUint8Array().slice()
}
function concat(chunks: readonly Uint8Array[]): Uint8Array {
@@ -438,13 +424,14 @@ export function patchFigMessage(
dataRaw: Uint8Array,
patch: FigRecordPatch
): Uint8Array {
- const { codec, skipper } = archiveCodec(schemaDeflated)
- const scanned = scanMessage(codec, skipper, dataRaw)
+ const codec = archiveCodec(schemaDeflated)
+ const { schema } = codec
+ const scanned = scanMessage(codec, dataRaw)
const recordsPart = scanned.parts.find((part) => part.kind === 'records')
// Only the records an edit changed some fields of are decoded; the rest stay bytes.
const decode = (bytes: Uint8Array): NodeChange => {
if (recordsPart?.kind !== 'records') throw new Error('The archive has no records')
- return decoderOf(codec, recordsPart.type)(new ByteBuffer(bytes)) as NodeChange
+ return schema.decode(schema.definition(recordsPart.type), new ByteBuffer(bytes)) as NodeChange
}
const merged = mergeRecords(scanned.records, patch, decode)
const blobs = (type: string) => [
@@ -469,9 +456,9 @@ export function patchFigMessage(
)
}
if (!scanned.hasBlobs && patch.blobs.length > 0) {
- const field = skipper.definition('Message').fields.find((entry) => entry.name === 'blobs')
- if (!field) throw new Error('The archive schema has no blobs')
- appendField(field.value, blobs(fieldType(field.type)))
+ const field = schema.definition('Message').fields.find((entry) => entry.name === 'blobs')
+ if (!field?.definition) throw new Error('The archive schema has no blobs')
+ appendField(field.id, blobs(field.definition.name))
}
chunks.push(varUint(0))
return concat(chunks)
@@ -559,8 +546,8 @@ export function figArchiveComponentUsePages(
componentIds: readonly string[]
): string[] {
const parts = readFigArchiveParts(bytes)
- const { codec, skipper } = archiveCodec(parts.schemaDeflated)
- const scanned = scanMessage(codec, skipper, parts.dataRaw, true)
+ const codec = archiveCodec(parts.schemaDeflated)
+ const scanned = scanMessage(codec, parts.dataRaw, true)
const records = scanned.records.map(
(entry) =>
({
diff --git a/packages/kiwi/package.json b/packages/kiwi/package.json
index 44c9f5f54..cca7a298c 100644
--- a/packages/kiwi/package.json
+++ b/packages/kiwi/package.json
@@ -75,8 +75,7 @@
},
"dependencies": {
"@hpcc-js/wasm-zstd": "^1.16.2",
- "fflate": "^0.8.3",
- "fzstd": "^0.1.1"
+ "fflate": "^0.8.3"
},
"devDependencies": {
"@types/bun": "^1.3.14",
diff --git a/packages/kiwi/src/fig/codec.ts b/packages/kiwi/src/fig/codec.ts
index a0a711958..05f8e64e4 100644
--- a/packages/kiwi/src/fig/codec.ts
+++ b/packages/kiwi/src/fig/codec.ts
@@ -6,9 +6,8 @@
* - fzstd: Browser-compatible Zstd decompression
*/
-import { decompress as zstdDecompress } from 'fzstd'
-
import { compileSchema, encodeBinarySchema } from '../schema-runtime'
+import { decompressFigKiwiData, loadFigDataDecompressor } from './container'
import { isZstdCompressed, getKiwiMessageType } from './protocol'
import figmaSchema from './schema'
import type { Color, GUID, Matrix, Vector } from './types'
@@ -27,6 +26,7 @@ let compiledSchema: CompiledSchema | null = null
*/
export async function initCodec(): Promise<void> {
if (compiledSchema) return
+ await loadFigDataDecompressor()
compiledSchema = compileSchema(figmaSchema) as CompiledSchema
}
@@ -58,7 +58,7 @@ export function compress(data: Uint8Array): Uint8Array {
*/
export function decompress(data: Uint8Array): Uint8Array {
if (!isZstdCompressed(data)) return data
- return zstdDecompress(data)
+ return decompressFigKiwiData(data)
}
/**
diff --git a/packages/kiwi/src/fig/container.ts b/packages/kiwi/src/fig/container.ts
index 4d6dec4f3..0287129dd 100644
--- a/packages/kiwi/src/fig/container.ts
+++ b/packages/kiwi/src/fig/container.ts
@@ -1,5 +1,5 @@
+import type { Zstd } from '@hpcc-js/wasm-zstd'
import { deflateSync, inflateSync } from 'fflate'
-import { decompress as fzstdDecompressSync } from 'fzstd'
import { isZstdCompressed } from './protocol'
@@ -8,16 +8,25 @@ export const FIG_KIWI_DEFAULT_VERSION = 101
/** Compresses a fig-kiwi data chunk. */
export type FigDataCompressor = (data: Uint8Array) => Uint8Array
+/** Decompresses a fig-kiwi data chunk, zstd or deflate. */
+export type FigDataDecompressor = (data: Uint8Array) => Uint8Array
+
/** The zstd level Figma itself saves with. */
export const FIG_ZSTD_DEFAULT_LEVEL = 3
type BunZstdCompress = (data: Uint8Array, options?: { level?: number }) => Uint8Array
+type BunZstdDecompress = (data: Uint8Array) => Uint8Array
function bunZstdCompress(): BunZstdCompress | undefined {
const g = globalThis as { Bun?: { zstdCompressSync?: BunZstdCompress } }
return g.Bun?.zstdCompressSync
}
+function bunZstdDecompress(): BunZstdDecompress | undefined {
+ const g = globalThis as { Bun?: { zstdDecompressSync?: BunZstdDecompress } }
+ return g.Bun?.zstdDecompressSync
+}
+
/**
* Bun's zstd at its default level, or deflate where zstd needs loading first. Figma reads both,
* so writers that cannot wait, such as the clipboard, use this one.
@@ -25,24 +34,27 @@ function bunZstdCompress(): BunZstdCompress | undefined {
export const defaultFigDataCompressor: FigDataCompressor = (data) =>
bunZstdCompress()?.(data) ?? deflateSync(data)
-let wasmZstd: Promise<(data: Uint8Array, level: number) => Uint8Array> | undefined
+let wasmZstd: Zstd | undefined
+let wasmZstdLoading: Promise<Zstd> | undefined
-/** The WebAssembly zstd encoder, loaded once; a failed load is retried on the next call. */
-export async function loadWasmFigDataCompressor(
- level = FIG_ZSTD_DEFAULT_LEVEL
-): Promise<FigDataCompressor> {
- wasmZstd ??= import('@hpcc-js/wasm-zstd')
+/** The WebAssembly zstd, loaded once; a failed load is retried on the next call. */
+function loadWasmZstd(): Promise<Zstd> {
+ wasmZstdLoading ??= import('@hpcc-js/wasm-zstd')
.then(({ Zstd }) => Zstd.load())
- .then(
- (zstd) => (data: Uint8Array, compressionLevel: number) =>
- zstd.compress(data, compressionLevel)
- )
+ .then((zstd) => (wasmZstd = zstd))
.catch((error: unknown) => {
- wasmZstd = undefined
+ wasmZstdLoading = undefined
throw error
})
- const compress = await wasmZstd
- return (data) => compress(data, level)
+ return wasmZstdLoading
+}
+
+/** The WebAssembly zstd encoder at `level`. */
+export async function loadWasmFigDataCompressor(
+ level = FIG_ZSTD_DEFAULT_LEVEL
+): Promise<FigDataCompressor> {
+ const zstd = await loadWasmZstd()
+ return (data) => zstd.compress(data, level)
}
/**
@@ -57,9 +69,42 @@ export async function loadFigDataCompressor(
return loadWasmFigDataCompressor(level)
}
-function bunZstdDecompressSync(data: Uint8Array): Uint8Array | undefined {
- const g = globalThis as { Bun?: { zstdDecompressSync?: (data: Uint8Array) => Uint8Array } }
- return g.Bun?.zstdDecompressSync?.(data)
+/** The WebAssembly zstd decoder. */
+export async function loadWasmFigDataDecompressor(): Promise<FigDataDecompressor> {
+ const zstd = await loadWasmZstd()
+ return (data) => (isZstdCompressed(data) ? zstd.decompress(data) : inflate(data))
+}
+
+/**
+ * Makes `decompressFigKiwiData` ready for zstd chunks: Bun's own zstd needs nothing, the
+ * WebAssembly build elsewhere loads once. Every path that opens a `.fig` synchronously awaits
+ * this first, so a document session, its worker, and the patches they write never wait.
+ */
+export async function loadFigDataDecompressor(): Promise<FigDataDecompressor> {
+ if (!bunZstdDecompress()) await loadWasmZstd()
+ return decompressFigKiwiData
+}
+
+function inflate(compressed: Uint8Array): Uint8Array {
+ try {
+ return inflateSync(compressed)
+ } catch {
+ throw new Error('Failed to decompress fig-kiwi data')
+ }
+}
+
+function decompressZstd(compressed: Uint8Array): Uint8Array {
+ const native = bunZstdDecompress()
+ if (native) {
+ // Bun returns a Node Buffer, whose `slice` is a view: a reader slicing byte arrays out of
+ // the message would then hand out views of the whole message, which `structuredClone`
+ // copies in full each time. A plain Uint8Array over the same memory slices by copying.
+ const buffer = native(compressed)
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)
+ }
+ if (!wasmZstd)
+ throw new Error('Zstd is not loaded: await loadFigDataDecompressor() before reading')
+ return wasmZstd.decompress(compressed)
}
export function parseFigKiwiChunks(binary: Uint8Array): Uint8Array[] | null {
@@ -79,31 +124,14 @@ export function parseFigKiwiChunks(binary: Uint8Array): Uint8Array[] | null {
return chunks.length >= 2 ? chunks : null
}
+/** A data chunk decompressed at once; a zstd chunk needs `loadFigDataDecompressor` first. */
export function decompressFigKiwiData(compressed: Uint8Array): Uint8Array {
- if (isZstdCompressed(compressed)) {
- const decompressed = bunZstdDecompressSync(compressed)
- if (decompressed) return decompressed
- return fzstdDecompressSync(compressed)
- }
-
- try {
- return inflateSync(compressed)
- } catch {
- throw new Error('Failed to decompress fig-kiwi data')
- }
+ return isZstdCompressed(compressed) ? decompressZstd(compressed) : inflate(compressed)
}
export async function decompressFigKiwiDataAsync(compressed: Uint8Array): Promise<Uint8Array> {
- if (isZstdCompressed(compressed)) {
- const bunDecompressed = bunZstdDecompressSync(compressed)
- if (bunDecompressed) return bunDecompressed
- return fzstdDecompressSync(compressed)
- }
- try {
- return inflateSync(compressed)
- } catch {
- throw new Error('Failed to decompress fig-kiwi data')
- }
+ const decompress = await loadFigDataDecompressor()
+ return decompress(compressed)
}
export function buildFigKiwi(
diff --git a/packages/kiwi/src/fig/page-manifest.ts b/packages/kiwi/src/fig/page-manifest.ts
index 084594d1a..be247a08a 100644
--- a/packages/kiwi/src/fig/page-manifest.ts
+++ b/packages/kiwi/src/fig/page-manifest.ts
@@ -1,5 +1,5 @@
import { ByteBuffer } from '../schema-runtime/bb'
-import type { Definition, Field, Schema } from '../schema-runtime/schema'
+import type { CompiledDefinition, CompiledSchema } from '../schema-runtime/interpreter'
export interface FigPageManifestEntry {
sourceId: string
@@ -14,103 +14,16 @@ interface PageCandidate extends FigPageManifestEntry {
type: string | null
}
-type DefinitionMap = Map<string, Definition>
-interface ScanContext {
- definitions: DefinitionMap
- fields: Map<string, Map<number, Field>>
-}
-
-function fieldMap(definition: Definition): Map<number, Field> {
- return new Map(definition.fields.map((field) => [field.value, field]))
-}
-
-function cachedFieldMap(context: ScanContext, definition: Definition): Map<number, Field> {
- let fields = context.fields.get(definition.name)
- if (!fields) {
- fields = fieldMap(definition)
- context.fields.set(definition.name, fields)
- }
- return fields
-}
-
-function skipSingleValue(bb: ByteBuffer, field: Field, context: ScanContext): void {
- switch (field.type) {
- case 'bool':
- case 'byte':
- bb.readByte()
- return
- case 'int':
- bb.readVarInt()
- return
- case 'uint':
- bb.readVarUint()
- return
- case 'float':
- bb.readVarFloat()
- return
- case 'string':
- bb.skipString()
- return
- case 'int64':
- bb.readVarInt64()
- return
- case 'uint64':
- bb.readVarUint64()
- return
- }
-
- const definition = field.type ? context.definitions.get(field.type) : undefined
- if (!definition) throw new Error(`Invalid Kiwi field type: ${String(field.type)}`)
- if (definition.kind === 'ENUM') {
- bb.readVarUint()
- return
- }
- skipDefinition(bb, definition, context)
-}
-
-function skipFieldValue(bb: ByteBuffer, field: Field, context: ScanContext): void {
- if (!field.isArray) {
- skipSingleValue(bb, field, context)
- return
- }
- if (field.type === 'byte') {
- bb.skipByteArray()
- return
- }
- let length = bb.readVarUint()
- while (length-- > 0) skipSingleValue(bb, field, context)
-}
-
-function skipDefinition(bb: ByteBuffer, definition: Definition, context: ScanContext): void {
- if (definition.kind === 'STRUCT') {
- for (const field of definition.fields) skipFieldValue(bb, field, context)
- return
- }
-
- const fields = cachedFieldMap(context, definition)
- for (;;) {
- const fieldId = bb.readVarUint()
- if (fieldId === 0) return
- const field = fields.get(fieldId)
- if (!field) throw new Error(`Invalid field ${fieldId} in Kiwi ${definition.name}`)
- skipFieldValue(bb, field, context)
- }
-}
-
-function enumName(bb: ByteBuffer, field: Field, context: ScanContext): string | null {
+function enumName(bb: ByteBuffer, definition: CompiledDefinition | null): string | null {
const value = bb.readVarUint()
- const definition = field.type ? context.definitions.get(field.type) : undefined
- return definition?.kind === 'ENUM'
- ? (definition.fields.find((candidate) => candidate.value === value)?.name ?? null)
- : null
+ return definition?.kind === 'ENUM' ? (definition.names[value] ?? null) : null
}
function scanNodeChange(
bb: ByteBuffer,
- definition: Definition,
- context: ScanContext
+ schema: CompiledSchema,
+ nodeChange: CompiledDefinition
): PageCandidate | null {
- const fields = cachedFieldMap(context, definition)
let sourceSessionId: number | null = null
let sourceLocalId: number | null = null
let parentSessionId: number | null = null
@@ -121,10 +34,8 @@ function scanNodeChange(
let name: string | null = null
let internalOnly = false
- for (;;) {
- const fieldId = bb.readVarUint()
- if (fieldId === 0) break
- const field = fields.get(fieldId)
+ for (let fieldId = bb.readVarUint(); fieldId !== 0; fieldId = bb.readVarUint()) {
+ const field = nodeChange.byId[fieldId]
if (!field) throw new Error(`Invalid field ${fieldId} in Kiwi NodeChange`)
switch (field.name) {
case 'guid':
@@ -138,10 +49,10 @@ function scanNodeChange(
bb.skipString()
break
case 'phase':
- phase = enumName(bb, field, context)
+ phase = enumName(bb, field.definition)
break
case 'type':
- type = enumName(bb, field, context)
+ type = enumName(bb, field.definition)
break
case 'name':
if (type === 'DOCUMENT' || type === 'CANVAS') name = bb.readString()
@@ -151,7 +62,7 @@ function scanNodeChange(
internalOnly = !!bb.readByte()
break
default:
- skipFieldValue(bb, field, context)
+ schema.skip(field, bb)
}
}
@@ -185,36 +96,28 @@ function scanNodeChange(
}
/**
- * Scans decoded Kiwi bytes without materializing NodeChange objects. Kiwi messages are not
+ * Scans encoded Kiwi bytes without materializing NodeChange objects. Kiwi messages are not
* length-prefixed, so every value is visited, but only document/page fields are allocated.
*/
-export function extractFigPageManifest(schema: Schema, data: Uint8Array): FigPageManifestEntry[] {
- const definitions: DefinitionMap = new Map(
- schema.definitions.map((definition) => [definition.name, definition])
- )
- const context: ScanContext = { definitions, fields: new Map() }
- const message = definitions.get('Message')
- const nodeChange = definitions.get('NodeChange')
- if (message?.kind !== 'MESSAGE' || nodeChange?.kind !== 'MESSAGE') {
- return []
- }
+export function extractFigPageManifest(
+ schema: CompiledSchema,
+ data: Uint8Array
+): FigPageManifestEntry[] {
+ const message = schema.definition('Message')
+ const nodeChange = schema.definition('NodeChange')
+ if (message.kind !== 'MESSAGE' || nodeChange.kind !== 'MESSAGE') return []
const bb = new ByteBuffer(data)
- const messageFields = cachedFieldMap(context, message)
const candidates: PageCandidate[] = []
- for (;;) {
- const fieldId = bb.readVarUint()
- if (fieldId === 0) break
- const field = messageFields.get(fieldId)
+ for (let fieldId = bb.readVarUint(); fieldId !== 0; fieldId = bb.readVarUint()) {
+ const field = message.byId[fieldId]
if (!field) throw new Error(`Invalid field ${fieldId} in Kiwi Message`)
if (field.name !== 'nodeChanges' || !field.isArray) {
- skipFieldValue(bb, field, context)
+ schema.skip(field, bb)
continue
}
-
- let length = bb.readVarUint()
- while (length-- > 0) {
- const candidate = scanNodeChange(bb, nodeChange, context)
+ for (let length = bb.readVarUint(); length > 0; length--) {
+ const candidate = scanNodeChange(bb, schema, nodeChange)
if (candidate) candidates.push(candidate)
}
break
diff --git a/packages/kiwi/src/fig/parse.ts b/packages/kiwi/src/fig/parse.ts
index 54115ac5e..1104cde5c 100644
--- a/packages/kiwi/src/fig/parse.ts
+++ b/packages/kiwi/src/fig/parse.ts
@@ -1,10 +1,15 @@
import { inflateSync } from 'fflate'
-import { decompress as zstdDecompress } from 'fzstd'
-import { decodeBinarySchema, compileSchema, ByteBuffer, type HeaderFields } from '../schema-runtime'
-import type { FigmaMessage, NodeChange } from './codec'
+import {
+ decodeBinarySchema,
+ compileSchema,
+ ByteBuffer,
+ type HeaderFields,
+ type RuntimeMessage
+} from '../schema-runtime'
+import type { NodeChange } from './codec'
+import { decompressFigKiwiData } from './container'
import { extractFigPageManifest, type FigPageManifestEntry } from './page-manifest'
-import { isZstdCompressed } from './protocol'
export type { NodeChange } from './codec'
@@ -43,10 +48,6 @@ interface FigKiwiPayload {
version: number
}
-interface CompiledKiwiSchema {
- decodeMessage(data: Uint8Array): unknown
-}
-
export function parseFigKiwiContainer(data: Uint8Array): FigKiwiPayload | null {
const header = new TextDecoder().decode(data.slice(0, 8))
if (header !== 'fig-kiwi') return null
@@ -70,19 +71,16 @@ export function parseFigKiwiContainer(data: Uint8Array): FigKiwiPayload | null {
}
if (chunks.length < 2) return null
- const compressed = chunks[1]
- let dataRaw: Uint8Array
- if (isZstdCompressed(compressed)) {
- dataRaw = zstdDecompress(compressed)
- } else {
- try {
- dataRaw = inflateSync(compressed)
- } catch {
- throw new Error('Failed to decompress fig-kiwi data chunk')
- }
- }
+ return { schemaDeflated: chunks[0], dataRaw: decompressFigKiwiData(chunks[1]), version }
+}
- return { schemaDeflated: chunks[0], dataRaw, version }
+function isRuntimeMessage(value: unknown): value is RuntimeMessage {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ !Array.isArray(value) &&
+ !(value instanceof Uint8Array)
+ )
}
export interface FigKiwiDecodeResult {
@@ -103,28 +101,29 @@ export function decodeFigKiwiCanvas(
if (!payload) throw new Error('Invalid fig-kiwi container')
const schemaBytes = inflateSync(payload.schemaDeflated)
- const schema = decodeBinarySchema(new ByteBuffer(schemaBytes))
+ const compiled = compileSchema(decodeBinarySchema(new ByteBuffer(schemaBytes)), headers)
if (onPages) {
try {
- const pages = extractFigPageManifest(schema, payload.dataRaw)
+ const pages = extractFigPageManifest(compiled.schema, payload.dataRaw)
if (pages.length > 0) onPages(pages)
} catch (error) {
console.warn('Failed to scan FIG page manifest; continuing with full decode:', error)
}
}
- const compiled = compileSchema(schema, headers) as CompiledKiwiSchema
- const message = compiled.decodeMessage(payload.dataRaw) as FigmaMessage
+ if (!compiled.decodeMessage) throw new Error('The fig-kiwi schema has no Message')
+ const message = compiled.decodeMessage(payload.dataRaw)
- const nodeChanges = message.nodeChanges
- if (!nodeChanges || nodeChanges.length === 0) {
+ const records = message.nodeChanges
+ if (!Array.isArray(records) || records.length === 0) {
throw new Error('No nodes found in .fig file')
}
-
+ const nodeChanges = records as NodeChange[]
deduplicateNodeChangePluginData(nodeChanges)
- const blobs: Uint8Array[] = (message.blobs ?? []).map((blob) =>
- blob.bytes instanceof Uint8Array ? blob.bytes : new Uint8Array(Object.values(blob.bytes))
- )
+ const blobs: Uint8Array[] = (Array.isArray(message.blobs) ? message.blobs : []).map((blob) => {
+ const bytes = isRuntimeMessage(blob) ? blob.bytes : undefined
+ return bytes instanceof Uint8Array ? bytes : new Uint8Array(Object.values(bytes ?? {}))
+ })
return {
nodeChanges,
diff --git a/packages/kiwi/src/schema-runtime/index.ts b/packages/kiwi/src/schema-runtime/index.ts
index 73ebda4a3..538dd6e79 100644
--- a/packages/kiwi/src/schema-runtime/index.ts
+++ b/packages/kiwi/src/schema-runtime/index.ts
@@ -2,12 +2,20 @@ export type { Schema, Definition, Field } from './schema'
export { ByteBuffer } from './bb'
export {
compileSchemaRuntime as compileSchema,
+ compileSchemaTables,
decodeWhole,
- type HeaderFields
+ TYPE,
+ type CompiledDefinition,
+ type CompiledField,
+ type CompiledSchema,
+ type HeaderFields,
+ type RuntimeCodec,
+ type RuntimeMessage,
+ type RuntimeValue,
+ type TypeCode
} from './interpreter'
export { decodeBinarySchema, encodeBinarySchema } from './binary'
export { parseSchema } from './parser'
-export { createSchemaSkipper, type SchemaSkipper } from './skip'
export {
validateSchema,
expectFieldNumber,
diff --git a/packages/kiwi/src/schema-runtime/interpreter.ts b/packages/kiwi/src/schema-runtime/interpreter.ts
index f97416c74..0e9076e68 100644
--- a/packages/kiwi/src/schema-runtime/interpreter.ts
+++ b/packages/kiwi/src/schema-runtime/interpreter.ts
@@ -1,11 +1,8 @@
import { ByteBuffer } from './bb'
-import { nativeTypes } from './parser'
-import type { Definition, Field, Schema } from './schema'
-import { createSchemaSkipper, type SchemaSkipper } from './skip'
+import type { Definition, DefinitionKind, Field, Schema } from './schema'
import { error, quote } from './util'
-type RuntimeEnum = { [name: string]: string | number }
-type RuntimeValue =
+export type RuntimeValue =
| boolean
| number
| string
@@ -14,10 +11,12 @@ type RuntimeValue =
| RuntimeMessage
| RuntimeValue[]
export type RuntimeMessage = { [name: string]: RuntimeValue }
+type RuntimeEnum = { [name: string]: string | number }
type DecodeFunction = (bb: ByteBuffer | Uint8Array) => RuntimeMessage
type EncodeFunction = (message: RuntimeMessage, bb?: ByteBuffer) => Uint8Array | undefined
type RuntimeEntry =
| typeof ByteBuffer
+ | CompiledSchema
| RuntimeEnum
| RuntimeValue
| DecodeFunction
@@ -25,13 +24,14 @@ type RuntimeEntry =
| undefined
export type RuntimeCodec = {
ByteBuffer: typeof ByteBuffer
+ /** The tables the codec reads with, for scanners that pick single fields out of a message. */
+ schema: CompiledSchema
encodeMessage?: EncodeFunction
decodeMessage?: DecodeFunction
encodePaint?: EncodeFunction
encodeNodeChange?: EncodeFunction
[name: string]: RuntimeEntry
}
-type Definitions = { [name: string]: Definition }
/**
* Message types decoded as headers: only the named fields are read, and the rest stay in the
@@ -40,6 +40,86 @@ type Definitions = { [name: string]: Definition }
*/
export type HeaderFields = Readonly<Record<string, readonly string[]>>
+/** What a field holds: a native type, or an enum, struct, or message of the schema. */
+export const TYPE = {
+ BOOL: 0,
+ BYTE: 1,
+ INT: 2,
+ UINT: 3,
+ FLOAT: 4,
+ STRING: 5,
+ INT64: 6,
+ UINT64: 7,
+ ENUM: 8,
+ STRUCT: 9,
+ MESSAGE: 10
+} as const
+export type TypeCode = (typeof TYPE)[keyof typeof TYPE]
+
+const NATIVE_TYPES: ReadonlyMap<string, TypeCode> = new Map([
+ ['bool', TYPE.BOOL],
+ ['byte', TYPE.BYTE],
+ ['int', TYPE.INT],
+ ['uint', TYPE.UINT],
+ ['float', TYPE.FLOAT],
+ ['string', TYPE.STRING],
+ ['int64', TYPE.INT64],
+ ['uint64', TYPE.UINT64]
+])
+
+const KIND_TYPES: Readonly<Record<DefinitionKind, TypeCode>> = {
+ ENUM: TYPE.ENUM,
+ STRUCT: TYPE.STRUCT,
+ MESSAGE: TYPE.MESSAGE
+}
+
+/** A field resolved once: its type as a number, and the definition behind it. */
+export interface CompiledField {
+ readonly name: string
+ readonly id: number
+ readonly isArray: boolean
+ readonly isDeprecated: boolean
+ readonly type: TypeCode
+ /** The definition an enum, struct, or message field holds; null for a native type. */
+ readonly definition: CompiledDefinition | null
+ /** Whether a header of the owning message keeps this field. */
+ readonly kept: boolean
+}
+
+export interface CompiledDefinition {
+ readonly name: string
+ readonly kind: DefinitionKind
+ readonly fields: readonly CompiledField[]
+ /** A message's fields by ID, with a hole at every ID the definition does not use. */
+ readonly byId: ReadonlyArray<CompiledField | undefined>
+ /** An enum's member names by value. */
+ readonly names: ReadonlyArray<string | undefined>
+ /** An enum's values by member name. */
+ readonly values: ReadonlyMap<string, number>
+ /** Whether messages of this definition decode as headers. */
+ readonly header: boolean
+}
+
+/**
+ * A schema's definitions resolved into tables, and the one reader, skipper, and writer that
+ * every codec and scanner shares; nothing is looked up by name while a message is read.
+ */
+export interface CompiledSchema {
+ readonly definitions: readonly CompiledDefinition[]
+ /** A definition by name; throws for one the schema lacks. */
+ definition(name: string): CompiledDefinition
+ /** One field's value, its array included; its shape follows the schema at run time. */
+ read(field: CompiledField, bb: ByteBuffer): unknown
+ /** Past one field's value, its array included. */
+ skip(field: CompiledField, bb: ByteBuffer): void
+ /** One field's value, its array included; a message field writes its own end marker. */
+ write(field: CompiledField, value: RuntimeValue, bb: ByteBuffer): void
+ /** A struct or message read in full, or as a header where the definition is one. */
+ decode(definition: CompiledDefinition, bb: ByteBuffer): RuntimeMessage
+ /** A struct or message written in full. */
+ encode(definition: CompiledDefinition, message: RuntimeMessage, bb: ByteBuffer): void
+}
+
/**
* What a header needs to be read whole: the bytes it came from, where it starts in them, and
* the decoder that reads every field. They are hidden properties of the header, so each costs a
@@ -49,12 +129,6 @@ const HEADER_BYTES = Symbol('header bytes')
const HEADER_START = Symbol('header start')
const HEADER_WHOLE = Symbol('header whole decoder')
-/**
- * How many whole decodes are running. A message type can nest itself, as instance overrides
- * are records too, and a message read whole is read whole all the way down.
- */
-let wholeDepth = 0
-
/**
* A header read again in full from the bytes it came from, as a new message the caller owns,
* or undefined for a message that was decoded whole.
@@ -74,330 +148,318 @@ function hide(message: RuntimeMessage, key: symbol, value: unknown): void {
Reflect.defineProperty(message, key, { value, enumerable: false })
}
-interface HeaderDecoding {
- keep: ReadonlySet<string>
- skipper: SchemaSkipper
- /** Reads the message in full, for `decodeWhole`. */
- whole: (bb: ByteBuffer) => RuntimeMessage
+function invalidMessage(): never {
+ throw new Error('Attempted to parse invalid message')
}
-function wholeDecoder(
- decode: (bb: ByteBuffer) => RuntimeMessage
-): (bb: ByteBuffer) => RuntimeMessage {
- return (bb) => {
- wholeDepth++
- try {
- return decode(bb)
- } finally {
- wholeDepth--
+function compileDefinitions(schema: Schema, headers?: HeaderFields): CompiledDefinition[] {
+ const byName = new Map<string, Definition>()
+ for (const definition of schema.definitions) byName.set(definition.name, definition)
+ const compiled = new Map<string, CompiledDefinition>()
+ const definitions = schema.definitions.map((definition): CompiledDefinition => {
+ const fields: CompiledField[] = []
+ const byId: (CompiledField | undefined)[] = []
+ const names: (string | undefined)[] = []
+ const values = new Map<string, number>()
+ if (definition.kind === 'ENUM')
+ for (const field of definition.fields) {
+ names[field.value] = field.name
+ values.set(field.name, field.value)
+ }
+ const kept = headers?.[definition.name]
+ const result: CompiledDefinition = {
+ name: definition.name,
+ kind: definition.kind,
+ fields,
+ byId,
+ names,
+ values,
+ header: definition.kind === 'MESSAGE' && kept !== undefined
}
- }
+ compiled.set(definition.name, result)
+ return result
+ })
+ schema.definitions.forEach((definition, index) => {
+ if (definition.kind === 'ENUM') return
+ const target = definitions[index]
+ const fields = target.fields as CompiledField[]
+ const byId = target.byId as (CompiledField | undefined)[]
+ const kept = headers?.[definition.name]
+ for (const field of definition.fields) {
+ const compiledField = compileField(field, kept, byName, compiled)
+ fields.push(compiledField)
+ byId[field.value] = compiledField
+ }
+ })
+ return definitions
}
-function asDecodeFunction(value: unknown): DecodeFunction {
- return value as DecodeFunction
-}
-function asEncodeFunction(value: unknown): EncodeFunction {
- return value as EncodeFunction
-}
-function asRuntimeEnum(value: unknown): RuntimeEnum {
- return value as RuntimeEnum
+function compileField(
+ field: Field,
+ kept: readonly string[] | undefined,
+ byName: ReadonlyMap<string, Definition>,
+ compiled: ReadonlyMap<string, CompiledDefinition>
+): CompiledField {
+ const type = field.type
+ if (type === null)
+ error('Invalid type null for field ' + quote(field.name), field.line, field.column)
+ const native = NATIVE_TYPES.get(type)
+ const definition = native === undefined ? byName.get(type) : undefined
+ if (native === undefined && !definition)
+ error(
+ 'Invalid type ' + quote(type) + ' for field ' + quote(field.name),
+ field.line,
+ field.column
+ )
+ return {
+ name: field.name,
+ id: field.value,
+ isArray: field.isArray,
+ isDeprecated: field.isDeprecated,
+ type: native ?? KIND_TYPES[(definition as Definition).kind],
+ definition: definition ? (compiled.get(definition.name) ?? null) : null,
+ kept: kept === undefined || kept.includes(field.name)
+ }
}
-function hasDefinition(definitions: Definitions, name: string): boolean {
- return Object.hasOwn(definitions, name)
-}
+export function compileSchemaTables(schema: Schema, headers?: HeaderFields): CompiledSchema {
+ const definitions = compileDefinitions(schema, headers)
+ const byName = new Map(definitions.map((definition) => [definition.name, definition]))
+ /**
+ * How many whole decodes are running. A message type can nest itself, as instance overrides
+ * are records too, and a message read whole is read whole all the way down.
+ */
+ let wholeDepth = 0
+ const wholeDecoders = new WeakMap<CompiledDefinition, (bb: ByteBuffer) => RuntimeMessage>()
+
+ const definition = (name: string): CompiledDefinition => {
+ const found = byName.get(name)
+ if (!found) error('Invalid type ' + quote(name), 0, 0)
+ return found
+ }
-function validateFieldTypes(definitions: Definitions): void {
- let definitionList = Object.values(definitions)
- for (let i = 0; i < definitionList.length; i++) {
- let definition = definitionList[i]
- if (definition.kind === 'ENUM') continue
- for (let j = 0; j < definition.fields.length; j++) {
- let field = definition.fields[j]
- let type = field.type
- if (type === null) {
- error('Invalid type null for field ' + quote(field.name), field.line, field.column)
- }
- if (!nativeTypes.includes(type) && !hasDefinition(definitions, type)) {
- error(
- 'Invalid type ' + quote(type) + ' for field ' + quote(field.name),
- field.line,
- field.column
- )
- }
+ const readValue = (field: CompiledField, bb: ByteBuffer): RuntimeValue => {
+ switch (field.type) {
+ case TYPE.BOOL:
+ return !!bb.readByte()
+ case TYPE.BYTE:
+ return bb.readByte()
+ case TYPE.INT:
+ return bb.readVarInt()
+ case TYPE.UINT:
+ return bb.readVarUint()
+ case TYPE.FLOAT:
+ return bb.readVarFloat()
+ case TYPE.STRING:
+ return bb.readString()
+ case TYPE.INT64:
+ return bb.readVarInt64()
+ case TYPE.UINT64:
+ return bb.readVarUint64()
+ case TYPE.ENUM:
+ return (field.definition as CompiledDefinition).names[bb.readVarUint()] as RuntimeValue
+ default:
+ return decode(field.definition as CompiledDefinition, bb)
}
}
-}
-// Interprets a schema field-by-field instead of generating and `eval`-ing a
-// per-schema decoder/encoder (as `compileSchemaJS` + `new Function` do). A
-// `new Function(...)`-built codec is indistinguishable from `eval` to a CSP:
-// embedders that run under `script-src` without `unsafe-eval` (e.g. a
-// sandboxed plugin host) cannot call `compileSchema` at all otherwise. This
-// walk produces byte-identical output to the generated code — same field
-// order, same tag/no-tag rules for MESSAGE vs STRUCT, same deprecated-field
-// skip behavior — so it is a drop-in replacement, not a new format.
-function readField(
- self: RuntimeCodec,
- definitions: Definitions,
- type: string,
- bb: ByteBuffer
-): RuntimeValue {
- switch (type) {
- case 'bool':
- return !!bb.readByte()
- case 'byte':
- return bb.readByte()
- case 'int':
- return bb.readVarInt()
- case 'uint':
- return bb.readVarUint()
- case 'float':
- return bb.readVarFloat()
- case 'string':
- return bb.readString()
- case 'int64':
- return bb.readVarInt64()
- case 'uint64':
- return bb.readVarUint64()
- default: {
- let definition = definitions[type]
- if (!definition) error('Invalid type ' + quote(type), 0, 0)
- if (definition.kind === 'ENUM') return asRuntimeEnum(self[definition.name])[bb.readVarUint()]
- return asDecodeFunction(self['decode' + definition.name])(bb)
- }
+ const read = (field: CompiledField, bb: ByteBuffer): RuntimeValue => {
+ if (!field.isArray) return readValue(field, bb)
+ if (field.type === TYPE.BYTE) return bb.readByteArray()
+ const length = bb.readVarUint()
+ const values: RuntimeValue[] = Array.from({ length })
+ for (let i = 0; i < length; i++) values[i] = readValue(field, bb)
+ return values
}
-}
-function writeField(
- self: RuntimeCodec,
- definitions: Definitions,
- type: string,
- value: RuntimeValue,
- bb: ByteBuffer
-): void {
- switch (type) {
- case 'bool':
- case 'byte':
- bb.writeByte(value as number)
- return
- case 'int':
- bb.writeVarInt(value as number)
- return
- case 'uint':
- bb.writeVarUint(value as number)
- return
- case 'float':
- bb.writeVarFloat(value as number)
- return
- case 'string':
- bb.writeString(value as string)
- return
- case 'int64':
- bb.writeVarInt64(value as bigint | string)
- return
- case 'uint64':
- bb.writeVarUint64(value as bigint | string)
- return
- default: {
- let definition = definitions[type]
- if (!definition) error('Invalid type ' + quote(type), 0, 0)
- if (definition.kind === 'ENUM') {
- let encoded = asRuntimeEnum(self[definition.name])[value as string]
- if (encoded === undefined) {
- throw new Error(
- 'Invalid value ' + JSON.stringify(value) + ' for enum ' + quote(definition.name)
- )
- }
- bb.writeVarUint(encoded as number)
- } else {
- asEncodeFunction(self['encode' + definition.name])(value as RuntimeMessage, bb)
+ const skipValue = (field: CompiledField, bb: ByteBuffer): void => {
+ switch (field.type) {
+ case TYPE.BOOL:
+ case TYPE.BYTE:
+ bb.readByte()
+ return
+ case TYPE.INT:
+ case TYPE.UINT:
+ case TYPE.ENUM:
+ bb.readVarUint()
+ return
+ case TYPE.FLOAT:
+ bb.readVarFloat()
+ return
+ case TYPE.STRING:
+ bb.skipString()
+ return
+ case TYPE.INT64:
+ case TYPE.UINT64:
+ bb.readVarUint64()
+ return
+ case TYPE.STRUCT:
+ for (const inner of (field.definition as CompiledDefinition).fields) skip(inner, bb)
+ return
+ default: {
+ const byId = (field.definition as CompiledDefinition).byId
+ for (let id = bb.readVarUint(); id !== 0; id = bb.readVarUint())
+ skip(byId[id] ?? invalidMessage(), bb)
}
}
}
-}
-
-function readInto(
- self: RuntimeCodec,
- definitions: Definitions,
- field: Field,
- bb: ByteBuffer,
- result: RuntimeMessage
-): void {
- let type = field.type
- if (type === null)
- error('Invalid type null for field ' + quote(field.name), field.line, field.column)
- if (field.isArray) {
- if (field.isDeprecated) {
- if (type === 'byte') bb.readByteArray()
- else {
- let length = bb.readVarUint()
- while (length-- > 0) readField(self, definitions, type, bb)
- }
+ const skip = (field: CompiledField, bb: ByteBuffer): void => {
+ if (!field.isArray) {
+ skipValue(field, bb)
return
}
- if (type === 'byte') {
- result[field.name] = bb.readByteArray()
+ if (field.type === TYPE.BYTE) {
+ bb.skipByteArray()
return
}
- let length = bb.readVarUint()
- let values: RuntimeValue[] = Array.from({ length })
- result[field.name] = values
- for (let i = 0; i < length; i++) values[i] = readField(self, definitions, type, bb)
- return
+ for (let length = bb.readVarUint(); length > 0; length--) skipValue(field, bb)
}
- if (field.isDeprecated) {
- readField(self, definitions, type, bb)
- return
+ const readInto = (field: CompiledField, bb: ByteBuffer, result: RuntimeMessage): void => {
+ if (field.isDeprecated) skip(field, bb)
+ else result[field.name] = read(field, bb)
}
- result[field.name] = readField(self, definitions, type, bb)
-}
-
-function writeFrom(
- self: RuntimeCodec,
- definitions: Definitions,
- field: Field,
- value: RuntimeValue,
- bb: ByteBuffer
-): void {
- let type = field.type
- if (type === null)
- error('Invalid type null for field ' + quote(field.name), field.line, field.column)
-
- if (field.isArray) {
- if (type === 'byte') {
- bb.writeByteArray(value as Uint8Array)
- return
+ const decode = (target: CompiledDefinition, bb: ByteBuffer): RuntimeMessage => {
+ const result: RuntimeMessage = {}
+ if (target.kind === 'STRUCT') {
+ for (const field of target.fields) readInto(field, bb, result)
+ return result
}
- let values = value as RuntimeValue[]
- bb.writeVarUint(values.length)
- for (let i = 0; i < values.length; i++) writeField(self, definitions, type, values[i], bb)
- return
+ const asHeader = target.header && wholeDepth === 0
+ if (asHeader) {
+ hide(result, HEADER_BYTES, bb.bytes)
+ hide(result, HEADER_START, bb.offset)
+ hide(result, HEADER_WHOLE, wholeDecoder(target))
+ }
+ const byId = target.byId
+ for (let id = bb.readVarUint(); id !== 0; id = bb.readVarUint()) {
+ const field = byId[id] ?? invalidMessage()
+ if (asHeader && !field.kept) skip(field, bb)
+ else readInto(field, bb, result)
+ }
+ return result
}
- writeField(self, definitions, type, value, bb)
-}
-
-function interpretDecode(
- self: RuntimeCodec,
- definitions: Definitions,
- definition: Definition,
- header?: HeaderDecoding
-) {
- let fieldsById = new Map<number, Field>()
- for (let i = 0; i < definition.fields.length; i++)
- fieldsById.set(definition.fields[i].value, definition.fields[i])
- return function (bb: ByteBuffer | Uint8Array): RuntimeMessage {
- let buffer = bb instanceof self.ByteBuffer ? bb : new self.ByteBuffer(bb)
- let result: RuntimeMessage = {}
-
- if (definition.kind === 'MESSAGE') {
- const asHeader = header && wholeDepth === 0 ? header : undefined
- if (asHeader) {
- hide(result, HEADER_BYTES, buffer.bytes)
- hide(result, HEADER_START, buffer.offset)
- hide(result, HEADER_WHOLE, asHeader.whole)
- }
- while (true) {
- const id = buffer.readVarUint()
- if (id === 0) return result
- const field = fieldsById.get(id)
- if (!field) throw new Error('Attempted to parse invalid message')
- if (asHeader && !asHeader.keep.has(field.name)) asHeader.skipper.skipField(field, buffer)
- else readInto(self, definitions, field, buffer, result)
+ const wholeDecoder = (target: CompiledDefinition): ((bb: ByteBuffer) => RuntimeMessage) => {
+ let whole = wholeDecoders.get(target)
+ if (!whole) {
+ whole = (bb) => {
+ wholeDepth++
+ try {
+ return decode(target, bb)
+ } finally {
+ wholeDepth--
+ }
}
- } else {
- for (let i = 0; i < definition.fields.length; i++) {
- readInto(self, definitions, definition.fields[i], buffer, result)
+ wholeDecoders.set(target, whole)
+ }
+ return whole
+ }
+
+ const writeValue = (field: CompiledField, value: RuntimeValue, bb: ByteBuffer): void => {
+ switch (field.type) {
+ case TYPE.BOOL:
+ case TYPE.BYTE:
+ bb.writeByte(value as number)
+ return
+ case TYPE.INT:
+ bb.writeVarInt(value as number)
+ return
+ case TYPE.UINT:
+ bb.writeVarUint(value as number)
+ return
+ case TYPE.FLOAT:
+ bb.writeVarFloat(value as number)
+ return
+ case TYPE.STRING:
+ bb.writeString(value as string)
+ return
+ case TYPE.INT64:
+ bb.writeVarInt64(value as bigint | string)
+ return
+ case TYPE.UINT64:
+ bb.writeVarUint64(value as bigint | string)
+ return
+ case TYPE.ENUM: {
+ const target = field.definition as CompiledDefinition
+ const encoded = target.values.get(value as string)
+ if (encoded === undefined)
+ throw new Error(
+ 'Invalid value ' + JSON.stringify(value) + ' for enum ' + quote(target.name)
+ )
+ bb.writeVarUint(encoded)
+ return
}
- return result
+ default:
+ encode(field.definition as CompiledDefinition, value as RuntimeMessage, bb)
}
}
-}
-function interpretEncode(self: RuntimeCodec, definitions: Definitions, definition: Definition) {
- return function (message: RuntimeMessage, bb?: ByteBuffer): Uint8Array | undefined {
- let isTopLevel = !bb
- let buffer = bb || new self.ByteBuffer()
+ const write = (field: CompiledField, value: RuntimeValue, bb: ByteBuffer): void => {
+ if (!field.isArray) {
+ writeValue(field, value, bb)
+ return
+ }
+ if (field.type === TYPE.BYTE) {
+ bb.writeByteArray(value as Uint8Array)
+ return
+ }
+ const values = value as RuntimeValue[]
+ bb.writeVarUint(values.length)
+ for (const item of values) writeValue(field, item, bb)
+ }
- for (let i = 0; i < definition.fields.length; i++) {
- let field = definition.fields[i]
+ const encode = (target: CompiledDefinition, message: RuntimeMessage, bb: ByteBuffer): void => {
+ const isMessage = target.kind === 'MESSAGE'
+ for (const field of target.fields) {
if (field.isDeprecated) continue
- let value = message[field.name]
+ const value = message[field.name]
if (value != null) {
- if (definition.kind === 'MESSAGE') buffer.writeVarUint(field.value)
- writeFrom(self, definitions, field, value, buffer)
- } else if (definition.kind === 'STRUCT') {
+ if (isMessage) bb.writeVarUint(field.id)
+ write(field, value, bb)
+ } else if (!isMessage) {
throw new Error('Missing required field ' + quote(field.name))
}
}
-
- if (definition.kind === 'MESSAGE') buffer.writeVarUint(0)
- if (isTopLevel) return buffer.toUint8Array()
- return undefined
+ if (isMessage) bb.writeVarUint(0)
}
+
+ return { definitions, definition, read, skip, write, decode, encode }
}
+/**
+ * Interprets a schema through its compiled tables instead of generating and `eval`-ing a
+ * per-schema decoder/encoder (as `compileSchemaJS` + `new Function` do). A `new Function(...)`-
+ * built codec is indistinguishable from `eval` to a CSP: embedders that run under `script-src`
+ * without `unsafe-eval` (e.g. a sandboxed plugin host) cannot call `compileSchema` at all
+ * otherwise. The tables produce byte-identical output to the generated code: same field order,
+ * same tag/no-tag rules for MESSAGE vs STRUCT, same deprecated-field skip behavior.
+ */
export function compileSchemaRuntime(schema: Schema, headers?: HeaderFields): RuntimeCodec {
- let definitions: Definitions = Object.create(null) as Definitions
- for (let i = 0; i < schema.definitions.length; i++) {
- definitions[schema.definitions[i].name] = schema.definitions[i]
- }
-
- validateFieldTypes(definitions)
-
- let result: RuntimeCodec = {
- ByteBuffer: ByteBuffer
- }
- let skipper: SchemaSkipper | undefined
-
- for (let i = 0; i < schema.definitions.length; i++) {
- let definition = schema.definitions[i]
-
- switch (definition.kind) {
- case 'ENUM': {
- let value: RuntimeEnum = {}
- for (let j = 0; j < definition.fields.length; j++) {
- let field = definition.fields[j]
- value[field.name] = field.value
- value[field.value] = field.name
- }
- result[definition.name] = value
- break
- }
-
- case 'STRUCT':
- case 'MESSAGE': {
- const keep = definition.kind === 'MESSAGE' ? headers?.[definition.name] : undefined
- const header: HeaderDecoding | undefined = keep && {
- keep: new Set(keep),
- skipper: (skipper ??= createSchemaSkipper(schema)),
- whole: wholeDecoder(interpretDecode(result, definitions, definition))
- }
- result['decode' + definition.name] = interpretDecode(
- result,
- definitions,
- definition,
- header
- )
- result['encode' + definition.name] = interpretEncode(result, definitions, definition)
- break
- }
-
- default: {
- error(
- 'Invalid definition kind ' + quote(definition.kind),
- definition.line,
- definition.column
- )
- break
+ const compiled = compileSchemaTables(schema, headers)
+ const codec: RuntimeCodec = { ByteBuffer, schema: compiled }
+ for (const definition of compiled.definitions) {
+ if (definition.kind === 'ENUM') {
+ const value: RuntimeEnum = {}
+ for (const [name, member] of definition.values) {
+ value[name] = member
+ value[member] = name
}
+ codec[definition.name] = value
+ continue
+ }
+ codec['decode' + definition.name] = (bb: ByteBuffer | Uint8Array): RuntimeMessage =>
+ compiled.decode(definition, bb instanceof codec.ByteBuffer ? bb : new codec.ByteBuffer(bb))
+ codec['encode' + definition.name] = (
+ message: RuntimeMessage,
+ bb?: ByteBuffer
+ ): Uint8Array | undefined => {
+ const buffer = bb ?? new codec.ByteBuffer()
+ compiled.encode(definition, message, buffer)
+ return bb ? undefined : buffer.toUint8Array()
}
}
-
- return result
+ return codec
}
diff --git a/packages/kiwi/src/schema-runtime/skip.ts b/packages/kiwi/src/schema-runtime/skip.ts
deleted file mode 100644
index 23649f86e..000000000
--- a/packages/kiwi/src/schema-runtime/skip.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import type { ByteBuffer } from './bb'
-import type { Definition, Field, Schema } from './schema'
-import { error, quote } from './util'
-
-/**
- * Moves a buffer past encoded values without building them, so a reader can find where each
- * value lies in a large message and copy the bytes of the ones it does not change.
- */
-export interface SchemaSkipper {
- definition(name: string): Definition
- /** A definition's fields by their IDs, built once per definition. */
- fieldsById(name: string): ReadonlyMap<number, Field>
- /** Past one value of a field, its array included. */
- skipField(field: Field, bb: ByteBuffer): void
- /** Past one value of a type: a native type, an enum, a struct or a message. */
- skipValue(type: string, bb: ByteBuffer): void
-}
-
-export function createSchemaSkipper(schema: Schema): SchemaSkipper {
- const definitions = new Map(schema.definitions.map((definition) => [definition.name, definition]))
- const fieldsById = new Map<string, Map<number, Field>>()
- const definition = (name: string): Definition => {
- const found = definitions.get(name)
- if (!found) error('Invalid type ' + quote(name), 0, 0)
- return found
- }
- const messageFields = (found: Definition): Map<number, Field> => {
- let fields = fieldsById.get(found.name)
- if (!fields) {
- fields = new Map(found.fields.map((field) => [field.value, field]))
- fieldsById.set(found.name, fields)
- }
- return fields
- }
-
- const skipValue = (type: string, bb: ByteBuffer): void => {
- switch (type) {
- case 'bool':
- case 'byte':
- bb.readByte()
- return
- case 'int':
- case 'uint':
- bb.readVarUint()
- return
- case 'float':
- bb.readVarFloat()
- return
- case 'string':
- bb.skipString()
- return
- case 'int64':
- case 'uint64':
- bb.readVarUint64()
- return
- }
- const found = definition(type)
- if (found.kind === 'ENUM') {
- bb.readVarUint()
- return
- }
- if (found.kind === 'STRUCT') {
- for (const field of found.fields) skipField(field, bb)
- return
- }
- const fields = messageFields(found)
- for (let id = bb.readVarUint(); id !== 0; id = bb.readVarUint()) {
- const field = fields.get(id)
- if (!field) throw new Error('Attempted to parse invalid message')
- skipField(field, bb)
- }
- }
-
- const skipField = (field: Field, bb: ByteBuffer): void => {
- const type = field.type
- if (type === null)
- error('Invalid type null for field ' + quote(field.name), field.line, field.column)
- if (!field.isArray) {
- skipValue(type, bb)
- return
- }
- if (type === 'byte') {
- bb.skipByteArray()
- return
- }
- for (let length = bb.readVarUint(); length > 0; length--) skipValue(type, bb)
- }
-
- return {
- definition,
- fieldsById: (name) => messageFields(definition(name)),
- skipField,
- skipValue
- }
-}
diff --git a/packages/kiwi/tests/compiled-schema.test.ts b/packages/kiwi/tests/compiled-schema.test.ts
new file mode 100644
index 000000000..39c15ba2f
--- /dev/null
+++ b/packages/kiwi/tests/compiled-schema.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ ByteBuffer,
+ compileSchema,
+ compileSchemaTables,
+ parseSchema,
+ TYPE,
+ type RuntimeMessage
+} from '../src/schema-runtime'
+
+const schema = parseSchema(`
+package Example;
+
+enum Kind {
+ CARD = 1;
+ BADGE = 2;
+}
+
+struct Point {
+ float x;
+ float y;
+}
+
+message Item {
+ uint id = 1;
+ Kind kind = 2;
+ Point[] outline = 3;
+ string note = 4;
+ byte[] payload = 5;
+ int64 stamp = 6;
+ Item[] children = 7;
+ bool old = 8 [deprecated];
+}
+
+message Document {
+ Item[] items = 1;
+ Kind[] kinds = 2;
+}
+`)
+
+const document: RuntimeMessage = {
+ items: [
+ {
+ id: 1,
+ kind: 'CARD',
+ outline: [
+ { x: 1, y: 2 },
+ { x: 0, y: -3.5 }
+ ],
+ note: 'first',
+ payload: new Uint8Array([7, 8, 9]),
+ stamp: 12345678901234n,
+ children: [{ id: 3, note: 'nested', children: [{ id: 4, kind: 'BADGE' }] }]
+ },
+ { id: 2, note: 'second' }
+ ],
+ kinds: ['BADGE', 'CARD']
+}
+
+function encodedDocument(): Uint8Array {
+ const encode = compileSchema(schema).encodeDocument as (message: RuntimeMessage) => Uint8Array
+ return encode(document)
+}
+
+describe('compiled schema tables', () => {
+ test('resolves every field to a type code and its definition', () => {
+ const tables = compileSchemaTables(schema)
+ const item = tables.definition('Item')
+
+ expect(item.fields.map((field) => field.type)).toEqual([
+ TYPE.UINT,
+ TYPE.ENUM,
+ TYPE.STRUCT,
+ TYPE.STRING,
+ TYPE.BYTE,
+ TYPE.INT64,
+ TYPE.MESSAGE,
+ TYPE.BOOL
+ ])
+ expect(item.byId[2]?.definition?.name).toBe('Kind')
+ expect(item.byId[7]?.definition).toBe(item)
+ expect(item.byId[9]).toBeUndefined()
+ expect(tables.definition('Kind').names[2]).toBe('BADGE')
+ expect(() => tables.definition('Missing')).toThrow('Invalid type "Missing"')
+ })
+
+ test('skipping a field lands where reading it does, for every field kind', () => {
+ const tables = compileSchemaTables(schema)
+ const bytes = encodedDocument()
+ const reading = new ByteBuffer(bytes)
+ const skipping = new ByteBuffer(bytes)
+ const message = tables.definition('Document')
+
+ for (let id = reading.readVarUint(); id !== 0; id = reading.readVarUint()) {
+ expect(skipping.readVarUint()).toBe(id)
+ const field = message.byId[id]
+ if (!field) throw new Error(`Unknown field ${id}`)
+ tables.read(field, reading)
+ tables.skip(field, skipping)
+ expect(skipping.offset).toBe(reading.offset)
+ }
+ expect(skipping.readVarUint()).toBe(0)
+ expect(reading.offset).toBe(bytes.length)
+ })
+
+ test('decodes through the tables what the codec encoded', () => {
+ const tables = compileSchemaTables(schema)
+ const decoded = tables.decode(tables.definition('Document'), new ByteBuffer(encodedDocument()))
+
+ expect<unknown>(decoded).toEqual(document)
+ })
+
+ test('rejects a field ID the definition does not use', () => {
+ const tables = compileSchemaTables(schema)
+ const bytes = new ByteBuffer()
+ bytes.writeVarUint(9)
+
+ expect(() => tables.decode(tables.definition('Item'), bytes)).toThrow(
+ 'Attempted to parse invalid message'
+ )
+ })
+})
diff --git a/packages/kiwi/tests/container.test.ts b/packages/kiwi/tests/container.test.ts
index c6933559b..03ac042cc 100644
--- a/packages/kiwi/tests/container.test.ts
+++ b/packages/kiwi/tests/container.test.ts
@@ -8,7 +8,9 @@ import {
decompressFigKiwiDataAsync,
FIG_KIWI_DEFAULT_VERSION,
loadFigDataCompressor,
+ loadFigDataDecompressor,
loadWasmFigDataCompressor,
+ loadWasmFigDataDecompressor,
parseFigKiwiChunks,
type FigDataCompressor
} from '../src/fig/container'
@@ -32,6 +34,26 @@ function declaresContentSize(frame: Uint8Array): boolean {
return singleSegment === 1 || descriptor >> 6 !== 0
}
+/**
+ * A zstd frame of one raw block that declares no content size (RFC 8878 §3.1.1): a frame header
+ * descriptor with every flag clear, a window descriptor, and a last raw block of `data`.
+ */
+function rawZstdFrameWithoutContentSize(data: Uint8Array): Uint8Array {
+ const blockHeader = 1 | (0 << 1) | (data.length << 3)
+ return new Uint8Array([
+ 0x28,
+ 0xb5,
+ 0x2f,
+ 0xfd,
+ 0x00,
+ 0x70,
+ blockHeader & 0xff,
+ (blockHeader >> 8) & 0xff,
+ (blockHeader >> 16) & 0xff,
+ ...data
+ ])
+}
+
describe('Figma FIG Kiwi container helpers', () => {
test('builds and parses fig-kiwi chunks', async () => {
const schemaDeflated = new Uint8Array([1, 2, 3])
@@ -99,4 +121,45 @@ describe('Figma FIG Kiwi container helpers', () => {
test('rejects non fig-kiwi data', () => {
expect(parseFigKiwiChunks(new TextEncoder().encode('not-fig-kiwi'))).toBeNull()
})
+
+ // Bun's own zstd where it runs, and the WebAssembly build browsers and webviews read with.
+ for (const [decoder, load] of [
+ ['native', loadFigDataDecompressor],
+ ['WebAssembly', loadWasmFigDataDecompressor]
+ ] as const) {
+ test(`${decoder} zstd decompresses every level, and deflate, synchronously`, async () => {
+ const dataRaw = sampleDocument()
+ const decompress = await load()
+ for (const level of [3, 19]) {
+ const compress = await loadWasmFigDataCompressor(level)
+ expect(decompress(compress(dataRaw))).toEqual(dataRaw)
+ }
+ expect(decompress(deflateSync(dataRaw))).toEqual(dataRaw)
+ })
+
+ // A Node Buffer slices into views of the whole message, which structuredClone then copies in
+ // full for every byte array a record holds; a plain Uint8Array slices by copying.
+ test(`${decoder} zstd returns a plain Uint8Array whose slice is a copy`, async () => {
+ const dataRaw = sampleDocument()
+ const decompress = await load()
+ const compress = await loadWasmFigDataCompressor(3)
+
+ const decompressed = decompress(compress(dataRaw))
+
+ expect(Object.getPrototypeOf(decompressed)).toBe(Uint8Array.prototype)
+ expect(decompressed.slice(0, 8).buffer.byteLength).toBe(8)
+ })
+
+ // Figma writes the size, but a frame from another tool may not; the decoder streams those.
+ test(`${decoder} zstd decompresses a frame that declares no content size`, async () => {
+ const dataRaw = new TextEncoder().encode('payload without a declared size')
+ const frame = rawZstdFrameWithoutContentSize(dataRaw)
+ expect(isZstdCompressed(frame)).toBe(true)
+ expect(declaresContentSize(frame)).toBe(false)
+
+ const decompress = await load()
+
+ expect(decompress(frame)).toEqual(dataRaw)
+ })
+ }
})
diff --git a/tests/AGENTS.md b/tests/AGENTS.md
index a2f49daec..10d470eec 100644
--- a/tests/AGENTS.md
+++ b/tests/AGENTS.md
@@ -23,6 +23,7 @@
- A stand-in for an interface a test cannot build (CanvasKit, `EditorStore`) goes through `asDouble` from `#tests/helpers/doubles`, which is the one sanctioned widening; `open-pencil/no-broad-double-cast` rejects the `as unknown as` spelling.
- In Bun tests prefer injected dependencies or scoped spies with explicit cleanup. `mock.restore()` restores spies but does not undo `mock.module()` overrides; do not assume module mocks are isolated by cleanup hooks. Read the installed runner's lifecycle and mocking docs before adding global or module-level instrumentation.
- Make flaky tests deterministic; raising a timeout is never the fix. Keep package-manager invocations out of `bun test` suites; their cold start is not bounded.
+- Heavy tests are opt-in: `runsHeavyTests` is false unless `BUN_HEAVY_TESTS=true`, which only the unit test runner sets while giving each heavy file its own process, so run suites through `bun run test:unit`, `test:unit:quick`, or `bun tools/dev/unit-tests/src/run.ts <group>`; a file that parses a large fixture, or a populated `gold-preview.fig` more than once, gates it with `heavy` or `test.if(runsHeavyTests)` and is listed in `HEAVY_UNIT_TEST_PATTERNS` (`tools/dev/unit-tests/src/shards.ts`).
## Browser runs
diff --git a/tests/engine/clipboard/fixtures/gold-preview-roundtrip.test.ts b/tests/engine/clipboard/fixtures/gold-preview-roundtrip.test.ts
index 7e4268858..a6a43d320 100644
--- a/tests/engine/clipboard/fixtures/gold-preview-roundtrip.test.ts
+++ b/tests/engine/clipboard/fixtures/gold-preview-roundtrip.test.ts
@@ -1,4 +1,4 @@
-import { beforeAll, describe, expect, it } from 'bun:test'
+import { beforeAll, expect, it } from 'bun:test'
import { readFileSync } from 'node:fs'
import {
@@ -14,9 +14,9 @@ import {
} from '@open-pencil/core'
import { expectDefined } from '#tests/helpers/assert'
-import { HEAVY_TEST_TIMEOUT_MS } from '#tests/helpers/test-utils'
+import { heavy, HEAVY_TEST_TIMEOUT_MS } from '#tests/helpers/test-utils'
-describe('gold-preview.fig clipboard roundtrip', () => {
+heavy('gold-preview.fig clipboard roundtrip', () => {
let graph: SceneGraph
let pageId: string
let topLevelNodes: SceneNode[]
diff --git a/tests/engine/io/fig/import/group-reclassify.test.ts b/tests/engine/io/fig/import/group-reclassify.test.ts
index 669c82563..c66d0111b 100644
--- a/tests/engine/io/fig/import/group-reclassify.test.ts
+++ b/tests/engine/io/fig/import/group-reclassify.test.ts
@@ -1,13 +1,13 @@
-import { describe, expect, test } from 'bun:test'
+import { expect, test } from 'bun:test'
import { nodeChangeToProps } from '@open-pencil/fig/node-change'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { parseFixture } from '#tests/helpers/fig/fixtures'
import { collectAllNodes } from '#tests/helpers/fig/traversal'
-import { HEAVY_TEST_TIMEOUT_MS } from '#tests/helpers/test-utils'
+import { heavy, HEAVY_TEST_TIMEOUT_MS } from '#tests/helpers/test-utils'
-describe('Figma group reclassification on import', () => {
+heavy('Figma group reclassification on import', () => {
test('FRAME with resizeToFit imports as GROUP', () => {
const props = nodeChangeToProps(
{ type: 'FRAME', name: 'Group 1', resizeToFit: true } as NodeChange,
diff --git a/tests/engine/layout/auto-layout/text/measurement.test.ts b/tests/engine/layout/auto-layout/text/measurement.test.ts
index 5dcce1fdf..6d80457ea 100644
--- a/tests/engine/layout/auto-layout/text/measurement.test.ts
+++ b/tests/engine/layout/auto-layout/text/measurement.test.ts
@@ -1,13 +1,13 @@
-import { describe, expect, test } from 'bun:test'
+import { expect, test } from 'bun:test'
import { computeAllLayouts, SceneGraph, setTextMeasurer } from '@open-pencil/core'
import { createEditor } from '@open-pencil/core/editor'
import { getNodeOrThrow } from '#tests/helpers/assert'
import { autoFrame, loadFixtureGraph, pageId, rect } from '#tests/helpers/layout'
-import { HEAVY_TEST_TIMEOUT_MS } from '#tests/helpers/test-utils'
+import { heavy, HEAVY_TEST_TIMEOUT_MS } from '#tests/helpers/test-utils'
-describe('text measurement', () => {
+heavy('text measurement', () => {
test('derived text layout preserves imported auto-layout text bounds during measurement', () => {
const graph = new SceneGraph()
const page = pageId(graph)
diff --git a/tests/engine/render/canvas/cache.test.ts b/tests/engine/render/canvas/cache.test.ts
index 4200fa305..fdc30b311 100644
--- a/tests/engine/render/canvas/cache.test.ts
+++ b/tests/engine/render/canvas/cache.test.ts
@@ -1,4 +1,4 @@
-import { beforeAll, describe, expect, setDefaultTimeout, test } from 'bun:test'
+import { beforeAll, expect, setDefaultTimeout, test } from 'bun:test'
import { readFileSync } from 'node:fs'
import {
@@ -15,7 +15,7 @@ import { initCanvasKit } from '#cli/headless'
import { expectDefined } from '#tests/helpers/assert'
import { repoPath } from '#tests/helpers/paths'
-import { HEAVY_TEST_TIMEOUT_MS } from '#tests/helpers/test-utils'
+import { heavy, HEAVY_TEST_TIMEOUT_MS } from '#tests/helpers/test-utils'
import { expectRgbaPixels } from './helpers'
@@ -103,7 +103,7 @@ function maskYCenter(
return (minY + maxY) / 2
}
-describe('render cache regressions', () => {
+heavy('render cache regressions', () => {
test('badge label is vertically centered in the pill', async () => {
const surface = expectDefined(ck.MakeSurface(120, 60), 'badge surface')
const renderer = new SkiaRenderer(ck, surface)
diff --git a/tests/helpers/test-utils.ts b/tests/helpers/test-utils.ts
index 5c1e57754..ce5d62813 100644
--- a/tests/helpers/test-utils.ts
+++ b/tests/helpers/test-utils.ts
@@ -1,11 +1,11 @@
import { describe } from 'bun:test'
-// Tests that don't run are not useful, but it may be desirable to run only a short subset of tests.
-// Set BUN_HEAVY_TESTS to false to skip tests marked as heavy, and set it to true to run them.
-// By default, all tests are run.
-export const runsHeavyTests = process.env.BUN_HEAVY_TESTS
- ? ['1', 't', 'true'].includes(process.env.BUN_HEAVY_TESTS.trim().toLowerCase())
- : true
+// Heavy tests parse the large fixtures, gigabytes each, and run only when BUN_HEAVY_TESTS is
+// true, which the unit test runner sets while giving each heavy file its own process. A bare
+// `bun test` over a directory skips them, so it cannot hold several such graphs in one process.
+export const runsHeavyTests = ['1', 't', 'true'].includes(
+ (process.env.BUN_HEAVY_TESTS ?? '').trim().toLowerCase()
+)
export const heavy = describe.if(runsHeavyTests)