easel-canvas 0.1.0 → 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.
- package/README.md +64 -20
- package/bin/mcp.mjs +151 -43
- package/bin/server.mjs +69 -6
- package/dist/assets/index-BZFSkKqU.css +1 -0
- package/dist/assets/index-BwyrrnkP.js +65 -0
- package/dist/index.html +3 -3
- package/dist/viewer/viewer.css +1 -0
- package/dist/viewer/viewer.js +49 -0
- package/package.json +2 -2
- package/server/activity.mjs +370 -0
- package/server/agents.mjs +20 -0
- package/server/args.mjs +22 -2
- package/server/board.mjs +33 -33
- package/server/boards.mjs +51 -25
- package/server/browser.mjs +68 -0
- package/server/chat.mjs +446 -51
- package/server/connect.mjs +94 -0
- package/server/copies.mjs +105 -0
- package/server/custom.mjs +101 -0
- package/server/edit.mjs +2 -2
- package/server/export.mjs +627 -0
- package/server/forks.mjs +214 -0
- package/server/fsutil.mjs +25 -0
- package/server/history.mjs +152 -24
- package/server/html.mjs +11 -1
- package/server/index.mjs +162 -17
- package/server/occupancy.mjs +183 -0
- package/server/permissions.mjs +141 -0
- package/server/place.mjs +87 -0
- package/server/registry.mjs +110 -0
- package/server/routes.mjs +37 -38
- package/server/runs.mjs +167 -0
- package/server/snapshot.mjs +21 -9
- package/server/tokens.mjs +15 -3
- package/server/update.mjs +63 -0
- package/server/watch.mjs +12 -1
- package/dist/assets/index-DbJY7lxA.css +0 -1
- package/dist/assets/index-O7RiYHEC.js +0 -55
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// AI-generated with Claude Code, 2026-11-10, reviewed by Hyun Park
|
|
2
|
+
// Running canvases: each app server writes <EASEL_HOME or ~/.easel>/servers/<port>.json, and the MCP server
|
|
3
|
+
// picks the one for the project it was started in, so agent configs need no --port.
|
|
4
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
|
|
8
|
+
import { DEFAULT_PORT } from "./args.mjs";
|
|
9
|
+
|
|
10
|
+
export const easelHome = (env = process.env) => env.EASEL_HOME || path.join(os.homedir(), ".easel");
|
|
11
|
+
const serversDir = (home) => path.join(home, "servers");
|
|
12
|
+
/** Resolved path (links like /var → /private/var), also for a folder that does not exist yet: its nearest existing parent */
|
|
13
|
+
const real = (p) => {
|
|
14
|
+
const abs = path.resolve(p);
|
|
15
|
+
try {
|
|
16
|
+
return realpathSync(abs);
|
|
17
|
+
} catch {
|
|
18
|
+
const up = path.dirname(abs);
|
|
19
|
+
return up === abs ? abs : path.join(real(up), path.basename(abs));
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/** Records a listening canvas; returns the remover (removes only our own entry) */
|
|
24
|
+
export function writeEntry({ port, dir, root, pid = process.pid }, home = easelHome()) {
|
|
25
|
+
const d = serversDir(home);
|
|
26
|
+
mkdirSync(d, { recursive: true });
|
|
27
|
+
const file = path.join(d, `${port}.json`);
|
|
28
|
+
writeFileSync(file, JSON.stringify({ port, pid, dir, root, startedAt: new Date().toISOString() }, null, 2) + "\n");
|
|
29
|
+
return () => {
|
|
30
|
+
try {
|
|
31
|
+
if (JSON.parse(readFileSync(file, "utf8")).pid === pid) rmSync(file, { force: true });
|
|
32
|
+
} catch {
|
|
33
|
+
/* already gone */
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function readEntries(home = easelHome()) {
|
|
39
|
+
const d = serversDir(home);
|
|
40
|
+
if (!existsSync(d)) return [];
|
|
41
|
+
const out = [];
|
|
42
|
+
for (const n of readdirSync(d).filter((n) => /^\d+\.json$/.test(n))) {
|
|
43
|
+
try {
|
|
44
|
+
const e = JSON.parse(readFileSync(path.join(d, n), "utf8"));
|
|
45
|
+
if (Number.isInteger(e.port) && e.dir && e.root) out.push(e);
|
|
46
|
+
} catch {
|
|
47
|
+
/* half-written or broken: skip */
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return out.sort((a, b) => a.port - b.port);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Whether a (resolved) folder is inside another one, or the same */
|
|
54
|
+
export const within = (child, parent) => {
|
|
55
|
+
const r = path.relative(parent, child);
|
|
56
|
+
return r === "" || (!r.startsWith("..") && !path.isAbsolute(r));
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Pure choice among live canvases for an MCP server started in cwd (paths already resolved):
|
|
61
|
+
* the entry whose root contains cwd (longest root wins), else the only one below cwd (several below: ambiguous),
|
|
62
|
+
* else the only one at all, else ambiguous/none.
|
|
63
|
+
*/
|
|
64
|
+
export function pickServer(entries, cwd) {
|
|
65
|
+
const around = entries.filter((e) => within(cwd, e.root)).sort((a, b) => b.root.length - a.root.length);
|
|
66
|
+
if (around.length) return { entry: around[0] };
|
|
67
|
+
const below = entries.filter((e) => within(e.root, cwd));
|
|
68
|
+
if (below.length) return below.length === 1 ? { entry: below[0] } : { ambiguous: below };
|
|
69
|
+
if (entries.length === 1) return { entry: entries[0] };
|
|
70
|
+
return entries.length ? { ambiguous: entries } : {};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const pidAlive = (pid) => {
|
|
74
|
+
try {
|
|
75
|
+
process.kill(pid, 0);
|
|
76
|
+
return true;
|
|
77
|
+
} catch (e) {
|
|
78
|
+
return e.code === "EPERM";
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/** /api/health answers and serves the same design folder */
|
|
83
|
+
export async function isAlive(e, ms = 800) {
|
|
84
|
+
try {
|
|
85
|
+
const r = await fetch(`http://127.0.0.1:${e.port}/api/health`, { signal: AbortSignal.timeout(ms) });
|
|
86
|
+
if (!r.ok) return false;
|
|
87
|
+
const h = await r.json();
|
|
88
|
+
return real(h.dir) === real(e.dir);
|
|
89
|
+
} catch {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Port for the MCP server: explicit (--port, or DESIGN_CANVAS_PORT from an in-app run) wins, else the registry, else the default.
|
|
96
|
+
* Throws when several canvases are live and cwd does not single one out.
|
|
97
|
+
*/
|
|
98
|
+
export async function discoverPort({ port = null, cwd = process.cwd(), home = easelHome() } = {}) {
|
|
99
|
+
if (port) return port;
|
|
100
|
+
const live = [];
|
|
101
|
+
for (const e of readEntries(home)) {
|
|
102
|
+
if (await isAlive(e)) live.push({ ...e, root: real(e.root) });
|
|
103
|
+
else if (!pidAlive(e.pid)) rmSync(path.join(serversDir(home), `${e.port}.json`), { force: true }); // left behind by a crash
|
|
104
|
+
}
|
|
105
|
+
const pick = pickServer(live, real(cwd));
|
|
106
|
+
if (pick.entry) return pick.entry.port;
|
|
107
|
+
if (pick.ambiguous)
|
|
108
|
+
throw new Error(`Several Easel canvases are running and ${cwd} does not single one out:\n${pick.ambiguous.map((e) => ` ${e.root} (port ${e.port})`).join("\n")}\nPass --port <n> to easel-mcp to pick one.`);
|
|
109
|
+
return DEFAULT_PORT;
|
|
110
|
+
}
|
package/server/routes.mjs
CHANGED
|
@@ -3,13 +3,16 @@
|
|
|
3
3
|
import fs from "node:fs/promises";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
|
|
6
|
-
import {
|
|
6
|
+
import { activityRoutes } from "./activity.mjs";
|
|
7
|
+
import { closeBrowser, newPage } from "./browser.mjs";
|
|
7
8
|
import { boardRoutes } from "./boards.mjs";
|
|
8
9
|
import { chatRoutes } from "./chat.mjs";
|
|
9
10
|
import { tokenRoutes } from "./tokens.mjs";
|
|
10
11
|
import { snapshotRoutes } from "./snapshot.mjs";
|
|
11
12
|
import { applyEdit, EditError } from "./edit.mjs";
|
|
12
|
-
import {
|
|
13
|
+
import { exportRoutes } from "./export.mjs";
|
|
14
|
+
import { forkMessage, forkRoutes, routeWrite } from "./forks.mjs";
|
|
15
|
+
import { easelDir, rootOf, toPosix, writeAtomic } from "./fsutil.mjs";
|
|
13
16
|
import { inspect, outline } from "./html.mjs";
|
|
14
17
|
import { readBody, safeJoin, sendJson } from "./index.mjs";
|
|
15
18
|
import { watchDesign } from "./watch.mjs";
|
|
@@ -47,27 +50,12 @@ async function writeComments(ctx, comments) {
|
|
|
47
50
|
}
|
|
48
51
|
|
|
49
52
|
/* ---------- Screenshots (when playwright is available) ---------- */
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
export async function closeBrowser() {
|
|
53
|
-
const b = await browserPromise?.catch(() => null);
|
|
54
|
-
browserPromise = null;
|
|
55
|
-
await b?.close().catch(() => {});
|
|
56
|
-
}
|
|
53
|
+
// The shared Chromium lives in browser.mjs (export uses it too); re-exported here for existing callers
|
|
54
|
+
export { cachedBrowser, closeBrowser, newPage } from "./browser.mjs";
|
|
57
55
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
const { chromium } = await import("playwright").catch(() => {
|
|
62
|
-
throw Object.assign(new Error("Screenshots are unavailable because playwright is not installed (npm run design:install)"), { status: 501 });
|
|
63
|
-
});
|
|
64
|
-
// Fall back to the installed Chrome if no downloaded Chromium exists
|
|
65
|
-
return chromium.launch().catch(() => chromium.launch({ channel: "chrome" }));
|
|
66
|
-
})();
|
|
67
|
-
browserPromise.catch(() => (browserPromise = null));
|
|
68
|
-
}
|
|
69
|
-
return browserPromise;
|
|
70
|
-
}
|
|
56
|
+
/** Thumbnail sizes (long side, device px) the client may ask for; anything else snaps to the next one up. Matches THUMB_SIZES in Canvas.tsx */
|
|
57
|
+
const THUMB_PX = [600, 1200, 2400];
|
|
58
|
+
export const thumbPx = (v) => THUMB_PX.find((s) => s >= Number(v)) ?? (Number(v) > 0 ? THUMB_PX[THUMB_PX.length - 1] : THUMB_PX[0]);
|
|
71
59
|
|
|
72
60
|
/** Generate at most two thumbnails at a time */
|
|
73
61
|
let running = 0;
|
|
@@ -92,11 +80,10 @@ function thumbQueue(job) {
|
|
|
92
80
|
|
|
93
81
|
export async function screenshot(ctx, port, file, elPath) {
|
|
94
82
|
const board = (await ctx.store.readBoard()).boards[file];
|
|
95
|
-
const
|
|
96
|
-
const page = await browser.newPage({ viewport: { width: board?.w ?? 390, height: board?.h ?? 844 }, deviceScaleFactor: 2 });
|
|
83
|
+
const page = await newPage({ viewport: { width: board?.w ?? 390, height: board?.h ?? 844 }, deviceScaleFactor: 2 });
|
|
97
84
|
try {
|
|
98
85
|
await page.goto(`http://127.0.0.1:${port}/screens/${encodeURI(file)}`, { waitUntil: "networkidle" });
|
|
99
|
-
const outDir = path.join(
|
|
86
|
+
const outDir = path.join(await easelDir(ctx.dir), "screenshots");
|
|
100
87
|
await fs.mkdir(outDir, { recursive: true });
|
|
101
88
|
const name = `${file.replace(/[\\/]/g, "_").replace(/\.html$/, "")}${elPath ? "--" + elPath.replace(/\//g, "-") : ""}.png`;
|
|
102
89
|
const out = path.join(outDir, name);
|
|
@@ -124,19 +111,24 @@ export const extraRoutes = [
|
|
|
124
111
|
"/api/edit",
|
|
125
112
|
async (req, res, url, ctx) => {
|
|
126
113
|
const b = await readBody(req);
|
|
127
|
-
|
|
114
|
+
await readScreen(ctx, b.file);
|
|
115
|
+
// An agent editing a board another agent is on works on its fork (people always edit the board they are on)
|
|
116
|
+
const to = await routeWrite(ctx, b.file);
|
|
117
|
+
const { p, html } = await readScreen(ctx, to.file);
|
|
118
|
+
const fork = to.forked ? { file: to.file, forked: true, original: b.file, message: forkMessage(ctx, b.file, to) } : {};
|
|
128
119
|
let next;
|
|
129
120
|
try {
|
|
130
121
|
next = applyEdit(html, b);
|
|
131
122
|
} catch (e) {
|
|
132
|
-
|
|
123
|
+
// On a fork the agent may hold the original's HTML, so the error says which file it is on now
|
|
124
|
+
if (e instanceof EditError) return sendJson(res, e.status, { error: to.forked ? `${e.message}. ${fork.message}` : e.message, ...fork });
|
|
133
125
|
throw e;
|
|
134
126
|
}
|
|
135
|
-
if (next === html) return sendJson(res, 200, { ok: true, changed: false });
|
|
127
|
+
if (next === html) return sendJson(res, 200, { ok: true, changed: false, ...fork });
|
|
136
128
|
await writeScreen(ctx, p, next);
|
|
137
|
-
ctx.history.push(`${
|
|
129
|
+
ctx.history.push(`${to.file} ${b.op}`, [{ path: p, before: html, after: next }]);
|
|
138
130
|
ctx.broadcast({ type: "history-changed" });
|
|
139
|
-
sendJson(res, 200, { ok: true, changed: true });
|
|
131
|
+
sendJson(res, 200, { ok: true, changed: true, ...fork });
|
|
140
132
|
},
|
|
141
133
|
],
|
|
142
134
|
// Legacy route: forwards to the chronological history
|
|
@@ -150,6 +142,8 @@ export const extraRoutes = [
|
|
|
150
142
|
},
|
|
151
143
|
]),
|
|
152
144
|
...boardRoutes(),
|
|
145
|
+
...forkRoutes(),
|
|
146
|
+
...activityRoutes(),
|
|
153
147
|
...chat.routes,
|
|
154
148
|
...tokenRoutes(),
|
|
155
149
|
// Zoomed-out thumbnails: small images shown below 25% instead of empty frames. Stored per modification time in docs/design/.thumbs/ (gitignored)
|
|
@@ -161,8 +155,11 @@ export const extraRoutes = [
|
|
|
161
155
|
const src = safeJoin(ctx.store.screensDir, f);
|
|
162
156
|
const st = src && (await fs.stat(src).catch(() => null));
|
|
163
157
|
if (!st) return sendJson(res, 404, { error: "File not found" });
|
|
158
|
+
const px = thumbPx(url.searchParams.get("px"));
|
|
164
159
|
const dir = path.join(ctx.dir, ".thumbs");
|
|
165
|
-
const
|
|
160
|
+
const base = f.replace(/[\\/]/g, "_");
|
|
161
|
+
const stamp = `${base}.${Math.round(st.mtimeMs)}.`;
|
|
162
|
+
const out = path.join(dir, `${stamp}${px}.jpg`);
|
|
166
163
|
let buf = await fs.readFile(out).catch(() => null);
|
|
167
164
|
if (!buf) {
|
|
168
165
|
buf = await thumbQueue(async () => {
|
|
@@ -171,14 +168,14 @@ export const extraRoutes = [
|
|
|
171
168
|
const board = (await ctx.store.readBoard()).boards[f];
|
|
172
169
|
const w = board?.w ?? 390;
|
|
173
170
|
const h = board?.h ?? 844;
|
|
174
|
-
|
|
175
|
-
const page = await
|
|
171
|
+
// Long side ≈ px device pixels, so large boards stay sharp when zoomed out on a 2× display
|
|
172
|
+
const page = await newPage({ viewport: { width: w, height: h }, deviceScaleFactor: Math.min(2, px / Math.max(w, h)) });
|
|
176
173
|
try {
|
|
177
174
|
await page.goto(`http://127.0.0.1:${req.socket.localPort}/screens/${encodeURI(f)}`, { waitUntil: "load", timeout: 15000 });
|
|
178
175
|
await page.waitForTimeout(150);
|
|
179
|
-
const b = await page.screenshot({ type: "jpeg", quality:
|
|
180
|
-
// Remove
|
|
181
|
-
for (const n of await fs.readdir(dir)) if (n.startsWith(
|
|
176
|
+
const b = await page.screenshot({ type: "jpeg", quality: 80 });
|
|
177
|
+
// Remove thumbnails of older versions (other sizes of this version stay)
|
|
178
|
+
for (const n of await fs.readdir(dir)) if (n.startsWith(base + ".") && !n.startsWith(stamp)) await fs.rm(path.join(dir, n), { force: true });
|
|
182
179
|
await fs.writeFile(out, b);
|
|
183
180
|
return b;
|
|
184
181
|
} finally {
|
|
@@ -191,6 +188,7 @@ export const extraRoutes = [
|
|
|
191
188
|
},
|
|
192
189
|
],
|
|
193
190
|
...snapshotRoutes(),
|
|
191
|
+
...exportRoutes(),
|
|
194
192
|
// Assets: list and upload docs/design/assets/ (images, fonts). Screens reference them as ../assets/<name>
|
|
195
193
|
[
|
|
196
194
|
"GET",
|
|
@@ -352,7 +350,7 @@ export const extraRoutes = [
|
|
|
352
350
|
await readScreen(ctx, b.file);
|
|
353
351
|
const port = Number(req.socket.localPort);
|
|
354
352
|
const out = await screenshot(ctx, port, b.file, b.path || "");
|
|
355
|
-
sendJson(res, 200, { path: out });
|
|
353
|
+
sendJson(res, 200, { path: out, relPath: toPosix(path.relative(rootOf(ctx.dir), out)) });
|
|
356
354
|
},
|
|
357
355
|
],
|
|
358
356
|
[
|
|
@@ -383,8 +381,9 @@ export async function attach(app) {
|
|
|
383
381
|
const stop = watchDesign(app.ctx);
|
|
384
382
|
const close = app.close;
|
|
385
383
|
app.close = async () => {
|
|
384
|
+
chat.close(); // open permission requests are denied, so a waiting agent does not hang
|
|
386
385
|
await stop();
|
|
387
|
-
|
|
386
|
+
await closeBrowser();
|
|
388
387
|
await close();
|
|
389
388
|
};
|
|
390
389
|
}
|
package/server/runs.mjs
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// AI-generated with Claude Code, 2026-11-11, reviewed by Hyun Park
|
|
2
|
+
// Undo and redo of one whole in-app AI run (and of the steps behind a board tag), and read-only access to a run's pre-run copy (Compare, restore after a restart).
|
|
3
|
+
// A run on top of the history is a plain undo/redo; an older run takes back only its own files, and asks before overwriting later changes.
|
|
4
|
+
import fs from "node:fs/promises";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
|
|
7
|
+
import { formatBoard } from "./boardFormat.mjs";
|
|
8
|
+
import { isTrackedRel } from "./copies.mjs";
|
|
9
|
+
import { toPosix, writeAtomic } from "./fsutil.mjs";
|
|
10
|
+
|
|
11
|
+
const read = (p) => fs.readFile(p, "utf8").catch(() => null);
|
|
12
|
+
const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
|
|
13
|
+
const parse = (t) => {
|
|
14
|
+
try {
|
|
15
|
+
return t ? JSON.parse(t) : {};
|
|
16
|
+
} catch {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/** A run's undo steps → one change per file, from its first before to its last after */
|
|
22
|
+
export function mergeSteps(steps) {
|
|
23
|
+
const m = new Map();
|
|
24
|
+
for (const s of steps)
|
|
25
|
+
for (const c of s.changes) {
|
|
26
|
+
const prev = m.get(c.path);
|
|
27
|
+
if (prev) prev.after = c.after;
|
|
28
|
+
else m.set(c.path, { path: c.path, before: c.before, after: c.after });
|
|
29
|
+
}
|
|
30
|
+
return [...m.values()].filter((c) => c.before !== c.after);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Boards a run touched, relative to screens/: changed, added (did not exist before) or removed */
|
|
34
|
+
export function runBoards(changes, screensDir) {
|
|
35
|
+
const out = [];
|
|
36
|
+
for (const c of changes) {
|
|
37
|
+
const rel = toPosix(path.relative(screensDir, c.path));
|
|
38
|
+
if (!c.path.endsWith(".html") || rel.startsWith("..")) continue;
|
|
39
|
+
out.push({ file: rel, kind: c.before == null ? "added" : c.after == null ? "removed" : "changed" });
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* board.json: applies the from → to difference of boards/notes entries (and pages/title) onto the current file, key by key,
|
|
46
|
+
* so moving another board since does not block the undo. conflicts: entries that changed since (board file names, note ids)
|
|
47
|
+
*/
|
|
48
|
+
export function mergeBoardJson(curText, fromText, toText, force = false) {
|
|
49
|
+
const cur = parse(curText);
|
|
50
|
+
const from = parse(fromText);
|
|
51
|
+
const to = parse(toText);
|
|
52
|
+
if (!cur || !from || !to) return { text: force ? toText : curText, conflicts: force ? [] : ["board.json"] };
|
|
53
|
+
const conflicts = [];
|
|
54
|
+
for (const sec of ["boards", "notes"]) {
|
|
55
|
+
const c = { ...(cur[sec] ?? {}) };
|
|
56
|
+
for (const k of new Set([...Object.keys(from[sec] ?? {}), ...Object.keys(to[sec] ?? {})])) {
|
|
57
|
+
const a = from[sec]?.[k];
|
|
58
|
+
const b = to[sec]?.[k];
|
|
59
|
+
if (same(a, b) || same(c[k], b)) continue;
|
|
60
|
+
if (!same(c[k], a) && !force) {
|
|
61
|
+
conflicts.push(k);
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (b === undefined) delete c[k];
|
|
65
|
+
else c[k] = b;
|
|
66
|
+
}
|
|
67
|
+
cur[sec] = c;
|
|
68
|
+
}
|
|
69
|
+
for (const key of ["pages", "title"]) {
|
|
70
|
+
if (same(from[key], to[key]) || same(cur[key], to[key])) continue;
|
|
71
|
+
if (!same(cur[key], from[key]) && !force) conflicts.push(key);
|
|
72
|
+
else cur[key] = to[key];
|
|
73
|
+
}
|
|
74
|
+
const order = (Array.isArray(cur.order) ? cur.order : []).filter((f) => cur.boards?.[f]);
|
|
75
|
+
for (const f of Object.keys(cur.boards ?? {})) if (!order.includes(f)) order.push(f);
|
|
76
|
+
cur.order = order;
|
|
77
|
+
return { text: formatBoard(cur), conflicts };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Applies a run's changes backwards (undo) or forwards (redo) as one new history step. Files changed since are conflicts:
|
|
82
|
+
* without mode the call writes nothing and returns them; mode "rest" skips them, "all" overwrites them.
|
|
83
|
+
*/
|
|
84
|
+
export async function applyRunChanges(ctx, changes, dir, { mode, label, mark }) {
|
|
85
|
+
const plan = [];
|
|
86
|
+
const conflicts = [];
|
|
87
|
+
for (const c of changes) {
|
|
88
|
+
const from = dir === "undo" ? c.after : c.before;
|
|
89
|
+
const to = dir === "undo" ? c.before : c.after;
|
|
90
|
+
const now = await read(c.path);
|
|
91
|
+
if (c.path === ctx.store.boardPath) {
|
|
92
|
+
const m = mergeBoardJson(now, from, to, mode === "all");
|
|
93
|
+
if (m.conflicts.length && mode !== "rest") conflicts.push(...m.conflicts.map((k) => ({ file: k, board: true })));
|
|
94
|
+
if (m.text !== now && (!m.conflicts.length || mode)) plan.push({ path: c.path, before: now, after: m.text });
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
if (now === to) continue;
|
|
98
|
+
if (now !== from) {
|
|
99
|
+
conflicts.push({ file: toPosix(path.relative(ctx.store.screensDir, c.path)) });
|
|
100
|
+
if (mode !== "all") continue;
|
|
101
|
+
}
|
|
102
|
+
plan.push({ path: c.path, before: now, after: to });
|
|
103
|
+
}
|
|
104
|
+
if (conflicts.length && !mode) return { conflicts };
|
|
105
|
+
for (const c of plan) {
|
|
106
|
+
if (c.after == null) await fs.rm(c.path, { force: true });
|
|
107
|
+
else {
|
|
108
|
+
await fs.mkdir(path.dirname(c.path), { recursive: true });
|
|
109
|
+
await writeAtomic(c.path, c.after);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
ctx.history.push(label, plan, mark);
|
|
113
|
+
await dropMissingAutoPlaced(ctx);
|
|
114
|
+
return { changed: plan.length, skipped: mode === "rest" ? conflicts.map((c) => c.file) : [] };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Undo of a set of changes that may be older than the newest step (a chat run, the steps behind a board tag): onTop plain history
|
|
119
|
+
* undos when they are the newest steps, else only their own files as one new step, with the same conflict rule as applyRunChanges
|
|
120
|
+
*/
|
|
121
|
+
export async function undoChanges(ctx, { onTop = 0, changes, mode, label, mark }) {
|
|
122
|
+
if (!onTop) return applyRunChanges(ctx, changes, "undo", { mode: ["rest", "all"].includes(mode) ? mode : undefined, label, mark });
|
|
123
|
+
for (let i = 0; i < onTop; i++) await ctx.history.undo();
|
|
124
|
+
await dropMissingAutoPlaced(ctx);
|
|
125
|
+
return { changed: onTop, skipped: [] };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Entries auto-placed for files that are gone again (an undone run's new screens): placement is not an undo step, so neither is this */
|
|
129
|
+
export async function dropMissingAutoPlaced(ctx) {
|
|
130
|
+
const board = await ctx.store.readBoard();
|
|
131
|
+
const files = new Set(await ctx.store.listScreenFiles());
|
|
132
|
+
const gone = Object.keys(board.boards).filter((f) => board.boards[f].autoPlaced && !files.has(f));
|
|
133
|
+
if (!gone.length) return;
|
|
134
|
+
for (const f of gone) delete board.boards[f];
|
|
135
|
+
board.order = board.order.filter((f) => !gone.includes(f));
|
|
136
|
+
await ctx.store.writeBoard(board);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/* ---------- The pre-run copy in .easel/runs/<id>/ ---------- */
|
|
140
|
+
const validId = (id) => /^r[0-9a-z]+$/.test(String(id ?? ""));
|
|
141
|
+
const copyDir = (dir, id) => path.join(dir, ".easel", "runs", id);
|
|
142
|
+
|
|
143
|
+
/** Saved time and label of a run's copy; null when it is gone (pruned) or the id is not a run id */
|
|
144
|
+
export async function runCopyInfo(dir, id) {
|
|
145
|
+
if (!validId(id)) return null;
|
|
146
|
+
const meta = parse(await read(path.join(copyDir(dir, id), "run.json")));
|
|
147
|
+
return meta && typeof meta.at === "string" ? { at: meta.at, label: typeof meta.label === "string" ? meta.label : "" } : null;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* A screen as it was before run id: f is screens/<…>.html (validated like the revert, and listed in the copy's run.json).
|
|
152
|
+
* null when the id, the name or the copy is not valid
|
|
153
|
+
*/
|
|
154
|
+
export async function readRunFile(dir, id, f) {
|
|
155
|
+
if (!validId(id) || !isTrackedRel(f) || !String(f).startsWith("screens/")) return null;
|
|
156
|
+
const src = copyDir(dir, id);
|
|
157
|
+
const meta = parse(await read(path.join(src, "run.json")));
|
|
158
|
+
if (!meta || !Array.isArray(meta.files) || !meta.files.includes(f)) return null;
|
|
159
|
+
return read(path.join(src, f));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** <base> so a copy served from the API resolves ../assets and links like the live screen at /screens/<file> */
|
|
163
|
+
export function withBase(html, file) {
|
|
164
|
+
const tag = `<base href="/screens/${file.split("/").map(encodeURIComponent).join("/")}">`;
|
|
165
|
+
const m = /<head[^>]*>/i.exec(html) ?? /<html[^>]*>/i.exec(html) ?? /<!doctype[^>]*>/i.exec(html);
|
|
166
|
+
return m ? html.slice(0, m.index + m[0].length) + tag + html.slice(m.index + m[0].length) : tag + html;
|
|
167
|
+
}
|
package/server/snapshot.mjs
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
// AI-generated with Claude Code, 2026-10-09, reviewed by Hyun Park
|
|
2
2
|
// git snapshots instead of versions: commits only the design folder (author from git config) and lists recent snapshots.
|
|
3
3
|
// No restore (use git directly). Commits only the design folder path so other staged files are not mixed in.
|
|
4
|
+
// Outside a git repository a snapshot is a folder copy in <design dir>/.easel/snapshots/ (kind "copy").
|
|
4
5
|
import { spawn } from "node:child_process";
|
|
5
6
|
import fs from "node:fs/promises";
|
|
6
7
|
import path from "node:path";
|
|
7
8
|
|
|
9
|
+
import { copySnapshot, listSnapshotCopies } from "./copies.mjs";
|
|
8
10
|
import { readBody, sendJson } from "./index.mjs";
|
|
9
11
|
|
|
10
12
|
export function git(cwd, args) {
|
|
@@ -39,19 +41,25 @@ export function snapshotRoutes() {
|
|
|
39
41
|
"/api/snapshots",
|
|
40
42
|
async (req, res, url, ctx) => {
|
|
41
43
|
const root = await repoOf(ctx.dir);
|
|
42
|
-
|
|
44
|
+
const copies = await listSnapshotCopies(ctx.dir);
|
|
45
|
+
if (!root) return sendJson(res, 200, { git: false, snapshots: copies.slice(0, 15), changed: 0 });
|
|
43
46
|
const rel = path.relative(root, await fs.realpath(ctx.dir)) || "."; // resolve links like /var → /private/var before comparing
|
|
44
|
-
const log = await git(root, ["log", "-n", "15", "--format=%h%x09%an%x09%ar%x09%s", "--", rel]);
|
|
47
|
+
const log = await git(root, ["log", "-n", "15", "--format=%h%x09%an%x09%ar%x09%s%x09%aI", "--", rel]);
|
|
45
48
|
const st = await git(root, ["status", "--porcelain", "--", rel]);
|
|
46
49
|
const branch = (await git(root, ["branch", "--show-current"])).out.trim();
|
|
47
50
|
sendJson(res, 200, {
|
|
48
51
|
git: true,
|
|
49
52
|
branch,
|
|
50
53
|
changed: st.out.split("\n").filter(Boolean).length,
|
|
51
|
-
snapshots:
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
54
|
+
snapshots: [
|
|
55
|
+
...log.out.split("\n").filter(Boolean).map((l) => {
|
|
56
|
+
const [hash, author, when, subject, at] = l.split("\t");
|
|
57
|
+
return { hash, author, when, subject, at, kind: "git" };
|
|
58
|
+
}),
|
|
59
|
+
...copies,
|
|
60
|
+
]
|
|
61
|
+
.sort((a, b) => new Date(b.at) - new Date(a.at))
|
|
62
|
+
.slice(0, 15),
|
|
55
63
|
});
|
|
56
64
|
},
|
|
57
65
|
],
|
|
@@ -61,9 +69,13 @@ export function snapshotRoutes() {
|
|
|
61
69
|
async (req, res, url, ctx) => {
|
|
62
70
|
const b = await readBody(req);
|
|
63
71
|
const root = await repoOf(ctx.dir);
|
|
64
|
-
if (!root) return sendJson(res, 400, { error: "The design folder is not inside a git repository" });
|
|
65
|
-
const rel = path.relative(root, await fs.realpath(ctx.dir)) || "."; // resolve links like /var → /private/var before comparing
|
|
66
72
|
const msg = String(b.message ?? "").trim() || `design: snapshot ${new Date().toLocaleString("en-US")}`;
|
|
73
|
+
if (!root) {
|
|
74
|
+
const me = await git(ctx.dir, ["config", "user.name"]);
|
|
75
|
+
const { name } = await copySnapshot(ctx.dir, { message: msg, author: me.code === 0 ? me.out.trim() : process.env.USER ?? "" });
|
|
76
|
+
return sendJson(res, 200, { ok: true, kind: "copy", hash: name, path: `.easel/snapshots/${name}`, message: msg });
|
|
77
|
+
}
|
|
78
|
+
const rel = path.relative(root, await fs.realpath(ctx.dir)) || "."; // resolve links like /var → /private/var before comparing
|
|
67
79
|
const add = await git(root, ["add", "--", rel]);
|
|
68
80
|
if (add.code !== 0) return sendJson(res, 500, { error: add.err.trim() || "git add failed" });
|
|
69
81
|
const diff = await git(root, ["diff", "--cached", "--quiet", "--", rel]);
|
|
@@ -72,7 +84,7 @@ export function snapshotRoutes() {
|
|
|
72
84
|
const c = await git(root, ["commit", "-m", msg, "--", rel]);
|
|
73
85
|
if (c.code !== 0) return sendJson(res, 500, { error: (c.err || c.out).trim().split("\n").slice(-3).join("\n") || "git commit failed" });
|
|
74
86
|
const hash = (await git(root, ["rev-parse", "--short", "HEAD"])).out.trim();
|
|
75
|
-
sendJson(res, 200, { ok: true, hash, message: msg });
|
|
87
|
+
sendJson(res, 200, { ok: true, kind: "git", hash, message: msg });
|
|
76
88
|
},
|
|
77
89
|
],
|
|
78
90
|
];
|
package/server/tokens.mjs
CHANGED
|
@@ -8,6 +8,9 @@ import { writeAtomic } from "./fsutil.mjs";
|
|
|
8
8
|
import { elementChildren, findBody, parseHtml } from "./html.mjs";
|
|
9
9
|
import { readBody, sendJson } from "./index.mjs";
|
|
10
10
|
|
|
11
|
+
/** System font stack only: no web font download, nothing language- or brand-specific (the starter templates use it too) */
|
|
12
|
+
export const SYSTEM_FONT = 'system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
|
|
13
|
+
|
|
11
14
|
export const DEFAULT_TOKENS = {
|
|
12
15
|
version: 1,
|
|
13
16
|
active: "Default",
|
|
@@ -27,10 +30,16 @@ export const DEFAULT_TOKENS = {
|
|
|
27
30
|
fontWeights: [400, 600, 700],
|
|
28
31
|
radii: [4, 8, 16, 999],
|
|
29
32
|
spacing: [0, 4, 8, 12, 16, 20, 24, 32, 40],
|
|
30
|
-
fontFamily:
|
|
33
|
+
fontFamily: SYSTEM_FONT,
|
|
31
34
|
minTarget: 48,
|
|
32
35
|
};
|
|
33
36
|
|
|
37
|
+
/** Said to agents (prompt, check_tokens, get_tokens) when the design folder has no tokens.json */
|
|
38
|
+
export const NO_TOKENS_NOTE = "No design tokens are registered; keep to the styles already in the file.";
|
|
39
|
+
|
|
40
|
+
/** What agents get from get_tokens: the tokens when registered, otherwise only that there are none (no default palette) */
|
|
41
|
+
export const tokensForAgent = (tk) => (tk.registered ? tk : { registered: false, note: NO_TOKENS_NOTE });
|
|
42
|
+
|
|
34
43
|
export async function readTokens(dir) {
|
|
35
44
|
try {
|
|
36
45
|
const t = JSON.parse(await fs.readFile(path.join(dir, "tokens.json"), "utf8"));
|
|
@@ -119,7 +128,8 @@ export function lintHtml(html, tokens) {
|
|
|
119
128
|
|
|
120
129
|
export function tokenRoutes() {
|
|
121
130
|
return [
|
|
122
|
-
|
|
131
|
+
// The app's Tokens tab gets the defaults as a starter; agents (?agent=1, MCP get_tokens) get no palette until tokens.json exists
|
|
132
|
+
["GET", "/api/tokens", async (req, res, url, ctx) => sendJson(res, 200, url.searchParams.get("agent") ? tokensForAgent(await readTokens(ctx.dir)) : await readTokens(ctx.dir))],
|
|
123
133
|
[
|
|
124
134
|
"PUT",
|
|
125
135
|
"/api/tokens",
|
|
@@ -145,13 +155,15 @@ export function tokenRoutes() {
|
|
|
145
155
|
"/api/lint",
|
|
146
156
|
async (req, res, url, ctx) => {
|
|
147
157
|
const tokens = await readTokens(ctx.dir);
|
|
158
|
+
// No tokens.json: nothing to check against (the defaults are only a starter for the Tokens tab)
|
|
159
|
+
if (!tokens.registered) return sendJson(res, 200, { registered: false, note: NO_TOKENS_NOTE, files: {} });
|
|
148
160
|
const files = url.searchParams.get("f") ? [url.searchParams.get("f")] : await ctx.store.listScreenFiles();
|
|
149
161
|
const result = {};
|
|
150
162
|
for (const f of files) {
|
|
151
163
|
const html = await fs.readFile(path.join(ctx.store.screensDir, f), "utf8").catch(() => null);
|
|
152
164
|
if (html != null) result[f] = lintHtml(html, tokens);
|
|
153
165
|
}
|
|
154
|
-
sendJson(res, 200, { theme: tokens.active, files: result });
|
|
166
|
+
sendJson(res, 200, { registered: true, theme: tokens.active, files: result });
|
|
155
167
|
},
|
|
156
168
|
],
|
|
157
169
|
];
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// AI-generated with Claude Code, 2026-11-15, reviewed by Hyun Park
|
|
2
|
+
// New-version notice: npx keeps the copy it cached, so nothing tells people a newer Easel exists. Once a day the canvas asks
|
|
3
|
+
// the npm registry for easel-canvas's latest version (only that: one GET, nothing about the project) and, when it is newer,
|
|
4
|
+
// says which command updates this install. Silent whenever it cannot ask: EASEL_NO_UPDATE_CHECK=1, CI, a source checkout
|
|
5
|
+
// (git clone or submodule: updated with git), offline, a slow or broken registry.
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
|
|
9
|
+
import { TOOL_ROOT } from "./args.mjs";
|
|
10
|
+
import { easelHome } from "./registry.mjs";
|
|
11
|
+
|
|
12
|
+
const DAY = 24 * 60 * 60 * 1000;
|
|
13
|
+
const REGISTRY = "https://registry.npmjs.org/easel-canvas/latest";
|
|
14
|
+
|
|
15
|
+
/** a > b for x.y.z versions; a pre-release (0.3.0-beta.1) is older than its release and never offered */
|
|
16
|
+
export function isNewer(a, b) {
|
|
17
|
+
const parse = (v) => String(v).replace(/^v/, "").split("-")[0].split(".").map((n) => parseInt(n, 10) || 0);
|
|
18
|
+
if (/-/.test(String(a))) return false;
|
|
19
|
+
const [x, y] = [parse(a), parse(b)];
|
|
20
|
+
for (let i = 0; i < 3; i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) > (y[i] ?? 0);
|
|
21
|
+
return /-/.test(String(b)); // 0.3.0 is newer than 0.3.0-beta.1
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The command that updates the copy running from root: npx's cache, a project's node_modules, or a global install */
|
|
25
|
+
export function updateCommand(root = TOOL_ROOT) {
|
|
26
|
+
const p = root.split(path.sep).join("/");
|
|
27
|
+
if (p.includes("/_npx/")) return "npx easel-canvas@latest";
|
|
28
|
+
if (/\/node_modules\/easel-canvas\/?$/.test(p)) {
|
|
29
|
+
const global = /\/lib\/node_modules\/easel-canvas\/?$/.test(p) || /\/npm\/node_modules\/easel-canvas\/?$/i.test(p);
|
|
30
|
+
return global ? "npm i -g easel-canvas@latest" : "npm i -D easel-canvas@latest";
|
|
31
|
+
}
|
|
32
|
+
return "npx easel-canvas@latest";
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Resolves to { current, latest, command } when the registry has a newer version, else null; never throws.
|
|
37
|
+
* The answer is kept a day in <EASEL_HOME>/update.json. EASEL_UPDATE_URL points the check elsewhere (tests, trying it out
|
|
38
|
+
* from a source checkout).
|
|
39
|
+
*/
|
|
40
|
+
export async function checkUpdate({ current, env = process.env, root = TOOL_ROOT, home = easelHome(env), now = Date.now(), fetchImpl = fetch } = {}) {
|
|
41
|
+
try {
|
|
42
|
+
if (env.EASEL_NO_UPDATE_CHECK === "1" || env.CI) return null;
|
|
43
|
+
const url = env.EASEL_UPDATE_URL || REGISTRY;
|
|
44
|
+
if (!env.EASEL_UPDATE_URL && existsSync(path.join(root, "app"))) return null;
|
|
45
|
+
const file = path.join(home, "update.json");
|
|
46
|
+
let latest = null;
|
|
47
|
+
try {
|
|
48
|
+
const c = JSON.parse(readFileSync(file, "utf8"));
|
|
49
|
+
if (c.url === url && now - c.checkedAt < DAY) latest = c.latest;
|
|
50
|
+
} catch {}
|
|
51
|
+
if (!latest) {
|
|
52
|
+
const r = await fetchImpl(url, { signal: AbortSignal.timeout(2000), headers: { accept: "application/json" } });
|
|
53
|
+
if (!r.ok) return null;
|
|
54
|
+
latest = (await r.json())?.version;
|
|
55
|
+
if (typeof latest !== "string") return null;
|
|
56
|
+
mkdirSync(home, { recursive: true });
|
|
57
|
+
writeFileSync(file, JSON.stringify({ url, checkedAt: now, latest }));
|
|
58
|
+
}
|
|
59
|
+
return isNewer(latest, current) ? { current, latest, command: updateCommand(root) } : null;
|
|
60
|
+
} catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|