easel-canvas 0.1.1 → 0.2.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.
@@ -0,0 +1,627 @@
1
+ // AI-generated with Claude Code, 2026-11-11, reviewed by Hyun Park
2
+ // Share a view-only copy: a static viewer of the design folder (web folder, or one self-contained .html), or PDF / PNG of the boards.
3
+ // Writes only inside the chosen folder; a re-export removes only the files its own manifest lists.
4
+ import { spawn } from "node:child_process";
5
+ import { existsSync } from "node:fs";
6
+ import fs from "node:fs/promises";
7
+ import http from "node:http";
8
+ import path from "node:path";
9
+
10
+ import { TOOL_ROOT } from "./args.mjs";
11
+ import { createBoardStore } from "./board.mjs";
12
+ import { browserStatus, newPage as sharedNewPage } from "./browser.mjs";
13
+ import { projectName, rootOf, toPosix } from "./fsutil.mjs";
14
+ import { MIME, readBody, safeJoin, sendJson } from "./index.mjs";
15
+ import { git } from "./snapshot.mjs";
16
+
17
+ export const MANIFEST = ".easel-export.json";
18
+ /** Viewer code and data sit in their own folder so they never collide with the design folder's files (screens/, assets/) */
19
+ const VIEWER = "easel-viewer";
20
+ export const EASEL_URL = "https://github.com/nemodleo/easel";
21
+ const DATA_MIME = { ...MIME, ".avif": "image/avif", ".ttf": "font/ttf", ".otf": "font/otf", ".mp4": "video/mp4", ".webm": "video/webm", ".mp3": "audio/mpeg", ".wav": "audio/wav", ".txt": "text/plain", ".map": "application/json" };
22
+ const fail = (status, message) => Object.assign(new Error(message), { status });
23
+
24
+ /** <project root>/easel-export: the folder the canvas exports to (the CLI can pick another with --out) */
25
+ export const defaultOut = (dir) => path.join(rootOf(dir), "easel-export");
26
+ const slug = (dir) => projectName(dir).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "easel";
27
+ export const singleName = (dir) => `${slug(dir)}-canvas.html`;
28
+
29
+ /* ---------- Scope ---------- */
30
+
31
+ /** Boards, notes, shapes and pages a scope covers. scope: { page: id or name } or { boards: [file] }; neither = the whole canvas */
32
+ export function pickScope(board, files, { page, boards } = {}) {
33
+ const have = new Set(files);
34
+ const first = board.pages[0]?.id;
35
+ const pageOf = (item) => item.page ?? first;
36
+ let keep;
37
+ let onPage = () => true;
38
+ if (boards?.length) {
39
+ for (const f of boards) if (typeof f !== "string" || !Object.hasOwn(board.boards, f) || !have.has(f)) throw fail(400, `Unknown board: ${String(f).slice(0, 120)}`);
40
+ keep = board.order.filter((f) => boards.includes(f));
41
+ // Notes and shapes come along when they sit next to the chosen boards
42
+ const r = bbox(keep.map((f) => board.boards[f]), 240);
43
+ const pages = new Set(keep.map((f) => pageOf(board.boards[f])));
44
+ onPage = (item) => pages.has(pageOf(item)) && item.x >= r.x && item.x <= r.x + r.w && item.y >= r.y && item.y <= r.y + r.h;
45
+ } else if (page) {
46
+ const pg = board.pages.find((p) => p.id === page) ?? board.pages.find((p) => p.name === page);
47
+ if (!pg) throw fail(400, board.pages.length ? `Unknown page: ${String(page).slice(0, 120)}` : "This canvas has no pages; leave the page out to export everything");
48
+ onPage = (item) => pageOf(item) === pg.id;
49
+ keep = board.order.filter((f) => have.has(f) && onPage(board.boards[f]));
50
+ } else keep = board.order.filter((f) => have.has(f) && board.boards[f]);
51
+ const notes = Object.keys(board.notes ?? {}).filter((id) => onPage(board.notes[id]));
52
+ const shapes = Object.keys(board.shapes ?? {}).filter((id) => onPage(board.shapes[id]));
53
+ const used = new Set(keep.map((f) => pageOf(board.boards[f])));
54
+ return { boards: keep, notes, shapes, pages: board.pages.filter((p) => used.has(p.id)) };
55
+ }
56
+
57
+ function bbox(rects, pad = 0) {
58
+ if (!rects.length) return { x: 0, y: 0, w: 0, h: 0 };
59
+ const x = Math.min(...rects.map((r) => r.x)) - pad;
60
+ const y = Math.min(...rects.map((r) => r.y)) - pad;
61
+ return { x, y, w: Math.max(...rects.map((r) => r.x + r.w)) + pad - x, h: Math.max(...rects.map((r) => r.y + r.h)) + pad - y };
62
+ }
63
+
64
+ /** Screens with no board.json entry yet get a spot below everything, in memory only (the CLI must not rewrite board.json in CI) */
65
+ async function placeMissing(board, files, sizeOf) {
66
+ const loose = files.filter((f) => !board.boards[f]);
67
+ if (!loose.length) return board;
68
+ const all = Object.values(board.boards);
69
+ let x = all.length ? Math.min(...all.map((b) => b.x)) : 0;
70
+ const y = all.length ? Math.max(...all.map((b) => b.y + b.h)) + 120 : 0;
71
+ const boards = { ...board.boards };
72
+ for (const f of loose) {
73
+ const s = await sizeOf(f);
74
+ boards[f] = { x, y, ...s, title: f.replace(/\.html$/, "") };
75
+ x += s.w + 80;
76
+ }
77
+ return { ...board, boards, order: [...board.order, ...loose] };
78
+ }
79
+
80
+ /* ---------- Stamp ---------- */
81
+
82
+ /** Export time, plus <repo>@<short commit> when the design folder is in a git repository */
83
+ export async function exportStamp(dir, now = new Date()) {
84
+ const at = now.toISOString();
85
+ const top = await git(dir, ["rev-parse", "--show-toplevel"]);
86
+ if (top.code !== 0) return { at };
87
+ const head = await git(dir, ["rev-parse", "--short", "HEAD"]);
88
+ return { at, repo: path.basename(top.out.trim()), ...(head.code === 0 && head.out.trim() ? { commit: head.out.trim() } : {}) };
89
+ }
90
+
91
+ /* ---------- URLs inside screens ---------- */
92
+
93
+ const unent = (s) => s.replace(/&(amp|quot|#39|apos);/g, (_, e) => ({ amp: "&", quot: '"', "#39": "'", apos: "'" })[e]);
94
+ const FRAME_TAGS = new Set(["iframe", "frame", "embed", "object"]);
95
+ const URL_ATTRS = new Set(["src", "href", "poster", "data", "background", "xlink:href"]);
96
+ const TOKENS = /<!--[\s\S]*?-->|<script\b(?:"[^"]*"|'[^']*'|[^'">])*>[\s\S]*?<\/script\s*>|<style\b((?:"[^"]*"|'[^']*'|[^'">])*)>([\s\S]*?)<\/style\s*>|<[a-zA-Z][\w:-]*(?:"[^"]*"|'[^']*'|[^'">])*>/gi;
97
+
98
+ /** Calls fn(url) for every url() and @import in CSS; fn returns a replacement, or undefined to keep it */
99
+ export function mapCssUrls(css, fn) {
100
+ return css.replace(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)'"\s]*))\s*\)|@import\s+(?:"([^"]*)"|'([^']*)')/gi, (m, a, b, c, d, e) => {
101
+ const u = a ?? b ?? c ?? d ?? e ?? "";
102
+ const r = u ? fn(u) : undefined;
103
+ if (r === undefined || r === u) return m;
104
+ return m.startsWith("@") ? `@import "${r}"` : `url("${r}")`;
105
+ });
106
+ }
107
+
108
+ /**
109
+ * Calls fn(url, kind) for every URL in an HTML document, outside scripts and comments; fn returns a replacement or undefined.
110
+ * kind: "link" for <a>/<area> href (navigation), "frame" for iframe/frame/embed/object, "asset" for everything else.
111
+ */
112
+ export function mapHtmlUrls(html, fn) {
113
+ const tag = (t) => {
114
+ const name = /^<([\w:-]+)/.exec(t)[1].toLowerCase();
115
+ if (name === "base") return t;
116
+ return t.replace(/(\s)([\w:.-]+)(\s*=\s*)("[^"]*"|'[^']*'|[^\s"'>]+)/g, (m, sp, attr, eq, raw) => {
117
+ const a = attr.toLowerCase();
118
+ const val = unent(raw[0] === '"' || raw[0] === "'" ? raw.slice(1, -1) : raw);
119
+ let next;
120
+ if (a === "style") next = mapCssUrls(val, (u) => fn(u, "asset"));
121
+ else if (a === "srcset" || a === "imagesrcset") next = mapSrcset(val, (u) => fn(u, "asset"));
122
+ else if (URL_ATTRS.has(a)) next = fn(val, a === "href" && (name === "a" || name === "area") ? "link" : FRAME_TAGS.has(name) ? "frame" : "asset");
123
+ if (next === undefined || next === val) return m;
124
+ return `${sp}${attr}${eq}"${next.replace(/&/g, "&amp;").replace(/"/g, "&quot;")}"`;
125
+ });
126
+ };
127
+ return html.replace(TOKENS, (m, styleAttrs, styleBody) => {
128
+ if (m.startsWith("<!--")) return m;
129
+ if (/^<script\b/i.test(m)) return m.replace(/^<script\b(?:"[^"]*"|'[^']*'|[^'">])*>/i, tag);
130
+ if (styleBody !== undefined) {
131
+ const open = /^<style\b(?:"[^"]*"|'[^']*'|[^'">])*>/i.exec(m)[0];
132
+ return tag(open) + mapCssUrls(styleBody, (u) => fn(u, "asset")) + m.slice(open.length + styleBody.length);
133
+ }
134
+ return tag(m);
135
+ });
136
+ }
137
+
138
+ /** srcset candidates: a URL runs to the next whitespace (data: URLs keep their commas), descriptors run to the next comma */
139
+ function mapSrcset(val, fn) {
140
+ const out = [];
141
+ let changed = false;
142
+ for (let i = 0; i < val.length; ) {
143
+ while (i < val.length && /[\s,]/.test(val[i])) i++;
144
+ if (i >= val.length) break;
145
+ let j = i;
146
+ while (j < val.length && !/\s/.test(val[j])) j++;
147
+ let url = val.slice(i, j);
148
+ let desc = "";
149
+ if (url.endsWith(",")) url = url.replace(/,+$/, "");
150
+ else {
151
+ const k = val.indexOf(",", j);
152
+ desc = val.slice(j, k < 0 ? val.length : k).trim();
153
+ j = k < 0 ? val.length : k;
154
+ }
155
+ const r = fn(url);
156
+ if (r !== undefined && r !== url) changed = true;
157
+ out.push([r ?? url, desc].filter(Boolean).join(" "));
158
+ i = j + 1;
159
+ }
160
+ return changed ? out.join(", ") : val;
161
+ }
162
+
163
+ /** Local URLs only: schemes (http:, data:, mailto:…), protocol-relative and fragment-only URLs are left alone */
164
+ const isLocal = (u) => !!u && !/^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i.test(u);
165
+ const splitSuffix = (u) => {
166
+ const i = u.search(/[?#]/);
167
+ return i < 0 ? [u, ""] : [u.slice(0, i), u.slice(i)];
168
+ };
169
+
170
+ /** Design-folder paths (posix) a local URL in fromRel may point to: a root-relative URL means screens/ first, then the folder (as the server serves it) */
171
+ export function refCandidates(fromRel, url) {
172
+ if (!isLocal(url.trim())) return [];
173
+ let [p] = splitSuffix(url.trim());
174
+ try {
175
+ p = decodeURIComponent(p);
176
+ } catch {
177
+ return [];
178
+ }
179
+ if (!p || p.includes("\0") || p.includes("\\")) return [];
180
+ const list = p.startsWith("/") ? [`screens/${p.slice(1)}`, p.slice(1)] : [path.posix.join(path.posix.dirname(fromRel), p)];
181
+ // Nothing outside the design folder, and no dot folders (.easel, .thumbs, .trash, .refs…) or dot files
182
+ return list.map((r) => path.posix.normalize(r)).filter((r) => r && r !== "." && !r.startsWith("../") && r !== ".." && !path.posix.isAbsolute(r) && !r.split("/").some((s) => s.startsWith(".")));
183
+ }
184
+
185
+ const relFrom = (fromRel, rel) => path.posix.relative(path.posix.dirname(fromRel), rel) || path.posix.basename(rel);
186
+ const encodePath = (rel) => rel.split("/").map(encodeURIComponent).join("/");
187
+
188
+ /* ---------- Collecting what the screens need ---------- */
189
+
190
+ /**
191
+ * Absolute path of a file inside the design folder, or null: missing, not a file, or a link that leads out of the folder.
192
+ * An export is handed to other people, so a link in a cloned project must not pull in files from elsewhere on this machine.
193
+ */
194
+ export async function fileIn(dir, rel) {
195
+ const p = safeJoin(dir, rel);
196
+ if (!p) return null;
197
+ try {
198
+ const [root, real] = await Promise.all([fs.realpath(dir), fs.realpath(p)]);
199
+ if (!real.startsWith(root + path.sep)) return null;
200
+ return (await fs.stat(real)).isFile() ? p : null;
201
+ } catch {
202
+ return null;
203
+ }
204
+ }
205
+
206
+ /**
207
+ * Walks the screens and everything they reference inside the design folder (CSS, images, fonts, scripts, embedded HTML).
208
+ * Returns { files: Map<rel, Buffer>, skipped: [{ ref, from, reason }] }.
209
+ */
210
+ async function collect(dir, screens, exclude) {
211
+ const files = new Map();
212
+ const skipped = [];
213
+ const seen = new Set();
214
+ const locate = async (fromRel, url) => {
215
+ for (const c of refCandidates(fromRel, url)) {
216
+ if (exclude(c)) continue;
217
+ if (await fileIn(dir, c)) return c;
218
+ }
219
+ return null;
220
+ };
221
+ const visit = async (rel) => {
222
+ if (seen.has(rel)) return;
223
+ seen.add(rel);
224
+ const p = await fileIn(dir, rel);
225
+ if (!p) throw fail(400, `${rel} is not a file inside the design folder`);
226
+ const buf = await fs.readFile(p);
227
+ files.set(rel, buf);
228
+ const ext = path.posix.extname(rel).toLowerCase();
229
+ if (ext !== ".html" && ext !== ".htm" && ext !== ".css") return;
230
+ const found = [];
231
+ const note = (u, kind) => {
232
+ if (kind !== "link" && isLocal(u.trim())) found.push(u);
233
+ };
234
+ if (ext === ".css") mapCssUrls(buf.toString("utf8"), (u) => note(u, "asset"));
235
+ else mapHtmlUrls(buf.toString("utf8"), note);
236
+ for (const u of found) {
237
+ const hit = await locate(rel, u);
238
+ if (hit) await visit(hit);
239
+ else if (!skipped.some((s) => s.ref === u && s.from === rel)) skipped.push({ ref: u, from: rel, reason: "not found in the design folder" });
240
+ }
241
+ };
242
+ for (const f of screens) await visit(`screens/${f}`);
243
+ return { files, skipped, locate };
244
+ }
245
+
246
+ /** Web folder: root-relative URLs become relative, so the copy works under any sub-path */
247
+ async function relativize(text, fromRel, isCss, locate) {
248
+ const hits = new Map();
249
+ const want = [];
250
+ const note = (u) => {
251
+ if (u.trim().startsWith("/") && isLocal(u.trim())) want.push(u);
252
+ };
253
+ if (isCss) mapCssUrls(text, note);
254
+ else mapHtmlUrls(text, note);
255
+ for (const u of want) {
256
+ const hit = await locate(fromRel, u);
257
+ if (hit) hits.set(u, relFrom(fromRel, hit) + splitSuffix(u.trim())[1]);
258
+ }
259
+ if (!hits.size) return text;
260
+ return isCss ? mapCssUrls(text, (u) => hits.get(u)) : mapHtmlUrls(text, (u) => hits.get(u));
261
+ }
262
+
263
+ const mimeOf = (rel) => (DATA_MIME[path.posix.extname(rel).toLowerCase()] ?? "application/octet-stream").split(";")[0];
264
+
265
+ /** Single file: every asset a document references becomes a data: URL (CSS recursively); embedded HTML cannot be inlined and is listed */
266
+ async function inline(text, fromRel, isCss, ctx, depth = 0) {
267
+ const { files, locate, skipped } = ctx;
268
+ const map = new Map();
269
+ const want = [];
270
+ const note = (u, kind) => {
271
+ if (isLocal(u.trim())) want.push([u, kind]);
272
+ };
273
+ if (isCss) mapCssUrls(text, (u) => note(u, "asset"));
274
+ else mapHtmlUrls(text, note);
275
+ for (const [u, kind] of want) {
276
+ if (map.has(u)) continue;
277
+ const hit = await locate(fromRel, u);
278
+ if (kind === "link") {
279
+ // Navigation stays a link (Play follows it inside the viewer); root-relative ones become relative so they resolve
280
+ if (hit && u.trim().startsWith("/")) map.set(u, relFrom(fromRel, hit) + splitSuffix(u.trim())[1]);
281
+ continue;
282
+ }
283
+ const buf = hit && files.get(hit);
284
+ if (!buf) continue; // already listed as missing by collect()
285
+ if (kind === "frame" || /\.html?$/i.test(hit)) {
286
+ if (!skipped.some((s) => s.ref === u && s.from === fromRel)) skipped.push({ ref: u, from: fromRel, reason: "embedded HTML is not inlined in a single file" });
287
+ continue;
288
+ }
289
+ if (/\.css$/i.test(hit) && depth < 8) {
290
+ const css = await inline(buf.toString("utf8"), hit, true, ctx, depth + 1);
291
+ map.set(u, `data:text/css;base64,${Buffer.from(css).toString("base64")}`);
292
+ } else map.set(u, `data:${mimeOf(hit)};base64,${buf.toString("base64")}`);
293
+ }
294
+ if (!map.size) return text;
295
+ return isCss ? mapCssUrls(text, (u) => map.get(u)) : mapHtmlUrls(text, (u) => map.get(u));
296
+ }
297
+
298
+ /* ---------- Viewer page ---------- */
299
+
300
+ const escHtml = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
301
+ /** JSON that is safe inside <script>: no </script> and no HTML comment openers */
302
+ const scriptJson = (v) => JSON.stringify(v).replace(/</g, "\\u003c");
303
+
304
+ async function viewerBuild() {
305
+ const d = path.join(TOOL_ROOT, "dist", "viewer");
306
+ try {
307
+ return { js: await fs.readFile(path.join(d, "viewer.js"), "utf8"), css: await fs.readFile(path.join(d, "viewer.css"), "utf8") };
308
+ } catch {
309
+ throw fail(500, "No viewer build found (run npm run build)");
310
+ }
311
+ }
312
+
313
+ const page = ({ title, head, body }) =>
314
+ `<!doctype html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<meta name="viewport" content="width=device-width, initial-scale=1">\n<meta name="generator" content="Easel">\n<title>${escHtml(title)} — view only</title>\n${head}\n</head>\n<body>\n<div id="root"></div>\n${body}\n</body>\n</html>\n`;
315
+
316
+ /* ---------- Output folder ---------- */
317
+
318
+ /** A path the manifest lists, only when it is a plain relative path inside out (no .., no absolute, no backslashes) */
319
+ function ownPath(out, rel) {
320
+ if (typeof rel !== "string" || !rel || rel.includes("\0") || rel.includes("\\") || path.posix.isAbsolute(rel) || /^[a-z]:/i.test(rel)) return null;
321
+ if (rel.split("/").some((s) => s === ".." || s === "." || s === "")) return null;
322
+ const p = path.join(out, ...rel.split("/"));
323
+ return p.startsWith(out + path.sep) ? p : null;
324
+ }
325
+
326
+ async function readManifest(out) {
327
+ try {
328
+ const m = JSON.parse(await fs.readFile(path.join(out, MANIFEST), "utf8"));
329
+ return m && m.easel === 1 && typeof m.exports === "object" && m.exports ? m : null;
330
+ } catch {
331
+ return null;
332
+ }
333
+ }
334
+
335
+ /** Refuses folders that are not ours, then removes this kind's files from the previous export (only what the manifest lists) */
336
+ async function prepareOut(out, dir, kind) {
337
+ const screensDir = path.join(dir, "screens");
338
+ if (out === path.parse(out).root) throw fail(400, "Pick a folder for the export, not the drive root");
339
+ if (dir === out || dir.startsWith(out + path.sep)) throw fail(400, `${out} holds the design folder; export to a folder of its own`);
340
+ if (out === screensDir || out.startsWith(screensDir + path.sep)) throw fail(400, "The export folder cannot be inside screens/ (it would turn into boards)");
341
+ const entries = await fs.readdir(out).catch((e) => (e.code === "ENOENT" ? null : Promise.reject(e)));
342
+ if (!entries) {
343
+ await fs.mkdir(out, { recursive: true });
344
+ return { easel: 1, exports: {} };
345
+ }
346
+ const manifest = await readManifest(out);
347
+ if (!manifest) {
348
+ if (entries.length) throw fail(409, `${out} is not empty and was not made by an Easel export. Empty it or pick another folder.`);
349
+ return { easel: 1, exports: {} };
350
+ }
351
+ const old = manifest.exports[kind]?.files ?? [];
352
+ const dirs = new Set();
353
+ for (const rel of Array.isArray(old) ? old : []) {
354
+ const p = ownPath(out, rel);
355
+ if (!p) continue;
356
+ await fs.rm(p, { force: true });
357
+ for (let d = path.dirname(p); d.startsWith(out + path.sep); d = path.dirname(d)) dirs.add(d);
358
+ }
359
+ // Empty folders left behind go too, deepest first
360
+ for (const d of [...dirs].sort((a, b) => b.length - a.length)) await fs.rmdir(d).catch(() => {});
361
+ delete manifest.exports[kind];
362
+ return manifest;
363
+ }
364
+
365
+ async function writeOut(out, manifest, kind, entries, at) {
366
+ // The manifest lists the new files before they are written, so a failed export still leaves nothing untracked
367
+ manifest.exports[kind] = { at, files: entries.map((e) => e.rel) };
368
+ await fs.writeFile(path.join(out, MANIFEST), JSON.stringify(manifest, null, 1) + "\n");
369
+ let bytes = 0;
370
+ for (const e of entries) {
371
+ const p = ownPath(out, e.rel);
372
+ if (!p) throw fail(400, `Refusing to write outside the export folder: ${e.rel}`);
373
+ await fs.mkdir(path.dirname(p), { recursive: true });
374
+ if (e.from) await fs.copyFile(e.from, p);
375
+ else await fs.writeFile(p, e.data);
376
+ bytes += e.from ? (await fs.stat(p)).size : Buffer.byteLength(e.data);
377
+ }
378
+ return bytes;
379
+ }
380
+
381
+ /* ---------- PDF and PNG ---------- */
382
+
383
+ /** A throwaway static server for the design folder while Chromium renders it (the CLI runs without a canvas) */
384
+ async function serveDesign(dir) {
385
+ const server = http.createServer(async (req, res) => {
386
+ let rel;
387
+ try {
388
+ rel = decodeURIComponent(new URL(req.url ?? "/", "http://x").pathname).slice(1);
389
+ } catch {
390
+ res.writeHead(400);
391
+ return res.end();
392
+ }
393
+ for (const c of rel.startsWith("screens/") ? [rel] : [`screens/${rel}`, rel]) {
394
+ if (c.split("/").some((s) => s.startsWith("."))) continue;
395
+ const p = await fileIn(dir, c);
396
+ if (!p) continue;
397
+ res.writeHead(200, { "Content-Type": MIME[path.extname(p).toLowerCase()] ?? "application/octet-stream" });
398
+ return res.end(await fs.readFile(p));
399
+ }
400
+ res.writeHead(404);
401
+ res.end();
402
+ });
403
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
404
+ return { url: `http://127.0.0.1:${server.address().port}`, close: () => new Promise((r) => server.close(r)) };
405
+ }
406
+
407
+ async function renderBoards(dir, boards, newPage) {
408
+ const srv = await serveDesign(dir);
409
+ const shots = [];
410
+ try {
411
+ for (const b of boards) {
412
+ let pg;
413
+ try {
414
+ pg = await newPage({ viewport: { width: b.w, height: b.h }, deviceScaleFactor: 2 });
415
+ } catch (e) {
416
+ throw fail(501, `PDF and PNG need a headless Chromium (${String(e.message ?? e).split("\n")[0]}). Run npx playwright install chromium.`);
417
+ }
418
+ try {
419
+ await pg.goto(`${srv.url}/screens/${encodePath(b.file)}`, { waitUntil: "load", timeout: 20000 });
420
+ await pg.waitForTimeout(150);
421
+ shots.push({ ...b, png: await pg.screenshot({ type: "png" }) });
422
+ } finally {
423
+ await pg.close();
424
+ }
425
+ }
426
+ } finally {
427
+ await srv.close();
428
+ }
429
+ return shots;
430
+ }
431
+
432
+ /** One page per board, each page the board's own size (CSS named pages) */
433
+ async function pdfOf(shots, newPage) {
434
+ const css = shots.map((s, i) => `@page b${i}{size:${s.w}px ${s.h}px;margin:0}.b${i}{page:b${i};width:${s.w}px;height:${s.h}px}`).join("");
435
+ const body = shots.map((s, i) => `<div class="b${i}"><img src="data:image/png;base64,${s.png.toString("base64")}" alt=""></div>`).join("");
436
+ const pg = await newPage();
437
+ try {
438
+ await pg.setContent(`<!doctype html><html><head><style>html,body{margin:0}div{break-after:page;overflow:hidden}div:last-child{break-after:auto}img{display:block;width:100%;height:100%}${css}</style></head><body>${body}</body></html>`, { waitUntil: "load" });
439
+ return await pg.pdf({ preferCSSPageSize: true, printBackground: true });
440
+ } finally {
441
+ await pg.close();
442
+ }
443
+ }
444
+
445
+ /* ---------- Export ---------- */
446
+
447
+ /**
448
+ * Exports the design folder. format: "web" (with singleFile for one .html), "pdf" or "png".
449
+ * scope: page (id or name) or boards ([file]); neither = everything. dryRun: build in memory and return the size only.
450
+ * Returns { kind, out, outRel, main, mainRel, files, bytes, skipped, deploy }.
451
+ */
452
+ export async function exportDesign({ dir, out, store, format = "web", singleFile = false, page: pageId, boards: boardList, dryRun = false, now = new Date(), newPage = sharedNewPage }) {
453
+ dir = path.resolve(dir);
454
+ if (!existsSync(path.join(dir, "screens"))) throw fail(400, `No screens/ folder in ${dir}`);
455
+ out = path.resolve(out ?? defaultOut(dir));
456
+ const kind = format === "pdf" ? "pdf" : format === "png" ? "png" : singleFile ? "single" : "web";
457
+ const st = store ?? createBoardStore(dir);
458
+ const files = await st.listScreenFiles();
459
+ const board = await placeMissing(await st.readBoard(), files, st.readBoardSize);
460
+ const scope = pickScope(board, files, { page: pageId, boards: boardList });
461
+ if (!scope.boards.length) throw fail(400, "Nothing to export: no boards in this scope");
462
+ const root = rootOf(dir);
463
+ const outRelOf = (p) => (p === root || p.startsWith(root + path.sep) ? toPosix(path.relative(root, p)) : toPosix(p));
464
+ const entries = [];
465
+ let skipped = [];
466
+ let main;
467
+
468
+ if (kind === "pdf" || kind === "png") {
469
+ const status = newPage === sharedNewPage ? await browserStatus() : { ok: true };
470
+ if (!status.ok) throw fail(501, `PDF and PNG are unavailable here. ${status.reason}`);
471
+ const shots = await renderBoards(dir, scope.boards.map((f) => ({ file: f, w: board.boards[f].w, h: board.boards[f].h })), newPage);
472
+ if (kind === "png") for (const s of shots) entries.push({ rel: `png/${s.file.replace(/\.html$/, "").replace(/\//g, "-")}@2x.png`, data: s.png });
473
+ else entries.push({ rel: `${slug(dir)}-canvas.pdf`, data: await pdfOf(shots, newPage) });
474
+ main = kind === "pdf" ? entries[0].rel : "png/";
475
+ } else {
476
+ const outInDir = out.startsWith(dir + path.sep) ? toPosix(path.relative(dir, out)) : null;
477
+ const exclude = (rel) => !!outInDir && (rel === outInDir || rel.startsWith(outInDir + "/"));
478
+ const col = await collect(dir, scope.boards, exclude);
479
+ skipped = col.skipped;
480
+ const viewer = await viewerBuild();
481
+ const comments = (await readComments(dir)).filter((c) => scope.boards.includes(c.file));
482
+ const pick = (obj, ids) => Object.fromEntries(ids.map((id) => [id, obj[id]]));
483
+ const shapes = pick(board.shapes ?? {}, scope.shapes);
484
+ const data = {
485
+ version: 1,
486
+ title: board.title,
487
+ stamp: await exportStamp(dir, now),
488
+ board: { version: 1, title: board.title, pages: scope.pages, boards: pick(board.boards, scope.boards), order: scope.boards, notes: pick(board.notes ?? {}, scope.notes), shapes, ...(board.groupNames ? { groupNames: board.groupNames } : {}) },
489
+ files: scope.boards,
490
+ comments,
491
+ };
492
+ // Image shapes point at ../assets/x (relative to screens/): the copy, or the image itself in a single file
493
+ const shapeFiles = new Map();
494
+ for (const [id, s] of Object.entries(shapes)) {
495
+ if (s.kind !== "image" || !s.src) continue;
496
+ const hit = await col.locate("screens/_", s.src);
497
+ if (!hit) {
498
+ skipped.push({ ref: s.src, from: "board.json", reason: "not found in the design folder" });
499
+ continue;
500
+ }
501
+ const buf = col.files.get(hit) ?? (await fs.readFile(path.join(dir, hit)));
502
+ shapeFiles.set(hit, buf);
503
+ shapes[id] = { ...s, src: kind === "single" ? `data:${mimeOf(hit)};base64,${buf.toString("base64")}` : encodePath(hit) };
504
+ }
505
+ if (kind === "single") {
506
+ data.screens = {};
507
+ for (const f of scope.boards) data.screens[f] = await inline(col.files.get(`screens/${f}`).toString("utf8"), `screens/${f}`, false, col);
508
+ main = singleName(dir);
509
+ const html = page({
510
+ title: board.title,
511
+ head: `<style>${viewer.css.replace(/<\/style/gi, "<\\/style")}</style>`,
512
+ body: `<script>window.EASEL_EXPORT=${scriptJson(data)};</script>\n<script>${viewer.js.replace(/<\/script/gi, "<\\/script")}</script>`,
513
+ });
514
+ entries.push({ rel: main, data: html });
515
+ } else {
516
+ for (const [rel, buf] of new Map([...col.files, ...shapeFiles])) {
517
+ const ext = path.posix.extname(rel).toLowerCase();
518
+ if ([".html", ".htm", ".css"].includes(ext)) entries.push({ rel, data: await relativize(buf.toString("utf8"), rel, ext === ".css", col.locate) });
519
+ else entries.push({ rel, from: path.join(dir, rel) });
520
+ }
521
+ const ours = new Set(["index.html", ".nojekyll"]);
522
+ for (const e of entries) if (ours.has(e.rel) || e.rel.startsWith(VIEWER + "/")) throw fail(409, `The design folder has ${e.rel}, which the viewer needs for itself`);
523
+ entries.push(
524
+ { rel: "index.html", data: page({ title: board.title, head: `<link rel="stylesheet" href="${VIEWER}/viewer.css">`, body: `<script src="${VIEWER}/data.js"></script>\n<script src="${VIEWER}/viewer.js"></script>` }) },
525
+ { rel: `${VIEWER}/viewer.js`, data: viewer.js },
526
+ { rel: `${VIEWER}/viewer.css`, data: viewer.css },
527
+ { rel: `${VIEWER}/data.js`, data: `window.EASEL_EXPORT=${scriptJson(data)};\n` },
528
+ // GitHub Pages: serve the folder as is (no Jekyll)
529
+ { rel: ".nojekyll", data: "" },
530
+ );
531
+ main = "index.html";
532
+ }
533
+ }
534
+
535
+ const result = { kind, out, outRel: outRelOf(out) + "/", main: path.join(out, main), mainRel: outRelOf(path.join(out, main)) + (main.endsWith("/") ? "/" : ""), files: entries.length, skipped };
536
+ if (dryRun) return { ...result, bytes: entries.reduce((n, e) => n + (e.data != null ? Buffer.byteLength(e.data) : 0), 0) };
537
+ const manifest = await prepareOut(out, dir, kind);
538
+ const bytes = await writeOut(out, manifest, kind, entries, now.toISOString());
539
+ return { ...result, bytes, ...(kind === "web" ? { deploy: deployCommand(root, out) } : {}) };
540
+ }
541
+
542
+ async function readComments(dir) {
543
+ try {
544
+ const d = JSON.parse(await fs.readFile(path.join(dir, "comments.json"), "utf8"));
545
+ return Array.isArray(d.comments) ? d.comments : [];
546
+ } catch {
547
+ return [];
548
+ }
549
+ }
550
+
551
+ const shellQuote = (s) => (/^[\w./@:,=+-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
552
+ /** Hosts the web folder on Vercel (a preview URL); asks to sign in on first use, nothing to configure in the repo */
553
+ export const deployCommand = (root, out) => `npx vercel deploy ${shellQuote(out.startsWith(root + path.sep) ? toPosix(path.relative(root, out)) : out)}`;
554
+
555
+ function revealFolder(p) {
556
+ const [cmd, args] = process.platform === "darwin" ? ["open", [p]] : process.platform === "win32" ? ["explorer", [p]] : ["xdg-open", [p]];
557
+ spawn(cmd, args, { stdio: "ignore", detached: true, windowsHide: true }).on("error", () => {}).unref();
558
+ }
559
+
560
+ /* ---------- HTTP ---------- */
561
+
562
+ /** reveal(path) opens a folder in the OS file manager (injectable for tests) */
563
+ export function exportRoutes({ reveal = revealFolder } = {}) {
564
+ const wrote = new WeakMap(); // ctx → the export folder this server wrote
565
+ // Expected failures (bad scope, foreign folder, no Chromium) answer with their status instead of a logged server error
566
+ const guard = (h) => async (req, res, url, ctx) => {
567
+ try {
568
+ await h(req, res, url, ctx);
569
+ } catch (e) {
570
+ if (!e.status) throw e;
571
+ sendJson(res, e.status, { error: e.message });
572
+ }
573
+ };
574
+ const scopeOf = (b) => (b.scope === "page" ? { page: String(b.page ?? "") } : b.scope === "boards" ? { boards: Array.isArray(b.boards) ? b.boards.slice(0, 2000) : [] } : {});
575
+ return [
576
+ [
577
+ "GET",
578
+ "/api/export",
579
+ async (req, res, url, ctx) => {
580
+ const root = rootOf(ctx.dir);
581
+ const out = defaultOut(ctx.dir);
582
+ const dirRel = toPosix(path.relative(root, ctx.dir)) || ".";
583
+ sendJson(res, 200, {
584
+ project: path.basename(root),
585
+ out: toPosix(path.relative(root, out)) + "/",
586
+ single: singleName(ctx.dir),
587
+ dirFlag: dirRel === "docs/design" || dirRel === "." ? "" : `--dir ${shellQuote(dirRel)}`,
588
+ deploy: deployCommand(root, out),
589
+ browser: await browserStatus(),
590
+ });
591
+ },
592
+ ],
593
+ [
594
+ "POST",
595
+ "/api/export",
596
+ guard(async (req, res, url, ctx) => {
597
+ const b = await readBody(req);
598
+ await ctx.store.syncBoard();
599
+ // The canvas always writes to <project root>/easel-export; only the CLI picks another folder
600
+ const r = await exportDesign({ dir: ctx.dir, store: ctx.store, out: defaultOut(ctx.dir), format: ["pdf", "png"].includes(b.format) ? b.format : "web", singleFile: !!b.singleFile, ...scopeOf(b) });
601
+ wrote.set(ctx, r.out);
602
+ sendJson(res, 200, r);
603
+ }),
604
+ ],
605
+ [
606
+ "POST",
607
+ "/api/export/estimate",
608
+ guard(async (req, res, url, ctx) => {
609
+ const b = await readBody(req);
610
+ await ctx.store.syncBoard();
611
+ const r = await exportDesign({ dir: ctx.dir, store: ctx.store, out: defaultOut(ctx.dir), singleFile: true, dryRun: true, ...scopeOf(b) });
612
+ sendJson(res, 200, { bytes: r.bytes, name: singleName(ctx.dir), skipped: r.skipped.length });
613
+ }),
614
+ ],
615
+ [
616
+ "POST",
617
+ "/api/export/reveal",
618
+ async (req, res, url, ctx) => {
619
+ const out = wrote.get(ctx);
620
+ // Only the folder this server exported to, and only while it still holds an Easel export
621
+ if (!out || !(await readManifest(out))) return sendJson(res, 409, { error: "Export first, then reveal the folder" });
622
+ reveal(out);
623
+ sendJson(res, 200, { ok: true, path: out });
624
+ },
625
+ ],
626
+ ];
627
+ }