frameboard 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -3037,12 +3037,15 @@ const EXIT_CODES = {
3037
3037
  "stale-layout": 11,
3038
3038
  "asset-type-refused": 2,
3039
3039
  "asset-too-large": 2,
3040
+ "image-type-refused": 2,
3040
3041
  "undo-overtaken": 12,
3041
3042
  "nothing-to-undo": 12,
3042
3043
  "frame-claimed": 4,
3043
3044
  "claims-invalid": 5,
3044
3045
  "client-not-built": 3,
3045
- "tokens-exist": 4
3046
+ "tokens-exist": 4,
3047
+ "dispatch-unavailable": 3,
3048
+ "dispatch-failed": 13
3046
3049
  };
3047
3050
  var FrameboardError = class extends Error {
3048
3051
  code;
@@ -9028,7 +9031,88 @@ const FRAME_SIZES = {
9028
9031
  height: 900
9029
9032
  }
9030
9033
  };
9034
+ /**
9035
+ * The devices the Frame tool and `--size` offer beside the three presets.
9036
+ * The iPad Pro 11 and a 1440 desktop are the tablet and desktop presets, so
9037
+ * neither repeats here.
9038
+ */
9039
+ const DEVICE_SIZES = [
9040
+ {
9041
+ name: "small-phone",
9042
+ label: "Small phone",
9043
+ group: "phone",
9044
+ width: 375,
9045
+ height: 667
9046
+ },
9047
+ {
9048
+ name: "iphone-16",
9049
+ label: "iPhone 16",
9050
+ group: "phone",
9051
+ width: 393,
9052
+ height: 852
9053
+ },
9054
+ {
9055
+ name: "android",
9056
+ label: "Android",
9057
+ group: "phone",
9058
+ width: 412,
9059
+ height: 917
9060
+ },
9061
+ {
9062
+ name: "iphone-16-pro-max",
9063
+ label: "iPhone 16 Pro Max",
9064
+ group: "phone",
9065
+ width: 440,
9066
+ height: 956
9067
+ },
9068
+ {
9069
+ name: "ipad-mini",
9070
+ label: "iPad mini",
9071
+ group: "tablet",
9072
+ width: 744,
9073
+ height: 1133
9074
+ },
9075
+ {
9076
+ name: "ipad-pro-12-9",
9077
+ label: "iPad Pro 12.9",
9078
+ group: "tablet",
9079
+ width: 1024,
9080
+ height: 1366
9081
+ },
9082
+ {
9083
+ name: "macbook-air",
9084
+ label: "MacBook Air",
9085
+ group: "desktop",
9086
+ width: 1280,
9087
+ height: 832
9088
+ },
9089
+ {
9090
+ name: "full-hd",
9091
+ label: "Full HD",
9092
+ group: "desktop",
9093
+ width: 1920,
9094
+ height: 1080
9095
+ }
9096
+ ];
9097
+ /** Every size name, the three presets first, then the devices. */
9098
+ const FRAME_SIZE_NAMES = [
9099
+ "phone",
9100
+ "tablet",
9101
+ "desktop",
9102
+ ...DEVICE_SIZES.map((device) => device.name)
9103
+ ];
9031
9104
  const DEFAULT_FRAME_SIZE = "desktop";
9105
+ function isFrameSizePreset(value) {
9106
+ return Object.hasOwn(FRAME_SIZES, value);
9107
+ }
9108
+ /** The width and height a size name stands for. */
9109
+ function frameSizeOf(name) {
9110
+ const { width, height } = isFrameSizePreset(name) ? FRAME_SIZES[name] : DEVICE_SIZES.find((device) => device.name === name) ?? FRAME_SIZES["desktop"];
9111
+ return {
9112
+ width,
9113
+ height
9114
+ };
9115
+ }
9032
9116
  // src/shared/records/board.ts
9033
9117
  const boardFileSchema = looseObject({ version: literal(1) });
9034
9118
  /** A project's own check rules, absent meaning the built-in rules alone. */
