AI-native design editor. Open-source Figma alternative.
Format remaining SDK refactor files
Danila Poyarkov1da5483fec17
diff --git a/packages/cli/src/app-client.ts b/packages/cli/src/app-client.tsindex 2bab21162..fd7538e51 100644--- a/packages/cli/src/app-client.ts+++ b/packages/cli/src/app-client.ts@@ -11,14 +11,14 @@ export async function getAppToken(): Promise<string> {if (!res || !res.ok) {throw new Error(`Could not connect to OpenPencil app on localhost:${AUTOMATION_HTTP_PORT}.\n` +- 'Is the app running? Start it with: bun run tauri dev'+ 'Is the app running? Start it with: bun run tauri dev')}const data = (await res.json()) as { status: string; token?: string }if (data.status !== 'ok' || !data.token) {throw new Error('OpenPencil app is running but no document is open.\n' +- 'Open a document in the app, or provide a .fig file path.'+ 'Open a document in the app, or provide a .fig file path.')}cachedToken = data.token@@ -37,7 +37,10 @@ export async function rpc<T = unknown>(command: string, args: unknown = {}): Pro})if (!res.ok) {- const body = (await res.json().catch(() => ({ error: `HTTP ${res.status}` }))) as { error?: string; ok?: boolean }+ const body = (await res.json().catch(() => ({ error: `HTTP ${res.status}` }))) as {+ error?: string+ ok?: boolean+ }throw new Error(body.error ?? `RPC failed: HTTP ${res.status}`)}diff --git a/packages/cli/src/commands/analyze/clusters.ts b/packages/cli/src/commands/analyze/clusters.tsindex 49a576a86..5743d959c 100644--- a/packages/cli/src/commands/analyze/clusters.ts+++ b/packages/cli/src/commands/analyze/clusters.ts@@ -1,9 +1,10 @@import { defineCommand } from 'citty'-import { loadDocument } from '../../headless'+import { executeRpcCommand, calcClusterConfidence } from '@open-pencil/core'+import { isAppMode, requireFile, rpc } from '../../app-client'import { bold, fmtList, fmtSummary } from '../../format'-import { executeRpcCommand, calcClusterConfidence } from '@open-pencil/core'+import { loadDocument } from '../../headless'import type { AnalyzeClustersResult } from '@open-pencil/core'@@ -24,8 +25,15 @@ function formatSignature(sig: string): string {return `${typeName} > [${childParts.join(', ')}]`}-async function getData(file: string | undefined, args: { limit?: string; 'min-size'?: string; 'min-count'?: string }): Promise<AnalyzeClustersResult> {- const rpcArgs = { limit: Number(args.limit ?? 20), minSize: Number(args['min-size'] ?? 30), minCount: Number(args['min-count'] ?? 2) }+async function getData(+ file: string | undefined,+ args: { limit?: string; 'min-size'?: string; 'min-count'?: string }+): Promise<AnalyzeClustersResult> {+ const rpcArgs = {+ limit: Number(args.limit ?? 20),+ minSize: Number(args['min-size'] ?? 30),+ minCount: Number(args['min-count'] ?? 2)+ }if (isAppMode(file)) return rpc<AnalyzeClustersResult>('analyze_clusters', rpcArgs)const graph = await loadDocument(requireFile(file))return executeRpcCommand(graph, 'analyze_clusters', rpcArgs) as AnalyzeClustersResult@@ -34,7 +42,11 @@ async function getData(file: string | undefined, args: { limit?: string; 'min-siexport default defineCommand({meta: { description: 'Find repeated design patterns (potential components)' },args: {- file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },+ file: {+ type: 'positional',+ description: '.fig file path (omit to connect to running app)',+ required: false+ },limit: { type: 'string', description: 'Max clusters to show', default: '20' },'min-size': { type: 'string', description: 'Min node size in px', default: '30' },'min-count': { type: 'string', description: 'Min instances to form cluster', default: '2' },@@ -78,7 +90,10 @@ export default defineCommand({details: {size: sizeStr,structure: formatSignature(c.signature),- examples: c.nodes.slice(0, 3).map((n) => n.id).join(', ')+ examples: c.nodes+ .slice(0, 3)+ .map((n) => n.id)+ .join(', ')}}})@@ -87,11 +102,13 @@ export default defineCommand({const clusteredNodes = data.clusters.reduce((sum, c) => sum + c.nodes.length, 0)console.log('')- console.log(fmtSummary({- clusters: data.clusters.length,- 'total nodes': data.totalNodes,- clustered: clusteredNodes- }))+ console.log(+ fmtSummary({+ clusters: data.clusters.length,+ 'total nodes': data.totalNodes,+ clustered: clusteredNodes+ })+ )console.log('')}})diff --git a/packages/cli/src/commands/analyze/colors.ts b/packages/cli/src/commands/analyze/colors.tsindex 382fff191..806f64cc4 100644--- a/packages/cli/src/commands/analyze/colors.ts+++ b/packages/cli/src/commands/analyze/colors.ts@@ -1,13 +1,17 @@import { defineCommand } from 'citty'-import { loadDocument } from '../../headless'+import { executeRpcCommand } from '@open-pencil/core'+import { isAppMode, requireFile, rpc } from '../../app-client'import { bold, fmtHistogram, fmtList, fmtSummary } from '../../format'-import { executeRpcCommand } from '@open-pencil/core'+import { loadDocument } from '../../headless'import type { AnalyzeColorsResult } from '@open-pencil/core'-async function getData(file: string | undefined, args: { threshold?: string; similar?: boolean }): Promise<AnalyzeColorsResult> {+async function getData(+ file: string | undefined,+ args: { threshold?: string; similar?: boolean }+): Promise<AnalyzeColorsResult> {const rpcArgs = { threshold: Number(args.threshold ?? 15), similar: args.similar }if (isAppMode(file)) return rpc<AnalyzeColorsResult>('analyze_colors', rpcArgs)const graph = await loadDocument(requireFile(file))@@ -17,9 +21,17 @@ async function getData(file: string | undefined, args: { threshold?: string; simexport default defineCommand({meta: { description: 'Analyze color palette usage' },args: {- file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },+ file: {+ type: 'positional',+ description: '.fig file path (omit to connect to running app)',+ required: false+ },limit: { type: 'string', description: 'Max colors to show', default: '30' },- threshold: { type: 'string', description: 'Distance threshold for clustering similar colors (0–50)', default: '15' },+ threshold: {+ type: 'string',+ description: 'Distance threshold for clustering similar colors (0–50)',+ default: '15'+ },similar: { type: 'boolean', description: 'Show similar color clusters' },json: { type: 'boolean', description: 'Output as JSON' }},@@ -57,7 +69,11 @@ export default defineCommand({console.log('')console.log(- fmtSummary({ 'unique colors': data.colors.length, 'from variables': fromVars.length, hardcoded: hardcoded.length })+ fmtSummary({+ 'unique colors': data.colors.length,+ 'from variables': fromVars.length,+ hardcoded: hardcoded.length+ }))if (args.similar && data.clusters.length > 0) {diff --git a/packages/cli/src/commands/analyze/index.ts b/packages/cli/src/commands/analyze/index.tsindex 54d2aebce..a4cb7818f 100644--- a/packages/cli/src/commands/analyze/index.ts+++ b/packages/cli/src/commands/analyze/index.ts@@ -1,9 +1,9 @@import { defineCommand } from 'citty'+import clusters from './clusters'import colors from './colors'-import typography from './typography'import spacing from './spacing'-import clusters from './clusters'+import typography from './typography'export default defineCommand({meta: { description: 'Analyze design tokens and patterns' },diff --git a/packages/cli/src/commands/analyze/spacing.ts b/packages/cli/src/commands/analyze/spacing.tsindex 257f68702..8543f0fc2 100644--- a/packages/cli/src/commands/analyze/spacing.ts+++ b/packages/cli/src/commands/analyze/spacing.ts@@ -1,9 +1,10 @@import { defineCommand } from 'citty'-import { loadDocument } from '../../headless'+import { executeRpcCommand } from '@open-pencil/core'+import { isAppMode, requireFile, rpc } from '../../app-client'import { bold, kv, fmtHistogram, fmtSummary } from '../../format'-import { executeRpcCommand } from '@open-pencil/core'+import { loadDocument } from '../../headless'import type { AnalyzeSpacingResult } from '@open-pencil/core'@@ -16,7 +17,11 @@ async function getData(file?: string): Promise<AnalyzeSpacingResult> {export default defineCommand({meta: { description: 'Analyze spacing values (gap, padding)' },args: {- file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },+ file: {+ type: 'positional',+ description: '.fig file path (omit to connect to running app)',+ required: false+ },grid: { type: 'string', description: 'Base grid size to check against', default: '8' },json: { type: 'boolean', description: 'Output as JSON' }},@@ -67,7 +72,9 @@ export default defineCommand({return}- console.log(fmtSummary({ 'gap values': data.gaps.length, 'padding values': data.paddings.length }))+ console.log(+ fmtSummary({ 'gap values': data.gaps.length, 'padding values': data.paddings.length })+ )const offGridGaps = data.gaps.filter((g) => g.value % gridSize !== 0)const offGridPaddings = data.paddings.filter((p) => p.value % gridSize !== 0)diff --git a/packages/cli/src/commands/analyze/typography.ts b/packages/cli/src/commands/analyze/typography.tsindex e5249f2a0..c0694fc86 100644--- a/packages/cli/src/commands/analyze/typography.ts+++ b/packages/cli/src/commands/analyze/typography.ts@@ -1,9 +1,10 @@import { defineCommand } from 'citty'-import { loadDocument } from '../../headless'+import { executeRpcCommand } from '@open-pencil/core'+import { isAppMode, requireFile, rpc } from '../../app-client'import { bold, fmtHistogram, fmtSummary } from '../../format'-import { executeRpcCommand } from '@open-pencil/core'+import { loadDocument } from '../../headless'import type { AnalyzeTypographyResult } from '@open-pencil/core'@@ -28,8 +29,15 @@ async function getData(file?: string): Promise<AnalyzeTypographyResult> {export default defineCommand({meta: { description: 'Analyze typography usage' },args: {- file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },- 'group-by': { type: 'string', description: 'Group by: family, size, weight (default: show all styles)' },+ file: {+ type: 'positional',+ description: '.fig file path (omit to connect to running app)',+ required: false+ },+ 'group-by': {+ type: 'string',+ description: 'Group by: family, size, weight (default: show all styles)'+ },limit: { type: 'string', description: 'Max styles to show', default: '30' },json: { type: 'boolean', description: 'Output as JSON' }},@@ -57,7 +65,9 @@ export default defineCommand({console.log('')console.log(fmtHistogram(- [...byFamily.entries()].sort((a, b) => b[1] - a[1]).map(([family, count]) => ({ label: family, value: count }))+ [...byFamily.entries()]+ .sort((a, b) => b[1] - a[1])+ .map(([family, count]) => ({ label: family, value: count }))))} else if (groupBy === 'size') {@@ -67,7 +77,9 @@ export default defineCommand({console.log('')console.log(fmtHistogram(- [...bySize.entries()].sort((a, b) => a[0] - b[0]).map(([size, count]) => ({ label: `${size}px`, value: count }))+ [...bySize.entries()]+ .sort((a, b) => a[0] - b[0])+ .map(([size, count]) => ({ label: `${size}px`, value: count }))))} else if (groupBy === 'weight') {@@ -77,7 +89,9 @@ export default defineCommand({console.log('')console.log(fmtHistogram(- [...byWeight.entries()].sort((a, b) => b[1] - a[1]).map(([weight, count]) => ({ label: `${weight} ${weightName(weight)}`, value: count }))+ [...byWeight.entries()]+ .sort((a, b) => b[1] - a[1])+ .map(([weight, count]) => ({ label: `${weight} ${weightName(weight)}`, value: count }))))} else {@@ -91,7 +105,9 @@ export default defineCommand({}console.log('')- console.log(fmtSummary({ 'unique styles': data.styles.length, 'text nodes': data.totalTextNodes }))+ console.log(+ fmtSummary({ 'unique styles': data.styles.length, 'text nodes': data.totalTextNodes })+ )console.log('')}})diff --git a/packages/cli/src/commands/eval.ts b/packages/cli/src/commands/eval.tsindex a9e8558dc..c6a91c530 100644--- a/packages/cli/src/commands/eval.ts+++ b/packages/cli/src/commands/eval.ts@@ -2,9 +2,9 @@ import { defineCommand } from 'citty'import { FigmaAPI } from '@open-pencil/core'-import { loadDocument } from '../headless'import { isAppMode, requireFile, rpc } from '../app-client'import { printError } from '../format'+import { loadDocument } from '../headless'function printResult(value: unknown, json: boolean) {if (json || !process.stdout.isTTY) {@@ -26,13 +26,22 @@ function serializeResult(value: unknown): unknown {export default defineCommand({meta: { description: 'Execute JavaScript with Figma plugin API' },args: {- file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },+ file: {+ type: 'positional',+ description: '.fig file path (omit to connect to running app)',+ required: false+ },code: { type: 'string', alias: 'c', description: 'JavaScript code to execute' },stdin: { type: 'boolean', description: 'Read code from stdin' },write: { type: 'boolean', alias: 'w', description: 'Write changes back to the input file' },- output: { type: 'string', alias: 'o', description: 'Write to a different file', required: false },+ output: {+ type: 'string',+ alias: 'o',+ description: 'Write to a different file',+ required: false+ },json: { type: 'boolean', description: 'Output as JSON' },- quiet: { type: 'boolean', alias: 'q', description: 'Suppress output' },+ quiet: { type: 'boolean', alias: 'q', description: 'Suppress output' }},async run({ args }) {let code = args.code@@ -88,5 +97,5 @@ export default defineCommand({console.error(`Written to ${outPath}`)}}- },+ }})diff --git a/packages/cli/src/commands/export.ts b/packages/cli/src/commands/export.tsindex e6b2eff05..cd2dd33d0 100644--- a/packages/cli/src/commands/export.ts+++ b/packages/cli/src/commands/export.ts@@ -1,11 +1,13 @@-import { defineCommand } from 'citty'import { basename, extname, resolve } from 'node:path'+import { defineCommand } from 'citty'+import { renderNodesToSVG, sceneNodeToJSX, selectionToJSX } from '@open-pencil/core'-import { loadDocument, exportNodes, exportThumbnail } from '../headless'import { isAppMode, requireFile, rpc } from '../app-client'import { ok, printError } from '../format'+import { loadDocument, exportNodes, exportThumbnail } from '../headless'+import type { ExportFormat, JSXFormat } from '@open-pencil/core'const RASTER_FORMATS = ['PNG', 'JPG', 'WEBP']@@ -34,15 +36,27 @@ async function writeAndLog(path: string, content: string | Uint8Array) {async function exportViaApp(format: string, args: ExportArgs) {if (format === 'SVG') {- const result = await rpc<{ svg: string }>('tool', { name: 'export_svg', args: { ids: args.node ? [args.node] : undefined } })- if (!result.svg) { printError('Nothing to export.'); process.exit(1) }+ const result = await rpc<{ svg: string }>('tool', {+ name: 'export_svg',+ args: { ids: args.node ? [args.node] : undefined }+ })+ if (!result.svg) {+ printError('Nothing to export.')+ process.exit(1)+ }await writeAndLog(resolve(args.output ?? 'export.svg'), result.svg)return}if (format === 'JSX') {- const result = await rpc<{ jsx: string }>('export_jsx', { nodeIds: args.node ? [args.node] : undefined, style: args.style })- if (!result.jsx) { printError('Nothing to export.'); process.exit(1) }+ const result = await rpc<{ jsx: string }>('export_jsx', {+ nodeIds: args.node ? [args.node] : undefined,+ style: args.style+ })+ if (!result.jsx) {+ printError('Nothing to export.')+ process.exit(1)+ }await writeAndLog(resolve(args.output ?? 'export.jsx'), result.jsx)return}@@ -63,16 +77,23 @@ async function exportFromFile(format: string, args: ExportArgs) {const pages = graph.getPages()const page = args.page ? pages.find((p) => p.name === args.page) : pages[0]- if (!page) { printError(`Page "${args.page}" not found.`); process.exit(1) }+ if (!page) {+ printError(`Page "${args.page}" not found.`)+ process.exit(1)+ }const defaultName = basename(file, extname(file))if (format === 'JSX') {const nodeIds = args.node ? [args.node] : page.childIds- const jsxStr = nodeIds.length === 1- ? sceneNodeToJSX(nodeIds[0], graph, args.style as JSXFormat)- : selectionToJSX(nodeIds, graph, args.style as JSXFormat)- if (!jsxStr) { printError('Nothing to export (empty page or no visible nodes).'); process.exit(1) }+ const jsxStr =+ nodeIds.length === 1+ ? sceneNodeToJSX(nodeIds[0], graph, args.style as JSXFormat)+ : selectionToJSX(nodeIds, graph, args.style as JSXFormat)+ if (!jsxStr) {+ printError('Nothing to export (empty page or no visible nodes).')+ process.exit(1)+ }await writeAndLog(resolve(args.output ?? `${defaultName}.jsx`), jsxStr)return}@@ -83,7 +104,10 @@ async function exportFromFile(format: string, args: ExportArgs) {if (format === 'SVG') {const nodeIds = args.node ? [args.node] : page.childIdsconst svgStr = renderNodesToSVG(graph, page.id, nodeIds)- if (!svgStr) { printError('Nothing to export (empty page or no visible nodes).'); process.exit(1) }+ if (!svgStr) {+ printError('Nothing to export (empty page or no visible nodes).')+ process.exit(1)+ }await writeAndLog(output, svgStr)return}@@ -100,21 +124,51 @@ async function exportFromFile(format: string, args: ExportArgs) {})}- if (!data) { printError('Nothing to export (empty page or no visible nodes).'); process.exit(1) }+ if (!data) {+ printError('Nothing to export (empty page or no visible nodes).')+ process.exit(1)+ }await writeAndLog(output, data)}export default defineCommand({meta: { description: 'Export a .fig file to PNG, JPG, WEBP, SVG, or JSX' },args: {- file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },- output: { type: 'string', alias: 'o', description: 'Output file path (default: <name>.<format>)', required: false },- format: { type: 'string', alias: 'f', description: 'Export format: png, jpg, webp, svg, jsx (default: png)', default: 'png' },+ file: {+ type: 'positional',+ description: '.fig file path (omit to connect to running app)',+ required: false+ },+ output: {+ type: 'string',+ alias: 'o',+ description: 'Output file path (default: <name>.<format>)',+ required: false+ },+ format: {+ type: 'string',+ alias: 'f',+ description: 'Export format: png, jpg, webp, svg, jsx (default: png)',+ default: 'png'+ },scale: { type: 'string', alias: 's', description: 'Export scale (default: 1)', default: '1' },- quality: { type: 'string', alias: 'q', description: 'Quality 0-100 for JPG/WEBP (default: 90)', required: false },+ quality: {+ type: 'string',+ alias: 'q',+ description: 'Quality 0-100 for JPG/WEBP (default: 90)',+ required: false+ },page: { type: 'string', description: 'Page name (default: first page)', required: false },- node: { type: 'string', description: 'Node ID to export (default: all top-level nodes)', required: false },- style: { type: 'string', description: 'JSX style: openpencil, tailwind (default: openpencil)', default: 'openpencil' },+ node: {+ type: 'string',+ description: 'Node ID to export (default: all top-level nodes)',+ required: false+ },+ style: {+ type: 'string',+ description: 'JSX style: openpencil, tailwind (default: openpencil)',+ default: 'openpencil'+ },thumbnail: { type: 'boolean', description: 'Export page thumbnail instead of full render' },width: { type: 'string', description: 'Thumbnail width (default: 1920)', default: '1920' },height: { type: 'string', description: 'Thumbnail height (default: 1080)', default: '1080' }diff --git a/packages/cli/src/commands/find.ts b/packages/cli/src/commands/find.tsindex fdc143dfd..be47a0753 100644--- a/packages/cli/src/commands/find.ts+++ b/packages/cli/src/commands/find.ts@@ -1,14 +1,23 @@import { defineCommand } from 'citty'-import { loadDocument } from '../headless'+import { executeRpcCommand } from '@open-pencil/core'+import { isAppMode, requireFile, rpc } from '../app-client'import { printNodeResults } from '../format'-import { executeRpcCommand } from '@open-pencil/core'+import { loadDocument } from '../headless'import type { FindNodeResult } from '@open-pencil/core'-async function getData(file: string | undefined, args: { name?: string; type?: string; page?: string; limit?: string }): Promise<FindNodeResult[]> {- const rpcArgs = { name: args.name, type: args.type, page: args.page, limit: args.limit ? Number(args.limit) : undefined }+async function getData(+ file: string | undefined,+ args: { name?: string; type?: string; page?: string; limit?: string }+): Promise<FindNodeResult[]> {+ const rpcArgs = {+ name: args.name,+ type: args.type,+ page: args.page,+ limit: args.limit ? Number(args.limit) : undefined+ }if (isAppMode(file)) return rpc<FindNodeResult[]>('find', rpcArgs)const graph = await loadDocument(requireFile(file))return executeRpcCommand(graph, 'find', rpcArgs) as FindNodeResult[]@@ -17,7 +26,11 @@ async function getData(file: string | undefined, args: { name?: string; type?: sexport default defineCommand({meta: { description: 'Find nodes by name or type' },args: {- file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },+ file: {+ type: 'positional',+ description: '.fig file path (omit to connect to running app)',+ required: false+ },name: { type: 'string', description: 'Node name (partial match, case-insensitive)' },type: { type: 'string', description: 'Node type: FRAME, TEXT, RECTANGLE, INSTANCE, etc.' },page: { type: 'string', description: 'Page name (default: all pages)' },diff --git a/packages/cli/src/commands/info.ts b/packages/cli/src/commands/info.tsindex f611a1148..d10534b7a 100644--- a/packages/cli/src/commands/info.ts+++ b/packages/cli/src/commands/info.ts@@ -1,11 +1,12 @@import { defineCommand } from 'citty'-import { loadDocument } from '../headless'+import { executeRpcCommand } from '@open-pencil/core'+import { isAppMode, requireFile, rpc } from '../app-client'import { bold, fmtHistogram, fmtSummary, kv } from '../format'+import { loadDocument } from '../headless'import type { InfoResult } from '@open-pencil/core'-import { executeRpcCommand } from '@open-pencil/core'async function getData(file?: string): Promise<InfoResult> {if (isAppMode(file)) return rpc<InfoResult>('info')@@ -16,7 +17,11 @@ async function getData(file?: string): Promise<InfoResult> {export default defineCommand({meta: { description: 'Show document info (pages, node counts, fonts)' },args: {- file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },+ file: {+ type: 'positional',+ description: '.fig file path (omit to connect to running app)',+ required: false+ },json: { type: 'boolean', description: 'Output as JSON' }},async run({ args }) {diff --git a/packages/cli/src/commands/node.ts b/packages/cli/src/commands/node.tsindex 0b795a468..6ae52c41d 100644--- a/packages/cli/src/commands/node.ts+++ b/packages/cli/src/commands/node.ts@@ -1,13 +1,17 @@import { defineCommand } from 'citty'-import { loadDocument } from '../headless'+import { executeRpcCommand, colorToHex } from '@open-pencil/core'+import { isAppMode, requireFile, rpc } from '../app-client'import { fmtNode, printError, formatType } from '../format'-import { executeRpcCommand, colorToHex } from '@open-pencil/core'+import { loadDocument } from '../headless'import type { Color, NodeResult } from '@open-pencil/core'-async function getData(file: string | undefined, id: string): Promise<NodeResult | { error: string }> {+async function getData(+ file: string | undefined,+ id: string+): Promise<NodeResult | { error: string }> {if (isAppMode(file)) return rpc<NodeResult>('node', { id })const graph = await loadDocument(requireFile(file))return executeRpcCommand(graph, 'node', { id }) as NodeResult | { error: string }@@ -16,7 +20,11 @@ async function getData(file: string | undefined, id: string): Promise<NodeResultexport default defineCommand({meta: { description: 'Show detailed node properties by ID' },args: {- file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },+ file: {+ type: 'positional',+ description: '.fig file path (omit to connect to running app)',+ required: false+ },id: { type: 'string', description: 'Node ID', required: true },json: { type: 'boolean', description: 'Output as JSON' }},@@ -47,8 +55,9 @@ export default defineCommand({if (data.parent) details.parent = `${data.parent.name} (${data.parent.id})`if (data.text) details.text = data.textif (data.fills.length > 0) {- const solid = (data.fills as Array<{ type: string; visible: boolean; color: Color; opacity: number }>)- .find((f) => f.type === 'SOLID' && f.visible)+ const solid = (+ data.fills as Array<{ type: string; visible: boolean; color: Color; opacity: number }>+ ).find((f) => f.type === 'SOLID' && f.visible)if (solid) {const hex = colorToHex(solid.color)details.fill = solid.opacity < 1 ? `${hex} ${Math.round(solid.opacity * 100)}%` : hexdiff --git a/packages/cli/src/commands/pages.ts b/packages/cli/src/commands/pages.tsindex f179048ae..2a23c045d 100644--- a/packages/cli/src/commands/pages.ts+++ b/packages/cli/src/commands/pages.ts@@ -1,11 +1,12 @@import { defineCommand } from 'citty'-import { loadDocument } from '../headless'+import { executeRpcCommand } from '@open-pencil/core'+import { isAppMode, requireFile, rpc } from '../app-client'import { bold, fmtList, entity } from '../format'+import { loadDocument } from '../headless'import type { PageItem } from '@open-pencil/core'-import { executeRpcCommand } from '@open-pencil/core'async function getData(file?: string): Promise<PageItem[]> {if (isAppMode(file)) return rpc<PageItem[]>('pages')@@ -16,7 +17,11 @@ async function getData(file?: string): Promise<PageItem[]> {export default defineCommand({meta: { description: 'List pages in a .fig file' },args: {- file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },+ file: {+ type: 'positional',+ description: '.fig file path (omit to connect to running app)',+ required: false+ },json: { type: 'boolean', description: 'Output as JSON' }},async run({ args }) {diff --git a/packages/cli/src/commands/query.ts b/packages/cli/src/commands/query.tsindex ab2d70f79..c22c52d98 100644--- a/packages/cli/src/commands/query.ts+++ b/packages/cli/src/commands/query.ts@@ -1,9 +1,10 @@import { defineCommand } from 'citty'-import { loadDocument } from '../headless'+import { executeRpcCommand } from '@open-pencil/core'+import { isAppMode, requireFile, rpc } from '../app-client'import { printNodeResults, printError } from '../format'-import { executeRpcCommand } from '@open-pencil/core'+import { loadDocument } from '../headless'import type { QueryNodeResult } from '@open-pencil/core'@@ -18,7 +19,7 @@ async function getData(}if (isAppMode(file)) return rpc<QueryNodeResult[]>('query', rpcArgs)const graph = await loadDocument(requireFile(file))- return await executeRpcCommand(graph, 'query', rpcArgs) as QueryNodeResult[] | { error: string }+ return (await executeRpcCommand(graph, 'query', rpcArgs)) as QueryNodeResult[] | { error: string }}export default defineCommand({@@ -41,8 +42,7 @@ Examples:},selector: {type: 'positional',- description:- 'XPath selector (e.g., //FRAME[@width < 300], //TEXT[contains(@name, "Label")])',+ description: 'XPath selector (e.g., //FRAME[@width < 300], //TEXT[contains(@name, "Label")])',required: true},page: { type: 'string', description: 'Page name (default: all pages)' },diff --git a/packages/cli/src/commands/tree.ts b/packages/cli/src/commands/tree.tsindex d8daa6321..c7ca8175b 100644--- a/packages/cli/src/commands/tree.ts+++ b/packages/cli/src/commands/tree.ts@@ -1,9 +1,10 @@import { defineCommand } from 'citty'-import { loadDocument } from '../headless'+import { executeRpcCommand } from '@open-pencil/core'+import { isAppMode, requireFile, rpc } from '../app-client'import { fmtTree, printError, entity, formatType } from '../format'-import { executeRpcCommand } from '@open-pencil/core'+import { loadDocument } from '../headless'import type { TreeResult, TreeNodeResult } from '@open-pencil/core'import type { TreeNode } from 'agentfmt'@@ -18,7 +19,10 @@ function toAgentfmtTree(node: TreeNodeResult, maxDepth: number, depth = 0): Treereturn treeNode}-async function getData(file: string | undefined, args: { page?: string; depth?: string }): Promise<TreeResult | { error: string }> {+async function getData(+ file: string | undefined,+ args: { page?: string; depth?: string }+): Promise<TreeResult | { error: string }> {const rpcArgs = { page: args.page, depth: args.depth ? Number(args.depth) : undefined }if (isAppMode(file)) return rpc<TreeResult>('tree', rpcArgs)const graph = await loadDocument(requireFile(file))@@ -28,7 +32,11 @@ async function getData(file: string | undefined, args: { page?: string; depth?:export default defineCommand({meta: { description: 'Print the node tree' },args: {- file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },+ file: {+ type: 'positional',+ description: '.fig file path (omit to connect to running app)',+ required: false+ },page: { type: 'string', description: 'Page name (default: first page)' },depth: { type: 'string', description: 'Max depth (default: unlimited)' },json: { type: 'boolean', description: 'Output as JSON' }diff --git a/packages/cli/src/commands/variables.ts b/packages/cli/src/commands/variables.tsindex 0a956e3eb..24e513579 100644--- a/packages/cli/src/commands/variables.ts+++ b/packages/cli/src/commands/variables.ts@@ -1,13 +1,17 @@import { defineCommand } from 'citty'-import { loadDocument } from '../headless'+import { executeRpcCommand } from '@open-pencil/core'+import { isAppMode, requireFile, rpc } from '../app-client'import { bold, entity, fmtList, fmtSummary } from '../format'-import { executeRpcCommand } from '@open-pencil/core'+import { loadDocument } from '../headless'import type { VariablesResult } from '@open-pencil/core'-async function getData(file: string | undefined, args: { collection?: string; type?: string }): Promise<VariablesResult> {+async function getData(+ file: string | undefined,+ args: { collection?: string; type?: string }+): Promise<VariablesResult> {const rpcArgs = { collection: args.collection, type: args.type }if (isAppMode(file)) return rpc<VariablesResult>('variables', rpcArgs)const graph = await loadDocument(requireFile(file))@@ -17,7 +21,11 @@ async function getData(file: string | undefined, args: { collection?: string; tyexport default defineCommand({meta: { description: 'List design variables and collections' },args: {- file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },+ file: {+ type: 'positional',+ description: '.fig file path (omit to connect to running app)',+ required: false+ },collection: { type: 'string', description: 'Filter by collection name' },type: { type: 'string', description: 'Filter by type: COLOR, FLOAT, STRING, BOOLEAN' },json: { type: 'boolean', description: 'Output as JSON' }diff --git a/packages/cli/src/format.ts b/packages/cli/src/format.tsindex 6c6a31fc4..c33a0f8ae 100644--- a/packages/cli/src/format.ts+++ b/packages/cli/src/format.ts@@ -13,10 +13,24 @@ import {histogram as fmtHistogram,summary as fmtSummary} from 'agentfmt'-import type { TreeNode, ListItem, NodeData } from 'agentfmt'+import type { SceneNode, SceneGraph } from '@open-pencil/core'+import type { TreeNode, ListItem, NodeData } from 'agentfmt'-export { ok, fail, dim, bold, cyan, entity, kv, fmtTree, fmtList, fmtNode, fmtHistogram, fmtSummary }+export {+ ok,+ fail,+ dim,+ bold,+ cyan,+ entity,+ kv,+ fmtTree,+ fmtList,+ fmtNode,+ fmtHistogram,+ fmtSummary+}export function printNodeResults(results: Array<{ type: string; name: string; id: string }>,@@ -63,7 +77,12 @@ export function formatType(type: string): string {}export function formatBox(node: SceneNode): string {- return fmtBox(Math.round(node.width), Math.round(node.height), Math.round(node.x), Math.round(node.y))+ return fmtBox(+ Math.round(node.width),+ Math.round(node.height),+ Math.round(node.x),+ Math.round(node.y)+ )}function formatFill(node: SceneNode): string | null {@@ -71,7 +90,15 @@ function formatFill(node: SceneNode): string | null {const solid = node.fills.find((f) => f.type === 'SOLID' && f.visible)if (!solid?.color) return nullconst { r, g, b } = solid.color- const hex = '#' + [r, g, b].map((c) => Math.round(c * 255).toString(16).padStart(2, '0')).join('')+ const hex =+ '#' ++ [r, g, b]+ .map((c) =>+ Math.round(c * 255)+ .toString(16)+ .padStart(2, '0')+ )+ .join('')return solid.opacity < 1 ? `${hex} ${Math.round(solid.opacity * 100)}%` : hex}@@ -79,7 +106,15 @@ function formatStroke(node: SceneNode): string | null {if (!node.strokes.length) return nullconst s = node.strokes[0]const { r, g, b } = s.color- const hex = '#' + [r, g, b].map((c) => Math.round(c * 255).toString(16).padStart(2, '0')).join('')+ const hex =+ '#' ++ [r, g, b]+ .map((c) =>+ Math.round(c * 255)+ .toString(16)+ .padStart(2, '0')+ )+ .join('')return `${hex} ${s.weight}px`}@@ -143,7 +178,12 @@ export function nodeDetails(node: SceneNode): Record<string, unknown> {return details}-export function nodeToTreeNode(graph: SceneGraph, node: SceneNode, maxDepth: number, depth = 0): TreeNode {+export function nodeToTreeNode(+ graph: SceneGraph,+ node: SceneNode,+ maxDepth: number,+ depth = 0+): TreeNode {const treeNode: TreeNode = {header: entity(formatType(node.type), node.name, node.id),details: nodeDetails(node)diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex 41bfb031c..d9ad253f8 100755--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -6,9 +6,9 @@ import evalCmd from './commands/eval'import exportCmd from './commands/export'import find from './commands/find'import info from './commands/info'-import query from './commands/query'import node from './commands/node'import pages from './commands/pages'+import query from './commands/query'import tree from './commands/tree'import variables from './commands/variables'diff --git a/packages/core/src/canvaskit.ts b/packages/core/src/canvaskit.tsindex f9df230d6..979f38b72 100644--- a/packages/core/src/canvaskit.ts+++ b/packages/core/src/canvaskit.ts@@ -29,9 +29,13 @@ function loadCanvasKitWebGPU(): Promise<(opts?: Record<string, unknown>) => Promconst script = document.createElement('script')script.src = '/canvaskit-webgpu/canvaskit.js'script.onload = () => {- const init = 'CanvasKitInit' in globalThis- ? ((globalThis as typeof globalThis & { CanvasKitInit: unknown }).CanvasKitInit as (opts?: { locateFile?: (file: string) => string }) => Promise<CanvasKit>)- : null+ const init =+ 'CanvasKitInit' in globalThis+ ? ((globalThis as typeof globalThis & { CanvasKitInit: unknown })+ .CanvasKitInit as (opts?: {+ locateFile?: (file: string) => string+ }) => Promise<CanvasKit>)+ : nullif (!init) return reject(new Error('CanvasKitInit not found after loading WebGPU build'))resolve(init)}@@ -54,9 +58,7 @@ export async function getCanvasKit(options?: CanvasKitOptions): Promise<CanvasKiif (backend === 'webgpu') {const init = await loadCanvasKitWebGPU()instance = await init({- locateFile:- options?.locateFile ??- ((file: string) => `/canvaskit-webgpu/${file}`)+ locateFile: options?.locateFile ?? ((file: string) => `/canvaskit-webgpu/${file}`)})} else {instance = await CanvasKitInit({diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.tsindex 37b01cb95..52085f383 100644--- a/packages/core/src/clipboard.ts+++ b/packages/core/src/clipboard.ts@@ -1,7 +1,9 @@import { inflateSync, deflateSync } from 'fflate'-import { randomInt } from './random'-+import { initCodec, getCompiledSchema, getSchemaBytes } from './kiwi/codec'+import { populateAndApplyOverrides } from './kiwi/instance-overrides'+import { nodeChangeToProps, sortChildren } from './kiwi/kiwi-convert'+import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi/kiwi-schema'import {sceneNodeToKiwi,buildFigKiwi,@@ -10,13 +12,10 @@ import {makeDocumentNodeChange,makeCanvasNodeChange} from './kiwi/kiwi-serialize'-import { initCodec, getCompiledSchema, getSchemaBytes } from './kiwi/codec'-import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi/kiwi-schema'-import { nodeChangeToProps, sortChildren } from './kiwi/kiwi-convert'-import { populateAndApplyOverrides } from './kiwi/instance-overrides'-import type { InstanceNodeChange } from './kiwi/instance-overrides'+import { randomInt } from './random'import type { NodeChange as KiwiNodeChange } from './kiwi/codec'+import type { InstanceNodeChange } from './kiwi/instance-overrides'import type { SceneGraph, SceneNode } from './scene-graph'interface FigmaClipboardMeta {@@ -85,7 +84,11 @@ function isChildOfVisualNode(nc: KiwiNodeChange, parentTypes: Map<string, stringconst parentId = nc.parentIndex?.guid? `${nc.parentIndex.guid.sessionID}:${nc.parentIndex.guid.localID}`: null- return !!parentId && parentTypes.has(parentId) && !NON_VISUAL_TYPES.has(parentTypes.get(parentId) ?? '')+ return (+ !!parentId &&+ parentTypes.has(parentId) &&+ !NON_VISUAL_TYPES.has(parentTypes.get(parentId) ?? '')+ )}export function figmaNodesBounds(@@ -217,7 +220,11 @@ export function importClipboardNodes(): string[] {const { guidMap, parentMap } = buildClipboardMaps(nodeChanges)const { internalCanvasIds, internalFigmaIds } = findInternalNodeIds(guidMap, parentMap)- const { topLevel, internalTopLevel } = classifyTopLevelNodes(guidMap, parentMap, internalCanvasIds)+ const { topLevel, internalTopLevel } = classifyTopLevelNodes(+ guidMap,+ parentMap,+ internalCanvasIds+ )const created = new Map<string, string>()const createdIds: string[] = []@@ -334,9 +341,7 @@ export interface OpenPencilClipboardData {images: Map<string, Uint8Array>}-export function parseOpenPencilClipboard(- html: string-): OpenPencilClipboardData | null {+export function parseOpenPencilClipboard(html: string): OpenPencilClipboardData | null {const match = html.match(/<!--\(openpencil\)(.*?)\(\/openpencil\)-->/s)if (!match) return nulldiff --git a/packages/core/src/color.ts b/packages/core/src/color.tsindex 426850611..bef58c008 100644--- a/packages/core/src/color.ts+++ b/packages/core/src/color.ts@@ -30,9 +30,7 @@ export function colorToHex(color: Color): string {export function colorToHex8(color: Color, alpha?: number): string {const a = alpha ?? color.aif (a >= 1) return colorToHex(color)- return (- formatHex8({ mode: 'rgb', r: color.r, g: color.g, b: color.b, alpha: a })- ).toUpperCase()+ return formatHex8({ mode: 'rgb', r: color.r, g: color.g, b: color.b, alpha: a }).toUpperCase()}export function colorToHexRaw(color: Color): string {@@ -76,8 +74,10 @@ export function colorToFill(color: string | Color) {const euclideanRgb255 = differenceEuclidean('rgb')export function colorDistance(c1: Color, c2: Color): number {- return euclideanRgb255(- { mode: 'rgb', r: c1.r, g: c1.g, b: c1.b },- { mode: 'rgb', r: c2.r, g: c2.g, b: c2.b }- ) * 255+ return (+ euclideanRgb255(+ { mode: 'rgb', r: c1.r, g: c1.g, b: c1.b },+ { mode: 'rgb', r: c2.r, g: c2.g, b: c2.b }+ ) * 255+ )}diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.tsindex 178f8f8f3..57c438173 100644--- a/packages/core/src/constants.ts+++ b/packages/core/src/constants.ts@@ -1,5 +1,5 @@-import type { Color } from './types'import type { Fill, Stroke } from './scene-graph'+import type { Color } from './types'export const IS_BROWSER = typeof window !== 'undefined'export const IS_TAURI = IS_BROWSER && '__TAURI_INTERNALS__' in window@@ -283,7 +283,6 @@ export const CJK_FALLBACK_FAMILIES_LINUX = [export const CJK_GOOGLE_FONT = 'Noto Sans SC'-export const DEFAULT_SHAPE_FILL: Fill = {type: 'SOLID',color: { r: 0.83, g: 0.83, b: 0.83, a: 1 },diff --git a/packages/core/src/copy.ts b/packages/core/src/copy.tsindex 455e45ed1..830d8e01e 100644--- a/packages/core/src/copy.ts+++ b/packages/core/src/copy.ts@@ -32,7 +32,7 @@ export function copyEffect(e: Effect): Effect {return {...e,color: { ...e.color },- offset: { ...e.offset },+ offset: { ...e.offset }}}@@ -41,8 +41,8 @@ export function copyStyleRun(r: StyleRun): StyleRun {...r,style: {...r.style,- fills: r.style.fills ? r.style.fills.map(copyFill) : undefined,- },+ fills: r.style.fills ? r.style.fills.map(copyFill) : undefined+ }}}@@ -67,7 +67,7 @@ export function copyStyleRuns(runs: StyleRun[]): StyleRun[] {export function copyGeometryPaths(paths: GeometryPath[]): GeometryPath[] {return paths.map((p) => ({windingRule: p.windingRule,- commandsBlob: p.commandsBlob.slice(),+ commandsBlob: p.commandsBlob.slice()}))}diff --git a/packages/core/src/editor/alignment.ts b/packages/core/src/editor/alignment.tsindex e436a66ff..029c30ec9 100644--- a/packages/core/src/editor/alignment.ts+++ b/packages/core/src/editor/alignment.ts@@ -1,6 +1,7 @@import { computeAbsoluteBounds } from '../geometry'-import type { Vector } from '../types'+import type { SceneNode } from '../scene-graph'+import type { Vector } from '../types'import type { EditorContext } from './types'function computeAlignTarget(@@ -50,9 +51,7 @@ function alignMultipleNodes(for (const n of nodes) {const abs = absPositions.get(n.id)if (!abs) continue- const parentAbs = n.parentId- ? ctx.graph.getAbsolutePosition(n.parentId)- : { x: 0, y: 0 }+ const parentAbs = n.parentId ? ctx.graph.getAbsolutePosition(n.parentId) : { x: 0, y: 0 }if (axis === 'horizontal') {const target = computeAlignTarget(minX, maxX, n.width, align)@@ -117,8 +116,7 @@ export function createAlignmentActions(ctx: EditorContext) {const node = ctx.graph.getNode(id)if (!node) continueoriginals.set(id, { flipX: node.flipX, flipY: node.flipY })- const changes =- axis === 'horizontal' ? { flipX: !node.flipX } : { flipY: !node.flipY }+ const changes = axis === 'horizontal' ? { flipX: !node.flipX } : { flipY: !node.flipY }ctx.graph.updateNode(id, changes)}@@ -149,7 +147,7 @@ export function createAlignmentActions(ctx: EditorContext) {const node = ctx.graph.getNode(id)if (!node) continueoriginals.set(id, node.rotation)- ctx.graph.updateNode(id, { rotation: ((node.rotation + degrees) % 360 + 360) % 360 })+ ctx.graph.updateNode(id, { rotation: (((node.rotation + degrees) % 360) + 360) % 360 })}const finals = new Map<string, number>()diff --git a/packages/core/src/editor/clipboard.ts b/packages/core/src/editor/clipboard.tsindex ba7cc27a0..ebde0d1b3 100644--- a/packages/core/src/editor/clipboard.ts+++ b/packages/core/src/editor/clipboard.ts@@ -1,14 +1,10 @@+import { buildFigmaClipboardHTML, importClipboardNodes, parseFigmaClipboard } from '../clipboard'+import { computeImageHash } from '../figma-api'+import { collectFontKeys } from '../fonts'import { computeBounds } from '../geometry'import { computeAllLayouts } from '../layout'-import {- buildFigmaClipboardHTML,- importClipboardNodes,- parseFigmaClipboard-} from '../clipboard'-import { collectFontKeys } from '../fonts'-import { computeImageHash } from '../figma-api'-import { renderNodesToSVG } from '../svg-export'import { selectionToJSX } from '../render'+import { renderNodesToSVG } from '../svg-export'import type { Fill, SceneGraph, SceneNode } from '../scene-graph'import type { Vector } from '../types'@@ -290,7 +286,8 @@ export function createClipboardActions(ctx: EditorContext) {}function copySelectionAsSVG(ids: string[]): string | null {- const nodeIds = ids.length > 0 ? ids : ctx.graph.getChildren(ctx.state.currentPageId).map((n) => n.id)+ const nodeIds =+ ids.length > 0 ? ids : ctx.graph.getChildren(ctx.state.currentPageId).map((n) => n.id)return renderNodesToSVG(ctx.graph, ctx.state.currentPageId, nodeIds)}diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.tsindex 94c156adc..3feed594b 100644--- a/packages/core/src/editor/index.ts+++ b/packages/core/src/editor/index.ts@@ -1,13 +1,4 @@export { createDefaultEditorState, createEditor } from './create'export type { Editor } from './create'-export {- EDITOR_TOOLS,- TOOL_SHORTCUTS-} from './types'-export type {- EditorContext,- EditorOptions,- EditorState,- EditorToolDef,- Tool-} from './types'+export { EDITOR_TOOLS, TOOL_SHORTCUTS } from './types'+export type { EditorContext, EditorOptions, EditorState, EditorToolDef, Tool } from './types'diff --git a/packages/core/src/editor/selection.ts b/packages/core/src/editor/selection.tsindex a5708ad8a..efb047a9c 100644--- a/packages/core/src/editor/selection.ts+++ b/packages/core/src/editor/selection.ts@@ -1,6 +1,6 @@-import type { Rect } from '../types'import type { SceneNode } from '../scene-graph'import type { SnapGuide } from '../snap'+import type { Rect } from '../types'import type { EditorContext } from './types'export function createSelectionActions(ctx: EditorContext) {@@ -110,9 +110,7 @@ export function createSelectionActions(ctx: EditorContext) {const abs = ctx.graph.getAbsolutePosition(scopeId)const lx = cx - abs.xconst ly = cy - abs.y- return deep- ? ctx.graph.hitTestDeep(lx, ly, scopeId)- : ctx.graph.hitTest(lx, ly, scopeId)+ return deep ? ctx.graph.hitTestDeep(lx, ly, scopeId) : ctx.graph.hitTest(lx, ly, scopeId)}}return deepdiff --git a/packages/core/src/editor/structure.ts b/packages/core/src/editor/structure.tsindex 99c33d5cd..e744b2c40 100644--- a/packages/core/src/editor/structure.ts+++ b/packages/core/src/editor/structure.ts@@ -118,13 +118,18 @@ export function createStructureActions(ctx: EditorContext) {const nodeIds = selectedNodes.map((n) => n.id)const origPositions = selectedNodes.map((n) => ({ id: n.id, x: n.x, y: n.y }))- const { x: minX, y: minY, width: bw, height: bh } = computeAbsoluteBounds(- selectedNodes, (id) => ctx.graph.getAbsolutePosition(id)- )+ const {+ x: minX,+ y: minY,+ width: bw,+ height: bh+ } = computeAbsoluteBounds(selectedNodes, (id) => ctx.graph.getAbsolutePosition(id))const maxX = minX + bwconst maxY = minY + bh- const parentAbs = isTopLevel(parentId) ? { x: 0, y: 0 } : ctx.graph.getAbsolutePosition(parentId)+ const parentAbs = isTopLevel(parentId)+ ? { x: 0, y: 0 }+ : ctx.graph.getAbsolutePosition(parentId)const firstIndex = Math.min(...nodeIds.map((id) => parent.childIds.indexOf(id)))const padding = containerType === 'COMPONENT_SET' ? 40 : 0@@ -140,9 +145,17 @@ export function createStructureActions(ctx: EditorContext) {y: minY - parentAbs.y - padding,width: maxX - minX + padding * 2,height: maxY - minY + padding * 2,- fills: containerType === 'COMPONENT_SET'- ? [{ type: 'SOLID', color: { r: 0.96, g: 0.96, b: 0.96, a: 1 }, opacity: 1, visible: true }]- : [],+ fills:+ containerType === 'COMPONENT_SET'+ ? [+ {+ type: 'SOLID',+ color: { r: 0.96, g: 0.96, b: 0.96, a: 1 },+ opacity: 1,+ visible: true+ }+ ]+ : [],...extraProps})const containerId = containerNode.id@@ -158,7 +171,11 @@ export function createStructureActions(ctx: EditorContext) {ctx.undo.push({label: `Create ${containerType.toLowerCase().replace('_', ' ')}`,forward: () => {- const c = ctx.graph.createNode(containerType, parentId, { ...containerNode, ...extraProps, id: containerId })+ const c = ctx.graph.createNode(containerType, parentId, {+ ...containerNode,+ ...extraProps,+ id: containerId+ })ctx.graph.insertChildAt(c.id, parentId, firstIndex)for (const n of origPositions) ctx.graph.reparentNode(n.id, c.id)ctx.state.selectedIds = new Set([c.id])@@ -287,7 +304,11 @@ export function createStructureActions(ctx: EditorContext) {ctx.state.selectedIds = new Set(childIds)},inverse: () => {- const g = ctx.graph.createNode('GROUP', parentId, { ...groupSnapshot, childIds: [], id: groupId })+ const g = ctx.graph.createNode('GROUP', parentId, {+ ...groupSnapshot,+ childIds: [],+ id: groupId+ })ctx.graph.insertChildAt(g.id, parentId, groupIndex)for (const orig of origPositions) {ctx.graph.reparentNode(orig.id, g.id)diff --git a/packages/core/src/editor/undo.ts b/packages/core/src/editor/undo.tsindex d554c304a..b88854825 100644--- a/packages/core/src/editor/undo.ts+++ b/packages/core/src/editor/undo.ts@@ -1,7 +1,7 @@import { computeAllLayouts } from '../layout'-import type { Rect, Vector } from '../types'import type { SceneNode } from '../scene-graph'+import type { Rect, Vector } from '../types'import type { UndoEntry } from '../undo'import type { EditorContext } from './types'diff --git a/packages/core/src/editor/variables.ts b/packages/core/src/editor/variables.tsindex 0c636fa7e..209035771 100644--- a/packages/core/src/editor/variables.ts+++ b/packages/core/src/editor/variables.ts@@ -34,7 +34,6 @@ export function createVariableActions(ctx: EditorContext) {return ctx.graph.variables.size}-function renameCollection(id: string, newName: string) {const collection = ctx.graph.variableCollections.get(id)if (!collection) returndiff --git a/packages/core/src/fig-export.ts b/packages/core/src/fig-export.tsindex 7dfce520b..599a13088 100644--- a/packages/core/src/fig-export.ts+++ b/packages/core/src/fig-export.ts@@ -130,10 +130,15 @@ export async function exportFigFile(if (!internalCanvasGuid) {const internalLocalID = localIdCounter.value++internalCanvasGuid = { sessionID: 0, localID: internalLocalID }- nodeChanges.push(makeCanvasNodeChange(- internalCanvasGuid, docGuid, fractionalPosition(pages.length), 'Internal Only Canvas',- { internalOnly: true }- ))+ nodeChanges.push(+ makeCanvasNodeChange(+ internalCanvasGuid,+ docGuid,+ fractionalPosition(pages.length),+ 'Internal Only Canvas',+ { internalOnly: true }+ )+ )}const modeIdToGuid = new Map<string, GUID>()diff --git a/packages/core/src/figma-api-proxy.ts b/packages/core/src/figma-api-proxy.tsindex f17128152..b2c5dbd27 100644--- a/packages/core/src/figma-api-proxy.ts+++ b/packages/core/src/figma-api-proxy.ts@@ -1,3 +1,7 @@+import { normalizeColor } from './color'+import { copyFills, copyStrokes, copyEffects } from './copy'+import { FONT_WEIGHT_NAMES } from './fonts'+/* eslint-disable max-lines -- Figma Plugin API proxy; FigmaAPI already in separate file */import type {SceneGraph,@@ -6,12 +10,9 @@ import type {Fill,Stroke,Effect,- LayoutMode,+ LayoutMode} from './scene-graph'-import { normalizeColor } from './color'-import { FONT_WEIGHT_NAMES } from './fonts'import type { Rect } from './types'-import { copyFills, copyStrokes, copyEffects } from './copy'const MIXED = Symbol('mixed')@@ -728,9 +729,10 @@ export class FigmaNodeProxy {const layout = n.layoutMode !== 'NONE' ? n.layoutMode : this._parentLayout()const parentLayout = this._parentLayout()const isMainAxis = parentLayout === 'HORIZONTAL'- const updates: Partial<SceneNode> = layout === 'VERTICAL'- ? { counterAxisSizing: v as SceneNode['counterAxisSizing'] }- : { primaryAxisSizing: v as SceneNode['primaryAxisSizing'] }+ const updates: Partial<SceneNode> =+ layout === 'VERTICAL'+ ? { counterAxisSizing: v as SceneNode['counterAxisSizing'] }+ : { primaryAxisSizing: v as SceneNode['primaryAxisSizing'] }if (isMainAxis) updates.layoutGrow = v === 'FILL' ? 1 : 0this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], updates)}@@ -747,9 +749,10 @@ export class FigmaNodeProxy {const layout = n.layoutMode !== 'NONE' ? n.layoutMode : this._parentLayout()const parentLayout = this._parentLayout()const isMainAxis = parentLayout === 'VERTICAL'- const updates: Partial<SceneNode> = layout === 'HORIZONTAL'- ? { counterAxisSizing: v as SceneNode['counterAxisSizing'] }- : { primaryAxisSizing: v as SceneNode['primaryAxisSizing'] }+ const updates: Partial<SceneNode> =+ layout === 'HORIZONTAL'+ ? { counterAxisSizing: v as SceneNode['counterAxisSizing'] }+ : { primaryAxisSizing: v as SceneNode['primaryAxisSizing'] }if (isMainAxis) updates.layoutGrow = v === 'FILL' ? 1 : 0this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], updates)}@@ -959,7 +962,9 @@ export class FigmaNodeProxy {if (maxDepth !== undefined && currentDepth >= maxDepth) {obj.childCount = children.length} else {- obj.children = children.map((c) => this[INTERNAL_API].wrapNode(c.id).toJSON(maxDepth, currentDepth + 1))+ obj.children = children.map((c) =>+ this[INTERNAL_API].wrapNode(c.id).toJSON(maxDepth, currentDepth + 1)+ )}}return objdiff --git a/packages/core/src/figma-api.ts b/packages/core/src/figma-api.tsindex 8dc31fe22..460284c1c 100644--- a/packages/core/src/figma-api.ts+++ b/packages/core/src/figma-api.ts@@ -1,3 +1,14 @@+import { IS_BROWSER } from './constants'+import { copyFills, copyStrokes, copyEffects } from './copy'+import {+ FigmaNodeProxy,+ INTERNAL_ID,+ MIXED,+ type FigmaFontName,+ type NodeProxyHost+} from './figma-api-proxy'+import { computeBounds } from './geometry'+import type {SceneGraph,NodeType,@@ -7,17 +18,6 @@ import type {VariableValue} from './scene-graph'import type { Rect, Vector } from './types'-import { IS_BROWSER } from './constants'-import { computeBounds } from './geometry'-import { copyFills, copyStrokes, copyEffects } from './copy'--import {- FigmaNodeProxy,- INTERNAL_ID,- MIXED,- type FigmaFontName,- type NodeProxyHost,-} from './figma-api-proxy'export { FigmaNodeProxy } from './figma-api-proxy'export type { FigmaFontName } from './figma-api-proxy'@@ -31,14 +31,29 @@ export function computeImageHash(data: Uint8Array): string {for (let i = 0; i < data.length; i++) {const b = data[i]switch (i % 5) {- case 0: h1 ^= b; h1 = Math.imul(h1, 0x01000193) >>> 0; break- case 1: h2 ^= b; h2 = Math.imul(h2, 0x01000193) >>> 0; break- case 2: h3 ^= b; h3 = Math.imul(h3, 0x01000193) >>> 0; break- case 3: h4 ^= b; h4 = Math.imul(h4, 0x01000193) >>> 0; break- case 4: h5 ^= b; h5 = Math.imul(h5, 0x01000193) >>> 0; break+ case 0:+ h1 ^= b+ h1 = Math.imul(h1, 0x01000193) >>> 0+ break+ case 1:+ h2 ^= b+ h2 = Math.imul(h2, 0x01000193) >>> 0+ break+ case 2:+ h3 ^= b+ h3 = Math.imul(h3, 0x01000193) >>> 0+ break+ case 3:+ h4 ^= b+ h4 = Math.imul(h4, 0x01000193) >>> 0+ break+ case 4:+ h5 ^= b+ h5 = Math.imul(h5, 0x01000193) >>> 0+ break}}- return [h1, h2, h3, h4, h5].map(h => h.toString(16).padStart(8, '0')).join('')+ return [h1, h2, h3, h4, h5].map((h) => h.toString(16).padStart(8, '0')).join('')}export class FigmaAPI implements NodeProxyHost {@@ -318,7 +333,11 @@ export class FigmaAPI implements NodeProxyHost {private _viewport = { x: 0, y: 0, zoom: 1 }- get viewport(): { center: Vector; zoom: number; scrollAndZoomIntoView: (nodes: readonly { absoluteBoundingBox: Rect }[]) => void } {+ get viewport(): {+ center: Vector+ zoom: number+ scrollAndZoomIntoView: (nodes: readonly { absoluteBoundingBox: Rect }[]) => void+ } {return {center: { x: this._viewport.x, y: this._viewport.y },zoom: this._viewport.zoom,diff --git a/packages/core/src/fonts.ts b/packages/core/src/fonts.tsindex 392fd5de9..7120426d7 100644--- a/packages/core/src/fonts.ts+++ b/packages/core/src/fonts.ts@@ -1,5 +1,3 @@-import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'-import {DEFAULT_FONT_FAMILY,IS_BROWSER,@@ -9,7 +7,9 @@ import {CJK_GOOGLE_FONT,GOOGLE_FONTS_API_KEY} from './constants'+import type { SceneGraph } from './scene-graph'+import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'export interface FontInfo {family: string@@ -124,10 +124,7 @@ async function fetchGoogleFont(family: string, style: string): Promise<ArrayBuffreturn response.arrayBuffer()}-async function findLocalFont(- family: string,- style?: string-): Promise<ArrayBuffer | null> {+async function findLocalFont(family: string, style?: string): Promise<ArrayBuffer | null> {if (!IS_BROWSER || !window.queryLocalFonts) return nulltry {const fonts = await window.queryLocalFonts()@@ -242,9 +239,12 @@ function registerFontInBrowser(family: string, style: string, data: ArrayBuffer)weight: String(weight),style: italic})- face.load().then(() => document.fonts.add(face)).catch(() => {- console.warn(`Failed to load font "${family}" (${style})`)- })+ face+ .load()+ .then(() => document.fonts.add(face))+ .catch(() => {+ console.warn(`Failed to load font "${family}" (${style})`)+ })}export function styleToWeight(style: string): number {diff --git a/packages/core/src/geometry.ts b/packages/core/src/geometry.tsindex e3c373682..4fe9bd5b3 100644--- a/packages/core/src/geometry.ts+++ b/packages/core/src/geometry.ts@@ -8,13 +8,7 @@ export function radToDeg(radians: number): number {return (radians * 180) / Math.PI}-export function rotatePoint(- px: number,- py: number,- cx: number,- cy: number,- rad: number-): Vector {+export function rotatePoint(px: number, py: number, cx: number, cy: number, rad: number): Vector {const cos = Math.cos(rad)const sin = Math.sin(rad)return {@@ -73,7 +67,10 @@ export function rotatedBBox(}export function computeBounds(items: Iterable<Rect>): Rect {- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity+ let minX = Infinity,+ minY = Infinity,+ maxX = -Infinity,+ maxY = -Infinityfor (const item of items) {minX = Math.min(minX, item.x)minY = Math.min(minY, item.y)@@ -88,7 +85,10 @@ export function computeAbsoluteBounds(nodes: Iterable<{ id: string; width: number; height: number }>,getAbsolutePosition: (id: string) => Vector): Rect {- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity+ let minX = Infinity,+ minY = Infinity,+ maxX = -Infinity,+ maxY = -Infinityfor (const n of nodes) {const abs = getAbsolutePosition(n.id)minX = Math.min(minX, abs.x)diff --git a/packages/core/src/headless-render.ts b/packages/core/src/headless-render.tsindex 07ef1deee..395351de4 100644--- a/packages/core/src/headless-render.ts+++ b/packages/core/src/headless-render.ts@@ -1,8 +1,8 @@-import type { CanvasKit } from 'canvaskit-wasm'-import { renderNodesToImage, renderThumbnail, type ExportFormat } from './render-image'import { SkiaRenderer } from './renderer'+import type { SceneGraph } from './scene-graph'+import type { CanvasKit } from 'canvaskit-wasm'let cachedCk: CanvasKit | null = nulllet cachedRenderer: SkiaRenderer | null = nulldiff --git a/packages/core/src/icon-render.ts b/packages/core/src/icon-render.tsindex 4d89545c5..228f58d71 100644--- a/packages/core/src/icon-render.ts+++ b/packages/core/src/icon-render.ts@@ -1,15 +1,19 @@import { parseColor } from './color'-import type { Color } from './types'-import type { SceneGraph, SceneNode, Stroke } from './scene-graph'import type { IconData } from './iconify'+import type { SceneGraph, SceneNode, Stroke } from './scene-graph'+import type { Color } from './types'const STROKE_CAP_MAP: Record<string, SceneNode['strokeCap']> = {- butt: 'NONE', round: 'ROUND', square: 'SQUARE'+ butt: 'NONE',+ round: 'ROUND',+ square: 'SQUARE'}const STROKE_JOIN_MAP: Record<string, SceneNode['strokeJoin']> = {- miter: 'MITER', round: 'ROUND', bevel: 'BEVEL'+ miter: 'MITER',+ round: 'ROUND',+ bevel: 'BEVEL'}export function createIconFromPaths(diff --git a/packages/core/src/iconify.ts b/packages/core/src/iconify.tsindex 833afc9df..3cdd5ad4a 100644--- a/packages/core/src/iconify.ts+++ b/packages/core/src/iconify.ts@@ -1,5 +1,5 @@-import svgpath from 'svgpath'import { iconToSVG } from '@iconify/utils'+import svgpath from 'svgpath'import { parseSVGPath } from './svg-path-parse'@@ -58,7 +58,9 @@ export function clearIconCache(): void {function parseIconName(name: string): { prefix: string; iconName: string } {const colonIdx = name.indexOf(':')if (colonIdx === -1) {- throw new Error(`Invalid icon name "${name}". Use prefix:name format (e.g. lucide:heart, mdi:home)`)+ throw new Error(+ `Invalid icon name "${name}". Use prefix:name format (e.g. lucide:heart, mdi:home)`+ )}return { prefix: name.slice(0, colonIdx), iconName: name.slice(colonIdx + 1) }}@@ -77,32 +79,52 @@ function num(tag: string, attr: string, fallback = 0): number {function shapeToD(tagName: string, tag: string): string | null {switch (tagName) {case 'circle': {- const cx = num(tag, 'cx'), cy = num(tag, 'cy'), r = num(tag, 'r')- return r > 0 ? `M${cx - r},${cy}A${r},${r},0,1,0,${cx + r},${cy}A${r},${r},0,1,0,${cx - r},${cy}Z` : null+ const cx = num(tag, 'cx'),+ cy = num(tag, 'cy'),+ r = num(tag, 'r')+ return r > 0+ ? `M${cx - r},${cy}A${r},${r},0,1,0,${cx + r},${cy}A${r},${r},0,1,0,${cx - r},${cy}Z`+ : null}case 'ellipse': {- const cx = num(tag, 'cx'), cy = num(tag, 'cy'), rx = num(tag, 'rx'), ry = num(tag, 'ry')- return rx > 0 && ry > 0 ? `M${cx - rx},${cy}A${rx},${ry},0,1,0,${cx + rx},${cy}A${rx},${ry},0,1,0,${cx - rx},${cy}Z` : null+ const cx = num(tag, 'cx'),+ cy = num(tag, 'cy'),+ rx = num(tag, 'rx'),+ ry = num(tag, 'ry')+ return rx > 0 && ry > 0+ ? `M${cx - rx},${cy}A${rx},${ry},0,1,0,${cx + rx},${cy}A${rx},${ry},0,1,0,${cx - rx},${cy}Z`+ : null}case 'rect': {- const x = num(tag, 'x'), y = num(tag, 'y'), w = num(tag, 'width'), h = num(tag, 'height')+ const x = num(tag, 'x'),+ y = num(tag, 'y'),+ w = num(tag, 'width'),+ h = num(tag, 'height')if (w <= 0 || h <= 0) return null- const rx = Math.min(num(tag, 'rx'), w / 2), ry = Math.min(num(tag, 'ry', rx), h / 2)+ const rx = Math.min(num(tag, 'rx'), w / 2),+ ry = Math.min(num(tag, 'ry', rx), h / 2)if (rx > 0 || ry > 0) {- const arx = rx || ry, ary = ry || rx+ const arx = rx || ry,+ ary = ry || rxreturn `M${x + arx},${y}H${x + w - arx}A${arx},${ary},0,0,1,${x + w},${y + ary}V${y + h - ary}A${arx},${ary},0,0,1,${x + w - arx},${y + h}H${x + arx}A${arx},${ary},0,0,1,${x},${y + h - ary}V${y + ary}A${arx},${ary},0,0,1,${x + arx},${y}Z`}return `M${x},${y}H${x + w}V${y + h}H${x}Z`}case 'line': {- const x1 = num(tag, 'x1'), y1 = num(tag, 'y1'), x2 = num(tag, 'x2'), y2 = num(tag, 'y2')+ const x1 = num(tag, 'x1'),+ y1 = num(tag, 'y1'),+ x2 = num(tag, 'x2'),+ y2 = num(tag, 'y2')return `M${x1},${y1}L${x2},${y2}`}case 'polygon':case 'polyline': {const points = attrValue(tag, 'points')if (!points) return null- const nums = points.trim().split(/[\s,]+/).map(Number)+ const nums = points+ .trim()+ .split(/[\s,]+/)+ .map(Number)if (nums.length < 4) return nulllet d = `M${nums[0]},${nums[1]}`for (let i = 2; i < nums.length; i += 2) d += `L${nums[i]},${nums[i + 1]}`@@ -114,14 +136,24 @@ function shapeToD(tagName: string, tag: string): string | null {}}-function resolveAttr(explicit: string | null, group: string | null, fallback: string | null): string | null {+function resolveAttr(+ explicit: string | null,+ group: string | null,+ fallback: string | null+): string | null {if (explicit !== null) return explicit === 'none' ? null : explicitif (group !== null) return group === 'none' ? null : groupreturn fallback}function extractPaths(svgBody: string): PathInfo[] {- const groupAttrs = { fill: null as string | null, stroke: null as string | null, strokeWidth: null as string | null, strokeCap: null as string | null, strokeJoin: null as string | null }+ const groupAttrs = {+ fill: null as string | null,+ stroke: null as string | null,+ strokeWidth: null as string | null,+ strokeCap: null as string | null,+ strokeJoin: null as string | null+ }const groupRe = /<g\b[^>]*>/glet gmwhile ((gm = groupRe.exec(svgBody)) !== null) {@@ -136,7 +168,8 @@ function extractPaths(svgBody: string): PathInfo[] {const shapeRe = /<(path|circle|ellipse|rect|line|polygon|polyline)\b[^>]*>/glet matchwhile ((match = shapeRe.exec(svgBody)) !== null) {- const tag = match[0], tagName = match[1]+ const tag = match[0],+ tagName = match[1]const d = tagName === 'path' ? attrValue(tag, 'd') : shapeToD(tagName, tag)if (!d) continue@@ -179,7 +212,7 @@ function buildIconData(width: size,height: size,paths: pathInfos.map((p) => {- const scaledD = (sx === 1 && sy === 1) ? p.d : svgpath(p.d).scale(sx, sy).round(2).toString()+ const scaledD = sx === 1 && sy === 1 ? p.d : svgpath(p.d).scale(sx, sy).round(2).toString()return {vectorNetwork: parseSVGPath(scaledD, p.fillRule),fill: p.fill,@@ -199,7 +232,8 @@ function fetchWithTimeout(url: string): Promise<Response> {export async function fetchIcon(name: string, size = 24): Promise<IconData> {const results = await fetchIcons([name], size)const result = results.get(name)- if (!result) throw new Error(`Icon "${name}" not found. Check the name at https://icon-sets.iconify.design/`)+ if (!result)+ throw new Error(`Icon "${name}" not found. Check the name at https://icon-sets.iconify.design/`)return result}@@ -223,7 +257,8 @@ export async function fetchIcons(names: string[], size = 24): Promise<Map<stringconst fetches = [...toFetch.entries()].map(async ([prefix, iconNames]) => {const url = `${ICONIFY_API}/${prefix}.json?icons=${iconNames.map(encodeURIComponent).join(',')}`const response = await fetchWithTimeout(url)- if (!response.ok) throw new Error(`Iconify API error: ${response.status} for prefix "${prefix}"`)+ if (!response.ok)+ throw new Error(`Iconify API error: ${response.status} for prefix "${prefix}"`)const data = (await response.json()) as IconifyResponseconst defaultW = data.width ?? 24const defaultH = data.height ?? 24@@ -252,10 +287,13 @@ export interface IconSearchResult {collections: Record<string, { name: string; total: number; category?: string }>}-export async function searchIcons(query: string, options?: {- limit?: number- prefix?: string-}): Promise<IconSearchResult> {+export async function searchIcons(+ query: string,+ options?: {+ limit?: number+ prefix?: string+ }+): Promise<IconSearchResult> {const params = new URLSearchParams({ query })if (options?.limit) params.set('limit', String(options.limit))if (options?.prefix) params.set('prefix', options.prefix)@@ -272,14 +310,19 @@ export async function searchIcons(query: string, options?: {}}-export async function searchIconsBatch(queries: string[], options?: {- limit?: number- prefix?: string-}): Promise<Map<string, IconSearchResult>> {+export async function searchIconsBatch(+ queries: string[],+ options?: {+ limit?: number+ prefix?: string+ }+): Promise<Map<string, IconSearchResult>> {const results = new Map<string, IconSearchResult>()- await Promise.all(queries.map(async (query) => {- const result = await searchIcons(query, options)- results.set(query, result)- }))+ await Promise.all(+ queries.map(async (query) => {+ const result = await searchIcons(query, options)+ results.set(query, result)+ })+ )return results}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex a803d2de6..37abf5dd9 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -1,15 +1,18 @@export type { GUID, Color, Vector, Matrix, Rect } from './types'-export { computeBounds, computeAbsoluteBounds, degToRad, radToDeg, rotatePoint, rotatedCorners, rotatedBBox } from './geometry'+export {+ computeBounds,+ computeAbsoluteBounds,+ degToRad,+ radToDeg,+ rotatePoint,+ rotatedCorners,+ rotatedBBox+} from './geometry'export { randomHex, randomInt, randomIndex } from './random'export * from './constants'-export {- createDefaultEditorState,- createEditor,- EDITOR_TOOLS,- TOOL_SHORTCUTS-} from './editor'+export { createDefaultEditorState, createEditor, EDITOR_TOOLS, TOOL_SHORTCUTS } from './editor'export type {Editor,EditorContext,@@ -68,19 +71,52 @@ export {} from './scene-graph'export { FigmaAPI, FigmaNodeProxy, computeImageHash, type FigmaFontName } from './figma-api'-export { ALL_TOOLS, CORE_TOOLS, EXTENDED_TOOLS, defineTool, toolsToAI, buildDebugLog, requireNode, NodeNotFoundError, calcClusterConfidence } from './tools'-export type { ToolDef, ParamDef, ParamType, ToolLogEntry, ToolDebugLog, AIAdapterOptions, StepBudget } from './tools'+export {+ ALL_TOOLS,+ CORE_TOOLS,+ EXTENDED_TOOLS,+ defineTool,+ toolsToAI,+ buildDebugLog,+ requireNode,+ NodeNotFoundError,+ calcClusterConfidence+} from './tools'+export type {+ ToolDef,+ ParamDef,+ ParamType,+ ToolLogEntry,+ ToolDebugLog,+ AIAdapterOptions,+ StepBudget+} from './tools'export { executeRpcCommand, ALL_RPC_COMMANDS } from './rpc'export { queryByXPath, matchByXPath } from './xpath'export type { XPathQueryOptions } from './xpath'export type {- InfoResult, PageItem, TreeArgs, TreeResult, TreeNodeResult,- FindArgs, FindNodeResult, QueryArgs, QueryNodeResult, NodeArgs, NodeResult,- VariablesArgs, VariablesResult,- AnalyzeColorsArgs, AnalyzeColorsResult,- AnalyzeTypographyArgs, AnalyzeTypographyResult,- AnalyzeSpacingResult, SpacingValue,- AnalyzeClustersArgs, AnalyzeClustersResult, TypographyStyle+ InfoResult,+ PageItem,+ TreeArgs,+ TreeResult,+ TreeNodeResult,+ FindArgs,+ FindNodeResult,+ QueryArgs,+ QueryNodeResult,+ NodeArgs,+ NodeResult,+ VariablesArgs,+ VariablesResult,+ AnalyzeColorsArgs,+ AnalyzeColorsResult,+ AnalyzeTypographyArgs,+ AnalyzeTypographyResult,+ AnalyzeSpacingResult,+ SpacingValue,+ AnalyzeClustersArgs,+ AnalyzeClustersResult,+ TypographyStyle} from './rpc'export { SkiaRenderer, type RenderOverlays } from './renderer/index'export { LabelCache, type CachedSection, type CachedComponent } from './renderer/label-cache'@@ -152,7 +188,12 @@ export {adjustRunsForInsert,adjustRunsForDelete} from './style-runs'-export { renderNodesToImage, renderThumbnail, computeContentBounds, type ExportFormat } from './render-image'+export {+ renderNodesToImage,+ renderThumbnail,+ computeContentBounds,+ type ExportFormat+} from './render-image'export { initCanvasKit, headlessRenderNodes, headlessRenderThumbnail } from './headless-render'export {renderNodesToSVG,@@ -162,7 +203,16 @@ export {} from './svg-export'export { svg, renderSVGNode, type SVGNode } from './svg-node'export { parseSVGPath } from './svg-path-parse'-export { fetchIcon, fetchIcons, searchIcons, searchIconsBatch, clearIconCache, type IconData, type IconPath, type IconSearchResult } from './iconify'+export {+ fetchIcon,+ fetchIcons,+ searchIcons,+ searchIconsBatch,+ clearIconCache,+ type IconData,+ type IconPath,+ type IconSearchResult+} from './iconify'export { exportFigFile, compressFigData, compressFigDataSync } from './fig-export'export {FIG_KIWI_VERSION,diff --git a/packages/core/src/kiwi/codec.ts b/packages/core/src/kiwi/codec.tsindex 11af85855..e9eea9e91 100644--- a/packages/core/src/kiwi/codec.ts+++ b/packages/core/src/kiwi/codec.ts@@ -574,11 +574,7 @@ export function encodeNodeChangeWithVariables(nodeChange: NodeChange): Uint8Arra/*** Inject variable binding into a paint at the specified marker*/-function injectVariableBinding(- hex: string,- marker: string,- binding: { variableID: GUID }-): string {+function injectVariableBinding(hex: string, marker: string, binding: { variableID: GUID }): string {const markerIdx = hex.indexOf(marker)if (markerIdx === -1) return hexdiff --git a/packages/core/src/kiwi/fig-parse-core.ts b/packages/core/src/kiwi/fig-parse-core.tsindex 09b1b6ff9..568428a2c 100644--- a/packages/core/src/kiwi/fig-parse-core.ts+++ b/packages/core/src/kiwi/fig-parse-core.ts@@ -53,7 +53,7 @@ export function parseFigBuffer(buffer: ArrayBuffer): FigParseResult {filter: (file) =>file.name === 'canvas.fig' ||file.name === 'canvas' ||- (file.name.startsWith('images/') && file.name !== 'images/'),+ (file.name.startsWith('images/') && file.name !== 'images/')})const entries = Object.keys(zip)diff --git a/packages/core/src/kiwi/instance-overrides/constraints.ts b/packages/core/src/kiwi/instance-overrides/constraints.tsindex 1154aea59..527e28bf0 100644--- a/packages/core/src/kiwi/instance-overrides/constraints.ts+++ b/packages/core/src/kiwi/instance-overrides/constraints.ts@@ -1,6 +1,7 @@+import { buildClonesMap } from './sync'+import type { SceneGraph, SceneNode } from '../../scene-graph'import type { OverrideContext } from './types'-import { buildClonesMap } from './sync'/*** Apply SCALE constraint resizing to children of instances whose sizediff --git a/packages/core/src/kiwi/instance-overrides/index.ts b/packages/core/src/kiwi/instance-overrides/index.tsindex b58ab15f2..aef2c9f03 100644--- a/packages/core/src/kiwi/instance-overrides/index.ts+++ b/packages/core/src/kiwi/instance-overrides/index.ts@@ -7,19 +7,20 @@ export type {ComponentPropValue,DerivedSymbolOverride,SymbolData,- SymbolOverride,+ SymbolOverride} from './types'-import type { SceneGraph } from '../../scene-graph'-import type { InstanceNodeChange, OverrideContext, ComponentPropValue } from './types'import { guidToString } from '../kiwi-convert'+import { applyConstraintScaling } from './constraints'+import { applyDerivedSymbolData } from './dsd'import { populateInstances } from './populate'+import { applyComponentProperties } from './props'import { preComputeRoots } from './resolve'import { applySymbolOverrides } from './symbol-overrides'import { propagateOverridesTransitively } from './sync'-import { applyComponentProperties } from './props'-import { applyDerivedSymbolData } from './dsd'-import { applyConstraintScaling } from './constraints'++import type { SceneGraph } from '../../scene-graph'+import type { InstanceNodeChange, OverrideContext, ComponentPropValue } from './types'/*** Identify nodes whose kiwi NC has explicit property values that DIFFER@@ -39,7 +40,8 @@ function buildKiwiPropertyNodes(const comp = graph.getNode(node.componentId)if (!comp) continueconst hasDiffFills = nc.fillPaints !== undefined && node.fills !== comp.fills- const hasDiffRadius = (nc.cornerRadius !== undefined || nc.rectangleCornerRadiiIndependent !== undefined) &&+ const hasDiffRadius =+ (nc.cornerRadius !== undefined || nc.rectangleCornerRadiiIndependent !== undefined) &&node.cornerRadius !== comp.cornerRadiusconst hasDiffVisible = nc.visible === false && comp.visibleif (hasDiffFills || hasDiffRadius || hasDiffVisible) result.add(nodeId)@@ -86,7 +88,7 @@ function buildOverrideContext(preComputedRoot: new Map(),componentIdRoot: new Map(),swappedInstances: new Set(),- kiwiPropertyNodes,+ kiwiPropertyNodes}}@@ -127,7 +129,13 @@ export function populateAndApplyOverrides(const propModified = applyComponentProperties(ctx)if (propModified.size > 0) {- propagateOverridesTransitively(graph, propModified, ctx.swappedInstances, ctx.componentIdRoot, overriddenNodes)+ propagateOverridesTransitively(+ graph,+ propModified,+ ctx.swappedInstances,+ ctx.componentIdRoot,+ overriddenNodes+ )}applyDerivedSymbolData(ctx)diff --git a/packages/core/src/kiwi/instance-overrides/props.ts b/packages/core/src/kiwi/instance-overrides/props.tsindex c84518238..fd8d4cd71 100644--- a/packages/core/src/kiwi/instance-overrides/props.ts+++ b/packages/core/src/kiwi/instance-overrides/props.ts@@ -1,7 +1,13 @@-import type { OverrideContext, ComponentPropAssignment, ComponentPropRef, ComponentPropValue } from './types'import { guidToString } from '../kiwi-convert'import { resolveOverrideTarget, repopulateInstance } from './resolve'+import type {+ OverrideContext,+ ComponentPropAssignment,+ ComponentPropRef,+ ComponentPropValue+} from './types'+function isEmptyPropValue(v: ComponentPropValue): boolean {return v.boolValue === undefined && v.textValue === undefined && v.guidValue === undefined}@@ -124,7 +130,13 @@ function applyInstanceDirectAssignments(if (!ownFigmaId) continueconst ownAssignments = assignmentSources.get(ownFigmaId)if (ownAssignments) {- applyPropAssignments(ctx, node.id, assignmentsToValueMap(ctx, ownAssignments), propRefsMap, modified)+ applyPropAssignments(+ ctx,+ node.id,+ assignmentsToValueMap(ctx, ownAssignments),+ propRefsMap,+ modified+ )}}}@@ -156,7 +168,13 @@ function applyOverrideAssignments(const targetId = resolveOverrideTarget(ctx, instanceNodeId, guids)if (!targetId) continue- applyPropAssignments(ctx, targetId, assignmentsToValueMap(ctx, ov.componentPropAssignments, true), propRefsMap, modified)+ applyPropAssignments(+ ctx,+ targetId,+ assignmentsToValueMap(ctx, ov.componentPropAssignments, true),+ propRefsMap,+ modified+ )}}}diff --git a/packages/core/src/kiwi/instance-overrides/resolve.ts b/packages/core/src/kiwi/instance-overrides/resolve.tsindex b03189646..7ec83ce63 100644--- a/packages/core/src/kiwi/instance-overrides/resolve.ts+++ b/packages/core/src/kiwi/instance-overrides/resolve.ts@@ -1,7 +1,8 @@+import { guidToString } from '../kiwi-convert'+import type { SceneNode } from '../../scene-graph'import type { GUID } from '../codec'import type { OverrideContext } from './types'-import { guidToString } from '../kiwi-convert'const MAX_CHAIN_DEPTH = 20@@ -79,7 +80,11 @@ export function getComponentRoot(ctx: OverrideContext, nodeId: string, depth = 0* ambiguity when multiple siblings share the same root).* Pass 3: recurse into children.*/-export function findNodeByComponentId(ctx: OverrideContext, parentId: string, componentId: string): string | null {+export function findNodeByComponentId(+ ctx: OverrideContext,+ parentId: string,+ componentId: string+): string | null {const parent = ctx.graph.getNode(parentId)if (!parent) return null@@ -95,9 +100,13 @@ export function findNodeByComponentId(ctx: OverrideContext, parentId: string, cofor (const childId of parent.childIds) {const child = ctx.graph.getNode(childId)if (!child?.componentId) continue- const childRoot = ctx.preComputedRoot.get(child.componentId) ?? getComponentRoot(ctx, child.componentId)+ const childRoot =+ ctx.preComputedRoot.get(child.componentId) ?? getComponentRoot(ctx, child.componentId)if (childRoot === targetRoot) {- if (rootMatch) { ambiguous = true; break }+ if (rootMatch) {+ ambiguous = true+ break+ }rootMatch = childId}}@@ -117,7 +126,11 @@ export function findNodeByComponentId(ctx: OverrideContext, parentId: string, co* Each GUID in the path identifies an overrideKey → figmaGuid → graph node.* The chain walks from the instance down to the target.*/-export function resolveOverrideTarget(ctx: OverrideContext, instanceId: string, guids: GUID[]): string | null {+export function resolveOverrideTarget(+ ctx: OverrideContext,+ instanceId: string,+ guids: GUID[]+): string | null {let currentId = instanceIdfor (const guid of guids) {const key = guidToString(guid)diff --git a/packages/core/src/kiwi/instance-overrides/symbol-overrides.ts b/packages/core/src/kiwi/instance-overrides/symbol-overrides.tsindex 29f03425b..a4c0aeebe 100644--- a/packages/core/src/kiwi/instance-overrides/symbol-overrides.ts+++ b/packages/core/src/kiwi/instance-overrides/symbol-overrides.ts@@ -1,8 +1,9 @@-import type { OverrideContext } from './types'import { guidToString } from '../kiwi-convert'import { convertOverrideToProps } from '../kiwi-convert-overrides'import { resolveOverrideTarget, repopulateInstance } from './resolve'+import type { OverrideContext } from './types'+/*** Apply symbolOverrides from kiwi data.*diff --git a/packages/core/src/kiwi/instance-overrides/types.ts b/packages/core/src/kiwi/instance-overrides/types.tsindex 5ca8f78f1..15907f5e1 100644--- a/packages/core/src/kiwi/instance-overrides/types.ts+++ b/packages/core/src/kiwi/instance-overrides/types.ts@@ -1,6 +1,6 @@import type { SceneGraph } from '../../scene-graph'-import type { GUID } from '../codec'import type { Matrix, Vector } from '../../types'+import type { GUID } from '../codec'export interface SymbolOverride {guidPath?: { guids?: GUID[] }diff --git a/packages/core/src/kiwi/kiwi-serialize.ts b/packages/core/src/kiwi/kiwi-serialize.tsindex dc5fc82c9..f88d9c645 100644--- a/packages/core/src/kiwi/kiwi-serialize.ts+++ b/packages/core/src/kiwi/kiwi-serialize.ts@@ -6,9 +6,9 @@ import { weightToStyle, getLoadedFontData } from '../fonts'import { encodeVectorNetworkBlob } from '../vector'import { stringToGuid, VARIABLE_BINDING_FIELDS } from './kiwi-convert'-import type { NodeChange, Paint, VariableConsumptionEntry } from './codec'import type { SceneGraph, SceneNode, CharacterStyleOverride } from '../scene-graph'import type { Color, GUID } from '../types'+import type { NodeChange, Paint, VariableConsumptionEntry } from './codec'const fontDigestCache = new Map<string, Uint8Array>()@@ -488,7 +488,19 @@ export function sceneNodeToKiwi(const result: KiwiNodeChange[] = [nc]const children = graph.getChildren(node.id)for (let i = 0; i < children.length; i++) {- result.push(...sceneNodeToKiwi(children[i], guid, i, localIdCounter, graph, blobs, nodeIdToGuid, fontDigestMap, varIdToGuid))+ result.push(+ ...sceneNodeToKiwi(+ children[i],+ guid,+ i,+ localIdCounter,+ graph,+ blobs,+ nodeIdToGuid,+ fontDigestMap,+ varIdToGuid+ )+ )}return resultdiff --git a/packages/core/src/profiler/draw-call-counter.ts b/packages/core/src/profiler/draw-call-counter.tsindex 789dfb283..95fc0dadf 100644--- a/packages/core/src/profiler/draw-call-counter.ts+++ b/packages/core/src/profiler/draw-call-counter.ts@@ -21,7 +21,10 @@ export class DrawCallCounter {const original = gl[method].bind(gl) as (...args: unknown[]) => voidthis.originals.set(method, original)// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- monkey-patching overloaded WebGL draw methods- ;(gl[method] as Function) = (...args: unknown[]) => { this.count++; original(...args) }+ ;(gl[method] as Function) = (...args: unknown[]) => {+ this.count+++ original(...args)+ }}}diff --git a/packages/core/src/profiler/frame-capture.ts b/packages/core/src/profiler/frame-capture.tsindex 0f88d7d3d..5f668b064 100644--- a/packages/core/src/profiler/frame-capture.ts+++ b/packages/core/src/profiler/frame-capture.ts@@ -1,4 +1,4 @@-const hasPerformance = typeof performance !== "undefined"+const hasPerformance = typeof performance !== 'undefined'export interface NodeProfile {nodeId: string@@ -41,7 +41,7 @@ export class CaptureStack {selfTime: 0,drawCalls: 0,culled,- children: [],+ children: []}this.stack.push(profile)}@@ -84,7 +84,7 @@ interface SpeedscopeFrame {}interface SpeedscopeEvent {- type: "O" | "C"+ type: 'O' | 'C'at: numberframe: number}@@ -107,11 +107,11 @@ export function toSpeedscopeJSON(capture: FrameCapture): string {function walk(profile: NodeProfile): void {const idx = getFrameIdx(profile.nodeId, profile.name)- events.push({ type: "O", at: profile.startTime, frame: idx })+ events.push({ type: 'O', at: profile.startTime, frame: idx })for (const child of profile.children) {walk(child)}- events.push({ type: "C", at: profile.endTime, frame: idx })+ events.push({ type: 'C', at: profile.endTime, frame: idx })}for (const root of capture.rootProfiles) {@@ -120,20 +120,20 @@ export function toSpeedscopeJSON(capture: FrameCapture): string {return JSON.stringify({- $schema: "https://www.speedscope.app/file-format-schema.json",+ $schema: 'https://www.speedscope.app/file-format-schema.json',shared: { frames },profiles: [{- type: "evented",- name: "Frame Render",- unit: "milliseconds",+ type: 'evented',+ name: 'Frame Render',+ unit: 'milliseconds',startValue: 0,endValue: capture.totalTimeMs,- events,- },- ],+ events+ }+ ]},null,- 2,+ 2)}diff --git a/packages/core/src/profiler/gpu-timer.ts b/packages/core/src/profiler/gpu-timer.tsindex c3eab9e74..9dda154be 100644--- a/packages/core/src/profiler/gpu-timer.ts+++ b/packages/core/src/profiler/gpu-timer.ts@@ -24,8 +24,7 @@ export class GPUTimer {this.gl = glif (gl) {this.ext =- (gl.getExtension('EXT_disjoint_timer_query_webgl2') as EXTDisjointTimerQuery | null) ??- null+ (gl.getExtension('EXT_disjoint_timer_query_webgl2') as EXTDisjointTimerQuery | null) ?? null}}diff --git a/packages/core/src/profiler/hud-renderer.ts b/packages/core/src/profiler/hud-renderer.tsindex 355f3ea03..394ea93fe 100644--- a/packages/core/src/profiler/hud-renderer.ts+++ b/packages/core/src/profiler/hud-renderer.ts@@ -129,14 +129,26 @@ export class HudRenderer {const cacheStatus = stats.scenePictureCacheHit ? 'HIT' : 'MISS'canvas.drawText(`FPS: ${fps} (${avgFrame}ms)`, col1, y, this.textPaint, this.hudFont)- canvas.drawText(`Nodes: ${stats.totalNodes} (${stats.culledNodes} culled)`, col2, y, this.textPaint, this.hudFont)+ canvas.drawText(+ `Nodes: ${stats.totalNodes} (${stats.culledNodes} culled)`,+ col2,+ y,+ this.textPaint,+ this.hudFont+ )y += LINE_HEIGHTcanvas.drawText(`CPU: ${avgCpu}ms`, col1, y, this.textPaint, this.hudFont)canvas.drawText(`Draws: ${stats.drawCalls}`, col2, y, this.textPaint, this.hudFont)y += LINE_HEIGHT- canvas.drawText(`GPU: ${avgGpu}${gpuAvailable ? 'ms' : ''}`, col1, y, this.textPaint, this.hudFont)+ canvas.drawText(+ `GPU: ${avgGpu}${gpuAvailable ? 'ms' : ''}`,+ col1,+ y,+ this.textPaint,+ this.hudFont+ )canvas.drawText(`Cache: ${cacheStatus}`, col2, y, this.textPaint, this.hudFont)if (visiblePhases.length > 0) {@@ -168,10 +180,7 @@ export class HudRenderer {let cx = xfor (const [paint, label] of items) {const swatchY = y - SWATCH_SIZE + 1- canvas.drawRect(- this.ck.LTRBRect(cx, swatchY, cx + SWATCH_SIZE, swatchY + SWATCH_SIZE),- paint- )+ canvas.drawRect(this.ck.LTRBRect(cx, swatchY, cx + SWATCH_SIZE, swatchY + SWATCH_SIZE), paint)cx += SWATCH_SIZE + SWATCH_GAPcanvas.drawText(label, cx, y, this.dimTextPaint, this.hudFont)cx += label.length * 5.5 + LEGEND_ITEM_GAP@@ -208,16 +217,18 @@ export class HudRenderer {paint = this.redPaint}- canvas.drawRect(- this.ck.LTRBRect(barX, barY, barX + BAR_WIDTH, graphY + GRAPH_HEIGHT),- paint- )+ canvas.drawRect(this.ck.LTRBRect(barX, barY, barX + BAR_WIDTH, graphY + GRAPH_HEIGHT), paint)const gpuTime = gpuHistory[histIndex]if (!Number.isNaN(gpuTime) && gpuTime > 0) {const gpuBarHeight = Math.min((gpuTime / MAX_SCALE_MS) * GRAPH_HEIGHT, GRAPH_HEIGHT)canvas.drawRect(- this.ck.LTRBRect(barX, graphY + GRAPH_HEIGHT - gpuBarHeight, barX + BAR_WIDTH, graphY + GRAPH_HEIGHT),+ this.ck.LTRBRect(+ barX,+ graphY + GRAPH_HEIGHT - gpuBarHeight,+ barX + BAR_WIDTH,+ graphY + GRAPH_HEIGHT+ ),this.gpuPaint)}diff --git a/packages/core/src/profiler/phase-timer.ts b/packages/core/src/profiler/phase-timer.tsindex d2cceb700..a4ab07a64 100644--- a/packages/core/src/profiler/phase-timer.ts+++ b/packages/core/src/profiler/phase-timer.ts@@ -37,10 +37,7 @@ export class PhaseTimer {const duration = performance.now() - startTimeconst prev = this.averages.get(name)- this.averages.set(- name,- prev === undefined ? duration : prev + (duration - prev) * SMOOTH- )+ this.averages.set(name, prev === undefined ? duration : prev + (duration - prev) * SMOOTH)performance.measure(name, {start: startTime,diff --git a/packages/core/src/profiler/render-profiler.ts b/packages/core/src/profiler/render-profiler.tsindex ea00b3ad3..d2abc2020 100644--- a/packages/core/src/profiler/render-profiler.ts+++ b/packages/core/src/profiler/render-profiler.ts@@ -1,9 +1,9 @@+import { DrawCallCounter } from './draw-call-counter'+import { CaptureStack, toSpeedscopeJSON } from './frame-capture'import { FrameStats } from './frame-stats'import { GPUTimer } from './gpu-timer'-import { DrawCallCounter } from './draw-call-counter'-import { PhaseTimer } from './phase-timer'import { HudRenderer } from './hud-renderer'-import { CaptureStack, toSpeedscopeJSON } from './frame-capture'+import { PhaseTimer } from './phase-timer'import type { FrameCapture } from './frame-capture'import type { CanvasKit, Canvas, Typeface } from 'canvaskit-wasm'diff --git a/packages/core/src/render/components.ts b/packages/core/src/render/components.tsindex d820cad85..06823e7c4 100644--- a/packages/core/src/render/components.ts+++ b/packages/core/src/render/components.ts@@ -29,11 +29,17 @@ export function Line(props: BaseProps, ...children: Child[]): TreeNode {return withChildren('line', props, children)}-export function Star(props: BaseProps & { points?: number; innerRadius?: number }, ...children: Child[]): TreeNode {+export function Star(+ props: BaseProps & { points?: number; innerRadius?: number },+ ...children: Child[]+): TreeNode {return withChildren('star', props, children)}-export function Polygon(props: BaseProps & { pointCount?: number }, ...children: Child[]): TreeNode {+export function Polygon(+ props: BaseProps & { pointCount?: number },+ ...children: Child[]+): TreeNode {return withChildren('polygon', props, children)}diff --git a/packages/core/src/render/export-jsx.ts b/packages/core/src/render/export-jsx.tsindex 027864683..f81514fa7 100644--- a/packages/core/src/render/export-jsx.ts+++ b/packages/core/src/render/export-jsx.ts@@ -189,8 +189,7 @@ function collectGridSizingProps(node: SceneNode, props: [string, unknown][]): voprops.push(['grid', true])if (node.gridTemplateColumns.length > 0)props.push(['columns', formatTracks(node.gridTemplateColumns)])- if (node.gridTemplateRows.length > 0)- props.push(['rows', formatTracks(node.gridTemplateRows)])+ if (node.gridTemplateRows.length > 0) props.push(['rows', formatTracks(node.gridTemplateRows)])if (node.width > 0) props.push(['w', node.width])if (node.gridTemplateRows.length > 0 && node.height > 0) props.push(['h', node.height])if (node.gridColumnGap > 0) props.push(['columnGap', node.gridColumnGap])@@ -202,13 +201,11 @@ function collectFlexSizingProps(node: SceneNode, props: [string, unknown][]): voconst primaryAxis = node.layoutMode === 'HORIZONTAL' ? 'width' : 'height'const crossAxis = node.layoutMode === 'HORIZONTAL' ? 'height' : 'width'- if (node.primaryAxisSizing === 'FILL')- props.push([primaryAxis === 'width' ? 'w' : 'h', 'fill'])+ if (node.primaryAxisSizing === 'FILL') props.push([primaryAxis === 'width' ? 'w' : 'h', 'fill'])else if (node.primaryAxisSizing !== 'HUG')props.push([primaryAxis === 'width' ? 'w' : 'h', node[primaryAxis]])- if (node.counterAxisSizing === 'FILL')- props.push([crossAxis === 'width' ? 'w' : 'h', 'fill'])+ if (node.counterAxisSizing === 'FILL') props.push([crossAxis === 'width' ? 'w' : 'h', 'fill'])else if (node.counterAxisSizing !== 'HUG')props.push([crossAxis === 'width' ? 'w' : 'h', node[crossAxis]])}@@ -246,7 +243,11 @@ function collectAutoLayoutPaddingProps(node: SceneNode, props: [string, unknown]...emitPadding(pad,(v) => ['p', v] as [string, unknown],- (y, x) => [['py', y], ['px', x]] as [string, unknown][],+ (y, x) =>+ [+ ['py', y],+ ['px', x]+ ] as [string, unknown][],({ pt, pr, pb, pl }) => {const r: [string, unknown][] = []if (pt > 0) r.push(['pt', pt])@@ -339,20 +340,28 @@ function collectSizingProps(}}-function collectTextSizingProps(node: SceneNode, graph: SceneGraph, props: [string, unknown][]): void {+function collectTextSizingProps(+ node: SceneNode,+ graph: SceneGraph,+ props: [string, unknown][]+): void {const autoResize = node.textAutoResizeconst emitH = autoResize === 'NONE' || autoResize === 'TRUNCATE'// Don't emit fixed w when text stretches to fill parent — the layoutAlignSelf// check below will emit w="fill" instead. Without this guard, w={computedPx}// gets emitted first and blocks the fill detection.- const isFillWidth = node.layoutAlignSelf === 'STRETCH' && (() => {- const parent = node.parentId ? graph.getNode(node.parentId) : null- return parent?.layoutMode === 'VERTICAL'- })()- const isGrowWidth = node.layoutGrow > 0 && (() => {- const parent = node.parentId ? graph.getNode(node.parentId) : null- return parent?.layoutMode === 'HORIZONTAL'- })()+ const isFillWidth =+ node.layoutAlignSelf === 'STRETCH' &&+ (() => {+ const parent = node.parentId ? graph.getNode(node.parentId) : null+ return parent?.layoutMode === 'VERTICAL'+ })()+ const isGrowWidth =+ node.layoutGrow > 0 &&+ (() => {+ const parent = node.parentId ? graph.getNode(node.parentId) : null+ return parent?.layoutMode === 'HORIZONTAL'+ })()const emitW = autoResize !== 'WIDTH_AND_HEIGHT' && !isFillWidth && !isGrowWidthif (emitW && node.width > 0) props.push(['w', node.width])if (emitH && node.height > 0) props.push(['h', node.height])@@ -372,7 +381,8 @@ function collectTextNodeProps(node: SceneNode, props: [string, unknown][]): void}if (node.lineHeight != null) props.push(['lineHeight', node.lineHeight])if (node.letterSpacing !== 0) props.push(['letterSpacing', node.letterSpacing])- if (node.textDecoration !== 'NONE') props.push(['textDecoration', node.textDecoration.toLowerCase()])+ if (node.textDecoration !== 'NONE')+ props.push(['textDecoration', node.textDecoration.toLowerCase()])if (node.textCase !== 'ORIGINAL') props.push(['textCase', node.textCase.toLowerCase()])if (node.maxLines != null) props.push(['maxLines', node.maxLines])if (node.textTruncation === 'ENDING' && node.maxLines == null) props.push(['truncate', true])diff --git a/packages/core/src/render/renderer.ts b/packages/core/src/render/renderer.tsindex df157ad79..fb81cadb5 100644--- a/packages/core/src/render/renderer.ts+++ b/packages/core/src/render/renderer.ts@@ -1,7 +1,7 @@import { parseColor, colorToFill } from '../color'import { TRANSPARENT } from '../constants'-import { fetchIcons } from '../iconify'import { createIconFromPaths } from '../icon-render'+import { fetchIcons } from '../iconify'import { computeAllLayouts } from '../layout'import { isTreeNode } from './tree'@@ -180,7 +180,10 @@ function applySizeOverrides(if (isParentGrid) o.layoutAlignSelf = 'STRETCH'else if (isParentRow) o.layoutGrow = 1else if (isParentCol) o.layoutAlignSelf = 'STRETCH'- else { o.layoutGrow = 1; o.layoutAlignSelf = 'STRETCH' }+ else {+ o.layoutGrow = 1+ o.layoutAlignSelf = 'STRETCH'+ }}if (h === 'fill') {if (isParentGrid) o.layoutAlignSelf = 'STRETCH'@@ -297,13 +300,19 @@ function applyGridOverrides(if (typeof props.columns === 'string') {o.gridTemplateColumns = parseTrackList(props.columns)} else if (typeof props.columns === 'number') {- o.gridTemplateColumns = Array.from({ length: props.columns }, () => ({ sizing: 'FR' as const, value: 1 }))+ o.gridTemplateColumns = Array.from({ length: props.columns }, () => ({+ sizing: 'FR' as const,+ value: 1+ }))}if (typeof props.rows === 'string') {o.gridTemplateRows = parseTrackList(props.rows)} else if (typeof props.rows === 'number') {- o.gridTemplateRows = Array.from({ length: props.rows }, () => ({ sizing: 'FR' as const, value: 1 }))+ o.gridTemplateRows = Array.from({ length: props.rows }, () => ({+ sizing: 'FR' as const,+ value: 1+ }))}if (typeof props.columnGap === 'number') o.gridColumnGap = props.columnGap@@ -356,10 +365,7 @@ function applyAutoLayoutSizing(if (counterDim === 'hug') o.counterAxisSizing = 'HUG'}-function shouldEnableAutoLayout(- props: Record<string, unknown>,- isText: boolean-): boolean {+function shouldEnableAutoLayout(props: Record<string, unknown>, isText: boolean): boolean {if (props.flex !== undefined) return trueif (!isText && hasAutoLayoutTriggerProps(props)) return truereturn false@@ -430,8 +436,10 @@ function applyTextStyleOverrides(props: Record<string, unknown>, o: Partial<Scenif (props.lineHeight !== undefined) o.lineHeight = props.lineHeight as numberif (props.letterSpacing !== undefined) o.letterSpacing = props.letterSpacing as number- if (props.textDecoration !== undefined) o.textDecoration = (props.textDecoration as string).toUpperCase() as SceneNode['textDecoration']- if (props.textCase !== undefined) o.textCase = (props.textCase as string).toUpperCase() as SceneNode['textCase']+ if (props.textDecoration !== undefined)+ o.textDecoration = (props.textDecoration as string).toUpperCase() as SceneNode['textDecoration']+ if (props.textCase !== undefined)+ o.textCase = (props.textCase as string).toUpperCase() as SceneNode['textCase']if (props.maxLines !== undefined) {o.maxLines = props.maxLines as numbero.textTruncation = 'ENDING'diff --git a/packages/core/src/render/tree.ts b/packages/core/src/render/tree.tsindex 0bd185261..aaf8e3ef0 100644--- a/packages/core/src/render/tree.ts+++ b/packages/core/src/render/tree.ts@@ -6,7 +6,13 @@ export interface TreeNode {export function isTreeNode(x: unknown): x is TreeNode {if (x === null || typeof x !== 'object') return false- return 'type' in x && typeof x.type === 'string' && 'props' in x && 'children' in x && Array.isArray(x.children)+ return (+ 'type' in x &&+ typeof x.type === 'string' &&+ 'props' in x &&+ 'children' in x &&+ Array.isArray(x.children)+ )}interface ReactElement {@@ -63,7 +69,10 @@ function resolveChild(child: unknown): TreeNode | string | null {return resolveToTree(child)}-export function node(type: string, props: { children?: unknown; [key: string]: unknown }): TreeNode {+export function node(+ type: string,+ props: { children?: unknown; [key: string]: unknown }+): TreeNode {const { children, ...rest } = propsconst processed = [children].flat(Infinity)diff --git a/packages/core/src/renderer/ai-overlays.ts b/packages/core/src/renderer/ai-overlays.tsindex 1e24b8495..70a52d016 100644--- a/packages/core/src/renderer/ai-overlays.ts+++ b/packages/core/src/renderer/ai-overlays.ts@@ -4,12 +4,11 @@ import {AI_PULSE_PERIOD_MS,AI_DONE_DURATION_MS} from '../constants'-import { drawNodeHighlightRect } from './highlight-rect'import type { SceneGraph } from '../scene-graph'-import type { Canvas } from 'canvaskit-wasm'import type { SkiaRenderer } from './renderer'+import type { Canvas } from 'canvaskit-wasm'export function drawAiOverlays(r: SkiaRenderer, canvas: Canvas, graph: SceneGraph): void {const now = performance.now()diff --git a/packages/core/src/renderer/effects.ts b/packages/core/src/renderer/effects.tsindex c3c2014d3..ca400e72a 100644--- a/packages/core/src/renderer/effects.ts+++ b/packages/core/src/renderer/effects.ts@@ -1,6 +1,6 @@import type { SceneNode } from '../scene-graph'-import type { Canvas, ImageFilter, MaskFilter } from 'canvaskit-wasm'import type { SkiaRenderer } from './renderer'+import type { Canvas, ImageFilter, MaskFilter } from 'canvaskit-wasm'export function getCachedDropShadow(r: SkiaRenderer,diff --git a/packages/core/src/renderer/fills.ts b/packages/core/src/renderer/fills.tsindex f7295c2b1..a5e9b3f93 100644--- a/packages/core/src/renderer/fills.ts+++ b/packages/core/src/renderer/fills.ts@@ -1,6 +1,6 @@import type { SceneNode, SceneGraph, Fill } from '../scene-graph'-import type { Canvas, Paint } from 'canvaskit-wasm'import type { SkiaRenderer } from './renderer'+import type { Canvas, Paint } from 'canvaskit-wasm'export function drawNodeFill(r: SkiaRenderer,@@ -105,10 +105,17 @@ export function applyGradientFill(r: SkiaRenderer, fill: Fill, node: SceneNode):// Figma's gradientTransform maps gradient space (center 0.5,0.5, radius 0.5)// to the node's normalized [0,1] coordinate space. The full local matrix// converts to pixel coordinates: scale(w, h) * gradientTransform.- const localMatrix = r.ck.Matrix.multiply(- r.ck.Matrix.scaled(w, h),- [t.m00, t.m01, t.m02, t.m10, t.m11, t.m12, 0, 0, 1]- )+ const localMatrix = r.ck.Matrix.multiply(r.ck.Matrix.scaled(w, h), [+ t.m00,+ t.m01,+ t.m02,+ t.m10,+ t.m11,+ t.m12,+ 0,+ 0,+ 1+ ])const shader = r.ck.Shader.MakeRadialGradient([0.5, 0.5],0.5,@@ -119,10 +126,17 @@ export function applyGradientFill(r: SkiaRenderer, fill: Fill, node: SceneNode):)r.fillPaint.setShader(shader)} else if (fill.type === 'GRADIENT_ANGULAR') {- const localMatrix = r.ck.Matrix.multiply(- r.ck.Matrix.scaled(w, h),- [t.m00, t.m01, t.m02, t.m10, t.m11, t.m12, 0, 0, 1]- )+ const localMatrix = r.ck.Matrix.multiply(r.ck.Matrix.scaled(w, h), [+ t.m00,+ t.m01,+ t.m02,+ t.m10,+ t.m11,+ t.m12,+ 0,+ 0,+ 1+ ])const shader = r.ck.Shader.MakeSweepGradient(0.5,0.5,@@ -157,12 +171,7 @@ export function applyImageFill(const scaleMode = fill.imageScaleMode ?? 'FILL'if (scaleMode === 'TILE') {- const shader = img.makeShaderCubic(- r.ck.TileMode.Repeat,- r.ck.TileMode.Repeat,- 1 / 3,- 1 / 3- )+ const shader = img.makeShaderCubic(r.ck.TileMode.Repeat, r.ck.TileMode.Repeat, 1 / 3, 1 / 3)r.fillPaint.setShader(shader)return true}diff --git a/packages/core/src/renderer/highlight-rect.ts b/packages/core/src/renderer/highlight-rect.tsindex a2168f010..c9d3baab9 100644--- a/packages/core/src/renderer/highlight-rect.ts+++ b/packages/core/src/renderer/highlight-rect.ts@@ -1,7 +1,8 @@import { FLASH_PADDING, FLASH_STROKE_WIDTH, FLASH_RADIUS } from '../constants'+import type { SceneGraph } from '../scene-graph'-import type { Canvas, Paint } from 'canvaskit-wasm'import type { SkiaRenderer } from './renderer'+import type { Canvas, Paint } from 'canvaskit-wasm'export function ensureFlashPaint(r: SkiaRenderer): Paint {if (!r._flashPaint) {diff --git a/packages/core/src/renderer/label-cache.ts b/packages/core/src/renderer/label-cache.tsindex f0ba31382..17548e46a 100644--- a/packages/core/src/renderer/label-cache.ts+++ b/packages/core/src/renderer/label-cache.ts@@ -47,22 +47,35 @@ export class LabelCache {this.components = []}- getSections(graph: SceneGraph, viewport: Viewport): Array<{ node: SceneNode; absX: number; absY: number; nested: boolean }> {+ getSections(+ graph: SceneGraph,+ viewport: Viewport+ ): Array<{ node: SceneNode; absX: number; absY: number; nested: boolean }> {const result: Array<{ node: SceneNode; absX: number; absY: number; nested: boolean }> = []for (const cached of this.sections) {const node = graph.getNode(cached.nodeId)- if (!node || !isInViewport(cached.absX, cached.absY, node.width, node.height, viewport)) continue+ if (!node || !isInViewport(cached.absX, cached.absY, node.width, node.height, viewport))+ continueresult.push({ node, absX: cached.absX, absY: cached.absY, nested: cached.nested })}return result}- getComponents(graph: SceneGraph, viewport: Viewport): Array<{ node: SceneNode; absX: number; absY: number; inside: boolean }> {+ getComponents(+ graph: SceneGraph,+ viewport: Viewport+ ): Array<{ node: SceneNode; absX: number; absY: number; inside: boolean }> {const result: Array<{ node: SceneNode; absX: number; absY: number; inside: boolean }> = []for (const cached of this.components) {const node = graph.getNode(cached.nodeId)- if (!node || !isInViewport(cached.absX, cached.absY, node.width, node.height, viewport)) continue- result.push({ node, absX: cached.absX, absY: cached.absY, inside: cached.parentType === 'COMPONENT_SET' })+ if (!node || !isInViewport(cached.absX, cached.absY, node.width, node.height, viewport))+ continue+ result.push({+ node,+ absX: cached.absX,+ absY: cached.absY,+ inside: cached.parentType === 'COMPONENT_SET'+ })}return result}@@ -77,7 +90,13 @@ export class LabelCache {this.walkChildren(graph, pageNode.id, 0, 0, false)}- private walkChildren(graph: SceneGraph, parentId: string, ox: number, oy: number, insideSection: boolean): void {+ private walkChildren(+ graph: SceneGraph,+ parentId: string,+ ox: number,+ oy: number,+ insideSection: boolean+ ): void {const parent = graph.getNode(parentId)if (!parent) returnconst parentType = parent.typediff --git a/packages/core/src/renderer/labels.ts b/packages/core/src/renderer/labels.tsindex 11b37bec2..d4231d80c 100644--- a/packages/core/src/renderer/labels.ts+++ b/packages/core/src/renderer/labels.ts@@ -8,9 +8,10 @@ import {COMPONENT_LABEL_ICON_SIZE,COMPONENT_LABEL_ICON_GAP} from '../constants'+import type { SceneNode, SceneGraph } from '../scene-graph'-import type { Canvas, Font } from 'canvaskit-wasm'import type { SkiaRenderer } from './renderer'+import type { Canvas, Font } from 'canvaskit-wasm'export function drawSectionTitles(r: SkiaRenderer, canvas: Canvas, graph: SceneGraph): void {if (!r.sectionTitleFont) return@@ -81,10 +82,7 @@ function drawSectionTitle(r.auxFill.setColor(r.ck.Color4f(0.37, 0.37, 0.37, 1))}const pillRect = r.ck.LTRBRect(pillX, pillY, pillX + pillW, pillY + pillH)- canvas.drawRRect(- r.ck.RRectXY(pillRect, SECTION_TITLE_RADIUS, SECTION_TITLE_RADIUS),- r.auxFill- )+ canvas.drawRRect(r.ck.RRectXY(pillRect, SECTION_TITLE_RADIUS, SECTION_TITLE_RADIUS), r.auxFill)const pillColor =node.fills.length > 0 && node.fills[0].visible@@ -157,12 +155,6 @@ export function drawComponentLabels(r: SkiaRenderer, canvas: Canvas, graph: Scenpath.delete()}- canvas.drawText(- node.name,- labelX + iconS + COMPONENT_LABEL_ICON_GAP,- labelY,- r.auxFill,- font- )+ canvas.drawText(node.name, labelX + iconS + COMPONENT_LABEL_ICON_GAP, labelY, r.auxFill, font)}}diff --git a/packages/core/src/renderer/overlays.ts b/packages/core/src/renderer/overlays.tsindex 2f6a3e40c..3dd0eef73 100644--- a/packages/core/src/renderer/overlays.ts+++ b/packages/core/src/renderer/overlays.ts@@ -9,7 +9,6 @@ import {MARQUEE_FILL_ALPHA,SELECTION_DASH_ALPHA,LAYOUT_INDICATOR_STROKE,-TEXT_SELECTION_COLOR,TEXT_CARET_COLOR,TEXT_CARET_WIDTH,@@ -21,12 +20,13 @@ import {} from '../constants'import { rotatedCorners } from '../geometry'import { drawNodeHighlightRect } from './highlight-rect'+import type { SceneNode, SceneGraph } from '../scene-graph'import type { SnapGuide } from '../snap'import type { TextEditor } from '../text-editor'import type { Rect, Vector } from '../types'-import type { Canvas } from 'canvaskit-wasm'import type { SkiaRenderer, RenderOverlays } from './renderer'+import type { Canvas } from 'canvaskit-wasm'export function drawHoverHighlight(r: SkiaRenderer,@@ -43,9 +43,7 @@ export function drawHoverHighlight(const sy = abs.y * r.zoom + r.panYr.auxStroke.setStrokeWidth(1 / r.zoom)- r.auxStroke.setColor(- r.isComponentType(node.type) ? r.compColor() : r.selColor()- )+ r.auxStroke.setColor(r.isComponentType(node.type) ? r.compColor() : r.selColor())r.auxStroke.setPathEffect(null)canvas.save()@@ -85,10 +83,7 @@ export function drawEnteredContainer(const cy = (node.height / 2) * r.zoomcanvas.rotate(node.rotation, cx, cy)}- canvas.drawRect(- r.ck.LTRBRect(0, 0, node.width * r.zoom, node.height * r.zoom),- r.auxStroke- )+ canvas.drawRect(r.ck.LTRBRect(0, 0, node.width * r.zoom, node.height * r.zoom), r.auxStroke)canvas.restore()r.auxStroke.setPathEffect(null)@@ -230,8 +225,7 @@ export function drawSelectionLabels(if (nodes.length === 1) {const node = nodes[0]const parentNode = node.parentId ? graph.getNode(node.parentId) : null- const isTopLevel =- !parentNode || parentNode.type === 'CANVAS' || parentNode.type === 'SECTION'+ const isTopLevel = !parentNode || parentNode.type === 'CANVAS' || parentNode.type === 'SECTION'if (node.type === 'FRAME' && isTopLevel) {r.auxFill.setColor(r.selColor())canvas.drawText(node.name, sx1, sy1 - LABEL_OFFSET_Y, r.auxFill, r.labelFont)@@ -370,11 +364,7 @@ export function drawGroupBounds(r.drawHandle(canvas, maxX, gmy)}-export function getRotatedCorners(- r: SkiaRenderer,- n: SceneNode,- abs: Vector-): Vector[] {+export function getRotatedCorners(r: SkiaRenderer, n: SceneNode, abs: Vector): Vector[] {const cx = (abs.x + n.width / 2) * r.zoom + r.panXconst cy = (abs.y + n.height / 2) * r.zoom + r.panYconst hw = (n.width / 2) * r.zoom@@ -394,11 +384,7 @@ export function drawHandle(r: SkiaRenderer, canvas: Canvas, x: number, y: numbercanvas.drawRect(rect, r.selectionPaint)}-export function drawSnapGuides(- r: SkiaRenderer,- canvas: Canvas,- guides?: SnapGuide[]-): void {+export function drawSnapGuides(r: SkiaRenderer, canvas: Canvas, guides?: SnapGuide[]): void {if (!guides || guides.length === 0) returnfor (const guide of guides) {@@ -513,10 +499,7 @@ export function drawTextEditOverlay())for (const sel of selRects) {- canvas.drawRect(- r.ck.LTRBRect(sel.x, sel.y, sel.x + sel.width, sel.y + sel.height),- r.auxFill- )+ canvas.drawRect(r.ck.LTRBRect(sel.x, sel.y, sel.x + sel.width, sel.y + sel.height), r.auxFill)}}@@ -524,12 +507,7 @@ export function drawTextEditOverlay(const caret = editor.getCaretRect()if (caret) {r.auxFill.setColor(- r.ck.Color4f(- TEXT_CARET_COLOR.r,- TEXT_CARET_COLOR.g,- TEXT_CARET_COLOR.b,- TEXT_CARET_COLOR.a- )+ r.ck.Color4f(TEXT_CARET_COLOR.r, TEXT_CARET_COLOR.g, TEXT_CARET_COLOR.b, TEXT_CARET_COLOR.a))const w = TEXT_CARET_WIDTH / r.zoomcanvas.drawRect(diff --git a/packages/core/src/renderer/pen-overlay.ts b/packages/core/src/renderer/pen-overlay.tsindex 88784afcc..37eb02048 100644--- a/packages/core/src/renderer/pen-overlay.ts+++ b/packages/core/src/renderer/pen-overlay.ts@@ -1,12 +1,9 @@-import {- PEN_HANDLE_RADIUS,- PEN_VERTEX_RADIUS,- PEN_CLOSE_RADIUS_BOOST,-} from '../constants'+import { PEN_HANDLE_RADIUS, PEN_VERTEX_RADIUS, PEN_CLOSE_RADIUS_BOOST } from '../constants'+import type { SceneGraph } from '../scene-graph'import type { Vector } from '../types'-import type { Canvas, Paint } from 'canvaskit-wasm'import type { SkiaRenderer, RenderOverlays } from './renderer'+import type { Canvas, Paint } from 'canvaskit-wasm'type ToScreenFn = (x: number, y: number) => Vectordiff --git a/packages/core/src/renderer/rulers.ts b/packages/core/src/renderer/rulers.tsindex 41d9f3605..27975461a 100644--- a/packages/core/src/renderer/rulers.ts+++ b/packages/core/src/renderer/rulers.ts@@ -12,9 +12,10 @@ import {RULER_MAJOR_TOLERANCE} from '../constants'import { computeAbsoluteBounds } from '../geometry'+import type { SceneNode, SceneGraph } from '../scene-graph'-import type { Canvas, CanvasKit } from 'canvaskit-wasm'import type { SkiaRenderer } from './renderer'+import type { Canvas, CanvasKit } from 'canvaskit-wasm'interface SelectionScreenBounds {sx1: number@@ -147,10 +148,42 @@ export function drawRulers(canvas.drawRect(r.ck.LTRBRect(Math.max(R, selBounds.sx1), 0, selBounds.sx2, R), r.rulerHlPaint)canvas.drawRect(r.ck.LTRBRect(0, Math.max(R, selBounds.sy1), R, selBounds.sy2), r.rulerHlPaint)- drawRulerBadge(r, canvas, font, Math.round((selBounds.sx1 - r.panX) / r.zoom).toString(), Math.max(R, selBounds.sx1), 0, 'horizontal')- drawRulerBadge(r, canvas, font, Math.round((selBounds.sx2 - r.panX) / r.zoom).toString(), selBounds.sx2, 0, 'horizontal')- drawRulerBadge(r, canvas, font, Math.round((selBounds.sy1 - r.panY) / r.zoom).toString(), 0, Math.max(R, selBounds.sy1), 'vertical')- drawRulerBadge(r, canvas, font, Math.round((selBounds.sy2 - r.panY) / r.zoom).toString(), 0, selBounds.sy2, 'vertical')+ drawRulerBadge(+ r,+ canvas,+ font,+ Math.round((selBounds.sx1 - r.panX) / r.zoom).toString(),+ Math.max(R, selBounds.sx1),+ 0,+ 'horizontal'+ )+ drawRulerBadge(+ r,+ canvas,+ font,+ Math.round((selBounds.sx2 - r.panX) / r.zoom).toString(),+ selBounds.sx2,+ 0,+ 'horizontal'+ )+ drawRulerBadge(+ r,+ canvas,+ font,+ Math.round((selBounds.sy1 - r.panY) / r.zoom).toString(),+ 0,+ Math.max(R, selBounds.sy1),+ 'vertical'+ )+ drawRulerBadge(+ r,+ canvas,+ font,+ Math.round((selBounds.sy2 - r.panY) / r.zoom).toString(),+ 0,+ selBounds.sy2,+ 'vertical'+ )}}diff --git a/packages/core/src/renderer/shapes.ts b/packages/core/src/renderer/shapes.tsindex 96b1ecd5b..c05614879 100644--- a/packages/core/src/renderer/shapes.ts+++ b/packages/core/src/renderer/shapes.ts@@ -1,7 +1,8 @@+import { vectorNetworkToPath, geometryBlobToPath } from '../vector'+import type { SceneNode } from '../scene-graph'-import type { Canvas, Path } from 'canvaskit-wasm'import type { SkiaRenderer } from './renderer'-import { vectorNetworkToPath, geometryBlobToPath } from '../vector'+import type { Canvas, Path } from 'canvaskit-wasm'export function makeNodeShapePath(r: SkiaRenderer,@@ -87,7 +88,11 @@ export function makeRRect(r: SkiaRenderer, node: SceneNode): Float32Array {)}-export function makeRRectWithSpread(r: SkiaRenderer, node: SceneNode, spread: number): Float32Array {+export function makeRRectWithSpread(+ r: SkiaRenderer,+ node: SceneNode,+ spread: number+): Float32Array {if (node.independentCorners) {return new Float32Array([-spread,diff --git a/packages/core/src/scene-graph-hit-test.ts b/packages/core/src/scene-graph-hit-test.tsindex cb82b158a..851fe2f4f 100644--- a/packages/core/src/scene-graph-hit-test.ts+++ b/packages/core/src/scene-graph-hit-test.ts@@ -1,7 +1,13 @@import type { SceneGraph, SceneNode, NodeType } from './scene-graph'const CONTAINER_TYPES = new Set<NodeType>([- 'CANVAS', 'FRAME', 'GROUP', 'SECTION', 'COMPONENT', 'COMPONENT_SET', 'INSTANCE'+ 'CANVAS',+ 'FRAME',+ 'GROUP',+ 'SECTION',+ 'COMPONENT',+ 'COMPONENT_SET',+ 'INSTANCE'])const OPAQUE_CONTAINER_TYPES = new Set<NodeType>(['COMPONENT', 'INSTANCE'])@@ -92,12 +98,22 @@ function hitTestChildren(return null}-export function hitTest(graph: SceneGraph, px: number, py: number, scopeId?: string): SceneNode | null {+export function hitTest(+ graph: SceneGraph,+ px: number,+ py: number,+ scopeId?: string+): SceneNode | null {const scope = scopeId ?? graph.rootIdreturn hitTestChildren(graph, px, py, scope, 0, 0, false)}-export function hitTestDeep(graph: SceneGraph, px: number, py: number, scopeId?: string): SceneNode | null {+export function hitTestDeep(+ graph: SceneGraph,+ px: number,+ py: number,+ scopeId?: string+): SceneNode | null {const scope = scopeId ?? graph.rootIdreturn hitTestChildren(graph, px, py, scope, 0, 0, true)}diff --git a/packages/core/src/scene-graph.ts b/packages/core/src/scene-graph.tsindex 12d972015..4c2f4bb79 100644--- a/packages/core/src/scene-graph.ts+++ b/packages/core/src/scene-graph.ts@@ -2,6 +2,11 @@import { createNanoEvents } from 'nanoevents'import { BLACK, DEFAULT_FONT_FAMILY, DEFAULT_STROKE_MITER_LIMIT } from './constants'+import {+ hitTest as hitTestFn,+ hitTestDeep as hitTestDeepFn,+ hitTestFrame as hitTestFrameFn+} from './scene-graph-hit-test'import {createInstance as createInstanceFn,populateInstanceChildren as populateInstanceChildrenFn,@@ -10,11 +15,6 @@ import {getMainComponent as getMainComponentFn,getInstances as getInstancesFn} from './scene-graph-instances'-import {- hitTest as hitTestFn,- hitTestDeep as hitTestDeepFn,- hitTestFrame as hitTestFrameFn-} from './scene-graph-hit-test'export type { GUID, Color } from './types'import type { Matrix, Vector, Color, Rect } from './types'@@ -82,7 +82,6 @@ export type NodeType =| 'CONNECTOR'| 'SHAPE_WITH_TEXT'-export type FillType =| 'SOLID'| 'GRADIENT_LINEAR'@@ -747,17 +746,32 @@ export class SceneGraph {}static TEXT_PICTURE_KEYS: ReadonlySet<string> = new Set([- 'text', 'fontSize', 'fontFamily', 'fontWeight', 'italic',- 'textAlignHorizontal', 'textAlignVertical', 'lineHeight',- 'letterSpacing', 'textDecoration', 'textCase', 'styleRuns', 'fills',- 'width', 'height',+ 'text',+ 'fontSize',+ 'fontFamily',+ 'fontWeight',+ 'italic',+ 'textAlignHorizontal',+ 'textAlignVertical',+ 'lineHeight',+ 'letterSpacing',+ 'textDecoration',+ 'textCase',+ 'styleRuns',+ 'fills',+ 'width',+ 'height'])updateNode(id: string, changes: Partial<SceneNode>): void {const node = this.nodes.get(id)if (!node) returnthis.absPosCache.clear()- if (node.type === 'INSTANCE' && 'componentId' in changes && changes.componentId !== node.componentId) {+ if (+ node.type === 'INSTANCE' &&+ 'componentId' in changes &&+ changes.componentId !== node.componentId+ ) {if (node.componentId) this.instanceIndex.get(node.componentId)?.delete(id)if (changes.componentId) {let set = this.instanceIndex.get(changes.componentId)@@ -768,7 +782,11 @@ export class SceneGraph {set.add(id)}}- if (node.type === 'TEXT' && node.textPicture && Object.keys(changes).some((k) => SceneGraph.TEXT_PICTURE_KEYS.has(k))) {+ if (+ node.type === 'TEXT' &&+ node.textPicture &&+ Object.keys(changes).some((k) => SceneGraph.TEXT_PICTURE_KEYS.has(k))+ ) {node.textPicture = null}Object.assign(node, changes)diff --git a/packages/core/src/snap.ts b/packages/core/src/snap.tsindex 88e5d0f8e..f3e357051 100644--- a/packages/core/src/snap.ts+++ b/packages/core/src/snap.ts@@ -1,4 +1,5 @@import { rotatedBBox } from './geometry'+import type { SceneNode } from './scene-graph'import type { Rect } from './types'diff --git a/packages/core/src/style-runs.ts b/packages/core/src/style-runs.tsindex 303e13f0f..f9b38ded5 100644--- a/packages/core/src/style-runs.ts+++ b/packages/core/src/style-runs.ts@@ -10,7 +10,10 @@ export function getStyleAt(runs: StyleRun[], index: number): CharacterStyleOverr}function expandRuns(runs: StyleRun[], textLength: number): (CharacterStyleOverride | null)[] {- const chars: (CharacterStyleOverride | null)[] = Array.from({ length: textLength }, (): CharacterStyleOverride | null => null)+ const chars: (CharacterStyleOverride | null)[] = Array.from(+ { length: textLength },+ (): CharacterStyleOverride | null => null+ )for (const run of runs) {for (let i = run.start; i < run.start + run.length && i < textLength; i++) {chars[i] = { ...chars[i], ...run.style }@@ -95,7 +98,10 @@ function compactRuns(chars: (CharacterStyleOverride | null)[]): StyleRun[] {}const start = iconst style = chars[i]- if (!style) { i++; continue }+ if (!style) {+ i+++ continue+ }while (i < chars.length && stylesEqual(chars[i], style)) i++result.push({ start, length: i - start, style: { ...style } })}diff --git a/packages/core/src/svg-export/defs.ts b/packages/core/src/svg-export/defs.tsindex 72007965a..44831ebc9 100644--- a/packages/core/src/svg-export/defs.ts+++ b/packages/core/src/svg-export/defs.ts@@ -1,10 +1,9 @@import { colorToHex, colorToHex8 } from '../color'-import { round } from './paths'-import { svg } from '../svg-node'+import { round } from './paths'-import type { SVGNode } from '../svg-node'import type { SceneGraph, SceneNode, Fill, Effect } from '../scene-graph'+import type { SVGNode } from '../svg-node'import type { Color } from '../types'export interface SVGExportContext {@@ -82,11 +81,7 @@ function createGradientDef(const r = Math.max(node.width, node.height)return {id,- node: svg(- 'radialGradient',- { id, cx, cy, r, gradientUnits: 'userSpaceOnUse' },- ...stopNodes- )+ node: svg('radialGradient', { id, cx, cy, r, gradientUnits: 'userSpaceOnUse' }, ...stopNodes)}}@@ -133,7 +128,10 @@ function detectImageMime(data: Uint8Array): string {return 'image/png'}-export function createFilterDef(effects: Effect[], ctx: SVGExportContext): { id: string; node: SVGNode } | null {+export function createFilterDef(+ effects: Effect[],+ ctx: SVGExportContext+): { id: string; node: SVGNode } | null {const visible = effects.filter((e) => e.visible)if (visible.length === 0) return null@@ -193,11 +191,7 @@ export function createFilterDef(effects: Effect[], ctx: SVGExportContext): { id:}}-export function resolveFill(- fill: Fill,- node: SceneNode,- ctx: SVGExportContext-): string | null {+export function resolveFill(fill: Fill, node: SceneNode, ctx: SVGExportContext): string | null {if (!fill.visible) return nullif (fill.type === 'SOLID') {diff --git a/packages/core/src/svg-path-parse.ts b/packages/core/src/svg-path-parse.tsindex f9e755e79..afd1d8bbe 100644--- a/packages/core/src/svg-path-parse.ts+++ b/packages/core/src/svg-path-parse.ts@@ -1,6 +1,12 @@import svgpath from 'svgpath'-import type { VectorNetwork, VectorVertex, VectorSegment, VectorRegion, WindingRule } from './scene-graph'+import type {+ VectorNetwork,+ VectorVertex,+ VectorSegment,+ VectorRegion,+ WindingRule+} from './scene-graph'interface SubPath {startVertexIndex: number@@ -36,10 +42,14 @@ export function parseSVGPath(d: string, windingRule: WindingRule = 'NONZERO'): V}function addSegment(- x1: number, y1: number,- x2: number, y2: number,- tx1: number, ty1: number,- tx2: number, ty2: number+ x1: number,+ y1: number,+ x2: number,+ y2: number,+ tx1: number,+ ty1: number,+ tx2: number,+ ty2: number): void {const startIdx = getOrCreateVertex(x1, y1)const endIdx = getOrCreateVertex(x2, y2)@@ -60,10 +70,14 @@ export function parseSVGPath(d: string, windingRule: WindingRule = 'NONZERO'): V}function addCubic(- x1: number, y1: number,- cp1x: number, cp1y: number,- cp2x: number, cp2y: number,- x2: number, y2: number+ x1: number,+ y1: number,+ cp1x: number,+ cp1y: number,+ cp2x: number,+ cp2y: number,+ x2: number,+ y2: number): void {addSegment(x1, y1, x2, y2, cp1x, cp1y, cp2x, cp2y)}diff --git a/packages/core/src/tools/ai-adapter.ts b/packages/core/src/tools/ai-adapter.tsindex 824e946d2..00495b92c 100644--- a/packages/core/src/tools/ai-adapter.ts+++ b/packages/core/src/tools/ai-adapter.ts@@ -78,8 +78,10 @@ function extractNodeIds(result: unknown): string[] {if ('deleted' in result && typeof result.deleted === 'string') return []const ids: string[] = []if ('id' in result && typeof result.id === 'string') ids.push(result.id)- if ('selection' in result && Array.isArray(result.selection)) ids.push(...extractIdsFromArray(result.selection))- if ('results' in result && Array.isArray(result.results)) ids.push(...extractIdsFromArray(result.results))+ if ('selection' in result && Array.isArray(result.selection))+ ids.push(...extractIdsFromArray(result.selection))+ if ('results' in result && Array.isArray(result.results))+ ids.push(...extractIdsFromArray(result.results))return ids}@@ -140,7 +142,7 @@ export function toolsToAI(// eslint-disable-next-line typescript-eslint/no-explicit-any -- Vercel AI tool() has complex overloads that can't be expressed without anytool: (...args: any[]) => unknown}-// eslint-disable-next-line typescript-eslint/no-explicit-any -- return type must be any to satisfy Vercel AI SDK's ToolSet which uses any internally+ // eslint-disable-next-line typescript-eslint/no-explicit-any -- return type must be any to satisfy Vercel AI SDK's ToolSet which uses any internally): Record<string, any> {const { v, valibotSchema, tool } = deps// eslint-disable-next-line typescript-eslint/no-explicit-any -- matches return type@@ -228,7 +230,13 @@ const SKIP_ARGS: Partial<Record<string, Set<string>>> = {set_effects: new Set(['type', 'color', 'offset_x', 'offset_y', 'radius', 'spread']),set_fill: new Set(['type', 'color']),set_stroke: new Set(['type', 'color']),- set_layout: new Set(['align', 'counter_align', 'padding', 'padding_horizontal', 'padding_vertical']),+ set_layout: new Set([+ 'align',+ 'counter_align',+ 'padding',+ 'padding_horizontal',+ 'padding_vertical'+ ])}function detectUnchangedProps(diff --git a/packages/core/src/tools/analyze.ts b/packages/core/src/tools/analyze.tsindex 88b9d3f07..51e1749d9 100644--- a/packages/core/src/tools/analyze.ts+++ b/packages/core/src/tools/analyze.ts@@ -2,12 +2,11 @@import { createTwoFilesPatch } from 'diff'import { colorDistance, colorToHex, parseColor } from '../color'-import { defineTool } from './schema'-import type { Color } from '../types'-import type { SceneNode } from '../scene-graph'import type { FigmaAPI } from '../figma-api'+import type { SceneNode } from '../scene-graph'+import type { Color } from '../types'interface SizedItem {width: number@@ -37,11 +36,7 @@ interface ColorEntry {variableName: string | null}-function trackColor(- colorMap: Map<string, ColorEntry>,- color: Color,- variableName: string | null-) {+function trackColor(colorMap: Map<string, ColorEntry>, color: Color, variableName: string | null) {const hex = colorToHex(color)const entry = colorMap.get(hex)if (entry) {@@ -155,7 +150,11 @@ function createUnifiedDiff(const patch = createTwoFilesPatch(oldFilename, newFilename, oldContent, newContent, '', '')return patch.split('\n')- .filter((l) => !l.startsWith('Index:') && l !== '===================================================================')+ .filter(+ (l) =>+ !l.startsWith('Index:') &&+ l !== '==================================================================='+ ).join('\n').trim()}@@ -197,7 +196,11 @@ export const analyzeColors = defineTool({}for (const stroke of raw.strokes) {if (stroke.visible) {- trackColor(colorMap, stroke.color, boundVars['strokes'] ? String(boundVars['strokes']) : null)+ trackColor(+ colorMap,+ stroke.color,+ boundVars['strokes'] ? String(boundVars['strokes']) : null+ )}}return false@@ -401,7 +404,14 @@ export const analyzeClusters = defineTool({const signatureMap = new Map<string,- { id: string; name: string; type: string; width: number; height: number; childCount: number }[]+ {+ id: string+ name: string+ type: string+ width: number+ height: number+ childCount: number+ }[]>()let totalNodes = 0diff --git a/packages/core/src/tools/calc.ts b/packages/core/src/tools/calc.tsindex a43db5b8e..469892125 100644--- a/packages/core/src/tools/calc.ts+++ b/packages/core/src/tools/calc.ts@@ -4,7 +4,9 @@ import { defineTool } from './schema'const parser = new ExprEval.Parser()-function evalExpr(expr: string): { expr: string; result: number } | { expr: string; error: string } {+function evalExpr(+ expr: string+): { expr: string; result: number } | { expr: string; error: string } {try {const result = parser.evaluate(expr)if (!Number.isFinite(result)) {diff --git a/packages/core/src/tools/codegen.ts b/packages/core/src/tools/codegen.tsindex e4fe5fea1..6b8d13ff5 100644--- a/packages/core/src/tools/codegen.ts+++ b/packages/core/src/tools/codegen.ts@@ -1,10 +1,15 @@import { colorToHex } from '../color'-import { defineTool } from './schema'-import type { Color } from '../types'import type { FigmaAPI } from '../figma-api'-import type { SceneGraph, Variable, VariableCollection, VariableValue, SceneNode } from '../scene-graph'+import type {+ SceneGraph,+ Variable,+ VariableCollection,+ VariableValue,+ SceneNode+} from '../scene-graph'+import type { Color } from '../types'function slugify(name: string): string {return name@@ -126,10 +131,7 @@ function renderCSS(return lines.join('\n') + '\n'}-function renderTailwindTheme(- tokens: TokenEntry[],- modes: { id: string; name: string }[]-): string {+function renderTailwindTheme(tokens: TokenEntry[], modes: { id: string; name: string }[]): string {const defaultModeId = modes[0]?.id ?? ''const colors: Record<string, string> = {}const spacing: Record<string, string> = {}@@ -152,10 +154,7 @@ export const designTokens = ${JSON.stringify(theme, null, 2)} as const`}-function renderJSON(- tokens: TokenEntry[],- modes: { id: string; name: string }[]-): string {+function renderJSON(tokens: TokenEntry[], modes: { id: string; name: string }[]): string {const result: Record<string, Record<string, string>> = {}for (const mode of modes) {@@ -247,10 +246,7 @@ interface ScreenInfo {topLevelSections: number}-function collectInstanceCounts(- figma: FigmaAPI,- componentIds: Set<string>-): Map<string, number> {+function collectInstanceCounts(figma: FigmaAPI, componentIds: Set<string>): Map<string, number> {const counts = new Map<string, number>()const page = figma.currentPage@@ -288,10 +284,7 @@ function detectPropCandidates(node: SceneNode, graph: SceneGraph): string[] {return props}-function detectVariants(- componentNode: SceneNode,- graph: SceneGraph-): string[] {+function detectVariants(componentNode: SceneNode, graph: SceneGraph): string[] {if (componentNode.type !== 'COMPONENT_SET') return []const variants: string[] = []@@ -421,5 +414,3 @@ export const designToComponentMap = defineTool({}}})--diff --git a/packages/core/src/tools/create.ts b/packages/core/src/tools/create.tsindex a2ccd336e..2c3175795 100644--- a/packages/core/src/tools/create.ts+++ b/packages/core/src/tools/create.ts@@ -1,7 +1,6 @@import { parseColor } from '../color'import { createIconFromPaths } from '../icon-render'import { fetchIcons, searchIconsBatch } from '../iconify'-import { defineTool, nodeSummary } from './schema'import type { FigmaNodeProxy } from '../figma-api'@@ -55,12 +54,18 @@ export const render = defineTool({description:'Render JSX to design nodes. Use replace_id to swap a skeleton placeholder with real content (keeps position in parent). Example: <Frame name="Card" w={320} h="hug" flex="col" gap={16} p={24} bg="#FFF" rounded={16}><Text size={18} weight="bold">Title</Text></Frame>',params: {- replace_id: { type: 'string', description: 'Node ID to replace — new node takes its position in parent, old node is deleted' },+ replace_id: {+ type: 'string',+ description: 'Node ID to replace — new node takes its position in parent, old node is deleted'+ },parent_id: { type: 'string', description: 'Parent node ID to render into' },- insert_index: { type: 'number', description: 'Position among siblings (0 = first child). Omit to append at end.' },+ insert_index: {+ type: 'number',+ description: 'Position among siblings (0 = first child). Omit to append at end.'+ },x: { type: 'number', description: 'X position of the root node' },y: { type: 'number', description: 'Y position of the root node' },- jsx: { type: 'string', description: 'JSX string to render', required: true },+ jsx: { type: 'string', description: 'JSX string to render', required: true }},execute: async (figma, args) => {const { renderJSX } = await import('../render/render-jsx.js')@@ -215,7 +220,6 @@ export const createSlice = defineTool({}})-export const fetchIconsTool = defineTool({name: 'fetch_icons',description:@@ -243,8 +247,6 @@ export const fetchIconsTool = defineTool({}})--export const insertIcon = defineTool({name: 'insert_icon',mutates: true,@@ -253,14 +255,18 @@ export const insertIcon = defineTool({params: {names: {type: 'string[]',- description: 'Icon names as prefix:name (e.g. ["lucide:heart"] or ["lucide:heart","lucide:home","lucide:star"])'+ description:+ 'Icon names as prefix:name (e.g. ["lucide:heart"] or ["lucide:heart","lucide:home","lucide:star"])'},name: {type: 'string',description: 'Single icon name (shorthand for names with one icon)'},size: { type: 'number', description: 'Icon size in pixels (default: 24)' },- color: { type: 'color', description: 'Icon color hex (replaces currentColor). Default: #000000' },+ color: {+ type: 'color',+ description: 'Icon color hex (replaces currentColor). Default: #000000'+ },parent_id: { type: 'string', description: 'Parent node ID for all icons' }},execute: async (figma, args) => {diff --git a/packages/core/src/tools/describe-issues.ts b/packages/core/src/tools/describe-issues.tsindex 57323ea52..dde73e20b 100644--- a/packages/core/src/tools/describe-issues.ts+++ b/packages/core/src/tools/describe-issues.ts@@ -1,12 +1,11 @@import { colorDistance, colorToHex } from '../color'-import { CONTAINER_TYPES, findAncestorBackground, looksLikeButton } from './describe-shared'-import { detectLayoutIssues } from './describe-layout-issues'+import { CONTAINER_TYPES, findAncestorBackground, looksLikeButton } from './describe-shared'import type { SceneGraph, SceneNode } from '../scene-graph'const MIN_FILL_OPACITY = 0.15-const MIN_STROKE_OPACITY = 0.20+const MIN_STROKE_OPACITY = 0.2const LOW_CONTRAST_THRESHOLD = 15const SHAPE_TYPES = new Set(['RECTANGLE', 'ELLIPSE', 'STAR', 'POLYGON', 'LINE'])const ICON_MAX_SIZE = 48@@ -21,12 +20,16 @@ export interface DescribeIssue {function checkEmptyIcon(node: SceneNode, graph: SceneGraph, issues: DescribeIssue[]): void {if (!CONTAINER_TYPES.has(node.type)) return- if (node.width > ICON_MAX_SIZE || node.height > ICON_MAX_SIZE || node.childIds.length === 0) return+ if (node.width > ICON_MAX_SIZE || node.height > ICON_MAX_SIZE || node.childIds.length === 0)+ returnif (node.fills.some((f) => f.visible) || node.strokes.some((s) => s.visible)) returnconst hasVisibleChild = node.childIds.some((id) => {const c = graph.getNode(id)- return c?.visible && (c.fills.some((f) => f.visible) || c.strokes.some((s) => s.visible) || c.type === 'TEXT')+ return (+ c?.visible &&+ (c.fills.some((f) => f.visible) || c.strokes.some((s) => s.visible) || c.type === 'TEXT')+ )})if (!hasVisibleChild) {issues.push({@@ -36,7 +39,12 @@ function checkEmptyIcon(node: SceneNode, graph: SceneGraph, issues: DescribeIssu}}-function detectStructuralIssues(node: SceneNode, gridSize: number, graph: SceneGraph, issues: DescribeIssue[]): void {+function detectStructuralIssues(+ node: SceneNode,+ gridSize: number,+ graph: SceneGraph,+ issues: DescribeIssue[]+): void {if (node.x % 1 !== 0 || node.y % 1 !== 0) {issues.push({message: `Subpixel position (${node.x}, ${node.y})`,@@ -56,11 +64,17 @@ function detectStructuralIssues(node: SceneNode, gridSize: number, graph: SceneG}checkEmptyIcon(node, graph, issues)if (looksLikeButton(node) && node.width < 44) {- issues.push({ message: `Touch target too small (${node.width}×${node.height})`, suggestion: 'Min 44×44' })+ issues.push({+ message: `Touch target too small (${node.width}×${node.height})`,+ suggestion: 'Min 44×44'+ })}if (node.itemSpacing > 0 && node.itemSpacing % gridSize !== 0) {const nearest = Math.round(node.itemSpacing / gridSize) * gridSize- issues.push({ message: `Gap ${node.itemSpacing} not on ${gridSize}px grid`, suggestion: `${nearest}` })+ issues.push({+ message: `Gap ${node.itemSpacing} not on ${gridSize}px grid`,+ suggestion: `${nearest}`+ })}checkStrokeMismatch(node, issues)@@ -74,14 +88,24 @@ function checkStrokeMismatch(node: SceneNode, issues: DescribeIssue[]): void {const hasStrokeColor = node.strokes.some((s) => s.visible)const hasStrokeWeight = node.strokes.some((s) => s.weight > 0)if (hasStrokeColor && !hasStrokeWeight) {- issues.push({ message: `"${node.name}" has stroke color but zero weight`, suggestion: 'Set strokeWidth={1} or remove stroke' })+ issues.push({+ message: `"${node.name}" has stroke color but zero weight`,+ suggestion: 'Set strokeWidth={1} or remove stroke'+ })}if (!hasStrokeColor && hasStrokeWeight && node.strokes.length > 0) {- issues.push({ message: `"${node.name}" has stroke weight but no visible stroke`, suggestion: 'Add stroke="#hex" or remove strokeWidth' })+ issues.push({+ message: `"${node.name}" has stroke weight but no visible stroke`,+ suggestion: 'Add stroke="#hex" or remove strokeWidth'+ })}}-function checkRoundedWithoutClip(node: SceneNode, graph: SceneGraph, issues: DescribeIssue[]): void {+function checkRoundedWithoutClip(+ node: SceneNode,+ graph: SceneGraph,+ issues: DescribeIssue[]+): void {if (!CONTAINER_TYPES.has(node.type)) returnif (node.cornerRadius <= 0 || node.clipsContent) returnconst minDim = Math.min(node.width, node.height)@@ -165,7 +189,11 @@ function checkNestedText(node: SceneNode, graph: SceneGraph, issues: DescribeIss}}-function checkZeroPaddingContainer(node: SceneNode, graph: SceneGraph, issues: DescribeIssue[]): void {+function checkZeroPaddingContainer(+ node: SceneNode,+ graph: SceneGraph,+ issues: DescribeIssue[]+): void {if (!CONTAINER_TYPES.has(node.type)) returnif (node.layoutMode === 'NONE') returnif (node.childIds.length < 3) return@@ -184,7 +212,11 @@ function checkZeroPaddingContainer(node: SceneNode, graph: SceneGraph, issues: D}}-function checkButtonWithoutPadding(node: SceneNode, _graph: SceneGraph, issues: DescribeIssue[]): void {+function checkButtonWithoutPadding(+ node: SceneNode,+ _graph: SceneGraph,+ issues: DescribeIssue[]+): void {if (!looksLikeButton(node)) returnif (node.layoutMode === 'NONE') returnconst hPad = node.paddingLeft + node.paddingRight@@ -196,7 +228,11 @@ function checkButtonWithoutPadding(node: SceneNode, _graph: SceneGraph, issues:}}-function checkFlexContainerWithoutAlignment(node: SceneNode, _graph: SceneGraph, issues: DescribeIssue[]): void {+function checkFlexContainerWithoutAlignment(+ node: SceneNode,+ _graph: SceneGraph,+ issues: DescribeIssue[]+): void {if (!CONTAINER_TYPES.has(node.type)) returnif (node.layoutMode === 'NONE') returnif (node.childIds.length === 0) return@@ -260,13 +296,17 @@ function detectRadiusIssues(node: SceneNode, graph: SceneGraph, issues: Describefor (const childId of node.childIds) {const child = graph.getNode(childId)- if (!child?.visible || child.cornerRadius <= 0 || child.layoutPositioning === 'ABSOLUTE') continue+ if (!child?.visible || child.cornerRadius <= 0 || child.layoutPositioning === 'ABSOLUTE')+ continueif (child.cornerRadius > node.cornerRadius + RADIUS_TOLERANCE) {issues.push({message: `"${child.name}" radius ${child.cornerRadius} > parent ${node.cornerRadius}`,suggestion: `Use rounded={${expectedInner}}`})- } else if (child.cornerRadius > expectedInner + RADIUS_TOLERANCE && expectedInner < node.cornerRadius) {+ } else if (+ child.cornerRadius > expectedInner + RADIUS_TOLERANCE &&+ expectedInner < node.cornerRadius+ ) {issues.push({message: `"${child.name}" radius ${child.cornerRadius} should be ${expectedInner} (parent ${node.cornerRadius} − padding ${minPad})`,suggestion: `Use rounded={${expectedInner}}`@@ -282,7 +322,12 @@ function detectTypographyIssues(node: SceneNode, graph: SceneGraph, issues: Descconst child = graph.getNode(childId)if (child?.type !== 'TEXT' || !child.visible) continueconst text = child.text- if (text === text.toUpperCase() && text.length > 1 && /[A-ZА-ЯЁ]/.test(text) && child.fontSize > UPPERCASE_MAX_SIZE) {+ if (+ text === text.toUpperCase() &&+ text.length > 1 &&+ /[A-ZА-ЯЁ]/.test(text) &&+ child.fontSize > UPPERCASE_MAX_SIZE+ ) {issues.push({message: `"${text.slice(0, 30)}" is uppercase at ${child.fontSize}px — only for small labels ≤${UPPERCASE_MAX_SIZE}px`,suggestion: `Reduce size or use mixed case`@@ -293,7 +338,12 @@ function detectTypographyIssues(node: SceneNode, graph: SceneGraph, issues: Descconst SPACING_GRID = 4-function detectSpacingIssues(node: SceneNode, graph: SceneGraph, _gridSize: number, issues: DescribeIssue[]): void {+function detectSpacingIssues(+ node: SceneNode,+ graph: SceneGraph,+ _gridSize: number,+ issues: DescribeIssue[]+): void {if (node.layoutMode === 'NONE') returnconst children = node.childIds.map((id) => graph.getNode(id))@@ -307,8 +357,13 @@ function detectSpacingIssues(node: SceneNode, graph: SceneGraph, _gridSize: numb})}- const spacingValues = [node.itemSpacing, node.paddingTop, node.paddingRight, node.paddingBottom, node.paddingLeft]- .filter((v) => v > 0)+ const spacingValues = [+ node.itemSpacing,+ node.paddingTop,+ node.paddingRight,+ node.paddingBottom,+ node.paddingLeft+ ].filter((v) => v > 0)for (const v of spacingValues) {if (v % SPACING_GRID !== 0) {issues.push({@@ -321,7 +376,9 @@ function detectSpacingIssues(node: SceneNode, graph: SceneGraph, _gridSize: numbconst flexChildren = children.filter((c) => c.layoutMode !== 'NONE')if (flexChildren.length >= 3) {- const paddings = flexChildren.map((c) => c.paddingTop + c.paddingRight + c.paddingBottom + c.paddingLeft)+ const paddings = flexChildren.map(+ (c) => c.paddingTop + c.paddingRight + c.paddingBottom + c.paddingLeft+ )const gaps = flexChildren.map((c) => c.itemSpacing)if (new Set(paddings).size > 2) {issues.push({@@ -340,12 +397,22 @@ function detectSpacingIssues(node: SceneNode, graph: SceneGraph, _gridSize: numb}const ERROR_PATTERNS = [- /overflow/i, /invisible/i, /no color/i, /collapses/i, /no fill and no stroke/i,- /dark on dark/i, /Touch target too small/i, /Nested Text/i+ /overflow/i,+ /invisible/i,+ /no color/i,+ /collapses/i,+ /no fill and no stroke/i,+ /dark on dark/i,+ /Touch target too small/i,+ /Nested Text/i]const INFO_PATTERNS = [- /children named/i, /uppercase at/i, /fill.*matches parent/i,- /radius.*should be/i, /width while siblings/i, /height while siblings/i,+ /children named/i,+ /uppercase at/i,+ /fill.*matches parent/i,+ /radius.*should be/i,+ /width while siblings/i,+ /height while siblings/i,/icon.*width/i]@@ -355,7 +422,11 @@ function classifySeverity(message: string): IssueSeverity {return 'warning'}-export function detectIssues(node: SceneNode, gridSize: number, graph: SceneGraph): DescribeIssue[] {+export function detectIssues(+ node: SceneNode,+ gridSize: number,+ graph: SceneGraph+): DescribeIssue[] {const issues: DescribeIssue[] = []detectStructuralIssues(node, gridSize, graph, issues)detectVisibilityIssues(node, graph, issues)diff --git a/packages/core/src/tools/describe-layout-issues.ts b/packages/core/src/tools/describe-layout-issues.tsindex 4326778ce..db17aef48 100644--- a/packages/core/src/tools/describe-layout-issues.ts+++ b/packages/core/src/tools/describe-layout-issues.ts@@ -3,8 +3,8 @@ import { wcagLuminance } from 'culori'import { colorToHex } from '../color'import { CONTAINER_TYPES, findAncestorBackground } from './describe-shared'-import type { Color } from '../types'import type { SceneGraph, SceneNode } from '../scene-graph'+import type { Color } from '../types'import type { DescribeIssue } from './describe-issues'const DARK_BG_LUMINANCE = 0.35@@ -39,8 +39,11 @@ function checkAlignmentIssues(ctx: LayoutContext): void {})}- if (node.primaryAxisAlign === 'SPACE_BETWEEN' && node.primaryAxisSizing === 'HUG'- && !isEffectivelyFilling(node, isRow, ctx.graph)) {+ if (+ node.primaryAxisAlign === 'SPACE_BETWEEN' &&+ node.primaryAxisSizing === 'HUG' &&+ !isEffectivelyFilling(node, isRow, ctx.graph)+ ) {issues.push({message: `justify="between" on "${node.name}" with HUG sizing — no effect when parent shrinks to fit`,suggestion: 'Set a fixed size or use w="fill"'@@ -48,9 +51,9 @@ function checkAlignmentIssues(ctx: LayoutContext): void {}if (node.counterAxisAlign === 'STRETCH') {- const allFixed = children.length > 0 && children.every((c) =>- c.layoutAlignSelf === 'AUTO' && (isRow ? c.height > 0 : c.width > 0)- )+ const allFixed =+ children.length > 0 &&+ children.every((c) => c.layoutAlignSelf === 'AUTO' && (isRow ? c.height > 0 : c.width > 0))if (allFixed) {issues.push({message: `items="stretch" on "${node.name}" but all children have fixed ${isRow ? 'height' : 'width'} — stretch ignored`,@@ -59,10 +62,12 @@ function checkAlignmentIssues(ctx: LayoutContext): void {}}- const allSameSize = children.length >= 3 && children.every((c) => {- const dim = isRow ? c.width : c.height- return Math.abs(dim - (isRow ? children[0].width : children[0].height)) < 2- })+ const allSameSize =+ children.length >= 3 &&+ children.every((c) => {+ const dim = isRow ? c.width : c.height+ return Math.abs(dim - (isRow ? children[0].width : children[0].height)) < 2+ })if (allSameSize && node.primaryAxisAlign === 'MIN' && node.itemSpacing === 0) {const total = children.reduce((s, c) => s + (isRow ? c.width : c.height), 0)const pad = isRow ? node.paddingLeft + node.paddingRight : node.paddingTop + node.paddingBottom@@ -94,9 +99,11 @@ function checkDividerOrientation(ctx: LayoutContext): void {}function willGetConcreteSize(node: SceneNode, isRow: boolean, graph: SceneGraph): boolean {- return node.layoutGrow > 0- || node.layoutAlignSelf === 'STRETCH'- || isEffectivelyFilling(node, isRow, graph)+ return (+ node.layoutGrow > 0 ||+ node.layoutAlignSelf === 'STRETCH' ||+ isEffectivelyFilling(node, isRow, graph)+ )}function checkGrowInHug(ctx: LayoutContext): void {@@ -165,7 +172,11 @@ function checkChildOverflow(ctx: LayoutContext): void {function checkHugCollapse(ctx: LayoutContext): void {const { node, isRow, graph, children, issues } = ctxif (children.length === 0) return- if (node.primaryAxisSizing === 'HUG' && !willGetConcreteSize(node, isRow, graph) && children.every((c) => c.layoutGrow > 0)) {+ if (+ node.primaryAxisSizing === 'HUG' &&+ !willGetConcreteSize(node, isRow, graph) &&+ children.every((c) => c.layoutGrow > 0)+ ) {issues.push({message: `"${node.name}" is HUG but all children use grow — collapses to zero`,suggestion: 'Give at least one child a fixed size, or set parent to fixed'@@ -173,7 +184,9 @@ function checkHugCollapse(ctx: LayoutContext): void {}if (node.counterAxisSizing === 'HUG') {const allStretch = children.every(- (c) => c.layoutAlignSelf === 'STRETCH' || (node.counterAxisAlign === 'STRETCH' && c.layoutAlignSelf === 'AUTO')+ (c) =>+ c.layoutAlignSelf === 'STRETCH' ||+ (node.counterAxisAlign === 'STRETCH' && c.layoutAlignSelf === 'AUTO'))const noConcreteChild = children.every((c) => (isRow ? c.height : c.width) <= 0)if (allStretch && noConcreteChild) {@@ -222,7 +235,11 @@ function checkTextOverflow(ctx: LayoutContext): void {suggestion: 'Use w="fill" or constrain width'})}- if (child.textAutoResize === 'HEIGHT' && child.height > child.fontSize * 1.8 && child.maxLines === 0) {+ if (+ child.textAutoResize === 'HEIGHT' &&+ child.height > child.fontSize * 1.8 &&+ child.maxLines === 0+ ) {const approxLines = Math.round(child.height / (child.fontSize * 1.3))issues.push({message: `Text "${child.text.slice(0, 25)}" wraps to ~${approxLines} lines in ${Math.round(child.width)}px`,@@ -256,7 +273,12 @@ function checkChildUndersize(ctx: LayoutContext): void {for (const childId of node.childIds) {const child = graph.getNode(childId)if (!child?.visible) continue- if (child.width > 0 && node.width > 0 && child.width < node.width * 0.3 && child.height >= node.height * 0.5) {+ if (+ child.width > 0 &&+ node.width > 0 &&+ child.width < node.width * 0.3 &&+ child.height >= node.height * 0.5+ ) {issues.push({message: `"${child.name}" is ${Math.round(child.width)}px wide inside ${Math.round(node.width)}px "${node.name}" (no auto-layout)`,suggestion: `Add flex="col" to "${node.name}" and w="fill" to "${child.name}"`@@ -268,7 +290,9 @@ function checkChildUndersize(ctx: LayoutContext): void {function checkCrossAxisOverflow(ctx: LayoutContext): void {const { node, isRow, children, issues } = ctxif (node.clipsContent) return- const crossPad = isRow ? node.paddingTop + node.paddingBottom : node.paddingLeft + node.paddingRight+ const crossPad = isRow+ ? node.paddingTop + node.paddingBottom+ : node.paddingLeft + node.paddingRightconst crossAvailable = (isRow ? node.height : node.width) - crossPadfor (const child of children) {const childCross = isRow ? child.height : child.width@@ -320,11 +344,19 @@ function childNeedsFill(child: SceneNode, parent: SceneNode, isRow: boolean): boif (effectivelyFillsCrossAxis(child, parent, isRow)) return falseif (child.childIds.length === 0) return falsereturn isRow- ? child.width < parent.width * 0.3 && child.counterAxisSizing !== 'FILL' && child.layoutGrow <= 0- : child.height < parent.height * 0.3 && child.primaryAxisSizing !== 'FILL' && child.layoutGrow <= 0+ ? child.width < parent.width * 0.3 &&+ child.counterAxisSizing !== 'FILL' &&+ child.layoutGrow <= 0+ : child.height < parent.height * 0.3 &&+ child.primaryAxisSizing !== 'FILL' &&+ child.layoutGrow <= 0}-function hasSiblingWithGrowOrFill(children: SceneNode[], exclude: SceneNode, isRow: boolean): boolean {+function hasSiblingWithGrowOrFill(+ children: SceneNode[],+ exclude: SceneNode,+ isRow: boolean+): boolean {return children.some((c) => {if (c === exclude) return falseif (c.layoutGrow > 0) return true@@ -366,7 +398,11 @@ function checkDuplicateNames(ctx: LayoutContext): void {}}-export function detectLayoutIssues(node: SceneNode, graph: SceneGraph, issues: DescribeIssue[]): void {+export function detectLayoutIssues(+ node: SceneNode,+ graph: SceneGraph,+ issues: DescribeIssue[]+): void {if (!CONTAINER_TYPES.has(node.type)) returnconst isRow = node.layoutMode === 'HORIZONTAL'diff --git a/packages/core/src/tools/describe-shared.ts b/packages/core/src/tools/describe-shared.tsindex 47f2eb363..3bebe1d6c 100644--- a/packages/core/src/tools/describe-shared.ts+++ b/packages/core/src/tools/describe-shared.ts@@ -1,5 +1,5 @@-import type { Color } from '../types'import type { SceneGraph, SceneNode } from '../scene-graph'+import type { Color } from '../types'export const CONTAINER_TYPES = new Set(['FRAME', 'COMPONENT', 'INSTANCE'])@@ -20,7 +20,12 @@ export function findAncestorBackground(node: SceneNode, graph: SceneGraph): Coloexport function looksLikeButton(node: SceneNode): boolean {if (!CONTAINER_TYPES.has(node.type)) return false- if (node.width > BUTTON_MAX_WIDTH || node.height > BUTTON_MAX_HEIGHT || node.height < BUTTON_MIN_HEIGHT) return false+ if (+ node.width > BUTTON_MAX_WIDTH ||+ node.height > BUTTON_MAX_HEIGHT ||+ node.height < BUTTON_MIN_HEIGHT+ )+ return falseif (node.fills.length === 0 && node.strokes.length === 0) return falseif (node.cornerRadius < BUTTON_MIN_RADIUS) return falsereturn node.childIds.length > 0diff --git a/packages/core/src/tools/describe.ts b/packages/core/src/tools/describe.tsindex cc6fd45ab..0489d61b0 100644--- a/packages/core/src/tools/describe.ts+++ b/packages/core/src/tools/describe.ts@@ -1,12 +1,10 @@import { colorToHex } from '../color'-import { looksLikeButton } from './describe-shared'-import { detectIssues } from './describe-issues'--import type { DescribeIssue } from './describe-issues'+import { looksLikeButton } from './describe-shared'import { defineTool } from './schema'import type { SceneGraph, SceneNode } from '../scene-graph'+import type { DescribeIssue } from './describe-issues'const NAME_ROLE_PATTERNS: { pattern: RegExp; role: string }[] = [{ pattern: /^icon$/i, role: 'icon' },@@ -48,7 +46,7 @@ const NAME_ROLE_PATTERNS: { pattern: RegExp; role: string }[] = [{ pattern: /^progress$/i, role: 'progressbar' },{ pattern: /^spinner$/i, role: 'progressbar' },{ pattern: /^divider$/i, role: 'separator' },- { pattern: /^separator$/i, role: 'separator' },+ { pattern: /^separator$/i, role: 'separator' }]function detectRoleFromName(name: string): string | null {@@ -74,8 +72,6 @@ function looksLikeSeparator(node: SceneNode): boolean {return ratio > 10 && Math.min(node.width, node.height) <= 4}--function describeVisual(node: SceneNode): string {const parts: string[] = []const fill = node.fills.find((f) => f.type === 'SOLID' && f.visible)@@ -94,19 +90,28 @@ function describeVisual(node: SceneNode): string {}const JUSTIFY_LABELS: Record<string, string> = {- MIN: 'start', CENTER: 'center', MAX: 'end', SPACE_BETWEEN: 'between'+ MIN: 'start',+ CENTER: 'center',+ MAX: 'end',+ SPACE_BETWEEN: 'between'}const ITEMS_LABELS: Record<string, string> = {- MIN: 'start', CENTER: 'center', MAX: 'end', STRETCH: 'stretch', BASELINE: 'baseline'+ MIN: 'start',+ CENTER: 'center',+ MAX: 'end',+ STRETCH: 'stretch',+ BASELINE: 'baseline'}function describeLayout(node: SceneNode): string | null {if (node.layoutMode === 'NONE') return nullconst dir = node.layoutMode === 'HORIZONTAL' ? 'horizontal' : 'vertical'const parts = [dir]- if (node.primaryAxisAlign !== 'MIN') parts.push(`justify=${JUSTIFY_LABELS[node.primaryAxisAlign] ?? node.primaryAxisAlign}`)- if (node.counterAxisAlign !== 'MIN') parts.push(`items=${ITEMS_LABELS[node.counterAxisAlign] ?? node.counterAxisAlign}`)+ if (node.primaryAxisAlign !== 'MIN')+ parts.push(`justify=${JUSTIFY_LABELS[node.primaryAxisAlign] ?? node.primaryAxisAlign}`)+ if (node.counterAxisAlign !== 'MIN')+ parts.push(`items=${ITEMS_LABELS[node.counterAxisAlign] ?? node.counterAxisAlign}`)if (node.itemSpacing > 0) parts.push(`${node.itemSpacing}px gap`)const pad = [node.paddingTop, node.paddingRight, node.paddingBottom, node.paddingLeft]const allSame = pad.every((p) => p === pad[0])@@ -114,7 +119,8 @@ function describeLayout(node: SceneNode): string | null {if (allSame && first > 0) parts.push(`${first}px padding`)else if (pad.some((p) => p > 0)) parts.push(`padding ${pad.join('/')}`)if (node.primaryAxisSizing !== 'FIXED') parts.push(`${node.primaryAxisSizing.toLowerCase()} main`)- if (node.counterAxisSizing !== 'FIXED') parts.push(`${node.counterAxisSizing.toLowerCase()} cross`)+ if (node.counterAxisSizing !== 'FIXED')+ parts.push(`${node.counterAxisSizing.toLowerCase()} cross`)if (node.layoutWrap === 'WRAP') parts.push('wrap')return parts.join(', ')}@@ -163,7 +169,12 @@ function summarizeText(node: SceneNode): string {return summary}-function describeChild(node: SceneNode, graph: SceneGraph, depth: number, gridSize: number): ChildDescription {+function describeChild(+ node: SceneNode,+ graph: SceneGraph,+ depth: number,+ gridSize: number+): ChildDescription {const role = detectRole(node)const summary = node.type === 'TEXT' ? summarizeText(node) : summarizeContainer(node)const result: ChildDescription = { role, name: node.name, summary, id: node.id }@@ -210,7 +221,7 @@ function describeOneNode(type: raw.type,role,size: `${raw.width}×${raw.height}`,- visual,+ visual}if (layout) result.layout = layoutif (children.length > 0) result.children = childrendiff --git a/packages/core/src/tools/read.ts b/packages/core/src/tools/read.tsindex fa58c479d..5476c731a 100644--- a/packages/core/src/tools/read.ts+++ b/packages/core/src/tools/read.ts@@ -2,8 +2,8 @@ import { createTwoFilesPatch } from 'diff'import { computeBounds } from '../geometry'import { sceneNodeToJSX } from '../render/export-jsx'-import { defineTool, nodeSummary, nodeToResult } from './schema'import { queryByXPath } from '../xpath'+import { defineTool, nodeSummary, nodeToResult } from './schema'import type { FigmaNodeProxy } from '../figma-api'@@ -27,7 +27,13 @@ interface TreeEntry {}function nodeToTreeEntry(node: FigmaNodeProxy): TreeEntry {- const entry: TreeEntry = { id: node.id, type: node.type, name: node.name, w: node.width, h: node.height }+ const entry: TreeEntry = {+ id: node.id,+ type: node.type,+ name: node.name,+ w: node.width,+ h: node.height+ }if (node.children.length > 0) {entry.children = node.children.map(nodeToTreeEntry)}@@ -50,10 +56,14 @@ export const getPageTree = defineTool({export const getNode = defineTool({name: 'get_node',- description: 'Get detailed properties of a node by ID. Use depth to limit child recursion (0 = node only, 1 = direct children, etc). Default: unlimited.',+ description:+ 'Get detailed properties of a node by ID. Use depth to limit child recursion (0 = node only, 1 = direct children, etc). Default: unlimited.',params: {id: { type: 'string', description: 'Node ID', required: true },- depth: { type: 'number', description: 'Max depth of children to include (0 = no children). Default: unlimited' }+ depth: {+ type: 'number',+ description: 'Max depth of children to include (0 = no children). Default: unlimited'+ }},execute: (figma, { id, depth }) => {const node = figma.getNodeById(id)diff --git a/packages/core/src/tools/registry.ts b/packages/core/src/tools/registry.tsindex ce8cc3b55..89389d2f4 100644--- a/packages/core/src/tools/registry.ts+++ b/packages/core/src/tools/registry.ts@@ -1,45 +1,118 @@-import type { ToolDef } from './schema'-import {- getSelection, getPageTree, getNode, findNodes, queryNodes, getComponents,- listPages, switchPage, getCurrentPage, pageBounds, selectNodes, listFonts,- getJsx, diffJsx-} from './read'+ analyzeColors,+ analyzeTypography,+ analyzeSpacing,+ analyzeClusters,+ diffCreate,+ diffShow,+ evalCode+} from './analyze'+import { calc } from './calc'+import { designToTokens, designToComponentMap } from './codegen'import {- createShape, render, createComponent, createInstance,- createPage, createVector, createSlice, fetchIconsTool, insertIcon, searchIconsTool+ createShape,+ render,+ createComponent,+ createInstance,+ createPage,+ createVector,+ createSlice,+ fetchIconsTool,+ insertIcon,+ searchIconsTool} from './create'+import { describe } from './describe'import {- setFill, setStroke, setEffects, updateNode, setLayout, setConstraints,- setRotation, setOpacity, setRadius, setMinMax, setText, setFont, setFontRange,- setTextResize, setVisible, setBlend, setLocked, setStrokeAlign,- setTextProperties, setLayoutChild, setImageFill+ setFill,+ setStroke,+ setEffects,+ updateNode,+ setLayout,+ setConstraints,+ setRotation,+ setOpacity,+ setRadius,+ setMinMax,+ setText,+ setFont,+ setFontRange,+ setTextResize,+ setVisible,+ setBlend,+ setLocked,+ setStrokeAlign,+ setTextProperties,+ setLayoutChild,+ setImageFill} from './modify'import {- deleteNode, cloneNode, renameNode, reparentNode, groupNodes, ungroupNode,- flattenNodes, nodeToComponent, nodeBounds, nodeMove, nodeResize,- nodeAncestors, nodeChildren, nodeTree, nodeBindings, nodeReplaceWith, arrangeNodes,+ getSelection,+ getPageTree,+ getNode,+ findNodes,+ queryNodes,+ getComponents,+ listPages,+ switchPage,+ getCurrentPage,+ pageBounds,+ selectNodes,+ listFonts,+ getJsx,+ diffJsx+} from './read'+import { stockPhoto } from './stock-photo'+import {+ deleteNode,+ cloneNode,+ renameNode,+ reparentNode,+ groupNodes,+ ungroupNode,+ flattenNodes,+ nodeToComponent,+ nodeBounds,+ nodeMove,+ nodeResize,+ nodeAncestors,+ nodeChildren,+ nodeTree,+ nodeBindings,+ nodeReplaceWith,+ arrangeNodes,batchUpdate} from './structure'import {- listVariables, listCollections, getVariable, findVariables,- createVariable, setVariable, deleteVariable, bindVariable,- getCollection, createCollection, deleteCollection+ listVariables,+ listCollections,+ getVariable,+ findVariables,+ createVariable,+ setVariable,+ deleteVariable,+ bindVariable,+ getCollection,+ createCollection,+ deleteCollection} from './variables'import {- booleanUnion, booleanSubtract, booleanIntersect, booleanExclude,- pathGet, pathSet, pathScale, pathFlip, pathMove,- viewportGet, viewportSet, viewportZoomToFit,- exportSvg, exportImage+ booleanUnion,+ booleanSubtract,+ booleanIntersect,+ booleanExclude,+ pathGet,+ pathSet,+ pathScale,+ pathFlip,+ pathMove,+ viewportGet,+ viewportSet,+ viewportZoomToFit,+ exportSvg,+ exportImage} from './vector'-import {- analyzeColors, analyzeTypography, analyzeSpacing, analyzeClusters,- diffCreate, diffShow, evalCode-} from './analyze'-import { describe } from './describe'-import { designToTokens, designToComponentMap } from './codegen'-import { calc } from './calc'-import { stockPhoto } from './stock-photo'++import type { ToolDef } from './schema'/*** Core tools registered by default in AI chat (~30 tools, ~3K schema tokens).@@ -73,7 +146,7 @@ export const CORE_TOOLS: ToolDef[] = [describe,calc,evalCode,- viewportZoomToFit,+ viewportZoomToFit]/**@@ -166,7 +239,7 @@ export const EXTENDED_TOOLS: ToolDef[] = [diffShow,// CodegendesignToTokens,- designToComponentMap,+ designToComponentMap]/** All tools combined — used by MCP server and CLI. */diff --git a/packages/core/src/tools/stock-photo.ts b/packages/core/src/tools/stock-photo.tsindex 3803682c9..282bc58e7 100644--- a/packages/core/src/tools/stock-photo.ts+++ b/packages/core/src/tools/stock-photo.ts@@ -12,11 +12,14 @@ export interface StockPhotoResult {export interface StockPhotoProvider {name: string- search(query: string, options: {- perPage: number- orientation: 'landscape' | 'portrait' | 'square'- targetDim: number- }): Promise<StockPhotoResult[]>+ search(+ query: string,+ options: {+ perPage: number+ orientation: 'landscape' | 'portrait' | 'square'+ targetDim: number+ }+ ): Promise<StockPhotoResult[]>}const providers = new Map<string, StockPhotoProvider>()@@ -155,7 +158,13 @@ interface PhotoRequest {interface PhotoResult {id: string- photo?: { sourceId: string; photographer: string; width: number; height: number; provider: string }+ photo?: {+ sourceId: string+ photographer: string+ width: number+ height: number+ provider: string+ }error?: string}@@ -196,14 +205,16 @@ async function applyPhoto(}const image = figma.createImage(imageBytes)- node.fills = [{- type: 'IMAGE',- color: { r: 1, g: 1, b: 1, a: 1 },- imageHash: image.hash,- imageScaleMode: 'FILL',- visible: true,- opacity: 1- }]+ node.fills = [+ {+ type: 'IMAGE',+ color: { r: 1, g: 1, b: 1, a: 1 },+ imageHash: image.hash,+ imageScaleMode: 'FILL',+ visible: true,+ opacity: 1+ }+ ]return {id: node.id,diff --git a/packages/core/src/tools/structure.ts b/packages/core/src/tools/structure.tsindex 3114cdddb..862638415 100644--- a/packages/core/src/tools/structure.ts+++ b/packages/core/src/tools/structure.ts@@ -347,43 +347,87 @@ export const arrangeNodes = defineTool({}})-interface BatchOp {id: stringprops: Record<string, unknown>}-function str(v: unknown): string { return typeof v === 'string' ? v : '' }-function num(v: unknown): number { return typeof v === 'number' ? v : 0 }+function str(v: unknown): string {+ return typeof v === 'string' ? v : ''+}+function num(v: unknown): number {+ return typeof v === 'number' ? v : 0+}function applyBatchProps(node: FigmaNodeProxy, p: Record<string, unknown>): string[] {const updated: string[] = []- if (p.spacing !== undefined) { node.itemSpacing = num(p.spacing); updated.push('spacing') }+ if (p.spacing !== undefined) {+ node.itemSpacing = num(p.spacing)+ updated.push('spacing')+ }if (p.padding !== undefined) {const v = num(p.padding)- node.paddingTop = v; node.paddingRight = v; node.paddingBottom = v; node.paddingLeft = v+ node.paddingTop = v+ node.paddingRight = v+ node.paddingBottom = v+ node.paddingLeft = vupdated.push('padding')}if (p.padding_horizontal !== undefined) {- node.paddingLeft = num(p.padding_horizontal); node.paddingRight = num(p.padding_horizontal)+ node.paddingLeft = num(p.padding_horizontal)+ node.paddingRight = num(p.padding_horizontal)updated.push('padding_horizontal')}if (p.padding_vertical !== undefined) {- node.paddingTop = num(p.padding_vertical); node.paddingBottom = num(p.padding_vertical)+ node.paddingTop = num(p.padding_vertical)+ node.paddingBottom = num(p.padding_vertical)updated.push('padding_vertical')}- if (p.counter_align !== undefined) { node.counterAxisAlignItems = str(p.counter_align); updated.push('counter_align') }- if (p.align !== undefined) { node.primaryAxisAlignItems = str(p.align); updated.push('align') }- if (p.sizing_horizontal !== undefined) { node.layoutSizingHorizontal = str(p.sizing_horizontal); updated.push('sizing_horizontal') }- if (p.sizing_vertical !== undefined) { node.layoutSizingVertical = str(p.sizing_vertical); updated.push('sizing_vertical') }- if (p.grow !== undefined) { node.layoutGrow = num(p.grow); updated.push('grow') }- if (p.name !== undefined) { node.name = str(p.name); updated.push('name') }- if (p.visible !== undefined) { node.visible = Boolean(p.visible); updated.push('visible') }- if (p.corner_radius !== undefined) { node.cornerRadius = num(p.corner_radius); updated.push('corner_radius') }- if (p.opacity !== undefined) { node.opacity = num(p.opacity); updated.push('opacity') }- if (p.auto_resize !== undefined) { node.textAutoResize = str(p.auto_resize); updated.push('auto_resize') }- if (p.direction !== undefined) { node.layoutMode = str(p.direction) as 'HORIZONTAL' | 'VERTICAL'; updated.push('direction') }+ if (p.counter_align !== undefined) {+ node.counterAxisAlignItems = str(p.counter_align)+ updated.push('counter_align')+ }+ if (p.align !== undefined) {+ node.primaryAxisAlignItems = str(p.align)+ updated.push('align')+ }+ if (p.sizing_horizontal !== undefined) {+ node.layoutSizingHorizontal = str(p.sizing_horizontal)+ updated.push('sizing_horizontal')+ }+ if (p.sizing_vertical !== undefined) {+ node.layoutSizingVertical = str(p.sizing_vertical)+ updated.push('sizing_vertical')+ }+ if (p.grow !== undefined) {+ node.layoutGrow = num(p.grow)+ updated.push('grow')+ }+ if (p.name !== undefined) {+ node.name = str(p.name)+ updated.push('name')+ }+ if (p.visible !== undefined) {+ node.visible = Boolean(p.visible)+ updated.push('visible')+ }+ if (p.corner_radius !== undefined) {+ node.cornerRadius = num(p.corner_radius)+ updated.push('corner_radius')+ }+ if (p.opacity !== undefined) {+ node.opacity = num(p.opacity)+ updated.push('opacity')+ }+ if (p.auto_resize !== undefined) {+ node.textAutoResize = str(p.auto_resize)+ updated.push('auto_resize')+ }+ if (p.direction !== undefined) {+ node.layoutMode = str(p.direction) as 'HORIZONTAL' | 'VERTICAL'+ updated.push('direction')+ }return updated}@@ -415,7 +459,10 @@ export const batchUpdate = defineTool({for (const op of ops) {const node = figma.getNodeById(op.id)- if (!node) { errors.push(`Node "${op.id}" not found`); continue }+ if (!node) {+ errors.push(`Node "${op.id}" not found`)+ continue+ }const updated = applyBatchProps(node, op.props)if (updated.length > 0) results.push({ id: op.id, updated })}diff --git a/packages/core/src/tools/variables.ts b/packages/core/src/tools/variables.tsindex ab30ea31f..691369765 100644--- a/packages/core/src/tools/variables.ts+++ b/packages/core/src/tools/variables.ts@@ -1,8 +1,8 @@import { parseColor } from '../color'-import type { VariableType, VariableValue } from '../scene-graph'-import { defineTool } from './schema'+import type { VariableType, VariableValue } from '../scene-graph'+export const listVariables = defineTool({name: 'list_variables',description: 'List all design variables (colors, numbers, strings, booleans).',diff --git a/packages/core/src/tools/vector.ts b/packages/core/src/tools/vector.tsindex 94632f034..eb63908fe 100644--- a/packages/core/src/tools/vector.ts+++ b/packages/core/src/tools/vector.ts@@ -267,9 +267,7 @@ export const exportSvg = defineTool({const { renderNodesToSVG } = await import('../svg-export/index.js')const pageId = figma.currentPageIdconst ids =- args.ids && args.ids.length > 0- ? args.ids- : figma.currentPage.children.map((n) => n.id)+ args.ids && args.ids.length > 0 ? args.ids : figma.currentPage.children.map((n) => n.id)const svg = renderNodesToSVG(figma.graph, pageId, ids)if (!svg) return { error: 'No visible nodes to export' }return { svg }@@ -304,9 +302,7 @@ export const exportImage = defineTool({return { error: 'Image export is not available in this environment' }}const ids =- args.ids && args.ids.length > 0- ? args.ids- : figma.currentPage.children.map((n) => n.id)+ args.ids && args.ids.length > 0 ? args.ids : figma.currentPage.children.map((n) => n.id)const format = (args.format ?? 'PNG').toUpperCase() as 'PNG' | 'JPG' | 'WEBP'const data = await figma.exportImage(ids, {scale: args.scale ?? 1,diff --git a/packages/core/src/undo.ts b/packages/core/src/undo.tsindex fbce15247..78a4e1654 100644--- a/packages/core/src/undo.ts+++ b/packages/core/src/undo.ts@@ -89,5 +89,3 @@ export class UndoManager {return this.redoStack.at(-1)?.label ?? null}}--diff --git a/packages/core/src/vector.ts b/packages/core/src/vector.tsindex c8688b052..e9bc20baa 100644--- a/packages/core/src/vector.ts+++ b/packages/core/src/vector.ts@@ -6,8 +6,8 @@ import type {VectorVertex,WindingRule} from './scene-graph'-import type { CanvasKit, Path } from 'canvaskit-wasm'import type { Rect } from './types'+import type { CanvasKit, Path } from 'canvaskit-wasm'// --- vectorNetworkBlob binary format ---// Header: [numVertices:u32, numSegments:u32, numRegions:u32] (12 bytes)diff --git a/packages/core/src/xpath.ts b/packages/core/src/xpath.tsindex 3c03ebbde..609852037 100644--- a/packages/core/src/xpath.ts+++ b/packages/core/src/xpath.ts@@ -1,5 +1,5 @@-import type { IDomFacade } from 'fontoxpath'import type { SceneGraph, SceneNode } from './scene-graph'+import type { IDomFacade } from 'fontoxpath'const NODE_TYPES = {ELEMENT_NODE: 1,@@ -105,7 +105,9 @@ function getAttrs(wrapped: XPathNode): XPathAttr[] {const value = (node as unknown as Record<string, unknown>)[attrName]if (value === undefined || value === null || typeof value === 'symbol') continueconst stringValue =- typeof value === 'object' ? JSON.stringify(value) : String(value as string | number | boolean)+ typeof value === 'object'+ ? JSON.stringify(value)+ : String(value as string | number | boolean)attrs.push({nodeType: NODE_TYPES.ATTRIBUTE_NODE,nodeName: attrName,@@ -152,7 +154,9 @@ function createDomFacade(graph: SceneGraph) {if (attributeName in sceneNode) {const value = (sceneNode as unknown as Record<string, unknown>)[attributeName]if (value === undefined || value === null || typeof value === 'symbol') return null- return typeof value === 'object' ? JSON.stringify(value) : String(value as string | number | boolean)+ return typeof value === 'object'+ ? JSON.stringify(value)+ : String(value as string | number | boolean)}return null},@@ -215,9 +219,7 @@ export async function queryByXPath(): Promise<SceneNode[]> {const { limit = 1000 } = optionsconst pages = graph.getPages()- const targetPages = options.page- ? pages.filter((p) => p.name === options.page)- : pages+ const targetPages = options.page ? pages.filter((p) => p.name === options.page) : pagesif (targetPages.length === 0) return []diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.tsindex 2d0b68469..acf5cb82f 100644--- a/packages/mcp/src/server.ts+++ b/packages/mcp/src/server.ts@@ -185,15 +185,22 @@ export function startServer(options: ServerOptions = {}) {const app = new Hono()if (corsOrigin) {- app.use('*', cors({- origin: corsOrigin,- allowMethods: ['GET', 'POST', 'DELETE', 'OPTIONS'],- allowHeaders: [- 'Content-Type', 'Authorization', 'x-mcp-token',- 'mcp-session-id', 'Last-Event-ID', 'mcp-protocol-version'- ],- exposeHeaders: ['mcp-session-id', 'mcp-protocol-version']- }))+ app.use(+ '*',+ cors({+ origin: corsOrigin,+ allowMethods: ['GET', 'POST', 'DELETE', 'OPTIONS'],+ allowHeaders: [+ 'Content-Type',+ 'Authorization',+ 'x-mcp-token',+ 'mcp-session-id',+ 'Last-Event-ID',+ 'mcp-protocol-version'+ ],+ exposeHeaders: ['mcp-session-id', 'mcp-protocol-version']+ })+ )} else {app.use('*', cors())}@@ -259,7 +266,13 @@ export function startServer(options: ServerOptions = {}) {const r = res.result as Record<string, unknown> | undefinedif (r && 'base64' in r && 'mimeType' in r) {return {- content: [{ type: 'image' as const, data: r.base64 as string, mimeType: r.mimeType as string }]+ content: [+ {+ type: 'image' as const,+ data: r.base64 as string,+ mimeType: r.mimeType as string+ }+ ]}}return ok(r)@@ -273,7 +286,8 @@ export function startServer(options: ServerOptions = {}) {register('get_codegen_prompt',{- description: 'Get design-to-code generation guidelines. Call before generating frontend code.',+ description:+ 'Get design-to-code generation guidelines. Call before generating frontend code.',inputSchema: z.object({})},async () => ok({ prompt: CODEGEN_PROMPT })@@ -290,7 +304,9 @@ export function startServer(options: ServerOptions = {}) {app.all('/mcp', async (c) => {if (authToken) {const auth = c.req.header('authorization')- const token = auth?.startsWith('Bearer ') ? auth.slice('Bearer '.length) : c.req.header('x-mcp-token')+ const token = auth?.startsWith('Bearer ')+ ? auth.slice('Bearer '.length)+ : c.req.header('x-mcp-token')if (token !== authToken) {return c.json({ error: 'Unauthorized' }, 401)}diff --git a/packages/vue/src/Canvas/useCanvasInput.ts b/packages/vue/src/Canvas/useCanvasInput.tsindex ac41fa9d0..5f45526a2 100644--- a/packages/vue/src/Canvas/useCanvasInput.ts+++ b/packages/vue/src/Canvas/useCanvasInput.ts@@ -14,11 +14,7 @@ import { hitTestCornerRotation } from '../shared/input/geometry'import { handleMoveMove, handleMoveUp } from '../shared/input/move'import { setupPanZoom } from '../shared/input/pan-zoom'import { applyResize } from '../shared/input/resize'-import {- handleSelectDown,- updateHoverCursor,- type HitTestFns-} from '../shared/input/select'+import { handleSelectDown, updateHoverCursor, type HitTestFns } from '../shared/input/select'import { TOOL_TO_NODE } from '../shared/input/types'import type { DragMarquee, DragPan, DragRotate, DragState } from '../shared/input/types'diff --git a/packages/vue/src/ColorPicker/ColorPickerRoot.vue b/packages/vue/src/ColorPicker/ColorPickerRoot.vueindex 8aa2c2ea3..b77401b50 100644--- a/packages/vue/src/ColorPicker/ColorPickerRoot.vue+++ b/packages/vue/src/ColorPicker/ColorPickerRoot.vue@@ -25,7 +25,12 @@ const swatchBg = computed(() => colorToCSS(props.color))</PopoverTrigger><PopoverPortal>- <PopoverContent data-test-id="color-picker-popover" :class="contentClass" :side-offset="4" side="left">+ <PopoverContent+ data-test-id="color-picker-popover"+ :class="contentClass"+ :side-offset="4"+ side="left"+ ><slot :color="color" :update="(nextColor: Color) => emit('update', nextColor)" /></PopoverContent></PopoverPortal>diff --git a/packages/vue/src/PropertyList/PropertyListItem.vue b/packages/vue/src/PropertyList/PropertyListItem.vueindex 60295ed1f..98a417789 100644--- a/packages/vue/src/PropertyList/PropertyListItem.vue+++ b/packages/vue/src/PropertyList/PropertyListItem.vue@@ -18,9 +18,29 @@ const { update, patch, remove, toggleVisibility } = usePropertyList()<template><slot:index="index"- :update="(item: unknown) => { emit('update', index, item); update(index, item) }"- :patch="(changes: Record<string, unknown>) => { emit('patch', index, changes); patch(index, changes) }"- :remove="() => { emit('remove', index); remove(index) }"- :toggle-visibility="() => { emit('toggleVisibility', index); toggleVisibility(index) }"+ :update="+ (item: unknown) => {+ emit('update', index, item)+ update(index, item)+ }+ "+ :patch="+ (changes: Record<string, unknown>) => {+ emit('patch', index, changes)+ patch(index, changes)+ }+ "+ :remove="+ () => {+ emit('remove', index)+ remove(index)+ }+ "+ :toggle-visibility="+ () => {+ emit('toggleVisibility', index)+ toggleVisibility(index)+ }+ "/></template>diff --git a/packages/vue/src/PropertyList/context.ts b/packages/vue/src/PropertyList/context.tsindex 69843e76b..ac4fef4da 100644--- a/packages/vue/src/PropertyList/context.ts+++ b/packages/vue/src/PropertyList/context.ts@@ -1,7 +1,7 @@import { type InjectionKey, inject, provide } from 'vue'-import type { Editor } from '@open-pencil/core/editor'import type { SceneNode } from '@open-pencil/core'+import type { Editor } from '@open-pencil/core/editor'import type { ComputedRef } from 'vue'type ArrayPropKey = 'fills' | 'strokes' | 'effects'diff --git a/packages/vue/src/ScrubInput/ScrubInputDisplay.vue b/packages/vue/src/ScrubInput/ScrubInputDisplay.vueindex 94e63082c..fc8cf6c94 100644--- a/packages/vue/src/ScrubInput/ScrubInputDisplay.vue+++ b/packages/vue/src/ScrubInput/ScrubInputDisplay.vue@@ -6,11 +6,7 @@ const ctx = useScrubInput()<template><span v-if="!ctx.editing.value" v-bind="$attrs">- <slot- :value="ctx.displayValue.value"- :is-mixed="ctx.isMixed.value"- :placeholder="''"- >+ <slot :value="ctx.displayValue.value" :is-mixed="ctx.isMixed.value" :placeholder="''">{{ ctx.isMixed.value ? '' : ctx.displayValue.value }}</slot></span>diff --git a/packages/vue/src/ScrubInput/ScrubInputField.vue b/packages/vue/src/ScrubInput/ScrubInputField.vueindex 1bea1bf64..3cb8951e1 100644--- a/packages/vue/src/ScrubInput/ScrubInputField.vue+++ b/packages/vue/src/ScrubInput/ScrubInputField.vue@@ -7,7 +7,11 @@ const ctx = useScrubInput()<template><inputv-if="ctx.editing.value"- :ref="(el) => { ctx.inputRef.value = el as HTMLInputElement | null }"+ :ref="+ (el) => {+ ctx.inputRef.value = el as HTMLInputElement | null+ }+ "type="number":value="ctx.isMixed.value ? '' : ctx.displayValue.value"v-bind="$attrs"diff --git a/packages/vue/src/ScrubInput/ScrubInputRoot.vue b/packages/vue/src/ScrubInput/ScrubInputRoot.vueindex ace5b3497..60a4ac96a 100644--- a/packages/vue/src/ScrubInput/ScrubInputRoot.vue+++ b/packages/vue/src/ScrubInput/ScrubInputRoot.vue@@ -4,20 +4,23 @@ import { useEventListener } from '@vueuse/core'import { provideScrubInput } from './context'-const props = withDefaults(defineProps<{- modelValue: number | symbol- min?: number- max?: number- step?: number- sensitivity?: number- placeholder?: string-}>(), {- min: -Infinity,- max: Infinity,- step: 1,- sensitivity: 1,- placeholder: 'Mixed'-})+const props = withDefaults(+ defineProps<{+ modelValue: number | symbol+ min?: number+ max?: number+ step?: number+ sensitivity?: number+ placeholder?: string+ }>(),+ {+ min: -Infinity,+ max: Infinity,+ step: 1,+ sensitivity: 1,+ placeholder: 'Mixed'+ }+)const emit = defineEmits<{'update:modelValue': [value: number]@@ -29,8 +32,8 @@ const scrubbing = ref(false)const inputRef = ref<HTMLInputElement | null>(null)const isMixed = computed(() => typeof props.modelValue === 'symbol')-const numericValue = computed(() => isMixed.value ? 0 : (props.modelValue as number))-const displayValue = computed(() => isMixed.value ? '' : String(Math.round(numericValue.value)))+const numericValue = computed(() => (isMixed.value ? 0 : (props.modelValue as number)))+const displayValue = computed(() => (isMixed.value ? '' : String(Math.round(numericValue.value))))let stopMove: (() => void) | undefinedlet stopUp: (() => void) | undefineddiff --git a/packages/vue/src/ScrubInput/context.ts b/packages/vue/src/ScrubInput/context.tsindex 1fbe2fca4..89d83c56b 100644--- a/packages/vue/src/ScrubInput/context.ts+++ b/packages/vue/src/ScrubInput/context.ts@@ -1,4 +1,5 @@import { type InjectionKey, inject, provide } from 'vue'+import type { Ref } from 'vue'export interface ScrubInputContext {diff --git a/packages/vue/src/Toolbar/ToolbarItem.vue b/packages/vue/src/Toolbar/ToolbarItem.vueindex 21879f916..fe57effe0 100644--- a/packages/vue/src/Toolbar/ToolbarItem.vue+++ b/packages/vue/src/Toolbar/ToolbarItem.vue@@ -15,9 +15,5 @@ const isActive = computed(() => activeTool.value === tool)</script><template>- <slot- :active="isActive"- :select="() => setTool(tool)"- :tool="tool"- />+ <slot :active="isActive" :select="() => setTool(tool)" :tool="tool" /></template>diff --git a/packages/vue/src/VariablesEditor/useVariablesEditor.ts b/packages/vue/src/VariablesEditor/useVariablesEditor.tsindex 023e98497..0f017de91 100644--- a/packages/vue/src/VariablesEditor/useVariablesEditor.ts+++ b/packages/vue/src/VariablesEditor/useVariablesEditor.ts@@ -1,5 +1,5 @@-import { computed, type Component } from 'vue'import { useVueTable, getCoreRowModel } from '@tanstack/vue-table'+import { computed, type Component } from 'vue'import { useVariablesDialogState } from './useVariablesDialogState'import { useVariablesTable } from './useVariablesTable'diff --git a/packages/vue/src/controls/useAppearance.ts b/packages/vue/src/controls/useAppearance.tsindex cf7780319..1bc2ace0e 100644--- a/packages/vue/src/controls/useAppearance.ts+++ b/packages/vue/src/controls/useAppearance.ts@@ -1,9 +1,9 @@import { computed } from 'vue'import { useEditor } from '../context/editorContext'-import { useSceneComputed } from '../internal/useSceneComputed'import { MIXED } from '../controls/useNodeProps'import { usePropScrub } from '../controls/usePropScrub'+import { useSceneComputed } from '../internal/useSceneComputed'import type { MixedValue } from '../controls/useNodeProps'import type { SceneNode } from '@open-pencil/core'diff --git a/packages/vue/src/controls/usePosition.ts b/packages/vue/src/controls/usePosition.tsindex 819207540..f7536ab41 100644--- a/packages/vue/src/controls/usePosition.ts+++ b/packages/vue/src/controls/usePosition.ts@@ -1,8 +1,8 @@import { computed } from 'vue'import { useEditor } from '../context/editorContext'-import { useSceneComputed } from '../internal/useSceneComputed'import { usePropScrub } from '../controls/usePropScrub'+import { useSceneComputed } from '../internal/useSceneComputed'import type { SceneNode } from '@open-pencil/core'diff --git a/src/components/FillPicker.vue b/src/components/FillPicker.vueindex d1efde713..f069cbba7 100644--- a/src/components/FillPicker.vue+++ b/src/components/FillPicker.vue@@ -36,7 +36,11 @@ const cls = usePopoverUI({ content: 'w-60 p-2' })<template #default="{ fill: currentFill, category, toSolid, toGradient, toImage, update }"><div class="mb-2 flex items-center gap-0.5"><Tip label="Solid">- <button :class="tabClass(category === 'SOLID')" data-test-id="fill-picker-tab-solid" @click="toSolid">+ <button+ :class="tabClass(category === 'SOLID')"+ data-test-id="fill-picker-tab-solid"+ @click="toSolid"+ ><icon-lucide-square class="size-3.5" /></button></Tip>@@ -50,7 +54,11 @@ const cls = usePopoverUI({ content: 'w-60 p-2' })</button></Tip><Tip label="Image">- <button :class="tabClass(category === 'IMAGE')" data-test-id="fill-picker-tab-image" @click="toImage">+ <button+ :class="tabClass(category === 'IMAGE')"+ data-test-id="fill-picker-tab-image"+ @click="toImage"+ ><icon-lucide-image class="size-3.5" /></button></Tip>diff --git a/src/components/VariablesDialog.vue b/src/components/VariablesDialog.vueindex e4454052a..fd8c82ca6 100644--- a/src/components/VariablesDialog.vue+++ b/src/components/VariablesDialog.vue@@ -44,158 +44,167 @@ const ctx = useVariablesEditor({</script><template>- <DialogRoot v-model:open="open">- <DialogPortal>- <DialogOverlay :class="cls.overlay" />- <DialogContent data-test-id="variables-dialog" :class="cls.content">- <div v-if="!ctx.hasCollections" class="flex flex-1 flex-col">- <div class="flex shrink-0 items-center justify-between border-b border-border px-4 py-3">- <DialogTitle class="text-sm font-semibold text-surface">Local variables</DialogTitle>- <DialogClose- class="flex size-6 cursor-pointer items-center justify-center rounded border-none bg-transparent text-muted hover:bg-hover hover:text-surface"+ <DialogRoot v-model:open="open">+ <DialogPortal>+ <DialogOverlay :class="cls.overlay" />+ <DialogContent data-test-id="variables-dialog" :class="cls.content">+ <div v-if="!ctx.hasCollections" class="flex flex-1 flex-col">+ <div class="flex shrink-0 items-center justify-between border-b border-border px-4 py-3">+ <DialogTitle class="text-sm font-semibold text-surface">Local variables</DialogTitle>+ <DialogClose+ class="flex size-6 cursor-pointer items-center justify-center rounded border-none bg-transparent text-muted hover:bg-hover hover:text-surface"+ >+ <icon-lucide-x class="size-4" />+ </DialogClose>+ </div>+ <div class="flex flex-1 items-center justify-center">+ <div class="text-center">+ <p class="text-sm text-muted">No variable collections</p>+ <button+ data-test-id="variables-create-collection"+ class="mt-2 cursor-pointer rounded bg-hover px-3 py-1.5 text-xs text-surface hover:bg-border"+ @click="ctx.addCollection">- <icon-lucide-x class="size-4" />- </DialogClose>- </div>- <div class="flex flex-1 items-center justify-center">- <div class="text-center">- <p class="text-sm text-muted">No variable collections</p>- <button- data-test-id="variables-create-collection"- class="mt-2 cursor-pointer rounded bg-hover px-3 py-1.5 text-xs text-surface hover:bg-border"- @click="ctx.addCollection"- >- Create collection- </button>- </div>+ Create collection+ </button></div></div>+ </div>- <template v-else>- <TabsRoot v-model="ctx.activeCollectionId.value" class="flex flex-1 flex-col overflow-hidden">- <div class="flex shrink-0 items-center border-b border-border">- <TabsList class="flex flex-1 gap-0.5 overflow-x-auto px-3 py-1">- <template v-for="col in ctx.collections.value" :key="col.id">- <input- v-if="ctx.editingCollectionId.value === col.id"- :ref="(el) => ctx.setCollectionInputRef(col.id, el as HTMLInputElement | null)"- class="w-24 rounded border border-accent bg-input px-2 py-0.5 text-xs text-surface outline-none"- :value="col.name"- @blur="ctx.commitRenameCollection(col.id, $event.target as HTMLInputElement)"- @keydown.enter="($event.target as HTMLInputElement).blur()"- @keydown.escape="ctx.editingCollectionId.value = null"- />- <TabsTrigger- v-else- :value="col.id"- data-test-id="variables-collection-tab"- class="cursor-pointer rounded border-none px-2.5 py-1 text-xs whitespace-nowrap text-muted data-[state=active]:bg-hover data-[state=active]:text-surface"- @dblclick="ctx.startRenameCollection(col.id)"- >- {{ col.name }}- </TabsTrigger>- </template>- </TabsList>+ <template v-else>+ <TabsRoot+ v-model="ctx.activeCollectionId.value"+ class="flex flex-1 flex-col overflow-hidden"+ >+ <div class="flex shrink-0 items-center border-b border-border">+ <TabsList class="flex flex-1 gap-0.5 overflow-x-auto px-3 py-1">+ <template v-for="col in ctx.collections.value" :key="col.id">+ <input+ v-if="ctx.editingCollectionId.value === col.id"+ :ref="(el) => ctx.setCollectionInputRef(col.id, el as HTMLInputElement | null)"+ class="w-24 rounded border border-accent bg-input px-2 py-0.5 text-xs text-surface outline-none"+ :value="col.name"+ @blur="ctx.commitRenameCollection(col.id, $event.target as HTMLInputElement)"+ @keydown.enter="($event.target as HTMLInputElement).blur()"+ @keydown.escape="ctx.editingCollectionId.value = null"+ />+ <TabsTrigger+ v-else+ :value="col.id"+ data-test-id="variables-collection-tab"+ class="cursor-pointer rounded border-none px-2.5 py-1 text-xs whitespace-nowrap text-muted data-[state=active]:bg-hover data-[state=active]:text-surface"+ @dblclick="ctx.startRenameCollection(col.id)"+ >+ {{ col.name }}+ </TabsTrigger>+ </template>+ </TabsList>- <div class="flex items-center gap-1.5 px-3">- <div class="flex items-center gap-1 rounded border border-border px-2 py-0.5">- <icon-lucide-search class="size-3 text-muted" />- <input- v-model="ctx.searchTerm.value"- data-test-id="variables-search-input"- class="w-24 border-none bg-transparent text-xs text-surface outline-none placeholder:text-muted"- placeholder="Search"- />- </div>- <Tip label="Add collection">- <button- data-test-id="variables-add-collection"- class="flex size-6 cursor-pointer items-center justify-center rounded border-none bg-transparent text-muted hover:bg-hover hover:text-surface"- @click="ctx.addCollection"- >- <icon-lucide-folder-plus class="size-3.5" />- </button>- </Tip>- <DialogClose+ <div class="flex items-center gap-1.5 px-3">+ <div class="flex items-center gap-1 rounded border border-border px-2 py-0.5">+ <icon-lucide-search class="size-3 text-muted" />+ <input+ v-model="ctx.searchTerm.value"+ data-test-id="variables-search-input"+ class="w-24 border-none bg-transparent text-xs text-surface outline-none placeholder:text-muted"+ placeholder="Search"+ />+ </div>+ <Tip label="Add collection">+ <button+ data-test-id="variables-add-collection"class="flex size-6 cursor-pointer items-center justify-center rounded border-none bg-transparent text-muted hover:bg-hover hover:text-surface"+ @click="ctx.addCollection">- <icon-lucide-x class="size-4" />- </DialogClose>- </div>+ <icon-lucide-folder-plus class="size-3.5" />+ </button>+ </Tip>+ <DialogClose+ class="flex size-6 cursor-pointer items-center justify-center rounded border-none bg-transparent text-muted hover:bg-hover hover:text-surface"+ >+ <icon-lucide-x class="size-4" />+ </DialogClose></div>+ </div>- <TabsContent- v-for="col in ctx.collections.value"- :key="col.id"- :value="col.id"- class="flex flex-1 flex-col overflow-hidden outline-none"- >- <div class="flex-1 overflow-auto">- <table class="w-full border-collapse" :style="{ width: `${ctx.table.getCenterTotalSize()}px` }">- <thead class="sticky top-0 z-10 bg-panel">- <tr- v-for="headerGroup in ctx.table.getHeaderGroups()"- :key="headerGroup.id"- class="border-b border-border"+ <TabsContent+ v-for="col in ctx.collections.value"+ :key="col.id"+ :value="col.id"+ class="flex flex-1 flex-col overflow-hidden outline-none"+ >+ <div class="flex-1 overflow-auto">+ <table+ class="w-full border-collapse"+ :style="{ width: `${ctx.table.getCenterTotalSize()}px` }"+ >+ <thead class="sticky top-0 z-10 bg-panel">+ <tr+ v-for="headerGroup in ctx.table.getHeaderGroups()"+ :key="headerGroup.id"+ class="border-b border-border"+ >+ <th+ v-for="header in headerGroup.headers"+ :key="header.id"+ class="relative px-4 py-2 text-left text-[11px] font-medium text-muted"+ :style="{ width: `${header.getSize()}px` }">- <th- v-for="header in headerGroup.headers"- :key="header.id"- class="relative px-4 py-2 text-left text-[11px] font-medium text-muted"- :style="{ width: `${header.getSize()}px` }"- >- <FlexRender- v-if="!header.isPlaceholder"- :render="header.column.columnDef.header"- :props="header.getContext()"- />- <div- v-if="header.column.getCanResize()"- class="absolute top-0 right-0 h-full w-1 cursor-col-resize touch-none select-none"- :class="- header.column.getIsResizing()- ? 'bg-accent'- : 'bg-transparent hover:bg-border'- "- @mousedown="header.getResizeHandler()?.($event)"- @touchstart="header.getResizeHandler()?.($event)"- @dblclick="header.column.resetSize()"- />- </th>- </tr>- </thead>- <tbody>- <tr- v-for="row in ctx.table.getRowModel().rows"- :key="row.id"- data-test-id="variable-row"- class="group border-b border-border/30 hover:bg-hover/50"+ <FlexRender+ v-if="!header.isPlaceholder"+ :render="header.column.columnDef.header"+ :props="header.getContext()"+ />+ <div+ v-if="header.column.getCanResize()"+ class="absolute top-0 right-0 h-full w-1 cursor-col-resize touch-none select-none"+ :class="+ header.column.getIsResizing()+ ? 'bg-accent'+ : 'bg-transparent hover:bg-border'+ "+ @mousedown="header.getResizeHandler()?.($event)"+ @touchstart="header.getResizeHandler()?.($event)"+ @dblclick="header.column.resetSize()"+ />+ </th>+ </tr>+ </thead>+ <tbody>+ <tr+ v-for="row in ctx.table.getRowModel().rows"+ :key="row.id"+ data-test-id="variable-row"+ class="group border-b border-border/30 hover:bg-hover/50"+ >+ <td+ v-for="cell in row.getVisibleCells()"+ :key="cell.id"+ class="px-4 py-1.5"+ :style="{ width: `${cell.column.getSize()}px` }">- <td- v-for="cell in row.getVisibleCells()"- :key="cell.id"- class="px-4 py-1.5"- :style="{ width: `${cell.column.getSize()}px` }"- >- <FlexRender :render="cell.column.columnDef.cell" :props="cell.getContext()" />- </td>- </tr>- </tbody>- </table>- </div>+ <FlexRender+ :render="cell.column.columnDef.cell"+ :props="cell.getContext()"+ />+ </td>+ </tr>+ </tbody>+ </table>+ </div>- <button- data-test-id="variables-add-variable"- class="flex w-full shrink-0 cursor-pointer items-center gap-1.5 border-t border-border bg-transparent px-4 py-2 text-xs text-muted hover:bg-hover hover:text-surface"- @click="ctx.addVariable"- >- <icon-lucide-plus class="size-3.5" />- Create variable- </button>- </TabsContent>- </TabsRoot>- </template>- </DialogContent>- </DialogPortal>- </DialogRoot>+ <button+ data-test-id="variables-add-variable"+ class="flex w-full shrink-0 cursor-pointer items-center gap-1.5 border-t border-border bg-transparent px-4 py-2 text-xs text-muted hover:bg-hover hover:text-surface"+ @click="ctx.addVariable"+ >+ <icon-lucide-plus class="size-3.5" />+ Create variable+ </button>+ </TabsContent>+ </TabsRoot>+ </template>+ </DialogContent>+ </DialogPortal>+ </DialogRoot></template>diff --git a/src/components/properties/EffectsSection.vue b/src/components/properties/EffectsSection.vueindex a2cd488b0..778e7782b 100644--- a/src/components/properties/EffectsSection.vue+++ b/src/components/properties/EffectsSection.vue@@ -57,7 +57,9 @@ const effectsCtx = useEffectsControls()<AppSelect:model-value="effect.type":options="effectsCtx.effectOptions"- @update:model-value="effectsCtx.updateType(patch, activeNode, i, $event as Effect['type'])"+ @update:model-value="+ effectsCtx.updateType(patch, activeNode, i, $event as Effect['type'])+ "/><button@@ -80,7 +82,9 @@ const effectsCtx = useEffectsControls()effectsCtx.scrubEffect(activeNode, i, { offset: { ...effect.offset, x: $event } })"@commit="- effectsCtx.commitEffect(activeNode, i, { offset: { ...effect.offset, x: $event } })+ effectsCtx.commitEffect(activeNode, i, {+ offset: { ...effect.offset, x: $event }+ })"/><ScrubInput@@ -90,7 +94,9 @@ const effectsCtx = useEffectsControls()effectsCtx.scrubEffect(activeNode, i, { offset: { ...effect.offset, y: $event } })"@commit="- effectsCtx.commitEffect(activeNode, i, { offset: { ...effect.offset, y: $event } })+ effectsCtx.commitEffect(activeNode, i, {+ offset: { ...effect.offset, y: $event }+ })"/></div>@@ -112,7 +118,11 @@ const effectsCtx = useEffectsControls()</div><div class="flex items-center gap-1.5">- <ColorInput :color="effect.color" editable @update="effectsCtx.updateColor(patch, i, $event)" />+ <ColorInput+ :color="effect.color"+ editable+ @update="effectsCtx.updateColor(patch, i, $event)"+ /><ScrubInputclass="w-14"suffix="%"diff --git a/src/components/properties/FillSection.vue b/src/components/properties/FillSection.vueindex c236b3627..55109eb29 100644--- a/src/components/properties/FillSection.vue+++ b/src/components/properties/FillSection.vue@@ -96,7 +96,9 @@ const fillCtx = useFillControls()"><Tip label="Apply variable">- <PopoverTrigger class="cursor-pointer border-none bg-transparent p-0 text-muted hover:text-surface">+ <PopoverTrigger+ class="cursor-pointer border-none bg-transparent p-0 text-muted hover:text-surface"+ ><icon-lucide-link class="size-3.5" /></PopoverTrigger></Tip>@@ -130,10 +132,9 @@ const fillCtx = useFillControls()<divclass="size-3 shrink-0 rounded-sm border border-border":style="{- background:- fillCtx.store.resolveColorVariable(v.id)- ? colorToCSS(fillCtx.store.resolveColorVariable(v.id)!)- : '#000'+ background: fillCtx.store.resolveColorVariable(v.id)+ ? colorToCSS(fillCtx.store.resolveColorVariable(v.id)!)+ : '#000'}"/><span class="min-w-0 flex-1 truncate">{{ v.name }}</span>diff --git a/src/components/properties/LayoutSection.vue b/src/components/properties/LayoutSection.vueindex a58f89fa2..e197ae275 100644--- a/src/components/properties/LayoutSection.vue+++ b/src/components/properties/LayoutSection.vue@@ -99,7 +99,9 @@ import { sectionWrapper } from '@/components/ui/section'? 'border-accent bg-accent/10 text-accent': 'border-border text-muted hover:bg-hover hover:text-surface'"- @click="ctx.updateProp('layoutWrap', ctx.node.layoutWrap === 'WRAP' ? 'NO_WRAP' : 'WRAP')"+ @click="+ ctx.updateProp('layoutWrap', ctx.node.layoutWrap === 'WRAP' ? 'NO_WRAP' : 'WRAP')+ "><icon-lucide-wrap-text class="size-3.5" /></button>@@ -137,7 +139,9 @@ import { sectionWrapper } from '@/components/ui/section':suffix="track.sizing === 'FR' ? 'fr' : 'px'"@update:model-value="ctx.updateGridTrack(trackProp, i, { value: $event })"/>- <span v-else class="flex-1 px-1 text-xs text-muted">{{ ctx.trackLabel(track) }}</span>+ <span v-else class="flex-1 px-1 text-xs text-muted">{{+ ctx.trackLabel(track)+ }}</span><AppSelect:model-value="track.sizing":options="ctx.trackSizingOptions"@@ -210,7 +214,11 @@ import { sectionWrapper } from '@/components/ui/section'</div></template>- <template v-if="ctx.isGrid || (ctx.isFlex && (ctx.showIndividualPadding || !ctx.hasUniformPadding))">+ <template+ v-if="+ ctx.isGrid || (ctx.isFlex && (ctx.showIndividualPadding || !ctx.hasUniformPadding))+ "+ ><div class="mt-1.5 grid grid-cols-2 gap-1.5"><ScrubInputv-for="side in [diff --git a/src/components/properties/PositionSection.vue b/src/components/properties/PositionSection.vueindex 9241b1c94..7d84f2575 100644--- a/src/components/properties/PositionSection.vue+++ b/src/components/properties/PositionSection.vue@@ -8,7 +8,20 @@ import { PositionControlsRoot } from '@open-pencil/vue'<template><PositionControlsRoot- v-slot="{ active, isMulti, xValue, yValue, wValue, hValue, rotationValue, updateProp, commitProp, align, flip, rotate }"+ v-slot="{+ active,+ isMulti,+ xValue,+ yValue,+ wValue,+ hValue,+ rotationValue,+ updateProp,+ commitProp,+ align,+ flip,+ rotate+ }"><div v-if="active" data-test-id="position-section" :class="sectionWrapper()"><label class="mb-1.5 block text-[11px] text-muted">Position</label>diff --git a/src/components/properties/StrokeSection.vue b/src/components/properties/StrokeSection.vueindex 63f4f6985..67494a035 100644--- a/src/components/properties/StrokeSection.vue+++ b/src/components/properties/StrokeSection.vue@@ -69,7 +69,10 @@ const sideMenuCls = useMenuUI({<button :class="iconButton({ ui: { base: 'shrink-0' } })" @click="remove(i)">−</button></div>- <div v-if="!isMixed && activeNode && activeNode.strokes.length > 0" class="mt-1 flex items-center gap-1.5">+ <div+ v-if="!isMixed && activeNode && activeNode.strokes.length > 0"+ class="mt-1 flex items-center gap-1.5"+ ><AppSelectclass="w-[72px]":model-value="strokeCtx.currentAlign(activeNode)"@@ -165,7 +168,12 @@ const sideMenuCls = useMenuUI({</div><div- v-if="!isMixed && activeNode && activeNode.strokes.length > 0 && activeNode.independentStrokeWeights"+ v-if="+ !isMixed &&+ activeNode &&+ activeNode.strokes.length > 0 &&+ activeNode.independentStrokeWeights+ "class="mt-1.5 grid grid-cols-2 gap-1.5"><ScrubInputdiff --git a/src/components/properties/TypographySection.vue b/src/components/properties/TypographySection.vueindex 726a0a423..7dea715f0 100644--- a/src/components/properties/TypographySection.vue+++ b/src/components/properties/TypographySection.vue@@ -17,7 +17,11 @@ import { loadFont } from '@/engine/fonts'<label class="mb-1.5 block text-[11px] text-muted">Typography</label><div class="mb-1.5 flex items-center gap-1.5">- <FontPicker class="min-w-0 flex-1" :model-value="ctx.node.value.fontFamily" @select="ctx.setFamily" />+ <FontPicker+ class="min-w-0 flex-1"+ :model-value="ctx.node.value.fontFamily"+ @select="ctx.setFamily"+ /><Tipv-if="ctx.hasMissingFonts.value":label="@@ -53,7 +57,9 @@ import { loadFont } from '@/engine/fonts'<div class="mb-1.5 flex gap-1.5"><ScrubInputclass="flex-1"- :model-value="ctx.node.value.lineHeight ?? Math.round((ctx.node.value.fontSize || 14) * 1.2)"+ :model-value="+ ctx.node.value.lineHeight ?? Math.round((ctx.node.value.fontSize || 14) * 1.2)+ ":min="0"@update:model-value="ctx.updateProp('lineHeight', $event)"@commit="(v: number, p: number) => ctx.commitProp('lineHeight', v, p)"