AI-native design editor. Open-source Figma alternative.
feat(core): serve the engine's files with a Vite plugin (#1720)
Danila Poyarkov7623adba21af
diff --git a/.storybook/preview.ts b/.storybook/preview.tsindex bbdbcfc65..428b2a0a9 100644--- a/.storybook/preview.ts+++ b/.storybook/preview.ts@@ -2,13 +2,13 @@ import { withThemeByDataAttribute } from '@storybook/addon-themes'import type { Preview, Renderer } from '@storybook/vue3-vite'import { watch } from 'vue'-import { installCanvasKitBinary } from '@/app/editor/canvas/canvaskit'-import { installBundledFonts } from '@/app/editor/fonts/bundled'+// Points Core at the engine files the openPencil() Vite plugin serves.+import '@/app/editor/canvas/canvaskit'+import { registerInterfaceFont } from '@/app/editor/fonts/interface'import { useAppTheme } from '@/app/shell/theme'import '@/app.css'-installBundledFonts()-installCanvasKitBinary()+registerInterfaceFont()const preview: Preview = {decorators: [diff --git a/AGENTS.md b/AGENTS.mdindex 4f79c214d..6cad08efe 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -52,7 +52,7 @@ Before a PR run `bun run check`, `bun run format`, `bun run test:unit`, and `bun- A package exports each name from exactly one entry, and never another package's names: a root entry holds the package's core model, domains get a subpath named after their source path, and consumers import a name from the package that declares it. The JSX runtime pair is the one exception (`check:packages`, `tools/checks/package-quality/src/checks/exports.ts`).- `bun run check:arch` enforces: public workspace exports, framework-neutral Core, no app services in views or shared UI, property-panel internals scoped to that panel.- The app, CLI, MCP server, and Vue SDK build layers from authored content (HTML, JSX, `.pen`) only through Core: IO `readDocument`, `readHTMLDocument`, `sceneGraphFromStyledHTML`, or `@open-pencil/core/design-jsx`, which lay the layers out. Format packages' own builders, such as `htmlToSceneGraph` or `parsePenFile`, skip that; `open-pencil/no-graph-builders-in-front-ends` (`check:arch`) rejects them outside Core.-- Package aliases are `#scene-graph/*`, `#core/*`, `#fig/*`, `#vue/*`, `#cli/*`, `#mcp/*`, `#cloud/*`, `#dom-css/*`, `#design-jsx/*`, `#emit/*`; a package's own tests use `#core-tests/*`, `#fig-tests/*`, `#dom-css-tests/*`, and `#cloud-tests/*`; the app uses `@/`. Prefer clear relative imports nearby. Never escape an alias root with `../` (for example `#tests/../vite`); fix module ownership instead.+- Package aliases are `#scene-graph/*`, `#core/*`, `#fig/*`, `#vue/*`, `#cli/*`, `#mcp/*`, `#cloud/*`, `#dom-css/*`, `#design-jsx/*`, `#emit/*`, plus `#core-assets/*.ttf` and `#core-assets/*.woff2` for the fonts in `packages/core/assets`; a package's own tests use `#core-tests/*`, `#fig-tests/*`, `#dom-css-tests/*`, and `#cloud-tests/*`; the app uses `@/`. Prefer clear relative imports nearby. Never escape an alias root with `../` (for example `#tests/../vite`); fix module ownership instead.- Never drill with `../../`: one `../` to a sibling folder is fine, two or more means an alias. This holds in tests as much as in source — a test reaches its package's source through `#<pkg>/*` and its own helpers through `#<pkg>-tests/*`. `open-pencil/no-deep-parent-relative-imports` enforces it for imports and `open-pencil/no-deep-parent-relative-paths` for paths built from `import.meta`; a new test directory must be added to `lint:structure` so the rules reach it.- Reuse named types from `@open-pencil/scene-graph`; do not respell `Color`, `Vector`, `SceneNode`, `Effect`, `Fill`, or `Stroke`.diff --git a/bun.lock b/bun.lockindex b1e3778c1..781d025af 100644--- a/bun.lock+++ b/bun.lock@@ -336,12 +336,15 @@"@types/rbush": "^4.0.0","typescript": "npm:@typescript/typescript6@^6.0.2","unplugin-raw": "^0.7.0",+ "vite": "8.1.4",},"peerDependencies": {"ai": "^7.0.127",+ "vite": ">=6",},"optionalPeers": ["ai",+ "vite",],},"packages/design-jsx": {diff --git a/changes/1720/added.md b/changes/1720/added.mdnew file mode 100644index 000000000..4debf34f4--- /dev/null+++ b/changes/1720/added.md@@ -0,0 +1 @@+- Vite apps serve CanvasKit's WebAssembly, the bundled fonts, and HarfBuzz's subsetter by adding `openPencil()` from `@open-pencil/core/node/vite`, and a host that does not serve one of them gets an error naming the file and the locator to set instead of a WebAssembly compile error (#1551).diff --git a/packages/core/package.json b/packages/core/package.jsonindex 8edabf8b4..2124f2571 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -13,12 +13,17 @@"assets"],"type": "module",- "sideEffects": false,+ "sideEffects": [+ "./src/runtime-assets/install.ts",+ "./dist/runtime-assets/install.js"+ ],"main": "./dist/index.js","types": "./dist/index.d.ts","imports": {"#core/*": "./src/*.ts",- "#core-tests/*": "./tests/*.ts"+ "#core-tests/*": "./tests/*.ts",+ "#core-assets/*.ttf": "./assets/*.ttf",+ "#core-assets/*.woff2": "./assets/*.woff2"},"exports": {"./package.json": "./package.json",@@ -159,6 +164,12 @@"import": "./dist/canvaskit.js","default": "./dist/canvaskit.js"},+ "./runtime-assets/install": {+ "bun": "./src/runtime-assets/install.ts",+ "types": "./dist/runtime-assets/install.d.ts",+ "import": "./dist/runtime-assets/install.js",+ "default": "./dist/runtime-assets/install.js"+ },"./layout": {"types": "./dist/layout.d.ts","import": "./dist/layout.js",@@ -169,6 +180,12 @@"types": "./dist/node/fs.d.ts","import": "./dist/node/fs.js","default": "./dist/node/fs.js"+ },+ "./node/vite": {+ "bun": "./src/node/vite.ts",+ "types": "./dist/node/vite.d.ts",+ "import": "./dist/node/vite.js",+ "default": "./dist/node/vite.js"}},"publishConfig": {@@ -238,14 +255,19 @@"@types/mdast": "^4.0.4","@types/rbush": "^4.0.0","typescript": "npm:@typescript/typescript6@^6.0.2",- "unplugin-raw": "^0.7.0"+ "unplugin-raw": "^0.7.0",+ "vite": "8.1.4"},"peerDependencies": {- "ai": "^7.0.127"+ "ai": "^7.0.127",+ "vite": ">=6"},"peerDependenciesMeta": {"ai": {"optional": true+ },+ "vite": {+ "optional": true}}}diff --git a/packages/core/src/canvaskit.ts b/packages/core/src/canvaskit.tsindex 4730b0379..68dad69a4 100644--- a/packages/core/src/canvaskit.ts+++ b/packages/core/src/canvaskit.ts@@ -1,9 +1,13 @@import CanvasKitInit, { type CanvasKit } from 'canvaskit-wasm/full'import { IS_BROWSER } from './constants'+import { servesRuntimeAsset, unservedRuntimeAssetMessage } from './runtime-assets/served'let instance: Promise<CanvasKit> | null = null+/** How long a failed load waits to learn whether its binary was served before giving up. */+const EXPLAIN_TIMEOUT_MS = 5000+/*** Maps a CanvasKit file name (`canvaskit.wasm`) to the URL it loads from. Mirrors the font* manager's bundled-font locator: under Node the file is read beside the package, since@@ -24,13 +28,35 @@ export function setCanvasKitLocator(locate: CanvasKitLocator): void {locator = locate}+/**+ * Why CanvasKit failed to load: when its binary is not served, an error naming the setup that+ * serves it, in place of the compile error the host's fallback page gave; otherwise the error.+ */+async function explainFailedLoad(url: string, error: unknown): Promise<unknown> {+ try {+ // Bounded, so a stalled request leaves the load failed rather than pending for every caller.+ const response = await fetch(url, { signal: AbortSignal.timeout(EXPLAIN_TIMEOUT_MS) })+ void response.body?.cancel()+ if (servesRuntimeAsset(response)) return error+ return new Error(+ unservedRuntimeAssetMessage('canvaskit.wasm', url, response, 'setCanvasKitLocator'),+ { cause: error }+ )+ } catch {+ return error+ }+}+/*** Loads CanvasKit once; callers that ask while it loads share the load, and a failed load is* retried. It is the full build, whose encoders write JPEG and WebP as well as PNG.*/export function getCanvasKit(options?: CanvasKitOptions): Promise<CanvasKit> {if (instance) return instance- const loading = CanvasKitInit({ locateFile: options?.locateFile ?? locator })+ const locate = options?.locateFile ?? locator+ const loading = CanvasKitInit({ locateFile: locate }).catch(async (error: unknown) => {+ throw IS_BROWSER ? await explainFailedLoad(locate('canvaskit.wasm'), error) : error+ })instance = loadingloading.catch(() => {if (instance === loading) instance = nulldiff --git a/packages/core/src/global.d.ts b/packages/core/src/global.d.tsindex c1f12f221..f29183562 100644--- a/packages/core/src/global.d.ts+++ b/packages/core/src/global.d.ts@@ -15,6 +15,12 @@ declare module '*?raw' {export default content}+/** A file a Vite build serves and emits, as its URL (`runtime-assets/install.ts`). */+declare module '*?url' {+ const url: string+ export default url+}+/** svg2pdf.js declares types for its package root only; its ES build is the same module. */declare module 'svg2pdf.js/dist/svg2pdf.es.min.js' {export * from 'svg2pdf.js'diff --git a/packages/core/src/node/vite.ts b/packages/core/src/node/vite.tsnew file mode 100644index 000000000..a22223d7d--- /dev/null+++ b/packages/core/src/node/vite.ts@@ -0,0 +1,42 @@+import type { Plugin } from 'vite'++/** The module that points Core at the files Vite serves (`runtime-assets/install.ts`). */+const RUNTIME_ASSETS_MODULE = '@open-pencil/core/runtime-assets/install'++export interface OpenPencilPluginOptions {+ /**+ * Adds the setup module to `index.html` ahead of the app's own scripts (default `true`). Turn+ * it off to import `@open-pencil/core/runtime-assets/install` yourself, as an app without an+ * `index.html`, or one that loads Core behind a gate of its own, does.+ */+ inject?: boolean+}++/**+ * Serves the files OpenPencil's engine loads at run time, CanvasKit's WebAssembly, the bundled+ * fonts, and HarfBuzz's subsetter, and points Core at them, so an app that uses+ * `@open-pencil/core` or `@open-pencil/vue` needs no setup of its own beyond adding this plugin.+ */+export function openPencil(options: OpenPencilPluginOptions = {}): Plugin {+ const inject = options.inject ?? true+ return {+ name: 'open-pencil:assets',+ // The module is pre-bundled like the rest of Core, so it sets the locators on the copy of+ // Core the app imports; Vite's pre-bundling keeps its `?url` imports for its asset handling.+ transformIndexHtml: {+ // Before Vite's own pass, which bundles the script with the page's in a build.+ order: 'pre',+ handler() {+ if (!inject) return []+ return [+ {+ tag: 'script',+ attrs: { type: 'module' },+ children: `import ${JSON.stringify(RUNTIME_ASSETS_MODULE)}`,+ injectTo: 'head-prepend'+ }+ ]+ }+ }+ }+}diff --git a/packages/core/src/runtime-assets/install.ts b/packages/core/src/runtime-assets/install.tsnew file mode 100644index 000000000..833954e25--- /dev/null+++ b/packages/core/src/runtime-assets/install.ts@@ -0,0 +1,33 @@+import caveatVariable from '#core-assets/CaveatVariable.woff2?url'+import interSemiBold from '#core-assets/Inter-SemiBold.ttf?url'+import interVariableItalic from '#core-assets/InterVariable-Italic.ttf?url'+import interVariable from '#core-assets/InterVariable.ttf?url'+import notoNaskhArabic from '#core-assets/NotoNaskhArabic-Regular.ttf?url'+import emojiMetrics from '#core-assets/OpenPencilEmojiMetrics-Regular.ttf?url'+/**+ * Points Core at the files it loads at run time, imported as Vite `?url` assets so a Vite build+ * serves them in development and emits them, hashed and under `base`, with the build. Importing+ * the module is the whole setup; the `openPencil()` plugin adds it to the page, and an app that+ * loads Core behind a gate of its own imports it there instead. Its `?url` imports stay as written in+ * `dist`, so the app's Vite resolves them, the fonts through Core's `#core-assets` import.+ */+import canvasKit from 'canvaskit-wasm/bin/full/canvaskit.wasm?url'+import harfBuzzSubset from 'harfbuzzjs/dist/harfbuzz-subset.wasm?url'++import { setCanvasKitLocator } from '#core/canvaskit'+import { setHarfBuzzSubsetLocator } from '#core/text/font/harfbuzz'+import { fontManager } from '#core/text/font/manager'++/** Every font file in `@open-pencil/core/assets`: the bundled faces and the stand-ins. */+const FONT_URLS: Record<string, string> = {+ 'CaveatVariable.woff2': caveatVariable,+ 'Inter-SemiBold.ttf': interSemiBold,+ 'InterVariable-Italic.ttf': interVariableItalic,+ 'InterVariable.ttf': interVariable,+ 'NotoNaskhArabic-Regular.ttf': notoNaskhArabic,+ 'OpenPencilEmojiMetrics-Regular.ttf': emojiMetrics+}++setCanvasKitLocator(() => canvasKit)+setHarfBuzzSubsetLocator(() => harfBuzzSubset)+fontManager.setBundledFontLocator((file) => FONT_URLS[file] ?? `/${file}`)diff --git a/packages/core/src/runtime-assets/served.ts b/packages/core/src/runtime-assets/served.tsnew file mode 100644index 000000000..107a19795--- /dev/null+++ b/packages/core/src/runtime-assets/served.ts@@ -0,0 +1,37 @@+/**+ * Core loads some files at run time: CanvasKit's WebAssembly, the bundled fonts, and HarfBuzz's+ * subsetter. A browser host serves them, and when it does not, a development server or an SPA+ * host answers with its HTML page, which would otherwise surface as a WebAssembly compile error+ * or an unreadable font.+ */++const SETUP_HINT =+ "Add openPencil() from '@open-pencil/core/node/vite' to the Vite config, or serve the file and point Core at it with"++/** `204 No Content`: `ok`, but with no file to read. */+const NO_CONTENT = 204++/** Whether the status carries a body: not an error, and not an empty answer. */+function answeredWithBody(response: Response): boolean {+ return response.ok && response.status !== NO_CONTENT+}++/** Whether a response carries the file asked for, not an error, an empty answer, or a fallback page. */+export function servesRuntimeAsset(response: Response): boolean {+ // Media types are case-insensitive, and a header keeps the case the server wrote.+ const type = (response.headers.get('content-type') ?? '').toLowerCase()+ return answeredWithBody(response) && !type.includes('text/html')+}++/** What a host that does not serve one of Core's files is told, naming the locator to set. */+export function unservedRuntimeAssetMessage(+ file: string,+ url: string,+ response: Response,+ locator: string+): string {+ const answer = answeredWithBody(response)+ ? (response.headers.get('content-type') ?? 'no content type')+ : response.status+ return `${file} is not served at ${url} (it answered ${answer}). ${SETUP_HINT} ${locator}.`+}diff --git a/packages/core/src/text/font/bundled.ts b/packages/core/src/text/font/bundled.tsindex 47d0353de..c21f819cb 100644--- a/packages/core/src/text/font/bundled.ts+++ b/packages/core/src/text/font/bundled.ts@@ -1,4 +1,5 @@import { IS_BROWSER } from '#core/constants'+import { servesRuntimeAsset, unservedRuntimeAssetMessage } from '#core/runtime-assets/served'/** Inter's weights, each drawn from Inter's variable files at its named instance. */const INTER_WEIGHTS = [@@ -68,9 +69,17 @@ export class BundledFonts {private async read(url: string): Promise<ArrayBuffer | null> {if (IS_BROWSER) {- const response = await fetch(this.locate(url.replace(/^\//, '')))- // A missing file answers with an error page, which must not be read as a font.- return response.ok ? response.arrayBuffer() : null+ const file = url.replace(/^\//, '')+ const located = this.locate(file)+ const response = await fetch(located)+ // A missing file answers with an error or fallback page, which must not be read as a font.+ if (!servesRuntimeAsset(response)) {+ void response.body?.cancel()+ throw new Error(+ unservedRuntimeAssetMessage(file, located, response, 'fontManager.setBundledFontLocator')+ )+ }+ return response.arrayBuffer()}const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')const packageJSONURL = import.meta.resolve('@open-pencil/core/package.json')diff --git a/packages/core/src/text/font/harfbuzz.ts b/packages/core/src/text/font/harfbuzz.tsindex 9d792c4a6..d30a97e07 100644--- a/packages/core/src/text/font/harfbuzz.ts+++ b/packages/core/src/text/font/harfbuzz.ts@@ -4,6 +4,7 @@ import type { FontVariation } from '@open-pencil/scene-graph'import { ResourceCache } from '#core/cache/resource'import { IS_BROWSER } from '#core/constants'+import { servesRuntimeAsset, unservedRuntimeAssetMessage } from '#core/runtime-assets/served'import { fontTableView } from './variation'@@ -87,7 +88,17 @@ async function readSubsetModule(): Promise<ArrayBuffer> {const url = locator()if (IS_BROWSER || !url.startsWith('file:')) {const response = await fetch(url)- if (!response.ok) throw new Error(`HarfBuzz subsetter answered ${response.status}`)+ if (!servesRuntimeAsset(response)) {+ void response.body?.cancel()+ throw new Error(+ unservedRuntimeAssetMessage(+ 'harfbuzz-subset.wasm',+ url,+ response,+ 'setHarfBuzzSubsetLocator'+ )+ )+ }return response.arrayBuffer()}const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')diff --git a/packages/core/tests/node/vite.test.ts b/packages/core/tests/node/vite.test.tsnew file mode 100644index 000000000..dec4b8442--- /dev/null+++ b/packages/core/tests/node/vite.test.ts@@ -0,0 +1,101 @@+import { afterAll, describe, expect, test } from 'bun:test'+import { mkdtemp, readdir, realpath, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { corePackagePath } from '#core-tests/helpers/paths'+import { build, defaultClientConditions, type Rolldown } from 'vite'++import { openPencil, type OpenPencilPluginOptions } from '@open-pencil/core/node/vite'++const CORE_SOURCE = corePackagePath('src')+const CORE_ASSETS = corePackagePath('assets')++// A page loads CanvasKit, as an app does: a locator nothing reads is left out of the bundle.+const LOAD_CANVASKIT =+ "import { getCanvasKit } from '@open-pencil/core/canvaskit'\nwindow.loadCanvasKit = getCanvasKit\n"++const roots: string[] = []++afterAll(() => Promise.all(roots.map((root) => rm(root, { recursive: true, force: true }))))++type Output = Array<Rolldown.OutputChunk | Rolldown.OutputAsset>++async function buildPage(+ options?: OpenPencilPluginOptions,+ { base = '/', main = LOAD_CANVASKIT } = {}+): Promise<Output> {+ // Real path: Vite names the page by its path relative to the root, which a symlinked temp dir breaks.+ const root = await realpath(await mkdtemp(join(tmpdir(), 'open-pencil-vite-')))+ roots.push(root)+ await writeFile(+ join(root, 'index.html'),+ '<!doctype html><html><head></head><body><script type="module" src="./main.js"></script></body></html>'+ )+ await writeFile(join(root, 'main.js'), main)+ const result = await build({+ root,+ base,+ logLevel: 'silent',+ configFile: false,+ // Workspace packages build from source, as tests run without their `dist`: Core through the+ // aliases, which keep its assets beside the sources as the app's do, and the packages it+ // imports through their `bun` export condition.+ resolve: {+ alias: [+ { find: /^@open-pencil\/core\/assets\//, replacement: `${CORE_ASSETS}/` },+ { find: /^@open-pencil\/core\/(.*)$/, replacement: `${CORE_SOURCE}/$1` }+ ],+ conditions: ['bun', ...defaultClientConditions]+ },+ build: { write: false, minify: false },+ plugins: [openPencil(options)]+ })+ const outputs = Array.isArray(result) ? result : [result]+ return outputs.flatMap((output) => ('output' in output ? output.output : []))+}++function code(output: Output): string {+ return output+ .filter((item): item is Rolldown.OutputChunk => item.type === 'chunk')+ .map((chunk) => chunk.code)+ .join('\n')+}++function assetNames(output: Output): string[] {+ return output.filter((item) => item.type === 'asset').map((item) => item.fileName)+}++async function expectEngineFiles(output: Output): Promise<void> {+ const assets = assetNames(output)+ const fonts = (await readdir(CORE_ASSETS)).filter((file) => /\.(?:ttf|woff2)$/.test(file))+ for (const file of ['canvaskit', 'harfbuzz-subset', ...fonts.map((f) => f.replace(/\..*$/, ''))])+ expect(assets.some((name) => new RegExp(`^assets/${file}-[\\w-]+\\.\\w+$`).test(name))).toBe(+ true+ )+}++describe('openPencil Vite plugin', () => {+ test('emits every engine file under base and points Core at them from the page', async () => {+ const output = await buildPage(undefined, { base: '/editor/' })+ await expectEngineFiles(output)++ const js = code(output)+ expect(js).toContain('/editor/assets/canvaskit-')+ expect(js).toContain('setBundledFontLocator')+ const html = output.find((item) => item.fileName === 'index.html')+ expect(html?.type === 'asset' ? String(html.source) : '').not.toContain('runtime-assets')+ }, 60_000)++ test('leaves the page alone without injection, and the app imports the module itself', async () => {+ const alone = await buildPage({ inject: false })+ expect(assetNames(alone).some((name) => name.includes('canvaskit'))).toBe(false)++ const imported = await buildPage(+ { inject: false },+ { main: `import '@open-pencil/core/runtime-assets/install'\n${LOAD_CANVASKIT}` }+ )+ await expectEngineFiles(imported)+ expect(code(imported)).toContain('/assets/canvaskit-')+ }, 60_000)+})diff --git a/packages/core/tests/runtime-assets/served.test.ts b/packages/core/tests/runtime-assets/served.test.tsnew file mode 100644index 000000000..c9d0dddfe--- /dev/null+++ b/packages/core/tests/runtime-assets/served.test.ts@@ -0,0 +1,40 @@+import { describe, expect, test } from 'bun:test'++import { servesRuntimeAsset, unservedRuntimeAssetMessage } from '#core/runtime-assets/served'++function response(status: number, contentType: string): Response {+ return new Response(status === 204 ? null : 'body', {+ status,+ headers: { 'content-type': contentType }+ })+}++describe('runtime assets', () => {+ test('a file is served when it answers with itself, not an error or the fallback page', () => {+ expect(servesRuntimeAsset(response(200, 'application/wasm'))).toBe(true)+ expect(servesRuntimeAsset(response(200, 'font/ttf'))).toBe(true)+ expect(servesRuntimeAsset(response(200, 'text/html; charset=utf-8'))).toBe(false)+ expect(servesRuntimeAsset(response(200, 'Text/HTML; charset=utf-8'))).toBe(false)+ expect(servesRuntimeAsset(response(404, 'text/plain'))).toBe(false)+ expect(servesRuntimeAsset(response(204, 'font/ttf'))).toBe(false)+ })++ test('the message names the file, what answered, the plugin, and the locator', () => {+ expect(+ unservedRuntimeAssetMessage(+ 'canvaskit.wasm',+ '/canvaskit.wasm',+ response(200, 'text/html'),+ 'setCanvasKitLocator'+ )+ ).toBe(+ "canvaskit.wasm is not served at /canvaskit.wasm (it answered text/html). Add openPencil() from '@open-pencil/core/node/vite' to the Vite config, or serve the file and point Core at it with setCanvasKitLocator."+ )+ expect(+ unservedRuntimeAssetMessage('Inter.ttf', '/Inter.ttf', response(404, 'text/plain'), 'x')+ ).toContain('(it answered 404)')+ expect(+ unservedRuntimeAssetMessage('Inter.ttf', '/Inter.ttf', response(204, 'font/ttf'), 'x')+ ).toContain('(it answered 204)')+ })+})diff --git a/packages/core/tsdown.config.ts b/packages/core/tsdown.config.tsindex 4a514e6ff..78f915432 100644--- a/packages/core/tsdown.config.ts+++ b/packages/core/tsdown.config.ts@@ -22,7 +22,9 @@ export default defineConfig({deps: {neverBundle: [...Object.keys({ ...packageJSON.dependencies, ...packageJSON.peerDependencies }),- /^node:/+ /^node:/,+ // The runtime assets module's `?url` imports stay as written, for the host's Vite.+ /\?url$/],onlyBundle: false}diff --git a/packages/docs/.vitepress/theme/landing/stage/engine-assets.ts b/packages/docs/.vitepress/theme/landing/stage/engine-assets.tsindex 627b47aab..260f999c0 100644--- a/packages/docs/.vitepress/theme/landing/stage/engine-assets.ts+++ b/packages/docs/.vitepress/theme/landing/stage/engine-assets.ts@@ -1,20 +1,16 @@import { getCanvasKit } from '@open-pencil/core/canvaskit'-import { installCanvasKitBinary } from '@/app/editor/canvas/canvaskit'-import { installBundledFonts } from '@/app/editor/fonts/bundled'+// The app's module that points Core at the files the openPencil() Vite plugin serves.+import '@/app/editor/canvas/canvaskit'+import { registerInterfaceFont } from '@/app/editor/fonts/interface'-/**- * The landing installs the app's emitted CanvasKit binary and fonts, so Vite serves both in- * development and emits them with the build.- */let ready: Promise<void> | null = null/** Loads CanvasKit from the emitted binary. Stages await it before mounting a canvas. */export function prepareEngine(): Promise<void> {if (ready) return readyconst request = (async () => {- installBundledFonts()- installCanvasKitBinary()+ registerInterfaceFont()await getCanvasKit()})()// A failed download is tried again by the next stage rather than shared.diff --git a/packages/docs/AGENTS.md b/packages/docs/AGENTS.mdindex 4c855c311..d3dea8809 100644--- a/packages/docs/AGENTS.md+++ b/packages/docs/AGENTS.md@@ -12,7 +12,7 @@ Published VitePress site. `bun run docs:dev`, `bun run docs:build` for fast chec## Landing-- The landing page (`.vitepress/theme/landing/`) mounts the app's own components, so the site takes the app's aliases, icon plugins, and build constants from `appSourceConfig()` in `@open-pencil/vite-config` (`vite/`) and its design tokens from `src/theme/tokens.css`. CanvasKit and core's bundled fonts come from the app's asset installers (`installCanvasKitBinary`, `installBundledFonts`), called in `landing/stage/engine-assets.ts`; do not copy them into `public/`. Server-rendered sections must not import from `landing/stage/`; they reach it through the client-only `ui/StageFrame.vue`, whose imports are guarded by `import.meta.env.SSR` so the server build never compiles the editor.+- The landing page (`.vitepress/theme/landing/`) mounts the app's own components, so the site takes the app's aliases, icon plugins, and build constants from `appSourceConfig()` in `@open-pencil/vite-config` (`vite/`) and its design tokens from `src/theme/tokens.css`. CanvasKit and core's bundled fonts are served by the `openPencil()` plugin `appSourceConfig()` includes and set up by the app's `@/app/editor/canvas/canvaskit` module, which `landing/stage/engine-assets.ts` imports; do not copy them into `public/`. Server-rendered sections must not import from `landing/stage/`; they reach it through the client-only `ui/StageFrame.vue`, whose imports are guarded by `import.meta.env.SSR` so the server build never compiles the editor.- The landing (`.vitepress/theme/landing/**`) is part of the root `tsconfig.json`, `bun run lint`, and `bun run format`, so it is checked with the app; its `#docs/*` imports resolve there to `.vitepress/*`, and it alone may import the app through `@/` (`oxlint.json` overrides).- Each landing stage is one document pinned with `provideTabEditorStore()` and one WebGL canvas that mounts once and is never unmounted. Browsers cap WebGL contexts per page, so do not use the app's two-canvas `EditorCanvas` there or mount and unmount stages on scroll (`landing/stage/StageCanvas.vue`).- The collaboration stage (`landing/stage/collab/`) joins two stages to one room through `createLocalRoom()`, an in-page `CollabRoomTransport`, and the app's own `openRoomSession()`; it never reaches the network or IndexedDB. It is the only stage with two canvases, so the page holds one more WebGL context than it has stages.diff --git a/packages/docs/programmable/sdk/getting-started.md b/packages/docs/programmable/sdk/getting-started.mdindex a764a919c..258dc803e 100644--- a/packages/docs/programmable/sdk/getting-started.md+++ b/packages/docs/programmable/sdk/getting-started.md@@ -19,6 +19,33 @@ import { provideEditor } from '@open-pencil/vue'import { useCanvas } from '@open-pencil/vue/canvas/surface'```+## Serve the engine's files++The canvas loads files at run time: CanvasKit's WebAssembly, the bundled fonts, and HarfBuzz's subsetter for PDF export. With Vite, add the `openPencil()` plugin and they are served in development and emitted with the build:++```ts+// vite.config.ts+import vue from '@vitejs/plugin-vue'+import { defineConfig } from 'vite'+import { openPencil } from '@open-pencil/core/node/vite'++export default defineConfig({+ plugins: [vue(), openPencil()],+})+```++The plugin adds `@open-pencil/core/runtime-assets/install` to `index.html`, a module that imports each file as a Vite asset and tells Core where it is. An app that loads Core behind a gate of its own, or has no `index.html`, passes `openPencil({ inject: false })` and imports that module itself before Core loads anything.++With another bundler, serve these files and point Core at them before the canvas mounts:++| File | Comes from | Point Core at it with |+| --- | --- | --- |+| `canvaskit.wasm` | `canvaskit-wasm/bin/full/` | `setCanvasKitLocator` from `@open-pencil/core/canvaskit` |+| Bundled fonts (`*.ttf`, `*.woff2`) | `@open-pencil/core/assets/` | `fontManager.setBundledFontLocator` from `@open-pencil/core/text` |+| `harfbuzz-subset.wasm` | `harfbuzzjs/dist/` | `setHarfBuzzSubsetLocator` from `@open-pencil/core/text` |++Without a locator, Core requests each file from the site root, such as `/canvaskit.wasm`. When a file is missing there, the error names it and the locator to set.+## Mental modelThere are three layers:diff --git a/packages/vue/README.md b/packages/vue/README.mdindex 111e959bb..04ef1c49c 100644--- a/packages/vue/README.md+++ b/packages/vue/README.md@@ -19,6 +19,17 @@ bun add @open-pencil/vue @open-pencil/core @open-pencil/scene-graph canvaskit-waThe current development version requires Vue `^3.5.41` and, when supplying the optional CanvasKit peer, `canvaskit-wasm >=0.41.1`. See [SDK Getting Started](https://openpencil.dev/programmable/sdk/getting-started) for migration guidance; older releases may have different peer requirements.+With Vite, add the plugin that serves the engine's WebAssembly and fonts; other bundlers set Core's locators instead (see the guide):++```ts+// vite.config.ts+import vue from '@vitejs/plugin-vue'+import { defineConfig } from 'vite'+import { openPencil } from '@open-pencil/core/node/vite'++export default defineConfig({ plugins: [vue(), openPencil()] })+```+## Quick start```vuediff --git a/packages/vue/example/src/main.ts b/packages/vue/example/src/main.tsindex b0f7c17cf..912d54f8d 100644--- a/packages/vue/example/src/main.ts+++ b/packages/vue/example/src/main.ts@@ -1,11 +1,5 @@-import canvasKitWasm from 'canvaskit-wasm/bin/full/canvaskit.wasm?url'import { createApp } from 'vue'-import { setCanvasKitLocator } from '@open-pencil/core/canvaskit'-import App from './App.vue'-// Vite serves CanvasKit's binary from the package and emits it with the build.-setCanvasKitLocator(() => canvasKitWasm)-createApp(App).mount('#app')diff --git a/packages/vue/example/vite.config.ts b/packages/vue/example/vite.config.tsindex 542515eb7..8e6b38c26 100644--- a/packages/vue/example/vite.config.ts+++ b/packages/vue/example/vite.config.ts@@ -1,8 +1,10 @@-import { defineConfig } from 'vite'import vue from '@vitejs/plugin-vue'+import { defineConfig } from 'vite'++import { openPencil } from '@open-pencil/core/node/vite'export default defineConfig({- plugins: [vue()],+ plugins: [vue(), openPencil()],server: {port: 3333}diff --git a/src/app/editor/canvas/canvaskit.ts b/src/app/editor/canvas/canvaskit.tsindex cce262073..47bde2b90 100644--- a/src/app/editor/canvas/canvaskit.ts+++ b/src/app/editor/canvas/canvaskit.ts@@ -1,15 +1,7 @@-import canvasKitWasm from 'canvaskit-wasm/bin/full/canvaskit.wasm?url'--import { getCanvasKit, setCanvasKitLocator } from '@open-pencil/core/canvaskit'--/**- * Importing CanvasKit's binary as an asset lets Vite serve it in development and emit a hashed- * copy with the build, so no host keeps a second copy in `public/`. Kept apart from other- * modules because `?url` imports only resolve in a Vite build, not in the Bun test runner.- */-export function installCanvasKitBinary(): void {- setCanvasKitLocator(() => canvasKitWasm)-}+// Points Core at the CanvasKit binary, bundled fonts, and HarfBuzz subsetter Vite serves;+// importing the module is what sets them, before anything loads.+import '@open-pencil/core/runtime-assets/install'+import { getCanvasKit } from '@open-pencil/core/canvaskit'/*** Starts loading CanvasKit as the app starts, so a document the app opens with does not wait fordiff --git a/src/app/editor/fonts/bundled.ts b/src/app/editor/fonts/bundled.tsdeleted file mode 100644index 1effc5a4e..000000000--- a/src/app/editor/fonts/bundled.ts+++ /dev/null@@ -1,55 +0,0 @@-import harfBuzzSubset from 'harfbuzzjs/dist/harfbuzz-subset.wasm?url'--import caveatVariable from '@open-pencil/core/assets/CaveatVariable.woff2?url'-import interSemiBold from '@open-pencil/core/assets/Inter-SemiBold.ttf?url'-import interVariableItalic from '@open-pencil/core/assets/InterVariable-Italic.ttf?url'-import interVariable from '@open-pencil/core/assets/InterVariable.ttf?url'-import notoNaskhArabic from '@open-pencil/core/assets/NotoNaskhArabic-Regular.ttf?url'-import emojiMetrics from '@open-pencil/core/assets/OpenPencilEmojiMetrics-Regular.ttf?url'-import { fontManager, setHarfBuzzSubsetLocator } from '@open-pencil/core/text'--/**- * Core ships its bundled fonts in `@open-pencil/core/assets`. Importing them as assets lets- * Vite serve them in development and emit hashed copies with the build, so no host keeps a- * second copy in `public/`. Kept apart from `index.ts` because `?url` imports only resolve- * in a Vite build, not in the Bun test runner.- */-const BUNDLED_FONT_URLS: Record<string, string> = {- 'InterVariable.ttf': interVariable,- 'InterVariable-Italic.ttf': interVariableItalic,- 'Inter-SemiBold.ttf': interSemiBold,- 'NotoNaskhArabic-Regular.ttf': notoNaskhArabic,- 'OpenPencilEmojiMetrics-Regular.ttf': emojiMetrics,- 'CaveatVariable.woff2': caveatVariable-}--/**- * Points core at the emitted font files, and at HarfBuzz's subsetter, which cuts static files of- * variable font instances for PDF export. Call before any font loads.- */-export function installBundledFonts(): void {- fontManager.setBundledFontLocator((file) => BUNDLED_FONT_URLS[file] ?? `/${file}`)- setHarfBuzzSubsetLocator(() => harfBuzzSubset)- registerInterfaceFont()-}--/** The interface's font, as `app.css` names it, and the weights its variable files cover. */-const INTERFACE_FONT_FAMILY = 'Inter'-const INTERFACE_FONT_WEIGHTS = '100 900'--/**- * The interface is set in Inter. Its variable files are registered for the page at start, for- * every weight, so Home and every panel draw in Inter's own weights on any system, whether Inter- * is installed or not and before a canvas loads the font for its own text.- */-function registerInterfaceFont(): void {- if (typeof document === 'undefined') return- for (const [url, style] of [- [interVariable, 'normal'],- [interVariableItalic, 'italic']- ] as const) {- document.fonts.add(- new FontFace(INTERFACE_FONT_FAMILY, `url(${url})`, { weight: INTERFACE_FONT_WEIGHTS, style })- )- }-}diff --git a/src/app/editor/fonts/interface.ts b/src/app/editor/fonts/interface.tsnew file mode 100644index 000000000..9ef1a9ff7--- /dev/null+++ b/src/app/editor/fonts/interface.ts@@ -0,0 +1,24 @@+import interVariableItalic from '@open-pencil/core/assets/InterVariable-Italic.ttf?url'+import interVariable from '@open-pencil/core/assets/InterVariable.ttf?url'++/** The interface's font, as `app.css` names it, and the weights its variable files cover. */+const INTERFACE_FONT_FAMILY = 'Inter'+const INTERFACE_FONT_WEIGHTS = '100 900'++/**+ * The interface is set in Inter. Its variable files are registered for the page at start, for+ * every weight, so Home and every panel draw in Inter's own weights on any system, whether Inter+ * is installed or not and before a canvas loads the font for its own text. Kept apart from+ * `index.ts` because `?url` imports only resolve in a Vite build, not in the Bun test runner.+ */+export function registerInterfaceFont(): void {+ if (typeof document === 'undefined') return+ for (const [url, style] of [+ [interVariable, 'normal'],+ [interVariableItalic, 'italic']+ ] as const) {+ document.fonts.add(+ new FontFace(INTERFACE_FONT_FAMILY, `url(${url})`, { weight: INTERFACE_FONT_WEIGHTS, style })+ )+ }+}diff --git a/src/boot.ts b/src/boot.tsindex f0f52a523..ec16f6a52 100644--- a/src/boot.ts+++ b/src/boot.ts@@ -8,9 +8,9 @@ import { createRetainedScopePlugin } from '@open-pencil/vue/lifecycle/retention'import './app.css'import { recordRuntimeError } from '@/app/diagnostics'import { installNativeFigArchives } from '@/app/document/io/native-fig'-import { installCanvasKitBinary, preloadCanvasKit } from '@/app/editor/canvas/canvaskit'+import { preloadCanvasKit } from '@/app/editor/canvas/canvaskit'import { preloadFonts } from '@/app/editor/fonts'-import { installBundledFonts } from '@/app/editor/fonts/bundled'+import { registerInterfaceFont } from '@/app/editor/fonts/interface'import { reportErrorAction } from '@/app/reports/state'import { observeBootErrors } from '@/app/shell/support/boot'import { reportBootFailure } from '@/app/shell/support/gate'@@ -26,9 +26,8 @@ import router from './router'* evaluates the app bundle and can still show the gate's guidance.*/export async function boot(): Promise<void> {- installBundledFonts()+ registerInterfaceFont()if (IS_TAURI) installNativeFigArchives()- installCanvasKitBinary()preloadCanvasKit()preloadFonts()const head = createHead()diff --git a/tools/checks/package-quality/src/smoke/runtime.ts b/tools/checks/package-quality/src/smoke/runtime.tsindex 92972af12..e69334b07 100644--- a/tools/checks/package-quality/src/smoke/runtime.ts+++ b/tools/checks/package-quality/src/smoke/runtime.ts@@ -37,7 +37,9 @@ export async function verifyPublicImports(consumerDirectory: string,execute: typeof runCommand = runCommand): Promise<void> {- const skipped = new Set(['@open-pencil/mcp/stdio'])+ // The stdio server starts on import; the runtime assets module imports `?url` assets, which+ // only a Vite build resolves, and the plugin's Vite build test covers it instead.+ const skipped = new Set(['@open-pencil/mcp/stdio', '@open-pencil/core/runtime-assets/install'])const specifiers = manifests.flatMap(concreteImportSpecifiers).filter((specifier) => !skipped.has(specifier))diff --git a/tools/checks/package-quality/tests/runtime.test.ts b/tools/checks/package-quality/tests/runtime.test.tsindex f2d8e4212..70cf9f1c1 100644--- a/tools/checks/package-quality/tests/runtime.test.ts+++ b/tools/checks/package-quality/tests/runtime.test.ts@@ -6,7 +6,7 @@ import { measurePhase } from '#package-quality/timing'import type { CommandRequest } from '@open-pencil/package-artifacts-tools'-test('public imports retain separate bounded Node and Bun invocations and the stdio exclusion', async () => {+test('public imports retain separate bounded Node and Bun invocations and their exclusions', async () => {const requests: CommandRequest[] = []const release = Promise.withResolvers<undefined>()const verification = verifyPublicImports(@@ -20,6 +20,11 @@ test('public imports retain separate bounded Node and Bun invocations and the stname: '@open-pencil/mcp',version: '1.0.0',exports: { '.': './index.js', './stdio': './stdio.js' }+ },+ {+ name: '@open-pencil/core',+ version: '1.0.0',+ exports: { './runtime-assets/install': './dist/runtime-assets/install.js' }}],'/fixture',diff --git a/tools/release/package-artifacts/src/manifest/exports.ts b/tools/release/package-artifacts/src/manifest/exports.tsindex 28932a779..5ab9764d9 100644--- a/tools/release/package-artifacts/src/manifest/exports.ts+++ b/tools/release/package-artifacts/src/manifest/exports.ts@@ -116,7 +116,7 @@ export function validateManifest(manifest: PackageManifest): PackageDiagnostic[]// file. A target naming another package resolves through that package's exports instead.for (const entry of collectExportTargets(manifest.imports, ['imports'])) {const local = entry.target.startsWith('./')- if (local && entry.target.includes('*') && !/\.[a-z]+$/i.test(entry.target)) {+ if (local && entry.target.includes('*') && !/\.[a-z0-9]+$/i.test(entry.target)) {report(entry.field, `wildcard target names no extension (${entry.target})`)}}diff --git a/tools/release/package-artifacts/tests/exports.test.ts b/tools/release/package-artifacts/tests/exports.test.tsindex e4dc913af..5217876b1 100644--- a/tools/release/package-artifacts/tests/exports.test.ts+++ b/tools/release/package-artifacts/tests/exports.test.ts@@ -71,6 +71,12 @@ describe('export metadata', () => {])})+ test('accepts a wildcard import target whose extension has a digit', () => {+ expect(+ validateManifest({ ...validManifest, imports: { '#fonts/*.woff2': './assets/*.woff2' } })+ ).toEqual([])+ })+test('accepts a wildcard import target that names an index file', () => {expect(validateManifest({diff --git a/vite.config.ts b/vite.config.tsindex 8e7242ebd..b98e0a5bb 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -9,6 +9,7 @@ import Components from 'unplugin-vue-components/vite'import { defineConfig, loadEnv } from 'vite'import { ensureBrandAssets } from '@open-pencil/brand-tools'+import { openPencil } from '@open-pencil/core/node/vite'import { ensureDemoDocument } from '@open-pencil/demo-tools'import packageJson from './package.json'@@ -72,6 +73,9 @@ export default defineConfig(async ({ command, mode }) => {pages: ['index.html', 'cloud.html', 'metrics.html']}),tailwindcss(),+ // Not added to the page: Core loads behind the support gate, so the app's canvas module,+ // which `boot.ts` loads, imports @open-pencil/core/runtime-assets/install itself.+ openPencil({ inject: false }),Icons({ compiler: 'vue3', customCollections: { ai: aiIconCollection() } }),Components({ resolvers: [IconsResolver({ prefix: 'icon', customCollections: ['ai'] })] }),automation ? openPencilAutomationPlugin(command, host) : undefined,diff --git a/vite/app-source.ts b/vite/app-source.tsindex ceaec98ca..54760115f 100644--- a/vite/app-source.ts+++ b/vite/app-source.ts@@ -6,6 +6,8 @@ import Icons from 'unplugin-icons/vite'import Components from 'unplugin-vue-components/vite'import type { Alias, Plugin, PluginOption } from 'vite'+import { openPencil } from '@open-pencil/core/node/vite'+import rootManifest from '../package.json' with { type: 'json' }import { createOpenPencilAliases } from './aliases.ts'import { inlineScriptPlugin } from './inline-script.ts'@@ -74,6 +76,8 @@ export function appSourceConfig(): AppSourceConfig {plugins: [appRawText(),inlineScriptPlugin(),+ // The app's canvas module imports the module that points Core at the engine's files.+ openPencil({ inject: false }),Icons({ compiler: 'vue3' }),Components({ dirs: [], dts: false, resolvers: [IconsResolver({ prefix: 'icon' })] })]