playground-studio 0.1.1 → 0.1.3

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
@@ -15040,9 +15040,9 @@ var require_picocolors = __commonJS({
15040
15040
  var argv = p.argv || [];
15041
15041
  var env = p.env || {};
15042
15042
  var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
15043
- var formatter = (open, close, replace = open) => (input) => {
15044
- let string = "" + input, index2 = string.indexOf(close, open.length);
15045
- return ~index2 ? open + replaceClose(string, close, replace, index2) + close : open + string + close;
15043
+ var formatter = (open2, close, replace = open2) => (input) => {
15044
+ let string = "" + input, index2 = string.indexOf(close, open2.length);
15045
+ return ~index2 ? open2 + replaceClose(string, close, replace, index2) + close : open2 + string + close;
15046
15046
  };
15047
15047
  var replaceClose = (string, close, replace, index2) => {
15048
15048
  let result = "", cursor = 0;
@@ -17073,27 +17073,27 @@ var require_util = __commonJS({
17073
17073
  };
17074
17074
  }
17075
17075
  var normalize = lruMemoize(function normalize2(aPath) {
17076
- var path16 = aPath;
17076
+ var path17 = aPath;
17077
17077
  var url = urlParse(aPath);
17078
17078
  if (url) {
17079
17079
  if (!url.path) {
17080
17080
  return aPath;
17081
17081
  }
17082
- path16 = url.path;
17082
+ path17 = url.path;
17083
17083
  }
17084
- var isAbsolute = exports.isAbsolute(path16);
17084
+ var isAbsolute = exports.isAbsolute(path17);
17085
17085
  var parts = [];
17086
17086
  var start = 0;
17087
17087
  var i = 0;
17088
17088
  while (true) {
17089
17089
  start = i;
17090
- i = path16.indexOf("/", start);
17090
+ i = path17.indexOf("/", start);
17091
17091
  if (i === -1) {
17092
- parts.push(path16.slice(start));
17092
+ parts.push(path17.slice(start));
17093
17093
  break;
17094
17094
  } else {
17095
- parts.push(path16.slice(start, i));
17096
- while (i < path16.length && path16[i] === "/") {
17095
+ parts.push(path17.slice(start, i));
17096
+ while (i < path17.length && path17[i] === "/") {
17097
17097
  i++;
17098
17098
  }
17099
17099
  }
@@ -17114,15 +17114,15 @@ var require_util = __commonJS({
17114
17114
  }
17115
17115
  }
17116
17116
  }
17117
- path16 = parts.join("/");
17118
- if (path16 === "") {
17119
- path16 = isAbsolute ? "/" : ".";
17117
+ path17 = parts.join("/");
17118
+ if (path17 === "") {
17119
+ path17 = isAbsolute ? "/" : ".";
17120
17120
  }
17121
17121
  if (url) {
17122
- url.path = path16;
17122
+ url.path = path17;
17123
17123
  return urlGenerate(url);
17124
17124
  }
17125
- return path16;
17125
+ return path17;
17126
17126
  });
17127
17127
  exports.normalize = normalize;
17128
17128
  function join(aRoot, aPath) {
@@ -18948,14 +18948,14 @@ var require_source_map = __commonJS({
18948
18948
  var require_previous_map = __commonJS({
18949
18949
  "../../node_modules/.pnpm/postcss@8.5.34/node_modules/postcss/lib/previous-map.js"(exports, module) {
18950
18950
  "use strict";
18951
- var { existsSync: existsSync6, readFileSync: readFileSync2, realpathSync: realpathSync3 } = __require("fs");
18951
+ var { existsSync: existsSync7, readFileSync: readFileSync3, realpathSync: realpathSync3 } = __require("fs");
18952
18952
  var { dirname, isAbsolute, join, relative, sep } = __require("path");
18953
18953
  var { SourceMapConsumer, SourceMapGenerator } = require_source_map();
18954
- function realPath(path16) {
18954
+ function realPath(path17) {
18955
18955
  try {
18956
- return realpathSync3(path16);
18956
+ return realpathSync3(path17);
18957
18957
  } catch {
18958
- return path16;
18958
+ return path17;
18959
18959
  }
18960
18960
  }
18961
18961
  function fromBase64(str) {
@@ -19018,19 +19018,19 @@ var require_previous_map = __commonJS({
19018
19018
  this.annotation = this.getAnnotationURL(css.substring(start, end));
19019
19019
  }
19020
19020
  }
19021
- loadFile(path16, cssFile, trusted) {
19021
+ loadFile(path17, cssFile, trusted) {
19022
19022
  if (!trusted && !this.unsafeMap) {
19023
- if (!/\.map$/i.test(path16)) return void 0;
19023
+ if (!/\.map$/i.test(path17)) return void 0;
19024
19024
  if (!cssFile) return void 0;
19025
- let rel = relative(realPath(dirname(cssFile)), realPath(path16));
19025
+ let rel = relative(realPath(dirname(cssFile)), realPath(path17));
19026
19026
  if (rel === ".." || rel.startsWith(".." + sep) || isAbsolute(rel)) {
19027
19027
  return void 0;
19028
19028
  }
19029
19029
  }
19030
- this.root = dirname(path16);
19031
- if (existsSync6(path16)) {
19032
- this.mapFile = path16;
19033
- return readFileSync2(path16, "utf-8").toString().trim();
19030
+ this.root = dirname(path17);
19031
+ if (existsSync7(path17)) {
19032
+ this.mapFile = path17;
19033
+ return readFileSync3(path17, "utf-8").toString().trim();
19034
19034
  }
19035
19035
  }
19036
19036
  loadMap(file, prev) {
@@ -19828,9 +19828,9 @@ var require_map_generator = __commonJS({
19828
19828
  if (typeof this.mapOpts.annotation === "string") {
19829
19829
  from = dirname(resolve2(from, this.mapOpts.annotation));
19830
19830
  }
19831
- let path16 = relative(from, file);
19832
- this.memoizedPaths.set(file, path16);
19833
- return path16;
19831
+ let path17 = relative(from, file);
19832
+ this.memoizedPaths.set(file, path17);
19833
+ return path17;
19834
19834
  }
19835
19835
  previous() {
19836
19836
  if (!this.previousMaps) {
@@ -19885,12 +19885,12 @@ var require_map_generator = __commonJS({
19885
19885
  return window.btoa(unescape(encodeURIComponent(str)));
19886
19886
  }
19887
19887
  }
19888
- toFileUrl(path16) {
19889
- let cached = this.memoizedFileURLs.get(path16);
19888
+ toFileUrl(path17) {
19889
+ let cached = this.memoizedFileURLs.get(path17);
19890
19890
  if (cached) return cached;
19891
19891
  if (pathToFileURL) {
19892
- let fileURL = pathToFileURL(path16).toString();
19893
- this.memoizedFileURLs.set(path16, fileURL);
19892
+ let fileURL = pathToFileURL(path17).toString();
19893
+ this.memoizedFileURLs.set(path17, fileURL);
19894
19894
  return fileURL;
19895
19895
  } else {
19896
19896
  throw new Error(
@@ -19898,14 +19898,14 @@ var require_map_generator = __commonJS({
19898
19898
  );
19899
19899
  }
19900
19900
  }
19901
- toUrl(path16) {
19902
- let cached = this.memoizedURLs.get(path16);
19901
+ toUrl(path17) {
19902
+ let cached = this.memoizedURLs.get(path17);
19903
19903
  if (cached) return cached;
19904
19904
  if (sep === "\\") {
19905
- path16 = path16.replace(/\\/g, "/");
19905
+ path17 = path17.replace(/\\/g, "/");
19906
19906
  }
19907
- let url = encodeURI(path16).replace(/[#?]/g, encodeURIComponent);
19908
- this.memoizedURLs.set(path16, url);
19907
+ let url = encodeURI(path17).replace(/[#?]/g, encodeURIComponent);
19908
+ this.memoizedURLs.set(path17, url);
19909
19909
  return url;
19910
19910
  }
19911
19911
  };
@@ -19960,7 +19960,7 @@ var require_parser = __commonJS({
19960
19960
  let prev;
19961
19961
  let shift;
19962
19962
  let last = false;
19963
- let open = false;
19963
+ let open2 = false;
19964
19964
  let params = [];
19965
19965
  let brackets = [];
19966
19966
  while (!this.tokenizer.endOfFile()) {
@@ -19980,7 +19980,7 @@ var require_parser = __commonJS({
19980
19980
  this.semicolon = true;
19981
19981
  break;
19982
19982
  } else if (type === "{") {
19983
- open = true;
19983
+ open2 = true;
19984
19984
  break;
19985
19985
  } else if (type === "}") {
19986
19986
  if (params.length > 0) {
@@ -20022,7 +20022,7 @@ var require_parser = __commonJS({
20022
20022
  node.raws.afterName = "";
20023
20023
  node.params = "";
20024
20024
  }
20025
- if (open) {
20025
+ if (open2) {
20026
20026
  node.nodes = [];
20027
20027
  this.current = node;
20028
20028
  }
@@ -21961,17 +21961,17 @@ __export(setup_exports, {
21961
21961
  runSetup: () => runSetup
21962
21962
  });
21963
21963
  import { spawnSync } from "node:child_process";
21964
- import { accessSync as accessSync2, constants as constants2, existsSync as existsSync5, lstatSync, mkdirSync, realpathSync, symlinkSync, unlinkSync } from "node:fs";
21964
+ import { accessSync as accessSync2, constants as constants2, existsSync as existsSync6, lstatSync, mkdirSync, readFileSync, realpathSync, symlinkSync, unlinkSync } from "node:fs";
21965
21965
  import { createInterface } from "node:readline/promises";
21966
21966
  import { homedir } from "node:os";
21967
- import path13 from "node:path";
21967
+ import path14 from "node:path";
21968
21968
  function exec(cmd, args) {
21969
21969
  const r = spawnSync(cmd, args, { encoding: "utf8", shell: win, timeout: 3e4 });
21970
21970
  return { ok: r.status === 0, out: `${r.stdout ?? ""}${r.stderr ?? ""}` };
21971
21971
  }
21972
- async function runSetup({ cliPath, yes }) {
21972
+ async function runSetup({ cliPath: from, yes }) {
21973
+ let cliPath = from;
21973
21974
  const shown = (cmd) => cmd.map((a) => /[\s"]/.test(a) ? JSON.stringify(a) : a).join(" ");
21974
- const server = ["node", cliPath, "mcp"];
21975
21975
  const interactive = !yes && !!process.stdin.isTTY;
21976
21976
  let rl = null;
21977
21977
  const ask = async (q) => {
@@ -21992,16 +21992,46 @@ async function runSetup({ cliPath, yes }) {
21992
21992
  return 1;
21993
21993
  }
21994
21994
  ok(`Node ${process.versions.node}`);
21995
+ if (fromNpx(cliPath)) {
21996
+ const want = versionOf(cliPath);
21997
+ const spec = `playground-studio@${want ?? "latest"}`;
21998
+ const installed = () => {
21999
+ const root2 = exec("npm", ["root", "-g"]);
22000
+ const found2 = [
22001
+ ...pathDirs().map((d) => path14.join(d, "pg-studio")).filter((p) => existsSync6(p)).map(real),
22002
+ root2.ok ? path14.join(root2.out.trim().split("\n").pop(), "playground-studio", "dist", "cli.js") : ""
22003
+ ];
22004
+ return found2.find((c) => c && !fromNpx(c) && existsSync6(c) && versionOf(c) === want) ?? null;
22005
+ };
22006
+ let kept = installed();
22007
+ if (kept) ok(`Playground ${want} is installed ${dim(path14.dirname(path14.dirname(kept)))}`);
22008
+ else if (await ask(`Install Playground for good (npm install -g ${spec}), so your agents can start it after npx clears its cache?`)) {
22009
+ const r = spawnSync("npm", ["install", "-g", spec], { stdio: ["ignore", "ignore", "inherit"], shell: win, timeout: 3e5 });
22010
+ kept = r.status === 0 ? installed() : null;
22011
+ if (!kept) {
22012
+ warn(r.status === 0 ? "Installed, but the pg-studio command isn\u2019t on your PATH. Add npm\u2019s global bin folder to it, then run pg-studio setup." : "npm couldn\u2019t install it. Run this, then pg-studio setup:");
22013
+ if (r.status !== 0) indent(`npm install -g ${spec}`);
22014
+ return 1;
22015
+ }
22016
+ ok(`Installed Playground ${want} ${dim(path14.dirname(path14.dirname(kept)))}`);
22017
+ } else {
22018
+ warn(interactive ? "Nothing changed. Your agents need a copy that stays, so to set up later, run:" : "Nothing changed. Run this, or run setup with --yes:");
22019
+ indent("npm install -g playground-studio && pg-studio setup");
22020
+ return 0;
22021
+ }
22022
+ cliPath = kept;
22023
+ }
22024
+ const server = ["node", cliPath, "mcp"];
21995
22025
  const found = which("pg-studio");
21996
22026
  if (found && real(found) === real(cliPath)) ok(`The pg-studio command is ready ${dim(found)}`);
21997
22027
  else if (found) skip(`A pg-studio command is already at ${found}. Left as it is.`);
21998
- else if (win) skip(`To start Playground from any folder, run: npm install -g ${path13.dirname(path13.dirname(cliPath))}`);
22028
+ else if (win) skip(`To start Playground from any folder, run: npm install -g ${path14.dirname(path14.dirname(cliPath))}`);
21999
22029
  else {
22000
22030
  const npmBin = exec("npm", ["prefix", "-g"]);
22001
- const dirs = [npmBin.ok ? path13.join(npmBin.out.trim().split("\n").pop(), "bin") : "", path13.join(homedir(), ".local", "bin")];
22031
+ const dirs = [npmBin.ok ? path14.join(npmBin.out.trim().split("\n").pop(), "bin") : "", path14.join(homedir(), ".local", "bin")];
22002
22032
  const onPath = new Set(pathDirs().map(real));
22003
22033
  const dir = dirs.find((d) => d && onPath.has(real(d)) && writable(d));
22004
- const link = dir && path13.join(dir, "pg-studio");
22034
+ const link = dir && path14.join(dir, "pg-studio");
22005
22035
  if (!link) {
22006
22036
  warn("No folder on your PATH can take the pg-studio command. Start Playground with:");
22007
22037
  indent(shown(["node", cliPath]));
@@ -22074,7 +22104,7 @@ Nothing is connected yet. Run ${bold("pg-studio setup")} again when you want to.
22074
22104
  );
22075
22105
  return 0;
22076
22106
  }
22077
- var win, tty, paint, dim, bold, ok, warn, skip, indent, pathDirs, real, writable, which;
22107
+ var win, tty, paint, dim, bold, ok, warn, skip, indent, fromNpx, pathDirs, real, writable, which, versionOf;
22078
22108
  var init_setup = __esm({
22079
22109
  "src/setup.ts"() {
22080
22110
  "use strict";
@@ -22087,7 +22117,8 @@ var init_setup = __esm({
22087
22117
  warn = (s) => console.log(`${paint(33)("!")} ${s}`);
22088
22118
  skip = (s) => console.log(`${dim("\u2013")} ${s}`);
22089
22119
  indent = (s) => console.log(` ${dim(s)}`);
22090
- pathDirs = () => (process.env.PATH ?? "").split(path13.delimiter).filter(Boolean);
22120
+ fromNpx = (cli) => /[\\/]_npx[\\/]/.test(cli);
22121
+ pathDirs = () => (process.env.PATH ?? "").split(path14.delimiter).filter(Boolean);
22091
22122
  real = (p) => {
22092
22123
  try {
22093
22124
  return realpathSync(p);
@@ -22103,7 +22134,14 @@ var init_setup = __esm({
22103
22134
  return false;
22104
22135
  }
22105
22136
  };
22106
- which = (name) => pathDirs().map((d) => path13.join(d, name)).find((p) => existsSync5(p)) ?? null;
22137
+ which = (name) => pathDirs().map((d) => path14.join(d, name)).find((p) => existsSync6(p) && !fromNpx(p)) ?? null;
22138
+ versionOf = (cli) => {
22139
+ try {
22140
+ return JSON.parse(readFileSync(path14.join(path14.dirname(cli), "..", "package.json"), "utf8")).version ?? null;
22141
+ } catch {
22142
+ return null;
22143
+ }
22144
+ };
22107
22145
  }
22108
22146
  });
22109
22147
 
@@ -22115,10 +22153,10 @@ __export(bridge_exports, {
22115
22153
  runBridge: () => runBridge,
22116
22154
  runWait: () => runWait
22117
22155
  });
22118
- import { spawn as spawn4 } from "node:child_process";
22156
+ import { spawn as spawn6 } from "node:child_process";
22119
22157
  import { randomUUID as randomUUID2 } from "node:crypto";
22120
- import { mkdirSync as mkdirSync2, openSync, readFileSync, realpathSync as realpathSync2, writeFileSync } from "node:fs";
22121
- import path14 from "node:path";
22158
+ import { mkdirSync as mkdirSync2, openSync, readFileSync as readFileSync2, realpathSync as realpathSync2, writeFileSync } from "node:fs";
22159
+ import path15 from "node:path";
22122
22160
  import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
22123
22161
  import { Server } from "@modelcontextprotocol/server";
22124
22162
  import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
@@ -22133,8 +22171,8 @@ async function health(port2) {
22133
22171
  async function ensureDaemon(root2, firstPort, cliPath) {
22134
22172
  const want = real2(root2);
22135
22173
  let free = null;
22136
- const dir = path14.join(want, ".playground");
22137
- const pidFile = path14.join(dir, "daemon.pid");
22174
+ const dir = path15.join(want, ".playground");
22175
+ const pidFile = path15.join(dir, "daemon.pid");
22138
22176
  for (let port2 = firstPort; port2 < firstPort + 20; port2++) {
22139
22177
  const h = await health(port2);
22140
22178
  if (h?.project && real2(h.project.root) === want) {
@@ -22148,8 +22186,8 @@ async function ensureDaemon(root2, firstPort, cliPath) {
22148
22186
  }
22149
22187
  if (free === null) throw new Error(`No free port between ${firstPort} and ${firstPort + 19} to start Playground on.`);
22150
22188
  mkdirSync2(dir, { recursive: true });
22151
- const log = openSync(path14.join(dir, "daemon.log"), "a");
22152
- const child = spawn4(process.execPath, [...process.execArgv, cliPath, want, "--port", String(free), "--no-open"], {
22189
+ const log = openSync(path15.join(dir, "daemon.log"), "a");
22190
+ const child = spawn6(process.execPath, [...process.execArgv, cliPath, want, "--port", String(free), "--no-open"], {
22153
22191
  cwd: want,
22154
22192
  detached: true,
22155
22193
  stdio: ["ignore", log, log]
@@ -22171,11 +22209,11 @@ async function ensureDaemon(root2, firstPort, cliPath) {
22171
22209
  return null;
22172
22210
  })();
22173
22211
  if (again) return again;
22174
- throw new Error(`Playground did not start. See ${path14.join(dir, "daemon.log")}.`);
22212
+ throw new Error(`Playground did not start. See ${path15.join(dir, "daemon.log")}.`);
22175
22213
  }
22176
22214
  function readPid(file) {
22177
22215
  try {
22178
- return Number(readFileSync(file, "utf8").trim()) || null;
22216
+ return Number(readFileSync2(file, "utf8").trim()) || null;
22179
22217
  } catch {
22180
22218
  return null;
22181
22219
  }
@@ -22353,7 +22391,7 @@ var init_bridge = __esm({
22353
22391
  try {
22354
22392
  return realpathSync2(p);
22355
22393
  } catch {
22356
- return path14.resolve(p);
22394
+ return path15.resolve(p);
22357
22395
  }
22358
22396
  };
22359
22397
  INSTRUCTIONS = `Playground (pg-studio) is the designer's canvas for this project. When a <channel source="pg-studio"> message arrives, the designer wants you in Playground: call wait_for_handback right away and do what it returns, as you would after opening a screen.`;
@@ -22363,16 +22401,16 @@ var init_bridge = __esm({
22363
22401
 
22364
22402
  // src/cli.ts
22365
22403
  import { statSync as statSync2 } from "node:fs";
22366
- import path15 from "node:path";
22367
- import { spawn as spawn5 } from "node:child_process";
22404
+ import path16 from "node:path";
22405
+ import { spawn as spawn7 } from "node:child_process";
22368
22406
  import { fileURLToPath as fileURLToPath2 } from "node:url";
22369
22407
  import { parseArgs } from "node:util";
22370
22408
 
22371
22409
  // ../daemon/src/server.ts
22372
22410
  import { createServer as createServer2 } from "node:http";
22373
- import { readFile as readFile8, realpath as realpath3, stat as stat4 } from "node:fs/promises";
22411
+ import { readFile as readFile9, realpath as realpath4, stat as stat4 } from "node:fs/promises";
22374
22412
  import { fileURLToPath } from "node:url";
22375
- import path12 from "node:path";
22413
+ import path13 from "node:path";
22376
22414
  import { localhostHostValidation, localhostOriginValidation, NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node";
22377
22415
  import { WebSocketServer } from "ws";
22378
22416
 
@@ -22478,7 +22516,7 @@ var LayoutGrid = z.object({
22478
22516
  align: z.enum(["stretch", "start", "center", "end"]).optional()
22479
22517
  });
22480
22518
  var ExportSetting = z.object({
22481
- format: z.enum(["png", "jpg", "pdf"]),
22519
+ format: z.enum(["png", "jpg", "pdf", "html"]),
22482
22520
  scale: z.number().min(0.25).max(4)
22483
22521
  });
22484
22522
  var Constraints = z.object({
@@ -22519,6 +22557,8 @@ var Node = z.object({
22519
22557
  /** Image layers only: a URL the daemon serves, e.g. /files/ab12.png. */
22520
22558
  src: z.string().optional(),
22521
22559
  fit: z.enum(["fill", "cover", "contain"]).optional(),
22560
+ /** Image layers only: a reference the designer put beside the design (a screenshot, a moodboard). Sent to the agent as context, never a change. */
22561
+ reference: z.boolean().optional(),
22522
22562
  /** CSS box-shadow from older imports. `effects` replaces it once edited. */
22523
22563
  shadow: z.string().optional(),
22524
22564
  /** Shadows and blurs, front to back. */
@@ -22948,6 +22988,8 @@ function diffDocs(before, after) {
22948
22988
  const pathIn = (doc, id) => id ? layerPath(doc, id) : null;
22949
22989
  const drafts = variantLayers(after);
22950
22990
  const oldDrafts = variantLayers(before);
22991
+ for (const [id, n] of Object.entries(after.nodes)) if (n.reference) drafts.add(id);
22992
+ for (const [id, n] of Object.entries(before.nodes)) if (n.reference) oldDrafts.add(id);
22951
22993
  for (const id of Object.keys(after.nodes)) {
22952
22994
  if (drafts.has(id)) continue;
22953
22995
  const a = after.nodes[id];
@@ -23763,9 +23805,9 @@ function lin(c) {
23763
23805
  function colorDistance(a, b) {
23764
23806
  const [r1, g1, b1] = hexRgb(a);
23765
23807
  const [r24, g2, b2] = hexRgb(b);
23766
- const rm3 = (r1 + r24) / 2;
23808
+ const rm4 = (r1 + r24) / 2;
23767
23809
  const dr = r1 - r24, dg = g1 - g2, db = b1 - b2;
23768
- return Math.sqrt((2 + rm3 / 256) * dr * dr + 4 * dg * dg + (2 + (255 - rm3) / 256) * db * db) / 3;
23810
+ return Math.sqrt((2 + rm4 / 256) * dr * dr + 4 * dg * dg + (2 + (255 - rm4) / 256) * db * db) / 3;
23769
23811
  }
23770
23812
  function hexHsl(hex3) {
23771
23813
  const [r, g, b] = hexRgb(hex3).map((v) => v / 255);
@@ -24250,26 +24292,34 @@ function inGroup(cls, group, scale = TW_DEFAULT) {
24250
24292
  return /^opacity-/.test(c);
24251
24293
  }
24252
24294
  }
24253
- var base = (c) => c.includes(":") ? null : c;
24254
- function replaceGroup(classes, group, next, scale = TW_DEFAULT) {
24295
+ var TW_SCREENS = { sm: 640, md: 768, lg: 1024, xl: 1280, "2xl": 1536 };
24296
+ var isScreen = (s) => typeof s === "string" && s in TW_SCREENS;
24297
+ var atScreen = (c, screen) => screen ? c.startsWith(`${screen}:`) && !c.slice(screen.length + 1).includes(":") ? c.slice(screen.length + 1) : null : c.includes(":") ? null : c;
24298
+ var base = (c) => atScreen(c, null);
24299
+ function replaceGroup(classes, group, next, scale = TW_DEFAULT, screen) {
24255
24300
  const out = [];
24256
24301
  let at = -1;
24302
+ let after = -1;
24257
24303
  for (const c of classes) {
24258
- const b = base(c);
24304
+ const b = atScreen(c, screen);
24259
24305
  if (b && inGroup(b, group, scale)) {
24260
24306
  if (at < 0) at = out.length;
24261
24307
  continue;
24262
24308
  }
24263
24309
  out.push(c);
24310
+ const plain2 = base(c);
24311
+ if (screen && plain2 && inGroup(plain2, group, scale)) after = out.length;
24264
24312
  }
24265
- const add = next.filter((c) => !out.includes(c));
24266
- if (at < 0) return [...out, ...add];
24267
- return [...out.slice(0, at), ...add, ...out.slice(at)];
24313
+ const want = screen ? next.map((c) => `${screen}:${c}`) : next;
24314
+ const add = want.filter((c) => !out.includes(c));
24315
+ const where = at >= 0 ? at : after;
24316
+ if (where < 0) return [...out, ...add];
24317
+ return [...out.slice(0, where), ...add, ...out.slice(where)];
24268
24318
  }
24269
- function rewriteClassString(text2, group, next, scale = TW_DEFAULT) {
24319
+ function rewriteClassString(text2, group, next, scale = TW_DEFAULT, screen) {
24270
24320
  const tokens = text2.split(/(\s+)/);
24271
24321
  const words2 = tokens.filter((t, i) => i % 2 === 0 && t);
24272
- const updated = replaceGroup(words2, group, next, scale);
24322
+ const updated = replaceGroup(words2, group, next, scale, screen);
24273
24323
  if (updated.join(" ") === words2.join(" ")) return text2;
24274
24324
  return text2.match(/^\s*/)[0] + updated.join(" ") + text2.match(/\s*$/)[0];
24275
24325
  }
@@ -24441,7 +24491,7 @@ function planAnimations(i, phase2, counts, reduced = false) {
24441
24491
  const out = [];
24442
24492
  const press = i.kind === "press";
24443
24493
  const tracks = activeTracks(i);
24444
- const run4 = (who, index2, extra) => {
24494
+ const run5 = (who, index2, extra) => {
24445
24495
  if (reduced) {
24446
24496
  const fade2 = [{ opacity: press ? 1 : 0 }, { opacity: 1 }];
24447
24497
  const d = Math.min(150, p.duration);
@@ -24459,10 +24509,10 @@ function planAnimations(i, phase2, counts, reduced = false) {
24459
24509
  };
24460
24510
  if (i.kind === "text") {
24461
24511
  const steps = staggerSteps(counts.pieces, i.order ?? "first");
24462
- for (let k = 0; k < counts.pieces; k++) run4("piece", k, steps[k] * i.stagger);
24512
+ for (let k = 0; k < counts.pieces; k++) run5("piece", k, steps[k] * i.stagger);
24463
24513
  return out;
24464
24514
  }
24465
- run4("self", 0, 0);
24515
+ run5("self", 0, 0);
24466
24516
  if (phase2 === "enter" && i.stagger > 0 && i.items > 1 && !reduced && counts.items) {
24467
24517
  const steps = staggerSteps(counts.items, i.order ?? "first");
24468
24518
  for (let k = 0; k < counts.items; k++) {
@@ -26847,9 +26897,9 @@ async function readTokens(root2) {
26847
26897
  return { colors, fonts: f.fonts, ...f.radius !== void 0 ? { radius: f.radius } : {}, sources: [...f.sources] };
26848
26898
  }
26849
26899
  var DARK_SEL = /(?:\.dark|\[data-theme=["']?dark["']?\]|\[data-mode=["']?dark["']?\])[^{,]*\{/g;
26850
- function blockEnd(css, open) {
26900
+ function blockEnd(css, open2) {
26851
26901
  let depth = 1;
26852
- let i = open;
26902
+ let i = open2;
26853
26903
  while (i < css.length && depth) {
26854
26904
  if (css[i] === "{") depth++;
26855
26905
  else if (css[i] === "}") depth--;
@@ -26931,10 +26981,10 @@ async function sourceFiles(root2, limit2 = 800) {
26931
26981
  }
26932
26982
  return out;
26933
26983
  }
26934
- function objectKeys(src, open) {
26984
+ function objectKeys(src, open2) {
26935
26985
  const keys = [];
26936
26986
  let depth = 0;
26937
- let i = open;
26987
+ let i = open2;
26938
26988
  let str = null;
26939
26989
  for (; i < src.length; i++) {
26940
26990
  const c = src[i];
@@ -26956,8 +27006,8 @@ function objectKeys(src, open) {
26956
27006
  }
26957
27007
  if (depth === 1) {
26958
27008
  const m = /^\s*["']?([\w-]+)["']?\s*:/.exec(src.slice(i, i + 60));
26959
- const prev = src.slice(Math.max(open, i - 1), i);
26960
- if (m && (i === open + 1 || /[,{\s]/.test(prev)) && /[\s,{]/.test(src[i - 1] ?? " ")) {
27009
+ const prev = src.slice(Math.max(open2, i - 1), i);
27010
+ if (m && (i === open2 + 1 || /[,{\s]/.test(prev)) && /[\s,{]/.test(src[i - 1] ?? " ")) {
26961
27011
  keys.push({ key: m[1], at: i + m[0].length });
26962
27012
  i += m[0].length - 1;
26963
27013
  }
@@ -26968,9 +27018,9 @@ function objectKeys(src, open) {
26968
27018
  function readVariants(src) {
26969
27019
  const at = src.search(/variants\s*:\s*\{/);
26970
27020
  if (at < 0) return {};
26971
- const open = src.indexOf("{", at);
27021
+ const open2 = src.indexOf("{", at);
26972
27022
  const out = {};
26973
- for (const { key, at: valAt } of objectKeys(src, open)) {
27023
+ for (const { key, at: valAt } of objectKeys(src, open2)) {
26974
27024
  const brace = src.slice(valAt).search(/\S/);
26975
27025
  if (src[valAt + brace] !== "{") continue;
26976
27026
  const values3 = objectKeys(src, valAt + brace).map((k) => k.key);
@@ -27992,7 +28042,7 @@ function findElement(text2, line, tag) {
27992
28042
  if (!el) return { ok: false, reason: `There's no <${tag || "element"}> at line ${line} any more. Save, let the page reload, then try again.` };
27993
28043
  return { ok: true, ast, el };
27994
28044
  }
27995
- function writeClasses(text2, line, tag, group, next, scale) {
28045
+ function writeClasses(text2, line, tag, group, next, scale, screen) {
27996
28046
  const found0 = findElement(text2, line, tag);
27997
28047
  if (!found0.ok) return found0;
27998
28048
  const { el } = found0;
@@ -28003,18 +28053,19 @@ function writeClasses(text2, line, tag, group, next, scale) {
28003
28053
  }
28004
28054
  const name = el.name;
28005
28055
  const at = name.end;
28006
- const add = ` className="${next.join(" ")}"`;
28007
- return { ok: true, text: text2.slice(0, at) + add + text2.slice(at), before: "", after: next.join(" "), .../^[A-Z]/.test(nameOf(el)) ? { note: `Added className to <${nameOf(el)}>; it applies if the component passes it on.` } : {} };
28056
+ const cls = (screen ? next.map((c) => `${screen}:${c}`) : next).join(" ");
28057
+ const add = ` className="${cls}"`;
28058
+ return { ok: true, text: text2.slice(0, at) + add + text2.slice(at), before: "", after: cls, .../^[A-Z]/.test(nameOf(el)) ? { note: `Added className to <${nameOf(el)}>; it applies if the component passes it on.` } : {} };
28008
28059
  }
28009
28060
  const value = attr.value;
28010
28061
  const found = value ? slots(value) : null;
28011
28062
  if (!found) return { ok: false, reason: `The classes on <${nameOf(el)}> come from a variable, so Playground can't change them safely. Hand this one to your agent.` };
28012
- const has = (s) => words(text2.slice(s.start, s.end)).some((c) => !c.includes(":") && inGroup(c, group, scale));
28063
+ const has = (s) => words(text2.slice(s.start, s.end)).some((c) => [atScreen(c, null), screen ? atScreen(c, screen) : null].some((b) => b && inGroup(b, group, scale)));
28013
28064
  const fixed = found.filter((s) => !s.conditional);
28014
28065
  const slot = fixed.find(has) ?? fixed[0];
28015
28066
  if (!slot) return { ok: false, reason: `Every class on <${nameOf(el)}> depends on a condition, so Playground can't tell which to change. Hand this one to your agent.` };
28016
28067
  const before = text2.slice(slot.start, slot.end);
28017
- const after = rewriteClassString(before, group, next, scale);
28068
+ const after = rewriteClassString(before, group, next, scale, screen);
28018
28069
  const also = found.filter((s) => s.conditional && has(s));
28019
28070
  return {
28020
28071
  ok: true,
@@ -28303,14 +28354,14 @@ function appendDecl(text2, c, base2, prop, value) {
28303
28354
  ` };
28304
28355
  }
28305
28356
  const r = c;
28306
- const open = text2.indexOf("{", base2 + r.source.start.offset) + 1;
28357
+ const open2 = text2.indexOf("{", base2 + r.source.start.offset) + 1;
28307
28358
  const close = base2 + r.source.end.offset - 1;
28308
28359
  const outer = (r.raws.before ?? "").split("\n").at(-1) ?? "";
28309
28360
  const inner = (r.nodes ?? []).find((n) => n.raws.before?.includes("\n"))?.raws.before?.split("\n").at(-1) ?? `${outer} `;
28310
- if (!text2.slice(open, close).trim()) return { start: open, end: close, text: `
28361
+ if (!text2.slice(open2, close).trim()) return { start: open2, end: close, text: `
28311
28362
  ${inner}${prop}: ${value};
28312
28363
  ${outer}` };
28313
- return { start: open, end: open, text: `
28364
+ return { start: open2, end: open2, text: `
28314
28365
  ${inner}${prop}: ${value};` };
28315
28366
  }
28316
28367
  function restoreContainer(text2, c, base2, group, before) {
@@ -29014,8 +29065,9 @@ import { McpServer } from "@modelcontextprotocol/server";
29014
29065
  import { z as z4 } from "zod";
29015
29066
 
29016
29067
  // ../daemon/src/devserver.ts
29017
- import { execFile as execFile2 } from "node:child_process";
29018
- import { readFile as readFile4, readlink, realpath } from "node:fs/promises";
29068
+ import { execFile as execFile2, spawn as spawn2 } from "node:child_process";
29069
+ import { existsSync as existsSync4 } from "node:fs";
29070
+ import { mkdir as mkdir3, open, readFile as readFile4, readlink, realpath } from "node:fs/promises";
29019
29071
  import path7 from "node:path";
29020
29072
  import { promisify as promisify2 } from "node:util";
29021
29073
  var run2 = promisify2(execFile2);
@@ -29086,26 +29138,119 @@ async function findDevServers(root2, skipPorts = []) {
29086
29138
  );
29087
29139
  return found.sort((a, b) => a.port - b.port);
29088
29140
  }
29089
- async function devCommand(root2) {
29141
+ async function devScript(root2) {
29090
29142
  try {
29091
29143
  const pkg = JSON.parse(await readFile4(path7.join(root2, "package.json"), "utf8"));
29092
29144
  const scripts = pkg.scripts ?? {};
29093
- const name = ["dev", "start", "serve"].find((s) => scripts[s]);
29094
- if (!name) return null;
29095
- const pm = pkg.packageManager?.split("@")[0] ?? (await exists(path7.join(root2, "pnpm-lock.yaml")) ? "pnpm" : await exists(path7.join(root2, "yarn.lock")) ? "yarn" : await exists(path7.join(root2, "bun.lockb")) ? "bun" : "npm");
29096
- return `${pm} run ${name}`;
29145
+ const script = ["dev", "start", "serve"].find((s) => scripts[s]);
29146
+ if (!script) return null;
29147
+ const lock = (f) => existsSync4(path7.join(root2, f));
29148
+ const pm = pkg.packageManager?.split("@")[0] ?? (lock("pnpm-lock.yaml") ? "pnpm" : lock("yarn.lock") ? "yarn" : lock("bun.lockb") || lock("bun.lock") ? "bun" : "npm");
29149
+ return { pm, script };
29097
29150
  } catch {
29098
29151
  return null;
29099
29152
  }
29100
29153
  }
29101
- async function exists(p) {
29102
- try {
29103
- await readFile4(p);
29104
- return true;
29105
- } catch {
29106
- return false;
29107
- }
29154
+ async function devCommand(root2) {
29155
+ const d = await devScript(root2);
29156
+ return d && `${d.pm} run ${d.script}`;
29108
29157
  }
29158
+ var DevServerStarter = class {
29159
+ constructor(root2, dir, host, patience = 4e4, limit2 = 18e4) {
29160
+ this.root = root2;
29161
+ this.dir = dir;
29162
+ this.host = host;
29163
+ this.patience = patience;
29164
+ this.limit = limit2;
29165
+ }
29166
+ root;
29167
+ dir;
29168
+ host;
29169
+ patience;
29170
+ limit;
29171
+ child = null;
29172
+ ready = null;
29173
+ command = "";
29174
+ /** Whether Playground started the running one. */
29175
+ get running() {
29176
+ return !!this.child && this.child.exitCode === null && this.child.signalCode === null;
29177
+ }
29178
+ /** A running dev server for the project: one already there, or one Playground starts now. */
29179
+ async ensure(skipPorts = []) {
29180
+ const found = await findDevServers(this.root, skipPorts);
29181
+ if (found.length) return { ok: true, server: found[0], started: false };
29182
+ if (process.env.PG_NO_DEVSERVER) return { ok: false, starting: false, reason: "starting dev servers is turned off (PG_NO_DEVSERVER)" };
29183
+ this.ready ??= this.start(skipPorts).finally(() => this.ready = null);
29184
+ const waited = await Promise.race([this.ready, new Promise((r) => setTimeout(() => r(null), this.patience).unref())]);
29185
+ return waited ?? { ok: false, starting: true, command: this.command };
29186
+ }
29187
+ async start(skipPorts) {
29188
+ const dev = await devScript(this.root);
29189
+ if (!dev) return { ok: false, starting: false, reason: "package.json has no dev, start or serve script" };
29190
+ this.command = `${dev.pm} run ${dev.script}`;
29191
+ if (!existsSync4(path7.join(this.root, "node_modules"))) {
29192
+ return { ok: false, starting: false, reason: `its dependencies aren't installed. Run \`${dev.pm} install\`, then try again` };
29193
+ }
29194
+ await mkdir3(this.dir, { recursive: true });
29195
+ const logFile = path7.join(this.dir, "devserver.log");
29196
+ const out = await open(logFile, "w");
29197
+ this.host.notify("info", `Starting your dev server (${this.command})\u2026`);
29198
+ this.host.log(`starting the dev server: ${this.command}`);
29199
+ const win2 = process.platform === "win32";
29200
+ const child = spawn2(dev.pm, ["run", dev.script], {
29201
+ cwd: this.root,
29202
+ detached: !win2,
29203
+ shell: win2,
29204
+ stdio: ["ignore", out.fd, out.fd],
29205
+ // BROWSER=none: Create React App and others open a browser tab on start otherwise.
29206
+ env: { ...process.env, BROWSER: "none", FORCE_COLOR: "0", NO_COLOR: "1" }
29207
+ });
29208
+ void out.close();
29209
+ this.child = child;
29210
+ let exited = null;
29211
+ child.on("error", (err) => exited = err.message);
29212
+ child.on("exit", (code, signal) => {
29213
+ exited ??= signal ? `it stopped (${signal})` : `it exited with code ${code}`;
29214
+ if (this.child === child) this.child = null;
29215
+ });
29216
+ const tail = async () => {
29217
+ const text2 = (await readFile4(logFile, "utf8").catch(() => "")).replace(/\x1b\[[0-9;]*m/g, "");
29218
+ const lines = text2.trim().split("\n").filter(Boolean).slice(-6).join("\n");
29219
+ return lines ? `
29220
+ Last lines of .playground/devserver.log:
29221
+ ${lines}` : "";
29222
+ };
29223
+ const until = Date.now() + this.limit;
29224
+ while (Date.now() < until) {
29225
+ await new Promise((r) => setTimeout(r, 400));
29226
+ if (exited) {
29227
+ this.host.notify("error", `Your dev server didn't start: ${exited}.`);
29228
+ return { ok: false, starting: false, reason: `\`${this.command}\` didn't start a server: ${exited}.${await tail()}` };
29229
+ }
29230
+ const found = await findDevServers(this.root, skipPorts);
29231
+ if (found.length) {
29232
+ this.host.notify("success", `Started your dev server on ${found[0].url}`);
29233
+ this.host.log(`dev server ready on ${found[0].url}`);
29234
+ return { ok: true, server: found[0], started: true };
29235
+ }
29236
+ }
29237
+ this.stop();
29238
+ this.host.notify("error", `Your dev server didn't answer within ${Math.round(this.limit / 1e3)} seconds, so Playground stopped it.`);
29239
+ return { ok: false, starting: false, reason: `\`${this.command}\` didn't serve a page within ${Math.round(this.limit / 1e3)} seconds.${await tail()}` };
29240
+ }
29241
+ /** Stops the dev server Playground started, and everything it started. */
29242
+ stop() {
29243
+ const child = this.child;
29244
+ this.child = null;
29245
+ if (!child?.pid || child.exitCode !== null) return;
29246
+ try {
29247
+ if (process.platform === "win32") spawn2("taskkill", ["/pid", String(child.pid), "/t", "/f"], { stdio: "ignore" });
29248
+ else process.kill(-child.pid, "SIGTERM");
29249
+ } catch {
29250
+ child.kill("SIGTERM");
29251
+ }
29252
+ }
29253
+ };
29109
29254
 
29110
29255
  // ../daemon/src/mcp.ts
29111
29256
  var requestContext = new AsyncLocalStorage();
@@ -29161,6 +29306,7 @@ function renderEvent(ev, agentName, lint = null, onCall = false, waitCmd = null,
29161
29306
  ...pics
29162
29307
  );
29163
29308
  }
29309
+ lines.push(...referenceLines(ev.references));
29164
29310
  if (ev.codeEdits?.length) {
29165
29311
  lines.push(
29166
29312
  "",
@@ -29175,13 +29321,14 @@ function renderEvent(ev, agentName, lint = null, onCall = false, waitCmd = null,
29175
29321
  "",
29176
29322
  `In live frames, the designer changed ${ev.liveChanges.length === 1 ? "one thing" : `${ev.liveChanges.length} things`}. These are already written to the code:`,
29177
29323
  ...ev.liveChanges.map((c, i) => {
29178
- const head2 = `${i + 1}. ${c.file}:${c.line}${c.component ? ` (${c.component})` : ""}: ${c.what} ${c.from} \u2192 ${c.to}`;
29324
+ const head2 = `${i + 1}. ${c.file}:${c.line}${c.component ? ` (${c.component})` : ""}: ${c.what} ${c.from} \u2192 ${c.to}${c.screen ? ` from the ${c.screen}: screen up only (smaller sizes keep the base classes)` : ""}`;
29179
29325
  if (c.how === "prop") return `${head2}, the prop where the app uses <${c.tag}>: ${c.before || "not set"} \u2192 ${c.after || "not set (its default)"}`;
29180
29326
  const how = !c.how || c.how === "tailwind" || !c.target ? `classes "${c.before}" \u2192 "${c.after}"` : `written to ${c.target.file}:${c.target.line}${c.target.selector ? ` (${c.target.selector})` : c.target.name ? ` (styled ${c.target.name})` : " (inline style)"} as "${c.before || "nothing"}" \u2192 "${c.after}"`;
29181
29327
  return `${head2}, ${how}${c.note ? `. ${c.note}` : ""}`;
29182
29328
  }),
29183
29329
  "",
29184
- "Keep these. Check whether the same fix belongs on sibling elements or other uses of the component, and say so rather than changing them unasked."
29330
+ "Keep these. Check whether the same fix belongs on sibling elements or other uses of the component, and say so rather than changing them unasked.",
29331
+ ...ev.liveBranch ? [`Playground also saved these edits on the git branch ${ev.liveBranch}, which isn't checked out: the files you have already contain them. Leave that branch alone unless the designer asks.`] : []
29185
29332
  );
29186
29333
  }
29187
29334
  if (ev.frame) {
@@ -29212,6 +29359,7 @@ function renderEvent(ev, agentName, lint = null, onCall = false, waitCmd = null,
29212
29359
  return [
29213
29360
  `The designer asked you, from the Playground canvas: "${ev.prompt}"`,
29214
29361
  ev.selection.length ? `Selected: ${ev.selection.map((s) => `${s.type} "${s.name}"${s.w ? ` ${Math.round(s.w)}\xD7${Math.round(s.h)}` : ""} (id ${s.id})`).join("; ")}` : "Nothing was selected.",
29362
+ ...referenceLines(ev.references),
29215
29363
  "",
29216
29364
  ...layers.length || !ev.selection.length ? [
29217
29365
  "How to do it on the canvas:",
@@ -29230,13 +29378,21 @@ function renderEvent(ev, agentName, lint = null, onCall = false, waitCmd = null,
29230
29378
  return "There is no open Playground session. Call open_screen first.";
29231
29379
  }
29232
29380
  }
29381
+ function referenceLines(refs) {
29382
+ if (!refs?.length) return [];
29383
+ return [
29384
+ "",
29385
+ `${refs.length === 1 ? "A reference image" : `${refs.length} reference images`} the designer put beside the design. Open ${refs.length === 1 ? "it" : "each file"} and look before you start: take direction from it (style, layout, density, mood), and don't copy it in as a layer or into the code unless asked.`,
29386
+ ...refs.map((r) => `- "${r.name}" (${r.w}\xD7${r.h}): ${r.file}`)
29387
+ ];
29388
+ }
29233
29389
  function outline(doc, depth = 4, max = 240) {
29234
29390
  const out = [];
29235
29391
  const walk4 = (id, d) => {
29236
29392
  const n = doc.nodes[id];
29237
29393
  if (!n || out.length >= max) return;
29238
29394
  const label2 = n.type === "text" ? ` "${(n.text?.content ?? "").slice(0, 40).replace(/\s+/g, " ")}"` : "";
29239
- out.push(`${" ".repeat(d)}${n.type} "${n.name}" ${Math.round(n.w)}\xD7${Math.round(n.h)} id ${n.id}${n.variant ? ` (variant of ${n.variant.of})` : ""}${label2}`);
29395
+ out.push(`${" ".repeat(d)}${n.type} "${n.name}" ${Math.round(n.w)}\xD7${Math.round(n.h)} id ${n.id}${n.variant ? ` (variant of ${n.variant.of})` : ""}${n.reference ? " (reference image: context, not part of the design)" : ""}${label2}`);
29240
29396
  if (d < depth) for (const c of n.children) walk4(c, d + 1);
29241
29397
  else if (n.children.length) out.push(`${" ".repeat(d + 1)}\u2026 ${n.children.length} more layer${n.children.length === 1 ? "" : "s"}`);
29242
29398
  };
@@ -29255,7 +29411,7 @@ function buildMcpServer(hub, showEditor = () => {
29255
29411
  "open_screen",
29256
29412
  {
29257
29413
  title: "Open a screen in Playground",
29258
- description: `Open a screen of this project in the Playground canvas for the designer to edit by hand. Playground loads the running page in a headless browser and turns it into editable layers (boxes, text, images, fonts) at their real positions. Pass url (for example http://localhost:5173/settings) when you know it. Without url, Playground finds the dev server this project is running and opens the page linked under the title (title "Settings" follows the app's Settings link). If no dev server is running, start it in the background and call again. Pass blank: true only for an empty frame to sketch in. Pass mode: "live" to show the running app itself instead of a copy: the designer selects elements and changes spacing, type, colour and radius, and Playground writes each change to the code as Tailwind classes, which the dev server reloads. Live suits small fixes to a Tailwind app; the default copy suits trying layouts freely. Afterwards, call wait_for_handback: it pauses until the designer presses Hand back, then returns the exact changes, each with the source element (and React component and file when available) it came from.`,
29414
+ description: `Open a screen of this project in the Playground canvas for the designer to edit by hand. Playground loads the running page in a headless browser and turns it into editable layers (boxes, text, images, fonts) at their real positions. Pass url (for example http://localhost:5173/settings) when you know it. Without url, Playground finds the dev server this project is running and opens the page linked under the title (title "Settings" follows the app's Settings link). If no dev server is running, Playground starts it with the project's own dev script; if it can't, it says why. Pass blank: true only for an empty frame to sketch in. Pass mode: "live" to show the running app itself instead of a copy: the designer selects elements and changes spacing, type, colour and radius, and Playground writes each change to the code as Tailwind classes, which the dev server reloads. Live suits small fixes to a Tailwind app; the default copy suits trying layouts freely. Afterwards, call wait_for_handback: it pauses until the designer presses Hand back, then returns the exact changes, each with the source element (and React component and file when available) it came from.`,
29259
29415
  inputSchema: z4.object({
29260
29416
  title: z4.string().min(1).describe('Name of the screen, e.g. "Settings". Without url, the link with this name is opened'),
29261
29417
  url: z4.string().url().optional().describe("The running page to import, e.g. http://localhost:5173/settings"),
@@ -29281,19 +29437,27 @@ function buildMcpServer(hub, showEditor = () => {
29281
29437
  const h = height ?? 900;
29282
29438
  let target = url;
29283
29439
  let find;
29440
+ let started = "";
29284
29441
  if (!target) {
29285
- const servers = await findDevServers(hub.storage.root);
29286
- if (!servers.length) {
29442
+ const dev = hub.devServer ? await hub.devServer.ensure() : null;
29443
+ if (dev?.ok === false && dev.starting) {
29444
+ return text(
29445
+ `Playground is starting this project's dev server (\`${dev.command}\`) and it isn't serving yet. Call open_screen again in about 15 seconds. Don't start another one.`
29446
+ );
29447
+ }
29448
+ if (!dev?.ok) {
29287
29449
  const cmd = await devCommand(hub.storage.root);
29450
+ const why = dev ? ` Playground tried to start it, but ${dev.reason}` : "";
29288
29451
  hub.notify("error", `Couldn't open ${title}: this project's dev server isn't running.`, "open");
29289
29452
  return {
29290
29453
  ...text(
29291
- `Could not open "${title}": no dev server is running for this project (${hub.storage.root}). Start it in the background${cmd ? ` (\`${cmd}\`)` : ""}, wait until it is ready, then call open_screen again. Pass url if the page is served from somewhere else.`
29454
+ `Could not open "${title}": no dev server is running for this project (${hub.storage.root}).${why} Fix that, or start it in the background${cmd ? ` (\`${cmd}\`)` : ""}, wait until it is ready, then call open_screen again. Pass url if the page is served from somewhere else.`
29292
29455
  ),
29293
29456
  isError: true
29294
29457
  };
29295
29458
  }
29296
- target = servers[0].url + "/";
29459
+ target = dev.server.url + "/";
29460
+ if (dev.started) started = `Playground started the dev server for this (${dev.server.url}); it keeps running until Playground stops, so don't start another. `;
29297
29461
  find = title;
29298
29462
  }
29299
29463
  if (mode === "live") {
@@ -29301,7 +29465,7 @@ function buildMcpServer(hub, showEditor = () => {
29301
29465
  const { session, live } = await hub.openLive(title, target);
29302
29466
  hub.notify("success", `${who} opened ${title} live`, "open");
29303
29467
  return text(
29304
- `Opened ${live.url} live in Playground as "${title}", session ${session.id}. The designer sees the running app at desktop and phone widths. ` + (find ? `It opened on the app's first page; the designer can go to ${title} from there, or call open_screen again with its url. ` : "") + "Their edits are written to the code as they make them, where each element is styled (its Tailwind classes, CSS or SCSS rule, styled component or inline style), so keep the dev server running and leave those files alone until they hand back. " + next
29468
+ `Opened ${live.url} live in Playground as "${title}", session ${session.id}. The designer sees the running app at desktop and phone widths. ` + started + (find ? `It opened on the app's first page; the designer can go to ${title} from there, or call open_screen again with its url. ` : "") + "Their edits are written to the code as they make them, where each element is styled (its Tailwind classes, CSS or SCSS rule, styled component or inline style), so keep the dev server running and leave those files alone until they hand back. " + next
29305
29469
  );
29306
29470
  } catch (err) {
29307
29471
  hub.notify("error", `Couldn't open ${title} live: ${err.message}`, "open");
@@ -29315,7 +29479,7 @@ function buildMcpServer(hub, showEditor = () => {
29315
29479
  const frame = hub.doc.nodes[session.frameId];
29316
29480
  const layers = imported.nodes.length - 1;
29317
29481
  return text(
29318
- `Imported ${imported.url} into Playground as "${title}" (${w}\xD7${Math.round(frame.h)}, ${layers} layers), session ${session.id}. The designer can see and edit it now. ` + (imported.notes.length ? `Notes: ${imported.notes.join(" ")} If this is not the right page, call open_screen again with its url. ` : "") + next
29482
+ `Imported ${imported.url} into Playground as "${title}" (${w}\xD7${Math.round(frame.h)}, ${layers} layers), session ${session.id}. The designer can see and edit it now. ` + started + (imported.notes.length ? `Notes: ${imported.notes.join(" ")} If this is not the right page, call open_screen again with its url. ` : "") + next
29319
29483
  );
29320
29484
  } catch (err) {
29321
29485
  if (err instanceof LinkNotFound) {
@@ -29606,11 +29770,11 @@ ${html}`
29606
29770
  placement: z4.enum(["top", "fill"]).optional().describe("On a frame: across the top, or covering the whole frame")
29607
29771
  })
29608
29772
  },
29609
- async ({ node_id, path: path16, url, placement }) => {
29773
+ async ({ node_id, path: path17, url, placement }) => {
29610
29774
  touch();
29611
- if (!path16 && !url) return { ...text("Give a path or a url."), isError: true };
29775
+ if (!path17 && !url) return { ...text("Give a path or a url."), isError: true };
29612
29776
  try {
29613
- const r = await hub.placeAsset(node_id, { path: path16, url }, placement);
29777
+ const r = await hub.placeAsset(node_id, { path: path17, url }, placement);
29614
29778
  return text(r.message);
29615
29779
  } catch (err) {
29616
29780
  return { ...text(err.message), isError: true };
@@ -29713,6 +29877,10 @@ var Hub = class {
29713
29877
  wakeGrace = WAKE_GRACE;
29714
29878
  /** Playground's own agent, started when the designer needs one and no chat is listening. Set by the server. */
29715
29879
  runner = null;
29880
+ /** Starts the project's dev server when a screen is opened and none is running. Set by the server. */
29881
+ devServer = null;
29882
+ /** Keeps live edits on a git branch of their own. Set by the server. */
29883
+ branch = null;
29716
29884
  /** What Playground's agent is working on now: taken from the queue, given back if the run fails. */
29717
29885
  running = [];
29718
29886
  saveTimer = null;
@@ -29971,6 +30139,7 @@ var Hub = class {
29971
30139
  const codeEdits = this.codeEdits.length ? this.codeEdits : void 0;
29972
30140
  const liveChanges = this.liveChanges.length ? this.liveChanges : void 0;
29973
30141
  const pictures = this.newPictures();
30142
+ const references = this.references().filter((r) => !this.baseline?.nodes[r.id]);
29974
30143
  return {
29975
30144
  status: "handed_back",
29976
30145
  playground: "product",
@@ -29981,9 +30150,26 @@ var Hub = class {
29981
30150
  codeEdits,
29982
30151
  liveChanges,
29983
30152
  ...pictures.length ? { pictures } : {},
30153
+ ...references.length ? { references } : {},
30154
+ ...liveChanges && this.branch?.info()?.name ? { liveBranch: this.branch.info().name } : {},
29984
30155
  ...s.native ? { native: s.native } : {}
29985
30156
  };
29986
30157
  }
30158
+ /**
30159
+ * Reference images on the canvas, as files the agent can open: of `only` the ones among those ids, or every one
30160
+ * when none of them is a reference. At most 8, the latest first.
30161
+ */
30162
+ references(only) {
30163
+ const all = Object.values(this.doc.nodes).filter((n) => n.reference && n.visible && n.src?.startsWith("/files/"));
30164
+ const picked = only ? all.filter((n) => only.includes(n.id)) : [];
30165
+ return (picked.length ? picked : all).slice(-8).reverse().map((n) => ({ id: n.id, name: n.name, file: path8.join(this.filesDir, path8.basename(n.src)), w: Math.round(n.w), h: Math.round(n.h) }));
30166
+ }
30167
+ /** Copy a file into the canvas's store, for a reference image the editor then puts on the canvas. */
30168
+ async storeAsset(from) {
30169
+ const asset = await readAsset(this.filesDir, from);
30170
+ if (!asset.mime.startsWith("image/")) throw new Error("A reference has to be an image (PNG, JPG, WebP, GIF, AVIF or SVG).");
30171
+ return asset;
30172
+ }
29987
30173
  /** Pictures in the session's screen that weren't there when it opened, as files in Playground's store. */
29988
30174
  newPictures() {
29989
30175
  const root2 = this.session?.frameId;
@@ -30013,6 +30199,7 @@ var Hub = class {
30013
30199
  this.bg(this.storage.saveSession(this.session), "the session");
30014
30200
  this.bg(this.storage.saveHandback(this.session.id, ev), "the hand back");
30015
30201
  if (this.liveChanges.length) {
30202
+ void this.branch?.reset();
30016
30203
  this.changesNow = [];
30017
30204
  this.emitLive();
30018
30205
  }
@@ -30035,10 +30222,11 @@ var Hub = class {
30035
30222
  const r = absoluteRect(this.doc, id);
30036
30223
  return { id, name: n.name, type: n.type, ...r };
30037
30224
  });
30038
- const how = this.deliver({ status: "request", sessionId: this.session.id, prompt, selection: items });
30225
+ const references = motionSel.length ? [] : this.references(selection);
30226
+ const how = this.deliver({ status: "request", sessionId: this.session.id, prompt, selection: items, ...references.length ? { references } : {} });
30039
30227
  const who = this.agent.name ?? "your agent";
30040
- const run4 = this.runner?.name;
30041
- const message = how === "sent" ? `Sent to ${who}` : how === "woke" ? `Calling ${who} back\u2026` : how === "started" ? `${run4} is on it` : how === "next" ? `${run4} takes it after what it's doing` : `Queued. ${cap(who)} isn't listening, so tell it in its chat to check Playground.`;
30228
+ const run5 = this.runner?.name;
30229
+ const message = how === "sent" ? `Sent to ${who}` : how === "woke" ? `Calling ${who} back\u2026` : how === "started" ? `${run5} is on it` : how === "next" ? `${run5} takes it after what it's doing` : `Queued. ${cap(who)} isn't listening, so tell it in its chat to check Playground.`;
30042
30230
  return { ok: true, message };
30043
30231
  }
30044
30232
  // ---------- drawn by the agent ----------
@@ -30458,16 +30646,22 @@ var Hub = class {
30458
30646
  codeEdits: this.codeEdits,
30459
30647
  live: this.live,
30460
30648
  liveChanges: this.liveChanges,
30649
+ liveBranch: this.branch?.info() ?? null,
30461
30650
  runner: this.runner?.info
30462
30651
  };
30463
30652
  }
30464
30653
  // ---------- live frames ----------
30654
+ liveBranchChanged() {
30655
+ this.emitLive();
30656
+ }
30465
30657
  emitLive() {
30466
- this.emit({ type: "live", live: this.live, changes: this.liveChanges });
30658
+ this.emit({ type: "live", live: this.live, changes: this.liveChanges, branch: this.branch?.info() ?? null });
30467
30659
  }
30468
30660
  set changesNow(c) {
30469
30661
  this.liveChanges = c;
30470
30662
  this.bg(this.storage.saveLiveChanges(c), "the live changes");
30663
+ const title = (this.session?.title ?? this.live?.title ?? "").replace(/^\/+|\/+$/g, "") || "Live edits";
30664
+ if (this.branch) this.bg(this.branch.sync(title), "the branch");
30471
30665
  if (c.length) this.reopenLive();
30472
30666
  }
30473
30667
  /** Open a handed-back session for more edits. The next hand back lists only what changes from here. */
@@ -30519,6 +30713,7 @@ var Hub = class {
30519
30713
  this.queue = [];
30520
30714
  this.session = this.newSession(title, "product", null, url);
30521
30715
  this.setCodeEdits([]);
30716
+ void this.branch?.reset();
30522
30717
  this.changesNow = [];
30523
30718
  this.baseline = cloneDoc(this.doc);
30524
30719
  this.bg(this.storage.saveSession(this.session, this.baseline), "the session");
@@ -30533,6 +30728,8 @@ var Hub = class {
30533
30728
  */
30534
30729
  async writeLive(e) {
30535
30730
  if (!this.sources) return { ok: false, reason: "Live edits are not available here." };
30731
+ const screen = e.screen ?? null;
30732
+ const cssOnly = { ok: false, reason: `This element is styled in CSS, so Playground can only change it for every size. Choose All sizes, or ask your agent to add a ${screen}: rule.` };
30536
30733
  const rel = await this.sources.resolve(e.file);
30537
30734
  if (!rel) return { ok: false, reason: `Playground can't find ${e.file} in this project.` };
30538
30735
  const src = await this.sources.read(rel);
@@ -30541,15 +30738,16 @@ var Hub = class {
30541
30738
  const name = e.site.name;
30542
30739
  const tw = !!f?.className && await this.sources.usesTailwind();
30543
30740
  if (!tw && !f?.style) return { ok: false, reason: `${name} doesn't pass className or style on to its outer element, so one ${name} can't change alone. Change every ${name}, or ask your agent to pass them on.` };
30544
- let next = e.next;
30741
+ if (!tw && screen) return cssOnly;
30742
+ let next2 = e.next;
30545
30743
  if (tw && (e.group === "padding" || e.group === "margin")) {
30546
30744
  const siteRel = await this.sources.resolve(e.site.file);
30547
30745
  const look = siteRel ? lookAt((await this.sources.read(siteRel)).text, e.site.line, name) : null;
30548
30746
  const scale2 = await this.scale();
30549
- const had = look?.ok ? look.look.classes.filter((c) => !c.conditional && !c.word.includes(":") && inGroup(c.word, e.group, scale2)).map((c) => c.word) : [];
30550
- next = mergeSideClasses(had, e.next);
30747
+ const had = look?.ok ? look.look.classes.filter((c) => !c.conditional).flatMap((c) => atScreen(c.word, screen) ?? []).filter((w2) => inGroup(w2, e.group, scale2)) : [];
30748
+ next2 = mergeSideClasses(had, e.next);
30551
30749
  }
30552
- return this.writeLive({ ...e, next, file: e.site.file, line: e.site.line, tag: name, component: name, site: void 0, shared: void 0, instance: tw ? "tailwind" : "inline" });
30750
+ return this.writeLive({ ...e, next: next2, file: e.site.file, line: e.site.line, tag: name, component: name, site: void 0, shared: void 0, instance: tw ? "tailwind" : "inline" });
30553
30751
  }
30554
30752
  const scale = await this.scale();
30555
30753
  const instanceNote = e.instance ? `Only this ${e.tag}, where this file uses it; ${e.tag} itself is unchanged.` : void 0;
@@ -30559,6 +30757,7 @@ var Hub = class {
30559
30757
  const at = e.instance === "inline" ? { ok: true, place: { how: "inline" } } : await this.styleWriter().place(rel, src.text, e.line, e.tag, e.group, scale);
30560
30758
  if (!at.ok) return at;
30561
30759
  if (at.place.how !== "tailwind") {
30760
+ if (screen) return cssOnly;
30562
30761
  const r4 = await this.styleWriter().write({ file: rel, text: src.text, version: src.version, line: e.line, tag: e.tag, group: e.group, css: e.css, fontSize: e.fontSize }, at.place);
30563
30762
  if (!r4.ok) return r4;
30564
30763
  if (r4.how === "tailwind") return { ok: false, reason: "Playground couldn\u2019t write that edit." };
@@ -30600,19 +30799,27 @@ var Hub = class {
30600
30799
  return { ok: true, change: change2, how: r4.how };
30601
30800
  }
30602
30801
  }
30603
- const r = writeClasses(src.text, e.line, e.tag, e.group, e.next, scale);
30802
+ let next = e.next;
30803
+ if (screen && !e.instance && (e.group === "padding" || e.group === "margin")) {
30804
+ const look = lookAt(src.text, e.line, e.tag);
30805
+ const had = look.ok ? look.look.classes.filter((c) => !c.conditional).flatMap((c) => atScreen(c.word, screen) ?? []).filter((w2) => inGroup(w2, e.group, scale)) : [];
30806
+ next = mergeSideClasses(had, e.next);
30807
+ }
30808
+ const r = writeClasses(src.text, e.line, e.tag, e.group, next, scale, screen);
30604
30809
  if (!r.ok) return r;
30605
30810
  const note = instanceNote ?? ([r.note, sharedNote].filter(Boolean).join(" ") || void 0);
30606
30811
  if (r.text === src.text) return { ok: true, change: null, how: "tailwind" };
30607
30812
  const w = await this.sources.write(rel, r.text, src.version);
30608
30813
  if (!w.ok) return { ok: false, reason: "The file changed on disk while Playground was writing. Try again." };
30609
- const prevGroup = r.before.split(/\s+/).filter((c) => c && !c.includes(":") && inGroup(c, e.group, scale));
30610
- const same2 = this.liveChanges.find((c) => c.file === rel && c.line === e.line && c.group === e.group && c.tag === e.tag && (c.how ?? "tailwind") === "tailwind");
30814
+ const prevGroup = r.before.split(/\s+/).flatMap((c) => c && atScreen(c, screen) || []).filter((c) => inGroup(c, e.group, scale));
30815
+ const same2 = this.liveChanges.find(
30816
+ (c) => c.file === rel && c.line === e.line && c.group === e.group && c.tag === e.tag && (c.how ?? "tailwind") === "tailwind" && (c.screen ?? null) === screen
30817
+ );
30611
30818
  let change;
30612
30819
  if (same2) {
30613
- const back = same2.prev.join(" ") === e.next.join(" ");
30820
+ const back = same2.prev.join(" ") === next.join(" ");
30614
30821
  this.changesNow = this.liveChanges.filter((c) => c !== same2);
30615
- change = back ? null : { ...same2, to: e.to, after: r.after, next: e.next, at: (/* @__PURE__ */ new Date()).toISOString(), ...note ? { note } : {} };
30822
+ change = back ? null : { ...same2, to: e.to, after: r.after, next, at: (/* @__PURE__ */ new Date()).toISOString(), ...note ? { note } : {} };
30616
30823
  } else {
30617
30824
  change = {
30618
30825
  id: newId("lc"),
@@ -30627,14 +30834,15 @@ var Hub = class {
30627
30834
  group: e.group,
30628
30835
  tag: e.tag,
30629
30836
  prev: prevGroup,
30630
- next: e.next,
30837
+ next,
30631
30838
  at: (/* @__PURE__ */ new Date()).toISOString(),
30632
30839
  ...scope,
30633
- ...note ? { note } : {}
30840
+ ...note ? { note } : {},
30841
+ ...screen ? { screen } : {}
30634
30842
  };
30635
30843
  }
30636
30844
  if (change) this.changesNow = [...this.liveChanges, change];
30637
- this.log(`live: ${rel}:${e.line} ${e.what} ${e.from} \u2192 ${e.to}`);
30845
+ this.log(`live: ${rel}:${e.line} ${e.what} ${e.from} \u2192 ${e.to}${screen ? ` (${screen}: and up)` : ""}`);
30638
30846
  this.emitLive();
30639
30847
  return { ok: true, change, how: "tailwind" };
30640
30848
  }
@@ -30714,6 +30922,15 @@ var Hub = class {
30714
30922
  this.emitLive();
30715
30923
  return { ok: true, change };
30716
30924
  }
30925
+ /** What Playground changed in each file this batch, for the tray's Review. */
30926
+ liveDiff() {
30927
+ return this.branch ? this.branch.diff() : Promise.resolve([]);
30928
+ }
30929
+ /** Push the branch and open a pull request, or update the open one. */
30930
+ openLivePr() {
30931
+ if (!this.branch) return Promise.resolve({ ok: false, message: "There\u2019s no branch for these edits." });
30932
+ return this.branch.openPr(this.liveChanges);
30933
+ }
30717
30934
  /** Put one live edit's classes back as they were. */
30718
30935
  async revertLive(id) {
30719
30936
  const c = this.liveChanges.find((x) => x.id === id);
@@ -30738,7 +30955,7 @@ var Hub = class {
30738
30955
  return { ok: true, message: `Reverted ${c.what} in ${(c.target?.file ?? c.file).split("/").pop()}` };
30739
30956
  }
30740
30957
  const src = await this.sources.read(c.file);
30741
- const r = writeClasses(src.text, c.line, c.tag, c.group, c.prev, await this.scale());
30958
+ const r = writeClasses(src.text, c.line, c.tag, c.group, c.prev, await this.scale(), c.screen && c.screen in TW_SCREENS ? c.screen : null);
30742
30959
  if (!r.ok) return { ok: false, message: r.reason };
30743
30960
  const text2 = c.before === "" ? dropEmptyClassName(r.text, c.line, c.tag) : r.text;
30744
30961
  if (text2 !== src.text) {
@@ -30791,10 +31008,10 @@ var Hub = class {
30791
31008
  };
30792
31009
 
30793
31010
  // ../daemon/src/runner.ts
30794
- import { spawn as spawn2 } from "node:child_process";
31011
+ import { spawn as spawn3 } from "node:child_process";
30795
31012
  import { randomUUID } from "node:crypto";
30796
31013
  import { accessSync, constants, createWriteStream } from "node:fs";
30797
- import { mkdir as mkdir3, readFile as readFile5, writeFile as writeFile3 } from "node:fs/promises";
31014
+ import { mkdir as mkdir4, readFile as readFile5, writeFile as writeFile3 } from "node:fs/promises";
30798
31015
  import path9 from "node:path";
30799
31016
  var RUNNER_HEADER = "x-pg-runner";
30800
31017
  var NAMES = { claude: "Claude Code", codex: "Codex" };
@@ -30900,7 +31117,7 @@ var Runner = class {
30900
31117
  await this.save();
30901
31118
  }
30902
31119
  async save() {
30903
- await mkdir3(path9.dirname(this.file), { recursive: true });
31120
+ await mkdir4(path9.dirname(this.file), { recursive: true });
30904
31121
  await writeFile3(this.file, JSON.stringify(this.settings, null, 2) + "\n");
30905
31122
  }
30906
31123
  set(p) {
@@ -30980,7 +31197,7 @@ ${task}
30980
31197
  } catch {
30981
31198
  log = null;
30982
31199
  }
30983
- const child = spawn2(bin, args, { cwd: this.root, env, stdio: ["pipe", "pipe", "pipe"] });
31200
+ const child = spawn3(bin, args, { cwd: this.root, env, stdio: ["pipe", "pipe", "pipe"] });
30984
31201
  this.child = child;
30985
31202
  this.stopped = false;
30986
31203
  this.set({ running: true, activity: "Starting", last: this.info.last });
@@ -31114,8 +31331,8 @@ function plain(text2) {
31114
31331
  }
31115
31332
 
31116
31333
  // ../daemon/src/storage.ts
31117
- import { mkdir as mkdir4, readFile as readFile6, rename, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
31118
- import { existsSync as existsSync4 } from "node:fs";
31334
+ import { mkdir as mkdir5, readFile as readFile6, rename, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
31335
+ import { existsSync as existsSync5 } from "node:fs";
31119
31336
  import path10 from "node:path";
31120
31337
  var tmpCounter = 0;
31121
31338
  var Storage = class {
@@ -31139,7 +31356,7 @@ var Storage = class {
31139
31356
  const prev = this.chains.get(file) ?? Promise.resolve();
31140
31357
  const next = prev.catch(() => {
31141
31358
  }).then(async () => {
31142
- await mkdir4(path10.dirname(file), { recursive: true });
31359
+ await mkdir5(path10.dirname(file), { recursive: true });
31143
31360
  await this.ignoreSelf();
31144
31361
  const tmp = `${file}.${process.pid}.${++tmpCounter}.tmp`;
31145
31362
  await writeFile4(tmp, body);
@@ -31158,14 +31375,14 @@ var Storage = class {
31158
31375
  if (this.ignored) return;
31159
31376
  this.ignored = true;
31160
31377
  const f = this.file(".gitignore");
31161
- if (!existsSync4(f)) {
31162
- await mkdir4(this.dir, { recursive: true });
31378
+ if (!existsSync5(f)) {
31379
+ await mkdir5(this.dir, { recursive: true });
31163
31380
  await writeFile4(f, "# Playground design sessions: local to this machine.\n*\n").catch(() => {
31164
31381
  });
31165
31382
  }
31166
31383
  }
31167
31384
  async readJson(file) {
31168
- if (!existsSync4(file)) return null;
31385
+ if (!existsSync5(file)) return null;
31169
31386
  try {
31170
31387
  return JSON.parse(await readFile6(file, "utf8"));
31171
31388
  } catch {
@@ -31241,7 +31458,7 @@ var Storage = class {
31241
31458
  };
31242
31459
 
31243
31460
  // ../daemon/src/source.ts
31244
- import { execFile as execFile3, spawn as spawn3 } from "node:child_process";
31461
+ import { execFile as execFile3, spawn as spawn4 } from "node:child_process";
31245
31462
  import { createHash as createHash3 } from "node:crypto";
31246
31463
  import { access, readdir as readdir2, readFile as readFile7, realpath as realpath2, stat as stat3, writeFile as writeFile5 } from "node:fs/promises";
31247
31464
  import path11 from "node:path";
@@ -31270,6 +31487,8 @@ var Sources = class {
31270
31487
  files = null;
31271
31488
  vocab = null;
31272
31489
  editor = null;
31490
+ /** Told each file's text just before it is written. */
31491
+ onWrite = null;
31273
31492
  /** Every source file, relative to the root. Cached for a few seconds. */
31274
31493
  list() {
31275
31494
  if (this.files && Date.now() - this.files.at < 5e3) return this.files.list;
@@ -31369,6 +31588,7 @@ var Sources = class {
31369
31588
  const abs = await this.abs(rel);
31370
31589
  const now = await readFile7(abs, "utf8");
31371
31590
  if (hash(now) !== version) return { ok: false, conflict: { file: rel, text: now, version: hash(now) } };
31591
+ this.onWrite?.(rel, now);
31372
31592
  await writeFile5(abs, text2, "utf8");
31373
31593
  this.vocab = null;
31374
31594
  return { ok: true, version: hash(text2) };
@@ -31426,7 +31646,7 @@ var Sources = class {
31426
31646
  const abs = await this.abs(rel);
31427
31647
  const at = Number.isFinite(line) && line > 0 ? Math.floor(line) : 1;
31428
31648
  const e = await this.findEditor();
31429
- const go = (cmd, args) => spawn3(cmd, args, { stdio: "ignore", detached: true }).unref();
31649
+ const go = (cmd, args) => spawn4(cmd, args, { stdio: "ignore", detached: true }).unref();
31430
31650
  if (process.platform === "darwin") {
31431
31651
  go("open", [e ? e.url(abs, at) : abs]);
31432
31652
  } else if (e) {
@@ -31438,6 +31658,285 @@ var Sources = class {
31438
31658
  }
31439
31659
  };
31440
31660
 
31661
+ // ../daemon/src/branch.ts
31662
+ import { spawn as spawn5 } from "node:child_process";
31663
+ import { mkdtemp as mkdtemp2, readFile as readFile8, realpath as realpath3, rm as rm3, writeFile as writeFile6 } from "node:fs/promises";
31664
+ import { tmpdir as tmpdir2 } from "node:os";
31665
+ import path12 from "node:path";
31666
+ function run4(cmd, args, cwd, opts = {}) {
31667
+ return new Promise((resolve2) => {
31668
+ const child = spawn5(cmd, args, { cwd, env: { ...process.env, ...opts.env, GIT_TERMINAL_PROMPT: "0" }, stdio: ["pipe", "pipe", "pipe"] });
31669
+ let out = "";
31670
+ let err = "";
31671
+ child.stdout.on("data", (d) => out += d);
31672
+ child.stderr.on("data", (d) => err += d);
31673
+ child.on("error", (e) => resolve2({ code: 127, out, err: e.message }));
31674
+ child.on("close", (code) => resolve2({ code: code ?? 1, out, err }));
31675
+ child.stdin.end(opts.input ?? "");
31676
+ });
31677
+ }
31678
+ var slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, "") || "edits";
31679
+ var LiveBranch = class {
31680
+ constructor(root2, file, host) {
31681
+ this.root = root2;
31682
+ this.file = file;
31683
+ this.host = host;
31684
+ }
31685
+ root;
31686
+ file;
31687
+ host;
31688
+ state = null;
31689
+ /** Snapshots taken before a branch exists: the first write comes before the first sync. */
31690
+ pending = {};
31691
+ chain = Promise.resolve();
31692
+ top = null;
31693
+ /** The project folder as git sees it: macOS reports /private/var for /var. */
31694
+ real = "";
31695
+ why = null;
31696
+ busy = false;
31697
+ async load() {
31698
+ try {
31699
+ this.state = JSON.parse(await readFile8(this.file, "utf8"));
31700
+ } catch {
31701
+ this.state = null;
31702
+ }
31703
+ }
31704
+ save() {
31705
+ const s = this.state;
31706
+ return (s ? writeFile6(this.file, JSON.stringify(s)) : rm3(this.file, { force: true })).catch(() => {
31707
+ });
31708
+ }
31709
+ /** One git job at a time, in order. */
31710
+ queue(job) {
31711
+ const next = this.chain.then(job, job);
31712
+ this.chain = next.catch(() => {
31713
+ });
31714
+ return next;
31715
+ }
31716
+ git(args, opts) {
31717
+ return run4("git", args, this.top ?? this.root, opts);
31718
+ }
31719
+ info() {
31720
+ if (this.why) return { name: null, unavailable: this.why, files: [], pr: null, ahead: false, busy: false };
31721
+ const s = this.state;
31722
+ if (!s) return null;
31723
+ return { name: s.name, files: s.files, pr: s.pr ? { url: s.pr.url } : null, ahead: !!s.pr && s.tip !== s.pr.pushed, busy: this.busy };
31724
+ }
31725
+ /** Called with a file's text just before Playground writes it. */
31726
+ remember(rel, text2) {
31727
+ const snaps = this.state?.snapshots ?? this.pending;
31728
+ if (!(rel in snaps)) snaps[rel] = text2;
31729
+ }
31730
+ /** The next live edits go on a new branch. The current one stays as it is. */
31731
+ reset() {
31732
+ return this.queue(async () => {
31733
+ this.state = null;
31734
+ this.pending = {};
31735
+ await this.save();
31736
+ this.host.changed();
31737
+ });
31738
+ }
31739
+ /** Bring the branch up to date with the files after a live edit or revert. */
31740
+ sync(title) {
31741
+ return this.queue(() => this.doSync(title));
31742
+ }
31743
+ /** Whether this project can have a branch: inside a git repo with at least one commit. */
31744
+ async repo() {
31745
+ if (this.top) return true;
31746
+ const top = await run4("git", ["rev-parse", "--show-toplevel"], this.root);
31747
+ if (top.code !== 0) {
31748
+ this.why = top.code === 127 ? "Git isn\u2019t installed, so there\u2019s no branch." : "This project isn\u2019t a git repository, so there\u2019s no branch.";
31749
+ return false;
31750
+ }
31751
+ this.top = top.out.trim();
31752
+ this.real = await realpath3(this.root).catch(() => this.root);
31753
+ const head = await this.git(["rev-parse", "--verify", "--quiet", "HEAD"]);
31754
+ if (head.code !== 0) {
31755
+ this.top = null;
31756
+ this.why = "This repository has no commits yet, so there\u2019s no branch.";
31757
+ return false;
31758
+ }
31759
+ this.why = null;
31760
+ return true;
31761
+ }
31762
+ repoPath(rel) {
31763
+ return path12.relative(this.top, path12.join(this.real, rel)).split(path12.sep).join("/");
31764
+ }
31765
+ async show(rev, rel) {
31766
+ const r = await this.git(["show", `${rev}:${this.repoPath(rel)}`]);
31767
+ return r.code === 0 ? r.out : null;
31768
+ }
31769
+ async now(rel) {
31770
+ return readFile8(path12.join(this.root, rel), "utf8").catch(() => null);
31771
+ }
31772
+ /** The base commit's text with Playground's edits (snapshot → now) laid on top: none of the designer's own changes. */
31773
+ async onBase(baseText, snap, now) {
31774
+ if (baseText === null || baseText === snap) return now;
31775
+ const dir = await mkdtemp2(path12.join(tmpdir2(), "pg-merge-"));
31776
+ try {
31777
+ const [a, o, b] = ["f", "snap", "now"].map((n) => path12.join(dir, n));
31778
+ await Promise.all([writeFile6(a, baseText), writeFile6(o, snap), writeFile6(b, now)]);
31779
+ const d = await run4("git", ["diff", "--no-index", "--no-color", "-U0", o, b], dir);
31780
+ const at = d.out.indexOf("\n@@");
31781
+ if (at >= 0) {
31782
+ await writeFile6(path12.join(dir, "p.diff"), `--- a/f
31783
+ +++ b/f
31784
+ ${d.out.slice(at + 1)}`);
31785
+ const r = await run4("git", ["apply", "--unidiff-zero", "p.diff"], dir);
31786
+ if (r.code === 0) return await readFile8(a, "utf8");
31787
+ }
31788
+ await writeFile6(a, baseText);
31789
+ const m = await run4("git", ["merge-file", "-p", a, o, b], dir);
31790
+ return m.code === 0 ? m.out : now;
31791
+ } finally {
31792
+ await rm3(dir, { recursive: true, force: true });
31793
+ }
31794
+ }
31795
+ async unique(title) {
31796
+ const d = /* @__PURE__ */ new Date();
31797
+ const pad = (n) => String(n).padStart(2, "0");
31798
+ const stem = `playground/${slug(title)}-${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}`;
31799
+ for (let i = 1; ; i++) {
31800
+ const name = i === 1 ? stem : `${stem}-${i}`;
31801
+ if ((await this.git(["rev-parse", "--verify", "--quiet", `refs/heads/${name}`])).code !== 0) return name;
31802
+ }
31803
+ }
31804
+ async doSync(title) {
31805
+ if (!this.state && !Object.keys(this.pending).length) return;
31806
+ if (!await this.repo()) return this.host.changed();
31807
+ if (!this.state) {
31808
+ const base2 = (await this.git(["rev-parse", "HEAD"])).out.trim();
31809
+ const up = await this.git(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]);
31810
+ this.state = { name: await this.unique(title), base: base2, upstream: up.code === 0 ? up.out.trim() : null, title, snapshots: this.pending, files: [], pr: null, tip: null };
31811
+ this.pending = {};
31812
+ }
31813
+ const s = this.state;
31814
+ const entries = [];
31815
+ const changed = [];
31816
+ for (const [rel, snap] of Object.entries(s.snapshots)) {
31817
+ const baseText = await this.show(s.base, rel);
31818
+ const now = await this.now(rel);
31819
+ const text2 = now === null || now === snap ? baseText : await this.onBase(baseText, snap, now);
31820
+ entries.push({ file: rel, text: text2 });
31821
+ if (text2 !== baseText) changed.push(rel);
31822
+ }
31823
+ if (!changed.length && !s.pr) {
31824
+ await this.git(["update-ref", "-d", `refs/heads/${s.name}`]);
31825
+ this.state = null;
31826
+ await this.save();
31827
+ return this.host.changed();
31828
+ }
31829
+ const parent = s.pr ? s.pr.pushed : s.base;
31830
+ const dir = await mkdtemp2(path12.join(tmpdir2(), "pg-index-"));
31831
+ const env = { GIT_INDEX_FILE: path12.join(dir, "index") };
31832
+ try {
31833
+ await this.git(["read-tree", parent], { env });
31834
+ for (const e of entries) {
31835
+ const p = this.repoPath(e.file);
31836
+ if (e.text === null) {
31837
+ await this.git(["update-index", "--force-remove", "--", p], { env });
31838
+ continue;
31839
+ }
31840
+ const sha = (await this.git(["hash-object", "-w", "--stdin"], { input: e.text })).out.trim();
31841
+ const mode = (await this.git(["ls-tree", s.base, "--", p])).out.split(/\s/)[0] || "100644";
31842
+ await this.git(["update-index", "--add", "--cacheinfo", `${mode},${sha},${p}`], { env });
31843
+ }
31844
+ const tree = (await this.git(["write-tree"], { env })).out.trim();
31845
+ const parentTree = (await this.git(["rev-parse", `${parent}^{tree}`])).out.trim();
31846
+ if (tree === parentTree && s.pr) {
31847
+ s.tip = s.pr.pushed;
31848
+ } else if (!s.tip || (await this.git(["rev-parse", `${s.tip}^{tree}`])).out.trim() !== tree) {
31849
+ const who = await this.git(["config", "user.email"]);
31850
+ const author = who.code === 0 && who.out.trim() ? {} : { GIT_AUTHOR_NAME: "Playground", GIT_AUTHOR_EMAIL: "playground@localhost", GIT_COMMITTER_NAME: "Playground", GIT_COMMITTER_EMAIL: "playground@localhost" };
31851
+ const msg = `Design changes: ${s.title}
31852
+
31853
+ Made by hand in Playground's live frames.`;
31854
+ const c = await this.git(["commit-tree", tree, "-p", parent, "-m", msg], { env: author });
31855
+ if (c.code !== 0) throw new Error(c.err.trim() || "git couldn\u2019t make the commit");
31856
+ s.tip = c.out.trim();
31857
+ await this.git(["update-ref", `refs/heads/${s.name}`, s.tip]);
31858
+ }
31859
+ s.files = changed;
31860
+ await this.save();
31861
+ } catch (err) {
31862
+ this.host.log(`live branch: ${err.message}`);
31863
+ } finally {
31864
+ await rm3(dir, { recursive: true, force: true });
31865
+ }
31866
+ this.host.changed();
31867
+ }
31868
+ /** What Playground changed in each file, as unified diff hunks. */
31869
+ diff() {
31870
+ return this.queue(async () => {
31871
+ const snaps = { ...this.pending, ...this.state?.snapshots };
31872
+ const out = [];
31873
+ const dir = await mkdtemp2(path12.join(tmpdir2(), "pg-diff-"));
31874
+ try {
31875
+ for (const [rel, snap] of Object.entries(snaps)) {
31876
+ const now = await this.now(rel) ?? "";
31877
+ if (now === snap) continue;
31878
+ const a = path12.join(dir, "before");
31879
+ const b = path12.join(dir, "after");
31880
+ await Promise.all([writeFile6(a, snap), writeFile6(b, now)]);
31881
+ const r = await run4("git", ["diff", "--no-index", "--no-color", "-U3", a, b], dir);
31882
+ const at = r.out.indexOf("\n@@");
31883
+ if (at >= 0) out.push({ file: rel, patch: r.out.slice(at + 1) });
31884
+ }
31885
+ } finally {
31886
+ await rm3(dir, { recursive: true, force: true });
31887
+ }
31888
+ return out;
31889
+ });
31890
+ }
31891
+ /** Push the branch and open a pull request with gh, or push the new edits to the one already open. */
31892
+ openPr(changes) {
31893
+ return this.queue(async () => {
31894
+ const s = this.state;
31895
+ if (!s?.tip || !s.files.length) return { ok: false, message: "There are no edits on the branch to put in a pull request." };
31896
+ const remotes = (await this.git(["remote"])).out.split("\n").filter(Boolean);
31897
+ const remote = remotes.includes("origin") ? "origin" : remotes[0];
31898
+ const branch = `refs/heads/${s.name}`;
31899
+ const commands = (r) => `git push ${r} ${s.name}
31900
+ gh pr create --head ${s.name}`;
31901
+ if (!remote) return { ok: false, message: "This repository has no remote to push the branch to. Add one, then try again." };
31902
+ const gh = process.env.PG_GH || findOnPath("gh");
31903
+ if (!gh) return { ok: false, message: `GitHub\u2019s gh command isn\u2019t installed. Install it, or run:
31904
+ ${commands(remote)}` };
31905
+ if (!s.pr && (await run4(gh, ["auth", "status"], this.top)).code !== 0) {
31906
+ return { ok: false, message: `gh isn\u2019t signed in. Run gh auth login, then try again, or run:
31907
+ ${commands(remote)}` };
31908
+ }
31909
+ if (s.pr && s.tip === s.pr.pushed) return { ok: true, url: s.pr.url, message: "The pull request is up to date." };
31910
+ this.busy = true;
31911
+ this.host.changed();
31912
+ try {
31913
+ const push = await this.git(["push", remote, `${branch}:${branch}`]);
31914
+ if (push.code !== 0) return { ok: false, message: `git couldn\u2019t push the branch: ${push.err.trim().split("\n").pop()}` };
31915
+ if (s.pr) {
31916
+ s.pr.pushed = s.tip;
31917
+ await this.save();
31918
+ return { ok: true, url: s.pr.url, message: "Pushed the new edits to the pull request." };
31919
+ }
31920
+ const [upRemote, ...upBranch] = (s.upstream ?? "").split("/");
31921
+ const base2 = upRemote === remote && upBranch.length ? ["--base", upBranch.join("/")] : [];
31922
+ const list3 = changes.map((c) => `- ${c.component || c.tag} \xB7 ${c.what}${c.screen ? ` (${c.screen}: and up)` : ""}: ${c.from} \u2192 ${c.to} (\`${c.file}:${c.line}\`)`);
31923
+ const body = [`Design changes made by hand in Playground's live frames on "${s.title}".`, "", ...list3, "", "Only Playground\u2019s edits are on this branch."].join("\n");
31924
+ const pr = await run4(gh, ["pr", "create", "--head", s.name, "--title", `Design changes: ${s.title}`, "--body", body, ...base2], this.top);
31925
+ const url = pr.out.split("\n").map((l) => l.trim()).filter((l) => /^https?:\/\//.test(l)).pop();
31926
+ if (pr.code !== 0 || !url) return { ok: false, message: `gh couldn\u2019t open the pull request: ${(pr.err || pr.out).trim().split("\n").pop()}` };
31927
+ s.pr = { url, pushed: s.tip };
31928
+ await this.save();
31929
+ const unpushed = Number((await this.git(["rev-list", "--count", s.base, "--not", `--remotes=${remote}`])).out.trim()) || 0;
31930
+ const note = unpushed ? ` It also has ${unpushed} commit${unpushed === 1 ? "" : "s"} of yours that weren\u2019t pushed before.` : "";
31931
+ return { ok: true, url, message: `Opened the pull request.${note}` };
31932
+ } finally {
31933
+ this.busy = false;
31934
+ this.host.changed();
31935
+ }
31936
+ });
31937
+ }
31938
+ };
31939
+
31441
31940
  // ../daemon/src/server.ts
31442
31941
  var GROUPS = /* @__PURE__ */ new Set(["padding", "margin", "gap", "width", "height", "font-size", "font-weight", "leading", "tracking", "radius", "bg", "text-color", "border-color", "opacity"]);
31443
31942
  var MIME = {
@@ -31495,7 +31994,7 @@ async function startDaemon(opts) {
31495
31994
  hub.origin = `http://127.0.0.1:${port2}`;
31496
31995
  await hub.load();
31497
31996
  if (opts.runner ?? !process.env.PG_NO_RUNNER) {
31498
- const runner = new Runner(path12.join(storage.dir, "agent.json"), opts.root, {
31997
+ const runner = new Runner(path13.join(storage.dir, "agent.json"), opts.root, {
31499
31998
  mcpUrl: () => `http://127.0.0.1:${port2}/mcp`,
31500
31999
  changed: (info) => hub.runnerChanged(info),
31501
32000
  ended: (ok2, stopped) => hub.runEnded(ok2, stopped),
@@ -31504,8 +32003,15 @@ async function startDaemon(opts) {
31504
32003
  await runner.load();
31505
32004
  hub.runner = runner;
31506
32005
  }
32006
+ const branch = new LiveBranch(opts.root, path13.join(storage.dir, "branch.json"), { changed: () => hub.liveBranchChanged(), log });
32007
+ await branch.load();
32008
+ hub.branch = branch;
32009
+ sources.onWrite = (rel, before) => {
32010
+ if (hub.live) branch.remember(rel, before);
32011
+ };
32012
+ hub.devServer = new DevServerStarter(opts.root, storage.dir, { notify: (tone, text2) => hub.notify(tone, text2, "devserver"), log: (l) => (opts.log ?? console.error)(l) });
31507
32013
  const project = {
31508
- name: path12.basename(opts.root),
32014
+ name: path13.basename(opts.root),
31509
32015
  root: opts.root,
31510
32016
  mcpUrl: `http://127.0.0.1:${port2}/mcp`,
31511
32017
  connect: opts.cliPath ? `node ${JSON.stringify(opts.cliPath)} setup` : null,
@@ -31630,9 +32136,13 @@ async function startDaemon(opts) {
31630
32136
  case "start": {
31631
32137
  let url = str("url");
31632
32138
  if (!url) {
31633
- const servers = await findDevServers(opts.root);
31634
- if (!servers.length) return json(404, { error: "Start this project's dev server, then switch to Live again." });
31635
- url = servers[0].url + "/";
32139
+ const dev = await hub.devServer.ensure([port2]);
32140
+ if (!dev.ok) {
32141
+ if (dev.starting) return json(503, { error: `Your dev server is starting (${dev.command}). Switch to Live again in a moment.` });
32142
+ const cmd = await devCommand(opts.root);
32143
+ return json(404, { error: `Playground couldn't start this project's dev server: ${dev.reason.split("\n")[0]}${cmd ? ` Start it with ${cmd}` : " Start it"}, then switch to Live again.` });
32144
+ }
32145
+ url = dev.server.url + "/";
31636
32146
  }
31637
32147
  if (!isLocalOrigin(url)) return json(400, { error: "Live frames show apps running on this computer." });
31638
32148
  return json(200, { live: await hub.startLive(url, str("title") || void 0) });
@@ -31646,15 +32156,15 @@ async function startDaemon(opts) {
31646
32156
  const refs = Array.isArray(body.refs) ? body.refs.filter((r) => typeof r === "string").slice(0, 200) : [];
31647
32157
  const live = hub.live;
31648
32158
  const allowed = live ? [new URL(live.url).origin, `http://localhost:${live.port}`, `http://127.0.0.1:${live.port}`] : [];
31649
- const root2 = await realpath3(opts.root).catch(() => opts.root);
32159
+ const root2 = await realpath4(opts.root).catch(() => opts.root);
31650
32160
  const fetchText = async (u) => {
31651
32161
  try {
31652
32162
  if (u.startsWith("file://")) {
31653
32163
  const raw = fileURLToPath(u.replace(/[?#].*$/, ""));
31654
- const file = await realpath3(raw).catch(() => "") || await realpath3(decodeURIComponent(raw)).catch(() => "");
31655
- const rel = path12.relative(root2, file);
31656
- if (!file || rel.startsWith("..") || path12.isAbsolute(rel) || !/\.(m?js|map)$/.test(file)) return null;
31657
- return await readFile8(file, "utf8");
32164
+ const file = await realpath4(raw).catch(() => "") || await realpath4(decodeURIComponent(raw)).catch(() => "");
32165
+ const rel = path13.relative(root2, file);
32166
+ if (!file || rel.startsWith("..") || path13.isAbsolute(rel) || !/\.(m?js|map)$/.test(file)) return null;
32167
+ return await readFile9(file, "utf8");
31658
32168
  }
31659
32169
  if (!allowed.includes(new URL(u).origin)) return null;
31660
32170
  const r = await fetch(u, { signal: AbortSignal.timeout(1e4) });
@@ -31693,7 +32203,9 @@ async function startDaemon(opts) {
31693
32203
  css,
31694
32204
  ...Number.isFinite(fontSize) && fontSize > 0 ? { fontSize } : {},
31695
32205
  ...site ? { site } : {},
31696
- ...shared ? { shared } : {}
32206
+ ...shared ? { shared } : {},
32207
+ // From one Tailwind screen up (md:, lg:), for an edit made in the tablet or desktop frame.
32208
+ ...isScreen(body.screen) ? { screen: body.screen } : {}
31697
32209
  });
31698
32210
  return json(r.ok ? 200 : 409, r.ok ? r : { error: r.reason });
31699
32211
  }
@@ -31725,6 +32237,12 @@ async function startDaemon(opts) {
31725
32237
  const r = await hub.revertLive(str("id"));
31726
32238
  return json(r.ok ? 200 : 409, r.ok ? r : { error: r.message });
31727
32239
  }
32240
+ case "diff":
32241
+ return json(200, { files: await hub.liveDiff() });
32242
+ case "pr": {
32243
+ const r = await hub.openLivePr();
32244
+ return json(r.ok ? 200 : 409, r.ok ? r : { error: r.message });
32245
+ }
31728
32246
  case "revertAll": {
31729
32247
  const r = await hub.revertAllLive();
31730
32248
  return json(r.ok ? 200 : 409, r.ok ? r : { error: r.message });
@@ -31738,12 +32256,12 @@ async function startDaemon(opts) {
31738
32256
  }
31739
32257
  }
31740
32258
  async function serveFile(req, res) {
31741
- const name = path12.basename(decodeURIComponent(new URL(req.url ?? "/", "http://x").pathname));
32259
+ const name = path13.basename(decodeURIComponent(new URL(req.url ?? "/", "http://x").pathname));
31742
32260
  if (!/^[a-f0-9]{16}\.[a-z0-9]+$/.test(name)) return void res.writeHead(404).end();
31743
32261
  try {
31744
- const data = await readFile8(path12.join(hub.filesDir, name));
32262
+ const data = await readFile9(path13.join(hub.filesDir, name));
31745
32263
  res.writeHead(200, {
31746
- "content-type": MIME[path12.extname(name)] ?? "application/octet-stream",
32264
+ "content-type": MIME[path13.extname(name)] ?? "application/octet-stream",
31747
32265
  "cache-control": "public, max-age=31536000, immutable"
31748
32266
  }).end(data);
31749
32267
  } catch {
@@ -31763,6 +32281,7 @@ async function startDaemon(opts) {
31763
32281
  chunks.push(c);
31764
32282
  }
31765
32283
  try {
32284
+ if (!node) return void json(200, await hub.storeAsset({ data: Buffer.concat(chunks), name }));
31766
32285
  const r = await hub.placeAsset(node, { data: Buffer.concat(chunks), name });
31767
32286
  json(200, r);
31768
32287
  } catch (err) {
@@ -31780,16 +32299,16 @@ async function startDaemon(opts) {
31780
32299
  const format = body?.format === "lottie" ? "lottie" : "mp4";
31781
32300
  const ms = Math.min(3e4, Math.max(1e3, Number(body?.ms) || 6e3));
31782
32301
  const url = `${origin ?? hub.origin}/?pg-stage=${encodeURIComponent(id)}&ms=${ms}`;
31783
- const slug = it.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "motion";
32302
+ const slug2 = it.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "motion";
31784
32303
  try {
31785
32304
  if (format === "mp4") {
31786
32305
  const data = await recordStage({ url, ms });
31787
- res.writeHead(200, { "content-type": "video/mp4", "content-disposition": `attachment; filename="${slug}.mp4"`, "cache-control": "no-store" }).end(data);
32306
+ res.writeHead(200, { "content-type": "video/mp4", "content-disposition": `attachment; filename="${slug2}.mp4"`, "cache-control": "no-store" }).end(data);
31788
32307
  } else {
31789
32308
  const stage = await measureStage({ url });
31790
32309
  const script = loopScript(it, ms, { enter: phaseEnd(it, it.enter), exit: it.exit ? phaseEnd(it, it.exit) : 0 });
31791
32310
  const data = JSON.stringify(toLottie(it, stage, script, ms));
31792
- res.writeHead(200, { "content-type": "application/json", "content-disposition": `attachment; filename="${slug}.json"`, "cache-control": "no-store" }).end(data);
32311
+ res.writeHead(200, { "content-type": "application/json", "content-disposition": `attachment; filename="${slug2}.json"`, "cache-control": "no-store" }).end(data);
31793
32312
  }
31794
32313
  } catch (err) {
31795
32314
  fail(500, err.message);
@@ -31815,18 +32334,18 @@ async function startDaemon(opts) {
31815
32334
  return;
31816
32335
  }
31817
32336
  const url = new URL(req.url ?? "/", "http://x");
31818
- const safe = path12.normalize(decodeURIComponent(url.pathname)).replace(/^(\.\.[/\\])+/, "");
31819
- let file = path12.join(opts.editorDir, safe);
32337
+ const safe = path13.normalize(decodeURIComponent(url.pathname)).replace(/^(\.\.[/\\])+/, "");
32338
+ let file = path13.join(opts.editorDir, safe);
31820
32339
  if (!file.startsWith(opts.editorDir)) return void res.writeHead(403).end();
31821
32340
  try {
31822
- if ((await stat4(file)).isDirectory()) file = path12.join(file, "index.html");
32341
+ if ((await stat4(file)).isDirectory()) file = path13.join(file, "index.html");
31823
32342
  } catch {
31824
- file = path12.join(opts.editorDir, "index.html");
32343
+ file = path13.join(opts.editorDir, "index.html");
31825
32344
  }
31826
32345
  try {
31827
- const data = await readFile8(file);
31828
- const cache = file.includes(`${path12.sep}assets${path12.sep}`) ? "public, max-age=31536000, immutable" : "no-cache";
31829
- res.writeHead(200, { "content-type": MIME[path12.extname(file)] ?? "application/octet-stream", "cache-control": cache }).end(data);
32346
+ const data = await readFile9(file);
32347
+ const cache = file.includes(`${path13.sep}assets${path13.sep}`) ? "public, max-age=31536000, immutable" : "no-cache";
32348
+ res.writeHead(200, { "content-type": MIME[path13.extname(file)] ?? "application/octet-stream", "cache-control": cache }).end(data);
31830
32349
  } catch {
31831
32350
  res.writeHead(404).end();
31832
32351
  }
@@ -31938,6 +32457,7 @@ async function startDaemon(opts) {
31938
32457
  close: () => new Promise((r) => {
31939
32458
  void closeImporter();
31940
32459
  hub.runner?.stop();
32460
+ hub.devServer?.stop();
31941
32461
  void hub.closeLive();
31942
32462
  for (const c of wss.clients) c.terminate();
31943
32463
  wss.close();
@@ -32025,17 +32545,17 @@ if (positionals[0] === "setup") {
32025
32545
  }
32026
32546
  if (positionals[0] === "wait") {
32027
32547
  const { runWait: runWait2 } = await Promise.resolve().then(() => (init_bridge(), bridge_exports));
32028
- process.exit(await runWait2({ root: path15.resolve(positionals[1] ?? process.cwd()), port, name: values2.as }));
32548
+ process.exit(await runWait2({ root: path16.resolve(positionals[1] ?? process.cwd()), port, name: values2.as }));
32029
32549
  }
32030
32550
  if (positionals[0] === "mcp") {
32031
32551
  const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_bridge(), bridge_exports));
32032
32552
  const folder = positionals[1] && !/\$\{\w+\}/.test(positionals[1]) ? positionals[1] : process.cwd();
32033
- await runBridge2({ root: path15.resolve(folder), port, cliPath: fileURLToPath2(import.meta.url) });
32553
+ await runBridge2({ root: path16.resolve(folder), port, cliPath: fileURLToPath2(import.meta.url) });
32034
32554
  } else {
32035
32555
  await serve();
32036
32556
  }
32037
32557
  async function serve() {
32038
- const root2 = path15.resolve(positionals[0] ?? process.cwd());
32558
+ const root2 = path16.resolve(positionals[0] ?? process.cwd());
32039
32559
  let isDir = false;
32040
32560
  try {
32041
32561
  isDir = statSync2(root2).isDirectory();
@@ -32049,10 +32569,10 @@ Run pg-studio from your project folder, or pass its path: pg-studio ~/code/my-ap
32049
32569
  );
32050
32570
  process.exit(1);
32051
32571
  }
32052
- const editorDir = process.env.PG_EDITOR_DIR ? path15.resolve(process.env.PG_EDITOR_DIR) : path15.join(path15.dirname(fileURLToPath2(import.meta.url)), "editor");
32572
+ const editorDir = process.env.PG_EDITOR_DIR ? path16.resolve(process.env.PG_EDITOR_DIR) : path16.join(path16.dirname(fileURLToPath2(import.meta.url)), "editor");
32053
32573
  const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
32054
32574
  const openInBrowser = (url2) => {
32055
- if (!process.env.PG_STUDIO_NO_BROWSER) spawn5(opener, [url2], { stdio: "ignore", detached: true }).unref();
32575
+ if (!process.env.PG_STUDIO_NO_BROWSER) spawn7(opener, [url2], { stdio: "ignore", detached: true }).unref();
32056
32576
  };
32057
32577
  let daemon;
32058
32578
  try {