openpencil/tests/engine/io/fig/export/parse-failures.test.ts

69 lines
2.3 KiB
TypeScript
Raw Normal View History

fix(export): prevent GUID collisions and file corruption on .fig round-trip (#333) * fix(export): prevent GUID collisions and file corruption on .fig round-trip Nodes sharing the same imported source.id (component instance children, cloned subtrees) silently overwrote each other on export because the GUID assignment reused imported GUID values without checking for duplicates. This caused data loss on reimport — only the last node with a given GUID survived. - Track all assigned GUID values in a Set for O(1) collision detection. - Scan imported source.ids for both sessionID 0 and 1 before assigning any new GUIDs, so the counter starts past every imported value. - Fall back to counter-based GUIDs when source.id collides with an already-assigned value. Additional fixes in the same change set: - cloneTree now deep-copies source.fig via structuredClone, preventing mutations on a clone from corrupting the original node's kiwi payload. - Removed decompressFigKiwiData sync wrapper (zero callers) and the silent try/catch fallback in parseFigKiwiContainer that masked corrupt data as raw bytes. - buildFigKiwi uses Bun.zstdCompressSync when available, matching the zstd decompression path already used on import. - Fixed setSavedVersion ordering in read.ts — must run after requestRender to capture the post-bump version, preventing spurious dirty-state immediately after file reload. Tests: GUID collision (2 and 3 node), clone isolation, parse failure, text export zstd compatibility, gold-preview round-trip. * fix(export): handle EXCLUDE boolean operation and BOOLEAN_OPERATION node type The internal representation uses EXCLUDE for exclude boolean operations, but Figma's kiwi schema uses XOR. Map EXCLUDE back to XOR on export so round-trips through .fig files don't fail. Also add BOOLEAN_OPERATION to VALID_NODE_TYPES and increase timeout for heavy material3 fixture test. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * style: format export-node.ts Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * test: add type guard after null assertion in guid-collision test Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clipboard): detect zstd-compressed data before zlib inflate fflate's inflateSync silently accepts zstd-compressed data and returns garbage instead of throwing. Check for the zstd magic bytes (28 b5 2f fd) before attempting zlib decompression. Also revert the EXCLUDE enum addition to the kiwi schema since the export-node.ts mapping is sufficient. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clipboard): add length guard before zstd magic byte check Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * test(scene-graph): group clone regression coverage * ci: retrigger CI checks * test: increase timeouts for heavy .fig fixture tests on slow CI runners Gold-preview.fig and material3.fig parsing/export tests consistently exceed the 5s bun:test default timeout on GitHub Actions runners. Increase to 30s for: beforeAll codec init, clipboard roundtrip, glyph blob roundtrip, group reclassification, and text measurement. * test: add individual test timeouts for heavy .fig fixture tests The beforeAll timeout helped but individual test() calls also need explicit 30s timeouts since bun:test applies the 5s default per-test. Fixes remaining CI flakes in glyph-blob roundtrip and clipboard roundtrip tests. * test: increase beforeAll timeout for render cache test The canvas/render cache test loads gold-preview.fig AND initializes CanvasKit (Skia WASM), which is much slower than the other fixture tests. Use 60s timeout to account for slow CI runners. * fix(export): reserve document GUID to prevent 0:0 namespace collision - Add docGuid (0:0) to assignedGuidValues before processing imported node source.ids, preventing an imported node with source.id "0:0" from reusing the document's GUID slot - Add regression test using session-0 source.ids to verify nodes survive roundtrip without document GUID collision - Remove unnecessary async keyword from synchronous component metadata test * fix(export): guard canvas GUID reuse with assignedGuidValues check - Mirror getOrCreateNodeGuid() collision logic in buildCanvasEntries(): if an imported page's source.id maps to a GUID already in assignedGuidValues, generate a fresh counter-based GUID instead - Prevents canvas-level last-write-wins when multiple pages share the same source.id or a page uses 0:0 * fix(test): use explicit little-endian writes and fix misleading test title - Replace host-endian Uint32Array writes with DataView.setUint32(offset, value, true) in parse-failures.test.ts to ensure platform-independent fig-kiwi container assembly - Rename test title from "clone clears source.id from the original" to "clone clears source.id from the clone" to accurately reflect what the assertions verify * test(io): use file-level timeout for heavy fixture --------- Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com> Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-06-23 15:05:23 +00:00
import { describe, expect, test } from 'bun:test'
import { parseFigKiwiContainer } from '@open-pencil/kiwi/fig/parse'
fix(export): prevent GUID collisions and file corruption on .fig round-trip (#333) * fix(export): prevent GUID collisions and file corruption on .fig round-trip Nodes sharing the same imported source.id (component instance children, cloned subtrees) silently overwrote each other on export because the GUID assignment reused imported GUID values without checking for duplicates. This caused data loss on reimport — only the last node with a given GUID survived. - Track all assigned GUID values in a Set for O(1) collision detection. - Scan imported source.ids for both sessionID 0 and 1 before assigning any new GUIDs, so the counter starts past every imported value. - Fall back to counter-based GUIDs when source.id collides with an already-assigned value. Additional fixes in the same change set: - cloneTree now deep-copies source.fig via structuredClone, preventing mutations on a clone from corrupting the original node's kiwi payload. - Removed decompressFigKiwiData sync wrapper (zero callers) and the silent try/catch fallback in parseFigKiwiContainer that masked corrupt data as raw bytes. - buildFigKiwi uses Bun.zstdCompressSync when available, matching the zstd decompression path already used on import. - Fixed setSavedVersion ordering in read.ts — must run after requestRender to capture the post-bump version, preventing spurious dirty-state immediately after file reload. Tests: GUID collision (2 and 3 node), clone isolation, parse failure, text export zstd compatibility, gold-preview round-trip. * fix(export): handle EXCLUDE boolean operation and BOOLEAN_OPERATION node type The internal representation uses EXCLUDE for exclude boolean operations, but Figma's kiwi schema uses XOR. Map EXCLUDE back to XOR on export so round-trips through .fig files don't fail. Also add BOOLEAN_OPERATION to VALID_NODE_TYPES and increase timeout for heavy material3 fixture test. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * style: format export-node.ts Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * test: add type guard after null assertion in guid-collision test Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clipboard): detect zstd-compressed data before zlib inflate fflate's inflateSync silently accepts zstd-compressed data and returns garbage instead of throwing. Check for the zstd magic bytes (28 b5 2f fd) before attempting zlib decompression. Also revert the EXCLUDE enum addition to the kiwi schema since the export-node.ts mapping is sufficient. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clipboard): add length guard before zstd magic byte check Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * test(scene-graph): group clone regression coverage * ci: retrigger CI checks * test: increase timeouts for heavy .fig fixture tests on slow CI runners Gold-preview.fig and material3.fig parsing/export tests consistently exceed the 5s bun:test default timeout on GitHub Actions runners. Increase to 30s for: beforeAll codec init, clipboard roundtrip, glyph blob roundtrip, group reclassification, and text measurement. * test: add individual test timeouts for heavy .fig fixture tests The beforeAll timeout helped but individual test() calls also need explicit 30s timeouts since bun:test applies the 5s default per-test. Fixes remaining CI flakes in glyph-blob roundtrip and clipboard roundtrip tests. * test: increase beforeAll timeout for render cache test The canvas/render cache test loads gold-preview.fig AND initializes CanvasKit (Skia WASM), which is much slower than the other fixture tests. Use 60s timeout to account for slow CI runners. * fix(export): reserve document GUID to prevent 0:0 namespace collision - Add docGuid (0:0) to assignedGuidValues before processing imported node source.ids, preventing an imported node with source.id "0:0" from reusing the document's GUID slot - Add regression test using session-0 source.ids to verify nodes survive roundtrip without document GUID collision - Remove unnecessary async keyword from synchronous component metadata test * fix(export): guard canvas GUID reuse with assignedGuidValues check - Mirror getOrCreateNodeGuid() collision logic in buildCanvasEntries(): if an imported page's source.id maps to a GUID already in assignedGuidValues, generate a fresh counter-based GUID instead - Prevents canvas-level last-write-wins when multiple pages share the same source.id or a page uses 0:0 * fix(test): use explicit little-endian writes and fix misleading test title - Replace host-endian Uint32Array writes with DataView.setUint32(offset, value, true) in parse-failures.test.ts to ensure platform-independent fig-kiwi container assembly - Rename test title from "clone clears source.id from the original" to "clone clears source.id from the clone" to accurately reflect what the assertions verify * test(io): use file-level timeout for heavy fixture --------- Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com> Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-06-23 15:05:23 +00:00
/**
* Build a minimal fig-kiwi container with a valid header + schema chunk
* but a corrupt (non-compressible) data chunk that will cause inflateSync
* to throw. This verifies that the decompressor does NOT silently fall
* back to raw compressed bytes.
*/
function buildCorruptFigKiwi(): Uint8Array {
const schemaDeflated = new Uint8Array([0x78, 0x01, 0x01, 0x00, 0x00]) // minimal deflate
// Data chunk: random bytes that are neither valid zlib nor valid zstd
const dataCorrupt = new Uint8Array(32)
for (let i = 0; i < dataCorrupt.length; i++) dataCorrupt[i] = (i * 37) & 0xff
const header = new TextEncoder().encode('fig-kiwi')
const total = 8 + 4 + 4 + schemaDeflated.length + 4 + dataCorrupt.length
const out = new Uint8Array(total)
const view = new DataView(out.buffer, out.byteOffset, out.byteLength)
let offset = 0
out.set(header, offset)
offset += 8
view.setUint32(offset, 101, true)
offset += 4
view.setUint32(offset, schemaDeflated.length, true)
offset += 4
out.set(schemaDeflated, offset)
offset += schemaDeflated.length
view.setUint32(offset, dataCorrupt.length, true)
offset += 4
out.set(dataCorrupt, offset)
return out
}
describe('parseFigKiwiContainer: decompression failures', () => {
test('throws on corrupt data chunk (not raw bytes)', () => {
const buf = buildCorruptFigKiwi()
expect(() => parseFigKiwiContainer(buf)).toThrow()
})
test('returns null for missing header', () => {
const buf = new Uint8Array([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07])
expect(parseFigKiwiContainer(buf)).toBeNull()
})
test('returns null for fewer than 2 chunks', () => {
const header = new TextEncoder().encode('fig-kiwi')
const schemaDeflated = new Uint8Array([0x78, 0x01])
// No data chunk — only one chunk total
const total = 8 + 4 + 4 + schemaDeflated.length
const out = new Uint8Array(total)
const view = new DataView(out.buffer, out.byteOffset, out.byteLength)
let offset = 0
out.set(header, offset)
offset += 8
view.setUint32(offset, 101, true)
offset += 4
view.setUint32(offset, schemaDeflated.length, true)
offset += 4
out.set(schemaDeflated, offset)
expect(parseFigKiwiContainer(out)).toBeNull()
})
})