Skip to content

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

refactor: print OpenPencil JSX export as syntax trees (#799)

Danila Poyarkov9b418de13e50
diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile
index 4a5959a59..68ed4015d 100644
--- a/.devcontainer/Dockerfile
+++ b/.devcontainer/Dockerfile
@@ -26,6 +26,7 @@ RUN apt-get update \
/workspace/open-pencil/packages/core/node_modules \
/workspace/open-pencil/packages/dom-css/node_modules \
/workspace/open-pencil/packages/design-jsx/node_modules \
+ /workspace/open-pencil/packages/codegen/node_modules \
/workspace/open-pencil/packages/vue/node_modules \
/workspace/open-pencil/packages/cli/node_modules \
/workspace/open-pencil/packages/mcp/node_modules \
diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json
index 7fd2e507b..3efc22616 100644
--- a/.devcontainer/devcontainer.json
+++ b/.devcontainer/devcontainer.json
@@ -18,6 +18,7 @@
"source=open-pencil-core-modules-${devcontainerId},target=/workspace/open-pencil/packages/core/node_modules,type=volume",
"source=open-pencil-dom-css-modules-${devcontainerId},target=/workspace/open-pencil/packages/dom-css/node_modules,type=volume",
"source=open-pencil-design-jsx-modules-${devcontainerId},target=/workspace/open-pencil/packages/design-jsx/node_modules,type=volume",
+ "source=open-pencil-codegen-modules-${devcontainerId},target=/workspace/open-pencil/packages/codegen/node_modules,type=volume",
"source=open-pencil-vue-modules-${devcontainerId},target=/workspace/open-pencil/packages/vue/node_modules,type=volume",
"source=open-pencil-cli-modules-${devcontainerId},target=/workspace/open-pencil/packages/cli/node_modules,type=volume",
"source=open-pencil-mcp-modules-${devcontainerId},target=/workspace/open-pencil/packages/mcp/node_modules,type=volume",
diff --git a/AGENTS.md b/AGENTS.md
index d958d3049..e253446eb 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -13,7 +13,8 @@ This file holds the repository map and the rules that apply everywhere. Rules fo
| `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` |
-| `packages/dom-css` | DOM/CSS/HTML/JSX/Tailwind projection and browser/headless adapters; depends only on scene-graph and takes engine services such as web-font resolution as injected options | `packages/dom-css/AGENTS.md` |
+| `packages/dom-css` | DOM/CSS/HTML/JSX/Tailwind projection and browser/headless adapters; depends only on scene-graph and codegen, and takes engine services such as web-font resolution as injected options | `packages/dom-css/AGENTS.md` |
+| `packages/codegen` | Syntax-tree code generation for exporters: ESTree and JSX builders, template filling, and esrap printing, with the literal rules that keep exported strings from being reinterpreted | — |
| `packages/design-jsx` | OpenPencil design JSX: elements, paint/effect helpers, variables, schema and authoring reference, JSX export, and a renderer that takes icons, SVG, and layout as injected services | `packages/design-jsx/AGENTS.md` |
| `packages/vue` | Headless Vue 3 SDK primitives, composables, commands, i18n, menu model | `packages/vue/AGENTS.md` |
| `packages/cli` | Headless `.fig` inspection, export, linting, `eval` | `packages/cli/AGENTS.md` |
@@ -44,7 +45,7 @@ Before a PR run `bun run check`, `bun run format`, `bun run test:unit`, and `bun
- Across package/app boundaries import the owning package's public exports, never workspace internals or forwarding-only shims. `@open-pencil/scene-graph` owns graph types and primitives; `@open-pencil/kiwi` owns low-level Kiwi/FIG helpers; `@open-pencil/core` provides the compatibility barrel plus the subpaths listed in `packages/core/package.json`.
- `bun run check:arch` enforces: public workspace exports, framework-neutral Core, no app services in views or shared UI, property-panel internals scoped to that panel.
-- Package aliases are `#core/*`, `#fig/*`, `#vue/*`, `#cli/*`, `#mcp/*`, `#dom-css/*`, `#design-jsx/*`; a package's own tests use `#core-tests/*` and `#fig-tests/*`; the app uses `@/`. Prefer clear relative imports nearby. Never escape an alias root with `../` (for example `#tests/../vite`); fix module ownership instead.
+- Package aliases are `#core/*`, `#fig/*`, `#vue/*`, `#cli/*`, `#mcp/*`, `#dom-css/*`, `#design-jsx/*`, `#codegen/*`; a package's own tests use `#core-tests/*` and `#fig-tests/*`; the app uses `@/`. Prefer clear relative imports nearby. Never escape an alias root with `../` (for example `#tests/../vite`); fix module ownership instead.
- Never drill with `../../`: one `../` to a sibling folder is fine, two or more means an alias. This holds in tests as much as in source — a test reaches its package's source through `#<pkg>/*` and its own helpers through `#<pkg>-tests/*`. `open-pencil/no-deep-parent-relative-imports` enforces it; a new test directory must be added to `lint:structure` so the rule reaches it.
- Reuse named types from `@open-pencil/scene-graph`; do not respell `Color`, `Vector`, `SceneNode`, `Effect`, `Fill`, or `Stroke`.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1113e57e4..b4f7dfeb8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,6 +32,7 @@
### Fixed
+- Keep line breaks in multi-line text when exporting OpenPencil JSX, so `get_jsx` output and `openpencil export -f jsx` render back to the same text instead of joining the lines with spaces.
- Announce unavailable commands in the command palette as disabled to screen readers.
- Keep the ordering keys a `.fig` gave its layers when saving one again, instead of renumbering every sibling, and give every layer on a canvas its own key. Shared styles, variables and the canvas's own layers were numbered in separate passes that each restarted, so Figma saw siblings claiming the same position and ordered them arbitrarily.
- Clear a `.fig` fill or stroke's colour-variable binding when you unbind it, instead of exporting the variable the layer was imported with and rebinding it on reopen. An emptied binding record is no longer written into the file either.
diff --git a/bun.lock b/bun.lock
index 0d2520c0e..67ed695a1 100644
--- a/bun.lock
+++ b/bun.lock
@@ -183,6 +183,20 @@
"@types/bun": "^1.3.14",
},
},
+ "packages/codegen": {
+ "name": "@open-pencil/codegen",
+ "version": "0.15.1",
+ "dependencies": {
+ "@sveltejs/acorn-typescript": "^1.0.13",
+ "acorn": "^8.18.0",
+ "esrap": "^2.3.11",
+ },
+ "devDependencies": {
+ "@types/bun": "^1.3.14",
+ "tsdown": "^0.22.14",
+ "typescript": "~5.8.3",
+ },
+ },
"packages/core": {
"name": "@open-pencil/core",
"version": "0.15.1",
@@ -241,6 +255,7 @@
"dependencies": {
"@lezer/common": "^1.5.2",
"@lezer/javascript": "^1.5.4",
+ "@open-pencil/codegen": "workspace:*",
"acorn": "^8.18.0",
"dedent": "^1.7.2",
"entities": "^8.0.0",
@@ -279,11 +294,9 @@
"version": "0.15.1",
"dependencies": {
"@acemir/cssom": "^0.9.31",
- "@sveltejs/acorn-typescript": "^1.0.13",
- "acorn": "^8.18.0",
+ "@open-pencil/codegen": "workspace:*",
"dedent": "^1.7.2",
"es-toolkit": "^1.51.0",
- "esrap": "^2.3.11",
"js-base64": "^3.9.3",
"parse5": "^8.0.1",
"postcss-value-parser": "^4.2.0",
@@ -1429,6 +1442,8 @@
"@open-pencil/cli": ["@open-pencil/cli@workspace:packages/cli"],
+ "@open-pencil/codegen": ["@open-pencil/codegen@workspace:packages/codegen"],
+
"@open-pencil/core": ["@open-pencil/core@workspace:packages/core"],
"@open-pencil/design-jsx": ["@open-pencil/design-jsx@workspace:packages/design-jsx"],
diff --git a/package.json b/package.json
index 864e784ec..95f7ad669 100644
--- a/package.json
+++ b/package.json
@@ -11,6 +11,7 @@
"packages/core",
"packages/dom-css",
"packages/design-jsx",
+ "packages/codegen",
"packages/vue",
"packages/cli",
"packages/mcp",
@@ -50,9 +51,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/dom-css/src/ packages/pen/src/ packages/design-jsx/src/ packages/kiwi/src/ packages/fig/src/",
- "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/harness/src/ packages/harness/tests/ packages/dom-css/src/ packages/dom-css/tests/ packages/dom-css/scripts/ packages/pen/src/ packages/pen/scripts/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/design-jsx/scripts/ packages/kiwi/src/ packages/kiwi/tests/ packages/kiwi/scripts/ packages/fig/src/ packages/fig/tests/ packages/fig/scripts/ packages/core/tests/ packages/scene-graph/tests/ packages/vue/tests/ tests/ scripts/ tools/",
- "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/harness/src/ packages/harness/tests/ packages/vue/src/ packages/dom-css/src/ packages/dom-css/tests/ packages/dom-css/scripts/ packages/pen/src/ packages/pen/scripts/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/design-jsx/scripts/ packages/kiwi/src/ packages/kiwi/tests/ packages/kiwi/scripts/ packages/fig/src/ packages/fig/tests/ packages/fig/scripts/ tests scripts/ tools/",
+ "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/dom-css/src/ packages/pen/src/ packages/design-jsx/src/ packages/codegen/src/ packages/kiwi/src/ packages/fig/src/",
+ "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/harness/src/ packages/harness/tests/ packages/dom-css/src/ packages/dom-css/tests/ packages/dom-css/scripts/ packages/pen/src/ packages/pen/scripts/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/design-jsx/scripts/ packages/codegen/src/ packages/codegen/tests/ packages/codegen/scripts/ packages/kiwi/src/ packages/kiwi/tests/ packages/kiwi/scripts/ packages/fig/src/ packages/fig/tests/ packages/fig/scripts/ packages/core/tests/ packages/scene-graph/tests/ packages/vue/tests/ tests/ scripts/ tools/",
+ "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/harness/src/ packages/harness/tests/ packages/vue/src/ packages/dom-css/src/ packages/dom-css/tests/ packages/dom-css/scripts/ packages/pen/src/ packages/pen/scripts/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/design-jsx/scripts/ packages/codegen/src/ packages/codegen/tests/ packages/codegen/scripts/ packages/kiwi/src/ packages/kiwi/tests/ packages/kiwi/scripts/ packages/fig/src/ packages/fig/tests/ packages/fig/scripts/ tests scripts/ tools/",
"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 test:type-shapes && bun run check:tools && bun run test:tools && bun run test:dupes",
"check:commits": "commitlint",
@@ -84,7 +85,7 @@
"test:coverage": "bun tools/dev/unit-tests/src/run.ts all --include-heavy -- --coverage",
"test:type-shapes": "bun tools/checks/type-shapes/src/index.ts",
"test:tools": "bun --filter '@open-pencil/*-tools' test && bun --filter @open-pencil/harness test",
- "test:dupes": "jscpd packages/scene-graph/src packages/pen/src packages/design-jsx/src packages/core/src packages/cli/src packages/dom-css/src packages/fig/src src --min-lines 5 --min-tokens 50 --format typescript --threshold 0",
+ "test:dupes": "jscpd packages/scene-graph/src packages/pen/src packages/design-jsx/src packages/codegen/src packages/core/src packages/cli/src packages/dom-css/src packages/fig/src src --min-lines 5 --min-tokens 50 --format typescript --threshold 0",
"test:packages": "bun tools/checks/package-quality/src/cli.ts verify",
"build:packages": "bun tools/release/package-artifacts/src/build.ts",
"open-pencil": "bun packages/cli/src/index.ts",
diff --git a/packages/codegen/README.md b/packages/codegen/README.md
new file mode 100644
index 000000000..1cc242013
--- /dev/null
+++ b/packages/codegen/README.md
@@ -0,0 +1,29 @@
+# @open-pencil/codegen
+
+Syntax-tree code generation for OpenPencil's exporters. Build JavaScript, TypeScript, and JSX as ESTree nodes and print them with [esrap](https://github.com/sveltejs/esrap), instead of concatenating strings.
+
+```ts
+import { jsx } from '@open-pencil/codegen'
+
+const card = jsx.element(
+ 'Card',
+ [jsx.attribute('title', jsx.stringValue('Fish & chips'))],
+ [jsx.text('Hello')],
+ 0,
+ true
+)
+jsx.printJSX(card) // <Card title={"Fish & chips"}>Hello</Card>
+```
+
+`jsx.stringValue` and `jsx.text` keep a value as plain JSX only when JSX reads it back unchanged; anything with quotes, entities, braces, angle brackets, backslashes, or line breaks becomes a string literal.
+
+`es` parses TypeScript templates, fills `$name` placeholders, and prints modules:
+
+```ts
+import { es } from '@open-pencil/codegen'
+
+const module = es.fill(es.parseModule("export const title = '$title'"), {
+ $title: es.string('Checkout')
+})
+es.printModule(module) // export const title = 'Checkout';
+```
diff --git a/packages/codegen/package.json b/packages/codegen/package.json
new file mode 100644
index 000000000..2a65c64c1
--- /dev/null
+++ b/packages/codegen/package.json
@@ -0,0 +1,56 @@
+{
+ "name": "@open-pencil/codegen",
+ "version": "0.15.1",
+ "license": "MIT",
+ "type": "module",
+ "description": "Syntax-tree code generation for OpenPencil exporters: JavaScript, TypeScript, and JSX built as ESTree and printed with esrap.",
+ "imports": {
+ "#codegen/*": {
+ "types": "./src/*",
+ "bun": "./src/*",
+ "default": "./dist/*"
+ }
+ },
+ "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 && bun run smoke:dist",
+ "prepack": "bun run build",
+ "smoke:dist": "bun scripts/smoke-dist.ts",
+ "typecheck": "bunx tsc --noEmit -p tsconfig.json"
+ },
+ "dependencies": {
+ "@sveltejs/acorn-typescript": "^1.0.13",
+ "acorn": "^8.18.0",
+ "esrap": "^2.3.11"
+ },
+ "devDependencies": {
+ "@types/bun": "^1.3.14",
+ "tsdown": "^0.22.14",
+ "typescript": "~5.8.3"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/open-pencil/open-pencil.git",
+ "directory": "packages/codegen"
+ },
+ "publishConfig": {
+ "access": "public",
+ "provenance": true
+ }
+}
diff --git a/packages/codegen/scripts/smoke-dist.ts b/packages/codegen/scripts/smoke-dist.ts
new file mode 100644
index 000000000..7311586c9
--- /dev/null
+++ b/packages/codegen/scripts/smoke-dist.ts
@@ -0,0 +1,11 @@
+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 codegen package to print JSX and modules')
+}
diff --git a/packages/dom-css/src/export/storybook/estree.ts b/packages/codegen/src/estree.ts
similarity index 100%
rename from packages/dom-css/src/export/storybook/estree.ts
rename to packages/codegen/src/estree.ts
diff --git a/packages/codegen/src/index.ts b/packages/codegen/src/index.ts
new file mode 100644
index 000000000..7ffd8569d
--- /dev/null
+++ b/packages/codegen/src/index.ts
@@ -0,0 +1,3 @@
+export * as es from './estree'
+export * as jsx from './jsx'
+export type { SyntaxNode } from './estree'
diff --git a/packages/codegen/src/jsx.ts b/packages/codegen/src/jsx.ts
new file mode 100644
index 000000000..aa88329cc
--- /dev/null
+++ b/packages/codegen/src/jsx.ts
@@ -0,0 +1,84 @@
+import { print } from 'esrap'
+import tsx from 'esrap/languages/tsx'
+
+import type { SyntaxNode } from './estree'
+
+/**
+ * JSX attribute strings end at `"`, decode `&` entities, and keep backslashes literally,
+ * so the printer's escapes for backslashes and line breaks would change the value. JSX
+ * text also treats braces and angle brackets as syntax and trims whitespace at line
+ * edges. Anything else is written as a string literal, which the printer escapes.
+ */
+const LITERAL_ATTRIBUTE = /^[^"&\\\r\n]*$/
+const LITERAL_TEXT = /^[^{}<>&\r\n]*$/
+
+export const identifier = (name: string): SyntaxNode => ({ type: 'JSXIdentifier', name })
+
+export const literal = (value: string | number | boolean): SyntaxNode => ({
+ type: 'Literal',
+ value
+})
+
+export const container = (expression: SyntaxNode): SyntaxNode => ({
+ type: 'JSXExpressionContainer',
+ expression
+})
+
+/** Raw JSX text, printed as is. */
+export const whitespace = (value: string): SyntaxNode => ({ type: 'JSXText', value, raw: value })
+
+/** A string attribute value: quoted when JSX keeps it as written, an expression otherwise. */
+export const stringValue = (value: string): SyntaxNode =>
+ LITERAL_ATTRIBUTE.test(value) ? literal(value) : container(literal(value))
+
+/** An attribute; a null value prints the bare name, as for `true`. */
+export const attribute = (name: string, value: SyntaxNode | null): SyntaxNode => ({
+ type: 'JSXAttribute',
+ name: identifier(name),
+ value
+})
+
+/** Text content: plain JSX text when it survives as written, a string expression otherwise. */
+export function text(value: string): SyntaxNode {
+ const plain = LITERAL_TEXT.test(value) && value.trim() === value && value.length > 0
+ return plain ? whitespace(value) : container(literal(value))
+}
+
+/** Children on their own lines; JSX drops whitespace-only lines between elements. */
+function indented(children: SyntaxNode[], depth: number): SyntaxNode[] {
+ const inner = `\n${' '.repeat(depth + 1)}`
+ return [
+ ...children.flatMap((child) => [whitespace(inner), child]),
+ whitespace(`\n${' '.repeat(depth)}`)
+ ]
+}
+
+/**
+ * An element at nesting `depth`. Children go on their own lines unless `inline`, as for a
+ * lone text child; without children the element self-closes.
+ */
+export function element(
+ tag: string,
+ attributes: SyntaxNode[],
+ children: SyntaxNode[],
+ depth: number,
+ inline = false
+): SyntaxNode {
+ const name = identifier(tag)
+ const content = inline || children.length === 0 ? children : indented(children, depth)
+ return {
+ type: 'JSXElement',
+ openingElement: {
+ type: 'JSXOpeningElement',
+ name,
+ attributes,
+ selfClosing: content.length === 0
+ },
+ closingElement: content.length > 0 ? { type: 'JSXClosingElement', name } : null,
+ children: content
+ }
+}
+
+export function printJSX(node: SyntaxNode): string {
+ return print(node, tsx({ quotes: 'double' }), { indent: ' ' }).code
+}
diff --git a/packages/codegen/tests/jsx.test.ts b/packages/codegen/tests/jsx.test.ts
new file mode 100644
index 000000000..34ec69077
--- /dev/null
+++ b/packages/codegen/tests/jsx.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, test } from 'bun:test'
+
+import { jsx } from '#codegen/index'
+
+const card = (attributes: ReturnType<typeof jsx.attribute>[], children = [jsx.text('Hi')]) =>
+ jsx.printJSX(jsx.element('Card', attributes, children, 0, true))
+
+describe('JSX attributes', () => {
+ test('keep plain strings quoted', () => {
+ expect(card([jsx.attribute('title', jsx.stringValue('Plain name'))])).toBe(
+ '<Card title="Plain name">Hi</Card>'
+ )
+ })
+
+ test.each(['a" w={999} x="', 'Fish &amp; chips', 'Back\\slash', 'Two\nlines'])(
+ 'write %p as a string literal JSX cannot reinterpret',
+ (value) => {
+ const code = card([jsx.attribute('title', jsx.stringValue(value))])
+ expect(code).toBe(`<Card title={${JSON.stringify(value)}}>Hi</Card>`)
+ }
+ )
+
+ test('print a null value as the bare name', () => {
+ expect(card([jsx.attribute('wide', null)], [])).toBe('<Card wide />')
+ })
+})
+
+describe('JSX text', () => {
+ test('keeps plain text as text', () => {
+ expect(card([], [jsx.text('Hello')])).toBe('<Card>Hello</Card>')
+ })
+
+ test.each(['{braces}', '<tag>', 'a & b', 'one\ntwo', ' padded '])(
+ 'writes %p as a string expression',
+ (value) => {
+ expect(card([], [jsx.text(value)])).toBe(`<Card>{${JSON.stringify(value)}}</Card>`)
+ }
+ )
+})
+
+describe('JSX elements', () => {
+ test('put children on indented lines', () => {
+ const child = jsx.element('Item', [], [], 1)
+ expect(jsx.printJSX(jsx.element('List', [], [child, child], 0))).toBe(
+ '<List>\n <Item />\n <Item />\n</List>'
+ )
+ })
+})
diff --git a/packages/codegen/tsconfig.json b/packages/codegen/tsconfig.json
new file mode 100644
index 000000000..c7d414f42
--- /dev/null
+++ b/packages/codegen/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": {
+ "#codegen/*": ["./src/*"],
+ "@open-pencil/codegen": ["./src/index.ts"]
+ }
+ },
+ "include": ["src/**/*.ts"],
+ "exclude": ["node_modules", "dist"]
+}
diff --git a/packages/codegen/tsdown.config.ts b/packages/codegen/tsdown.config.ts
new file mode 100644
index 000000000..19391dd50
--- /dev/null
+++ b/packages/codegen/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: [/^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/core/tests/design-jsx/export-round-trip.test.ts b/packages/core/tests/design-jsx/export-round-trip.test.ts
new file mode 100644
index 000000000..fb0a4f9ac
--- /dev/null
+++ b/packages/core/tests/design-jsx/export-round-trip.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'bun:test'
+
+import { renderJSX } from '@open-pencil/core/design-jsx'
+import { sceneNodeToJSX } from '@open-pencil/design-jsx'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { getNodeOrThrow } from '../helpers/assert'
+
+describe('attribute string round-trip', () => {
+ it.each([
+ // Unescaped, this name would inject `w={999}` into the exported frame.
+ 'a" w={999} x="',
+ 'Fish &amp; chips',
+ 'Back\\slash',
+ 'Two\nlines',
+ 'Tab\there',
+ 'Plain name'
+ ])('keeps the layer name %p', async (name) => {
+ const g = new SceneGraph()
+ const [source] = await renderJSX(g, '<Frame w={10} h={10} />')
+ getNodeOrThrow(g, source.id).name = name
+ const [result] = await renderJSX(g, sceneNodeToJSX(source.id, g))
+ expect(getNodeOrThrow(g, result.id)).toMatchObject({ name, width: 10 })
+ })
+})
+
+describe('text content round-trip', () => {
+ it.each([
+ 'Curly {braces} and <tags>',
+ 'Fish &amp; chips',
+ 'Line one\nLine two',
+ ' padded ',
+ 'Back\\slash',
+ 'Tab\there'
+ ])('keeps the text %p', async (text) => {
+ const g = new SceneGraph()
+ const [source] = await renderJSX(g, '<Text color="#000">Placeholder</Text>')
+ getNodeOrThrow(g, source.id).text = text
+ const [result] = await renderJSX(g, sceneNodeToJSX(source.id, g))
+ expect(getNodeOrThrow(g, result.id).text).toBe(text)
+ })
+})
diff --git a/packages/design-jsx/AGENTS.md b/packages/design-jsx/AGENTS.md
index 3845ef594..fd8381460 100644
--- a/packages/design-jsx/AGENTS.md
+++ b/packages/design-jsx/AGENTS.md
@@ -4,7 +4,8 @@ OpenPencil's design JSX: the elements (`Frame`, `Text`, …) and the trees they
Rules:
-- Depend only on `@open-pencil/scene-graph`. Engine work the renderer needs — icon lookup, SVG path conversion, vector node creation, and layout — comes in through `DesignJSXServices` (`src/services.ts`). Core binds them in `packages/core/src/design-jsx/renderer.ts` and exports the bound `renderJSX` and `renderTree` from `@open-pencil/core/design-jsx`.
+- Depend only on `@open-pencil/scene-graph` and `@open-pencil/codegen`. Engine work the renderer needs — icon lookup, SVG path conversion, vector node creation, and layout — comes in through `DesignJSXServices` (`src/services.ts`). Core binds them in `packages/core/src/design-jsx/renderer.ts` and exports the bound `renderJSX` and `renderTree` from `@open-pencil/core/design-jsx`.
- `src/streaming/` parses JSX as it streams in and projects the static subset into trees without evaluating expressions; Core's `packages/core/src/design-jsx/preview/` stages and records those trees on the canvas.
+- JSX export (`src/export/`) collects typed props in `props.ts` and prints them with `@open-pencil/codegen`'s JSX builders; never build JSX from string fragments.
- `src/reference/authoring.md` is the source of the shared authoring reference. Run `bun run generate:authoring-reference` after changing it or the schema; never edit the generated copies.
- Tests that need icons, layout, or the bound renderer live in `packages/core/tests/design-jsx` (existing ones still in `tests/engine/render/jsx`); tests of trees, parsing, schema, and export live in `packages/design-jsx/tests`.
diff --git a/packages/design-jsx/README.md b/packages/design-jsx/README.md
index bc1c00f1c..94a9364d5 100644
--- a/packages/design-jsx/README.md
+++ b/packages/design-jsx/README.md
@@ -27,4 +27,4 @@ import { renderJSX } from '@open-pencil/core/design-jsx'
await renderJSX(graph, '<Frame w={320} p={16} bg="#FFFFFF"><Text>Hello</Text></Frame>')
```
-This package depends only on `@open-pencil/scene-graph`. Rendering needs icons, SVG conversion, and layout, which `@open-pencil/core/design-jsx` provides; other engines can supply their own through `createDesignJSXRenderer(services)`.
+This package depends only on `@open-pencil/scene-graph` and `@open-pencil/codegen`. Rendering needs icons, SVG conversion, and layout, which `@open-pencil/core/design-jsx` provides; other engines can supply their own through `createDesignJSXRenderer(services)`.
diff --git a/packages/design-jsx/package.json b/packages/design-jsx/package.json
index 15c68740b..d5fc47346 100644
--- a/packages/design-jsx/package.json
+++ b/packages/design-jsx/package.json
@@ -60,6 +60,7 @@
"dependencies": {
"@lezer/common": "^1.5.2",
"@lezer/javascript": "^1.5.4",
+ "@open-pencil/codegen": "workspace:*",
"acorn": "^8.18.0",
"dedent": "^1.7.2",
"entities": "^8.0.0",
diff --git a/packages/design-jsx/src/export/helpers.ts b/packages/design-jsx/src/export/helpers.ts
index e7be5dba7..deb4faac7 100644
--- a/packages/design-jsx/src/export/helpers.ts
+++ b/packages/design-jsx/src/export/helpers.ts
@@ -37,32 +37,6 @@ export function formatShadow(e: Effect): string | null {
return `${e.offset.x} ${e.offset.y} ${e.radius} ${formatColor(e.color, e.color.a)}`
}
-const JSX_ENTITY: Record<string, string> = {
- '{': '&#123;',
- '}': '&#125;',
- '<': '&lt;',
- '>': '&gt;',
- '&': '&amp;'
-}
-
-export function escapeJSXText(text: string): string {
- return text.replace(/[{}<>&]/g, (c) => JSX_ENTITY[c])
-}
-
-/**
- * JSX attribute strings end at `"` and decode `&` entities, so other strings become
- * expression containers with a JavaScript string literal.
- */
-const LITERAL_ATTRIBUTE = /^[^"&]*$/
-
-export function formatProp(key: string, value: unknown): string {
- if (typeof value === 'string')
- return LITERAL_ATTRIBUTE.test(value) ? `${key}="${value}"` : `${key}={${JSON.stringify(value)}}`
- if (typeof value === 'number') return `${key}={${value}}`
- if (typeof value === 'boolean') return value ? key : `${key}={false}`
- return `${key}={${JSON.stringify(value)}}`
-}
-
export function getNodeContext(node: SceneNode, graph: SceneGraph) {
const parent = node.parentId ? graph.getNode(node.parentId) : null
return {
diff --git a/packages/design-jsx/src/export/index.ts b/packages/design-jsx/src/export/index.ts
index e8e4ebb22..b4ea83f19 100644
--- a/packages/design-jsx/src/export/index.ts
+++ b/packages/design-jsx/src/export/index.ts
@@ -1,324 +1,43 @@
-import type { SceneGraph, SceneNode, NodeType } from '@open-pencil/scene-graph'
-import { DEFAULT_FONT_FAMILY } from '@open-pencil/scene-graph/constants'
-import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
+import { jsx, type SyntaxNode } from '@open-pencil/codegen'
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-import {
- collectCornerRadii,
- collectPadding,
- emitPadding,
- escapeJSXText,
- formatProp,
- formatShadow,
- formatTracks,
- getNodeContext,
- solidFillColor,
- solidStroke
-} from './helpers'
+import { collectProps, NODE_TYPE_TO_TAG, type JSXProp } from './props'
-const NODE_TYPE_TO_TAG: Partial<Record<NodeType, string>> = {
- FRAME: 'Frame',
- RECTANGLE: 'Rectangle',
- ROUNDED_RECTANGLE: 'Rectangle',
- ELLIPSE: 'Ellipse',
- TEXT: 'Text',
- LINE: 'Line',
- STAR: 'Star',
- POLYGON: 'Polygon',
- VECTOR: 'Vector',
- GROUP: 'Group',
- SECTION: 'Section',
- COMPONENT: 'Component',
- COMPONENT_SET: 'Frame',
- INSTANCE: 'Frame'
-}
-
-// --- OpenPencil format helpers ---
-
-function collectGridSizingProps(node: SceneNode, props: [string, unknown][]): void {
- props.push(['grid', true])
- if (node.gridTemplateColumns.length > 0)
- props.push(['columns', formatTracks(node.gridTemplateColumns)])
- if (node.gridTemplateRows.length > 0) props.push(['rows', formatTracks(node.gridTemplateRows)])
- if (node.width > 0) props.push(['w', node.width])
- if (node.gridTemplateRows.length > 0 && node.height > 0) props.push(['h', node.height])
- if (node.gridColumnGap > 0) props.push(['columnGap', node.gridColumnGap])
- if (node.gridRowGap > 0) props.push(['rowGap', node.gridRowGap])
-}
-
-function collectFlexSizingProps(node: SceneNode, props: [string, unknown][]): void {
- props.push(['flex', node.layoutMode === 'HORIZONTAL' ? 'row' : 'col'])
- if (node.layoutDirection === 'RTL') props.push(['dir', 'rtl'])
- const primaryAxis = node.layoutMode === 'HORIZONTAL' ? 'width' : 'height'
- const crossAxis = node.layoutMode === 'HORIZONTAL' ? 'height' : 'width'
-
- if (node.primaryAxisSizing === 'FILL') props.push([primaryAxis === 'width' ? 'w' : 'h', 'fill'])
- else if (node.primaryAxisSizing !== 'HUG')
- props.push([primaryAxis === 'width' ? 'w' : 'h', node[primaryAxis]])
-
- if (node.counterAxisSizing === 'FILL') props.push([crossAxis === 'width' ? 'w' : 'h', 'fill'])
- else if (node.counterAxisSizing !== 'HUG')
- props.push([crossAxis === 'width' ? 'w' : 'h', node[crossAxis]])
-}
-
-function collectGridPositionProps(node: SceneNode, props: [string, unknown][]): void {
- if (!node.gridPosition) return
- const pos = node.gridPosition
- if (pos.column > 0) props.push(['colStart', pos.column])
- if (pos.row > 0) props.push(['rowStart', pos.row])
- if (pos.columnSpan > 1) props.push(['colSpan', pos.columnSpan])
- if (pos.rowSpan > 1) props.push(['rowSpan', pos.rowSpan])
-}
-
-function collectFlexAlignmentProps(node: SceneNode, props: [string, unknown][]): void {
- if (node.itemSpacing > 0) props.push(['gap', node.itemSpacing])
-
- if (node.layoutWrap === 'WRAP') {
- props.push(['wrap', true])
- if (node.counterAxisSpacing > 0) props.push(['rowGap', node.counterAxisSpacing])
- }
-
- if (node.primaryAxisAlign === 'CENTER') props.push(['justify', 'center'])
- else if (node.primaryAxisAlign === 'MAX') props.push(['justify', 'end'])
- else if (node.primaryAxisAlign === 'SPACE_BETWEEN') props.push(['justify', 'between'])
-
- if (node.counterAxisAlign === 'CENTER') props.push(['items', 'center'])
- else if (node.counterAxisAlign === 'MAX') props.push(['items', 'end'])
- else if (node.counterAxisAlign === 'STRETCH') props.push(['items', 'stretch'])
-}
-
-function collectAutoLayoutPaddingProps(node: SceneNode, props: [string, unknown][]): void {
- const pad = collectPadding(node)
- if (!pad) return
- props.push(
- ...emitPadding(
- pad,
- (v) => ['p', v] as [string, unknown],
- (y, x) =>
- [
- ['py', y],
- ['px', x]
- ] as [string, unknown][],
- ({ pt, pr, pb, pl }) => {
- const r: [string, unknown][] = []
- if (pt > 0) r.push(['pt', pt])
- if (pr > 0) r.push(['pr', pr])
- if (pb > 0) r.push(['pb', pb])
- if (pl > 0) r.push(['pl', pl])
- return r
- }
- )
- )
-}
-
-function collectCornerRadiiProps(node: SceneNode, props: [string, unknown][]): void {
- const corners = collectCornerRadii(node)
- if (!corners) return
- const { tl, tr, br, bl } = corners
- if (tl === tr && tr === br && br === bl) {
- props.push(['rounded', tl])
- } else {
- if (tl > 0) props.push(['roundedTL', tl])
- if (tr > 0) props.push(['roundedTR', tr])
- if (br > 0) props.push(['roundedBR', br])
- if (bl > 0) props.push(['roundedBL', bl])
- }
-}
-
-function collectAppearanceProps(node: SceneNode, props: [string, unknown][]): void {
- const bg = solidFillColor(node.fills)
- if (bg) props.push(['bg', bg])
-
- const stroke = solidStroke(node.strokes)
- if (stroke) {
- props.push(['stroke', stroke.color])
- if (stroke.weight !== 1) props.push(['strokeWidth', stroke.weight])
- if (stroke.dash) props.push(['strokeDash', stroke.dash])
- }
-
- collectCornerRadiiProps(node, props)
-
- if (node.cornerSmoothing > 0) props.push(['cornerSmoothing', node.cornerSmoothing])
- if (node.opacity < 1) props.push(['opacity', Math.round(node.opacity * 100) / 100])
- if (node.rotation !== 0) props.push(['rotate', Math.round(node.rotation * 100) / 100])
- if (node.blendMode !== 'PASS_THROUGH' && node.blendMode !== 'NORMAL') {
- props.push(['blendMode', node.blendMode.toLowerCase()])
- }
- if (node.clipsContent) props.push(['overflow', 'hidden'])
-
- for (const effect of node.effects) {
- if (!effect.visible) continue
- if (effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW') {
- const shadow = formatShadow(effect)
- if (shadow) props.push(['shadow', shadow])
- } else if (effect.type === 'LAYER_BLUR' || effect.type === 'BACKGROUND_BLUR') {
- props.push(['blur', effect.radius])
- }
- }
-}
-
-function collectPositionProps(
- node: SceneNode,
- ctx: ReturnType<typeof getNodeContext>,
- props: [string, unknown][]
-): void {
- if (ctx.parentIsAutoLayout || ctx.parentIsGrid) return
- if (node.x !== 0) props.push(['x', node.x])
- if (node.y !== 0) props.push(['y', node.y])
-}
-
-function collectSizingProps(
- node: SceneNode,
- ctx: ReturnType<typeof getNodeContext>,
- graph: SceneGraph,
- props: [string, unknown][]
-): void {
- if (ctx.isGrid) collectGridSizingProps(node, props)
- else if (ctx.isFlex) collectFlexSizingProps(node, props)
- else if (node.type === 'TEXT') collectTextSizingProps(node, graph, props)
- else {
- if (node.width > 0) props.push(['w', node.width])
- if (node.height > 0) props.push(['h', node.height])
+function propValue(value: JSXProp[1]): SyntaxNode | null {
+ if (value === true) return null
+ if (typeof value === 'string') return jsx.stringValue(value)
+ if (Array.isArray(value)) {
+ return jsx.container({
+ type: 'ArrayExpression',
+ elements: value.map((item) => jsx.literal(item))
+ })
}
-
- if (!ctx.parentIsAutoLayout) return
- if (node.layoutGrow > 0) props.push(['grow', node.layoutGrow])
- if (node.layoutAlignSelf === 'STRETCH') {
- const parent = node.parentId ? graph.getNode(node.parentId) : null
- if (parent && (parent.layoutMode === 'HORIZONTAL' || parent.layoutMode === 'VERTICAL')) {
- const crossDim = parent.layoutMode === 'HORIZONTAL' ? 'h' : 'w'
- if (!props.some(([k]) => k === crossDim)) props.push([crossDim, 'fill'])
- }
- }
-}
-
-function collectTextSizingProps(
- node: SceneNode,
- graph: SceneGraph,
- props: [string, unknown][]
-): void {
- const autoResize = node.textAutoResize
- const emitH = autoResize === 'NONE' || autoResize === 'TRUNCATE'
- // Don't emit fixed w when text stretches to fill parent — the layoutAlignSelf
- // check below will emit w="fill" instead. Without this guard, w={computedPx}
- // gets emitted first and blocks the fill detection.
- const isFillWidth =
- node.layoutAlignSelf === 'STRETCH' &&
- (() => {
- const parent = node.parentId ? graph.getNode(node.parentId) : null
- return parent?.layoutMode === 'VERTICAL'
- })()
- const isGrowWidth =
- node.layoutGrow > 0 &&
- (() => {
- const parent = node.parentId ? graph.getNode(node.parentId) : null
- return parent?.layoutMode === 'HORIZONTAL'
- })()
- const emitW = autoResize !== 'WIDTH_AND_HEIGHT' && !isFillWidth && !isGrowWidth
- if (emitW && node.width > 0) props.push(['w', node.width])
- if (emitH && node.height > 0) props.push(['h', node.height])
+ return jsx.container(jsx.literal(value))
}
-function collectTextNodeProps(node: SceneNode, props: [string, unknown][]): void {
- const direction = resolveNodeTextDirection(node)
- if (node.fontSize !== 14) props.push(['size', node.fontSize])
- if (node.fontFamily && node.fontFamily !== DEFAULT_FONT_FAMILY)
- props.push(['font', node.fontFamily])
- if (node.fontWeight !== 400) {
- if (node.fontWeight === 700) props.push(['weight', 'bold'])
- else if (node.fontWeight === 500) props.push(['weight', 'medium'])
- else props.push(['weight', node.fontWeight])
- }
- if (direction === 'RTL') props.push(['dir', 'rtl'])
- if (node.textAlignHorizontal !== 'LEFT') {
- props.push(['textAlign', node.textAlignHorizontal.toLowerCase()])
- }
- if (node.lineHeight != null) props.push(['lineHeight', node.lineHeight])
- if (node.letterSpacing !== 0) props.push(['letterSpacing', node.letterSpacing])
- if (node.textDecoration !== 'NONE')
- props.push(['textDecoration', node.textDecoration.toLowerCase()])
- if (node.textCase !== 'ORIGINAL') props.push(['textCase', node.textCase.toLowerCase()])
- if (node.maxLines != null) props.push(['maxLines', node.maxLines])
- if (node.textTruncation === 'ENDING' && node.maxLines == null) props.push(['truncate', true])
- const textColor = solidFillColor(node.fills)
- if (textColor) {
- const bgIdx = props.findIndex(([k]) => k === 'bg')
- if (bgIdx !== -1) props.splice(bgIdx, 1)
- props.push(['color', textColor])
- }
-}
-
-function collectShapeNodeProps(node: SceneNode, props: [string, unknown][]): void {
- if (node.type === 'STAR') {
- if (node.pointCount !== 5) props.push(['points', node.pointCount])
- if (node.starInnerRadius !== 0.382) props.push(['innerRadius', node.starInnerRadius])
- }
- if (node.type === 'POLYGON' && node.pointCount !== 3) {
- props.push(['points', node.pointCount])
- }
+/** A prop as a JSX attribute: `true` prints the bare name, other values as typed literals. */
+function propAttribute([name, value]: JSXProp): SyntaxNode {
+ return jsx.attribute(name, propValue(value))
}
-function collectProps(node: SceneNode, graph: SceneGraph): [string, unknown][] {
- const props: [string, unknown][] = []
- const ctx = getNodeContext(node, graph)
-
- if (node.name && node.name !== node.type) props.push(['name', node.name])
-
- collectPositionProps(node, ctx, props)
- collectSizingProps(node, ctx, graph, props)
- if (ctx.parentIsGrid) collectGridPositionProps(node, props)
- if (ctx.isFlex) collectFlexAlignmentProps(node, props)
- if (ctx.isAutoLayout) collectAutoLayoutPaddingProps(node, props)
- collectAppearanceProps(node, props)
- if (node.type === 'TEXT') collectTextNodeProps(node, props)
- collectShapeNodeProps(node, props)
-
- return props
-}
-
-// --- JSX rendering ---
-
-function nodeToJSX(node: SceneNode, graph: SceneGraph, indent: number): string {
+function nodeToJSX(node: SceneNode, graph: SceneGraph, depth: number): SyntaxNode | null {
const tag = NODE_TYPE_TO_TAG[node.type]
- if (!tag) return ''
-
- const prefix = ' '.repeat(indent)
- const attrsStr = collectProps(node, graph)
- .map(([k, v]) => formatProp(k, v))
- .join(' ')
-
- const opening = attrsStr ? `<${tag} ${attrsStr}` : `<${tag}`
- const children = graph.getChildren(node.id)
-
+ if (!tag) return null
+ const attributes = collectProps(node, graph).map(propAttribute)
if (node.type === 'TEXT') {
- const text = node.text
- if (!text) return `${prefix}${opening} />`
- const escaped = escapeJSXText(text)
- if (!escaped.includes('\n')) {
- return `${prefix}${opening}>${escaped}</${tag}>`
- }
- return [
- `${prefix}${opening}>`,
- ...escaped.split('\n').map((l) => `${prefix} ${l}`),
- `${prefix}</${tag}>`
- ].join('\n')
+ return jsx.element(tag, attributes, node.text ? [jsx.text(node.text)] : [], depth, true)
}
-
- if (children.length === 0) return `${prefix}${opening} />`
-
- const childJSX = children
- .filter((c) => c.visible)
- .map((c) => nodeToJSX(c, graph, indent + 1))
- .filter(Boolean)
-
- if (childJSX.length === 0) return `${prefix}${opening} />`
-
- return [`${prefix}${opening}>`, ...childJSX, `${prefix}</${tag}>`].join('\n')
+ const children = graph
+ .getChildren(node.id)
+ .filter((child) => child.visible)
+ .flatMap((child) => nodeToJSX(child, graph, depth + 1) ?? [])
+ return jsx.element(tag, attributes, children, depth)
}
export function sceneNodeToJSX(nodeId: string, graph: SceneGraph): string {
const node = graph.getNode(nodeId)
- if (!node) return ''
- return nodeToJSX(node, graph, 0)
+ const syntax = node ? nodeToJSX(node, graph, 0) : null
+ return syntax ? jsx.printJSX(syntax) : ''
}
export function selectionToJSX(nodeIds: string[], graph: SceneGraph): string {
diff --git a/packages/design-jsx/src/export/props.ts b/packages/design-jsx/src/export/props.ts
new file mode 100644
index 000000000..d6db518d3
--- /dev/null
+++ b/packages/design-jsx/src/export/props.ts
@@ -0,0 +1,273 @@
+import type { SceneGraph, SceneNode, NodeType } from '@open-pencil/scene-graph'
+import { DEFAULT_FONT_FAMILY } from '@open-pencil/scene-graph/constants'
+import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
+
+import {
+ collectCornerRadii,
+ collectPadding,
+ emitPadding,
+ formatShadow,
+ formatTracks,
+ getNodeContext,
+ solidFillColor,
+ solidStroke
+} from './helpers'
+
+/** A prop name and its value: a string, number, boolean, or number list. */
+export type JSXProp = [name: string, value: string | number | boolean | number[]]
+
+/** The element that represents each node type; other types are not exported. */
+export const NODE_TYPE_TO_TAG: Partial<Record<NodeType, string>> = {
+ FRAME: 'Frame',
+ RECTANGLE: 'Rectangle',
+ ROUNDED_RECTANGLE: 'Rectangle',
+ ELLIPSE: 'Ellipse',
+ TEXT: 'Text',
+ LINE: 'Line',
+ STAR: 'Star',
+ POLYGON: 'Polygon',
+ VECTOR: 'Vector',
+ GROUP: 'Group',
+ SECTION: 'Section',
+ COMPONENT: 'Component',
+ COMPONENT_SET: 'Frame',
+ INSTANCE: 'Frame'
+}
+
+function collectGridSizingProps(node: SceneNode, props: JSXProp[]): void {
+ props.push(['grid', true])
+ if (node.gridTemplateColumns.length > 0)
+ props.push(['columns', formatTracks(node.gridTemplateColumns)])
+ if (node.gridTemplateRows.length > 0) props.push(['rows', formatTracks(node.gridTemplateRows)])
+ if (node.width > 0) props.push(['w', node.width])
+ if (node.gridTemplateRows.length > 0 && node.height > 0) props.push(['h', node.height])
+ if (node.gridColumnGap > 0) props.push(['columnGap', node.gridColumnGap])
+ if (node.gridRowGap > 0) props.push(['rowGap', node.gridRowGap])
+}
+
+function collectFlexSizingProps(node: SceneNode, props: JSXProp[]): void {
+ props.push(['flex', node.layoutMode === 'HORIZONTAL' ? 'row' : 'col'])
+ if (node.layoutDirection === 'RTL') props.push(['dir', 'rtl'])
+ const primaryAxis = node.layoutMode === 'HORIZONTAL' ? 'width' : 'height'
+ const crossAxis = node.layoutMode === 'HORIZONTAL' ? 'height' : 'width'
+
+ if (node.primaryAxisSizing === 'FILL') props.push([primaryAxis === 'width' ? 'w' : 'h', 'fill'])
+ else if (node.primaryAxisSizing !== 'HUG')
+ props.push([primaryAxis === 'width' ? 'w' : 'h', node[primaryAxis]])
+
+ if (node.counterAxisSizing === 'FILL') props.push([crossAxis === 'width' ? 'w' : 'h', 'fill'])
+ else if (node.counterAxisSizing !== 'HUG')
+ props.push([crossAxis === 'width' ? 'w' : 'h', node[crossAxis]])
+}
+
+function collectGridPositionProps(node: SceneNode, props: JSXProp[]): void {
+ if (!node.gridPosition) return
+ const pos = node.gridPosition
+ if (pos.column > 0) props.push(['colStart', pos.column])
+ if (pos.row > 0) props.push(['rowStart', pos.row])
+ if (pos.columnSpan > 1) props.push(['colSpan', pos.columnSpan])
+ if (pos.rowSpan > 1) props.push(['rowSpan', pos.rowSpan])
+}
+
+function collectFlexAlignmentProps(node: SceneNode, props: JSXProp[]): void {
+ if (node.itemSpacing > 0) props.push(['gap', node.itemSpacing])
+
+ if (node.layoutWrap === 'WRAP') {
+ props.push(['wrap', true])
+ if (node.counterAxisSpacing > 0) props.push(['rowGap', node.counterAxisSpacing])
+ }
+
+ if (node.primaryAxisAlign === 'CENTER') props.push(['justify', 'center'])
+ else if (node.primaryAxisAlign === 'MAX') props.push(['justify', 'end'])
+ else if (node.primaryAxisAlign === 'SPACE_BETWEEN') props.push(['justify', 'between'])
+
+ if (node.counterAxisAlign === 'CENTER') props.push(['items', 'center'])
+ else if (node.counterAxisAlign === 'MAX') props.push(['items', 'end'])
+ else if (node.counterAxisAlign === 'STRETCH') props.push(['items', 'stretch'])
+}
+
+function collectAutoLayoutPaddingProps(node: SceneNode, props: JSXProp[]): void {
+ const pad = collectPadding(node)
+ if (!pad) return
+ props.push(
+ ...emitPadding(
+ pad,
+ (v) => ['p', v] as JSXProp,
+ (y, x) =>
+ [
+ ['py', y],
+ ['px', x]
+ ] as JSXProp[],
+ ({ pt, pr, pb, pl }) => {
+ const r: JSXProp[] = []
+ if (pt > 0) r.push(['pt', pt])
+ if (pr > 0) r.push(['pr', pr])
+ if (pb > 0) r.push(['pb', pb])
+ if (pl > 0) r.push(['pl', pl])
+ return r
+ }
+ )
+ )
+}
+
+function collectCornerRadiiProps(node: SceneNode, props: JSXProp[]): void {
+ const corners = collectCornerRadii(node)
+ if (!corners) return
+ const { tl, tr, br, bl } = corners
+ if (tl === tr && tr === br && br === bl) {
+ props.push(['rounded', tl])
+ } else {
+ if (tl > 0) props.push(['roundedTL', tl])
+ if (tr > 0) props.push(['roundedTR', tr])
+ if (br > 0) props.push(['roundedBR', br])
+ if (bl > 0) props.push(['roundedBL', bl])
+ }
+}
+
+function collectAppearanceProps(node: SceneNode, props: JSXProp[]): void {
+ const bg = solidFillColor(node.fills)
+ if (bg) props.push(['bg', bg])
+
+ const stroke = solidStroke(node.strokes)
+ if (stroke) {
+ props.push(['stroke', stroke.color])
+ if (stroke.weight !== 1) props.push(['strokeWidth', stroke.weight])
+ if (stroke.dash) props.push(['strokeDash', stroke.dash])
+ }
+
+ collectCornerRadiiProps(node, props)
+
+ if (node.cornerSmoothing > 0) props.push(['cornerSmoothing', node.cornerSmoothing])
+ if (node.opacity < 1) props.push(['opacity', Math.round(node.opacity * 100) / 100])
+ if (node.rotation !== 0) props.push(['rotate', Math.round(node.rotation * 100) / 100])
+ if (node.blendMode !== 'PASS_THROUGH' && node.blendMode !== 'NORMAL') {
+ props.push(['blendMode', node.blendMode.toLowerCase()])
+ }
+ if (node.clipsContent) props.push(['overflow', 'hidden'])
+
+ for (const effect of node.effects) {
+ if (!effect.visible) continue
+ if (effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW') {
+ const shadow = formatShadow(effect)
+ if (shadow) props.push(['shadow', shadow])
+ } else if (effect.type === 'LAYER_BLUR' || effect.type === 'BACKGROUND_BLUR') {
+ props.push(['blur', effect.radius])
+ }
+ }
+}
+
+function collectPositionProps(
+ node: SceneNode,
+ ctx: ReturnType<typeof getNodeContext>,
+ props: JSXProp[]
+): void {
+ if (ctx.parentIsAutoLayout || ctx.parentIsGrid) return
+ if (node.x !== 0) props.push(['x', node.x])
+ if (node.y !== 0) props.push(['y', node.y])
+}
+
+function collectSizingProps(
+ node: SceneNode,
+ ctx: ReturnType<typeof getNodeContext>,
+ graph: SceneGraph,
+ props: JSXProp[]
+): void {
+ if (ctx.isGrid) collectGridSizingProps(node, props)
+ else if (ctx.isFlex) collectFlexSizingProps(node, props)
+ else if (node.type === 'TEXT') collectTextSizingProps(node, graph, props)
+ else {
+ if (node.width > 0) props.push(['w', node.width])
+ if (node.height > 0) props.push(['h', node.height])
+ }
+
+ if (!ctx.parentIsAutoLayout) return
+ if (node.layoutGrow > 0) props.push(['grow', node.layoutGrow])
+ if (node.layoutAlignSelf === 'STRETCH') {
+ const parent = node.parentId ? graph.getNode(node.parentId) : null
+ if (parent && (parent.layoutMode === 'HORIZONTAL' || parent.layoutMode === 'VERTICAL')) {
+ const crossDim = parent.layoutMode === 'HORIZONTAL' ? 'h' : 'w'
+ if (!props.some(([k]) => k === crossDim)) props.push([crossDim, 'fill'])
+ }
+ }
+}
+
+function collectTextSizingProps(node: SceneNode, graph: SceneGraph, props: JSXProp[]): void {
+ const autoResize = node.textAutoResize
+ const emitH = autoResize === 'NONE' || autoResize === 'TRUNCATE'
+ // Don't emit fixed w when text stretches to fill parent — the layoutAlignSelf
+ // check below will emit w="fill" instead. Without this guard, w={computedPx}
+ // gets emitted first and blocks the fill detection.
+ const isFillWidth =
+ node.layoutAlignSelf === 'STRETCH' &&
+ (() => {
+ const parent = node.parentId ? graph.getNode(node.parentId) : null
+ return parent?.layoutMode === 'VERTICAL'
+ })()
+ const isGrowWidth =
+ node.layoutGrow > 0 &&
+ (() => {
+ const parent = node.parentId ? graph.getNode(node.parentId) : null
+ return parent?.layoutMode === 'HORIZONTAL'
+ })()
+ const emitW = autoResize !== 'WIDTH_AND_HEIGHT' && !isFillWidth && !isGrowWidth
+ if (emitW && node.width > 0) props.push(['w', node.width])
+ if (emitH && node.height > 0) props.push(['h', node.height])
+}
+
+function collectTextNodeProps(node: SceneNode, props: JSXProp[]): void {
+ const direction = resolveNodeTextDirection(node)
+ if (node.fontSize !== 14) props.push(['size', node.fontSize])
+ if (node.fontFamily && node.fontFamily !== DEFAULT_FONT_FAMILY)
+ props.push(['font', node.fontFamily])
+ if (node.fontWeight !== 400) {
+ if (node.fontWeight === 700) props.push(['weight', 'bold'])
+ else if (node.fontWeight === 500) props.push(['weight', 'medium'])
+ else props.push(['weight', node.fontWeight])
+ }
+ if (direction === 'RTL') props.push(['dir', 'rtl'])
+ if (node.textAlignHorizontal !== 'LEFT') {
+ props.push(['textAlign', node.textAlignHorizontal.toLowerCase()])
+ }
+ if (node.lineHeight != null) props.push(['lineHeight', node.lineHeight])
+ if (node.letterSpacing !== 0) props.push(['letterSpacing', node.letterSpacing])
+ if (node.textDecoration !== 'NONE')
+ props.push(['textDecoration', node.textDecoration.toLowerCase()])
+ if (node.textCase !== 'ORIGINAL') props.push(['textCase', node.textCase.toLowerCase()])
+ if (node.maxLines != null) props.push(['maxLines', node.maxLines])
+ if (node.textTruncation === 'ENDING' && node.maxLines == null) props.push(['truncate', true])
+ const textColor = solidFillColor(node.fills)
+ if (textColor) {
+ const bgIdx = props.findIndex(([k]) => k === 'bg')
+ if (bgIdx !== -1) props.splice(bgIdx, 1)
+ props.push(['color', textColor])
+ }
+}
+
+function collectShapeNodeProps(node: SceneNode, props: JSXProp[]): void {
+ if (node.type === 'STAR') {
+ if (node.pointCount !== 5) props.push(['points', node.pointCount])
+ if (node.starInnerRadius !== 0.382) props.push(['innerRadius', node.starInnerRadius])
+ }
+ if (node.type === 'POLYGON' && node.pointCount !== 3) {
+ props.push(['points', node.pointCount])
+ }
+}
+
+/** The props of `node`, in the order they are printed. */
+export function collectProps(node: SceneNode, graph: SceneGraph): JSXProp[] {
+ const props: JSXProp[] = []
+ const ctx = getNodeContext(node, graph)
+
+ if (node.name && node.name !== node.type) props.push(['name', node.name])
+
+ collectPositionProps(node, ctx, props)
+ collectSizingProps(node, ctx, graph, props)
+ if (ctx.parentIsGrid) collectGridPositionProps(node, props)
+ if (ctx.isFlex) collectFlexAlignmentProps(node, props)
+ if (ctx.isAutoLayout) collectAutoLayoutPaddingProps(node, props)
+ collectAppearanceProps(node, props)
+ if (node.type === 'TEXT') collectTextNodeProps(node, props)
+ collectShapeNodeProps(node, props)
+
+ return props
+}
diff --git a/packages/dom-css/AGENTS.md b/packages/dom-css/AGENTS.md
index 250111460..8550c9dd1 100644
--- a/packages/dom-css/AGENTS.md
+++ b/packages/dom-css/AGENTS.md
@@ -8,7 +8,7 @@ DOM, CSS, HTML, JSX, and Tailwind projection between documents and SceneGraph, w
Rules:
-- Depend only on `@open-pencil/scene-graph`. Engine services such as web-font resolution come in as options; Core registers the HTML and Tailwind JSX formats (`packages/core/AGENTS.md`).
+- Depend only on `@open-pencil/scene-graph` and `@open-pencil/codegen`. Engine services such as web-font resolution come in as options; Core registers the HTML and Tailwind JSX formats (`packages/core/AGENTS.md`).
- Keep the `./export` entry browser-safe: load `node:*` modules and the headless CSS object model lazily inside the functions that need them, so the app never bundles them.
-- Build generated code as syntax trees printed with esrap, not string fragments; values JSX or TypeScript would reinterpret go through string literals.
+- Build generated code as syntax trees with `@open-pencil/codegen` (`es` for TypeScript modules, `jsx` for JSX), not string fragments.
- Imported documents are untrusted: check Base64 with `js-base64`'s `isValid` before decoding.
diff --git a/packages/dom-css/package.json b/packages/dom-css/package.json
index 28391fba9..aca6a3444 100644
--- a/packages/dom-css/package.json
+++ b/packages/dom-css/package.json
@@ -77,11 +77,9 @@
},
"dependencies": {
"@acemir/cssom": "^0.9.31",
- "@sveltejs/acorn-typescript": "^1.0.13",
- "acorn": "^8.18.0",
+ "@open-pencil/codegen": "workspace:*",
"dedent": "^1.7.2",
"es-toolkit": "^1.51.0",
- "esrap": "^2.3.11",
"js-base64": "^3.9.3",
"parse5": "^8.0.1",
"postcss-value-parser": "^4.2.0",
diff --git a/packages/dom-css/src/export/storybook/module.ts b/packages/dom-css/src/export/storybook/module.ts
index 6c99af90b..8af26f049 100644
--- a/packages/dom-css/src/export/storybook/module.ts
+++ b/packages/dom-css/src/export/storybook/module.ts
@@ -1,6 +1,6 @@
import dedent from 'dedent'
-import * as es from './estree'
+import { es } from '@open-pencil/codegen'
export const STORYBOOK_FRAMEWORKS = ['react', 'vue', 'html'] as const
export type StorybookFramework = (typeof STORYBOOK_FRAMEWORKS)[number]
diff --git a/packages/dom-css/src/export/tailwind-jsx.ts b/packages/dom-css/src/export/tailwind-jsx.ts
index 2298f3ab1..f8c893e2e 100644
--- a/packages/dom-css/src/export/tailwind-jsx.ts
+++ b/packages/dom-css/src/export/tailwind-jsx.ts
@@ -1,57 +1,19 @@
-import { print } from 'esrap'
-import tsx from 'esrap/languages/tsx'
-
+import { jsx, type SyntaxNode } from '@open-pencil/codegen'
import type { SceneGraph } from '@open-pencil/scene-graph'
import type { DesignDocument, DesignElement, DesignNode } from '../types'
import { mergeClassNames, serializeTailwindClasses } from './html'
import { sceneNodeToDesignDocument } from './projection'
-/** A JSX node as esrap prints it. */
-interface JSXNode {
- type: string
- [key: string]: unknown
-}
-
/** HTML attribute names that JSX spells differently. */
const JSX_ATTRIBUTE_NAMES: Record<string, string> = { class: 'className', for: 'htmlFor' }
-/**
- * JSX attribute strings end at `"`, decode `&` entities, and keep backslashes literally,
- * so the printer's escapes for backslashes and line breaks would change the value. JSX
- * text also treats braces and angle brackets as syntax and trims whitespace at line
- * edges. Anything else is written as a string literal, which the printer escapes.
- */
-const LITERAL_ATTRIBUTE = /^[^"&\\\r\n]*$/
-const LITERAL_TEXT = /^[^{}<>&\n]*$/
-
-const identifier = (name: string): JSXNode => ({ type: 'JSXIdentifier', name })
-const literal = (value: string): JSXNode => ({ type: 'Literal', value })
-const expression = (value: string): JSXNode => ({
- type: 'JSXExpressionContainer',
- expression: literal(value)
-})
-const whitespace = (value: string): JSXNode => ({ type: 'JSXText', value, raw: value })
-
-function attribute(name: string, value: string): JSXNode {
- return {
- type: 'JSXAttribute',
- name: identifier(JSX_ATTRIBUTE_NAMES[name] ?? name),
- value: LITERAL_ATTRIBUTE.test(value) ? literal(value) : expression(value)
- }
-}
-
-function text(value: string): JSXNode {
- const plain = LITERAL_TEXT.test(value) && value.trim() === value && value.length > 0
- return plain ? whitespace(value) : expression(value)
-}
-
/** Scene text layers become paragraphs; Tailwind's preflight removes their margins. */
function tagName(node: DesignElement): string {
return node.sourceSceneNode?.type === 'TEXT' ? 'p' : node.tagName
}
-function attributes(node: DesignElement): JSXNode[] {
+function attributes(node: DesignElement): SyntaxNode[] {
const { class: className, ...attrs } = node.attrs
const name = node.sourceSceneNode?.name
const entries: [string, string | undefined][] = [
@@ -59,51 +21,27 @@ function attributes(node: DesignElement): JSXNode[] {
...Object.entries(attrs),
['className', mergeClassNames(className, serializeTailwindClasses(node))]
]
- return entries.flatMap(([key, value]) => (value === undefined ? [] : [attribute(key, value)]))
-}
-
-/** Children on their own lines; JSX drops whitespace-only lines between elements. */
-function indented(children: JSXNode[], depth: number): JSXNode[] {
- const inner = `\n${' '.repeat(depth + 1)}`
- return [
- ...children.flatMap((child) => [whitespace(inner), child]),
- whitespace(`\n${' '.repeat(depth)}`)
- ]
+ return entries.flatMap(([key, value]) =>
+ value === undefined
+ ? []
+ : [jsx.attribute(JSX_ATTRIBUTE_NAMES[key] ?? key, jsx.stringValue(value))]
+ )
}
-function childNodes(node: DesignElement, depth: number): JSXNode[] {
+function element(node: DesignElement, depth: number): SyntaxNode {
const children = node.children.map((child) => jsxNode(child, depth + 1))
- if (children.length === 0) return []
// A lone text child stays on the element's line.
- if (children.length === 1 && node.children[0]?.type === 'text') return children
- return indented(children, depth)
+ const inline = children.length === 1 && node.children[0]?.type === 'text'
+ return jsx.element(tagName(node), attributes(node), children, depth, inline)
}
-function element(node: DesignElement, depth: number): JSXNode {
- const name = identifier(tagName(node))
- const children = childNodes(node, depth)
- return {
- type: 'JSXElement',
- openingElement: {
- type: 'JSXOpeningElement',
- name,
- attributes: attributes(node),
- selfClosing: children.length === 0
- },
- closingElement: children.length > 0 ? { type: 'JSXClosingElement', name } : null,
- children
- }
-}
-
-function jsxNode(node: DesignNode, depth: number): JSXNode {
- return node.type === 'text' ? text(node.text) : element(node, depth)
+function jsxNode(node: DesignNode, depth: number): SyntaxNode {
+ return node.type === 'text' ? jsx.text(node.text) : element(node, depth)
}
/** Print a design document as Tailwind JSX, one top-level element per block. */
export function designDocumentToTailwindJSX(document: DesignDocument): string {
- return document.children
- .map((node) => print(jsxNode(node, 0), tsx({ quotes: 'double' }), { indent: ' ' }).code)
- .join('\n\n')
+ return document.children.map((node) => jsx.printJSX(jsxNode(node, 0))).join('\n\n')
}
/** Tailwind JSX for scene nodes, separated by blank lines. */
diff --git a/tests/engine/render/jsx/text-props.test.ts b/tests/engine/render/jsx/text-props.test.ts
index c40cc3e74..3a44b623f 100644
--- a/tests/engine/render/jsx/text-props.test.ts
+++ b/tests/engine/render/jsx/text-props.test.ts
@@ -148,20 +148,3 @@ describe('text props round-trip', () => {
expect(jsx).not.toMatch(/\bw=\{\d+\}/)
})
})
-
-describe('attribute string round-trip', () => {
- it.each([
- // Unescaped, this name would inject `w={999}` into the exported frame.
- 'a" w={999} x="',
- 'Fish &amp; chips',
- 'Back\\slash',
- 'Two\nlines',
- 'Plain name'
- ])('keeps the layer name %p', async (name) => {
- const g = makeSceneGraph()
- const [source] = await renderJSX(g, '<Frame w={10} h={10} />')
- getNodeOrThrow(g, source.id).name = name
- const [result] = await renderJSX(g, sceneNodeToJSX(source.id, g))
- expect(getNodeOrThrow(g, result.id)).toMatchObject({ name, width: 10 })
- })
-})
diff --git a/tools/checks/package-quality/src/smoke/scenarios.ts b/tools/checks/package-quality/src/smoke/scenarios.ts
index b1c2fa7c9..717cc0a5d 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: 'Codegen package',
+ code: "const { jsx } = await import('@open-pencil/codegen'); const code = jsx.printJSX(jsx.element('Card', [jsx.attribute('wide', null)], [], 0)); if (code !== '<Card wide />') throw new Error('Codegen package smoke failed: ' + code)"
+ },
{
name: 'Design JSX package',
code: "const { Frame, Text, JSX_REFERENCE } = await import('@open-pencil/design-jsx'); const tree = Frame({ w: 100, children: [Text({ children: 'OpenPencil' })] }); if (tree.type !== 'frame' || tree.children.length !== 1 || !JSX_REFERENCE.includes('Frame')) throw new Error('Design JSX package smoke failed')"
diff --git a/tools/dev/unit-tests/src/shards.ts b/tools/dev/unit-tests/src/shards.ts
index dce62e6b3..d641fa313 100644
--- a/tools/dev/unit-tests/src/shards.ts
+++ b/tools/dev/unit-tests/src/shards.ts
@@ -43,6 +43,7 @@ export const UNIT_TEST_GROUPS = {
'tests/engine/vector'
],
dom: [
+ 'packages/codegen/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.ts
index 91e37f53e..f93604b4d 100644
--- a/tools/dev/unit-tests/tests/shards.test.ts
+++ b/tools/dev/unit-tests/tests/shards.test.ts
@@ -46,6 +46,7 @@ test('canonical destinations are registered before they hold files', async () =>
'kiwi',
'dom-css',
'design-jsx',
+ 'codegen',
'pen',
'cli',
'mcp'
diff --git a/tsconfig.json b/tsconfig.json
index ee7460b05..6be1ecb60 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -80,6 +80,12 @@
"@open-pencil/scene-graph/*": [
"./packages/scene-graph/src/*"
],
+ "#codegen/*": [
+ "./packages/codegen/src/*"
+ ],
+ "@open-pencil/codegen": [
+ "./packages/codegen/src/index.ts"
+ ],
"#design-jsx/*": [
"./packages/design-jsx/src/*"
],
diff --git a/vite/aliases.ts b/vite/aliases.ts
index ea7e7c87c..6254b083c 100644
--- a/vite/aliases.ts
+++ b/vite/aliases.ts
@@ -35,6 +35,11 @@ export function createOpenPencilAliases(rootDir: string) {
replacement: resolve(rootDir, 'packages/scene-graph/src/index.ts')
},
{ find: '@open-pencil/scene-graph', replacement: resolve(rootDir, 'packages/scene-graph/src') },
+ { find: '#codegen', replacement: resolve(rootDir, 'packages/codegen/src') },
+ {
+ find: /^@open-pencil\/codegen$/,
+ replacement: resolve(rootDir, 'packages/codegen/src/index.ts')
+ },
{ find: '#design-jsx', replacement: resolve(rootDir, 'packages/design-jsx/src') },
{
find: /^@open-pencil\/design-jsx$/,