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/cli.js CHANGED
@@ -2276,7 +2276,7 @@ var require_websocket = __commonJS({
2276
2276
  var EventEmitter = __require("events");
2277
2277
  var https = __require("https");
2278
2278
  var http = __require("http");
2279
- var net = __require("net");
2279
+ var net2 = __require("net");
2280
2280
  var tls = __require("tls");
2281
2281
  var { randomBytes, createHash } = __require("crypto");
2282
2282
  var { Duplex, Readable } = __require("stream");
@@ -3033,12 +3033,12 @@ var require_websocket = __commonJS({
3033
3033
  }
3034
3034
  function netConnect(options) {
3035
3035
  options.path = options.socketPath;
3036
- return net.connect(options);
3036
+ return net2.connect(options);
3037
3037
  }
3038
3038
  function tlsConnect(options) {
3039
3039
  options.path = void 0;
3040
3040
  if (!options.servername && options.servername !== "") {
3041
- options.servername = net.isIP(options.host) ? "" : options.host;
3041
+ options.servername = net2.isIP(options.host) ? "" : options.host;
3042
3042
  }
3043
3043
  return tls.connect(options);
3044
3044
  }
@@ -3743,7 +3743,7 @@ var init_package = __esm({
3743
3743
  "package.json"() {
3744
3744
  package_default = {
3745
3745
  name: "figma-lupa",
3746
- version: "0.2.0",
3746
+ version: "0.2.2",
3747
3747
  description: "Read-only Figma CLI, MCP server and plugin for pixel-faithful design-to-code with a small context footprint.",
3748
3748
  type: "module",
3749
3749
  license: "GPL-3.0-or-later",
@@ -3867,12 +3867,23 @@ var init_hub = __esm({
3867
3867
  waiters = /* @__PURE__ */ new Set();
3868
3868
  want;
3869
3869
  activeAt = Date.now();
3870
+ onStopRequest;
3871
+ version;
3872
+ /** Peer: the hub's version and whether it stops on request. */
3873
+ hubVersion;
3874
+ hubCanStop = false;
3870
3875
  constructor(opts = {}) {
3871
3876
  this.port = opts.port ?? Number(process.env.LUPA_PORT ?? DEFAULT_PORT);
3872
3877
  this.host = opts.host ?? "127.0.0.1";
3873
3878
  this.log = opts.log ?? (() => {
3874
3879
  });
3875
3880
  this.want = opts.role ?? "auto";
3881
+ this.onStopRequest = opts.onStopRequest;
3882
+ this.version = opts.version ?? SERVER_VERSION;
3883
+ }
3884
+ /** Peer: ask the hub to stop. Only `lupa serve` hubs (hubCanStop) do. */
3885
+ askHubToStop() {
3886
+ if (this.hubSocket?.readyState === import_websocket.default.OPEN) this.hubSocket.send(JSON.stringify({ t: "stop" }));
3876
3887
  }
3877
3888
  /** Milliseconds since this process last handled or forwarded a request. */
3878
3889
  get idleMs() {
@@ -4025,7 +4036,7 @@ var init_hub = __esm({
4025
4036
  ws.terminate();
4026
4037
  finish(false);
4027
4038
  }, 2e3);
4028
- ws.on("open", () => ws.send(JSON.stringify({ t: "hello", role: "peer", protocol: PROTOCOL_VERSION })));
4039
+ ws.on("open", () => ws.send(JSON.stringify({ t: "hello", role: "peer", protocol: PROTOCOL_VERSION, version: this.version })));
4029
4040
  ws.on("message", (data) => {
4030
4041
  let msg;
4031
4042
  try {
@@ -4035,6 +4046,8 @@ var init_hub = __esm({
4035
4046
  }
4036
4047
  if (msg.t === "welcome") {
4037
4048
  this.hubSocket = ws;
4049
+ this.hubVersion = msg.serverVersion;
4050
+ this.hubCanStop = msg.canStop === true;
4038
4051
  this.role = "peer";
4039
4052
  this.log("connected to hub as peer");
4040
4053
  finish(true);
@@ -4119,7 +4132,7 @@ var init_hub = __esm({
4119
4132
  } else {
4120
4133
  this.peers.add(ws);
4121
4134
  }
4122
- ws.send(JSON.stringify({ t: "welcome", role: msg.role, conn, serverVersion: SERVER_VERSION }));
4135
+ ws.send(JSON.stringify({ t: "welcome", role: msg.role, conn, serverVersion: this.version, canStop: !!this.onStopRequest }));
4123
4136
  if (msg.role === "peer") ws.send(JSON.stringify({ t: "plugins", plugins: this.list() }));
4124
4137
  return;
4125
4138
  }
@@ -4149,7 +4162,10 @@ var init_hub = __esm({
4149
4162
  }
4150
4163
  return;
4151
4164
  }
4152
- if (msg.t === "list") {
4165
+ if (msg.t === "stop") {
4166
+ this.log(this.onStopRequest ? "a newer Lupa asked this hub to stop" : "ignored a stop request (not a lupa serve hub)");
4167
+ this.onStopRequest?.();
4168
+ } else if (msg.t === "list") {
4153
4169
  ws.send(JSON.stringify({ t: "plugins", plugins: this.list() }));
4154
4170
  } else if (msg.t === "req") {
4155
4171
  let target;
@@ -4247,6 +4263,193 @@ Reproduce exact values (sizes, spacing, colours, type). Before writing any colou
4247
4263
  }
4248
4264
  });
4249
4265
 
4266
+ // src/tools/browser.ts
4267
+ import { existsSync as existsSync2, readdirSync } from "node:fs";
4268
+ import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
4269
+ import { createServer } from "node:http";
4270
+ import { createRequire } from "node:module";
4271
+ import os2 from "node:os";
4272
+ import path2 from "node:path";
4273
+ import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";
4274
+ async function loadChromium() {
4275
+ const fromProject = createRequire(path2.join(process.cwd(), "package.json"));
4276
+ for (const name of ["playwright", "@playwright/test", "playwright-core"]) {
4277
+ try {
4278
+ const mod = await import(pathToFileURL(fromProject.resolve(name)).href);
4279
+ const chromium = mod.chromium ?? mod.default?.chromium;
4280
+ if (chromium) return chromium;
4281
+ } catch {
4282
+ }
4283
+ }
4284
+ try {
4285
+ const mod = await import("playwright-core");
4286
+ return mod.chromium ?? mod.default?.chromium;
4287
+ } catch {
4288
+ throw new Error(`Rendering a URL needs Playwright: run \`npm install\` in the Lupa folder, or add playwright to your project. ${INSTALL_HINT}`);
4289
+ }
4290
+ }
4291
+ function playwrightCache() {
4292
+ if (process.env.PLAYWRIGHT_BROWSERS_PATH) return process.env.PLAYWRIGHT_BROWSERS_PATH;
4293
+ if (process.platform === "darwin") return path2.join(os2.homedir(), "Library", "Caches", "ms-playwright");
4294
+ if (process.platform === "win32") return path2.join(process.env.LOCALAPPDATA ?? os2.homedir(), "ms-playwright");
4295
+ return path2.join(os2.homedir(), ".cache", "ms-playwright");
4296
+ }
4297
+ function cachedChromiums() {
4298
+ const root = playwrightCache();
4299
+ let dirs;
4300
+ try {
4301
+ dirs = readdirSync(root).filter((d) => /^chromium-\d+$/.test(d));
4302
+ } catch {
4303
+ return [];
4304
+ }
4305
+ dirs.sort((a, b) => Number(b.split("-")[1]) - Number(a.split("-")[1]));
4306
+ const inside = [
4307
+ "chrome-linux64/chrome",
4308
+ "chrome-linux/chrome",
4309
+ "chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
4310
+ "chrome-mac-x64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
4311
+ "chrome-mac/Chromium.app/Contents/MacOS/Chromium",
4312
+ "chrome-win64/chrome.exe",
4313
+ "chrome-win/chrome.exe"
4314
+ ];
4315
+ return dirs.flatMap((d) => inside.map((p) => path2.join(root, d, p))).filter((p) => existsSync2(p));
4316
+ }
4317
+ async function launch(chromium) {
4318
+ const attempts = [];
4319
+ if (process.env.LUPA_BROWSER) attempts.push({ executablePath: process.env.LUPA_BROWSER, label: `LUPA_BROWSER (${process.env.LUPA_BROWSER})` });
4320
+ attempts.push(
4321
+ { label: "Playwright's Chromium" },
4322
+ ...cachedChromiums().map((p) => ({ executablePath: p, label: `Playwright's Chromium (${p})` })),
4323
+ { channel: "chrome", label: "Google Chrome" }
4324
+ );
4325
+ const errors = [];
4326
+ for (const { label, ...a } of attempts) {
4327
+ try {
4328
+ return { browser: await chromium.launch({ ...a, headless: true }), label };
4329
+ } catch (e) {
4330
+ errors.push(`${a.executablePath ?? a.channel ?? "bundled"}: ${String(e.message).split("\n")[0]}`);
4331
+ }
4332
+ }
4333
+ throw new Error(`Could not start Chromium. ${INSTALL_HINT}
4334
+ ${errors.map((e) => ` ${e}`).join("\n")}`);
4335
+ }
4336
+ async function checkBrowser() {
4337
+ const { browser, label } = await launch(await loadChromium());
4338
+ await browser.close();
4339
+ return label;
4340
+ }
4341
+ function missingFamilies(families) {
4342
+ const doc = globalThis.document;
4343
+ const ctx = doc.createElement("canvas").getContext("2d");
4344
+ const width = (font) => {
4345
+ ctx.font = font;
4346
+ return ctx.measureText("mmmmmmmmmmlli10WQ@#").width;
4347
+ };
4348
+ return families.filter((f) => ["monospace", "serif", "sans-serif"].every((g) => width(`72px "${f}", ${g}`) === width(`72px ${g}`)));
4349
+ }
4350
+ async function serveFile(url2) {
4351
+ const u = new URL(url2);
4352
+ const file2 = fileURLToPath2(u);
4353
+ if (!existsSync2(file2)) throw new Error(`${file2} does not exist`);
4354
+ const inCwd = !path2.relative(process.cwd(), file2).startsWith("..");
4355
+ const root = inCwd ? process.cwd() : path2.dirname(file2);
4356
+ const server = createServer(async (req, res) => {
4357
+ let p = path2.join(root, decodeURIComponent(new URL(req.url ?? "/", "http://x").pathname));
4358
+ try {
4359
+ if (path2.relative(root, p).startsWith("..")) throw new Error("outside");
4360
+ if ((await stat(p)).isDirectory()) p = path2.join(p, "index.html");
4361
+ const body = await readFile(p);
4362
+ res.writeHead(200, { "content-type": TYPES[path2.extname(p).toLowerCase()] ?? "application/octet-stream" });
4363
+ res.end(body);
4364
+ } catch {
4365
+ res.writeHead(404).end();
4366
+ }
4367
+ });
4368
+ await new Promise((ok) => server.listen(0, "127.0.0.1", ok));
4369
+ const port = server.address().port;
4370
+ const rel = path2.relative(root, file2).split(path2.sep).map(encodeURIComponent).join("/");
4371
+ return { url: `http://127.0.0.1:${port}/${rel}${u.search}${u.hash}`, close: () => server.close() };
4372
+ }
4373
+ async function renderUrl(opts) {
4374
+ const served = opts.url.startsWith("file:") ? await serveFile(opts.url) : void 0;
4375
+ try {
4376
+ const { browser } = await launch(await loadChromium());
4377
+ try {
4378
+ const page = await browser.newPage({
4379
+ viewport: { width: Math.round(opts.width), height: opts.height ?? 900 },
4380
+ deviceScaleFactor: opts.scale ?? 2
4381
+ });
4382
+ await page.goto(served?.url ?? opts.url, { waitUntil: "load", timeout: 3e4 });
4383
+ await page.waitForLoadState("networkidle", { timeout: 5e3 }).catch(() => {
4384
+ });
4385
+ const waitFor = opts.waitFor ?? opts.selector;
4386
+ if (waitFor) {
4387
+ await page.locator(waitFor).first().waitFor({ state: "visible", timeout: 15e3 }).catch(() => {
4388
+ throw new Error(`"${waitFor}" did not appear on ${opts.url} within 15s`);
4389
+ });
4390
+ }
4391
+ await page.evaluate(() => globalThis.document.fonts.ready);
4392
+ const missingFonts = await page.evaluate(missingFamilies, opts.fonts ?? []);
4393
+ const png = opts.selector ? await page.locator(opts.selector).first().screenshot({ animations: "disabled" }) : await page.screenshot({ fullPage: true, animations: "disabled" });
4394
+ return { png, missingFonts };
4395
+ } finally {
4396
+ await browser.close();
4397
+ }
4398
+ } finally {
4399
+ served?.close();
4400
+ }
4401
+ }
4402
+ async function renderSvg(svg, o) {
4403
+ const dir = path2.join(os2.tmpdir(), "lupa");
4404
+ await mkdir(dir, { recursive: true });
4405
+ const file2 = path2.join(dir, `render-${process.pid}-${Date.now()}.svg`);
4406
+ await writeFile(file2, svg);
4407
+ try {
4408
+ const { browser } = await launch(await loadChromium());
4409
+ try {
4410
+ const page = await browser.newPage({
4411
+ viewport: { width: Math.ceil(o.width), height: Math.ceil(o.height) },
4412
+ deviceScaleFactor: o.scale
4413
+ });
4414
+ await page.goto(pathToFileURL(file2).href, { waitUntil: "load", timeout: 3e4 });
4415
+ return await page.screenshot({ clip: { x: 0, y: 0, width: o.width, height: o.height }, omitBackground: true, animations: "disabled" });
4416
+ } finally {
4417
+ await browser.close();
4418
+ }
4419
+ } finally {
4420
+ await rm(file2, { force: true });
4421
+ }
4422
+ }
4423
+ var INSTALL_HINT, TYPES;
4424
+ var init_browser = __esm({
4425
+ "src/tools/browser.ts"() {
4426
+ "use strict";
4427
+ INSTALL_HINT = "Install a browser with `npx playwright install chromium` (or install Google Chrome), or set LUPA_BROWSER to a Chrome/Chromium executable. You can also pass a screenshot with --image.";
4428
+ TYPES = {
4429
+ ".html": "text/html",
4430
+ ".htm": "text/html",
4431
+ ".css": "text/css",
4432
+ ".js": "text/javascript",
4433
+ ".mjs": "text/javascript",
4434
+ ".json": "application/json",
4435
+ ".svg": "image/svg+xml",
4436
+ ".png": "image/png",
4437
+ ".jpg": "image/jpeg",
4438
+ ".jpeg": "image/jpeg",
4439
+ ".gif": "image/gif",
4440
+ ".webp": "image/webp",
4441
+ ".avif": "image/avif",
4442
+ ".ico": "image/x-icon",
4443
+ ".woff": "font/woff",
4444
+ ".woff2": "font/woff2",
4445
+ ".ttf": "font/ttf",
4446
+ ".otf": "font/otf",
4447
+ ".mp4": "video/mp4",
4448
+ ".webm": "video/webm"
4449
+ };
4450
+ }
4451
+ });
4452
+
4250
4453
  // src/model/css.ts
4251
4454
  function n(v, places = 2) {
4252
4455
  if (!Number.isFinite(v)) return "0";
@@ -5246,7 +5449,7 @@ var init_components = __esm({
5246
5449
  this.diffChildren(inst, def, "", out, keyOf, resized);
5247
5450
  return out;
5248
5451
  }
5249
- diffChildren(a, d, path5, out, keyOf, resized) {
5452
+ diffChildren(a, d, path6, out, keyOf, resized) {
5250
5453
  const defByKey = new Map(d.children.map((c) => [keyOf(c, true), c]));
5251
5454
  const matched = /* @__PURE__ */ new Set();
5252
5455
  const names = pathNames(d.children);
@@ -5257,7 +5460,7 @@ var init_components = __esm({
5257
5460
  const cand = d.children[a.children.indexOf(child)];
5258
5461
  dc = ok(cand) ? cand : d.children.find(ok);
5259
5462
  }
5260
- const p = joinPath(path5, dc ? names.get(dc) ?? dc.name : child.name);
5463
+ const p = joinPath(path6, dc ? names.get(dc) ?? dc.name : child.name);
5261
5464
  if (!dc) {
5262
5465
  out.push({ path: p, changes: ["added"], sub: child });
5263
5466
  continue;
@@ -5268,20 +5471,20 @@ var init_components = __esm({
5268
5471
  for (const dc of d.children) {
5269
5472
  if (matched.has(dc) || dc.hidden) continue;
5270
5473
  if (dc.propRefs?.visible) continue;
5271
- out.push({ path: joinPath(path5, names.get(dc) ?? dc.name), changes: ["hidden"] });
5474
+ out.push({ path: joinPath(path6, names.get(dc) ?? dc.name), changes: ["hidden"] });
5272
5475
  }
5273
5476
  }
5274
- diffNode(a, d, path5, out, keyOf, resized) {
5477
+ diffNode(a, d, path6, out, keyOf, resized) {
5275
5478
  if (a.hidden && !d.hidden) {
5276
- if (!d.propRefs?.visible) out.push({ path: path5, changes: ["hidden"] });
5479
+ if (!d.propRefs?.visible) out.push({ path: path6, changes: ["hidden"] });
5277
5480
  return;
5278
5481
  }
5279
5482
  if (!a.hidden && d.hidden) {
5280
5483
  if (d.propRefs?.visible) {
5281
5484
  const changes2 = this.nodeChanges(a, d, resized);
5282
- if (changes2.length) out.push({ path: path5, changes: changes2 });
5283
- this.diffChildren(a, d, path5, out, keyOf, resized);
5284
- } else out.push({ path: path5, changes: ["shown"], sub: a });
5485
+ if (changes2.length) out.push({ path: path6, changes: changes2 });
5486
+ this.diffChildren(a, d, path6, out, keyOf, resized);
5487
+ } else out.push({ path: path6, changes: ["shown"], sub: a });
5285
5488
  return;
5286
5489
  }
5287
5490
  if (a.hidden) return;
@@ -5295,22 +5498,22 @@ var init_components = __esm({
5295
5498
  if (a.kind === "svg" || !a.children.length) {
5296
5499
  if (a.kind === "svg" && a.style.src !== d.style.src && a.style.src) changes2.push(`src:${a.style.src}`);
5297
5500
  if (a.kind === "svg" && a.style.color !== d.style.color && a.style.color) changes2.push(`color:${a.style.color}`);
5298
- if (changes2.length) out.push({ path: path5, changes: changes2 });
5501
+ if (changes2.length) out.push({ path: path6, changes: changes2 });
5299
5502
  } else if (def) {
5300
5503
  changes2.push(...this.rootChanges(a, def.ir));
5301
- if (changes2.length) out.push({ path: path5, changes: changes2 });
5504
+ if (changes2.length) out.push({ path: path6, changes: changes2 });
5302
5505
  const nested = this.overrides(a, def.ir);
5303
- for (const o2 of nested) out.push({ ...o2, path: joinPath(path5, o2.path) });
5506
+ for (const o2 of nested) out.push({ ...o2, path: joinPath(path6, o2.path) });
5304
5507
  } else {
5305
- out.push({ path: path5, changes: changes2.length ? changes2 : [`swap\u2192${label}`], sub: a });
5508
+ out.push({ path: path6, changes: changes2.length ? changes2 : [`swap\u2192${label}`], sub: a });
5306
5509
  }
5307
5510
  return;
5308
5511
  }
5309
5512
  const changes = this.nodeChanges(a, d, resized);
5310
- const o = { path: path5, changes };
5513
+ const o = { path: path6, changes };
5311
5514
  if (a.runs && JSON.stringify(a.runs) !== JSON.stringify(d.runs)) o.runs = a.runs;
5312
5515
  if (changes.length || o.runs) out.push(o);
5313
- if (a.kind !== "svg") this.diffChildren(a, d, path5, out, keyOf, resized);
5516
+ if (a.kind !== "svg") this.diffChildren(a, d, path6, out, keyOf, resized);
5314
5517
  }
5315
5518
  nodeChanges(a, d, resized) {
5316
5519
  const changes = [];
@@ -5795,190 +5998,12 @@ var init_render = __esm({
5795
5998
  }
5796
5999
  });
5797
6000
 
5798
- // src/tools/browser.ts
5799
- import { existsSync, readdirSync } from "node:fs";
5800
- import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
5801
- import { createServer } from "node:http";
5802
- import { createRequire } from "node:module";
5803
- import os from "node:os";
5804
- import path from "node:path";
5805
- import { fileURLToPath, pathToFileURL } from "node:url";
5806
- async function loadChromium() {
5807
- const fromProject = createRequire(path.join(process.cwd(), "package.json"));
5808
- for (const name of ["playwright", "@playwright/test", "playwright-core"]) {
5809
- try {
5810
- const mod = await import(pathToFileURL(fromProject.resolve(name)).href);
5811
- const chromium = mod.chromium ?? mod.default?.chromium;
5812
- if (chromium) return chromium;
5813
- } catch {
5814
- }
5815
- }
5816
- try {
5817
- const mod = await import("playwright-core");
5818
- return mod.chromium ?? mod.default?.chromium;
5819
- } catch {
5820
- throw new Error(`Rendering a URL needs Playwright: run \`npm install\` in the Lupa folder, or add playwright to your project. ${INSTALL_HINT}`);
5821
- }
5822
- }
5823
- function playwrightCache() {
5824
- if (process.env.PLAYWRIGHT_BROWSERS_PATH) return process.env.PLAYWRIGHT_BROWSERS_PATH;
5825
- if (process.platform === "darwin") return path.join(os.homedir(), "Library", "Caches", "ms-playwright");
5826
- if (process.platform === "win32") return path.join(process.env.LOCALAPPDATA ?? os.homedir(), "ms-playwright");
5827
- return path.join(os.homedir(), ".cache", "ms-playwright");
5828
- }
5829
- function cachedChromiums() {
5830
- const root = playwrightCache();
5831
- let dirs;
5832
- try {
5833
- dirs = readdirSync(root).filter((d) => /^chromium-\d+$/.test(d));
5834
- } catch {
5835
- return [];
5836
- }
5837
- dirs.sort((a, b) => Number(b.split("-")[1]) - Number(a.split("-")[1]));
5838
- const inside = [
5839
- "chrome-linux64/chrome",
5840
- "chrome-linux/chrome",
5841
- "chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
5842
- "chrome-mac-x64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
5843
- "chrome-mac/Chromium.app/Contents/MacOS/Chromium",
5844
- "chrome-win64/chrome.exe",
5845
- "chrome-win/chrome.exe"
5846
- ];
5847
- return dirs.flatMap((d) => inside.map((p) => path.join(root, d, p))).filter((p) => existsSync(p));
5848
- }
5849
- async function launch(chromium) {
5850
- const attempts = [];
5851
- if (process.env.LUPA_BROWSER) attempts.push({ executablePath: process.env.LUPA_BROWSER });
5852
- attempts.push({}, ...cachedChromiums().map((p) => ({ executablePath: p })), { channel: "chrome" });
5853
- const errors = [];
5854
- for (const a of attempts) {
5855
- try {
5856
- return await chromium.launch({ ...a, headless: true });
5857
- } catch (e) {
5858
- errors.push(`${a.executablePath ?? a.channel ?? "bundled"}: ${String(e.message).split("\n")[0]}`);
5859
- }
5860
- }
5861
- throw new Error(`Could not start Chromium. ${INSTALL_HINT}
5862
- ${errors.map((e) => ` ${e}`).join("\n")}`);
5863
- }
5864
- function missingFamilies(families) {
5865
- const doc = globalThis.document;
5866
- const ctx = doc.createElement("canvas").getContext("2d");
5867
- const width = (font) => {
5868
- ctx.font = font;
5869
- return ctx.measureText("mmmmmmmmmmlli10WQ@#").width;
5870
- };
5871
- return families.filter((f) => ["monospace", "serif", "sans-serif"].every((g) => width(`72px "${f}", ${g}`) === width(`72px ${g}`)));
5872
- }
5873
- async function serveFile(url2) {
5874
- const u = new URL(url2);
5875
- const file2 = fileURLToPath(u);
5876
- if (!existsSync(file2)) throw new Error(`${file2} does not exist`);
5877
- const inCwd = !path.relative(process.cwd(), file2).startsWith("..");
5878
- const root = inCwd ? process.cwd() : path.dirname(file2);
5879
- const server = createServer(async (req, res) => {
5880
- let p = path.join(root, decodeURIComponent(new URL(req.url ?? "/", "http://x").pathname));
5881
- try {
5882
- if (path.relative(root, p).startsWith("..")) throw new Error("outside");
5883
- if ((await stat(p)).isDirectory()) p = path.join(p, "index.html");
5884
- const body = await readFile(p);
5885
- res.writeHead(200, { "content-type": TYPES[path.extname(p).toLowerCase()] ?? "application/octet-stream" });
5886
- res.end(body);
5887
- } catch {
5888
- res.writeHead(404).end();
5889
- }
5890
- });
5891
- await new Promise((ok) => server.listen(0, "127.0.0.1", ok));
5892
- const port = server.address().port;
5893
- const rel = path.relative(root, file2).split(path.sep).map(encodeURIComponent).join("/");
5894
- return { url: `http://127.0.0.1:${port}/${rel}${u.search}${u.hash}`, close: () => server.close() };
5895
- }
5896
- async function renderUrl(opts) {
5897
- const served = opts.url.startsWith("file:") ? await serveFile(opts.url) : void 0;
5898
- try {
5899
- const browser = await launch(await loadChromium());
5900
- try {
5901
- const page = await browser.newPage({
5902
- viewport: { width: Math.round(opts.width), height: opts.height ?? 900 },
5903
- deviceScaleFactor: opts.scale ?? 2
5904
- });
5905
- await page.goto(served?.url ?? opts.url, { waitUntil: "load", timeout: 3e4 });
5906
- await page.waitForLoadState("networkidle", { timeout: 5e3 }).catch(() => {
5907
- });
5908
- const waitFor = opts.waitFor ?? opts.selector;
5909
- if (waitFor) {
5910
- await page.locator(waitFor).first().waitFor({ state: "visible", timeout: 15e3 }).catch(() => {
5911
- throw new Error(`"${waitFor}" did not appear on ${opts.url} within 15s`);
5912
- });
5913
- }
5914
- await page.evaluate(() => globalThis.document.fonts.ready);
5915
- const missingFonts = await page.evaluate(missingFamilies, opts.fonts ?? []);
5916
- const png = opts.selector ? await page.locator(opts.selector).first().screenshot({ animations: "disabled" }) : await page.screenshot({ fullPage: true, animations: "disabled" });
5917
- return { png, missingFonts };
5918
- } finally {
5919
- await browser.close();
5920
- }
5921
- } finally {
5922
- served?.close();
5923
- }
5924
- }
5925
- async function renderSvg(svg, o) {
5926
- const dir = path.join(os.tmpdir(), "lupa");
5927
- await mkdir(dir, { recursive: true });
5928
- const file2 = path.join(dir, `render-${process.pid}-${Date.now()}.svg`);
5929
- await writeFile(file2, svg);
5930
- try {
5931
- const browser = await launch(await loadChromium());
5932
- try {
5933
- const page = await browser.newPage({
5934
- viewport: { width: Math.ceil(o.width), height: Math.ceil(o.height) },
5935
- deviceScaleFactor: o.scale
5936
- });
5937
- await page.goto(pathToFileURL(file2).href, { waitUntil: "load", timeout: 3e4 });
5938
- return await page.screenshot({ clip: { x: 0, y: 0, width: o.width, height: o.height }, omitBackground: true, animations: "disabled" });
5939
- } finally {
5940
- await browser.close();
5941
- }
5942
- } finally {
5943
- await rm(file2, { force: true });
5944
- }
5945
- }
5946
- var INSTALL_HINT, TYPES;
5947
- var init_browser = __esm({
5948
- "src/tools/browser.ts"() {
5949
- "use strict";
5950
- INSTALL_HINT = "Install a browser with `npx playwright install chromium` (or install Google Chrome), or set LUPA_BROWSER to a Chrome/Chromium executable. You can also pass a screenshot with --image.";
5951
- TYPES = {
5952
- ".html": "text/html",
5953
- ".htm": "text/html",
5954
- ".css": "text/css",
5955
- ".js": "text/javascript",
5956
- ".mjs": "text/javascript",
5957
- ".json": "application/json",
5958
- ".svg": "image/svg+xml",
5959
- ".png": "image/png",
5960
- ".jpg": "image/jpeg",
5961
- ".jpeg": "image/jpeg",
5962
- ".gif": "image/gif",
5963
- ".webp": "image/webp",
5964
- ".avif": "image/avif",
5965
- ".ico": "image/x-icon",
5966
- ".woff": "font/woff",
5967
- ".woff2": "font/woff2",
5968
- ".ttf": "font/ttf",
5969
- ".otf": "font/otf",
5970
- ".mp4": "video/mp4",
5971
- ".webm": "video/webm"
5972
- };
5973
- }
5974
- });
5975
-
5976
6001
  // src/tools/format.ts
5977
6002
  function formatStatus(plugins, role, port) {
5978
6003
  if (!plugins.length) {
5979
6004
  return [
5980
6005
  `Lupa ${role} on port ${port}. No Figma file connected.`,
5981
- "In Figma: open the file \u2192 Plugins \u2192 Development \u2192 Lupa (import plugin/manifest.json once). Keep the plugin window open."
6006
+ "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."
5982
6007
  ].join("\n");
5983
6008
  }
5984
6009
  const lines = [`Lupa ${role} on port ${port}. Connected files (most recently active first):`];
@@ -6016,9 +6041,9 @@ function formatOutline(o) {
6016
6041
  function formatMatches(r) {
6017
6042
  if (!r.matches.length) return "No matches.";
6018
6043
  const out = r.matches.map((m) => {
6019
- const path5 = [m.page, ...m.path].filter(Boolean).join(" \u203A ");
6044
+ const path6 = [m.page, ...m.path].filter(Boolean).join(" \u203A ");
6020
6045
  const text2 = m.text !== void 0 ? ` ${JSON.stringify(m.text)}` : "";
6021
- return `${m.type.toLowerCase()} "${m.name}" #${m.id} ${m.w}\xD7${m.h}${text2} \u2014 ${path5}`;
6046
+ return `${m.type.toLowerCase()} "${m.name}" #${m.id} ${m.w}\xD7${m.h}${text2} \u2014 ${path6}`;
6022
6047
  });
6023
6048
  if (r.truncated) out.push("\u2026 more matches; narrow the query, page or type.");
6024
6049
  return out.join("\n");
@@ -6117,43 +6142,62 @@ var init_format = __esm({
6117
6142
  });
6118
6143
 
6119
6144
  // src/tools/project.ts
6145
+ import { execFile } from "node:child_process";
6120
6146
  import { readdir, readFile as readFile2 } from "node:fs/promises";
6121
- import os2 from "node:os";
6122
- import path2 from "node:path";
6123
- async function scanProject(root, exclude = []) {
6124
- root = path2.resolve(root);
6125
- if (root === path2.parse(root).root || root === os2.homedir()) return void 0;
6126
- const skip = new Set(exclude.map((e) => path2.resolve(e)));
6147
+ import os3 from "node:os";
6148
+ import path3 from "node:path";
6149
+ import { promisify } from "node:util";
6150
+ async function scanProject(root, exclude = [], maxEntries = MAX_ENTRIES) {
6151
+ root = path3.resolve(root);
6152
+ if (root === path3.parse(root).root || root === os3.homedir()) return void 0;
6153
+ const skip = [...new Set(exclude.map((e) => path3.resolve(e)))];
6127
6154
  const styles = [];
6128
6155
  const svgs = [];
6129
6156
  const comps = [];
6130
- const started = Date.now();
6131
- let entries = 0;
6132
- const walk = async (dir, depth) => {
6133
- if (depth > 10 || entries > MAX_ENTRIES || Date.now() - started > MAX_MS) return;
6134
- let list;
6135
- try {
6136
- list = await readdir(dir, { withFileTypes: true });
6137
- } catch {
6138
- return;
6157
+ const shown = (p) => path3.relative(process.cwd(), p).split(path3.sep).join("/");
6158
+ let incomplete;
6159
+ const sort = (p) => {
6160
+ const name = path3.basename(p);
6161
+ if (STYLE.test(name)) styles.push(p);
6162
+ else if (/\.svg$/i.test(name)) svgs.push(p);
6163
+ else if (COMPONENT_FILE.test(name)) comps.push(p);
6164
+ };
6165
+ const skipped = (p) => skip.some((s) => p === s || p.startsWith(s + path3.sep));
6166
+ const tracked = await gitFiles(root);
6167
+ if (tracked?.length) {
6168
+ for (const p of tracked) {
6169
+ const dirs = path3.relative(root, p).split(path3.sep).slice(0, -1);
6170
+ if (!dirs.some((d) => d.startsWith(".") || SKIP_DIRS.has(d)) && !skipped(p)) sort(p);
6139
6171
  }
6140
- entries += list.length;
6141
- list.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
6142
- for (const e of list) {
6143
- const p = path2.join(dir, e.name);
6144
- if (e.isDirectory()) {
6145
- if (!e.name.startsWith(".") && !SKIP_DIRS.has(e.name) && !skip.has(p)) await walk(p, depth + 1);
6146
- } else if (e.isFile()) {
6147
- if (STYLE.test(e.name)) styles.push(p);
6148
- else if (/\.svg$/i.test(e.name)) svgs.push(p);
6149
- else if (COMPONENT_FILE.test(e.name)) comps.push(p);
6172
+ } else {
6173
+ const started = Date.now();
6174
+ let entries = 0;
6175
+ const walk = async (dir, depth) => {
6176
+ if (depth > 10) return;
6177
+ if (entries > maxEntries || Date.now() - started > MAX_MS) {
6178
+ incomplete ??= `stopped after ${entries > maxEntries ? `${maxEntries} entries` : `${MAX_MS / 1e3}s`}, before ${shown(dir) || "."}`;
6179
+ return;
6150
6180
  }
6151
- }
6152
- };
6153
- await walk(root, 0);
6181
+ let list;
6182
+ try {
6183
+ list = await readdir(dir, { withFileTypes: true });
6184
+ } catch {
6185
+ return;
6186
+ }
6187
+ entries += list.length;
6188
+ list.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
6189
+ for (const e of list) {
6190
+ const p = path3.join(dir, e.name);
6191
+ if (e.isDirectory()) {
6192
+ if (!e.name.startsWith(".") && !SKIP_DIRS.has(e.name) && !skipped(p)) await walk(p, depth + 1);
6193
+ } else if (e.isFile()) sort(p);
6194
+ }
6195
+ };
6196
+ await walk(root, 0);
6197
+ }
6198
+ if (styles.length > MAX_STYLES) incomplete ??= `read only the first ${MAX_STYLES} of ${styles.length} stylesheets`;
6154
6199
  const idx = { colors: /* @__PURE__ */ new Map(), fonts: /* @__PURE__ */ new Map(), icons: /* @__PURE__ */ new Map(), components: /* @__PURE__ */ new Map(), textStyles: [] };
6155
6200
  const rules = [];
6156
- const shown = (p) => path2.relative(process.cwd(), p).split(path2.sep).join("/");
6157
6201
  const add = (m, key, ref2) => {
6158
6202
  const list = m.get(key) ?? [];
6159
6203
  if (!list.includes(ref2)) list.push(ref2);
@@ -6161,7 +6205,7 @@ async function scanProject(root, exclude = []) {
6161
6205
  };
6162
6206
  const vars = /* @__PURE__ */ new Map();
6163
6207
  const classes = /* @__PURE__ */ new Map();
6164
- for (const f of styles.slice(0, 600)) {
6208
+ for (const f of styles.slice(0, MAX_STYLES)) {
6165
6209
  const css = await readText(f, 1e6);
6166
6210
  if (!css) continue;
6167
6211
  const text2 = css.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "");
@@ -6171,7 +6215,7 @@ async function scanProject(root, exclude = []) {
6171
6215
  define(/(?<=(?:^|[{;])\s*)(--[\w-]+)\s*:\s*([^;{}]+)/g);
6172
6216
  if (/\.(scss|sass)$/i.test(f)) define(/^\s*(\$[\w-]+)\s*:\s*([^;\n]+)/gm);
6173
6217
  if (/\.less$/i.test(f)) define(/^\s*(@[\w-]+)\s*:\s*([^;\n]+)/gm);
6174
- const stem = slug2(path2.basename(f).replace(/\.[^.]+$/, ""));
6218
+ const stem = slug2(path3.basename(f).replace(/\.[^.]+$/, ""));
6175
6219
  for (const m of text2.matchAll(/(?<=^|[{};])\s*\.(-?[_a-zA-Z][\w-]*)\s*\{([^{}]*)\}/g)) {
6176
6220
  if (!/__|--/.test(m[1])) rules.push({ cls: m[1], decls: m[2], file: shown(f) });
6177
6221
  }
@@ -6223,7 +6267,7 @@ async function scanProject(root, exclude = []) {
6223
6267
  const t = textStyle(r.decls, family);
6224
6268
  if (t) idx.textStyles.push({ ...t, ref: `.${r.cls} (${r.file})` });
6225
6269
  }
6226
- for (const f of svgs.slice(0, 3e3)) {
6270
+ for (const f of svgs.slice(0, MAX_SVGS)) {
6227
6271
  const svg = await readText(f, 64e3);
6228
6272
  const s = svg && shapeOf(svg);
6229
6273
  if (!s) continue;
@@ -6232,14 +6276,35 @@ async function scanProject(root, exclude = []) {
6232
6276
  idx.icons.set(s.key, list);
6233
6277
  }
6234
6278
  for (const f of comps) {
6235
- let stem = path2.basename(f).replace(/\.[^.]+$/, "");
6236
- if (/^index$/i.test(stem)) stem = path2.basename(path2.dirname(f));
6279
+ let stem = path3.basename(f).replace(/\.[^.]+$/, "");
6280
+ if (/^index$/i.test(stem)) stem = path3.basename(path3.dirname(f));
6237
6281
  if (NOT_COMPONENT.test(stem)) continue;
6238
6282
  add(idx.components, slug2(stem), shown(f));
6239
6283
  }
6240
6284
  for (const [c, f] of classes) add(idx.components, c.toLowerCase(), `.${c} (${f})`);
6285
+ if (svgs.length > MAX_SVGS) incomplete ??= `read only the first ${MAX_SVGS} of ${svgs.length} SVG files`;
6286
+ if (incomplete) idx.incomplete = `project scan of ${shown(root) || "."} ${incomplete}`;
6241
6287
  const empty = !idx.colors.size && !idx.fonts.size && !idx.icons.size && !idx.components.size && !idx.textStyles.length;
6242
- return empty ? void 0 : idx;
6288
+ return empty && !incomplete ? void 0 : idx;
6289
+ }
6290
+ async function gitFiles(root) {
6291
+ try {
6292
+ const { stdout } = await promisify(execFile)("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], {
6293
+ cwd: root,
6294
+ maxBuffer: 256 * 1024 * 1024,
6295
+ timeout: 1e4
6296
+ });
6297
+ return stdout.split("\0").filter(Boolean).map((f) => path3.join(root, f));
6298
+ } catch {
6299
+ return void 0;
6300
+ }
6301
+ }
6302
+ function withScanNote(text2, idx) {
6303
+ if (!idx?.incomplete) return text2;
6304
+ return `${text2}
6305
+
6306
+ ## project scan incomplete
6307
+ ${idx.incomplete}: a colour, font, icon or component without a project match may still exist, so search the code before adding a copy`;
6243
6308
  }
6244
6309
  function firstFamily(stack) {
6245
6310
  return stack.split(",")[0].trim().replace(/^["']|["']$/g, "").toLowerCase();
@@ -6533,7 +6598,7 @@ function absolutePath(d) {
6533
6598
  }
6534
6599
  return { key, vals };
6535
6600
  }
6536
- var TEXT_PROPS, SKIP_DIRS, STYLE, COMPONENT_FILE, NOT_COMPONENT, MAX_ENTRIES, MAX_MS, WEIGHTS, hex22, pct, ARGS;
6601
+ var TEXT_PROPS, SKIP_DIRS, STYLE, COMPONENT_FILE, NOT_COMPONENT, MAX_ENTRIES, MAX_MS, MAX_STYLES, MAX_SVGS, WEIGHTS, hex22, pct, ARGS;
6537
6602
  var init_project = __esm({
6538
6603
  "src/tools/project.ts"() {
6539
6604
  "use strict";
@@ -6553,13 +6618,17 @@ var init_project = __esm({
6553
6618
  "Pods",
6554
6619
  "DerivedData",
6555
6620
  "tmp",
6556
- "temp"
6621
+ "temp",
6622
+ "_build",
6623
+ "deps"
6557
6624
  ]);
6558
6625
  STYLE = /\.(css|scss|sass|less|styl|pcss)$/i;
6559
6626
  COMPONENT_FILE = /\.(tsx|jsx|vue|svelte|astro)$/i;
6560
6627
  NOT_COMPONENT = /^(index|page|layout|main|app|route|\+page|\+layout)$|\.(test|spec|stories|story)$/i;
6561
6628
  MAX_ENTRIES = 3e4;
6562
6629
  MAX_MS = 2e3;
6630
+ MAX_STYLES = 600;
6631
+ MAX_SVGS = 3e3;
6563
6632
  WEIGHTS = { normal: 400, bold: 700, lighter: 300, bolder: 700 };
6564
6633
  hex22 = (v) => Math.round(Math.max(0, Math.min(255, v))).toString(16).padStart(2, "0");
6565
6634
  pct = (s, full) => s.endsWith("%") ? parseFloat(s) / 100 * full : parseFloat(s);
@@ -8999,7 +9068,7 @@ var init_png = __esm({
8999
9068
 
9000
9069
  // src/tools/media.ts
9001
9070
  import { mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2 } from "node:fs/promises";
9002
- import path3 from "node:path";
9071
+ import path4 from "node:path";
9003
9072
  function rasterWaitMs(frozen) {
9004
9073
  return Number(process.env.LUPA_RASTER_WAIT_MS) || (frozen ? 2500 : 1e4);
9005
9074
  }
@@ -9044,9 +9113,9 @@ async function screenshot(bridge, ids, file2, opts) {
9044
9113
  const raster = decodePng(buf);
9045
9114
  if (opts.saveTo) {
9046
9115
  const target = ids.length > 1 || head.roots.length > 1 ? withSuffix(opts.saveTo, slug(root.name) || root.id) : opts.saveTo;
9047
- await mkdir2(path3.dirname(path3.resolve(target)), { recursive: true });
9116
+ await mkdir2(path4.dirname(path4.resolve(target)), { recursive: true });
9048
9117
  await writeFile2(target, buf);
9049
- lines.push(`saved ${path3.resolve(target)} (${raster.width}\xD7${raster.height}px)`);
9118
+ lines.push(`saved ${path4.resolve(target)} (${raster.width}\xD7${raster.height}px)`);
9050
9119
  }
9051
9120
  const parts = tiles(raster);
9052
9121
  const visionScale = scale * parts[0].scale;
@@ -9060,8 +9129,8 @@ async function screenshot(bridge, ids, file2, opts) {
9060
9129
  return { text: lines.join("\n"), images };
9061
9130
  }
9062
9131
  function withSuffix(file2, suffix) {
9063
- const ext = path3.extname(file2) || ".png";
9064
- return `${file2.slice(0, file2.length - path3.extname(file2).length)}-${suffix}${ext}`;
9132
+ const ext = path4.extname(file2) || ".png";
9133
+ return `${file2.slice(0, file2.length - path4.extname(file2).length)}-${suffix}${ext}`;
9065
9134
  }
9066
9135
  function collect(snap, defs = []) {
9067
9136
  const graphics = [];
@@ -9131,7 +9200,7 @@ function fileNamer() {
9131
9200
  }
9132
9201
  async function exportAssets(bridge, ids, file2, opts) {
9133
9202
  if (opts.as !== "auto") {
9134
- const dir = path3.resolve(opts.dir);
9203
+ const dir = path4.resolve(opts.dir);
9135
9204
  await mkdir2(dir, { recursive: true });
9136
9205
  const fileName = fileNamer();
9137
9206
  const lines = [];
@@ -9140,7 +9209,7 @@ async function exportAssets(bridge, ids, file2, opts) {
9140
9209
  for (const b of res2.blobs) {
9141
9210
  const name = fileName(b.name, opts.as);
9142
9211
  const data = b.encoding === "utf8" ? opts.currentColor ? toCurrentColor(b.data) : b.data : Buffer.from(b.data, "base64");
9143
- await writeFile2(path3.join(dir, name), data);
9212
+ await writeFile2(path4.join(dir, name), data);
9144
9213
  lines.push(`${name} \u2190 "${b.name}" #${b.id} ${n(b.w)}\xD7${n(b.h)}${opts.as === "png" ? ` @${opts.scale ?? 2}x` : ""}`);
9145
9214
  }
9146
9215
  for (const e of res2.errors) lines.push(`failed #${e.id}: ${e.error}`);
@@ -9154,10 +9223,10 @@ async function exportAssets(bridge, ids, file2, opts) {
9154
9223
  return res.report;
9155
9224
  }
9156
9225
  async function writeAssets(bridge, snap, file2, opts) {
9157
- const dir = path3.resolve(opts.dir);
9226
+ const dir = path4.resolve(opts.dir);
9158
9227
  await mkdir2(dir, { recursive: true });
9159
9228
  const fileName = fileNamer();
9160
- const rel = (name) => path3.join(opts.dir, name).split(path3.sep).join("/");
9229
+ const rel = (name) => path4.join(opts.dir, name).split(path4.sep).join("/");
9161
9230
  const lines = [];
9162
9231
  const failures = [];
9163
9232
  const fail2 = (line) => {
@@ -9195,7 +9264,7 @@ async function writeAssets(bridge, snap, file2, opts) {
9195
9264
  const own3 = opts.project && iconFile(opts.project, svg);
9196
9265
  const name = own3 || fileName(g.base, "svg");
9197
9266
  if (own3) reused.add(own3);
9198
- else await writeFile2(path3.join(dir, name), svg);
9267
+ else await writeFile2(path4.join(dir, name), svg);
9199
9268
  written.set(key, { name, line: lines.length, uses: 1, component: g.component, also: [] });
9200
9269
  byNode.set(g.nodeId, own3 || rel(name));
9201
9270
  if (g.sig) bySig.set(g.sig, name);
@@ -9230,7 +9299,7 @@ async function writeAssets(bridge, snap, file2, opts) {
9230
9299
  }
9231
9300
  const buf = Buffer.from(got.data, "base64");
9232
9301
  const name = fileName(img.base, imageExt(buf));
9233
- await writeFile2(path3.join(dir, name), buf);
9302
+ await writeFile2(path4.join(dir, name), buf);
9234
9303
  byImage.set(img.hash, rel(name));
9235
9304
  lines.push(`${name} \u2190 src:${img.hash.slice(0, 10)} "${img.name}" #${img.nodeId}${got.w ? ` ${got.w}\xD7${got.h}px original` : ""}${img.uses > 1 ? ` (used ${img.uses}\xD7)` : ""}`);
9236
9305
  }
@@ -9341,9 +9410,9 @@ async function compare(bridge, root, file2, opts) {
9341
9410
  if (d.regions.length > 10) lines.push(` \u2026 +${d.regions.length - 10} smaller regions`);
9342
9411
  let strip = sideBySide([a, b, d.diff]);
9343
9412
  if (opts.saveDiff) {
9344
- await mkdir2(path3.dirname(path3.resolve(opts.saveDiff)), { recursive: true });
9413
+ await mkdir2(path4.dirname(path4.resolve(opts.saveDiff)), { recursive: true });
9345
9414
  await writeFile2(opts.saveDiff, encodePng(strip));
9346
- lines.push(`saved ${path3.resolve(opts.saveDiff)}`);
9415
+ lines.push(`saved ${path4.resolve(opts.saveDiff)}`);
9347
9416
  }
9348
9417
  if (strip.width > VISION_MAX_EDGE || strip.height > VISION_MAX_EDGE) {
9349
9418
  const s = Math.min(VISION_MAX_EDGE / strip.width, VISION_MAX_EDGE / strip.height);
@@ -9485,14 +9554,14 @@ var init_ops = __esm({
9485
9554
  if (!snap.roots.length) throw new Error(`Nothing found for ${r.ids.join(", ")}${snap.missing.length ? " (not in this file, or deleted)" : ""}`);
9486
9555
  const index = await scan;
9487
9556
  const opts = { budget: o.budget ?? 8e3, components: o.components ?? "auto", project: index && projectHints(index) };
9488
- if (!o.assetsDir) return renderSnapshot(snap, opts).text;
9557
+ if (!o.assetsDir) return withScanNote(renderSnapshot(snap, opts).text, index);
9489
9558
  const defs = printedDefs(snap, opts.components);
9490
9559
  const written = await writeAssets(this.bridge, snap, r.file, { dir: o.assetsDir, currentColor: o.currentColor, defs, project: index });
9491
9560
  const text2 = renderSnapshot(snap, { ...opts, files: { ...written, dir: o.assetsDir } }).text;
9492
- return written.failures.length ? `${text2}
9561
+ return withScanNote(written.failures.length ? `${text2}
9493
9562
 
9494
9563
  ## asset export failures
9495
- ${written.failures.join("\n")}` : text2;
9564
+ ${written.failures.join("\n")}` : text2, index);
9496
9565
  }
9497
9566
  async screenshot(o) {
9498
9567
  const r = await this.resolve(o.target, o.file);
@@ -9502,7 +9571,8 @@ ${written.failures.join("\n")}` : text2;
9502
9571
  const r = await this.resolve(o.target, o.file);
9503
9572
  const dir = o.dir ?? "figma-assets";
9504
9573
  const project = o.as === "auto" || !o.as ? await scanProject(process.cwd(), [dir]).catch(() => void 0) : void 0;
9505
- return exportAssets(this.bridge, r.ids, r.file, { dir, as: o.as ?? "auto", scale: o.scale, currentColor: o.currentColor, project });
9574
+ const text2 = await exportAssets(this.bridge, r.ids, r.file, { dir, as: o.as ?? "auto", scale: o.scale, currentColor: o.currentColor, project });
9575
+ return withScanNote(text2, project);
9506
9576
  }
9507
9577
  async tokens(o) {
9508
9578
  await this.connect();
@@ -9957,8 +10027,8 @@ var init_parseUtil = __esm({
9957
10027
  init_errors();
9958
10028
  init_en();
9959
10029
  makeIssue = (params) => {
9960
- const { data, path: path5, errorMaps, issueData } = params;
9961
- const fullPath = [...path5, ...issueData.path || []];
10030
+ const { data, path: path6, errorMaps, issueData } = params;
10031
+ const fullPath = [...path6, ...issueData.path || []];
9962
10032
  const fullIssue = {
9963
10033
  ...issueData,
9964
10034
  path: fullPath
@@ -10242,11 +10312,11 @@ var init_types = __esm({
10242
10312
  init_parseUtil();
10243
10313
  init_util();
10244
10314
  ParseInputLazyPath = class {
10245
- constructor(parent, value, path5, key) {
10315
+ constructor(parent, value, path6, key) {
10246
10316
  this._cachedPath = [];
10247
10317
  this.parent = parent;
10248
10318
  this.data = value;
10249
- this._path = path5;
10319
+ this._path = path6;
10250
10320
  this._key = key;
10251
10321
  }
10252
10322
  get path() {
@@ -13721,10 +13791,10 @@ function mergeDefs(...defs) {
13721
13791
  function cloneDef(schema) {
13722
13792
  return mergeDefs(schema._zod.def);
13723
13793
  }
13724
- function getElementAtPath(obj, path5) {
13725
- if (!path5)
13794
+ function getElementAtPath(obj, path6) {
13795
+ if (!path6)
13726
13796
  return obj;
13727
- return path5.reduce((acc, key) => acc?.[key], obj);
13797
+ return path6.reduce((acc, key) => acc?.[key], obj);
13728
13798
  }
13729
13799
  function promiseAllObject(promisesObj) {
13730
13800
  const keys = Object.keys(promisesObj);
@@ -13983,11 +14053,11 @@ function explicitlyAborted(x, startIndex = 0) {
13983
14053
  }
13984
14054
  return false;
13985
14055
  }
13986
- function prefixIssues(path5, issues) {
14056
+ function prefixIssues(path6, issues) {
13987
14057
  return issues.map((iss) => {
13988
14058
  var _a3;
13989
14059
  (_a3 = iss).path ?? (_a3.path = []);
13990
- iss.path.unshift(path5);
14060
+ iss.path.unshift(path6);
13991
14061
  return iss;
13992
14062
  });
13993
14063
  }
@@ -14520,16 +14590,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
14520
14590
  }
14521
14591
  function formatError(error62, mapper = (issue2) => issue2.message) {
14522
14592
  const fieldErrors = { _errors: [] };
14523
- const processError = (error63, path5 = []) => {
14593
+ const processError = (error63, path6 = []) => {
14524
14594
  for (const issue2 of error63.issues) {
14525
14595
  if (issue2.code === "invalid_union" && issue2.errors.length) {
14526
- issue2.errors.map((issues) => processError({ issues }, [...path5, ...issue2.path]));
14596
+ issue2.errors.map((issues) => processError({ issues }, [...path6, ...issue2.path]));
14527
14597
  } else if (issue2.code === "invalid_key") {
14528
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
14598
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
14529
14599
  } else if (issue2.code === "invalid_element") {
14530
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
14600
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
14531
14601
  } else {
14532
- const fullpath = [...path5, ...issue2.path];
14602
+ const fullpath = [...path6, ...issue2.path];
14533
14603
  if (fullpath.length === 0) {
14534
14604
  fieldErrors._errors.push(mapper(issue2));
14535
14605
  } else {
@@ -14568,17 +14638,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
14568
14638
  }
14569
14639
  function treeifyError(error62, mapper = (issue2) => issue2.message) {
14570
14640
  const result = { errors: [] };
14571
- const processError = (error63, path5 = []) => {
14641
+ const processError = (error63, path6 = []) => {
14572
14642
  var _a3;
14573
14643
  for (const issue2 of error63.issues) {
14574
14644
  if (issue2.code === "invalid_union" && issue2.errors.length) {
14575
- issue2.errors.map((issues) => processError({ issues }, [...path5, ...issue2.path]));
14645
+ issue2.errors.map((issues) => processError({ issues }, [...path6, ...issue2.path]));
14576
14646
  } else if (issue2.code === "invalid_key") {
14577
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
14647
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
14578
14648
  } else if (issue2.code === "invalid_element") {
14579
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
14649
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
14580
14650
  } else {
14581
- const fullpath = [...path5, ...issue2.path];
14651
+ const fullpath = [...path6, ...issue2.path];
14582
14652
  if (fullpath.length === 0) {
14583
14653
  result.errors.push(mapper(issue2));
14584
14654
  continue;
@@ -14617,8 +14687,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
14617
14687
  }
14618
14688
  function toDotPath(_path) {
14619
14689
  const segs = [];
14620
- const path5 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
14621
- for (const seg of path5) {
14690
+ const path6 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
14691
+ for (const seg of path6) {
14622
14692
  if (typeof seg === "number")
14623
14693
  segs.push(`[${seg}]`);
14624
14694
  else if (typeof seg === "symbol")
@@ -31156,11 +31226,11 @@ function normalizeObjectSchema(schema) {
31156
31226
  }
31157
31227
  return void 0;
31158
31228
  }
31159
- function getDotPath(path5) {
31160
- if (path5.length === 0) {
31229
+ function getDotPath(path6) {
31230
+ if (path6.length === 0) {
31161
31231
  return "object root";
31162
31232
  }
31163
- return path5.reduce((acc, seg, index) => {
31233
+ return path6.reduce((acc, seg, index) => {
31164
31234
  if (index === 0) {
31165
31235
  return String(seg);
31166
31236
  }
@@ -33098,13 +33168,13 @@ function resolveRef(ref, ctx) {
33098
33168
  if (!ref.startsWith("#")) {
33099
33169
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
33100
33170
  }
33101
- const path5 = ref.slice(1).split("/").filter(Boolean);
33102
- if (path5.length === 0) {
33171
+ const path6 = ref.slice(1).split("/").filter(Boolean);
33172
+ if (path6.length === 0) {
33103
33173
  return ctx.rootSchema;
33104
33174
  }
33105
33175
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
33106
- if (path5[0] === defsKey) {
33107
- const key = path5[1] === void 0 ? void 0 : decodeJSONPointerSegment(path5[1]);
33176
+ if (path6[0] === defsKey) {
33177
+ const key = path6[1] === void 0 ? void 0 : decodeJSONPointerSegment(path6[1]);
33108
33178
  if (!key || !ctx.defs[key]) {
33109
33179
  throw new Error(`Reference not found: ${ref}`);
33110
33180
  }
@@ -41581,8 +41651,8 @@ var require_utils = __commonJS({
41581
41651
  }
41582
41652
  return ind;
41583
41653
  }
41584
- function removeDotSegments(path5) {
41585
- let input2 = path5;
41654
+ function removeDotSegments(path6) {
41655
+ let input2 = path6;
41586
41656
  const output2 = [];
41587
41657
  let nextSlash = -1;
41588
41658
  let len = 0;
@@ -41656,11 +41726,11 @@ var require_utils = __commonJS({
41656
41726
  }
41657
41727
  return output2.join("");
41658
41728
  }
41659
- function removeDotSegmentsRelative(path5) {
41660
- if (path5 === "" || path5[0] === "/") {
41661
- return removeDotSegments(path5);
41729
+ function removeDotSegmentsRelative(path6) {
41730
+ if (path6 === "" || path6[0] === "/") {
41731
+ return removeDotSegments(path6);
41662
41732
  }
41663
- const segments = path5.split("/");
41733
+ const segments = path6.split("/");
41664
41734
  const last = segments.length - 1;
41665
41735
  const output2 = [];
41666
41736
  let trailingDirectory = false;
@@ -42023,8 +42093,8 @@ var require_schemes = __commonJS({
42023
42093
  }
42024
42094
  if (wsComponent.resourceName) {
42025
42095
  const queryIndex = wsComponent.resourceName.indexOf("?");
42026
- const path5 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
42027
- wsComponent.path = path5 && path5 !== "/" ? path5 : void 0;
42096
+ const path6 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
42097
+ wsComponent.path = path6 && path6 !== "/" ? path6 : void 0;
42028
42098
  wsComponent.query = queryIndex === -1 ? void 0 : wsComponent.resourceName.slice(queryIndex + 1);
42029
42099
  wsComponent.resourceName = void 0;
42030
42100
  }
@@ -47637,15 +47707,190 @@ ${FORMAT_LEGEND}`;
47637
47707
 
47638
47708
  // src/cli.ts
47639
47709
  init_hub();
47710
+ import { spawn } from "node:child_process";
47711
+ import { mkdirSync as mkdirSync2, openSync, writeFileSync as writeFileSync2 } from "node:fs";
47712
+ import net from "node:net";
47713
+ import os4 from "node:os";
47714
+ import path5 from "node:path";
47715
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
47716
+ import { parseArgs } from "node:util";
47717
+
47718
+ // src/install.ts
47719
+ init_hub();
47720
+ import { spawnSync } from "node:child_process";
47721
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
47722
+ import os from "node:os";
47723
+ import path from "node:path";
47724
+ import { fileURLToPath } from "node:url";
47725
+ var PACKAGE_NAME = "figma-lupa";
47726
+ var SKILL = "figma-implement";
47727
+ var DAY = 24 * 60 * 60 * 1e3;
47728
+ function packageRoot() {
47729
+ return path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
47730
+ }
47731
+ function isCheckout(root = packageRoot()) {
47732
+ return existsSync(path.join(root, ".git"));
47733
+ }
47734
+ function compareVersions(a, b) {
47735
+ const parse3 = (v) => {
47736
+ const [core = "", pre] = v.trim().replace(/^v/, "").split("-", 2);
47737
+ return { nums: core.split(".").map((x2) => Number(x2) || 0), pre };
47738
+ };
47739
+ const x = parse3(a);
47740
+ const y = parse3(b);
47741
+ for (let i = 0; i < 3; i++) {
47742
+ const d = (x.nums[i] ?? 0) - (y.nums[i] ?? 0);
47743
+ if (d) return Math.sign(d);
47744
+ }
47745
+ if (x.pre === y.pre) return 0;
47746
+ if (!x.pre) return 1;
47747
+ if (!y.pre) return -1;
47748
+ return x.pre < y.pre ? -1 : 1;
47749
+ }
47750
+ function cacheDir() {
47751
+ if (process.env.LUPA_CACHE_DIR) return process.env.LUPA_CACHE_DIR;
47752
+ return path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache"), "lupa");
47753
+ }
47754
+ var updateChecksOff = () => !!process.env.LUPA_NO_UPDATE_CHECK;
47755
+ function readInfo(dir) {
47756
+ try {
47757
+ return JSON.parse(readFileSync(path.join(dir, "update.json"), "utf8"));
47758
+ } catch {
47759
+ return void 0;
47760
+ }
47761
+ }
47762
+ function writeInfo(dir, info) {
47763
+ try {
47764
+ mkdirSync(dir, { recursive: true });
47765
+ writeFileSync(path.join(dir, "update.json"), JSON.stringify(info));
47766
+ } catch {
47767
+ }
47768
+ }
47769
+ async function fetchLatest(timeoutMs = 4e3) {
47770
+ try {
47771
+ const res = await fetch(`https://registry.npmjs.org/${PACKAGE_NAME}/latest`, { signal: AbortSignal.timeout(timeoutMs) });
47772
+ if (!res.ok) return void 0;
47773
+ const body = await res.json();
47774
+ return typeof body.version === "string" ? body.version : void 0;
47775
+ } catch {
47776
+ return void 0;
47777
+ }
47778
+ }
47779
+ async function refreshUpdateInfo(dir = cacheDir(), fetchVersion = fetchLatest) {
47780
+ if (updateChecksOff()) return;
47781
+ const info = readInfo(dir);
47782
+ if (info && Date.now() - info.checkedAt < DAY) return;
47783
+ const latest = await fetchVersion();
47784
+ writeInfo(dir, { ...info, checkedAt: Date.now(), latest: latest ?? info?.latest });
47785
+ }
47786
+ function updateNotice(dir = cacheDir(), current = SERVER_VERSION) {
47787
+ if (updateChecksOff()) return void 0;
47788
+ const info = readInfo(dir);
47789
+ if (!info?.latest || compareVersions(info.latest, current) <= 0) return void 0;
47790
+ if (info.notified === info.latest && info.notifiedAt && Date.now() - info.notifiedAt < DAY) return void 0;
47791
+ writeInfo(dir, { ...info, notified: info.latest, notifiedAt: Date.now() });
47792
+ return `Lupa ${info.latest} is available (this is ${current}). To update, run: lupa update`;
47793
+ }
47794
+ function skillsDirs() {
47795
+ const home = path.join(os.homedir(), ".claude", "skills");
47796
+ const config2 = process.env.CLAUDE_CONFIG_DIR ? path.join(process.env.CLAUDE_CONFIG_DIR, "skills") : home;
47797
+ return [.../* @__PURE__ */ new Set([config2, home])];
47798
+ }
47799
+ function linkSkill(skillsDir, source = path.join(packageRoot(), "skills", SKILL)) {
47800
+ const link = path.join(skillsDir, SKILL);
47801
+ let stat2;
47802
+ try {
47803
+ stat2 = lstatSync(link);
47804
+ } catch {
47805
+ }
47806
+ let note = "";
47807
+ if (stat2?.isSymbolicLink()) {
47808
+ const target = path.resolve(skillsDir, readlinkSync(link));
47809
+ if (target === source) return `\u2713 Claude skill: ${link} \u2192 ${source}`;
47810
+ rmSync(link);
47811
+ note = ` (it pointed at ${target})`;
47812
+ } else if (stat2) {
47813
+ const backup = `${link}.old-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}`;
47814
+ rmSync(backup, { recursive: true, force: true });
47815
+ renameSync(link, backup);
47816
+ note = ` (your copy is now ${backup}; delete it when you like)`;
47817
+ }
47818
+ mkdirSync(skillsDir, { recursive: true });
47819
+ symlinkSync(source, link, process.platform === "win32" ? "junction" : "dir");
47820
+ return `\u2713 Claude skill: linked ${link} \u2192 ${source}${note}`;
47821
+ }
47822
+ async function setup(o) {
47823
+ const root = packageRoot();
47824
+ const lines = [`Lupa ${SERVER_VERSION} in ${root}${isCheckout(root) ? " (a git checkout)" : ""}`, ""];
47825
+ const dirs = o.skillsDir ? [path.resolve(o.skillsDir)] : skillsDirs().filter((d, i) => i === 0 || existsSync(path.join(d, SKILL)));
47826
+ for (const d of dirs) {
47827
+ try {
47828
+ lines.push(linkSkill(d));
47829
+ } catch (e) {
47830
+ lines.push(`\u2717 Claude skill: could not link it into ${d}: ${e.message}`);
47831
+ }
47832
+ }
47833
+ const manifest = path.join(root, "plugin", "manifest.json");
47834
+ if (existsSync(path.join(root, "plugin", "dist", "code.js"))) {
47835
+ lines.push(
47836
+ "\u2713 Figma plugin: import it once. In Figma: Plugins \u2192 Development \u2192 Import plugin from manifest\u2026, then pick",
47837
+ ` ${manifest}`,
47838
+ " Updates replace the files at this path, so you never import it again. After an update, run the plugin again."
47839
+ );
47840
+ } else {
47841
+ lines.push(`\u2717 Figma plugin: ${path.dirname(manifest)}/dist is missing. Run npm run build in ${root}.`);
47842
+ }
47843
+ try {
47844
+ lines.push(`\u2713 Browser for lupa compare --url: ${await o.checkBrowser()}`);
47845
+ } catch {
47846
+ lines.push("\u2717 Browser for lupa compare --url: none found. Run: npx playwright install chromium (or install Google Chrome, or set LUPA_BROWSER)");
47847
+ }
47848
+ lines.push(" Optional, for MCP clients without a shell: claude mcp add --scope user lupa -- lupa mcp");
47849
+ const latest = await (o.latest ?? fetchLatest)();
47850
+ if (!latest) lines.push(" Could not reach npm to check for updates.");
47851
+ else if (compareVersions(latest, SERVER_VERSION) > 0) lines.push(`\u2191 Lupa ${latest} is available. Run: lupa update`);
47852
+ else lines.push("\u2713 Up to date.");
47853
+ return lines.join("\n");
47854
+ }
47855
+ function npm(args, inherit = false) {
47856
+ return spawnSync("npm", args, { stdio: inherit ? "inherit" : "pipe", encoding: "utf8", shell: process.platform === "win32" });
47857
+ }
47858
+ async function update(latest = fetchLatest) {
47859
+ const root = packageRoot();
47860
+ if (isCheckout(root)) {
47861
+ return { code: 0, text: `This lupa runs from a git checkout. Update it with:
47862
+ cd ${root} && git pull && npm ci && npm run build` };
47863
+ }
47864
+ const version2 = await latest();
47865
+ if (!version2) return { code: 1, text: "Could not reach the npm registry. Check your connection and try again." };
47866
+ if (compareVersions(version2, SERVER_VERSION) <= 0) return { code: 0, text: `Lupa ${SERVER_VERSION} is the latest version.` };
47867
+ const globalRoot = npm(["root", "-g"]).stdout?.trim();
47868
+ if (!globalRoot || path.resolve(globalRoot) !== path.dirname(root)) {
47869
+ return {
47870
+ code: 1,
47871
+ text: `Lupa ${version2} is available, but this copy (${root}) was not installed with npm install -g. Update it with the tool that installed it, e.g. pnpm add -g ${PACKAGE_NAME}@latest.`
47872
+ };
47873
+ }
47874
+ const res = npm(["install", "-g", `${PACKAGE_NAME}@${version2}`], true);
47875
+ if (res.status !== 0) {
47876
+ return { code: 1, text: `npm install failed. Run it yourself to see why:
47877
+ npm install -g ${PACKAGE_NAME}@latest` };
47878
+ }
47879
+ return {
47880
+ code: 0,
47881
+ text: [
47882
+ `Updated Lupa ${SERVER_VERSION} \u2192 ${version2}.`,
47883
+ "- The next lupa command restarts the background hub on the new version.",
47884
+ "- In Figma, close the Lupa plugin and run it again to load its new version."
47885
+ ].join("\n")
47886
+ };
47887
+ }
47888
+
47889
+ // src/cli.ts
47640
47890
  init_legend();
47641
47891
  init_protocol();
47892
+ init_browser();
47642
47893
  init_ops();
47643
- import { spawn } from "node:child_process";
47644
- import { mkdirSync, openSync, writeFileSync } from "node:fs";
47645
- import os3 from "node:os";
47646
- import path4 from "node:path";
47647
- import { fileURLToPath as fileURLToPath2 } from "node:url";
47648
- import { parseArgs } from "node:util";
47649
47894
  var USAGE = `lupa \u2014 read Figma designs for faithful implementation (read-only)
47650
47895
 
47651
47896
  Usage: lupa <command> [target] [options]
@@ -47679,6 +47924,11 @@ Verify
47679
47924
  --image PNG or use a screenshot you took
47680
47925
  --threshold N (0\u20131, default 0.1) -o PATH
47681
47926
 
47927
+ Install
47928
+ setup Link the Claude skill, show where the Figma plugin is, check the browser
47929
+ --skills-dir DIR Claude Code's skills folder (default: $CLAUDE_CONFIG_DIR/skills or ~/.claude/skills)
47930
+ update Install the latest Lupa from npm
47931
+
47682
47932
  Other
47683
47933
  format Legend for the design output
47684
47934
  serve [--idle MIN] Run the hub in the foreground (otherwise started automatically;
@@ -47716,6 +47966,8 @@ var SPECS = {
47716
47966
  out: { type: "string", short: "o" }
47717
47967
  },
47718
47968
  format: {},
47969
+ setup: { "skills-dir": { type: "string" } },
47970
+ update: {},
47719
47971
  serve: { idle: { type: "string" } },
47720
47972
  mcp: {}
47721
47973
  };
@@ -47736,17 +47988,17 @@ function oneOf(v, key, allowed) {
47736
47988
  }
47737
47989
  var str = (v, key) => v[key];
47738
47990
  function imageDir() {
47739
- return path4.join(os3.tmpdir(), "lupa");
47991
+ return path5.join(os4.tmpdir(), "lupa");
47740
47992
  }
47741
47993
  function deliver(v, out, kind) {
47742
47994
  if (!v.images.length) return v.text;
47743
- const base = out ?? path4.join(imageDir(), `${kind}-${Date.now().toString(36)}.png`);
47744
- mkdirSync(path4.dirname(path4.resolve(base)), { recursive: true });
47745
- const ext = path4.extname(base) || ".png";
47746
- const stem = base.slice(0, base.length - path4.extname(base).length);
47995
+ const base = out ?? path5.join(imageDir(), `${kind}-${Date.now().toString(36)}.png`);
47996
+ mkdirSync2(path5.dirname(path5.resolve(base)), { recursive: true });
47997
+ const ext = path5.extname(base) || ".png";
47998
+ const stem = base.slice(0, base.length - path5.extname(base).length);
47747
47999
  const files = v.images.map((png, i) => {
47748
- const f = path4.resolve(i === 0 ? `${stem}${ext}` : `${stem}-${i + 1}${ext}`);
47749
- writeFileSync(f, png);
48000
+ const f = path5.resolve(i === 0 ? `${stem}${ext}` : `${stem}-${i + 1}${ext}`);
48001
+ writeFileSync2(f, png);
47750
48002
  return f;
47751
48003
  });
47752
48004
  return [v.text, ...files.map((f) => `image: ${f}`)].join("\n");
@@ -47825,10 +48077,10 @@ ${deliver(await lupa.screenshot({ target, file: file2 }), void 0, "screenshot")}
47825
48077
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
47826
48078
  function spawnHub(port) {
47827
48079
  const dir = imageDir();
47828
- mkdirSync(dir, { recursive: true });
47829
- const logFile = path4.join(dir, "hub.log");
48080
+ mkdirSync2(dir, { recursive: true });
48081
+ const logFile = path5.join(dir, "hub.log");
47830
48082
  const log = openSync(logFile, "a");
47831
- const entry = fileURLToPath2(import.meta.url);
48083
+ const entry = fileURLToPath3(import.meta.url);
47832
48084
  spawn(process.execPath, [...process.execArgv, entry, "serve", "--port", String(port)], {
47833
48085
  detached: true,
47834
48086
  stdio: ["ignore", log, log],
@@ -47836,9 +48088,32 @@ function spawnHub(port) {
47836
48088
  }).unref();
47837
48089
  return logFile;
47838
48090
  }
48091
+ function portInUse(port) {
48092
+ return new Promise((resolve) => {
48093
+ const s = net.connect({ port, host: "127.0.0.1" });
48094
+ s.once("connect", () => {
48095
+ s.destroy();
48096
+ resolve(true);
48097
+ });
48098
+ s.once("error", () => resolve(false));
48099
+ });
48100
+ }
48101
+ function outdatedHub(bridge) {
48102
+ return bridge.hubCanStop && !!bridge.hubVersion && compareVersions(bridge.hubVersion, SERVER_VERSION) < 0;
48103
+ }
48104
+ async function stopHub(bridge, port) {
48105
+ bridge.askHubToStop();
48106
+ await bridge.close();
48107
+ for (const until = Date.now() + 3e3; Date.now() < until && await portInUse(port); ) await sleep(100);
48108
+ }
47839
48109
  async function joinHub(port, log) {
47840
- const bridge = new Bridge({ port, role: "peer", log });
48110
+ let bridge = new Bridge({ port, role: "peer", log });
47841
48111
  try {
48112
+ await bridge.start();
48113
+ if (!outdatedHub(bridge)) return { bridge, fresh: false };
48114
+ log(`replacing the hub of Lupa ${bridge.hubVersion}`);
48115
+ await stopHub(bridge, port);
48116
+ bridge = new Bridge({ port, role: "peer", log });
47842
48117
  await bridge.start();
47843
48118
  return { bridge, fresh: false };
47844
48119
  } catch {
@@ -47855,17 +48130,21 @@ async function joinHub(port, log) {
47855
48130
  throw new Error(`Could not start the Lupa hub on port ${port} (is another program using it? set LUPA_PORT). Log: ${logFile}`);
47856
48131
  }
47857
48132
  async function serve(port, idleMin, log) {
47858
- const bridge = new Bridge({ port, role: "hub", log });
48133
+ const bridge = new Bridge({ port, role: "hub", log, onStopRequest: () => stop("a newer Lupa replaces this hub") });
47859
48134
  try {
47860
48135
  await bridge.start();
47861
48136
  } catch (e) {
47862
48137
  log(e.message);
47863
48138
  return;
47864
48139
  }
47865
- const stop = (why) => {
48140
+ function stop(why) {
47866
48141
  log(`stopping: ${why}`);
47867
48142
  bridge.close().finally(() => process.exit(0));
47868
- };
48143
+ }
48144
+ const check2 = () => refreshUpdateInfo().catch(() => {
48145
+ });
48146
+ void check2();
48147
+ setInterval(check2, 6 * 60 * 60 * 1e3);
47869
48148
  if (idleMin > 0) {
47870
48149
  setInterval(() => {
47871
48150
  if (bridge.idleMs > idleMin * 6e4) stop(`idle for ${idleMin} min`);
@@ -47876,6 +48155,11 @@ async function serve(port, idleMin, log) {
47876
48155
  await new Promise(() => {
47877
48156
  });
47878
48157
  }
48158
+ function pluginWarnings(plugins) {
48159
+ return plugins.filter((p) => p.pluginVersion && p.pluginVersion !== SERVER_VERSION).map(
48160
+ (p) => `the Lupa plugin in "${p.fileName}" is version ${p.pluginVersion}, lupa is ${SERVER_VERSION}. Close the plugin in Figma and run it again. If it keeps the old version, Figma loads it from an old folder: run lupa setup and import the manifest it shows.`
48161
+ );
48162
+ }
47879
48163
  async function runCli(argv, io = { out: (t) => process.stdout.write(`${t}
47880
48164
  `), err: (t) => process.stderr.write(`${t}
47881
48165
  `) }) {
@@ -47912,6 +48196,15 @@ Run lupa help.`);
47912
48196
  io.out(FORMAT_LEGEND);
47913
48197
  return 0;
47914
48198
  }
48199
+ if (cmd === "setup") {
48200
+ io.out(await setup({ skillsDir: str(values, "skills-dir"), checkBrowser }));
48201
+ return 0;
48202
+ }
48203
+ if (cmd === "update") {
48204
+ const r = await update();
48205
+ (r.code ? io.err : io.out)(r.text);
48206
+ return r.code;
48207
+ }
47915
48208
  const debug = !!process.env.LUPA_DEBUG;
47916
48209
  let port;
47917
48210
  let idle;
@@ -47940,6 +48233,7 @@ Run lupa help.`);
47940
48233
  const lupa = new Lupa(bridge);
47941
48234
  if (fresh) lupa.pluginWaitMs = 8e3;
47942
48235
  io.out(await run(cmd, values, positionals, lupa));
48236
+ for (const line of [...pluginWarnings(bridge.list()), updateNotice()]) if (line) io.err(`lupa: ${line}`);
47943
48237
  return 0;
47944
48238
  } catch (e) {
47945
48239
  io.err(`Error: ${e.message}`);