@lamsa/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,1330 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from "commander";
3
+ import { A as recordActivity, B as validateProject, C as loadComments, D as moveNode, E as loadTokens, F as stableStringify, G as createOutput, H as designFileJsonSchema, I as summarize$1, K as formatIssue, L as toRepoPath, M as replyToComment, N as resolveComment, O as readDesignFile, P as saveDesignFile, R as treeLines, S as listDesignFiles, T as loadProject, U as CliError, V as writeFileAtomic, W as ExitCode, _ as fontSetup, a as resolveRoot, b as isDesignFile, c as addTree, d as commentAuthor, f as deleteNodes, g as findProjectRoot, h as diffAgainstRef, i as readInput, j as reopenComment, k as readSession, l as allNodes, m as didYouMean, n as renderFrames, o as CONFIG_FILE, p as detectTokenSource, q as reportError, r as openWorkspace, s as addComment, u as buildChildIndex, v as formatDesignFile, w as loadConfig, x as isOpen, y as indexNodes, z as validateComments } from "./render-B5Kz3okC.js";
4
+ import { delimiter, join, relative, resolve } from "node:path";
5
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
6
+ import { execFileSync, spawn } from "node:child_process";
7
+ import { tmpdir } from "node:os";
8
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
9
+ import { fileURLToPath } from "node:url";
10
+ // src/run.ts
11
+ async function checkCommandResult(task, json) {
12
+ try {
13
+ process.exitCode = await task();
14
+ } catch (error) {
15
+ process.exitCode = reportError(error, json);
16
+ }
17
+ }
18
+ // src/commands/check.ts
19
+ async function validateCommand({ out, files }) {
20
+ const workspace = await openWorkspace();
21
+ const comments = await loadComments({
22
+ root: workspace.project.root,
23
+ config: workspace.project.config
24
+ });
25
+ const all = [
26
+ ...validateProject({
27
+ project: workspace.project,
28
+ tokens: workspace.tokens
29
+ }),
30
+ ...comments.issues,
31
+ ...validateComments({
32
+ threads: comments.threads,
33
+ nodes: allNodes(workspace.project)
34
+ })
35
+ ];
36
+ const wanted = new Set(files.map((f) => toRepoPath(workspace.project.root, f)));
37
+ const issues = wanted.size > 0 ? all.filter((i) => !i.file || wanted.has(i.file)) : all;
38
+ const counts = summarize$1(issues);
39
+ out.result({
40
+ ok: counts.errors === 0,
41
+ ...counts,
42
+ files: workspace.project.files.size,
43
+ issues
44
+ }, () => {
45
+ const lines = issues.map(formatIssue);
46
+ lines.push(counts.errors === 0 ? `valid · ${workspace.project.files.size} file(s)${counts.warnings ? ` · ${counts.warnings} warning(s)` : ""}` : `${counts.errors} error(s), ${counts.warnings} warning(s)`);
47
+ return lines.join("\n");
48
+ });
49
+ return counts.errors === 0 ? ExitCode.ok : ExitCode.invalid;
50
+ }
51
+ async function fmtCommand({ out, files, fix, check }) {
52
+ const root = resolveRoot();
53
+ const config = await loadConfig(root);
54
+ const paths = files.length > 0 ? files.map((f) => toRepoPath(root, f)) : await listDesignFiles(root, config);
55
+ const loaded = await Promise.all(paths.map((p) => readDesignFile(root, p)));
56
+ const taken = /* @__PURE__ */ new Set();
57
+ for (const file of loaded) if (isDesignFile(file.raw)) for (const id of Object.keys(file.raw.nodes)) taken.add(id);
58
+ const report = [];
59
+ for (const file of loaded) {
60
+ if (file.parseError) {
61
+ report.push({
62
+ file: file.path,
63
+ changed: false,
64
+ changes: [],
65
+ error: `not valid JSON: ${file.parseError}`
66
+ });
67
+ continue;
68
+ }
69
+ const { file: formatted, changes } = formatDesignFile({
70
+ raw: file.raw,
71
+ fix,
72
+ takenIds: taken
73
+ });
74
+ const before = stableStringify(file.raw);
75
+ const after = stableStringify(formatted);
76
+ const original = JSON.stringify(file.raw, null, 2) + "\n";
77
+ const changed = before !== after || original !== after;
78
+ if (changed && !check) await saveDesignFile(root, file.path, formatted);
79
+ report.push({
80
+ file: file.path,
81
+ changed,
82
+ changes: changed && changes.length === 0 ? ["sorted keys"] : changes
83
+ });
84
+ }
85
+ const failed = report.filter((r) => r.error);
86
+ const changed = report.filter((r) => r.changed);
87
+ out.result({
88
+ ok: failed.length === 0 && (!check || changed.length === 0),
89
+ check,
90
+ files: report
91
+ }, () => [...report.flatMap((r) => r.error ? [`error ${r.file}: ${r.error}`] : r.changed ? [`${check ? "would format" : "formatted"} ${r.file}`, ...r.changes.map((c) => ` - ${c}`)] : []), `${changed.length} of ${report.length} file(s) ${check ? "need formatting" : "changed"}`].join("\n"));
92
+ if (failed.length > 0) return ExitCode.invalid;
93
+ return check && changed.length > 0 ? ExitCode.invalid : ExitCode.ok;
94
+ }
95
+ // src/commands/comments.ts
96
+ function viewOf(thread, locations) {
97
+ const location = locations.get(thread.nodeId);
98
+ return {
99
+ ...thread,
100
+ open: isOpen(thread),
101
+ orphaned: !location,
102
+ node: location ? {
103
+ name: location.node.name,
104
+ type: location.node.type,
105
+ file: location.file
106
+ } : null
107
+ };
108
+ }
109
+ const when = (iso) => iso.slice(0, 16).replace("T", " ");
110
+ const line = (message, prefix) => `${prefix}${message.author} · ${when(message.createdAt)}: ${message.text}`;
111
+ const targetOf = (view) => view.node ? `on ${view.nodeId}${view.node.name ? ` ${JSON.stringify(view.node.name)}` : ""} (${view.node.file})` : `on ${view.nodeId} (deleted node)`;
112
+ function describe(view) {
113
+ const state = view.resolved ? `resolved by ${view.resolved.author}` : "open";
114
+ return [
115
+ `${view.id} · ${state} · ${targetOf(view)}`,
116
+ line(view, " "),
117
+ ...view.replies.map((reply) => line(reply, " ↳ "))
118
+ ].join("\n");
119
+ }
120
+ async function commentsContext() {
121
+ const root = resolveRoot();
122
+ return {
123
+ root,
124
+ location: {
125
+ root,
126
+ config: await loadConfig(root)
127
+ }
128
+ };
129
+ }
130
+ function requireNode({ locations, nodeId }) {
131
+ if (locations.has(nodeId)) return;
132
+ throw new CliError(`no node "${nodeId}"`, ExitCode.notFound, didYouMean(nodeId, locations.keys()) || "run `lamsa tree` to list node IDs", nodeId);
133
+ }
134
+ async function commentsCommand({ out, open, resolved, node }) {
135
+ if (open && resolved) throw new CliError("--open and --resolved can't be combined", ExitCode.usage, "pass one of them, or neither for every comment");
136
+ const { project } = await openWorkspace();
137
+ const { threads, issues } = await loadComments({
138
+ root: project.root,
139
+ config: project.config
140
+ });
141
+ const locations = indexNodes(project);
142
+ if (node && !threads.some((thread) => thread.nodeId === node)) requireNode({
143
+ locations,
144
+ nodeId: node
145
+ });
146
+ const views = threads.filter((thread) => (!node || thread.nodeId === node) && (!open || isOpen(thread)) && (!resolved || !isOpen(thread))).map((thread) => viewOf(thread, locations));
147
+ const counts = {
148
+ open: threads.filter(isOpen).length,
149
+ resolved: threads.filter((thread) => !isOpen(thread)).length
150
+ };
151
+ out.result({
152
+ ok: true,
153
+ counts,
154
+ comments: views,
155
+ issues
156
+ }, () => {
157
+ const which = open ? "open " : resolved ? "resolved " : "";
158
+ return [
159
+ views.length === 0 ? `no ${which}comments${node ? ` on ${node}` : ""}` : `${views.length} ${which}comment(s) · ${counts.open} open, ${counts.resolved} resolved in total`,
160
+ ...views.map(describe),
161
+ ...issues.map((issue) => `error ${issue.file}: ${issue.message}`)
162
+ ].join("\n\n");
163
+ });
164
+ return ExitCode.ok;
165
+ }
166
+ function parseOffset(value) {
167
+ if (value === void 0) return void 0;
168
+ const [x, y, ...rest] = value.split(",").map((part) => Number(part.trim()));
169
+ if (rest.length || x === void 0 || y === void 0 || !Number.isFinite(x) || !Number.isFinite(y)) throw new CliError(`--offset "${value}" isn't a point`, ExitCode.usage, "pass x,y in the node's own pixels, e.g. --offset 24,8");
170
+ return {
171
+ x,
172
+ y
173
+ };
174
+ }
175
+ async function commentAddCommand({ out, node, text, offset, author }) {
176
+ const point = parseOffset(offset);
177
+ const { project } = await openWorkspace();
178
+ const locations = indexNodes(project);
179
+ requireNode({
180
+ locations,
181
+ nodeId: node
182
+ });
183
+ const thread = await addComment({
184
+ location: {
185
+ root: project.root,
186
+ config: project.config
187
+ },
188
+ nodeId: node,
189
+ text,
190
+ offset: point,
191
+ author: commentAuthor({
192
+ root: project.root,
193
+ explicit: author
194
+ })
195
+ });
196
+ const view = viewOf(thread, locations);
197
+ out.result({
198
+ ok: true,
199
+ comment: view
200
+ }, () => `added comment ${thread.id} ${targetOf(view)}`);
201
+ return ExitCode.ok;
202
+ }
203
+ async function finish({ out, thread, verb }) {
204
+ const { project } = await openWorkspace();
205
+ const view = viewOf(thread, indexNodes(project));
206
+ out.result({
207
+ ok: true,
208
+ comment: view
209
+ }, () => `${verb} ${thread.id}\n${describe(view)}`);
210
+ return ExitCode.ok;
211
+ }
212
+ async function commentReplyCommand({ out, id, text, author }) {
213
+ const { root, location } = await commentsContext();
214
+ return finish({
215
+ out,
216
+ thread: await replyToComment({
217
+ location,
218
+ id,
219
+ text,
220
+ author: commentAuthor({
221
+ root,
222
+ explicit: author
223
+ })
224
+ }),
225
+ verb: "replied to"
226
+ });
227
+ }
228
+ async function commentResolveCommand({ out, id, reply, author }) {
229
+ const { root, location } = await commentsContext();
230
+ return finish({
231
+ out,
232
+ thread: await resolveComment({
233
+ location,
234
+ id,
235
+ reply,
236
+ author: commentAuthor({
237
+ root,
238
+ explicit: author
239
+ })
240
+ }),
241
+ verb: "resolved"
242
+ });
243
+ }
244
+ async function commentReopenCommand({ out, id }) {
245
+ const { location } = await commentsContext();
246
+ return finish({
247
+ out,
248
+ thread: await reopenComment({
249
+ location,
250
+ id
251
+ }),
252
+ verb: "reopened"
253
+ });
254
+ }
255
+ // src/commands/edit.ts
256
+ async function persist(project, paths) {
257
+ for (const path of new Set(paths)) {
258
+ const file = project.files.get(path);
259
+ if (file && isDesignFile(file.raw)) await saveDesignFile(project.root, path, file.raw);
260
+ }
261
+ }
262
+ /** Errors that touch the given nodes; edits are refused when they would introduce any. */
263
+ function issuesFor(workspace, ids) {
264
+ return validateProject({
265
+ project: workspace.project,
266
+ tokens: workspace.tokens
267
+ }).filter((issue) => issue.nodeId !== void 0 && ids.has(issue.nodeId));
268
+ }
269
+ function placementFrom({ workspace, parent, file, before, after }) {
270
+ if (before && after) throw new CliError("pass --before or --after, not both");
271
+ return {
272
+ parentId: parent,
273
+ file: file ? toRepoPath(workspace.project.root, file) : void 0,
274
+ before,
275
+ after
276
+ };
277
+ }
278
+ async function addCommand({ out, tree, parent, file, before, after, force }) {
279
+ const workspace = await openWorkspace();
280
+ const input = await readInput(tree);
281
+ if (!input || typeof input !== "object") throw new CliError("--tree must be a node object or an array of nodes");
282
+ if (file && !file.endsWith(".lamsa.json")) throw new CliError(`design files end in .lamsa.json: ${file}`, ExitCode.usage);
283
+ const placement = placementFrom({
284
+ workspace,
285
+ parent,
286
+ file,
287
+ before,
288
+ after
289
+ });
290
+ const result = addTree({
291
+ project: workspace.project,
292
+ input,
293
+ placement
294
+ });
295
+ const issues = issuesFor(workspace, new Set(result.created));
296
+ if (summarize$1(issues).errors > 0 && !force) {
297
+ out.result({
298
+ ok: false,
299
+ written: false,
300
+ issues
301
+ }, () => [...issues.map(formatIssue), "nothing written; fix the input or pass --force"].join("\n"));
302
+ return ExitCode.invalid;
303
+ }
304
+ await persist(workspace.project, [result.file]);
305
+ await recordActivity({
306
+ root: workspace.project.root,
307
+ activity: {
308
+ command: "add",
309
+ kind: "write",
310
+ ids: result.rootIds,
311
+ file: result.file
312
+ }
313
+ });
314
+ out.result({
315
+ ok: true,
316
+ written: true,
317
+ ...result,
318
+ issues
319
+ }, () => [
320
+ ...issues.map(formatIssue),
321
+ `added ${result.created.length} node(s) to ${result.file}`,
322
+ `top-level ids: ${result.rootIds.join(", ")}`
323
+ ].join("\n"));
324
+ return ExitCode.ok;
325
+ }
326
+ async function moveCommand({ out, id, parent, file, before, after }) {
327
+ const workspace = await openWorkspace();
328
+ if (!parent && !file && !before && !after) throw new CliError("say where to move it", ExitCode.usage, "pass --parent <frame>, --file <path> (top level), or --before/--after <sibling>");
329
+ let placement = placementFrom({
330
+ workspace,
331
+ parent,
332
+ file,
333
+ before,
334
+ after
335
+ });
336
+ if (!parent && !file && (before || after)) {
337
+ const sibling = Object.fromEntries([...workspace.project.files.values()].flatMap((f) => isDesignFile(f.raw) ? Object.entries(f.raw.nodes) : []))[before ?? after];
338
+ placement = {
339
+ ...placement,
340
+ parentId: sibling?.parentId
341
+ };
342
+ if (sibling && sibling.parentId === void 0) {
343
+ const owner = [...workspace.project.files.values()].find((f) => isDesignFile(f.raw) && (before ?? after) in f.raw.nodes);
344
+ placement.file = owner?.path;
345
+ }
346
+ }
347
+ const result = moveNode({
348
+ project: workspace.project,
349
+ id,
350
+ placement
351
+ });
352
+ await persist(workspace.project, [result.from, result.to]);
353
+ await recordActivity({
354
+ root: workspace.project.root,
355
+ activity: {
356
+ command: "move",
357
+ kind: "write",
358
+ ids: [id],
359
+ file: result.to
360
+ }
361
+ });
362
+ out.result({
363
+ ok: true,
364
+ ...result
365
+ }, () => `moved ${id} (${result.moved.length} node(s))${result.from !== result.to ? ` from ${result.from} to ${result.to}` : ` within ${result.to}`}`);
366
+ return ExitCode.ok;
367
+ }
368
+ async function splitCommand({ out, id, to }) {
369
+ if (!to.endsWith(".lamsa.json")) throw new CliError(`design files end in .lamsa.json: ${to}`);
370
+ return moveCommand({
371
+ out,
372
+ id,
373
+ file: to
374
+ });
375
+ }
376
+ async function deleteCommand({ out, ids }) {
377
+ const workspace = await openWorkspace();
378
+ const before = allNodes(workspace.project);
379
+ const result = deleteNodes({
380
+ project: workspace.project,
381
+ ids
382
+ });
383
+ await persist(workspace.project, result.files);
384
+ const parents = ids.flatMap((id) => before[id]?.parentId ?? []).filter((id) => !result.deleted.includes(id));
385
+ await recordActivity({
386
+ root: workspace.project.root,
387
+ activity: {
388
+ command: "delete",
389
+ kind: "write",
390
+ ids: parents,
391
+ file: result.files[0]
392
+ }
393
+ });
394
+ out.result({
395
+ ok: true,
396
+ ...result
397
+ }, () => [`deleted ${result.deleted.length} node(s)`, ...result.danglingInstances.length > 0 ? [`warning: instances now point at a deleted component: ${result.danglingInstances.join(", ")}`] : []].join("\n"));
398
+ return ExitCode.ok;
399
+ }
400
+ function defaultRenderDir(root) {
401
+ return join(root, ".lamsa", "render");
402
+ }
403
+ // src/commands/read.ts
404
+ /** Accepts node IDs, design file paths (→ their top-level nodes) and exact top-level names. */
405
+ function resolveTargets(project, targets) {
406
+ const nodes = allNodes(project);
407
+ const index = buildChildIndex(nodes);
408
+ if (targets.length === 0) return index.roots;
409
+ const result = [];
410
+ for (const target of targets) {
411
+ if (nodes[target]) {
412
+ result.push(target);
413
+ continue;
414
+ }
415
+ const path = toRepoPath(project.root, target);
416
+ const file = project.files.get(path);
417
+ if (file) {
418
+ if (isDesignFile(file.raw)) result.push(...index.roots.filter((id) => id in file.raw.nodes));
419
+ continue;
420
+ }
421
+ const named = index.roots.filter((id) => nodes[id]?.name === target);
422
+ if (named.length === 1) {
423
+ result.push(named[0]);
424
+ continue;
425
+ }
426
+ if (named.length > 1) throw new CliError(`"${target}" names ${named.length} top-level nodes: ${named.join(", ")}`, ExitCode.usage, "pass the node ID instead");
427
+ const candidates = [...Object.keys(nodes), ...index.roots.map((id) => nodes[id]?.name ?? "")].filter(Boolean);
428
+ throw new CliError(`no node, file or top-level name matches "${target}"`, ExitCode.notFound, didYouMean(target, candidates) || "run `lamsa tree` to list nodes");
429
+ }
430
+ return [...new Set(result)];
431
+ }
432
+ async function treeCommand({ out, targets, depth }) {
433
+ const { project } = await openWorkspace();
434
+ const nodes = allNodes(project);
435
+ const index = buildChildIndex(nodes);
436
+ const locations = indexNodes(project);
437
+ const from = resolveTargets(project, targets);
438
+ const lines = treeLines({
439
+ nodes,
440
+ index,
441
+ from,
442
+ maxDepth: depth ?? 1e400
443
+ });
444
+ if (targets.length > 0) await recordActivity({
445
+ root: project.root,
446
+ activity: {
447
+ command: "tree",
448
+ kind: "read",
449
+ ids: from,
450
+ file: from[0] ? locations.get(from[0])?.file : void 0
451
+ }
452
+ });
453
+ out.result({
454
+ ok: true,
455
+ nodes: lines.map((line) => ({
456
+ id: line.id,
457
+ depth: line.depth,
458
+ file: locations.get(line.id)?.file,
459
+ parentId: nodes[line.id]?.parentId,
460
+ ...nodes[line.id]
461
+ }))
462
+ }, () => {
463
+ let currentFile;
464
+ const text = [];
465
+ for (const line of lines) {
466
+ const file = locations.get(line.id)?.file;
467
+ if (line.depth === 0 && file !== currentFile) {
468
+ currentFile = file;
469
+ text.push(`${file}`);
470
+ }
471
+ text.push(`${" ".repeat(line.depth + 1)}${line.label}`);
472
+ }
473
+ return text.length > 0 ? text.join("\n") : "no nodes";
474
+ });
475
+ return ExitCode.ok;
476
+ }
477
+ async function tokensCommand({ out, kind }) {
478
+ const { tokens } = await openWorkspace();
479
+ const list = Object.values(tokens.tokens).filter((t) => !kind || t.kind === kind).sort((a, b) => a.path.localeCompare(b.path, void 0, { numeric: true }));
480
+ out.result({
481
+ ok: true,
482
+ adapter: tokens.adapter,
483
+ source: tokens.source,
484
+ tokens: list
485
+ }, () => {
486
+ if (list.length === 0) return `no tokens (adapter: ${tokens.adapter})`;
487
+ const width = Math.max(...list.map((t) => t.path.length)) + 2;
488
+ return [`${tokens.adapter}${tokens.source ? ` · ${tokens.source}` : ""} · ${list.length} token(s) · use as "{path}"`, ...list.map((t) => ` ${`{${t.path}}`.padEnd(width + 2)} ${t.values.light}${t.values.dark ? ` / dark: ${t.values.dark}` : ""}`)].join("\n");
489
+ });
490
+ return ExitCode.ok;
491
+ }
492
+ async function componentsCommand({ out, all }) {
493
+ const { project } = await openWorkspace();
494
+ const components = [...indexNodes(project).entries()].filter(([, { node }]) => node.type === "frame" && node.component && (all || !node.component.internal)).map(([id, { file, node }]) => ({
495
+ id,
496
+ file,
497
+ name: node.name,
498
+ description: node.type === "frame" ? node.component?.description : void 0,
499
+ internal: node.type === "frame" ? node.component?.internal ?? false : false,
500
+ props: node.type === "frame" ? node.component?.props ?? {} : {}
501
+ }));
502
+ out.result({
503
+ ok: true,
504
+ components
505
+ }, () => {
506
+ if (components.length === 0) return "no components; mark a frame with \"component\": {} to make one";
507
+ return components.map((c) => {
508
+ const props = Object.entries(c.props).map(([name, def]) => def.type === "enum" ? `${name}: ${def.options.join(" | ")} (default ${def.default})` : def.type === "boolean" ? `${name}: boolean (default ${def.default})` : `${name}: text → ${def.target}`);
509
+ return [`${c.id} ${JSON.stringify(c.name ?? "")} · ${c.file}${c.internal ? " · internal" : ""}`, ...props.map((p) => ` ${p}`)].join("\n");
510
+ }).join("\n");
511
+ });
512
+ return ExitCode.ok;
513
+ }
514
+ async function selectionCommand({ out }) {
515
+ const { project } = await openWorkspace();
516
+ const session = await readSession(project.root);
517
+ const nodes = allNodes(project);
518
+ const locations = indexNodes(project);
519
+ const selection = (session?.selection ?? []).map((id) => {
520
+ const baseId = id.split("/")[0];
521
+ return {
522
+ id,
523
+ file: locations.get(baseId)?.file,
524
+ node: nodes[baseId] ?? null
525
+ };
526
+ });
527
+ out.result({
528
+ ok: true,
529
+ editorOpen: !!session,
530
+ updatedAt: session?.updatedAt,
531
+ selection,
532
+ open: session?.open ?? null
533
+ }, () => {
534
+ if (!session) return "no editor session (the desktop app has not run in this repo)";
535
+ const files = session.open ? `open files: ${session.open.join(", ") || "none"}` : "open files: not chosen yet";
536
+ if (selection.length === 0) return `nothing selected\n${files}`;
537
+ return [...selection.map((s) => `${s.id}${s.node?.name ? ` ${JSON.stringify(s.node.name)}` : ""} (${s.node?.type ?? "missing"}) in ${s.file ?? "?"}`), files].join("\n");
538
+ });
539
+ return ExitCode.ok;
540
+ }
541
+ // src/commands/render.ts
542
+ function slug(text) {
543
+ return text.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
544
+ }
545
+ async function renderCommand({ out, targets, outDir, scale, mode, animate, state }) {
546
+ if (animate !== void 0 && (!Number.isInteger(animate) || animate < 2 || animate > 24)) throw new CliError("--animate takes a frame count from 2 to 24");
547
+ if (state !== void 0 && !/^[\w-]+$/.test(state)) throw new CliError(`--state must be a single word, not "${state}"`);
548
+ if (mode && mode !== "light" && mode !== "dark") throw new CliError(`--mode must be light or dark, not ${mode}`);
549
+ if (!Number.isFinite(scale) || scale <= 0 || scale > 4) throw new CliError("--scale must be between 0 and 4");
550
+ const workspace = await openWorkspace();
551
+ const ids = resolveTargets(workspace.project, targets);
552
+ if (ids.length === 0) throw new CliError("nothing to render", ExitCode.notFound, "add a top-level frame first");
553
+ if (targets.length > 0) {
554
+ const file = ids[0] ? indexNodes(workspace.project).get(ids[0])?.file : void 0;
555
+ await recordActivity({
556
+ root: workspace.project.root,
557
+ activity: {
558
+ command: "render",
559
+ kind: "read",
560
+ ids,
561
+ file
562
+ }
563
+ });
564
+ }
565
+ const nodes = allNodes(workspace.project);
566
+ const dir = outDir ? resolve(outDir) : defaultRenderDir(workspace.project.root);
567
+ mkdirSync(dir, { recursive: true });
568
+ const frames = await renderFrames({
569
+ workspace,
570
+ ids,
571
+ outDir: dir,
572
+ scale,
573
+ mode,
574
+ naming: (id) => `${[slug(nodes[id]?.name ?? ""), id].filter(Boolean).join("-")}${state ? `.${state}` : ""}${animate ? ".animate" : ""}${mode ? `.${mode}` : ""}.png`,
575
+ log: (message) => process.stderr.write(message + "\n"),
576
+ animate,
577
+ state
578
+ });
579
+ const root = workspace.project.root;
580
+ const shown = frames.map((f) => ({
581
+ ...f,
582
+ path: relative(root, f.path) || f.path
583
+ }));
584
+ out.result({
585
+ ok: true,
586
+ frames: shown
587
+ }, () => shown.map((f) => `${f.path} ${f.width}×${f.height} @${scale}x ${f.mode}` + (f.times ? `\n moments: ${f.times.map((t) => `${t}ms`).join(", ")}` : "") + (f.missingTokens.length ? `\n missing tokens: ${f.missingTokens.join(", ")}` : "") + (f.missingIcons.length ? `\n missing icons: ${f.missingIcons.join(", ")}` : "")).join("\n"));
588
+ return ExitCode.ok;
589
+ }
590
+ // src/commands/diff-page.ts
591
+ const escapeHtml = (text) => text.replace(/[&<>"']/g, (c) => ({
592
+ "&": "&amp;",
593
+ "<": "&lt;",
594
+ ">": "&gt;",
595
+ "\"": "&quot;",
596
+ "'": "&#39;"
597
+ })[c]);
598
+ const layerName = (change) => change.name ?? (change.text !== void 0 ? JSON.stringify(change.text) : `${change.type} ${change.id}`);
599
+ function detail({ change, input }) {
600
+ if (change.kind !== "changed") return change.type;
601
+ return change.values.map((value) => input.describe({
602
+ value,
603
+ names: input.names
604
+ })).join(" · ");
605
+ }
606
+ /** Changes worth listing under a screen: its layers, plus the screen frame itself when it changed. */
607
+ const listed = (screen) => screen.changes.filter((change) => change.id !== screen.id || change.kind === "changed");
608
+ const groups = (screens) => ({
609
+ changed: screens.filter((screen) => screen.kind === "changed" && screen.visible !== false),
610
+ invisible: screens.filter((screen) => screen.kind === "changed" && screen.visible === false),
611
+ added: screens.filter((screen) => screen.kind === "added"),
612
+ removed: screens.filter((screen) => screen.kind === "removed")
613
+ });
614
+ function summaryLine({ diff, screens }) {
615
+ const { changed, invisible, added, removed } = groups(screens);
616
+ return [
617
+ `${changed.length} changed`,
618
+ added.length ? `${added.length} new` : "",
619
+ removed.length ? `${removed.length} removed` : "",
620
+ invisible.length ? `${invisible.length} with no visible change` : "",
621
+ diff.repositioned.length ? `${diff.repositioned.length} moved on the canvas` : ""
622
+ ].filter(Boolean).join(" · ").concat(` · ${diff.changes.length} layer change${diff.changes.length === 1 ? "" : "s"}`);
623
+ }
624
+ function diffPage(input) {
625
+ const { diff, screens, colors } = input;
626
+ const { changed, invisible, added, removed } = groups(screens);
627
+ const symbol = {
628
+ added: "+",
629
+ removed: "−",
630
+ changed: "~"
631
+ };
632
+ const changeRows = (screen) => listed(screen).map((change) => `<li class="${change.kind}"><span class="sym">${symbol[change.kind]}</span><b>${escapeHtml(layerName(change))}</b><span>${escapeHtml(detail({
633
+ change,
634
+ input
635
+ }))}</span></li>`).join("");
636
+ const card = (screen) => `
637
+ <section class="card" id="${escapeHtml(screen.id)}">
638
+ <header>
639
+ <h3>${escapeHtml(screen.name ?? screen.id)}</h3>
640
+ <span class="meta">${escapeHtml(screen.file)} · <code>${escapeHtml(screen.id)}</code>${screen.components.length ? ` · via ${screen.components.map((id) => escapeHtml(input.names(id))).join(", ")}` : ""}</span>
641
+ <div class="views">
642
+ <button class="on" data-view="side">Side by side</button><button data-view="slider">Slider</button>
643
+ <label><input type="checkbox" checked data-outlines> Outlines</label>
644
+ </div>
645
+ </header>
646
+ <div class="side">
647
+ <figure><figcaption>Before</figcaption>${image(screen, "before")}</figure>
648
+ <figure><figcaption>After</figcaption>${image(screen, "after")}</figure>
649
+ </div>
650
+ <div class="slider" hidden>
651
+ <div class="stack">${image(screen, "before")}<div class="top">${image(screen, "after")}</div></div>
652
+ <input type="range" min="0" max="100" value="50" aria-label="Before / after">
653
+ </div>
654
+ <ul class="changes">${changeRows(screen)}</ul>
655
+ </section>`;
656
+ const tile = (screen, side) => `
657
+ <figure class="tile"><div class="thumb">${image(screen, side)}</div><figcaption>${escapeHtml(screen.name ?? screen.id)}<span>${escapeHtml(screen.file)}</span></figcaption></figure>`;
658
+ return `<!doctype html>
659
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
660
+ <title>Design changes · ${escapeHtml(diff.base)} → ${escapeHtml(diff.head)}</title>
661
+ <style>
662
+ :root { --bg:#f6f5f1; --card:#fff; --ink:#1b1a17; --ink2:#65635c; --line:#e3e0d8; --checker:#eeece6;
663
+ --added:${colors.added}; --removed:${colors.removed}; --changed:${colors.changed}; color-scheme: light; }
664
+ @media (prefers-color-scheme: dark) { :root { --bg:#151513; --card:#1e1e1b; --ink:#eceae4; --ink2:#a19e95; --line:#34332f; --checker:#262622; color-scheme: dark; } }
665
+ * { box-sizing: border-box; } [hidden] { display:none !important; }
666
+ body { margin:0; background:var(--bg); color:var(--ink); font:14px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }
667
+ main { max-width:1280px; margin:0 auto; padding:32px 24px 64px; }
668
+ h1 { font-size:22px; margin:0 0 4px; } h2 { font-size:15px; margin:40px 0 12px; color:var(--ink2); font-weight:600; }
669
+ .sub { color:var(--ink2); margin:0; } code { font:12px ui-monospace, monospace; }
670
+ .legend { display:flex; gap:16px; margin-top:12px; color:var(--ink2); font-size:13px; flex-wrap:wrap; }
671
+ .legend span::before { content:""; display:inline-block; width:10px; height:10px; border-radius:3px; margin-right:6px; vertical-align:-1px; border:2px solid var(--c); background:color-mix(in srgb, var(--c) 15%, transparent); }
672
+ .card { background:var(--card); border:1px solid var(--line); border-radius:12px; padding:16px; margin-bottom:20px; }
673
+ .card header { display:flex; align-items:baseline; gap:12px; flex-wrap:wrap; margin-bottom:12px; }
674
+ .card h3 { margin:0; font-size:16px; } .meta { color:var(--ink2); font-size:12px; }
675
+ .views { margin-left:auto; display:flex; gap:4px; align-items:center; }
676
+ .views button { font:inherit; font-size:12px; border:1px solid var(--line); background:transparent; color:var(--ink2); padding:3px 10px; border-radius:6px; cursor:pointer; }
677
+ .views button.on { background:var(--ink); color:var(--card); border-color:var(--ink); }
678
+ .views label { font-size:12px; color:var(--ink2); margin-left:8px; display:flex; gap:4px; align-items:center; }
679
+ .side { display:grid; grid-template-columns:1fr 1fr; gap:12px; }
680
+ figure { margin:0; min-width:0; } figcaption { font-size:12px; color:var(--ink2); margin-bottom:6px; }
681
+ .side img, .stack img { display:block; max-width:100%; min-width:0; height:auto; }
682
+ .tile img { width:auto !important; }
683
+ .frame { background:repeating-conic-gradient(var(--checker) 0 25%, transparent 0 50%) 0 0/16px 16px; border-radius:6px; padding:8px; display:flex; justify-content:center; align-items:flex-start; justify-content:flex-start; min-width:0; overflow:hidden; }
684
+ .frame img.plain { display:none; } .no-outlines .frame img.plain { display:block; } .no-outlines .frame img.marked { display:none; }
685
+ .slider .stack { position:relative; max-width:900px; margin:0 auto; } .slider .stack .frame { padding:0; }
686
+ .slider .top { position:absolute; inset:0; clip-path:inset(0 0 0 var(--split, 50%)); }
687
+ .slider .top::before { content:""; position:absolute; top:0; bottom:0; left:var(--split, 50%); width:2px; background:var(--ink); z-index:1; }
688
+ .slider input { display:block; width:100%; max-width:900px; margin:10px auto 0; }
689
+ .changes { list-style:none; margin:14px 0 0; padding:12px 0 0; border-top:1px solid var(--line); display:grid; gap:4px; font-size:13px; }
690
+ .changes li { display:flex; gap:8px; align-items:baseline; } .changes li span:last-child { color:var(--ink2); overflow-wrap:anywhere; }
691
+ .sym { width:14px; text-align:center; font-weight:700; } .added .sym { color:var(--added); } .removed .sym { color:var(--removed); } .changed .sym { color:var(--changed); }
692
+ .grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(220px, 1fr)); gap:16px; }
693
+ .tile { background:var(--card); border:1px solid var(--line); border-radius:10px; padding:10px; }
694
+ .tile .thumb { height:180px; display:flex; align-items:center; justify-content:center; overflow:hidden; background:repeating-conic-gradient(var(--checker) 0 25%, transparent 0 50%) 0 0/16px 16px; border-radius:6px; }
695
+ .tile img { max-width:100%; max-height:100%; } .tile figcaption { margin:8px 0 0; color:var(--ink); font-size:13px; display:flex; flex-direction:column; }
696
+ .tile figcaption span { color:var(--ink2); font-size:11px; } .tile.removed-tile img { opacity:.6; }
697
+ details { margin-top:8px; } summary { cursor:pointer; color:var(--ink2); }
698
+ table { border-collapse:collapse; width:100%; font-size:12px; margin-top:8px; } td, th { border-bottom:1px solid var(--line); padding:4px 8px; text-align:left; vertical-align:top; }
699
+ @media (max-width:720px) { .side { grid-template-columns:1fr; } .views { margin-left:0; } }
700
+ </style></head>
701
+ <body><main>
702
+ <h1>Design changes</h1>
703
+ <p class="sub"><code>${escapeHtml(diff.base)}</code> → <code>${escapeHtml(diff.head)}</code> · ${escapeHtml(summaryLine(input))}</p>
704
+ <div class="legend"><span style="--c:var(--added)">New layer</span><span style="--c:var(--changed)">Changed layer</span><span style="--c:var(--removed)">Removed layer</span></div>
705
+ ${changed.length ? `<h2>Changed screens</h2>${changed.map(card).join("")}` : diff.changes.length ? "" : "<p>No design changes.</p>"}
706
+ ${added.length ? `<h2>New screens</h2><div class="grid">${added.map((screen) => tile(screen, "after")).join("")}</div>` : ""}
707
+ ${removed.length ? `<h2>Removed screens</h2><div class="grid">${removed.map((screen) => tile(screen, "before").replace("class=\"tile\"", "class=\"tile removed-tile\"")).join("")}</div>` : ""}
708
+ ${invisible.length ? `<h2>No visible change</h2><p class="sub">These screens changed in the file, but render the same.</p>${invisible.map((screen) => `<details><summary>${escapeHtml(screen.name ?? screen.id)} <span class="meta">${escapeHtml(screen.file)}</span></summary><ul class="changes">${changeRows(screen)}</ul></details>`).join("")}` : ""}
709
+ <h2>All layer changes</h2>
710
+ <details><summary>${diff.changes.length} layer change${diff.changes.length === 1 ? "" : "s"}</summary><table><tr><th></th><th>Layer</th><th>File</th><th>Change</th></tr>
711
+ ${diff.changes.map((change) => `<tr class="${change.kind}"><td class="sym">${symbol[change.kind]}</td><td>${escapeHtml(layerName(change))} <code>${escapeHtml(change.id)}</code></td><td>${escapeHtml(change.file)}</td><td>${escapeHtml(detail({
712
+ change,
713
+ input
714
+ }))}</td></tr>`).join("\n")}
715
+ </table></details>
716
+ </main>
717
+ <script>
718
+ for (const card of document.querySelectorAll(".card")) {
719
+ const side = card.querySelector(".side"), slider = card.querySelector(".slider");
720
+ for (const button of card.querySelectorAll("[data-view]")) button.addEventListener("click", () => {
721
+ for (const other of card.querySelectorAll("[data-view]")) other.classList.toggle("on", other === button);
722
+ side.hidden = button.dataset.view !== "side"; slider.hidden = button.dataset.view !== "slider";
723
+ });
724
+ card.querySelector("[data-outlines]").addEventListener("change", (event) => card.classList.toggle("no-outlines", !event.target.checked));
725
+ const range = slider.querySelector("input");
726
+ range.addEventListener("input", () => slider.style.setProperty("--split", range.value + "%"));
727
+ }
728
+ <\/script>
729
+ </body></html>
730
+ `;
731
+ }
732
+ function image(screen, side) {
733
+ const plain = side === "before" ? screen.before : screen.after;
734
+ const marked = side === "before" ? screen.beforeMarked : screen.afterMarked;
735
+ if (!plain) return `<div class="frame"><span class="meta">${side === "before" ? "new" : "removed"}</span></div>`;
736
+ const size = side === "before" ? screen.beforeSize : screen.afterSize;
737
+ const widest = Math.max(screen.beforeSize?.width ?? 0, screen.afterSize?.width ?? 0);
738
+ const style = size && widest ? ` style="width:${(size.width / widest * 100).toFixed(2)}%"` : "";
739
+ const alt = `${screen.name ?? screen.id}, ${side}`;
740
+ if (!marked) return `<div class="frame"><img src="${escapeHtml(plain)}"${style} alt="${escapeHtml(alt)}"></div>`;
741
+ return `<div class="frame"><img class="marked" src="${escapeHtml(marked)}"${style} alt="${escapeHtml(alt)}, changes outlined"><img class="plain" src="${escapeHtml(plain)}"${style} alt="${escapeHtml(alt)}"></div>`;
742
+ }
743
+ function diffMarkdown(input) {
744
+ const { diff, screens, imageBaseUrl } = input;
745
+ const { changed, invisible, added, removed } = groups(screens);
746
+ const url = (file) => imageBaseUrl ? `${imageBaseUrl.replace(/\/$/, "")}/${file}` : file;
747
+ const img = (file, width) => file ? `<img src="${url(file)}" width="${width}">` : "";
748
+ const square = {
749
+ added: "🟩",
750
+ removed: "🟥",
751
+ changed: "🟧"
752
+ };
753
+ const lines = [
754
+ "<!-- lamsa-diff -->",
755
+ "## lamsa design changes",
756
+ ""
757
+ ];
758
+ if (diff.changes.length === 0) lines.push(`No design changes since \`${diff.base}\`.`);
759
+ else {
760
+ lines.push(`${summaryLine(input)} since \`${diff.base}\`.`, "", "🟩 new layer · 🟧 changed layer · 🟥 removed layer", "");
761
+ for (const screen of changed) {
762
+ lines.push(`### ${screen.name ?? screen.id}`, "", `<sub>${screen.file} · \`${screen.id}\`${screen.components.length ? ` · via ${screen.components.map(input.names).join(", ")}` : ""}</sub>`, "");
763
+ lines.push("| Before | After |", "|---|---|", `| ${img(screen.beforeMarked ?? screen.before, 400)} | ${img(screen.afterMarked ?? screen.after, 400)} |`, "");
764
+ for (const change of listed(screen)) lines.push(`- ${square[change.kind]} **${layerName(change)}** ${detail({
765
+ change,
766
+ input
767
+ })}`);
768
+ lines.push("");
769
+ }
770
+ const tiles = (list, side) => {
771
+ const rows = ["| | | |", "|---|---|---|"];
772
+ for (let i = 0; i < list.length; i += 3) {
773
+ const row = list.slice(i, i + 3);
774
+ rows.push(`| ${[
775
+ 0,
776
+ 1,
777
+ 2
778
+ ].map((n) => row[n] ? `${img(side === "before" ? row[n].before : row[n].after, 240)}<br>**${row[n].name ?? row[n].id}**` : "").join(" | ")} |`);
779
+ }
780
+ return rows;
781
+ };
782
+ if (added.length) lines.push(`### New screens (${added.length})`, "", ...tiles(added, "after"), "");
783
+ if (removed.length) lines.push(`### Removed screens (${removed.length})`, "", ...tiles(removed, "before"), "");
784
+ if (invisible.length) lines.push(`<sub>No visible change: ${invisible.map((screen) => screen.name ?? screen.id).join(", ")}</sub>`, "");
785
+ lines.push("<details><summary>All layer changes</summary>", "", "| | Layer | File | Change |", "|---|---|---|---|");
786
+ for (const change of diff.changes) lines.push(`| ${square[change.kind]} | ${layerName(change)} \`${change.id}\` | ${change.file} | ${detail({
787
+ change,
788
+ input
789
+ }).replace(/\|/g, "\\|")} |`);
790
+ lines.push("", "</details>");
791
+ }
792
+ lines.push("", "<sub>Made by `lamsa diff`. Designs are specs; the agent implements them in code.</sub>", "");
793
+ return lines.join("\n");
794
+ }
795
+ // src/commands/diff.ts
796
+ const MARK_COLORS = {
797
+ added: "#16a34a",
798
+ removed: "#dc2626",
799
+ changed: "#d97706"
800
+ };
801
+ const OUTPUT_FILE = /\.(before|after)(\.marked)?\.png$|^(index\.html|report\.md)$/;
802
+ function git(cwd, args) {
803
+ return execFileSync("git", args, {
804
+ cwd,
805
+ encoding: "utf8",
806
+ stdio: [
807
+ "ignore",
808
+ "pipe",
809
+ "pipe"
810
+ ]
811
+ }).trim();
812
+ }
813
+ async function workspaceAt(root) {
814
+ const project = await loadProject(root);
815
+ return {
816
+ project,
817
+ tokens: await loadTokens(root, project.config),
818
+ fonts: fontSetup(project.config)
819
+ };
820
+ }
821
+ /** Checks `ref` out into a temporary worktree, runs `use` on the project there, then removes it. */
822
+ async function atRef({ root, ref, use }) {
823
+ const top = git(root, ["rev-parse", "--show-toplevel"]);
824
+ const worktree = mkdtempSync(join(tmpdir(), "lamsa-ref-"));
825
+ try {
826
+ try {
827
+ git(top, [
828
+ "worktree",
829
+ "add",
830
+ "--detach",
831
+ "--force",
832
+ worktree,
833
+ ref
834
+ ]);
835
+ } catch (error) {
836
+ throw new CliError(`could not check out ${ref}: ${error.message}`, ExitCode.notFound, "fetch the ref first (e.g. git fetch origin main)");
837
+ }
838
+ const projectRoot = findProjectRoot(join(worktree, relative(top, root)));
839
+ return await use(projectRoot && existsSync(projectRoot) ? await workspaceAt(projectRoot) : void 0);
840
+ } finally {
841
+ try {
842
+ git(top, [
843
+ "worktree",
844
+ "remove",
845
+ "--force",
846
+ worktree
847
+ ]);
848
+ } catch {
849
+ rmSync(worktree, {
850
+ recursive: true,
851
+ force: true
852
+ });
853
+ }
854
+ }
855
+ }
856
+ const pngSize = (path) => {
857
+ const header = readFileSync(path).subarray(16, 24);
858
+ return {
859
+ width: header.readUInt32BE(0),
860
+ height: header.readUInt32BE(4)
861
+ };
862
+ };
863
+ const MAX_VALUE = 40;
864
+ function formatValue(value) {
865
+ if (value === void 0) return "unset";
866
+ const text = typeof value === "string" ? JSON.stringify(value) : JSON.stringify(value) ?? String(value);
867
+ return text.length > MAX_VALUE ? `${text.slice(0, 39)}…` : text;
868
+ }
869
+ /** One change in words: `width 342 → "100%"`, `moved into Form`, `reordered`. */
870
+ function describeValue({ value, names }) {
871
+ if (value.field === "index") return "reordered";
872
+ if (value.field === "parentId") return `moved into ${names(value.after)}`;
873
+ if (value.field === "file") return `moved to ${String(value.after)}`;
874
+ return `${value.field.replace(/^style\./, "")} ${formatValue(value.before)} → ${formatValue(value.after)}`;
875
+ }
876
+ const label = (node) => node.name ?? (node.text !== void 0 ? JSON.stringify(node.text) : node.type === "text" && node.content ? JSON.stringify(node.content.slice(0, 40)) : `${node.type} ${node.id}`);
877
+ function screenLines({ screen, names }) {
878
+ const symbol = {
879
+ added: "+",
880
+ removed: "-",
881
+ changed: "~"
882
+ };
883
+ const head = `${symbol[screen.kind]} ${screen.name ?? screen.id} ${screen.file}${screen.visible === false ? " (no visible change)" : ""}`;
884
+ if (screen.kind !== "changed") return [head];
885
+ const lines = [head];
886
+ const shown = screen.changes.filter((change) => change.id !== screen.id || change.kind === "changed");
887
+ for (const change of shown.slice(0, 12)) {
888
+ const detail = change.kind === "changed" ? change.values.map((value) => describeValue({
889
+ value,
890
+ names
891
+ })).join(" · ") : change.type;
892
+ lines.push(` ${symbol[change.kind]} ${label(change)} ${detail}`);
893
+ }
894
+ if (shown.length > 12) lines.push(` … ${shown.length - 12} more`);
895
+ if (screen.components.length) lines.push(` via ${screen.components.map(names).join(", ")}`);
896
+ return lines;
897
+ }
898
+ function summarize(diff) {
899
+ const count = (kind) => diff.screens.filter((screen) => screen.kind === kind).length;
900
+ const parts = [
901
+ `${count("changed")} changed`,
902
+ count("added") && `${count("added")} new`,
903
+ count("removed") && `${count("removed")} removed`
904
+ ].filter(Boolean);
905
+ const plural = (n, word) => `${word}${n === 1 ? "" : "s"}`;
906
+ return `${`${parts.join(" · ")} ${plural(diff.screens.length, "screen")}`}${diff.repositioned.length ? ` · ${diff.repositioned.length} moved on the canvas` : ""} · ${diff.changes.length} layer ${plural(diff.changes.length, "change")} (${diff.base} → ${diff.head})`;
907
+ }
908
+ function openInBrowser(path) {
909
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
910
+ spawn(command, [path], {
911
+ detached: true,
912
+ stdio: "ignore"
913
+ }).unref();
914
+ }
915
+ async function diffCommand({ out, base, head, only, render, outDir, open, imageBaseUrl, scale, exitCode }) {
916
+ const current = await openWorkspace();
917
+ const root = current.project.root;
918
+ let diff;
919
+ try {
920
+ diff = diffAgainstRef({
921
+ project: current.project,
922
+ ref: base,
923
+ head,
924
+ only
925
+ });
926
+ } catch (error) {
927
+ throw new CliError(error.message, ExitCode.notFound, "check the ref with `git log`, or fetch it first");
928
+ }
929
+ const after = allNodes(current.project);
930
+ const nameOf = (nodes) => (id) => {
931
+ const node = typeof id === "string" ? nodes[id] : void 0;
932
+ return node ? label({
933
+ ...node,
934
+ id
935
+ }) : String(id);
936
+ };
937
+ const screens = diff.screens.map((screen) => ({
938
+ ...screen,
939
+ changes: diff.changes.filter((change) => change.screen === screen.id)
940
+ }));
941
+ const dir = resolve(root, outDir);
942
+ if (render && screens.length > 0) {
943
+ mkdirSync(dir, { recursive: true });
944
+ for (const file of readdirSync(dir)) if (OUTPUT_FILE.test(file)) rmSync(join(dir, file));
945
+ const log = (message) => process.stderr.write(message + "\n");
946
+ const marksFor = (side) => Object.fromEntries(screens.filter((screen) => screen.kind === "changed").map((screen) => [screen.id, [{
947
+ ids: side === "before" ? screen.removed : screen.added,
948
+ color: side === "before" ? MARK_COLORS.removed : MARK_COLORS.added
949
+ }, {
950
+ ids: screen.changed,
951
+ color: MARK_COLORS.changed
952
+ }]]));
953
+ const draw = async ({ workspace, side }) => {
954
+ if (!workspace) return [];
955
+ const nodes = allNodes(workspace.project);
956
+ const ids = screens.filter((screen) => screen.kind !== (side === "before" ? "added" : "removed")).map((screen) => screen.id).filter((id) => nodes[id] && nodes[id].parentId === void 0);
957
+ if (!ids.length) return [];
958
+ return renderFrames({
959
+ workspace,
960
+ ids,
961
+ outDir: dir,
962
+ scale,
963
+ naming: (id) => `${id}.${side}.png`,
964
+ marks: marksFor(side),
965
+ markedNaming: (id) => `${id}.${side}.marked.png`,
966
+ log
967
+ });
968
+ };
969
+ const afterFrames = head ? await atRef({
970
+ root,
971
+ ref: head,
972
+ use: (workspace) => draw({
973
+ workspace,
974
+ side: "after"
975
+ })
976
+ }) : await draw({
977
+ workspace: current,
978
+ side: "after"
979
+ });
980
+ const beforeFrames = await atRef({
981
+ root,
982
+ ref: base,
983
+ use: (workspace) => draw({
984
+ workspace,
985
+ side: "before"
986
+ })
987
+ });
988
+ const fileName = (frame, marked) => {
989
+ const path = marked ? frame?.markedPath : frame?.path;
990
+ return path ? relative(dir, path) : void 0;
991
+ };
992
+ for (const screen of screens) {
993
+ const before = beforeFrames.find((frame) => frame.id === screen.id);
994
+ const afterFrame = afterFrames.find((frame) => frame.id === screen.id);
995
+ screen.before = fileName(before, false);
996
+ screen.after = fileName(afterFrame, false);
997
+ screen.beforeMarked = fileName(before, true);
998
+ screen.afterMarked = fileName(afterFrame, true);
999
+ screen.beforeSize = before && pngSize(before.path);
1000
+ screen.afterSize = afterFrame && pngSize(afterFrame.path);
1001
+ if (screen.kind === "changed" && before && afterFrame) screen.visible = !readFileSync(before.path).equals(readFileSync(afterFrame.path));
1002
+ }
1003
+ const page = {
1004
+ diff,
1005
+ screens,
1006
+ colors: MARK_COLORS,
1007
+ names: nameOf(after),
1008
+ describe: describeValue
1009
+ };
1010
+ writeFileSync(join(dir, "index.html"), diffPage(page));
1011
+ writeFileSync(join(dir, "report.md"), diffMarkdown({
1012
+ ...page,
1013
+ imageBaseUrl
1014
+ }));
1015
+ if (open) openInBrowser(join(dir, "index.html"));
1016
+ }
1017
+ const rendered = render && screens.length > 0;
1018
+ out.result({
1019
+ ok: true,
1020
+ base: diff.base,
1021
+ head: diff.head,
1022
+ changes: diff.changes,
1023
+ screens: screens.map(({ changes: _changes, ...screen }) => screen),
1024
+ affectedRoots: diff.affectedRoots,
1025
+ repositioned: diff.repositioned,
1026
+ ...rendered ? {
1027
+ outDir: dir,
1028
+ page: join(dir, "index.html"),
1029
+ report: join(dir, "report.md")
1030
+ } : {}
1031
+ }, () => {
1032
+ if (diff.changes.length === 0) return `no design changes (${diff.base} → ${diff.head})`;
1033
+ const names = nameOf(after);
1034
+ const ordered = [...screens].sort((a, b) => Number(a.visible === false) - Number(b.visible === false));
1035
+ const lines = [
1036
+ summarize(diff),
1037
+ "",
1038
+ ...ordered.flatMap((screen) => screenLines({
1039
+ screen,
1040
+ names
1041
+ }))
1042
+ ];
1043
+ if (diff.repositioned.length) lines.push(`moved on the canvas: ${diff.repositioned.map(names).join(", ")}`);
1044
+ if (rendered) lines.push("", `→ ${relative(process.cwd(), join(dir, "index.html")) || "index.html"}${open ? " (opened)" : ""}`);
1045
+ return lines.join("\n");
1046
+ });
1047
+ return exitCode && diff.changes.length > 0 ? ExitCode.invalid : ExitCode.ok;
1048
+ }
1049
+ // src/commands/setup.ts
1050
+ const AGENTS = [
1051
+ "claude",
1052
+ "codex",
1053
+ "cursor",
1054
+ "generic"
1055
+ ];
1056
+ const MARK_START = "<!-- lamsa:start -->";
1057
+ const MARK_END = "<!-- lamsa:end -->";
1058
+ function skillText() {
1059
+ return readFileSync(fileURLToPath(new URL("../skill/SKILL.md", import.meta.url)), "utf8");
1060
+ }
1061
+ const AGENTS_SECTION = `${MARK_START}
1062
+ ## Design files (lamsa)
1063
+
1064
+ UI designs live in \`*.lamsa.json\` files (see \`lamsa.config.json\`). They are specs: read the JSON and a render, then implement with this repo's own components and tokens.
1065
+
1066
+ - Discover: \`lamsa tokens\`, \`lamsa components\`, \`lamsa tree\`.
1067
+ - Change: \`lamsa add --tree\`, \`lamsa move\`, \`lamsa delete\`, or edit the JSON directly.
1068
+ - Check: \`lamsa validate\`, then \`lamsa render <id|file>\` and look at the PNG.
1069
+ - The user's selection in the editor: \`lamsa selection --json\`.
1070
+ - Comments people pinned to layers: \`lamsa comments --open --json\`; address each, then \`lamsa comments resolve <id> --reply "<what you did>"\`.
1071
+ - Every command takes \`--json\`. Full guide: \`lamsa skill\`.
1072
+ ${MARK_END}
1073
+ `;
1074
+ async function upsertSection(path) {
1075
+ if (!existsSync(path)) {
1076
+ await writeFile(path, `# Agent instructions\n\n${AGENTS_SECTION}`);
1077
+ return "created";
1078
+ }
1079
+ const text = await readFile(path, "utf8");
1080
+ const start = text.indexOf(MARK_START);
1081
+ const end = text.indexOf(MARK_END);
1082
+ const next = start !== -1 && end > start ? text.slice(0, start) + AGENTS_SECTION.trimEnd() + text.slice(end + 18) : `${text.trimEnd()}\n\n${AGENTS_SECTION}`;
1083
+ if (next === text) return "unchanged";
1084
+ await writeFile(path, next);
1085
+ return "updated";
1086
+ }
1087
+ async function ensureGitignore(root) {
1088
+ const path = join(root, ".gitignore");
1089
+ const text = existsSync(path) ? await readFile(path, "utf8") : "";
1090
+ if (text.split("\n").some((line) => line.trim() === ".lamsa/" || line.trim() === ".lamsa")) return false;
1091
+ await writeFile(path, `${text}${text && !text.endsWith("\n") ? "\n" : ""}.lamsa/\n`);
1092
+ return true;
1093
+ }
1094
+ async function initCommand({ out, agent, tokens, designs, force }) {
1095
+ if (!AGENTS.includes(agent)) throw new CliError(`unknown agent "${agent}"`, ExitCode.usage, `use one of ${AGENTS.join(", ")}`);
1096
+ const root = findProjectRoot(process.cwd()) ?? process.cwd();
1097
+ const actions = [];
1098
+ const configPath = join(root, CONFIG_FILE);
1099
+ if (!existsSync(configPath) || force) {
1100
+ const tokenPath = tokens ?? detectTokenSource(root);
1101
+ const config = {
1102
+ designs: [`${designs.replace(/\/+$/, "")}/**/*.lamsa.json`],
1103
+ tokens: tokenPath ? {
1104
+ adapter: "shadcn-tailwind4",
1105
+ path: tokenPath
1106
+ } : { adapter: "none" },
1107
+ assetsDir: `${designs.replace(/\/+$/, "")}/assets`,
1108
+ commentsDir: `${designs.replace(/\/+$/, "")}/comments`,
1109
+ agent: {
1110
+ command: agent === "generic" || agent === "cursor" ? "claude" : agent,
1111
+ args: []
1112
+ }
1113
+ };
1114
+ await writeFileAtomic(configPath, stableStringify(config));
1115
+ actions.push(`wrote ${CONFIG_FILE}${tokenPath ? ` (tokens from ${tokenPath})` : " (no token source found; tokens disabled)"}`);
1116
+ } else actions.push(`kept existing ${CONFIG_FILE}`);
1117
+ await mkdir(join(root, designs), { recursive: true });
1118
+ if (agent === "claude") {
1119
+ const skillPath = join(root, ".claude", "skills", "lamsa", "SKILL.md");
1120
+ await mkdir(join(root, ".claude", "skills", "lamsa"), { recursive: true });
1121
+ await writeFile(skillPath, skillText());
1122
+ actions.push("installed skill at .claude/skills/lamsa/SKILL.md");
1123
+ } else if (agent === "cursor") {
1124
+ await mkdir(join(root, ".cursor", "rules"), { recursive: true });
1125
+ await writeFile(join(root, ".cursor", "rules", "lamsa.mdc"), skillText());
1126
+ actions.push("installed rule at .cursor/rules/lamsa.mdc");
1127
+ }
1128
+ actions.push(`${await upsertSection(join(root, "AGENTS.md"))} lamsa section in AGENTS.md`);
1129
+ if (await ensureGitignore(root)) actions.push("added .lamsa/ to .gitignore");
1130
+ out.result({
1131
+ ok: true,
1132
+ root,
1133
+ agent,
1134
+ actions
1135
+ }, () => actions.join("\n"));
1136
+ return ExitCode.ok;
1137
+ }
1138
+ async function skillCommand({ out }) {
1139
+ const text = skillText();
1140
+ out.result({
1141
+ ok: true,
1142
+ skill: text
1143
+ }, () => text);
1144
+ return ExitCode.ok;
1145
+ }
1146
+ async function schemaCommand({ out }) {
1147
+ const schema = designFileJsonSchema();
1148
+ process.stdout.write(JSON.stringify(schema, null, 2) + "\n");
1149
+ return ExitCode.ok;
1150
+ }
1151
+ async function migrateCommand({ out }) {
1152
+ const report = [...(await loadProject(resolveRoot())).files.values()].map((file) => {
1153
+ const version = isDesignFile(file.raw) ? file.raw.version : void 0;
1154
+ return {
1155
+ file: file.path,
1156
+ version,
1157
+ status: version === 1 ? "current" : version && version > 1 ? "newer" : "unknown"
1158
+ };
1159
+ });
1160
+ const newer = report.filter((r) => r.status === "newer");
1161
+ out.result({
1162
+ ok: newer.length === 0,
1163
+ formatVersion: 1,
1164
+ files: report
1165
+ }, () => newer.length > 0 ? `${newer.length} file(s) are newer than this lamsa; upgrade lamsa` : `all ${report.length} file(s) are on format version 1; nothing to migrate`);
1166
+ return newer.length > 0 ? ExitCode.invalid : ExitCode.ok;
1167
+ }
1168
+ function findOnPath(command) {
1169
+ for (const dir of (process.env.PATH ?? "").split(delimiter)) {
1170
+ const candidate = join(dir, command);
1171
+ if (existsSync(candidate)) return candidate;
1172
+ }
1173
+ }
1174
+ async function openCommand({ out, file, select }) {
1175
+ const root = resolveRoot();
1176
+ const ids = [...new Set((select ?? []).map((id) => id.trim()).filter(Boolean))];
1177
+ if (ids.length) await checkNodesExist({
1178
+ root,
1179
+ ids
1180
+ });
1181
+ const app = process.env.LAMSA_DESKTOP_BIN ?? findOnPath("lamsa-desktop");
1182
+ if (!app) throw new CliError("the lamsa desktop app is not installed", ExitCode.notFound, "install it, or set LAMSA_DESKTOP_BIN; everything else works without it (use `lamsa render` to look at designs)");
1183
+ const args = [`--root=${root}`];
1184
+ if (file) args.push(`--file=${toRepoPath(root, file)}`);
1185
+ if (ids.length) args.push(`--select=${ids.join(",")}`);
1186
+ spawn(app, args, {
1187
+ detached: true,
1188
+ stdio: "ignore"
1189
+ }).unref();
1190
+ out.result({
1191
+ ok: true,
1192
+ app,
1193
+ args,
1194
+ select: ids
1195
+ }, () => `opened lamsa${file ? ` on ${file}` : ""}${ids.length ? ` with ${ids.join(", ")} selected` : ""}`);
1196
+ return ExitCode.ok;
1197
+ }
1198
+ async function checkNodesExist({ root, ids }) {
1199
+ const project = await loadProject(root);
1200
+ const nodes = allNodes(project);
1201
+ const missing = ids.filter((id) => !nodes[id.split("/")[0]]);
1202
+ if (missing.length === 0) return;
1203
+ throw new CliError(`no node with ID ${missing.join(", ")}`, ExitCode.notFound, missing.map((id) => didYouMean(id, Object.keys(nodes))).filter(Boolean).join("; ") || "run `lamsa tree` to list nodes");
1204
+ }
1205
+ // src/cli.ts
1206
+ const program = new Command().name("lamsa").description("Design files for apps, driven by your own coding agent. Every command is non-interactive.").version("0.1.0").option("--json", "machine-readable output").showHelpAfterError();
1207
+ const out = () => createOutput(Boolean(program.opts().json));
1208
+ const run = (task) => checkCommandResult(task, Boolean(program.opts().json));
1209
+ program.command("init").description("set up lamsa in this repo: config, agent skill, AGENTS.md section").option("--agent <name>", "claude | codex | cursor | generic", "claude").option("--tokens <path>", "token source CSS (default: detect globals.css)").option("--designs <dir>", "where design files live", "designs").option("--force", "overwrite an existing lamsa.config.json").option("--yes", "accepted for scripts; init never prompts").action((o) => run(() => initCommand({
1210
+ out: out(),
1211
+ agent: o.agent,
1212
+ tokens: o.tokens,
1213
+ designs: o.designs,
1214
+ force: !!o.force
1215
+ })));
1216
+ program.command("validate [files...]").description("check design files; exit 1 on errors").action((files) => run(() => validateCommand({
1217
+ out: out(),
1218
+ files
1219
+ })));
1220
+ program.command("fmt [files...]").description("normalise files: flatten nested children, fill order indexes, sort keys").option("--fix", "also remove orphaned nodes").option("--check", "report without writing; exit 1 if anything would change").action((files, o) => run(() => fmtCommand({
1221
+ out: out(),
1222
+ files,
1223
+ fix: !!o.fix,
1224
+ check: !!o.check
1225
+ })));
1226
+ program.command("tree [targets...]").description("show node structure with IDs (targets: node ID, file, or top-level name)").option("--depth <n>", "limit depth", (v) => Number.parseInt(v, 10)).action((targets, o) => run(() => treeCommand({
1227
+ out: out(),
1228
+ targets,
1229
+ depth: o.depth
1230
+ })));
1231
+ program.command("tokens").description("list design tokens read from the app's CSS").option("--kind <kind>", "color | radius | font | spacing | shadow | text | other").action((o) => run(() => tokensCommand({
1232
+ out: out(),
1233
+ kind: o.kind
1234
+ })));
1235
+ program.command("components").description("list components and their props").option("--all", "include internal components").action((o) => run(() => componentsCommand({
1236
+ out: out(),
1237
+ all: !!o.all
1238
+ })));
1239
+ program.command("add").description("insert nodes from nested JSON").requiredOption("--tree <json>", "node or array of nodes (inline JSON, a file path, or - for stdin)").option("--parent <id>", "frame to insert into").option("--file <path>", "design file for top-level nodes (created if missing)").option("--before <id>", "insert before this sibling").option("--after <id>", "insert after this sibling").option("--force", "write even if the result has validation errors").action((o) => run(() => addCommand({
1240
+ out: out(),
1241
+ tree: o.tree,
1242
+ parent: o.parent,
1243
+ file: o.file,
1244
+ before: o.before,
1245
+ after: o.after,
1246
+ force: !!o.force
1247
+ })));
1248
+ program.command("move <id>").description("reparent or reorder a node with its subtree").option("--parent <id>", "new parent frame").option("--file <path>", "make it top-level in this file").option("--before <id>", "place before this sibling").option("--after <id>", "place after this sibling").action((id, o) => run(() => moveCommand({
1249
+ out: out(),
1250
+ id,
1251
+ parent: o.parent,
1252
+ file: o.file,
1253
+ before: o.before,
1254
+ after: o.after
1255
+ })));
1256
+ program.command("split <id>").description("move a top-level node and its subtree into another file").requiredOption("--to <file>", "target design file").action((id, o) => run(() => splitCommand({
1257
+ out: out(),
1258
+ id,
1259
+ to: o.to
1260
+ })));
1261
+ program.command("delete <ids...>").description("remove nodes and their subtrees").action((ids) => run(() => deleteCommand({
1262
+ out: out(),
1263
+ ids
1264
+ })));
1265
+ program.command("render [targets...]").description("render top-level frames to PNG (default: all)").option("--out <dir>", "output directory (default .lamsa/render)").option("--scale <n>", "device scale factor", (v) => Number.parseFloat(v), 2).option("--mode <mode>", "force light or dark tokens").option("--animate [frames]", "capture the frame's motion as a strip of moments (default 6)", (v) => Number.parseInt(v, 10)).option("--state <state>", "render with every node in a state: hover, press, focus, or a data-state value its css styles").action((targets, o) => run(() => renderCommand({
1266
+ out: out(),
1267
+ targets,
1268
+ outDir: o.out,
1269
+ scale: o.scale,
1270
+ mode: o.mode,
1271
+ animate: o.animate === true ? 6 : o.animate,
1272
+ state: o.state
1273
+ })));
1274
+ program.command("diff [base] [head]").description("design changes from a git ref (default HEAD) to another ref or the working tree, rendered as before/after images with changed layers outlined").option("--text", "list the changes only, without rendering").option("--file <paths...>", "only changes in these design files or globs").option("--out <dir>", "where the images, index.html and report.md go", ".lamsa/diff").option("--open", "open the page in the browser").option("--image-base-url <url>", "prefix for image links in report.md (where the images will be hosted)").option("--scale <n>", "device scale factor", (v) => Number.parseFloat(v), 2).option("--exit-code", "exit with 1 when there are changes").action((base, head, o) => run(() => diffCommand({
1275
+ out: out(),
1276
+ base: base ?? "HEAD",
1277
+ head,
1278
+ only: o.file,
1279
+ render: !o.text,
1280
+ outDir: o.out,
1281
+ open: o.open === true,
1282
+ imageBaseUrl: o.imageBaseUrl,
1283
+ scale: o.scale,
1284
+ exitCode: o.exitCode === true
1285
+ })));
1286
+ program.command("selection").description("what the user has selected in the desktop editor").action(() => run(() => selectionCommand({ out: out() })));
1287
+ const joinText = (words) => words.join(" ");
1288
+ const comments = program.command("comments").alias("comment").description("comment threads pinned to layers: list them, or add, reply, resolve");
1289
+ comments.command("list", { isDefault: true }).description("list comment threads (the default)").option("--open", "only open threads").option("--resolved", "only resolved threads").option("--node <id>", "only threads pinned to this node").action((o) => run(() => commentsCommand({
1290
+ out: out(),
1291
+ open: !!o.open,
1292
+ resolved: !!o.resolved,
1293
+ node: o.node
1294
+ })));
1295
+ comments.command("add <text...>").description("pin a new comment to a node").requiredOption("--node <id>", "node to pin it to").option("--offset <x,y>", "point inside the node, in its own pixels (default: its top-right corner)").option("--author <name>", "who is commenting (default: LAMSA_AUTHOR, the agent, git user.name, the OS user)").action((text, o) => run(() => commentAddCommand({
1296
+ out: out(),
1297
+ node: o.node,
1298
+ text: joinText(text),
1299
+ offset: o.offset,
1300
+ author: o.author
1301
+ })));
1302
+ comments.command("reply <id> <text...>").description("reply to a comment thread").option("--author <name>", "who is replying").action((id, text, o) => run(() => commentReplyCommand({
1303
+ out: out(),
1304
+ id,
1305
+ text: joinText(text),
1306
+ author: o.author
1307
+ })));
1308
+ comments.command("resolve <id>").description("mark a thread resolved, optionally with a closing reply").option("--reply <text>", "say what you did").option("--author <name>", "who is resolving").action((id, o) => run(() => commentResolveCommand({
1309
+ out: out(),
1310
+ id,
1311
+ reply: o.reply,
1312
+ author: o.author
1313
+ })));
1314
+ comments.command("reopen <id>").description("reopen a resolved thread").action((id) => run(() => commentReopenCommand({
1315
+ out: out(),
1316
+ id
1317
+ })));
1318
+ program.command("open [file]").description("show a design in the desktop editor (optional; nothing else needs it)").option("--select <ids>", "nodes to select: comma-separated IDs; repeatable", (value, previous = []) => [...previous, ...value.split(",")]).action((file, o) => run(() => openCommand({
1319
+ out: out(),
1320
+ file,
1321
+ select: o.select
1322
+ })));
1323
+ program.command("migrate").description("upgrade design files to the current format version").action(() => run(() => migrateCommand({ out: out() })));
1324
+ program.command("schema").description("print the design file JSON Schema").action(() => run(() => schemaCommand({ out: out() })));
1325
+ program.command("skill").description("print the agent guide").action(() => run(() => skillCommand({ out: out() })));
1326
+ program.parseAsync(process.argv).catch((error) => {
1327
+ process.stderr.write(`lamsa: ${error.message}\n`);
1328
+ process.exit(2);
1329
+ });
1330
+ export {};