easel-canvas 0.3.0 → 0.5.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 +39 -13
- package/bin/mcp.mjs +90 -6
- package/bin/server.mjs +48 -15
- package/dist/assets/index-0pl9ILre.css +1 -0
- package/dist/assets/index-BRuM-YIO.js +75 -0
- package/dist/index.html +2 -2
- package/dist/viewer/viewer.css +1 -1
- package/dist/viewer/viewer.js +19 -19
- package/package.json +4 -2
- package/server/activity.mjs +17 -2
- package/server/boards.mjs +15 -8
- package/server/chat.mjs +2 -0
- package/server/edit.mjs +27 -0
- package/server/export.mjs +24 -6
- package/server/index.mjs +72 -7
- package/server/occupancy.mjs +14 -3
- package/server/place.mjs +11 -0
- package/server/requests.mjs +562 -0
- package/server/routes.mjs +51 -8
- package/server/selfupdate.mjs +98 -0
- package/server/stamps.mjs +134 -0
- package/server/up.mjs +1 -1
- package/server/update.mjs +80 -18
- package/server/watch.mjs +25 -7
- package/dist/assets/index-B7XvZ2rQ.js +0 -70
- package/dist/assets/index-CLVWE3wq.css +0 -1
package/server/routes.mjs
CHANGED
|
@@ -16,6 +16,7 @@ import { easelDir, rootOf, toPosix, writeAtomic } from "./fsutil.mjs";
|
|
|
16
16
|
import { inspect, outline } from "./html.mjs";
|
|
17
17
|
import { contentHash, livePatch } from "./livePatch.mjs";
|
|
18
18
|
import { readBody, safeJoin, sendJson } from "./index.mjs";
|
|
19
|
+
import { requestRoutes, undoState } from "./requests.mjs";
|
|
19
20
|
import { watchDesign } from "./watch.mjs";
|
|
20
21
|
|
|
21
22
|
const OUTER_LIMIT = 4096;
|
|
@@ -97,6 +98,14 @@ export function createThumbQueue(limit = 2) {
|
|
|
97
98
|
}
|
|
98
99
|
const thumbQueue = createThumbQueue(2);
|
|
99
100
|
|
|
101
|
+
/** The newest thumbnail of a board on disk (any version, this size first), for when a new one cannot be made */
|
|
102
|
+
async function previousThumb(dir, base, px) {
|
|
103
|
+
const names = (await fs.readdir(dir).catch(() => [])).filter((n) => n.startsWith(base + ".") && n.endsWith(".jpg"));
|
|
104
|
+
const dated = await Promise.all(names.map(async (n) => ({ n, t: (await fs.stat(path.join(dir, n)).catch(() => null))?.mtimeMs ?? 0, same: n.endsWith(`.${px}.jpg`) })));
|
|
105
|
+
dated.sort((a, b) => b.same - a.same || b.t - a.t);
|
|
106
|
+
return dated.length ? fs.readFile(path.join(dir, dated[0].n)).catch(() => null) : null;
|
|
107
|
+
}
|
|
108
|
+
|
|
100
109
|
export async function screenshot(ctx, port, file, elPath) {
|
|
101
110
|
const board = (await ctx.store.readBoard()).boards[file];
|
|
102
111
|
return withPage({ viewport: { width: board?.w ?? 390, height: board?.h ?? 844 }, deviceScaleFactor: 2 }, async (page) => {
|
|
@@ -142,7 +151,9 @@ export const extraRoutes = [
|
|
|
142
151
|
}
|
|
143
152
|
if (next === html) return sendJson(res, 200, { ok: true, changed: false, ...fork });
|
|
144
153
|
await writeScreen(ctx, p, next);
|
|
145
|
-
|
|
154
|
+
// What a style step changed (its human name says "colour", "fill", "radius"…): the property, or a batch's when they agree
|
|
155
|
+
const props = b.op === "setStyle" ? [b.prop] : b.op === "batch" && Array.isArray(b.ops) ? [...new Set(b.ops.filter((o) => o.op === "setStyle").map((o) => o.prop))] : [];
|
|
156
|
+
ctx.history.push(`${to.file} ${b.op}`, [{ path: p, before: html, after: next }], props.length === 1 && props[0] ? { prop: props[0] } : {});
|
|
146
157
|
ctx.broadcast({ type: "history-changed" });
|
|
147
158
|
// base/hash: the file's content hash before and after; live: the DOM change that turns a board showing base into one showing
|
|
148
159
|
// hash, when that is proven (server/livePatch.mjs). Never for a fork: the caller's board is not the file written
|
|
@@ -164,8 +175,11 @@ export const extraRoutes = [
|
|
|
164
175
|
...forkRoutes(),
|
|
165
176
|
...activityRoutes(),
|
|
166
177
|
...chat.routes,
|
|
178
|
+
...requestRoutes({ chatState: chat.state, getSelection: () => selection }),
|
|
167
179
|
...tokenRoutes(),
|
|
168
|
-
// Zoomed-out thumbnails: small images shown below 25% instead of empty frames. Stored per
|
|
180
|
+
// Zoomed-out thumbnails: small images shown below 25% instead of empty frames. Stored per render stamp (server/stamps.mjs: the
|
|
181
|
+
// board's HTML and every local file it loads) in docs/design/.thumbs/ (gitignored). The app asks with the stamp it was told
|
|
182
|
+
// (s=), so that URL is cached for good; without it, or with a stamp that is no longer current, the answer is revalidated
|
|
169
183
|
[
|
|
170
184
|
"GET",
|
|
171
185
|
"/api/thumb",
|
|
@@ -173,17 +187,19 @@ export const extraRoutes = [
|
|
|
173
187
|
const f = url.searchParams.get("f") ?? "";
|
|
174
188
|
const src = safeJoin(ctx.store.screensDir, f);
|
|
175
189
|
const st = src && (await fs.stat(src).catch(() => null));
|
|
176
|
-
if (!st) return sendJson(res, 404, { error: "File not found" });
|
|
190
|
+
if (!st?.isFile()) return sendJson(res, 404, { error: "File not found" });
|
|
177
191
|
const px = thumbPx(url.searchParams.get("px"));
|
|
178
192
|
const dir = path.join(ctx.dir, ".thumbs");
|
|
179
193
|
const base = f.replace(/[\\/]/g, "_");
|
|
180
|
-
const
|
|
194
|
+
const cur = (await ctx.stamps.stamp(f)) ?? `m${Math.round(st.mtimeMs)}`;
|
|
195
|
+
const stamp = `${base}.${cur}.`;
|
|
181
196
|
const out = path.join(dir, `${stamp}${px}.jpg`);
|
|
182
197
|
// Read the port now: a job that waits in the queue runs after its request may have closed, and a closed socket has no localPort
|
|
183
198
|
const port = req.socket.localPort;
|
|
184
199
|
let gone = false;
|
|
185
200
|
res.on("close", () => (gone = true));
|
|
186
201
|
let buf = await fs.readFile(out).catch(() => null);
|
|
202
|
+
let fresh = true;
|
|
187
203
|
if (!buf) {
|
|
188
204
|
buf = await thumbQueue.push(async () => {
|
|
189
205
|
await fs.mkdir(dir, { recursive: true });
|
|
@@ -196,18 +212,23 @@ export const extraRoutes = [
|
|
|
196
212
|
await page.goto(`http://127.0.0.1:${port}/screens/${encodeURI(f)}`, { waitUntil: "load", timeout: 15000 });
|
|
197
213
|
await page.waitForTimeout(150);
|
|
198
214
|
const b = await page.screenshot({ type: "jpeg", quality: 80 });
|
|
199
|
-
// Remove thumbnails of older versions (other sizes of this version stay)
|
|
215
|
+
// Remove thumbnails of older versions (other sizes of this version stay); only once the new one is made
|
|
200
216
|
for (const n of await fs.readdir(dir)) if (n.startsWith(base + ".") && !n.startsWith(stamp)) await fs.rm(path.join(dir, n), { force: true });
|
|
201
217
|
await fs.writeFile(out, b);
|
|
202
218
|
return b;
|
|
203
219
|
});
|
|
204
|
-
}, () => gone).catch((e) => {
|
|
220
|
+
}, () => gone).catch(async (e) => {
|
|
205
221
|
if (e.dropped) return null;
|
|
206
|
-
|
|
222
|
+
// The render failed: the last picture of this board, if there is one, beats no picture (and is asked for again next time)
|
|
223
|
+
const old = await previousThumb(dir, base, px);
|
|
224
|
+
if (!old) throw e;
|
|
225
|
+
fresh = false;
|
|
226
|
+
return old;
|
|
207
227
|
});
|
|
208
228
|
if (!buf) return; // nobody is waiting for it any more
|
|
209
229
|
}
|
|
210
|
-
|
|
230
|
+
const cache = fresh && url.searchParams.get("s") === cur ? "max-age=31536000, immutable" : "no-cache";
|
|
231
|
+
res.writeHead(200, { "Content-Type": "image/jpeg", "Content-Length": buf.length, "Cache-Control": cache });
|
|
211
232
|
res.end(buf);
|
|
212
233
|
},
|
|
213
234
|
],
|
|
@@ -334,6 +355,10 @@ export const extraRoutes = [
|
|
|
334
355
|
const f = url.searchParams.get("file");
|
|
335
356
|
if (f) list = list.filter((c) => c.file === f);
|
|
336
357
|
if (url.searchParams.get("unresolved") === "1") list = list.filter((c) => !c.resolved);
|
|
358
|
+
// for_agent=1: only comments marked For AI (requests for the agent the person is talking to)
|
|
359
|
+
if (url.searchParams.get("for_agent") === "1") list = list.filter((c) => c.forAgent);
|
|
360
|
+
// A done request says whether its own undo steps can still be undone (not stored: read from this server's history)
|
|
361
|
+
list = list.map((c) => (c.request?.state === "done" && c.request.steps?.length ? { ...c, request: { ...c.request, undo: undoState(ctx.history, c.request.steps) } } : c));
|
|
337
362
|
sendJson(res, 200, { comments: list });
|
|
338
363
|
},
|
|
339
364
|
],
|
|
@@ -354,6 +379,23 @@ export const extraRoutes = [
|
|
|
354
379
|
ctx.broadcast({ type: "comments-changed" });
|
|
355
380
|
return sendJson(res, 200, { comment: c, reply: r });
|
|
356
381
|
}
|
|
382
|
+
if (b.action === "edit") {
|
|
383
|
+
const c = list.find((x) => x.id === b.id);
|
|
384
|
+
if (!c) return sendJson(res, 404, { error: "Comment not found" });
|
|
385
|
+
if (!String(b.text ?? "").trim()) return sendJson(res, 400, { error: "text is required" });
|
|
386
|
+
c.text = String(b.text).trim();
|
|
387
|
+
await writeComments(ctx, list);
|
|
388
|
+
ctx.broadcast({ type: "comments-changed" });
|
|
389
|
+
return sendJson(res, 200, { comment: c });
|
|
390
|
+
}
|
|
391
|
+
if (b.action === "delete") {
|
|
392
|
+
const i = list.findIndex((x) => x.id === b.id);
|
|
393
|
+
if (i < 0) return sendJson(res, 404, { error: "Comment not found" });
|
|
394
|
+
const [c] = list.splice(i, 1);
|
|
395
|
+
await writeComments(ctx, list);
|
|
396
|
+
ctx.broadcast({ type: "comments-changed" });
|
|
397
|
+
return sendJson(res, 200, { comment: c });
|
|
398
|
+
}
|
|
357
399
|
if (b.action === "resolve") {
|
|
358
400
|
const c = list.find((x) => x.id === b.id);
|
|
359
401
|
if (!c) return sendJson(res, 404, { error: "Comment not found" });
|
|
@@ -417,6 +459,7 @@ export const extraRoutes = [
|
|
|
417
459
|
|
|
418
460
|
/** Things to attach after the server starts (file watching etc.) */
|
|
419
461
|
export async function attach(app) {
|
|
462
|
+
app.ctx.busy = chat.busy; // the one-click update waits while an Easel AI run is going
|
|
420
463
|
const stop = watchDesign(app.ctx);
|
|
421
464
|
const close = app.close;
|
|
422
465
|
app.close = async () => {
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// AI-generated with Claude Code, 2026-12-03, reviewed by Hyun Park
|
|
2
|
+
// One-click update, where Easel can replace itself (an npx cache or a global install; see update.mjs installKind): npm installs
|
|
3
|
+
// easel-canvas@<x.y.z> into the prefix this copy runs from, the version on disk is checked, and only then is the canvas handed over to
|
|
4
|
+
// the new files (bin/server.mjs: the old server closes its port, starts the new one on the same port and folder, and goes back to
|
|
5
|
+
// listening if the new one does not answer). Nothing from the registry reaches a shell: the version must be x.y.z and npm is spawned
|
|
6
|
+
// with an argument array. EASEL_UPDATE_INSTALLER (a JSON argument array, as DESIGN_CANVAS_AGENT_CMD) stands in for npm in tests.
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
|
|
11
|
+
import { TOOL_ROOT } from "./args.mjs";
|
|
12
|
+
import { installKind, validVersion } from "./update.mjs";
|
|
13
|
+
|
|
14
|
+
/** How to run npm without a shell: node + npm-cli.js beside this node when it is there (also on Windows, where npm is a .cmd), else npm */
|
|
15
|
+
export function npmCommand({ execPath = process.execPath, exists = existsSync, platform = process.platform } = {}) {
|
|
16
|
+
const dir = path.dirname(execPath);
|
|
17
|
+
for (const cli of [path.join(dir, "node_modules/npm/bin/npm-cli.js"), path.join(dir, "../lib/node_modules/npm/bin/npm-cli.js")]) if (exists(cli)) return [execPath, cli];
|
|
18
|
+
return platform === "win32" ? null : ["npm"];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** npm's arguments for this install kind: into npx's cache dir as its own package, or -g into the global prefix this copy lives under */
|
|
22
|
+
export function installArgs(kind, prefix, version) {
|
|
23
|
+
if (!validVersion(version)) throw new Error(`Not a release version: ${String(version).slice(0, 40)}`);
|
|
24
|
+
if (!prefix || !path.isAbsolute(prefix)) throw new Error("No install folder");
|
|
25
|
+
const common = ["--no-audit", "--no-fund", "--loglevel=error"];
|
|
26
|
+
if (kind === "npx") return ["install", `easel-canvas@${version}`, "--prefix", prefix, ...common];
|
|
27
|
+
if (kind === "global") return ["install", "-g", `easel-canvas@${version}`, "--prefix", prefix, ...common];
|
|
28
|
+
throw new Error(`Easel cannot update itself here (${kind})`);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Why an install failed, in a word the page turns into plain words (strings.update.why): permission, network or failed */
|
|
32
|
+
export function classifyInstallFailure(text = "", code = null) {
|
|
33
|
+
if (/EACCES|EPERM|permission denied|operation not permitted/i.test(text)) return "permission";
|
|
34
|
+
if (/ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|ECONNREFUSED|network|fetch failed|ENETUNREACH/i.test(text)) return "network";
|
|
35
|
+
if (code === "ENOENT") return "nonpm";
|
|
36
|
+
return "failed";
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The version in <root>/package.json, or null */
|
|
40
|
+
export function versionOnDisk(root) {
|
|
41
|
+
try {
|
|
42
|
+
const v = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).version;
|
|
43
|
+
return validVersion(v) ? v : null;
|
|
44
|
+
} catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Installs easel-canvas@version where the copy at root came from. Resolves to { ok: true, root } (the folder to start the new server
|
|
51
|
+
* from, its package.json at that version) or { ok: false, why, detail }; never throws. Times out after `timeout` (npm hanging on a
|
|
52
|
+
* registry that does not answer).
|
|
53
|
+
*/
|
|
54
|
+
export async function install({ version, root = TOOL_ROOT, env = process.env, spawnImpl = spawn, timeout = 180_000, npm = npmCommand() } = {}) {
|
|
55
|
+
try {
|
|
56
|
+
const { kind, prefix } = installKind(root);
|
|
57
|
+
const args = installArgs(kind, prefix, version);
|
|
58
|
+
let cmd;
|
|
59
|
+
if (env.EASEL_UPDATE_INSTALLER) {
|
|
60
|
+
const fake = JSON.parse(env.EASEL_UPDATE_INSTALLER);
|
|
61
|
+
if (!Array.isArray(fake) || !fake.every((a) => typeof a === "string")) throw new Error("EASEL_UPDATE_INSTALLER is not an argument array");
|
|
62
|
+
cmd = [...fake, ...args];
|
|
63
|
+
} else {
|
|
64
|
+
if (!npm) return { ok: false, why: "nonpm", detail: "npm was not found beside node" };
|
|
65
|
+
cmd = [...npm, ...args];
|
|
66
|
+
}
|
|
67
|
+
const out = await new Promise((resolve) => {
|
|
68
|
+
let text = "";
|
|
69
|
+
const p = spawnImpl(cmd[0], cmd.slice(1), { stdio: ["ignore", "pipe", "pipe"], env: { ...env, npm_config_update_notifier: "false" }, windowsHide: true });
|
|
70
|
+
const t = setTimeout(() => (p.kill("SIGTERM"), (text += "\nTimed out (network)")), timeout);
|
|
71
|
+
p.stdout?.on("data", (d) => (text += d));
|
|
72
|
+
p.stderr?.on("data", (d) => (text += d));
|
|
73
|
+
p.on("error", (e) => (clearTimeout(t), resolve({ code: e.code ?? "error", text: text + String(e.message) })));
|
|
74
|
+
p.on("close", (code) => (clearTimeout(t), resolve({ code, text })));
|
|
75
|
+
});
|
|
76
|
+
if (out.code !== 0) return { ok: false, why: classifyInstallFailure(out.text, out.code), detail: out.text.trim().split("\n").slice(-3).join("\n").slice(0, 400) };
|
|
77
|
+
const got = versionOnDisk(root);
|
|
78
|
+
if (got !== version) return { ok: false, why: "failed", detail: `After the install ${root} holds ${got ?? "no version"}, not ${version}` };
|
|
79
|
+
if (!existsSync(path.join(root, "bin", "server.mjs"))) return { ok: false, why: "failed", detail: "The new copy has no bin/server.mjs" };
|
|
80
|
+
return { ok: true, root };
|
|
81
|
+
} catch (e) {
|
|
82
|
+
return { ok: false, why: "failed", detail: String(e?.message ?? e) };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Polls http://127.0.0.1:port/api/health until a server with another pid answers, or the time is up; false if `alive()` says the new process died */
|
|
87
|
+
export async function waitForNew({ port, pid, ms = 30_000, alive = () => true, fetchImpl = fetch }) {
|
|
88
|
+
const end = Date.now() + ms;
|
|
89
|
+
while (Date.now() < end) {
|
|
90
|
+
if (!alive()) return false;
|
|
91
|
+
try {
|
|
92
|
+
const r = await fetchImpl(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(1000) });
|
|
93
|
+
if (r.ok && (await r.json()).pid !== pid) return true;
|
|
94
|
+
} catch {}
|
|
95
|
+
await new Promise((r) => setTimeout(r, 250));
|
|
96
|
+
}
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// AI-generated with Claude Code, 2026-11-29
|
|
2
|
+
// A board's render stamp: a short hash of the modification time and size of its HTML and of every local file the page loads
|
|
3
|
+
// (stylesheets and what they import, scripts, images, fonts, media, embedded boards and what those load). It changes whenever
|
|
4
|
+
// the rendered board can change, so the zoomed-out thumbnail is keyed by it on disk and in its URL (cached for a year by the
|
|
5
|
+
// browser). Not followed: what scripts fetch at run time, and remote URLs (both rarely change what a board looks like).
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import fs from "node:fs/promises";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
|
|
10
|
+
/** Tags whose attributes load something into the page (an <a href> only links, so it is not one) */
|
|
11
|
+
const LOADING_TAG = /<(link|script|img|source|video|audio|track|iframe|frame|object|embed|image|use|feimage|input)\b([^>]*)>/gi;
|
|
12
|
+
const LOADING_ATTR = /(?:^|\s)(src|href|srcset|poster|data|xlink:href)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi;
|
|
13
|
+
const CSS_URL = /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)'"\s]+))\s*\)/gi;
|
|
14
|
+
const CSS_IMPORT = /@import\s+(?:"([^"]*)"|'([^']*)')/gi;
|
|
15
|
+
/** A board's page loads at most this many local files that count (a runaway page still gets a stamp) */
|
|
16
|
+
const MAX_FILES = 400;
|
|
17
|
+
|
|
18
|
+
const kindOf = (p) => (/\.html?$/i.test(p) ? "html" : /\.css$/i.test(p) ? "css" : "leaf");
|
|
19
|
+
|
|
20
|
+
/** The local references in an HTML page or a stylesheet, as written */
|
|
21
|
+
export function refsIn(text, kind) {
|
|
22
|
+
const out = [];
|
|
23
|
+
const css = (s) => {
|
|
24
|
+
for (const m of s.matchAll(CSS_URL)) out.push(m[1] ?? m[2] ?? m[3]);
|
|
25
|
+
for (const m of s.matchAll(CSS_IMPORT)) out.push(m[1] ?? m[2]);
|
|
26
|
+
};
|
|
27
|
+
if (kind === "css") {
|
|
28
|
+
css(text);
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
for (const t of text.matchAll(LOADING_TAG)) {
|
|
32
|
+
for (const a of t[2].matchAll(LOADING_ATTR)) {
|
|
33
|
+
const v = a[2] ?? a[3] ?? a[4] ?? "";
|
|
34
|
+
if (a[1].toLowerCase() === "srcset") for (const part of v.split(",")) out.push(part.trim().split(/\s+/)[0]);
|
|
35
|
+
else out.push(v);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
// Inline <style> blocks and style="" attributes (a url() inside a script only adds a needless dependency)
|
|
39
|
+
css(text);
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function createStamps(dir) {
|
|
44
|
+
const root = path.resolve(dir);
|
|
45
|
+
const screensDir = path.join(root, "screens");
|
|
46
|
+
const parsed = new Map(); // abs → { key, refs: abs[] }
|
|
47
|
+
const depsOf = new Map(); // board file → Set(abs) its last stamp covered
|
|
48
|
+
|
|
49
|
+
/** Where the server finds what a page at `fromAbs` asks for with `ref` (the same mapping as the static routes), or null */
|
|
50
|
+
async function resolve(fromAbs, ref) {
|
|
51
|
+
ref = String(ref ?? "").trim();
|
|
52
|
+
if (!ref || ref.startsWith("#") || ref.startsWith("//") || /^[a-z][\w+.-]*:/i.test(ref)) return null;
|
|
53
|
+
let pathname;
|
|
54
|
+
try {
|
|
55
|
+
const base = new URL("http://x/" + path.relative(root, fromAbs).split(path.sep).map(encodeURIComponent).join("/"));
|
|
56
|
+
pathname = decodeURIComponent(new URL(ref, base).pathname);
|
|
57
|
+
} catch {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
const inside = (p) => (p === root || p.startsWith(root + path.sep) ? p : null);
|
|
61
|
+
if (pathname.startsWith("/screens/") || pathname.startsWith("/assets/")) return inside(path.join(root, pathname));
|
|
62
|
+
// Other root paths: the server sends them to screens/ when the file is there, else serves them from the design folder
|
|
63
|
+
const inScreens = inside(path.join(screensDir, pathname));
|
|
64
|
+
if (inScreens && (await fs.stat(inScreens).catch(() => null))) return inScreens;
|
|
65
|
+
return inside(path.join(root, pathname));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function refsOf(abs, key) {
|
|
69
|
+
const hit = parsed.get(abs);
|
|
70
|
+
if (hit?.key === key) return hit.refs;
|
|
71
|
+
const kind = kindOf(abs);
|
|
72
|
+
let refs = [];
|
|
73
|
+
if (kind !== "leaf") {
|
|
74
|
+
const text = await fs.readFile(abs, "utf8").catch(() => "");
|
|
75
|
+
refs = (await Promise.all(refsIn(text, kind).map((r) => resolve(abs, r)))).filter((p) => p && p !== abs);
|
|
76
|
+
}
|
|
77
|
+
parsed.set(abs, { key, refs });
|
|
78
|
+
return refs;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The stamp of a board (path under screens/), or null when its file is missing. memo: stats shared by several stamps made
|
|
83
|
+
* together (a hundred boards using the same fonts stat them once)
|
|
84
|
+
*/
|
|
85
|
+
async function stamp(file, memo = new Map()) {
|
|
86
|
+
const start = path.join(screensDir, file);
|
|
87
|
+
const statOf = (p) => {
|
|
88
|
+
if (!memo.has(p)) memo.set(p, fs.stat(p).then((s) => (s.isFile() ? `${Math.round(s.mtimeMs)}:${s.size}` : "-"), () => "-"));
|
|
89
|
+
return memo.get(p);
|
|
90
|
+
};
|
|
91
|
+
const first = await statOf(start);
|
|
92
|
+
if (first === "-") {
|
|
93
|
+
depsOf.delete(file);
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
const seen = new Map([[start, first]]);
|
|
97
|
+
let level = [start];
|
|
98
|
+
while (level.length && seen.size < MAX_FILES) {
|
|
99
|
+
const next = [];
|
|
100
|
+
for (const refs of await Promise.all(level.map(async (p) => (kindOf(p) === "leaf" || seen.get(p) === "-" ? [] : refsOf(p, seen.get(p)))))) {
|
|
101
|
+
for (const r of refs) if (!seen.has(r) && seen.size < MAX_FILES) {
|
|
102
|
+
seen.set(r, null);
|
|
103
|
+
next.push(r);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
await Promise.all(next.map(async (p) => seen.set(p, await statOf(p))));
|
|
107
|
+
level = next;
|
|
108
|
+
}
|
|
109
|
+
depsOf.set(file, new Set(seen.keys()));
|
|
110
|
+
const h = createHash("sha1");
|
|
111
|
+
for (const [p, s] of [...seen].sort((a, b) => (a[0] < b[0] ? -1 : 1))) h.update(`${path.relative(root, p)}\0${s}\n`);
|
|
112
|
+
return h.digest("hex").slice(0, 12);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Stamps of many boards at once */
|
|
116
|
+
async function stampAll(files) {
|
|
117
|
+
const memo = new Map();
|
|
118
|
+
const out = {};
|
|
119
|
+
await Promise.all(files.map(async (f) => {
|
|
120
|
+
const s = await stamp(f, memo);
|
|
121
|
+
if (s) out[f] = s;
|
|
122
|
+
}));
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Boards whose last stamp covered abs (a file they load, directly or through a stylesheet or an embedded board) */
|
|
127
|
+
function users(abs) {
|
|
128
|
+
const out = [];
|
|
129
|
+
for (const [f, set] of depsOf) if (set.has(abs)) out.push(f);
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return { stamp, stampAll, users, forget: (file) => depsOf.delete(file) };
|
|
134
|
+
}
|
package/server/up.mjs
CHANGED
|
@@ -80,6 +80,6 @@ export async function up({ dir, dirGiven = false, port = null, init = false, ope
|
|
|
80
80
|
|
|
81
81
|
/** One line for people (and agents reading the output) */
|
|
82
82
|
export function describe(r, dir) {
|
|
83
|
-
if (!r) return `No Easel canvas is running for ${dir}. Start one with: npx easel-canvas up`;
|
|
83
|
+
if (!r) return `No Easel canvas is running for ${dir}. Start one with: npx easel-canvas@latest up`;
|
|
84
84
|
return `${r.started ? "Started Easel" : "Easel is already running"}: ${r.url} (design folder ${r.dir}, pid ${r.pid})${r.log ? `\nLog: ${r.log}` : ""}`;
|
|
85
85
|
}
|
package/server/update.mjs
CHANGED
|
@@ -1,17 +1,25 @@
|
|
|
1
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.
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
// (
|
|
6
|
-
|
|
2
|
+
// New-version notice: npx keeps the copy it cached, so nothing tells people a newer Easel exists. The canvas asks the npm registry
|
|
3
|
+
// for easel-canvas's latest version (only that: one GET, nothing about the project) when the page loads and every few hours while it
|
|
4
|
+
// runs, keeping the answer an hour, and when it is newer says how this install updates: in one click where Easel can replace itself
|
|
5
|
+
// (npx's cache, a global install; see selfupdate.mjs), else the command to run. Silent whenever it cannot ask:
|
|
6
|
+
// EASEL_NO_UPDATE_CHECK=1, CI, a source checkout (git clone or submodule: updated with git), offline, a slow or broken registry.
|
|
7
|
+
import { accessSync, constants, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
8
|
import path from "node:path";
|
|
8
9
|
|
|
9
10
|
import { TOOL_ROOT } from "./args.mjs";
|
|
10
11
|
import { easelHome } from "./registry.mjs";
|
|
11
12
|
|
|
12
|
-
const
|
|
13
|
+
export const HOUR = 60 * 60 * 1000;
|
|
14
|
+
/** How long an answer from the registry is kept (in memory and in <EASEL_HOME>/update.json) */
|
|
15
|
+
export const CACHE_MS = HOUR;
|
|
16
|
+
/** How often a running canvas asks again on its own (a page load asks too, when the answer is older than CACHE_MS) */
|
|
17
|
+
export const EVERY_MS = 3 * HOUR;
|
|
13
18
|
const REGISTRY = "https://registry.npmjs.org/easel-canvas/latest";
|
|
14
19
|
|
|
20
|
+
/** A plain release version, x.y.z: the only thing ever passed on to npm (never a tag, a range or a URL) */
|
|
21
|
+
export const validVersion = (v) => typeof v === "string" && /^\d{1,4}\.\d{1,4}\.\d{1,6}$/.test(v);
|
|
22
|
+
|
|
15
23
|
/** a > b for x.y.z versions; a pre-release (0.3.0-beta.1) is older than its release and never offered */
|
|
16
24
|
export function isNewer(a, b) {
|
|
17
25
|
const parse = (v) => String(v).replace(/^v/, "").split("-")[0].split(".").map((n) => parseInt(n, 10) || 0);
|
|
@@ -21,21 +29,48 @@ export function isNewer(a, b) {
|
|
|
21
29
|
return /-/.test(String(b)); // 0.3.0 is newer than 0.3.0-beta.1
|
|
22
30
|
}
|
|
23
31
|
|
|
32
|
+
/**
|
|
33
|
+
* Where the running copy comes from, and so how it updates:
|
|
34
|
+
* npx (npx's cache, <prefix>/_npx/<hash>/node_modules/easel-canvas): installs into that prefix in place, so plain `npx easel-canvas` starts
|
|
35
|
+
* the new one too; global (<prefix>/lib/node_modules, or <prefix>\node_modules on Windows): `npm i -g` into that prefix; project (a
|
|
36
|
+
* project's node_modules: its lockfile is the owner's call) and source (a checkout: git) only say the command; other: as npx.
|
|
37
|
+
*/
|
|
38
|
+
export function installKind(root = TOOL_ROOT) {
|
|
39
|
+
const p = root.split(path.sep).join("/").replace(/\/+$/, "");
|
|
40
|
+
if (existsSync(path.join(root, "app")) || existsSync(path.join(root, ".git"))) return { kind: "source", prefix: null };
|
|
41
|
+
const m = p.match(/^(.*\/_npx\/[^/]+)\/node_modules\/easel-canvas$/);
|
|
42
|
+
if (m) return { kind: "npx", prefix: m[1].split("/").join(path.sep) };
|
|
43
|
+
const g = p.match(/^(.*)\/lib\/node_modules\/easel-canvas$/) ?? p.match(/^(.*\/npm)\/node_modules\/easel-canvas$/i);
|
|
44
|
+
if (g) return { kind: "global", prefix: g[1].split("/").join(path.sep) };
|
|
45
|
+
if (/\/node_modules\/easel-canvas$/.test(p)) return { kind: "project", prefix: null };
|
|
46
|
+
return { kind: "other", prefix: null };
|
|
47
|
+
}
|
|
48
|
+
|
|
24
49
|
/** The command that updates the copy running from root: npx's cache, a project's node_modules, or a global install */
|
|
25
50
|
export function updateCommand(root = TOOL_ROOT) {
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
51
|
+
const { kind } = installKind(root);
|
|
52
|
+
return kind === "global" ? "npm i -g easel-canvas@latest" : kind === "project" ? "npm i -D easel-canvas@latest" : kind === "source" ? "git pull" : "npx easel-canvas@latest";
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Whether Easel can replace this copy itself, and if not, why (shown under the row in plain words; see strings.update.why) */
|
|
56
|
+
export function selfUpdatable(root = TOOL_ROOT) {
|
|
57
|
+
const { kind } = installKind(root);
|
|
58
|
+
if (kind === "npx") return { self: true };
|
|
59
|
+
if (kind === "global") {
|
|
60
|
+
try {
|
|
61
|
+
accessSync(path.dirname(root), constants.W_OK); // …/lib/node_modules: npm writes there
|
|
62
|
+
return { self: true };
|
|
63
|
+
} catch {
|
|
64
|
+
return { self: false, why: "permission" };
|
|
65
|
+
}
|
|
31
66
|
}
|
|
32
|
-
return "
|
|
67
|
+
return { self: false, why: kind === "project" ? "project" : kind === "source" ? "source" : "other" };
|
|
33
68
|
}
|
|
34
69
|
|
|
35
70
|
/**
|
|
36
|
-
* Resolves to { current, latest, command } when the registry has a newer version, else null; never throws.
|
|
37
|
-
* The answer is kept
|
|
38
|
-
*
|
|
71
|
+
* Resolves to { current, latest, command, kind, self, why? } when the registry has a newer version, else null; never throws.
|
|
72
|
+
* The answer is kept CACHE_MS in <EASEL_HOME>/update.json. EASEL_UPDATE_URL points the check elsewhere (tests, trying it out from a
|
|
73
|
+
* source checkout).
|
|
39
74
|
*/
|
|
40
75
|
export async function checkUpdate({ current, env = process.env, root = TOOL_ROOT, home = easelHome(env), now = Date.now(), fetchImpl = fetch } = {}) {
|
|
41
76
|
try {
|
|
@@ -46,18 +81,45 @@ export async function checkUpdate({ current, env = process.env, root = TOOL_ROOT
|
|
|
46
81
|
let latest = null;
|
|
47
82
|
try {
|
|
48
83
|
const c = JSON.parse(readFileSync(file, "utf8"));
|
|
49
|
-
if (c.url === url && now - c.checkedAt <
|
|
84
|
+
if (c.url === url && now - c.checkedAt < CACHE_MS && now >= c.checkedAt) latest = c.latest;
|
|
50
85
|
} catch {}
|
|
51
86
|
if (!latest) {
|
|
52
87
|
const r = await fetchImpl(url, { signal: AbortSignal.timeout(2000), headers: { accept: "application/json" } });
|
|
53
88
|
if (!r.ok) return null;
|
|
54
89
|
latest = (await r.json())?.version;
|
|
55
|
-
if (
|
|
90
|
+
if (!validVersion(latest)) return null;
|
|
56
91
|
mkdirSync(home, { recursive: true });
|
|
57
92
|
writeFileSync(file, JSON.stringify({ url, checkedAt: now, latest }));
|
|
58
93
|
}
|
|
59
|
-
|
|
94
|
+
if (!validVersion(latest) || !isNewer(latest, current)) return null;
|
|
95
|
+
const { kind } = installKind(root);
|
|
96
|
+
return { current, latest, command: updateCommand(root), kind, ...selfUpdatable(root) };
|
|
60
97
|
} catch {
|
|
61
98
|
return null;
|
|
62
99
|
}
|
|
63
100
|
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The server's view of the notice: get() answers from memory while the last check is younger than CACHE_MS, else asks again (one at a
|
|
104
|
+
* time); a timer asks every EVERY_MS while the canvas runs (unref'd: it never keeps the process alive). onNews(u) is told the first time
|
|
105
|
+
* each newer version is seen (the terminal line).
|
|
106
|
+
*/
|
|
107
|
+
export function createUpdater({ current, env = process.env, root = TOOL_ROOT, home, now = () => Date.now(), fetchImpl = fetch, onNews = () => {}, every = EVERY_MS } = {}) {
|
|
108
|
+
let last = null; // { at, value }
|
|
109
|
+
let pending = null;
|
|
110
|
+
let told = null;
|
|
111
|
+
const get = () => {
|
|
112
|
+
if (last && now() - last.at < CACHE_MS && now() >= last.at) return Promise.resolve(last.value);
|
|
113
|
+
pending ??= checkUpdate({ current, env, root, home: home ?? easelHome(env), now: now(), fetchImpl })
|
|
114
|
+
.then((value) => {
|
|
115
|
+
last = { at: now(), value };
|
|
116
|
+
if (value && told !== value.latest) (told = value.latest), onNews(value);
|
|
117
|
+
return value;
|
|
118
|
+
})
|
|
119
|
+
.finally(() => (pending = null));
|
|
120
|
+
return pending;
|
|
121
|
+
};
|
|
122
|
+
const timer = setInterval(() => void get(), every);
|
|
123
|
+
timer.unref?.();
|
|
124
|
+
return { get, close: () => clearInterval(timer) };
|
|
125
|
+
}
|
package/server/watch.mjs
CHANGED
|
@@ -7,12 +7,14 @@ import path from "node:path";
|
|
|
7
7
|
import chokidar from "chokidar";
|
|
8
8
|
|
|
9
9
|
import { createDeps } from "./deps.mjs";
|
|
10
|
+
import { createStamps } from "./stamps.mjs";
|
|
10
11
|
import { toPosix } from "./fsutil.mjs";
|
|
11
12
|
import { contentHash } from "./livePatch.mjs";
|
|
12
13
|
|
|
13
|
-
export function watchDesign({ dir, store, broadcast, history }) {
|
|
14
|
+
export function watchDesign({ dir, store, broadcast, history, stamps = createStamps(dir) }) {
|
|
14
15
|
const screensDir = store.screensDir;
|
|
15
|
-
|
|
16
|
+
// The whole design folder: a stylesheet, image or font a board loads may sit anywhere in it (assets/ mostly)
|
|
17
|
+
const watcher = chokidar.watch([dir, screensDir, store.boardPath], {
|
|
16
18
|
ignoreInitial: true,
|
|
17
19
|
// Ignore iCloud placeholders (.icloud) and hidden files (PLAN.md ch. 9)
|
|
18
20
|
ignored: (p) => {
|
|
@@ -31,6 +33,8 @@ export function watchDesign({ dir, store, broadcast, history }) {
|
|
|
31
33
|
for (const f of files) hashes.set(f, sha(await fs.readFile(path.join(screensDir, f), "utf8").catch(() => "")));
|
|
32
34
|
});
|
|
33
35
|
store.listScreenFiles().then((files) => deps.init(files));
|
|
36
|
+
// Which files each board loads, so a change to a shared one finds its boards
|
|
37
|
+
store.listScreenFiles().then((files) => stamps.stampAll(files)).catch(() => {});
|
|
34
38
|
let syncTimer = null;
|
|
35
39
|
const scheduleSync = () => {
|
|
36
40
|
clearTimeout(syncTimer);
|
|
@@ -79,7 +83,15 @@ export function watchDesign({ dir, store, broadcast, history }) {
|
|
|
79
83
|
broadcast({ type: "board-changed", source: "server:external" });
|
|
80
84
|
return;
|
|
81
85
|
}
|
|
82
|
-
|
|
86
|
+
const inScreens = abs.startsWith(screensDir + path.sep);
|
|
87
|
+
if (!abs.endsWith(".html") || !inScreens) {
|
|
88
|
+
// A file boards load (a stylesheet, an image, a font, a page outside screens/): redraw those boards and their thumbnails
|
|
89
|
+
for (const host of stamps.users(abs)) {
|
|
90
|
+
const stamp = await stamps.stamp(host);
|
|
91
|
+
broadcast({ type: "file-changed", file: host, kind: "change", via: toPosix(path.relative(dir, abs)), ...(stamp ? { stamp } : {}) });
|
|
92
|
+
}
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
83
95
|
const file = toPosix(path.relative(screensDir, abs));
|
|
84
96
|
const kind = event === "add" ? "add" : event === "unlink" ? "unlink" : "change";
|
|
85
97
|
void track(path.join(screensDir, file));
|
|
@@ -102,10 +114,16 @@ export function watchDesign({ dir, store, broadcast, history }) {
|
|
|
102
114
|
}
|
|
103
115
|
}
|
|
104
116
|
}
|
|
105
|
-
// hash: the content read now. A tab whose board already shows exactly this content (it patched its own edit in place) keeps it
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
117
|
+
// hash: the content read now. A tab whose board already shows exactly this content (it patched its own edit in place) keeps it.
|
|
118
|
+
// stamp: the board's render stamp now, the version of its thumbnail
|
|
119
|
+
const stamp = kind === "unlink" ? (stamps.forget(file), null) : await stamps.stamp(file);
|
|
120
|
+
broadcast({ type: "file-changed", file, kind, ...(hash ? { hash } : {}), ...(stamp ? { stamp } : {}) });
|
|
121
|
+
// Also redraw boards that embed this screen (flow diagrams etc.), or load it some other way
|
|
122
|
+
for (const host of new Set([...deps.dependents(file), ...stamps.users(abs)])) {
|
|
123
|
+
if (host === file) continue;
|
|
124
|
+
const s = await stamps.stamp(host);
|
|
125
|
+
broadcast({ type: "file-changed", file: host, kind: "change", via: file, ...(s ? { stamp: s } : {}) });
|
|
126
|
+
}
|
|
109
127
|
if (kind !== "change") scheduleSync();
|
|
110
128
|
});
|
|
111
129
|
|