@@ -9170,7 +9254,8 @@ function placeFrames(frames, names) {
9170
9254
  /**
9171
9255
  * Where a frame with no layout entry sits: desktop size at `y` 0, 80 past the
9172
9256
  * right edge of every frame already placed, on top of all of them. The board
9173
- * draws what the scanner returns, and `frame add` persists the same box.
9257
+ * draws what the scanner returns, and `frame add` persists the same box for
9258
+ * the first unplaced file, placing any other past the placed frames alone.
9174
9259
  */
9175
9260
  function placeNext(placed) {
9176
9261
  const right = Math.max(...placed.map(({ box }) => box.x + box.width + 80), 0);
@@ -9330,7 +9415,7 @@ async function isDirectory(path) {
9330
9415
  }
9331
9416
  }
9332
9417
  // package.json
9333
- var version$1 = "0.13.0";
9418
+ var version$1 = "0.15.0";
9334
9419
  var dependencies = { "playwright-core": "1.64.1" };
9335
9420
  // src/shared/version.ts
9336
9421
  const version = version$1;
@@ -9586,8 +9671,9 @@ async function framePathParts(root, ref, cwd) {
9586
9671
  // src/server/board/frames.ts
9587
9672
  /**
9588
9673
  * Places a frame on its page, writing a skeleton file only when none exists.
9589
- * A file with no entry keeps its bytes and takes the box `list` showed for it
9590
- * unless a size or position is given. Every axis no size names hugs its
9674
+ * A file with no entry keeps its bytes and lands 80 past the placed frames,
9675
+ * as `placeNext` puts it, ignoring the page's other unplaced files, unless a
9676
+ * size or position is given. Every axis no size names hugs its
9591
9677
  * content, a preset fixing the width alone, and the box stands in until the
9592
9678
  * server measures.
9593
9679
  */
@@ -9604,7 +9690,8 @@ async function addFrame(root, ref, options) {
9604
9690
  const exists = existsSync(frame.path);
9605
9691
  if (exists && layout.hasEntry(frame.name)) throw new FrameboardError("name-taken", `${frame.project}/${frame.page}/${frame.name} is already a placed frame.`, { ref: refOf(frame) });
9606
9692
  const names = exists ? layout.names : [...layout.names, frame.name].sort();
9607
- const computed = placeFrames(layout.file.frames, names).get(frame.name);
9693
+ const slot = names.filter((name) => name === frame.name || layout.hasEntry(name));
9694
+ const computed = placeFrames(layout.file.frames, slot).get(frame.name);
9608
9695
  if (!computed) throw new Error(`No placement computed for ${frame.name}.`);
9609
9696
  if (!exists) {
9610
9697
  await writeFile(frame.path, skeleton(frame.name), { flag: "wx" });
@@ -9897,7 +9984,7 @@ function sizeOf({ size, width, height }) {
9897
9984
  width,
9898
9985
  height
9899
9986
  });
9900
- if (size !== void 0) return { ...FRAME_SIZES[size] };
9987
+ if (size !== void 0) return frameSizeOf(size);
9901
9988
  return {
9902
9989
  ...width === void 0 ? {} : { width },
9903
9990
  ...height === void 0 ? {} : { height }
@@ -26771,6 +26858,16 @@ function serializeDocumentTypeNode(node, { treeAdapter }) {
26771
26858
  function parse$3(html, options) {
26772
26859
  return Parser.parse(html, options);
26773
26860
  }
26861
+ function parseFragment(fragmentContext, html, options) {
26862
+ if (typeof fragmentContext === "string") {
26863
+ options = html;
26864
+ html = fragmentContext;
26865
+ fragmentContext = null;
26866
+ }
26867
+ const parser = Parser.getFragmentParser(fragmentContext, options);
26868
+ parser.tokenizer.write(html, true);
26869
+ return parser.getFragment();
26870
+ }
26774
26871
  // node_modules/domelementtype/dist/index.js
26775
26872
  /** Types of elements found in htmlparser2's DOM */
26776
26873
  var ElementType;
@@ -28935,14 +29032,80 @@ function applyEdit(source, address, change) {
28935
29032
  span
28936
29033
  };
28937
29034
  }
29035
+ // src/shared/starter-tokens.ts
29036
+ /**
29037
+ * The looks a new project can start from, each accent paired by hand with a
29038
+ * dark value, so both themes hold without a derived color. The keys are the
29039
+ * values `project tokens --accent` and the route take.
29040
+ */
29041
+ const STARTER_ACCENTS = {
29042
+ blue: {
29043
+ light: "#2f7bf0",
29044
+ dark: "#4e92f6"
29045
+ },
29046
+ red: {
29047
+ light: "#e5484d",
29048
+ dark: "#ff6369"
29049
+ },
29050
+ green: {
29051
+ light: "#30a46c",
29052
+ dark: "#3dd68c"
29053
+ },
29054
+ orange: {
29055
+ light: "#f76b15",
29056
+ dark: "#ff801f"
29057
+ },
29058
+ purple: {
29059
+ light: "#8e4ec6",
29060
+ dark: "#9a5cd0"
29061
+ }
29062
+ };
29063
+ /** The served faces a starter sheet may name, keyed by their face folder. */
29064
+ const STARTER_FONTS = {
29065
+ geist: {
29066
+ family: "Geist",
29067
+ stack: "Geist, sans-serif"
29068
+ },
29069
+ "geist-mono": {
29070
+ family: "Geist Mono",
29071
+ stack: "'Geist Mono', monospace"
29072
+ }
29073
+ };
29074
+ const DEFAULT_LOOK = {
29075
+ accent: "blue",
29076
+ font: "geist"
29077
+ };
29078
+ /** A project token sheet setting the names the fixture sheets use, light then dark. */
29079
+ function starterSheet({ accent, font }) {
29080
+ const pair = STARTER_ACCENTS[accent];
29081
+ return `:root {
29082
+ --accent: ${pair.light};
29083
+ --surface: #ffffff;
29084
+ --text: #111111;
29085
+ --muted: #6b7280;
29086
+ --border: #e5e7eb;
29087
+ --radius: 10px;
29088
+ --font-text: ${STARTER_FONTS[font].stack};
29089
+ }
29090
+
29091
+ [data-theme='dark'] {
29092
+ --accent: ${pair.dark};
29093
+ --surface: #111111;
29094
+ --text: #ededed;
29095
+ --muted: #9ca3af;
29096
+ --border: #2e2e2e;
29097
+ }
29098
+ `;
29099
+ }
28938
29100
  // src/server/edit/insert.ts
28939
- const SHAPE_SIZE = "100px";
29101
+ const SHAPE_SIZE = 100;
28940
29102
  const FILL_TOKENS = [
28941
29103
  "--muted",
28942
29104
  "--secondary",
28943
29105
  "--accent"
28944
29106
  ];
28945
29107
  const LINE_TOKEN = "--border";
29108
+ const TEXT_FONT_TOKEN = "--font-text";
28946
29109
  /** Raw on purpose, so the check names it once the project sets no color token. */
28947
29110
  const RAW_GREY = "#d9d9d9";
28948
29111
  const PAINT_VALUE = /^(?:var\(--[\w-]+\)|#[0-9a-f]{6})$/i;
@@ -28986,15 +29149,25 @@ function shapePaint(tokens) {
28986
29149
  line: paint(names.has(LINE_TOKEN) ? LINE_TOKEN : firstColor)
28987
29150
  };
28988
29151
  }
28989
- /** Every byte an insert of `element` writes, with its `data-name` and default size. */
28990
- function elementMarkup(element, paint) {
29152
+ /**
29153
+ * The family placed text sets, being the project's text font token, else
29154
+ * Geist, so a frame with no font of its own still passes `default-font`.
29155
+ */
29156
+ function textFont(tokens) {
29157
+ return tokens.some((row) => row.name === TEXT_FONT_TOKEN) ? `var(${TEXT_FONT_TOKEN})` : STARTER_FONTS.geist.stack;
29158
+ }
29159
+ /** Every byte an insert of `element` writes, with its `data-name` and size. */
29160
+ function elementMarkup(element, paint, font) {
28991
29161
  const { fill, line } = paint;
28992
29162
  if (!PAINT_VALUE.test(fill) || !PAINT_VALUE.test(line)) throw new Error(`Unexpected shape paint ${fill} ${line}`);
28993
- const box = `width: ${SHAPE_SIZE}; height: ${SHAPE_SIZE}; background: ${fill}`;
29163
+ const box = ({ width = SHAPE_SIZE, height = SHAPE_SIZE }) => {
29164
+ if (!Number.isInteger(width) || !Number.isInteger(height)) throw new Error(`Unexpected shape size ${width} ${height}`);
29165
+ return `width: ${width}px; height: ${height}px; background: ${fill}`;
29166
+ };
28994
29167
  switch (element.kind) {
28995
- case "text": return "<p data-name=\"Text\">Text</p>";
28996
- case "rectangle": return `<div data-name="Rectangle" style="${box}"></div>`;
28997
- case "ellipse": return `<div data-name="Ellipse" style="${box}; border-radius: 50%"></div>`;
29168
+ case "text": return `<p data-name="Text" style="font-family: ${font}">Text</p>`;
29169
+ case "rectangle": return `<div data-name="Rectangle" style="${box(element)}"></div>`;
29170
+ case "ellipse": return `<div data-name="Ellipse" style="${box(element)}; border-radius: 50%"></div>`;
28998
29171
  case "divider": return `<hr data-name="Divider" style="align-self: stretch; margin: 0; border: 0; ${element.vertical ? "border-left" : "border-top"}: 1px solid ${line}">`;
28999
29172
  }
29000
29173
  }
@@ -29038,18 +29211,24 @@ function gapOffset(tree, placement) {
29038
29211
  * the input's with that one element added under the parent, so a tag the
29039
29212
  * parser would move, as a `<div>` closing a `<p>`, is refused rather than
29040
29213
  * written somewhere else.
29214
+ *
29215
+ * A `lead` lands the element that many bytes ahead of the gap, once they
29216
+ * read as given, so an element put back lands where it stood and not past
29217
+ * the whitespace that followed it.
29041
29218
  */
29042
- function insertElement(source, placement, markup) {
29219
+ function insertElement(source, placement, markup, lead = "") {
29043
29220
  const before = parseFrame(source);
29044
29221
  const gap = gapOffset(before, placement);
29045
29222
  if ("ok" in gap) return gap;
29046
- const { parent, offset } = gap;
29223
+ const { parent } = gap;
29224
+ const offset = gap.offset - lead.length;
29225
+ if (offset < 0 || source.slice(offset, gap.offset) !== lead) return refuse$1("address-mismatch", `the bytes ahead of the gap in the <${parent.tagName}> at ${placement.parent} changed`);
29047
29226
  const written = source.slice(0, offset) + markup + source.slice(offset);
29048
29227
  const after = parseFrame(written);
29049
29228
  const index = after.elements.findIndex((element) => element.sourceCodeLocation?.startOffset === offset);
29050
29229
  const added = after.elements[index];
29051
- if (!added || after.elements.length !== before.elements.length + 1 || added.parentNode !== after.elements[placement.parent] || spanText(written, added, "element") !== markup || !addsOnly(before, after, added)) return refuse$1("verify-failed", `a <${added?.tagName ?? "new element"}> there would change more than the <${parent.tagName}> it goes in, so nothing was written`);
29052
- const next = children(parent).find((child) => child.sourceCodeLocation?.startOffset === offset);
29230
+ if (!added || after.elements.length !== before.elements.length + 1 + descendants(added) || added.parentNode !== after.elements[placement.parent] || spanText(written, added, "element") !== markup || !addsOnly(before, after, added)) return refuse$1("verify-failed", `a <${added?.tagName ?? "new element"}> there would change more than the <${parent.tagName}> it goes in, so nothing was written`);
29231
+ const next = children(parent).find((child) => child.sourceCodeLocation?.startOffset === gap.offset);
29053
29232
  return {
29054
29233
  ok: true,
29055
29234
  html: written,
@@ -29063,10 +29242,15 @@ function insertElement(source, placement, markup) {
29063
29242
  tagName: parent.tagName,
29064
29243
  tag: startTag(source, parent)
29065
29244
  },
29066
- next: next ? startTag(source, next) : null
29245
+ next: next ? startTag(source, next) : null,
29246
+ lead
29067
29247
  }
29068
29248
  };
29069
29249
  }
29250
+ /** How many elements `element` holds, at any depth. */
29251
+ function descendants(element) {
29252
+ return children(element).reduce((count, child) => count + 1 + descendants(child), 0);
29253
+ }
29070
29254
  /** Whether `after` is `before` with `added` alone added, compared once it is taken out. */
29071
29255
  function addsOnly(before, after, added) {
29072
29256
  const parent = added.parentNode;
@@ -29087,7 +29271,8 @@ function locateInserted(source, tree, span) {
29087
29271
  /** The gap the span goes back into, read off its anchors where the frame now stands. */
29088
29272
  function locateGap(source, tree, span) {
29089
29273
  const reads = (element) => element !== void 0 && element.tagName === span.parent.tagName && startTag(source, element) === span.parent.tag;
29090
- const candidates = tree.elements.length === span.count - 1 && reads(tree.elements[span.placement.parent]) ? [span.placement.parent] : tree.elements.flatMap((element, index) => reads(element) ? [index] : []);
29274
+ const held = tree.elements.length === span.count - markupSize(span.markup);
29275
+ const candidates = held && reads(tree.elements[span.placement.parent]) ? [span.placement.parent] : tree.elements.flatMap((element, index) => reads(element) ? [index] : []);
29091
29276
  const parentIndex = candidates.length === 1 ? candidates[0] : void 0;
29092
29277
  const parent = parentIndex === void 0 ? void 0 : tree.elements[parentIndex];
29093
29278
  if (parentIndex === void 0 || !parent) return void 0;
@@ -29095,6 +29280,11 @@ function locateGap(source, tree, span) {
29095
29280
  parent: parentIndex,
29096
29281
  before: null
29097
29282
  };
29283
+ const recorded = span.placement.before === null ? void 0 : tree.elements[span.placement.before];
29284
+ if (held && recorded && recorded.parentNode === parent && startTag(source, recorded) === span.next) return {
29285
+ parent: parentIndex,
29286
+ before: span.placement.before
29287
+ };
29098
29288
  const next = children(parent).filter((child) => startTag(source, child) === span.next);
29099
29289
  const [sibling] = next;
29100
29290
  return next.length === 1 && sibling ? {
@@ -29102,6 +29292,11 @@ function locateGap(source, tree, span) {
29102
29292
  before: tree.elements.indexOf(sibling)
29103
29293
  } : void 0;
29104
29294
  }
29295
+ /** How many elements `markup` holds, itself and everything inside it. */
29296
+ function markupSize(markup) {
29297
+ const count = (node) => node.childNodes.reduce((total, child) => total + (hasTag(child) ? 1 + count(child) : 0), 0);
29298
+ return count(parseFragment(markup));
29299
+ }
29105
29300
  /** Whether the frame stands as `side` of the insert left it, with the element or with its gap. */
29106
29301
  function holdsInserted(source, span, side) {
29107
29302
  const tree = parseFrame(source);
@@ -29115,16 +29310,29 @@ function holdsInserted(source, span, side) {
29115
29310
  function removeInserted(source, span) {
29116
29311
  const tree = parseFrame(source);
29117
29312
  const index = locateInserted(source, tree, span);
29118
- const element = index === void 0 ? void 0 : tree.elements[index];
29313
+ return index === void 0 ? void 0 : takeOut$1(source, tree, index);
29314
+ }
29315
+ /**
29316
+ * Takes the element at `index` out with its descendants and answers the span
29317
+ * that puts it back, holding the bytes that stood between it and its gap.
29318
+ * Answers undefined when the element is not stated, or when putting it back
29319
+ * would not give `source` again, since the removal then reached past it.
29320
+ */
29321
+ function takeOut$1(source, tree, index) {
29322
+ const element = tree.elements[index];
29119
29323
  const at = element?.sourceCodeLocation;
29120
29324
  const parent = element?.parentNode;
29121
- if (index === void 0 || !at || !parent || !hasTag(parent)) return void 0;
29325
+ if (!element || !at?.startTag || !parent || !hasTag(parent)) return void 0;
29122
29326
  const removed = source.slice(0, at.startOffset) + source.slice(at.endOffset);
29123
29327
  const next = children(parent)[children(parent).indexOf(element) + 1];
29124
- const back = insertElement(removed, {
29328
+ const placement = {
29125
29329
  parent: tree.elements.indexOf(parent),
29126
29330
  before: next ? index : null
29127
- }, span.markup);
29331
+ };
29332
+ const gap = gapOffset(parseFrame(removed), placement);
29333
+ if ("ok" in gap || gap.offset < at.startOffset) return void 0;
29334
+ const lead = removed.slice(at.startOffset, gap.offset);
29335
+ const back = insertElement(removed, placement, source.slice(at.startOffset, at.endOffset), lead);
29128
29336
  if (!back.ok || back.html !== source) return void 0;
29129
29337
  return {
29130
29338
  html: removed,
@@ -29132,6 +29340,44 @@ function removeInserted(source, span) {
29132
29340
  };
29133
29341
  }
29134
29342
  /**
29343
+ * Takes out the element at `index`, with everything it holds, and answers
29344
+ * the span `restoreInserted` puts it back by, so a delete is an insert run
29345
+ * backwards. Only an element under `body` is taken, and the removal is
29346
+ * refused as `verify-failed` unless the result parses as the source with
29347
+ * that element alone gone, and its bytes go back as that one element.
29348
+ * Putting it back lands it
29349
+ * before the same sibling, so the whitespace around it may sit on its other
29350
+ * side.
29351
+ */
29352
+ function removeElement$1(source, index) {
29353
+ const tree = parseFrame(source);
29354
+ if (tree.unstated) return refuse$1("address-mismatch", `the browser builds a <${tree.unstated.tagName}> the file does not state, so indices after it disagree`);
29355
+ const element = tree.elements[index];
29356
+ if (!element || !underBody(element)) return refuse$1("invalid-address", `${index} names no element under the frame's body`);
29357
+ const at = element.sourceCodeLocation;
29358
+ const parent = element.parentNode;
29359
+ if (!at || !parent || !hasTag(parent)) return refuse$1("address-mismatch", `the <${element.tagName}> at ${index} is not stated in the file`);
29360
+ const removed = source.slice(0, at.startOffset) + source.slice(at.endOffset);
29361
+ const next = children(parent)[children(parent).indexOf(element) + 1];
29362
+ const back = insertElement(removed, {
29363
+ parent: tree.elements.indexOf(parent),
29364
+ before: next ? index : null
29365
+ }, source.slice(at.startOffset, at.endOffset));
29366
+ parent.childNodes = parent.childNodes.filter((node) => node !== element);
29367
+ const removesOnly = serialize(tree.document) === serialize(parseFrame(removed).document);
29368
+ if (!back.ok || !removesOnly) return refuse$1("verify-failed", `taking out the <${element.tagName}> at ${index} would change more than it, so nothing was written`);
29369
+ if (!holdsInserted(removed, back.span, "before")) return refuse$1("verify-failed", `the <${element.tagName}> at ${index} could not be put back once taken out, so nothing was written`);
29370
+ return {
29371
+ ok: true,
29372
+ html: removed,
29373
+ span: back.span
29374
+ };
29375
+ }
29376
+ function underBody(element) {
29377
+ for (let node = element.parentNode; node && hasTag(node); node = node.parentNode) if (node.tagName === "body") return true;
29378
+ return false;
29379
+ }
29380
+ /**
29135
29381
  * Writes the element back into its gap, found by the parent's and the next
29136
29382
  * sibling's start tags, and answers the span as it now stands. Answers
29137
29383
  * undefined when the gap is not found or the write is refused.
@@ -29139,12 +29385,68 @@ function removeInserted(source, span) {
29139
29385
  function restoreInserted(source, span) {
29140
29386
  const placement = locateGap(source, parseFrame(source), span);
29141
29387
  if (!placement) return void 0;
29142
- const inserted = insertElement(source, placement, span.markup);
29388
+ const inserted = insertElement(source, placement, span.markup, span.lead);
29143
29389
  return inserted.ok ? {
29144
29390
  html: inserted.html,
29145
29391
  span: inserted.span
29146
29392
  } : void 0;
29147
29393
  }
29394
+ /**
29395
+ * Takes the element at `index` out by its bytes and writes them into the gap
29396
+ * `placement` names, both read in the frame as it stands, leaving every other
29397
+ * byte. A gap in the element or under it is refused as `invalid-container`,
29398
+ * since the element would be written inside itself, and the gap it already
29399
+ * sits in as `invalid-address`. Each half is checked as `insertElement`
29400
+ * checks a placement, so a move the parser would rebuild is refused whole.
29401
+ */
29402
+ function moveElement(source, index, placement) {
29403
+ const tree = parseFrame(source);
29404
+ const element = Number.isInteger(index) ? tree.elements[index] : void 0;
29405
+ if (!element?.sourceCodeLocation?.startTag) return refuse$1("invalid-address", `${index} names no element the file states`);
29406
+ const end = index + 1 + descendants(element);
29407
+ const shift = (at) => at < end ? at : at - (end - index);
29408
+ if (placement.parent >= index && placement.parent < end) return refuse$1("invalid-container", `the <${element.tagName}> at ${index} cannot go inside itself`);
29409
+ const taken = takeOut$1(source, tree, index);
29410
+ if (!taken) return refuse$1("verify-failed", `taking the <${element.tagName}> at ${index} out would change more than it, so nothing was written`);
29411
+ const target = {
29412
+ parent: shift(placement.parent),
29413
+ before: placement.before === null ? null : shift(placement.before)
29414
+ };
29415
+ if (target.parent === taken.span.placement.parent && target.before === taken.span.placement.before) return refuse$1("invalid-address", `the <${element.tagName}> at ${index} already sits in that gap`);
29416
+ const moved = insertElement(taken.html, target, taken.span.markup);
29417
+ if (!moved.ok) return moved;
29418
+ return {
29419
+ ok: true,
29420
+ html: moved.html,
29421
+ index: moved.index,
29422
+ span: {
29423
+ from: taken.span,
29424
+ to: moved.span
29425
+ }
29426
+ };
29427
+ }
29428
+ /**
29429
+ * Writes the moved element back to `side` of the move, taking it out of the
29430
+ * other gap by its bytes and into this one by its anchors, and answers the
29431
+ * span as the frame then stands. Answers undefined when either half is not
29432
+ * found, so a step the frame no longer allows is refused rather than guessed.
29433
+ */
29434
+ function relocateMoved(source, span, side) {
29435
+ const [leave, land] = side === "before" ? [span.to, span.from] : [span.from, span.to];
29436
+ const removed = removeInserted(source, leave);
29437
+ const written = removed && restoreInserted(removed.html, land);
29438
+ if (!removed || !written) return void 0;
29439
+ return {
29440
+ html: written.html,
29441
+ span: side === "before" ? {
29442
+ from: written.span,
29443
+ to: removed.span
29444
+ } : {
29445
+ from: removed.span,
29446
+ to: written.span
29447
+ }
29448
+ };
29449
+ }
29148
29450
  // src/server/edit/frame-file.ts
29149
29451
  function stale(path) {
29150
29452
  return refuse$1("stale-address", `${basename(path)} changed after this edit was made, so nothing was written`);
@@ -29214,6 +29516,43 @@ function insertFrameFile(path, hash, placement, markup) {
29214
29516
  };
29215
29517
  }
29216
29518
  /**
29519
+ * Takes one element out of a frame file the way `insertFrameFile` writes one
29520
+ * in, refusing a hash the file no longer has as stale, so a retried delete
29521
+ * takes out at most one element.
29522
+ */
29523
+ function removeFrameFile(path, hash, index) {
29524
+ const read = readSource(path);
29525
+ if (!read.ok) return read;
29526
+ if (read.hash !== hash) return stale(path);
29527
+ const removed = removeElement$1(read.source, index);
29528
+ if (!removed.ok) return removed;
29529
+ if (!replaceFile(path, hash, removed.html)) return stale(path);
29530
+ return {
29531
+ ok: true,
29532
+ hash: contentHash(removed.html),
29533
+ span: removed.span
29534
+ };
29535
+ }
29536
+ /**
29537
+ * Moves one element of a frame file into another gap, written as
29538
+ * `insertFrameFile` writes, and refused as stale on a hash the file no longer
29539
+ * has, since both indices name nothing once the file moved.
29540
+ */
29541
+ function moveFrameFile(path, hash, index, placement) {
29542
+ const read = readSource(path);
29543
+ if (!read.ok) return read;
29544
+ if (read.hash !== hash) return stale(path);
29545
+ const moved = moveElement(read.source, index, placement);
29546
+ if (!moved.ok) return moved;
29547
+ if (!replaceFile(path, hash, moved.html)) return stale(path);
29548
+ return {
29549
+ ok: true,
29550
+ hash: contentHash(moved.html),
29551
+ index: moved.index,
29552
+ span: moved.span
29553
+ };
29554
+ }
29555
+ /**
29217
29556
  * A frame file's text and hash. Bytes that do not survive a UTF-8 round trip
29218
29557
  * are refused, since decoding would rewrite every invalid byte.
29219
29558
  */
@@ -29288,6 +29627,8 @@ async function parseBody$1(request, schema) {
29288
29627
  // src/server/routes/edit.ts
29289
29628
  const value = string$1().max(1e4);
29290
29629
  const name$1 = string$1().min(1).max(256);
29630
+ /** A dragged shape's side in CSS pixels. */
29631
+ const side = int$1().min(1).max(1e4);
29291
29632
  const editSchema = object$1({
29292
29633
  ref: string$1().min(1).max(1024),
29293
29634
  index: int$1().min(0),
@@ -29316,16 +29657,36 @@ const insertSchema = object$1({
29316
29657
  before: int$1().min(0).nullable(),
29317
29658
  element: discriminatedUnion("kind", [
29318
29659
  object$1({ kind: literal("text") }),
29319
- object$1({ kind: literal("rectangle") }),
29320
- object$1({ kind: literal("ellipse") }),
29660
+ object$1({
29661
+ kind: literal("rectangle"),
29662
+ width: side.optional(),
29663
+ height: side.optional()
29664
+ }),
29665
+ object$1({
29666
+ kind: literal("ellipse"),
29667
+ width: side.optional(),
29668
+ height: side.optional()
29669
+ }),
29321
29670
  object$1({
29322
29671
  kind: literal("divider"),
29323
29672
  vertical: boolean$1()
29324
29673
  })
29325
29674
  ])
29326
29675
  });
29676
+ const removeSchema = object$1({
29677
+ ref: string$1().min(1).max(1024),
29678
+ index: int$1().min(0),
29679
+ hash: string$1().regex(/^[0-9a-f]{64}$/)
29680
+ });
29681
+ const moveSchema$1 = object$1({
29682
+ ref: string$1().min(1).max(1024),
29683
+ hash: string$1().regex(/^[0-9a-f]{64}$/),
29684
+ index: int$1().min(0),
29685
+ parent: int$1().min(0),
29686
+ before: int$1().min(0).nullable()
29687
+ });
29327
29688
  /**
29328
- * A hand edit of one element and a placed element, each behind
29689
+ * A hand edit of one element, a placed element, and a deleted one, each behind
29329
29690
  * `requireWriter` and refused on a frame another session holds.
29330
29691
  *
29331
29692
  * The edit's body mirrors
@@ -29342,6 +29703,18 @@ const insertSchema = object$1({
29342
29703
  * the new element's index, and the hash written. A hash the file no longer
29343
29704
  * has answers 409 `stale-address` with nothing written, since the gap's
29344
29705
  * indices name nothing past an agent's write, and a retried insert lands once.
29706
+ * A rectangle or an ellipse takes an optional width and height a drag drew.
29707
+ *
29708
+ * The remove takes out the element at `index`, with what it holds, from the
29709
+ * bytes `hash` names, and records it as one step whose undo puts it back
29710
+ * under its parent. It answers the frame and the hash written, and refuses a
29711
+ * moved file as `stale-address` the way the insert does.
29712
+ *
29713
+ * The move takes one element by index and the gap it goes into, both read
29714
+ * in the frame as the hash names it, and records it as one step an undo
29715
+ * puts back byte for byte. It answers the element's new index and the hash
29716
+ * written, and refuses as the insert does, with `invalid-container` for a
29717
+ * gap inside the element itself.
29345
29718
  */
29346
29719
  function editRoutes(root, access, history, version, sheets) {
29347
29720
  const app = new Hono();
@@ -29397,7 +29770,7 @@ function editRoutes(root, access, history, version, sheets) {
29397
29770
  const result = insertFrameFile(frame.path, body.hash, {
29398
29771
  parent: body.parent,
29399
29772
  before: body.before
29400
- }, elementMarkup(body.element, shapePaint(tokens)));
29773
+ }, elementMarkup(body.element, shapePaint(tokens), textFont(tokens)));
29401
29774
  if (!result.ok) return c.json({
29402
29775
  ok: false,
29403
29776
  error: {
@@ -29427,6 +29800,79 @@ function editRoutes(root, access, history, version, sheets) {
29427
29800
  data
29428
29801
  });
29429
29802
  });
29803
+ app.post("/api/frames/remove", requireWriter(access), async (c) => {
29804
+ const body = await parseBody$1(c.req.raw, removeSchema);
29805
+ const frame = await resolveFrameRef(root, body.ref, { cwd: root });
29806
+ const ref = `${frame.project}/${frame.page}/${frame.name}`;
29807
+ await refuseClaimed(root, [ref], /* @__PURE__ */ new Date());
29808
+ const result = removeFrameFile(frame.path, body.hash, body.index);
29809
+ if (!result.ok) return c.json({
29810
+ ok: false,
29811
+ error: {
29812
+ code: result.reason,
29813
+ message: result.detail,
29814
+ details: {
29815
+ ref,
29816
+ index: body.index
29817
+ }
29818
+ }
29819
+ }, 409);
29820
+ const journal = history.journal();
29821
+ journal.deletedElement(frame.path, ref, result.span);
29822
+ history.record({
29823
+ id: journal.id,
29824
+ changes: journal.changes,
29825
+ page: null,
29826
+ frames: [ref]
29827
+ });
29828
+ const data = {
29829
+ ref,
29830
+ hash: result.hash
29831
+ };
29832
+ return c.json({
29833
+ ok: true,
29834
+ data
29835
+ });
29836
+ });
29837
+ app.post("/api/frames/move", requireWriter(access), async (c) => {
29838
+ const body = await parseBody$1(c.req.raw, moveSchema$1);
29839
+ const frame = await resolveFrameRef(root, body.ref, { cwd: root });
29840
+ const ref = `${frame.project}/${frame.page}/${frame.name}`;
29841
+ await refuseClaimed(root, [ref], /* @__PURE__ */ new Date());
29842
+ const result = moveFrameFile(frame.path, body.hash, body.index, {
29843
+ parent: body.parent,
29844
+ before: body.before
29845
+ });
29846
+ if (!result.ok) return c.json({
29847
+ ok: false,
29848
+ error: {
29849
+ code: result.reason,
29850
+ message: result.detail,
29851
+ details: {
29852
+ ref,
29853
+ index: body.index,
29854
+ parent: body.parent
29855
+ }
29856
+ }
29857
+ }, 409);
29858
+ const journal = history.journal();
29859
+ journal.relocated(frame.path, ref, result.span);
29860
+ history.record({
29861
+ id: journal.id,
29862
+ changes: journal.changes,
29863
+ page: null,
29864
+ frames: [ref]
29865
+ });
29866
+ const data = {
29867
+ ref,
29868
+ index: result.index,
29869
+ hash: result.hash
29870
+ };
29871
+ return c.json({
29872
+ ok: true,
29873
+ data
29874
+ });
29875
+ });
29430
29876
  app.onError(answerRefusal);
29431
29877
  return app;
29432
29878
  }
@@ -34489,7 +34935,7 @@ function inlineDeclarations(element, reads) {
34489
34935
  0,
34490
34936
  0
34491
34937
  ],
34492
- order: Number.MAX_SAFE_INTEGER
34938
+ order: declarations.length
34493
34939
  });
34494
34940
  });
34495
34941
  return declarations;
@@ -34568,15 +35014,17 @@ const LAYOUT_PROPERTIES = /* @__PURE__ */ new Set([
34568
35014
  "flex-direction",
34569
35015
  "flex-flow"
34570
35016
  ]);
35017
+ const ROUND_PROPERTIES = /* @__PURE__ */ new Set(["border-radius"]);
34571
35018
  /**
34572
35019
  * A frame's elements under `body` in index order, each with its parent and
34573
35020
  * name, read from the same parse and the same index `edit` addresses. A
34574
35021
  * frame where the browser builds an element the file does not state is
34575
35022
  * refused, since every index after it would name another element.
34576
35023
  * `layouts` is `elementLayouts`'s read by the same index, and an element it
34577
- * does not reach reads as `block`.
35024
+ * does not reach reads as `block`. `rounds` is `elementRounds`'s read, which
35025
+ * marks an element round only while it holds nothing.
34578
35026
  */
34579
- function elementTree(source, layouts = []) {
35027
+ function elementTree(source, layouts = [], rounds = []) {
34580
35028
  const tree = parseFrame(source);
34581
35029
  if (tree.unstated) return refuse$1("address-mismatch", `the browser builds a <${tree.unstated.tagName}> the file does not state, so indices after it disagree`);
34582
35030
  const index = new Map(tree.elements.map((element, at) => [element, at]));
@@ -34594,7 +35042,8 @@ function elementTree(source, layouts = []) {
34594
35042
  tag: element.tagName,
34595
35043
  name: elementName(element),
34596
35044
  textOnly: ownText$2(element) !== null,
34597
- layout: layouts[at] ?? "block"
35045
+ layout: layouts[at] ?? "block",
35046
+ round: (rounds[at] ?? false) && isEmpty(element)
34598
35047
  });
34599
35048
  }
34600
35049
  return listed;
@@ -34610,6 +35059,17 @@ function elementLayouts(source, tokens) {
34610
35059
  const cascade = buildCascade(source, tokens, { properties: LAYOUT_PROPERTIES });
34611
35060
  return source.elements.map((element) => layoutOf(cascade, element));
34612
35061
  }
35062
+ /**
35063
+ * Whether each element's corners round by half its size or more, read from
35064
+ * the same static cascade by the edit index, as a placed ellipse sets them.
35065
+ */
35066
+ function elementRounds(source, tokens) {
35067
+ const cascade = buildCascade(source, tokens, { properties: ROUND_PROPERTIES });
35068
+ return source.elements.map((element) => {
35069
+ const percent = (cascade.specified(element, "border-radius")?.value.trim())?.match(/^(\d+(?:\.\d+)?)%$/)?.[1];
35070
+ return percent !== void 0 && Number(percent) >= 50;
35071
+ });
35072
+ }
34613
35073
  function layoutOf(cascade, element) {
34614
35074
  const display = words(cascade.specified(element, "display")?.value);
34615
35075
  if (display.includes("grid") || display.includes("inline-grid")) return "grid";
@@ -34639,6 +35099,10 @@ function ownText$2(element) {
34639
35099
  const text = texts.map((node) => node.value).join("").replace(/\s+/g, " ").trim();
34640
35100
  return text === "" ? null : text;
34641
35101
  }
35102
+ /** True when the element holds no element and no text past whitespace. */
35103
+ function isEmpty(element) {
35104
+ return element.childNodes.every((node) => isText(node) && node.value.trim() === "");
35105
+ }
34642
35106
  function isText(node) {
34643
35107
  return node.nodeName === "#text";
34644
35108
  }
@@ -34858,8 +35322,9 @@ function elementsRoutes(root, access, selection, tokens = null) {
34858
35322
  const readTree = async (ref) => {
34859
35323
  const frame = await resolveFrameRef(root, ref, { cwd: root });
34860
35324
  const bytes = await readFile(frame.path);
34861
- const layouts = elementLayouts(readFrame(frame), tokenSheets(root, frame.project, tokens));
34862
- const elements = elementTree(bytes.toString("utf8"), layouts);
35325
+ const source = readFrame(frame);
35326
+ const sheets = tokenSheets(root, frame.project, tokens);
35327
+ const elements = elementTree(bytes.toString("utf8"), elementLayouts(source, sheets), elementRounds(source, sheets));
34863
35328
  if (!Array.isArray(elements)) throw new FrameboardError(elements.reason, elements.detail, { ref });
34864
35329
  return {
34865
35330
  ref: `${frame.project}/${frame.page}/${frame.name}`,
@@ -35451,6 +35916,141 @@ async function hashOf(path) {
35451
35916
  throw error;
35452
35917
  }
35453
35918
  }
35919
+ // src/server/notes/dispatch.ts
35920
+ /** The `serve` environment variable holding the command a dispatched note runs. */
35921
+ const DISPATCH_ENV = "FRAMEBOARD_DISPATCH";
35922
+ const DISPATCH_LOG = "dispatch.log";
35923
+ /**
35924
+ * How long a command has to fail before it counts as started. A command that
35925
+ * backgrounds its session and exits 0, as `claude --bg` does, counts at once.
35926
+ * `claude --bg` refusing an untrusted folder exits 1 near 700 ms, so the
35927
+ * window sits well past that.
35928
+ */
35929
+ const START_WINDOW_MS = 2e3;
35930
+ /**
35931
+ * Starts a session for a note by running the developer's command detached,
35932
+ * its output appended to `.run/dispatch.log`. The note reaches the command as
35933
+ * environment variables alone, never spliced into the command string, so its
35934
+ * text is data to the shell. Resolves once the command exits 0 or outlives
35935
+ * the window, and refuses `dispatch-failed` when it exits otherwise inside it.
35936
+ */
35937
+ function createDispatcher({ command, cwd, root, env, windowMs = START_WINDOW_MS }) {
35938
+ return async ({ session, id, line }) => {
35939
+ const log = await open(join(await ensureRunFolder(root), DISPATCH_LOG), "a");
35940
+ try {
35941
+ await started(spawn("sh", ["-c", command], {
35942
+ cwd,
35943
+ detached: true,
35944
+ stdio: [
35945
+ "ignore",
35946
+ log.fd,
35947
+ log.fd
35948
+ ],
35949
+ env: {
35950
+ ...env,
35951
+ FRAMEBOARD_SESSION: session,
35952
+ FRAMEBOARD_NOTE: line,
35953
+ FRAMEBOARD_NOTE_ID: id,
35954
+ FRAMEBOARD_ROOT: root
35955
+ }
35956
+ }), windowMs);
35957
+ } finally {
35958
+ await log.close();
35959
+ }
35960
+ };
35961
+ }
35962
+ function started(child, windowMs) {
35963
+ return new Promise((resolve, reject) => {
35964
+ const timer = setTimeout(() => {
35965
+ child.unref();
35966
+ resolve();
35967
+ }, windowMs);
35968
+ child.once("error", (error) => {
35969
+ clearTimeout(timer);
35970
+ reject(new FrameboardError("dispatch-failed", `The ${DISPATCH_ENV} command did not start: ${error.message}`, {}, { cause: error }));
35971
+ });
35972
+ child.once("exit", (code, signal) => {
35973
+ clearTimeout(timer);
35974
+ if (code === 0) {
35975
+ resolve();
35976
+ return;
35977
+ }
35978
+ reject(new FrameboardError("dispatch-failed", `The ${DISPATCH_ENV} command exited ${code ?? signal} within ${windowMs} ms. Its output is in .run/${DISPATCH_LOG}.`, {
35979
+ code,
35980
+ signal
35981
+ }));
35982
+ });
35983
+ });
35984
+ }
35985
+ // src/server/notes/images.ts
35986
+ /** A page's folder of note images, dot-named so the board never reads it as content. */
35987
+ const NOTES_FOLDER = ".notes";
35988
+ /** A stored image as a note records it, relative to its page. */
35989
+ const STORED = /^\.notes\/[0-9a-f]{12}\.(png|jpg|gif|webp)$/;
35990
+ const IMAGE_CONTENT_TYPES = {
35991
+ png: "image/png",
35992
+ jpg: "image/jpeg",
35993
+ gif: "image/gif",
35994
+ webp: "image/webp"
35995
+ };
35996
+ /**
35997
+ * The extension an image's bytes declare, or null for anything but PNG,
35998
+ * JPEG, GIF, and WebP. SVG is left out on purpose, since it can carry script
35999
+ * and the thumbnails render in the board's own page.
36000
+ */
36001
+ function imageExtension(bytes) {
36002
+ const ascii = (from, to) => String.fromCharCode(...bytes.subarray(from, to));
36003
+ if (bytes[0] === 137 && ascii(1, 4) === "PNG") return "png";
36004
+ if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "jpg";
36005
+ if (ascii(0, 4) === "GIF8") return "gif";
36006
+ if (ascii(0, 4) === "RIFF" && ascii(8, 12) === "WEBP") return "webp";
36007
+ return null;
36008
+ }
36009
+ /**
36010
+ * Saves each image to `<page>/.notes/` under a fresh random name and answers
36011
+ * the page-relative paths in order. Every image is checked before any is
36012
+ * written, so a refusal leaves the folder as it was.
36013
+ */
36014
+ async function saveImages(pageDir, images) {
36015
+ const typed = images.map((bytes, index) => {
36016
+ const extension = imageExtension(bytes);
36017
+ if (extension === null) throw new FrameboardError("image-type-refused", "A note takes PNG, JPEG, GIF, or WebP images. Nothing was saved.", { index });
36018
+ return {
36019
+ bytes,
36020
+ extension
36021
+ };
36022
+ });
36023
+ const folder = join(pageDir, NOTES_FOLDER);
36024
+ await mkdir(folder, { recursive: true });
36025
+ return Promise.all(typed.map(async ({ bytes, extension }) => {
36026
+ const name = `${randomBytes(6).toString("hex")}.${extension}`;
36027
+ await writeFile(join(folder, name), bytes, { flag: "wx" });
36028
+ return `${NOTES_FOLDER}/${name}`;
36029
+ }));
36030
+ }
36031
+ /**
36032
+ * The absolute path of a stored image in a page, or null when the path is
36033
+ * not one `saveImages` writes, the file is gone, or its real path leaves the
36034
+ * page's `.notes/`.
36035
+ */
36036
+ async function storedImage(pageDir, stored) {
36037
+ if (!STORED.test(stored)) return null;
36038
+ try {
36039
+ const folder = await realpath(join(pageDir, NOTES_FOLDER));
36040
+ const file = await realpath(join(pageDir, stored));
36041
+ if (!file.startsWith(folder + sep)) return null;
36042
+ return (await stat(file)).isFile() ? file : null;
36043
+ } catch (error) {
36044
+ if (isCode(error, "ENOENT") || isCode(error, "ENOTDIR")) return null;
36045
+ throw error;
36046
+ }
36047
+ }
36048
+ /** Refuses a note naming an image its page does not hold, before anything is written. */
36049
+ async function assertStored(pageDir, images) {
36050
+ const found = await Promise.all(images.map((image) => storedImage(pageDir, image)));
36051
+ const missing = images.filter((_, index) => found[index] === null);
36052
+ if (missing.length > 0) throw new FrameboardError("usage", `The note names images its page does not hold: ${missing.join(", ")}. Upload each one first.`, { missing });
36053
+ }
35454
36054
  // src/shared/records/notes.ts
35455
36055
  /** Where a note on one element points, in the edit address's terms. */
35456
36056
  const noteAnchorSchema = looseObject({
@@ -35469,6 +36069,8 @@ const noteSchema = looseObject({
35469
36069
  /** Null for a note on the whole frame. */
35470
36070
  anchor: noteAnchorSchema.nullable(),
35471
36071
  text: string$1(),
36072
+ /** Images saved with the message, relative to its page, as `.notes/<file>`. Absent on a note with none. */
36073
+ images: array$1(string$1()).optional(),
35472
36074
  from: _enum$1(["developer", "agent"]),
35473
36075
  /** Who signed it, as git names them, stamped by the server. */
35474
36076
  author: string$1().nullable(),
@@ -35504,15 +36106,21 @@ const listenerSchema = object$1({
35504
36106
  * The one line a follower prints per note. It opens with `frameboard note`,
35505
36107
  * which the skill tells the agent to act on, and names the verbs that answer
35506
36108
  * it. Text is collapsed onto one line, stripped of control characters so it
35507
- * cannot drive the terminal, and cut at 200 characters.
36109
+ * cannot drive the terminal, and cut at 200 characters. Image paths sit
36110
+ * between the text and the hints, so the prefix and the hints never move.
35508
36111
  */
35509
- function noteLine({ id, ref, element, text }) {
35510
- return `frameboard note ${id} on ${element === null ? ref : `${ref} element ${element}`}: ${collapse(text)} (reply: frameboard notes reply ${id} "<text>", close: frameboard notes done ${id})`;
36112
+ function noteLine({ id, ref, element, text, images = [] }) {
36113
+ const where = element === null ? ref : `${ref} element ${element}`;
36114
+ const attached = images.length === 0 ? "" : ` (images: ${images.map(flatten).join(", ")})`;
36115
+ return `frameboard note ${id} on ${where}: ${collapse(text)}${attached} (reply: frameboard notes reply ${id} "<text>", close: frameboard notes done ${id})`;
35511
36116
  }
35512
36117
  function collapse(text) {
35513
- const flat = text.replace(/\s+/g, " ").replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim();
36118
+ const flat = flatten(text);
35514
36119
  return flat.length > 200 ? `${flat.slice(0, 200)}...` : flat;
35515
36120
  }
36121
+ function flatten(text) {
36122
+ return text.replace(/\s+/g, " ").replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim();
36123
+ }
35516
36124
  // src/server/notes/store.ts
35517
36125
  const NOTES_FILE$1 = "notes.json";
35518
36126
  const notesSpec = {
@@ -35589,6 +36197,7 @@ function addRoot(file, fields, { now, id }) {
35589
36197
  frame: fields.frame,
35590
36198
  anchor: fields.anchor,
35591
36199
  text: fields.text,
36200
+ ...withImages(fields.images),
35592
36201
  from: "developer",
35593
36202
  author: fields.author,
35594
36203
  session: null,
@@ -35613,6 +36222,7 @@ function addReply(file, replyTo, fields, { now, id }) {
35613
36222
  frame: root.frame,
35614
36223
  anchor: root.anchor,
35615
36224
  text: fields.text,
36225
+ ...withImages(fields.images),
35616
36226
  from: fields.from,
35617
36227
  author: fields.author,
35618
36228
  session: fields.session,
@@ -35633,6 +36243,10 @@ function addReply(file, replyTo, fields, { now, id }) {
35633
36243
  notes: [...notes, reply]
35634
36244
  };
35635
36245
  }
36246
+ /** A note with no images carries no key, so it reads as one written before images. */
36247
+ function withImages(images) {
36248
+ return images === void 0 || images.length === 0 ? {} : { images };
36249
+ }
35636
36250
  /** Sets the state of the thread `id` belongs to, and its addressee when one is given. */
35637
36251
  function setState(file, id, state, now, to) {
35638
36252
  const root = rootOf(file, id);
@@ -35646,6 +36260,13 @@ function setState(file, id, state, now, to) {
35646
36260
  } : note)
35647
36261
  };
35648
36262
  }
36263
+ /** Takes one message out, for a write whose send failed after it landed. */
36264
+ function removeNote(file, id) {
36265
+ return {
36266
+ ...file,
36267
+ notes: file.notes.filter((note) => note.id !== id)
36268
+ };
36269
+ }
35649
36270
  /** A page's notes as the board draws them, an unreadable file reading as none. */
35650
36271
  async function pageView(root, place) {
35651
36272
  let file;
@@ -35677,23 +36298,36 @@ async function queuedFor(root, session) {
35677
36298
  for (const note of notes) {
35678
36299
  if (note.thread !== null || note.state !== "queued") continue;
35679
36300
  if (note.to !== session) continue;
35680
- const ref = `${place.project}/${place.page}/${note.frame}`;
35681
- const newest = notes.filter((each) => (each.id === note.id || each.thread === note.id) && each.from === "developer").at(-1);
35682
- const { element, ...stored } = note;
35683
- deliveries.push({
35684
- note: stored,
35685
- ref,
35686
- line: noteLine({
35687
- id: note.id,
35688
- ref,
35689
- element,
35690
- text: (newest ?? note).text
35691
- })
35692
- });
36301
+ deliveries.push(toDelivery(place, notes, note));
35693
36302
  }
35694
36303
  }
35695
36304
  return deliveries;
35696
36305
  }
36306
+ /** A root note as a follower would receive it, read from its page whatever its state. */
36307
+ async function deliveryOf(root, place, rootId) {
36308
+ const notes = await pageView(root, place);
36309
+ const note = notes.find((each) => each.id === rootId && each.thread === null);
36310
+ if (!note) throw new FrameboardError("note-not-found", `No note ${rootId} in this page.`, { id: rootId });
36311
+ return toDelivery(place, notes, note);
36312
+ }
36313
+ function toDelivery(place, notes, note) {
36314
+ const ref = `${place.project}/${place.page}/${note.frame}`;
36315
+ const newest = notes.filter((each) => (each.id === note.id || each.thread === note.id) && each.from === "developer").at(-1);
36316
+ const { element, ...stored } = note;
36317
+ const message = newest ?? note;
36318
+ const pageDir = dirname(place.path);
36319
+ return {
36320
+ note: stored,
36321
+ ref,
36322
+ line: noteLine({
36323
+ id: note.id,
36324
+ ref,
36325
+ element,
36326
+ text: message.text,
36327
+ images: message.images?.map((image) => join(pageDir, image))
36328
+ })
36329
+ };
36330
+ }
35697
36331
  /** Marks a root note delivered, while it is still queued to that session. */
35698
36332
  async function markDelivered(root, id, session, now) {
35699
36333
  await updateNotes((await findNote(root, id)).path, (file) => {
@@ -35710,33 +36344,64 @@ const STATUS$1 = {
35710
36344
  "frame-not-found": 404,
35711
36345
  "note-not-found": 404,
35712
36346
  "stale-address": 409,
36347
+ "dispatch-unavailable": 409,
35713
36348
  "notes-invalid": 422,
36349
+ "image-type-refused": 415,
36350
+ "dispatch-failed": 502,
35714
36351
  "lock-timeout": 503
35715
36352
  };
35716
36353
  const text = string$1().trim().min(1).max(1e5);
35717
36354
  const session = string$1().min(1).max(256);
36355
+ /** Page-relative paths an upload answered, each checked against the page on write. */
36356
+ const images = array$1(string$1().max(256)).max(32).optional();
36357
+ /** Asks for a new session in place of `to`. */
36358
+ const dispatch = literal(true).optional();
36359
+ const oneAddressee = {
36360
+ check: (body) => body.to === void 0 || body.dispatch === void 0,
36361
+ message: { message: "names a session or asks to start one, never both" }
36362
+ };
35718
36363
  const pinSchema = object$1({
35719
36364
  /** The frame ref, `<project>/<page>/<frame>`. */
35720
36365
  frame: string$1().min(1).max(1024),
35721
36366
  text,
36367
+ images,
35722
36368
  /** The element's index, given with the `modifiedAt` the board rendered it at. */
35723
36369
  element: int$1().min(0).optional(),
35724
36370
  renderedAt: string$1().optional(),
35725
- to: session.optional()
35726
- });
36371
+ to: session.optional(),
36372
+ dispatch
36373
+ }).refine(oneAddressee.check, oneAddressee.message);
35727
36374
  const replySchema = object$1({
35728
36375
  text,
35729
- to: session.optional()
35730
- });
35731
- const sendSchema = object$1({ to: session });
36376
+ images,
36377
+ to: session.optional(),
36378
+ dispatch
36379
+ }).refine(oneAddressee.check, oneAddressee.message);
36380
+ const sendSchema = object$1({
36381
+ to: session.optional(),
36382
+ dispatch
36383
+ }).refine((body) => body.to === void 0 !== (body.dispatch === void 0), { message: "names a session to send to or asks to start one" });
35732
36384
  /**
35733
36385
  * The board's note writes, each behind `requireWriter`: pin a note, reply in
35734
36386
  * its thread, send it to a listening session, and mark it done. Each answers
35735
36387
  * the CLI's `{ ok, data }` envelope with the note it wrote, and a refusal its
35736
36388
  * `{ ok, error }`. A write offers the queue to delivery at once rather than
35737
36389
  * waiting on the watcher.
35738
- */
35739
- function notesRoutes(root, access, delivery) {
36390
+ *
36391
+ * Pin, reply, and send take `dispatch: true` in place of `to`, which starts a
36392
+ * session through `dispatch` under an id minted here and marks the thread's
36393
+ * root delivered to it, so the started session's inbox never prints it a
36394
+ * second time. A failed start takes back the message the request added, and
36395
+ * no `dispatch` refuses before anything is written.
36396
+ *
36397
+ * A note's images go up first, as multipart `files` with the `page` ref, to
36398
+ * `/api/notes/images`, which saves them to the page's `.notes/` and answers
36399
+ * their page-relative paths for pin and reply to carry. A write naming an
36400
+ * image its page does not hold is refused. `/api/note-images/...` reads one
36401
+ * back with no writer check, as the frames route reads a page's files, since
36402
+ * an `<img>` sends no `Origin`.
36403
+ */
36404
+ function notesRoutes(root, access, delivery, dispatch, imageLimit = ASSET_BODY_LIMIT) {
35740
36405
  const app = new Hono();
35741
36406
  app.use("/api/notes", requireWriter(access));
35742
36407
  app.use("/api/notes/*", requireWriter(access));
@@ -35745,35 +36410,106 @@ function notesRoutes(root, access, delivery) {
35745
36410
  delivery?.offer().catch(() => {});
35746
36411
  return file.notes.find((note) => note.id === id);
35747
36412
  };
36413
+ const dispatcher = (asked) => {
36414
+ if (asked === void 0) return void 0;
36415
+ if (!dispatch) throw new FrameboardError("dispatch-unavailable", `No session can be started, since serve was started without ${DISPATCH_ENV}.`);
36416
+ return dispatch;
36417
+ };
36418
+ /**
36419
+ * Starts a session on a thread already on disk, then hands the root to it
36420
+ * as delivered, answering the note `answer` names.
36421
+ */
36422
+ const startSession = async (run, place, rootId, added, answer) => {
36423
+ const minted = randomUUID();
36424
+ try {
36425
+ const { line } = await deliveryOf(root, place, rootId);
36426
+ await run({
36427
+ session: minted,
36428
+ id: rootId,
36429
+ line
36430
+ });
36431
+ } catch (error) {
36432
+ if (added !== null) await updateNotes(place.path, (file) => removeNote(file, added));
36433
+ throw error;
36434
+ }
36435
+ return write(place.path, (file) => setState(file, rootId, "delivered", /* @__PURE__ */ new Date(), minted), answer);
36436
+ };
36437
+ app.post("/api/notes/images", bodyLimit({
36438
+ maxSize: imageLimit,
36439
+ onError: (c) => c.json({
36440
+ ok: false,
36441
+ error: {
36442
+ code: "asset-too-large",
36443
+ message: `A note's images may carry ${imageLimit / 1024 / 1024} MiB at most. Nothing was saved.`
36444
+ }
36445
+ }, 413)
36446
+ }), async (c) => {
36447
+ const form = await c.req.parseBody({ all: true }).catch(() => ({}));
36448
+ const sent = [form.files].flat().filter((v) => v instanceof File);
36449
+ if (typeof form.page !== "string" || sent.length === 0) throw new FrameboardError("usage", "Send multipart/form-data with the page ref in \"page\" and images in \"files\".");
36450
+ const page = await resolvePageRef(root, form.page, { cwd: root });
36451
+ const bytes = await Promise.all(sent.map(async (file) => new Uint8Array(await file.arrayBuffer())));
36452
+ return c.json({
36453
+ ok: true,
36454
+ data: { images: await saveImages(page.path, bytes) }
36455
+ });
36456
+ });
36457
+ app.get("/api/note-images/:project/:page/:name", async (c) => {
36458
+ const { project, page, name } = c.req.param();
36459
+ const found = await resolvePageRef(root, `${project}/${page}`, { cwd: root }).catch(() => null);
36460
+ const file = found && await storedImage(found.path, `.notes/${name}`);
36461
+ if (!file) return c.notFound();
36462
+ return c.body(new Uint8Array(await readFile(file)), 200, {
36463
+ "Content-Type": IMAGE_CONTENT_TYPES[extname(file).slice(1)] ?? "application/octet-stream",
36464
+ "Cache-Control": "no-store"
36465
+ });
36466
+ });
35748
36467
  app.post("/api/notes", async (c) => {
35749
36468
  const body = await parseBody(c.req.raw, pinSchema);
36469
+ const run = dispatcher(body.dispatch);
35750
36470
  const frame = await resolveFrameRef(root, body.frame, { cwd: root });
36471
+ await assertStored(dirname(frame.path), body.images ?? []);
35751
36472
  if (body.element !== void 0 && body.renderedAt === void 0) throw new FrameboardError("usage", "An element note needs the renderedAt the board showed it at.");
35752
36473
  const anchor = body.element === void 0 ? null : await anchorFor(frame.path, body.element, body.renderedAt ?? "");
35753
36474
  const id = newNoteId();
35754
36475
  const author = await readAuthor(root);
35755
- const note = await write(notesPath(root, frame.project, frame.page), (file) => addRoot(file, {
36476
+ const place = {
36477
+ project: frame.project,
36478
+ page: frame.page,
36479
+ path: notesPath(root, frame.project, frame.page)
36480
+ };
36481
+ const note = await write(place.path, (file) => addRoot(file, {
35756
36482
  frame: frame.name,
35757
36483
  anchor,
35758
36484
  text: body.text,
36485
+ images: body.images,
35759
36486
  author,
35760
36487
  to: body.to ?? null
35761
36488
  }, {
35762
36489
  now: /* @__PURE__ */ new Date(),
35763
36490
  id
35764
36491
  }), id);
35765
- return c.json({
36492
+ if (!run) return c.json({
35766
36493
  ok: true,
35767
36494
  data: { note }
35768
36495
  });
36496
+ const started = await startSession(run, place, id, id, id);
36497
+ return c.json({
36498
+ ok: true,
36499
+ data: { note: started }
36500
+ });
35769
36501
  });
35770
36502
  app.post("/api/notes/:id/replies", async (c) => {
35771
36503
  const body = await parseBody(c.req.raw, replySchema);
36504
+ const run = dispatcher(body.dispatch);
35772
36505
  const found = await findNote(root, c.req.param("id"));
36506
+ await assertStored(dirname(found.path), body.images ?? []);
36507
+ const rootId = found.note.thread ?? found.note.id;
35773
36508
  const id = newNoteId();
35774
36509
  const author = await readAuthor(root);
35775
36510
  const note = await write(found.path, (file) => addReply(file, found.note.id, {
35776
36511
  text: body.text,
36512
+ images: body.images,
35777
36513
  from: "developer",
35778
36514
  author,
35779
36515
  session: null,
@@ -35782,15 +36518,28 @@ function notesRoutes(root, access, delivery) {
35782
36518
  now: /* @__PURE__ */ new Date(),
35783
36519
  id
35784
36520
  }), id);
35785
- return c.json({
36521
+ if (!run) return c.json({
35786
36522
  ok: true,
35787
36523
  data: { note }
35788
36524
  });
36525
+ const started = await startSession(run, found, rootId, id, id);
36526
+ return c.json({
36527
+ ok: true,
36528
+ data: { note: started }
36529
+ });
35789
36530
  });
35790
36531
  app.post("/api/notes/:id/send", async (c) => {
35791
36532
  const body = await parseBody(c.req.raw, sendSchema);
36533
+ const run = dispatcher(body.dispatch);
35792
36534
  const found = await findNote(root, c.req.param("id"));
35793
36535
  const rootId = found.note.thread ?? found.note.id;
36536
+ if (run) {
36537
+ const note = await startSession(run, found, rootId, null, rootId);
36538
+ return c.json({
36539
+ ok: true,
36540
+ data: { note }
36541
+ });
36542
+ }
35794
36543
  const note = await write(found.path, (file) => setState(file, rootId, "queued", /* @__PURE__ */ new Date(), body.to), rootId);
35795
36544
  return c.json({
35796
36545
  ok: true,
@@ -35873,8 +36622,8 @@ function isTheme(value) {
35873
36622
  return value === "light" || value === "dark";
35874
36623
  }
35875
36624
  // src/server/board/pages.ts
35876
- /** Notes belong to the page they were pinned on, so a copy starts without them. */
35877
- const NOT_COPIED = /* @__PURE__ */ new Set(["notes.json"]);
36625
+ /** Notes and their images belong to the page they were pinned on, so a copy starts without them. */
36626
+ const NOT_COPIED = /* @__PURE__ */ new Set(["notes.json", ".notes"]);
35878
36627
  async function addPage(root, ref, { index, ...options }) {
35879
36628
  const page = await resolvePageRef(root, ref, {
35880
36629
  ...options,
@@ -36130,71 +36879,6 @@ async function assertFree(root, name, self) {
36130
36879
  taken
36131
36880
  });
36132
36881
  }
36133
- // src/shared/starter-tokens.ts
36134
- /**
36135
- * The looks a new project can start from, each accent paired by hand with a
36136
- * dark value, so both themes hold without a derived color. The keys are the
36137
- * values `project tokens --accent` and the route take.
36138
- */
36139
- const STARTER_ACCENTS = {
36140
- blue: {
36141
- light: "#2f7bf0",
36142
- dark: "#4e92f6"
36143
- },
36144
- red: {
36145
- light: "#e5484d",
36146
- dark: "#ff6369"
36147
- },
36148
- green: {
36149
- light: "#30a46c",
36150
- dark: "#3dd68c"
36151
- },
36152
- orange: {
36153
- light: "#f76b15",
36154
- dark: "#ff801f"
36155
- },
36156
- purple: {
36157
- light: "#8e4ec6",
36158
- dark: "#9a5cd0"
36159
- }
36160
- };
36161
- /** The served faces a starter sheet may name, keyed by their face folder. */
36162
- const STARTER_FONTS = {
36163
- geist: {
36164
- family: "Geist",
36165
- stack: "Geist, sans-serif"
36166
- },
36167
- "geist-mono": {
36168
- family: "Geist Mono",
36169
- stack: "'Geist Mono', monospace"
36170
- }
36171
- };
36172
- const DEFAULT_LOOK = {
36173
- accent: "blue",
36174
- font: "geist"
36175
- };
36176
- /** A project token sheet setting the names the fixture sheets use, light then dark. */
36177
- function starterSheet({ accent, font }) {
36178
- const pair = STARTER_ACCENTS[accent];
36179
- return `:root {
36180
- --accent: ${pair.light};
36181
- --surface: #ffffff;
36182
- --text: #111111;
36183
- --muted: #6b7280;
36184
- --border: #e5e7eb;
36185
- --radius: 10px;
36186
- --font-text: ${STARTER_FONTS[font].stack};
36187
- }
36188
-
36189
- [data-theme='dark'] {
36190
- --accent: ${pair.dark};
36191
- --surface: #111111;
36192
- --text: #ededed;
36193
- --muted: #9ca3af;
36194
- --border: #2e2e2e;
36195
- }
36196
- `;
36197
- }
36198
36882
  // src/server/look/starter.ts
36199
36883
  /**
36200
36884
  * Writes a starter `tokens.css` into a project that renders with no token
@@ -36253,7 +36937,9 @@ const refs = array$1(ref).min(1).max(1e3);
36253
36937
  const coordinate = int$1();
36254
36938
  const frameAddSchema = object$1({
36255
36939
  ref,
36256
- size: _enum$1(Object.keys(FRAME_SIZES)).optional(),
36940
+ size: _enum$1(FRAME_SIZE_NAMES).optional(),
36941
+ width: int$1().min(1).optional(),
36942
+ height: int$1().min(1).optional(),
36257
36943
  x: coordinate.optional(),
36258
36944
  y: coordinate.optional()
36259
36945
  });
@@ -36380,7 +37066,11 @@ function structureRoutes(root, access, history, measure, tokens = null) {
36380
37066
  before: `${source.project}/${source.name}`,
36381
37067
  after: renamed.ref
36382
37068
  },
36383
- frames: []
37069
+ frames: [],
37070
+ renamed: {
37071
+ before: `${source.project}/${source.name}`,
37072
+ after: renamed.ref
37073
+ }
36384
37074
  }));
36385
37075
  return c.json({
36386
37076
  ok: true,
@@ -36596,8 +37286,15 @@ function structureRoutes(root, access, history, measure, tokens = null) {
36596
37286
  });
36597
37287
  app.post("/api/project/rename", async (c) => {
36598
37288
  const body = await parseBody$1(c.req.raw, renameSchema);
36599
- await refuseHeld([(await resolveProject(root, body.ref)).name]);
36600
- const project = await recorded((journal) => renameProject(root, body.ref, body.name, { journal }), onHome);
37289
+ const source = await resolveProject(root, body.ref);
37290
+ await refuseHeld([source.name]);
37291
+ const project = await recorded((journal) => renameProject(root, body.ref, body.name, { journal }), async (renamed) => ({
37292
+ ...await onHome(),
37293
+ renamed: {
37294
+ before: source.name,
37295
+ after: renamed.name
37296
+ }
37297
+ }));
36601
37298
  return c.json({
36602
37299
  ok: true,
36603
37300
  data: project
@@ -36722,7 +37419,7 @@ function boardHostGuard(port) {
36722
37419
  await next();
36723
37420
  };
36724
37421
  }
36725
- function createApp({ clientDir, root, port, actions, tickets, renderFrame, facesDir, tokens, delivery, history, selection, checks, thumbnails, measure, frameVersion, settledVersion }) {
37422
+ function createApp({ clientDir, root, port, actions, tickets, renderFrame, facesDir, tokens, delivery, dispatch, history, selection, checks, thumbnails, measure, frameVersion, settledVersion }) {
36726
37423
  const app = new Hono();
36727
37424
  const given = tokens ?? null;
36728
37425
  app.use("*", async (c, next) => {
@@ -36744,7 +37441,7 @@ function createApp({ clientDir, root, port, actions, tickets, renderFrame, faces
36744
37441
  app.route("/", apiRoutes(root, actions, frames.look, history));
36745
37442
  app.route("/", structureRoutes(root, actions.access, history, measure, given));
36746
37443
  app.route("/", historyRoutes(actions.access, history));
36747
- app.route("/", notesRoutes(root, actions.access, delivery));
37444
+ app.route("/", notesRoutes(root, actions.access, delivery, dispatch));
36748
37445
  app.route("/", assetsRoutes(root, actions.access));
36749
37446
  app.route("/", elementsRoutes(root, actions.access, selection, given));
36750
37447
  app.route("/", findRoutes(root));
@@ -38140,10 +38837,45 @@ function readContentSize() {
38140
38837
  for (let parent = element.parentElement; parent && parent !== document.body; parent = parent.parentElement) if (crops(parent)) return true;
38141
38838
  return false;
38142
38839
  };
38840
+ const hangOf = (lineHeight, height) => lineHeight < height ? (height - lineHeight) / 2 : 0;
38841
+ const textBottom = (element) => {
38842
+ let bottom = -Infinity;
38843
+ if (crops(element)) return bottom;
38844
+ const lineHeight = parseFloat(getComputedStyle(element).lineHeight);
38845
+ for (const child of element.childNodes) {
38846
+ if (child.nodeType !== Node.TEXT_NODE) continue;
38847
+ const range = document.createRange();
38848
+ range.selectNodeContents(child);
38849
+ for (const rect of range.getClientRects()) {
38850
+ if (rect.width === 0 && rect.height === 0) continue;
38851
+ bottom = Math.max(bottom, rect.bottom - hangOf(lineHeight, rect.height));
38852
+ }
38853
+ }
38854
+ return bottom;
38855
+ };
38856
+ const replaced = [
38857
+ "img",
38858
+ "video",
38859
+ "canvas",
38860
+ "iframe",
38861
+ "object",
38862
+ "embed",
38863
+ "audio"
38864
+ ];
38865
+ const ownBottom = (element) => {
38866
+ const rect = element.getBoundingClientRect();
38867
+ if (element.namespaceURI !== "http://www.w3.org/1999/xhtml") return rect.bottom;
38868
+ if (replaced.includes(element.localName)) return rect.bottom;
38869
+ const style = getComputedStyle(element);
38870
+ if (style.display !== "inline") return rect.bottom;
38871
+ if (parseFloat(style.paddingBottom) + parseFloat(style.borderBottomWidth) > 0) return rect.bottom;
38872
+ const above = parseFloat(style.paddingTop) + parseFloat(style.borderTopWidth);
38873
+ return rect.bottom - hangOf(parseFloat(style.lineHeight), rect.height - above);
38874
+ };
38143
38875
  let bottom = root.getBoundingClientRect().bottom;
38144
38876
  for (const element of document.querySelectorAll("body *")) {
38145
38877
  if (isCropped(element)) continue;
38146
- bottom = Math.max(bottom, element.getBoundingClientRect().bottom);
38878
+ bottom = Math.max(bottom, ownBottom(element), textBottom(element));
38147
38879
  }
38148
38880
  return {
38149
38881
  height: Math.max(1, Math.ceil(bottom + window.scrollY)),
@@ -38268,6 +39000,48 @@ function readLayout() {
38268
39000
  for (let parent = element.parentElement; parent && parent !== document.body; parent = parent.parentElement) if (crops(parent)) return true;
38269
39001
  return false;
38270
39002
  };
39003
+ const hangOf = (lineHeight, height) => lineHeight < height ? (height - lineHeight) / 2 : 0;
39004
+ const textReach = (element) => {
39005
+ let bottom = -Infinity;
39006
+ let right = -Infinity;
39007
+ if (crops(element)) return {
39008
+ bottom,
39009
+ right
39010
+ };
39011
+ const lineHeight = parseFloat(getComputedStyle(element).lineHeight);
39012
+ for (const child of element.childNodes) {
39013
+ if (child.nodeType !== Node.TEXT_NODE) continue;
39014
+ const range = document.createRange();
39015
+ range.selectNodeContents(child);
39016
+ for (const rect of range.getClientRects()) {
39017
+ if (rect.width === 0 && rect.height === 0) continue;
39018
+ bottom = Math.max(bottom, rect.bottom - hangOf(lineHeight, rect.height));
39019
+ right = Math.max(right, rect.right);
39020
+ }
39021
+ }
39022
+ return {
39023
+ bottom,
39024
+ right
39025
+ };
39026
+ };
39027
+ const replaced = [
39028
+ "img",
39029
+ "video",
39030
+ "canvas",
39031
+ "iframe",
39032
+ "object",
39033
+ "embed",
39034
+ "audio"
39035
+ ];
39036
+ const ownBottom = (element, rect) => {
39037
+ if (element.namespaceURI !== "http://www.w3.org/1999/xhtml") return rect.bottom;
39038
+ if (replaced.includes(element.localName)) return rect.bottom;
39039
+ const style = getComputedStyle(element);
39040
+ if (style.display !== "inline") return rect.bottom;
39041
+ if (parseFloat(style.paddingBottom) + parseFloat(style.borderBottomWidth) > 0) return rect.bottom;
39042
+ const above = parseFloat(style.paddingTop) + parseFloat(style.borderTopWidth);
39043
+ return rect.bottom - hangOf(parseFloat(style.lineHeight), rect.height - above);
39044
+ };
38271
39045
  const rootRect = root.getBoundingClientRect();
38272
39046
  let index = 0;
38273
39047
  for (const node of document.querySelectorAll("*")) {
@@ -38277,13 +39051,14 @@ function readLayout() {
38277
39051
  if (!(node instanceof HTMLElement || node instanceof SVGElement)) continue;
38278
39052
  if (node === root || node === document.body || !document.body.contains(node)) continue;
38279
39053
  const rect = node.getBoundingClientRect();
38280
- if (rect.width === 0 && rect.height === 0) continue;
39054
+ const text = textReach(node);
39055
+ if (rect.width === 0 && rect.height === 0 && text.right === -Infinity) continue;
38281
39056
  const tag = node.tagName.toLowerCase();
38282
39057
  boxes.push({
38283
39058
  index: own,
38284
39059
  tag,
38285
- bottom: Math.ceil(rect.bottom + window.scrollY),
38286
- right: Math.ceil(rect.right + window.scrollX),
39060
+ bottom: Math.ceil(Math.max(ownBottom(node, rect), text.bottom) + window.scrollY),
39061
+ right: Math.ceil(Math.max(rect.right, text.right) + window.scrollX),
38287
39062
  height: Math.round(rect.height),
38288
39063
  cropped: isCropped(node)
38289
39064
  });
@@ -38793,6 +39568,15 @@ object$1({
38793
39568
  index: int$1().min(0),
38794
39569
  hash
38795
39570
  });
39571
+ object$1({
39572
+ ref: string$1(),
39573
+ hash
39574
+ });
39575
+ object$1({
39576
+ ref: string$1(),
39577
+ index: int$1().min(0),
39578
+ hash
39579
+ });
38796
39580
  // src/shared/records/elements.ts
38797
39581
  /**
38798
39582
  * How an element lays out what it holds, read from the frame's static
@@ -38816,7 +39600,9 @@ const treeElementSchema = object$1({
38816
39600
  /** True when the element holds text and nothing else. */
38817
39601
  textOnly: boolean$1(),
38818
39602
  /** Its layout, which a culled frame's Layers rows draw from without an iframe. */
38819
- layout: layoutSchema
39603
+ layout: layoutSchema,
39604
+ /** True when it holds nothing and its corners round by half or more, so it draws as an ellipse. */
39605
+ round: boolean$1()
38820
39606
  });
38821
39607
  /** What `GET /api/frames/elements` answers: a frame's elements under `body` in index order, and the hash they were read from. */
38822
39608
  const elementTreeSchema = object$1({
@@ -38970,7 +39756,7 @@ function contentFormat() {
38970
39756
  `A project is any folder in the board whose name does not open with a dot. Its ${PROJECT_FILE} lists page names in display order, and pages it does not list follow by name.`,
38971
39757
  `A page is any folder in a project except ${ASSETS_FOLDER}/ and dot-named ones. Its ${LAYOUT_FILE} holds each frame's box, stacking order, and flags.`,
38972
39758
  `A frame is any *${FRAME_EXTENSION} file directly in a page, named by its stem.`,
38973
- `A page's notes sit in its ${NOTES_FILE$1}, never in a frame. A note pins to a frame or to one element by index and the frame file's hash, and reads at the frame once the file changes. Read them with notes, answer with notes reply, and close them with notes done.`,
39759
+ `A page's notes sit in its ${NOTES_FILE$1}, never in a frame. A note pins to a frame or to one element by index and the frame file's hash, and reads at the frame once the file changes. Read them with notes, answer with notes reply, and close them with notes done. A note's images sit in its page's ${NOTES_FOLDER}/ folder, and its images field lists them relative to the page.`,
38974
39760
  `serve reuses a board the walk finds, and otherwise creates ${DEFAULT_BOARD_FOLDER}/ in the working folder with project ${START_PROJECT} and empty page ${START_PAGE}, and records its address in ${RUN_FOLDER}/${ADDRESS_FILE}.`,
38975
39761
  `Dot-named folders, *${LOCK_SUFFIX} files, and *${TEMP_SUFFIX} files belong to Frameboard and are never content.`
38976
39762
  ],
@@ -38980,15 +39766,15 @@ function contentFormat() {
38980
39766
  reservedPageNames: [...RESERVED_PAGE_NAMES],
38981
39767
  collision: "Two names collide when they match case-insensitively. A verb choosing a name itself takes the first free -2, -3, and onward."
38982
39768
  },
38983
- frameSizes: FRAME_SIZES,
39769
+ frameSizes: Object.fromEntries(FRAME_SIZE_NAMES.map((name) => [name, frameSizeOf(name)])),
38984
39770
  defaultFrameSize: DEFAULT_FRAME_SIZE,
38985
39771
  layout: [
38986
39772
  "x and y are integers, width and height integers of at least 1, and order an integer of at least 0, where a higher order draws on top.",
38987
39773
  "hidden, locked, hugWidth, and hugHeight read as false when absent, and an axis whose hug flag is false holds the size its entry states.",
38988
- `An axis that hugs takes its size from the frame's content: a running serve measures it after each write to the frame file, its width at most ${FRAME_SIZES.desktop.width} px, and writes width and height alone, never a flag. Content sized off the viewport keeps the box it has.`,
39774
+ `An axis that hugs takes its size from the frame's content: a running serve measures it after each write to the frame file and when frame add places a file already written, its width at most ${FRAME_SIZES.desktop.width} px, and writes width and height alone, never a flag. Content sized off the viewport keeps the box it has.`,
38989
39775
  "frame add with no size hugs both axes, --size or --width fixes the width and hugs the height, and --height fixes the height alone, its box standing in until serve measures. frame resize and a hand resize fix each axis they set, and frame fit sets the height and turns hugHeight on.",
38990
39776
  "Frames sort by order, then name, and a write that changes order renumbers the page from 0.",
38991
- `A frame file with no entry is unplaced: it reads at desktop size, y 0, 80 px past the right edge of every frame placed before it in name order, and frame add persists that box.`,
39777
+ `A frame file with no entry is unplaced: it reads at desktop size, y 0, 80 px past the right edge of every frame placed before it in name order. frame add places it 80 px past the placed frames alone, so the first unplaced file keeps that box and any later one moves left.`,
38992
39778
  "An entry with no frame file beside it is ignored on read and kept on write.",
38993
39779
  `A ${LAYOUT_FILE} that does not parse is reported by list and refused by every verb writing that page, never overwritten.`,
38994
39780
  `Moving or resizing a frame writes ${LAYOUT_FILE} alone and never the frame file.`
@@ -39236,13 +40022,13 @@ function registerFrame(program, context) {
39236
40022
  const { io } = context;
39237
40023
  const frame = program.command("frame").description("Manage frames");
39238
40024
  const verb = (name, description) => addVerb(frame, name, description, { project: true }).argument("<frame-ref>", FRAME_REF);
39239
- const withSize = (command) => command.addOption(new Option("--size <preset>", "a size preset").choices(Object.keys(FRAME_SIZES))).option("--width <n>", "width in px", parseInteger(1)).option("--height <n>", "height in px", parseInteger(1));
40025
+ const withSize = (command) => command.addOption(new Option("--size <preset>", "a size preset or device").choices(FRAME_SIZE_NAMES)).option("--width <n>", "width in px", parseInteger(1)).option("--height <n>", "height in px", parseInteger(1));
39240
40026
  const withPosition = (command) => command.option("--x <n>", "board x in px", ANY_INTEGER).option("--y <n>", "board y in px", ANY_INTEGER);
39241
40027
  const done = (record, what) => ({
39242
40028
  data: record,
39243
40029
  human: `${what} ${record.ref}`
39244
40030
  });
39245
- act(withPosition(withSize(verb("add", "Place a frame past every frame, writing a skeleton file when none exists. Each axis no size names hugs its content, so a preset or --width fixes the width and the height hugs."))), context, async ([ref = ""], options) => done(await addFrame(await boardOf(options, io), ref, {
40031
+ act(withPosition(withSize(verb("add", "Place a frame past every frame, as written when its file exists and with a skeleton file only when none does, so write the file first to show no empty box. Each axis no size names hugs its content, so a preset or --width fixes the width and the height hugs."))), context, async ([ref = ""], options) => done(await addFrame(await boardOf(options, io), ref, {
39246
40032
  ...options,
39247
40033
  cwd: io.cwd
39248
40034
  }), "Added"));
@@ -43148,11 +43934,13 @@ function registerNotes(program, context) {
43148
43934
  const file = await readNotes(place.path);
43149
43935
  const done = new Set(file.notes.filter((n) => n.state === "done").map((n) => n.id));
43150
43936
  const kept = byThread(file.notes).filter((note) => (options.all || !done.has(note.thread ?? note.id)) && (!frame || note.frame === frame.name));
43151
- const elements = await resolveAnchors(join(root, place.project, place.page), kept);
43937
+ const pageDir = join(root, place.project, place.page);
43938
+ const elements = await resolveAnchors(pageDir, kept);
43152
43939
  listed.push(...kept.map((note) => ({
43153
43940
  ...note,
43154
43941
  ref: `${place.project}/${place.page}/${note.frame}`,
43155
- element: elements[note.id] ?? null
43942
+ element: elements[note.id] ?? null,
43943
+ ...note.images?.length ? { imagePaths: note.images.map((image) => join(pageDir, image)) } : {}
43156
43944
  })));
43157
43945
  }
43158
43946
  return {
@@ -43220,7 +44008,7 @@ function byThread(notes) {
43220
44008
  function describe$1(notes) {
43221
44009
  if (notes.length === 0) return "No open notes";
43222
44010
  return notes.map((note) => {
43223
- const text = note.text.replace(/\s+/g, " ").trim();
44011
+ const text = `${note.text.replace(/\s+/g, " ").trim()}${(note.imagePaths ?? []).map((path) => `\n image: ${path}`).join("")}`;
43224
44012
  if (note.thread) return ` ${note.from === "agent" ? "agent" : note.author ?? "developer"}: ${text}`;
43225
44013
  const where = note.element === null ? note.ref : `${note.ref} element ${note.element}`;
43226
44014
  return `${note.id} Note ${note.number} on ${where} ${note.state}${note.to ? ` to ${note.to}` : ""}\n ${note.author ?? "developer"}: ${text}`;
@@ -43727,7 +44515,7 @@ function versionKey(ref, hash) {
43727
44515
  /** The files and folders a step wrote, being every rewrite, creation, removal, and move. */
43728
44516
  function writtenPaths(step) {
43729
44517
  return step.changes.flatMap((change) => {
43730
- if (change.kind === "element" || change.kind === "inserted" || change.kind === "path") return [change.path];
44518
+ if (change.kind === "element" || change.kind === "inserted" || change.kind === "relocated" || change.kind === "path") return [change.path];
43731
44519
  if (change.kind === "moved") return [change.from, change.to];
43732
44520
  return [];
43733
44521
  });
@@ -43923,7 +44711,8 @@ async function reads(change, side) {
43923
44711
  }
43924
44712
  case "path": return change.present === side ? await exists(change.path) && await hashPath(change.path) === change.hash : !await exists(change.path) && await exists(change.slot);
43925
44713
  case "element": return await exists(change.path) && holdsSpan(await readFile(change.path, "utf8"), change.span, side);
43926
- case "inserted": return await exists(change.path) && holdsInserted(await readFile(change.path, "utf8"), change.span, side);
44714
+ case "inserted": return await exists(change.path) && holdsInserted(await readFile(change.path, "utf8"), change.span, side === change.present ? "after" : "before");
44715
+ case "relocated": return await exists(change.path) && relocateMoved(await readFile(change.path, "utf8"), change.span, OTHER[side]) !== void 0;
43927
44716
  }
43928
44717
  }
43929
44718
  /**
@@ -43992,7 +44781,16 @@ async function restore(change, side) {
43992
44781
  };
43993
44782
  });
43994
44783
  case "inserted": return rewriteFrame(change, (source) => {
43995
- const written = side === "before" ? removeInserted(source, change.span) : restoreInserted(source, change.span);
44784
+ const written = side === change.present ? restoreInserted(source, change.span) : removeInserted(source, change.span);
44785
+ return written && {
44786
+ html: written.html,
44787
+ keep: () => {
44788
+ change.span = written.span;
44789
+ }
44790
+ };
44791
+ });
44792
+ case "relocated": return rewriteFrame(change, (source) => {
44793
+ const written = relocateMoved(source, change.span, side);
43996
44794
  return written && {
43997
44795
  html: written.html,
43998
44796
  keep: () => {
@@ -44089,6 +44887,26 @@ var StepJournal = class {
44089
44887
  kind: "inserted",
44090
44888
  path,
44091
44889
  ref,
44890
+ span,
44891
+ present: "after"
44892
+ });
44893
+ }
44894
+ /** The element a hand delete took out of a frame file, which this journal does not write. */
44895
+ deletedElement(path, ref, span) {
44896
+ this.changes.push({
44897
+ kind: "inserted",
44898
+ path,
44899
+ ref,
44900
+ span,
44901
+ present: "before"
44902
+ });
44903
+ }
44904
+ /** The element a hand move took to another gap of a frame file, which this journal does not write. */
44905
+ relocated(path, ref, span) {
44906
+ this.changes.push({
44907
+ kind: "relocated",
44908
+ path,
44909
+ ref,
44092
44910
  span
44093
44911
  });
44094
44912
  }
@@ -44192,7 +45010,7 @@ var History = class {
44192
45010
  if (this.#undo.length > 100) this.#undo.shift();
44193
45011
  this.#redo = [];
44194
45012
  this.onChange(this.counts());
44195
- this.onWrite(step);
45013
+ this.onWrite(step, "after");
44196
45014
  }
44197
45015
  /**
44198
45016
  * The refs the top undo or redo step would write, without popping it, so a
@@ -44253,7 +45071,7 @@ var History = class {
44253
45071
  }
44254
45072
  onto.push(step);
44255
45073
  this.onChange(this.counts());
44256
- this.onWrite(step);
45074
+ this.onWrite(step, to);
44257
45075
  const answer = {
44258
45076
  page: step.page?.[to] ?? null,
44259
45077
  frames: step.frames
@@ -47561,6 +48379,24 @@ function reloadRefs(root, paths, board, tokens = null) {
47561
48379
  return named;
47562
48380
  }
47563
48381
  /**
48382
+ * `refs` less each frame that only moved with a folder the board renamed,
48383
+ * being one under a moved folder whose file carries the stamp `last`, the
48384
+ * board sent before the move, showed at its old path. It renders what the
48385
+ * tab already shows, so a reload would restart it for nothing, while a file
48386
+ * written before or after the move that `last` never showed still reloads.
48387
+ */
48388
+ function unmovedRefs(refs, board, moved, last) {
48389
+ if (moved.length === 0 || !last) return refs;
48390
+ const shown = new Map(last.projects.flatMap((project) => project.pages.flatMap((page) => page.frames.map((frame) => [frame.path, frame.modifiedAt]))));
48391
+ const onlyMoved = /* @__PURE__ */ new Set();
48392
+ for (const project of board.projects) for (const page of project.pages) for (const frame of page.frames) {
48393
+ const folder = moved.find(({ path }) => frame.path.startsWith(`${path}${sep}`));
48394
+ const before = folder && `${folder.from}${frame.path.slice(folder.path.length)}`;
48395
+ if (before && shown.get(before) === frame.modifiedAt) onlyMoved.add(frame.ref);
48396
+ }
48397
+ return refs.filter((ref) => !onlyMoved.has(ref));
48398
+ }
48399
+ /**
47564
48400
  * The frame a page-folder file belongs to: `hero.html` itself, or a temp file
47565
48401
  * an editor or atomic writer saves it through, such as `hero.html.swap`.
47566
48402
  */
@@ -47569,6 +48405,19 @@ function frameNameOf(name) {
47569
48405
  const temp = name.lastIndexOf(`${FRAME_EXTENSION}.`);
47570
48406
  return temp > 0 ? name.slice(0, temp) : null;
47571
48407
  }
48408
+ /**
48409
+ * The hugging frames `next` holds placed that `previous` held unplaced or
48410
+ * not at all, on a page whose `layout.json` is among `paths`, as one an
48411
+ * agent wrote and then placed. Placing writes `layout.json` alone, which
48412
+ * reloads nothing, so these are measured without a reload. A frame that only
48413
+ * moved was placed in both, and one a folder rename carried has a new ref
48414
+ * but a batch naming the folder alone, so both are left out.
48415
+ */
48416
+ function placedRefs(previous, next, paths) {
48417
+ const written = new Set(paths);
48418
+ const before = new Set(previous.projects.flatMap((project) => project.pages.flatMap((page) => page.frames.filter((frame) => frame.placed).map((frame) => frame.ref))));
48419
+ return next.projects.flatMap((project) => project.pages.filter((page) => written.has(join(page.path, LAYOUT_FILE))).flatMap((page) => page.frames.filter((frame) => frame.placed && (frame.hugWidth || frame.hugHeight) && !before.has(frame.ref)).map((frame) => frame.ref)));
48420
+ }
47572
48421
  // src/server/live/findings.ts
47573
48422
  /**
47574
48423
  * The board's check findings, held between batches so a hello needs no
@@ -47659,7 +48508,7 @@ function checkOne(root, frame, context) {
47659
48508
  * it never counts as a tab, and taken only from a socket upgraded with the
47660
48509
  * address token as a bearer, since a browser page must never register one.
47661
48510
  */
47662
- function createHub({ tabs, port, access, snapshot, findings, notes, delivery, history, claims, changes, closeTab }) {
48511
+ function createHub({ tabs, port, access, snapshot, findings, notes, delivery, history, claims, changes, closeTab, dispatch = false }) {
47663
48512
  const server = new import_websocket_server.default({ noServer: true });
47664
48513
  const boards = /* @__PURE__ */ new Map();
47665
48514
  const inboxes = /* @__PURE__ */ new Map();
@@ -47701,7 +48550,8 @@ function createHub({ tabs, port, access, snapshot, findings, notes, delivery, hi
47701
48550
  });
47702
48551
  send(socket, {
47703
48552
  type: "access",
47704
- write: writer
48553
+ write: writer,
48554
+ dispatch: writer && dispatch
47705
48555
  });
47706
48556
  if (history) send(socket, {
47707
48557
  type: "history",
@@ -48089,6 +48939,11 @@ const HOSTNAME = "127.0.0.1";
48089
48939
  */
48090
48940
  const OWN_GRACE_MS = 1e3;
48091
48941
  /**
48942
+ * How long a folder the board's own rename moved keeps its unchanged frames
48943
+ * from reloading, well past the watcher reporting the move under load.
48944
+ */
48945
+ const MOVED_MS = 1e4;
48946
+ /**
48092
48947
  * The board tabs holding a live connection to this server, counting apart the
48093
48948
  * ones that can write. The route a tab connects through calls `open` and
48094
48949
  * `close`, and `serve` waits on a writer before deciding to open a tab of its
@@ -48141,7 +48996,7 @@ async function startServer({ strictPort = true, port, ...options }) {
48141
48996
  });
48142
48997
  }
48143
48998
  }
48144
- async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch }) {
48999
+ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch, dispatch }) {
48145
49000
  const tabs = new BoardTabs();
48146
49001
  const tickets = createTickets();
48147
49002
  let bound = 0;
@@ -48170,6 +49025,10 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
48170
49025
  }),
48171
49026
  now: () => /* @__PURE__ */ new Date()
48172
49027
  });
49028
+ const dispatcher = dispatch ? createDispatcher({
49029
+ ...dispatch,
49030
+ root
49031
+ }) : void 0;
48173
49032
  await emptyTrash(root);
48174
49033
  const tracker = createChangeTracker(root);
48175
49034
  const settling = /* @__PURE__ */ new Set();
@@ -48186,23 +49045,52 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
48186
49045
  }, OWN_GRACE_MS);
48187
49046
  settling.add(timer);
48188
49047
  };
49048
+ const shown = { board: null };
49049
+ const scanned = { board: null };
49050
+ let moved = [];
49051
+ const recentlyMoved = () => {
49052
+ moved = moved.filter(({ at }) => Date.now() - at < MOVED_MS);
49053
+ return moved;
49054
+ };
48189
49055
  const history = new History(root, (counts) => hub.broadcast({
48190
49056
  type: "history",
48191
49057
  ...counts
48192
- }), (step) => void inTurn(() => tracker.own(step)));
49058
+ }), (step, side) => {
49059
+ if (step.renamed) {
49060
+ for (const change of step.changes) {
49061
+ if (change.kind !== "moved") continue;
49062
+ moved = [...recentlyMoved(), {
49063
+ from: side === "after" ? change.from : change.to,
49064
+ path: side === "after" ? change.to : change.from,
49065
+ at: Date.now()
49066
+ }];
49067
+ }
49068
+ const from = side === "after" ? "before" : "after";
49069
+ hub.broadcast({
49070
+ type: "renamed",
49071
+ before: step.renamed[from],
49072
+ after: step.renamed[side]
49073
+ });
49074
+ }
49075
+ inTurn(() => tracker.own(step));
49076
+ });
48193
49077
  const selection = createSelectionHolder(() => tabs.writers);
48194
49078
  const hub = createHub({
48195
49079
  tabs,
48196
49080
  port: boundPort,
48197
49081
  access,
48198
- snapshot: () => inTurn(() => scanBoard(root)),
49082
+ snapshot: () => inTurn(async () => {
49083
+ shown.board = await scanBoard(root);
49084
+ return shown.board;
49085
+ }),
48199
49086
  findings: () => inTurn(async () => findings.all()),
48200
49087
  notes: () => inTurn(() => boardView(root)),
48201
49088
  delivery,
48202
49089
  history: () => history.counts(),
48203
49090
  claims: () => inTurn(() => claims.read()),
48204
49091
  changes: () => inTurn(async () => tracker.log()),
48205
- closeTab: selection.closeTab
49092
+ closeTab: selection.closeTab,
49093
+ dispatch: dispatcher !== void 0
48206
49094
  });
48207
49095
  const claims = createClaimsPush(root, {
48208
49096
  broadcast: (list) => hub.broadcast({
@@ -48282,6 +49170,7 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
48282
49170
  port: boundPort,
48283
49171
  tickets,
48284
49172
  delivery,
49173
+ dispatch: dispatcher,
48285
49174
  history,
48286
49175
  selection,
48287
49176
  renderFrame,
@@ -48332,6 +49221,7 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
48332
49221
  let board = await scanBoard(root);
48333
49222
  const stale = await writtenSinceLayout(board).catch(() => []);
48334
49223
  if (await hug.now(board, stale).catch(() => false)) board = await scanBoard(root);
49224
+ scanned.board = board;
48335
49225
  await tracker.prime(board);
48336
49226
  findings.update(board, "all");
48337
49227
  rendered.queue(board, []);
@@ -48352,7 +49242,10 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
48352
49242
  claims,
48353
49243
  thumbnails,
48354
49244
  hug,
48355
- settleLater
49245
+ settleLater,
49246
+ moved: recentlyMoved,
49247
+ shown,
49248
+ scanned
48356
49249
  }));
48357
49250
  });
48358
49251
  return {
@@ -48390,13 +49283,20 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
48390
49283
  * notes or frames it touched, whose queue it offers to delivery. The frames
48391
49284
  * an agent changed wait out the grace before the board hears of them.
48392
49285
  */
48393
- async function pushBatch(root, tokens, paths, { hub, findings, rendered, delivery, tracker, claims, thumbnails, hug, settleLater }) {
49286
+ async function pushBatch(root, tokens, paths, { hub, findings, rendered, delivery, tracker, claims, thumbnails, hug, settleLater, moved, shown, scanned }) {
48394
49287
  let board;
48395
49288
  let own;
49289
+ let placed;
48396
49290
  try {
48397
49291
  board = await scanBoard(root);
49292
+ const previous = scanned.board;
49293
+ scanned.board = board;
48398
49294
  own = ownFileRefs(board, paths);
48399
- if (await hug.now(board, own).catch(() => false)) board = await scanBoard(root);
49295
+ placed = previous ? placedRefs(previous, board, paths).filter((ref) => !own.includes(ref)) : [];
49296
+ if (await hug.now(board, [...own, ...placed]).catch(() => false)) {
49297
+ board = await scanBoard(root);
49298
+ scanned.board = board;
49299
+ }
48400
49300
  } catch {
48401
49301
  return;
48402
49302
  }
@@ -48404,12 +49304,15 @@ async function pushBatch(root, tokens, paths, { hub, findings, rendered, deliver
48404
49304
  type: "board",
48405
49305
  data: board
48406
49306
  });
49307
+ const last = shown.board;
49308
+ shown.board = board;
48407
49309
  const refs = reloadRefs(root, paths, board, tokens);
48408
- hug.later(board, refs.filter((ref) => !own.includes(ref)));
49310
+ hug.later(board, refs.filter((ref) => !own.includes(ref) && !placed.includes(ref)));
48409
49311
  if (refs.length > 0) {
48410
- hub.broadcast({
49312
+ const reloads = unmovedRefs(refs, board, moved(), last);
49313
+ if (reloads.length > 0) hub.broadcast({
48411
49314
  type: "reload",
48412
- refs
49315
+ refs: reloads
48413
49316
  });
48414
49317
  thumbnails.invalidate(refs);
48415
49318
  const stale = Object.fromEntries(refs.map((ref) => [ref, null]));
@@ -48478,7 +49381,7 @@ const DEFAULT_PORT = 4173;
48478
49381
  const RECONNECT_WAIT_MS = 1e3;
48479
49382
  function registerServe(program, context) {
48480
49383
  const { io } = context;
48481
- act(addVerb(program, "serve", "Serve the board in a local browser").option("-p, --port <port>", "port to listen on, falling back to a free one when the default is taken", parsePort, DEFAULT_PORT).option("--no-open", "leave the browser alone").option("--tokens <path>", "a token sheet another tool manages, standing in for the board's tokens.css"), context, async (_args, options, self) => {
49384
+ act(addVerb(program, "serve", `Serve the board in a local browser. A note sent to a new session runs the shell command in ${DISPATCH_ENV}, read once at start, with the note in FRAMEBOARD_NOTE, FRAMEBOARD_NOTE_ID, FRAMEBOARD_SESSION, and FRAMEBOARD_ROOT`).option("-p, --port <port>", "port to listen on, falling back to a free one when the default is taken", parsePort, DEFAULT_PORT).option("--no-open", "leave the browser alone").option("--tokens <path>", "a token sheet another tool manages, standing in for the board's tokens.css"), context, async (_args, options, self) => {
48482
49385
  const tokens = options.tokens === void 0 ? void 0 : resolve(io.cwd, options.tokens);
48483
49386
  if (tokens !== void 0 && !isFile(tokens)) throw new FrameboardError("tokens-not-found", `No token sheet at ${tokens}.`, { tokens });
48484
49387
  const existing = await resolveBoard({
@@ -48514,7 +49417,8 @@ function registerServe(program, context) {
48514
49417
  tokens,
48515
49418
  port: options.port,
48516
49419
  strictPort: self.getOptionValueSource("port") !== "default",
48517
- openUrl: io.openUrl
49420
+ openUrl: io.openUrl,
49421
+ dispatch: dispatchCommand(io.cwd)
48518
49422
  });
48519
49423
  const address = newAddress({
48520
49424
  root,
@@ -48546,6 +49450,19 @@ function registerServe(program, context) {
48546
49450
  };
48547
49451
  });
48548
49452
  }
49453
+ /**
49454
+ * The developer's dispatch command, read from this process's environment
49455
+ * alone, never from a file a repository carries, so a cloned board cannot
49456
+ * make Send run anything.
49457
+ */
49458
+ function dispatchCommand(cwd) {
49459
+ const command = process.env[DISPATCH_ENV]?.trim();
49460
+ return command ? {
49461
+ command,
49462
+ cwd,
49463
+ env: process.env
49464
+ } : void 0;
49465
+ }
48549
49466
  /** True for a file, and false for a folder or a path that does not exist. */
48550
49467
  function isFile(path) {
48551
49468
  return statSync(path, { throwIfNoEntry: false })?.isFile() ?? false;