cursor-canvas-export 0.1.0 → 0.1.1

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.
Files changed (3) hide show
  1. package/README.md +8 -5
  2. package/dist/cli.js +197 -27
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,10 +1,11 @@
1
1
  # cursor-canvas-export
2
2
 
3
- Export a Cursor canvas (`.canvas.tsx`) to a self-contained HTML file and a one-page PDF.
3
+ [![npm](https://img.shields.io/npm/v/cursor-canvas-export.svg)](https://www.npmjs.com/package/cursor-canvas-export)
4
+ [![Add to Cursor](https://img.shields.io/badge/Add_to_Cursor-111111?logo=cursor&logoColor=white)](https://cursor.com/install-mcp?name=canvas-export&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImN1cnNvci1jYW52YXMtZXhwb3J0IiwibWNwIl19)
4
5
 
5
- HTML is the rendered page. The PDF is that page printed by headless Chromium, so colors, type, tables, and charts stay together. Nothing opens on screen. The page is one continuous sheet the width of the canvas panel.
6
+ Command-line tool and MCP server. It exports a Cursor canvas (`.canvas.tsx`) to a self-contained HTML file and a one-page PDF.
6
7
 
7
- The same tool is published for agents as an MCP server.
8
+ HTML is the rendered page. The PDF is that page printed by headless Chromium, so colors, type, tables, and charts stay together. Nothing opens on screen. The page is one continuous sheet the width of the canvas panel.
8
9
 
9
10
  ## Install
10
11
 
@@ -15,7 +16,7 @@ npm install
15
16
  npx playwright install chromium
16
17
  ```
17
18
 
18
- The first export downloads Chromium if it is not cached yet. Later runs reuse that copy on Windows, macOS, and Linux.
19
+ The first export downloads Chromium if it is not cached yet. On the command line that download happens inside the command. The MCP tools return immediately and ask for a short wait while the download continues in the background. Later runs reuse that copy on Windows, macOS, and Linux.
19
20
 
20
21
  ## Command line
21
22
 
@@ -64,7 +65,7 @@ Add this to `~/.cursor/mcp.json`:
64
65
  }
65
66
  ```
66
67
 
67
- [Add to Cursor](https://cursor.com/install-mcp?name=canvas-export&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImN1cnNvci1jYW52YXMtZXhwb3J0IiwibWNwIl19)
68
+ <a href="https://cursor.com/install-mcp?name=canvas-export&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImN1cnNvci1jYW52YXMtZXhwb3J0IiwibWNwIl19"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/deeplink/mcp-install-dark.svg"><img alt="Add to Cursor" src="https://cursor.com/deeplink/mcp-install-light.svg"></picture></a>
68
69
 
69
70
  The server exposes three tools:
70
71
 
@@ -76,6 +77,8 @@ The server exposes three tools:
76
77
 
77
78
  Ask the agent to export a canvas. It calls the tool and returns the file paths.
78
79
 
80
+ The first time Chromium is not cached, `export_canvas` and `preview_canvas` return at once and tell the agent to wait about 30 seconds, then call the same tool again with the same arguments. That reply is not a failed export. The file appears when a later call returns the output paths.
81
+
79
82
  ## How it works
80
83
 
81
84
  A canvas only imports `cursor/canvas`. This package bundles the file with esbuild against a local implementation of that SDK, mounts it in headless Chromium, and saves the DOM. Chart colors and the type scale come from the public canvas tokens.
package/dist/cli.js CHANGED
@@ -17,20 +17,46 @@ import { createRequire } from "node:module";
17
17
  import path from "node:path";
18
18
  import { chromium } from "playwright";
19
19
  var require2 = createRequire(import.meta.url);
20
+ var BrowserNotReady = class extends Error {
21
+ gate;
22
+ constructor(gate) {
23
+ super(gate.state === "failed" ? gate.message : "Chromium is still downloading");
24
+ this.name = "BrowserNotReady";
25
+ this.gate = gate;
26
+ }
27
+ };
20
28
  var browserPromise;
21
29
  var users = 0;
22
30
  var hold = false;
31
+ var phase = "idle";
32
+ var failureMessage = "";
33
+ var downloadListeners = [];
34
+ var forcedGate;
35
+ var launchGeneration = 0;
36
+ var installChild;
23
37
  function holdBrowserProcess() {
24
38
  hold = true;
25
39
  }
40
+ function warmBrowser() {
41
+ if (forcedGate) return;
42
+ if (phase === "failed" || browserPromise) return;
43
+ startLaunch();
44
+ }
45
+ function browserGate() {
46
+ if (forcedGate) return Promise.resolve(forcedGate);
47
+ if (phase === "failed") {
48
+ const message = failureMessage;
49
+ startLaunch();
50
+ return Promise.resolve({ state: "failed", message });
51
+ }
52
+ if (phase === "downloading") return Promise.resolve({ state: "downloading" });
53
+ if (!browserPromise) startLaunch();
54
+ if (phase === "ready") return Promise.resolve({ state: "ready" });
55
+ return waitForLaunch(browserPromise);
56
+ }
26
57
  function acquireBrowser() {
27
58
  users += 1;
28
- if (!browserPromise) {
29
- browserPromise = launchChromium().catch((error) => {
30
- browserPromise = void 0;
31
- throw error;
32
- });
33
- }
59
+ if (!browserPromise) startLaunch();
34
60
  return browserPromise;
35
61
  }
36
62
  async function releaseBrowser() {
@@ -41,24 +67,100 @@ async function closeBrowser() {
41
67
  hold = false;
42
68
  if (users === 0) await shutdown();
43
69
  }
70
+ function startLaunch() {
71
+ if (browserPromise) return browserPromise;
72
+ const generation = launchGeneration;
73
+ phase = "launching";
74
+ failureMessage = "";
75
+ const pending = launchChromium(generation).then(
76
+ (browser) => {
77
+ if (browserPromise === pending) phase = "ready";
78
+ return browser;
79
+ },
80
+ (error) => {
81
+ if (browserPromise !== pending) throw error;
82
+ browserPromise = void 0;
83
+ phase = "failed";
84
+ failureMessage = error instanceof Error ? error.message : String(error);
85
+ throw error;
86
+ }
87
+ );
88
+ void pending.catch(() => {
89
+ });
90
+ browserPromise = pending;
91
+ return pending;
92
+ }
93
+ function waitForLaunch(pending) {
94
+ return new Promise((resolve) => {
95
+ let settled = false;
96
+ const finish = (gate) => {
97
+ if (settled) return;
98
+ settled = true;
99
+ downloadListeners = downloadListeners.filter((listener) => listener !== onDownload);
100
+ resolve(gate);
101
+ };
102
+ const onDownload = () => finish({ state: "downloading" });
103
+ downloadListeners.push(onDownload);
104
+ if (phase === "downloading") {
105
+ finish({ state: "downloading" });
106
+ return;
107
+ }
108
+ pending.then(
109
+ () => finish({ state: "ready" }),
110
+ (error) => {
111
+ const message = failureMessage || (error instanceof Error ? error.message : String(error));
112
+ const alreadySettled = settled;
113
+ finish({ state: "failed", message });
114
+ if (!alreadySettled && phase === "failed" && !browserPromise) startLaunch();
115
+ }
116
+ );
117
+ });
118
+ }
119
+ function notifyDownloading() {
120
+ phase = "downloading";
121
+ const listeners = downloadListeners;
122
+ downloadListeners = [];
123
+ for (const listener of listeners) listener();
124
+ }
44
125
  async function shutdown() {
45
126
  if (users > 0 || hold || !browserPromise) return;
127
+ launchGeneration += 1;
128
+ stopInstallChild();
46
129
  const pending = browserPromise;
130
+ const wasReady = phase === "ready";
47
131
  browserPromise = void 0;
132
+ downloadListeners = [];
133
+ if (!wasReady) {
134
+ phase = "idle";
135
+ failureMessage = "";
136
+ return;
137
+ }
48
138
  const browser = await pending.catch(() => void 0);
49
139
  if (users > 0 && browser) {
50
140
  browserPromise = Promise.resolve(browser);
141
+ phase = "ready";
51
142
  return;
52
143
  }
53
144
  await browser?.close().catch(() => {
54
145
  });
146
+ if (!browserPromise && phase !== "failed") phase = "idle";
55
147
  }
56
- async function launchChromium() {
148
+ async function launchChromium(generation) {
57
149
  try {
58
- return await chromium.launch({ headless: true });
150
+ const browser = await chromium.launch({ headless: true });
151
+ if (generation !== launchGeneration) {
152
+ await browser.close().catch(() => {
153
+ });
154
+ throw new Error("browser launch cancelled");
155
+ }
156
+ return browser;
59
157
  } catch (error) {
158
+ if (generation !== launchGeneration) throw error;
60
159
  if (!isMissingBrowser(error)) throw error;
160
+ notifyDownloading();
161
+ if (generation !== launchGeneration) throw new Error("browser launch cancelled");
61
162
  await installChromium();
163
+ if (generation !== launchGeneration) throw new Error("browser launch cancelled");
62
164
  return await chromium.launch({ headless: true });
63
165
  }
64
166
  }
@@ -73,15 +175,34 @@ function installChromium() {
73
175
  const child = spawn(process.execPath, [cli, "install", "chromium"], {
74
176
  stdio: ["ignore", "pipe", "pipe"]
75
177
  });
178
+ installChild = child;
179
+ let settled = false;
180
+ const finish = (error) => {
181
+ if (settled) return;
182
+ settled = true;
183
+ if (installChild === child) installChild = void 0;
184
+ if (error) reject(error);
185
+ else resolve();
186
+ };
76
187
  child.stdout.on("data", (chunk) => process.stderr.write(chunk));
77
188
  child.stderr.on("data", (chunk) => process.stderr.write(chunk));
78
- child.on("error", reject);
189
+ child.on("error", (error) => finish(error));
79
190
  child.on("close", (code) => {
80
- if (code === 0) resolve();
81
- else reject(new Error(`playwright install chromium exited with code ${code ?? "unknown"}`));
191
+ if (code === 0) finish();
192
+ else finish(new Error(`playwright install chromium exited with code ${code ?? "unknown"}`));
82
193
  });
83
194
  });
84
195
  }
196
+ function stopInstallChild() {
197
+ const child = installChild;
198
+ installChild = void 0;
199
+ if (!child?.pid || child.killed) return;
200
+ if (process.platform === "win32") {
201
+ spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
202
+ return;
203
+ }
204
+ child.kill("SIGKILL");
205
+ }
85
206
 
86
207
  // src/sdk/tokens.ts
87
208
  var chartPalette = {
@@ -323,6 +444,10 @@ async function convert(options) {
323
444
  <script>${script}</script>
324
445
  </body>
325
446
  </html>`;
447
+ if (options.deferBrowser) {
448
+ const gate = await browserGate();
449
+ if (gate.state !== "ready") throw new BrowserNotReady(gate);
450
+ }
326
451
  const browser = await acquireBrowser();
327
452
  let page;
328
453
  try {
@@ -531,9 +656,16 @@ function slug(value) {
531
656
  // src/mcp.ts
532
657
  var themeSchema = z.enum(["dark", "light"]).describe("Canvas theme. Defaults to dark.");
533
658
  var widthSchema = z.number().int().min(320).optional().describe("Page width in pixels. Defaults to 800.");
659
+ var browserWait = "If the result tells you to wait because Chromium is downloading, that is not an error. Wait about 30 seconds and call this tool again with the same arguments. Nothing is written until a later call finishes the render.";
534
660
  function createServer() {
535
661
  holdBrowserProcess();
536
- const server = new McpServer({ name: "cursor-canvas-export", version: "0.1.0" });
662
+ warmBrowser();
663
+ const server = new McpServer(
664
+ { name: "cursor-canvas-export", version: "0.1.1" },
665
+ {
666
+ instructions: "If export_canvas or preview_canvas tells you to wait because Chromium is downloading, that is not an error. Wait about 30 seconds and call the same tool again with the same arguments. The file or preview is ready only when that later call returns it."
667
+ }
668
+ );
537
669
  server.registerTool(
538
670
  "list_canvases",
539
671
  {
@@ -554,7 +686,7 @@ function createServer() {
554
686
  "export_canvas",
555
687
  {
556
688
  title: "Export canvas",
557
- description: "Render a Cursor canvas to HTML and/or a one-page PDF. Pass a full path or a canvas name. Files are written next to the canvas unless out is set. Returns output paths, page size, and warnings. The browser runs headless.",
689
+ description: `Render a Cursor canvas to HTML and/or a one-page PDF. Pass a full path or a canvas name. Files are written next to the canvas unless out is set. Returns output paths, page size, and warnings. The browser runs headless. ${browserWait}`,
558
690
  inputSchema: {
559
691
  canvas: z.string().describe("Absolute path to a .canvas.tsx file, or its name without the extension."),
560
692
  format: z.enum(["html", "pdf", "both"]).optional().describe("Defaults to both."),
@@ -566,13 +698,21 @@ function createServer() {
566
698
  async ({ canvas, format, theme, width, out }) => {
567
699
  const resolved = resolveCanvas(canvas);
568
700
  if (!resolved.match) return unresolvedCanvas(canvas, resolved.matches);
569
- const result = await convert({
570
- input: resolved.match.path,
571
- out,
572
- format: format ?? "both",
573
- theme,
574
- width
575
- });
701
+ let result;
702
+ try {
703
+ result = await convert({
704
+ input: resolved.match.path,
705
+ out,
706
+ format: format ?? "both",
707
+ theme,
708
+ width,
709
+ deferBrowser: true
710
+ });
711
+ } catch (error) {
712
+ const waiting = browserWaitReply("export_canvas", error);
713
+ if (waiting) return waiting;
714
+ throw error;
715
+ }
576
716
  const lines = [
577
717
  result.html ? `html: ${result.html}` : "",
578
718
  result.pdf ? `pdf: ${result.pdf}` : "",
@@ -586,7 +726,7 @@ function createServer() {
586
726
  "preview_canvas",
587
727
  {
588
728
  title: "Preview canvas",
589
- description: "Render a canvas and return a PNG of the page so you can check layout before handing the file over. Tall pages are clipped to the top 1600px. Nothing is written next to the canvas.",
729
+ description: `Render a canvas and return a PNG of the page so you can check layout before handing the file over. Tall pages are clipped to the top 1600px. Nothing is written next to the canvas. ${browserWait}`,
590
730
  inputSchema: {
591
731
  canvas: z.string().describe("Absolute path to a .canvas.tsx file, or its name without the extension."),
592
732
  theme: themeSchema.optional(),
@@ -596,12 +736,20 @@ function createServer() {
596
736
  async ({ canvas, theme, width }) => {
597
737
  const resolved = resolveCanvas(canvas);
598
738
  if (!resolved.match) return unresolvedCanvas(canvas, resolved.matches);
599
- const result = await convert({
600
- input: resolved.match.path,
601
- preview: true,
602
- theme,
603
- width
604
- });
739
+ let result;
740
+ try {
741
+ result = await convert({
742
+ input: resolved.match.path,
743
+ preview: true,
744
+ theme,
745
+ width,
746
+ deferBrowser: true
747
+ });
748
+ } catch (error) {
749
+ const waiting = browserWaitReply("preview_canvas", error);
750
+ if (waiting) return waiting;
751
+ throw error;
752
+ }
605
753
  const note = result.previewClipped ? `Preview clipped to the top 1600px of a ${result.height}px page.` : `Preview of ${resolved.match.name}, ${result.width}x${result.height}px.`;
606
754
  return {
607
755
  content: [
@@ -633,6 +781,28 @@ function unresolvedCanvas(canvas, matches) {
633
781
  ${matches.map((hit) => hit.path).join("\n")}`
634
782
  );
635
783
  }
784
+ function browserWaitReply(tool, error) {
785
+ if (!(error instanceof BrowserNotReady)) return;
786
+ return text(error.gate.state === "downloading" ? downloadingMessage(tool) : failedDownloadMessage(tool, error.gate.message));
787
+ }
788
+ function downloadingMessage(tool) {
789
+ const until = tool === "export_canvas" ? "it returns the output paths" : "it returns the preview image";
790
+ return [
791
+ `Wait about 30 seconds, then call ${tool} again with the same arguments. Chromium is still downloading.`,
792
+ "This is not an error. The canvas and the arguments are fine. Nothing was rendered or written yet.",
793
+ "The download is already running. Calling the tool again does not start a second download.",
794
+ `After waiting, call ${tool} once more with the same arguments. Repeat until ${until}.`
795
+ ].join("\n");
796
+ }
797
+ function failedDownloadMessage(tool, message) {
798
+ return [
799
+ `Chromium download failed: ${message}`,
800
+ `Wait about 30 seconds, then call ${tool} again with the same arguments. A new download is already running.`,
801
+ "This is not a problem with the canvas or the arguments.",
802
+ "If the same failure comes back, install Chromium from a terminal and call the tool again:",
803
+ "npx playwright install chromium"
804
+ ].join("\n");
805
+ }
636
806
  function text(value) {
637
807
  return { content: [{ type: "text", text: value }] };
638
808
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursor-canvas-export",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Export a Cursor canvas to HTML and a one-page PDF. Headless, for agents and the command line.",
5
5
  "license": "MIT",
6
6
  "type": "module",