import { DOMParser } from '@xmldom/xmldom' import { createHash } from 'node:crypto' import { readFile } from 'node:fs/promises' import { join } from 'node:path' import { EQUINE_SOURCE_PATHS, assetIdFromSha256, cleanedAsset, parseViewBox, stripLegacyAnnotations, } from '../src' import { REPO_ROOT } from './helpers' let source: string let cleaned: string function count(text: string, pattern: RegExp): number { return [...text.matchAll(pattern)].length } beforeAll(async () => { source = await readFile(join(REPO_ROOT, EQUINE_SOURCE_PATHS.mainSvg), 'utf8') cleaned = stripLegacyAnnotations(source) }) describe('stripLegacyAnnotations on the real Horse.svg', () => { it('removes exactly the elements carrying data-anno-id', () => { const annotated = count(source, /<[a-z]+\b[^>]*\sdata-anno-id="/g) const elements = (text: string) => count(text, /<[a-zA-Z]+[\s/>]/g) expect(annotated).toBe(30) // 12 points × (hitbox + marker) + 6 polygons // each annotated element carries one child, removed with it const titles = count(source, /data-anno-id="[^"]*"[^>]*><title>/g) expect(elements(source) - elements(cleaned)).toBe(annotated + titles) }) it('keeps the 270 drawing paths and every non-annotation byte', () => { expect(count(source, /<path\b/g)).toBe(270) expect(count(cleaned, /<path\b/g)).toBe(270) expect(cleaned).not.toContain('data-anno-') expect(cleaned.startsWith('<?xml version="1.0" encoding="UTF-8"?>')).toBe( true, ) expect(cleaned).not.toContain('max-width: 100%') }) it('is deterministic and parses as XML', () => { expect(stripLegacyAnnotations(source)).toBe(cleaned) const errors: string[] = [] const doc = new DOMParser({ onError: (level, message) => { if (level !== 'warning') errors.push(message) }, }).parseFromString(cleaned, 'image/svg+xml') expect(errors).toEqual([]) expect(doc.documentElement?.tagName).toBe('svg') }) it('describes the cleaned bytes with their sha256', () => { const bytes = new TextEncoder().encode(cleaned) const asset = cleanedAsset(bytes) const sha256 = createHash('sha256').update(bytes).digest('hex') expect(asset).toEqual({ file: 'horse.svg', sha256, byte_size: bytes.byteLength, svg_asset_id: assetIdFromSha256(sha256), }) }) it('reads a viewBox into a document view_box', () => { expect(parseViewBox('60 100 500 380')).toEqual({ min_x: 60, min_y: 100, width: 500, height: 380, }) expect(() => parseViewBox('1 2 3')).toThrow('invalid viewBox') }) })