AI-native design editor. Open-source Figma alternative.
fix(CLI): give components asset keys before publishing a library (#1469)
Marcos Velásquez6c0491ad0f1f
diff --git a/changes/1469/fixed.md b/changes/1469/fixed.mdnew file mode 100644index 000000000..a83128a2d--- /dev/null+++ b/changes/1469/fixed.md@@ -0,0 +1 @@+- `openpencil libraries publish` gives a component without an asset key a valid one made from its name instead of failing, and keeps those keys in the `.fig` source with `--write`.diff --git a/packages/cli/src/commands/libraries.ts b/packages/cli/src/commands/libraries.tsindex abf7fb726..a1e857125 100644--- a/packages/cli/src/commands/libraries.ts+++ b/packages/cli/src/commands/libraries.ts@@ -1,9 +1,11 @@-import { resolve } from 'node:path'+import { extname, resolve } from 'node:path'import { defineCommand } from 'citty'-import { bold, fmtList, ok } from '#cli/format'-import { loadDocument, populateWholeDocument } from '#cli/headless'+import { ensureLibraryAssetKeys } from '@open-pencil/core/library'++import { bold, dim, fmtList, ok, printError } from '#cli/format'+import { loadDocument, populateWholeDocument, writeFigDocument } from '#cli/headless'import { FileSystemLibraryCatalog } from '#cli/library/catalog'const list = defineCommand({@@ -47,11 +49,24 @@ const publish = defineCommand({name: { type: 'string', description: 'Library name', required: true },description: { type: 'string', description: 'Revision description' },previous: { type: 'string', description: 'Expected previous revision ID' },+ write: {+ type: 'boolean',+ alias: 'w',+ description: 'Save the asset keys given to components without one back to the source .fig'+ },json: { type: 'boolean', description: 'Output as JSON' }},async run({ args }) {- const graph = await loadDocument(resolve(args.file))+ const file = resolve(args.file)+ if (args.write && extname(file).toLowerCase() !== '.fig') {+ printError('--write saves asset keys only to a .fig source')+ process.exit(1)+ }+ const graph = await loadDocument(file)populateWholeDocument(graph)+ // A component without an asset key takes the one its name gives; `--write` keeps it in the+ // source, so renaming the component later does not change its identity across revisions.+ const assigned = ensureLibraryAssetKeys(graph).filter((assignment) => !assignment.existing)const revision = await new FileSystemLibraryCatalog(args.root).publishRevision({libraryId: args.id,name: args.name,@@ -59,10 +74,22 @@ const publish = defineCommand({description: args.description,previousRevisionId: args.previous || null})+ // Only once published: a failed publication leaves the source as it was.+ if (args.write && assigned.length > 0) await writeFigDocument(graph, file)if (args.json) {console.log(JSON.stringify(revision.manifest, null, 2))return}+ if (assigned.length > 0) {+ const one = assigned.length === 1+ console.log(+ args.write+ ? ok(`Saved ${assigned.length} new asset key${one ? '' : 's'} to ${file}`)+ : dim(+ `${assigned.length} ${one ? 'component took an asset key from its name' : 'components took asset keys from their names'}; pass --write to keep ${one ? 'it' : 'them'} in ${file}`+ )+ )+ }console.log(ok(`Published ${revision.manifest.name} @ ${revision.manifest.revisionId}`))}})diff --git a/packages/cli/tests/commands/libraries.test.ts b/packages/cli/tests/commands/libraries.test.tsnew file mode 100644index 000000000..66c26090e--- /dev/null+++ b/packages/cli/tests/commands/libraries.test.ts@@ -0,0 +1,86 @@+import { describe, expect, setDefaultTimeout, test } from 'bun:test'+import { mkdtemp, readFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { CLI_ENTRY } from '#cli-tests/helpers/paths'+import * as v from 'valibot'++import { FileSystemLibraryCatalog } from '@open-pencil/cli/library'++setDefaultTimeout(60_000)++async function cli(args: string[]) {+ const proc = Bun.spawn([process.execPath, CLI_ENTRY, ...args], { stdout: 'pipe', stderr: 'pipe' })+ const [stdout, stderr] = await Promise.all([+ new Response(proc.stdout).text(),+ new Response(proc.stderr).text()+ ])+ return { stdout: stdout.trim(), stderr: stderr.trim(), exitCode: await proc.exited }+}++const librarySchema = v.object({ latestRevisionId: v.string() })++describe('libraries CLI', () => {+ test('publishes components that have no asset key yet, saving the keys it gives only with --write', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-libraries-cli-'))+ const authored = join(dir, 'library.pen')+ const source = join(dir, 'library.fig')+ const catalog = join(dir, 'catalog')+ await Bun.write(+ authored,+ JSON.stringify({+ version: '2.21',+ children: [{ id: 'button', type: 'frame', name: 'Primary Button', reusable: true }]+ })+ )+ const created = await cli(['convert', authored, '-o', source])+ expect(created.exitCode).toBe(0)++ const publish = (...extra: string[]) =>+ cli([+ 'libraries',+ 'publish',+ source,+ '--root',+ catalog,+ '--id',+ 'ds',+ '--name',+ 'DS',+ ...extra+ ])+ const latest = async () => {+ const listed = await cli(['libraries', 'list', '--root', catalog, '--json'])+ const [library] = v.parse(+ v.pipe(v.string(), v.parseJson(), v.array(librarySchema)),+ listed.stdout+ )+ return library?.latestRevisionId ?? ''+ }+ const authoredBytes = await readFile(source)++ const first = await publish()+ expect(first.exitCode).toBe(0)+ expect(first.stdout).toContain('1 component took an asset key from its name')+ expect(await readFile(source)).toEqual(authoredBytes)++ // A publication that fails leaves the source as it was, even with --write.+ const stale = await publish('--previous', 'stale', '--write')+ expect(stale.exitCode).not.toBe(0)+ expect(await readFile(source)).toEqual(authoredBytes)++ const saved = await publish('--previous', await latest(), '--write')+ expect(saved.exitCode).toBe(0)+ expect(saved.stdout).toContain('Saved 1 new asset key to')+ expect(await readFile(source)).not.toEqual(authoredBytes)++ // The next publication reads the key the source now keeps instead of giving a new one.+ const third = await publish('--previous', await latest())+ expect(third.exitCode).toBe(0)+ expect(third.stdout).not.toContain('asset key')++ const revision = await new FileSystemLibraryCatalog(catalog).getRevision('ds')+ expect(revision.manifest.assets.map((asset) => asset.key)).toEqual(['primary-button'])+ })+})diff --git a/packages/core/src/library/asset-keys.ts b/packages/core/src/library/asset-keys.tsindex 67c190c5f..2912c8f61 100644--- a/packages/core/src/library/asset-keys.ts+++ b/packages/core/src/library/asset-keys.ts@@ -8,12 +8,17 @@ export interface AssetKeyAssignment {existing: boolean}+/** The longest key a name gives, leaving room for the `-N` a namesake's key takes. */+const MAX_NAME_KEY_LENGTH = 240++/** A valid asset key from a component's name: it starts with a letter or digit. */function normalizeAssetKey(name: string): string {const normalized = name.trim().toLowerCase().replace(/[^a-z0-9._:/-]+/g, '-')- .replace(/^-+|-+$/g, '')+ .replace(/^[^a-z0-9]+|-+$/g, '')+ .slice(0, MAX_NAME_KEY_LENGTH)return normalized || 'component'}@@ -36,19 +41,34 @@ function publishedRoots(graph: SceneGraph, assetNodeIds?: string[]): SceneNode[]return publishableLibraryRoots(graph).filter((node) => selected.has(node.id))}+/**+ * The asset key a component already publishes under: its own key, or else the library key, publish+ * ID or file ID it was read with — the identity a revision gives the asset.+ */+export function existingAssetKey(node: SceneNode): string | null {+ return node.componentKey ?? node.sourceLibraryKey ?? node.publishId ?? node.source.id+}++/**+ * Gives each published component without an asset key one made from its name, distinct from every+ * key the document already uses; a component keeps the identity it already publishes under.+ */export function ensureLibraryAssetKeys(graph: SceneGraph,assetNodeIds?: string[]): AssetKeyAssignment[] {const roots = publishedRoots(graph, assetNodeIds)const used = new Set(- [...graph.getAllNodes()].flatMap((node) =>- node.componentKey && isValidLibraryAssetKey(node.componentKey) ? [node.componentKey] : []- )+ [...graph.getAllNodes()].flatMap((node) => {+ const key =+ node.type === 'COMPONENT' || node.type === 'COMPONENT_SET' ? existingAssetKey(node) : null+ return key && isValidLibraryAssetKey(key) ? [key] : []+ }))return roots.map((node) => {- if (node.componentKey && isValidLibraryAssetKey(node.componentKey)) {- return { nodeId: node.id, assetKey: node.componentKey, existing: true }+ const existing = existingAssetKey(node)+ if (existing && isValidLibraryAssetKey(existing)) {+ return { nodeId: node.id, assetKey: existing, existing: true }}const base = normalizeAssetKey(node.name)let assetKey = basediff --git a/packages/core/src/library/snapshot.ts b/packages/core/src/library/snapshot.tsindex ff474412d..a3be1ba19 100644--- a/packages/core/src/library/snapshot.ts+++ b/packages/core/src/library/snapshot.ts@@ -2,6 +2,7 @@ import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'import { cloneNodeProps } from '@open-pencil/scene-graph/copy'import { contentPluginData } from '@open-pencil/scene-graph/plugin-data'+import { existingAssetKey } from './asset-keys'import { remapCopiedReferences } from './copied-references'import { contentHash } from './hash'import { assertLibraryAssetKey } from './identity'@@ -21,7 +22,7 @@ const VOLATILE_NODE_FIELDS = new Set([])function assetKey(node: SceneNode): string {- const key = node.componentKey ?? node.sourceLibraryKey ?? node.publishId ?? node.source.id+ const key = existingAssetKey(node)if (!key) throw new Error(`Component ${node.name} has no stable library asset key`)assertLibraryAssetKey(key)return keydiff --git a/packages/core/tests/library/asset-keys.test.ts b/packages/core/tests/library/asset-keys.test.tsnew file mode 100644index 000000000..e1fdbaeea--- /dev/null+++ b/packages/core/tests/library/asset-keys.test.ts@@ -0,0 +1,34 @@+import { describe, expect, test } from 'bun:test'++import { ensureLibraryAssetKeys, isValidLibraryAssetKey } from '@open-pencil/core/library'+import { SceneGraph } from '@open-pencil/scene-graph'++describe('asset keys a library gives from component names', () => {+ test('are valid however the component is named, and distinct among namesakes', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ for (const name of ['.icon', '--', '★', 'x'.repeat(300), 'Button', 'Button'])+ graph.createNode('COMPONENT', page.id, { name })++ const keys = ensureLibraryAssetKeys(graph).map((assignment) => assignment.assetKey)++ expect(keys.every(isValidLibraryAssetKey)).toBe(true)+ expect(new Set(keys).size).toBe(keys.length)+ expect(keys.slice(0, 3)).toEqual(['icon', 'component', 'component-2'])+ })++ test('keeps the identity a component already publishes under', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const figma = graph.createNode('COMPONENT', page.id, { name: 'Chip', sourceLibraryKey: 'chip' })+ const named = graph.createNode('COMPONENT', page.id, { name: 'Chip' })++ const assignments = ensureLibraryAssetKeys(graph)++ expect(assignments).toEqual([+ { nodeId: figma.id, assetKey: 'chip', existing: true },+ { nodeId: named.id, assetKey: 'chip-2', existing: false }+ ])+ expect(graph.getNode(figma.id)?.componentKey).toBeNull()+ })+})