easel-canvas 0.2.2 → 0.3.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 +34 -6
- package/bin/mcp.mjs +21 -5
- package/bin/server.mjs +22 -1
- package/dist/assets/index-B7XvZ2rQ.js +70 -0
- package/dist/assets/index-CLVWE3wq.css +1 -0
- package/dist/index.html +2 -2
- package/dist/viewer/viewer.css +1 -1
- package/dist/viewer/viewer.js +20 -14
- package/examples/demo/.thumbs/home.html.1791613627606.jpg +0 -0
- package/package.json +6 -2
- package/server/args.mjs +5 -4
- package/server/boards.mjs +49 -0
- package/server/browser.mjs +262 -32
- package/server/export.mjs +17 -22
- package/server/index.mjs +5 -2
- package/server/livePatch.mjs +109 -0
- package/server/registry.mjs +1 -1
- package/server/routes.mjs +75 -36
- package/server/up.mjs +85 -0
- package/server/watch.mjs +8 -4
- package/dist/assets/index-CjyXUlEx.css +0 -1
- package/dist/assets/index-DFCSLJXY.js +0 -66
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "easel-canvas",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Easel: an HTML design canvas for AI agents. Shows screens/*.html as boards and edits the source directly, with Claude Code / Codex via MCP",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Hyun Park",
|
|
@@ -22,11 +22,15 @@
|
|
|
22
22
|
"demo": "node bin/server.mjs --dir examples/demo --open",
|
|
23
23
|
"build": "vite build app --config vite.config.mjs && vite build app --config vite.config.mjs --mode viewer",
|
|
24
24
|
"prepack": "npm run build",
|
|
25
|
+
"version": "node tools/plugin-sync.mjs && git add plugin",
|
|
25
26
|
"mcp": "node bin/mcp.mjs",
|
|
26
27
|
"typecheck": "tsc --noEmit",
|
|
27
28
|
"test": "node --test test/*.test.mjs",
|
|
28
29
|
"test:e2e": "node --test --test-concurrency=1 test/e2e/*.e2e.mjs",
|
|
29
|
-
"design:css": "node tools/mkcss.mjs"
|
|
30
|
+
"design:css": "node tools/mkcss.mjs",
|
|
31
|
+
"verify:agents": "node tools/verify-agents.mjs",
|
|
32
|
+
"perf": "node tools/perf/measure.mjs",
|
|
33
|
+
"perf:phases": "node tools/perf/phases.mjs"
|
|
30
34
|
},
|
|
31
35
|
"engines": {
|
|
32
36
|
"node": ">=20"
|
package/server/args.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// AI-generated with Claude Code, 2026-10-09, reviewed by Hyun Park
|
|
2
|
-
// Command-line args: [connect] [--dir <design folder>] [--port 4317] [--open] [--demo] [--init] [--help] [--version],
|
|
3
|
-
// plus --agents a,b and --dry-run for connect, --out, --page, --boards a,b, --single-file, --pdf, --png for export,
|
|
2
|
+
// Command-line args: [connect|export|up|status] [--dir <design folder>] [--port 4317] [--open] [--demo] [--init] [--help] [--version],
|
|
3
|
+
// plus --agents a,b and --dry-run for connect, --json for up and status, --out, --page, --boards a,b, --single-file, --pdf, --png for export,
|
|
4
4
|
// and --chat / --permission for easel-mcp (the server of an in-app chat run: canvas tools and its permission tool / that tool only).
|
|
5
5
|
// Default design folder: <repo>/docs/design when Easel lives in <repo>/tools/<name> (submodule); otherwise
|
|
6
6
|
// ./docs/design or the current folder if it has screens/ (npx).
|
|
@@ -25,7 +25,7 @@ export const DEFAULT_DIR = defaultDir();
|
|
|
25
25
|
const expand = (p) => path.resolve(p.replace(/^~(?=\/)/, process.env.HOME ?? "~"));
|
|
26
26
|
|
|
27
27
|
export function parseArgs(argv = process.argv.slice(2)) {
|
|
28
|
-
const out = { command: null, dir: null, port: DEFAULT_PORT, portGiven: false, dirGiven: false, agents: null, dryRun: false, out: null, page: null, boards: null, singleFile: false, pdf: false, png: false, permission: false, chat: false, open: false, noOpen: false, demo: false, init: false, help: false, version: false, prod: false };
|
|
28
|
+
const out = { command: null, dir: null, port: DEFAULT_PORT, portGiven: false, dirGiven: false, agents: null, dryRun: false, json: false, out: null, page: null, boards: null, singleFile: false, pdf: false, png: false, permission: false, chat: false, open: false, noOpen: false, demo: false, init: false, help: false, version: false, prod: false };
|
|
29
29
|
for (let i = 0; i < argv.length; i++) {
|
|
30
30
|
const a = argv[i];
|
|
31
31
|
const next = () => argv[++i];
|
|
@@ -36,6 +36,7 @@ export function parseArgs(argv = process.argv.slice(2)) {
|
|
|
36
36
|
else if (a === "--agents") out.agents = next();
|
|
37
37
|
else if (a.startsWith("--agents=")) out.agents = a.slice(9);
|
|
38
38
|
else if (a === "--dry-run") out.dryRun = true;
|
|
39
|
+
else if (a === "--json") out.json = true;
|
|
39
40
|
else if (a === "--out") out.out = argv[i + 1] ? expand(next()) : null;
|
|
40
41
|
else if (a.startsWith("--out=")) out.out = expand(a.slice(6));
|
|
41
42
|
else if (a === "--page") out.page = next();
|
|
@@ -45,7 +46,7 @@ export function parseArgs(argv = process.argv.slice(2)) {
|
|
|
45
46
|
else if (a === "--single-file") out.singleFile = true;
|
|
46
47
|
else if (a === "--pdf") out.pdf = true;
|
|
47
48
|
else if (a === "--png") out.png = true;
|
|
48
|
-
else if (i === 0 &&
|
|
49
|
+
else if (i === 0 && ["connect", "export", "up", "status"].includes(a)) out.command = a;
|
|
49
50
|
else if (a === "--open") out.open = true;
|
|
50
51
|
else if (a === "--no-open") out.noOpen = true;
|
|
51
52
|
else if (a === "--demo") out.demo = true;
|
package/server/boards.mjs
CHANGED
|
@@ -21,6 +21,9 @@ export const TEMPLATES = {
|
|
|
21
21
|
mobile: { label: "Mobile screen", w: 390, h: 844 },
|
|
22
22
|
desktop: { label: "Desktop screen", w: 1440, h: 900 },
|
|
23
23
|
doc: { label: "Document", w: 800, h: 1000 },
|
|
24
|
+
tablet: { label: "Tablet screen", w: 834, h: 1194 },
|
|
25
|
+
watch: { label: "Watch screen", w: 198, h: 242 },
|
|
26
|
+
email: { label: "Email", w: 600, h: 1200 },
|
|
24
27
|
};
|
|
25
28
|
|
|
26
29
|
export function newBoardHtml({ title, w, h, template = "blank", brand = "" }) {
|
|
@@ -53,6 +56,52 @@ export function newBoardHtml({ title, w, h, template = "blank", brand = "" }) {
|
|
|
53
56
|
doc: `<div style="width:${w}px;min-height:${h}px;box-sizing:border-box;padding:48px;display:flex;flex-direction:column;gap:16px;background:#FFFFFF">
|
|
54
57
|
<h1 style="margin:0;font-size:34px;font-weight:700;letter-spacing:-0.02em">${t}</h1>
|
|
55
58
|
<p style="margin:0;font-size:17px;line-height:1.6;color:#111111">Body text</p>
|
|
59
|
+
</div>`,
|
|
60
|
+
// Two cards side by side under the heading, one action at the bottom: the shape of a tablet screen with room to spare
|
|
61
|
+
tablet: `<div style="width:${w}px;height:${h}px;box-sizing:border-box;background:#FFFFFF;display:flex;flex-direction:column;overflow:hidden">
|
|
62
|
+
<header style="height:64px;display:flex;align-items:center;padding:0 32px;border-bottom:1px solid #E8E8E6;flex:none">
|
|
63
|
+
<span style="font-size:17px;font-weight:700">${t}</span>
|
|
64
|
+
</header>
|
|
65
|
+
<main style="flex:1;padding:32px;display:flex;flex-direction:column;gap:24px">
|
|
66
|
+
<h1 style="margin:0;font-size:34px;font-weight:700;letter-spacing:-0.02em;line-height:1.15">Title</h1>
|
|
67
|
+
<p style="margin:0;font-size:17px;line-height:1.5;color:#6B6B6B">Description</p>
|
|
68
|
+
<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
|
|
69
|
+
<section style="padding:24px;border-radius:16px;background:#F5F5F3;display:flex;flex-direction:column;gap:8px">
|
|
70
|
+
<h2 style="margin:0;font-size:22px;font-weight:600">Section</h2>
|
|
71
|
+
<p style="margin:0;font-size:16px;line-height:1.5;color:#6B6B6B">Supporting text</p>
|
|
72
|
+
</section>
|
|
73
|
+
<section style="padding:24px;border-radius:16px;background:#F5F5F3;display:flex;flex-direction:column;gap:8px">
|
|
74
|
+
<h2 style="margin:0;font-size:22px;font-weight:600">Section</h2>
|
|
75
|
+
<p style="margin:0;font-size:16px;line-height:1.5;color:#6B6B6B">Supporting text</p>
|
|
76
|
+
</section>
|
|
77
|
+
</div>
|
|
78
|
+
</main>
|
|
79
|
+
<footer style="padding:16px 32px 32px;flex:none;display:flex;justify-content:flex-end">
|
|
80
|
+
<a href="#" style="display:flex;align-items:center;justify-content:center;height:56px;padding:0 32px;border-radius:16px;background:#C94F0C;color:#FFFFFF;font-size:17px;font-weight:700;text-decoration:none">Next</a>
|
|
81
|
+
</footer>
|
|
82
|
+
</div>`,
|
|
83
|
+
// A glance and one action: a short label, a large value, a full-width button that is still a 48px target
|
|
84
|
+
watch: `<div style="width:${w}px;height:${h}px;box-sizing:border-box;padding:12px;background:#FFFFFF;display:flex;flex-direction:column;gap:4px;overflow:hidden">
|
|
85
|
+
<span style="font-size:15px;font-weight:600;color:#6B6B6B">${t}</span>
|
|
86
|
+
<strong style="font-size:34px;font-weight:700;line-height:1.15">Title</strong>
|
|
87
|
+
<span style="font-size:15px;color:#6B6B6B">Description</span>
|
|
88
|
+
<a href="#" style="margin-top:auto;display:flex;align-items:center;justify-content:center;height:48px;border-radius:999px;background:#C94F0C;color:#FFFFFF;font-size:16px;font-weight:700;text-decoration:none">Next</a>
|
|
89
|
+
</div>`,
|
|
90
|
+
// One 600px column, as an email client shows it: sender, heading, text, one button, a footer with the unsubscribe link
|
|
91
|
+
email: `<div style="width:${w}px;min-height:${h}px;box-sizing:border-box;background:#FFFFFF;display:flex;flex-direction:column">
|
|
92
|
+
<header style="padding:32px 40px 24px">
|
|
93
|
+
<strong style="font-size:17px">${name}</strong>
|
|
94
|
+
</header>
|
|
95
|
+
<main style="padding:0 40px 40px;display:flex;flex-direction:column;gap:16px">
|
|
96
|
+
<h1 style="margin:0;font-size:34px;font-weight:700;letter-spacing:-0.02em;line-height:1.15">${t}</h1>
|
|
97
|
+
<p style="margin:0;font-size:17px;line-height:1.6">Hi there,</p>
|
|
98
|
+
<p style="margin:0;font-size:17px;line-height:1.6">Body text</p>
|
|
99
|
+
<a href="#" style="align-self:flex-start;display:flex;align-items:center;height:48px;padding:0 24px;margin-top:8px;border-radius:8px;background:#C94F0C;color:#FFFFFF;font-size:17px;font-weight:700;text-decoration:none">Call to action</a>
|
|
100
|
+
</main>
|
|
101
|
+
<footer style="margin-top:auto;padding:24px 40px 32px;border-top:1px solid #E8E8E6;display:flex;flex-direction:column;gap:4px">
|
|
102
|
+
<p style="margin:0;font-size:15px;line-height:1.5;color:#6B6B6B">You are receiving this email because you signed up.</p>
|
|
103
|
+
<a href="#" style="align-self:flex-start;display:flex;align-items:center;min-height:48px;font-size:15px;color:#6B6B6B">Unsubscribe</a>
|
|
104
|
+
</footer>
|
|
56
105
|
</div>`,
|
|
57
106
|
};
|
|
58
107
|
return `<!doctype html>
|
package/server/browser.mjs
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
// AI-generated with Claude Code, 2026-11-11, reviewed by Hyun Park
|
|
2
2
|
// The one shared headless Chromium (playwright, an optional dependency) behind screenshots, thumbnails and PDF/PNG export.
|
|
3
|
+
// Launched on first use (never at server start), shared by concurrent first calls, one fresh context per render, at most
|
|
4
|
+
// MAX_PAGES renders at a time (the rest wait), closed after EASEL_BROWSER_IDLE_SECONDS without a render, and launched again
|
|
5
|
+
// after it dies or is killed (a render that hits a dead browser is tried once more on a new one). Files from other hosts
|
|
6
|
+
// (web fonts, CDN images) are cached across renders while the browser is up (createRemoteCache).
|
|
3
7
|
import { existsSync } from "node:fs";
|
|
4
8
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
export
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
9
|
+
/** Default seconds without a render before the browser is closed (EASEL_BROWSER_IDLE_SECONDS overrides; 0 closes right away) */
|
|
10
|
+
export const IDLE_SECONDS = 120;
|
|
11
|
+
/** Renders open at once across screenshots, thumbnails and export; more wait in line */
|
|
12
|
+
export const MAX_PAGES = 4;
|
|
13
|
+
|
|
14
|
+
export function idleMsFromEnv(env = process.env) {
|
|
15
|
+
const v = Number(env.EASEL_BROWSER_IDLE_SECONDS);
|
|
16
|
+
return (env.EASEL_BROWSER_IDLE_SECONDS != null && env.EASEL_BROWSER_IDLE_SECONDS !== "" && Number.isFinite(v) && v >= 0 ? v : IDLE_SECONDS) * 1000;
|
|
11
17
|
}
|
|
12
18
|
|
|
13
19
|
const loadPlaywright = () =>
|
|
@@ -15,41 +21,265 @@ const loadPlaywright = () =>
|
|
|
15
21
|
throw Object.assign(new Error("Screenshots are unavailable because playwright is not installed (npm run design:install)"), { status: 501 });
|
|
16
22
|
});
|
|
17
23
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
24
|
+
async function launchChromium() {
|
|
25
|
+
const { chromium } = await loadPlaywright();
|
|
26
|
+
// Fall back to the installed Chrome if no downloaded Chromium exists
|
|
27
|
+
return chromium.launch().catch(() => chromium.launch({ channel: "chrome" }));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);
|
|
31
|
+
const maxAgeOf = (cc) => {
|
|
32
|
+
if (/(^|,)\s*(no-store|no-cache|private)\b/i.test(cc)) return 0;
|
|
33
|
+
const m = /(?:^|,)\s*(?:s-maxage|max-age)\s*=\s*(\d+)/i.exec(cc);
|
|
34
|
+
return m ? Number(m[1]) : 0;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* HTTP cache for files boards load from other hosts (web fonts, font CSS, CDN images), shared by every render while the
|
|
39
|
+
* browser is up. Each render has a fresh context, and a fresh context starts with an empty HTTP cache, so without this a
|
|
40
|
+
* board using a 2 MB CDN font downloaded it again for every thumbnail. Only GETs from non-loopback hosts are routed (the
|
|
41
|
+
* canvas's own files are no-store and stay direct). Kept: 200 responses with a positive max-age, no no-store/no-cache/
|
|
42
|
+
* private, no Set-Cookie, no Vary beyond Accept-Encoding/Origin, at most maxEntryBytes, maxBytes in all (oldest out first),
|
|
43
|
+
* keyed by URL and Origin (the CORS answer depends on it). Requests with cookies or Authorization go straight through.
|
|
44
|
+
*/
|
|
45
|
+
export const isRemoteUrl = (u) => (u.protocol === "http:" || u.protocol === "https:") && !LOOPBACK.has(u.hostname);
|
|
46
|
+
|
|
47
|
+
export function createRemoteCache({ maxBytes = 64 * 1048576, maxEntryBytes = 8 * 1048576, now = () => Date.now(), routes = isRemoteUrl } = {}) {
|
|
48
|
+
const entries = new Map(); // key -> { status, headers, body, expires }; Map order = age
|
|
49
|
+
const inflight = new Map();
|
|
50
|
+
let bytes = 0;
|
|
51
|
+
const drop = (k) => {
|
|
52
|
+
const e = entries.get(k);
|
|
53
|
+
if (e) (bytes -= e.body.length), entries.delete(k);
|
|
54
|
+
};
|
|
55
|
+
const cacheable = (res, body) => {
|
|
56
|
+
if (res.status !== 200 || body.length > maxEntryBytes) return 0;
|
|
57
|
+
const h = res.headers;
|
|
58
|
+
if (h["set-cookie"]) return 0;
|
|
59
|
+
if (h.vary && h.vary.split(",").some((v) => !/^\s*(accept-encoding|origin)\s*$/i.test(v))) return 0;
|
|
60
|
+
return maxAgeOf(h["cache-control"] ?? "");
|
|
61
|
+
};
|
|
62
|
+
async function fetchVia(route, key) {
|
|
63
|
+
const r = await route.fetch();
|
|
64
|
+
const res = { status: r.status(), headers: r.headers(), body: await r.body() };
|
|
65
|
+
const age = cacheable(res, res.body);
|
|
66
|
+
if (age > 0) {
|
|
67
|
+
const { "set-cookie": _, ...headers } = res.headers;
|
|
68
|
+
drop(key);
|
|
69
|
+
entries.set(key, { ...res, headers, expires: now() + age * 1000 });
|
|
70
|
+
bytes += res.body.length;
|
|
71
|
+
for (const k of entries.keys()) {
|
|
72
|
+
if (bytes <= maxBytes) break;
|
|
73
|
+
drop(k);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return res;
|
|
77
|
+
}
|
|
78
|
+
/** The page.route handler */
|
|
79
|
+
async function handle(route) {
|
|
80
|
+
const req = route.request();
|
|
81
|
+
const h = req.headers();
|
|
82
|
+
if (req.method() !== "GET" || h.cookie || h.authorization) return route.continue().catch(() => {});
|
|
83
|
+
const key = `${req.url()}\n${h.origin ?? ""}`;
|
|
84
|
+
try {
|
|
85
|
+
let hit = entries.get(key);
|
|
86
|
+
if (hit && hit.expires <= now()) drop(key), (hit = null);
|
|
87
|
+
if (hit) {
|
|
88
|
+
entries.delete(key), entries.set(key, hit); // most recently used goes last
|
|
89
|
+
} else {
|
|
90
|
+
// Two renders asking for the same font at once share one download
|
|
91
|
+
let p = inflight.get(key);
|
|
92
|
+
if (!p) {
|
|
93
|
+
p = fetchVia(route, key).finally(() => inflight.delete(key));
|
|
94
|
+
inflight.set(key, p);
|
|
95
|
+
}
|
|
96
|
+
hit = await p;
|
|
97
|
+
}
|
|
98
|
+
await route.fulfill({ status: hit.status, headers: hit.headers, body: hit.body });
|
|
99
|
+
} catch {
|
|
100
|
+
await route.continue().catch(() => {}); // a failed fetch or a closed page: let the browser deal with it
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
handle,
|
|
105
|
+
/** Routed URLs: http(s) on a host other than this machine */
|
|
106
|
+
routes,
|
|
107
|
+
clear() {
|
|
108
|
+
entries.clear();
|
|
109
|
+
bytes = 0;
|
|
110
|
+
},
|
|
111
|
+
stats: () => ({ entries: entries.size, bytes }),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* The pool. launch() returns a playwright-like Browser (isConnected, on("disconnected"), newPage(opts), close).
|
|
117
|
+
* timers is injectable so tests drive the idle close without waiting.
|
|
118
|
+
*/
|
|
119
|
+
export function createBrowserPool({ launch = launchChromium, idleMs = idleMsFromEnv(), maxPages = MAX_PAGES, timers = globalThis, remoteCache = createRemoteCache() } = {}) {
|
|
120
|
+
let browserPromise = null;
|
|
121
|
+
let idleTimer = null;
|
|
122
|
+
let active = 0; // pages open (each holds a slot)
|
|
123
|
+
const waiting = [];
|
|
124
|
+
|
|
125
|
+
const clearIdle = () => {
|
|
126
|
+
if (idleTimer) timers.clearTimeout(idleTimer);
|
|
127
|
+
idleTimer = null;
|
|
128
|
+
};
|
|
129
|
+
// Armed whenever nothing is rendering and a browser is up; must not keep the Node process alive
|
|
130
|
+
const armIdle = () => {
|
|
131
|
+
clearIdle();
|
|
132
|
+
if (active > 0 || waiting.length || !browserPromise) return;
|
|
133
|
+
const p = browserPromise;
|
|
134
|
+
idleTimer = timers.setTimeout(() => {
|
|
135
|
+
idleTimer = null;
|
|
136
|
+
if (active === 0 && !waiting.length && browserPromise === p) void close();
|
|
137
|
+
}, idleMs);
|
|
138
|
+
idleTimer?.unref?.();
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
async function getBrowser() {
|
|
142
|
+
clearIdle();
|
|
143
|
+
// A browser that exited behind our back (crash, killed, sleep) must not stay cached, or every render fails until a restart
|
|
144
|
+
const pending = browserPromise;
|
|
145
|
+
const cached = pending && (await pending.catch(() => null));
|
|
146
|
+
if (cached && !cached.isConnected() && browserPromise === pending) browserPromise = null;
|
|
147
|
+
if (!browserPromise) {
|
|
148
|
+
const p = (browserPromise = (async () => {
|
|
149
|
+
const b = await launch();
|
|
150
|
+
b.on("disconnected", () => {
|
|
151
|
+
if (browserPromise === p) browserPromise = null;
|
|
152
|
+
});
|
|
153
|
+
return b;
|
|
154
|
+
})());
|
|
155
|
+
// A failed launch is not kept: installing a browser later works without a restart
|
|
156
|
+
p.catch(() => {
|
|
29
157
|
if (browserPromise === p) browserPromise = null;
|
|
30
158
|
});
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
159
|
+
}
|
|
160
|
+
const b = await browserPromise;
|
|
161
|
+
armIdle(); // browserStatus() launches without a render: still closed when idle
|
|
162
|
+
return b;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function close() {
|
|
166
|
+
clearIdle();
|
|
167
|
+
remoteCache?.clear(); // the cache lives as long as the browser
|
|
168
|
+
const b = await browserPromise?.catch(() => null);
|
|
169
|
+
browserPromise = null;
|
|
170
|
+
await b?.close().catch(() => {});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const acquire = () =>
|
|
174
|
+
new Promise((resolve) => {
|
|
175
|
+
clearIdle();
|
|
176
|
+
if (active < maxPages) {
|
|
177
|
+
active++;
|
|
178
|
+
resolve();
|
|
179
|
+
} else waiting.push(resolve);
|
|
35
180
|
});
|
|
181
|
+
const release = () => {
|
|
182
|
+
const next = waiting.shift();
|
|
183
|
+
if (next) next(); // hand the slot over
|
|
184
|
+
else {
|
|
185
|
+
active--;
|
|
186
|
+
armIdle();
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
/** A page in its own fresh context (cookies, storage, viewport, color scheme, scale never leak between renders). Holds a slot until the page or its context closes */
|
|
191
|
+
async function newPage(opts) {
|
|
192
|
+
await acquire();
|
|
193
|
+
let released = false;
|
|
194
|
+
const free = () => {
|
|
195
|
+
if (!released) (released = true), release();
|
|
196
|
+
};
|
|
197
|
+
try {
|
|
198
|
+
let browser = await getBrowser();
|
|
199
|
+
let page;
|
|
200
|
+
try {
|
|
201
|
+
page = await browser.newPage(opts);
|
|
202
|
+
} catch (e) {
|
|
203
|
+
if (browser.isConnected()) throw e;
|
|
204
|
+
browser = await getBrowser(); // drops the dead one and launches again
|
|
205
|
+
page = await browser.newPage(opts);
|
|
206
|
+
}
|
|
207
|
+
if (remoteCache && page.route) await page.route(remoteCache.routes, remoteCache.handle).catch((e) => page.close().catch(() => {}).then(() => Promise.reject(e)));
|
|
208
|
+
// browser.newPage owns its context: closing the page closes it; the context also closes when the browser goes away
|
|
209
|
+
const ctx = page.context?.();
|
|
210
|
+
if (ctx?.once) ctx.once("close", free);
|
|
211
|
+
page.once?.("close", free);
|
|
212
|
+
return page;
|
|
213
|
+
} catch (e) {
|
|
214
|
+
free();
|
|
215
|
+
throw Object.assign(e, { opening: true });
|
|
216
|
+
}
|
|
36
217
|
}
|
|
37
|
-
return browserPromise;
|
|
38
|
-
}
|
|
39
218
|
|
|
40
|
-
/**
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
219
|
+
/** Runs fn(page) on a fresh page and closes it. If the browser died during the render, tries once more on a new one */
|
|
220
|
+
async function withPage(opts, fn) {
|
|
221
|
+
for (let attempt = 0; ; attempt++) {
|
|
222
|
+
const page = await newPage(opts);
|
|
223
|
+
const browser = page.context?.().browser?.();
|
|
224
|
+
try {
|
|
225
|
+
return await fn(page);
|
|
226
|
+
} catch (e) {
|
|
227
|
+
if (attempt === 0 && browser && !browser.isConnected()) continue;
|
|
228
|
+
throw e;
|
|
229
|
+
} finally {
|
|
230
|
+
await page.close().catch(() => {});
|
|
231
|
+
}
|
|
232
|
+
}
|
|
48
233
|
}
|
|
234
|
+
|
|
235
|
+
return {
|
|
236
|
+
getBrowser,
|
|
237
|
+
newPage,
|
|
238
|
+
withPage,
|
|
239
|
+
close,
|
|
240
|
+
/** For tests: the browser currently cached, if any */
|
|
241
|
+
cached: () => browserPromise?.catch(() => null) ?? Promise.resolve(null),
|
|
242
|
+
stats: () => ({ active, waiting: waiting.length, idleArmed: !!idleTimer }),
|
|
243
|
+
};
|
|
49
244
|
}
|
|
50
245
|
|
|
246
|
+
const pool = createBrowserPool();
|
|
247
|
+
export const getBrowser = pool.getBrowser;
|
|
248
|
+
export const newPage = pool.newPage;
|
|
249
|
+
export const withPage = pool.withPage;
|
|
250
|
+
/** Close the Chromium used for screenshots/thumbnails/export when the server stops (otherwise it becomes an orphan process) */
|
|
251
|
+
export const closeBrowser = pool.close;
|
|
51
252
|
/** For tests: the browser currently cached for screenshots, if any */
|
|
52
|
-
export const cachedBrowser =
|
|
253
|
+
export const cachedBrowser = pool.cached;
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Goes to url and waits until the board has settled: the load event, web fonts, then no request in flight for quietMs.
|
|
257
|
+
* Replaces waitUntil "networkidle", whose fixed 500 ms quiet window was most of every screenshot. A page that never goes
|
|
258
|
+
* quiet (polling) is captured after maxWaitMs instead of failing.
|
|
259
|
+
*/
|
|
260
|
+
export async function gotoSettled(page, url, { timeout = 30000, quietMs = 100, maxWaitMs = 5000 } = {}) {
|
|
261
|
+
const inflight = new Set();
|
|
262
|
+
const on = (r) => inflight.add(r);
|
|
263
|
+
const off = (r) => inflight.delete(r);
|
|
264
|
+
page.on("request", on);
|
|
265
|
+
page.on("requestfinished", off);
|
|
266
|
+
page.on("requestfailed", off);
|
|
267
|
+
try {
|
|
268
|
+
await page.goto(url, { waitUntil: "load", timeout });
|
|
269
|
+
await page.evaluate(() => document.fonts?.ready.then(() => undefined)).catch(() => {});
|
|
270
|
+
const end = Date.now() + maxWaitMs;
|
|
271
|
+
let quietSince = Date.now();
|
|
272
|
+
while (Date.now() < end) {
|
|
273
|
+
if (inflight.size) quietSince = Date.now();
|
|
274
|
+
else if (Date.now() - quietSince >= quietMs) break;
|
|
275
|
+
await new Promise((r) => setTimeout(r, 20));
|
|
276
|
+
}
|
|
277
|
+
} finally {
|
|
278
|
+
page.off("request", on);
|
|
279
|
+
page.off("requestfinished", off);
|
|
280
|
+
page.off("requestfailed", off);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
53
283
|
|
|
54
284
|
/** Can PDF/PNG export run here? { ok } or { ok: false, reason } in one line, without launching when the downloaded Chromium is on disk */
|
|
55
285
|
export async function browserStatus() {
|
package/server/export.mjs
CHANGED
|
@@ -9,7 +9,7 @@ import path from "node:path";
|
|
|
9
9
|
|
|
10
10
|
import { TOOL_ROOT } from "./args.mjs";
|
|
11
11
|
import { createBoardStore } from "./board.mjs";
|
|
12
|
-
import { browserStatus,
|
|
12
|
+
import { browserStatus, withPage as sharedWithPage } from "./browser.mjs";
|
|
13
13
|
import { projectName, rootOf, toPosix } from "./fsutil.mjs";
|
|
14
14
|
import { MIME, readBody, safeJoin, sendJson } from "./index.mjs";
|
|
15
15
|
import { git } from "./snapshot.mjs";
|
|
@@ -404,24 +404,22 @@ async function serveDesign(dir) {
|
|
|
404
404
|
return { url: `http://127.0.0.1:${server.address().port}`, close: () => new Promise((r) => server.close(r)) };
|
|
405
405
|
}
|
|
406
406
|
|
|
407
|
-
async function renderBoards(dir, boards,
|
|
407
|
+
async function renderBoards(dir, boards, withPage) {
|
|
408
408
|
const srv = await serveDesign(dir);
|
|
409
409
|
const shots = [];
|
|
410
410
|
try {
|
|
411
411
|
for (const b of boards) {
|
|
412
|
-
let pg;
|
|
413
412
|
try {
|
|
414
|
-
|
|
413
|
+
const png = await withPage({ viewport: { width: b.w, height: b.h }, deviceScaleFactor: 2 }, async (pg) => {
|
|
414
|
+
await pg.goto(`${srv.url}/screens/${encodePath(b.file)}`, { waitUntil: "load", timeout: 20000 });
|
|
415
|
+
await pg.waitForTimeout(150);
|
|
416
|
+
return pg.screenshot({ type: "png" });
|
|
417
|
+
});
|
|
418
|
+
shots.push({ ...b, png });
|
|
415
419
|
} catch (e) {
|
|
420
|
+
if (!e.opening) throw e;
|
|
416
421
|
throw fail(501, `PDF and PNG need a headless Chromium (${String(e.message ?? e).split("\n")[0]}). Run npx playwright install chromium.`);
|
|
417
422
|
}
|
|
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
423
|
}
|
|
426
424
|
} finally {
|
|
427
425
|
await srv.close();
|
|
@@ -430,16 +428,13 @@ async function renderBoards(dir, boards, newPage) {
|
|
|
430
428
|
}
|
|
431
429
|
|
|
432
430
|
/** One page per board, each page the board's own size (CSS named pages) */
|
|
433
|
-
async function pdfOf(shots,
|
|
431
|
+
async function pdfOf(shots, withPage) {
|
|
434
432
|
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
433
|
const body = shots.map((s, i) => `<div class="b${i}"><img src="data:image/png;base64,${s.png.toString("base64")}" alt=""></div>`).join("");
|
|
436
|
-
|
|
437
|
-
try {
|
|
434
|
+
return withPage(undefined, async (pg) => {
|
|
438
435
|
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
|
|
440
|
-
}
|
|
441
|
-
await pg.close();
|
|
442
|
-
}
|
|
436
|
+
return pg.pdf({ preferCSSPageSize: true, printBackground: true });
|
|
437
|
+
});
|
|
443
438
|
}
|
|
444
439
|
|
|
445
440
|
/* ---------- Export ---------- */
|
|
@@ -449,7 +444,7 @@ async function pdfOf(shots, newPage) {
|
|
|
449
444
|
* scope: page (id or name) or boards ([file]); neither = everything. dryRun: build in memory and return the size only.
|
|
450
445
|
* Returns { kind, out, outRel, main, mainRel, files, bytes, skipped, deploy }.
|
|
451
446
|
*/
|
|
452
|
-
export async function exportDesign({ dir, out, store, format = "web", singleFile = false, page: pageId, boards: boardList, dryRun = false, now = new Date(),
|
|
447
|
+
export async function exportDesign({ dir, out, store, format = "web", singleFile = false, page: pageId, boards: boardList, dryRun = false, now = new Date(), withPage = sharedWithPage }) {
|
|
453
448
|
dir = path.resolve(dir);
|
|
454
449
|
if (!existsSync(path.join(dir, "screens"))) throw fail(400, `No screens/ folder in ${dir}`);
|
|
455
450
|
out = path.resolve(out ?? defaultOut(dir));
|
|
@@ -466,11 +461,11 @@ export async function exportDesign({ dir, out, store, format = "web", singleFile
|
|
|
466
461
|
let main;
|
|
467
462
|
|
|
468
463
|
if (kind === "pdf" || kind === "png") {
|
|
469
|
-
const status =
|
|
464
|
+
const status = withPage === sharedWithPage ? await browserStatus() : { ok: true };
|
|
470
465
|
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 })),
|
|
466
|
+
const shots = await renderBoards(dir, scope.boards.map((f) => ({ file: f, w: board.boards[f].w, h: board.boards[f].h })), withPage);
|
|
472
467
|
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,
|
|
468
|
+
else entries.push({ rel: `${slug(dir)}-canvas.pdf`, data: await pdfOf(shots, withPage) });
|
|
474
469
|
main = kind === "pdf" ? entries[0].rel : "png/";
|
|
475
470
|
} else {
|
|
476
471
|
const outInDir = out.startsWith(dir + path.sep) ? toPosix(path.relative(dir, out)) : null;
|
package/server/index.mjs
CHANGED
|
@@ -13,6 +13,7 @@ import { createBoardStore } from "./board.mjs";
|
|
|
13
13
|
import { isTrackedRel } from "./copies.mjs";
|
|
14
14
|
import { rootOf, toPosix } from "./fsutil.mjs";
|
|
15
15
|
import { createHistory, requestScope } from "./history.mjs";
|
|
16
|
+
import { contentHash } from "./livePatch.mjs";
|
|
16
17
|
import { createOccupancy } from "./occupancy.mjs";
|
|
17
18
|
import { writeEntry } from "./registry.mjs";
|
|
18
19
|
import { checkUpdate } from "./update.mjs";
|
|
@@ -91,8 +92,10 @@ export function safeJoin(root, rel) {
|
|
|
91
92
|
}
|
|
92
93
|
|
|
93
94
|
// When serving screen HTML, inject an error-collecting script into <head> (the file is untouched). The parent window (canvas) gathers them into the errored boards list
|
|
94
|
-
const
|
|
95
|
-
|
|
95
|
+
const PROBE_TAG = `<script data-dc-probe data-dc-src="@SRC@">(function(){var f=decodeURIComponent(location.pathname.replace(/^\\/screens\\//,""));function send(m){try{if(parent!==window)parent.postMessage(Object.assign({type:"dc-error",file:f},m),"*")}catch(e){}}send({start:true});addEventListener("error",function(e){var t=e.target;if(t&&t!==window&&(t.src||t.href)){send({kind:"resource",message:"Failed to load: "+(t.getAttribute("src")||t.getAttribute("href"))})}else{send({kind:"script",message:String(e.message||e),line:e.lineno,col:e.colno})}},true);addEventListener("unhandledrejection",function(e){send({kind:"script",message:"Promise: "+String(e.reason&&e.reason.message||e.reason)})});addEventListener("load",function(){send({loaded:true})});function tw(){var el=document.getElementById("board-tweaks");if(!el)return;try{var d=JSON.parse(el.textContent);for(var k in d){var t=d[k];if(!t||typeof t!=="object")continue;var v=t.type==="boolean"?(t.value?"1":"0"):String(t.value)+(t.type==="number"&&t.unit?t.unit:"");if(t.var)document.documentElement.style.setProperty(t.var,v);document.documentElement.setAttribute("data-tweak-"+k,t.type==="boolean"?(t.value?"on":"off"):String(t.value))}}catch(e){send({kind:"script",message:"board-tweaks JSON error: "+e.message})}}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",tw);else tw()})()</script>`;
|
|
96
|
+
/** src: the content hash of the file as served (data-dc-src), so the app knows which version of the file a board shows */
|
|
97
|
+
export function injectProbe(html, src = contentHash(html)) {
|
|
98
|
+
const PROBE = PROBE_TAG.replace("@SRC@", src);
|
|
96
99
|
const m = /<meta[^>]*charset[^>]*>/i.exec(html) ?? /<head[^>]*>/i.exec(html) ?? /<html[^>]*>/i.exec(html) ?? /<!doctype[^>]*>/i.exec(html);
|
|
97
100
|
return m ? html.slice(0, m.index + m[0].length) + PROBE + html.slice(m.index + m[0].length) : PROBE + html;
|
|
98
101
|
}
|