Skip to content

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

refactor!: move shared primitives below dom-css and core (#771)

Danila Poyarkove532f616ba86
diff --git a/AGENTS.md b/AGENTS.md
index 2fd7bb9bd..6844e0127 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -8,12 +8,12 @@ Vue 3 + CanvasKit (Skia WASM) + Yoga WASM design editor. Tauri v2 desktop, also
Bun workspace packages:
-- `scene-graph` — framework-neutral graph, node types, geometry, copy/snap/undo, variables, instances, and hit testing.
+- `scene-graph` — framework-neutral graph, node types, geometry, copy/snap/undo, variables, instances, hit testing, and the shared primitives formats need: color conversion and color management, and text/layout direction.
- `pen` — Pencil.dev `.pen` model, parser, and SceneGraph adapter.
- `kiwi` — SceneGraph-independent Kiwi schema/runtime, codecs, containers, and parse helpers.
- `fig` — `.fig` archives, SceneGraph conversion, metadata policy, and component/instance interpretation.
-- `core` — renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and document I/O; depends on scene-graph, pen, kiwi, and fig, and keeps browser DOM out.
-- `dom-css` — DOM/CSS/HTML/JSX/Tailwind projection and browser/headless adapters.
+- `core` — renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and document I/O; depends on scene-graph and the format packages (pen, kiwi, fig, dom-css), and keeps browser DOM out.
+- `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.
- `vue` — headless Vue 3 SDK primitives and composables; the root app is one consumer.
- `cli` — headless `.fig` inspection, export, and linting with `citty` and `agentfmt`.
- `mcp` — stdio and Hono HTTP MCP server reusing Core tools.
@@ -179,6 +179,7 @@ Private tooling belongs under `tools/<domain>/{src,tests}`, with kebab-case doma
- Prefer test-runner-owned fixtures and request/route counters over browser globals. For in-page performance instrumentation, return a scoped `JSHandle` from `evaluateHandle()`; restore patched methods/listeners and dispose the handle in `finally`. Handles do not survive navigation. Assert transient DOM state with locators before the interaction ends when possible. Do not create a catch-all test Window interface or add ad-hoc counter properties to window.
- In Bun tests, prefer injected dependencies or scoped spies with explicit cleanup. `mock.restore()` restores spies but does not undo `mock.module()` overrides; do not assume module mocks are isolated by cleanup hooks. Read the installed runner's current lifecycle/mocking docs before introducing global or module-level instrumentation.
- Use `culori` for color conversion and existing dependencies before custom implementations.
+- Use `js-base64` directly for Base64: `fromUint8Array`/`toUint8Array` for bytes, `encode`/`decode` for text, and `isValid` before decoding input from outside (clipboard, imported files, tool arguments). Do not wrap it or use `atob`, `btoa`, or `Buffer` Base64 conversions; `open-pencil/no-hand-rolled-base64` enforces this.
- Prefer VueUse for common browser, event, focus, clipboard, storage, and timer behavior, but keep one-shot rAF or explicit service-owned timers when clearer.
- Components must not hold module-level mutable state. Share repeated logic/constants rather than copying it.
- Keep Kiwi runtime changes minimal; prefer wrappers for project policy.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 31b008900..60416d372 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@
- The desktop app now requires macOS 13 or later; the web app supports Chrome 111, Edge 111, Firefox 128, and Safari 16.4 or later.
- `sceneNodeToJSX` and `selectionToJSX` in `@open-pencil/core` produce only OpenPencil JSX, and `JSXFormat` and `JSXExportOptions` are removed. For Tailwind JSX, use `sceneNodesToTailwindJSX(graph, nodeIds)` from `@open-pencil/dom-css` or `@open-pencil/dom-css/browser`.
+- Color conversion and management and text/layout direction helpers moved from `@open-pencil/core/color` and `@open-pencil/core/text` to `@open-pencil/scene-graph/color` and `@open-pencil/scene-graph/text-direction`, and `@open-pencil/core/bytes` is removed in favor of `js-base64`; the `@open-pencil/core` root exports are unchanged. `@open-pencil/dom-css` no longer requires `@open-pencil/core`, and `exportHTMLBundle` takes a font resolver in `fonts` instead of `'assets'`; pass one built on `exportWebFontFaceAssets` from `@open-pencil/core/text/web-font/assets` to keep font files in standalone exports.
### Added
diff --git a/bun.lock b/bun.lock
index b67ed4311..7b858db49 100644
--- a/bun.lock
+++ b/bun.lock
@@ -64,6 +64,7 @@
"fzstd": "^0.1.1",
"hast-util-to-html": "^9.0.5",
"idb": "^8.0.3",
+ "js-base64": "^3.9.3",
"jspdf": "^4.2.1",
"lib0": "^0.2.117",
"motion-v": "^2.4.0",
@@ -173,6 +174,7 @@
"agentfmt": "^0.1.3",
"canvaskit-wasm": "^0.41.1",
"citty": "^0.1.6",
+ "js-base64": "^3.9.3",
},
"devDependencies": {
"@types/bun": "^1.3.14",
@@ -184,6 +186,7 @@
"dependencies": {
"@chenglou/pretext": "^0.0.7",
"@iconify/utils": "^3.1.4",
+ "@open-pencil/dom-css": "workspace:*",
"@open-pencil/fig": "workspace:*",
"@open-pencil/kiwi": "workspace:*",
"@open-pencil/pen": "workspace:*",
@@ -248,6 +251,7 @@
"dependencies": {
"@acemir/cssom": "^0.9.31",
"esrap": "^2.3.11",
+ "js-base64": "^3.9.3",
"parse5": "^8.0.1",
"postcss-value-parser": "^4.2.0",
"tailwindcss": "^4.3.3",
@@ -259,7 +263,6 @@
"typescript": "~5.8.3",
},
"peerDependencies": {
- "@open-pencil/core": "workspace:*",
"@open-pencil/scene-graph": "workspace:*",
},
},
@@ -321,8 +324,10 @@
"@hono/node-server": "^1.19.17",
"@modelcontextprotocol/server": "^2.0.0",
"@open-pencil/core": "workspace:*",
+ "@open-pencil/scene-graph": "workspace:*",
"@valibot/to-json-schema": "^1.8.0",
"hono": "^4.13.2",
+ "js-base64": "^3.9.3",
"package-manager-detector": "^1.8.0",
"valibot": "^1.4.2",
"ws": "^8.21.3",
@@ -352,12 +357,14 @@
"name": "@open-pencil/scene-graph",
"version": "0.15.1",
"dependencies": {
+ "culori": "^4.0.2",
"es-toolkit": "^1.51.0",
"nanoevents": "^9.1.0",
"svgpath": "^2.6.0",
},
"devDependencies": {
"@types/bun": "^1.3.14",
+ "@types/culori": "^4.0.1",
"tsdown": "^0.22.14",
"typescript": "~5.8.3",
},
@@ -453,6 +460,7 @@
"@open-pencil/package-quality-tools": "workspace:*",
"citty": "^0.1.6",
"es-toolkit": "^1.51.0",
+ "js-base64": "^3.9.3",
"valibot": "^1.4.2",
},
},
diff --git a/oxlint.json b/oxlint.json
index d4d141278..baf74576d 100644
--- a/oxlint.json
+++ b/oxlint.json
@@ -419,6 +419,7 @@
"unicorn/prefer-includes": "error",
"no-loop-func": "error",
"typescript/no-dynamic-delete": "error",
+ "open-pencil/no-hand-rolled-base64": "error",
"open-pencil/no-module-mocking": "error",
"open-pencil/no-reduce-accumulator-copy": "error",
"open-pencil/no-widen-then-assert": "error"
diff --git a/package.json b/package.json
index 0d5169fc7..5fb163c67 100644
--- a/package.json
+++ b/package.json
@@ -143,6 +143,7 @@
"fzstd": "^0.1.1",
"hast-util-to-html": "^9.0.5",
"idb": "^8.0.3",
+ "js-base64": "^3.9.3",
"jspdf": "^4.2.1",
"lib0": "^0.2.117",
"motion-v": "^2.4.0",
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 528b552ce..ac1694f3f 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -42,7 +42,8 @@
"@open-pencil/scene-graph": "workspace:*",
"agentfmt": "^0.1.3",
"canvaskit-wasm": "^0.41.1",
- "citty": "^0.1.6"
+ "citty": "^0.1.6",
+ "js-base64": "^3.9.3"
},
"devDependencies": {
"@types/bun": "^1.3.14"
diff --git a/packages/cli/src/commands/export.ts b/packages/cli/src/commands/export.ts
index 780d638f4..487c4985b 100644
--- a/packages/cli/src/commands/export.ts
+++ b/packages/cli/src/commands/export.ts
@@ -2,9 +2,10 @@ import { mkdir, writeFile } from 'node:fs/promises'
import { basename, dirname, extname, join, resolve } from 'node:path'
import { defineCommand } from 'citty'
+import { toUint8Array } from 'js-base64'
-import { decodeBase64 } from '@open-pencil/core/bytes'
import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'
+import { exportWebFontFaceAssets } from '@open-pencil/core/text/web-font/assets'
import {
exportHTMLBundle,
sceneNodesToTailwindJSX,
@@ -86,7 +87,7 @@ async function exportViaApp(format: string, args: ExportArgs) {
printError('Nothing to export.')
process.exit(1)
}
- const data = decodeBase64(result.base64)
+ const data = toUint8Array(result.base64)
await writeAndLog(resolve(args.output ?? 'export.pdf'), data)
return
}
@@ -102,7 +103,7 @@ async function exportViaApp(format: string, args: ExportArgs) {
scale: Number(args.scale),
format: format.toLowerCase()
})
- const data = decodeBase64(result.base64)
+ const data = toUint8Array(result.base64)
const ext = format.toLowerCase() === 'jpg' ? 'jpg' : format.toLowerCase()
await writeAndLog(resolve(args.output ?? `export.${ext}`), data)
}
@@ -172,7 +173,11 @@ async function exportHTMLFromFile(
html: args.html as ExportHTMLBundleOptions['html'],
style: args.css as ExportHTMLBundleOptions['style'],
assets: args.assets as ExportHTMLBundleOptions['assets'],
- fonts: args.fonts as ExportHTMLBundleOptions['fonts'],
+ fonts:
+ args.fonts === 'assets'
+ ? async (fonts, assetBasePath) =>
+ (await exportWebFontFaceAssets({ fonts, assetBasePath })).assets
+ : 'none',
assetBasePath
})
await writeHTMLFiles(output, bundle)
diff --git a/packages/cli/src/commands/node.ts b/packages/cli/src/commands/node.ts
index 4a6b8b44a..2fd1bbf23 100644
--- a/packages/cli/src/commands/node.ts
+++ b/packages/cli/src/commands/node.ts
@@ -1,7 +1,7 @@
import { defineCommand } from 'citty'
-import { colorToHex } from '@open-pencil/core/color'
import type { NodeResult } from '@open-pencil/core/rpc'
+import { colorToHex } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
import { appTargetOptions } from '#cli/app-target'
diff --git a/packages/core/package.json b/packages/core/package.json
index 6b3490adf..b4429fe5e 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -31,11 +31,6 @@
"import": "./dist/geometry/index.js",
"default": "./dist/geometry/index.js"
},
- "./color": {
- "types": "./dist/color/index.d.ts",
- "import": "./dist/color/index.js",
- "default": "./dist/color/index.js"
- },
"./text": {
"types": "./dist/text/index.d.ts",
"import": "./dist/text/index.js",
@@ -137,12 +132,6 @@
"import": "./dist/clipboard.js",
"default": "./dist/clipboard.js"
},
- "./bytes": {
- "bun": "./src/bytes/index.ts",
- "types": "./dist/bytes/index.d.ts",
- "import": "./dist/bytes/index.js",
- "default": "./dist/bytes/index.js"
- },
"./constants": {
"types": "./dist/constants.d.ts",
"import": "./dist/constants.js",
@@ -180,6 +169,7 @@
"dependencies": {
"@chenglou/pretext": "^0.0.7",
"@iconify/utils": "^3.1.4",
+ "@open-pencil/dom-css": "workspace:*",
"@open-pencil/fig": "workspace:*",
"@open-pencil/kiwi": "workspace:*",
"@open-pencil/pen": "workspace:*",
diff --git a/packages/core/src/bytes/base64.ts b/packages/core/src/bytes/base64.ts
deleted file mode 100644
index b69c02f1e..000000000
--- a/packages/core/src/bytes/base64.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import {
- decode as decodeText,
- encode as encodeText,
- fromUint8Array,
- isValid,
- toUint8Array
-} from 'js-base64'
-
-export type Base64Alphabet = 'base64' | 'base64url'
-
-function assertValidBase64(value: string): void {
- if (!isValid(value)) throw new TypeError('Invalid Base64 string')
-}
-
-/** Encode binary data without converting it through a JavaScript string. */
-export function encodeBase64(bytes: Uint8Array, alphabet: Base64Alphabet = 'base64'): string {
- return fromUint8Array(bytes, alphabet === 'base64url')
-}
-
-/** Decode standard or URL-safe Base64 into binary data. */
-export function decodeBase64(value: string): Uint8Array {
- assertValidBase64(value)
- return toUint8Array(value)
-}
-
-/** Encode a Unicode string as UTF-8 Base64. */
-export function encodeBase64Text(value: string, alphabet: Base64Alphabet = 'base64'): string {
- return encodeText(value, alphabet === 'base64url')
-}
-
-/** Decode standard or URL-safe UTF-8 Base64 into a Unicode string. */
-export function decodeBase64Text(value: string): string {
- assertValidBase64(value)
- return decodeText(value)
-}
diff --git a/packages/core/src/bytes/index.ts b/packages/core/src/bytes/index.ts
deleted file mode 100644
index 1506b5daf..000000000
--- a/packages/core/src/bytes/index.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-export {
- decodeBase64,
- decodeBase64Text,
- encodeBase64,
- encodeBase64Text,
- type Base64Alphabet
-} from './base64'
diff --git a/packages/core/src/canvas/labels/paragraph-cache.ts b/packages/core/src/canvas/labels/paragraph-cache.ts
index ccde57a33..d94e46a87 100644
--- a/packages/core/src/canvas/labels/paragraph-cache.ts
+++ b/packages/core/src/canvas/labels/paragraph-cache.ts
@@ -8,12 +8,12 @@ import type {
} from 'canvaskit-wasm'
import type { Size } from '@open-pencil/scene-graph'
+import { detectTextDirection } from '@open-pencil/scene-graph/text-direction'
import { ResourceCache } from '#core/cache/resource'
import { resolveParagraphFontFamilies } from '#core/canvas/text/font-families'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
import { textHasFallbackScript } from '#core/text/coverage'
-import { detectTextDirection } from '#core/text/direction'
import { weightToStyle } from '#core/text/fonts'
import { missingGlyphOccurrences, type MissingGlyphOccurrence } from '#core/text/resolver'
diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.ts
index 9a7ecf98c..402ee9f7b 100644
--- a/packages/core/src/canvas/renderer.ts
+++ b/packages/core/src/canvas/renderer.ts
@@ -1,9 +1,10 @@
+import { toUint8Array } from 'js-base64'
+
import type { SceneNode, SceneGraph, Fill, Stroke } from '@open-pencil/scene-graph'
+import type { RenderColorSpace, ResolvedRenderColor } from '@open-pencil/scene-graph/color'
import type { Color, Rect, Vector } from '@open-pencil/scene-graph/primitives'
import type { SnapGuide } from '@open-pencil/scene-graph/snap'
-import { decodeBase64 } from '#core/bytes'
-import type { RenderColorSpace, ResolvedRenderColor } from '#core/color/management'
/* eslint-disable max-lines -- SkiaRenderer facade owns CanvasKit state and delegates domain drawing */
import {
SELECTION_COLOR,
@@ -745,7 +746,7 @@ export class SkiaRenderer {
if (!dataURL.startsWith(`data:${mime}`)) return null
const base64 = dataURL.split(',')[1]
if (!base64) return null
- return decodeBase64(base64)
+ return toUint8Array(base64)
} catch (err) {
console.warn('Raster encode fallback failed:', err)
return null
diff --git a/packages/core/src/canvas/renderer/colors.ts b/packages/core/src/canvas/renderer/colors.ts
index 1a9f8054c..d3b4e5877 100644
--- a/packages/core/src/canvas/renderer/colors.ts
+++ b/packages/core/src/canvas/renderer/colors.ts
@@ -1,14 +1,15 @@
import type { Fill, SceneGraph, SceneNode, Stroke } from '@open-pencil/scene-graph'
-import type { Color } from '@open-pencil/scene-graph/primitives'
-
import {
resolveNodeFillColor,
resolveNodeStrokeColor,
- resolveRGBAForPreview
-} from '#core/color/management'
-import type { RenderColorSpace, ResolvedRenderColor } from '#core/color/management'
-import { normalizeColor } from '#core/color/normalize'
-import { getFillOkHCL, getStrokeOkHCL } from '#core/color/okhcl'
+ resolveRGBAForPreview,
+ type RenderColorSpace,
+ type ResolvedRenderColor,
+ normalizeColor,
+ getFillOkHCL,
+ getStrokeOkHCL
+} from '@open-pencil/scene-graph/color'
+import type { Color } from '@open-pencil/scene-graph/primitives'
function resolvedVariableColor(
color: Color,
diff --git a/packages/core/src/canvas/text/derived.ts b/packages/core/src/canvas/text/derived.ts
index 4eaf5ac14..afc1c4fdd 100644
--- a/packages/core/src/canvas/text/derived.ts
+++ b/packages/core/src/canvas/text/derived.ts
@@ -1,4 +1,5 @@
import type { Canvas, Paint, Path } from 'canvaskit-wasm'
+import { fromUint8Array } from 'js-base64'
import type {
Color,
@@ -10,7 +11,6 @@ import type {
TextDecorationStyle
} from '@open-pencil/scene-graph'
-import { encodeBase64 } from '#core/bytes'
import { ResourceCache } from '#core/cache/resource'
import type { SkiaRenderer } from '#core/canvas/renderer'
import { geometryBlobToPath } from '#core/vector'
@@ -277,7 +277,7 @@ function getGlyphSilhouette(
): GlyphSilhouette {
const blob = glyph.commandsBlob
const relativeWeight = stroke.weight / glyph.fontSize
- const key = `${encodeBase64(blob)}:${relativeWeight.toFixed(5)}`
+ const key = `${fromUint8Array(blob)}:${relativeWeight.toFixed(5)}`
const cached = r.glyphSilhouetteCache.peek(key)
if (cached) return { path: cached, cached: true }
diff --git a/packages/core/src/canvas/text/index.ts b/packages/core/src/canvas/text/index.ts
index 96073ecc8..33377a755 100644
--- a/packages/core/src/canvas/text/index.ts
+++ b/packages/core/src/canvas/text/index.ts
@@ -9,11 +9,11 @@ import type {
} from 'canvaskit-wasm'
import type { SceneNode } from '@open-pencil/scene-graph'
+import { resolveRGBAForPreview } from '@open-pencil/scene-graph/color'
+import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
-import { resolveRGBAForPreview } from '#core/color/management'
import { DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from '#core/constants'
import { transformTextCase } from '#core/text/case'
-import { resolveNodeTextDirection } from '#core/text/direction'
import { fontManager, weightToStyle } from '#core/text/fonts'
import {
fontCoverageDemand,
diff --git a/packages/core/src/clipboard/openpencil.ts b/packages/core/src/clipboard/openpencil.ts
index 7153af7dc..c5bf6e425 100644
--- a/packages/core/src/clipboard/openpencil.ts
+++ b/packages/core/src/clipboard/openpencil.ts
@@ -1,4 +1,5 @@
import { deflateSync, inflateSync } from 'fflate'
+import { fromUint8Array, isValid, toUint8Array } from 'js-base64'
import {
createInstanceOverrideState,
@@ -13,7 +14,6 @@ import {
} from '@open-pencil/scene-graph'
import type { JSONObject } from '@open-pencil/scene-graph/primitives'
-import { decodeBase64, encodeBase64 } from '#core/bytes'
import type { ClipboardSnapshot } from '#core/editor/clipboard/copy'
interface SerializedClipboardNode extends JSONObject {
@@ -32,7 +32,7 @@ export function parseOpenPencilClipboard(html: string): OpenPencilClipboardData
if (!match) return null
try {
- const raw = decodeBase64(match[1])
+ const raw = clipboardBytes(match[1])
let bytes: Uint8Array
try {
bytes = inflateSync(raw)
@@ -46,7 +46,7 @@ export function parseOpenPencilClipboard(html: string): OpenPencilClipboardData
if (decoded.images && typeof decoded.images === 'object') {
for (const [hash, b64] of Object.entries(decoded.images)) {
if (typeof b64 === 'string') {
- images.set(hash, decodeBase64(b64))
+ images.set(hash, clipboardBytes(b64))
}
}
}
@@ -87,6 +87,12 @@ function restoreGeometry(paths: unknown): GeometryPath[] {
)
}
+/** Clipboard HTML comes from other applications, so its Base64 is checked before decoding. */
+function clipboardBytes(value: string): Uint8Array {
+ if (!isValid(value)) throw new TypeError('Invalid Base64 string')
+ return toUint8Array(value)
+}
+
function restoreNodeData(nodes: SerializedClipboardNode[]): ClipboardNode[] {
return nodes.map((node) => {
const { children, instanceOverrides, overrides, textPicture, ...rest } = node
@@ -99,7 +105,7 @@ function restoreNodeData(nodes: SerializedClipboardNode[]): ClipboardNode[] {
fillGeometry: restoreGeometry(rest.fillGeometry),
strokeGeometry: restoreGeometry(rest.strokeGeometry),
instanceOverrides: overrideState,
- textPicture: typeof textPicture === 'string' ? decodeBase64(textPicture) : textPicture,
+ textPicture: typeof textPicture === 'string' ? clipboardBytes(textPicture) : textPicture,
...(children ? { children: restoreNodeData(children) } : {})
} as ClipboardNode
})
@@ -131,7 +137,7 @@ export function buildOpenPencilClipboardHTML(
const images: Record<string, string> = {}
for (const hash of hashes) {
const bytes = graph.images.get(hash)
- if (bytes) images[hash] = encodeBase64(bytes)
+ if (bytes) images[hash] = fromUint8Array(bytes)
}
const data = {
format: 'openpencil/v1',
@@ -139,7 +145,7 @@ export function buildOpenPencilClipboardHTML(
images
}
const compressed = deflateSync(new TextEncoder().encode(JSON.stringify(data)))
- return `<!--(openpencil)${encodeBase64(compressed)}(/openpencil)-->`
+ return `<!--(openpencil)${fromUint8Array(compressed)}(/openpencil)-->`
}
function collectNodeTree(
@@ -156,7 +162,7 @@ function collectNodeTree(
if (node.type === 'TEXT' && node.text && textPictureBuilder) {
const pic = node.textPicture ?? textPictureBuilder(node)
- if (pic) serialized.textPicture = encodeBase64(pic)
+ if (pic) serialized.textPicture = fromUint8Array(pic)
} else {
delete serialized.textPicture
}
diff --git a/packages/core/src/color/analysis.ts b/packages/core/src/color/analysis.ts
deleted file mode 100644
index 73083a715..000000000
--- a/packages/core/src/color/analysis.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import type { Color } from '@open-pencil/scene-graph/primitives'
-
-export interface ColorUsageEntry {
- hex: string
- color: Color
- count: number
- variableName: string | null
-}
diff --git a/packages/core/src/design-jsx/effects.ts b/packages/core/src/design-jsx/effects.ts
index bdb63169a..1f94635af 100644
--- a/packages/core/src/design-jsx/effects.ts
+++ b/packages/core/src/design-jsx/effects.ts
@@ -1,7 +1,7 @@
import type { BlendMode, Effect } from '@open-pencil/scene-graph'
+import { parseColor } from '@open-pencil/scene-graph/color'
import type { Color, Vector } from '@open-pencil/scene-graph/primitives'
-import { parseColor } from '#core/color'
import { TRANSPARENT } from '#core/constants'
export type EffectColor = string | Color
diff --git a/packages/core/src/design-jsx/paints.ts b/packages/core/src/design-jsx/paints.ts
index 2cdeda833..ef2fc284b 100644
--- a/packages/core/src/design-jsx/paints.ts
+++ b/packages/core/src/design-jsx/paints.ts
@@ -5,9 +5,9 @@ import type {
GradientStop,
GradientTransform
} from '@open-pencil/scene-graph'
+import { colorToFill, parseColor } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
-import { colorToFill, parseColor } from '#core/color'
import { TRANSPARENT } from '#core/constants'
export type PaintColor = string | Color
diff --git a/packages/core/src/design-jsx/props-overrides.ts b/packages/core/src/design-jsx/props-overrides.ts
index ee480dd18..c9b1f5bb4 100644
--- a/packages/core/src/design-jsx/props-overrides.ts
+++ b/packages/core/src/design-jsx/props-overrides.ts
@@ -8,9 +8,9 @@ import type {
SceneNode,
Stroke
} from '@open-pencil/scene-graph'
+import { colorToFill, parseColor } from '@open-pencil/scene-graph/color'
import type { Color, JSONObject } from '@open-pencil/scene-graph/primitives'
-import { colorToFill, parseColor } from '#core/color'
import { TRANSPARENT } from '#core/constants'
const WEIGHT_MAP: Record<string, number> = {
diff --git a/packages/core/src/design-jsx/renderer.ts b/packages/core/src/design-jsx/renderer.ts
index 95bc566e0..f62371e3f 100644
--- a/packages/core/src/design-jsx/renderer.ts
+++ b/packages/core/src/design-jsx/renderer.ts
@@ -6,8 +6,8 @@ import {
type SceneGraph,
type SceneNode
} from '@open-pencil/scene-graph'
+import { parseColor } from '@open-pencil/scene-graph/color'
-import { parseColor } from '#core/color'
import type { RenderOptions } from '#core/design-jsx/types'
import { fetchIcons } from '#core/icons'
import { createIconFromPaths } from '#core/icons/render'
diff --git a/packages/core/src/editor/color-space.ts b/packages/core/src/editor/color-space.ts
index 68036fe71..5953cc5d3 100644
--- a/packages/core/src/editor/color-space.ts
+++ b/packages/core/src/editor/color-space.ts
@@ -1,9 +1,7 @@
import type { DocumentColorSpace, SceneNode } from '@open-pencil/scene-graph'
+import { resolveOkHCLForPreview, rgbaToOkHCL } from '@open-pencil/scene-graph/color'
import { copyEffects, copyFill, copyStyleRuns, copyStroke } from '@open-pencil/scene-graph/copy'
-import { resolveOkHCLForPreview } from '#core/color/management'
-import { rgbaToOkHCL } from '#core/color/okhcl'
-
import type { EditorContext } from './types'
export type DocumentColorProfileMode = 'assign' | 'convert'
diff --git a/packages/core/src/figma-api/accessors/visual.ts b/packages/core/src/figma-api/accessors/visual.ts
index 76d80f5f4..81f630ff0 100644
--- a/packages/core/src/figma-api/accessors/visual.ts
+++ b/packages/core/src/figma-api/accessors/visual.ts
@@ -1,7 +1,7 @@
import type { Effect, Fill, SceneNode, Stroke } from '@open-pencil/scene-graph'
+import { normalizeColor } from '@open-pencil/scene-graph/color'
import { copyEffects, copyFills, copyStrokes } from '@open-pencil/scene-graph/copy'
-import { normalizeColor } from '#core/color'
import {
raw,
updateNode,
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index adede5158..a9a8987f8 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -1,3 +1,5 @@
+import { fromUint8Array, isValid, toUint8Array } from 'js-base64'
+
import type {
SceneGraph,
SceneNode as CoreSceneNode,
@@ -12,7 +14,6 @@ import { computeBounds } from '@open-pencil/scene-graph/geometry'
import { computeImageHash } from '@open-pencil/scene-graph/images'
import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
-import { decodeBase64, encodeBase64 } from '#core/bytes'
import type { SkiaRenderer } from '#core/canvas'
import { canMakeBooleanSourceNode } from '#core/canvas/boolean'
import { flattenNodesToVectorProps } from '#core/canvas/flatten'
@@ -555,11 +556,12 @@ export class FigmaAPI implements NodeProxyHost {
}
base64Encode(data: Uint8Array): string {
- return encodeBase64(data)
+ return fromUint8Array(data)
}
base64Decode(data: string): Uint8Array {
- return decodeBase64(data)
+ if (!isValid(data)) throw new TypeError('Invalid Base64 string')
+ return toUint8Array(data)
}
notify(message: string): { cancel: () => void } {
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index 22a10ebaa..26813c9f1 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -8,15 +8,15 @@ import type {
Effect,
LayoutMode
} from '@open-pencil/scene-graph'
-import type { Rect } from '@open-pencil/scene-graph/primitives'
-
import {
getFillOkHCL,
getStrokeOkHCL,
setNodeFillOkHCL,
setNodeStrokeOkHCL
-} from '#core/color/okhcl'
-import type { OkHCLColor, OkHCLPayload } from '#core/color/okhcl'
+} from '@open-pencil/scene-graph/color'
+import type { OkHCLColor, OkHCLPayload } from '@open-pencil/scene-graph/color'
+import type { Rect } from '@open-pencil/scene-graph/primitives'
+
import { assertNodeEditable } from '#core/editor/capabilities'
import { installBasicNodeProxyAccessors } from './accessors/basic'
diff --git a/packages/core/src/icons/render.ts b/packages/core/src/icons/render.ts
index ff3a9b047..d994335a7 100644
--- a/packages/core/src/icons/render.ts
+++ b/packages/core/src/icons/render.ts
@@ -1,7 +1,7 @@
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { parseColor } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
-import { parseColor } from '#core/color'
import { createPathStroke } from '#core/icons/path-style'
import type { IconData } from './types'
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 3d94ade45..4ca0da2cf 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -109,7 +109,7 @@ export {
getStrokeOkHCL,
type OkHCLColor,
type OkHCLPayload
-} from './color/okhcl'
+} from '@open-pencil/scene-graph/color'
export type {
InfoResult,
PageItem,
@@ -156,7 +156,7 @@ export {
resolveNodeLayoutDirection,
isLogicalTextAlignStart,
isLogicalTextAlignEnd
-} from './text/direction'
+} from '@open-pencil/scene-graph/text-direction'
export {
FONT_WEIGHT_NAMES,
FontManager,
@@ -208,7 +208,7 @@ export {
rgba255ToColor,
colorToFill,
colorDistance
-} from './color'
+} from '@open-pencil/scene-graph/color'
export {
resolveOkHCLForPreview,
resolveRGBAForPreview,
@@ -220,7 +220,7 @@ export {
type ColorIntentSpace,
type ColorPreviewOptions,
type ResolvedRenderColor
-} from './color/management'
+} from '@open-pencil/scene-graph/color'
export {
vectorNetworkToPath,
geometryBlobToPath,
diff --git a/packages/core/src/io/formats/fig/export.ts b/packages/core/src/io/formats/fig/export.ts
index 94ddc8d75..47f2f0905 100644
--- a/packages/core/src/io/formats/fig/export.ts
+++ b/packages/core/src/io/formats/fig/export.ts
@@ -1,6 +1,7 @@
/* eslint-disable max-lines -- FIG export orchestration keeps shared GUID state in one pipeline */
import type { CanvasKit } from 'canvaskit-wasm'
import { deflateSync, inflateSync } from 'fflate'
+import { toUint8Array } from 'js-base64'
import { compressFigDataSync } from '@open-pencil/fig'
import {
@@ -15,7 +16,6 @@ import { decodeBinarySchema, compileSchema, ByteBuffer } from '@open-pencil/kiwi
import type { SceneGraph, VariableValue } from '@open-pencil/scene-graph'
import type { GUID } from '@open-pencil/scene-graph/primitives'
-import { decodeBase64 } from '#core/bytes'
import type { SkiaRenderer } from '#core/canvas'
import { CANVAS_BG_COLOR, IS_BROWSER, IS_TAURI } from '#core/constants'
import { applyEnabledLibrariesPluginData } from '#core/io/formats/fig/library-metadata'
@@ -33,7 +33,7 @@ import {
import { cloneSceneGraphForFigExport } from '#core/kiwi/fig/parse/transfer'
import { originalFigArchive } from '#core/kiwi/fig/session/original-archive'
-const THUMBNAIL_1X1 = decodeBase64(
+const THUMBNAIL_1X1 = toUint8Array(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=='
)
diff --git a/packages/core/src/io/formats/jsx/export.ts b/packages/core/src/io/formats/jsx/export.ts
index 13a3c840d..86be78ed1 100644
--- a/packages/core/src/io/formats/jsx/export.ts
+++ b/packages/core/src/io/formats/jsx/export.ts
@@ -1,7 +1,7 @@
import type { SceneGraph, SceneNode, NodeType } from '@open-pencil/scene-graph'
+import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
import { DEFAULT_FONT_FAMILY } from '#core/constants'
-import { resolveNodeTextDirection } from '#core/text/direction'
import {
collectCornerRadii,
diff --git a/packages/core/src/io/formats/jsx/helpers.ts b/packages/core/src/io/formats/jsx/helpers.ts
index 8fec44504..e7be5dba7 100644
--- a/packages/core/src/io/formats/jsx/helpers.ts
+++ b/packages/core/src/io/formats/jsx/helpers.ts
@@ -7,8 +7,7 @@ import type {
Color,
GridTrack
} from '@open-pencil/scene-graph'
-
-import { colorToHex8 } from '#core/color'
+import { colorToHex8 } from '@open-pencil/scene-graph/color'
export function formatColor(color: Color, opacity = 1): string {
return colorToHex8(color, opacity)
diff --git a/packages/core/src/io/formats/pptx/export.ts b/packages/core/src/io/formats/pptx/export.ts
index 9e2a0d170..cea4f25bb 100644
--- a/packages/core/src/io/formats/pptx/export.ts
+++ b/packages/core/src/io/formats/pptx/export.ts
@@ -1,10 +1,9 @@
+import { fromUint8Array } from 'js-base64'
import type PptxGenJS from 'pptxgenjs'
import type { Fill, Mat3, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { TransformMatrix, getWorldMatrix } from '@open-pencil/scene-graph'
-import { encodeBase64 } from '#core/bytes'
-
import {
hasUnsupportedTransform,
inch,
@@ -514,7 +513,7 @@ async function addFallbackImage(
}
const box = nodeBox(ctx, node)
ctx.slide.addImage({
- data: `data:image/png;base64,${encodeBase64(data)}`,
+ data: `data:image/png;base64,${fromUint8Array(data)}`,
x: box.x,
y: box.y,
w: box.w,
diff --git a/packages/core/src/io/formats/pptx/style.ts b/packages/core/src/io/formats/pptx/style.ts
index 67ce7e6a6..3515286f0 100644
--- a/packages/core/src/io/formats/pptx/style.ts
+++ b/packages/core/src/io/formats/pptx/style.ts
@@ -1,8 +1,7 @@
import type PptxGenJS from 'pptxgenjs'
import type { Color, Fill, SceneNode, Stroke } from '@open-pencil/scene-graph'
-
-import { colorToHex } from '#core/color'
+import { colorToHex } from '@open-pencil/scene-graph/color'
/** Scene paint/effect/text style → PPT property mapping (no slide geometry). */
diff --git a/packages/core/src/io/formats/raster/render.ts b/packages/core/src/io/formats/raster/render.ts
index a2bb298fb..197a0cf34 100644
--- a/packages/core/src/io/formats/raster/render.ts
+++ b/packages/core/src/io/formats/raster/render.ts
@@ -6,10 +6,10 @@ import {
type SceneGraph,
type SceneNode
} from '@open-pencil/scene-graph'
+import type { RenderColorSpace } from '@open-pencil/scene-graph/color'
import { computeDescendantVisualBounds } from '@open-pencil/scene-graph/geometry'
import type { SkiaRenderer } from '#core/canvas'
-import type { RenderColorSpace } from '#core/color/management'
import { extractExportGraph, findPageId } from '#core/io/subgraph'
export type RasterExportFormat = 'PNG' | 'JPG' | 'WEBP'
diff --git a/packages/core/src/io/formats/svg/defs.ts b/packages/core/src/io/formats/svg/defs.ts
index 52224bfa3..a01a1812e 100644
--- a/packages/core/src/io/formats/svg/defs.ts
+++ b/packages/core/src/io/formats/svg/defs.ts
@@ -1,11 +1,14 @@
+import { fromUint8Array } from 'js-base64'
+
import type { Effect, Fill, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import {
+ colorToHex,
+ colorToDisplayCSS,
+ getDefaultRenderColorSpace,
+ type RenderColorSpace
+} from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
-import { encodeBase64 } from '#core/bytes'
-import { colorToHex } from '#core/color'
-import { colorToDisplayCSS, getDefaultRenderColorSpace } from '#core/color/management'
-import type { RenderColorSpace } from '#core/color/management'
-
import { svg, type SVGNode } from './node'
import { round } from './paths'
@@ -110,7 +113,7 @@ function createImagePattern(
if (!data) return null
const id = nextDefId(ctx, 'img')
- const base64 = encodeBase64(data)
+ const base64 = fromUint8Array(data)
const mime = detectImageMime(data)
return {
diff --git a/packages/core/src/io/formats/svg/export.ts b/packages/core/src/io/formats/svg/export.ts
index 1cbb75944..a62f60f58 100644
--- a/packages/core/src/io/formats/svg/export.ts
+++ b/packages/core/src/io/formats/svg/export.ts
@@ -1,5 +1,6 @@
+import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
+
import { computeContentBounds } from '#core/io/formats/raster'
-import { resolveNodeTextDirection } from '#core/text/direction'
import {
nextDefId,
diff --git a/packages/core/src/io/types.ts b/packages/core/src/io/types.ts
index 455f236c6..dbe6ecf20 100644
--- a/packages/core/src/io/types.ts
+++ b/packages/core/src/io/types.ts
@@ -1,9 +1,9 @@
import type { CanvasKit } from 'canvaskit-wasm'
import type { SceneGraph } from '@open-pencil/scene-graph'
+import type { RenderColorSpace } from '@open-pencil/scene-graph/color'
import type { SkiaRenderer } from '#core/canvas'
-import type { RenderColorSpace } from '#core/color/management'
import type { RasterExportFormat } from './formats/raster'
diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.ts
index eb51a631c..e116c0177 100644
--- a/packages/core/src/layout.ts
+++ b/packages/core/src/layout.ts
@@ -11,11 +11,12 @@ import {
type Node as YogaNode
} from 'yoga-layout'
+import { resolveNodeLayoutDirection } from '@open-pencil/scene-graph/text-direction'
+
import { applyYogaLayout } from './layout/apply'
import { usesDetachedDerivedLayout } from './layout/derived'
import { applyEffectiveGeneratedTextLayout } from './layout/effective-generated-text'
import { buildGridTree, createGridChildNode } from './layout/grid'
-import { resolveNodeLayoutDirection } from './text/direction'
export {
estimateTextSize,
getTextMeasurer,
diff --git a/packages/core/src/layout/grid.ts b/packages/core/src/layout/grid.ts
index d5b30050a..5f240feb8 100644
--- a/packages/core/src/layout/grid.ts
+++ b/packages/core/src/layout/grid.ts
@@ -1,8 +1,7 @@
import { Direction, Display, Gutter, Edge, type Node as YogaNode } from 'yoga-layout'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-
-import { resolveNodeLayoutDirection } from '#core/text/direction'
+import { resolveNodeLayoutDirection } from '@open-pencil/scene-graph/text-direction'
import { configureAbsoluteChild, createYogaNode, mapGridTrack } from './yoga-helpers'
diff --git a/packages/core/src/rpc/analyze-commands.ts b/packages/core/src/rpc/analyze-commands.ts
index ea7550f16..f20df1168 100644
--- a/packages/core/src/rpc/analyze-commands.ts
+++ b/packages/core/src/rpc/analyze-commands.ts
@@ -1,10 +1,10 @@
import { orderBy, sortBy } from 'es-toolkit/array'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { colorToHex, colorDistance as colorDist } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
-import { colorToHex, colorDistance as colorDist } from '#core/color'
-import type { ColorUsageEntry } from '#core/color/analysis'
+import type { ColorUsageEntry } from '#core/tools/analyze/colors'
import {
computeOverlaps,
type AnalyzeOverlapsArgs,
diff --git a/packages/core/src/rpc/variables-command.ts b/packages/core/src/rpc/variables-command.ts
index 796373929..377ac1946 100644
--- a/packages/core/src/rpc/variables-command.ts
+++ b/packages/core/src/rpc/variables-command.ts
@@ -1,6 +1,5 @@
import type { SceneGraph, Variable } from '@open-pencil/scene-graph'
-
-import { colorToHex } from '#core/color'
+import { colorToHex } from '@open-pencil/scene-graph/color'
import type { RPCCommand } from './types'
diff --git a/packages/core/src/text/editor.ts b/packages/core/src/text/editor.ts
index c15d65b65..3f7361cc0 100644
--- a/packages/core/src/text/editor.ts
+++ b/packages/core/src/text/editor.ts
@@ -2,11 +2,10 @@ import type { CanvasKit, Paragraph } from 'canvaskit-wasm'
import type { SceneNode } from '@open-pencil/scene-graph'
import type { Rect } from '@open-pencil/scene-graph/primitives'
+import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
import type { SkiaRenderer } from '#core/canvas'
-import { resolveNodeTextDirection } from './direction'
-
export interface TextCaret {
x: number
y0: number
diff --git a/packages/core/src/text/index.ts b/packages/core/src/text/index.ts
index d50a8a355..0869fd643 100644
--- a/packages/core/src/text/index.ts
+++ b/packages/core/src/text/index.ts
@@ -1,6 +1,5 @@
export * from './editor'
export * from './style-runs'
-export * from './direction'
export * from './case'
export * from './coverage'
export * from './fonts'
diff --git a/packages/core/src/text/web-font/assets.ts b/packages/core/src/text/web-font/assets.ts
index 7fcf49bd5..05849bba8 100644
--- a/packages/core/src/text/web-font/assets.ts
+++ b/packages/core/src/text/web-font/assets.ts
@@ -1,5 +1,7 @@
import type { RemoteFontSource, ResolveFontResult } from 'unifont'
+import type { WebFontFaceAsset, WebFontFaceRequest } from '@open-pencil/dom-css'
+
import {
createProviderUnifont,
isRemoteFontSource,
@@ -11,24 +13,6 @@ import {
type WebFontProviderId
} from '#core/text/web-fonts'
-export interface WebFontFaceRequest {
- family: string
- weight: number
- style?: 'normal' | 'italic'
-}
-
-export interface WebFontFaceAsset {
- family: string
- weight: string | number | [number, number]
- style: string
- display?: string
- stretch?: string
- unicodeRange?: string[]
- format: 'woff2' | 'woff' | 'opentype' | 'truetype'
- path: string
- content: Uint8Array
-}
-
export interface ExportWebFontFaceAssetsOptions {
fonts: WebFontFaceRequest[]
providers?: WebFontProviderId[]
diff --git a/packages/core/src/tools/analyze/colors.ts b/packages/core/src/tools/analyze/colors.ts
index f3c9e0087..80d799436 100644
--- a/packages/core/src/tools/analyze/colors.ts
+++ b/packages/core/src/tools/analyze/colors.ts
@@ -2,15 +2,21 @@ import { orderBy } from 'es-toolkit/array'
import { sumBy } from 'es-toolkit/math'
import * as v from 'valibot'
+import { colorDistance, colorToHex } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
-import { colorDistance, colorToHex } from '#core/color'
-import type { ColorUsageEntry } from '#core/color/analysis'
import { toolNumber } from '#core/tools/input'
import { defineTool } from '#core/tools/schema'
import { analysisLimitInput } from './input'
+export interface ColorUsageEntry {
+ hex: string
+ color: Color
+ count: number
+ variableName: string | null
+}
+
type ColorEntry = ColorUsageEntry
function trackColor(colorMap: Map<string, ColorEntry>, color: Color, variableName: string | null) {
diff --git a/packages/core/src/tools/analyze/diff.ts b/packages/core/src/tools/analyze/diff.ts
index 1dee4019e..45a5d76f9 100644
--- a/packages/core/src/tools/analyze/diff.ts
+++ b/packages/core/src/tools/analyze/diff.ts
@@ -3,8 +3,8 @@ import { createTwoFilesPatch } from 'diff'
import * as v from 'valibot'
import type { SceneNode } from '@open-pencil/scene-graph'
+import { colorToHex, parseColor } from '@open-pencil/scene-graph/color'
-import { colorToHex, parseColor } from '#core/color'
import type { FigmaAPI } from '#core/figma-api'
import { toolNumber, nodeIdInput, nodeComparisonInput } from '#core/tools/input'
import { defineTool } from '#core/tools/schema'
diff --git a/packages/core/src/tools/codegen/tokens.ts b/packages/core/src/tools/codegen/tokens.ts
index fea676278..1983dc866 100644
--- a/packages/core/src/tools/codegen/tokens.ts
+++ b/packages/core/src/tools/codegen/tokens.ts
@@ -1,9 +1,9 @@
import * as v from 'valibot'
import type { Variable, VariableCollection, VariableValue } from '@open-pencil/scene-graph'
+import { colorToHex } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
-import { colorToHex } from '#core/color'
import { defineTool } from '#core/tools/schema'
function slugify(name: string): string {
diff --git a/packages/core/src/tools/create/icons.ts b/packages/core/src/tools/create/icons.ts
index 5f1a7e3eb..1ac5156cc 100644
--- a/packages/core/src/tools/create/icons.ts
+++ b/packages/core/src/tools/create/icons.ts
@@ -1,6 +1,7 @@
import * as v from 'valibot'
-import { parseColor } from '#core/color'
+import { parseColor } from '@open-pencil/scene-graph/color'
+
import { fetchIcons, searchIconsBatch } from '#core/icons'
import { createIconFromPaths } from '#core/icons/render'
import { toolNumber } from '#core/tools/input'
diff --git a/packages/core/src/tools/create/vector.ts b/packages/core/src/tools/create/vector.ts
index 33c123f31..0b0107390 100644
--- a/packages/core/src/tools/create/vector.ts
+++ b/packages/core/src/tools/create/vector.ts
@@ -7,9 +7,9 @@ import {
validateVectorNetwork
} from '@open-pencil/scene-graph'
import type { VectorNetwork } from '@open-pencil/scene-graph'
+import { parseColor } from '@open-pencil/scene-graph/color'
import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'
-import { parseColor } from '#core/color'
import { toolNumber, positionInputs } from '#core/tools/input'
import { defineTool, nodeSummary } from '#core/tools/schema'
import { computeAccurateBounds } from '#core/vector/curve-math'
diff --git a/packages/core/src/tools/describe/issues.ts b/packages/core/src/tools/describe/issues.ts
index 74ffbac73..b23a207d2 100644
--- a/packages/core/src/tools/describe/issues.ts
+++ b/packages/core/src/tools/describe/issues.ts
@@ -1,6 +1,5 @@
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-
-import { colorDistance, colorToHex } from '#core/color'
+import { colorDistance, colorToHex } from '@open-pencil/scene-graph/color'
import { detectLayoutIssues } from './layout-issues'
import { CONTAINER_TYPES, findAncestorBackground, looksLikeButton } from './shared'
diff --git a/packages/core/src/tools/describe/layout-issues.ts b/packages/core/src/tools/describe/layout-issues.ts
index b30809582..37a3ff6b4 100644
--- a/packages/core/src/tools/describe/layout-issues.ts
+++ b/packages/core/src/tools/describe/layout-issues.ts
@@ -2,10 +2,9 @@ import { wcagLuminance } from 'culori'
import { sumBy } from 'es-toolkit/math'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { colorToHex } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
-import { colorToHex } from '#core/color'
-
import type { DescribeIssue } from './issues'
import { CONTAINER_TYPES, findAncestorBackground } from './shared'
diff --git a/packages/core/src/tools/describe/summaries.ts b/packages/core/src/tools/describe/summaries.ts
index b6d403bb3..1a217abf6 100644
--- a/packages/core/src/tools/describe/summaries.ts
+++ b/packages/core/src/tools/describe/summaries.ts
@@ -1,6 +1,5 @@
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-
-import { colorToHex } from '#core/color'
+import { colorToHex } from '@open-pencil/scene-graph/color'
function boundFillSuffix(node: SceneNode, fillIndex: number, graph?: SceneGraph): string {
const varId = node.boundVariables[`fills/${fillIndex}/color`]
diff --git a/packages/core/src/tools/modify/effects.ts b/packages/core/src/tools/modify/effects.ts
index 61534b219..7d464aa90 100644
--- a/packages/core/src/tools/modify/effects.ts
+++ b/packages/core/src/tools/modify/effects.ts
@@ -1,8 +1,8 @@
import * as v from 'valibot'
import type { Effect } from '@open-pencil/scene-graph'
+import { parseColor } from '@open-pencil/scene-graph/color'
-import { parseColor } from '#core/color'
import { DEFAULT_SHADOW_COLOR, TRANSPARENT } from '#core/constants'
import { toolNumber, nodeIdInput } from '#core/tools/input'
import { defineTool, nodeNotFound } from '#core/tools/schema'
diff --git a/packages/core/src/tools/modify/paint.ts b/packages/core/src/tools/modify/paint.ts
index 3026bb6a2..53cd8353c 100644
--- a/packages/core/src/tools/modify/paint.ts
+++ b/packages/core/src/tools/modify/paint.ts
@@ -1,9 +1,9 @@
+import { isValid, toUint8Array } from 'js-base64'
import * as v from 'valibot'
+import { parseColor } from '@open-pencil/scene-graph/color'
import type { Matrix } from '@open-pencil/scene-graph/primitives'
-import { decodeBase64 } from '#core/bytes'
-import { parseColor } from '#core/color'
import { BLACK } from '#core/constants'
import { toolNumber, nodeIdInput } from '#core/tools/input'
import { defineTool } from '#core/tools/schema'
@@ -116,7 +116,8 @@ export const setImageFill = defineTool({
execute: (figma, { id, image_data, scale_mode }) => {
const node = figma.getNodeById(id)
if (!node) return { error: `Node "${id}" not found` }
- const bytes = decodeBase64(image_data)
+ if (!isValid(image_data)) return { error: 'image_data is not valid Base64' }
+ const bytes = toUint8Array(image_data)
const image = figma.createImage(bytes)
const mode = scale_mode
node.fills = [
diff --git a/packages/core/src/tools/modify/text.ts b/packages/core/src/tools/modify/text.ts
index 2af5d6906..36c0009b6 100644
--- a/packages/core/src/tools/modify/text.ts
+++ b/packages/core/src/tools/modify/text.ts
@@ -1,8 +1,8 @@
import * as v from 'valibot'
import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph'
+import { parseColor } from '@open-pencil/scene-graph/color'
-import { parseColor } from '#core/color'
import { styleToWeight } from '#core/text/fonts'
import { applyStyleToRange } from '#core/text/style-runs'
import { toolNumber, nodeIdInput } from '#core/tools/input'
diff --git a/packages/core/src/tools/variables/values.ts b/packages/core/src/tools/variables/values.ts
index bd6e4e035..c034b7384 100644
--- a/packages/core/src/tools/variables/values.ts
+++ b/packages/core/src/tools/variables/values.ts
@@ -1,8 +1,8 @@
import * as v from 'valibot'
import type { VariableType, VariableValue } from '@open-pencil/scene-graph'
+import { parseColor } from '@open-pencil/scene-graph/color'
-import { parseColor } from '#core/color'
import { defineTool } from '#core/tools/schema'
function parseVariableValue(type: VariableType, value: string): VariableValue {
diff --git a/packages/core/src/tools/vector/export.ts b/packages/core/src/tools/vector/export.ts
index 16c650ca2..fc38e06ea 100644
--- a/packages/core/src/tools/vector/export.ts
+++ b/packages/core/src/tools/vector/export.ts
@@ -1,6 +1,6 @@
+import { fromUint8Array } from 'js-base64'
import * as v from 'valibot'
-import { encodeBase64 } from '#core/bytes'
import type { RasterExportFormat } from '#core/io/formats/raster'
import { toolNumber } from '#core/tools/input'
import { defineTool } from '#core/tools/schema'
@@ -54,7 +54,7 @@ export const exportPDF = defineTool({
args.ids && args.ids.length > 0 ? args.ids : figma.currentPage.children.map((node) => node.id)
const data = await renderNodesToPDF(figma.graph, pageId, ids)
if (!data || data.length === 0) return { error: 'No visible nodes to export' }
- const base64 = encodeBase64(data)
+ const base64 = fromUint8Array(data)
return { mimeType: 'application/pdf', base64, byteLength: data.length }
}
})
@@ -135,7 +135,7 @@ export const exportImage = defineTool({
format
})
if (!data || data.length === 0) return { error: 'No visible nodes to export' }
- const base64 = encodeBase64(data)
+ const base64 = fromUint8Array(data)
const mimeMap = { PNG: 'image/png', JPG: 'image/jpeg', WEBP: 'image/webp' } as const
return {
mimeType: mimeMap[format],
diff --git a/packages/core/src/vector/vectorize/svg/gradients.ts b/packages/core/src/vector/vectorize/svg/gradients.ts
index f9cc5a207..56c831783 100644
--- a/packages/core/src/vector/vectorize/svg/gradients.ts
+++ b/packages/core/src/vector/vectorize/svg/gradients.ts
@@ -10,9 +10,9 @@
* gradientTransform convention used by the SVG exporter (see io/formats/svg/defs).
*/
import type { Fill, GradientStop } from '@open-pencil/scene-graph'
+import { parseColor } from '@open-pencil/scene-graph/color'
import type { Color, Matrix, Rect, Vector } from '@open-pencil/scene-graph/primitives'
-import { parseColor } from '#core/color'
import { parseSVGDocument } from '#core/io/formats/svg/document'
import { mapSVGPointToViewport, type SVGViewportMapping } from './transform'
diff --git a/packages/core/src/vector/vectorize/svg/to-vectors.ts b/packages/core/src/vector/vectorize/svg/to-vectors.ts
index 16268ed17..5717b5b65 100644
--- a/packages/core/src/vector/vectorize/svg/to-vectors.ts
+++ b/packages/core/src/vector/vectorize/svg/to-vectors.ts
@@ -9,11 +9,11 @@ import svgpath from 'svgpath'
import type { Fill, Stroke, VectorNetwork, WindingRule } from '@open-pencil/scene-graph'
import { mergeVectorNetworks } from '@open-pencil/scene-graph'
+import { parseColor } from '@open-pencil/scene-graph/color'
import { computeBounds } from '@open-pencil/scene-graph/geometry'
import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'
import type { Rect, Size } from '@open-pencil/scene-graph/primitives'
-import { parseColor } from '#core/color'
import { createPathStroke } from '#core/icons/path-style'
import { extractPaths } from '#core/icons/svg'
import type { IconPathInfo } from '#core/icons/types'
diff --git a/packages/dom-css/package.json b/packages/dom-css/package.json
index a33a48ff9..e09f91e4e 100644
--- a/packages/dom-css/package.json
+++ b/packages/dom-css/package.json
@@ -62,7 +62,6 @@
"provenance": true
},
"peerDependencies": {
- "@open-pencil/core": "workspace:*",
"@open-pencil/scene-graph": "workspace:*"
},
"devDependencies": {
@@ -73,6 +72,7 @@
"dependencies": {
"@acemir/cssom": "^0.9.31",
"esrap": "^2.3.11",
+ "js-base64": "^3.9.3",
"parse5": "^8.0.1",
"postcss-value-parser": "^4.2.0",
"tailwindcss": "^4.3.3",
diff --git a/packages/dom-css/src/css-values.ts b/packages/dom-css/src/css-values.ts
index cba10e0b6..af2654251 100644
--- a/packages/dom-css/src/css-values.ts
+++ b/packages/dom-css/src/css-values.ts
@@ -1,7 +1,7 @@
import valueParser, { type ParsedNode } from 'postcss-value-parser'
-import { colorToCSS, colorToHex, parseColor } from '@open-pencil/core/color'
import type { Effect, Fill, SceneNode, Stroke } from '@open-pencil/scene-graph'
+import { colorToCSS, colorToHex, parseColor } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
import type { DesignStyleDeclaration } from './types'
diff --git a/packages/dom-css/src/from-scene-graph.ts b/packages/dom-css/src/from-scene-graph.ts
index 4b4781c21..fe2c55066 100644
--- a/packages/dom-css/src/from-scene-graph.ts
+++ b/packages/dom-css/src/from-scene-graph.ts
@@ -1,7 +1,8 @@
-import { encodeBase64 } from '@open-pencil/core/bytes'
-import { resolveNodeTextDirection } from '@open-pencil/core/text'
+import { fromUint8Array } from 'js-base64'
+
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { BLACK } from '@open-pencil/scene-graph/constants'
+import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
import {
cssColor,
@@ -255,7 +256,7 @@ function attrsForNode(
if (fill?.type !== 'IMAGE' || !fill.imageHash) return attrs
const bytes = graph.images.get(fill.imageHash)
if (!bytes) return attrs
- return { ...attrs, src: `data:image/png;base64,${encodeBase64(bytes)}` }
+ return { ...attrs, src: `data:image/png;base64,${fromUint8Array(bytes)}` }
}
function tagNameForNode(node: SceneNode): string {
diff --git a/packages/dom-css/src/html-export.ts b/packages/dom-css/src/html-export.ts
index f05fe7135..3590e6563 100644
--- a/packages/dom-css/src/html-export.ts
+++ b/packages/dom-css/src/html-export.ts
@@ -1,22 +1,44 @@
import { CSSFontFaceRule } from '@acemir/cssom'
+import { isValid, toUint8Array } from 'js-base64'
import { parseFragment, serialize, type DefaultTreeAdapterTypes } from 'parse5'
-import { decodeBase64 } from '@open-pencil/core/bytes'
-import { normalizeFontFamily } from '@open-pencil/core/text'
-import {
- exportWebFontFaceAssets,
- type WebFontFaceAsset,
- type WebFontFaceRequest
-} from '@open-pencil/core/text/web-font/assets'
+import { normalizeFontFamily } from '@open-pencil/scene-graph'
import { mergeClassNames, serializeHTML, splitWhitespace } from './serialize'
import type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from './types'
+/** A font face the exported text uses. */
+export interface WebFontFaceRequest {
+ family: string
+ weight: number
+ style?: 'normal' | 'italic'
+}
+
+/** A font file to ship next to the page, described as an `@font-face` rule. */
+export interface WebFontFaceAsset {
+ family: string
+ weight: string | number | [number, number]
+ style: string
+ display?: string
+ stretch?: string
+ unicodeRange?: string[]
+ format: 'woff2' | 'woff' | 'opentype' | 'truetype'
+ path: string
+ content: Uint8Array
+}
+
+/** Finds font files for the requested faces; paths start with `assetBasePath`. */
+export type WebFontFaceResolver = (
+ fonts: WebFontFaceRequest[],
+ assetBasePath: string
+) => Promise<WebFontFaceAsset[]>
+
export interface ExportHTMLBundleOptions {
html?: 'fragment' | 'standalone'
style?: 'inline' | 'tailwind'
assets?: 'inline' | 'external'
- fonts?: 'assets' | 'none'
+ /** Resolves font files to include with external assets; `none` includes no fonts. */
+ fonts?: 'none' | WebFontFaceResolver
assetBasePath?: string
}
@@ -239,11 +261,8 @@ async function fontFaceAssets(
if (options.fonts === 'none' || options.assets !== 'external') return { css: '', files: [] }
const requests = new Map<string, WebFontFaceRequest>()
for (const child of document.children) collectFontRequests(child, requests)
- const result = await exportWebFontFaceAssets({
- fonts: [...requests.values()],
- assetBasePath: `${options.assetBasePath}/fonts`
- })
- return { css: result.assets.map(fontFaceCSS).join(''), files: result.assets }
+ const assets = await options.fonts([...requests.values()], `${options.assetBasePath}/fonts`)
+ return { css: assets.map(fontFaceCSS).join(''), files: assets }
}
function dataImageParts(value: string): { mime: string; base64: string } | undefined {
@@ -251,10 +270,10 @@ function dataImageParts(value: string): { mime: string; base64: string } | undef
const marker = ';base64,'
const markerIndex = value.indexOf(marker)
if (markerIndex === -1) return undefined
- return {
- mime: value.slice('data:'.length, markerIndex),
- base64: value.slice(markerIndex + marker.length)
- }
+ const base64 = value.slice(markerIndex + marker.length)
+ // Documents can come from parsed HTML; an invalid payload stays inline rather than decoding to other bytes.
+ if (!isValid(base64)) return undefined
+ return { mime: value.slice('data:'.length, markerIndex), base64 }
}
function extensionForMime(mime: string): string {
@@ -284,7 +303,7 @@ function extractImageAssets(
}
const path = `${assetBasePath}/images/image-${sources.size + 1}.${extensionForMime(parts.mime)}`
sources.set(src.value, path)
- files.push({ path, content: decodeBase64(parts.base64) })
+ files.push({ path, content: toUint8Array(parts.base64) })
src.value = path
})
return { html: serialize(fragment), files }
diff --git a/packages/dom-css/src/index.ts b/packages/dom-css/src/index.ts
index 99801b026..b0c5eab1b 100644
--- a/packages/dom-css/src/index.ts
+++ b/packages/dom-css/src/index.ts
@@ -63,7 +63,14 @@ export type {
BrowserToSceneGraphOptions
} from './browser'
export type { CompileTailwindCSSOptions } from './tailwind'
-export type { ExportHTMLBundle, ExportHTMLBundleOptions, ExportHTMLFile } from './html-export'
+export type {
+ ExportHTMLBundle,
+ ExportHTMLBundleOptions,
+ ExportHTMLFile,
+ WebFontFaceAsset,
+ WebFontFaceRequest,
+ WebFontFaceResolver
+} from './html-export'
export type { SerializeHTMLOptions } from './serialize'
export type { ToSceneGraphOptions } from './to-scene-graph'
export type CSSComputeOptions = DesignTypes.CSSComputeOptions
diff --git a/packages/dom-css/src/to-scene-graph.ts b/packages/dom-css/src/to-scene-graph.ts
index 54b62f770..03d6c91da 100644
--- a/packages/dom-css/src/to-scene-graph.ts
+++ b/packages/dom-css/src/to-scene-graph.ts
@@ -1,4 +1,5 @@
-import { decodeBase64 } from '@open-pencil/core/bytes'
+import { isValid, toUint8Array } from 'js-base64'
+
import {
SceneGraph,
type Fill,
@@ -239,8 +240,9 @@ function bytesFromDataURL(value: string | undefined): Uint8Array | null {
if (commaIndex === -1) return null
const metadata = value.slice(0, commaIndex)
const body = value.slice(commaIndex + 1)
- if (!metadata.endsWith(';base64')) return null
- return decodeBase64(body)
+ // Invalid Base64 in imported HTML drops that image instead of the whole import.
+ if (!metadata.endsWith(';base64') || !isValid(body)) return null
+ return toUint8Array(body)
}
function applyImageFill(
diff --git a/packages/dom-css/tests/helpers.ts b/packages/dom-css/tests/helpers.ts
index 71d7757ec..11a0ccf28 100644
--- a/packages/dom-css/tests/helpers.ts
+++ b/packages/dom-css/tests/helpers.ts
@@ -1,4 +1,4 @@
-import { colorToCSS } from '@open-pencil/core/color'
+import { colorToCSS } from '@open-pencil/scene-graph/color'
import type { DesignDocument } from '../src/index'
diff --git a/packages/dom-css/tests/runtime.test.ts b/packages/dom-css/tests/runtime.test.ts
index 1d66e0f37..76794fac5 100644
--- a/packages/dom-css/tests/runtime.test.ts
+++ b/packages/dom-css/tests/runtime.test.ts
@@ -14,6 +14,21 @@ describe('@open-pencil/dom-css runtime', () => {
expect(serializeHTML(cardDocument)).toContain('OpenPencil')
})
+ it('keeps images with invalid Base64 inline instead of extracting them', async () => {
+ const src = 'data:image/png;base64,A!QID'
+ const bundle = await exportHTMLBundle(
+ {
+ type: 'document',
+ children: [{ type: 'element', tagName: 'img', attrs: { src }, children: [] }]
+ },
+ { html: 'standalone', assets: 'external' }
+ )
+ const page = bundle.files.find((file) => file.path === bundle.entrypoint)
+
+ expect(bundle.files.some((file) => file.path.includes('/images/'))).toBe(false)
+ expect(String(page?.content)).toContain(src)
+ })
+
it('serializes inline styles as Tailwind classes when requested', () => {
const html = serializeHTML(
{
diff --git a/packages/dom-css/tsdown.config.ts b/packages/dom-css/tsdown.config.ts
index 420d24580..a82f8740c 100644
--- a/packages/dom-css/tsdown.config.ts
+++ b/packages/dom-css/tsdown.config.ts
@@ -18,7 +18,7 @@ export default defineConfig({
moduleSideEffects: false
},
deps: {
- neverBundle: ['@open-pencil/core', /^@open-pencil\/core\//, 'node:fs/promises'],
+ neverBundle: ['@open-pencil/scene-graph', /^@open-pencil\/scene-graph\//, 'node:fs/promises'],
onlyBundle: false
},
outputOptions: {
diff --git a/packages/fig/src/clipboard/import.ts b/packages/fig/src/clipboard/import.ts
index bb2c07f45..740092fad 100644
--- a/packages/fig/src/clipboard/import.ts
+++ b/packages/fig/src/clipboard/import.ts
@@ -15,15 +15,6 @@ import {
decompressFigKiwiDataAsync
} from '../node-change'
-function decodeBase64(value: string): Uint8Array {
- if (!isValid(value)) throw new TypeError('Invalid Base64 string')
- return toUint8Array(value)
-}
-function decodeBase64Text(value: string): string {
- if (!isValid(value)) throw new TypeError('Invalid Base64 string')
- return decodeText(value)
-}
-
interface FigmaClipboardMeta {
fileKey: string
pasteID: number
@@ -37,8 +28,10 @@ export async function parseFigmaClipboard(
const bufMatch = html.match(/\(figma\)(.*?)\(\/figma\)/s)
if (!metaMatch || !bufMatch) return null
- const meta: FigmaClipboardMeta = JSON.parse(decodeBase64Text(metaMatch[1]))
- const binary = decodeBase64(bufMatch[1])
+ // Clipboard HTML comes from other applications, so its Base64 is checked first.
+ if (!isValid(metaMatch[1]) || !isValid(bufMatch[1])) throw new TypeError('Invalid Base64 string')
+ const meta: FigmaClipboardMeta = JSON.parse(decodeText(metaMatch[1]))
+ const binary = toUint8Array(bufMatch[1])
try {
const chunks = parseFigKiwiChunks(binary)
diff --git a/packages/mcp/package.json b/packages/mcp/package.json
index 23ff20327..b113aaed3 100644
--- a/packages/mcp/package.json
+++ b/packages/mcp/package.json
@@ -66,8 +66,10 @@
"@hono/node-server": "^1.19.17",
"@modelcontextprotocol/server": "^2.0.0",
"@open-pencil/core": "workspace:*",
+ "@open-pencil/scene-graph": "workspace:*",
"@valibot/to-json-schema": "^1.8.0",
"hono": "^4.13.2",
+ "js-base64": "^3.9.3",
"package-manager-detector": "^1.8.0",
"valibot": "^1.4.2",
"ws": "^8.21.3"
diff --git a/packages/mcp/src/tool/output.ts b/packages/mcp/src/tool/output.ts
index 7a52e660d..6087bd6bc 100644
--- a/packages/mcp/src/tool/output.ts
+++ b/packages/mcp/src/tool/output.ts
@@ -1,7 +1,7 @@
import { lstat, mkdir, readlink, realpath, writeFile } from 'node:fs/promises'
import { dirname, basename, isAbsolute, join, parse, resolve, sep as osSep } from 'node:path'
-import { decodeBase64 } from '@open-pencil/core/bytes'
+import { toUint8Array } from 'js-base64'
import { ok } from '#mcp/result'
import type { MCPResult } from '#mcp/result'
@@ -239,7 +239,7 @@ export async function writeToolOutput(
return ok({ written: resolved, byteLength: Buffer.byteLength(result.svg, 'utf8') })
}
if (toolName === 'export_image' && typeof result.base64 === 'string') {
- const bytes = decodeBase64(result.base64)
+ const bytes = toUint8Array(result.base64)
await writeFile(realPath, bytes)
await resolveSafePath(realPath, root)
return ok({ written: resolved, byteLength: bytes.length })
diff --git a/packages/scene-graph/package.json b/packages/scene-graph/package.json
index 9e4acfd7c..afe6f5710 100644
--- a/packages/scene-graph/package.json
+++ b/packages/scene-graph/package.json
@@ -172,6 +172,18 @@
"bun": "./src/parse-path.ts",
"import": "./dist/parse-path.js",
"default": "./dist/parse-path.js"
+ },
+ "./color": {
+ "types": "./dist/color.d.ts",
+ "bun": "./src/color/index.ts",
+ "import": "./dist/color.js",
+ "default": "./dist/color.js"
+ },
+ "./text-direction": {
+ "types": "./dist/text-direction.d.ts",
+ "bun": "./src/text-direction.ts",
+ "import": "./dist/text-direction.js",
+ "default": "./dist/text-direction.js"
}
},
"publishConfig": {
@@ -186,12 +198,14 @@
"typecheck": "bunx tsc --noEmit -p tsconfig.json"
},
"dependencies": {
+ "culori": "^4.0.2",
"es-toolkit": "^1.51.0",
"nanoevents": "^9.1.0",
"svgpath": "^2.6.0"
},
"devDependencies": {
"@types/bun": "^1.3.14",
+ "@types/culori": "^4.0.1",
"tsdown": "^0.22.14",
"typescript": "~5.8.3"
}
diff --git a/packages/core/src/color/index.ts b/packages/scene-graph/src/color/index.ts
similarity index 95%
rename from packages/core/src/color/index.ts
rename to packages/scene-graph/src/color/index.ts
index ac58d9d0d..bb3f283a4 100644
--- a/packages/core/src/color/index.ts
+++ b/packages/scene-graph/src/color/index.ts
@@ -4,9 +4,8 @@ export * from './okhcl'
import { parse, formatHex, formatHex8, formatRgb, converter, differenceEuclidean } from 'culori'
-import type { Color } from '@open-pencil/scene-graph/primitives'
-
-import { BLACK } from '#core/constants'
+import { BLACK } from '../constants'
+import type { Color } from '../primitives'
const toRGB = converter('rgb')
diff --git a/packages/core/src/color/management.ts b/packages/scene-graph/src/color/management.ts
similarity index 98%
rename from packages/core/src/color/management.ts
rename to packages/scene-graph/src/color/management.ts
index 7b6f2a6f4..3fe6ee0ec 100644
--- a/packages/core/src/color/management.ts
+++ b/packages/scene-graph/src/color/management.ts
@@ -1,8 +1,7 @@
import { converter, formatCss, formatRgb, inGamut, toGamut } from 'culori'
-import type { DocumentColorSpace, Fill, SceneNode, Stroke } from '@open-pencil/scene-graph'
-import type { Color } from '@open-pencil/scene-graph/primitives'
-
+import type { Color } from '../primitives'
+import type { DocumentColorSpace, Fill, SceneNode, Stroke } from '../types'
import { normalizeColor } from './normalize'
import { getFillOkHCL, getStrokeOkHCL, type OkHCLColor } from './okhcl'
diff --git a/packages/core/src/color/normalize.ts b/packages/scene-graph/src/color/normalize.ts
similarity index 63%
rename from packages/core/src/color/normalize.ts
rename to packages/scene-graph/src/color/normalize.ts
index 452b67579..ac45ee475 100644
--- a/packages/core/src/color/normalize.ts
+++ b/packages/scene-graph/src/color/normalize.ts
@@ -1,6 +1,5 @@
-import type { Color } from '@open-pencil/scene-graph/primitives'
-
-import { BLACK } from '#core/constants'
+import { BLACK } from '../constants'
+import type { Color } from '../primitives'
export function normalizeColor(color?: Partial<Color>): Color {
if (!color) return { ...BLACK }
diff --git a/packages/core/src/color/okhcl.ts b/packages/scene-graph/src/color/okhcl.ts
similarity index 97%
rename from packages/core/src/color/okhcl.ts
rename to packages/scene-graph/src/color/okhcl.ts
index b9ca9ed39..ce03a563d 100644
--- a/packages/core/src/color/okhcl.ts
+++ b/packages/scene-graph/src/color/okhcl.ts
@@ -1,9 +1,8 @@
import { converter, toGamut } from 'culori'
-import type { SceneNode } from '@open-pencil/scene-graph'
-import { copyFill, copyStroke } from '@open-pencil/scene-graph/copy'
-import type { Color } from '@open-pencil/scene-graph/primitives'
-
+import { copyFill, copyStroke } from '../copy'
+import type { Color } from '../primitives'
+import type { SceneNode } from '../types'
import { normalizeColor } from './normalize'
export interface OkHCLColor {
diff --git a/packages/core/src/text/direction.ts b/packages/scene-graph/src/text-direction.ts
similarity index 98%
rename from packages/core/src/text/direction.ts
rename to packages/scene-graph/src/text-direction.ts
index 86e603dd8..f90f523f3 100644
--- a/packages/core/src/text/direction.ts
+++ b/packages/scene-graph/src/text-direction.ts
@@ -1,4 +1,4 @@
-import type { LayoutDirection, SceneNode, TextDirection } from '@open-pencil/scene-graph'
+import type { LayoutDirection, SceneNode, TextDirection } from './types'
const RTL_CHAR_RE =
/\p{Script=Arabic}|\p{Script=Hebrew}|\p{Script=Syriac}|\p{Script=Thaana}|\p{Script=Nko}|\p{Script=Adlam}/u
diff --git a/packages/scene-graph/tsdown.config.ts b/packages/scene-graph/tsdown.config.ts
index c44eb0196..24a9fc666 100644
--- a/packages/scene-graph/tsdown.config.ts
+++ b/packages/scene-graph/tsdown.config.ts
@@ -27,7 +27,9 @@ export default defineConfig({
guides: './src/guides.ts',
'layout-guides': './src/layout-guides.ts',
resize: './src/resize.ts',
- 'parse-path': './src/parse-path.ts'
+ 'parse-path': './src/parse-path.ts',
+ color: './src/color/index.ts',
+ 'text-direction': './src/text-direction.ts'
},
platform: 'neutral',
format: ['esm'],
diff --git a/packages/vue/src/controls/color-model/model.ts b/packages/vue/src/controls/color-model/model.ts
index d60a38762..870b20f3d 100644
--- a/packages/vue/src/controls/color-model/model.ts
+++ b/packages/vue/src/controls/color-model/model.ts
@@ -1,9 +1,14 @@
import { convertToHsb, convertToHsl, convertToRgb } from 'reka-ui'
import type { Color as RekaColor, HSBColor, HSLColor, RGBColor } from 'reka-ui'
-import { colorToCSS, okhclToRGBA, rgba255ToColor, rgbaToOkHCL } from '@open-pencil/core/color'
-import type { OkHCLColor } from '@open-pencil/core/color'
import type { Fill, Stroke } from '@open-pencil/scene-graph'
+import {
+ colorToCSS,
+ okhclToRGBA,
+ rgba255ToColor,
+ rgbaToOkHCL
+} from '@open-pencil/scene-graph/color'
+import type { OkHCLColor } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
import type {
diff --git a/packages/vue/src/controls/color-model/types.ts b/packages/vue/src/controls/color-model/types.ts
index 17f8e242c..ef4f23990 100644
--- a/packages/vue/src/controls/color-model/types.ts
+++ b/packages/vue/src/controls/color-model/types.ts
@@ -1,7 +1,7 @@
import type { Color as RekaColor } from 'reka-ui'
import type { MaybeRefOrGetter } from 'vue'
-import type { OkHCLColor, RenderColorSpace } from '@open-pencil/core/color'
+import type { OkHCLColor, RenderColorSpace } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
export type BuiltInColorFormat = 'hex' | 'rgb' | 'hsl' | 'hsb' | 'okhcl'
diff --git a/packages/vue/src/controls/color-model/use.ts b/packages/vue/src/controls/color-model/use.ts
index 5ba7e9c0b..9dd52f8f8 100644
--- a/packages/vue/src/controls/color-model/use.ts
+++ b/packages/vue/src/controls/color-model/use.ts
@@ -1,6 +1,6 @@
import { computed, ref, toValue } from 'vue'
-import { colorToHexRaw, okhclToRGBA, parseColor } from '@open-pencil/core/color'
+import { colorToHexRaw, okhclToRGBA, parseColor } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
import {
diff --git a/packages/vue/src/controls/okhcl/helpers.ts b/packages/vue/src/controls/okhcl/helpers.ts
index 620658672..ce952430f 100644
--- a/packages/vue/src/controls/okhcl/helpers.ts
+++ b/packages/vue/src/controls/okhcl/helpers.ts
@@ -1,5 +1,8 @@
import type { Ref } from 'vue'
+import { BLACK } from '@open-pencil/core/constants'
+import type { Editor } from '@open-pencil/core/editor'
+import type { SceneNode } from '@open-pencil/scene-graph'
import {
getFillOkHCL,
getStrokeOkHCL,
@@ -7,11 +10,8 @@ import {
rgbaToOkHCL,
setNodeFillOkHCL,
setNodeStrokeOkHCL
-} from '@open-pencil/core/color'
-import type { OkHCLColor, OkHCLColorSpace } from '@open-pencil/core/color'
-import { BLACK } from '@open-pencil/core/constants'
-import type { Editor } from '@open-pencil/core/editor'
-import type { SceneNode } from '@open-pencil/scene-graph'
+} from '@open-pencil/scene-graph/color'
+import type { OkHCLColor, OkHCLColorSpace } from '@open-pencil/scene-graph/color'
import type { ColorFieldFormat } from '#vue/controls/color-model/types'
diff --git a/packages/vue/src/primitives/ColorPicker/ColorPickerRoot.vue b/packages/vue/src/primitives/ColorPicker/ColorPickerRoot.vue
index 1f6b97e9d..6644adc32 100644
--- a/packages/vue/src/primitives/ColorPicker/ColorPickerRoot.vue
+++ b/packages/vue/src/primitives/ColorPicker/ColorPickerRoot.vue
@@ -2,7 +2,7 @@
import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'
import { computed } from 'vue'
-import { colorToCSS } from '@open-pencil/core/color'
+import { colorToCSS } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
import { useRetainedPopup } from '#vue/lifecycle/retention/popup'
diff --git a/packages/vue/src/primitives/Fill/useFill.ts b/packages/vue/src/primitives/Fill/useFill.ts
index 4426bbca5..8707de63e 100644
--- a/packages/vue/src/primitives/Fill/useFill.ts
+++ b/packages/vue/src/primitives/Fill/useFill.ts
@@ -1,8 +1,8 @@
import { computed } from 'vue'
import type { Ref } from 'vue'
-import { colorToCSS } from '@open-pencil/core/color'
import type { Fill, GradientStop } from '@open-pencil/scene-graph'
+import { colorToCSS } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
import type { FillCategory } from './types'
diff --git a/packages/vue/src/primitives/GradientEditor/GradientEditorStop.vue b/packages/vue/src/primitives/GradientEditor/GradientEditorStop.vue
index 94edb279f..3171244a0 100644
--- a/packages/vue/src/primitives/GradientEditor/GradientEditorStop.vue
+++ b/packages/vue/src/primitives/GradientEditor/GradientEditorStop.vue
@@ -2,7 +2,7 @@
import { Primitive } from 'reka-ui'
import { computed } from 'vue'
-import { colorToCSS, colorToHexRaw } from '@open-pencil/core/color'
+import { colorToCSS, colorToHexRaw } from '@open-pencil/scene-graph/color'
import type {
GradientEditorStopActions,
diff --git a/packages/vue/src/primitives/GradientEditor/useGradientStops.ts b/packages/vue/src/primitives/GradientEditor/useGradientStops.ts
index 35bdf9212..6cdfcb6c1 100644
--- a/packages/vue/src/primitives/GradientEditor/useGradientStops.ts
+++ b/packages/vue/src/primitives/GradientEditor/useGradientStops.ts
@@ -1,7 +1,7 @@
import { computed, ref, type Ref } from 'vue'
-import { colorToCSS } from '@open-pencil/core/color'
import type { Fill, GradientStop, GradientTransform } from '@open-pencil/scene-graph'
+import { colorToCSS } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
import { useColorModel } from '#vue/controls/color-model/use'
diff --git a/packages/vue/src/shared/input/auto-layout.ts b/packages/vue/src/shared/input/auto-layout.ts
index 9df13e8fc..c11a6ed8f 100644
--- a/packages/vue/src/shared/input/auto-layout.ts
+++ b/packages/vue/src/shared/input/auto-layout.ts
@@ -1,7 +1,7 @@
import type { Editor } from '@open-pencil/core/editor'
-import { resolveNodeLayoutDirection } from '@open-pencil/core/text'
import type { SceneNode } from '@open-pencil/scene-graph'
import type { Vector } from '@open-pencil/scene-graph/primitives'
+import { resolveNodeLayoutDirection } from '@open-pencil/scene-graph/text-direction'
import type { DragMove } from '#vue/shared/input/types'
diff --git a/packages/vue/src/variables/helpers.ts b/packages/vue/src/variables/helpers.ts
index b36a4d0e9..65c0f251b 100644
--- a/packages/vue/src/variables/helpers.ts
+++ b/packages/vue/src/variables/helpers.ts
@@ -1,6 +1,5 @@
import type { Ref } from 'vue'
-import { colorToHexRaw, parseColor } from '@open-pencil/core/color'
import { BLACK } from '@open-pencil/core/constants'
import type { Editor } from '@open-pencil/core/editor'
import { randomHex } from '@open-pencil/core/random'
@@ -10,6 +9,7 @@ import type {
VariableType,
VariableValue
} from '@open-pencil/scene-graph'
+import { colorToHexRaw, parseColor } from '@open-pencil/scene-graph/color'
export function createVariableCollectionActions(editor: Editor, activeCollectionId: Ref<string>) {
function setActiveCollection(id: string) {
diff --git a/src/app/automation/bridge/export-handlers.ts b/src/app/automation/bridge/export-handlers.ts
index 33a31e1fd..7cc8f4107 100644
--- a/src/app/automation/bridge/export-handlers.ts
+++ b/src/app/automation/bridge/export-handlers.ts
@@ -1,4 +1,5 @@
-import { encodeBase64 } from '@open-pencil/core/bytes'
+import { fromUint8Array } from 'js-base64'
+
import { selectionToJSX, type RasterExportFormat } from '@open-pencil/core/io'
import { sceneNodesToTailwindJSX } from '@open-pencil/dom-css/browser'
@@ -15,7 +16,7 @@ export async function handleExport(target: AutomationTarget, args: unknown): Pro
(exportArgs?.format ?? 'PNG') as RasterExportFormat
)
if (!data) throw new Error('Export failed')
- const base64 = encodeBase64(data)
+ const base64 = fromUint8Array(data)
return {
ok: true,
result: { base64, mimeType: `image/${(exportArgs?.format ?? 'png').toLowerCase()}` }
diff --git a/src/app/demo/announcement/tokens.ts b/src/app/demo/announcement/tokens.ts
index 45d7764e4..5fd5e8970 100644
--- a/src/app/demo/announcement/tokens.ts
+++ b/src/app/demo/announcement/tokens.ts
@@ -1,6 +1,6 @@
-import { parseColor } from '@open-pencil/core/color'
import { defineVars } from '@open-pencil/core/design-jsx'
import type { SceneGraph } from '@open-pencil/scene-graph'
+import { parseColor } from '@open-pencil/scene-graph/color'
export function createAnnouncementTokens(graph: SceneGraph) {
graph.addCollection({
diff --git a/src/app/demo/typography/section.ts b/src/app/demo/typography/section.ts
index 2c6559801..4cbe9716e 100644
--- a/src/app/demo/typography/section.ts
+++ b/src/app/demo/typography/section.ts
@@ -1,6 +1,6 @@
-import { parseColor } from '@open-pencil/core/color'
import { Frame, Text, renderTree } from '@open-pencil/core/design-jsx'
import type { SceneGraph } from '@open-pencil/scene-graph'
+import { parseColor } from '@open-pencil/scene-graph/color'
import { ARTICLE, FEATURE_COMPARISONS } from './content'
import { createTypographySample } from './samples'
diff --git a/src/app/editor/vectorize/providers.ts b/src/app/editor/vectorize/providers.ts
index 081f60d4f..6c7d78289 100644
--- a/src/app/editor/vectorize/providers.ts
+++ b/src/app/editor/vectorize/providers.ts
@@ -1,4 +1,5 @@
-import { encodeBase64 } from '@open-pencil/core/bytes'
+import { fromUint8Array } from 'js-base64'
+
import { IS_TAURI } from '@open-pencil/core/constants'
import { readBoundedBody } from '@/app/document/io/browser'
@@ -200,7 +201,7 @@ const fal: VectorizeProvider = {
Authorization: `Key ${apiKey}`,
'Content-Type': 'application/json'
},
- body: JSON.stringify({ image_url: `data:image/png;base64,${encodeBase64(pngBytes)}` }),
+ body: JSON.stringify({ image_url: `data:image/png;base64,${fromUint8Array(pngBytes)}` }),
credentials: 'omit',
redirect: 'error'
})
diff --git a/src/app/libraries/catalog/storage.ts b/src/app/libraries/catalog/storage.ts
index 2195ee154..f5285a46a 100644
--- a/src/app/libraries/catalog/storage.ts
+++ b/src/app/libraries/catalog/storage.ts
@@ -1,4 +1,5 @@
-import { decodeBase64, encodeBase64 } from '@open-pencil/core/bytes'
+import { fromUint8Array, toUint8Array } from 'js-base64'
+
import {
createLibraryRevision,
deserializeLibraryRevision,
@@ -60,7 +61,7 @@ function encodeValue(value: unknown): unknown {
entries: [...value].map(([key, entry]) => [encodeValue(key), encodeValue(entry)])
}
}
- if (value instanceof Uint8Array) return { $bytes: encodeBase64(value) }
+ if (value instanceof Uint8Array) return { $bytes: fromUint8Array(value) }
if (Array.isArray(value)) return value.map(encodeValue)
if (value && typeof value === 'object') {
const encoded = Object.fromEntries(
@@ -98,7 +99,7 @@ function decodeValue(value: unknown): unknown {
)
}
if ('$bytes' in value && typeof (value as { $bytes?: unknown }).$bytes === 'string') {
- return decodeBase64((value as { $bytes: string }).$bytes)
+ return toUint8Array((value as { $bytes: string }).$bytes)
}
return Object.fromEntries(
Object.entries(value).map(([key, entry]) => [key, decodeValue(entry)])
diff --git a/src/app/shell/theme.ts b/src/app/shell/theme.ts
index 1cfff72e1..5cec6b852 100644
--- a/src/app/shell/theme.ts
+++ b/src/app/shell/theme.ts
@@ -2,8 +2,8 @@ import { useLocalStorage, usePreferredDark } from '@vueuse/core'
import { computed, watch } from 'vue'
import type { RulerTheme } from '@open-pencil/core/canvas'
-import { parseColor } from '@open-pencil/core/color'
import { IS_BROWSER } from '@open-pencil/core/constants'
+import { parseColor } from '@open-pencil/scene-graph/color'
import { getActiveEditorStoreOrNull, useActiveEditorStoreRef } from '@/app/editor/active-store'
diff --git a/src/components/CollabPanel/CollabAvatarStack.vue b/src/components/CollabPanel/CollabAvatarStack.vue
index 0ab3fe4ad..42ecfa1f9 100644
--- a/src/components/CollabPanel/CollabAvatarStack.vue
+++ b/src/components/CollabPanel/CollabAvatarStack.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { tv } from 'tailwind-variants'
-import { colorToCSS } from '@open-pencil/core/color'
+import { colorToCSS } from '@open-pencil/scene-graph/color'
import { useI18n } from '@open-pencil/vue'
import { initials } from '@/app/shell/ui'
diff --git a/src/components/MobileHud/MobilePresencePopover.vue b/src/components/MobileHud/MobilePresencePopover.vue
index ab34b7acb..d2bf2bfc7 100644
--- a/src/components/MobileHud/MobilePresencePopover.vue
+++ b/src/components/MobileHud/MobilePresencePopover.vue
@@ -2,7 +2,7 @@
import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'
import { tv } from 'tailwind-variants'
-import { colorToCSS } from '@open-pencil/core/color'
+import { colorToCSS } from '@open-pencil/scene-graph/color'
import { initials } from '@/app/shell/ui'
import HudButton from '@/components/mobile-hud/HudButton.vue'
diff --git a/src/components/canvas/labels/CanvasLabelEditor.vue b/src/components/canvas/labels/CanvasLabelEditor.vue
index dc0304705..56312cf62 100644
--- a/src/components/canvas/labels/CanvasLabelEditor.vue
+++ b/src/components/canvas/labels/CanvasLabelEditor.vue
@@ -2,7 +2,7 @@
import type { ReferenceElement } from 'reka-ui'
import { PopoverContent, PopoverPortal, PopoverRoot } from 'reka-ui'
-import { colorToCSS } from '@open-pencil/core/color'
+import { colorToCSS } from '@open-pencil/scene-graph/color'
import type { CanvasLabelEdit } from '@open-pencil/vue'
import type { CanvasLabelPresentation } from '@/components/canvas/labels/presentation'
diff --git a/src/components/chat/attachment/AttachmentList.stories.ts b/src/components/chat/attachment/AttachmentList.stories.ts
index ec719eaf7..3aef356ce 100644
--- a/src/components/chat/attachment/AttachmentList.stories.ts
+++ b/src/components/chat/attachment/AttachmentList.stories.ts
@@ -1,4 +1,5 @@
import type { Meta, StoryObj } from '@storybook/vue3-vite'
+import { toUint8Array } from 'js-base64'
import type { AttachmentPresentation } from '@/app/ai/attachment/presentation/types'
@@ -7,10 +8,9 @@ import AttachmentList from './AttachmentList.vue'
const pixel = new Blob(
[
Uint8Array.from(
- atob(
+ toUint8Array(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M/wHwAEAQH/69cbGAAAAABJRU5ErkJggg=='
- ),
- (character) => character.charCodeAt(0)
+ )
)
],
{ type: 'image/png' }
diff --git a/src/components/color-picker-panel/HsbFields.vue b/src/components/color-picker-panel/HsbFields.vue
index 8679404d6..957b16a6b 100644
--- a/src/components/color-picker-panel/HsbFields.vue
+++ b/src/components/color-picker-panel/HsbFields.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { colorToCSS } from '@open-pencil/core/color'
+import { colorToCSS } from '@open-pencil/scene-graph/color'
import { inputNumberValue, useI18n } from '@open-pencil/vue'
import { useColorPickerPanelContext } from '@/components/color-picker-panel/context'
diff --git a/src/components/color-picker-panel/HslFields.vue b/src/components/color-picker-panel/HslFields.vue
index 7420834a2..089442647 100644
--- a/src/components/color-picker-panel/HslFields.vue
+++ b/src/components/color-picker-panel/HslFields.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { colorToCSS } from '@open-pencil/core/color'
+import { colorToCSS } from '@open-pencil/scene-graph/color'
import { inputNumberValue, useI18n } from '@open-pencil/vue'
import { useColorPickerPanelContext } from '@/components/color-picker-panel/context'
diff --git a/src/components/color-picker-panel/HueAlphaSliders.vue b/src/components/color-picker-panel/HueAlphaSliders.vue
index 64e35d032..4176d2130 100644
--- a/src/components/color-picker-panel/HueAlphaSliders.vue
+++ b/src/components/color-picker-panel/HueAlphaSliders.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { colorToCSS } from '@open-pencil/core/color'
+import { colorToCSS } from '@open-pencil/scene-graph/color'
import { useI18n } from '@open-pencil/vue'
import { useColorPickerPanelContext } from '@/components/color-picker-panel/context'
diff --git a/src/components/color-picker-panel/OkhclFields.vue b/src/components/color-picker-panel/OkhclFields.vue
index d9045d509..fcc649cf8 100644
--- a/src/components/color-picker-panel/OkhclFields.vue
+++ b/src/components/color-picker-panel/OkhclFields.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { colorToCSS } from '@open-pencil/core/color'
+import { colorToCSS } from '@open-pencil/scene-graph/color'
import { fromPercent, toPercent, useI18n } from '@open-pencil/vue'
import { useColorPickerPanelContext } from '@/components/color-picker-panel/context'
diff --git a/src/components/fill-picker/GradientEditor.vue b/src/components/fill-picker/GradientEditor.vue
index 4137df8f0..1e84bcc8a 100644
--- a/src/components/fill-picker/GradientEditor.vue
+++ b/src/components/fill-picker/GradientEditor.vue
@@ -1,8 +1,8 @@
<script setup lang="ts">
import { tv } from 'tailwind-variants'
-import { colorToCSS } from '@open-pencil/core/color'
import type { Fill } from '@open-pencil/scene-graph'
+import { colorToCSS } from '@open-pencil/scene-graph/color'
import {
GradientEditorRoot,
GradientEditorBar,
diff --git a/src/components/properties/FillSection.vue b/src/components/properties/FillSection.vue
index 50171793f..df565cc1d 100644
--- a/src/components/properties/FillSection.vue
+++ b/src/components/properties/FillSection.vue
@@ -1,6 +1,6 @@
<script setup lang="ts">
-import { colorToHexRaw } from '@open-pencil/core/color'
import type { Fill } from '@open-pencil/scene-graph'
+import { colorToHexRaw } from '@open-pencil/scene-graph/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
import {
BindableValueRoot,
diff --git a/src/components/properties/fill-label.ts b/src/components/properties/fill-label.ts
index 17a735edb..daa3803e8 100644
--- a/src/components/properties/fill-label.ts
+++ b/src/components/properties/fill-label.ts
@@ -1,5 +1,5 @@
-import { colorToHexRaw } from '@open-pencil/core/color'
import type { Fill, Variable } from '@open-pencil/scene-graph'
+import { colorToHexRaw } from '@open-pencil/scene-graph/color'
export function fillLabel(fill: Fill, boundVariable?: Variable): string {
if (boundVariable) return boundVariable.name
diff --git a/src/components/properties/stroke/StrokeSection.vue b/src/components/properties/stroke/StrokeSection.vue
index 1be9cd1ae..e5e2e58d8 100644
--- a/src/components/properties/stroke/StrokeSection.vue
+++ b/src/components/properties/stroke/StrokeSection.vue
@@ -1,8 +1,8 @@
<script setup lang="ts">
import { ref } from 'vue'
-import { colorToHexRaw } from '@open-pencil/core/color'
import type { Color, Fill, SceneNode, Stroke } from '@open-pencil/scene-graph'
+import { colorToHexRaw } from '@open-pencil/scene-graph/color'
import {
applySolidStrokeColor,
BindableValueRoot,
diff --git a/tests/e2e/canvas/text/raster-history.spec.ts b/tests/e2e/canvas/text/raster-history.spec.ts
index 6b7f80f56..bdeda96da 100644
--- a/tests/e2e/canvas/text/raster-history.spec.ts
+++ b/tests/e2e/canvas/text/raster-history.spec.ts
@@ -1,6 +1,7 @@
import { writeFile } from 'node:fs/promises'
import type { Browser } from '@playwright/test'
+import { toUint8Array } from 'js-base64'
import { expect, test } from '#tests/e2e/fixtures'
import { CanvasHelper } from '#tests/helpers/canvas'
@@ -154,7 +155,7 @@ async function captureText(
expect(result.ink).toBeGreaterThan(100)
expect(result.hadBacking).toBe(backing)
await cdp.detach()
- return Buffer.from(result.png.split(',')[1], 'base64')
+ return Buffer.from(toUint8Array(result.png.split(',')[1]))
} finally {
await lease.evaluate((release) => release?.())
await lease.dispose()
diff --git a/tests/e2e/chat/markdown.spec.ts b/tests/e2e/chat/markdown.spec.ts
index b6fb1427c..1abbcaaff 100644
--- a/tests/e2e/chat/markdown.spec.ts
+++ b/tests/e2e/chat/markdown.spec.ts
@@ -1,3 +1,5 @@
+import { toUint8Array } from 'js-base64'
+
import { expect, test } from '#tests/helpers/chat/fixture'
test('completed responses release streaming parser history', async ({ configuredChat: chat }) => {
@@ -32,8 +34,9 @@ test('Markdown blocks unsafe links and cross-origin images', async ({ configured
await chat.page.route(approvedImageURL, async (route) => {
await route.fulfill({
body: Buffer.from(
- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M/wHwAEAQH/69cbGAAAAABJRU5ErkJggg==',
- 'base64'
+ toUint8Array(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M/wHwAEAQH/69cbGAAAAABJRU5ErkJggg=='
+ )
),
contentType: 'image/png'
})
diff --git a/tests/e2e/color-picker/basic.spec.ts b/tests/e2e/color-picker/basic.spec.ts
index 4b74b90d4..25b1539cd 100644
--- a/tests/e2e/color-picker/basic.spec.ts
+++ b/tests/e2e/color-picker/basic.spec.ts
@@ -1,6 +1,6 @@
import { expect, test, type Page } from '@playwright/test'
-import type { OkHCLPayload } from '@open-pencil/core/color'
+import type { OkHCLPayload } from '@open-pencil/scene-graph/color'
import { CanvasHelper } from '#tests/helpers/canvas'
diff --git a/tests/engine/bytes/base64.test.ts b/tests/engine/bytes/base64.test.ts
deleted file mode 100644
index 4f6b8965f..000000000
--- a/tests/engine/bytes/base64.test.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { describe, expect, test } from 'bun:test'
-
-import {
- decodeBase64,
- decodeBase64Text,
- encodeBase64,
- encodeBase64Text
-} from '@open-pencil/core/bytes'
-
-describe('Base64 byte helpers', () => {
- test('encode and decode empty and binary data', () => {
- expect(encodeBase64(new Uint8Array())).toBe('')
-
- const bytes = new Uint8Array([0, 1, 127, 128, 254, 255])
- expect(decodeBase64(encodeBase64(bytes))).toEqual(bytes)
- })
-
- test('encode and decode Unicode text as UTF-8', () => {
- const text = 'OpenPencil — Привет 🎨'
- expect(decodeBase64Text(encodeBase64Text(text))).toBe(text)
- })
-
- test('support URL-safe Base64', () => {
- const bytes = new Uint8Array([251, 255, 254])
- expect(encodeBase64(bytes, 'base64url')).toBe('-__-')
- expect(decodeBase64('-__-')).toEqual(bytes)
- })
-
- test('handle data larger than browser argument limits', () => {
- const bytes = Uint8Array.from({ length: 256 * 1024 }, (_, index) => index % 251)
- expect(decodeBase64(encodeBase64(bytes))).toEqual(bytes)
- })
-
- test('reject malformed Base64', () => {
- expect(() => decodeBase64('not%base64')).toThrow('Invalid Base64 string')
- expect(() => decodeBase64Text('%%%')).toThrow('Invalid Base64 string')
- })
-})
diff --git a/tests/engine/clipboard/openpencil/images.test.ts b/tests/engine/clipboard/openpencil/images.test.ts
index 2d66e19c7..6964334c5 100644
--- a/tests/engine/clipboard/openpencil/images.test.ts
+++ b/tests/engine/clipboard/openpencil/images.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, test } from 'bun:test'
import { deflateSync } from 'fflate'
+import { fromUint8Array } from 'js-base64'
import {
buildOpenPencilClipboardHTML,
@@ -9,7 +10,6 @@ import {
SceneGraph
} from '@open-pencil/core'
import type { SceneNode } from '@open-pencil/core'
-import { encodeBase64 } from '@open-pencil/core/bytes'
import { getInstanceOverride, setInstanceOverride } from '@open-pencil/scene-graph'
import { expectDefined } from '#tests/helpers/assert'
@@ -59,7 +59,7 @@ describe('clipboard roundtrip with images', () => {
],
images: {}
}
- const encoded = encodeBase64(deflateSync(new TextEncoder().encode(JSON.stringify(legacy))))
+ const encoded = fromUint8Array(deflateSync(new TextEncoder().encode(JSON.stringify(legacy))))
const parsed = expectDefined(
parseOpenPencilClipboard(`<!--(openpencil)${encoded}(/openpencil)-->`),
'OpenPencil clipboard'
diff --git a/tests/engine/color/document-space-conversion.test.ts b/tests/engine/color/document-space-conversion.test.ts
index 09ed599a5..6ba97f543 100644
--- a/tests/engine/color/document-space-conversion.test.ts
+++ b/tests/engine/color/document-space-conversion.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { resolveOkHCLForPreview, resolveRGBAForPreview } from '#core/color/management'
+import { resolveOkHCLForPreview, resolveRGBAForPreview } from '@open-pencil/scene-graph/color'
/** #2563EB as authored in an sRGB document. */
const BLUE = { r: 0.1450980392156863, g: 0.38823529411764707, b: 0.9215686274509803, a: 1 }
diff --git a/tests/engine/color/okhcl/document-color-space.test.ts b/tests/engine/color/okhcl/document-color-space.test.ts
index 3d055a0d9..38be6d977 100644
--- a/tests/engine/color/okhcl/document-color-space.test.ts
+++ b/tests/engine/color/okhcl/document-color-space.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, test } from 'bun:test'
+import { SceneGraph } from '@open-pencil/scene-graph'
import {
colorDistance,
getFillOkHCL,
@@ -7,8 +8,7 @@ import {
rgbaToOkHCL,
setNodeFillOkHCL,
setNodeStrokeOkHCL
-} from '@open-pencil/core/color'
-import { SceneGraph } from '@open-pencil/scene-graph'
+} from '@open-pencil/scene-graph/color'
const SATURATED = { l: 0.6, c: 0.3, h: 20, a: 1 }
diff --git a/tests/engine/io/pptx/export/helpers.ts b/tests/engine/io/pptx/export/helpers.ts
index d8d09b804..39d6332aa 100644
--- a/tests/engine/io/pptx/export/helpers.ts
+++ b/tests/engine/io/pptx/export/helpers.ts
@@ -1,13 +1,13 @@
import { expect } from 'bun:test'
import { unzipSync } from 'fflate'
+import { toUint8Array } from 'js-base64'
-import { decodeBase64 } from '@open-pencil/core/bytes'
import type { Fill, Stroke } from '@open-pencil/scene-graph'
import { SceneGraph } from '@open-pencil/scene-graph'
// 1x1 transparent PNG — stub rasterizer output so unit tests avoid CanvasKit.
-export const TINY_PNG = decodeBase64(
+export const TINY_PNG = toUint8Array(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=='
)
diff --git a/tests/helpers/dom-css.ts b/tests/helpers/dom-css.ts
index ffe17bd87..b38717a63 100644
--- a/tests/helpers/dom-css.ts
+++ b/tests/helpers/dom-css.ts
@@ -1,5 +1,5 @@
-import { colorToCSS } from '@open-pencil/core/color'
import type { DesignDocument, DesignElement, DesignNode } from '@open-pencil/dom-css'
+import { colorToCSS } from '@open-pencil/scene-graph/color'
export function findTextElement(nodes: DesignNode[]): DesignElement | undefined {
for (const node of nodes) {
diff --git a/tests/helpers/tauri/windows-input.ts b/tests/helpers/tauri/windows-input.ts
index ddf028c1c..aba79d1fc 100644
--- a/tests/helpers/tauri/windows-input.ts
+++ b/tests/helpers/tauri/windows-input.ts
@@ -1,6 +1,8 @@
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
+import { fromUint8Array } from 'js-base64'
+
const execFileAsync = promisify(execFile)
interface ClientPoint {
@@ -55,7 +57,8 @@ $scale = $dpi / 96.0
async function runPowerShell(script: string): Promise<void> {
if (process.platform !== 'win32') throw new Error('Win32 input is only available on Windows')
- const encoded = Buffer.from(script, 'utf16le').toString('base64')
+ // PowerShell -EncodedCommand takes UTF-16LE text as Base64.
+ const encoded = fromUint8Array(Buffer.from(script, 'utf16le'))
await execFileAsync('powershell.exe', ['-NoProfile', '-EncodedCommand', encoded])
}
diff --git a/tools/lint/src/plugin.ts b/tools/lint/src/plugin.ts
index c04664b15..007f7fa26 100644
--- a/tools/lint/src/plugin.ts
+++ b/tools/lint/src/plugin.ts
@@ -3,6 +3,7 @@ import {
noFlatKiwiModules,
noMixedCaseAcronymIdentifiers
} from '#lint/rules/policy.ts'
+import { noHandRolledBase64Rule } from '#lint/rules/quality/base64.ts'
import { noModuleMockingRule } from '#lint/rules/quality/module-mocking.ts'
import { noReduceAccumulatorCopyRule } from '#lint/rules/quality/reduce-accumulator-copy.ts'
import { noWidenThenAssertRule } from '#lint/rules/quality/widen-then-assert.ts'
@@ -490,6 +491,7 @@ const plugin = {
'no-bun-globals-in-cli': noBunGlobalsInCli,
'no-top-level-prefixed-test-files': noTopLevelPrefixedTestFiles,
'no-conditional-object-spreads': noConditionalObjectSpreads,
+ 'no-hand-rolled-base64': noHandRolledBase64Rule,
'no-module-mocking': noModuleMockingRule,
'no-reduce-accumulator-copy': noReduceAccumulatorCopyRule,
'no-widen-then-assert': noWidenThenAssertRule,
diff --git a/tools/lint/src/rules/quality/base64.ts b/tools/lint/src/rules/quality/base64.ts
new file mode 100644
index 000000000..28e1a3821
--- /dev/null
+++ b/tools/lint/src/rules/quality/base64.ts
@@ -0,0 +1,64 @@
+import { resolveVariable } from '#lint/support/scope.ts'
+import { defineRule } from '@oxlint/plugins'
+import type { ESTree, SourceCode } from '@oxlint/plugins'
+
+const BASE64_ENCODINGS = new Set(['base64', 'base64url'])
+const GLOBAL_OBJECTS = new Set(['globalThis', 'window', 'self'])
+
+function isBase64Encoding(node: ESTree.Node | undefined): boolean {
+ return (
+ node?.type === 'Literal' && typeof node.value === 'string' && BASE64_ENCODINGS.has(node.value)
+ )
+}
+
+/** `atob` or `btoa` that no local binding shadows. */
+function isGlobalBase64Function(sourceCode: SourceCode, node: ESTree.IdentifierReference): boolean {
+ if (node.name !== 'atob' && node.name !== 'btoa') return false
+ const variable = resolveVariable(sourceCode, node)
+ return variable === null || variable.defs.length === 0
+}
+
+function propertyName(node: ESTree.MemberExpression): string | null {
+ if (!node.computed && node.property.type === 'Identifier') return node.property.name
+ if (node.computed && node.property.type === 'Literal' && typeof node.property.value === 'string')
+ return node.property.value
+ return null
+}
+
+/** Require js-base64 instead of the platform's string-based or Node-only Base64 conversions. */
+export const noHandRolledBase64Rule = defineRule({
+ meta: {
+ type: 'suggestion',
+ docs: {
+ description: 'Disallow atob, btoa, and Buffer Base64 conversions; use js-base64.'
+ },
+ messages: {
+ handRolled:
+ 'Use js-base64: fromUint8Array/toUint8Array for bytes, encode/decode for text, and isValid before decoding untrusted input.'
+ }
+ },
+ createOnce(context) {
+ return {
+ CallExpression(node) {
+ const { callee } = node
+ if (callee.type === 'Identifier') {
+ if (isGlobalBase64Function(context.sourceCode, callee))
+ context.report({ node, messageId: 'handRolled' })
+ return
+ }
+ if (callee.type !== 'MemberExpression') return
+ const name = propertyName(callee)
+ const onGlobal =
+ callee.object.type === 'Identifier' && GLOBAL_OBJECTS.has(callee.object.name)
+ const bufferFrom =
+ name === 'from' &&
+ callee.object.type === 'Identifier' &&
+ callee.object.name === 'Buffer' &&
+ isBase64Encoding(node.arguments[1])
+ const toBase64String = name === 'toString' && isBase64Encoding(node.arguments[0])
+ if ((onGlobal && (name === 'atob' || name === 'btoa')) || bufferFrom || toBase64String)
+ context.report({ node, messageId: 'handRolled' })
+ }
+ }
+ }
+})
diff --git a/tools/lint/tests/base64.test.ts b/tools/lint/tests/base64.test.ts
new file mode 100644
index 000000000..806c771f8
--- /dev/null
+++ b/tools/lint/tests/base64.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, test } from 'bun:test'
+
+import { lint, ruleDiagnostics } from './helpers/lint.ts'
+
+const rule = 'no-hand-rolled-base64'
+const rules = { [`open-pencil/${rule}`]: 'error' }
+
+describe('no-hand-rolled-base64', () => {
+ test.each([
+ "atob('AA==')",
+ "btoa('a')",
+ "globalThis.atob('AA==')",
+ "window['btoa']('a')",
+ "Buffer.from(value, 'base64')",
+ "Buffer.from(value, 'base64url')",
+ "bytes.toString('base64')"
+ ])('rejects %s', async (source) => {
+ expect(ruleDiagnostics(await lint(source, rules), rule)).toHaveLength(1)
+ })
+
+ test.each([
+ "import { toUint8Array } from 'js-base64'; toUint8Array('AA==')",
+ 'function decode(atob: (value: string) => string) { return atob("AA==") }',
+ "Buffer.from(script, 'utf16le')",
+ "bytes.toString('hex')",
+ 'value.toString()'
+ ])('accepts %s', async (source) => {
+ expect(ruleDiagnostics(await lint(source, rules), rule)).toHaveLength(0)
+ })
+})
diff --git a/tools/release-packages/package.json b/tools/release-packages/package.json
index e942e2483..1705d85d3 100644
--- a/tools/release-packages/package.json
+++ b/tools/release-packages/package.json
@@ -18,6 +18,7 @@
"@open-pencil/package-quality-tools": "workspace:*",
"citty": "^0.1.6",
"es-toolkit": "^1.51.0",
+ "js-base64": "^3.9.3",
"valibot": "^1.4.2"
}
}
diff --git a/tools/release-packages/src/native/assemble.ts b/tools/release-packages/src/native/assemble.ts
index 48c2bd096..0c2dea1b2 100644
--- a/tools/release-packages/src/native/assemble.ts
+++ b/tools/release-packages/src/native/assemble.ts
@@ -4,6 +4,7 @@ import { join } from 'node:path'
import { readReleaseNotes } from '#release/release-notes'
import { isEqual } from 'es-toolkit'
+import { toUint8Array } from 'js-base64'
import * as v from 'valibot'
import { desktopAssets } from './catalog.ts'
@@ -41,7 +42,7 @@ const platforms: Record<string, { signature: string; url: string }> = {}
try {
const publicKey = join(temporary, 'key.pub')
- await writeFile(publicKey, Buffer.from(config.plugins.updater.pubkey, 'base64'))
+ await writeFile(publicKey, toUint8Array(config.plugins.updater.pubkey))
for (const [index, manifest] of manifests.entries()) {
const directory = directories[index]
@@ -71,7 +72,7 @@ try {
const signature = (await readFile(join(source, `${asset.name}.sig`), 'utf8')).trim()
const decoded = join(temporary, `${asset.name}.minisig`)
- await writeFile(decoded, Buffer.from(signature, 'base64'))
+ await writeFile(decoded, toUint8Array(signature))
await verifySignature(join(source, asset.name), publicKey, decoded)
for (const platform of asset.updaterKeys) {
diff --git a/tools/unit-tests/src/shards.ts b/tools/unit-tests/src/shards.ts
index 3e0d681f1..5dbcd842d 100644
--- a/tools/unit-tests/src/shards.ts
+++ b/tools/unit-tests/src/shards.ts
@@ -45,7 +45,6 @@ export const UNIT_TEST_GROUPS = {
fig: [
'packages/fig/tests',
'packages/kiwi/tests',
- 'tests/engine/bytes',
'tests/engine/figma',
'tests/engine/io',
'tests/engine/kiwi'
diff --git a/tools/visual-oracles/src/operations/bisect.ts b/tools/visual-oracles/src/operations/bisect.ts
index 7651f6639..e12ac37d9 100644
--- a/tools/visual-oracles/src/operations/bisect.ts
+++ b/tools/visual-oracles/src/operations/bisect.ts
@@ -6,10 +6,10 @@ import { parseArgs } from 'node:util'
import { $ } from 'bun'
-import { parseColor } from '@open-pencil/core/color'
import { headlessRenderNodes, initCanvasKit, parseFigFile } from '@open-pencil/core/io'
import { computeAllLayouts } from '@open-pencil/core/layout'
import type { SceneGraph } from '@open-pencil/scene-graph'
+import { parseColor } from '@open-pencil/scene-graph/color'
interface DiffMetrics {
mean: number