sketchframe 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +48 -2
- package/dist/sketchframe-mcp.cjs +1186 -0
- package/dist/sketchframe.cjs +1563 -0
- package/package.json +47 -4
|
@@ -0,0 +1,1563 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
// src/cli.ts
|
|
5
|
+
var import_node_fs3 = require("node:fs");
|
|
6
|
+
var import_node_os = require("node:os");
|
|
7
|
+
var import_node_path4 = require("node:path");
|
|
8
|
+
|
|
9
|
+
// ../core/src/format.ts
|
|
10
|
+
var MIMETYPE = "application/vnd.sketchframe+zip";
|
|
11
|
+
var MIMETYPE_FILE = "mimetype";
|
|
12
|
+
var DESIGN_FILE = "design.json";
|
|
13
|
+
var ANNOTATIONS_FILE = "annotations.json";
|
|
14
|
+
var README_FILE = "README.md";
|
|
15
|
+
var DEFAULT_PREVIEW_FILE = "preview@2x.png";
|
|
16
|
+
var STORED_EXTENSIONS = ["png", "jpg", "jpeg", "gif", "webp", "heic", "avif"];
|
|
17
|
+
function isObject(value) {
|
|
18
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
19
|
+
}
|
|
20
|
+
function number(value) {
|
|
21
|
+
return typeof value === "number" ? value : void 0;
|
|
22
|
+
}
|
|
23
|
+
function string(value) {
|
|
24
|
+
return typeof value === "string" ? value : void 0;
|
|
25
|
+
}
|
|
26
|
+
function compareNames(a, b) {
|
|
27
|
+
return a.localeCompare(b, void 0, { numeric: true, sensitivity: "base" });
|
|
28
|
+
}
|
|
29
|
+
function prettyJSON(value) {
|
|
30
|
+
return JSON.stringify(sortedKeys(value), null, 2);
|
|
31
|
+
}
|
|
32
|
+
function sortedKeys(value) {
|
|
33
|
+
if (Array.isArray(value)) return value.map(sortedKeys);
|
|
34
|
+
if (isObject(value)) {
|
|
35
|
+
return Object.fromEntries(
|
|
36
|
+
Object.keys(value).sort().map((key) => [key, sortedKeys(value[key])])
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
return value;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// ../core/src/annotations.ts
|
|
43
|
+
var annotationCategories = ["development", "interaction", "accessibility", "content"];
|
|
44
|
+
function parseAnnotations(text3) {
|
|
45
|
+
if (!text3) return [];
|
|
46
|
+
let file2;
|
|
47
|
+
try {
|
|
48
|
+
file2 = JSON.parse(text3);
|
|
49
|
+
} catch {
|
|
50
|
+
return [];
|
|
51
|
+
}
|
|
52
|
+
if (!isObject(file2) || !Array.isArray(file2.annotations)) return [];
|
|
53
|
+
return file2.annotations.flatMap((value) => {
|
|
54
|
+
if (!isObject(value)) return [];
|
|
55
|
+
const id = string(value.id);
|
|
56
|
+
const nodeId = string(value.nodeId);
|
|
57
|
+
const text4 = string(value.text);
|
|
58
|
+
const createdAt = string(value.createdAt);
|
|
59
|
+
if (id === void 0 || nodeId === void 0 || text4 === void 0 || createdAt === void 0) return [];
|
|
60
|
+
const category = annotationCategories.find((category2) => category2 === value.category) ?? "content";
|
|
61
|
+
return [
|
|
62
|
+
{
|
|
63
|
+
id,
|
|
64
|
+
nodeId,
|
|
65
|
+
sketchId: string(value.sketchId),
|
|
66
|
+
layerPath: Array.isArray(value.layerPath) ? value.layerPath.filter((name) => typeof name === "string") : [],
|
|
67
|
+
layerName: string(value.layerName) ?? "",
|
|
68
|
+
category,
|
|
69
|
+
text: text4,
|
|
70
|
+
createdAt,
|
|
71
|
+
updatedAt: string(value.updatedAt)
|
|
72
|
+
}
|
|
73
|
+
];
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
function annotatedNode(nodes, annotation) {
|
|
77
|
+
if (annotation.sketchId) {
|
|
78
|
+
const node3 = nodes.find((node4) => node4.sketchId === annotation.sketchId);
|
|
79
|
+
if (node3) return node3;
|
|
80
|
+
}
|
|
81
|
+
if (annotation.layerPath.length > 0) {
|
|
82
|
+
const key = JSON.stringify(annotation.layerPath);
|
|
83
|
+
const node3 = nodes.find((node4) => JSON.stringify(node4.path) === key);
|
|
84
|
+
if (node3) return node3;
|
|
85
|
+
}
|
|
86
|
+
const node2 = nodes.find((node3) => node3.id === annotation.nodeId);
|
|
87
|
+
return node2?.name === annotation.layerName ? node2 : void 0;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// ../core/src/zip.ts
|
|
91
|
+
var import_node_zlib = require("node:zlib");
|
|
92
|
+
var LOCAL = 67324752;
|
|
93
|
+
var CENTRAL = 33639248;
|
|
94
|
+
var END = 101010256;
|
|
95
|
+
var crcTable;
|
|
96
|
+
function crc32(data) {
|
|
97
|
+
if (!crcTable) {
|
|
98
|
+
crcTable = new Uint32Array(256);
|
|
99
|
+
for (let n = 0; n < 256; n++) {
|
|
100
|
+
let c = n;
|
|
101
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
|
|
102
|
+
crcTable[n] = c >>> 0;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
let crc = 4294967295;
|
|
106
|
+
for (let i = 0; i < data.length; i++) crc = crcTable[(crc ^ data[i]) & 255] ^ crc >>> 8;
|
|
107
|
+
return (crc ^ 4294967295) >>> 0;
|
|
108
|
+
}
|
|
109
|
+
function unzip(bytes) {
|
|
110
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
111
|
+
let end = -1;
|
|
112
|
+
for (let i = bytes.length - 22; i >= Math.max(0, bytes.length - 22 - 65535); i--) {
|
|
113
|
+
if (view.getUint32(i, true) === END) {
|
|
114
|
+
end = i;
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (end < 0) throw new Error("no end of central directory record");
|
|
119
|
+
const count = view.getUint16(end + 10, true);
|
|
120
|
+
let offset = view.getUint32(end + 16, true);
|
|
121
|
+
if (count === 65535 || offset === 4294967295) throw new Error("zip64 archives are not supported");
|
|
122
|
+
const decoder = new TextDecoder();
|
|
123
|
+
const entries = [];
|
|
124
|
+
for (let i = 0; i < count; i++) {
|
|
125
|
+
if (offset + 46 > bytes.length || view.getUint32(offset, true) !== CENTRAL) throw new Error("corrupt central directory");
|
|
126
|
+
const flags = view.getUint16(offset + 8, true);
|
|
127
|
+
const method = view.getUint16(offset + 10, true);
|
|
128
|
+
const expectedCRC = view.getUint32(offset + 16, true);
|
|
129
|
+
const compressedSize = view.getUint32(offset + 20, true);
|
|
130
|
+
const size = view.getUint32(offset + 24, true);
|
|
131
|
+
const nameLength = view.getUint16(offset + 28, true);
|
|
132
|
+
const extraLength = view.getUint16(offset + 30, true);
|
|
133
|
+
const commentLength = view.getUint16(offset + 32, true);
|
|
134
|
+
const localOffset = view.getUint32(offset + 42, true);
|
|
135
|
+
const name = decoder.decode(bytes.subarray(offset + 46, offset + 46 + nameLength));
|
|
136
|
+
offset += 46 + nameLength + extraLength + commentLength;
|
|
137
|
+
if (flags & 1) throw new Error(`${name} is encrypted`);
|
|
138
|
+
if (view.getUint32(localOffset, true) !== LOCAL) throw new Error(`corrupt local header for ${name}`);
|
|
139
|
+
const start = localOffset + 30 + view.getUint16(localOffset + 26, true) + view.getUint16(localOffset + 28, true);
|
|
140
|
+
const raw = bytes.subarray(start, start + compressedSize);
|
|
141
|
+
let data;
|
|
142
|
+
if (method === 0) data = raw;
|
|
143
|
+
else if (method === 8) data = new Uint8Array((0, import_node_zlib.inflateRawSync)(raw));
|
|
144
|
+
else throw new Error(`${name} uses unsupported compression method ${method}`);
|
|
145
|
+
if (data.length !== size || crc32(data) !== expectedCRC) throw new Error(`${name} is corrupt (checksum mismatch)`);
|
|
146
|
+
entries.push({ name, data });
|
|
147
|
+
}
|
|
148
|
+
return entries;
|
|
149
|
+
}
|
|
150
|
+
function zip(inputs, date = new Date(2026, 0, 1)) {
|
|
151
|
+
const encoder = new TextEncoder();
|
|
152
|
+
const dosTime = date.getHours() << 11 | date.getMinutes() << 5 | date.getSeconds() >> 1;
|
|
153
|
+
const dosDate = date.getFullYear() - 1980 << 9 | date.getMonth() + 1 << 5 | date.getDate();
|
|
154
|
+
const locals = [];
|
|
155
|
+
const centrals = [];
|
|
156
|
+
let offset = 0;
|
|
157
|
+
for (const input of inputs) {
|
|
158
|
+
const name = encoder.encode(input.name);
|
|
159
|
+
const crc = crc32(input.data);
|
|
160
|
+
let method = 0;
|
|
161
|
+
let body = input.data;
|
|
162
|
+
if (!input.store && input.data.length > 0) {
|
|
163
|
+
const deflated = new Uint8Array((0, import_node_zlib.deflateRawSync)(input.data, { level: 6 }));
|
|
164
|
+
if (deflated.length < input.data.length) {
|
|
165
|
+
method = 8;
|
|
166
|
+
body = deflated;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const flags = /^[\x20-\x7e]*$/.test(input.name) ? 0 : 2048;
|
|
170
|
+
const local = new Uint8Array(30 + name.length);
|
|
171
|
+
const lv = new DataView(local.buffer);
|
|
172
|
+
lv.setUint32(0, LOCAL, true);
|
|
173
|
+
lv.setUint16(4, 20, true);
|
|
174
|
+
lv.setUint16(6, flags, true);
|
|
175
|
+
lv.setUint16(8, method, true);
|
|
176
|
+
lv.setUint16(10, dosTime, true);
|
|
177
|
+
lv.setUint16(12, dosDate, true);
|
|
178
|
+
lv.setUint32(14, crc, true);
|
|
179
|
+
lv.setUint32(18, body.length, true);
|
|
180
|
+
lv.setUint32(22, input.data.length, true);
|
|
181
|
+
lv.setUint16(26, name.length, true);
|
|
182
|
+
lv.setUint16(28, 0, true);
|
|
183
|
+
local.set(name, 30);
|
|
184
|
+
const central = new Uint8Array(46 + name.length);
|
|
185
|
+
const cv = new DataView(central.buffer);
|
|
186
|
+
cv.setUint32(0, CENTRAL, true);
|
|
187
|
+
cv.setUint16(4, 788, true);
|
|
188
|
+
cv.setUint16(6, 20, true);
|
|
189
|
+
cv.setUint16(8, flags, true);
|
|
190
|
+
cv.setUint16(10, method, true);
|
|
191
|
+
cv.setUint16(12, dosTime, true);
|
|
192
|
+
cv.setUint16(14, dosDate, true);
|
|
193
|
+
cv.setUint32(16, crc, true);
|
|
194
|
+
cv.setUint32(20, body.length, true);
|
|
195
|
+
cv.setUint32(24, input.data.length, true);
|
|
196
|
+
cv.setUint16(28, name.length, true);
|
|
197
|
+
cv.setUint32(38, 33188 << 16 >>> 0, true);
|
|
198
|
+
cv.setUint32(42, offset, true);
|
|
199
|
+
central.set(name, 46);
|
|
200
|
+
locals.push(local, body);
|
|
201
|
+
centrals.push(central);
|
|
202
|
+
offset += local.length + body.length;
|
|
203
|
+
}
|
|
204
|
+
const centralSize = centrals.reduce((sum, part) => sum + part.length, 0);
|
|
205
|
+
const end = new Uint8Array(22);
|
|
206
|
+
const ev = new DataView(end.buffer);
|
|
207
|
+
ev.setUint32(0, END, true);
|
|
208
|
+
ev.setUint16(8, inputs.length, true);
|
|
209
|
+
ev.setUint16(10, inputs.length, true);
|
|
210
|
+
ev.setUint32(12, centralSize, true);
|
|
211
|
+
ev.setUint32(16, offset, true);
|
|
212
|
+
const out = new Uint8Array(offset + centralSize + end.length);
|
|
213
|
+
let position = 0;
|
|
214
|
+
for (const part of [...locals, ...centrals, end]) {
|
|
215
|
+
out.set(part, position);
|
|
216
|
+
position += part.length;
|
|
217
|
+
}
|
|
218
|
+
return out;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// ../core/src/archive.ts
|
|
222
|
+
function readArchive(bytes) {
|
|
223
|
+
let files;
|
|
224
|
+
try {
|
|
225
|
+
files = unzip(bytes);
|
|
226
|
+
} catch (error) {
|
|
227
|
+
throw new Error(`Not a readable Sketchframe archive (${error instanceof Error ? error.message : error}).`);
|
|
228
|
+
}
|
|
229
|
+
let entries = new Map(
|
|
230
|
+
files.filter(({ name }) => !name.endsWith("/") && !name.startsWith("__MACOSX/") && !name.endsWith(".DS_Store") && name !== MIMETYPE_FILE).map(({ name, data }) => [name, data])
|
|
231
|
+
);
|
|
232
|
+
if (!entries.has(DESIGN_FILE)) {
|
|
233
|
+
const prefixes = new Set([...entries.keys()].map((path) => path.split("/")[0]));
|
|
234
|
+
const [prefix] = prefixes;
|
|
235
|
+
if (prefixes.size === 1 && entries.has(`${prefix}/${DESIGN_FILE}`)) {
|
|
236
|
+
entries = new Map([...entries].map(([path, data]) => [path.slice(prefix.length + 1), data]));
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return entries;
|
|
240
|
+
}
|
|
241
|
+
function archiveFiles(bytes) {
|
|
242
|
+
const entries = readArchive(bytes);
|
|
243
|
+
return { kind: "archive", read: (path) => entries.get(normalise(path)), paths: () => [...entries.keys()] };
|
|
244
|
+
}
|
|
245
|
+
var leadingFiles = [README_FILE, DESIGN_FILE, ANNOTATIONS_FILE, DEFAULT_PREVIEW_FILE];
|
|
246
|
+
function writeArchive(entries) {
|
|
247
|
+
const map = entries instanceof Map ? entries : new Map(Object.entries(entries));
|
|
248
|
+
const paths = [...map.keys()].map(normalise).filter((path) => path !== MIMETYPE_FILE && path !== "" && !path.endsWith("/"));
|
|
249
|
+
const rank = (path) => {
|
|
250
|
+
const index = leadingFiles.indexOf(path);
|
|
251
|
+
return index === -1 ? leadingFiles.length : index;
|
|
252
|
+
};
|
|
253
|
+
paths.sort((a, b) => rank(a) - rank(b) || (a < b ? -1 : a > b ? 1 : 0));
|
|
254
|
+
const inputs = [{ name: MIMETYPE_FILE, data: strToU8(MIMETYPE), store: true }];
|
|
255
|
+
for (const path of paths) {
|
|
256
|
+
const value = map.get(path) ?? map.get(`./${path}`);
|
|
257
|
+
if (value === void 0) continue;
|
|
258
|
+
const data = typeof value === "string" ? strToU8(value) : value;
|
|
259
|
+
const extension = path.split(".").pop()?.toLowerCase() ?? "";
|
|
260
|
+
inputs.push({ name: path, data, store: STORED_EXTENSIONS.includes(extension) });
|
|
261
|
+
}
|
|
262
|
+
return zip(inputs);
|
|
263
|
+
}
|
|
264
|
+
function text(files, path) {
|
|
265
|
+
const bytes = files.read(path);
|
|
266
|
+
return bytes === void 0 ? void 0 : strFromU8(bytes);
|
|
267
|
+
}
|
|
268
|
+
function strToU8(text3) {
|
|
269
|
+
return new TextEncoder().encode(text3);
|
|
270
|
+
}
|
|
271
|
+
function strFromU8(bytes) {
|
|
272
|
+
return new TextDecoder().decode(bytes);
|
|
273
|
+
}
|
|
274
|
+
function normalise(path) {
|
|
275
|
+
return path.replace(/\\/g, "/").replace(/^(\.\/)+/, "").replace(/\/+/g, "/");
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// ../core/src/geometry.ts
|
|
279
|
+
var identity = { a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0 };
|
|
280
|
+
var translate = (tx, ty) => ({ ...identity, tx, ty });
|
|
281
|
+
var scale = (sx, sy) => ({ ...identity, a: sx, d: sy });
|
|
282
|
+
function rotate(degrees) {
|
|
283
|
+
const radians = degrees * Math.PI / 180;
|
|
284
|
+
const cos = Math.cos(radians);
|
|
285
|
+
const sin = Math.sin(radians);
|
|
286
|
+
return { a: cos, b: sin, c: -sin, d: cos, tx: 0, ty: 0 };
|
|
287
|
+
}
|
|
288
|
+
function concat(m, n) {
|
|
289
|
+
return {
|
|
290
|
+
a: m.a * n.a + m.b * n.c,
|
|
291
|
+
b: m.a * n.b + m.b * n.d,
|
|
292
|
+
c: m.c * n.a + m.d * n.c,
|
|
293
|
+
d: m.c * n.b + m.d * n.d,
|
|
294
|
+
tx: m.tx * n.a + m.ty * n.c + n.tx,
|
|
295
|
+
ty: m.tx * n.b + m.ty * n.d + n.ty
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
function apply(t, p) {
|
|
299
|
+
return { x: t.a * p.x + t.c * p.y + t.tx, y: t.b * p.x + t.d * p.y + t.ty };
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// ../core/src/preview.ts
|
|
303
|
+
function frameOrigin(preview, root, styles, overflow) {
|
|
304
|
+
if (isObject(preview.origin)) {
|
|
305
|
+
const x = number(preview.origin.x);
|
|
306
|
+
const y = number(preview.origin.y);
|
|
307
|
+
if (x !== void 0 && y !== void 0) return { x, y };
|
|
308
|
+
}
|
|
309
|
+
const resolved = (field) => typeof root[field] === "string" ? styles[root[field]] : root[field];
|
|
310
|
+
let left = 0;
|
|
311
|
+
let top = 0;
|
|
312
|
+
let right = 0;
|
|
313
|
+
let bottom = 0;
|
|
314
|
+
const extend = (l, t, r, b) => {
|
|
315
|
+
left = Math.max(left, l);
|
|
316
|
+
top = Math.max(top, t);
|
|
317
|
+
right = Math.max(right, r);
|
|
318
|
+
bottom = Math.max(bottom, b);
|
|
319
|
+
};
|
|
320
|
+
const effects = resolved("effects");
|
|
321
|
+
const shadows = isObject(effects) && Array.isArray(effects.shadows) ? effects.shadows.filter(isObject) : [];
|
|
322
|
+
for (const shadow of shadows) {
|
|
323
|
+
if (shadow.inset === true) continue;
|
|
324
|
+
const x = number(shadow.x) ?? 0;
|
|
325
|
+
const y = number(shadow.y) ?? 0;
|
|
326
|
+
const reach = (number(shadow.blur) ?? 0) + (number(shadow.spread) ?? 0);
|
|
327
|
+
extend(reach - x, reach - y, reach + x, reach + y);
|
|
328
|
+
}
|
|
329
|
+
const borders = resolved("borders");
|
|
330
|
+
for (const border of Array.isArray(borders) ? borders.filter(isObject) : []) {
|
|
331
|
+
const thickness = number(border.thickness) ?? 0;
|
|
332
|
+
if (border.position === "outside") extend(thickness, thickness, thickness, thickness);
|
|
333
|
+
if (border.position === "center") extend(thickness / 2, thickness / 2, thickness / 2, thickness / 2);
|
|
334
|
+
}
|
|
335
|
+
return {
|
|
336
|
+
x: Math.abs(left + right - overflow.width) <= 1 ? left : overflow.width / 2,
|
|
337
|
+
y: Math.abs(top + bottom - overflow.height) <= 1 ? top : overflow.height / 2
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// ../core/src/model.ts
|
|
342
|
+
var styleFields = ["fills", "borders", "effects", "corners", "layout", "textStyle"];
|
|
343
|
+
var SketchframeError = class extends Error {
|
|
344
|
+
};
|
|
345
|
+
function loadSketchframe(files) {
|
|
346
|
+
const designText = text(files, DESIGN_FILE);
|
|
347
|
+
if (designText === void 0) throw new SketchframeError("This Sketchframe has no design.json.");
|
|
348
|
+
let design;
|
|
349
|
+
try {
|
|
350
|
+
design = JSON.parse(designText);
|
|
351
|
+
} catch {
|
|
352
|
+
throw new SketchframeError("This Sketchframe's design.json isn't valid JSON.");
|
|
353
|
+
}
|
|
354
|
+
if (!isObject(design) || design.format !== "sketchframe" || !isObject(design.root)) {
|
|
355
|
+
throw new SketchframeError("This Sketchframe's design.json isn't a Sketchframe design.");
|
|
356
|
+
}
|
|
357
|
+
const root = parseNode(design.root, void 0);
|
|
358
|
+
const components = Object.entries(isObject(design.components) ? design.components : {}).flatMap(
|
|
359
|
+
([id, value]) => isObject(value) && isObject(value.root) ? [{ id, name: string(value.name) ?? "", library: string(value.library), root: parseNode(value.root, void 0) }] : []
|
|
360
|
+
).sort((a, b) => compareNames(a.name, b.name));
|
|
361
|
+
const styles = isObject(design.styles) ? design.styles : {};
|
|
362
|
+
const tokens2 = isObject(design.tokens) ? design.tokens : {};
|
|
363
|
+
const colors = Object.fromEntries(
|
|
364
|
+
Object.entries(isObject(tokens2.colors) ? tokens2.colors : {}).flatMap(
|
|
365
|
+
([name, value]) => typeof value === "string" ? [[name, value]] : []
|
|
366
|
+
)
|
|
367
|
+
);
|
|
368
|
+
const previewObject = isObject(design.preview) ? design.preview : {};
|
|
369
|
+
const previewScale = number(previewObject.scale) ?? 2;
|
|
370
|
+
const preview = {
|
|
371
|
+
src: string(previewObject.src) ?? DEFAULT_PREVIEW_FILE,
|
|
372
|
+
scale: previewScale,
|
|
373
|
+
pixelWidth: number(previewObject.pixelWidth) ?? root.size.width * previewScale,
|
|
374
|
+
pixelHeight: number(previewObject.pixelHeight) ?? root.size.height * previewScale
|
|
375
|
+
};
|
|
376
|
+
return {
|
|
377
|
+
name: string(design.name) ?? root.name,
|
|
378
|
+
design,
|
|
379
|
+
root,
|
|
380
|
+
components,
|
|
381
|
+
styles,
|
|
382
|
+
colors,
|
|
383
|
+
annotations: parseAnnotations(text(files, ANNOTATIONS_FILE)),
|
|
384
|
+
preview,
|
|
385
|
+
frameOrigin: frameOrigin(previewObject, design.root, styles, {
|
|
386
|
+
width: preview.pixelWidth / previewScale - root.size.width,
|
|
387
|
+
height: preview.pixelHeight / previewScale - root.size.height
|
|
388
|
+
}),
|
|
389
|
+
files
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
function parseNode(object, parent) {
|
|
393
|
+
const size = { width: number(object.width) ?? 0, height: number(object.height) ?? 0 };
|
|
394
|
+
const name = string(object.name) ?? "";
|
|
395
|
+
let transform = identity;
|
|
396
|
+
if (parent) {
|
|
397
|
+
const x = number(object.x) ?? 0;
|
|
398
|
+
const y = number(object.y) ?? 0;
|
|
399
|
+
transform = [
|
|
400
|
+
translate(-size.width / 2, -size.height / 2),
|
|
401
|
+
scale(object.flipX === true ? -1 : 1, object.flipY === true ? -1 : 1),
|
|
402
|
+
rotate(number(object.rotation) ?? 0),
|
|
403
|
+
translate(x + size.width / 2, y + size.height / 2),
|
|
404
|
+
parent.transform
|
|
405
|
+
].reduce(concat);
|
|
406
|
+
}
|
|
407
|
+
const raw = { ...object };
|
|
408
|
+
delete raw.children;
|
|
409
|
+
const node2 = {
|
|
410
|
+
id: string(object.id) ?? "",
|
|
411
|
+
sketchId: string(object.sketchId),
|
|
412
|
+
name,
|
|
413
|
+
type: string(object.type) ?? "group",
|
|
414
|
+
path: parent ? [...parent.path, name] : [],
|
|
415
|
+
raw,
|
|
416
|
+
size,
|
|
417
|
+
transform,
|
|
418
|
+
parent,
|
|
419
|
+
children: []
|
|
420
|
+
};
|
|
421
|
+
node2.children = Array.isArray(object.children) ? object.children.filter(isObject).map((child) => parseNode(child, node2)) : [];
|
|
422
|
+
return node2;
|
|
423
|
+
}
|
|
424
|
+
function allNodes(node2) {
|
|
425
|
+
return [node2, ...node2.children.flatMap(allNodes)];
|
|
426
|
+
}
|
|
427
|
+
function everyNode(frame) {
|
|
428
|
+
return [frame.root, ...frame.components.map((component) => component.root)].flatMap(allNodes);
|
|
429
|
+
}
|
|
430
|
+
function isInFrame(frame, node2) {
|
|
431
|
+
let top = node2;
|
|
432
|
+
while (top.parent) top = top.parent;
|
|
433
|
+
return top === frame.root;
|
|
434
|
+
}
|
|
435
|
+
function findNode(frame, query) {
|
|
436
|
+
const nodes = everyNode(frame);
|
|
437
|
+
const frameNodes = allNodes(frame.root);
|
|
438
|
+
const trimmed = query.trim();
|
|
439
|
+
if (trimmed === "" || trimmed === "/") return frame.root;
|
|
440
|
+
const byId = nodes.find((node2) => node2.id === trimmed) ?? nodes.find((node2) => node2.sketchId === trimmed);
|
|
441
|
+
if (byId) return byId;
|
|
442
|
+
const path = trimmed.replace(/^\/+|\/+$/g, "").split("/");
|
|
443
|
+
const byPath = frameNodes.find((node2) => node2.path.length === path.length && node2.path.every((name, i) => name === path[i]));
|
|
444
|
+
if (byPath) return byPath;
|
|
445
|
+
const byName = nodes.filter((node2) => node2.name === trimmed);
|
|
446
|
+
return byName.length === 1 ? byName[0] : void 0;
|
|
447
|
+
}
|
|
448
|
+
function requireNode(frame, query) {
|
|
449
|
+
const node2 = findNode(frame, query);
|
|
450
|
+
if (node2) return node2;
|
|
451
|
+
const matches = everyNode(frame).filter((node3) => node3.name === query.trim());
|
|
452
|
+
if (matches.length > 1) {
|
|
453
|
+
throw new SketchframeError(
|
|
454
|
+
`${matches.length} layers are named "${query}" (${matches.map((node3) => node3.id).join(", ")}). Pass an id or a layer path instead.`
|
|
455
|
+
);
|
|
456
|
+
}
|
|
457
|
+
throw new SketchframeError(`No layer matches "${query}". Use an id from the outline (e.g. n4), a sketchId or a layer path (e.g. Header/Title).`);
|
|
458
|
+
}
|
|
459
|
+
function nodeForAnnotation(frame, annotation) {
|
|
460
|
+
return annotatedNode(allNodes(frame.root), annotation);
|
|
461
|
+
}
|
|
462
|
+
function corners(node2) {
|
|
463
|
+
const { width, height } = node2.size;
|
|
464
|
+
return [
|
|
465
|
+
{ x: 0, y: 0 },
|
|
466
|
+
{ x: width, y: 0 },
|
|
467
|
+
{ x: width, y: height },
|
|
468
|
+
{ x: 0, y: height }
|
|
469
|
+
].map((point) => apply(node2.transform, point));
|
|
470
|
+
}
|
|
471
|
+
function bounds(node2) {
|
|
472
|
+
const points = corners(node2);
|
|
473
|
+
const xs = points.map((p) => p.x);
|
|
474
|
+
const ys = points.map((p) => p.y);
|
|
475
|
+
const x = Math.min(...xs);
|
|
476
|
+
const y = Math.min(...ys);
|
|
477
|
+
return { x: tidy(x), y: tidy(y), width: tidy(Math.max(...xs) - x), height: tidy(Math.max(...ys) - y) };
|
|
478
|
+
}
|
|
479
|
+
function resolvedFields(frame, node2) {
|
|
480
|
+
const fields = { ...node2.raw };
|
|
481
|
+
for (const field of styleFields) {
|
|
482
|
+
const key = fields[field];
|
|
483
|
+
if (typeof key === "string" && key in frame.styles) fields[field] = frame.styles[key];
|
|
484
|
+
}
|
|
485
|
+
return fields;
|
|
486
|
+
}
|
|
487
|
+
function styleKeys(frame, node2) {
|
|
488
|
+
return styleFields.flatMap((field) => {
|
|
489
|
+
const key = node2.raw[field];
|
|
490
|
+
return typeof key === "string" && key in frame.styles ? [key] : [];
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
function tokenNames(value, names = /* @__PURE__ */ new Set()) {
|
|
494
|
+
if (Array.isArray(value)) {
|
|
495
|
+
for (const child of value) tokenNames(child, names);
|
|
496
|
+
} else if (isObject(value)) {
|
|
497
|
+
for (const [key, child] of Object.entries(value)) {
|
|
498
|
+
if ((key === "token" || key === "colorToken") && typeof child === "string") {
|
|
499
|
+
names.add(child);
|
|
500
|
+
} else {
|
|
501
|
+
tokenNames(child, names);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
return names;
|
|
506
|
+
}
|
|
507
|
+
function tidy(value) {
|
|
508
|
+
return Math.round(value * 1e3) / 1e3 + 0;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// ../core/src/operations.ts
|
|
512
|
+
function outline(frame, start = frame.root, options = {}) {
|
|
513
|
+
const notes = annotationCounts(frame);
|
|
514
|
+
const lines = [];
|
|
515
|
+
const walk = (node2, depth2) => {
|
|
516
|
+
const position = node2.raw.x === void 0 || node2 === start ? "" : ` ${num(node2.raw.x)},${num(node2.raw.y)}`;
|
|
517
|
+
const extras = [
|
|
518
|
+
typeof node2.raw.component === "string" ? `\u25C6 ${node2.raw.component}` : "",
|
|
519
|
+
typeof node2.raw.rotation === "number" ? `\u21BB${node2.raw.rotation}\xB0` : "",
|
|
520
|
+
typeof node2.raw.text === "string" ? JSON.stringify(truncate(node2.raw.text, 40)) : "",
|
|
521
|
+
notes.get(node2.id) ? `\u270E${notes.get(node2.id)}` : ""
|
|
522
|
+
].filter(Boolean);
|
|
523
|
+
lines.push(
|
|
524
|
+
`${" ".repeat(depth2)}${node2.name || "(unnamed)"} [${node2.type}]${position} ${num(node2.size.width)}\xD7${num(node2.size.height)} ${node2.id}${extras.length ? ` ${extras.join(" ")}` : ""}`
|
|
525
|
+
);
|
|
526
|
+
if (options.depth !== void 0 && depth2 >= options.depth) {
|
|
527
|
+
const hidden = allNodes(node2).length - 1;
|
|
528
|
+
if (hidden > 0) lines.push(`${" ".repeat(depth2 + 1)}\u2026 ${hidden} more`);
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
for (const child of node2.children) walk(child, depth2 + 1);
|
|
532
|
+
};
|
|
533
|
+
walk(start, 0);
|
|
534
|
+
return lines.join("\n");
|
|
535
|
+
}
|
|
536
|
+
function summary(frame) {
|
|
537
|
+
const nodes = allNodes(frame.root).length;
|
|
538
|
+
const { pixelWidth, pixelHeight, scale: scale2 } = frame.preview;
|
|
539
|
+
return [
|
|
540
|
+
`${frame.name}: ${num(frame.root.size.width)}\xD7${num(frame.root.size.height)} pt, ${nodes} layers` + (frame.components.length ? `, ${frame.components.length} components` : "") + (frame.annotations.length ? `, ${frame.annotations.length} annotations` : ""),
|
|
541
|
+
`Preview: ${frame.preview.src}, ${pixelWidth}\xD7${pixelHeight} px at ${scale2}x; the frame starts ${num(frame.frameOrigin.x)},${num(frame.frameOrigin.y)} pt into it.`,
|
|
542
|
+
typeof frame.design.generator === "string" ? `Exported by ${frame.design.generator}${typeof frame.design.exportedAt === "string" ? ` at ${frame.design.exportedAt}` : ""}.` : ""
|
|
543
|
+
].filter(Boolean).join("\n");
|
|
544
|
+
}
|
|
545
|
+
function nodeContext(frame, node2, options = {}) {
|
|
546
|
+
const tree = (current, depth2) => {
|
|
547
|
+
const fields = resolvedFields(frame, current);
|
|
548
|
+
if (current.children.length === 0) return fields;
|
|
549
|
+
if (options.depth !== void 0 && depth2 >= options.depth) {
|
|
550
|
+
return { ...fields, children: `${current.children.length} ${current.children.length === 1 ? "child" : "children"} omitted; ask for them by id` };
|
|
551
|
+
}
|
|
552
|
+
return { ...fields, children: current.children.map((child) => tree(child, depth2 + 1)) };
|
|
553
|
+
};
|
|
554
|
+
const subtree = allNodes(node2);
|
|
555
|
+
const used = /* @__PURE__ */ new Set();
|
|
556
|
+
for (const each of subtree) tokenNames(resolvedFields(frame, each), used);
|
|
557
|
+
const tokens2 = Object.fromEntries([...used].sort().map((name) => [name, frame.colors[name] ?? null]));
|
|
558
|
+
const keys = [...new Set(subtree.flatMap((each) => styleKeys(frame, each)))].sort();
|
|
559
|
+
const sharedStyles = [...new Set(subtree.flatMap((each) => typeof each.raw.sharedStyle === "string" ? [each.raw.sharedStyle] : []))].sort();
|
|
560
|
+
const inFrame = isInFrame(frame, node2);
|
|
561
|
+
const componentId = typeof node2.raw.componentId === "string" ? node2.raw.componentId : void 0;
|
|
562
|
+
const component = componentId ? frame.components.find((each) => each.id === componentId) : void 0;
|
|
563
|
+
const ids = new Set(subtree.map((each) => each.id));
|
|
564
|
+
const annotations2 = inFrame ? frame.annotations.flatMap((annotation) => {
|
|
565
|
+
const target = nodeForAnnotation(frame, annotation);
|
|
566
|
+
return target && ids.has(target.id) ? [annotationSummary(annotation, target)] : [];
|
|
567
|
+
}) : [];
|
|
568
|
+
return clean({
|
|
569
|
+
id: node2.id,
|
|
570
|
+
name: node2.name,
|
|
571
|
+
type: node2.type,
|
|
572
|
+
path: node2.path.join("/") || "/",
|
|
573
|
+
parent: node2.parent ? { id: node2.parent.id, name: node2.parent.name, layout: resolvedFields(frame, node2.parent).layout } : void 0,
|
|
574
|
+
where: inFrame ? "frame" : "component definition",
|
|
575
|
+
bounds: inFrame ? { ...bounds(node2), note: "In frame coordinates (points), axis-aligned around any rotation." } : void 0,
|
|
576
|
+
component: component ? { id: component.id, name: component.name, library: component.library } : void 0,
|
|
577
|
+
tokens: Object.keys(tokens2).length ? tokens2 : void 0,
|
|
578
|
+
reusedStyles: keys.length ? keys : void 0,
|
|
579
|
+
sharedStyles: sharedStyles.length ? sharedStyles : void 0,
|
|
580
|
+
annotations: annotations2.length ? annotations2 : void 0,
|
|
581
|
+
node: tree(node2, 0)
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
function tokens(frame) {
|
|
585
|
+
const nodes = allNodes(frame.root);
|
|
586
|
+
const users = (match) => nodes.filter(match).map((node2) => node2.id);
|
|
587
|
+
const colors = Object.fromEntries(
|
|
588
|
+
Object.entries(frame.colors).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([name, value]) => [name, { value, usedBy: users((node2) => tokenNames(resolvedFields(frame, node2)).has(name)) }])
|
|
589
|
+
);
|
|
590
|
+
const sharedNames = [...new Set(nodes.flatMap((node2) => typeof node2.raw.sharedStyle === "string" ? [node2.raw.sharedStyle] : []))].sort();
|
|
591
|
+
const sharedStyles = Object.fromEntries(
|
|
592
|
+
sharedNames.map((name) => {
|
|
593
|
+
const usedBy = nodes.filter((node2) => node2.raw.sharedStyle === name);
|
|
594
|
+
const fields = resolvedFields(frame, usedBy[0]);
|
|
595
|
+
const appearance = Object.fromEntries(
|
|
596
|
+
Object.entries(fields).filter(
|
|
597
|
+
([key]) => ["fills", "borders", "borderOptions", "effects", "corners", "textStyle", "opacity", "blendMode"].includes(key)
|
|
598
|
+
)
|
|
599
|
+
);
|
|
600
|
+
return [name, { usedBy: usedBy.map((node2) => node2.id), value: appearance }];
|
|
601
|
+
})
|
|
602
|
+
);
|
|
603
|
+
const reusedStyles = Object.fromEntries(
|
|
604
|
+
Object.entries(frame.styles).map(([key, value]) => [key, { value, usedBy: users((node2) => styleKeys(frame, node2).includes(key)) }])
|
|
605
|
+
);
|
|
606
|
+
return clean({
|
|
607
|
+
colors: Object.keys(colors).length ? colors : void 0,
|
|
608
|
+
sharedStyles: Object.keys(sharedStyles).length ? sharedStyles : void 0,
|
|
609
|
+
reusedStyles: Object.keys(reusedStyles).length ? reusedStyles : void 0
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
function annotations(frame) {
|
|
613
|
+
return frame.annotations.map((annotation) => annotationSummary(annotation, nodeForAnnotation(frame, annotation)));
|
|
614
|
+
}
|
|
615
|
+
function annotationSummary(annotation, node2) {
|
|
616
|
+
return clean({
|
|
617
|
+
id: annotation.id,
|
|
618
|
+
category: annotation.category,
|
|
619
|
+
text: annotation.text,
|
|
620
|
+
layer: node2 ? { id: node2.id, name: node2.name, path: node2.path.join("/") || "/", bounds: bounds(node2) } : { detached: true, name: annotation.layerName, path: annotation.layerPath.join("/"), note: "The layer is no longer in the design." },
|
|
621
|
+
createdAt: annotation.createdAt,
|
|
622
|
+
updatedAt: annotation.updatedAt
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
function annotationCounts(frame) {
|
|
626
|
+
const counts = /* @__PURE__ */ new Map();
|
|
627
|
+
for (const annotation of frame.annotations) {
|
|
628
|
+
const node2 = nodeForAnnotation(frame, annotation);
|
|
629
|
+
if (node2) counts.set(node2.id, (counts.get(node2.id) ?? 0) + 1);
|
|
630
|
+
}
|
|
631
|
+
return counts;
|
|
632
|
+
}
|
|
633
|
+
function previewRegion(frame, node2, padding = 0) {
|
|
634
|
+
const { scale: scale2, pixelWidth, pixelHeight } = frame.preview;
|
|
635
|
+
if (!node2) return { x: 0, y: 0, width: pixelWidth, height: pixelHeight };
|
|
636
|
+
const box = bounds(node2);
|
|
637
|
+
const left = Math.max(0, Math.floor((box.x - padding + frame.frameOrigin.x) * scale2));
|
|
638
|
+
const top = Math.max(0, Math.floor((box.y - padding + frame.frameOrigin.y) * scale2));
|
|
639
|
+
const right = Math.min(pixelWidth, Math.ceil((box.x + box.width + padding + frame.frameOrigin.x) * scale2));
|
|
640
|
+
const bottom = Math.min(pixelHeight, Math.ceil((box.y + box.height + padding + frame.frameOrigin.y) * scale2));
|
|
641
|
+
return { x: left, y: top, width: Math.max(0, right - left), height: Math.max(0, bottom - top) };
|
|
642
|
+
}
|
|
643
|
+
function catText(files) {
|
|
644
|
+
const parts = [];
|
|
645
|
+
const paths = files.paths().sort();
|
|
646
|
+
parts.push(`# Sketchframe (${files.kind})`, "", "## Files", "");
|
|
647
|
+
for (const path of paths) parts.push(`${path} ${files.read(path)?.length ?? 0} bytes`);
|
|
648
|
+
for (const name of [DESIGN_FILE, ANNOTATIONS_FILE]) {
|
|
649
|
+
const bytes = files.read(name);
|
|
650
|
+
if (!bytes) continue;
|
|
651
|
+
parts.push("", `## ${name}`, "");
|
|
652
|
+
const text3 = strFromU8(bytes);
|
|
653
|
+
try {
|
|
654
|
+
const json = JSON.parse(text3);
|
|
655
|
+
if (name === DESIGN_FILE && isObject(json)) delete json.exportedAt;
|
|
656
|
+
parts.push(prettyJSON(json));
|
|
657
|
+
} catch {
|
|
658
|
+
parts.push(text3.trimEnd());
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
return `${parts.join("\n")}
|
|
662
|
+
`;
|
|
663
|
+
}
|
|
664
|
+
function toJSON(value) {
|
|
665
|
+
return JSON.stringify(value, null, 2);
|
|
666
|
+
}
|
|
667
|
+
function num(value) {
|
|
668
|
+
return typeof value === "number" ? String(Math.round(value * 100) / 100) : "?";
|
|
669
|
+
}
|
|
670
|
+
function truncate(text3, length) {
|
|
671
|
+
const line = text3.replace(/\s+/g, " ").trim();
|
|
672
|
+
return line.length > length ? `${line.slice(0, length - 1)}\u2026` : line;
|
|
673
|
+
}
|
|
674
|
+
function clean(object) {
|
|
675
|
+
return Object.fromEntries(Object.entries(object).filter(([, value]) => value !== void 0));
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
// ../core/src/code.ts
|
|
679
|
+
function htmlForNode(frame, node2) {
|
|
680
|
+
const rules = [];
|
|
681
|
+
const usedTokens = /* @__PURE__ */ new Set();
|
|
682
|
+
const classNames = /* @__PURE__ */ new Map();
|
|
683
|
+
const className = (current) => {
|
|
684
|
+
const base = (current.name || current.type).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || current.type;
|
|
685
|
+
const safe = /^[a-z]/.test(base) ? base : `n-${base}`;
|
|
686
|
+
const count = (classNames.get(safe) ?? 0) + 1;
|
|
687
|
+
classNames.set(safe, count);
|
|
688
|
+
return count === 1 ? safe : `${safe}-${count}`;
|
|
689
|
+
};
|
|
690
|
+
const color = (value, token) => {
|
|
691
|
+
if (typeof token === "string" && frame.colors[token] !== void 0) {
|
|
692
|
+
usedTokens.add(token);
|
|
693
|
+
return `var(${tokenVariable(token)}, ${frame.colors[token]})`;
|
|
694
|
+
}
|
|
695
|
+
return string(value) ?? "transparent";
|
|
696
|
+
};
|
|
697
|
+
const render = (current, parent, depth2) => {
|
|
698
|
+
const fields = resolvedFields(frame, current);
|
|
699
|
+
const parentLayout = parent ? resolvedFields(frame, parent).layout : void 0;
|
|
700
|
+
const inFlow = isObject(parentLayout) && fields.position !== "absolute";
|
|
701
|
+
const name = className(current);
|
|
702
|
+
const css = [];
|
|
703
|
+
const notes = [];
|
|
704
|
+
if (!parent) {
|
|
705
|
+
css.push("position: relative");
|
|
706
|
+
} else if (!inFlow) {
|
|
707
|
+
css.push("position: absolute", `left: ${px(fields.x)}`, `top: ${px(fields.y)}`);
|
|
708
|
+
} else {
|
|
709
|
+
css.push("position: relative");
|
|
710
|
+
}
|
|
711
|
+
const sizing = isObject(fields.sizing) ? fields.sizing : {};
|
|
712
|
+
const parentMode = isObject(parentLayout) ? parentLayout.mode : void 0;
|
|
713
|
+
const axis = (dimension, mode) => {
|
|
714
|
+
const main2 = parentMode === "row" === (dimension === "width");
|
|
715
|
+
if (mode === "fill" && inFlow) css.push(main2 ? "flex: 1 1 0" : "align-self: stretch");
|
|
716
|
+
else if (mode === "hug") css.push(`${dimension}: fit-content`);
|
|
717
|
+
else css.push(`${dimension}: ${px(fields[dimension])}`);
|
|
718
|
+
};
|
|
719
|
+
axis("width", sizing.horizontal);
|
|
720
|
+
axis("height", sizing.vertical);
|
|
721
|
+
for (const [key, property] of [
|
|
722
|
+
["minSize", "min"],
|
|
723
|
+
["maxSize", "max"]
|
|
724
|
+
]) {
|
|
725
|
+
const size = fields[key];
|
|
726
|
+
if (isObject(size)) {
|
|
727
|
+
if (number(size.width) !== void 0) css.push(`${property}-width: ${px(size.width)}`);
|
|
728
|
+
if (number(size.height) !== void 0) css.push(`${property}-height: ${px(size.height)}`);
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
css.push("box-sizing: border-box");
|
|
732
|
+
const layout = fields.layout;
|
|
733
|
+
if (isObject(layout)) {
|
|
734
|
+
css.push("display: flex", `flex-direction: ${layout.mode === "column" ? "column" : "row"}`);
|
|
735
|
+
if (layout.justifyContent) css.push(`justify-content: ${layout.justifyContent}`);
|
|
736
|
+
if (layout.alignItems) css.push(`align-items: ${layout.alignItems}`);
|
|
737
|
+
if (number(layout.gap) !== void 0) css.push(`gap: ${px(layout.gap)}`);
|
|
738
|
+
if (layout.padding) css.push(`padding: ${layout.padding}`);
|
|
739
|
+
if (layout.wrap) {
|
|
740
|
+
css.push("flex-wrap: wrap");
|
|
741
|
+
if (layout.alignContent) css.push(`align-content: ${layout.alignContent}`);
|
|
742
|
+
if (number(layout.crossAxisGap) !== void 0) css.push(`row-gap: ${px(layout.crossAxisGap)}`);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
if (fields.clipContent === true) css.push("overflow: hidden");
|
|
746
|
+
const transforms = [];
|
|
747
|
+
if (number(fields.rotation)) transforms.push(`rotate(${fields.rotation}deg)`);
|
|
748
|
+
if (fields.flipX === true || fields.flipY === true) {
|
|
749
|
+
transforms.push(`scale(${fields.flipX === true ? -1 : 1}, ${fields.flipY === true ? -1 : 1})`);
|
|
750
|
+
}
|
|
751
|
+
if (transforms.length) css.push(`transform: ${transforms.join(" ")}`);
|
|
752
|
+
if (number(fields.opacity) !== void 0) css.push(`opacity: ${fields.opacity}`);
|
|
753
|
+
if (string(fields.blendMode)) css.push(`mix-blend-mode: ${fields.blendMode}`);
|
|
754
|
+
const fills = Array.isArray(fields.fills) ? fields.fills.filter(isObject) : [];
|
|
755
|
+
const isText = current.type === "text";
|
|
756
|
+
if (!isText && fills.length) {
|
|
757
|
+
const layers = fills.map((paint) => {
|
|
758
|
+
if (paint.approximate === true) notes.push(`${paint.type} gradient is approximate; check the preview`);
|
|
759
|
+
if (paint.type === "solid") {
|
|
760
|
+
const value = color(paint.color, paint.token);
|
|
761
|
+
return fills.length === 1 ? value : `linear-gradient(${value}, ${value})`;
|
|
762
|
+
}
|
|
763
|
+
if (paint.type === "image") return `url("${paint.src}") center / ${paint.fit === "stretch" ? "100% 100%" : paint.fit === "tile" ? "auto" : paint.fit ?? "cover"} ${paint.fit === "tile" ? "repeat" : "no-repeat"}`;
|
|
764
|
+
return string(paint.css) ?? "transparent";
|
|
765
|
+
});
|
|
766
|
+
css.push(`background: ${layers.join(", ")}`);
|
|
767
|
+
}
|
|
768
|
+
const borders = Array.isArray(fields.borders) ? fields.borders.filter(isObject) : [];
|
|
769
|
+
if (borders.length) {
|
|
770
|
+
const border = borders[0];
|
|
771
|
+
const thickness = number(border.thickness) ?? 1;
|
|
772
|
+
const value = border.type === "solid" || border.type === void 0 ? color(border.color, border.token) : "currentColor";
|
|
773
|
+
if (border.type && border.type !== "solid") notes.push("gradient border; check the preview");
|
|
774
|
+
if (border.position === "outside") css.push(`outline: ${px(thickness)} solid ${value}`);
|
|
775
|
+
else if (border.position === "center") css.push(`outline: ${px(thickness)} solid ${value}`, `outline-offset: ${px(-thickness / 2)}`);
|
|
776
|
+
else css.push(`border: ${px(thickness)} solid ${value}`);
|
|
777
|
+
const options = isObject(fields.borderOptions) ? fields.borderOptions : {};
|
|
778
|
+
if (Array.isArray(options.dashPattern) && options.dashPattern.length) css.push("border-style: dashed");
|
|
779
|
+
if (borders.length > 1) notes.push(`${borders.length - 1} more border(s) in the design`);
|
|
780
|
+
}
|
|
781
|
+
const corners2 = isObject(fields.corners) ? fields.corners : void 0;
|
|
782
|
+
if (corners2) {
|
|
783
|
+
const radius = corners2.radius;
|
|
784
|
+
if (Array.isArray(radius)) css.push(`border-radius: ${radius.map(px).join(" ")}`);
|
|
785
|
+
else if (number(radius) !== void 0) css.push(`border-radius: ${current.type === "oval" ? "50%" : px(radius)}`);
|
|
786
|
+
if (corners2.style === "smooth") notes.push("smooth (squircle) corners");
|
|
787
|
+
} else if (current.type === "oval") {
|
|
788
|
+
css.push("border-radius: 50%");
|
|
789
|
+
}
|
|
790
|
+
const effects = isObject(fields.effects) ? fields.effects : void 0;
|
|
791
|
+
const effectCSS = effects && isObject(effects.css) ? effects.css : {};
|
|
792
|
+
if (string(effectCSS.boxShadow) && !isText) css.push(`box-shadow: ${effectCSS.boxShadow}`);
|
|
793
|
+
if (string(effectCSS.textShadow)) css.push(`text-shadow: ${effectCSS.textShadow}`);
|
|
794
|
+
if (string(effectCSS.filter)) css.push(`filter: ${effectCSS.filter}`);
|
|
795
|
+
if (string(effectCSS.backdropFilter)) css.push(`backdrop-filter: ${effectCSS.backdropFilter}`);
|
|
796
|
+
const textStyle = isObject(fields.textStyle) ? fields.textStyle : void 0;
|
|
797
|
+
if (isText && textStyle) css.push(...textCSS(textStyle, color));
|
|
798
|
+
if (isText && fields.textBehaviour === "auto-width") css.push("white-space: nowrap");
|
|
799
|
+
if (isText && Array.isArray(fields.textRuns) && fields.textRuns.length) notes.push("mixed text styles; see textRuns");
|
|
800
|
+
rules.push(`${notes.length ? `/* ${notes.join("; ")} */
|
|
801
|
+
` : ""}.${name} {
|
|
802
|
+
${css.map((line) => ` ${line};`).join("\n")}
|
|
803
|
+
}`);
|
|
804
|
+
const indent = " ".repeat(depth2);
|
|
805
|
+
const label = current.name ? ` data-name="${attribute(current.name)}"` : "";
|
|
806
|
+
if (isText) {
|
|
807
|
+
return `${indent}<p class="${name}"${label}>${escape(string(fields.text) ?? "").replace(/\n/g, "<br>")}</p>`;
|
|
808
|
+
}
|
|
809
|
+
if ((current.type === "image" || current.type === "vector") && string(fields.src)) {
|
|
810
|
+
return `${indent}<img class="${name}"${label} src="${attribute(string(fields.src) ?? "")}" alt="${attribute(current.name)}">`;
|
|
811
|
+
}
|
|
812
|
+
const children = isObject(layout) && layout.stackingOrder === "firstOnTop" ? current.children.map((child, index) => ({ child, z: current.children.length - index })) : current.children.map((child) => ({ child, z: 0 }));
|
|
813
|
+
const inner = children.map(({ child }) => render(child, current, depth2 + 1));
|
|
814
|
+
children.forEach(({ z }, index) => {
|
|
815
|
+
if (z) rules.push(`.${name} > :nth-child(${index + 1}) { z-index: ${z}; }`);
|
|
816
|
+
});
|
|
817
|
+
return inner.length ? `${indent}<div class="${name}"${label}>
|
|
818
|
+
${inner.join("\n")}
|
|
819
|
+
${indent}</div>` : `${indent}<div class="${name}"${label}></div>`;
|
|
820
|
+
};
|
|
821
|
+
const html = render(node2, void 0, 0);
|
|
822
|
+
const variables = [...usedTokens].sort().map((token) => ` ${tokenVariable(token)}: ${frame.colors[token]}; /* token "${token}" */`);
|
|
823
|
+
const style = [variables.length ? `:root {
|
|
824
|
+
${variables.join("\n")}
|
|
825
|
+
}` : "", ...rules].filter(Boolean).join("\n\n");
|
|
826
|
+
return `<!-- "${node2.name}" (${node2.id}) from ${frame.name}.sketchframe. Image paths are inside the Sketchframe. -->
|
|
827
|
+
<style>
|
|
828
|
+
${style}
|
|
829
|
+
</style>
|
|
830
|
+
|
|
831
|
+
${html}
|
|
832
|
+
`;
|
|
833
|
+
}
|
|
834
|
+
function textCSS(style, color) {
|
|
835
|
+
const css = [];
|
|
836
|
+
if (string(style.fontFamily)) css.push(`font-family: ${JSON.stringify(style.fontFamily)}`);
|
|
837
|
+
if (number(style.fontWeight) !== void 0) css.push(`font-weight: ${style.fontWeight}`);
|
|
838
|
+
if (string(style.fontStyle) && style.fontStyle !== "normal") css.push(`font-style: ${style.fontStyle}`);
|
|
839
|
+
if (number(style.fontSize) !== void 0) css.push(`font-size: ${px(style.fontSize)}`);
|
|
840
|
+
if (number(style.lineHeight) !== void 0 && style.lineHeightAuto !== true) css.push(`line-height: ${px(style.lineHeight)}`);
|
|
841
|
+
if (number(style.letterSpacing)) css.push(`letter-spacing: ${px(style.letterSpacing)}`);
|
|
842
|
+
if (string(style.textTransform) && style.textTransform !== "none") css.push(`text-transform: ${style.textTransform}`);
|
|
843
|
+
if (string(style.textAlign)) css.push(`text-align: ${style.textAlign === "justified" ? "justify" : style.textAlign}`);
|
|
844
|
+
if (string(style.textDecoration) && style.textDecoration !== "none") css.push(`text-decoration: ${style.textDecoration}`);
|
|
845
|
+
if (style.color !== void 0 || style.colorToken !== void 0) css.push(`color: ${color(style.color, style.colorToken)}`);
|
|
846
|
+
css.push("margin: 0");
|
|
847
|
+
return css;
|
|
848
|
+
}
|
|
849
|
+
function tokenVariable(token) {
|
|
850
|
+
return `--${token.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "token"}`;
|
|
851
|
+
}
|
|
852
|
+
function px(value) {
|
|
853
|
+
const n = typeof value === "number" ? value : 0;
|
|
854
|
+
return n === 0 ? "0" : `${Math.round(n * 100) / 100}px`;
|
|
855
|
+
}
|
|
856
|
+
function escape(text3) {
|
|
857
|
+
return text3.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
858
|
+
}
|
|
859
|
+
function attribute(text3) {
|
|
860
|
+
return escape(text3).replace(/"/g, """);
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
// ../core/src/png.ts
|
|
864
|
+
var import_node_zlib2 = require("node:zlib");
|
|
865
|
+
var SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
|
|
866
|
+
var KEPT = /* @__PURE__ */ new Set(["PLTE", "tRNS", "gAMA", "cHRM", "sRGB", "iCCP", "sBIT", "pHYs"]);
|
|
867
|
+
var CHANNELS = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 };
|
|
868
|
+
function chunks(bytes) {
|
|
869
|
+
if (bytes.length < 8 || SIGNATURE.some((value, i) => bytes[i] !== value)) throw new Error("not a PNG");
|
|
870
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
871
|
+
const out = [];
|
|
872
|
+
let offset = 8;
|
|
873
|
+
while (offset + 12 <= bytes.length) {
|
|
874
|
+
const length = view.getUint32(offset);
|
|
875
|
+
const type = String.fromCharCode(...bytes.subarray(offset + 4, offset + 8));
|
|
876
|
+
out.push({ type, data: bytes.subarray(offset + 8, offset + 8 + length) });
|
|
877
|
+
offset += 12 + length;
|
|
878
|
+
if (type === "IEND") break;
|
|
879
|
+
}
|
|
880
|
+
return out;
|
|
881
|
+
}
|
|
882
|
+
function pngHeader(bytes) {
|
|
883
|
+
const ihdr = chunks(bytes).find((chunk2) => chunk2.type === "IHDR");
|
|
884
|
+
if (!ihdr) throw new Error("PNG has no header");
|
|
885
|
+
const view = new DataView(ihdr.data.buffer, ihdr.data.byteOffset, ihdr.data.byteLength);
|
|
886
|
+
return { width: view.getUint32(0), height: view.getUint32(4), bitDepth: ihdr.data[8], colorType: ihdr.data[9], interlace: ihdr.data[12] };
|
|
887
|
+
}
|
|
888
|
+
function cropPNG(bytes, x, y, width, height) {
|
|
889
|
+
const all = chunks(bytes);
|
|
890
|
+
const header = pngHeader(bytes);
|
|
891
|
+
if (header.interlace !== 0) throw new Error("interlaced PNGs are not supported");
|
|
892
|
+
const channels = CHANNELS[header.colorType];
|
|
893
|
+
if (!channels) throw new Error(`unknown PNG colour type ${header.colorType}`);
|
|
894
|
+
if (x < 0 || y < 0 || width <= 0 || height <= 0 || x + width > header.width || y + height > header.height) {
|
|
895
|
+
throw new Error("crop rectangle is outside the image");
|
|
896
|
+
}
|
|
897
|
+
const bitsPerPixel = channels * header.bitDepth;
|
|
898
|
+
const filterStep = Math.max(1, bitsPerPixel >> 3);
|
|
899
|
+
const stride = Math.ceil(header.width * bitsPerPixel / 8);
|
|
900
|
+
const compressed = concat2(all.filter((chunk2) => chunk2.type === "IDAT").map((chunk2) => chunk2.data));
|
|
901
|
+
const raw = new Uint8Array((0, import_node_zlib2.inflateSync)(compressed));
|
|
902
|
+
if (raw.length < (stride + 1) * header.height) throw new Error("PNG image data is truncated");
|
|
903
|
+
const rows = [];
|
|
904
|
+
let previous = new Uint8Array(stride);
|
|
905
|
+
for (let row = 0; row < y + height; row++) {
|
|
906
|
+
const start = row * (stride + 1);
|
|
907
|
+
const line = unfilter(raw[start], raw.subarray(start + 1, start + 1 + stride), previous, filterStep);
|
|
908
|
+
if (row >= y) rows.push(line);
|
|
909
|
+
previous = line;
|
|
910
|
+
}
|
|
911
|
+
const outStride = Math.ceil(width * bitsPerPixel / 8);
|
|
912
|
+
const out = new Uint8Array((outStride + 1) * height);
|
|
913
|
+
rows.forEach((line, index) => {
|
|
914
|
+
const target = out.subarray(index * (outStride + 1) + 1, (index + 1) * (outStride + 1));
|
|
915
|
+
if (bitsPerPixel % 8 === 0) {
|
|
916
|
+
const bytesPerPixel = bitsPerPixel / 8;
|
|
917
|
+
target.set(line.subarray(x * bytesPerPixel, (x + width) * bytesPerPixel));
|
|
918
|
+
} else {
|
|
919
|
+
for (let i = 0; i < width * bitsPerPixel; i++) {
|
|
920
|
+
const from = x * bitsPerPixel + i;
|
|
921
|
+
if (line[from >> 3] & 128 >> (from & 7)) target[i >> 3] |= 128 >> (i & 7);
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
});
|
|
925
|
+
const ihdr = new Uint8Array(13);
|
|
926
|
+
const view = new DataView(ihdr.buffer);
|
|
927
|
+
view.setUint32(0, width);
|
|
928
|
+
view.setUint32(4, height);
|
|
929
|
+
ihdr.set([header.bitDepth, header.colorType, 0, 0, 0], 8);
|
|
930
|
+
return concat2([
|
|
931
|
+
new Uint8Array(SIGNATURE),
|
|
932
|
+
chunk("IHDR", ihdr),
|
|
933
|
+
...all.filter((each) => KEPT.has(each.type)).map((each) => chunk(each.type, each.data)),
|
|
934
|
+
chunk("IDAT", new Uint8Array((0, import_node_zlib2.deflateSync)(out))),
|
|
935
|
+
chunk("IEND", new Uint8Array())
|
|
936
|
+
]);
|
|
937
|
+
}
|
|
938
|
+
function unfilter(type, line, previous, step) {
|
|
939
|
+
const out = new Uint8Array(line.length);
|
|
940
|
+
for (let i = 0; i < line.length; i++) {
|
|
941
|
+
const left = i >= step ? out[i - step] : 0;
|
|
942
|
+
const up = previous[i];
|
|
943
|
+
const upLeft = i >= step ? previous[i - step] : 0;
|
|
944
|
+
let predictor = 0;
|
|
945
|
+
switch (type) {
|
|
946
|
+
case 0:
|
|
947
|
+
break;
|
|
948
|
+
case 1:
|
|
949
|
+
predictor = left;
|
|
950
|
+
break;
|
|
951
|
+
case 2:
|
|
952
|
+
predictor = up;
|
|
953
|
+
break;
|
|
954
|
+
case 3:
|
|
955
|
+
predictor = left + up >> 1;
|
|
956
|
+
break;
|
|
957
|
+
case 4: {
|
|
958
|
+
const p = left + up - upLeft;
|
|
959
|
+
const pa = Math.abs(p - left);
|
|
960
|
+
const pb = Math.abs(p - up);
|
|
961
|
+
const pc = Math.abs(p - upLeft);
|
|
962
|
+
predictor = pa <= pb && pa <= pc ? left : pb <= pc ? up : upLeft;
|
|
963
|
+
break;
|
|
964
|
+
}
|
|
965
|
+
default:
|
|
966
|
+
throw new Error(`unknown PNG filter ${type}`);
|
|
967
|
+
}
|
|
968
|
+
out[i] = line[i] + predictor & 255;
|
|
969
|
+
}
|
|
970
|
+
return out;
|
|
971
|
+
}
|
|
972
|
+
function chunk(type, data) {
|
|
973
|
+
const out = new Uint8Array(12 + data.length);
|
|
974
|
+
const view = new DataView(out.buffer);
|
|
975
|
+
view.setUint32(0, data.length);
|
|
976
|
+
for (let i = 0; i < 4; i++) out[4 + i] = type.charCodeAt(i);
|
|
977
|
+
out.set(data, 8);
|
|
978
|
+
view.setUint32(8 + data.length, crc32(out.subarray(4, 8 + data.length)));
|
|
979
|
+
return out;
|
|
980
|
+
}
|
|
981
|
+
function concat2(parts) {
|
|
982
|
+
const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
|
|
983
|
+
let offset = 0;
|
|
984
|
+
for (const part of parts) {
|
|
985
|
+
out.set(part, offset);
|
|
986
|
+
offset += part.length;
|
|
987
|
+
}
|
|
988
|
+
return out;
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
// ../core/src/crop.ts
|
|
992
|
+
function cropPreview(frame, node2, padding = 0) {
|
|
993
|
+
const bytes = frame.files.read(frame.preview.src);
|
|
994
|
+
if (!bytes) throw new SketchframeError(`This Sketchframe has no preview image (${frame.preview.src}).`);
|
|
995
|
+
if (!node2) return { png: bytes, region: previewRegion(frame) };
|
|
996
|
+
let header;
|
|
997
|
+
try {
|
|
998
|
+
header = pngHeader(bytes);
|
|
999
|
+
} catch {
|
|
1000
|
+
throw new SketchframeError(`The preview image (${frame.preview.src}) isn't a readable PNG.`);
|
|
1001
|
+
}
|
|
1002
|
+
const region = previewRegion(
|
|
1003
|
+
{ ...frame, preview: { ...frame.preview, pixelWidth: header.width, pixelHeight: header.height } },
|
|
1004
|
+
node2,
|
|
1005
|
+
padding
|
|
1006
|
+
);
|
|
1007
|
+
if (region.width === 0 || region.height === 0) {
|
|
1008
|
+
throw new SketchframeError(`"${node2.name}" (${node2.id}) is outside the preview or has no size.`);
|
|
1009
|
+
}
|
|
1010
|
+
try {
|
|
1011
|
+
return { png: cropPNG(bytes, region.x, region.y, region.width, region.height), region };
|
|
1012
|
+
} catch (error) {
|
|
1013
|
+
throw new SketchframeError(`Couldn't crop the preview: ${error instanceof Error ? error.message : error}.`);
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
// ../core/src/node.ts
|
|
1018
|
+
var import_node_fs = require("node:fs");
|
|
1019
|
+
var import_node_path = require("node:path");
|
|
1020
|
+
function openFiles(path) {
|
|
1021
|
+
let stats;
|
|
1022
|
+
try {
|
|
1023
|
+
stats = (0, import_node_fs.statSync)(path);
|
|
1024
|
+
} catch {
|
|
1025
|
+
throw new SketchframeError(`No such file: ${path}`);
|
|
1026
|
+
}
|
|
1027
|
+
if (stats.isDirectory()) return folderFiles(path);
|
|
1028
|
+
return archiveFiles(new Uint8Array((0, import_node_fs.readFileSync)(path)));
|
|
1029
|
+
}
|
|
1030
|
+
function openSketchframe(path) {
|
|
1031
|
+
return loadSketchframe(openFiles(path));
|
|
1032
|
+
}
|
|
1033
|
+
function folderFiles(root) {
|
|
1034
|
+
if (!(0, import_node_fs.existsSync)((0, import_node_path.join)(root, DESIGN_FILE))) throw new SketchframeError(`${root} is a folder with no design.json.`);
|
|
1035
|
+
return {
|
|
1036
|
+
kind: "folder",
|
|
1037
|
+
read: (path) => {
|
|
1038
|
+
const full = (0, import_node_path.join)(root, ...path.split("/"));
|
|
1039
|
+
if ((0, import_node_path.relative)(root, full).startsWith("..")) return void 0;
|
|
1040
|
+
try {
|
|
1041
|
+
return new Uint8Array((0, import_node_fs.readFileSync)(full));
|
|
1042
|
+
} catch {
|
|
1043
|
+
return void 0;
|
|
1044
|
+
}
|
|
1045
|
+
},
|
|
1046
|
+
paths: () => listFiles(root)
|
|
1047
|
+
};
|
|
1048
|
+
}
|
|
1049
|
+
function listFiles(root) {
|
|
1050
|
+
const out = [];
|
|
1051
|
+
const walk = (dir) => {
|
|
1052
|
+
for (const entry of (0, import_node_fs.readdirSync)(dir, { withFileTypes: true })) {
|
|
1053
|
+
if (entry.name === ".DS_Store") continue;
|
|
1054
|
+
const full = (0, import_node_path.join)(dir, entry.name);
|
|
1055
|
+
if (entry.isDirectory()) walk(full);
|
|
1056
|
+
else if (entry.isFile()) out.push((0, import_node_path.relative)(root, full).split(import_node_path.sep).join("/"));
|
|
1057
|
+
}
|
|
1058
|
+
};
|
|
1059
|
+
walk(root);
|
|
1060
|
+
return out.sort();
|
|
1061
|
+
}
|
|
1062
|
+
function extract(source, dir) {
|
|
1063
|
+
const files = openFiles(source);
|
|
1064
|
+
const paths = files.paths().sort();
|
|
1065
|
+
(0, import_node_fs.mkdirSync)(dir, { recursive: true });
|
|
1066
|
+
for (const path of paths) {
|
|
1067
|
+
const target = (0, import_node_path.join)(dir, ...path.split("/"));
|
|
1068
|
+
if ((0, import_node_path.relative)(dir, target).startsWith("..")) continue;
|
|
1069
|
+
(0, import_node_fs.mkdirSync)((0, import_node_path.dirname)(target), { recursive: true });
|
|
1070
|
+
(0, import_node_fs.writeFileSync)(target, files.read(path) ?? new Uint8Array());
|
|
1071
|
+
}
|
|
1072
|
+
return paths;
|
|
1073
|
+
}
|
|
1074
|
+
function pack(source, file2) {
|
|
1075
|
+
const files = openFiles(source);
|
|
1076
|
+
const entries = new Map(files.paths().filter((path) => path !== MIMETYPE_FILE).map((path) => [path, files.read(path) ?? new Uint8Array()]));
|
|
1077
|
+
writeAtomically(file2, writeArchive(entries));
|
|
1078
|
+
}
|
|
1079
|
+
function writeAtomically(file2, bytes) {
|
|
1080
|
+
(0, import_node_fs.mkdirSync)((0, import_node_path.dirname)(file2), { recursive: true });
|
|
1081
|
+
const temporary = `${file2}.${process.pid}.tmp`;
|
|
1082
|
+
(0, import_node_fs.writeFileSync)(temporary, bytes);
|
|
1083
|
+
(0, import_node_fs.renameSync)(temporary, file2);
|
|
1084
|
+
}
|
|
1085
|
+
function findSketchframes(root, limit = 200) {
|
|
1086
|
+
const found = [];
|
|
1087
|
+
const walk = (dir) => {
|
|
1088
|
+
let entries;
|
|
1089
|
+
try {
|
|
1090
|
+
entries = (0, import_node_fs.readdirSync)(dir, { withFileTypes: true });
|
|
1091
|
+
} catch {
|
|
1092
|
+
return;
|
|
1093
|
+
}
|
|
1094
|
+
for (const entry of entries) {
|
|
1095
|
+
if (found.length >= limit) return;
|
|
1096
|
+
const full = (0, import_node_path.join)(dir, entry.name);
|
|
1097
|
+
if (entry.name.endsWith(".sketchframe")) {
|
|
1098
|
+
found.push((0, import_node_path.relative)(root, full).split(import_node_path.sep).join("/"));
|
|
1099
|
+
} else if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules") {
|
|
1100
|
+
walk(full);
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
};
|
|
1104
|
+
walk(root);
|
|
1105
|
+
return found.sort();
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
// src/init.ts
|
|
1109
|
+
var import_node_fs2 = require("node:fs");
|
|
1110
|
+
var import_node_path2 = require("node:path");
|
|
1111
|
+
function skillText() {
|
|
1112
|
+
const skill = true ? "---\nname: sketchframe\ndescription: Build UI from .sketchframe design files exported from Sketch. Use whenever a task mentions a .sketchframe file, a Sketch design or frame to implement, or asks to match a design, and the repository contains .sketchframe files.\n---\n\n# Building from a Sketchframe\n\nA `.sketchframe` is a design exported from Sketch: a rendered preview of one\nframe plus the full design tree (positions, sizes, fills, borders, effects,\ntypography, stack layouts, components, color tokens) and notes designers left\non layers. It is a zip archive (older exports are folders with the same\nfiles inside).\n\nDon't eyeball the preview alone, and don't read the whole `design.json`\neither: it can be huge. Use the tools to look at the outline, then pull the\ndetails of only the layers you're building.\n\n## Tools, in order of preference\n\n1. **MCP tools** (`sketchframe` server): `list_sketchframes`, `get_outline`,\n `get_node`, `get_screenshot`, `get_annotations`, `get_tokens`, `get_code`.\n2. **CLI**, when the MCP server isn't connected. Run it with\n `npx -y sketchframe <command>` (or `sketchframe` if installed, or\n `node path/to/sketchframe.cjs` if the repository commits the bundle):\n\n | MCP tool | CLI |\n |---|---|\n | `list_sketchframes` | `sketchframe list [dir]` |\n | `get_outline` | `sketchframe outline <file> [node] [--depth N]` |\n | `get_node` | `sketchframe node <file> <node> [--depth N]` |\n | `get_screenshot` | `sketchframe crop <file> [node] [-o out.png] [--padding N]`, then open the PNG with your Read tool |\n | `get_annotations` | `sketchframe annotations <file>` |\n | `get_tokens` | `sketchframe tokens <file>` |\n | `get_code` | `sketchframe code <file> <node>` |\n\n3. **No tools at all**: it's a zip.\n `unzip -p Design.sketchframe design.json`, or\n `python3 -m zipfile -e Design.sketchframe out/` and look at\n `out/preview@2x.png`. `docs/FORMAT.md` in the Sketchframe repository\n describes every field. (An older export is a folder; read its files\n directly.)\n\nA `<node>` is an id from the outline (`n4`), a `sketchId`, a layer path from\nthe frame's children down (`Header/Title`), or a unique layer name.\n\n## Workflow\n\n1. **Find the file** with `list_sketchframes` if you weren't given one.\n2. **Get the outline** (`get_outline`) and **look at the whole frame**\n (`get_screenshot` with no node). The outline gives every layer's name,\n type, position relative to its parent, size and id, and marks component\n instances (\u25C6), rotation (\u21BB) and annotated layers (\u270E).\n3. **Read the annotations** (`get_annotations`). They are instructions from\n the designer about specific layers (behaviour, accessibility, content,\n implementation notes, \"this is a mistake\"). Follow them; they override\n what the design shows.\n4. **Pick the layers to build**: usually the frame's direct children or the\n distinct sections, not every leaf.\n5. For each, **pull its context** (`get_node`) and **its screenshot**\n (`get_screenshot` with the node, maybe `padding` for context).\n `get_node` resolves shared styles inline, lists the tokens it uses with\n their values, includes its parent's layout, and the annotations on it.\n Use `depth` on large subtrees and fetch deeper children by id.\n6. **Map tokens** (`get_tokens`) onto the codebase's own design variables\n (CSS custom properties, Tailwind theme, Swift/Compose color assets)\n instead of hard-coding hex values. Reuse existing components where a\n Sketch component (instance `component` name) matches one.\n7. Optionally use **`get_code`** for an HTML/CSS starting point for a layer,\n then adapt it to the codebase's framework and conventions.\n8. **Compare** what you built against the screenshots.\n\n## Reading the values\n\n- Units are points (CSS px). `x`/`y` are relative to the parent node.\n- Stacks (`layout`) are flexbox: `mode` row/column, `gap`, `padding`,\n `justifyContent`, `alignItems`. Children with `position: \"absolute\"` sit\n outside the flow. `sizing` of `fill`/`hug`/`fixed` maps to\n `flex: 1`/`fit-content`/fixed size.\n- `fills` and `borders` are listed **top-most first**, like CSS backgrounds.\n- `effects.css` already holds ready-made `boxShadow` / `filter` /\n `backdropFilter` values.\n- Paints with `approximate: true` can't be expressed exactly in CSS; trust\n the screenshot for those.\n- `textStyle.fontWeight` is CSS (100\u2013900); `lineHeight` and `letterSpacing`\n are px. `textRuns` lists ranges styled differently.\n- Instances (`type: \"instance\"`) carry `component` (the symbol's name) and\n their resolved children; the symbol's own definition is in `components`.\n- Image and vector layers have `src` paths to files inside the archive\n (`assets/\u2026`); extract them with `sketchframe extract` if you need the\n originals.\n" : globalThis.SKETCHFRAME_SKILL;
|
|
1113
|
+
if (typeof skill !== "string") throw new Error("This build of sketchframe has no skill embedded.");
|
|
1114
|
+
return skill;
|
|
1115
|
+
}
|
|
1116
|
+
var mcpServer = { command: "npx", args: ["-y", "sketchframe", "mcp"] };
|
|
1117
|
+
var gitattributesLine = "*.sketchframe diff=sketchframe";
|
|
1118
|
+
function init(root, options = {}) {
|
|
1119
|
+
const report = [];
|
|
1120
|
+
if (options.mcp !== false) {
|
|
1121
|
+
const file2 = (0, import_node_path2.join)(root, ".mcp.json");
|
|
1122
|
+
let config = {};
|
|
1123
|
+
if ((0, import_node_fs2.existsSync)(file2)) {
|
|
1124
|
+
try {
|
|
1125
|
+
config = JSON.parse((0, import_node_fs2.readFileSync)(file2, "utf8"));
|
|
1126
|
+
} catch {
|
|
1127
|
+
throw new Error(`${file2} isn't valid JSON; fix it or pass --no-mcp.`);
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
if (config.mcpServers?.sketchframe && !options.force) {
|
|
1131
|
+
report.push(".mcp.json: already has a sketchframe server (left as it is)");
|
|
1132
|
+
} else {
|
|
1133
|
+
config.mcpServers = { ...config.mcpServers, sketchframe: mcpServer };
|
|
1134
|
+
(0, import_node_fs2.writeFileSync)(file2, `${JSON.stringify(config, null, 2)}
|
|
1135
|
+
`);
|
|
1136
|
+
report.push(".mcp.json: added the sketchframe MCP server");
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
if (options.skill !== false) {
|
|
1140
|
+
const file2 = (0, import_node_path2.join)(root, ".claude", "skills", "sketchframe", "SKILL.md");
|
|
1141
|
+
if ((0, import_node_fs2.existsSync)(file2) && !options.force) {
|
|
1142
|
+
report.push(".claude/skills/sketchframe/SKILL.md: already there (left as it is; --force replaces it)");
|
|
1143
|
+
} else {
|
|
1144
|
+
(0, import_node_fs2.mkdirSync)((0, import_node_path2.dirname)(file2), { recursive: true });
|
|
1145
|
+
(0, import_node_fs2.writeFileSync)(file2, skillText());
|
|
1146
|
+
report.push(".claude/skills/sketchframe/SKILL.md: added the skill");
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
if (options.gitattributes !== false) {
|
|
1150
|
+
const file2 = (0, import_node_path2.join)(root, ".gitattributes");
|
|
1151
|
+
const existing = (0, import_node_fs2.existsSync)(file2) ? (0, import_node_fs2.readFileSync)(file2, "utf8") : "";
|
|
1152
|
+
if (existing.split(/\r?\n/).some((line) => line.trim().startsWith("*.sketchframe "))) {
|
|
1153
|
+
report.push(".gitattributes: already has a *.sketchframe rule (left as it is)");
|
|
1154
|
+
} else {
|
|
1155
|
+
const separator = existing === "" || existing.endsWith("\n") ? "" : "\n";
|
|
1156
|
+
(0, import_node_fs2.writeFileSync)(file2, `${existing}${separator}${gitattributesLine}
|
|
1157
|
+
`);
|
|
1158
|
+
report.push('.gitattributes: added the diff driver; enable it with: git config diff.sketchframe.textconv "npx -y sketchframe cat"');
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
return report;
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
// src/mcp.ts
|
|
1165
|
+
var import_node_readline = require("node:readline");
|
|
1166
|
+
|
|
1167
|
+
// ../core/src/tools.ts
|
|
1168
|
+
var import_node_buffer = require("node:buffer");
|
|
1169
|
+
var import_node_path3 = require("node:path");
|
|
1170
|
+
var file = { type: "string", description: "Path to a .sketchframe file (or legacy folder), absolute or relative to the working directory." };
|
|
1171
|
+
var node = {
|
|
1172
|
+
type: "string",
|
|
1173
|
+
description: `The layer: an id from the outline (e.g. "n4"), a sketchId, a layer path from the frame's children down (e.g. "Header/Title"), or a unique layer name.`
|
|
1174
|
+
};
|
|
1175
|
+
var depth = { type: "integer", minimum: 0, description: "How many levels of children to include. Omit for all of them." };
|
|
1176
|
+
var tools = [
|
|
1177
|
+
{
|
|
1178
|
+
name: "list_sketchframes",
|
|
1179
|
+
title: "List Sketchframes",
|
|
1180
|
+
description: "Finds .sketchframe design files under a directory (the working directory by default). Start here when you don't know which file holds the design.",
|
|
1181
|
+
inputSchema: { type: "object", properties: { dir: { type: "string", description: "Directory to search. Defaults to the working directory." } }, additionalProperties: false },
|
|
1182
|
+
run(args, cwd) {
|
|
1183
|
+
const dir = resolvePath(optionalString(args.dir) ?? ".", cwd);
|
|
1184
|
+
const found = findSketchframes(dir);
|
|
1185
|
+
return [text2(found.length ? found.join("\n") : `No .sketchframe files under ${dir}.`)];
|
|
1186
|
+
}
|
|
1187
|
+
},
|
|
1188
|
+
{
|
|
1189
|
+
name: "get_outline",
|
|
1190
|
+
title: "Get Sketchframe outline",
|
|
1191
|
+
description: "A compact outline of a Sketchframe design: one line per layer with its name, type, position relative to its parent, size and id (`name [type] x,y w\xD7h id`), plus components (\u25C6), rotation (\u21BB), text and annotation counts (\u270E). Read this first, then pick the layers to build and call get_node and get_screenshot on them.",
|
|
1192
|
+
inputSchema: {
|
|
1193
|
+
type: "object",
|
|
1194
|
+
properties: { file, node: { ...node, description: `${node.description} Outlines from this layer down; the whole frame when omitted.` }, depth },
|
|
1195
|
+
required: ["file"],
|
|
1196
|
+
additionalProperties: false
|
|
1197
|
+
},
|
|
1198
|
+
run(args, cwd) {
|
|
1199
|
+
const frame = openSketchframe(resolvePath(requiredString(args, "file"), cwd));
|
|
1200
|
+
const start = optionalString(args.node) ? requireNode(frame, optionalString(args.node) ?? "") : frame.root;
|
|
1201
|
+
return [text2(`${summary(frame)}
|
|
1202
|
+
|
|
1203
|
+
${outline(frame, start, { depth: optionalInteger(args.depth) })}`)];
|
|
1204
|
+
}
|
|
1205
|
+
},
|
|
1206
|
+
{
|
|
1207
|
+
name: "get_node",
|
|
1208
|
+
title: "Get Sketchframe layer",
|
|
1209
|
+
description: "Everything needed to build one layer: its subtree from design.json with shared styles resolved inline, its bounds in the frame, its parent's layout, the color tokens it uses with their values, the component it instantiates, and the annotations designers left on it or its children (treat those as instructions). Positions are points relative to the parent; fills and borders are listed top-most first.",
|
|
1210
|
+
inputSchema: { type: "object", properties: { file, node, depth }, required: ["file", "node"], additionalProperties: false },
|
|
1211
|
+
run(args, cwd) {
|
|
1212
|
+
const frame = openSketchframe(resolvePath(requiredString(args, "file"), cwd));
|
|
1213
|
+
const target = requireNode(frame, requiredString(args, "node"));
|
|
1214
|
+
return [text2(toJSON(nodeContext(frame, target, { depth: optionalInteger(args.depth) })))];
|
|
1215
|
+
}
|
|
1216
|
+
},
|
|
1217
|
+
{
|
|
1218
|
+
name: "get_screenshot",
|
|
1219
|
+
title: "Get Sketchframe screenshot",
|
|
1220
|
+
description: "An image of the design as Sketch rendered it: the region of the preview showing one layer, or the whole frame when no layer is given. Use it alongside get_node to check what the values should look like.",
|
|
1221
|
+
inputSchema: {
|
|
1222
|
+
type: "object",
|
|
1223
|
+
properties: {
|
|
1224
|
+
file,
|
|
1225
|
+
node: { ...node, description: `${node.description} Omit for the whole frame.` },
|
|
1226
|
+
padding: { type: "number", minimum: 0, description: "Points of surrounding context to include around the layer. Defaults to 0." }
|
|
1227
|
+
},
|
|
1228
|
+
required: ["file"],
|
|
1229
|
+
additionalProperties: false
|
|
1230
|
+
},
|
|
1231
|
+
run(args, cwd) {
|
|
1232
|
+
const frame = openSketchframe(resolvePath(requiredString(args, "file"), cwd));
|
|
1233
|
+
const query = optionalString(args.node);
|
|
1234
|
+
const target = query ? requireNode(frame, query) : void 0;
|
|
1235
|
+
if (target && !frame.files.read(frame.preview.src)) throw new SketchframeError("This Sketchframe has no preview image.");
|
|
1236
|
+
const crop = cropPreview(frame, target, optionalNumber(args.padding) ?? 0);
|
|
1237
|
+
const scale2 = frame.preview.scale;
|
|
1238
|
+
return [
|
|
1239
|
+
{ type: "image", data: import_node_buffer.Buffer.from(crop.png).toString("base64"), mimeType: "image/png" },
|
|
1240
|
+
text2(
|
|
1241
|
+
`${target ? `"${target.name}" (${target.id})` : frame.name}: ${crop.region.width}\xD7${crop.region.height} px at ${scale2}x (${crop.region.width / scale2}\xD7${crop.region.height / scale2} pt).`
|
|
1242
|
+
)
|
|
1243
|
+
];
|
|
1244
|
+
}
|
|
1245
|
+
},
|
|
1246
|
+
{
|
|
1247
|
+
name: "get_tokens",
|
|
1248
|
+
title: "Get Sketchframe tokens",
|
|
1249
|
+
description: "The design's color tokens (Sketch color variables) with their values, its Sketch shared styles, and style values reused by several layers, each with the ids of the layers that use it. Map these onto the target codebase's variables rather than hard-coding values.",
|
|
1250
|
+
inputSchema: { type: "object", properties: { file }, required: ["file"], additionalProperties: false },
|
|
1251
|
+
run(args, cwd) {
|
|
1252
|
+
const frame = openSketchframe(resolvePath(requiredString(args, "file"), cwd));
|
|
1253
|
+
return [text2(toJSON(tokens(frame)))];
|
|
1254
|
+
}
|
|
1255
|
+
},
|
|
1256
|
+
{
|
|
1257
|
+
name: "get_annotations",
|
|
1258
|
+
title: "Get Sketchframe annotations",
|
|
1259
|
+
description: "Notes designers left on layers, each with a category (development, interaction, accessibility, content) and the layer it is attached to. Treat them as instructions about those layers. Detached notes are on layers that are no longer in the design.",
|
|
1260
|
+
inputSchema: { type: "object", properties: { file }, required: ["file"], additionalProperties: false },
|
|
1261
|
+
run(args, cwd) {
|
|
1262
|
+
const frame = openSketchframe(resolvePath(requiredString(args, "file"), cwd));
|
|
1263
|
+
const list = annotations(frame);
|
|
1264
|
+
return [text2(list.length ? toJSON(list) : "This Sketchframe has no annotations.")];
|
|
1265
|
+
}
|
|
1266
|
+
},
|
|
1267
|
+
{
|
|
1268
|
+
name: "get_code",
|
|
1269
|
+
title: "Get Sketchframe layer as HTML/CSS",
|
|
1270
|
+
description: "A starting point in HTML and CSS for one layer and its children: stacks as flexbox, other layers positioned absolutely, token colors as CSS variables. Adapt it to the target codebase's components and conventions rather than pasting it.",
|
|
1271
|
+
inputSchema: { type: "object", properties: { file, node }, required: ["file", "node"], additionalProperties: false },
|
|
1272
|
+
run(args, cwd) {
|
|
1273
|
+
const frame = openSketchframe(resolvePath(requiredString(args, "file"), cwd));
|
|
1274
|
+
return [text2(htmlForNode(frame, requireNode(frame, requiredString(args, "node"))))];
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
];
|
|
1278
|
+
function toolNamed(name) {
|
|
1279
|
+
return tools.find((tool) => tool.name === name);
|
|
1280
|
+
}
|
|
1281
|
+
function text2(value) {
|
|
1282
|
+
return { type: "text", text: value };
|
|
1283
|
+
}
|
|
1284
|
+
function resolvePath(path, cwd) {
|
|
1285
|
+
return (0, import_node_path3.isAbsolute)(path) ? path : (0, import_node_path3.resolve)(cwd, path);
|
|
1286
|
+
}
|
|
1287
|
+
function requiredString(args, key) {
|
|
1288
|
+
const value = args[key];
|
|
1289
|
+
if (typeof value !== "string" || value === "") throw new SketchframeError(`Missing "${key}".`);
|
|
1290
|
+
return value;
|
|
1291
|
+
}
|
|
1292
|
+
function optionalString(value) {
|
|
1293
|
+
return typeof value === "string" && value !== "" ? value : void 0;
|
|
1294
|
+
}
|
|
1295
|
+
function optionalNumber(value) {
|
|
1296
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
1297
|
+
if (typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value))) return Number(value);
|
|
1298
|
+
return void 0;
|
|
1299
|
+
}
|
|
1300
|
+
function optionalInteger(value) {
|
|
1301
|
+
const n = optionalNumber(value);
|
|
1302
|
+
return n === void 0 ? void 0 : Math.max(0, Math.floor(n));
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
// src/version.ts
|
|
1306
|
+
var version = true ? "0.4.0" : "dev";
|
|
1307
|
+
|
|
1308
|
+
// src/mcp.ts
|
|
1309
|
+
var protocolVersions = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
|
|
1310
|
+
var instructions = `Sketchframe tools read .sketchframe design files exported from Sketch: a preview image plus the full design tree.
|
|
1311
|
+
Workflow: list_sketchframes (if you don't know the file) \u2192 get_outline \u2192 get_screenshot of the whole frame \u2192 pick the layers to build \u2192 get_node and get_screenshot for each \u2192 get_annotations for designers' notes (follow them) \u2192 get_tokens to map colors onto the codebase's variables. get_code gives an HTML/CSS starting point for a layer.`;
|
|
1312
|
+
function startServer(cwd = process.cwd()) {
|
|
1313
|
+
const send = (message) => process.stdout.write(`${JSON.stringify(message)}
|
|
1314
|
+
`);
|
|
1315
|
+
const reply = (id, result) => send({ jsonrpc: "2.0", id, result });
|
|
1316
|
+
const fail = (id, code, message) => send({ jsonrpc: "2.0", id: id ?? null, error: { code, message } });
|
|
1317
|
+
const handle = (request) => {
|
|
1318
|
+
const { id, method, params = {} } = request;
|
|
1319
|
+
const isNotification = id === void 0;
|
|
1320
|
+
switch (method) {
|
|
1321
|
+
case "initialize": {
|
|
1322
|
+
const requested = typeof params.protocolVersion === "string" ? params.protocolVersion : "";
|
|
1323
|
+
reply(id, {
|
|
1324
|
+
protocolVersion: protocolVersions.includes(requested) ? requested : protocolVersions[0],
|
|
1325
|
+
capabilities: { tools: { listChanged: false } },
|
|
1326
|
+
serverInfo: { name: "sketchframe", title: "Sketchframe", version },
|
|
1327
|
+
instructions
|
|
1328
|
+
});
|
|
1329
|
+
return;
|
|
1330
|
+
}
|
|
1331
|
+
case "ping":
|
|
1332
|
+
reply(id, {});
|
|
1333
|
+
return;
|
|
1334
|
+
case "tools/list":
|
|
1335
|
+
reply(id, {
|
|
1336
|
+
tools: tools.map((tool) => ({
|
|
1337
|
+
name: tool.name,
|
|
1338
|
+
title: tool.title,
|
|
1339
|
+
description: tool.description,
|
|
1340
|
+
inputSchema: tool.inputSchema,
|
|
1341
|
+
annotations: { readOnlyHint: true, openWorldHint: false }
|
|
1342
|
+
}))
|
|
1343
|
+
});
|
|
1344
|
+
return;
|
|
1345
|
+
case "tools/call": {
|
|
1346
|
+
const name = typeof params.name === "string" ? params.name : "";
|
|
1347
|
+
const tool = toolNamed(name);
|
|
1348
|
+
if (!tool) {
|
|
1349
|
+
fail(id, -32602, `Unknown tool: ${name}`);
|
|
1350
|
+
return;
|
|
1351
|
+
}
|
|
1352
|
+
const args = typeof params.arguments === "object" && params.arguments !== null ? params.arguments : {};
|
|
1353
|
+
try {
|
|
1354
|
+
reply(id, { content: tool.run(args, cwd) });
|
|
1355
|
+
} catch (error) {
|
|
1356
|
+
reply(id, { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true });
|
|
1357
|
+
}
|
|
1358
|
+
return;
|
|
1359
|
+
}
|
|
1360
|
+
case "resources/list":
|
|
1361
|
+
reply(id, { resources: [] });
|
|
1362
|
+
return;
|
|
1363
|
+
case "prompts/list":
|
|
1364
|
+
reply(id, { prompts: [] });
|
|
1365
|
+
return;
|
|
1366
|
+
default:
|
|
1367
|
+
if (!isNotification) fail(id, -32601, `Method not found: ${method}`);
|
|
1368
|
+
}
|
|
1369
|
+
};
|
|
1370
|
+
const lines = (0, import_node_readline.createInterface)({ input: process.stdin, crlfDelay: Infinity });
|
|
1371
|
+
lines.on("line", (line) => {
|
|
1372
|
+
if (!line.trim()) return;
|
|
1373
|
+
let message;
|
|
1374
|
+
try {
|
|
1375
|
+
message = JSON.parse(line);
|
|
1376
|
+
} catch {
|
|
1377
|
+
fail(null, -32700, "Parse error");
|
|
1378
|
+
return;
|
|
1379
|
+
}
|
|
1380
|
+
for (const request of Array.isArray(message) ? message : [message]) {
|
|
1381
|
+
if (typeof request !== "object" || request === null || typeof request.method !== "string") {
|
|
1382
|
+
continue;
|
|
1383
|
+
}
|
|
1384
|
+
try {
|
|
1385
|
+
handle(request);
|
|
1386
|
+
} catch (error) {
|
|
1387
|
+
fail(request.id, -32603, error instanceof Error ? error.message : String(error));
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
});
|
|
1391
|
+
process.stderr.write(`sketchframe MCP server ${version} on stdio (cwd ${cwd})
|
|
1392
|
+
`);
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
// src/cli.ts
|
|
1396
|
+
var usage = `sketchframe ${version}: read .sketchframe design files
|
|
1397
|
+
|
|
1398
|
+
Usage:
|
|
1399
|
+
sketchframe list [dir] Find .sketchframe files (default: current directory)
|
|
1400
|
+
sketchframe outline <file> [node] [--depth N] A compact tree of ids, names, types and sizes
|
|
1401
|
+
sketchframe node <file> <node> [--depth N] One layer's subtree with styles and tokens resolved
|
|
1402
|
+
sketchframe crop <file> [node] [-o out.png] [--padding N]
|
|
1403
|
+
The preview, or one layer's region of it, as a PNG
|
|
1404
|
+
sketchframe tokens <file> Color tokens, shared styles and reused style values
|
|
1405
|
+
sketchframe annotations <file> Designers' notes, with the layers they're attached to
|
|
1406
|
+
sketchframe code <file> <node> An HTML/CSS starting point for a layer
|
|
1407
|
+
sketchframe cat <file> A stable text rendering (used as a git diff driver)
|
|
1408
|
+
sketchframe extract <file> <dir> Unpack an archive into a folder
|
|
1409
|
+
sketchframe pack <dir> <file> Pack a folder (or legacy package) into an archive
|
|
1410
|
+
sketchframe mcp Run the MCP server on stdio
|
|
1411
|
+
sketchframe init [dir] [--force] [--no-mcp] [--no-skill] [--no-gitattributes]
|
|
1412
|
+
Set a repository up for Claude Code: .mcp.json,
|
|
1413
|
+
the skill and the git diff driver
|
|
1414
|
+
sketchframe skill Print the Claude skill (SKILL.md)
|
|
1415
|
+
|
|
1416
|
+
<node> is an id from the outline (n4), a sketchId, a layer path (Header/Title)
|
|
1417
|
+
or a unique layer name. <file> can be a .sketchframe archive or a legacy
|
|
1418
|
+
.sketchframe folder.
|
|
1419
|
+
|
|
1420
|
+
Docs: https://github.com/zaccomode/sketchframe/blob/main/docs/agents.md`;
|
|
1421
|
+
function parseArgs(argv) {
|
|
1422
|
+
const positional = [];
|
|
1423
|
+
const flags = {};
|
|
1424
|
+
const takesValue = /* @__PURE__ */ new Set(["depth", "padding", "o", "output"]);
|
|
1425
|
+
for (let i = 0; i < argv.length; i++) {
|
|
1426
|
+
const arg = argv[i];
|
|
1427
|
+
const match = /^--?([a-zA-Z][\w-]*)(?:=(.*))?$/.exec(arg);
|
|
1428
|
+
if (!match || arg === "-") {
|
|
1429
|
+
positional.push(arg);
|
|
1430
|
+
continue;
|
|
1431
|
+
}
|
|
1432
|
+
const [, name, inline] = match;
|
|
1433
|
+
if (inline !== void 0) flags[name] = inline;
|
|
1434
|
+
else if (takesValue.has(name) && i + 1 < argv.length) flags[name] = argv[++i];
|
|
1435
|
+
else flags[name] = true;
|
|
1436
|
+
}
|
|
1437
|
+
return { positional, flags };
|
|
1438
|
+
}
|
|
1439
|
+
function integer(value, name) {
|
|
1440
|
+
if (value === void 0) return void 0;
|
|
1441
|
+
const n = Number(value);
|
|
1442
|
+
if (value === true || !Number.isFinite(n) || n < 0) throw new UsageError(`--${name} takes a number.`);
|
|
1443
|
+
return n;
|
|
1444
|
+
}
|
|
1445
|
+
var UsageError = class extends Error {
|
|
1446
|
+
};
|
|
1447
|
+
function need(positional, index, what) {
|
|
1448
|
+
const value = positional[index];
|
|
1449
|
+
if (value === void 0) throw new UsageError(`Missing ${what}.`);
|
|
1450
|
+
return value;
|
|
1451
|
+
}
|
|
1452
|
+
function run(argv, out = (text3) => process.stdout.write(text3)) {
|
|
1453
|
+
const { positional, flags } = parseArgs(argv);
|
|
1454
|
+
const [command, ...rest] = positional;
|
|
1455
|
+
const print = (text3) => out(text3.endsWith("\n") ? text3 : `${text3}
|
|
1456
|
+
`);
|
|
1457
|
+
if (flags.version || flags.v) {
|
|
1458
|
+
print(version);
|
|
1459
|
+
return 0;
|
|
1460
|
+
}
|
|
1461
|
+
if (!command || command === "help" || flags.help || flags.h) {
|
|
1462
|
+
print(usage);
|
|
1463
|
+
return command || flags.help || flags.h ? 0 : 1;
|
|
1464
|
+
}
|
|
1465
|
+
switch (command) {
|
|
1466
|
+
case "list":
|
|
1467
|
+
case "ls": {
|
|
1468
|
+
const found = findSketchframes((0, import_node_path4.resolve)(rest[0] ?? "."));
|
|
1469
|
+
print(found.length ? found.join("\n") : "No .sketchframe files found.");
|
|
1470
|
+
return 0;
|
|
1471
|
+
}
|
|
1472
|
+
case "outline": {
|
|
1473
|
+
const frame = openSketchframe(need(rest, 0, "<file>"));
|
|
1474
|
+
const start = rest[1] ? requireNode(frame, rest[1]) : frame.root;
|
|
1475
|
+
print(`${summary(frame)}
|
|
1476
|
+
|
|
1477
|
+
${outline(frame, start, { depth: integer(flags.depth, "depth") })}`);
|
|
1478
|
+
return 0;
|
|
1479
|
+
}
|
|
1480
|
+
case "node": {
|
|
1481
|
+
const frame = openSketchframe(need(rest, 0, "<file>"));
|
|
1482
|
+
const node2 = requireNode(frame, need(rest, 1, "<node>"));
|
|
1483
|
+
print(toJSON(nodeContext(frame, node2, { depth: integer(flags.depth, "depth") })));
|
|
1484
|
+
return 0;
|
|
1485
|
+
}
|
|
1486
|
+
case "crop":
|
|
1487
|
+
case "screenshot": {
|
|
1488
|
+
const file2 = need(rest, 0, "<file>");
|
|
1489
|
+
const frame = openSketchframe(file2);
|
|
1490
|
+
const node2 = rest[1] ? requireNode(frame, rest[1]) : void 0;
|
|
1491
|
+
const crop = cropPreview(frame, node2, integer(flags.padding, "padding") ?? 0);
|
|
1492
|
+
const output = flags.o ?? flags.output;
|
|
1493
|
+
const target = typeof output === "string" ? output : (0, import_node_path4.join)((0, import_node_os.tmpdir)(), `${(0, import_node_path4.basename)(file2, ".sketchframe").replace(/[^\w.-]+/g, "-")}${node2 ? `-${node2.id}` : ""}.png`);
|
|
1494
|
+
(0, import_node_fs3.writeFileSync)(target, crop.png);
|
|
1495
|
+
print(`${(0, import_node_path4.resolve)(target)} (${crop.region.width}\xD7${crop.region.height} px at ${frame.preview.scale}x)`);
|
|
1496
|
+
return 0;
|
|
1497
|
+
}
|
|
1498
|
+
case "tokens": {
|
|
1499
|
+
print(toJSON(tokens(openSketchframe(need(rest, 0, "<file>")))));
|
|
1500
|
+
return 0;
|
|
1501
|
+
}
|
|
1502
|
+
case "annotations": {
|
|
1503
|
+
const list = annotations(openSketchframe(need(rest, 0, "<file>")));
|
|
1504
|
+
print(list.length ? toJSON(list) : "No annotations.");
|
|
1505
|
+
return 0;
|
|
1506
|
+
}
|
|
1507
|
+
case "code": {
|
|
1508
|
+
const frame = openSketchframe(need(rest, 0, "<file>"));
|
|
1509
|
+
print(htmlForNode(frame, requireNode(frame, need(rest, 1, "<node>"))));
|
|
1510
|
+
return 0;
|
|
1511
|
+
}
|
|
1512
|
+
case "cat": {
|
|
1513
|
+
out(catText(openFiles(need(rest, 0, "<file>"))));
|
|
1514
|
+
return 0;
|
|
1515
|
+
}
|
|
1516
|
+
case "extract": {
|
|
1517
|
+
const paths = extract(need(rest, 0, "<file>"), need(rest, 1, "<dir>"));
|
|
1518
|
+
print(`Extracted ${paths.length} files to ${rest[1]}.`);
|
|
1519
|
+
return 0;
|
|
1520
|
+
}
|
|
1521
|
+
case "pack": {
|
|
1522
|
+
pack(need(rest, 0, "<dir>"), need(rest, 1, "<file>"));
|
|
1523
|
+
print(`Packed ${rest[0]} into ${rest[1]}.`);
|
|
1524
|
+
return 0;
|
|
1525
|
+
}
|
|
1526
|
+
case "init": {
|
|
1527
|
+
const report = init((0, import_node_path4.resolve)(rest[0] ?? "."), {
|
|
1528
|
+
mcp: !flags["no-mcp"],
|
|
1529
|
+
skill: !flags["no-skill"],
|
|
1530
|
+
gitattributes: !flags["no-gitattributes"],
|
|
1531
|
+
force: Boolean(flags.force)
|
|
1532
|
+
});
|
|
1533
|
+
print(`${report.join("\n")}
|
|
1534
|
+
Commit these files so cloud sessions get them too.`);
|
|
1535
|
+
return 0;
|
|
1536
|
+
}
|
|
1537
|
+
case "skill": {
|
|
1538
|
+
out(skillText());
|
|
1539
|
+
return 0;
|
|
1540
|
+
}
|
|
1541
|
+
default:
|
|
1542
|
+
throw new UsageError(`Unknown command "${command}".`);
|
|
1543
|
+
}
|
|
1544
|
+
}
|
|
1545
|
+
function main(argv = process.argv.slice(2)) {
|
|
1546
|
+
if (argv[0] === "mcp") {
|
|
1547
|
+
startServer();
|
|
1548
|
+
return;
|
|
1549
|
+
}
|
|
1550
|
+
try {
|
|
1551
|
+
process.exitCode = run(argv);
|
|
1552
|
+
} catch (error) {
|
|
1553
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1554
|
+
process.stderr.write(`sketchframe: ${message}
|
|
1555
|
+
`);
|
|
1556
|
+
if (error instanceof UsageError) process.stderr.write(`Run "sketchframe help" for usage.
|
|
1557
|
+
`);
|
|
1558
|
+
process.exitCode = error instanceof UsageError ? 2 : 1;
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
|
|
1562
|
+
// src/main.ts
|
|
1563
|
+
main();
|