AI-native design editor. Open-source Figma alternative.
refactor: import Tauri modules statically, and lint inline imports (#1631)
Danila Poyarkove0defef22989
diff --git a/AGENTS.md b/AGENTS.mdindex 36fc70a13..891dfa30b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -9,28 +9,28 @@ This file holds the repository map and the rules that apply everywhere. Rules fo| Path | Owns | Guide || ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- || `packages/scene-graph` | Framework-neutral graph, node types, geometry, copy/snap/undo, variables, instances, hit testing, plus the shared primitives formats need: color conversion and management, CSS value parsing, text/layout direction | `packages/scene-graph/AGENTS.md` |-| `packages/pen` | Pencil.dev `.pen` model, parser, SceneGraph adapter | — |-| `packages/drawio` | draw.io model, reader and writer for `.drawio`/`.dio` files and the diagrams draw.io PNG and SVG exports embed; no SceneGraph | — |-| `packages/kiwi` | SceneGraph-independent Kiwi schema/runtime, codecs, containers, parse helpers | `packages/fig/AGENTS.md` |-| `packages/fig` | `.fig` archives, SceneGraph conversion, metadata policy, component/instance interpretation, Figma clipboard | `packages/fig/AGENTS.md` |-| `packages/core` | Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, document I/O; depends on scene-graph and the format packages (pen, drawio, kiwi, fig, dom-css, design-jsx); no browser DOM | `packages/core/AGENTS.md` |-| `packages/dom-css` | DOM/CSS/HTML/JSX/Tailwind projection and browser/headless adapters; depends only on scene-graph and emit, and takes engine services such as web-font resolution as injected options | `packages/dom-css/AGENTS.md` |-| `packages/emit` | Source emission for exporters: ESTree and JSX builders, template filling, and esrap printing, with the literal rules that keep exported strings from being reinterpreted | — |-| `packages/design-jsx` | OpenPencil design JSX: elements, paint/effect helpers, variables, schema and authoring reference, JSX export, and a renderer that takes icons, SVG, and layout as injected services | `packages/design-jsx/AGENTS.md` |-| `packages/vue` | Headless Vue 3 SDK primitives, composables, commands, i18n, menu model | `packages/vue/AGENTS.md` |-| `packages/cli` | Headless `.fig` inspection, export, linting, `eval` | `packages/cli/AGENTS.md` |-| `packages/mcp` | stdio and Hono HTTP MCP server reusing Core tools | `packages/mcp/AGENTS.md` |-| `packages/harness` | Optional Node companion for HarnessAgent sessions | `packages/harness/AGENTS.md` |-| `packages/feedback` | Cloudflare Worker at `feedback.openpencil.dev`: daily ping counts, opt-in usage stats proxied to PostHog, Cloud waitlist; its contract defines every field the app may send | `packages/feedback/AGENTS.md` |-| `packages/cloud` | Optional self-hostable backend: contracts, typed client, Hono server, Node runtime, PostgreSQL migrations, transactional email | `packages/cloud/AGENTS.md` |-| `packages/docs` | Published VitePress site | `packages/docs/AGENTS.md` |-| `src` | Tauri/Vite app: services and state in `src/app/**`, views in `src/views/**`, UI in `src/components/**` | `src/AGENTS.md` |-| `desktop` | Tauri v2 shell, capabilities, native credentials, menus | `desktop/AGENTS.md` |-| `vite` | The app's Vite plugins, aliases, and dev server; `appSourceConfig()` lends the aliases, icons, and build constants to the docs landing | — |-| `tests` | Central app, integration, E2E, native, and Figma acceptance tests | `tests/AGENTS.md` |-| `tools`, `.github` | Private repo tooling, CI classification, releases, brand generation | `tools/AGENTS.md` |-| `skills/open-pencil` | Installable agent skill | `packages/core/AGENTS.md` (Tools) |-| `assets/brand` | Canonical brand artwork | `assets/brand/README.md` |+| `packages/pen` | Pencil.dev `.pen` model, parser, SceneGraph adapter | — |+| `packages/drawio` | draw.io model, reader and writer for `.drawio`/`.dio` files and the diagrams draw.io PNG and SVG exports embed; no SceneGraph | — |+| `packages/kiwi` | SceneGraph-independent Kiwi schema/runtime, codecs, containers, parse helpers | `packages/fig/AGENTS.md` |+| `packages/fig` | `.fig` archives, SceneGraph conversion, metadata policy, component/instance interpretation, Figma clipboard | `packages/fig/AGENTS.md` |+| `packages/core` | Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, document I/O; depends on scene-graph and the format packages (pen, drawio, kiwi, fig, dom-css, design-jsx); no browser DOM | `packages/core/AGENTS.md` |+| `packages/dom-css` | DOM/CSS/HTML/JSX/Tailwind projection and browser/headless adapters; depends only on scene-graph and emit, and takes engine services such as web-font resolution as injected options | `packages/dom-css/AGENTS.md` |+| `packages/emit` | Source emission for exporters: ESTree and JSX builders, template filling, and esrap printing, with the literal rules that keep exported strings from being reinterpreted | — |+| `packages/design-jsx` | OpenPencil design JSX: elements, paint/effect helpers, variables, schema and authoring reference, JSX export, and a renderer that takes icons, SVG, and layout as injected services | `packages/design-jsx/AGENTS.md` |+| `packages/vue` | Headless Vue 3 SDK primitives, composables, commands, i18n, menu model | `packages/vue/AGENTS.md` |+| `packages/cli` | Headless `.fig` inspection, export, linting, `eval` | `packages/cli/AGENTS.md` |+| `packages/mcp` | stdio and Hono HTTP MCP server reusing Core tools | `packages/mcp/AGENTS.md` |+| `packages/harness` | Optional Node companion for HarnessAgent sessions | `packages/harness/AGENTS.md` |+| `packages/feedback` | Cloudflare Worker at `feedback.openpencil.dev`: daily ping counts, opt-in usage stats proxied to PostHog, Cloud waitlist; its contract defines every field the app may send | `packages/feedback/AGENTS.md` |+| `packages/cloud` | Optional self-hostable backend: contracts, typed client, Hono server, Node runtime, PostgreSQL migrations, transactional email | `packages/cloud/AGENTS.md` |+| `packages/docs` | Published VitePress site | `packages/docs/AGENTS.md` |+| `src` | Tauri/Vite app: services and state in `src/app/**`, views in `src/views/**`, UI in `src/components/**` | `src/AGENTS.md` |+| `desktop` | Tauri v2 shell, capabilities, native credentials, menus | `desktop/AGENTS.md` |+| `vite` | The app's Vite plugins, aliases, and dev server; `appSourceConfig()` lends the aliases, icons, and build constants to the docs landing | — |+| `tests` | Central app, integration, E2E, native, and Figma acceptance tests | `tests/AGENTS.md` |+| `tools`, `.github` | Private repo tooling, CI classification, releases, brand generation | `tools/AGENTS.md` |+| `skills/open-pencil` | Installable agent skill | `packages/core/AGENTS.md` (Tools) |+| `assets/brand` | Canonical brand artwork | `assets/brand/README.md` |## Commands@@ -71,6 +71,7 @@ Before a PR run `bun run check`, `bun run format`, `bun run test:unit`, and `bun- Window API augmentations belong to the owning compilation boundary: `src/global.d.ts` for the app, the package's `global.d.ts` for package DOM gaps, `tests/helpers/tauri/native-global.d.ts` for native tests. Never put `declare global` in specs or implementation modules; include canonical declarations through tsconfig. Keep app API contracts named and owned by their implementation domain; derive vendor API types from top-level type imports. Optional runtime globals stay optional and need a runtime guard.- Use `structuredClone` or typed copy helpers for nested mutable data. Self-review for duplication, named shared types, precise unions, and files approaching ~600 lines.- Detect desktop with `IS_TAURI`, never ad-hoc `__TAURI_INTERNALS__` checks.+- Import modules statically. Inline `import()` is for code split on purpose: routes and async components, a heavy dependency only some sessions need, and the `src/main.ts` support gate. Tauri modules are always static, since they reach the native side only when called (`open-pencil/no-inline-tauri-imports`).### Dependency documentationdiff --git a/oxlint.json b/oxlint.jsonindex dda773ca4..dafc009c5 100644--- a/oxlint.json+++ b/oxlint.json@@ -190,6 +190,7 @@"open-pencil/no-cross-package-source-imports": "error","open-pencil/no-app-imports-in-packages": "error","open-pencil/no-core-framework-imports": "error",+ "open-pencil/no-inline-tauri-imports": "error","open-pencil/no-direct-storage-access": "error","open-pencil/no-deep-parent-relative-imports": "error","open-pencil/no-deep-parent-relative-paths": "error",diff --git a/packages/core/src/io/formats/fig/export/index.ts b/packages/core/src/io/formats/fig/export/index.tsindex a1c247313..a5cc32536 100644--- a/packages/core/src/io/formats/fig/export/index.ts+++ b/packages/core/src/io/formats/fig/export/index.ts@@ -8,12 +8,12 @@ import {import { initCodec } from '@open-pencil/kiwi/fig/codec'import type { NodeChange } from '@open-pencil/kiwi/fig/codec'import { loadFigDataCompressor, type FigFileKind } from '@open-pencil/kiwi/fig/container'-import type { SceneGraph } from '@open-pencil/scene-graph'+import type { DocumentKind, SceneGraph } from '@open-pencil/scene-graph'import { fractionalPosition } from '@open-pencil/scene-graph/order-keys'import type { GUID } from '@open-pencil/scene-graph/primitives'import { withFigExportRuntime } from '#core/canvas/text/shape'-import { IS_BROWSER, IS_TAURI } from '#core/constants'+import { IS_BROWSER } from '#core/constants'import { figCompressionLevel } from '#core/io/formats/fig/compression'import { cloneSceneGraphForFigExport } from '#core/kiwi/fig/parse/transfer'import {@@ -38,6 +38,32 @@ import type { CompressResult } from './worker'type InternalResourceContext = FigExportSetup & { nodeChanges: KiwiNodeChange[] }+/** A `.fig` archive's parts before they are compressed and packed. */+export interface FigArchiveParts {+ schemaDeflated: Uint8Array+ kiwiData: Uint8Array+ thumbnailPNG: Uint8Array+ metaJSON: string+ images: Array<{ name: string; data: Uint8Array }>+ figKiwiVersion?: number+ compressionLevel?: number+ documentKind: DocumentKind+}++/** Packs a `.fig` archive from its parts, as a host can do natively off the main thread. */+export type FigArchiveAssembler = (parts: FigArchiveParts) => Promise<Uint8Array>++let hostAssembler: FigArchiveAssembler | null = null++/**+ * Lets the host pack every `.fig` written from now on, as the desktop app does in Rust, since+ * high compression levels take seconds. Without one, a worker packs them, or the main thread+ * where workers are unavailable.+ */+export function setFigArchiveAssembler(assembler: FigArchiveAssembler | null): void {+ hostAssembler = assembler+}+/*** Children already written under a canvas. Shared styles, variables and the canvas's own* layers all append to the internal canvas from separate passes, so each continues this@@ -196,22 +222,17 @@ async function writeFigFile(const version = graph.figKiwiVersion ?? undefinedconst compressionLevel = figCompressionLevel(sourceGraph)- if (IS_TAURI) {- const { invoke } = await import('@tauri-apps/api/core')- return new Uint8Array(- await invoke<ArrayBuffer>('build_fig_file', {- file: {- schemaDeflated: Array.from(schemaDeflated),- kiwiData: Array.from(kiwiData),- thumbnailPng: Array.from(extras.thumbnailPNG),- metaJson: extras.metaJSON,- images: extras.images.map((e) => ({ name: e.name, data: Array.from(e.data) })),- figKiwiVersion: version,- compressionLevel,- board: graph.documentKind === 'board'- }- })- )+ if (hostAssembler) {+ return hostAssembler({+ schemaDeflated,+ kiwiData,+ thumbnailPNG: extras.thumbnailPNG,+ metaJSON: extras.metaJSON,+ images: extras.images,+ figKiwiVersion: version,+ compressionLevel,+ documentKind: graph.documentKind+ })}return compressFigData(diff --git a/packages/core/src/io/formats/fig/index.ts b/packages/core/src/io/formats/fig/index.tsindex 38fa2a425..6afbfb8d8 100644--- a/packages/core/src/io/formats/fig/index.ts+++ b/packages/core/src/io/formats/fig/index.ts@@ -1,5 +1,12 @@export { readFigFile, parseFigFile, type ParseFigFileOptions } from './read'-export { exportFigFile, compressFigData, type FigFileExtrasOptions } from './write'+export {+ exportFigFile,+ compressFigData,+ setFigArchiveAssembler,+ type FigArchiveAssembler,+ type FigArchiveParts,+ type FigFileExtrasOptions+} from './write'export { figThumbnailPageId } from './thumbnail-page'export {isReaderPagePending as isFigPagePending,diff --git a/packages/core/src/io/formats/fig/write.ts b/packages/core/src/io/formats/fig/write.tsindex 4bc180b3d..1dc1c0fb0 100644--- a/packages/core/src/io/formats/fig/write.ts+++ b/packages/core/src/io/formats/fig/write.ts@@ -1 +1,8 @@-export { exportFigFile, compressFigData, type FigFileExtrasOptions } from './export'+export {+ exportFigFile,+ compressFigData,+ setFigArchiveAssembler,+ type FigArchiveAssembler,+ type FigArchiveParts,+ type FigFileExtrasOptions+} from './export'diff --git a/packages/core/tests/io/formats/fig/export/host-assembler.test.ts b/packages/core/tests/io/formats/fig/export/host-assembler.test.tsnew file mode 100644index 000000000..4c0e1aa2f--- /dev/null+++ b/packages/core/tests/io/formats/fig/export/host-assembler.test.ts@@ -0,0 +1,38 @@+import { afterEach, expect, test } from 'bun:test'+import { unzipSync } from 'fflate'++import {+ exportFigFile,+ setFigArchiveAssembler,+ type FigArchiveParts+} from '@open-pencil/core/io/formats/fig'+import { SceneGraph } from '@open-pencil/scene-graph'++afterEach(() => setFigArchiveAssembler(null))++test('a host assembler packs the archive from the parts the export prepared', async () => {+ const graph = new SceneGraph()+ graph.documentKind = 'board'+ graph.createNode('RECTANGLE', graph.getPages()[0].id, { name: 'Card', width: 40, height: 20 })+ const received: FigArchiveParts[] = []+ const packed = new Uint8Array([1, 2, 3])+ setFigArchiveAssembler(async (parts) => {+ received.push(parts)+ return packed+ })++ expect(await exportFigFile(graph, { documentName: 'Board' })).toBe(packed)+ expect(received).toHaveLength(1)+ const [parts] = received+ expect(parts.documentKind).toBe('board')+ expect(parts.kiwiData.length).toBeGreaterThan(0)+ expect(parts.schemaDeflated.length).toBeGreaterThan(0)+ expect(JSON.parse(parts.metaJSON)).toMatchObject({ file_name: 'Board' })+})++test('without a host assembler the export packs the archive itself', async () => {+ const graph = new SceneGraph()+ const entries = unzipSync(await exportFigFile(graph))+ expect(Object.keys(entries)).toContain('canvas.fig')+ expect(entries['canvas.fig'].length).toBeGreaterThan(0)+})diff --git a/src/app/ai/agents/acp/auth/terminal.ts b/src/app/ai/agents/acp/auth/terminal.tsindex bea7b312a..e16641f44 100644--- a/src/app/ai/agents/acp/auth/terminal.ts+++ b/src/app/ai/agents/acp/auth/terminal.ts@@ -1,3 +1,5 @@+import { Command } from '@tauri-apps/plugin-shell'+import type { ACPAgentDef } from '@open-pencil/core/constants'import { createDeferred } from '@/app/runtime/deferred'@@ -45,7 +47,6 @@ export async function startTerminalSignIn(args: string[],onURL: (url: string) => void): Promise<TerminalSignIn> {- const { Command } = await import('@tauri-apps/plugin-shell')const resolved = resolveScopedCommand(signInScope(agent), agent.command, args)const command = Command.create(resolved.command, resolved.args)const finished = createDeferred<undefined>()diff --git a/src/app/ai/agents/acp/process.ts b/src/app/ai/agents/acp/process.tsindex 97fe03339..3b8465c87 100644--- a/src/app/ai/agents/acp/process.ts+++ b/src/app/ai/agents/acp/process.ts@@ -1,3 +1,5 @@+import { Command } from '@tauri-apps/plugin-shell'+import { decodeTauriStderr } from '@/app/shell/ui'import { resolvePlatformCommand } from '@/app/tauri/command'@@ -21,7 +23,6 @@ export async function spawnACPProcess({destroying,onUnexpectedClose}: ACPProcessOptions) {- const { Command } = await import('@tauri-apps/plugin-shell')const resolved = resolvePlatformCommand(commandName, args)const command = Command.create(resolved.command, resolved.args, {encoding: 'raw',diff --git a/src/app/ai/agents/pi/process.ts b/src/app/ai/agents/pi/process.tsindex 602d3b560..2c129a809 100644--- a/src/app/ai/agents/pi/process.ts+++ b/src/app/ai/agents/pi/process.ts@@ -1,3 +1,4 @@+import { Command } from '@tauri-apps/plugin-shell'import * as v from 'valibot'import type { HarnessSidecarMessage, JSONValue } from '@open-pencil/harness'@@ -61,7 +62,6 @@ export async function spawnHarnessProcess(options: {environment: Record<string, string>onUnexpectedClose: () => void}): Promise<HarnessProcess> {- const { Command } = await import('@tauri-apps/plugin-shell')const resolved = resolvePlatformCommand('openpencil-harness')const command = Command.create(resolved.command, resolved.args, {encoding: 'raw',diff --git a/src/app/ai/agents/pi/settings.ts b/src/app/ai/agents/pi/settings.tsindex 4d5dce8b1..5d99df9b4 100644--- a/src/app/ai/agents/pi/settings.ts+++ b/src/app/ai/agents/pi/settings.ts@@ -1,3 +1,5 @@+import { homeDir, join } from '@tauri-apps/api/path'+import { exists, readTextFile } from '@tauri-apps/plugin-fs'import * as v from 'valibot'/** The settings Pi's CLI keeps next to its sign-ins; only non-secret fields are read. */@@ -25,10 +27,6 @@ export function parsePiSettings(text: string): string | null {* in there, on the desktop. Null where there is no home folder to look in.*/export async function readPiAccount(): Promise<PiAccount | null> {- const [{ homeDir, join }, { exists, readTextFile }] = await Promise.all([- import('@tauri-apps/api/path'),- import('@tauri-apps/plugin-fs')- ])const home = await homeDir().catch(() => '')if (!home) return nullconst agentDir = await join(home, '.pi', 'agent')diff --git a/src/app/ai/agents/setup/native.ts b/src/app/ai/agents/setup/native.tsindex cd1f075c5..a1a463257 100644--- a/src/app/ai/agents/setup/native.ts+++ b/src/app/ai/agents/setup/native.ts@@ -1,3 +1,5 @@+import { invoke } from '@tauri-apps/api/core'+import { Command } from '@tauri-apps/plugin-shell'import * as v from 'valibot'import type { ACPAgentDef } from '@open-pencil/core/constants'@@ -20,13 +22,11 @@ const lookupSchema = v.object({export type AgentLookup = v.InferOutput<typeof lookupSchema>export async function lookupAgents(): Promise<AgentLookup> {- const { invoke } = await import('@tauri-apps/api/core')return v.parse(lookupSchema, await invoke<unknown>('agent_lookup'))}/** The folder coding agents start in, which the desktop shell creates in the app's data. */export async function agentWorkspace(): Promise<string> {- const { invoke } = await import('@tauri-apps/api/core')return v.parse(v.string(), await invoke<unknown>('agent_workspace'))}@@ -69,7 +69,6 @@ async function installPackage(searchPath: string,manager: PackageManager = 'npm'): Promise<void> {- const { Command } = await import('@tauri-apps/plugin-shell')const resolved = resolvePlatformCommand(manager,manager === 'bun' ? bunInstallArgs(packageName) : npmInstallArgs(packageName)diff --git a/src/app/ai/providers/openrouter/sign-in.ts b/src/app/ai/providers/openrouter/sign-in.tsindex c68274bf8..efd4a347c 100644--- a/src/app/ai/providers/openrouter/sign-in.ts+++ b/src/app/ai/providers/openrouter/sign-in.ts@@ -1,3 +1,4 @@+import { listen } from '@tauri-apps/api/event'import * as v from 'valibot'import { IS_TAURI } from '@open-pencil/core/constants'@@ -83,7 +84,6 @@ function popupCallback(state: string): Promise<SignInCallback | { failure: 'bloc* the desktop shell forwards its query as an `oauth-callback` event.*/async function deepLinkCallback(state: string): Promise<SignInCallback> {- const { listen } = await import('@tauri-apps/api/event')const { received, stop } = pendingRedirect()const unlisten = await listen<unknown>(OAUTH_CALLBACK_EVENT, (event) => {const callback = v.safeParse(oauthCallbackSchema, event.payload)diff --git a/src/app/ai/skills/library.ts b/src/app/ai/skills/library.tsindex bc0ded501..eedc6fa40 100644--- a/src/app/ai/skills/library.ts+++ b/src/app/ai/skills/library.ts@@ -1,3 +1,4 @@+import { dirname, homeDir } from '@tauri-apps/api/path'import { computed, shallowRef } from 'vue'import { IS_TAURI } from '@open-pencil/core/constants'@@ -50,7 +51,6 @@ async function readFolders(): Promise<{ project: SkillScan; home: SkillScan }> {projectSkillsFolders.value = []return { project: NO_SKILLS, home: NO_SKILLS }}- const { dirname, homeDir } = await import('@tauri-apps/api/path')const home = await homeDir()const reader = await nativeHomeSkillReader()const documentPath = getActiveEditorStoreOrNull()?.getDocumentFilePath() ?? nulldiff --git a/src/app/ai/skills/sources/home.ts b/src/app/ai/skills/sources/home.tsindex 00a7cddc5..ea5fd7512 100644--- a/src/app/ai/skills/sources/home.ts+++ b/src/app/ai/skills/sources/home.ts@@ -1,3 +1,4 @@+import { invoke } from '@tauri-apps/api/core'import { partition } from 'es-toolkit'import * as v from 'valibot'@@ -77,7 +78,6 @@ export async function readHomeSkills(home: string, reader: HomeSkillReader): Pro/** The desktop's reader, through the shell's skill commands. */export async function nativeHomeSkillReader(): Promise<HomeSkillReader> {- const { invoke } = await import('@tauri-apps/api/core')return {folders: (root) => invoke<unknown>('skill_folders', { root }),readFile: (dir, path) => invoke<string>('skill_folder_file', { dir, path })diff --git a/src/app/ai/skills/sources/project.ts b/src/app/ai/skills/sources/project.tsindex 7b93b125b..b4cca15da 100644--- a/src/app/ai/skills/sources/project.ts+++ b/src/app/ai/skills/sources/project.ts@@ -1,3 +1,4 @@+import { invoke } from '@tauri-apps/api/core'import * as v from 'valibot'import type { SkillScan } from '../types'@@ -62,6 +63,5 @@ export async function readProjectSkills(/** The desktop's reader, through the shell's skill commands. */export async function nativeProjectSkillReader(home: HomeSkillReader): Promise<ProjectSkillReader> {- const { invoke } = await import('@tauri-apps/api/core')return { ...home, skillsFolders: (dir) => invoke<unknown>('project_skill_folders', { dir }) }}diff --git a/src/app/automation/bridge/file-handlers.ts b/src/app/automation/bridge/file-handlers.tsindex c84b49429..1dc1002d0 100644--- a/src/app/automation/bridge/file-handlers.ts+++ b/src/app/automation/bridge/file-handlers.ts@@ -1,3 +1,5 @@+import { dirname } from '@tauri-apps/api/path'+import { mkdir } from '@tauri-apps/plugin-fs'import * as v from 'valibot'import { parseToolArgs } from '@open-pencil/core/tools'@@ -28,10 +30,6 @@ const closeArgsSchema = v.object({export async function ensureTauriParentDirectory(path: string): Promise<void> {if (!isTauri()) return- const [{ dirname }, { mkdir }] = await Promise.all([- import('@tauri-apps/api/path'),- import('@tauri-apps/plugin-fs')- ])const dir = await dirname(path)if (dir === path) returnawait mkdir(dir, { recursive: true })diff --git a/src/app/automation/mcp/settings/use.ts b/src/app/automation/mcp/settings/use.tsindex e2fd76f24..c2b008563 100644--- a/src/app/automation/mcp/settings/use.ts+++ b/src/app/automation/mcp/settings/use.ts@@ -1,3 +1,4 @@+import { open } from '@tauri-apps/plugin-dialog'import { onMounted } from 'vue'import { mcpRootDirectory } from '@/app/automation/mcp/preferences'@@ -16,7 +17,6 @@ export function useMCPSettings() {async function chooseRootDirectory(): Promise<void> {if (!isTauri()) return- const { open } = await import('@tauri-apps/plugin-dialog')const directory = await open({ directory: true, multiple: false })if (typeof directory === 'string') mcpRootDirectory.value = directory}diff --git a/src/app/automation/mcp/spawn.ts b/src/app/automation/mcp/spawn.tsindex 774e3dcbc..279a1614d 100644--- a/src/app/automation/mcp/spawn.ts+++ b/src/app/automation/mcp/spawn.ts@@ -1,3 +1,7 @@+import { invoke } from '@tauri-apps/api/core'+import { homeDir, join } from '@tauri-apps/api/path'+import { readTextFile, exists } from '@tauri-apps/plugin-fs'+import { Command } from '@tauri-apps/plugin-shell'import { promiseTimeout } from '@vueuse/core'import { compact } from 'es-toolkit/array'import * as v from 'valibot'@@ -147,7 +151,6 @@ const discoveryTokenSchema = v.pipe(*/async function readDiscoveryToken(discoveryPath: string): Promise<string | null> {try {- const { readTextFile } = await import('@tauri-apps/plugin-fs')const info = v.safeParse(discoveryTokenSchema, await readTextFile(discoveryPath))return info.success ? (info.output.authToken ?? null) : null} catch {@@ -158,7 +161,6 @@ async function readDiscoveryToken(discoveryPath: string): Promise<string | null>/** Check whether the discovery file exists on disk. */async function discoveryFileExists(discoveryPath: string): Promise<boolean> {try {- const { exists } = await import('@tauri-apps/plugin-fs')return await exists(discoveryPath)} catch {return false@@ -172,7 +174,6 @@ async function discoveryFileExists(discoveryPath: string): Promise<boolean> {* endpoint's discoveryPath field.*/async function computeExpectedDiscoveryPath(): Promise<string> {- const { homeDir, join } = await import('@tauri-apps/api/path')const home = await homeDir()if (!home) throw new Error('homeDir() returned an empty string')@@ -218,7 +219,6 @@ async function resolveDiscoveryPath(healthDiscoveryPath?: string): Promise<strin// Validate the server-reported path before accepting it. The /health// endpoint is unauthenticated, so we only accept paths within the// user's home directory ending in mcp.json.- const { homeDir } = await import('@tauri-apps/api/path')const home = await homeDir()const sep = home.includes('\\') ? '\\' : '/'const hasTraversal = healthDiscoveryPath.split(/[\\/]/).some((segment) => segment === '..')@@ -515,14 +515,12 @@ async function startMCPIfNeeded(timing: MCPStartupTiming): Promise<AutomationSerreturn existing}- const { invoke } = await import('@tauri-apps/api/core')const lookup = await invoke<MCPLookup>('mcp_lookup')if (!lookup.available) return rememberStartupError(missingMCPError(lookup.searched))const authToken = mcpAuthenticationEnabled.value ? randomHex(32) : null// Cache only after MCP startup is confirmed healthy.- const { Command } = await import('@tauri-apps/plugin-shell')// Scope file tools to the configured root, defaulting to the user's home.// The app bundle directory (Tauri executableDir) is read-only and cannot be// used as a safe fallback for open_file, save_file, or export tools.@@ -655,7 +653,6 @@ export async function spawnMCPIfNeeded(*/async function resolveTauriHomeDir(): Promise<string> {try {- const { homeDir } = await import('@tauri-apps/api/path')const dir = await homeDir()if (!dir) {throw new Error('homeDir() returned an empty string')diff --git a/src/app/cache/index.ts b/src/app/cache/index.tsindex 6f394ff30..a727a4a33 100644--- a/src/app/cache/index.ts+++ b/src/app/cache/index.ts@@ -1,3 +1,4 @@+import { BaseDirectory, readFile, mkdir, writeFile, remove } from '@tauri-apps/plugin-fs'import { dirname } from 'pathe'import * as v from 'valibot'@@ -40,7 +41,6 @@ function removeStorageEntriesWithPrefix(prefix: string): void {export async function readCacheText(key: string): Promise<string | null> {if (isTauriRuntime()) {try {- const { BaseDirectory, readFile } = await import('@tauri-apps/plugin-fs')return textDecoder.decode(await readFile(cachePath(key), { baseDir: BaseDirectory.AppLocalData }))@@ -55,7 +55,6 @@ export async function readCacheText(key: string): Promise<string | null> {export async function writeCacheText(key: string, value: string): Promise<void> {if (isTauriRuntime()) {- const { BaseDirectory, mkdir, writeFile } = await import('@tauri-apps/plugin-fs')await mkdir(cacheDirectoryPath(key), { baseDir: BaseDirectory.AppLocalData, recursive: true })await writeFile(cachePath(key), textEncoder.encode(value), {baseDir: BaseDirectory.AppLocalData@@ -70,7 +69,6 @@ export async function writeCacheText(key: string, value: string): Promise<void>export async function removeCacheEntry(key: string): Promise<void> {if (isTauriRuntime()) {try {- const { BaseDirectory, remove } = await import('@tauri-apps/plugin-fs')await remove(cachePath(key), { baseDir: BaseDirectory.AppLocalData })} catch (error) {console.warn(`Cache delete skipped for "${key}":`, error)@@ -86,7 +84,6 @@ export async function readCacheBytes(key: string): Promise<ArrayBuffer | null> {if (!isTauriRuntime()) return nulltry {- const { BaseDirectory, readFile } = await import('@tauri-apps/plugin-fs')const data = await readFile(cachePath(key), { baseDir: BaseDirectory.AppLocalData })return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)} catch {@@ -97,7 +94,6 @@ export async function readCacheBytes(key: string): Promise<ArrayBuffer | null> {export async function writeCacheBytes(key: string, value: ArrayBuffer): Promise<void> {if (!isTauriRuntime()) return- const { BaseDirectory, mkdir, writeFile } = await import('@tauri-apps/plugin-fs')await mkdir(cacheDirectoryPath(key), { baseDir: BaseDirectory.AppLocalData, recursive: true })await writeFile(cachePath(key), new Uint8Array(value), { baseDir: BaseDirectory.AppLocalData })}@@ -105,7 +101,6 @@ export async function writeCacheBytes(key: string, value: ArrayBuffer): Promise<export async function removeCachePrefix(prefix: string): Promise<void> {if (isTauriRuntime()) {try {- const { BaseDirectory, remove } = await import('@tauri-apps/plugin-fs')await remove(cachePath(prefix), { baseDir: BaseDirectory.AppLocalData, recursive: true })} catch (error) {console.warn(`Cache prefix delete skipped for "${prefix}":`, error)diff --git a/src/app/document/close/exit.ts b/src/app/document/close/exit.tsindex eb0c84ed6..ccc976c9c 100644--- a/src/app/document/close/exit.ts+++ b/src/app/document/close/exit.ts@@ -1,3 +1,5 @@+import { exit } from '@tauri-apps/plugin-process'+import { prepareForClose } from '@/app/tabs'/** Shared approval so the window close handler and the Quit item cannot prompt twice. */@@ -36,6 +38,5 @@ export function confirmAppExit(): Promise<boolean> {/** Shared by the native Quit item and the platform exit request. */export async function requestAppExit(): Promise<void> {if (!(await confirmAppExit())) return- const { exit } = await import('@tauri-apps/plugin-process')await exit(0)}diff --git a/src/app/document/close/use.ts b/src/app/document/close/use.tsindex f97deed39..a9be2f83b 100644--- a/src/app/document/close/use.ts+++ b/src/app/document/close/use.ts@@ -1,3 +1,4 @@+import { getCurrentWindow } from '@tauri-apps/api/window'import { useEventListener } from '@vueuse/core'import { onMounted, onScopeDispose } from 'vue'@@ -42,7 +43,6 @@ export function useDocumentCloseProtection() {onMounted(async () => {if (!IS_TAURI) return- const { getCurrentWindow } = await import('@tauri-apps/api/window')if (disposed) returnconst window = getCurrentWindow()await windowdiff --git a/src/app/document/export/files.ts b/src/app/document/export/files.tsindex b959c77e4..9dba21893 100644--- a/src/app/document/export/files.ts+++ b/src/app/document/export/files.ts@@ -1,3 +1,5 @@+import { save } from '@tauri-apps/plugin-dialog'+import { writeFile as tauriWrite } from '@tauri-apps/plugin-fs'import { zipSync, type Zippable } from 'fflate'import { extname } from 'pathe'@@ -132,7 +134,6 @@ export function createExportTargetActions(editor: Editor, state: EditorState, io}export async function chooseTauriExportPath(fileName: string, format: string, ext: string) {- const { save } = await import('@tauri-apps/plugin-dialog')return save({defaultPath: fileName,filters: [{ name: format, extensions: [ext.slice(1)] }]@@ -140,7 +141,6 @@ export async function chooseTauriExportPath(fileName: string, format: string, ex}export async function writeTauriExportFile(path: string, data: Uint8Array) {- const { writeFile: tauriWrite } = await import('@tauri-apps/plugin-fs')await tauriWrite(path, data)}diff --git a/src/app/document/io/assets.ts b/src/app/document/io/assets.tsindex 07bb06414..38fe1cda2 100644--- a/src/app/document/io/assets.ts+++ b/src/app/document/io/assets.ts@@ -1,3 +1,6 @@+import { dirname, join, resolve, sep } from '@tauri-apps/api/path'+import { lstat, readFile } from '@tauri-apps/plugin-fs'+import { IS_TAURI } from '@open-pencil/core/constants'import type { ReadDocumentInput } from '@open-pencil/core/io'@@ -10,10 +13,6 @@ import type { ReadDocumentInput } from '@open-pencil/core/io'export function documentAssetReader(path: string | undefined): ReadDocumentInput['readAsset'] {if (!IS_TAURI || !path) return undefinedreturn async (relative) => {- const [{ dirname, join, resolve, sep }, { lstat, readFile }] = await Promise.all([- import('@tauri-apps/api/path'),- import('@tauri-apps/plugin-fs')- ])const folder = await dirname(path)const target = await resolve(folder, relative)if (!target.startsWith(folder + sep())) return nulldiff --git a/src/app/document/io/deep-link.ts b/src/app/document/io/deep-link.tsindex cb1ea1060..f35185dbc 100644--- a/src/app/document/io/deep-link.ts+++ b/src/app/document/io/deep-link.ts@@ -9,6 +9,8 @@// not touch the list. No fs// scope is widened here: the dialog plugin scopes what it returns, and nothing// else is ever read from disk.+import { invoke } from '@tauri-apps/api/core'+import { notificationMessages } from '@/app/i18n/notifications'import { activateTabForPath, chooseTauriOpenPaths, openFileFromPath } from '@/app/shell/menu/files'@@ -55,7 +57,6 @@ export async function searchLinkedNode(export type SuffixMatcher = (candidate: string, relative: string) => Promise<boolean>const tauriMatchesSuffix: SuffixMatcher = async (candidate, relative) => {- const { invoke } = await import('@tauri-apps/api/core')return invoke<boolean>('path_matches_suffix', { candidate, suffix: relative })}diff --git a/src/app/document/io/native-fig.ts b/src/app/document/io/native-fig.tsnew file mode 100644index 000000000..c092f21cb--- /dev/null+++ b/src/app/document/io/native-fig.ts@@ -0,0 +1,30 @@+import { invoke } from '@tauri-apps/api/core'++import { setFigArchiveAssembler } from '@open-pencil/core/io/formats/fig'++/**+ * The desktop app packs every `.fig` it writes in Rust, on a blocking thread, since high+ * compression levels take seconds (`build_fig_file`, `desktop/AGENTS.md`).+ */+export function installNativeFigArchives(): void {+ setFigArchiveAssembler(+ async (parts) =>+ new Uint8Array(+ await invoke<ArrayBuffer>('build_fig_file', {+ file: {+ schemaDeflated: Array.from(parts.schemaDeflated),+ kiwiData: Array.from(parts.kiwiData),+ thumbnailPng: Array.from(parts.thumbnailPNG),+ metaJson: parts.metaJSON,+ images: parts.images.map((image) => ({+ name: image.name,+ data: Array.from(image.data)+ })),+ figKiwiVersion: parts.figKiwiVersion,+ compressionLevel: parts.compressionLevel,+ board: parts.documentKind === 'board'+ }+ })+ )+ )+}diff --git a/src/app/document/io/reload-source.ts b/src/app/document/io/reload-source.tsindex f79f2d9d9..2885ac7f2 100644--- a/src/app/document/io/reload-source.ts+++ b/src/app/document/io/reload-source.ts@@ -1,3 +1,5 @@+import { readFile as tauriRead } from '@tauri-apps/plugin-fs'+import { readFigFile } from '@open-pencil/core/io/formats/fig'import { isTauri } from '@/app/tauri/env'@@ -17,7 +19,6 @@ export async function readReloadSource({}: ReloadSourceOptions) {signal?.throwIfAborted()if (filePath && isTauri()) {- const { readFile: tauriRead } = await import('@tauri-apps/plugin-fs')const bytes = await tauriRead(filePath)signal?.throwIfAborted()const blob = new Blob([bytes])diff --git a/src/app/document/io/save/targets.ts b/src/app/document/io/save/targets.tsindex 3f5985092..d3bdfabdc 100644--- a/src/app/document/io/save/targets.ts+++ b/src/app/document/io/save/targets.ts@@ -1,3 +1,5 @@+import { save } from '@tauri-apps/plugin-dialog'+import { DOCUMENT_EXTENSIONS } from '@open-pencil/core/io'import type { DocumentKind } from '@open-pencil/scene-graph'@@ -11,7 +13,6 @@ const FILE_TYPE_NAMES: Readonly<Record<DocumentKind, string>> = {}export async function chooseTauriFigSavePath(kind: DocumentKind) {- const { save } = await import('@tauri-apps/plugin-dialog')return save({defaultPath: documentFileName('Untitled', kind),filters: [{ name: FILE_TYPE_NAMES[kind], extensions: [DOCUMENT_EXTENSIONS[kind]] }]diff --git a/src/app/document/io/watch/targets.ts b/src/app/document/io/watch/targets.tsindex 0d4cd25c8..ff9b8b097 100644--- a/src/app/document/io/watch/targets.ts+++ b/src/app/document/io/watch/targets.ts@@ -1,3 +1,4 @@+import { watch as tauriWatch } from '@tauri-apps/plugin-fs'import { useIntervalFn } from '@vueuse/core'const RECENT_WRITE_MS = 1000@@ -9,7 +10,6 @@ export async function watchTauriFile(getLastWriteTime: () => number,reloadFromDisk: () => void) {- const { watch: tauriWatch } = await import('@tauri-apps/plugin-fs')const unwatch = await tauriWatch(filePath,(event) => {diff --git a/src/app/document/io/write.ts b/src/app/document/io/write.tsindex 7b4194f05..f0ff995be 100644--- a/src/app/document/io/write.ts+++ b/src/app/document/io/write.ts@@ -1,3 +1,5 @@+import { writeFile as tauriWrite } from '@tauri-apps/plugin-fs'+import { describeDiagnosticError, recordDocumentFailure } from '@/app/diagnostics'import { storageLocationOf } from '@/app/integrations/storage/location'import type { StorageDocumentBinding } from '@/app/integrations/storage/types'@@ -52,7 +54,6 @@ export function createDocumentWriter({const filePath = getFilePath()const fileHandle = getFileHandle()if (filePath && isTauri()) {- const { writeFile: tauriWrite } = await import('@tauri-apps/plugin-fs')await tauriWrite(filePath, data)return await finishWrite(version)}diff --git a/src/app/editor/fonts/index.ts b/src/app/editor/fonts/index.tsindex edf5c50a8..9c5efb869 100644--- a/src/app/editor/fonts/index.ts+++ b/src/app/editor/fonts/index.ts@@ -1,3 +1,4 @@+import { invoke } from '@tauri-apps/api/core'import { useLocalStorage } from '@vueuse/core'import { watch } from 'vue'@@ -73,8 +74,7 @@ let tauriFontsPromise: Promise<HostFontFamily[]> | null = nullasync function getTauriFonts(): Promise<HostFontFamily[]> {if (tauriFontsCache) return tauriFontsCacheif (!tauriFontsPromise) {- tauriFontsPromise = import('@tauri-apps/api/core')- .then(({ invoke }) => invoke<HostFontFamily[]>('list_system_fonts'))+ tauriFontsPromise = invoke<HostFontFamily[]>('list_system_fonts').then((fonts) => {tauriFontsCache = fonts// The weight list and family switches read each family's faces from these.@@ -201,7 +201,6 @@ type NativeFontLoadError = { code?: 'not-found' | 'unsupported-format' | 'failedasync function loadSystemFont(family: string, style = 'Regular'): Promise<ArrayBuffer | null> {if (!isTauri()) return nulltry {- const { invoke } = await import('@tauri-apps/api/core')const data = await invoke<ArrayBuffer>('load_system_font', { family, style })if (data.byteLength === 0) return nullreturn datadiff --git a/src/app/editor/icons/provider.ts b/src/app/editor/icons/provider.tsindex 5851da249..9de17d9a8 100644--- a/src/app/editor/icons/provider.ts+++ b/src/app/editor/icons/provider.ts@@ -1,3 +1,5 @@+import { invoke } from '@tauri-apps/api/core'+import {createIconProvider,createSFSymbolsProvider,@@ -8,15 +10,10 @@ import { browserWebFontFetch } from '@/app/editor/fonts/browser-fetch'import { tauriFetch } from '@/app/tauri/http'import { IS_TAURI } from '@/constants'-async function invoke(command: string, args?: Record<string, unknown>): Promise<string | null> {- const { invoke } = await import('@tauri-apps/api/core')- return invoke<string | null>(command, args)-}-/** SF Symbols, drawn by the desktop app, which offers them only on a Mac that can draw them. */const sfSymbols = createSFSymbolsProvider({- catalogue: () => invoke('sf_symbols_catalogue'),- render: (request) => invoke('sf_symbols_render', { request })+ catalogue: () => invoke<string | null>('sf_symbols_catalogue'),+ render: (request) => invoke<string | null>('sf_symbols_render', { request })})/**diff --git a/src/app/recent-files/thumbnails.ts b/src/app/recent-files/thumbnails.tsindex 3236011eb..4359ea794 100644--- a/src/app/recent-files/thumbnails.ts+++ b/src/app/recent-files/thumbnails.ts@@ -1,3 +1,5 @@+import { stat, open, SeekMode } from '@tauri-apps/plugin-fs'+import { extractFigThumbnailFromReader } from '@open-pencil/fig'import { readCacheBytes, removeCachePrefix, writeCacheBytes } from '@/app/cache'@@ -9,7 +11,6 @@ const RECENT_FILE_THUMBNAIL_CACHE_DIR = 'recent-file-thumbnails/v2'async function recentFileThumbnailCacheKey(path: string): Promise<string> {let fingerprint = pathtry {- const { stat } = await import('@tauri-apps/plugin-fs')const info = await stat(path)fingerprint = `${path}\0${info.size}\0${info.mtime?.getTime() ?? 0}`} catch (error) {@@ -42,7 +43,6 @@ export async function loadRecentFileThumbnail(path: string): Promise<Uint8Arrayif (!isTauri() || !isFigArchiveName(path)) return nullconst cached = await loadCachedRecentFileThumbnail(path)if (cached) return cached- const { open, SeekMode } = await import('@tauri-apps/plugin-fs')const file = await open(path, { read: true })try {const info = await file.stat()diff --git a/src/app/settings/preferences/native-menu.ts b/src/app/settings/preferences/native-menu.tsindex c3fecc90b..45de1fcdd 100644--- a/src/app/settings/preferences/native-menu.ts+++ b/src/app/settings/preferences/native-menu.ts@@ -1,3 +1,5 @@+import { invoke } from '@tauri-apps/api/core'+import type { SnappingPreferences } from '@open-pencil/core'import { isTauri } from '@/app/tauri/env'@@ -13,7 +15,6 @@ const SNAPPING_MENU_IDS = {export async function syncNativeSnappingMenu(preferences: SnappingPreferences): Promise<void> {if (!isTauri()) return- const { invoke } = await import('@tauri-apps/api/core')await Promise.all(Object.entries(SNAPPING_MENU_IDS).map(([preference, id]) =>invoke('set_native_menu_checked', {@@ -26,13 +27,11 @@ export async function syncNativeSnappingMenu(preferences: SnappingPreferences):export async function syncNativeDesignIssuesMenu(showOnCanvas: boolean): Promise<void> {if (!isTauri()) return- const { invoke } = await import('@tauri-apps/api/core')await invoke('set_native_menu_checked', { id: DESIGN_ISSUES_MENU_ID, checked: showOnCanvas })}/** View → Comments, which Shift+C and the comment menus also toggle. */export async function syncNativeCommentsMenu(shown: boolean): Promise<void> {if (!isTauri()) return- const { invoke } = await import('@tauri-apps/api/core')await invoke('set_native_menu_checked', { id: COMMENTS_MENU_ID, checked: shown })}diff --git a/src/app/shell/menu/features.ts b/src/app/shell/menu/features.tsindex c4f096b82..a2e08cfba 100644--- a/src/app/shell/menu/features.ts+++ b/src/app/shell/menu/features.ts@@ -1,3 +1,4 @@+import { invoke } from '@tauri-apps/api/core'import { computed, watch } from 'vue'import { isCloudBinding } from '@/app/cloud/integration'@@ -30,11 +31,9 @@ export function watchNativeMenuFeatures(): () => void {availableFeatures,(features) => {if (!isTauri()) return- void import('@tauri-apps/api/core')- .then(({ invoke }) => invoke('set_native_menu_features', { features }))- .catch((error: unknown) => {- console.warn('[Menu] Failed to update the native menu', error)- })+ invoke('set_native_menu_features', { features }).catch((error: unknown) => {+ console.warn('[Menu] Failed to update the native menu', error)+ })},{ immediate: true })diff --git a/src/app/shell/menu/files.ts b/src/app/shell/menu/files.tsindex 5b72de9a7..0b6d805d1 100644--- a/src/app/shell/menu/files.ts+++ b/src/app/shell/menu/files.ts@@ -1,3 +1,5 @@+import { open } from '@tauri-apps/plugin-dialog'+import { readFile } from '@tauri-apps/plugin-fs'import { useFileDialog } from '@vueuse/core'import { uniq } from 'es-toolkit/array'import { basename } from 'pathe'@@ -123,13 +125,11 @@ export async function openDesignFileBatch<T>(export async function readTauriDesignFile(path: string): Promise<File> {assertSupportedDesignFile(path)- const { readFile } = await import('@tauri-apps/plugin-fs')const bytes = await readFile(path)return new File([bytes], basename(path) || 'file.fig')}export async function chooseTauriOpenPaths(): Promise<string[]> {- const { open } = await import('@tauri-apps/plugin-dialog')const paths = await open({filters: [{ name: 'Design file', extensions: READABLE_DOCUMENT_EXTENSIONS }],multiple: truediff --git a/src/app/shell/menu/native-events.ts b/src/app/shell/menu/native-events.tsindex 48f2fa6e1..3b3c452ff 100644--- a/src/app/shell/menu/native-events.ts+++ b/src/app/shell/menu/native-events.ts@@ -1,17 +1,16 @@+import { listen } from '@tauri-apps/api/event'import { tryOnScopeDispose } from '@vueuse/core'export function useNativeMenuEvents(handler: (id: string) => void): void {let disposed = falselet unlisten: (() => void) | undefined- void import('@tauri-apps/api/event').then(({ listen }) => {- return listen<string>('menu-event', (event) => {- handler(event.payload)- }).then((fn) => {- if (disposed) fn()- else unlisten = fn- return undefined- })+ void listen<string>('menu-event', (event) => {+ handler(event.payload)+ }).then((fn) => {+ if (disposed) fn()+ else unlisten = fn+ return undefined})tryOnScopeDispose(() => {diff --git a/src/app/shell/menu/recent-files.ts b/src/app/shell/menu/recent-files.tsindex 52d32b4ab..8086a645f 100644--- a/src/app/shell/menu/recent-files.ts+++ b/src/app/shell/menu/recent-files.ts@@ -1,3 +1,4 @@+import { invoke } from '@tauri-apps/api/core'import { watch } from 'vue'import { recentLocalFilePaths } from '@/app/recent-files'@@ -7,7 +8,6 @@ export const OPEN_RECENT_EVENT_PREFIX = 'open-recent:'export async function syncRecentFilesMenu(): Promise<void> {if (!isTauri()) return- const { invoke } = await import('@tauri-apps/api/core')await invoke('set_recent_files', { paths: recentLocalFilePaths.value })}diff --git a/src/app/shell/notifications/index.ts b/src/app/shell/notifications/index.tsindex a5660bc45..e96c880c6 100644--- a/src/app/shell/notifications/index.ts+++ b/src/app/shell/notifications/index.ts@@ -1,3 +1,5 @@+import { getCurrentWindow } from '@tauri-apps/api/window'+import { onAction, sendNotification } from '@tauri-apps/plugin-notification'import { useDocumentVisibility, useWindowFocus } from '@vueuse/core'import { watch } from 'vue'@@ -54,7 +56,6 @@ watch([windowFocused, documentVisibility, () => activeTab.value?.id], () => {})async function focusDesktopWindow(): Promise<void> {- const { getCurrentWindow } = await import('@tauri-apps/api/window')const window = getCurrentWindow()await window.unminimize()await window.setFocus()@@ -66,7 +67,6 @@ async function focusDesktopWindow(): Promise<void> {* moved to the Action Center.*/async function addDesktopClickListener(): Promise<void> {- const { onAction } = await import('@tauri-apps/plugin-notification')await onAction(({ actionId, notification }) => {const id = notification?.idconst open = id === undefined ? undefined : shownOnDesktop.get(id)@@ -87,7 +87,6 @@ function listenForDesktopClicks(): Promise<void> {async function showOnDesktop(notification: AppNotification): Promise<void> {await listenForDesktopClicks()- const { sendNotification } = await import('@tauri-apps/plugin-notification')const id = randomInt()shownOnDesktop.set(id, notification.open)for (const old of shownOnDesktop.keys()) {diff --git a/src/app/shell/ui.ts b/src/app/shell/ui.tsindex 574568d97..576edaadb 100644--- a/src/app/shell/ui.ts+++ b/src/app/shell/ui.ts@@ -1,3 +1,4 @@+import { invoke } from '@tauri-apps/api/core'import { useEventListener } from '@vueuse/core'import { ref } from 'vue'@@ -173,7 +174,6 @@ export const toast = {export async function openExternalLink(url: string) {if (isTauri()) {// An app command, so native tests can read the address instead of opening a browser.- const { invoke } = await import('@tauri-apps/api/core')await invoke('open_external_url', { url })} else {window.open(url, '_blank')diff --git a/src/app/shell/updater/approvals.ts b/src/app/shell/updater/approvals.tsindex dc1f4417d..b1d4fd58e 100644--- a/src/app/shell/updater/approvals.ts+++ b/src/app/shell/updater/approvals.ts@@ -1,3 +1,4 @@+import { emitTo, listen } from '@tauri-apps/api/event'import * as v from 'valibot'import { onScopeDispose } from 'vue'@@ -15,7 +16,6 @@ export function useRestartApprovals(): void {let disposed = falseasync function register() {- const { emitTo, listen } = await import('@tauri-apps/api/event')const unlisten = await listen<unknown>(RESTART_REQUEST_EVENT, ({ payload }) => {const parsed = v.safeParse(restartRequestSchema, payload)if (!parsed.success) returndiff --git a/src/app/shell/updater/check.ts b/src/app/shell/updater/check.tsindex b3571e8db..8d5f7b468 100644--- a/src/app/shell/updater/check.ts+++ b/src/app/shell/updater/check.ts@@ -1,3 +1,4 @@+import { check } from '@tauri-apps/plugin-updater'import { promiseTimeout } from '@vueuse/core'import type { Ref } from 'vue'@@ -40,7 +41,6 @@ export function scheduleStartupUpdateCheck(messages: Ref<UpdaterMessages>) {// window checks again for its own handle, then shows the notes and installs.async function runUpdateCheck(silent: boolean, messages: Ref<UpdaterMessages>) {try {- const { check } = await import('@tauri-apps/plugin-updater')const update = await check()if (!update) {if (!silent) toast.info(messages.value.upToDate)diff --git a/src/app/shell/updater/restart.ts b/src/app/shell/updater/restart.tsindex 864751413..10f850986 100644--- a/src/app/shell/updater/restart.ts+++ b/src/app/shell/updater/restart.ts@@ -1,3 +1,5 @@+import { emitTo, listen, TauriEvent } from '@tauri-apps/api/event'+import { WebviewWindow } from '@tauri-apps/api/webviewWindow'import * as v from 'valibot'import { randomHex } from '@open-pencil/scene-graph/random'@@ -14,10 +16,6 @@ export const EDITOR_WINDOW_LABEL = 'main'/** Called from the Software Update window; resolves true once the editor's documents may close. */export async function requestRestartApproval(): Promise<boolean> {- const [{ emitTo, listen, TauriEvent }, { WebviewWindow }] = await Promise.all([- import('@tauri-apps/api/event'),- import('@tauri-apps/api/webviewWindow')- ])const editor = await WebviewWindow.getByLabel(EDITOR_WINDOW_LABEL)if (!editor) return truediff --git a/src/app/shell/updater/session.ts b/src/app/shell/updater/session.tsindex 5c8663a4c..dba417ebf 100644--- a/src/app/shell/updater/session.ts+++ b/src/app/shell/updater/session.ts@@ -1,3 +1,6 @@+import { getCurrentWindow } from '@tauri-apps/api/window'+import { relaunch } from '@tauri-apps/plugin-process'+import { check } from '@tauri-apps/plugin-updater'import type { DownloadEvent } from '@tauri-apps/plugin-updater'import { shallowRef, type ShallowRef } from 'vue'@@ -241,16 +244,13 @@ function errorMessage(error: unknown): string {export function createTauriUpdaterBackend(): UpdaterBackend {return {async check() {- const { check } = await import('@tauri-apps/plugin-updater')return check()},confirmRestart: requestRestartApproval,async relaunch() {- const { relaunch } = await import('@tauri-apps/plugin-process')await relaunch()},async closeWindow() {- const { getCurrentWindow } = await import('@tauri-apps/api/window')await getCurrentWindow().close()},installQuitsApp: navigator.userAgent.includes('Windows')diff --git a/src/app/shell/updater/window.ts b/src/app/shell/updater/window.tsindex 47aab1843..52cd374b0 100644--- a/src/app/shell/updater/window.ts+++ b/src/app/shell/updater/window.ts@@ -1,3 +1,4 @@+import { WebviewWindow } from '@tauri-apps/api/webviewWindow'export const UPDATER_WINDOW_LABEL = 'updater'/** Separate Vite entry, so the window never boots the editor. */export const UPDATER_WINDOW_URL = 'updater.html'@@ -7,7 +8,6 @@ const UPDATER_WINDOW_HEIGHT = 520/** Shows the Software Update window, focusing it when it is already open. */export async function openUpdaterWindow(title: string): Promise<void> {- const { WebviewWindow } = await import('@tauri-apps/api/webviewWindow')const existing = await WebviewWindow.getByLabel(UPDATER_WINDOW_LABEL)if (existing) {await existing.unminimize()diff --git a/src/app/tauri/http.ts b/src/app/tauri/http.tsindex 0d430ebc0..4f5d13885 100644--- a/src/app/tauri/http.ts+++ b/src/app/tauri/http.ts@@ -1,3 +1,5 @@+import { Channel, invoke } from '@tauri-apps/api/core'+import { randomHex } from '@open-pencil/scene-graph/random'import type { FetchFunction } from '@/app/http/types'@@ -144,7 +146,6 @@ async function executeTauriFetch(const request = new Request(input, init)request.signal.throwIfAborted()- const { Channel, invoke } = await import('@tauri-apps/api/core')request.signal.throwIfAborted()// Capture generated multipart headers before consuming the Request body.diff --git a/src/app/tauri/link-queue.ts b/src/app/tauri/link-queue.tsindex a93800c78..2ad6b8d58 100644--- a/src/app/tauri/link-queue.ts+++ b/src/app/tauri/link-queue.ts@@ -1,3 +1,5 @@+import { invoke } from '@tauri-apps/api/core'+import { listen } from '@tauri-apps/api/event'import * as v from 'valibot'import { isTauri } from '@/app/tauri/env'@@ -15,10 +17,6 @@ export async function bindDesktopLinkQueue<T>(options: {open: (item: T) => unknown}): Promise<() => void> {if (!isTauri()) return () => undefined- const [{ invoke }, { listen }] = await Promise.all([- import('@tauri-apps/api/core'),- import('@tauri-apps/api/event')- ])const queue = v.array(options.schema)async function drain() {const items = v.parse(queue, await invoke<unknown>(options.command))diff --git a/src/app/telemetry/build.ts b/src/app/telemetry/build.tsindex 355be23d2..fd6aaab1a 100644--- a/src/app/telemetry/build.ts+++ b/src/app/telemetry/build.ts@@ -1,3 +1,5 @@+import { platform, arch } from '@tauri-apps/plugin-os'+import type { Architecture, Build } from '@open-pencil/feedback/contract'import { APP_VERSION } from '@/app/runtime/version'@@ -16,7 +18,6 @@ async function detectBuild(): Promise<Build> {const { os, browser } = describeEnvironment(facts)return { version: APP_VERSION, platform: os, arch: 'unknown', app: 'web', browser }}- const { platform, arch } = await import('@tauri-apps/plugin-os')const { os } = describeEnvironment(facts, { platform: platform() })return {version: APP_VERSION,diff --git a/src/app/telemetry/state.ts b/src/app/telemetry/state.tsindex d8672dc33..eef414505 100644--- a/src/app/telemetry/state.ts+++ b/src/app/telemetry/state.ts@@ -1,3 +1,4 @@+import { invoke } from '@tauri-apps/api/core'import { useLocalStorage } from '@vueuse/core'import * as v from 'valibot'@@ -34,7 +35,6 @@ const ENVIRONMENT_CHECK_TIMEOUT_MS = 2_000let disabledByEnvironment: Promise<boolean> | null = nullasync function readDesktopEnvironment(): Promise<boolean> {- const { invoke } = await import('@tauri-apps/api/core')const timeout = new Promise<boolean>((resolve) => {setTimeout(() => resolve(true), ENVIRONMENT_CHECK_TIMEOUT_MS)})diff --git a/src/boot.ts b/src/boot.tsindex 610294bf7..f5668cbbd 100644--- a/src/boot.ts+++ b/src/boot.ts@@ -6,6 +6,7 @@ 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 { preloadFonts } from '@/app/editor/fonts'import { installBundledFonts } from '@/app/editor/fonts/bundled'@@ -23,6 +24,7 @@ import router from './router'*/export async function boot(): Promise<void> {installBundledFonts()+ if (IS_TAURI) installNativeFigArchives()installCanvasKitBinary()preloadCanvasKit()preloadFonts()diff --git a/src/views/UpdaterView.vue b/src/views/UpdaterView.vueindex fae148a97..4de990a6e 100644--- a/src/views/UpdaterView.vue+++ b/src/views/UpdaterView.vue@@ -1,4 +1,5 @@<script setup lang="ts">+import { getCurrentWindow } from '@tauri-apps/api/window'import { useHead } from '@unhead/vue'import { computed, onMounted, onScopeDispose } from 'vue'@@ -28,7 +29,6 @@ let stopCloseGuard: (() => void) | undefinedlet disposed = falseonMounted(async () => {void session.check()- const { getCurrentWindow } = await import('@tauri-apps/api/window')// Closing mid-install would leave the app half replaced.const stop = await getCurrentWindow().onCloseRequested((event) => {if (session.state.value.status === 'installing') event.preventDefault()diff --git a/src/views/WorkspaceView.vue b/src/views/WorkspaceView.vueindex 63c952386..13ed9f102 100644--- a/src/views/WorkspaceView.vue+++ b/src/views/WorkspaceView.vue@@ -1,4 +1,6 @@<script setup lang="ts">+import { invoke } from '@tauri-apps/api/core'+import { listen } from '@tauri-apps/api/event'import { useHead } from '@unhead/vue'import { useEventListener, whenever } from '@vueuse/core'import { computed, onMounted, onUnmounted, provide, ref, watch } from 'vue'@@ -224,7 +226,6 @@ async function selectNodeByName(name: string): Promise<boolean> {}async function openPendingAssociatedFiles(): Promise<void> {- const { invoke } = await import('@tauri-apps/api/core')const files = await invoke<PendingOpenFile[]>('take_pending_open')await openPendingFiles(files, {openPaths: openDocumentPaths,@@ -244,7 +245,6 @@ function drainPendingOpens(): Promise<void> {async function bindAssociatedFileOpen(): Promise<void> {if (!isTauri()) return- const { listen } = await import('@tauri-apps/api/event')fileAssociationCleanup.value = await listen('open-associated-files', () => {void drainPendingOpens()})diff --git a/tests/helpers/tauri/fig-export-fixture.ts b/tests/helpers/tauri/fig-export-fixture.tsindex faa60f76d..aaec71625 100644--- a/tests/helpers/tauri/fig-export-fixture.ts+++ b/tests/helpers/tauri/fig-export-fixture.ts@@ -1,5 +1,10 @@import { mockIPC } from '@tauri-apps/api/mocks'+import { exportFigFile } from '@open-pencil/core/io/formats/fig'+import { SceneGraph } from '@open-pencil/scene-graph'++import { installNativeFigArchives } from '@/app/document/io/native-fig'+import { installTauriMockWindow } from './mocks'installTauriMockWindow()@@ -25,10 +30,7 @@ mockIPC((cmd, args) => {return new Uint8Array([7, 8, 9]).buffer})-const [{ exportFigFile }, { SceneGraph }] = await Promise.all([- import('@open-pencil/core/io/formats/fig/export'),- import('@open-pencil/scene-graph')-])+installNativeFigArchives()const bytes = await exportFigFile(new SceneGraph())if (bytes.length !== 3 || bytes[0] !== 7 || bytes[1] !== 8 || bytes[2] !== 9) {throw new Error(`Unexpected export bytes: ${Array.from(bytes).join(',')}`)diff --git a/tools/checks/lint/src/plugin.ts b/tools/checks/lint/src/plugin.tsindex 3eb54266c..8f7181473 100644--- a/tools/checks/lint/src/plugin.ts+++ b/tools/checks/lint/src/plugin.ts@@ -393,7 +393,8 @@ import {noCoreSelfPackageImports,noInlinePromptConstants,noAppImportsInPackages,- noCoreFrameworkImports+ noCoreFrameworkImports,+ noInlineTauriImports} from '#lint/rules/imports.ts'import {noDirectStorageAccess,@@ -473,6 +474,7 @@ const plugin = {'no-inline-prompt-constants': noInlinePromptConstants,'no-app-imports-in-packages': noAppImportsInPackages,'no-core-framework-imports': noCoreFrameworkImports,+ 'no-inline-tauri-imports': noInlineTauriImports,'no-direct-storage-access': noDirectStorageAccess,'no-broad-double-cast': noBroadDoubleCast,'no-unknown-record-double-cast': noUnknownRecordDoubleCast,diff --git a/tools/checks/lint/src/rules/imports.ts b/tools/checks/lint/src/rules/imports.tsindex fee7fa7e7..f6ac30e35 100644--- a/tools/checks/lint/src/rules/imports.ts+++ b/tools/checks/lint/src/rules/imports.ts@@ -1,4 +1,4 @@-import { importSource, normalizedFilename } from '#lint/support/context.ts'+import { importSource, inlineImportSource, normalizedFilename } from '#lint/support/context.ts'import { createImportSourceRule } from '#lint/support/factories.ts'import type { RuleContext, RuleDefinition } from '#lint/support/types.ts'import type { TSESTree } from '@typescript-eslint/utils'@@ -227,6 +227,35 @@ const noCoreFrameworkImports = createImportSourceRule({`@open-pencil/core must stay framework-agnostic; do not import '${source}'.`})+/**+ * Tauri's modules reach the native side only when one of their functions is called, so shipped+ * code imports them statically like any other module. Only the startup support gate loads them+ * inline: it must parse on engines that cannot run the app, which `src/main.ts` keeps free of the+ * app bundle. Tests and tooling, which load Tauri's mocks and CLI in a set order, are not shipped.+ */+const noInlineTauriImports: RuleDefinition = {+ meta: {+ type: 'suggestion',+ docs: { description: 'Import Tauri modules statically, outside the startup support gate' },+ schema: []+ },+ create(context: RuleContext) {+ const file = normalizedFilename(context)+ if (!file.includes('/src/') || /\/(tools|tests)\//.test(file)) return {}+ if (/\/src\/app\/shell\/support\/(gate|render)\.ts$/.test(file)) return {}+ return {+ ImportExpression(node) {+ const source = inlineImportSource(node)+ if (!source?.startsWith('@tauri-apps/')) return+ context.report({+ node,+ message: `Import '${source}' statically; Tauri's modules reach the native side only when called.`+ })+ }+ }+ }+}+/*** An edit records what it changed through `recordEdit` or `recordEditAsync`, which push its undo* step when the document's unsaved state expects it; capturing a change by hand elsewhere is how@@ -273,5 +302,6 @@ export {noCoreSelfPackageImports,noInlinePromptConstants,noAppImportsInPackages,- noCoreFrameworkImports+ noCoreFrameworkImports,+ noInlineTauriImports}diff --git a/tools/checks/lint/src/support/context.ts b/tools/checks/lint/src/support/context.tsindex 240323375..355982171 100644--- a/tools/checks/lint/src/support/context.ts+++ b/tools/checks/lint/src/support/context.ts@@ -29,3 +29,13 @@ export function importSource(): string | null {return typeof node.source?.value === 'string' ? node.source.value : null}++/** The module an inline `import()` names, when it is a string or a template without expressions. */+export function inlineImportSource(node: TSESTree.ImportExpression): string | null {+ const { source } = node+ if (source.type === 'Literal') return typeof source.value === 'string' ? source.value : null+ if (source.type === 'TemplateLiteral' && source.expressions.length === 0) {+ return source.quasis[0]?.value.cooked ?? null+ }+ return null+}diff --git a/tools/checks/lint/src/support/factories.ts b/tools/checks/lint/src/support/factories.tsindex 1b40516f3..0938b87b8 100644--- a/tools/checks/lint/src/support/factories.ts+++ b/tools/checks/lint/src/support/factories.ts@@ -1,4 +1,4 @@-import { importSource, normalizedFilename } from '#lint/support/context.ts'+import { importSource, inlineImportSource, normalizedFilename } from '#lint/support/context.ts'import type { RuleDefinition, RuleListener } from '#lint/support/types.ts'import type { TSESTree } from '@typescript-eslint/utils'@@ -50,7 +50,16 @@ export function createImportSourceRule({const message = check(source, file)if (message) context.report({ node, message })}- const visitors: RuleListener = { ImportDeclaration: inspect }+ const visitors: RuleListener = {+ ImportDeclaration: inspect,+ // An inline import crosses the same boundary as a static one.+ ImportExpression(node) {+ const source = inlineImportSource(node)+ if (!source) return+ const message = check(source, file)+ if (message) context.report({ node, message })+ }+ }if (includeExports) {visitors.ExportNamedDeclaration = inspectvisitors.ExportAllDeclaration = inspectdiff --git a/tools/checks/lint/tests/inline-imports.test.ts b/tools/checks/lint/tests/inline-imports.test.tsnew file mode 100644index 000000000..494418407--- /dev/null+++ b/tools/checks/lint/tests/inline-imports.test.ts@@ -0,0 +1,53 @@+import { describe, expect, test } from 'bun:test'++import { lintFiles, ruleDiagnostics } from './helpers/lint.ts'++describe('no-inline-tauri-imports', () => {+ const rule = 'no-inline-tauri-imports'+ const rules = { [`open-pencil/${rule}`]: 'error' }++ test('rejects an inline Tauri import in app code, and allows it only in the support gate files', async () => {+ const source =+ "export async function run() { const { invoke } = await import('@tauri-apps/api/core'); return invoke('x') }"+ const diagnostics = ruleDiagnostics(+ await lintFiles(+ {+ 'src/app/document/save.ts': source,+ 'src/app/shell/support/gate.ts': source,+ 'src/app/shell/support/render.ts': source,+ 'src/app/shell/support/detect.ts': source,+ 'src/app/document/template.ts':+ 'export const load = () => import(`@tauri-apps/api/core`)',+ 'src/app/document/static.ts':+ "import { invoke } from '@tauri-apps/api/core'\nexport const run = () => invoke('x')",+ 'src/app/document/lazy.ts': "export const load = () => import('./heavy')",+ 'tests/helpers/tauri/mocks.ts': source+ },+ rules+ ),+ rule+ )+ expect(diagnostics.map((diagnostic) => diagnostic.filename).sort()).toEqual([+ expect.stringMatching(/src\/app\/document\/save\.ts$/),+ expect.stringMatching(/src\/app\/document\/template\.ts$/),+ expect.stringMatching(/src\/app\/shell\/support\/detect\.ts$/)+ ])+ })+})++describe('import boundary rules', () => {+ test('see inline imports as well as static ones', async () => {+ const rule = 'no-core-framework-imports'+ const diagnostics = ruleDiagnostics(+ await lintFiles(+ {+ 'packages/core/src/io/export.ts':+ "export const load = () => import('@tauri-apps/api/core')"+ },+ { [`open-pencil/${rule}`]: 'error' }+ ),+ rule+ )+ expect(diagnostics).toHaveLength(1)+ })+})