AI-native design editor. Open-source Figma alternative.
feat(drawio): read and write draw.io files (#1445)
Danila Poyarkov3f97edb5224c
diff --git a/AGENTS.md b/AGENTS.mdindex 8953d5b35..2f18406e0 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -10,6 +10,7 @@ This file holds the repository map and the rules that apply everywhere. Rules fo| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- || `packages/scene-graph` | Framework-neutral graph, node types, geometry, copy/snap/undo, variables, instances, hit testing, plus the shared primitives formats need: color conversion and management, CSS value parsing, text/layout direction | `packages/scene-graph/AGENTS.md` || `packages/pen` | Pencil.dev `.pen` model, parser, SceneGraph adapter | — |+| `packages/drawio` | draw.io model, reader and writer for `.drawio`/`.dio` files and the diagrams draw.io PNG and SVG exports embed; no SceneGraph | — || `packages/kiwi` | SceneGraph-independent Kiwi schema/runtime, codecs, containers, parse helpers | `packages/fig/AGENTS.md` || `packages/fig` | `.fig` archives, SceneGraph conversion, metadata policy, component/instance interpretation, Figma clipboard | `packages/fig/AGENTS.md` || `packages/core` | Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, document I/O; depends on scene-graph and the format packages (pen, kiwi, fig, dom-css, design-jsx); no browser DOM | `packages/core/AGENTS.md` |diff --git a/bun.lock b/bun.lockindex 439ad752c..64d8521b0 100644--- a/bun.lock+++ b/bun.lock@@ -407,6 +407,20 @@"@open-pencil/scene-graph": "workspace:*",},},+ "packages/drawio": {+ "name": "@open-pencil/drawio",+ "version": "0.16.0",+ "dependencies": {+ "@xmldom/xmldom": "^0.9.12",+ "fflate": "^0.8.3",+ "js-base64": "^3.9.3",+ },+ "devDependencies": {+ "@types/bun": "^1.3.14",+ "tsdown": "^0.22.14",+ "typescript": "~5.8.3",+ },+ },"packages/emit": {"name": "@open-pencil/emit","version": "0.16.0",@@ -1618,6 +1632,8 @@"@open-pencil/dom-css": ["@open-pencil/dom-css@workspace:packages/dom-css"],+ "@open-pencil/drawio": ["@open-pencil/drawio@workspace:packages/drawio"],+"@open-pencil/emit": ["@open-pencil/emit@workspace:packages/emit"],"@open-pencil/emoji-metrics-tools": ["@open-pencil/emoji-metrics-tools@workspace:tools/generate/emoji-metrics"],diff --git a/package.json b/package.jsonindex 00cc49ce8..dbbd481d9 100644--- a/package.json+++ b/package.json@@ -6,6 +6,7 @@"workspaces": ["packages/scene-graph","packages/pen",+ "packages/drawio","packages/kiwi","packages/fig","packages/core",@@ -63,9 +64,9 @@"build:native-test": "bun run generate:icons --target desktop && bun run build:packages && bun tauri build --debug --no-bundle --features native-test --config desktop/tauri.native-test.conf.json","benchmark:navigation": "bun tools/dev/navigation-benchmark/src/cli.ts run","test:native": "bun run build:native-test && wdio run wdio.conf.ts",- "lint": "bun run lint:structure && oxlint -c oxlint.json --type-aware --type-check src/ packages/scene-graph/src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/feedback/src/ packages/cloud/src/ packages/dom-css/src/ packages/pen/src/ packages/design-jsx/src/ packages/emit/src/ packages/kiwi/src/ packages/fig/src/ packages/docs/.vitepress/theme/landing/",- "lint:structure": "oxlint -c oxlint.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/scene-graph/scripts/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/dom-css/src/ packages/dom-css/tests/ packages/dom-css/scripts/ packages/pen/src/ packages/pen/tests/ packages/pen/scripts/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/design-jsx/scripts/ packages/emit/src/ packages/emit/tests/ packages/emit/scripts/ packages/kiwi/src/ packages/kiwi/tests/ packages/kiwi/scripts/ packages/fig/src/ packages/fig/tests/ packages/fig/scripts/ packages/core/tests/ packages/cli/tests/ packages/scene-graph/tests/ packages/vue/tests/ tests/ scripts/ tools/ packages/docs/.vitepress/theme/landing/",- "format": "oxfmt --write .oxfmtrc.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/scene-graph/scripts/ packages/core/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/cloud/tsdown.config.ts packages/cloud/tsdown.standalone.config.ts packages/vue/src/ packages/dom-css/src/ packages/dom-css/tests/ packages/dom-css/scripts/ packages/pen/src/ packages/pen/tests/ packages/pen/scripts/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/design-jsx/scripts/ packages/emit/src/ packages/emit/tests/ packages/emit/scripts/ packages/kiwi/src/ packages/kiwi/tests/ packages/kiwi/scripts/ packages/fig/src/ packages/fig/tests/ packages/fig/scripts/ tests scripts/ tools/ packages/docs/.vitepress/theme/landing/",+ "lint": "bun run lint:structure && oxlint -c oxlint.json --type-aware --type-check src/ packages/scene-graph/src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/feedback/src/ packages/cloud/src/ packages/dom-css/src/ packages/pen/src/ packages/design-jsx/src/ packages/emit/src/ packages/kiwi/src/ packages/fig/src/ packages/drawio/src/ packages/docs/.vitepress/theme/landing/",+ "lint:structure": "oxlint -c oxlint.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/dom-css/src/ packages/dom-css/tests/ packages/pen/src/ packages/pen/tests/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/emit/src/ packages/emit/tests/ packages/kiwi/src/ packages/kiwi/tests/ packages/fig/src/ packages/fig/tests/ packages/drawio/src/ packages/drawio/tests/ packages/core/tests/ packages/cli/tests/ packages/scene-graph/tests/ packages/vue/tests/ tests/ scripts/ tools/ packages/docs/.vitepress/theme/landing/",+ "format": "oxfmt --write .oxfmtrc.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/core/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/cloud/tsdown.config.ts packages/cloud/tsdown.standalone.config.ts packages/vue/src/ packages/dom-css/src/ packages/dom-css/tests/ packages/pen/src/ packages/pen/tests/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/emit/src/ packages/emit/tests/ packages/kiwi/src/ packages/kiwi/tests/ packages/fig/src/ packages/fig/tests/ packages/drawio/src/ packages/drawio/tests/ tests scripts/ tools/ packages/docs/.vitepress/theme/landing/","format:check": "bun run format && status=$(git status --porcelain -uall) && test -z \"$status\" || (echo \"$status\" && exit 1)","check": "bun run check:icons && bun run build:packages && bun run lint && tsgo --noEmit && bun run check:vue && bun run check:native-test && bun run check:i18n && bun run check:docs && bun run check:changelog && bun run check:packages && bun run check:deps && bun run check:audit && bun run check:secrets && bun run check:monorepo && bun run check:arch && bun run check:test-homes && bun run check:cloud-off && bun run check:test-types && bun run test:type-shapes && bun run check:tools && bun run test:tools && bun run test:dupes","check:commits": "commitlint",diff --git a/packages/design-jsx/package.json b/packages/design-jsx/package.jsonindex dc0a1423a..41bff60e1 100644--- a/packages/design-jsx/package.json+++ b/packages/design-jsx/package.json@@ -40,9 +40,8 @@],"scripts": {"build": "bunx tsdown --config tsdown.config.ts",- "check": "bun run typecheck && bun run build && bun run smoke:dist",+ "check": "bun run typecheck && bun run build","prepack": "bun run build",- "smoke:dist": "bun scripts/smoke-dist.ts","typecheck": "bunx tsc --noEmit -p tsconfig.json"},"repository": {diff --git a/packages/design-jsx/scripts/smoke-dist.ts b/packages/design-jsx/scripts/smoke-dist.tsdeleted file mode 100644index 1412168db..000000000--- a/packages/design-jsx/scripts/smoke-dist.ts+++ /dev/null@@ -1,8 +0,0 @@-export {}--const mod = await import('../dist/index.js')--const tree = mod.Frame({ name: 'Card', w: 100, h: 50 })-if (!mod.isTreeNode(tree) || !mod.JSX_REFERENCE.includes('Frame')) {- throw new Error('Expected built Design JSX package to build trees and ship its reference')-}diff --git a/packages/dom-css/README.md b/packages/dom-css/README.mdindex 6f33279c8..4969e372a 100644--- a/packages/dom-css/README.md+++ b/packages/dom-css/README.md@@ -26,10 +26,9 @@ bun run checkPackage scripts:- `bun run test` — package-local Bun tests for runtime, conversion, and Tailwind APIs-- `bun run typecheck` — type-checks `src`, tests, and package scripts+- `bun run typecheck` — type-checks `src` and tests- `bun run build` — builds the distributable `dist` entrypoint-- `bun run smoke:dist` — imports the built `dist` bundle and exercises the public API-- `bun run check` — runs typecheck, tests, build, and dist smoke in sequence+- `bun run check` — runs typecheck, tests, and build in sequenceThe repository also keeps integration/oracle coverage under `tests/engine/dom-css` and `tests/e2e/dom-css`. The package-local suite focuses on the library's public API, while the repo-level E2E suite verifies browser `getComputedStyle()` parity through Playwright.diff --git a/packages/dom-css/package.json b/packages/dom-css/package.jsonindex c411607f3..8ec41cafd 100644--- a/packages/dom-css/package.json+++ b/packages/dom-css/package.json@@ -59,9 +59,8 @@],"scripts": {"build": "bunx tsdown --config tsdown.config.ts",- "check": "bun run typecheck && bun run test && bun run build && bun run smoke:dist",+ "check": "bun run typecheck && bun run test && bun run build","prepack": "bun run build",- "smoke:dist": "bun scripts/smoke-dist.ts","test": "bun test tests","typecheck": "bunx tsc --noEmit -p tsconfig.test.json"},diff --git a/packages/dom-css/scripts/smoke-dist.ts b/packages/dom-css/scripts/smoke-dist.tsdeleted file mode 100644index 0c92f576b..000000000--- a/packages/dom-css/scripts/smoke-dist.ts+++ /dev/null@@ -1,74 +0,0 @@-import type * as DomCSS from '../src/index'--const distPath = '../dist/index.js'-const browserDistPath = '../dist/browser.js'-const dist = await import(distPath)-const browserDist = await import(browserDistPath)--const browserHTMLToSceneGraph: typeof DomCSS.browserHTMLToSceneGraph = dist.browserHTMLToSceneGraph-const browserTailwindJSXToDesignDocument: typeof DomCSS.browserTailwindJSXToDesignDocument =- dist.browserTailwindJSXToDesignDocument-const compileTailwindCSS: typeof DomCSS.compileTailwindCSS = dist.compileTailwindCSS-const createHeadlessCSSRuntime: typeof DomCSS.createHeadlessCSSRuntime =- dist.createHeadlessCSSRuntime-const htmlToSceneGraph: typeof DomCSS.htmlToSceneGraph = dist.htmlToSceneGraph-const jsx: typeof DomCSS.jsx = dist.jsx-const jsxToDesignDocument: typeof DomCSS.jsxToDesignDocument = dist.jsxToDesignDocument-const serializeHTML: typeof DomCSS.serializeHTML = dist.serializeHTML--type DesignDocument = DomCSS.DesignDocument--const document: DesignDocument = {- type: 'document',- children: [- {- type: 'element',- tagName: 'article',- attrs: { class: 'card' },- children: [{ type: 'text', text: 'OpenPencil' }]- }- ]-}--const html = serializeHTML(document)-if (!html.includes('OpenPencil')) {- throw new Error('Expected built serializeHTML() to emit document text')-}--const css = await compileTailwindCSS(['flex', 'w-80'])-if (!css.includes('.w-80')) {- throw new Error('Expected built compileTailwindCSS() to emit Tailwind utility CSS')-}--const graph = await htmlToSceneGraph('<article class="card">OpenPencil</article>', {- cssText: '.card { display: flex; width: 320px; }',- runtime: createHeadlessCSSRuntime()-})-const page = graph.getPages()[0]-const card = page ? graph.getChildren(page.id)[0] : undefined-if (card?.type !== 'FRAME' || card.width !== 320) {- throw new Error('Expected built htmlToSceneGraph() to produce a sized frame')-}--const jsxDocument = await jsxToDesignDocument(- jsx('article', { class: 'card', children: 'OpenPencil' })-)-if (jsxDocument.children[0]?.type !== 'element') {- throw new Error('Expected built JSX helpers to produce DesignDOM elements')-}--if (typeof browserHTMLToSceneGraph !== 'function') {- throw new TypeError('Expected built browser HTML helper to be exported')-}--if (typeof browserTailwindJSXToDesignDocument !== 'function') {- throw new TypeError('Expected built browser JSX helper to be exported')-}--if (typeof browserDist.browserHTMLToSceneGraph !== 'function') {- throw new TypeError('Expected built browser subpath HTML helper to be exported')-}--if (typeof browserDist.browserTailwindJSXToDesignDocument !== 'function') {- throw new TypeError('Expected built browser subpath helper to be exported')-}diff --git a/packages/dom-css/tsconfig.test.json b/packages/dom-css/tsconfig.test.jsonindex 9cd84bf82..0d4d11fa7 100644--- a/packages/dom-css/tsconfig.test.json+++ b/packages/dom-css/tsconfig.test.json@@ -8,8 +8,7 @@"src/**/*.tsx","src/**/*.d.ts","tests/**/*.ts",- "tests/**/*.tsx",- "scripts/**/*.ts"+ "tests/**/*.tsx"],"exclude": ["node_modules", "dist"]}diff --git a/packages/drawio/README.md b/packages/drawio/README.mdnew file mode 100644index 000000000..1025dbf0a--- /dev/null+++ b/packages/drawio/README.md@@ -0,0 +1,5 @@+# @open-pencil/drawio++The draw.io (diagrams.net) file format: its document model, and a reader and writer for `.drawio` and `.dio` files and the diagrams draw.io embeds in its PNG and SVG exports.++The reader takes plain and compressed pages, keeps cells in draw.io's drawing order with their layers, styles, geometry and `UserObject` attributes, and unpacks everything a file holds within one size limit. The writer saves pages uncompressed, as draw.io does by default. Neither depends on `@open-pencil/scene-graph`; converting diagrams to and from design layers happens in `@open-pencil/core`.diff --git a/packages/drawio/package.json b/packages/drawio/package.jsonnew file mode 100644index 000000000..2f43c91f7--- /dev/null+++ b/packages/drawio/package.json@@ -0,0 +1,47 @@+{+ "name": "@open-pencil/drawio",+ "version": "0.16.0",+ "license": "MIT",+ "type": "module",+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "bun": "./src/index.ts",+ "import": "./dist/index.js",+ "default": "./dist/index.js"+ }+ },+ "main": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "sideEffects": false,+ "files": [+ "dist",+ "src",+ "README.md"+ ],+ "scripts": {+ "build": "bunx tsdown --config tsdown.config.ts",+ "check": "bun run typecheck && bun run build",+ "prepack": "bun run build",+ "typecheck": "bunx tsc --noEmit -p tsconfig.json"+ },+ "repository": {+ "type": "git",+ "url": "git+https://github.com/open-pencil/open-pencil.git",+ "directory": "packages/drawio"+ },+ "publishConfig": {+ "access": "public",+ "provenance": true+ },+ "dependencies": {+ "@xmldom/xmldom": "^0.9.12",+ "fflate": "^0.8.3",+ "js-base64": "^3.9.3"+ },+ "devDependencies": {+ "@types/bun": "^1.3.14",+ "tsdown": "^0.22.14",+ "typescript": "~5.8.3"+ }+}diff --git a/packages/drawio/src/embedded.ts b/packages/drawio/src/embedded.tsnew file mode 100644index 000000000..79da1e266--- /dev/null+++ b/packages/drawio/src/embedded.ts@@ -0,0 +1,92 @@+import type { Element } from '@xmldom/xmldom'++import { boundedInflate, percentDecoded, type InflateBudget } from './inflate'+import { parseXML } from './xml'++const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]+/** The keyword draw.io stores its diagram under in a PNG's text chunks. */+const DRAWIO_KEYWORD = 'mxfile'++const latin1 = new TextDecoder('latin1')+const utf8 = new TextDecoder()++function isPNG(bytes: Uint8Array): boolean {+ return PNG_SIGNATURE.every((byte, index) => bytes[index] === byte)+}++/** Where a NUL byte ends the field that starts at `from`, or -1. */+function fieldEnd(data: Uint8Array, from: number): number {+ return data.indexOf(0, from)+}++/**+ * The diagram a text chunk holds when its keyword is draw.io's: `tEXt` as Latin-1, `zTXt`+ * zlib-compressed, `iTXt` as UTF-8, compressed or not. draw.io percent-encodes the XML in all three.+ */+function chunkDiagram(type: string, data: Uint8Array, budget: InflateBudget): string | null {+ const keywordEnd = fieldEnd(data, 0)+ if (keywordEnd === -1 || latin1.decode(data.subarray(0, keywordEnd)) !== DRAWIO_KEYWORD)+ return null+ if (type === 'tEXt') return percentDecoded(latin1.decode(data.subarray(keywordEnd + 1)))+ if (type === 'zTXt') {+ // The compression method byte, then a zlib stream: a 2-byte header before raw deflate.+ const inflated = boundedInflate(data.subarray(keywordEnd + 4), budget)+ return percentDecoded(latin1.decode(inflated))+ }+ // iTXt: compressed flag and method, then language and translated keyword, each NUL-ended.+ const compressed = data[keywordEnd + 1] === 1+ const languageEnd = fieldEnd(data, keywordEnd + 3)+ const translatedEnd = languageEnd === -1 ? -1 : fieldEnd(data, languageEnd + 1)+ if (translatedEnd === -1) return null+ const text = data.subarray(translatedEnd + 1)+ return percentDecoded(utf8.decode(compressed ? boundedInflate(text.subarray(2), budget) : text))+}++/**+ * The draw.io diagram a PNG export carries, or null when it carries none. A compressed chunk that+ * is damaged or too large to unpack is an error that says so.+ */+function diagramInPNG(bytes: Uint8Array, budget: InflateBudget): string | null {+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)+ let offset = PNG_SIGNATURE.length+ while (offset + 8 <= bytes.length) {+ const length = view.getUint32(offset)+ const type = latin1.decode(bytes.subarray(offset + 4, offset + 8))+ const start = offset + 8+ if (type === 'IEND') return null+ if (start + length > bytes.length) {+ throw new Error('Could not read the draw.io diagram in this image: it is cut short')+ }+ if (type === 'tEXt' || type === 'zTXt' || type === 'iTXt') {+ let diagram: string | null+ try {+ diagram = chunkDiagram(type, bytes.subarray(start, start + length), budget)+ } catch (error) {+ throw new Error('Could not read the draw.io diagram in this image', { cause: error })+ }+ if (diagram) return diagram+ }+ // The chunk's data, then its 4-byte CRC.+ offset = start + length + 4+ }+ return null+}++/**+ * The root element of the draw.io XML a file holds: the file itself for `.drawio` and `.dio`, or+ * the diagram a PNG export embeds in a text chunk or an SVG export in its root's `content`. Null+ * when the file is not XML or an export embeds no diagram.+ */+export function drawioRoot(bytes: Uint8Array, budget: InflateBudget): Element | null {+ const source = isPNG(bytes) ? diagramInPNG(bytes, budget) : utf8.decode(bytes)+ const root = source === null ? null : parseXML(source)+ if (root?.localName !== 'svg') return root+ const content = root.getAttribute('content')+ return content ? parseXML(content) : null+}++/** Whether a file name is draw.io's for an editable export, such as `flow.drawio.png`. */+export function isDrawioExportFileName(fileName: string): boolean {+ const name = fileName.toLowerCase()+ return name.endsWith('.drawio.png') || name.endsWith('.drawio.svg')+}diff --git a/packages/drawio/src/index.ts b/packages/drawio/src/index.tsnew file mode 100644index 000000000..9d95de536--- /dev/null+++ b/packages/drawio/src/index.ts@@ -0,0 +1,30 @@+import { drawioRoot } from './embedded'+import { inflateBudget } from './inflate'+import type { DrawioFile } from './model'+import { readDrawioRoot } from './read'++export { isDrawioExportFileName } from './embedded'+export { MAX_INFLATED_BYTES } from './inflate'+export type {+ DrawioCell,+ DrawioFile,+ DrawioGeometry,+ DrawioLayer,+ DrawioPage,+ DrawioPoint,+ DrawioStyle+} from './model'+export { parseDrawioFile } from './read'+export { formatStyle, parseStyle, styleFlag, styleNumber } from './style'+export { writeDrawioFile } from './write'++/**+ * The draw.io file in `bytes`: a `.drawio` or `.dio` file, or the diagram a draw.io PNG or SVG+ * export embeds. Null when the bytes hold no draw.io diagram. Everything the file unpacks, its+ * compressed pages and image chunks together, shares one size limit.+ */+export function readDrawioBytes(bytes: Uint8Array): DrawioFile | null {+ const budget = inflateBudget()+ const root = drawioRoot(bytes, budget)+ return root ? readDrawioRoot(root, budget) : null+}diff --git a/packages/drawio/src/inflate.ts b/packages/drawio/src/inflate.tsnew file mode 100644index 000000000..25a8c13b3--- /dev/null+++ b/packages/drawio/src/inflate.ts@@ -0,0 +1,65 @@+import { Inflate } from 'fflate'++/**+ * The most a file's compressed parts may unpack to, all together, so a small crafted file with+ * many diagrams or image chunks cannot exhaust memory.+ */+export const MAX_INFLATED_BYTES = 32 * 1024 * 1024+/** Input fed per step; deflate expands at most about 1032 times, so each step stays small. */+const STEP_BYTES = 4096++/** What is left of a file's unpacking allowance, shared by every part it unpacks. */+export interface InflateBudget {+ remaining: number+}++export function inflateBudget(bytes = MAX_INFLATED_BYTES): InflateBudget {+ return { remaining: bytes }+}++/** Raw deflate, charged to `budget`; throws once the file would unpack to more than it allows. */+export function boundedInflate(data: Uint8Array, budget: InflateBudget): Uint8Array {+ const chunks: Uint8Array[] = []+ let size = 0+ const inflater = new Inflate((chunk) => {+ size += chunk.length+ budget.remaining -= chunk.length+ if (budget.remaining < 0) throw new RangeError('The draw.io file unpacks to too much data')+ chunks.push(chunk)+ })+ for (let start = 0; start < data.length; start += STEP_BYTES) {+ const end = start + STEP_BYTES+ inflater.push(data.subarray(start, end), end >= data.length)+ }+ const output = new Uint8Array(size)+ let offset = 0+ for (const chunk of chunks) {+ output.set(chunk, offset)+ offset += chunk.length+ }+ return output+}++/** A `%` that does not start an escape, as in "50% done". */+const STRAY_PERCENT = /%(?![0-9A-Fa-f]{2})/g+/** A run of escapes, decoded together so a character spread over several bytes stays whole. */+const ESCAPE_RUN = /(?:%[0-9A-Fa-f]{2})+/g++/**+ * The text with its percent escapes decoded. A stray `%` is kept as it is, and an escape run that+ * is not valid UTF-8 stays encoded, so neither stops the rest of the text from decoding.+ */+export function percentDecoded(text: string): string {+ const escaped = text.replace(STRAY_PERCENT, '%25')+ try {+ return decodeURIComponent(escaped)+ } catch {+ return escaped.replace(ESCAPE_RUN, (run) => {+ try {+ return decodeURIComponent(run)+ } catch {+ return run+ }+ })+ }+}diff --git a/packages/drawio/src/model.ts b/packages/drawio/src/model.tsnew file mode 100644index 000000000..6738c8a3e--- /dev/null+++ b/packages/drawio/src/model.ts@@ -0,0 +1,77 @@+/** A point or offset, in the coordinates of the cell's parent. */+export interface DrawioPoint {+ x: number+ y: number+}++/**+ * A cell's `mxGeometry`. A vertex has a box in its parent's coordinates. An edge has its bend+ * `points` and, when an end is not attached, `sourcePoint` and `targetPoint`. A `relative` vertex+ * whose parent is an edge, as draw.io stores an edge label it moved, sits `x` of the way along the+ * edge, from -1 at its source to 1 at its target, `y` across it, and `offset` from there.+ */+export interface DrawioGeometry {+ x: number+ y: number+ width: number+ height: number+ relative: boolean+ points: DrawioPoint[]+ sourcePoint: DrawioPoint | null+ targetPoint: DrawioPoint | null+ offset: DrawioPoint | null+}++/**+ * A `style` string: the names of stylesheet styles it starts from, such as `ellipse` or `text`,+ * and its `key=value` pairs, both in the order written.+ */+export interface DrawioStyle {+ names: string[]+ values: Partial<Record<string, string>>+}++/** A shape or a connecting edge, in the order draw.io draws them. */+export interface DrawioCell {+ id: string+ /** The cell or layer it belongs to. */+ parent: string+ kind: 'vertex' | 'edge'+ /** The label: HTML when the style says `html=1`, plain text otherwise. */+ value: string+ style: DrawioStyle+ geometry: DrawioGeometry+ visible: boolean+ source: string | null+ target: string | null+ /**+ * Attributes of the `UserObject` or `object` that wraps the cell, such as `tooltip` and `link`,+ * and placeholders it fills in.+ */+ attributes: Record<string, string>+}++/** One of a page's layers, bottom first: the cells whose parent it is draw on it. */+export interface DrawioLayer {+ id: string+ name: string+ visible: boolean+ locked: boolean+}++export interface DrawioPage {+ id: string+ name: string+ /** The model's own attributes, such as `grid` and `background`. */+ attributes: Record<string, string>+ /** The id of the cell at the root of the model, which the layers belong to. */+ rootId: string+ layers: DrawioLayer[]+ cells: DrawioCell[]+}++/** A draw.io file: its pages, and the names of those that could not be read. */+export interface DrawioFile {+ pages: DrawioPage[]+ unreadable: string[]+}diff --git a/packages/drawio/src/read.ts b/packages/drawio/src/read.tsnew file mode 100644index 000000000..45b932a16--- /dev/null+++ b/packages/drawio/src/read.ts@@ -0,0 +1,182 @@+import type { Element } from '@xmldom/xmldom'+import { isValid, toUint8Array } from 'js-base64'++import { boundedInflate, inflateBudget, percentDecoded, type InflateBudget } from './inflate'+import type {+ DrawioCell,+ DrawioFile,+ DrawioGeometry,+ DrawioLayer,+ DrawioPage,+ DrawioPoint+} from './model'+import { parseStyle, styleFlag } from './style'+import { attributesOf, childElements, parseXML } from './xml'++/** What a cell wrapper keeps for itself rather than as the cell's attributes. */+const WRAPPER_OWN = new Set(['id', 'label'])++function number(element: Element, name: string, fallback = 0): number {+ const value = Number.parseFloat(element.getAttribute(name) ?? '')+ return Number.isFinite(value) ? value : fallback+}++function pointOf(element: Element): DrawioPoint {+ return { x: number(element, 'x'), y: number(element, 'y') }+}++const NO_GEOMETRY: DrawioGeometry = {+ x: 0,+ y: 0,+ width: 0,+ height: 0,+ relative: false,+ points: [],+ sourcePoint: null,+ targetPoint: null,+ offset: null+}++function readGeometry(cell: Element): DrawioGeometry {+ const geometry = childElements(cell, 'mxGeometry').at(0)+ if (!geometry) return structuredClone(NO_GEOMETRY)+ const points = childElements(geometry, 'Array').find((e) => e.getAttribute('as') === 'points')+ const point = (as: string) => {+ const found = childElements(geometry, 'mxPoint').find((p) => p.getAttribute('as') === as)+ return found ? pointOf(found) : null+ }+ return {+ x: number(geometry, 'x'),+ y: number(geometry, 'y'),+ width: number(geometry, 'width'),+ height: number(geometry, 'height'),+ relative: geometry.getAttribute('relative') === '1',+ points: points ? childElements(points, 'mxPoint').map(pointOf) : [],+ sourcePoint: point('sourcePoint'),+ targetPoint: point('targetPoint'),+ offset: point('offset')+ }+}++/** A cell element, and the `UserObject` or `object` around it when there is one. */+interface CellElements {+ cell: Element+ wrapper: Element | null+}++function cellElements(element: Element): CellElements | null {+ if (element.localName === 'mxCell') return { cell: element, wrapper: null }+ if (element.localName !== 'UserObject' && element.localName !== 'object') return null+ const cell = childElements(element, 'mxCell').at(0)+ return cell ? { cell, wrapper: element } : null+}++function readCell({ cell, wrapper }: CellElements, id: string, parent: string): DrawioCell {+ const isEdge = cell.getAttribute('edge') === '1'+ return {+ id,+ parent,+ kind: isEdge ? 'edge' : 'vertex',+ value: (wrapper ? wrapper.getAttribute('label') : cell.getAttribute('value')) ?? '',+ style: parseStyle(cell.getAttribute('style') ?? ''),+ geometry: readGeometry(cell),+ visible: cell.getAttribute('visible') !== '0',+ source: cell.getAttribute('source'),+ target: cell.getAttribute('target'),+ attributes: wrapper ? attributesOf(wrapper, WRAPPER_OWN) : {}+ }+}++/**+ * A model's cells. Its root is the one cell without a parent, and its layers are the cells under+ * the root that are neither shapes nor edges; draw.io names them `0` and `1` by default.+ */+function readModel(model: Element, page: Pick<DrawioPage, 'id' | 'name'>): DrawioPage | null {+ const root = childElements(model, 'root').at(0)+ if (!root) return null+ const read: { elements: CellElements; id: string; parent: string | null }[] = []+ for (const element of childElements(root)) {+ const elements = cellElements(element)+ const id = (elements?.wrapper ?? elements?.cell)?.getAttribute('id')+ if (elements && id) read.push({ elements, id, parent: elements.cell.getAttribute('parent') })+ }+ const rootId = read.find((entry) => !entry.parent)?.id+ if (rootId === undefined) return null+ const layers: DrawioLayer[] = []+ const cells: DrawioCell[] = []+ for (const { elements, id, parent } of read) {+ if (!parent) continue+ const { cell } = elements+ const shown = cell.getAttribute('vertex') === '1' || cell.getAttribute('edge') === '1'+ if (!shown && parent === rootId) {+ layers.push({+ id,+ name: cell.getAttribute('value') ?? '',+ visible: cell.getAttribute('visible') !== '0',+ locked: styleFlag(parseStyle(cell.getAttribute('style') ?? ''), 'locked')+ })+ } else if (shown) {+ cells.push(readCell(elements, id, parent))+ }+ }+ return {+ ...page,+ attributes: attributesOf(model, new Set()),+ rootId,+ layers,+ cells+ }+}++/** The XML inside a compressed `<diagram>`: Base64, raw deflate, then percent-encoded text. */+function inflateDiagram(text: string, budget: InflateBudget): string | null {+ const encoded = text.trim()+ if (!encoded || !isValid(encoded)) return null+ try {+ return percentDecoded(new TextDecoder().decode(boundedInflate(toUint8Array(encoded), budget)))+ } catch {+ return null+ }+}++function readDiagram(+ diagram: Element,+ index: number,+ budget: InflateBudget+): DrawioPage | { unreadable: string } {+ const name = diagram.getAttribute('name') || `Page ${index + 1}`+ const page = { id: diagram.getAttribute('id') ?? `page-${index + 1}`, name }+ let model = childElements(diagram, 'mxGraphModel').at(0) ?? null+ if (!model) {+ const xml = inflateDiagram(diagram.textContent ?? '', budget)+ const root = xml ? parseXML(xml) : null+ model = root?.localName === 'mxGraphModel' ? root : null+ }+ return (model ? readModel(model, page) : null) ?? { unreadable: name }+}++/**+ * The pages of a draw.io file, whether its diagrams are plain or compressed, with the names of+ * pages it could not read: damaged, or past what the file may unpack to. Null when the source+ * is not a draw.io file.+ */+export function parseDrawioFile(source: string, budget = inflateBudget()): DrawioFile | null {+ const root = parseXML(source)+ return root ? readDrawioRoot(root, budget) : null+}++/** The pages of a draw.io document from its parsed root, as `parseDrawioFile` reads them. */+export function readDrawioRoot(root: Element, budget: InflateBudget): DrawioFile | null {+ if (root.localName === 'mxGraphModel') {+ const page = readModel(root, { id: 'page-1', name: 'Page 1' })+ return page ? { pages: [page], unreadable: [] } : null+ }+ if (root.localName !== 'mxfile') return null+ const file: DrawioFile = { pages: [], unreadable: [] }+ for (const [index, diagram] of childElements(root, 'diagram').entries()) {+ const read = readDiagram(diagram, index, budget)+ if ('unreadable' in read) file.unreadable.push(read.unreadable)+ else file.pages.push(read)+ }+ return file+}diff --git a/packages/drawio/src/style.ts b/packages/drawio/src/style.tsnew file mode 100644index 000000000..6cb04bee7--- /dev/null+++ b/packages/drawio/src/style.ts@@ -0,0 +1,33 @@+import type { DrawioStyle } from './model'++/** A `style` string as its style names and its pairs. */+export function parseStyle(style: string): DrawioStyle {+ const result: DrawioStyle = { names: [], values: {} }+ for (const part of style.split(';')) {+ const text = part.trim()+ if (!text) continue+ const eq = text.indexOf('=')+ if (eq === -1) result.names.push(text)+ else result.values[text.slice(0, eq)] = text.slice(eq + 1)+ }+ return result+}++/** A style as draw.io writes it: its names, then `key=value;` pairs, in order. */+export function formatStyle({ names, values }: DrawioStyle): string {+ const pairs = Object.entries(values).flatMap(([key, value]) =>+ value === undefined ? [] : [`${key}=${value}`]+ )+ return [...names, ...pairs].map((part) => `${part};`).join('')+}++/** A number the style sets for `key`, or `fallback`. */+export function styleNumber(style: DrawioStyle, key: string, fallback: number): number {+ const value = Number.parseFloat(style.values[key] ?? '')+ return Number.isFinite(value) ? value : fallback+}++/** Whether the style turns `key` on, as `key=1` does. */+export function styleFlag(style: DrawioStyle, key: string): boolean {+ return style.values[key] === '1'+}diff --git a/packages/drawio/src/write.ts b/packages/drawio/src/write.tsnew file mode 100644index 000000000..ac27bb51b--- /dev/null+++ b/packages/drawio/src/write.ts@@ -0,0 +1,106 @@+import { DOMImplementation, XMLSerializer, type Document, type Element } from '@xmldom/xmldom'++import type { DrawioCell, DrawioFile, DrawioGeometry, DrawioPage, DrawioPoint } from './model'+import { formatStyle } from './style'++/** What the writer puts on `<mxfile>`, so draw.io knows who wrote it. */+const HOST = 'OpenPencil'++function setNumber(element: Element, name: string, value: number) {+ if (value !== 0) element.setAttribute(name, String(value))+}++function point(document: Document, at: DrawioPoint, as?: string): Element {+ const element = document.createElement('mxPoint')+ element.setAttribute('x', String(at.x))+ element.setAttribute('y', String(at.y))+ if (as) element.setAttribute('as', as)+ return element+}++function geometry(document: Document, value: DrawioGeometry): Element {+ const element = document.createElement('mxGeometry')+ setNumber(element, 'x', value.x)+ setNumber(element, 'y', value.y)+ setNumber(element, 'width', value.width)+ setNumber(element, 'height', value.height)+ if (value.relative) element.setAttribute('relative', '1')+ element.setAttribute('as', 'geometry')+ if (value.sourcePoint) element.appendChild(point(document, value.sourcePoint, 'sourcePoint'))+ if (value.targetPoint) element.appendChild(point(document, value.targetPoint, 'targetPoint'))+ if (value.points.length > 0) {+ const points = document.createElement('Array')+ points.setAttribute('as', 'points')+ for (const at of value.points) points.appendChild(point(document, at))+ element.appendChild(points)+ }+ if (value.offset) element.appendChild(point(document, value.offset, 'offset'))+ return element+}++/** A cell as draw.io writes it, wrapped in a `UserObject` when it carries attributes. */+function cellElement(document: Document, cell: DrawioCell): Element {+ const element = document.createElement('mxCell')+ const wrapped = Object.keys(cell.attributes).length > 0+ if (!wrapped) {+ element.setAttribute('id', cell.id)+ element.setAttribute('value', cell.value)+ }+ const style = formatStyle(cell.style)+ if (style) element.setAttribute('style', style)+ element.setAttribute(cell.kind, '1')+ if (!cell.visible) element.setAttribute('visible', '0')+ element.setAttribute('parent', cell.parent)+ if (cell.source) element.setAttribute('source', cell.source)+ if (cell.target) element.setAttribute('target', cell.target)+ element.appendChild(geometry(document, cell.geometry))+ if (!wrapped) return element+ const wrapper = document.createElement('UserObject')+ wrapper.setAttribute('label', cell.value)+ for (const [name, value] of Object.entries(cell.attributes)) wrapper.setAttribute(name, value)+ wrapper.setAttribute('id', cell.id)+ wrapper.appendChild(element)+ return wrapper+}++function pageElement(document: Document, page: DrawioPage): Element {+ const diagram = document.createElement('diagram')+ diagram.setAttribute('id', page.id)+ diagram.setAttribute('name', page.name)+ const model = document.createElement('mxGraphModel')+ for (const [name, value] of Object.entries(page.attributes)) model.setAttribute(name, value)+ const root = document.createElement('root')+ const rootCell = document.createElement('mxCell')+ rootCell.setAttribute('id', page.rootId)+ root.appendChild(rootCell)+ for (const layer of page.layers) {+ const element = document.createElement('mxCell')+ element.setAttribute('id', layer.id)+ if (layer.name) element.setAttribute('value', layer.name)+ if (layer.locked) element.setAttribute('style', 'locked=1;')+ if (!layer.visible) element.setAttribute('visible', '0')+ element.setAttribute('parent', page.rootId)+ root.appendChild(element)+ }+ for (const cell of page.cells) root.appendChild(cellElement(document, cell))+ model.appendChild(root)+ diagram.appendChild(model)+ return diagram+}++/**+ * A draw.io file as XML draw.io opens: each page a `<diagram>` holding its model uncompressed,+ * as draw.io itself saves by default, so the file diffs and reads as text. A file with pages that+ * could not be read is refused, since writing it would drop them.+ */+export function writeDrawioFile(file: DrawioFile): string {+ if (file.unreadable.length > 0) {+ throw new Error(`Could not write the draw.io pages ${file.unreadable.join(', ')}`)+ }+ const document = new DOMImplementation().createDocument(null, 'mxfile', null)+ const root = document.documentElement+ if (!root) throw new Error('Could not create a draw.io document')+ root.setAttribute('host', HOST)+ for (const page of file.pages) root.appendChild(pageElement(document, page))+ return new XMLSerializer().serializeToString(document)+}diff --git a/packages/drawio/src/xml.ts b/packages/drawio/src/xml.tsnew file mode 100644index 000000000..0fd951c3f--- /dev/null+++ b/packages/drawio/src/xml.ts@@ -0,0 +1,38 @@+import { DOMParser, type Element } from '@xmldom/xmldom'++/** The root element of `source`, or null when it is not well-formed XML. */+export function parseXML(source: string): Element | null {+ try {+ const parsed = new DOMParser({+ onError: (level, message) => {+ if (level !== 'warning') throw new Error(message)+ }+ }).parseFromString(source, 'text/xml')+ return parsed.documentElement+ } catch {+ return null+ }+}++/** The element children of `element`, named `name` when given. */+export function childElements(element: Element, name?: string): Element[] {+ const found: Element[] = []+ for (let node = element.firstChild; node; node = node.nextSibling) {+ if (node.nodeType === node.ELEMENT_NODE && (!name || (node as Element).localName === name)) {+ found.push(node as Element)+ }+ }+ return found+}++/** All of an element's attributes but those in `except`. */+export function attributesOf(+ element: Element,+ except: ReadonlySet<string>+): Record<string, string> {+ const attributes: Record<string, string> = {}+ for (const attribute of Array.from(element.attributes)) {+ if (!except.has(attribute.name)) attributes[attribute.name] = attribute.value+ }+ return attributes+}diff --git a/packages/drawio/tests/read.test.ts b/packages/drawio/tests/read.test.tsnew file mode 100644index 000000000..ebc1aa9cf--- /dev/null+++ b/packages/drawio/tests/read.test.ts@@ -0,0 +1,206 @@+import { describe, expect, test } from 'bun:test'++import { deflateSync } from 'fflate'+import { fromUint8Array } from 'js-base64'++import { MAX_INFLATED_BYTES, parseDrawioFile, readDrawioBytes } from '@open-pencil/drawio'++/**+ * A page as draw.io saves it: the root and default layer, a second hidden layer, a plain shape,+ * a shape wrapped in a `UserObject`, an edge with bend points between them, and a label moved+ * along that edge, which draw.io keeps as a relative child of the edge.+ */+const MODEL = `<mxGraphModel dx="1018" dy="616" grid="1" gridSize="10" background="#ffffff">+ <root>+ <mxCell id="0"/>+ <mxCell id="1" parent="0"/>+ <mxCell id="notes" value="Notes" style="locked=1;" parent="0" visible="0"/>+ <mxCell id="a" value="Start" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;" vertex="1" parent="1">+ <mxGeometry x="40" y="60" width="120" height="60" as="geometry"/>+ </mxCell>+ <UserObject label="<b>Done</b>" tooltip="Why" link="https://example.com" id="b">+ <mxCell style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1">+ <mxGeometry x="320" y="200" width="120" height="80" as="geometry"/>+ </mxCell>+ </UserObject>+ <mxCell id="e" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;" edge="1" parent="1" source="a" target="b">+ <mxGeometry relative="1" as="geometry">+ <Array as="points"><mxPoint x="240" y="90"/><mxPoint x="240" y="240"/></Array>+ </mxGeometry>+ </mxCell>+ <mxCell id="l" value="next" style="edgeLabel;html=1;align=center;" vertex="1" connectable="0" parent="e">+ <mxGeometry x="-0.3" y="2" relative="1" as="geometry"><mxPoint x="4" y="-6" as="offset"/></mxGeometry>+ </mxCell>+ <mxCell id="hidden" value="Draft" style="text;" vertex="1" parent="notes" visible="0">+ <mxGeometry x="10" y="10" width="60" height="20" as="geometry"/>+ </mxCell>+ </root>+</mxGraphModel>`++const page = (name: string, model = MODEL) =>+ `<diagram id="${name}" name="${name}">${model}</diagram>`++/** A page as draw.io compresses it: the model percent-encoded, raw-deflated, then Base64. */+function compressed(model: string): string {+ const raw = new TextEncoder().encode(encodeURIComponent(model))+ return fromUint8Array(deflateSync(raw, { level: 9 }))+}++describe('reading a draw.io file', () => {+ test('keeps each page’s layers, cells in drawing order, styles, and geometry', () => {+ const file = parseDrawioFile(`<mxfile host="drawio">${page('First')}</mxfile>`)+ const [first] = file?.pages ?? []+ expect(first).toMatchObject({+ name: 'First',+ rootId: '0',+ attributes: { grid: '1', background: '#ffffff' },+ layers: [+ { id: '1', name: '', visible: true, locked: false },+ { id: 'notes', name: 'Notes', visible: false, locked: true }+ ]+ })+ expect(first?.cells.map((cell) => [cell.id, cell.kind, cell.parent])).toEqual([+ ['a', 'vertex', '1'],+ ['b', 'vertex', '1'],+ ['e', 'edge', '1'],+ ['l', 'vertex', 'e'],+ ['hidden', 'vertex', 'notes']+ ])+ const [start, done, edge, label, hidden] = first?.cells ?? []+ expect(start.style).toEqual({+ names: [],+ values: { rounded: '1', whiteSpace: 'wrap', html: '1', fillColor: '#dae8fc' }+ })+ expect(done).toMatchObject({+ value: '<b>Done</b>',+ style: { names: ['ellipse'] },+ attributes: { tooltip: 'Why', link: 'https://example.com' }+ })+ expect(edge).toMatchObject({ source: 'a', target: 'b' })+ expect(edge.geometry.points).toEqual([+ { x: 240, y: 90 },+ { x: 240, y: 240 }+ ])+ expect(label.geometry).toMatchObject({ x: -0.3, y: 2, relative: true, offset: { x: 4, y: -6 } })+ expect(hidden.visible).toBe(false)+ })++ test('reads a bare model and compressed pages', () => {+ expect(parseDrawioFile(MODEL)?.pages[0]?.cells).toHaveLength(5)+ const file = parseDrawioFile(+ `<mxfile><diagram id="z" name="Packed">${compressed(MODEL)}</diagram></mxfile>`+ )+ expect(file?.pages[0]?.cells.map((cell) => cell.id)).toEqual(['a', 'b', 'e', 'l', 'hidden'])+ })++ test('names pages it cannot read, and reads the rest', () => {+ const file = parseDrawioFile(+ `<mxfile>${page('Good')}<diagram id="bad" name="Broken">not base64 %%%</diagram></mxfile>`+ )+ expect(file?.pages.map((p) => p.name)).toEqual(['Good'])+ expect(file?.unreadable).toEqual(['Broken'])+ })++ test('is not fooled by other XML', () => {+ expect(parseDrawioFile('<svg xmlns="http://www.w3.org/2000/svg"/>')).toBeNull()+ expect(parseDrawioFile('not xml')).toBeNull()+ })++ test('stops unpacking once the whole file passes its limit, however many pages share it', () => {+ // Each page alone unpacks within the limit; together they do not.+ const big = `<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0" value="${'x'.repeat(+ MAX_INFLATED_BYTES / 4+ )}"/></root></mxGraphModel>`+ const packed = compressed(big)+ const pages = Array.from(+ { length: 6 },+ (_, i) => `<diagram id="p${i}" name="P${i}">${packed}</diagram>`+ )+ const file = parseDrawioFile(`<mxfile>${pages.join('')}</mxfile>`)+ expect(file?.pages.length).toBeLessThan(6)+ expect(file?.unreadable.length).toBeGreaterThan(0)+ })+})++const latin1 = (value: string) => Uint8Array.from(value, (c) => c.charCodeAt(0))++function concat(parts: Uint8Array[]): Uint8Array {+ const bytes = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0))+ let offset = 0+ for (const part of parts) {+ bytes.set(part, offset)+ offset += part.length+ }+ return bytes+}++/** A PNG chunk: its length, type, data, and a CRC, which the reader does not check. */+function chunk(type: string, data: Uint8Array): Uint8Array {+ const out = new Uint8Array(12 + data.length)+ new DataView(out.buffer).setUint32(0, data.length)+ out.set(latin1(type), 4)+ out.set(data, 8)+ return out+}++/** A PNG holding only the given chunks between its signature and `IEND`. */+function png(...chunks: Uint8Array[]): Uint8Array {+ const signature = Uint8Array.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])+ return concat([signature, ...chunks, chunk('IEND', new Uint8Array())])+}++/** A PNG holding only the chunk draw.io adds: a `tEXt` chunk under `keyword`. */+function pngWithText(keyword: string, text: string): Uint8Array {+ return png(chunk('tEXt', latin1(`${keyword}\0${encodeURIComponent(text)}`)))+}++/** A zlib stream of `text`: a 2-byte header, then raw deflate, as PNG text chunks hold it. */+function zlib(text: string): Uint8Array {+ return concat([Uint8Array.from([0x78, 0xda]), deflateSync(latin1(text), { level: 9 })])+}++const EMBEDDED = encodeURIComponent(`<mxfile>${page('Embedded')}</mxfile>`)++describe('reading the diagram a draw.io export embeds', () => {+ test('from a PNG’s text chunk', () => {+ const file = readDrawioBytes(pngWithText('mxfile', `<mxfile>${page('Embedded')}</mxfile>`))+ expect(file?.pages[0]?.name).toBe('Embedded')+ expect(readDrawioBytes(pngWithText('Software', 'paint.net'))).toBeNull()+ })++ test('from an SVG’s content attribute', () => {+ const content = `<mxfile>${page('Vector')}</mxfile>`+ .replaceAll('&', '&')+ .replaceAll('"', '"')+ .replaceAll('<', '<')+ const svg = `<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" content="${content}"><rect/></svg>`+ expect(readDrawioBytes(new TextEncoder().encode(svg))?.pages[0]?.name).toBe('Vector')+ expect(+ readDrawioBytes(new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"/>'))+ ).toBeNull()+ })++ test('from a PNG’s compressed and international text chunks', () => {+ const zTXt = png(chunk('zTXt', concat([latin1('mxfile\0\0'), zlib(EMBEDDED)])))+ expect(readDrawioBytes(zTXt)?.pages[0]?.name).toBe('Embedded')+ // iTXt: keyword, compression flag and method, then empty language and translated keyword.+ const packed = png(chunk('iTXt', concat([latin1('mxfile\0\x01\0\0\0'), zlib(EMBEDDED)])))+ expect(readDrawioBytes(packed)?.pages[0]?.name).toBe('Embedded')+ const plain = png(chunk('iTXt', latin1(`mxfile\0\0\0\0\0${EMBEDDED}`)))+ expect(readDrawioBytes(plain)?.pages[0]?.name).toBe('Embedded')+ })++ test('says a damaged or cut short PNG cannot be read, rather than that it holds no diagram', () => {+ const damaged = png(chunk('zTXt', latin1('mxfile\0\0not zlib')))+ expect(() => readDrawioBytes(damaged)).toThrow(+ 'Could not read the draw.io diagram in this image'+ )+ const whole = pngWithText('mxfile', `<mxfile>${page('Embedded')}</mxfile>`)+ expect(() => readDrawioBytes(whole.subarray(0, 40))).toThrow('cut short')+ })++ test('takes an SVG’s comments before its root in stride', () => {+ const svg = `${'<!---->'.repeat(10_000)}x`+ expect(readDrawioBytes(new TextEncoder().encode(svg))).toBeNull()+ })+})diff --git a/packages/drawio/tests/write.test.ts b/packages/drawio/tests/write.test.tsnew file mode 100644index 000000000..2bf44e274--- /dev/null+++ b/packages/drawio/tests/write.test.ts@@ -0,0 +1,45 @@+import { expect, test } from 'bun:test'++import { parseDrawioFile, writeDrawioFile } from '@open-pencil/drawio'++const MODEL = `<mxGraphModel grid="1"><root>+ <mxCell id="0"/><mxCell id="1" parent="0"/>+ <mxCell id="notes" value="Notes" style="locked=1;" parent="0" visible="0"/>+ <mxCell id="a" value="A & B" style="ellipse;fillColor=#fff2cc;" vertex="1" parent="1">+ <mxGeometry x="40" y="60" width="120" height="60" as="geometry">+ <Array as="points"><mxPoint x="10" y="20"/></Array>+ </mxGeometry>+ </mxCell>+ <UserObject label="Linked" link="https://example.com" placeholders="1" id="b">+ <mxCell style="rounded=1;" vertex="1" parent="notes">+ <mxGeometry x="300" y="60" width="120" height="60" as="geometry"/>+ </mxCell>+ </UserObject>+ <mxCell id="e" value="" style="edgeStyle=orthogonalEdgeStyle;" edge="1" parent="1" source="a">+ <mxGeometry relative="1" as="geometry">+ <mxPoint x="500" y="90" as="targetPoint"/>+ <Array as="points"><mxPoint x="240" y="90"/></Array>+ </mxGeometry>+ </mxCell>+ <mxCell id="l" value="next" style="edgeLabel;" vertex="1" parent="e">+ <mxGeometry x="0.5" relative="1" as="geometry"><mxPoint x="2" y="-8" as="offset"/></mxGeometry>+ </mxCell>+</root></mxGraphModel>`++test('a written file reads back as the file it was written from', () => {+ const file = parseDrawioFile(`<mxfile><diagram id="p" name="Page">${MODEL}</diagram></mxfile>`)+ if (!file) throw new Error('Fixture did not read')+ const written = writeDrawioFile(file)+ expect(written).toStartWith('<mxfile host="OpenPencil">')+ // Saved uncompressed, as draw.io saves by default.+ expect(written).toContain('<mxGraphModel grid="1"><root><mxCell id="0"/>')+ expect(parseDrawioFile(written)).toEqual(file)+})++test('a file with pages it could not read is not written, since they would be lost', () => {+ const file = parseDrawioFile(+ `<mxfile><diagram id="p" name="Page">${MODEL}</diagram><diagram id="q" name="Broken">!</diagram></mxfile>`+ )+ if (!file) throw new Error('Fixture did not read')+ expect(() => writeDrawioFile(file)).toThrow('Could not write the draw.io pages Broken')+})diff --git a/packages/drawio/tsconfig.json b/packages/drawio/tsconfig.jsonnew file mode 100644index 000000000..04e7fc8dd--- /dev/null+++ b/packages/drawio/tsconfig.json@@ -0,0 +1,24 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "lib": ["ES2023", "DOM", "DOM.Iterable"],+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "declaration": true,+ "declarationDir": "./dist/src",+ "declarationMap": true,+ "outDir": "./dist",+ "rootDir": "./src",+ "skipLibCheck": true,+ "esModuleInterop": true,+ "resolveJsonModule": true,+ "types": ["bun"],+ "paths": {+ "#drawio/*": ["./src/*"],+ "@open-pencil/drawio": ["./src/index.ts"]+ }+ },+ "include": ["src/**/*.ts"],+ "exclude": ["node_modules", "dist"]+}diff --git a/packages/drawio/tsdown.config.ts b/packages/drawio/tsdown.config.tsnew file mode 100644index 000000000..ce2725b7e--- /dev/null+++ b/packages/drawio/tsdown.config.ts@@ -0,0 +1,38 @@+import { defineConfig } from 'tsdown'++export default defineConfig({+ entry: {+ index: './src/index.ts'+ },+ platform: 'neutral',+ format: ['esm'],+ dts: true,+ sourcemap: true,+ hash: false,+ clean: true,+ outDir: './dist',+ treeshake: {+ moduleSideEffects: false+ },+ deps: {+ neverBundle: [/^@xmldom\//, 'fflate', 'js-base64', /^node:/],+ onlyBundle: false+ },+ outputOptions: {+ minifyInternalExports: false,+ codeSplitting: {+ groups: [+ {+ test: /(?<!\.d\.c?ts)$/,+ name: (id) => {+ const cleanId = id.split('?')[0]+ const parts = cleanId.split(/[\\/]/g)+ const srcIndex = parts.lastIndexOf('src')+ const file = srcIndex >= 0 ? parts.slice(srcIndex + 1).join('/') : parts.at(-1) ?? 'chunk'+ return `chunks/${file.replace(/\.(ts|tsx)$/, '')}`+ }+ }+ ]+ }+ }+})diff --git a/packages/emit/package.json b/packages/emit/package.jsonindex 4ca109360..c5d0bd553 100644--- a/packages/emit/package.json+++ b/packages/emit/package.json@@ -38,9 +38,8 @@},"scripts": {"build": "bunx tsdown --config tsdown.config.ts",- "check": "bun run typecheck && bun run build && bun run smoke:dist",+ "check": "bun run typecheck && bun run build","prepack": "bun run build",- "smoke:dist": "bun scripts/smoke-dist.ts","typecheck": "bunx tsc --noEmit -p tsconfig.json"},"dependencies": {diff --git a/packages/emit/scripts/smoke-dist.ts b/packages/emit/scripts/smoke-dist.tsdeleted file mode 100644index 068f7c138..000000000--- a/packages/emit/scripts/smoke-dist.ts+++ /dev/null@@ -1,11 +0,0 @@-export {}--const { es, jsx } = await import('../dist/index.js')--const card = jsx.printJSX(- jsx.element('Card', [jsx.attribute('title', jsx.stringValue('a "quoted" title'))], [], 0)-)-const module = es.printModule(es.parseModule('export const answer = 42'))-if (card !== '<Card title={"a \\"quoted\\" title"} />' || !module.includes('answer = 42')) {- throw new Error('Expected built emit package to print JSX and modules')-}diff --git a/packages/fig/package.json b/packages/fig/package.jsonindex e9d3036f3..04ab63bbc 100644--- a/packages/fig/package.json+++ b/packages/fig/package.json@@ -52,9 +52,8 @@},"scripts": {"build": "bunx tsdown --config tsdown.config.ts",- "check": "bun run typecheck && bun run test && bun run build && bun run smoke:dist",+ "check": "bun run typecheck && bun run test && bun run build","prepack": "bun run build",- "smoke:dist": "bun scripts/smoke-dist.ts","test": "bun test tests","typecheck": "bunx tsc --noEmit -p tsconfig.test.json"},diff --git a/packages/fig/scripts/smoke-dist.ts b/packages/fig/scripts/smoke-dist.tsdeleted file mode 100644index 2ed3b7da4..000000000--- a/packages/fig/scripts/smoke-dist.ts+++ /dev/null@@ -1,27 +0,0 @@-export {}--const mod = await import('../dist/index.js')-const instanceOverrides = await import('../dist/instance-overrides.js')-const nodeChange = await import('../dist/node-change.js')--if (- mod.FIG_PACKAGE_STATUS !== 'document-reader' ||- typeof mod.effectiveFigmaRawNodeFields !== 'function' ||- typeof mod.parseFigBuffer !== 'function' ||- typeof mod.writeFigArchive !== 'function' ||- typeof instanceOverrides.interpretInstance !== 'function' ||- typeof nodeChange.convertLineHeight !== 'function' ||- typeof nodeChange.sceneNodeToKiwi !== 'function'-) {- throw new Error('Expected @open-pencil/fig archive API exports')-}--const bytes = mod.writeFigContainer({- schemaDeflated: new Uint8Array([1]),- dataRaw: new Uint8Array([2])-})-const document = mod.readFigContainer(bytes)--if (document.dataRaw[0] !== 2) {- throw new Error('Expected @open-pencil/fig container round-trip')-}diff --git a/packages/kiwi/README.md b/packages/kiwi/README.mdindex 637878e31..3aa860765 100644--- a/packages/kiwi/README.md+++ b/packages/kiwi/README.md@@ -26,10 +26,9 @@ bun run checkPackage scripts:- `bun run test` — package-local Bun tests for schema runtime, Figma schema guards, codec, container, parse, GUID, and variable bindings-- `bun run typecheck` — type-checks `src`, tests, and package scripts+- `bun run typecheck` — type-checks `src` and tests- `bun run build` — builds the distributable `dist` entrypoints-- `bun run smoke:dist` — imports built output and exercises the public API-- `bun run check` — runs typecheck, tests, build, and dist smoke in sequence+- `bun run check` — runs typecheck, tests, and build in sequence## Schema runtimediff --git a/packages/kiwi/package.json b/packages/kiwi/package.jsonindex c3714b003..b086c8adf 100644--- a/packages/kiwi/package.json+++ b/packages/kiwi/package.json@@ -59,9 +59,8 @@},"scripts": {"build": "bunx tsdown --config tsdown.config.ts",- "check": "bun run typecheck && bun run test && bun run build && bun run smoke:dist",+ "check": "bun run typecheck && bun run test && bun run build","prepack": "bun run build",- "smoke:dist": "bun scripts/smoke-dist.ts","test": "bun test tests","typecheck": "bunx tsc --noEmit -p tsconfig.test.json"},diff --git a/packages/kiwi/scripts/smoke-dist.ts b/packages/kiwi/scripts/smoke-dist.tsdeleted file mode 100644index 7c7f4fc71..000000000--- a/packages/kiwi/scripts/smoke-dist.ts+++ /dev/null@@ -1,40 +0,0 @@-import { getSchemaBytes, initCodec, isCodecReady } from '../dist/fig/codec.js'-import { buildFigKiwi, parseFigKiwiChunks } from '../dist/fig/container.js'-import { guidToString } from '../dist/fig/guid.js'-import { parseFigKiwiContainer } from '../dist/fig/parse.js'-import { figmaSchema, getKiwiMessageType, parseSchema, validateSchema } from '../dist/index.js'--const schema = parseSchema(`-message Smoke {- uint id = 1;-}-`)-validateSchema(schema)-validateSchema(figmaSchema)--if (figmaSchema.definitions.length !== 605) {- throw new Error(`Unexpected Figma schema definition count: ${figmaSchema.definitions.length}`)-}--if (getKiwiMessageType(new Uint8Array([1, 3, 0])) !== 3) {- throw new Error('Failed to read Kiwi message type from built dist')-}--await initCodec()--if (!isCodecReady() || getSchemaBytes().length === 0) {- throw new Error('Failed to initialize built FIG codec')-}--if (parseFigKiwiContainer(new TextEncoder().encode('not-fig-kiwi')) !== null) {- throw new Error('Failed to reject invalid FIG Kiwi container')-}--const figKiwi = buildFigKiwi(new Uint8Array([1]), new Uint8Array([2]))-if (parseFigKiwiChunks(figKiwi)?.length !== 2) {- throw new Error('Failed to read built FIG Kiwi container chunks')-}--if (guidToString({ sessionID: 1, localID: 2 }) !== '1:2') {- throw new Error('Failed to format built FIG GUID helper')-}diff --git a/packages/kiwi/tsconfig.json b/packages/kiwi/tsconfig.jsonindex 9ff324e95..2485804b5 100644--- a/packages/kiwi/tsconfig.json+++ b/packages/kiwi/tsconfig.json@@ -11,5 +11,5 @@"types": ["bun"]},"include": ["src/**/*.ts"],- "exclude": ["dist", "tests", "scripts"]+ "exclude": ["dist", "tests"]}diff --git a/packages/kiwi/tsconfig.test.json b/packages/kiwi/tsconfig.test.jsonindex b89f8132d..dbfec6428 100644--- a/packages/kiwi/tsconfig.test.json+++ b/packages/kiwi/tsconfig.test.json@@ -3,5 +3,5 @@"compilerOptions": {"noEmit": true},- "include": ["src/**/*.ts", "tests/**/*.ts", "scripts/**/*.ts"]+ "include": ["src/**/*.ts", "tests/**/*.ts"]}diff --git a/packages/pen/package.json b/packages/pen/package.jsonindex 0c2822132..1a56436ad 100644--- a/packages/pen/package.json+++ b/packages/pen/package.json@@ -30,9 +30,8 @@},"scripts": {"build": "bunx tsdown --config tsdown.config.ts",- "check": "bun run typecheck && bun run build && bun run smoke:dist",+ "check": "bun run typecheck && bun run build","prepack": "bun run build",- "smoke:dist": "bun scripts/smoke-dist.ts","typecheck": "bunx tsc --noEmit -p tsconfig.json"},"dependencies": {diff --git a/packages/pen/scripts/smoke-dist.ts b/packages/pen/scripts/smoke-dist.tsdeleted file mode 100644index 99ae854d6..000000000--- a/packages/pen/scripts/smoke-dist.ts+++ /dev/null@@ -1,14 +0,0 @@-export {}--const mod = await import('../dist/index.js')--const graph = mod.parsePenFile(- JSON.stringify({- version: '1',- children: [{ id: 'frame', type: 'frame', name: 'Frame', width: 100, height: 50 }]- })-)--if (graph.getPages()[0]?.childIds.length !== 1) {- throw new Error('Expected built Pen package to parse a document')-}diff --git a/packages/scene-graph/package.json b/packages/scene-graph/package.jsonindex 45e178d01..683b38202 100644--- a/packages/scene-graph/package.json+++ b/packages/scene-graph/package.json@@ -381,9 +381,8 @@},"scripts": {"build": "bunx tsdown --config tsdown.config.ts",- "check": "bun run typecheck && bun run test && bun run build && bun run smoke:dist",+ "check": "bun run typecheck && bun run test && bun run build","prepack": "bun run build",- "smoke:dist": "bun scripts/smoke-dist.ts","test": "bun test tests","typecheck": "bunx tsc --noEmit -p tsconfig.test.json"},diff --git a/packages/scene-graph/scripts/smoke-dist.ts b/packages/scene-graph/scripts/smoke-dist.tsdeleted file mode 100644index 8ee0f7e6c..000000000--- a/packages/scene-graph/scripts/smoke-dist.ts+++ /dev/null@@ -1,11 +0,0 @@-export {}--const mod = await import('../dist/index.js')--const graph = new mod.SceneGraph()-const page = graph.getPages()[0]-const node = graph.createNode('RECTANGLE', page.id, { width: 10, height: 20 })--if (graph.getNode(node.id)?.width !== 10) {- throw new Error('Expected built SceneGraph package to create nodes')-}diff --git a/tools/checks/package-quality/src/smoke/scenarios.ts b/tools/checks/package-quality/src/smoke/scenarios.tsindex 9b64fb85b..ac8a44567 100644--- a/tools/checks/package-quality/src/smoke/scenarios.ts+++ b/tools/checks/package-quality/src/smoke/scenarios.ts@@ -32,6 +32,10 @@ export const runtimeScenarios: RuntimeScenario[] = [name: 'PEN parser',code: "const { parsePenFile } = await import('@open-pencil/pen'); const graph = parsePenFile(JSON.stringify({ version: '1', children: [{ id: 'frame', type: 'frame', width: 100, height: 50 }] })); if (graph.getPages()[0].childIds.length !== 1) throw new Error('Pen package smoke failed')"},+ {+ name: 'draw.io codec',+ code: 'const { parseDrawioFile, writeDrawioFile } = await import(\'@open-pencil/drawio\'); const file = parseDrawioFile(\'<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/><mxCell id="a" vertex="1" parent="1"/></root></mxGraphModel>\'); if (file?.pages[0]?.cells.length !== 1 || !writeDrawioFile(file).startsWith(\'<mxfile\')) throw new Error(\'draw.io package smoke failed\')'+ },{name: 'Emit package',code: "const { jsx } = await import('@open-pencil/emit'); const code = jsx.printJSX(jsx.element('Card', [jsx.attribute('wide', null)], [], 0)); if (code !== '<Card wide />') throw new Error('Codegen package smoke failed: ' + code)"diff --git a/tools/checks/package-quality/src/smoke/type-consumer.ts b/tools/checks/package-quality/src/smoke/type-consumer.tsindex 68a5a0ae9..584b27828 100644--- a/tools/checks/package-quality/src/smoke/type-consumer.ts+++ b/tools/checks/package-quality/src/smoke/type-consumer.ts@@ -6,6 +6,7 @@ import { runCommand } from '@open-pencil/package-artifacts-tools'const TYPE_CONSUMER = `import { createEditor, type Editor } from '@open-pencil/core'import { Frame, type TreeNode } from '@open-pencil/design-jsx'import { htmlToDesignDocument, type DesignDocument } from '@open-pencil/dom-css'+import { parseDrawioFile, type DrawioFile } from '@open-pencil/drawio'import { FIG_PACKAGE_STATUS, type FigContainerDocument } from '@open-pencil/fig'import { FIG_KIWI_DEFAULT_VERSION, buildFigKiwi } from '@open-pencil/kiwi/fig/container'import type { GUID as KiwiGUID } from '@open-pencil/kiwi/fig'@@ -25,10 +26,11 @@ const maybeNode: SceneNode | undefined = graph.getPages()[0]const penDocument: PenDocument = { version: '1', children: [] }const figDocument: FigContainerDocument = { schemaDeflated: new Uint8Array([1]), dataRaw: new Uint8Array([2]) }const kiwiGuid: KiwiGUID = { sessionID: 1, localID: 2 }+const drawioFile: DrawioFile | null = parseDrawioFile('<mxfile/>')void editorFactory; void editor; void designDocument; void color; void vector; void maybeNodevoid penDocument; void figDocument; void kiwiGuid; void FIG_PACKAGE_STATUSvoid FIG_KIWI_DEFAULT_VERSION; void buildFigKiwi; void parsePenFile; void htmlToDesignDocument-void testIdSelector; void tree+void testIdSelector; void tree; void drawioFile`export async function verifyTypeConsumer(root: string, consumerDirectory: string): Promise<void> {diff --git a/tools/dev/unit-tests/src/shards.ts b/tools/dev/unit-tests/src/shards.tsindex d881ed9a6..04e74b7e3 100644--- a/tools/dev/unit-tests/src/shards.ts+++ b/tools/dev/unit-tests/src/shards.ts@@ -45,6 +45,7 @@ export const UNIT_TEST_GROUPS = {],dom: ['packages/emit/tests',+ 'packages/drawio/tests','packages/design-jsx/tests','packages/dom-css/tests','packages/pen/tests',diff --git a/tools/dev/unit-tests/tests/shards.test.ts b/tools/dev/unit-tests/tests/shards.test.tsindex 1f15af4ee..251e2609c 100644--- a/tools/dev/unit-tests/tests/shards.test.ts+++ b/tools/dev/unit-tests/tests/shards.test.ts@@ -50,6 +50,7 @@ test('canonical destinations are registered before they hold files', async () =>'dom-css','design-jsx','emit',+ 'drawio','pen','cli','mcp'diff --git a/tsconfig.json b/tsconfig.jsonindex 792d2b0c1..70a8e4e78 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -106,6 +106,12 @@"@open-pencil/scene-graph/*": ["./packages/scene-graph/src/*"],+ "#drawio/*": [+ "./packages/drawio/src/*"+ ],+ "@open-pencil/drawio": [+ "./packages/drawio/src/index.ts"+ ],"#emit/*": ["./packages/emit/src/*"],diff --git a/tsconfig.tests.json b/tsconfig.tests.jsonindex c58803172..1095abc89 100644--- a/tsconfig.tests.json+++ b/tsconfig.tests.json@@ -100,6 +100,12 @@"@open-pencil/scene-graph/*": ["./packages/scene-graph/src/*"],+ "#drawio/*": [+ "./packages/drawio/src/*"+ ],+ "@open-pencil/drawio": [+ "./packages/drawio/src/index.ts"+ ],"#emit/*": ["./packages/emit/src/*"],