figma-lupa 0.2.0 → 0.2.2

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/dist/server.js CHANGED
@@ -42436,7 +42436,7 @@ var import_websocket_server = __toESM(require_websocket_server(), 1);
42436
42436
  // package.json
42437
42437
  var package_default = {
42438
42438
  name: "figma-lupa",
42439
- version: "0.2.0",
42439
+ version: "0.2.2",
42440
42440
  description: "Read-only Figma CLI, MCP server and plugin for pixel-faithful design-to-code with a small context footprint.",
42441
42441
  type: "module",
42442
42442
  license: "GPL-3.0-or-later",
@@ -42544,12 +42544,23 @@ var Bridge = class {
42544
42544
  waiters = /* @__PURE__ */ new Set();
42545
42545
  want;
42546
42546
  activeAt = Date.now();
42547
+ onStopRequest;
42548
+ version;
42549
+ /** Peer: the hub's version and whether it stops on request. */
42550
+ hubVersion;
42551
+ hubCanStop = false;
42547
42552
  constructor(opts = {}) {
42548
42553
  this.port = opts.port ?? Number(process.env.LUPA_PORT ?? DEFAULT_PORT);
42549
42554
  this.host = opts.host ?? "127.0.0.1";
42550
42555
  this.log = opts.log ?? (() => {
42551
42556
  });
42552
42557
  this.want = opts.role ?? "auto";
42558
+ this.onStopRequest = opts.onStopRequest;
42559
+ this.version = opts.version ?? SERVER_VERSION;
42560
+ }
42561
+ /** Peer: ask the hub to stop. Only `lupa serve` hubs (hubCanStop) do. */
42562
+ askHubToStop() {
42563
+ if (this.hubSocket?.readyState === import_websocket.default.OPEN) this.hubSocket.send(JSON.stringify({ t: "stop" }));
42553
42564
  }
42554
42565
  /** Milliseconds since this process last handled or forwarded a request. */
42555
42566
  get idleMs() {
@@ -42702,7 +42713,7 @@ var Bridge = class {
42702
42713
  ws.terminate();
42703
42714
  finish(false);
42704
42715
  }, 2e3);
42705
- ws.on("open", () => ws.send(JSON.stringify({ t: "hello", role: "peer", protocol: PROTOCOL_VERSION })));
42716
+ ws.on("open", () => ws.send(JSON.stringify({ t: "hello", role: "peer", protocol: PROTOCOL_VERSION, version: this.version })));
42706
42717
  ws.on("message", (data) => {
42707
42718
  let msg;
42708
42719
  try {
@@ -42712,6 +42723,8 @@ var Bridge = class {
42712
42723
  }
42713
42724
  if (msg.t === "welcome") {
42714
42725
  this.hubSocket = ws;
42726
+ this.hubVersion = msg.serverVersion;
42727
+ this.hubCanStop = msg.canStop === true;
42715
42728
  this.role = "peer";
42716
42729
  this.log("connected to hub as peer");
42717
42730
  finish(true);
@@ -42796,7 +42809,7 @@ var Bridge = class {
42796
42809
  } else {
42797
42810
  this.peers.add(ws);
42798
42811
  }
42799
- ws.send(JSON.stringify({ t: "welcome", role: msg.role, conn, serverVersion: SERVER_VERSION }));
42812
+ ws.send(JSON.stringify({ t: "welcome", role: msg.role, conn, serverVersion: this.version, canStop: !!this.onStopRequest }));
42800
42813
  if (msg.role === "peer") ws.send(JSON.stringify({ t: "plugins", plugins: this.list() }));
42801
42814
  return;
42802
42815
  }
@@ -42826,7 +42839,10 @@ var Bridge = class {
42826
42839
  }
42827
42840
  return;
42828
42841
  }
42829
- if (msg.t === "list") {
42842
+ if (msg.t === "stop") {
42843
+ this.log(this.onStopRequest ? "a newer Lupa asked this hub to stop" : "ignored a stop request (not a lupa serve hub)");
42844
+ this.onStopRequest?.();
42845
+ } else if (msg.t === "list") {
42830
42846
  ws.send(JSON.stringify({ t: "plugins", plugins: this.list() }));
42831
42847
  } else if (msg.t === "req") {
42832
42848
  let target;
@@ -44480,12 +44496,16 @@ function cachedChromiums() {
44480
44496
  }
44481
44497
  async function launch(chromium) {
44482
44498
  const attempts = [];
44483
- if (process.env.LUPA_BROWSER) attempts.push({ executablePath: process.env.LUPA_BROWSER });
44484
- attempts.push({}, ...cachedChromiums().map((p) => ({ executablePath: p })), { channel: "chrome" });
44499
+ if (process.env.LUPA_BROWSER) attempts.push({ executablePath: process.env.LUPA_BROWSER, label: `LUPA_BROWSER (${process.env.LUPA_BROWSER})` });
44500
+ attempts.push(
44501
+ { label: "Playwright's Chromium" },
44502
+ ...cachedChromiums().map((p) => ({ executablePath: p, label: `Playwright's Chromium (${p})` })),
44503
+ { channel: "chrome", label: "Google Chrome" }
44504
+ );
44485
44505
  const errors = [];
44486
- for (const a of attempts) {
44506
+ for (const { label, ...a } of attempts) {
44487
44507
  try {
44488
- return await chromium.launch({ ...a, headless: true });
44508
+ return { browser: await chromium.launch({ ...a, headless: true }), label };
44489
44509
  } catch (e) {
44490
44510
  errors.push(`${a.executablePath ?? a.channel ?? "bundled"}: ${String(e.message).split("\n")[0]}`);
44491
44511
  }
@@ -44550,7 +44570,7 @@ async function serveFile(url2) {
44550
44570
  async function renderUrl(opts) {
44551
44571
  const served = opts.url.startsWith("file:") ? await serveFile(opts.url) : void 0;
44552
44572
  try {
44553
- const browser = await launch(await loadChromium());
44573
+ const { browser } = await launch(await loadChromium());
44554
44574
  try {
44555
44575
  const page = await browser.newPage({
44556
44576
  viewport: { width: Math.round(opts.width), height: opts.height ?? 900 },
@@ -44582,7 +44602,7 @@ async function renderSvg(svg, o) {
44582
44602
  const file2 = path.join(dir, `render-${process.pid}-${Date.now()}.svg`);
44583
44603
  await writeFile(file2, svg);
44584
44604
  try {
44585
- const browser = await launch(await loadChromium());
44605
+ const { browser } = await launch(await loadChromium());
44586
44606
  try {
44587
44607
  const page = await browser.newPage({
44588
44608
  viewport: { width: Math.ceil(o.width), height: Math.ceil(o.height) },
@@ -44603,7 +44623,7 @@ function formatStatus(plugins, role, port) {
44603
44623
  if (!plugins.length) {
44604
44624
  return [
44605
44625
  `Lupa ${role} on port ${port}. No Figma file connected.`,
44606
- "In Figma: open the file \u2192 Plugins \u2192 Development \u2192 Lupa (import plugin/manifest.json once). Keep the plugin window open."
44626
+ "In Figma: open the file \u2192 Plugins \u2192 Development \u2192 Lupa. Keep the plugin window open. Not in the list yet? lupa setup shows the manifest to import once."
44607
44627
  ].join("\n");
44608
44628
  }
44609
44629
  const lines = [`Lupa ${role} on port ${port}. Connected files (most recently active first):`];
@@ -44740,9 +44760,11 @@ import { mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2 } from
44740
44760
  import path3 from "node:path";
44741
44761
 
44742
44762
  // src/tools/project.ts
44763
+ import { execFile } from "node:child_process";
44743
44764
  import { readdir, readFile as readFile2 } from "node:fs/promises";
44744
44765
  import os2 from "node:os";
44745
44766
  import path2 from "node:path";
44767
+ import { promisify } from "node:util";
44746
44768
  var TEXT_PROPS = /^(font(-[\w-]+)?|line-height|letter-spacing|text-transform|text-decoration[\w-]*|color|-webkit-font-smoothing|-moz-osx-font-smoothing|text-rendering)$/;
44747
44769
  var SKIP_DIRS = /* @__PURE__ */ new Set([
44748
44770
  "node_modules",
@@ -44759,47 +44781,68 @@ var SKIP_DIRS = /* @__PURE__ */ new Set([
44759
44781
  "Pods",
44760
44782
  "DerivedData",
44761
44783
  "tmp",
44762
- "temp"
44784
+ "temp",
44785
+ "_build",
44786
+ "deps"
44763
44787
  ]);
44764
44788
  var STYLE = /\.(css|scss|sass|less|styl|pcss)$/i;
44765
44789
  var COMPONENT_FILE = /\.(tsx|jsx|vue|svelte|astro)$/i;
44766
44790
  var NOT_COMPONENT = /^(index|page|layout|main|app|route|\+page|\+layout)$|\.(test|spec|stories|story)$/i;
44767
44791
  var MAX_ENTRIES = 3e4;
44768
44792
  var MAX_MS = 2e3;
44769
- async function scanProject(root, exclude = []) {
44793
+ var MAX_STYLES = 600;
44794
+ var MAX_SVGS = 3e3;
44795
+ async function scanProject(root, exclude = [], maxEntries = MAX_ENTRIES) {
44770
44796
  root = path2.resolve(root);
44771
44797
  if (root === path2.parse(root).root || root === os2.homedir()) return void 0;
44772
- const skip = new Set(exclude.map((e) => path2.resolve(e)));
44798
+ const skip = [...new Set(exclude.map((e) => path2.resolve(e)))];
44773
44799
  const styles = [];
44774
44800
  const svgs = [];
44775
44801
  const comps = [];
44776
- const started = Date.now();
44777
- let entries = 0;
44778
- const walk = async (dir, depth) => {
44779
- if (depth > 10 || entries > MAX_ENTRIES || Date.now() - started > MAX_MS) return;
44780
- let list;
44781
- try {
44782
- list = await readdir(dir, { withFileTypes: true });
44783
- } catch {
44784
- return;
44802
+ const shown = (p) => path2.relative(process.cwd(), p).split(path2.sep).join("/");
44803
+ let incomplete;
44804
+ const sort = (p) => {
44805
+ const name = path2.basename(p);
44806
+ if (STYLE.test(name)) styles.push(p);
44807
+ else if (/\.svg$/i.test(name)) svgs.push(p);
44808
+ else if (COMPONENT_FILE.test(name)) comps.push(p);
44809
+ };
44810
+ const skipped = (p) => skip.some((s) => p === s || p.startsWith(s + path2.sep));
44811
+ const tracked = await gitFiles(root);
44812
+ if (tracked?.length) {
44813
+ for (const p of tracked) {
44814
+ const dirs = path2.relative(root, p).split(path2.sep).slice(0, -1);
44815
+ if (!dirs.some((d) => d.startsWith(".") || SKIP_DIRS.has(d)) && !skipped(p)) sort(p);
44785
44816
  }
44786
- entries += list.length;
44787
- list.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
44788
- for (const e of list) {
44789
- const p = path2.join(dir, e.name);
44790
- if (e.isDirectory()) {
44791
- if (!e.name.startsWith(".") && !SKIP_DIRS.has(e.name) && !skip.has(p)) await walk(p, depth + 1);
44792
- } else if (e.isFile()) {
44793
- if (STYLE.test(e.name)) styles.push(p);
44794
- else if (/\.svg$/i.test(e.name)) svgs.push(p);
44795
- else if (COMPONENT_FILE.test(e.name)) comps.push(p);
44817
+ } else {
44818
+ const started = Date.now();
44819
+ let entries = 0;
44820
+ const walk = async (dir, depth) => {
44821
+ if (depth > 10) return;
44822
+ if (entries > maxEntries || Date.now() - started > MAX_MS) {
44823
+ incomplete ??= `stopped after ${entries > maxEntries ? `${maxEntries} entries` : `${MAX_MS / 1e3}s`}, before ${shown(dir) || "."}`;
44824
+ return;
44796
44825
  }
44797
- }
44798
- };
44799
- await walk(root, 0);
44826
+ let list;
44827
+ try {
44828
+ list = await readdir(dir, { withFileTypes: true });
44829
+ } catch {
44830
+ return;
44831
+ }
44832
+ entries += list.length;
44833
+ list.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
44834
+ for (const e of list) {
44835
+ const p = path2.join(dir, e.name);
44836
+ if (e.isDirectory()) {
44837
+ if (!e.name.startsWith(".") && !SKIP_DIRS.has(e.name) && !skipped(p)) await walk(p, depth + 1);
44838
+ } else if (e.isFile()) sort(p);
44839
+ }
44840
+ };
44841
+ await walk(root, 0);
44842
+ }
44843
+ if (styles.length > MAX_STYLES) incomplete ??= `read only the first ${MAX_STYLES} of ${styles.length} stylesheets`;
44800
44844
  const idx = { colors: /* @__PURE__ */ new Map(), fonts: /* @__PURE__ */ new Map(), icons: /* @__PURE__ */ new Map(), components: /* @__PURE__ */ new Map(), textStyles: [] };
44801
44845
  const rules = [];
44802
- const shown = (p) => path2.relative(process.cwd(), p).split(path2.sep).join("/");
44803
44846
  const add = (m, key, ref2) => {
44804
44847
  const list = m.get(key) ?? [];
44805
44848
  if (!list.includes(ref2)) list.push(ref2);
@@ -44807,7 +44850,7 @@ async function scanProject(root, exclude = []) {
44807
44850
  };
44808
44851
  const vars = /* @__PURE__ */ new Map();
44809
44852
  const classes = /* @__PURE__ */ new Map();
44810
- for (const f of styles.slice(0, 600)) {
44853
+ for (const f of styles.slice(0, MAX_STYLES)) {
44811
44854
  const css = await readText(f, 1e6);
44812
44855
  if (!css) continue;
44813
44856
  const text2 = css.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "");
@@ -44869,7 +44912,7 @@ async function scanProject(root, exclude = []) {
44869
44912
  const t = textStyle(r.decls, family);
44870
44913
  if (t) idx.textStyles.push({ ...t, ref: `.${r.cls} (${r.file})` });
44871
44914
  }
44872
- for (const f of svgs.slice(0, 3e3)) {
44915
+ for (const f of svgs.slice(0, MAX_SVGS)) {
44873
44916
  const svg = await readText(f, 64e3);
44874
44917
  const s = svg && shapeOf(svg);
44875
44918
  if (!s) continue;
@@ -44884,8 +44927,29 @@ async function scanProject(root, exclude = []) {
44884
44927
  add(idx.components, slug2(stem), shown(f));
44885
44928
  }
44886
44929
  for (const [c, f] of classes) add(idx.components, c.toLowerCase(), `.${c} (${f})`);
44930
+ if (svgs.length > MAX_SVGS) incomplete ??= `read only the first ${MAX_SVGS} of ${svgs.length} SVG files`;
44931
+ if (incomplete) idx.incomplete = `project scan of ${shown(root) || "."} ${incomplete}`;
44887
44932
  const empty = !idx.colors.size && !idx.fonts.size && !idx.icons.size && !idx.components.size && !idx.textStyles.length;
44888
- return empty ? void 0 : idx;
44933
+ return empty && !incomplete ? void 0 : idx;
44934
+ }
44935
+ async function gitFiles(root) {
44936
+ try {
44937
+ const { stdout } = await promisify(execFile)("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], {
44938
+ cwd: root,
44939
+ maxBuffer: 256 * 1024 * 1024,
44940
+ timeout: 1e4
44941
+ });
44942
+ return stdout.split("\0").filter(Boolean).map((f) => path2.join(root, f));
44943
+ } catch {
44944
+ return void 0;
44945
+ }
44946
+ }
44947
+ function withScanNote(text2, idx) {
44948
+ if (!idx?.incomplete) return text2;
44949
+ return `${text2}
44950
+
44951
+ ## project scan incomplete
44952
+ ${idx.incomplete}: a colour, font, icon or component without a project match may still exist, so search the code before adding a copy`;
44889
44953
  }
44890
44954
  function firstFamily(stack) {
44891
44955
  return stack.split(",")[0].trim().replace(/^["']|["']$/g, "").toLowerCase();
@@ -45973,14 +46037,14 @@ var Lupa = class {
45973
46037
  if (!snap.roots.length) throw new Error(`Nothing found for ${r.ids.join(", ")}${snap.missing.length ? " (not in this file, or deleted)" : ""}`);
45974
46038
  const index = await scan;
45975
46039
  const opts = { budget: o.budget ?? 8e3, components: o.components ?? "auto", project: index && projectHints(index) };
45976
- if (!o.assetsDir) return renderSnapshot(snap, opts).text;
46040
+ if (!o.assetsDir) return withScanNote(renderSnapshot(snap, opts).text, index);
45977
46041
  const defs = printedDefs(snap, opts.components);
45978
46042
  const written = await writeAssets(this.bridge, snap, r.file, { dir: o.assetsDir, currentColor: o.currentColor, defs, project: index });
45979
46043
  const text2 = renderSnapshot(snap, { ...opts, files: { ...written, dir: o.assetsDir } }).text;
45980
- return written.failures.length ? `${text2}
46044
+ return withScanNote(written.failures.length ? `${text2}
45981
46045
 
45982
46046
  ## asset export failures
45983
- ${written.failures.join("\n")}` : text2;
46047
+ ${written.failures.join("\n")}` : text2, index);
45984
46048
  }
45985
46049
  async screenshot(o) {
45986
46050
  const r = await this.resolve(o.target, o.file);
@@ -45990,7 +46054,8 @@ ${written.failures.join("\n")}` : text2;
45990
46054
  const r = await this.resolve(o.target, o.file);
45991
46055
  const dir = o.dir ?? "figma-assets";
45992
46056
  const project = o.as === "auto" || !o.as ? await scanProject(process.cwd(), [dir]).catch(() => void 0) : void 0;
45993
- return exportAssets(this.bridge, r.ids, r.file, { dir, as: o.as ?? "auto", scale: o.scale, currentColor: o.currentColor, project });
46057
+ const text2 = await exportAssets(this.bridge, r.ids, r.file, { dir, as: o.as ?? "auto", scale: o.scale, currentColor: o.currentColor, project });
46058
+ return withScanNote(text2, project);
45994
46059
  }
45995
46060
  async tokens(o) {
45996
46061
  await this.connect();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "figma-lupa",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Read-only Figma CLI, MCP server and plugin for pixel-faithful design-to-code with a small context footprint.",
5
5
  "type": "module",
6
6
  "license": "GPL-3.0-or-later",
@@ -1118,7 +1118,7 @@
1118
1118
  t: "hello",
1119
1119
  role: "plugin",
1120
1120
  protocol: PROTOCOL_VERSION,
1121
- pluginVersion: "0.2.0",
1121
+ pluginVersion: "0.2.2",
1122
1122
  fileKey: fileKey(),
1123
1123
  editorType: figma.editorType
1124
1124
  }, state());
@@ -7,8 +7,9 @@ description: Implement a Figma frame or component faithfully in code with the `l
7
7
 
8
8
  `lupa` reads the live Figma file through the Lupa plugin, and it is read-only. If the first command fails:
9
9
 
10
- - **"command not found":** ask the user to run `npm link` in the Lupa folder.
10
+ - **"command not found":** ask the user to install Lupa with `npm install -g figma-lupa && lupa setup`.
11
11
  - **No file connected:** ask the user to open the file in Figma, run *Plugins → Development → Lupa*, and keep the plugin window open.
12
+ - **A line starting with `lupa:`** (a newer Lupa, or a plugin on another version): pass it on to the user when you report back. Don't update Lupa yourself.
12
13
 
13
14
  The target is a Figma URL (in quotes, because it contains `&`), node ids like `12:34`, or nothing for the current selection. When a session also has the Lupa MCP tools (`get_design`, …), they take the same options.
14
15