@lamsa/cli 0.0.0-stage → 0.1.1-rc.1
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/LICENSE +21 -0
- package/README.md +30 -2
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +1345 -0
- package/dist/index.d.ts +114 -0
- package/dist/index.js +1 -0
- package/dist/render-CiFXTSpf.js +2770 -0
- package/package.json +61 -4
- package/skill/SKILL.md +120 -0
|
@@ -0,0 +1,2770 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises";
|
|
4
|
+
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
5
|
+
import { randomBytes } from "node:crypto";
|
|
6
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
7
|
+
import { tmpdir, userInfo } from "node:os";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import { customAlphabet } from "nanoid";
|
|
10
|
+
import postcss from "postcss";
|
|
11
|
+
import { generateKeyBetween, generateNKeysBetween } from "fractional-indexing";
|
|
12
|
+
import { glob } from "tinyglobby";
|
|
13
|
+
import picomatch from "picomatch";
|
|
14
|
+
import { pathToFileURL } from "node:url";
|
|
15
|
+
import { chromium } from "playwright-core";
|
|
16
|
+
// src/output.ts
|
|
17
|
+
const ExitCode = {
|
|
18
|
+
ok: 0,
|
|
19
|
+
invalid: 1,
|
|
20
|
+
usage: 2,
|
|
21
|
+
notFound: 3,
|
|
22
|
+
renderFailed: 4
|
|
23
|
+
};
|
|
24
|
+
var CliError = class extends Error {
|
|
25
|
+
exitCode;
|
|
26
|
+
fix;
|
|
27
|
+
nodeId;
|
|
28
|
+
constructor(message, exitCode = ExitCode.usage, fix, nodeId) {
|
|
29
|
+
super(message);
|
|
30
|
+
this.exitCode = exitCode;
|
|
31
|
+
this.fix = fix;
|
|
32
|
+
this.nodeId = nodeId;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
function createOutput(json) {
|
|
36
|
+
return {
|
|
37
|
+
json,
|
|
38
|
+
result(data, human) {
|
|
39
|
+
if (json) process.stdout.write(JSON.stringify(data, null, 2) + "\n");
|
|
40
|
+
else {
|
|
41
|
+
const text = human();
|
|
42
|
+
if (text) process.stdout.write(text.endsWith("\n") ? text : text + "\n");
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function formatIssue(issue) {
|
|
48
|
+
const where = [issue.file, issue.nodeId].filter(Boolean).join(" ");
|
|
49
|
+
const fix = issue.fix ? `\n fix: ${issue.fix}` : "";
|
|
50
|
+
return `${issue.severity === "error" ? "error" : "warn "} ${where ? `${where}: ` : ""}${issue.message} [${issue.code}]${fix}`;
|
|
51
|
+
}
|
|
52
|
+
function reportError(error, json) {
|
|
53
|
+
const cli = error instanceof CliError ? error : error && typeof error === "object" && "fix" in error ? new CliError(error.message, error.notFound ? ExitCode.notFound : ExitCode.usage, error.fix, error.nodeId) : new CliError(error?.message ?? String(error), ExitCode.usage);
|
|
54
|
+
if (json) process.stdout.write(JSON.stringify({
|
|
55
|
+
ok: false,
|
|
56
|
+
error: {
|
|
57
|
+
message: cli.message,
|
|
58
|
+
fix: cli.fix,
|
|
59
|
+
nodeId: cli.nodeId
|
|
60
|
+
}
|
|
61
|
+
}, null, 2) + "\n");
|
|
62
|
+
else process.stderr.write(`lamsa: ${cli.message}\n${cli.fix ? ` fix: ${cli.fix}\n` : ""}`);
|
|
63
|
+
return cli.exitCode;
|
|
64
|
+
}
|
|
65
|
+
// ../schema/dist/index.js
|
|
66
|
+
const SCHEMA_URL = "https://lamsa.dev/schema/v1.json";
|
|
67
|
+
const nodeIdSchema = z.string().regex(/^[A-Za-z0-9_-]{1,64}$/, "node IDs use letters, digits, '_' and '-'");
|
|
68
|
+
const styleValueSchema = z.union([z.string(), z.number()]);
|
|
69
|
+
/**
|
|
70
|
+
* CSS declarations keyed by kebab-case property name. Unitless numbers mean px
|
|
71
|
+
* for length properties. Values may contain token references like `{color.primary}`.
|
|
72
|
+
*/
|
|
73
|
+
const styleSchema = z.record(z.string(), styleValueSchema);
|
|
74
|
+
/**
|
|
75
|
+
* Plain CSS for one node: declarations plus nested rules where `&` is the node,
|
|
76
|
+
* e.g. `transition: scale 150ms; &:hover { scale: 1.02 }`. Token references like
|
|
77
|
+
* `{color.primary}` work here too.
|
|
78
|
+
*/
|
|
79
|
+
const nodeCssSchema = z.string();
|
|
80
|
+
const nodePatchSchema = z.object({
|
|
81
|
+
style: styleSchema.optional(),
|
|
82
|
+
css: nodeCssSchema.optional(),
|
|
83
|
+
content: z.string().optional(),
|
|
84
|
+
src: z.string().optional(),
|
|
85
|
+
icon: z.string().optional(),
|
|
86
|
+
hidden: z.boolean().optional()
|
|
87
|
+
}).strict();
|
|
88
|
+
const patchMapSchema = z.record(nodeIdSchema, nodePatchSchema);
|
|
89
|
+
const propDefSchema = z.discriminatedUnion("type", [
|
|
90
|
+
z.object({
|
|
91
|
+
type: z.literal("enum"),
|
|
92
|
+
options: z.array(z.string()).min(1),
|
|
93
|
+
default: z.string(),
|
|
94
|
+
overrides: z.record(z.string(), patchMapSchema).optional()
|
|
95
|
+
}).strict(),
|
|
96
|
+
z.object({
|
|
97
|
+
type: z.literal("boolean"),
|
|
98
|
+
default: z.boolean(),
|
|
99
|
+
overrides: z.object({
|
|
100
|
+
true: patchMapSchema.optional(),
|
|
101
|
+
false: patchMapSchema.optional()
|
|
102
|
+
}).strict().optional()
|
|
103
|
+
}).strict(),
|
|
104
|
+
z.object({
|
|
105
|
+
type: z.literal("text"),
|
|
106
|
+
default: z.string(),
|
|
107
|
+
target: nodeIdSchema
|
|
108
|
+
}).strict()
|
|
109
|
+
]);
|
|
110
|
+
const componentDefSchema = z.object({
|
|
111
|
+
internal: z.boolean().optional(),
|
|
112
|
+
description: z.string().optional(),
|
|
113
|
+
props: z.record(z.string(), propDefSchema).optional()
|
|
114
|
+
}).strict();
|
|
115
|
+
const tokenModeSchema = z.enum(["light", "dark"]);
|
|
116
|
+
const baseNodeShape = {
|
|
117
|
+
name: z.string().optional(),
|
|
118
|
+
parentId: nodeIdSchema.optional(),
|
|
119
|
+
index: z.string().optional(),
|
|
120
|
+
x: z.number().optional(),
|
|
121
|
+
y: z.number().optional(),
|
|
122
|
+
hidden: z.boolean().optional(),
|
|
123
|
+
/** Locked in the editor: not selectable or movable on the canvas. Agents leave locked nodes alone unless asked. */
|
|
124
|
+
locked: z.boolean().optional(),
|
|
125
|
+
style: styleSchema.optional(),
|
|
126
|
+
css: nodeCssSchema.optional()
|
|
127
|
+
};
|
|
128
|
+
const frameNodeSchema = z.object({
|
|
129
|
+
...baseNodeShape,
|
|
130
|
+
type: z.literal("frame"),
|
|
131
|
+
mode: tokenModeSchema.optional(),
|
|
132
|
+
component: componentDefSchema.optional()
|
|
133
|
+
}).strict();
|
|
134
|
+
const textNodeSchema = z.object({
|
|
135
|
+
...baseNodeShape,
|
|
136
|
+
type: z.literal("text"),
|
|
137
|
+
content: z.string()
|
|
138
|
+
}).strict();
|
|
139
|
+
const imageNodeSchema = z.object({
|
|
140
|
+
...baseNodeShape,
|
|
141
|
+
type: z.literal("image"),
|
|
142
|
+
src: z.string(),
|
|
143
|
+
alt: z.string().optional()
|
|
144
|
+
}).strict();
|
|
145
|
+
const iconNodeSchema = z.object({
|
|
146
|
+
...baseNodeShape,
|
|
147
|
+
type: z.literal("icon"),
|
|
148
|
+
set: z.literal("lucide"),
|
|
149
|
+
icon: z.string()
|
|
150
|
+
}).strict();
|
|
151
|
+
const instanceNodeSchema = z.object({
|
|
152
|
+
...baseNodeShape,
|
|
153
|
+
type: z.literal("instance"),
|
|
154
|
+
componentId: nodeIdSchema,
|
|
155
|
+
props: z.record(z.string(), z.union([z.string(), z.boolean()])).optional(),
|
|
156
|
+
overrides: patchMapSchema.optional()
|
|
157
|
+
}).strict();
|
|
158
|
+
const nodeSchema = z.discriminatedUnion("type", [
|
|
159
|
+
frameNodeSchema,
|
|
160
|
+
textNodeSchema,
|
|
161
|
+
imageNodeSchema,
|
|
162
|
+
iconNodeSchema,
|
|
163
|
+
instanceNodeSchema
|
|
164
|
+
]);
|
|
165
|
+
const designFileSchema = z.object({
|
|
166
|
+
$schema: z.string().optional(),
|
|
167
|
+
version: z.number().int().positive(),
|
|
168
|
+
/** File-level CSS shared by every node in the file: `@keyframes` (and other at-rules) only. */
|
|
169
|
+
css: z.string().optional(),
|
|
170
|
+
nodes: z.record(nodeIdSchema, nodeSchema)
|
|
171
|
+
}).strict();
|
|
172
|
+
const configSchema = z.object({
|
|
173
|
+
$schema: z.string().optional(),
|
|
174
|
+
designs: z.array(z.string()).default(["designs/**/*.lamsa.json"]),
|
|
175
|
+
tokens: z.object({
|
|
176
|
+
adapter: z.enum(["shadcn-tailwind4", "none"]),
|
|
177
|
+
path: z.string().optional()
|
|
178
|
+
}).strict().default({ adapter: "none" }),
|
|
179
|
+
fonts: z.record(z.string(), z.union([z.object({ google: z.string() }).strict(), z.object({ files: z.array(z.string()).min(1) }).strict()])).default({}),
|
|
180
|
+
assetsDir: z.string().default("designs/assets"),
|
|
181
|
+
/** Where comment threads live, one JSON file per thread. Committed with the designs. */
|
|
182
|
+
commentsDir: z.string().default("designs/comments"),
|
|
183
|
+
agent: z.object({
|
|
184
|
+
command: z.string().default("claude"),
|
|
185
|
+
args: z.array(z.string()).default([])
|
|
186
|
+
}).strict().default({
|
|
187
|
+
command: "claude",
|
|
188
|
+
args: []
|
|
189
|
+
})
|
|
190
|
+
}).strict();
|
|
191
|
+
const commentMessageSchema = z.object({
|
|
192
|
+
author: z.string().min(1),
|
|
193
|
+
createdAt: z.iso.datetime({ offset: true }),
|
|
194
|
+
text: z.string().min(1)
|
|
195
|
+
}).strict();
|
|
196
|
+
/**
|
|
197
|
+
* One comment thread, stored as `<commentsDir>/<id>.json`. It pins to a node by ID; `offset` is a point inside the
|
|
198
|
+
* node's box in its own unscaled pixels (the top-right corner when missing).
|
|
199
|
+
*/
|
|
200
|
+
const commentThreadSchema = z.object({
|
|
201
|
+
version: z.number().int().positive(),
|
|
202
|
+
nodeId: nodeIdSchema,
|
|
203
|
+
offset: z.object({
|
|
204
|
+
x: z.number(),
|
|
205
|
+
y: z.number()
|
|
206
|
+
}).strict().optional(),
|
|
207
|
+
...commentMessageSchema.shape,
|
|
208
|
+
replies: z.array(commentMessageSchema).default([]),
|
|
209
|
+
resolved: z.object({
|
|
210
|
+
author: z.string().min(1),
|
|
211
|
+
at: z.iso.datetime({ offset: true })
|
|
212
|
+
}).strict().optional()
|
|
213
|
+
}).strict();
|
|
214
|
+
const emptyTokenSet = {
|
|
215
|
+
adapter: "none",
|
|
216
|
+
tokens: {},
|
|
217
|
+
css: ""
|
|
218
|
+
};
|
|
219
|
+
const TOKEN_REF$1 = /\{([A-Za-z0-9_][A-Za-z0-9_.\-]*)\}/g;
|
|
220
|
+
function tokenRefs(value) {
|
|
221
|
+
if (typeof value !== "string") return [];
|
|
222
|
+
return [...value.matchAll(TOKEN_REF$1)].map((match) => match[1]);
|
|
223
|
+
}
|
|
224
|
+
function resolveTokenRefs(value, tokens) {
|
|
225
|
+
const missing = [];
|
|
226
|
+
return {
|
|
227
|
+
css: value.replace(TOKEN_REF$1, (whole, path) => {
|
|
228
|
+
const token = tokens[path];
|
|
229
|
+
if (!token) {
|
|
230
|
+
missing.push(path);
|
|
231
|
+
return whole;
|
|
232
|
+
}
|
|
233
|
+
return token.css;
|
|
234
|
+
}),
|
|
235
|
+
missing
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
function designFileJsonSchema() {
|
|
239
|
+
return {
|
|
240
|
+
...z.toJSONSchema(designFileSchema),
|
|
241
|
+
$id: SCHEMA_URL,
|
|
242
|
+
title: "lamsa design file"
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
// ../core/dist/index.js
|
|
246
|
+
function sortValue(value) {
|
|
247
|
+
if (Array.isArray(value)) return value.map(sortValue);
|
|
248
|
+
if (value && typeof value === "object") {
|
|
249
|
+
const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
250
|
+
return Object.fromEntries(entries.map(([k, v]) => [k, sortValue(v)]));
|
|
251
|
+
}
|
|
252
|
+
return value;
|
|
253
|
+
}
|
|
254
|
+
/** Deterministic JSON: keys sorted at every level, 2-space indent, trailing newline. */
|
|
255
|
+
function stableStringify(value) {
|
|
256
|
+
return JSON.stringify(sortValue(value), null, 2) + "\n";
|
|
257
|
+
}
|
|
258
|
+
/** Write via temp file + rename so readers (the editor, other agents) never see a partial file. */
|
|
259
|
+
async function writeFileAtomic(path, contents) {
|
|
260
|
+
await mkdir(dirname(path), { recursive: true });
|
|
261
|
+
const temp = join(dirname(path), `.${basename(path)}.${randomBytes(4).toString("hex")}.tmp`);
|
|
262
|
+
await writeFile(temp, contents, "utf8");
|
|
263
|
+
await rename(temp, path);
|
|
264
|
+
}
|
|
265
|
+
/** The agent's latest CLI command, so the desktop editor can show where it is working. Newest entry wins. */
|
|
266
|
+
const ACTIVITY_FILE = ".lamsa/activity.json";
|
|
267
|
+
function agentName(env = process.env) {
|
|
268
|
+
const named = env.LAMSA_AGENT_NAME?.trim();
|
|
269
|
+
if (named) return named;
|
|
270
|
+
if (env.CLAUDECODE === "1") return "Claude";
|
|
271
|
+
return "Agent";
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Records the command in `.lamsa/activity.json`, but only in a project the editor has used (it creates `.lamsa/`),
|
|
275
|
+
* so plain CLI use, CI and read-only checkouts get no new files. Never throws: activity is a hint, not part of the command.
|
|
276
|
+
*/
|
|
277
|
+
async function recordActivity({ root, activity, env = process.env }) {
|
|
278
|
+
if (!existsSync(join(root, ".lamsa"))) return;
|
|
279
|
+
const entry = {
|
|
280
|
+
...activity,
|
|
281
|
+
ids: [...new Set(activity.ids)].slice(0, 50),
|
|
282
|
+
agent: agentName(env),
|
|
283
|
+
at: (/* @__PURE__ */ new Date()).toISOString()
|
|
284
|
+
};
|
|
285
|
+
try {
|
|
286
|
+
await writeFileAtomic(join(root, ACTIVITY_FILE), stableStringify(entry));
|
|
287
|
+
} catch {}
|
|
288
|
+
}
|
|
289
|
+
const generate = customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 8);
|
|
290
|
+
function newId(taken) {
|
|
291
|
+
for (;;) {
|
|
292
|
+
const id = generate();
|
|
293
|
+
if (!taken?.has(id)) return id;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
/** Node CSS is a rule body (declarations and nested rules), so it's parsed inside a wrapper rule. */
|
|
297
|
+
const WRAPPER = "__lamsa__";
|
|
298
|
+
/** Token references like `{color.primary}` would read as blocks, so they're swapped for a function call while parsing. */
|
|
299
|
+
const TOKEN_REF = /\{([A-Za-z0-9_][A-Za-z0-9_.\-]*)\}/g;
|
|
300
|
+
const protect = (css) => css.replace(TOKEN_REF, "lamsa-token($1)");
|
|
301
|
+
const unprotect = (css) => css.replace(/lamsa-token\(([A-Za-z0-9_.\-]+)\)/g, "{$1}");
|
|
302
|
+
function parseBody(css) {
|
|
303
|
+
return postcss.parse(`${WRAPPER}{${protect(css)}\n}`).first;
|
|
304
|
+
}
|
|
305
|
+
function oneLine(text) {
|
|
306
|
+
return text.replace(/\s+/g, " ").trim();
|
|
307
|
+
}
|
|
308
|
+
/** Splits a value on commas that aren't inside parentheses. */
|
|
309
|
+
function topLevelList(value) {
|
|
310
|
+
const parts = [];
|
|
311
|
+
let depth = 0;
|
|
312
|
+
let current = "";
|
|
313
|
+
for (const char of value) {
|
|
314
|
+
if (char === "(") depth++;
|
|
315
|
+
if (char === ")") depth--;
|
|
316
|
+
if (char === "," && depth === 0) {
|
|
317
|
+
parts.push(current.trim());
|
|
318
|
+
current = "";
|
|
319
|
+
} else current += char;
|
|
320
|
+
}
|
|
321
|
+
parts.push(current.trim());
|
|
322
|
+
return parts;
|
|
323
|
+
}
|
|
324
|
+
/** A long comma list (several transitions, shadows, animations) goes one item per line. */
|
|
325
|
+
function printValue(prop, value, indent) {
|
|
326
|
+
const list = topLevelList(oneLine(value));
|
|
327
|
+
if (list.length < 2 || prop.length + value.length < 60) return ` ${oneLine(value)}`;
|
|
328
|
+
return `\n${list.map((item) => `${indent} ${item}`).join(",\n")}`;
|
|
329
|
+
}
|
|
330
|
+
function print(nodes, depth) {
|
|
331
|
+
const indent = " ".repeat(depth);
|
|
332
|
+
const lines = [];
|
|
333
|
+
(nodes ?? []).forEach((node, i) => {
|
|
334
|
+
if ((node.type === "rule" || node.type === "atrule" && node.nodes) && i > 0) lines.push("");
|
|
335
|
+
if (node.type === "decl") lines.push(`${indent}${node.prop}:${printValue(node.prop, node.value, indent)}${node.important ? " !important" : ""};`);
|
|
336
|
+
else if (node.type === "comment") lines.push(`${indent}/* ${node.text.trim()} */`);
|
|
337
|
+
else if (node.type === "rule") lines.push(`${indent}${oneLine(node.selector).replace(/\s*,\s*/g, ", ")} {`, print(node.nodes, depth + 1), `${indent}}`);
|
|
338
|
+
else if (node.type === "atrule") {
|
|
339
|
+
const head = `${indent}@${node.name}${node.params ? ` ${oneLine(node.params)}` : ""}`;
|
|
340
|
+
if (node.nodes) lines.push(`${head} {`, print(node.nodes, depth + 1), `${indent}}`);
|
|
341
|
+
else lines.push(`${head};`);
|
|
342
|
+
}
|
|
343
|
+
});
|
|
344
|
+
return lines.filter((line, i, all) => !(line === "" && all[i + 1] === void 0)).join("\n");
|
|
345
|
+
}
|
|
346
|
+
function errorProblem(error) {
|
|
347
|
+
if (error instanceof postcss.CssSyntaxError) return {
|
|
348
|
+
message: error.reason,
|
|
349
|
+
line: error.line
|
|
350
|
+
};
|
|
351
|
+
return { message: String(error) };
|
|
352
|
+
}
|
|
353
|
+
/** Formats a node's CSS: one declaration per line, nested rules indented. Unparseable CSS comes back unchanged. */
|
|
354
|
+
function formatNodeCss(css) {
|
|
355
|
+
try {
|
|
356
|
+
return unprotect(print(parseBody(css).nodes, 0));
|
|
357
|
+
} catch {
|
|
358
|
+
return css;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
/** Formats file-level CSS (`@keyframes` blocks). Unparseable CSS comes back unchanged. */
|
|
362
|
+
function formatFileCss(css) {
|
|
363
|
+
try {
|
|
364
|
+
return unprotect(print(postcss.parse(protect(css)).nodes, 0));
|
|
365
|
+
} catch {
|
|
366
|
+
return css;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
/** Names of the `@keyframes` defined in a stylesheet. */
|
|
370
|
+
function keyframeNames(css) {
|
|
371
|
+
const names = [];
|
|
372
|
+
try {
|
|
373
|
+
postcss.parse(css).walkAtRules("keyframes", (rule) => {
|
|
374
|
+
names.push(rule.params.trim());
|
|
375
|
+
});
|
|
376
|
+
} catch {}
|
|
377
|
+
return names;
|
|
378
|
+
}
|
|
379
|
+
const ANIMATION_KEYWORDS = /* @__PURE__ */ new Set([
|
|
380
|
+
"none",
|
|
381
|
+
"infinite",
|
|
382
|
+
"normal",
|
|
383
|
+
"reverse",
|
|
384
|
+
"alternate",
|
|
385
|
+
"alternate-reverse",
|
|
386
|
+
"forwards",
|
|
387
|
+
"backwards",
|
|
388
|
+
"both",
|
|
389
|
+
"running",
|
|
390
|
+
"paused",
|
|
391
|
+
"ease",
|
|
392
|
+
"ease-in",
|
|
393
|
+
"ease-out",
|
|
394
|
+
"ease-in-out",
|
|
395
|
+
"linear",
|
|
396
|
+
"step-start",
|
|
397
|
+
"step-end",
|
|
398
|
+
"initial",
|
|
399
|
+
"inherit",
|
|
400
|
+
"unset",
|
|
401
|
+
"revert",
|
|
402
|
+
"revert-layer",
|
|
403
|
+
"auto"
|
|
404
|
+
]);
|
|
405
|
+
function namesInAnimation(value) {
|
|
406
|
+
if (/var\(/.test(value)) return [];
|
|
407
|
+
return value.replace(/[a-z-]+\([^()]*\)/gi, " ").split(",").flatMap((part) => part.trim().split(/\s+/)).filter((word) => word && !ANIMATION_KEYWORDS.has(word) && !/^-?[\d.]/.test(word));
|
|
408
|
+
}
|
|
409
|
+
/** Keyframe names a node's CSS uses in `animation` / `animation-name`. */
|
|
410
|
+
function animationNamesUsed(css) {
|
|
411
|
+
const names = /* @__PURE__ */ new Set();
|
|
412
|
+
try {
|
|
413
|
+
parseBody(css).walkDecls(/^animation(-name)?$/, (decl) => {
|
|
414
|
+
for (const name of namesInAnimation(decl.value)) names.add(name);
|
|
415
|
+
});
|
|
416
|
+
} catch {}
|
|
417
|
+
return [...names];
|
|
418
|
+
}
|
|
419
|
+
function checkNodeCss(css) {
|
|
420
|
+
let body;
|
|
421
|
+
try {
|
|
422
|
+
body = parseBody(css);
|
|
423
|
+
} catch (error) {
|
|
424
|
+
return [errorProblem(error)];
|
|
425
|
+
}
|
|
426
|
+
const problems = [];
|
|
427
|
+
body.walkAtRules("keyframes", (rule) => {
|
|
428
|
+
problems.push({
|
|
429
|
+
message: `@keyframes ${rule.params} can't be nested in a node; put it in the file's "css"`,
|
|
430
|
+
line: rule.source?.start?.line
|
|
431
|
+
});
|
|
432
|
+
});
|
|
433
|
+
return problems;
|
|
434
|
+
}
|
|
435
|
+
/** Page-transition rules (`::view-transition-old(card)`, `:active-view-transition-type(back) …`) style the whole document, so they live in file CSS. */
|
|
436
|
+
function isViewTransitionRule(rule) {
|
|
437
|
+
return rule.selectors.every((selector) => /view-transition/.test(selector));
|
|
438
|
+
}
|
|
439
|
+
function checkFileCss(css) {
|
|
440
|
+
let root;
|
|
441
|
+
try {
|
|
442
|
+
root = postcss.parse(protect(css));
|
|
443
|
+
} catch (error) {
|
|
444
|
+
return [errorProblem(error)];
|
|
445
|
+
}
|
|
446
|
+
const problems = [];
|
|
447
|
+
for (const node of root.nodes) if (node.type === "rule" && !isViewTransitionRule(node)) problems.push({
|
|
448
|
+
message: `"${oneLine(node.selector)}" is a style rule; file CSS is for @keyframes and ::view-transition-* rules, so put styles in the node's "css"`,
|
|
449
|
+
line: node.source?.start?.line
|
|
450
|
+
});
|
|
451
|
+
else if (node.type === "decl") problems.push({
|
|
452
|
+
message: `declaration "${node.prop}" outside a rule`,
|
|
453
|
+
line: node.source?.start?.line
|
|
454
|
+
});
|
|
455
|
+
return problems;
|
|
456
|
+
}
|
|
457
|
+
function keyBetween(before, after) {
|
|
458
|
+
return generateKeyBetween(before, after);
|
|
459
|
+
}
|
|
460
|
+
function keysBetween(before, after, count) {
|
|
461
|
+
return generateNKeysBetween(before, after, count);
|
|
462
|
+
}
|
|
463
|
+
function compareIndex(a, b) {
|
|
464
|
+
const left = a ?? "";
|
|
465
|
+
const right = b ?? "";
|
|
466
|
+
if (left === right) return 0;
|
|
467
|
+
return left < right ? -1 : 1;
|
|
468
|
+
}
|
|
469
|
+
function flattenNested({ input, parentId, before = null, after = null, taken }) {
|
|
470
|
+
const nodes = {};
|
|
471
|
+
const rootIds = [];
|
|
472
|
+
const visit = (list, parent, low, high, isRoot) => {
|
|
473
|
+
const keys = parent === void 0 && !isRoot ? [] : keysBetween(low, high, list.length);
|
|
474
|
+
list.forEach((entry, i) => {
|
|
475
|
+
const { id: givenId, children, ...rest } = entry;
|
|
476
|
+
const id = typeof givenId === "string" && givenId.length > 0 ? givenId : newId(taken);
|
|
477
|
+
if (taken.has(id)) throw new Error(`node ID ${id} is already used; drop "id" to get a fresh one`);
|
|
478
|
+
taken.add(id);
|
|
479
|
+
const node = { ...rest };
|
|
480
|
+
if (parent !== void 0) {
|
|
481
|
+
node.parentId = parent;
|
|
482
|
+
node.index = keys[i];
|
|
483
|
+
} else if (isRoot && parentId === void 0 && rest.index === void 0) node.index = keys[i];
|
|
484
|
+
nodes[id] = node;
|
|
485
|
+
if (isRoot) rootIds.push(id);
|
|
486
|
+
if (Array.isArray(children) && children.length > 0) visit(children, id, null, null, false);
|
|
487
|
+
});
|
|
488
|
+
};
|
|
489
|
+
visit(input, parentId, before, after, true);
|
|
490
|
+
return {
|
|
491
|
+
nodes,
|
|
492
|
+
rootIds
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
function isNestedArray(value) {
|
|
496
|
+
return Array.isArray(value);
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* Normalise a raw design file: flatten nested `children`, assign missing
|
|
500
|
+
* indexes, set version and $schema. With `fix`, drop nodes whose parent is
|
|
501
|
+
* missing (and their subtrees). Key sorting happens on write.
|
|
502
|
+
*/
|
|
503
|
+
function formatDesignFile({ raw, fix = false, takenIds = /* @__PURE__ */ new Set() }) {
|
|
504
|
+
const changes = [];
|
|
505
|
+
const source = raw && typeof raw === "object" ? raw : {};
|
|
506
|
+
let nodes = {};
|
|
507
|
+
const taken = new Set(takenIds);
|
|
508
|
+
if (isNestedArray(source.nodes)) {
|
|
509
|
+
nodes = flattenNested({
|
|
510
|
+
input: source.nodes,
|
|
511
|
+
taken
|
|
512
|
+
}).nodes;
|
|
513
|
+
changes.push(`converted nested node list to a flat map (${Object.keys(nodes).length} nodes)`);
|
|
514
|
+
} else if (source.nodes && typeof source.nodes === "object") {
|
|
515
|
+
const entries = Object.entries(source.nodes);
|
|
516
|
+
for (const [id] of entries) taken.add(id);
|
|
517
|
+
for (const [id, value] of entries) {
|
|
518
|
+
const { children, id: _ignored, ...rest } = value ?? {};
|
|
519
|
+
nodes[id] = rest;
|
|
520
|
+
if (isNestedArray(children) && children.length > 0) {
|
|
521
|
+
const flat = flattenNested({
|
|
522
|
+
input: children,
|
|
523
|
+
parentId: id,
|
|
524
|
+
taken
|
|
525
|
+
});
|
|
526
|
+
Object.assign(nodes, flat.nodes);
|
|
527
|
+
changes.push(`flattened ${Object.keys(flat.nodes).length} nested children of ${id}`);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
} else changes.push("added empty nodes map");
|
|
531
|
+
const missingIndex = /* @__PURE__ */ new Map();
|
|
532
|
+
const lastIndex = /* @__PURE__ */ new Map();
|
|
533
|
+
for (const [id, node] of Object.entries(nodes)) {
|
|
534
|
+
const parent = typeof node.parentId === "string" ? node.parentId : "";
|
|
535
|
+
if (typeof node.index === "string") {
|
|
536
|
+
const current = lastIndex.get(parent);
|
|
537
|
+
if (current === void 0 || node.index > current) lastIndex.set(parent, node.index);
|
|
538
|
+
} else if (parent !== "") missingIndex.set(parent, [...missingIndex.get(parent) ?? [], id]);
|
|
539
|
+
}
|
|
540
|
+
for (const [parent, ids] of missingIndex) {
|
|
541
|
+
const keys = keysBetween(lastIndex.get(parent) ?? null, null, ids.length);
|
|
542
|
+
ids.forEach((id, i) => {
|
|
543
|
+
nodes[id].index = keys[i];
|
|
544
|
+
});
|
|
545
|
+
changes.push(`assigned order index to ${ids.length} child(ren) of ${parent}`);
|
|
546
|
+
}
|
|
547
|
+
let formattedCss = 0;
|
|
548
|
+
for (const node of Object.values(nodes)) {
|
|
549
|
+
if (typeof node.css !== "string") continue;
|
|
550
|
+
const formatted = formatNodeCss(node.css);
|
|
551
|
+
if (formatted !== node.css) {
|
|
552
|
+
formattedCss++;
|
|
553
|
+
node.css = formatted;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
if (formattedCss > 0) changes.push(`formatted css on ${formattedCss} node(s)`);
|
|
557
|
+
const fileCss = typeof source.css === "string" ? formatFileCss(source.css) : void 0;
|
|
558
|
+
if (fileCss !== void 0 && fileCss !== source.css) changes.push("formatted file css");
|
|
559
|
+
if (fix) {
|
|
560
|
+
const removed = removeOrphans(nodes);
|
|
561
|
+
if (removed.length > 0) changes.push(`removed ${removed.length} orphaned node(s): ${removed.join(", ")}`);
|
|
562
|
+
}
|
|
563
|
+
if (source.version === void 0) changes.push(`set version 1`);
|
|
564
|
+
return {
|
|
565
|
+
file: {
|
|
566
|
+
$schema: typeof source.$schema === "string" ? source.$schema : SCHEMA_URL,
|
|
567
|
+
version: typeof source.version === "number" ? source.version : 1,
|
|
568
|
+
...fileCss?.trim() ? { css: fileCss } : {},
|
|
569
|
+
nodes
|
|
570
|
+
},
|
|
571
|
+
changes
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
function removeOrphans(nodes) {
|
|
575
|
+
const removed = [];
|
|
576
|
+
let changed = true;
|
|
577
|
+
while (changed) {
|
|
578
|
+
changed = false;
|
|
579
|
+
for (const [id, node] of Object.entries(nodes)) {
|
|
580
|
+
const parent = node.parentId;
|
|
581
|
+
if (typeof parent === "string" && !(parent in nodes)) {
|
|
582
|
+
delete nodes[id];
|
|
583
|
+
removed.push(id);
|
|
584
|
+
changed = true;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
return removed;
|
|
589
|
+
}
|
|
590
|
+
const CONFIG_FILE = "lamsa.config.json";
|
|
591
|
+
function findProjectRoot(start) {
|
|
592
|
+
let dir = resolve(start);
|
|
593
|
+
for (;;) {
|
|
594
|
+
if (existsSync(join(dir, "lamsa.config.json"))) return dir;
|
|
595
|
+
const parent = dirname(dir);
|
|
596
|
+
if (parent === dir) return void 0;
|
|
597
|
+
dir = parent;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
async function loadConfig(root) {
|
|
601
|
+
const path = join(root, CONFIG_FILE);
|
|
602
|
+
if (!existsSync(path)) return configSchema.parse({});
|
|
603
|
+
const raw = JSON.parse(await readFile(path, "utf8"));
|
|
604
|
+
return configSchema.parse(raw);
|
|
605
|
+
}
|
|
606
|
+
function toRepoPath(root, path) {
|
|
607
|
+
return relative(root, resolve(root, path)).split("\\").join("/");
|
|
608
|
+
}
|
|
609
|
+
async function listDesignFiles(root, config) {
|
|
610
|
+
return (await glob(config.designs, {
|
|
611
|
+
cwd: root,
|
|
612
|
+
ignore: ["**/node_modules/**", "**/.lamsa/**"],
|
|
613
|
+
dot: false
|
|
614
|
+
})).map((p) => p.split("\\").join("/")).sort();
|
|
615
|
+
}
|
|
616
|
+
async function readDesignFile(root, path) {
|
|
617
|
+
const text = await readFile(join(root, path), "utf8");
|
|
618
|
+
try {
|
|
619
|
+
return {
|
|
620
|
+
path,
|
|
621
|
+
raw: JSON.parse(text)
|
|
622
|
+
};
|
|
623
|
+
} catch (error) {
|
|
624
|
+
return {
|
|
625
|
+
path,
|
|
626
|
+
raw: void 0,
|
|
627
|
+
parseError: error.message
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
async function loadProject(root) {
|
|
632
|
+
const config = await loadConfig(root);
|
|
633
|
+
const paths = await listDesignFiles(root, config);
|
|
634
|
+
const files = /* @__PURE__ */ new Map();
|
|
635
|
+
for (const path of paths) files.set(path, await readDesignFile(root, path));
|
|
636
|
+
return {
|
|
637
|
+
root,
|
|
638
|
+
config,
|
|
639
|
+
files
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
function isDesignFile(value) {
|
|
643
|
+
return !!value && typeof value === "object" && "nodes" in value && !!value.nodes && typeof value.nodes === "object";
|
|
644
|
+
}
|
|
645
|
+
/** Every node across all files. Later files lose on duplicate IDs; validation reports duplicates. */
|
|
646
|
+
function indexNodes(project) {
|
|
647
|
+
const index = /* @__PURE__ */ new Map();
|
|
648
|
+
for (const file of project.files.values()) {
|
|
649
|
+
if (!isDesignFile(file.raw)) continue;
|
|
650
|
+
for (const [id, node] of Object.entries(file.raw.nodes)) if (!index.has(id)) index.set(id, {
|
|
651
|
+
file: file.path,
|
|
652
|
+
node
|
|
653
|
+
});
|
|
654
|
+
}
|
|
655
|
+
return index;
|
|
656
|
+
}
|
|
657
|
+
function allNodes(project) {
|
|
658
|
+
const nodes = {};
|
|
659
|
+
for (const [id, location] of indexNodes(project)) nodes[id] = location.node;
|
|
660
|
+
return nodes;
|
|
661
|
+
}
|
|
662
|
+
/** File-level CSS (`@keyframes` and friends) from every design file, in path order. */
|
|
663
|
+
function allFileCss(project) {
|
|
664
|
+
return [...project.files.values()].sort((a, b) => a.path < b.path ? -1 : 1).map((file) => isDesignFile(file.raw) && typeof file.raw.css === "string" ? file.raw.css : "").filter((css) => css.trim()).join("\n");
|
|
665
|
+
}
|
|
666
|
+
async function saveDesignFile(root, path, file) {
|
|
667
|
+
await writeFileAtomic(join(root, path), stableStringify(file));
|
|
668
|
+
}
|
|
669
|
+
function byIndexThenId(nodes) {
|
|
670
|
+
return (a, b) => compareIndex(nodes[a]?.index, nodes[b]?.index) || (a < b ? -1 : a > b ? 1 : 0);
|
|
671
|
+
}
|
|
672
|
+
function buildChildIndex(nodes) {
|
|
673
|
+
const roots = [];
|
|
674
|
+
const children = /* @__PURE__ */ new Map();
|
|
675
|
+
for (const [id, node] of Object.entries(nodes)) {
|
|
676
|
+
if (node.parentId === void 0) {
|
|
677
|
+
roots.push(id);
|
|
678
|
+
continue;
|
|
679
|
+
}
|
|
680
|
+
const list = children.get(node.parentId) ?? [];
|
|
681
|
+
list.push(id);
|
|
682
|
+
children.set(node.parentId, list);
|
|
683
|
+
}
|
|
684
|
+
const order = byIndexThenId(nodes);
|
|
685
|
+
roots.sort(order);
|
|
686
|
+
for (const list of children.values()) list.sort(order);
|
|
687
|
+
return {
|
|
688
|
+
roots,
|
|
689
|
+
children
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
function childrenOf(index, id) {
|
|
693
|
+
return index.children.get(id) ?? [];
|
|
694
|
+
}
|
|
695
|
+
function descendants(index, id) {
|
|
696
|
+
const result = [];
|
|
697
|
+
const stack = [...childrenOf(index, id)].reverse();
|
|
698
|
+
while (stack.length > 0) {
|
|
699
|
+
const next = stack.pop();
|
|
700
|
+
result.push(next);
|
|
701
|
+
stack.push(...[...childrenOf(index, next)].reverse());
|
|
702
|
+
}
|
|
703
|
+
return result;
|
|
704
|
+
}
|
|
705
|
+
function ancestors(nodes, id) {
|
|
706
|
+
const result = [];
|
|
707
|
+
const seen = /* @__PURE__ */ new Set([id]);
|
|
708
|
+
let current = nodes[id]?.parentId;
|
|
709
|
+
while (current !== void 0 && !seen.has(current)) {
|
|
710
|
+
result.push(current);
|
|
711
|
+
seen.add(current);
|
|
712
|
+
current = nodes[current]?.parentId;
|
|
713
|
+
}
|
|
714
|
+
return result;
|
|
715
|
+
}
|
|
716
|
+
function rootOf(nodes, id) {
|
|
717
|
+
const chain = ancestors(nodes, id);
|
|
718
|
+
return chain.length > 0 ? chain[chain.length - 1] : id;
|
|
719
|
+
}
|
|
720
|
+
function nodeLabel(id, node) {
|
|
721
|
+
const detail = node.type === "text" ? ` "${truncate(node.content, 40)}"` : node.type === "icon" ? ` ${node.icon}` : node.type === "instance" ? ` → ${node.componentId}` : node.type === "image" ? ` ${node.src}` : "";
|
|
722
|
+
const component = node.type === "frame" && node.component ? " [component]" : "";
|
|
723
|
+
const name = node.name ? ` ${JSON.stringify(node.name)}` : "";
|
|
724
|
+
return `${node.type}${component} ${id}${name}${detail}${node.hidden ? " (hidden)" : ""}`;
|
|
725
|
+
}
|
|
726
|
+
function truncate(text, max) {
|
|
727
|
+
const flat = text.replace(/\s+/g, " ");
|
|
728
|
+
return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
|
|
729
|
+
}
|
|
730
|
+
function treeLines({ nodes, index, from, maxDepth = 1e400 }) {
|
|
731
|
+
const lines = [];
|
|
732
|
+
const visit = (id, depth) => {
|
|
733
|
+
const node = nodes[id];
|
|
734
|
+
if (!node) return;
|
|
735
|
+
lines.push({
|
|
736
|
+
id,
|
|
737
|
+
depth,
|
|
738
|
+
label: nodeLabel(id, node)
|
|
739
|
+
});
|
|
740
|
+
if (depth + 1 > maxDepth) return;
|
|
741
|
+
for (const child of childrenOf(index, id)) visit(child, depth + 1);
|
|
742
|
+
};
|
|
743
|
+
for (const id of from) visit(id, 0);
|
|
744
|
+
return lines;
|
|
745
|
+
}
|
|
746
|
+
var EditError = class extends Error {
|
|
747
|
+
fix;
|
|
748
|
+
nodeId;
|
|
749
|
+
notFound;
|
|
750
|
+
constructor(message, fix, nodeId, notFound = false) {
|
|
751
|
+
super(message);
|
|
752
|
+
this.fix = fix;
|
|
753
|
+
this.nodeId = nodeId;
|
|
754
|
+
this.notFound = notFound;
|
|
755
|
+
}
|
|
756
|
+
};
|
|
757
|
+
function designFile(project, path) {
|
|
758
|
+
const loaded = project.files.get(path);
|
|
759
|
+
if (!loaded) throw new EditError(`design file ${path} is not part of this project`);
|
|
760
|
+
if (loaded.parseError || !isDesignFile(loaded.raw)) throw new EditError(`${path} is not a valid design file`, "run `lamsa validate` and fix it first");
|
|
761
|
+
return loaded.raw;
|
|
762
|
+
}
|
|
763
|
+
function locate$1(project, id) {
|
|
764
|
+
for (const [path, loaded] of project.files) {
|
|
765
|
+
if (!isDesignFile(loaded.raw)) continue;
|
|
766
|
+
const node = loaded.raw.nodes[id];
|
|
767
|
+
if (node) return {
|
|
768
|
+
path,
|
|
769
|
+
file: loaded.raw,
|
|
770
|
+
node
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
throw new EditError(`node ${id} not found`, "run `lamsa tree` to list node IDs", id, true);
|
|
774
|
+
}
|
|
775
|
+
function allIds(project) {
|
|
776
|
+
const ids = /* @__PURE__ */ new Set();
|
|
777
|
+
for (const loaded of project.files.values()) if (isDesignFile(loaded.raw)) for (const id of Object.keys(loaded.raw.nodes)) ids.add(id);
|
|
778
|
+
return ids;
|
|
779
|
+
}
|
|
780
|
+
function ensureFile(project, path) {
|
|
781
|
+
if (project.files.get(path)) return designFile(project, path);
|
|
782
|
+
const file = {
|
|
783
|
+
$schema: SCHEMA_URL,
|
|
784
|
+
version: 1,
|
|
785
|
+
nodes: {}
|
|
786
|
+
};
|
|
787
|
+
project.files.set(path, {
|
|
788
|
+
path,
|
|
789
|
+
raw: file
|
|
790
|
+
});
|
|
791
|
+
return file;
|
|
792
|
+
}
|
|
793
|
+
function siblingKeys({ nodes, parentId, before, after }) {
|
|
794
|
+
const index = buildChildIndex(nodes);
|
|
795
|
+
const siblings = parentId === void 0 ? index.roots : childrenOf(index, parentId);
|
|
796
|
+
const keyOf = (id) => nodes[id]?.index ?? null;
|
|
797
|
+
const anchor = before ?? after;
|
|
798
|
+
if (anchor !== void 0) {
|
|
799
|
+
const position = siblings.indexOf(anchor);
|
|
800
|
+
if (position === -1) throw new EditError(`${anchor} is not a sibling at the target position`, "--before/--after must name a child of the target parent", anchor);
|
|
801
|
+
if (before !== void 0) return {
|
|
802
|
+
low: position > 0 ? keyOf(siblings[position - 1]) : null,
|
|
803
|
+
high: keyOf(anchor)
|
|
804
|
+
};
|
|
805
|
+
return {
|
|
806
|
+
low: keyOf(anchor),
|
|
807
|
+
high: position < siblings.length - 1 ? keyOf(siblings[position + 1]) : null
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
const last = siblings[siblings.length - 1];
|
|
811
|
+
return {
|
|
812
|
+
low: last !== void 0 ? keyOf(last) : null,
|
|
813
|
+
high: null
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
function nextCanvasX(nodes) {
|
|
817
|
+
let right = -80;
|
|
818
|
+
for (const node of Object.values(nodes)) {
|
|
819
|
+
if (node.parentId !== void 0) continue;
|
|
820
|
+
const width = typeof node.style?.width === "number" ? node.style.width : 400;
|
|
821
|
+
right = Math.max(right, (node.x ?? 0) + width);
|
|
822
|
+
}
|
|
823
|
+
return right + 80;
|
|
824
|
+
}
|
|
825
|
+
function addTree({ project, input, placement }) {
|
|
826
|
+
const list = Array.isArray(input) ? input : [input];
|
|
827
|
+
if (list.length === 0) throw new EditError("nothing to add");
|
|
828
|
+
let path;
|
|
829
|
+
if (placement.parentId !== void 0) {
|
|
830
|
+
const parent = locate$1(project, placement.parentId);
|
|
831
|
+
if (parent.node.type !== "frame") throw new EditError(`${placement.parentId} is a ${parent.node.type}; only frames have children`, "pick a frame as --parent", placement.parentId);
|
|
832
|
+
path = parent.path;
|
|
833
|
+
} else {
|
|
834
|
+
if (!placement.file) throw new EditError("top-level nodes need a file", "pass --file <path> or --parent <frame id>");
|
|
835
|
+
path = placement.file;
|
|
836
|
+
}
|
|
837
|
+
const file = ensureFile(project, path);
|
|
838
|
+
const { low, high } = siblingKeys({
|
|
839
|
+
nodes: file.nodes,
|
|
840
|
+
parentId: placement.parentId,
|
|
841
|
+
before: placement.before,
|
|
842
|
+
after: placement.after
|
|
843
|
+
});
|
|
844
|
+
const flat = flattenNested({
|
|
845
|
+
input: list,
|
|
846
|
+
parentId: placement.parentId,
|
|
847
|
+
before: low,
|
|
848
|
+
after: high,
|
|
849
|
+
taken: allIds(project)
|
|
850
|
+
});
|
|
851
|
+
if (placement.parentId === void 0) {
|
|
852
|
+
let x = nextCanvasX(file.nodes);
|
|
853
|
+
for (const id of flat.rootIds) {
|
|
854
|
+
const node = flat.nodes[id];
|
|
855
|
+
if (node.x === void 0) node.x = x;
|
|
856
|
+
if (node.y === void 0) node.y = 0;
|
|
857
|
+
const width = node.style?.width;
|
|
858
|
+
x = node.x + (typeof width === "number" ? width : 400) + 80;
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
Object.assign(file.nodes, flat.nodes);
|
|
862
|
+
return {
|
|
863
|
+
file: path,
|
|
864
|
+
rootIds: flat.rootIds,
|
|
865
|
+
created: Object.keys(flat.nodes)
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
function moveNode({ project, id, placement }) {
|
|
869
|
+
const source = locate$1(project, id);
|
|
870
|
+
const subtree = [id, ...descendants(buildChildIndex(source.file.nodes), id)];
|
|
871
|
+
let targetPath;
|
|
872
|
+
if (placement.parentId !== void 0) {
|
|
873
|
+
if (subtree.includes(placement.parentId)) throw new EditError(`cannot move ${id} into itself or its own subtree`, void 0, id);
|
|
874
|
+
const parent = locate$1(project, placement.parentId);
|
|
875
|
+
if (parent.node.type !== "frame") throw new EditError(`${placement.parentId} is a ${parent.node.type}; only frames have children`, void 0, placement.parentId);
|
|
876
|
+
targetPath = parent.path;
|
|
877
|
+
} else targetPath = placement.file ?? source.path;
|
|
878
|
+
const target = ensureFile(project, targetPath);
|
|
879
|
+
const nodes = { ...target.nodes };
|
|
880
|
+
delete nodes[id];
|
|
881
|
+
const { low, high } = siblingKeys({
|
|
882
|
+
nodes,
|
|
883
|
+
parentId: placement.parentId,
|
|
884
|
+
before: placement.before,
|
|
885
|
+
after: placement.after
|
|
886
|
+
});
|
|
887
|
+
const moved = {};
|
|
888
|
+
for (const nodeId of subtree) {
|
|
889
|
+
moved[nodeId] = source.file.nodes[nodeId];
|
|
890
|
+
delete source.file.nodes[nodeId];
|
|
891
|
+
}
|
|
892
|
+
const root = { ...moved[id] };
|
|
893
|
+
root.index = keyBetween(low, high);
|
|
894
|
+
if (placement.parentId === void 0) {
|
|
895
|
+
delete root.parentId;
|
|
896
|
+
if (root.x === void 0) root.x = nextCanvasX(target.nodes);
|
|
897
|
+
if (root.y === void 0) root.y = 0;
|
|
898
|
+
} else {
|
|
899
|
+
root.parentId = placement.parentId;
|
|
900
|
+
delete root.x;
|
|
901
|
+
delete root.y;
|
|
902
|
+
}
|
|
903
|
+
moved[id] = root;
|
|
904
|
+
Object.assign(target.nodes, moved);
|
|
905
|
+
return {
|
|
906
|
+
from: source.path,
|
|
907
|
+
to: targetPath,
|
|
908
|
+
moved: subtree
|
|
909
|
+
};
|
|
910
|
+
}
|
|
911
|
+
function deleteNodes({ project, ids }) {
|
|
912
|
+
const deleted = [];
|
|
913
|
+
const files = /* @__PURE__ */ new Set();
|
|
914
|
+
for (const id of ids) {
|
|
915
|
+
if (deleted.includes(id)) continue;
|
|
916
|
+
const source = locate$1(project, id);
|
|
917
|
+
const subtree = [id, ...descendants(buildChildIndex(source.file.nodes), id)];
|
|
918
|
+
for (const nodeId of subtree) {
|
|
919
|
+
delete source.file.nodes[nodeId];
|
|
920
|
+
deleted.push(nodeId);
|
|
921
|
+
}
|
|
922
|
+
files.add(source.path);
|
|
923
|
+
}
|
|
924
|
+
const removed = new Set(deleted);
|
|
925
|
+
const danglingInstances = [];
|
|
926
|
+
for (const loaded of project.files.values()) {
|
|
927
|
+
if (!isDesignFile(loaded.raw)) continue;
|
|
928
|
+
for (const [nodeId, node] of Object.entries(loaded.raw.nodes)) if (node.type === "instance" && removed.has(node.componentId)) danglingInstances.push(nodeId);
|
|
929
|
+
}
|
|
930
|
+
return {
|
|
931
|
+
deleted,
|
|
932
|
+
files: [...files],
|
|
933
|
+
danglingInstances
|
|
934
|
+
};
|
|
935
|
+
}
|
|
936
|
+
function distance(a, b) {
|
|
937
|
+
const row = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
938
|
+
for (let i = 1; i <= a.length; i++) {
|
|
939
|
+
let previous = row[0];
|
|
940
|
+
row[0] = i;
|
|
941
|
+
for (let j = 1; j <= b.length; j++) {
|
|
942
|
+
const current = row[j];
|
|
943
|
+
row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
944
|
+
previous = current;
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
return row[b.length];
|
|
948
|
+
}
|
|
949
|
+
/** Closest candidates to `input`, best first; empty when nothing is reasonably close. */
|
|
950
|
+
function closest(input, candidates, limit = 3) {
|
|
951
|
+
const max = Math.max(2, Math.floor(input.length / 3));
|
|
952
|
+
return [...candidates].map((candidate) => ({
|
|
953
|
+
candidate,
|
|
954
|
+
score: distance(input, candidate)
|
|
955
|
+
})).filter(({ candidate, score }) => score <= max || candidate.includes(input)).sort((a, b) => a.score - b.score).slice(0, limit).map(({ candidate }) => candidate);
|
|
956
|
+
}
|
|
957
|
+
function didYouMean(input, candidates) {
|
|
958
|
+
const matches = closest(input, candidates);
|
|
959
|
+
return matches.length > 0 ? `did you mean ${matches.map((m) => `"${m}"`).join(" or ")}?` : "";
|
|
960
|
+
}
|
|
961
|
+
const THREAD_FILE = /^([A-Za-z0-9_-]{1,64})\.json$/;
|
|
962
|
+
const threadPath = ({ config }, id) => `${config.commentsDir.replace(/\/+$/, "")}/${id}.json`;
|
|
963
|
+
const isOpen = (thread) => !thread.resolved;
|
|
964
|
+
async function readThread(location, id) {
|
|
965
|
+
const path = threadPath(location, id);
|
|
966
|
+
let raw;
|
|
967
|
+
try {
|
|
968
|
+
raw = JSON.parse(await readFile(join(location.root, path), "utf8"));
|
|
969
|
+
} catch (error) {
|
|
970
|
+
return { issue: {
|
|
971
|
+
severity: "error",
|
|
972
|
+
code: "comment-invalid",
|
|
973
|
+
file: path,
|
|
974
|
+
message: `comment thread is not valid JSON: ${error.message}`,
|
|
975
|
+
fix: "fix the JSON or delete the file"
|
|
976
|
+
} };
|
|
977
|
+
}
|
|
978
|
+
const parsed = commentThreadSchema.safeParse(raw);
|
|
979
|
+
if (!parsed.success) {
|
|
980
|
+
const first = parsed.error.issues[0];
|
|
981
|
+
return { issue: {
|
|
982
|
+
severity: "error",
|
|
983
|
+
code: "comment-invalid",
|
|
984
|
+
file: path,
|
|
985
|
+
message: `comment thread doesn't match the schema: ${first?.path.length ? `${first.path.join(".")}: ` : ""}${first?.message ?? "invalid"}`,
|
|
986
|
+
fix: "edit comments with `lamsa comments`, not by hand"
|
|
987
|
+
} };
|
|
988
|
+
}
|
|
989
|
+
return { thread: {
|
|
990
|
+
...parsed.data,
|
|
991
|
+
id,
|
|
992
|
+
path
|
|
993
|
+
} };
|
|
994
|
+
}
|
|
995
|
+
async function threadIds(location) {
|
|
996
|
+
const dir = join(location.root, location.config.commentsDir);
|
|
997
|
+
if (!existsSync(dir)) return [];
|
|
998
|
+
return (await readdir(dir)).map((name) => THREAD_FILE.exec(name)?.[1]).filter((id) => !!id).sort();
|
|
999
|
+
}
|
|
1000
|
+
/** Every comment thread in the project, oldest first. A missing comments directory means no comments. */
|
|
1001
|
+
async function loadComments(location) {
|
|
1002
|
+
const threads = [];
|
|
1003
|
+
const issues = [];
|
|
1004
|
+
for (const id of await threadIds(location)) {
|
|
1005
|
+
const { thread, issue } = await readThread(location, id);
|
|
1006
|
+
if (thread) threads.push(thread);
|
|
1007
|
+
if (issue) issues.push(issue);
|
|
1008
|
+
}
|
|
1009
|
+
threads.sort((a, b) => a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : a.id < b.id ? -1 : 1);
|
|
1010
|
+
return {
|
|
1011
|
+
threads,
|
|
1012
|
+
issues
|
|
1013
|
+
};
|
|
1014
|
+
}
|
|
1015
|
+
/** Comments pinned to nodes that no longer exist. They are kept (the conversation still matters) but flagged. */
|
|
1016
|
+
function validateComments({ threads, nodes }) {
|
|
1017
|
+
return threads.filter((thread) => !nodes[thread.nodeId]).map((thread) => ({
|
|
1018
|
+
severity: "warning",
|
|
1019
|
+
code: "comment-orphaned",
|
|
1020
|
+
file: thread.path,
|
|
1021
|
+
nodeId: thread.nodeId,
|
|
1022
|
+
message: `comment ${thread.id} is pinned to ${thread.nodeId}, which no longer exists`,
|
|
1023
|
+
fix: isOpen(thread) ? `address it, then \`lamsa comments resolve ${thread.id} --reply "<what you did>"\`` : `delete ${thread.path} if the thread is no longer useful`
|
|
1024
|
+
}));
|
|
1025
|
+
}
|
|
1026
|
+
/** The agent's name when the CLI runs under one: `LAMSA_AGENT_NAME`, or Claude Code's own marker. */
|
|
1027
|
+
function agentAuthor(env) {
|
|
1028
|
+
const named = env.LAMSA_AGENT_NAME?.trim();
|
|
1029
|
+
if (named) return named;
|
|
1030
|
+
return env.CLAUDECODE === "1" ? "Claude" : void 0;
|
|
1031
|
+
}
|
|
1032
|
+
/**
|
|
1033
|
+
* Who is writing a comment: `explicit` (the `--author` flag), `LAMSA_AUTHOR`, the agent running the CLI (when
|
|
1034
|
+
* `detectAgent`), then git's `user.name`, then the OS user.
|
|
1035
|
+
*/
|
|
1036
|
+
function commentAuthor({ root, explicit, env = process.env, detectAgent = true }) {
|
|
1037
|
+
const chosen = explicit?.trim() || env.LAMSA_AUTHOR?.trim() || (detectAgent ? agentAuthor(env) : void 0);
|
|
1038
|
+
if (chosen) return chosen;
|
|
1039
|
+
const git = spawnSync("git", ["config", "user.name"], {
|
|
1040
|
+
cwd: root,
|
|
1041
|
+
encoding: "utf8"
|
|
1042
|
+
});
|
|
1043
|
+
const name = git.status === 0 ? git.stdout.trim() : "";
|
|
1044
|
+
if (name) return name;
|
|
1045
|
+
try {
|
|
1046
|
+
return userInfo().username || "unknown";
|
|
1047
|
+
} catch {
|
|
1048
|
+
return "unknown";
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
async function writeThread(location, thread) {
|
|
1052
|
+
const { id: _id, path: _path, ...file } = thread;
|
|
1053
|
+
await writeFileAtomic(join(location.root, thread.path), stableStringify(file));
|
|
1054
|
+
return thread;
|
|
1055
|
+
}
|
|
1056
|
+
function requireText(text) {
|
|
1057
|
+
const trimmed = text.trim();
|
|
1058
|
+
if (!trimmed) throw new EditError("comment text is empty", "pass the text as an argument, e.g. \"make this denser\"");
|
|
1059
|
+
return trimmed;
|
|
1060
|
+
}
|
|
1061
|
+
/** Reads a thread fresh from disk, so concurrent writers (the editor, an agent) don't overwrite each other's replies. */
|
|
1062
|
+
async function requireThread(location, id) {
|
|
1063
|
+
const ids = await threadIds(location);
|
|
1064
|
+
if (!ids.includes(id)) throw new EditError(`no comment "${id}"`, didYouMean(id, ids) || "run `lamsa comments --json` to list comment IDs", void 0, true);
|
|
1065
|
+
const { thread, issue } = await readThread(location, id);
|
|
1066
|
+
if (!thread) throw new EditError(issue.message, issue.fix);
|
|
1067
|
+
return thread;
|
|
1068
|
+
}
|
|
1069
|
+
async function addComment({ location, nodeId, text, author, offset, now = /* @__PURE__ */ new Date() }) {
|
|
1070
|
+
const id = newId(new Set(await threadIds(location)));
|
|
1071
|
+
return writeThread(location, {
|
|
1072
|
+
id,
|
|
1073
|
+
path: threadPath(location, id),
|
|
1074
|
+
version: 1,
|
|
1075
|
+
nodeId,
|
|
1076
|
+
...offset ? { offset: {
|
|
1077
|
+
x: Math.round(offset.x),
|
|
1078
|
+
y: Math.round(offset.y)
|
|
1079
|
+
} } : {},
|
|
1080
|
+
author,
|
|
1081
|
+
createdAt: now.toISOString(),
|
|
1082
|
+
text: requireText(text),
|
|
1083
|
+
replies: []
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
async function replyToComment({ location, id, text, author, now = /* @__PURE__ */ new Date() }) {
|
|
1087
|
+
const thread = await requireThread(location, id);
|
|
1088
|
+
return writeThread(location, {
|
|
1089
|
+
...thread,
|
|
1090
|
+
replies: [...thread.replies, {
|
|
1091
|
+
author,
|
|
1092
|
+
createdAt: now.toISOString(),
|
|
1093
|
+
text: requireText(text)
|
|
1094
|
+
}]
|
|
1095
|
+
});
|
|
1096
|
+
}
|
|
1097
|
+
/** Resolves a thread, optionally with a closing reply. Resolving a resolved thread keeps who resolved it first. */
|
|
1098
|
+
async function resolveComment({ location, id, author, reply, now = /* @__PURE__ */ new Date() }) {
|
|
1099
|
+
const thread = await requireThread(location, id);
|
|
1100
|
+
const replies = reply === void 0 ? thread.replies : [...thread.replies, {
|
|
1101
|
+
author,
|
|
1102
|
+
createdAt: now.toISOString(),
|
|
1103
|
+
text: requireText(reply)
|
|
1104
|
+
}];
|
|
1105
|
+
return writeThread(location, {
|
|
1106
|
+
...thread,
|
|
1107
|
+
replies,
|
|
1108
|
+
resolved: thread.resolved ?? {
|
|
1109
|
+
author,
|
|
1110
|
+
at: now.toISOString()
|
|
1111
|
+
}
|
|
1112
|
+
});
|
|
1113
|
+
}
|
|
1114
|
+
async function reopenComment({ location, id }) {
|
|
1115
|
+
const { resolved: _resolved, ...thread } = await requireThread(location, id);
|
|
1116
|
+
return writeThread(location, thread);
|
|
1117
|
+
}
|
|
1118
|
+
const CANVAS_FIELDS = /* @__PURE__ */ new Set([
|
|
1119
|
+
"x",
|
|
1120
|
+
"y",
|
|
1121
|
+
"index"
|
|
1122
|
+
]);
|
|
1123
|
+
/** A top-level frame moved or reordered on the canvas, and nothing else about it changed. */
|
|
1124
|
+
const onlyRepositioned = (change) => change.kind === "changed" && change.id === change.screen && change.fields.every((field) => CANVAS_FIELDS.has(field));
|
|
1125
|
+
function git(root, args) {
|
|
1126
|
+
return execFileSync("git", args, {
|
|
1127
|
+
cwd: root,
|
|
1128
|
+
encoding: "utf8",
|
|
1129
|
+
stdio: [
|
|
1130
|
+
"ignore",
|
|
1131
|
+
"pipe",
|
|
1132
|
+
"ignore"
|
|
1133
|
+
],
|
|
1134
|
+
maxBuffer: 268435456
|
|
1135
|
+
});
|
|
1136
|
+
}
|
|
1137
|
+
function readJsonAtRef({ root, ref, path }) {
|
|
1138
|
+
try {
|
|
1139
|
+
return JSON.parse(git(root, ["show", `${ref}:./${path}`]));
|
|
1140
|
+
} catch {
|
|
1141
|
+
return;
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
/** The design files a project had at a git ref, chosen by that ref's own `designs` globs. */
|
|
1145
|
+
function designFilesAtRef({ root, ref, fallback }) {
|
|
1146
|
+
let paths;
|
|
1147
|
+
try {
|
|
1148
|
+
paths = git(root, [
|
|
1149
|
+
"ls-tree",
|
|
1150
|
+
"-r",
|
|
1151
|
+
"--name-only",
|
|
1152
|
+
ref,
|
|
1153
|
+
"--",
|
|
1154
|
+
"."
|
|
1155
|
+
]).split("\n").filter(Boolean);
|
|
1156
|
+
} catch {
|
|
1157
|
+
throw new Error(`unknown git ref ${ref}`);
|
|
1158
|
+
}
|
|
1159
|
+
const rawConfig = readJsonAtRef({
|
|
1160
|
+
root,
|
|
1161
|
+
ref,
|
|
1162
|
+
path: CONFIG_FILE
|
|
1163
|
+
});
|
|
1164
|
+
const parsed = rawConfig === void 0 ? void 0 : configSchema.safeParse(rawConfig);
|
|
1165
|
+
const config = parsed?.success ? parsed.data : fallback;
|
|
1166
|
+
const isDesign = picomatch(config.designs, { ignore: ["**/node_modules/**", "**/.lamsa/**"] });
|
|
1167
|
+
const files = /* @__PURE__ */ new Map();
|
|
1168
|
+
for (const path of paths.filter((path) => isDesign(path)).sort()) files.set(path, readJsonAtRef({
|
|
1169
|
+
root,
|
|
1170
|
+
ref,
|
|
1171
|
+
path
|
|
1172
|
+
}));
|
|
1173
|
+
return files;
|
|
1174
|
+
}
|
|
1175
|
+
function locate(files) {
|
|
1176
|
+
const nodes = /* @__PURE__ */ new Map();
|
|
1177
|
+
for (const [file, raw] of files) {
|
|
1178
|
+
if (!isDesignFile(raw)) continue;
|
|
1179
|
+
for (const [id, node] of Object.entries(raw.nodes)) nodes.set(id, {
|
|
1180
|
+
file,
|
|
1181
|
+
node
|
|
1182
|
+
});
|
|
1183
|
+
}
|
|
1184
|
+
return nodes;
|
|
1185
|
+
}
|
|
1186
|
+
const textOf = (node) => node.type === "text" && !node.name ? { text: node.content.length > 40 ? `${node.content.slice(0, 39)}…` : node.content } : {};
|
|
1187
|
+
const nodeMapOf = (nodes) => Object.fromEntries([...nodes].map(([id, { node }]) => [id, node]));
|
|
1188
|
+
function changedValues(before, after) {
|
|
1189
|
+
const values = [];
|
|
1190
|
+
const record = (field, a, b) => {
|
|
1191
|
+
if (JSON.stringify(a) === JSON.stringify(b)) return;
|
|
1192
|
+
values.push({
|
|
1193
|
+
field,
|
|
1194
|
+
...a === void 0 ? {} : { before: a },
|
|
1195
|
+
...b === void 0 ? {} : { after: b }
|
|
1196
|
+
});
|
|
1197
|
+
};
|
|
1198
|
+
const fields = (node) => node;
|
|
1199
|
+
for (const key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])) {
|
|
1200
|
+
const a = fields(before)[key];
|
|
1201
|
+
const b = fields(after)[key];
|
|
1202
|
+
if (key !== "style") {
|
|
1203
|
+
record(key, a, b);
|
|
1204
|
+
continue;
|
|
1205
|
+
}
|
|
1206
|
+
const styleA = a ?? {};
|
|
1207
|
+
const styleB = b ?? {};
|
|
1208
|
+
for (const property of /* @__PURE__ */ new Set([...Object.keys(styleA), ...Object.keys(styleB)])) record(`style.${property}`, styleA[property], styleB[property]);
|
|
1209
|
+
}
|
|
1210
|
+
return values.sort((x, y) => x.field.localeCompare(y.field));
|
|
1211
|
+
}
|
|
1212
|
+
/** Compares two sets of design files node by node, matching nodes by ID. */
|
|
1213
|
+
function diffDesignFiles({ before, after, base, head, only }) {
|
|
1214
|
+
const beforeNodes = locate(before);
|
|
1215
|
+
const afterNodes = locate(after);
|
|
1216
|
+
const beforeMap = nodeMapOf(beforeNodes);
|
|
1217
|
+
const afterMap = nodeMapOf(afterNodes);
|
|
1218
|
+
const inScope = only?.length ? picomatch(only.map((path) => path.replace(/^\.\//, ""))) : () => true;
|
|
1219
|
+
const changes = [];
|
|
1220
|
+
for (const [id, now] of afterNodes) {
|
|
1221
|
+
const was = beforeNodes.get(id);
|
|
1222
|
+
const common = {
|
|
1223
|
+
id,
|
|
1224
|
+
file: now.file,
|
|
1225
|
+
name: now.node.name,
|
|
1226
|
+
type: now.node.type,
|
|
1227
|
+
...textOf(now.node),
|
|
1228
|
+
screen: rootOf(afterMap, id)
|
|
1229
|
+
};
|
|
1230
|
+
if (!was) {
|
|
1231
|
+
changes.push({
|
|
1232
|
+
...common,
|
|
1233
|
+
kind: "added"
|
|
1234
|
+
});
|
|
1235
|
+
continue;
|
|
1236
|
+
}
|
|
1237
|
+
const values = changedValues(was.node, now.node);
|
|
1238
|
+
if (was.file !== now.file) values.push({
|
|
1239
|
+
field: "file",
|
|
1240
|
+
before: was.file,
|
|
1241
|
+
after: now.file
|
|
1242
|
+
});
|
|
1243
|
+
if (values.length > 0) changes.push({
|
|
1244
|
+
...common,
|
|
1245
|
+
kind: "changed",
|
|
1246
|
+
fields: values.map((value) => value.field),
|
|
1247
|
+
values
|
|
1248
|
+
});
|
|
1249
|
+
}
|
|
1250
|
+
for (const [id, was] of beforeNodes) {
|
|
1251
|
+
if (afterNodes.has(id)) continue;
|
|
1252
|
+
changes.push({
|
|
1253
|
+
id,
|
|
1254
|
+
file: was.file,
|
|
1255
|
+
kind: "removed",
|
|
1256
|
+
name: was.node.name,
|
|
1257
|
+
type: was.node.type,
|
|
1258
|
+
...textOf(was.node),
|
|
1259
|
+
screen: rootOf(beforeMap, id)
|
|
1260
|
+
});
|
|
1261
|
+
}
|
|
1262
|
+
const kept = changes.filter((change) => inScope(change.file));
|
|
1263
|
+
kept.sort((a, b) => a.file.localeCompare(b.file) || a.screen.localeCompare(b.screen) || a.id.localeCompare(b.id));
|
|
1264
|
+
const screens = /* @__PURE__ */ new Map();
|
|
1265
|
+
const screenFor = (id) => {
|
|
1266
|
+
let screen = screens.get(id);
|
|
1267
|
+
if (!screen) {
|
|
1268
|
+
const node = afterMap[id] ?? beforeMap[id];
|
|
1269
|
+
const kind = !beforeMap[id] ? "added" : !afterMap[id] ? "removed" : "changed";
|
|
1270
|
+
screen = {
|
|
1271
|
+
id,
|
|
1272
|
+
name: node?.name,
|
|
1273
|
+
file: (afterNodes.get(id) ?? beforeNodes.get(id)).file,
|
|
1274
|
+
kind,
|
|
1275
|
+
added: [],
|
|
1276
|
+
removed: [],
|
|
1277
|
+
changed: [],
|
|
1278
|
+
components: []
|
|
1279
|
+
};
|
|
1280
|
+
screens.set(id, screen);
|
|
1281
|
+
}
|
|
1282
|
+
return screen;
|
|
1283
|
+
};
|
|
1284
|
+
for (const change of kept) {
|
|
1285
|
+
if (onlyRepositioned(change)) continue;
|
|
1286
|
+
const screen = screenFor(change.screen);
|
|
1287
|
+
if (screen.kind !== "changed" || change.id === screen.id) continue;
|
|
1288
|
+
screen[change.kind].push(change.id);
|
|
1289
|
+
}
|
|
1290
|
+
const isComponent = (id) => {
|
|
1291
|
+
const node = afterMap[id];
|
|
1292
|
+
return node?.type === "frame" && Boolean(node.component);
|
|
1293
|
+
};
|
|
1294
|
+
const changedComponents = new Set([...screens.values()].filter((screen) => screen.kind === "changed" && isComponent(screen.id)).map((screen) => screen.id));
|
|
1295
|
+
const reached = /* @__PURE__ */ new Set();
|
|
1296
|
+
let grew = true;
|
|
1297
|
+
while (grew) {
|
|
1298
|
+
grew = false;
|
|
1299
|
+
for (const [id, node] of Object.entries(afterMap)) {
|
|
1300
|
+
if (node.type !== "instance" || !changedComponents.has(node.componentId)) continue;
|
|
1301
|
+
const key = `${node.componentId}>${id}`;
|
|
1302
|
+
if (reached.has(key)) continue;
|
|
1303
|
+
reached.add(key);
|
|
1304
|
+
grew = true;
|
|
1305
|
+
const component = screens.get(node.componentId);
|
|
1306
|
+
const rootId = rootOf(afterMap, id);
|
|
1307
|
+
if (!beforeMap[rootId] || !inScope(afterNodes.get(rootId).file)) continue;
|
|
1308
|
+
const screen = screenFor(rootId);
|
|
1309
|
+
if (!screen.components.includes(component.id)) screen.components.push(component.id);
|
|
1310
|
+
for (const kind of [
|
|
1311
|
+
"added",
|
|
1312
|
+
"removed",
|
|
1313
|
+
"changed"
|
|
1314
|
+
]) for (const layer of component[kind]) if (!screen[kind].includes(layer)) screen[kind].push(layer);
|
|
1315
|
+
if (component.changed.includes(component.id) || kept.some((change) => change.id === component.id)) {
|
|
1316
|
+
if (!screen.changed.includes(id)) screen.changed.push(id);
|
|
1317
|
+
}
|
|
1318
|
+
if (isComponent(screen.id)) changedComponents.add(screen.id);
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
const ordered = [...screens.values()].sort((a, b) => a.file.localeCompare(b.file) || a.id.localeCompare(b.id));
|
|
1322
|
+
return {
|
|
1323
|
+
base,
|
|
1324
|
+
head,
|
|
1325
|
+
changes: kept,
|
|
1326
|
+
screens: ordered,
|
|
1327
|
+
affectedRoots: ordered.filter((screen) => screen.kind !== "removed").map((screen) => screen.id),
|
|
1328
|
+
repositioned: kept.filter((change) => onlyRepositioned(change) && !screens.has(change.id)).map((change) => change.id)
|
|
1329
|
+
};
|
|
1330
|
+
}
|
|
1331
|
+
/** Design changes between a git ref and either another ref or the files on disk. */
|
|
1332
|
+
function diffAgainstRef({ project, ref = "HEAD", head, only }) {
|
|
1333
|
+
return diffDesignFiles({
|
|
1334
|
+
before: designFilesAtRef({
|
|
1335
|
+
root: project.root,
|
|
1336
|
+
ref,
|
|
1337
|
+
fallback: project.config
|
|
1338
|
+
}),
|
|
1339
|
+
after: head ? designFilesAtRef({
|
|
1340
|
+
root: project.root,
|
|
1341
|
+
ref: head,
|
|
1342
|
+
fallback: project.config
|
|
1343
|
+
}) : [...project.files.values()].map((file) => [file.path, file.raw]),
|
|
1344
|
+
base: ref,
|
|
1345
|
+
head: head ?? "working tree",
|
|
1346
|
+
only
|
|
1347
|
+
});
|
|
1348
|
+
}
|
|
1349
|
+
const require$1 = createRequire(import.meta.url);
|
|
1350
|
+
let iconDir;
|
|
1351
|
+
let iconNames;
|
|
1352
|
+
const cache = /* @__PURE__ */ new Map();
|
|
1353
|
+
function lucideIconDir() {
|
|
1354
|
+
if (iconDir) return iconDir;
|
|
1355
|
+
const pkg = require$1.resolve("lucide-static/package.json");
|
|
1356
|
+
iconDir = join(dirname(pkg), "icons");
|
|
1357
|
+
return iconDir;
|
|
1358
|
+
}
|
|
1359
|
+
function lucideIconNames() {
|
|
1360
|
+
if (iconNames) return iconNames;
|
|
1361
|
+
iconNames = new Set(readdirSync(lucideIconDir()).filter((file) => file.endsWith(".svg")).map((file) => file.slice(0, -4)));
|
|
1362
|
+
return iconNames;
|
|
1363
|
+
}
|
|
1364
|
+
/** SVG markup for a lucide icon by kebab-case name, or undefined if unknown. */
|
|
1365
|
+
function lucideIconSvg(name) {
|
|
1366
|
+
if (!/^[a-z0-9-]+$/.test(name)) return void 0;
|
|
1367
|
+
const cached = cache.get(name);
|
|
1368
|
+
if (cached) return cached;
|
|
1369
|
+
const path = join(lucideIconDir(), `${name}.svg`);
|
|
1370
|
+
if (!existsSync(path)) return void 0;
|
|
1371
|
+
const svg = readFileSync(path, "utf8").replace(/<!--[\s\S]*?-->/g, "").trim();
|
|
1372
|
+
cache.set(name, svg);
|
|
1373
|
+
return svg;
|
|
1374
|
+
}
|
|
1375
|
+
const SESSION_FILE = ".lamsa/session.json";
|
|
1376
|
+
async function readSession(root) {
|
|
1377
|
+
const path = join(root, SESSION_FILE);
|
|
1378
|
+
if (!existsSync(path)) return void 0;
|
|
1379
|
+
try {
|
|
1380
|
+
return JSON.parse(await readFile(path, "utf8"));
|
|
1381
|
+
} catch {
|
|
1382
|
+
return;
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
const SPACING_STEPS = [
|
|
1386
|
+
0,
|
|
1387
|
+
.5,
|
|
1388
|
+
1,
|
|
1389
|
+
1.5,
|
|
1390
|
+
2,
|
|
1391
|
+
2.5,
|
|
1392
|
+
3,
|
|
1393
|
+
3.5,
|
|
1394
|
+
4,
|
|
1395
|
+
5,
|
|
1396
|
+
6,
|
|
1397
|
+
7,
|
|
1398
|
+
8,
|
|
1399
|
+
9,
|
|
1400
|
+
10,
|
|
1401
|
+
11,
|
|
1402
|
+
12,
|
|
1403
|
+
14,
|
|
1404
|
+
16,
|
|
1405
|
+
20,
|
|
1406
|
+
24,
|
|
1407
|
+
28,
|
|
1408
|
+
32,
|
|
1409
|
+
36,
|
|
1410
|
+
40,
|
|
1411
|
+
44,
|
|
1412
|
+
48,
|
|
1413
|
+
52,
|
|
1414
|
+
56,
|
|
1415
|
+
60,
|
|
1416
|
+
64,
|
|
1417
|
+
72,
|
|
1418
|
+
80,
|
|
1419
|
+
96
|
|
1420
|
+
];
|
|
1421
|
+
const KIND_BY_NAMESPACE = {
|
|
1422
|
+
color: "color",
|
|
1423
|
+
radius: "radius",
|
|
1424
|
+
font: "font",
|
|
1425
|
+
spacing: "spacing",
|
|
1426
|
+
shadow: "shadow",
|
|
1427
|
+
text: "text"
|
|
1428
|
+
};
|
|
1429
|
+
/** Tailwind namespaces whose built-in values become tokens. Others (animations, breakpoints, …) don't map to a style value. */
|
|
1430
|
+
const BUILTIN_NAMESPACES = /* @__PURE__ */ new Set([
|
|
1431
|
+
"color",
|
|
1432
|
+
"font",
|
|
1433
|
+
"font-weight",
|
|
1434
|
+
"text",
|
|
1435
|
+
"tracking",
|
|
1436
|
+
"leading",
|
|
1437
|
+
"radius",
|
|
1438
|
+
"shadow",
|
|
1439
|
+
"inset-shadow",
|
|
1440
|
+
"drop-shadow",
|
|
1441
|
+
"blur",
|
|
1442
|
+
"ease",
|
|
1443
|
+
"container"
|
|
1444
|
+
]);
|
|
1445
|
+
const MULTI_WORD_NAMESPACES = [
|
|
1446
|
+
"font-weight",
|
|
1447
|
+
"inset-shadow",
|
|
1448
|
+
"drop-shadow",
|
|
1449
|
+
"text-shadow"
|
|
1450
|
+
];
|
|
1451
|
+
function isRootSelector(selector) {
|
|
1452
|
+
return selector.split(",").some((part) => part.trim() === ":root");
|
|
1453
|
+
}
|
|
1454
|
+
function isDarkSelector(selector) {
|
|
1455
|
+
return selector.split(",").some((part) => {
|
|
1456
|
+
const s = part.trim();
|
|
1457
|
+
return s === ".dark" || s === ":root.dark" || s === "html.dark";
|
|
1458
|
+
});
|
|
1459
|
+
}
|
|
1460
|
+
function customProps(nodes) {
|
|
1461
|
+
const result = [];
|
|
1462
|
+
for (const node of nodes ?? []) if (node.type === "decl" && node.prop.startsWith("--")) result.push({
|
|
1463
|
+
name: node.prop,
|
|
1464
|
+
value: node.value.trim()
|
|
1465
|
+
});
|
|
1466
|
+
return result;
|
|
1467
|
+
}
|
|
1468
|
+
function substituteVars(value, scope, depth = 0) {
|
|
1469
|
+
if (depth > 8) return value;
|
|
1470
|
+
const replaced = value.replace(/var\(\s*(--[A-Za-z0-9_-]+)\s*(?:,\s*([^()]*(?:\([^()]*\)[^()]*)*))?\)/g, (whole, name, fallback) => scope.get(name) ?? fallback?.trim() ?? whole);
|
|
1471
|
+
return replaced === value ? value : substituteVars(replaced, scope, depth + 1);
|
|
1472
|
+
}
|
|
1473
|
+
function tokenPath(varName) {
|
|
1474
|
+
const bare = varName.slice(2);
|
|
1475
|
+
const multi = MULTI_WORD_NAMESPACES.find((ns) => bare.startsWith(`${ns}-`));
|
|
1476
|
+
const dash = multi ? multi.length : bare.indexOf("-");
|
|
1477
|
+
if (dash <= 0) return void 0;
|
|
1478
|
+
const namespace = bare.slice(0, dash);
|
|
1479
|
+
const rest = bare.slice(dash + 1);
|
|
1480
|
+
if (!rest || rest.includes("*") || rest.includes("--")) return void 0;
|
|
1481
|
+
return {
|
|
1482
|
+
path: `${namespace}.${rest}`,
|
|
1483
|
+
namespace,
|
|
1484
|
+
kind: KIND_BY_NAMESPACE[namespace] ?? "other"
|
|
1485
|
+
};
|
|
1486
|
+
}
|
|
1487
|
+
/** `--color-*: initial` clears a namespace of Tailwind's defaults; `--*: initial` clears them all. */
|
|
1488
|
+
function resetNamespaces(decls) {
|
|
1489
|
+
const namespaces = /* @__PURE__ */ new Set();
|
|
1490
|
+
let all = false;
|
|
1491
|
+
for (const decl of decls) {
|
|
1492
|
+
if (decl.value !== "initial") continue;
|
|
1493
|
+
if (decl.name === "--*") all = true;
|
|
1494
|
+
else if (decl.name.endsWith("-*")) namespaces.add(decl.name.slice(2, -2));
|
|
1495
|
+
}
|
|
1496
|
+
return {
|
|
1497
|
+
all,
|
|
1498
|
+
namespaces
|
|
1499
|
+
};
|
|
1500
|
+
}
|
|
1501
|
+
function themeDeclsOf(css, source) {
|
|
1502
|
+
const root = postcss.parse(css, { from: source });
|
|
1503
|
+
const rootDecls = [];
|
|
1504
|
+
const darkDecls = [];
|
|
1505
|
+
const themeDecls = [];
|
|
1506
|
+
root.walk((node) => {
|
|
1507
|
+
if (node.type === "rule") {
|
|
1508
|
+
if (isRootSelector(node.selector)) rootDecls.push(...customProps(node.nodes));
|
|
1509
|
+
else if (isDarkSelector(node.selector)) darkDecls.push(...customProps(node.nodes));
|
|
1510
|
+
} else if (node.type === "atrule" && node.name === "theme" && !/\breference\b/.test(node.params)) {
|
|
1511
|
+
const inline = /\binline\b/.test(node.params);
|
|
1512
|
+
for (const decl of customProps(node.nodes)) themeDecls.push({
|
|
1513
|
+
...decl,
|
|
1514
|
+
inline
|
|
1515
|
+
});
|
|
1516
|
+
}
|
|
1517
|
+
});
|
|
1518
|
+
return {
|
|
1519
|
+
rootDecls,
|
|
1520
|
+
darkDecls,
|
|
1521
|
+
themeDecls
|
|
1522
|
+
};
|
|
1523
|
+
}
|
|
1524
|
+
/** Tailwind's own theme (`tailwindcss/theme.css`), minus namespaces the project resets. */
|
|
1525
|
+
function builtinDecls(defaultsCss, projectTheme) {
|
|
1526
|
+
const reset = resetNamespaces(projectTheme);
|
|
1527
|
+
if (reset.all) return [];
|
|
1528
|
+
const overridden = new Set(projectTheme.map((d) => d.name));
|
|
1529
|
+
return themeDeclsOf(defaultsCss).themeDecls.filter((decl) => {
|
|
1530
|
+
if (overridden.has(decl.name)) return false;
|
|
1531
|
+
const located = tokenPath(decl.name);
|
|
1532
|
+
return !!located && BUILTIN_NAMESPACES.has(located.namespace) && !reset.namespaces.has(located.namespace);
|
|
1533
|
+
}).map((decl) => ({
|
|
1534
|
+
...decl,
|
|
1535
|
+
inline: false,
|
|
1536
|
+
builtin: true
|
|
1537
|
+
}));
|
|
1538
|
+
}
|
|
1539
|
+
function spacingDisplay(base, step) {
|
|
1540
|
+
const match = /^(\d*\.?\d+)(rem|px)$/.exec(base.trim());
|
|
1541
|
+
if (!match) return `calc(${base} * ${step})`;
|
|
1542
|
+
const value = Number(match[1]) * step;
|
|
1543
|
+
return `${Number(value.toFixed(4))}${match[2]}`;
|
|
1544
|
+
}
|
|
1545
|
+
/**
|
|
1546
|
+
* Reads a shadcn + Tailwind v4 stylesheet. With `defaults` (the text of `tailwindcss/theme.css`),
|
|
1547
|
+
* Tailwind's built-in scales (palette, text sizes, radii, shadows, …) become tokens too, marked `builtin`.
|
|
1548
|
+
*/
|
|
1549
|
+
/** Every `@keyframes` block, by name; later sources win. */
|
|
1550
|
+
function keyframesOf(sources) {
|
|
1551
|
+
const found = /* @__PURE__ */ new Map();
|
|
1552
|
+
for (const css of sources) {
|
|
1553
|
+
if (!css) continue;
|
|
1554
|
+
postcss.parse(css).walkAtRules("keyframes", (rule) => {
|
|
1555
|
+
const name = rule.params.trim();
|
|
1556
|
+
if (name) found.set(name, rule.clone({ raws: {
|
|
1557
|
+
before: "",
|
|
1558
|
+
after: "\n"
|
|
1559
|
+
} }).toString());
|
|
1560
|
+
});
|
|
1561
|
+
}
|
|
1562
|
+
return found;
|
|
1563
|
+
}
|
|
1564
|
+
function parseShadcnTailwind4(css, options = {}) {
|
|
1565
|
+
const { source, defaults } = options;
|
|
1566
|
+
const parsed = themeDeclsOf(css, source);
|
|
1567
|
+
const { rootDecls, darkDecls } = parsed;
|
|
1568
|
+
const projectTheme = parsed.themeDecls.filter((d) => d.value !== "initial");
|
|
1569
|
+
const themeDecls = [...defaults ? builtinDecls(defaults, parsed.themeDecls) : [], ...projectTheme];
|
|
1570
|
+
const lightScope = /* @__PURE__ */ new Map();
|
|
1571
|
+
for (const decl of rootDecls) lightScope.set(decl.name, decl.value);
|
|
1572
|
+
for (const decl of themeDecls) if (!decl.inline) lightScope.set(decl.name, decl.value);
|
|
1573
|
+
const darkScope = new Map(lightScope);
|
|
1574
|
+
for (const decl of darkDecls) darkScope.set(decl.name, decl.value);
|
|
1575
|
+
const tokens = {};
|
|
1576
|
+
for (const decl of themeDecls) {
|
|
1577
|
+
const located = tokenPath(decl.name);
|
|
1578
|
+
if (!located) continue;
|
|
1579
|
+
const light = substituteVars(decl.value, lightScope);
|
|
1580
|
+
const dark = substituteVars(decl.value, darkScope);
|
|
1581
|
+
tokens[located.path] = {
|
|
1582
|
+
path: located.path,
|
|
1583
|
+
css: decl.inline ? decl.value : `var(${decl.name})`,
|
|
1584
|
+
kind: located.kind,
|
|
1585
|
+
values: dark === light ? { light } : {
|
|
1586
|
+
light,
|
|
1587
|
+
dark
|
|
1588
|
+
},
|
|
1589
|
+
...decl.builtin ? { builtin: true } : {}
|
|
1590
|
+
};
|
|
1591
|
+
}
|
|
1592
|
+
const spacingBase = lightScope.get("--spacing") ?? "0.25rem";
|
|
1593
|
+
for (const step of SPACING_STEPS) {
|
|
1594
|
+
const path = `spacing.${step}`;
|
|
1595
|
+
if (tokens[path]) continue;
|
|
1596
|
+
tokens[path] = {
|
|
1597
|
+
path,
|
|
1598
|
+
css: step === 0 ? "0px" : `calc(var(--spacing) * ${step})`,
|
|
1599
|
+
kind: "spacing",
|
|
1600
|
+
values: { light: step === 0 ? "0px" : spacingDisplay(spacingBase, step) }
|
|
1601
|
+
};
|
|
1602
|
+
}
|
|
1603
|
+
const rootBlock = [
|
|
1604
|
+
...themeDecls.filter((decl) => decl.builtin),
|
|
1605
|
+
...rootDecls,
|
|
1606
|
+
...themeDecls.filter((decl) => !decl.inline && !decl.builtin),
|
|
1607
|
+
...lightScope.has("--spacing") ? [] : [{
|
|
1608
|
+
name: "--spacing",
|
|
1609
|
+
value: "0.25rem"
|
|
1610
|
+
}]
|
|
1611
|
+
];
|
|
1612
|
+
const block = (selector, decls) => decls.length === 0 ? "" : `${selector} {\n${decls.map((d) => ` ${d.name}: ${d.value};`).join("\n")}\n}\n`;
|
|
1613
|
+
const keyframes = keyframesOf([defaults, css]);
|
|
1614
|
+
return {
|
|
1615
|
+
adapter: "shadcn-tailwind4",
|
|
1616
|
+
source,
|
|
1617
|
+
tokens,
|
|
1618
|
+
css: block(":root", rootBlock) + block(".dark", darkDecls) + [...keyframes.values()].join("\n"),
|
|
1619
|
+
keyframes: [...keyframes.keys()].sort()
|
|
1620
|
+
};
|
|
1621
|
+
}
|
|
1622
|
+
const GLOBALS_CSS_CANDIDATES = [
|
|
1623
|
+
"app/globals.css",
|
|
1624
|
+
"src/app/globals.css",
|
|
1625
|
+
"src/styles/globals.css",
|
|
1626
|
+
"styles/globals.css",
|
|
1627
|
+
"src/index.css",
|
|
1628
|
+
"src/globals.css",
|
|
1629
|
+
"app/app.css"
|
|
1630
|
+
];
|
|
1631
|
+
function detectTokenSource(root) {
|
|
1632
|
+
return GLOBALS_CSS_CANDIDATES.find((candidate) => existsSync(join(root, candidate)));
|
|
1633
|
+
}
|
|
1634
|
+
var TokenSourceError = class extends Error {};
|
|
1635
|
+
async function loadTokens(root, config) {
|
|
1636
|
+
if (config.tokens.adapter === "none") return emptyTokenSet;
|
|
1637
|
+
const source = config.tokens.path ?? detectTokenSource(root);
|
|
1638
|
+
if (!source) throw new TokenSourceError(`no token source found for adapter ${config.tokens.adapter}; set "tokens.path" in lamsa.config.json`);
|
|
1639
|
+
const path = join(root, source);
|
|
1640
|
+
if (!existsSync(path)) throw new TokenSourceError(`token source ${source} does not exist; fix "tokens.path" in lamsa.config.json`);
|
|
1641
|
+
const css = await readFile(path, "utf8");
|
|
1642
|
+
const themePath = importsTailwind(css) ? tailwindThemePath(root) : void 0;
|
|
1643
|
+
return parseShadcnTailwind4(css, {
|
|
1644
|
+
source,
|
|
1645
|
+
defaults: themePath ? await readFile(themePath, "utf8") : void 0
|
|
1646
|
+
});
|
|
1647
|
+
}
|
|
1648
|
+
function importsTailwind(css) {
|
|
1649
|
+
return /@import\s+(?:url\()?["']tailwindcss(?:\/theme(?:\.css)?)?["']/.test(css);
|
|
1650
|
+
}
|
|
1651
|
+
/** The project's own `tailwindcss/theme.css` when installed, so tokens match its Tailwind version; else lamsa's copy. */
|
|
1652
|
+
function tailwindThemePath(root) {
|
|
1653
|
+
for (const from of [join(root, "package.json"), import.meta.url]) try {
|
|
1654
|
+
return createRequire(from).resolve("tailwindcss/theme.css");
|
|
1655
|
+
} catch {
|
|
1656
|
+
continue;
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
/** Fonts the token adapter can't locate (e.g. `next/font`), mapped in config. */
|
|
1660
|
+
function fontSetup(config) {
|
|
1661
|
+
const rootVars = [];
|
|
1662
|
+
const faces = [];
|
|
1663
|
+
const links = [];
|
|
1664
|
+
for (const [key, spec] of Object.entries(config.fonts)) {
|
|
1665
|
+
const family = key.startsWith("--") ? "google" in spec ? spec.google.split(":")[0] : key.slice(2) : key;
|
|
1666
|
+
if ("google" in spec) {
|
|
1667
|
+
const [name, axes] = spec.google.split(":");
|
|
1668
|
+
const familyParam = `${encodeURIComponent(name).replace(/%20/g, "+")}:${axes ?? "wght@100..900"}`;
|
|
1669
|
+
links.push(`https://fonts.googleapis.com/css2?family=${familyParam}&display=block`);
|
|
1670
|
+
} else for (const file of spec.files) faces.push(`@font-face { font-family: "${family}"; src: url("${file}"); font-display: block; }`);
|
|
1671
|
+
if (key.startsWith("--")) rootVars.push(` ${key}: "${family}";`);
|
|
1672
|
+
}
|
|
1673
|
+
const rootBlock = rootVars.length > 0 ? `:root {\n${rootVars.join("\n")}\n}\n` : "";
|
|
1674
|
+
return {
|
|
1675
|
+
css: faces.join("\n") + (faces.length ? "\n" : "") + rootBlock,
|
|
1676
|
+
links
|
|
1677
|
+
};
|
|
1678
|
+
}
|
|
1679
|
+
const KEBAB_PROPERTY = /^(--[A-Za-z0-9_-]+|-?[a-z][a-z0-9-]*)$/;
|
|
1680
|
+
function kebab(property) {
|
|
1681
|
+
return property.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
|
|
1682
|
+
}
|
|
1683
|
+
function normaliseColor(value) {
|
|
1684
|
+
return value.trim().toLowerCase().replace(/\s+/g, " ");
|
|
1685
|
+
}
|
|
1686
|
+
function colorTokensByValue(tokens) {
|
|
1687
|
+
const colorValues = /* @__PURE__ */ new Map();
|
|
1688
|
+
const byPreference = Object.values(tokens.tokens).sort((a, b) => Number(!!b.builtin) - Number(!!a.builtin));
|
|
1689
|
+
for (const token of byPreference) if (token.kind === "color") colorValues.set(normaliseColor(token.values.light), token.path);
|
|
1690
|
+
return colorValues;
|
|
1691
|
+
}
|
|
1692
|
+
function validateProject({ project, tokens }) {
|
|
1693
|
+
const issues = [];
|
|
1694
|
+
const nodes = {};
|
|
1695
|
+
const fileOf = /* @__PURE__ */ new Map();
|
|
1696
|
+
const keyframes = new Set(tokens.keyframes ?? []);
|
|
1697
|
+
for (const file of project.files.values()) {
|
|
1698
|
+
if (file.parseError) {
|
|
1699
|
+
issues.push({
|
|
1700
|
+
severity: "error",
|
|
1701
|
+
code: "invalid-json",
|
|
1702
|
+
file: file.path,
|
|
1703
|
+
message: `not valid JSON: ${file.parseError}`,
|
|
1704
|
+
fix: "fix the syntax; the editor keeps showing the last valid version meanwhile"
|
|
1705
|
+
});
|
|
1706
|
+
continue;
|
|
1707
|
+
}
|
|
1708
|
+
const version = file.raw?.version;
|
|
1709
|
+
if (typeof version === "number" && version > 1) {
|
|
1710
|
+
issues.push({
|
|
1711
|
+
severity: "error",
|
|
1712
|
+
code: "newer-version",
|
|
1713
|
+
file: file.path,
|
|
1714
|
+
message: `file format version ${version} is newer than this lamsa (1)`,
|
|
1715
|
+
fix: "upgrade lamsa"
|
|
1716
|
+
});
|
|
1717
|
+
continue;
|
|
1718
|
+
}
|
|
1719
|
+
const parsed = designFileSchema.safeParse(file.raw);
|
|
1720
|
+
if (!parsed.success) {
|
|
1721
|
+
for (const problem of parsed.error.issues) {
|
|
1722
|
+
const [first, second, ...rest] = problem.path.map(String);
|
|
1723
|
+
const nodeId = first === "nodes" ? second : void 0;
|
|
1724
|
+
const where = nodeId ? rest.join(".") : problem.path.join(".");
|
|
1725
|
+
issues.push({
|
|
1726
|
+
severity: "error",
|
|
1727
|
+
code: "schema",
|
|
1728
|
+
file: file.path,
|
|
1729
|
+
nodeId,
|
|
1730
|
+
message: `${where ? `${where}: ` : ""}${problem.message}`,
|
|
1731
|
+
fix: hasNestedChildren(file.raw) ? "run `lamsa fmt` to flatten nested children" : void 0
|
|
1732
|
+
});
|
|
1733
|
+
}
|
|
1734
|
+
continue;
|
|
1735
|
+
}
|
|
1736
|
+
if (parsed.data.css) {
|
|
1737
|
+
for (const problem of checkFileCss(parsed.data.css)) issues.push({
|
|
1738
|
+
severity: "error",
|
|
1739
|
+
code: "file-css",
|
|
1740
|
+
file: file.path,
|
|
1741
|
+
message: `css${problem.line ? ` line ${problem.line}` : ""}: ${problem.message}`,
|
|
1742
|
+
fix: "file-level css holds @keyframes; each node's own styles go in its \"css\""
|
|
1743
|
+
});
|
|
1744
|
+
for (const name of keyframeNames(parsed.data.css)) keyframes.add(name);
|
|
1745
|
+
}
|
|
1746
|
+
for (const [id, node] of Object.entries(parsed.data.nodes)) {
|
|
1747
|
+
const existing = fileOf.get(id);
|
|
1748
|
+
if (existing) {
|
|
1749
|
+
issues.push({
|
|
1750
|
+
severity: "error",
|
|
1751
|
+
code: "duplicate-id",
|
|
1752
|
+
file: file.path,
|
|
1753
|
+
nodeId: id,
|
|
1754
|
+
message: `node ID ${id} is also used in ${existing}`,
|
|
1755
|
+
fix: "IDs are global across the repo; give one of them a new ID"
|
|
1756
|
+
});
|
|
1757
|
+
continue;
|
|
1758
|
+
}
|
|
1759
|
+
nodes[id] = node;
|
|
1760
|
+
fileOf.set(id, file.path);
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
const context = {
|
|
1764
|
+
project,
|
|
1765
|
+
tokens,
|
|
1766
|
+
nodes,
|
|
1767
|
+
fileOf,
|
|
1768
|
+
issues,
|
|
1769
|
+
keyframes,
|
|
1770
|
+
colorValues: colorTokensByValue(tokens)
|
|
1771
|
+
};
|
|
1772
|
+
checkStructure(context);
|
|
1773
|
+
checkComponents(context);
|
|
1774
|
+
checkContent(context);
|
|
1775
|
+
return issues;
|
|
1776
|
+
}
|
|
1777
|
+
function hasNestedChildren(raw) {
|
|
1778
|
+
const nodes = raw?.nodes;
|
|
1779
|
+
if (Array.isArray(nodes)) return true;
|
|
1780
|
+
if (!nodes || typeof nodes !== "object") return false;
|
|
1781
|
+
return Object.values(nodes).some((node) => !!node && typeof node === "object" && "children" in node);
|
|
1782
|
+
}
|
|
1783
|
+
function push(context, issue) {
|
|
1784
|
+
context.issues.push({
|
|
1785
|
+
file: context.fileOf.get(issue.nodeId),
|
|
1786
|
+
...issue
|
|
1787
|
+
});
|
|
1788
|
+
}
|
|
1789
|
+
function checkStructure(context) {
|
|
1790
|
+
const { nodes, fileOf } = context;
|
|
1791
|
+
for (const [id, node] of Object.entries(nodes)) {
|
|
1792
|
+
if (node.parentId === void 0) continue;
|
|
1793
|
+
const parent = nodes[node.parentId];
|
|
1794
|
+
if (!parent) {
|
|
1795
|
+
push(context, {
|
|
1796
|
+
severity: "error",
|
|
1797
|
+
code: "missing-parent",
|
|
1798
|
+
nodeId: id,
|
|
1799
|
+
message: `parentId ${node.parentId} does not exist`,
|
|
1800
|
+
fix: "set parentId to an existing frame, or run `lamsa fmt --fix` to remove orphans"
|
|
1801
|
+
});
|
|
1802
|
+
continue;
|
|
1803
|
+
}
|
|
1804
|
+
if (fileOf.get(node.parentId) !== fileOf.get(id)) push(context, {
|
|
1805
|
+
severity: "error",
|
|
1806
|
+
code: "cross-file-parent",
|
|
1807
|
+
nodeId: id,
|
|
1808
|
+
message: `parent ${node.parentId} is in ${fileOf.get(node.parentId)}; children must live in their parent's file`,
|
|
1809
|
+
fix: `use \`lamsa move ${id} --parent ${node.parentId}\` to move it with its subtree`
|
|
1810
|
+
});
|
|
1811
|
+
if (parent.type !== "frame") push(context, {
|
|
1812
|
+
severity: "error",
|
|
1813
|
+
code: "invalid-parent",
|
|
1814
|
+
nodeId: id,
|
|
1815
|
+
message: `parent ${node.parentId} is a ${parent.type}; only frames have children`,
|
|
1816
|
+
fix: "wrap content in a frame, or override instance content via `overrides`"
|
|
1817
|
+
});
|
|
1818
|
+
if (node.index === void 0) push(context, {
|
|
1819
|
+
severity: "warning",
|
|
1820
|
+
code: "missing-index",
|
|
1821
|
+
nodeId: id,
|
|
1822
|
+
message: "child has no order index",
|
|
1823
|
+
fix: "run `lamsa fmt`"
|
|
1824
|
+
});
|
|
1825
|
+
if (isCyclic(nodes, id)) push(context, {
|
|
1826
|
+
severity: "error",
|
|
1827
|
+
code: "cycle",
|
|
1828
|
+
nodeId: id,
|
|
1829
|
+
message: "parentId chain forms a cycle",
|
|
1830
|
+
fix: "point parentId at a frame that is not inside this node"
|
|
1831
|
+
});
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
1834
|
+
function isCyclic(nodes, id) {
|
|
1835
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1836
|
+
let current = id;
|
|
1837
|
+
while (current !== void 0) {
|
|
1838
|
+
if (seen.has(current)) return true;
|
|
1839
|
+
seen.add(current);
|
|
1840
|
+
current = nodes[current]?.parentId;
|
|
1841
|
+
}
|
|
1842
|
+
return false;
|
|
1843
|
+
}
|
|
1844
|
+
function checkComponents(context) {
|
|
1845
|
+
const { nodes } = context;
|
|
1846
|
+
const index = buildChildIndex(nodes);
|
|
1847
|
+
const insideOf = (componentId) => new Set(descendants(index, componentId));
|
|
1848
|
+
for (const [id, node] of Object.entries(nodes)) {
|
|
1849
|
+
if (node.type === "frame" && node.component) {
|
|
1850
|
+
const inner = insideOf(id);
|
|
1851
|
+
for (const [propName, prop] of Object.entries(node.component.props ?? {})) if (prop.type === "enum") {
|
|
1852
|
+
if (!prop.options.includes(prop.default)) push(context, {
|
|
1853
|
+
severity: "error",
|
|
1854
|
+
code: "prop-default",
|
|
1855
|
+
nodeId: id,
|
|
1856
|
+
message: `prop ${propName}: default "${prop.default}" is not one of ${prop.options.join(", ")}`
|
|
1857
|
+
});
|
|
1858
|
+
for (const [option, patches] of Object.entries(prop.overrides ?? {})) {
|
|
1859
|
+
if (!prop.options.includes(option)) push(context, {
|
|
1860
|
+
severity: "error",
|
|
1861
|
+
code: "prop-option",
|
|
1862
|
+
nodeId: id,
|
|
1863
|
+
message: `prop ${propName}: overrides for unknown option "${option}"`,
|
|
1864
|
+
fix: didYouMean(option, prop.options) || `add "${option}" to options`
|
|
1865
|
+
});
|
|
1866
|
+
checkPatchTargets(context, {
|
|
1867
|
+
ownerId: id,
|
|
1868
|
+
componentId: id,
|
|
1869
|
+
inner,
|
|
1870
|
+
patches,
|
|
1871
|
+
label: `prop ${propName}=${option}`
|
|
1872
|
+
});
|
|
1873
|
+
}
|
|
1874
|
+
} else if (prop.type === "boolean") for (const [value, patches] of Object.entries(prop.overrides ?? {})) checkPatchTargets(context, {
|
|
1875
|
+
ownerId: id,
|
|
1876
|
+
componentId: id,
|
|
1877
|
+
inner,
|
|
1878
|
+
patches: patches ?? {},
|
|
1879
|
+
label: `prop ${propName}=${value}`
|
|
1880
|
+
});
|
|
1881
|
+
else if (!inner.has(prop.target) || nodes[prop.target]?.type !== "text") push(context, {
|
|
1882
|
+
severity: "error",
|
|
1883
|
+
code: "prop-target",
|
|
1884
|
+
nodeId: id,
|
|
1885
|
+
message: `text prop ${propName} targets ${prop.target}, which is not a text node inside this component`
|
|
1886
|
+
});
|
|
1887
|
+
}
|
|
1888
|
+
if (node.type !== "instance") continue;
|
|
1889
|
+
const component = nodes[node.componentId];
|
|
1890
|
+
if (!component || component.type !== "frame" || !component.component) {
|
|
1891
|
+
const componentIds = Object.entries(nodes).filter(([, n]) => n.type === "frame" && n.component).map(([cid]) => cid);
|
|
1892
|
+
push(context, {
|
|
1893
|
+
severity: "error",
|
|
1894
|
+
code: "missing-component",
|
|
1895
|
+
nodeId: id,
|
|
1896
|
+
message: component ? `componentId ${node.componentId} is a ${component.type} without a "component" definition` : `componentId ${node.componentId} does not exist`,
|
|
1897
|
+
fix: didYouMean(node.componentId, componentIds) || "run `lamsa components` to list components"
|
|
1898
|
+
});
|
|
1899
|
+
continue;
|
|
1900
|
+
}
|
|
1901
|
+
checkInstanceProps(context, {
|
|
1902
|
+
id,
|
|
1903
|
+
node,
|
|
1904
|
+
component
|
|
1905
|
+
});
|
|
1906
|
+
checkPatchTargets(context, {
|
|
1907
|
+
ownerId: id,
|
|
1908
|
+
componentId: node.componentId,
|
|
1909
|
+
inner: insideOf(node.componentId),
|
|
1910
|
+
patches: node.overrides ?? {},
|
|
1911
|
+
label: "overrides"
|
|
1912
|
+
});
|
|
1913
|
+
if (instanceCycle(nodes, index, node.componentId, /* @__PURE__ */ new Set([node.componentId]))) push(context, {
|
|
1914
|
+
severity: "error",
|
|
1915
|
+
code: "component-cycle",
|
|
1916
|
+
nodeId: id,
|
|
1917
|
+
message: `component ${node.componentId} contains an instance of itself`
|
|
1918
|
+
});
|
|
1919
|
+
}
|
|
1920
|
+
}
|
|
1921
|
+
function checkInstanceProps(context, { id, node, component }) {
|
|
1922
|
+
const defs = component.component?.props ?? {};
|
|
1923
|
+
for (const [name, value] of Object.entries(node.props ?? {})) {
|
|
1924
|
+
const def = defs[name];
|
|
1925
|
+
if (!def) {
|
|
1926
|
+
push(context, {
|
|
1927
|
+
severity: "error",
|
|
1928
|
+
code: "unknown-prop",
|
|
1929
|
+
nodeId: id,
|
|
1930
|
+
message: `component ${node.componentId} has no prop "${name}"`,
|
|
1931
|
+
fix: didYouMean(name, Object.keys(defs)) || `props: ${Object.keys(defs).join(", ") || "(none)"}`
|
|
1932
|
+
});
|
|
1933
|
+
continue;
|
|
1934
|
+
}
|
|
1935
|
+
if (!(def.type === "enum" ? typeof value === "string" && def.options.includes(value) : def.type === "boolean" ? typeof value === "boolean" : typeof value === "string")) push(context, {
|
|
1936
|
+
severity: "error",
|
|
1937
|
+
code: "prop-value",
|
|
1938
|
+
nodeId: id,
|
|
1939
|
+
message: `prop ${name}: ${JSON.stringify(value)} is not valid`,
|
|
1940
|
+
fix: def.type === "enum" ? `use one of ${def.options.join(", ")}` : def.type === "boolean" ? "use true or false" : "use a string"
|
|
1941
|
+
});
|
|
1942
|
+
}
|
|
1943
|
+
}
|
|
1944
|
+
function checkPatchTargets(context, { ownerId, componentId, inner, patches, label }) {
|
|
1945
|
+
for (const [target, patch] of Object.entries(patches)) {
|
|
1946
|
+
if (!inner.has(target) && target !== componentId) push(context, {
|
|
1947
|
+
severity: "error",
|
|
1948
|
+
code: "override-target",
|
|
1949
|
+
nodeId: ownerId,
|
|
1950
|
+
message: `${label}: ${target} is not a node inside component ${componentId}`,
|
|
1951
|
+
fix: didYouMean(target, inner) || `run \`lamsa tree ${componentId}\` to see its node IDs`
|
|
1952
|
+
});
|
|
1953
|
+
if (patch.style) checkStyle(context, {
|
|
1954
|
+
nodeId: ownerId,
|
|
1955
|
+
style: patch.style,
|
|
1956
|
+
label: `${label} ${target}`
|
|
1957
|
+
});
|
|
1958
|
+
if (patch.css) checkCss(context, {
|
|
1959
|
+
nodeId: ownerId,
|
|
1960
|
+
css: patch.css,
|
|
1961
|
+
label: `${label} ${target} css`
|
|
1962
|
+
});
|
|
1963
|
+
}
|
|
1964
|
+
}
|
|
1965
|
+
function instanceCycle(nodes, index, componentId, visiting) {
|
|
1966
|
+
for (const inner of descendants(index, componentId)) {
|
|
1967
|
+
const node = nodes[inner];
|
|
1968
|
+
if (node?.type !== "instance") continue;
|
|
1969
|
+
if (visiting.has(node.componentId)) return true;
|
|
1970
|
+
visiting.add(node.componentId);
|
|
1971
|
+
if (instanceCycle(nodes, index, node.componentId, visiting)) return true;
|
|
1972
|
+
visiting.delete(node.componentId);
|
|
1973
|
+
}
|
|
1974
|
+
return false;
|
|
1975
|
+
}
|
|
1976
|
+
function checkContent(context) {
|
|
1977
|
+
const { nodes, project } = context;
|
|
1978
|
+
const icons = lucideIconNames();
|
|
1979
|
+
for (const [id, node] of Object.entries(nodes)) {
|
|
1980
|
+
if (node.style) checkStyle(context, {
|
|
1981
|
+
nodeId: id,
|
|
1982
|
+
style: node.style,
|
|
1983
|
+
label: "style"
|
|
1984
|
+
});
|
|
1985
|
+
if (node.css) checkCss(context, {
|
|
1986
|
+
nodeId: id,
|
|
1987
|
+
css: node.css,
|
|
1988
|
+
label: "css"
|
|
1989
|
+
});
|
|
1990
|
+
if (node.type === "icon" && !icons.has(node.icon)) push(context, {
|
|
1991
|
+
severity: "error",
|
|
1992
|
+
code: "unknown-icon",
|
|
1993
|
+
nodeId: id,
|
|
1994
|
+
message: `lucide has no icon "${node.icon}"`,
|
|
1995
|
+
fix: didYouMean(node.icon, icons) || "see https://lucide.dev/icons"
|
|
1996
|
+
});
|
|
1997
|
+
if (node.type === "image") {
|
|
1998
|
+
if (/^https?:\/\//.test(node.src)) push(context, {
|
|
1999
|
+
severity: "warning",
|
|
2000
|
+
code: "remote-asset",
|
|
2001
|
+
nodeId: id,
|
|
2002
|
+
message: `image src is a remote URL (${node.src}); renders depend on the network`,
|
|
2003
|
+
fix: `download it into ${project.config.assetsDir} and use the repo-relative path`
|
|
2004
|
+
});
|
|
2005
|
+
else if (!node.src.startsWith("data:") && !existsSync(join(project.root, node.src))) push(context, {
|
|
2006
|
+
severity: "error",
|
|
2007
|
+
code: "missing-asset",
|
|
2008
|
+
nodeId: id,
|
|
2009
|
+
message: `image src ${node.src} does not exist`,
|
|
2010
|
+
fix: "use a path relative to the repo root"
|
|
2011
|
+
});
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
}
|
|
2015
|
+
function checkCss(context, { nodeId, css, label }) {
|
|
2016
|
+
for (const problem of checkNodeCss(css)) push(context, {
|
|
2017
|
+
severity: "error",
|
|
2018
|
+
code: "node-css",
|
|
2019
|
+
nodeId,
|
|
2020
|
+
message: `${label}${problem.line ? ` line ${problem.line}` : ""}: ${problem.message}`,
|
|
2021
|
+
fix: "write plain CSS: declarations, then nested rules like `&:hover { … }`"
|
|
2022
|
+
});
|
|
2023
|
+
for (const name of animationNamesUsed(css)) {
|
|
2024
|
+
if (context.keyframes.has(name)) continue;
|
|
2025
|
+
push(context, {
|
|
2026
|
+
severity: "warning",
|
|
2027
|
+
code: "unknown-keyframes",
|
|
2028
|
+
nodeId,
|
|
2029
|
+
message: `${label}: animation uses @keyframes ${name}, which no design file or app stylesheet defines`,
|
|
2030
|
+
fix: didYouMean(name, context.keyframes) || `add \`@keyframes ${name} { … }\` to the file's "css"`
|
|
2031
|
+
});
|
|
2032
|
+
}
|
|
2033
|
+
for (const ref of tokenRefs(css)) {
|
|
2034
|
+
if (context.tokens.tokens[ref]) continue;
|
|
2035
|
+
push(context, {
|
|
2036
|
+
severity: "error",
|
|
2037
|
+
code: "unknown-token",
|
|
2038
|
+
nodeId,
|
|
2039
|
+
message: `${label}: references unknown token {${ref}}`,
|
|
2040
|
+
fix: didYouMean(ref, Object.keys(context.tokens.tokens)) || "run `lamsa tokens` to list tokens"
|
|
2041
|
+
});
|
|
2042
|
+
}
|
|
2043
|
+
}
|
|
2044
|
+
function checkStyle(context, { nodeId, style, label }) {
|
|
2045
|
+
const { tokens, colorValues } = context;
|
|
2046
|
+
for (const [property, value] of Object.entries(style)) {
|
|
2047
|
+
if (!KEBAB_PROPERTY.test(property)) push(context, {
|
|
2048
|
+
severity: "warning",
|
|
2049
|
+
code: "property-name",
|
|
2050
|
+
nodeId,
|
|
2051
|
+
message: `${label}: "${property}" is not a CSS property name`,
|
|
2052
|
+
fix: `use kebab-case: "${kebab(property)}"`
|
|
2053
|
+
});
|
|
2054
|
+
for (const ref of tokenRefs(value)) if (!tokens.tokens[ref]) push(context, {
|
|
2055
|
+
severity: "error",
|
|
2056
|
+
code: "unknown-token",
|
|
2057
|
+
nodeId,
|
|
2058
|
+
message: `${label}: ${property} references unknown token {${ref}}`,
|
|
2059
|
+
fix: didYouMean(ref, Object.keys(tokens.tokens)) || "run `lamsa tokens` to list tokens"
|
|
2060
|
+
});
|
|
2061
|
+
if (typeof value === "string" && tokenRefs(value).length === 0) {
|
|
2062
|
+
const match = colorValues.get(normaliseColor(value));
|
|
2063
|
+
if (match) push(context, {
|
|
2064
|
+
severity: "warning",
|
|
2065
|
+
code: "raw-token-value",
|
|
2066
|
+
nodeId,
|
|
2067
|
+
message: `${label}: ${property} uses raw value ${value}, which matches token {${match}}`,
|
|
2068
|
+
fix: `use "{${match}}"`
|
|
2069
|
+
});
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
}
|
|
2073
|
+
function summarize(issues) {
|
|
2074
|
+
return {
|
|
2075
|
+
errors: issues.filter((i) => i.severity === "error").length,
|
|
2076
|
+
warnings: issues.filter((i) => i.severity === "warning").length
|
|
2077
|
+
};
|
|
2078
|
+
}
|
|
2079
|
+
// src/context.ts
|
|
2080
|
+
function resolveRoot(explicit) {
|
|
2081
|
+
if (explicit) return explicit;
|
|
2082
|
+
const found = findProjectRoot(process.cwd());
|
|
2083
|
+
if (!found) throw new CliError("no lamsa.config.json found in this directory or its parents", ExitCode.notFound, "run `lamsa init --yes` at the repo root");
|
|
2084
|
+
return found;
|
|
2085
|
+
}
|
|
2086
|
+
async function openWorkspace(root) {
|
|
2087
|
+
const project = await loadProject(resolveRoot(root));
|
|
2088
|
+
let tokens;
|
|
2089
|
+
try {
|
|
2090
|
+
tokens = await loadTokens(project.root, project.config);
|
|
2091
|
+
} catch (error) {
|
|
2092
|
+
throw new CliError(error.message, ExitCode.notFound);
|
|
2093
|
+
}
|
|
2094
|
+
return {
|
|
2095
|
+
project,
|
|
2096
|
+
tokens,
|
|
2097
|
+
fonts: fontSetup(project.config)
|
|
2098
|
+
};
|
|
2099
|
+
}
|
|
2100
|
+
async function readInput(value) {
|
|
2101
|
+
let text = value;
|
|
2102
|
+
if (value === "-") {
|
|
2103
|
+
const chunks = [];
|
|
2104
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
2105
|
+
text = Buffer.concat(chunks).toString("utf8");
|
|
2106
|
+
} else if (!value.trimStart().startsWith("{") && !value.trimStart().startsWith("[") && existsSync(value)) text = readFileSync(value, "utf8");
|
|
2107
|
+
try {
|
|
2108
|
+
return JSON.parse(text);
|
|
2109
|
+
} catch (error) {
|
|
2110
|
+
throw new CliError(`input is not valid JSON: ${error.message}`, ExitCode.usage, "pass JSON inline, a file path, or - for stdin");
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
2113
|
+
// ../renderer/dist/index.js
|
|
2114
|
+
/**
|
|
2115
|
+
* Puts nodes into a state without a pointer. With `target`, hover/press/focus apply to it and its
|
|
2116
|
+
* ancestors (as a real pointer would) and `data-state` values to it and its descendants; without,
|
|
2117
|
+
* to every node under `scope`.
|
|
2118
|
+
*/
|
|
2119
|
+
function applyMotionState(scope, state, target) {
|
|
2120
|
+
const forced = {
|
|
2121
|
+
hover: "data-force-hover",
|
|
2122
|
+
press: "data-force-active",
|
|
2123
|
+
focus: "data-force-focus"
|
|
2124
|
+
};
|
|
2125
|
+
const all = Array.from(scope.querySelectorAll("[data-node-id]"));
|
|
2126
|
+
for (const element of all) {
|
|
2127
|
+
for (const attr of Object.values(forced)) element.removeAttribute(attr);
|
|
2128
|
+
if (element.hasAttribute("data-lamsa-states")) element.removeAttribute("data-state");
|
|
2129
|
+
}
|
|
2130
|
+
if (state === "rest") return;
|
|
2131
|
+
const attr = forced[state];
|
|
2132
|
+
let elements = all;
|
|
2133
|
+
if (target) {
|
|
2134
|
+
if (attr) {
|
|
2135
|
+
elements = [];
|
|
2136
|
+
for (let current = target; current; current = current.parentElement) if (current.hasAttribute("data-node-id")) elements.push(current);
|
|
2137
|
+
} else elements = [target, ...Array.from(target.querySelectorAll("[data-node-id]"))];
|
|
2138
|
+
}
|
|
2139
|
+
for (const element of elements) if (attr) element.setAttribute(attr, "");
|
|
2140
|
+
else if ((element.getAttribute("data-lamsa-states") ?? "").split(" ").includes(state)) element.setAttribute("data-state", state);
|
|
2141
|
+
}
|
|
2142
|
+
/** Jumps finite animations and transitions to their end; parks infinite ones at their start. */
|
|
2143
|
+
function settleAnimations(scope) {
|
|
2144
|
+
for (const animation of scope.getAnimations()) {
|
|
2145
|
+
const timing = animation.effect?.getComputedTiming();
|
|
2146
|
+
if (timing && timing.endTime === 1e400) {
|
|
2147
|
+
animation.pause();
|
|
2148
|
+
animation.currentTime = 0;
|
|
2149
|
+
} else try {
|
|
2150
|
+
animation.finish();
|
|
2151
|
+
} catch {
|
|
2152
|
+
animation.pause();
|
|
2153
|
+
}
|
|
2154
|
+
}
|
|
2155
|
+
}
|
|
2156
|
+
/** Milliseconds until every animation under `scope` ends; an infinite one counts one iteration. */
|
|
2157
|
+
function motionLength(scope) {
|
|
2158
|
+
let end = 0;
|
|
2159
|
+
for (const animation of scope.getAnimations()) {
|
|
2160
|
+
const timing = animation.effect?.getComputedTiming();
|
|
2161
|
+
if (!timing) continue;
|
|
2162
|
+
const delay = Number(timing.delay ?? 0);
|
|
2163
|
+
const duration = typeof timing.duration === "number" ? timing.duration : 0;
|
|
2164
|
+
const finite = timing.endTime === 1e400 ? delay + duration : Number(timing.endTime ?? 0);
|
|
2165
|
+
end = Math.max(end, finite);
|
|
2166
|
+
}
|
|
2167
|
+
return end;
|
|
2168
|
+
}
|
|
2169
|
+
/** Pauses every animation under `scope` at `time` ms. */
|
|
2170
|
+
function seekAnimations(scope, time) {
|
|
2171
|
+
for (const animation of scope.getAnimations()) {
|
|
2172
|
+
animation.pause();
|
|
2173
|
+
animation.currentTime = time;
|
|
2174
|
+
}
|
|
2175
|
+
}
|
|
2176
|
+
const UNITLESS = /* @__PURE__ */ new Set([
|
|
2177
|
+
"opacity",
|
|
2178
|
+
"z-index",
|
|
2179
|
+
"flex",
|
|
2180
|
+
"flex-grow",
|
|
2181
|
+
"flex-shrink",
|
|
2182
|
+
"font-weight",
|
|
2183
|
+
"line-height",
|
|
2184
|
+
"order",
|
|
2185
|
+
"zoom",
|
|
2186
|
+
"aspect-ratio",
|
|
2187
|
+
"grid-row",
|
|
2188
|
+
"grid-column",
|
|
2189
|
+
"grid-row-start",
|
|
2190
|
+
"grid-row-end",
|
|
2191
|
+
"grid-column-start",
|
|
2192
|
+
"grid-column-end",
|
|
2193
|
+
"orphans",
|
|
2194
|
+
"widows",
|
|
2195
|
+
"tab-size",
|
|
2196
|
+
"fill-opacity",
|
|
2197
|
+
"stroke-opacity",
|
|
2198
|
+
"column-count",
|
|
2199
|
+
"scale"
|
|
2200
|
+
]);
|
|
2201
|
+
const ICON_DEFAULT_SIZE = 24;
|
|
2202
|
+
/** Rendering every top-level frame of one node map reuses one index instead of rebuilding it per frame. */
|
|
2203
|
+
const childMaps = /* @__PURE__ */ new WeakMap();
|
|
2204
|
+
function childMap(nodes) {
|
|
2205
|
+
const cached = childMaps.get(nodes);
|
|
2206
|
+
if (cached) return cached;
|
|
2207
|
+
const map = /* @__PURE__ */ new Map();
|
|
2208
|
+
for (const [id, node] of Object.entries(nodes)) {
|
|
2209
|
+
if (node.parentId === void 0) continue;
|
|
2210
|
+
const list = map.get(node.parentId) ?? [];
|
|
2211
|
+
list.push(id);
|
|
2212
|
+
map.set(node.parentId, list);
|
|
2213
|
+
}
|
|
2214
|
+
for (const list of map.values()) list.sort((a, b) => {
|
|
2215
|
+
const ia = nodes[a]?.index ?? "";
|
|
2216
|
+
const ib = nodes[b]?.index ?? "";
|
|
2217
|
+
return ia < ib ? -1 : ia > ib ? 1 : a < b ? -1 : a > b ? 1 : 0;
|
|
2218
|
+
});
|
|
2219
|
+
childMaps.set(nodes, map);
|
|
2220
|
+
return map;
|
|
2221
|
+
}
|
|
2222
|
+
function cssValue(property, value) {
|
|
2223
|
+
if (typeof value === "number") return UNITLESS.has(property) || property.startsWith("--") || value === 0 ? String(value) : `${value}px`;
|
|
2224
|
+
return value;
|
|
2225
|
+
}
|
|
2226
|
+
function resolveStyle(style, context) {
|
|
2227
|
+
const result = {};
|
|
2228
|
+
for (const [property, value] of Object.entries(style ?? {})) {
|
|
2229
|
+
const { css, missing } = resolveTokenRefs(cssValue(property, value), context.options.tokens.tokens);
|
|
2230
|
+
for (const path of missing) context.missingTokens.add(path);
|
|
2231
|
+
result[property] = css;
|
|
2232
|
+
}
|
|
2233
|
+
return result;
|
|
2234
|
+
}
|
|
2235
|
+
const joinCss = (...parts) => {
|
|
2236
|
+
const kept = parts.filter((part) => !!part && part.trim().length > 0);
|
|
2237
|
+
return kept.length ? kept.join("\n") : void 0;
|
|
2238
|
+
};
|
|
2239
|
+
function mergePatch(into, patches) {
|
|
2240
|
+
for (const [id, patch] of Object.entries(patches ?? {})) {
|
|
2241
|
+
const current = into.get(id) ?? {};
|
|
2242
|
+
into.set(id, {
|
|
2243
|
+
...current,
|
|
2244
|
+
...patch,
|
|
2245
|
+
style: {
|
|
2246
|
+
...current.style,
|
|
2247
|
+
...patch.style
|
|
2248
|
+
},
|
|
2249
|
+
css: joinCss(current.css, patch.css)
|
|
2250
|
+
});
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
/**
|
|
2254
|
+
* A node with its own `css` gets one rule: its `style` first, then its CSS. Inline styles would
|
|
2255
|
+
* beat every rule, so the style moves out of the element; `&:hover { … }` and friends can then
|
|
2256
|
+
* override style values by normal specificity.
|
|
2257
|
+
*/
|
|
2258
|
+
function withNodeCss(element, css, context) {
|
|
2259
|
+
if (!css?.trim() || element.style.display === "none") return element;
|
|
2260
|
+
const { css: resolved, missing } = resolveTokenRefs(css, context.options.tokens.tokens);
|
|
2261
|
+
for (const path of missing) context.missingTokens.add(path);
|
|
2262
|
+
const declarations = Object.entries(element.style).map(([property, value]) => `${property}: ${value};`);
|
|
2263
|
+
context.rules.push(`[data-node-id="${element.nodeId.replace(/"/g, "\\\"")}"] {\n${[...declarations, resolved].join("\n")}\n}`);
|
|
2264
|
+
return {
|
|
2265
|
+
...element,
|
|
2266
|
+
style: {}
|
|
2267
|
+
};
|
|
2268
|
+
}
|
|
2269
|
+
/** `data-state` values a node's CSS styles on itself, e.g. `&[data-state="open"]` gives `open`. */
|
|
2270
|
+
function cssStates(css) {
|
|
2271
|
+
if (!css) return [];
|
|
2272
|
+
return [...new Set([...css.matchAll(/&\[data-state\s*=\s*["']?([\w-]+)["']?\s*\]/g)].map((m) => m[1]))];
|
|
2273
|
+
}
|
|
2274
|
+
/** Marks elements whose CSS styles `data-state` values, so previews and renders can set them. */
|
|
2275
|
+
function stateAttrs(css) {
|
|
2276
|
+
const states = cssStates(css);
|
|
2277
|
+
return states.length ? { "data-lamsa-states": states.join(" ") } : {};
|
|
2278
|
+
}
|
|
2279
|
+
const FORCEABLE = /:(hover|active|focus-visible|focus)(?![-\w])/g;
|
|
2280
|
+
const FORCE_ATTR = {
|
|
2281
|
+
hover: "hover",
|
|
2282
|
+
active: "active",
|
|
2283
|
+
"focus-visible": "focus",
|
|
2284
|
+
focus: "focus"
|
|
2285
|
+
};
|
|
2286
|
+
/**
|
|
2287
|
+
* Lets a preview put elements into a state without the pointer: `:hover` also matches
|
|
2288
|
+
* `[data-force-hover]`, `:active` `[data-force-active]`, `:focus`/`:focus-visible` `[data-force-focus]`.
|
|
2289
|
+
*/
|
|
2290
|
+
function withForcedStates(css) {
|
|
2291
|
+
return css.replace(FORCEABLE, (_, state) => `:is(:${state}, [data-force-${FORCE_ATTR[state]}])`);
|
|
2292
|
+
}
|
|
2293
|
+
function instancePatches(instance, component) {
|
|
2294
|
+
const patches = /* @__PURE__ */ new Map();
|
|
2295
|
+
if (component.type !== "frame" || !component.component) return patches;
|
|
2296
|
+
for (const [name, def] of Object.entries(component.component.props ?? {})) {
|
|
2297
|
+
const given = instance.props?.[name];
|
|
2298
|
+
if (def.type === "enum") {
|
|
2299
|
+
const value = typeof given === "string" ? given : def.default;
|
|
2300
|
+
mergePatch(patches, def.overrides?.[value]);
|
|
2301
|
+
} else if (def.type === "boolean") mergePatch(patches, (typeof given === "boolean" ? given : def.default) ? def.overrides?.true : def.overrides?.false);
|
|
2302
|
+
else {
|
|
2303
|
+
const value = typeof given === "string" ? given : def.default;
|
|
2304
|
+
mergePatch(patches, { [def.target]: { content: value } });
|
|
2305
|
+
}
|
|
2306
|
+
}
|
|
2307
|
+
mergePatch(patches, instance.overrides);
|
|
2308
|
+
return patches;
|
|
2309
|
+
}
|
|
2310
|
+
function applyPatch(node, patch) {
|
|
2311
|
+
if (!patch) return node;
|
|
2312
|
+
const next = {
|
|
2313
|
+
...node,
|
|
2314
|
+
style: {
|
|
2315
|
+
...node.style,
|
|
2316
|
+
...patch.style
|
|
2317
|
+
}
|
|
2318
|
+
};
|
|
2319
|
+
const css = joinCss(node.css, patch.css);
|
|
2320
|
+
if (css !== void 0) next.css = css;
|
|
2321
|
+
if (patch.hidden !== void 0) next.hidden = patch.hidden;
|
|
2322
|
+
if (patch.content !== void 0 && next.type === "text") next.content = patch.content;
|
|
2323
|
+
if (patch.src !== void 0 && next.type === "image") next.src = patch.src;
|
|
2324
|
+
if (patch.icon !== void 0 && next.type === "icon") next.icon = patch.icon;
|
|
2325
|
+
return next;
|
|
2326
|
+
}
|
|
2327
|
+
function renderNode({ id, displayId, node, context, patches, isRoot }) {
|
|
2328
|
+
const { nodes } = context.options;
|
|
2329
|
+
const style = resolveStyle(node.style, context);
|
|
2330
|
+
if (node.hidden) style.display = "none";
|
|
2331
|
+
const base = {
|
|
2332
|
+
nodeId: displayId,
|
|
2333
|
+
nodeType: node.type,
|
|
2334
|
+
attrs: {
|
|
2335
|
+
"data-node-id": displayId,
|
|
2336
|
+
...stateAttrs(node.css)
|
|
2337
|
+
}
|
|
2338
|
+
};
|
|
2339
|
+
if (isRoot) {
|
|
2340
|
+
style.position ??= "relative";
|
|
2341
|
+
style.overflow ??= "hidden";
|
|
2342
|
+
}
|
|
2343
|
+
if (node.type === "instance") {
|
|
2344
|
+
const component = nodes[node.componentId];
|
|
2345
|
+
if (!component || context.depth > 32) return {
|
|
2346
|
+
...base,
|
|
2347
|
+
tag: "div",
|
|
2348
|
+
style: {
|
|
2349
|
+
...style,
|
|
2350
|
+
outline: "2px dashed #e5484d"
|
|
2351
|
+
},
|
|
2352
|
+
children: [],
|
|
2353
|
+
text: `missing component ${node.componentId}`
|
|
2354
|
+
};
|
|
2355
|
+
const own = instancePatches(node, component);
|
|
2356
|
+
const rootPatch = own.get(node.componentId);
|
|
2357
|
+
const merged = {
|
|
2358
|
+
...applyPatch(component, rootPatch),
|
|
2359
|
+
style: {
|
|
2360
|
+
...component.style,
|
|
2361
|
+
...rootPatch?.style,
|
|
2362
|
+
...node.style
|
|
2363
|
+
},
|
|
2364
|
+
css: joinCss(component.css, rootPatch?.css, node.css),
|
|
2365
|
+
hidden: node.hidden ?? component.hidden
|
|
2366
|
+
};
|
|
2367
|
+
context.depth++;
|
|
2368
|
+
const element = renderFrameLike({
|
|
2369
|
+
id: node.componentId,
|
|
2370
|
+
displayId,
|
|
2371
|
+
node: merged,
|
|
2372
|
+
context,
|
|
2373
|
+
patches: own,
|
|
2374
|
+
prefix: displayId,
|
|
2375
|
+
isRoot,
|
|
2376
|
+
nodeType: "instance"
|
|
2377
|
+
});
|
|
2378
|
+
context.depth--;
|
|
2379
|
+
return element;
|
|
2380
|
+
}
|
|
2381
|
+
if (node.type === "frame") return renderFrameLike({
|
|
2382
|
+
id,
|
|
2383
|
+
displayId,
|
|
2384
|
+
node,
|
|
2385
|
+
context,
|
|
2386
|
+
patches,
|
|
2387
|
+
prefix: void 0,
|
|
2388
|
+
isRoot,
|
|
2389
|
+
nodeType: "frame"
|
|
2390
|
+
});
|
|
2391
|
+
if (node.type === "text") {
|
|
2392
|
+
style["white-space"] ??= "pre-wrap";
|
|
2393
|
+
return withNodeCss({
|
|
2394
|
+
...base,
|
|
2395
|
+
tag: "div",
|
|
2396
|
+
style,
|
|
2397
|
+
children: [],
|
|
2398
|
+
text: node.content
|
|
2399
|
+
}, node.css, context);
|
|
2400
|
+
}
|
|
2401
|
+
if (node.type === "image") {
|
|
2402
|
+
const src = context.options.assetUrl ? context.options.assetUrl(node.src) : node.src;
|
|
2403
|
+
return withNodeCss({
|
|
2404
|
+
...base,
|
|
2405
|
+
tag: "img",
|
|
2406
|
+
style,
|
|
2407
|
+
attrs: {
|
|
2408
|
+
...base.attrs,
|
|
2409
|
+
src,
|
|
2410
|
+
alt: node.alt ?? ""
|
|
2411
|
+
},
|
|
2412
|
+
children: []
|
|
2413
|
+
}, node.css, context);
|
|
2414
|
+
}
|
|
2415
|
+
const svg = context.options.iconSvg(node.icon);
|
|
2416
|
+
if (!svg) context.missingIcons.add(node.icon);
|
|
2417
|
+
style.width ??= `${ICON_DEFAULT_SIZE}px`;
|
|
2418
|
+
style.height ??= `${ICON_DEFAULT_SIZE}px`;
|
|
2419
|
+
style["flex-shrink"] ??= "0";
|
|
2420
|
+
return withNodeCss({
|
|
2421
|
+
...base,
|
|
2422
|
+
tag: "div",
|
|
2423
|
+
className: "lamsa-icon",
|
|
2424
|
+
style,
|
|
2425
|
+
children: [],
|
|
2426
|
+
html: svg ?? ""
|
|
2427
|
+
}, node.css, context);
|
|
2428
|
+
}
|
|
2429
|
+
function renderFrameLike({ id, displayId, node, context, patches, prefix, isRoot, nodeType }) {
|
|
2430
|
+
const { nodes } = context.options;
|
|
2431
|
+
const style = resolveStyle(node.style, context);
|
|
2432
|
+
if (node.hidden) style.display = "none";
|
|
2433
|
+
if (isRoot) {
|
|
2434
|
+
style.position ??= "relative";
|
|
2435
|
+
style.overflow ??= "hidden";
|
|
2436
|
+
}
|
|
2437
|
+
const mode = node.type === "frame" ? node.mode : void 0;
|
|
2438
|
+
const children = (context.children.get(id) ?? []).map((childId) => {
|
|
2439
|
+
const child = nodes[childId];
|
|
2440
|
+
const childDisplayId = prefix ? `${prefix}/${childId}` : childId;
|
|
2441
|
+
const patched = applyPatch(child, patches?.get(childId));
|
|
2442
|
+
if (patched.type === "instance") return renderNode({
|
|
2443
|
+
id: childId,
|
|
2444
|
+
displayId: childDisplayId,
|
|
2445
|
+
node: patched,
|
|
2446
|
+
context,
|
|
2447
|
+
isRoot: false
|
|
2448
|
+
});
|
|
2449
|
+
if (patched.type === "frame") return renderFrameLike({
|
|
2450
|
+
id: childId,
|
|
2451
|
+
displayId: childDisplayId,
|
|
2452
|
+
node: patched,
|
|
2453
|
+
context,
|
|
2454
|
+
patches,
|
|
2455
|
+
prefix,
|
|
2456
|
+
isRoot: false,
|
|
2457
|
+
nodeType: "frame"
|
|
2458
|
+
});
|
|
2459
|
+
return renderNode({
|
|
2460
|
+
id: childId,
|
|
2461
|
+
displayId: childDisplayId,
|
|
2462
|
+
node: patched,
|
|
2463
|
+
context,
|
|
2464
|
+
patches,
|
|
2465
|
+
isRoot: false
|
|
2466
|
+
});
|
|
2467
|
+
});
|
|
2468
|
+
return withNodeCss({
|
|
2469
|
+
tag: "div",
|
|
2470
|
+
nodeId: displayId,
|
|
2471
|
+
nodeType,
|
|
2472
|
+
className: mode,
|
|
2473
|
+
style,
|
|
2474
|
+
attrs: {
|
|
2475
|
+
"data-node-id": displayId,
|
|
2476
|
+
...stateAttrs(node.css)
|
|
2477
|
+
},
|
|
2478
|
+
children
|
|
2479
|
+
}, node.css, context);
|
|
2480
|
+
}
|
|
2481
|
+
function buildRenderTree(options) {
|
|
2482
|
+
const node = options.nodes[options.rootId];
|
|
2483
|
+
if (!node) throw new Error(`node ${options.rootId} not found`);
|
|
2484
|
+
const context = {
|
|
2485
|
+
options,
|
|
2486
|
+
missingTokens: /* @__PURE__ */ new Set(),
|
|
2487
|
+
missingIcons: /* @__PURE__ */ new Set(),
|
|
2488
|
+
children: childMap(options.nodes),
|
|
2489
|
+
depth: 0,
|
|
2490
|
+
rules: []
|
|
2491
|
+
};
|
|
2492
|
+
let root;
|
|
2493
|
+
if (node.type === "frame" && node.component) {
|
|
2494
|
+
const defaults = instancePatches({
|
|
2495
|
+
type: "instance",
|
|
2496
|
+
componentId: options.rootId,
|
|
2497
|
+
props: options.componentProps
|
|
2498
|
+
}, node);
|
|
2499
|
+
const own = applyPatch(node, defaults.get(options.rootId));
|
|
2500
|
+
root = renderFrameLike({
|
|
2501
|
+
id: options.rootId,
|
|
2502
|
+
displayId: options.rootId,
|
|
2503
|
+
node: own,
|
|
2504
|
+
context,
|
|
2505
|
+
patches: defaults,
|
|
2506
|
+
prefix: void 0,
|
|
2507
|
+
isRoot: true,
|
|
2508
|
+
nodeType: "frame"
|
|
2509
|
+
});
|
|
2510
|
+
} else root = renderNode({
|
|
2511
|
+
id: options.rootId,
|
|
2512
|
+
displayId: options.rootId,
|
|
2513
|
+
node,
|
|
2514
|
+
context,
|
|
2515
|
+
isRoot: true
|
|
2516
|
+
});
|
|
2517
|
+
const frameMode = node.type === "frame" ? node.mode : void 0;
|
|
2518
|
+
const mode = options.mode ?? frameMode ?? options.canvasMode ?? "light";
|
|
2519
|
+
if (options.mode) root.className = options.mode;
|
|
2520
|
+
const css = withForcedStates([options.fileCss ?? "", ...context.rules].filter((part) => part.trim()).join("\n"));
|
|
2521
|
+
return {
|
|
2522
|
+
root,
|
|
2523
|
+
css,
|
|
2524
|
+
mode,
|
|
2525
|
+
missingTokens: [...context.missingTokens],
|
|
2526
|
+
missingIcons: [...context.missingIcons]
|
|
2527
|
+
};
|
|
2528
|
+
}
|
|
2529
|
+
const ESCAPES = {
|
|
2530
|
+
"&": "&",
|
|
2531
|
+
"<": "<",
|
|
2532
|
+
">": ">",
|
|
2533
|
+
"\"": """
|
|
2534
|
+
};
|
|
2535
|
+
function escapeHtml(text) {
|
|
2536
|
+
return text.replace(/[&<>"]/g, (c) => ESCAPES[c]);
|
|
2537
|
+
}
|
|
2538
|
+
function styleString(style) {
|
|
2539
|
+
return Object.entries(style).map(([property, value]) => `${property}: ${value}`).join("; ");
|
|
2540
|
+
}
|
|
2541
|
+
function toHtml(element) {
|
|
2542
|
+
const attrs = { ...element.attrs };
|
|
2543
|
+
if (element.className) attrs.class = element.className;
|
|
2544
|
+
const styleText = styleString(element.style);
|
|
2545
|
+
if (styleText) attrs.style = styleText;
|
|
2546
|
+
const attrText = Object.entries(attrs).map(([name, value]) => ` ${name}="${escapeHtml(value)}"`).join("");
|
|
2547
|
+
if (element.tag === "img") return `<img${attrText}>`;
|
|
2548
|
+
return `<div${attrText}>${element.html ?? (element.text !== void 0 ? escapeHtml(element.text) : element.children.map(toHtml).join(""))}</div>`;
|
|
2549
|
+
}
|
|
2550
|
+
/** Base styles every render uses, in the editor and in exports. */
|
|
2551
|
+
function baseCss(tokens) {
|
|
2552
|
+
return `*, ::before, ::after { box-sizing: border-box; margin: 0; padding: 0; border: 0 solid; }
|
|
2553
|
+
img, svg { display: block; max-width: 100%; }
|
|
2554
|
+
.lamsa-surface { font-family: ${tokens.tokens["font.sans"]?.css ?? "ui-sans-serif, system-ui, sans-serif"}; color: ${tokens.tokens["color.foreground"]?.css ?? "#0a0a0a"}; line-height: 1.5; -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; }
|
|
2555
|
+
.lamsa-icon > svg { width: 100%; height: 100%; }
|
|
2556
|
+
`;
|
|
2557
|
+
}
|
|
2558
|
+
function renderDocument({ result, tokens, fontCss = "", fontLinks = [], baseHref }) {
|
|
2559
|
+
const links = fontLinks.map((href) => `<link rel="stylesheet" href="${escapeHtml(href)}">`).join("\n");
|
|
2560
|
+
return `<!doctype html>
|
|
2561
|
+
<html>
|
|
2562
|
+
<head>
|
|
2563
|
+
<meta charset="utf-8">
|
|
2564
|
+
${baseHref ? `<base href="${escapeHtml(baseHref)}">` : ""}
|
|
2565
|
+
${links}
|
|
2566
|
+
<style>
|
|
2567
|
+
${baseCss(tokens)}
|
|
2568
|
+
${tokens.css}
|
|
2569
|
+
${fontCss}
|
|
2570
|
+
html, body { background: transparent; }
|
|
2571
|
+
${result.css}
|
|
2572
|
+
</style>
|
|
2573
|
+
</head>
|
|
2574
|
+
<body>
|
|
2575
|
+
<div id="lamsa-render" class="lamsa-surface ${result.mode}" style="display: inline-block">${toHtml(result.root)}</div>
|
|
2576
|
+
</body>
|
|
2577
|
+
</html>
|
|
2578
|
+
`;
|
|
2579
|
+
}
|
|
2580
|
+
// src/render.ts
|
|
2581
|
+
const require = createRequire(import.meta.url);
|
|
2582
|
+
const call = (fn, ...args) => `(${fn.toString()})(${args.map((arg) => arg === "document" ? "document" : JSON.stringify(arg)).join(", ")})`;
|
|
2583
|
+
/** Screenshots the frame at evenly spaced moments of its motion and lays them out in one image. */
|
|
2584
|
+
async function captureStrip({ page, frames, path, label }) {
|
|
2585
|
+
const target = page.locator("#lamsa-render > div").first();
|
|
2586
|
+
const length = await page.evaluate(call(motionLength, "document"));
|
|
2587
|
+
const count = length > 0 ? Math.max(2, frames) : 1;
|
|
2588
|
+
const times = Array.from({ length: count }, (_, i) => count === 1 ? 0 : Math.round(length * i / (count - 1)));
|
|
2589
|
+
const shots = [];
|
|
2590
|
+
for (const time of times) {
|
|
2591
|
+
await page.evaluate(call(seekAnimations, "document", time));
|
|
2592
|
+
shots.push((await target.screenshot({ omitBackground: true })).toString("base64"));
|
|
2593
|
+
}
|
|
2594
|
+
const box = await target.boundingBox();
|
|
2595
|
+
const cellWidth = Math.min(box.width, 480);
|
|
2596
|
+
const cells = shots.map((shot, i) => `<figure><img src="data:image/png;base64,${shot}" style="width:${cellWidth}px"><figcaption>${times[i]} ms</figcaption></figure>`).join("");
|
|
2597
|
+
await page.setContent(`<!doctype html><html><body style="margin:0;background:#f3f2ee;font:12px ui-monospace,monospace;color:#585955">
|
|
2598
|
+
<div id="strip" style="display:inline-flex;flex-direction:column;gap:8px;padding:16px">
|
|
2599
|
+
<div>${label}${length > 0 ? ` · ${length} ms` : " · no animations"}</div>
|
|
2600
|
+
<div style="display:flex;gap:16px;align-items:flex-start">${cells}</div></div>
|
|
2601
|
+
<style>figure{margin:0;display:flex;flex-direction:column;gap:6px;align-items:center}img{display:block;background:#fff;outline:1px solid #e2dfd8}</style>
|
|
2602
|
+
</body></html>`);
|
|
2603
|
+
await page.setViewportSize({
|
|
2604
|
+
width: Math.ceil(32 + count * (cellWidth + 16)),
|
|
2605
|
+
height: 900
|
|
2606
|
+
});
|
|
2607
|
+
await page.locator("#strip").screenshot({ path });
|
|
2608
|
+
return times;
|
|
2609
|
+
}
|
|
2610
|
+
/**
|
|
2611
|
+
* Outlines layers over the render. A layer inside a component instance renders as `<instance>/<layer>`,
|
|
2612
|
+
* so a component's own layer IDs find it in every instance.
|
|
2613
|
+
*/
|
|
2614
|
+
function drawMarks(marks) {
|
|
2615
|
+
const target = document.querySelector("#lamsa-render > div");
|
|
2616
|
+
if (!target) return;
|
|
2617
|
+
const frame = target.getBoundingClientRect();
|
|
2618
|
+
const layer = document.createElement("div");
|
|
2619
|
+
layer.id = "lamsa-marks";
|
|
2620
|
+
layer.style.cssText = `position:absolute;left:${frame.left + scrollX}px;top:${frame.top + scrollY}px;width:${frame.width}px;height:${frame.height}px;pointer-events:none;z-index:2147483647`;
|
|
2621
|
+
for (const { ids, color } of marks) for (const id of ids) {
|
|
2622
|
+
const escaped = CSS.escape(id);
|
|
2623
|
+
for (const element of Array.from(document.querySelectorAll(`[data-node-id="${escaped}"], [data-node-id$="/${escaped}"]`))) {
|
|
2624
|
+
const box = element.getBoundingClientRect();
|
|
2625
|
+
if (box.width === 0 && box.height === 0) continue;
|
|
2626
|
+
const outline = document.createElement("div");
|
|
2627
|
+
const left = Math.max(0, box.left - frame.left - 2);
|
|
2628
|
+
const top = Math.max(0, box.top - frame.top - 2);
|
|
2629
|
+
const right = Math.min(frame.width, box.right - frame.left + 2);
|
|
2630
|
+
const bottom = Math.min(frame.height, box.bottom - frame.top + 2);
|
|
2631
|
+
outline.style.cssText = `position:absolute;left:${left}px;top:${top}px;width:${right - left}px;height:${bottom - top}px;border:2px solid ${color};border-radius:4px;background:color-mix(in srgb, ${color} 12%, transparent);box-sizing:border-box`;
|
|
2632
|
+
layer.append(outline);
|
|
2633
|
+
}
|
|
2634
|
+
}
|
|
2635
|
+
document.body.append(layer);
|
|
2636
|
+
}
|
|
2637
|
+
function installChromium(log) {
|
|
2638
|
+
if (process.env.LAMSA_NO_BROWSER_DOWNLOAD) throw new CliError("no Chrome or Chromium found and LAMSA_NO_BROWSER_DOWNLOAD is set", ExitCode.renderFailed, "install Google Chrome, or unset LAMSA_NO_BROWSER_DOWNLOAD to let lamsa download Chromium once");
|
|
2639
|
+
log("lamsa: downloading Chromium for rendering (one time)…");
|
|
2640
|
+
const cli = join(dirname(require.resolve("playwright-core/package.json")), "cli.js");
|
|
2641
|
+
execFileSync(process.execPath, [
|
|
2642
|
+
cli,
|
|
2643
|
+
"install",
|
|
2644
|
+
"chromium-headless-shell"
|
|
2645
|
+
], {
|
|
2646
|
+
stdio: [
|
|
2647
|
+
"ignore",
|
|
2648
|
+
"ignore",
|
|
2649
|
+
"inherit"
|
|
2650
|
+
],
|
|
2651
|
+
env: {
|
|
2652
|
+
...process.env,
|
|
2653
|
+
ELECTRON_RUN_AS_NODE: "1"
|
|
2654
|
+
}
|
|
2655
|
+
});
|
|
2656
|
+
}
|
|
2657
|
+
async function launchBrowser(log = () => {}) {
|
|
2658
|
+
if (!process.env.LAMSA_BUNDLED_CHROMIUM) try {
|
|
2659
|
+
return await chromium.launch({ channel: "chrome" });
|
|
2660
|
+
} catch {}
|
|
2661
|
+
try {
|
|
2662
|
+
return await chromium.launch();
|
|
2663
|
+
} catch (error) {
|
|
2664
|
+
if (!/Executable doesn't exist|install/i.test(error.message)) throw error;
|
|
2665
|
+
}
|
|
2666
|
+
installChromium(log);
|
|
2667
|
+
return chromium.launch();
|
|
2668
|
+
}
|
|
2669
|
+
async function renderFrames({ workspace, ids, outDir, scale = 2, mode, naming, log, animate, state, marks, markedNaming }) {
|
|
2670
|
+
const { project, tokens, fonts } = workspace;
|
|
2671
|
+
const nodes = allNodes(project);
|
|
2672
|
+
const fileCss = allFileCss(project);
|
|
2673
|
+
const browser = await launchBrowser(log);
|
|
2674
|
+
const scratch = mkdtempSync(join(tmpdir(), "lamsa-render-"));
|
|
2675
|
+
const baseHref = pathToFileURL(project.root + "/").href;
|
|
2676
|
+
const results = [];
|
|
2677
|
+
try {
|
|
2678
|
+
const context = await browser.newContext({
|
|
2679
|
+
deviceScaleFactor: scale,
|
|
2680
|
+
viewport: {
|
|
2681
|
+
width: 1440,
|
|
2682
|
+
height: 900
|
|
2683
|
+
}
|
|
2684
|
+
});
|
|
2685
|
+
const page = await context.newPage();
|
|
2686
|
+
for (const id of ids) {
|
|
2687
|
+
const result = buildRenderTree({
|
|
2688
|
+
nodes,
|
|
2689
|
+
rootId: id,
|
|
2690
|
+
tokens,
|
|
2691
|
+
mode,
|
|
2692
|
+
iconSvg: lucideIconSvg,
|
|
2693
|
+
fileCss
|
|
2694
|
+
});
|
|
2695
|
+
const html = renderDocument({
|
|
2696
|
+
result,
|
|
2697
|
+
tokens,
|
|
2698
|
+
fontCss: fonts.css,
|
|
2699
|
+
fontLinks: fonts.links,
|
|
2700
|
+
baseHref
|
|
2701
|
+
});
|
|
2702
|
+
await page.setViewportSize({
|
|
2703
|
+
width: 1440,
|
|
2704
|
+
height: 900
|
|
2705
|
+
});
|
|
2706
|
+
const file = join(scratch, `${id}.html`);
|
|
2707
|
+
writeFileSync(file, html);
|
|
2708
|
+
await page.goto(pathToFileURL(file).href, { waitUntil: "load" });
|
|
2709
|
+
await page.evaluate(async () => {
|
|
2710
|
+
await document.fonts.ready;
|
|
2711
|
+
});
|
|
2712
|
+
if (state) {
|
|
2713
|
+
await page.evaluate(call(settleAnimations, "document"));
|
|
2714
|
+
await page.evaluate(call(applyMotionState, "document", state));
|
|
2715
|
+
await page.evaluate(() => document.body.getBoundingClientRect());
|
|
2716
|
+
}
|
|
2717
|
+
if (!animate) await page.evaluate(call(settleAnimations, "document"));
|
|
2718
|
+
const target = page.locator("#lamsa-render > div").first();
|
|
2719
|
+
const box = await target.boundingBox();
|
|
2720
|
+
if (!box) throw new CliError(`node ${id} rendered with no size`, ExitCode.renderFailed, "give the frame a width and height", id);
|
|
2721
|
+
if (box.width > 1440 || box.height > 900) await page.setViewportSize({
|
|
2722
|
+
width: Math.ceil(Math.max(1440, box.width)),
|
|
2723
|
+
height: Math.ceil(Math.max(900, box.height))
|
|
2724
|
+
});
|
|
2725
|
+
const path = join(outDir, naming(id));
|
|
2726
|
+
let times;
|
|
2727
|
+
if (animate) times = await captureStrip({
|
|
2728
|
+
page,
|
|
2729
|
+
frames: animate,
|
|
2730
|
+
path,
|
|
2731
|
+
label: `${nodes[id]?.name ?? id}${state ? ` · ${state}` : ""}`
|
|
2732
|
+
});
|
|
2733
|
+
else await target.screenshot({
|
|
2734
|
+
path,
|
|
2735
|
+
omitBackground: true
|
|
2736
|
+
});
|
|
2737
|
+
let markedPath;
|
|
2738
|
+
const frameMarks = marks?.[id]?.filter((mark) => mark.ids.length > 0);
|
|
2739
|
+
if (!animate && frameMarks?.length && markedNaming) {
|
|
2740
|
+
markedPath = join(outDir, markedNaming(id));
|
|
2741
|
+
await page.evaluate(call(drawMarks, frameMarks));
|
|
2742
|
+
await target.screenshot({
|
|
2743
|
+
path: markedPath,
|
|
2744
|
+
omitBackground: true
|
|
2745
|
+
});
|
|
2746
|
+
}
|
|
2747
|
+
results.push({
|
|
2748
|
+
markedPath,
|
|
2749
|
+
times,
|
|
2750
|
+
id,
|
|
2751
|
+
name: nodes[id]?.name,
|
|
2752
|
+
path,
|
|
2753
|
+
width: Math.round(box.width),
|
|
2754
|
+
height: Math.round(box.height),
|
|
2755
|
+
mode: result.mode,
|
|
2756
|
+
missingTokens: result.missingTokens,
|
|
2757
|
+
missingIcons: result.missingIcons
|
|
2758
|
+
});
|
|
2759
|
+
}
|
|
2760
|
+
await context.close();
|
|
2761
|
+
} finally {
|
|
2762
|
+
await browser.close();
|
|
2763
|
+
rmSync(scratch, {
|
|
2764
|
+
recursive: true,
|
|
2765
|
+
force: true
|
|
2766
|
+
});
|
|
2767
|
+
}
|
|
2768
|
+
return results;
|
|
2769
|
+
}
|
|
2770
|
+
export { recordActivity as A, validateProject as B, loadComments as C, moveNode as D, loadTokens as E, stableStringify as F, createOutput as G, designFileJsonSchema as H, summarize as I, formatIssue as K, toRepoPath as L, replyToComment as M, resolveComment as N, readDesignFile as O, saveDesignFile as P, treeLines as R, listDesignFiles as S, loadProject as T, CliError as U, writeFileAtomic as V, ExitCode as W, fontSetup as _, resolveRoot as a, isDesignFile as b, addTree as c, commentAuthor as d, deleteNodes as f, findProjectRoot as g, diffAgainstRef as h, readInput as i, reopenComment as j, readSession as k, allNodes as l, didYouMean as m, renderFrames as n, CONFIG_FILE as o, detectTokenSource as p, reportError as q, openWorkspace as r, addComment as s, launchBrowser as t, buildChildIndex as u, formatDesignFile as v, loadConfig as w, isOpen as x, indexNodes as y, validateComments as z };
|