frameboard 0.22.0 → 0.24.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
@@ -3,7 +3,7 @@ import { createRequire } from "node:module";
3
3
  import childProcess, { execFile, spawn } from "node:child_process";
4
4
  import { EventEmitter, once } from "node:events";
5
5
  import * as sp from "node:path";
6
- import path, { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
+ import path, { basename, delimiter, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
7
  import fs, { copyFileSync, createReadStream, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
8
8
  import process$1, { versions } from "node:process";
9
9
  import { isDeepStrictEqual, promisify, stripVTControlCharacters } from "node:util";
@@ -14,7 +14,7 @@ import { fileURLToPath } from "node:url";
14
14
  import { STATUS_CODES, ServerResponse, createServer } from "node:http";
15
15
  import { Http2ServerRequest, constants as constants$1 } from "node:http2";
16
16
  import { Readable } from "node:stream";
17
- import { homedir, type } from "node:os";
17
+ import { homedir, release, type } from "node:os";
18
18
  // \0rolldown/runtime.js
19
19
  var __create = Object.create;
20
20
  var __defProp = Object.defineProperty;
@@ -3048,7 +3048,8 @@ const EXIT_CODES = {
3048
3048
  "dispatch-unavailable": 3,
3049
3049
  "dispatch-failed": 13,
3050
3050
  "section-not-found": 3,
3051
- "reanchors-descendant": 7
3051
+ "reanchors-descendant": 7,
3052
+ "clipboard-unsupported": 3
3052
3053
  };
3053
3054
  var FrameboardError = class extends Error {
3054
3055
  code;
@@ -3151,7 +3152,7 @@ async function withLocks(paths, run, options = {}) {
3151
3152
  }
3152
3153
  return await run();
3153
3154
  } finally {
3154
- await Promise.all(held.map(({ lock, nonce }) => release$1(lock, nonce)));
3155
+ await Promise.all(held.map(({ lock, nonce }) => release$2(lock, nonce)));
3155
3156
  }
3156
3157
  }
3157
3158
  /** Takes the lock and returns the nonce written into it, which release checks. */
@@ -3218,7 +3219,7 @@ async function breakLock(lock, judged) {
3218
3219
  }
3219
3220
  }
3220
3221
  /** Removes the lock only while it still holds this writer's nonce. */
3221
- async function release$1(lock, nonce) {
3222
+ async function release$2(lock, nonce) {
3222
3223
  try {
3223
3224
  if ((await readFile(lock, "utf8")).includes(`"nonce":"${nonce}"`)) await rm(lock, { force: true });
3224
3225
  } catch (error) {
@@ -9109,6 +9110,20 @@ const DEVICE_SIZES = [
9109
9110
  group: "slide",
9110
9111
  width: 1024,
9111
9112
  height: 768
9113
+ },
9114
+ {
9115
+ name: "og-card",
9116
+ label: "Open Graph",
9117
+ group: "social",
9118
+ width: 1200,
9119
+ height: 630
9120
+ },
9121
+ {
9122
+ name: "linkedin-post",
9123
+ label: "LinkedIn post",
9124
+ group: "social",
9125
+ width: 1200,
9126
+ height: 627
9112
9127
  }
9113
9128
  ];
9114
9129
  /** Every size name, the three presets first, then the devices. */
@@ -9482,7 +9497,7 @@ async function isDirectory(path) {
9482
9497
  }
9483
9498
  }
9484
9499
  // package.json
9485
- var version$1 = "0.22.0";
9500
+ var version$1 = "0.24.0";
9486
9501
  var dependencies = { "playwright-core": "1.64.1" };
9487
9502
  // src/shared/version.ts
9488
9503
  const version = version$1;
@@ -13962,7 +13977,7 @@ async function claim(root, fields, now) {
13962
13977
  * Drops a session's claim on one frame, or every claim it holds when no
13963
13978
  * frame is named, returning what it dropped.
13964
13979
  */
13965
- async function release(root, session, frame, now) {
13980
+ async function release$1(root, session, frame, now) {
13966
13981
  const dropped = [];
13967
13982
  await ensureRunFolder(root);
13968
13983
  await updateRecord(claimsPath(root), claimsSpec, (file) => {
@@ -28095,7 +28110,7 @@ function readTokenTable(root, paths) {
28095
28110
  read.push({
28096
28111
  label,
28097
28112
  kind,
28098
- tokens: readSheet(bytes.toString("utf8"))
28113
+ tokens: readSheet$1(bytes.toString("utf8"))
28099
28114
  });
28100
28115
  sheets.push({
28101
28116
  path: label,
@@ -28134,7 +28149,7 @@ function readTokenTable(root, paths) {
28134
28149
  }))
28135
28150
  };
28136
28151
  }
28137
- function readSheet(css) {
28152
+ function readSheet$1(css) {
28138
28153
  const tokens = /* @__PURE__ */ new Map();
28139
28154
  postcss_default.parse(css).walkRules((rule) => {
28140
28155
  const side = sideOf(rule);
@@ -28199,7 +28214,7 @@ const boxesBodySchema = object$1({
28199
28214
  sections: boxesSchema.optional(),
28200
28215
  expectedSections: boxesSchema.optional()
28201
28216
  });
28202
- const STATUS$4 = {
28217
+ const STATUS$5 = {
28203
28218
  usage: 400,
28204
28219
  "invalid-name": 400,
28205
28220
  "project-required": 400,
@@ -28262,7 +28277,7 @@ function apiRoutes(root, actions, look, history) {
28262
28277
  code: error.code,
28263
28278
  message: error.message
28264
28279
  }
28265
- }, STATUS$4[error.code] ?? 500);
28280
+ }, STATUS$5[error.code] ?? 500);
28266
28281
  }
28267
28282
  return c.json({
28268
28283
  ok: true,
@@ -28330,7 +28345,7 @@ function apiRoutes(root, actions, look, history) {
28330
28345
  message: error.message,
28331
28346
  details: error.details
28332
28347
  }
28333
- }, STATUS$4[error.code] ?? 500);
28348
+ }, STATUS$5[error.code] ?? 500);
28334
28349
  }
28335
28350
  });
28336
28351
  return app;
@@ -28726,6 +28741,192 @@ function checkRoutes(access, checks) {
28726
28741
  });
28727
28742
  return app;
28728
28743
  }
28744
+ // src/server/clipboard/wsl.ts
28745
+ /** The folder under Windows' temp folder each copy writes into. */
28746
+ const CLIP_FOLDER = "frameboard-clip";
28747
+ /** Characters a Windows file name cannot hold. */
28748
+ const WINDOWS_RESERVED = /[<>:"/\\|?*]/g;
28749
+ /**
28750
+ * The Windows clipboard reached from WSL. The images land in Windows' temp
28751
+ * folder, since a file drop list names Windows paths and a pasting app reads
28752
+ * the files after the copy returns. Each copy clears the last one's folder,
28753
+ * the only time a pasted list is known to be done with.
28754
+ */
28755
+ function wslClipboard(run) {
28756
+ return {
28757
+ backend: "wsl",
28758
+ write: async (files) => {
28759
+ const windowsDir = `${(await run("powershell.exe", [
28760
+ "-NoProfile",
28761
+ "-Command",
28762
+ "[IO.Path]::GetTempPath()"
28763
+ ])).trim().replace(/\\$/, "")}\\${CLIP_FOLDER}\\${randomUUID()}`;
28764
+ const linuxDir = (await run("wslpath", [windowsDir])).trim();
28765
+ await rm(join(linuxDir, ".."), {
28766
+ recursive: true,
28767
+ force: true
28768
+ });
28769
+ await mkdir(linuxDir, { recursive: true });
28770
+ const names = fileNames(files);
28771
+ await Promise.all(files.map((file, index) => writeFile(join(linuxDir, names[index] ?? ""), file.bytes)));
28772
+ await run("powershell.exe", [
28773
+ "-NoProfile",
28774
+ "-STA",
28775
+ "-Command",
28776
+ `Set-Clipboard -Path ${pathList(windowsDir, names)}`
28777
+ ]);
28778
+ }
28779
+ };
28780
+ }
28781
+ /** Each file's name made safe for Windows and unique in the folder, as `hero.png`, `hero-2.png`. */
28782
+ function fileNames(files) {
28783
+ const taken = /* @__PURE__ */ new Set();
28784
+ return files.map(({ name }) => {
28785
+ const base = name.replace(WINDOWS_RESERVED, "-").trim() || "frame";
28786
+ let candidate = `${base}.png`;
28787
+ for (let n = 2; taken.has(candidate.toLowerCase()); n++) candidate = `${base}-${n}.png`;
28788
+ taken.add(candidate.toLowerCase());
28789
+ return candidate;
28790
+ });
28791
+ }
28792
+ /** The PowerShell argument naming every file, each single-quoted with its quotes doubled. */
28793
+ function pathList(windowsDir, names) {
28794
+ return names.map((name) => `'${`${windowsDir}\\${name}`.replaceAll("'", "''")}'`).join(",");
28795
+ }
28796
+ // src/server/clipboard/files.ts
28797
+ /**
28798
+ * The backend this machine has, or null where none applies, so a caller
28799
+ * reports it before any copy is asked for. WSL needs `powershell.exe` on its
28800
+ * `PATH`, since interop can be turned off.
28801
+ */
28802
+ function clipboardFiles(host = processHost()) {
28803
+ if (isWsl(host) && host.onPath("powershell.exe")) return wslClipboard(host.run);
28804
+ return null;
28805
+ }
28806
+ /** The refusal for a copy where `clipboardFiles` found no backend. */
28807
+ function clipboardUnsupported() {
28808
+ return new FrameboardError("clipboard-unsupported", "This system has no clipboard backend for a file list. Only Windows under WSL has one.");
28809
+ }
28810
+ function isWsl({ platform, release, env }) {
28811
+ if (platform !== "linux") return false;
28812
+ return Boolean(env.WSL_DISTRO_NAME) || /microsoft/i.test(release);
28813
+ }
28814
+ function processHost() {
28815
+ const run = promisify(execFile);
28816
+ return {
28817
+ platform: process.platform,
28818
+ release: release(),
28819
+ env: process.env,
28820
+ run: async (command, args) => (await run(command, args)).stdout,
28821
+ onPath: (command) => (process.env.PATH ?? "").split(delimiter).some((dir) => dir !== "" && existsSync(join(dir, command)))
28822
+ };
28823
+ }
28824
+ // src/server/routes/envelope.ts
28825
+ /** The status each refusal of a structure or history write answers with. */
28826
+ const STATUS$4 = {
28827
+ usage: 400,
28828
+ "invalid-name": 400,
28829
+ "project-required": 400,
28830
+ "project-not-found": 404,
28831
+ "page-not-found": 404,
28832
+ "frame-not-found": 404,
28833
+ "section-not-found": 404,
28834
+ "name-taken": 409,
28835
+ "stale-layout": 409,
28836
+ "frame-claimed": 409,
28837
+ "undo-overtaken": 409,
28838
+ "nothing-to-undo": 409,
28839
+ "tokens-exist": 409,
28840
+ "stale-tokens": 409,
28841
+ "invalid-edit": 409,
28842
+ "frame-locked": 423,
28843
+ "layout-invalid": 422,
28844
+ "project-file-invalid": 422,
28845
+ "fit-unbounded": 422,
28846
+ "lock-timeout": 503,
28847
+ "browser-not-found": 503
28848
+ };
28849
+ /**
28850
+ * Answers a refusal in the CLI's `{ ok, error }` envelope, for a route
28851
+ * module's `onError`. Anything else is a fault and goes on to Hono.
28852
+ */
28853
+ function answerRefusal(error, c) {
28854
+ if (!(error instanceof FrameboardError)) throw error;
28855
+ return c.json({
28856
+ ok: false,
28857
+ error: {
28858
+ code: error.code,
28859
+ message: error.message,
28860
+ details: error.details
28861
+ }
28862
+ }, STATUS$4[error.code] ?? 500);
28863
+ }
28864
+ /** The request's JSON body as the schema reads it, or `usage` naming what failed. */
28865
+ async function parseBody$1(request, schema) {
28866
+ const parsed = schema.safeParse(await request.json().catch(() => null));
28867
+ if (!parsed.success) throw new FrameboardError("usage", `The body ${parsed.error.message}`);
28868
+ return parsed.data;
28869
+ }
28870
+ // src/server/routes/clipboard.ts
28871
+ const STATUS$3 = {
28872
+ usage: 400,
28873
+ "project-required": 400,
28874
+ "project-not-found": 404,
28875
+ "page-not-found": 404,
28876
+ "frame-not-found": 404,
28877
+ "font-missing": 422,
28878
+ "capture-too-large": 422,
28879
+ "clipboard-unsupported": 501,
28880
+ "browser-not-found": 503
28881
+ };
28882
+ /** The scale every copied frame renders at, matching Copy as PNG. */
28883
+ const COPY_SCALE = 2;
28884
+ const CopyBody = object$1({
28885
+ refs: array$1(string$1().min(1)).min(1),
28886
+ theme: _enum$1(["light", "dark"])
28887
+ });
28888
+ /**
28889
+ * `POST /api/frames/clipboard` with `{ refs, theme }`, rendering each frame
28890
+ * at twice its layout size and putting the images on the OS clipboard as one
28891
+ * file list. It sits behind `requireWriter`, since it replaces whatever the
28892
+ * developer held, and a system with no backend refuses before any render.
28893
+ */
28894
+ function clipboardRoutes(root, access, render, clipboard) {
28895
+ const app = new Hono();
28896
+ app.onError((error, c) => {
28897
+ if (!(error instanceof FrameboardError)) throw error;
28898
+ return c.json({
28899
+ ok: false,
28900
+ error: {
28901
+ code: error.code,
28902
+ message: error.message,
28903
+ details: error.details
28904
+ }
28905
+ }, STATUS$3[error.code] ?? 500);
28906
+ });
28907
+ app.use("/api/frames/clipboard", requireWriter(access));
28908
+ app.post("/api/frames/clipboard", async (c) => {
28909
+ const { refs, theme } = await parseBody$1(c.req.raw, CopyBody);
28910
+ if (clipboard === null) throw clipboardUnsupported();
28911
+ const files = [];
28912
+ for (const ref of refs) {
28913
+ const frame = await readFrame$1(root, ref, { cwd: root });
28914
+ files.push({
28915
+ name: frame.name,
28916
+ bytes: await render(frame, theme, COPY_SCALE)
28917
+ });
28918
+ }
28919
+ await clipboard.write(files);
28920
+ return c.json({
28921
+ ok: true,
28922
+ data: {
28923
+ copied: files.length,
28924
+ backend: clipboard.backend
28925
+ }
28926
+ });
28927
+ });
28928
+ return app;
28929
+ }
28729
28930
  // node_modules/@bramus/specificity/dist/index.js
28730
28931
  var Jn = Object.create;
28731
28932
  var te = Object.defineProperty;
@@ -35247,6 +35448,7 @@ function placeElement(source, index, spot, facts, drop = []) {
35247
35448
  };
35248
35449
  }
35249
35450
  // src/server/edit/frame-file.ts
35451
+ const identity = (index) => index;
35250
35452
  function stale$1(path) {
35251
35453
  return refuse$2("stale-address", `${basename(path)} changed after this edit was made, so nothing was written`);
35252
35454
  }
@@ -35290,7 +35492,8 @@ function editFrameFile(path, address, change, sourceAt) {
35290
35492
  hash: contentHash(applied.html),
35291
35493
  from: hash,
35292
35494
  index,
35293
- span: applied.span
35495
+ span: applied.span,
35496
+ remap: identity
35294
35497
  };
35295
35498
  }
35296
35499
  /**
@@ -35311,7 +35514,8 @@ function insertFrameFile(path, hash, placement, markup) {
35311
35514
  ok: true,
35312
35515
  hash: contentHash(inserted.html),
35313
35516
  index: inserted.index,
35314
- span: inserted.span
35517
+ span: inserted.span,
35518
+ remap: shiftedPast(inserted.index, subtreeSize(inserted.html, inserted.index))
35315
35519
  };
35316
35520
  }
35317
35521
  /**
@@ -35329,7 +35533,8 @@ function removeFrameFile(path, hash, index) {
35329
35533
  return {
35330
35534
  ok: true,
35331
35535
  hash: contentHash(removed.html),
35332
- span: removed.span
35536
+ span: removed.span,
35537
+ remap: takenOut(index, subtreeSize(read.source, index))
35333
35538
  };
35334
35539
  }
35335
35540
  /**
@@ -35348,7 +35553,8 @@ function moveFrameFile(path, hash, index, placement) {
35348
35553
  ok: true,
35349
35554
  hash: contentHash(moved.html),
35350
35555
  index: moved.index,
35351
- span: moved.span
35556
+ span: moved.span,
35557
+ remap: carried(index, moved.index, subtreeSize(read.source, index))
35352
35558
  };
35353
35559
  }
35354
35560
  /**
@@ -35369,9 +35575,37 @@ function placeFrameFile(path, hash, index, spot, facts, drop = []) {
35369
35575
  ok: true,
35370
35576
  hash: contentHash(placed.html),
35371
35577
  spans: placed.spans,
35372
- sized: placed.sized
35578
+ sized: placed.sized,
35579
+ remap: identity
35373
35580
  };
35374
35581
  }
35582
+ /** Elements written in at `at`, `size` of them with the descendants, push every later one on. */
35583
+ function shiftedPast(at, size) {
35584
+ return (index) => index < at ? index : index + size;
35585
+ }
35586
+ /** Elements taken out from `at`, `size` of them, map to nothing and pull every later one back. */
35587
+ function takenOut(at, size) {
35588
+ return (index) => {
35589
+ if (index < at) return index;
35590
+ return index < at + size ? null : index - size;
35591
+ };
35592
+ }
35593
+ /** A subtree of `size` elements carried from `from` to `to`, both in document order. */
35594
+ function carried(from, to, size) {
35595
+ const out = takenOut(from, size);
35596
+ const into = shiftedPast(to, size);
35597
+ return (index) => {
35598
+ if (index >= from && index < from + size) return to + index - from;
35599
+ const rest = out(index);
35600
+ return rest === null ? null : into(rest);
35601
+ };
35602
+ }
35603
+ /** The element at `index` with its descendants, which run on from it in document order. */
35604
+ function subtreeSize(source, index) {
35605
+ const element = parseFrame(source).elements[index];
35606
+ const count = (node) => node.childNodes.reduce((total, child) => hasTag(child) ? total + count(child) : total, 1);
35607
+ return element ? count(element) : 1;
35608
+ }
35375
35609
  /**
35376
35610
  * A frame file's text and hash. Bytes that do not survive a UTF-8 round trip
35377
35611
  * are refused, since decoding would rewrite every invalid byte.
@@ -35401,273 +35635,1338 @@ function replaceFile(path, hash, html) {
35401
35635
  renameSync(temp, path);
35402
35636
  return true;
35403
35637
  }
35404
- // src/shared/records/edit.ts
35405
- const hash = string$1().regex(/^[0-9a-f]{64}$/);
35406
- /** What `edit` returns: the frame it wrote, the element, and the hash the next edit is made from. */
35407
- const editResultSchema = object$1({
35408
- ref: string$1(),
35409
- /** The element's index in the file as written, which moves once the edit was found again by its bytes. */
35410
- index: int$1().min(0),
35411
- hash,
35412
- /** The hash the edit was written over, which differs from the one sent once the edit was found again. */
35413
- from: hash.optional()
35414
- });
35415
- object$1({
35416
- ref: string$1(),
35638
+ // src/shared/records/notes.ts
35639
+ /** Where a note on one element points, in the edit address's terms. */
35640
+ const noteAnchorSchema = looseObject({
35641
+ /** The element's `querySelectorAll('*')` index, skipping injected elements. */
35417
35642
  index: int$1().min(0),
35418
- hash
35643
+ /** The frame file's `contentHash` when the note was pinned. */
35644
+ hash: string$1(),
35645
+ /**
35646
+ * The element's index under each later hash a board write carried it to,
35647
+ * oldest first. Absent on a note no hand edit has followed.
35648
+ */
35649
+ known: record(string$1(), int$1().min(0)).optional()
35419
35650
  });
35420
- object$1({
35421
- ref: string$1(),
35422
- hash
35651
+ const noteSchema = looseObject({
35652
+ /** `n_` and 8 hex characters, unique across the board. */
35653
+ id: string$1(),
35654
+ /** The page's ordinal on a root note, never reused. A reply carries null. */
35655
+ number: int$1().min(1).nullable(),
35656
+ /** The frame's name in this page. */
35657
+ frame: string$1(),
35658
+ /** Null for a note on the whole frame. */
35659
+ anchor: noteAnchorSchema.nullable(),
35660
+ text: string$1(),
35661
+ /** Images saved with the message, relative to its page, as `.notes/<file>`. Absent on a note with none. */
35662
+ images: array$1(string$1()).optional(),
35663
+ from: _enum$1(["developer", "agent"]),
35664
+ /** Who signed it, as git names them, stamped by the server. */
35665
+ author: string$1().nullable(),
35666
+ /** The agent's session id on an agent reply. */
35667
+ session: string$1().nullable(),
35668
+ /** The session a root note is sent to. */
35669
+ to: string$1().nullable(),
35670
+ /** A root note's delivery state. A reply carries `open`. */
35671
+ state: _enum$1([
35672
+ "open",
35673
+ "queued",
35674
+ "delivered",
35675
+ "done"
35676
+ ]),
35677
+ /** The root note's id on a reply, else null. */
35678
+ thread: string$1().nullable(),
35679
+ createdAt: string$1(),
35680
+ updatedAt: string$1()
35423
35681
  });
35424
- object$1({
35425
- ref: string$1(),
35426
- index: int$1().min(0),
35427
- hash
35682
+ /** `<project>/<page>/notes.json`. */
35683
+ const notesFileSchema = looseObject({
35684
+ version: literal(1),
35685
+ notes: array$1(noteSchema)
35428
35686
  });
35429
- /** A size a placement wrote where no rule set one. */
35430
- const placedSizeSchema = _enum$1(["width", "height"]);
35431
- object$1({
35432
- ref: string$1(),
35433
- index: int$1().min(0),
35434
- hash,
35435
- sized: array$1(placedSizeSchema)
35687
+ /** A session following its inbox on the live socket. */
35688
+ const listenerSchema = object$1({
35689
+ session: string$1(),
35690
+ /** What the board shows for it, never used to address it. */
35691
+ tag: string$1(),
35692
+ since: string$1()
35436
35693
  });
35437
- // src/server/routes/envelope.ts
35438
- /** The status each refusal of a structure or history write answers with. */
35439
- const STATUS$3 = {
35440
- usage: 400,
35441
- "invalid-name": 400,
35442
- "project-required": 400,
35443
- "project-not-found": 404,
35444
- "page-not-found": 404,
35445
- "frame-not-found": 404,
35446
- "section-not-found": 404,
35447
- "name-taken": 409,
35448
- "stale-layout": 409,
35449
- "frame-claimed": 409,
35450
- "undo-overtaken": 409,
35451
- "nothing-to-undo": 409,
35452
- "tokens-exist": 409,
35453
- "stale-tokens": 409,
35454
- "invalid-edit": 409,
35455
- "frame-locked": 423,
35456
- "layout-invalid": 422,
35457
- "project-file-invalid": 422,
35458
- "fit-unbounded": 422,
35459
- "lock-timeout": 503,
35460
- "browser-not-found": 503
35461
- };
35694
+ // src/server/look/token-edit.ts
35695
+ const NAME = /^--[\w-]+$/;
35696
+ const UNSAFE_VALUE = /[;{}\n\r]|\/\*/;
35462
35697
  /**
35463
- * Answers a refusal in the CLI's `{ ok, error }` envelope, for a route
35464
- * module's `onError`. Anything else is a fault and goes on to Hono.
35698
+ * The project or board sheet with `edit` applied, every byte outside the
35699
+ * token's declarations left as it stood. `board` is the token's declarations
35700
+ * in the board sheet under it, none when `css` is the board sheet itself. A
35701
+ * one-theme edit keeps the other theme rendering as it did,
35702
+ * pinning its old value under that theme's rule when the new declaration
35703
+ * would reach it, since a project `:root` ties a board dark rule on
35704
+ * specificity and wins by coming later. Refuses `invalid-edit` for a name or
35705
+ * value that is not one declaration, a reset of a token the board does not
35706
+ * set, and a sheet that does not parse.
35465
35707
  */
35466
- function answerRefusal(error, c) {
35467
- if (!(error instanceof FrameboardError)) throw error;
35468
- return c.json({
35469
- ok: false,
35470
- error: {
35471
- code: error.code,
35472
- message: error.message,
35473
- details: error.details
35474
- }
35475
- }, STATUS$3[error.code] ?? 500);
35708
+ function editTokenCss(css, board, edit) {
35709
+ if (!NAME.test(edit.name)) refuse$1(`${edit.name} is not a custom property.`);
35710
+ const root = parseSheet(css);
35711
+ const own = sidesIn(root, edit.name);
35712
+ if ("reset" in edit) {
35713
+ if (Object.keys(board).length === 0 || Object.keys(own).length === 0) refuse$1(`${edit.name} has no board value under the project's, so there is nothing to reset to.`);
35714
+ return writeSides(root, edit.name, {});
35715
+ }
35716
+ const value = edit.value.trim();
35717
+ if (value === "" || UNSAFE_VALUE.test(edit.value)) refuse$1(`${JSON.stringify(edit.value)} is not one declaration value.`);
35718
+ const next = { ...own };
35719
+ if (edit.side === "dark") next.dark = value;
35720
+ else if (edit.side === "light") {
35721
+ if (next.light !== void 0) next.light = value;
35722
+ else next.base = value;
35723
+ const darkWas = shown(board, own).dark;
35724
+ if (shown(board, next).dark !== darkWas && darkWas !== void 0) next.dark = darkWas;
35725
+ } else {
35726
+ next.base = value;
35727
+ if (next.light !== void 0) next.light = value;
35728
+ if (next.dark !== void 0) next.dark = value;
35729
+ }
35730
+ const written = writeSides(root, edit.name, next);
35731
+ let readBack;
35732
+ try {
35733
+ readBack = sidesIn(postcss_default.parse(written), edit.name);
35734
+ } catch {
35735
+ readBack = void 0;
35736
+ }
35737
+ if (!isDeepStrictEqual(readBack, next)) refuse$1(`${JSON.stringify(edit.value)} would leave the sheet unreadable.`);
35738
+ return written;
35476
35739
  }
35477
- /** The request's JSON body as the schema reads it, or `usage` naming what failed. */
35478
- async function parseBody$1(request, schema) {
35479
- const parsed = schema.safeParse(await request.json().catch(() => null));
35480
- if (!parsed.success) throw new FrameboardError("usage", `The body ${parsed.error.message}`);
35481
- return parsed.data;
35740
+ /**
35741
+ * The sheet with the token's declarations made exactly `sides`, as undo
35742
+ * restores them. A side present replaces the last declaration on that side,
35743
+ * or is added to that side's rule, and a side absent takes out every
35744
+ * declaration on it, dropping a rule it leaves empty.
35745
+ */
35746
+ function setTokenSides(css, name, sides) {
35747
+ return writeSides(parseSheet(css), name, sides);
35748
+ }
35749
+ /** The token's declarations in a sheet, the last on each side winning, as the table reads them. */
35750
+ function tokenSides(css, name) {
35751
+ return sidesIn(parseSheet(css), name);
35482
35752
  }
35483
- // src/server/routes/edit.ts
35484
- const value = string$1().max(1e4);
35485
- const name$1 = string$1().min(1).max(256);
35486
- /** A dragged shape's side in CSS pixels. */
35487
- const side = int$1().min(1).max(1e4);
35488
- const editSchema$1 = object$1({
35489
- ref: string$1().min(1).max(1024),
35490
- index: int$1().min(0),
35491
- hash: string$1().regex(/^[0-9a-f]{64}$/),
35492
- change: discriminatedUnion("kind", [
35493
- object$1({
35494
- kind: literal("style"),
35495
- property: name$1,
35496
- value
35497
- }),
35498
- object$1({
35499
- kind: literal("attribute"),
35500
- name: name$1,
35501
- value
35502
- }),
35503
- object$1({
35504
- kind: literal("text"),
35505
- value
35506
- }),
35507
- object$1({
35508
- kind: literal("styles"),
35509
- declarations: array$1(object$1({
35510
- property: name$1,
35511
- value
35512
- })).max(16)
35513
- })
35514
- ])
35515
- });
35516
- const insertSchema = object$1({
35517
- ref: string$1().min(1).max(1024),
35518
- hash: string$1().regex(/^[0-9a-f]{64}$/),
35519
- parent: int$1().min(0),
35520
- before: int$1().min(0).nullable(),
35521
- element: discriminatedUnion("kind", [
35522
- object$1({ kind: literal("text") }),
35523
- object$1({
35524
- kind: literal("rectangle"),
35525
- width: side.optional(),
35526
- height: side.optional()
35527
- }),
35528
- object$1({
35529
- kind: literal("ellipse"),
35530
- width: side.optional(),
35531
- height: side.optional()
35532
- }),
35533
- object$1({
35534
- kind: literal("divider"),
35535
- vertical: boolean$1()
35536
- }),
35537
- object$1({
35538
- kind: literal("asset"),
35539
- path: string$1().min(1).max(1024),
35540
- width: side,
35541
- height: side
35542
- })
35543
- ])
35544
- });
35545
- const removeSchema = object$1({
35546
- ref: string$1().min(1).max(1024),
35547
- index: int$1().min(0),
35548
- hash: string$1().regex(/^[0-9a-f]{64}$/)
35549
- });
35550
- const moveSchema$1 = object$1({
35551
- ref: string$1().min(1).max(1024),
35552
- hash: string$1().regex(/^[0-9a-f]{64}$/),
35553
- index: int$1().min(0),
35554
- parent: int$1().min(0),
35555
- before: int$1().min(0).nullable()
35556
- });
35557
- /** A spot in CSS pixels, bounded well past any frame. */
35558
- const offset = number().min(-1e5).max(1e5);
35559
- const placeSchema = object$1({
35560
- ref: string$1().min(1).max(1024),
35561
- hash: string$1().regex(/^[0-9a-f]{64}$/),
35562
- index: int$1().min(0),
35563
- spot: object$1({
35564
- left: offset,
35565
- top: offset,
35566
- width: side.optional(),
35567
- height: side.optional()
35568
- }).nullable(),
35569
- /** Back in flow, the sizes to drop, being ones a placement wrote that nothing changed since. */
35570
- drop: array$1(placedSizeSchema).max(2).optional()
35571
- });
35572
35753
  /**
35573
- * A hand edit of one element, a placed element, and a deleted one, each behind
35574
- * `requireWriter` and refused on a frame another session holds.
35575
- *
35576
- * The edit's body mirrors
35577
- * `edit`'s flags with the hash required, since the board always holds the
35578
- * one it rendered, plus a `styles` change the CLI never sends, which writes
35579
- * several declarations as one step. It writes through `editFrameFile`, which finds the element
35580
- * again in a frame an agent wrote since from the source `version` kept, and
35581
- * records the edited element's span as one step. It answers the `edit`
35582
- * record with the index written and the hash written over. Each refusal the
35583
- * writer returns answers 409 with its code, `stale-address` among them.
35584
- *
35585
- * The insert takes an element kind, never markup, and writes that kind's one
35586
- * tag into the gap `parent` and `before` name, painted from the project's
35587
- * tokens through `sheets`, and records it as one step. It answers the frame,
35588
- * the new element's index, and the hash written. A hash the file no longer
35589
- * has answers 409 `stale-address` with nothing written, since the gap's
35590
- * indices name nothing past an agent's write, and a retried insert lands once.
35591
- * A rectangle or an ellipse takes an optional width and height a drag drew.
35592
- * An asset names a file under the project's `assets/` and the size it
35593
- * shows at, and the server picks its tag from the file's kind. A file
35594
- * outside that folder or not there answers 409 `asset-missing`, and one that
35595
- * is no image, GIF, SVG, or video `asset-not-placeable`, each writing nothing.
35596
- *
35597
- * The remove takes out the element at `index`, with what it holds, from the
35598
- * bytes `hash` names, and records it as one step whose undo puts it back
35599
- * under its parent. It answers the frame and the hash written, and refuses a
35600
- * moved file as `stale-address` the way the insert does.
35601
- *
35602
- * The move takes one element by index and the gap it goes into, both read
35603
- * in the frame as the hash names it, and records it as one step an undo
35604
- * puts back byte for byte. It answers the element's new index and the hash
35605
- * written, and refuses as the insert does, with `invalid-container` for a
35606
- * gap inside the element itself.
35607
- *
35608
- * The place takes one element by index and a spot in CSS pixels against its
35609
- * containing block, or null to put it back in the flow, read in the frame as
35610
- * the hash names it, with `drop` naming the sizes back in flow takes off. It
35611
- * writes the element's start tag, and its static parent's first, and records
35612
- * both as one step, so one undo restores both. It answers the element's
35613
- * index, the hash written, and the sizes a placement wrote, refuses as the move
35614
- * does, and refuses `reanchors-descendant` where a positioned parent would
35615
- * move another element anchored above it.
35754
+ * Writes the token sheet at `path` through a temporary file and a rename,
35755
+ * reading the sheet again just before the rename and leaving it as it is
35756
+ * when its hash is no longer `hash`. A null `hash` means the sheet did not
35757
+ * exist, so it is created only while none does. Takes no lock, since an
35758
+ * agent's raw write never takes one.
35616
35759
  */
35617
- function editRoutes(root, access, history, version, sheets) {
35618
- const app = new Hono();
35619
- app.post("/api/frames/edit", requireWriter(access), async (c) => {
35620
- const body = await parseBody$1(c.req.raw, editSchema$1);
35621
- const frame = await resolveFrameRef(root, body.ref, { cwd: root });
35622
- const ref = `${frame.project}/${frame.page}/${frame.name}`;
35623
- await refuseClaimed(root, [ref], /* @__PURE__ */ new Date());
35624
- const was = contentHash(await readFile(frame.path)) !== body.hash ? await version?.(ref, body.hash) ?? null : null;
35625
- const result = editFrameFile(frame.path, {
35626
- index: body.index,
35627
- hash: body.hash
35628
- }, body.change, (hash) => hash === body.hash ? was : null);
35629
- if (!result.ok) return c.json({
35630
- ok: false,
35631
- error: {
35632
- code: result.reason,
35633
- message: result.detail,
35634
- details: {
35635
- ref,
35636
- index: body.index,
35637
- ..."moved" in result ? { moved: result.moved } : {}
35638
- }
35639
- }
35640
- }, 409);
35641
- if (result.span.before !== result.span.after) {
35642
- const journal = history.journal();
35643
- journal.element(frame.path, ref, result.span);
35644
- history.record({
35645
- id: journal.id,
35646
- changes: journal.changes,
35647
- page: null,
35648
- frames: [ref]
35649
- });
35650
- }
35651
- const data = {
35652
- ref,
35653
- index: result.index,
35654
- hash: result.hash,
35655
- from: result.from
35656
- };
35657
- return c.json({
35658
- ok: true,
35659
- data
35760
+ function writeTokenSheet(path, hash, css) {
35761
+ if (hash === null) try {
35762
+ writeFileSync(path, css, { flag: "wx" });
35763
+ return "created";
35764
+ } catch (error) {
35765
+ if (isCode(error, "EEXIST")) return "stale";
35766
+ throw error;
35767
+ }
35768
+ const temp = join(dirname(path), `.${basename(path)}.${process.pid}.tmp`);
35769
+ writeFileSync(temp, css);
35770
+ if (hashOrNull(path) !== hash) {
35771
+ rmSync(temp, { force: true });
35772
+ return "stale";
35773
+ }
35774
+ renameSync(temp, path);
35775
+ return "written";
35776
+ }
35777
+ /** A sheet's content hash, or null when it does not exist. */
35778
+ function hashOrNull(path) {
35779
+ try {
35780
+ return contentHash(readFileSync(path));
35781
+ } catch (error) {
35782
+ if (isCode(error, "ENOENT")) return null;
35783
+ throw error;
35784
+ }
35785
+ }
35786
+ /** The light and dark values a token renders with, the project's sides over the board's. */
35787
+ function shown(board, project) {
35788
+ return {
35789
+ light: project.light ?? project.base ?? board.light ?? board.base,
35790
+ dark: project.dark ?? project.base ?? board.dark ?? board.base
35791
+ };
35792
+ }
35793
+ function parseSheet(css) {
35794
+ try {
35795
+ return postcss_default.parse(css);
35796
+ } catch (error) {
35797
+ return refuse$1(`The token sheet does not parse: ${error instanceof postcss_default.CssSyntaxError ? error.reason : String(error)}.`);
35798
+ }
35799
+ }
35800
+ /** Every declaration of `name` in a rule the table reads, by side, in sheet order. */
35801
+ function declsIn(root, name) {
35802
+ const found = {
35803
+ base: [],
35804
+ light: [],
35805
+ dark: []
35806
+ };
35807
+ root.walkRules((rule) => {
35808
+ const side = sideOf(rule);
35809
+ if (!side) return;
35810
+ rule.each((node) => {
35811
+ if (node.type === "decl" && node.prop === name) found[side].push(node);
35660
35812
  });
35661
35813
  });
35662
- app.post("/api/frames/insert", requireWriter(access), async (c) => {
35663
- const body = await parseBody$1(c.req.raw, insertSchema);
35664
- const frame = await resolveFrameRef(root, body.ref, { cwd: root });
35665
- const ref = `${frame.project}/${frame.page}/${frame.name}`;
35666
- await refuseClaimed(root, [ref], /* @__PURE__ */ new Date());
35667
- const tokens = sheets ? readTokenTable(root, sheets(frame.project)).tokens : [];
35668
- let element;
35669
- if (body.element.kind !== "asset") element = body.element;
35670
- else {
35814
+ return found;
35815
+ }
35816
+ function sidesIn(root, name) {
35817
+ const sides = {};
35818
+ for (const [side, decls] of Object.entries(declsIn(root, name))) {
35819
+ const last = decls.at(-1);
35820
+ if (last) sides[side] = last.value.trim();
35821
+ }
35822
+ return sides;
35823
+ }
35824
+ function writeSides(root, name, sides) {
35825
+ const found = declsIn(root, name);
35826
+ for (const side of [
35827
+ "dark",
35828
+ "base",
35829
+ "light"
35830
+ ]) {
35831
+ const value = sides[side];
35832
+ const decls = found[side];
35833
+ const last = decls.at(-1);
35834
+ if (value === void 0) for (const decl of decls) {
35835
+ const rule = decl.parent;
35836
+ decl.remove();
35837
+ if (rule && rule.nodes?.length === 0) rule.remove();
35838
+ }
35839
+ else if (last) {
35840
+ if (last.value.trim() !== value) last.value = value;
35841
+ } else ruleFor(root, side, side === "dark" ? void 0 : firstTopLevel(root, declsIn(root, name).dark)).append(postcss_default.decl({
35842
+ prop: name,
35843
+ value,
35844
+ raws: declRaws(root)
35845
+ }));
35846
+ }
35847
+ return root.toString();
35848
+ }
35849
+ /** The earliest top-level node holding any of `decls`, undefined for none. */
35850
+ function firstTopLevel(root, decls) {
35851
+ let first;
35852
+ for (const decl of decls) {
35853
+ let node = decl;
35854
+ while (node.parent && node.parent !== root) node = node.parent;
35855
+ const top = node;
35856
+ if (!first || root.index(top) < root.index(first)) first = top;
35857
+ }
35858
+ return first;
35859
+ }
35860
+ /** The spacing of the sheet's first declaration, so an added one reads like its neighbors. */
35861
+ function declRaws(root) {
35862
+ let sample;
35863
+ root.walkDecls((decl) => {
35864
+ sample = decl;
35865
+ return false;
35866
+ });
35867
+ return {
35868
+ before: sample?.raws.before ?? "\n ",
35869
+ between: sample?.raws.between ?? ": "
35870
+ };
35871
+ }
35872
+ const NEW_SELECTOR = {
35873
+ base: ":root",
35874
+ light: "[data-theme='light']",
35875
+ dark: "[data-theme='dark']"
35876
+ };
35877
+ /**
35878
+ * The top-level rule a new declaration on `side` goes into: the last such
35879
+ * rule outside any at-rule, else a new one. A new `:root` or light rule goes
35880
+ * ahead of every other rule, so a dark rule that ties it on specificity
35881
+ * still comes later and wins in dark, and a new dark rule goes last. With
35882
+ * `before`, the token's first dark declaration, a rule must come ahead of
35883
+ * it, and a new one goes just before it when none does.
35884
+ */
35885
+ function ruleFor(root, side, before) {
35886
+ const last = root.nodes.filter((node) => node.type === "rule" && sideOf(node) === side && (!before || root.index(node) < root.index(before))).at(-1);
35887
+ if (last) return last;
35888
+ const rule = postcss_default.rule({
35889
+ selector: NEW_SELECTOR[side],
35890
+ raws: {
35891
+ between: " ",
35892
+ semicolon: true,
35893
+ after: "\n"
35894
+ }
35895
+ });
35896
+ const first = before ?? root.nodes.find((node) => node.type === "rule");
35897
+ if (side !== "dark" && first) {
35898
+ const spacing = first.raws.before ?? "";
35899
+ root.insertBefore(first, rule);
35900
+ rule.raws.before = spacing;
35901
+ first.raws.before = "\n\n";
35902
+ } else {
35903
+ rule.raws.before = root.nodes.length > 0 ? "\n\n" : "";
35904
+ root.append(rule);
35905
+ if (!root.raws.after?.includes("\n")) root.raws.after = "\n";
35906
+ }
35907
+ return rule;
35908
+ }
35909
+ function refuse$1(message) {
35910
+ throw new FrameboardError("invalid-edit", message);
35911
+ }
35912
+ // src/server/history/trash.ts
35913
+ const TRASH_FOLDER = "trash";
35914
+ /**
35915
+ * Where the `index`th path a step takes out waits. The trash sits in `.run/`
35916
+ * inside the board root, so taking a path out is a rename on one volume, and
35917
+ * the watcher and scanner already skip the dot folder.
35918
+ */
35919
+ function trashSlot(root, step, index) {
35920
+ return join(root, RUN_FOLDER, TRASH_FOLDER, String(step), String(index));
35921
+ }
35922
+ async function takeOut(path, slot) {
35923
+ await mkdir(dirname(slot), { recursive: true });
35924
+ await rename(path, slot);
35925
+ }
35926
+ /** Emptied when the server starts and stops, since the history it serves lives in memory. */
35927
+ async function emptyTrash(root) {
35928
+ await rm(join(root, RUN_FOLDER, TRASH_FOLDER), {
35929
+ recursive: true,
35930
+ force: true
35931
+ });
35932
+ }
35933
+ // src/server/history/changes.ts
35934
+ /** The records a change writes, whose locks are held while it is checked and written. */
35935
+ function lockPaths(change) {
35936
+ if (change.kind === "entry" || change.kind === "section") return [change.layout];
35937
+ if (change.kind === "pages") return [change.file];
35938
+ return [];
35939
+ }
35940
+ /**
35941
+ * Whether the board still stands as `side` of the change left it, read
35942
+ * under the record's lock. A change that no longer holds was overtaken, and
35943
+ * so was one whose record an agent left unreadable, since writing it back
35944
+ * would overwrite that file and keeping the step would block every older one.
35945
+ */
35946
+ async function holds(change, side) {
35947
+ try {
35948
+ return await reads(change, side);
35949
+ } catch (error) {
35950
+ if (error instanceof FrameboardError && UNREADABLE.has(error.code)) return false;
35951
+ throw error;
35952
+ }
35953
+ }
35954
+ const UNREADABLE = /* @__PURE__ */ new Set(["layout-invalid", "project-file-invalid"]);
35955
+ async function reads(change, side) {
35956
+ switch (change.kind) {
35957
+ case "entry": {
35958
+ const stored = (await readRecord(change.layout, layoutSpec)).frames[change.frame];
35959
+ return isDeepStrictEqual(stored, withMeasured(change[side], stored));
35960
+ }
35961
+ case "section": {
35962
+ const file = await readRecord(change.layout, layoutSpec);
35963
+ return isDeepStrictEqual(file.sections?.[change.section], change[side]);
35964
+ }
35965
+ case "pages": {
35966
+ const file = await readRecord(change.file, {
35967
+ ...projectSpec,
35968
+ empty: emptyProject
35969
+ });
35970
+ return isDeepStrictEqual(file.pages, change[side]);
35971
+ }
35972
+ case "moved": {
35973
+ const [present, absent] = side === "after" ? [change.to, change.from] : [change.from, change.to];
35974
+ return await exists(present) && !await exists(absent);
35975
+ }
35976
+ case "path": return change.present === side ? await exists(change.path) && await hashPath(change.path) === change.hash : !await exists(change.path) && await exists(change.slot);
35977
+ case "element": return await exists(change.path) && holdsSpan(await readFile(change.path, "utf8"), change.span, side);
35978
+ case "inserted": return await exists(change.path) && holdsInserted(await readFile(change.path, "utf8"), change.span, side === change.present ? "after" : "before");
35979
+ case "token": return await exists(change.path) && holdsToken(change, side);
35980
+ case "relocated": return await exists(change.path) && relocateMoved(await readFile(change.path, "utf8"), change.span, OTHER[side]) !== void 0;
35981
+ }
35982
+ }
35983
+ /**
35984
+ * The entry a step holds, taking the stored size on each axis both it and the
35985
+ * stored entry hug, since the server measures that size and the developer
35986
+ * never set it, so a measure after a hand move neither overtakes the step nor
35987
+ * is reverted by it.
35988
+ */
35989
+ function withMeasured(entry, stored) {
35990
+ if (!entry || !stored) return entry;
35991
+ return {
35992
+ ...entry,
35993
+ ...entry.hugWidth && stored.hugWidth ? { width: stored.width } : {},
35994
+ ...entry.hugHeight && stored.hugHeight ? { height: stored.height } : {}
35995
+ };
35996
+ }
35997
+ const OTHER = {
35998
+ before: "after",
35999
+ after: "before"
36000
+ };
36001
+ /**
36002
+ * Writes `side` of a change back, under the record's lock, once `holds` read
36003
+ * the other side. A hand edit's change answers the frame's content hash as it
36004
+ * left it, and every other kind answers undefined.
36005
+ */
36006
+ async function restore(change, side) {
36007
+ switch (change.kind) {
36008
+ case "entry": {
36009
+ const file = await readRecord(change.layout, layoutSpec);
36010
+ const frames = { ...file.frames };
36011
+ const entry = withMeasured(change[side], frames[change.frame]);
36012
+ if (entry) frames[change.frame] = entry;
36013
+ else delete frames[change.frame];
36014
+ await writeRecord(change.layout, {
36015
+ ...file,
36016
+ frames
36017
+ });
36018
+ return;
36019
+ }
36020
+ case "section": {
36021
+ const file = await readRecord(change.layout, layoutSpec);
36022
+ const sections = { ...file.sections };
36023
+ const entry = change[side];
36024
+ if (entry) sections[change.section] = entry;
36025
+ else delete sections[change.section];
36026
+ await writeRecord(change.layout, {
36027
+ ...file,
36028
+ sections
36029
+ });
36030
+ return;
36031
+ }
36032
+ case "pages": {
36033
+ const file = await readRecord(change.file, {
36034
+ ...projectSpec,
36035
+ empty: emptyProject
36036
+ });
36037
+ await writeRecord(change.file, {
36038
+ ...file,
36039
+ pages: change[side]
36040
+ });
36041
+ return;
36042
+ }
36043
+ case "moved":
36044
+ if (side === "before") await rename(change.to, change.from);
36045
+ else await rename(change.from, change.to);
36046
+ return;
36047
+ case "path":
36048
+ if (change.present === side) await rename(change.slot, change.path);
36049
+ else await takeOut(change.path, change.slot);
36050
+ return;
36051
+ case "element": return rewriteFrame(change, (source) => {
36052
+ const swapped = swapSpan(source, change.span, OTHER[side]);
36053
+ return swapped && {
36054
+ html: swapped.html,
36055
+ keep: () => {
36056
+ change.span = swapped.span;
36057
+ }
36058
+ };
36059
+ });
36060
+ case "inserted": return rewriteFrame(change, (source) => {
36061
+ const written = side === change.present ? restoreInserted(source, change.span) : removeInserted(source, change.span);
36062
+ return written && {
36063
+ html: written.html,
36064
+ keep: () => {
36065
+ change.span = written.span;
36066
+ }
36067
+ };
36068
+ });
36069
+ case "relocated": return rewriteFrame(change, (source) => {
36070
+ const written = relocateMoved(source, change.span, side);
36071
+ return written && {
36072
+ html: written.html,
36073
+ keep: () => {
36074
+ change.span = written.span;
36075
+ }
36076
+ };
36077
+ });
36078
+ case "token": return rewriteToken(change, side);
36079
+ }
36080
+ }
36081
+ /** Whether the sheet sets the token exactly as `side` holds it, false for a sheet that no longer parses. */
36082
+ async function holdsToken(change, side) {
36083
+ try {
36084
+ const css = await readFile(change.path, "utf8");
36085
+ return isDeepStrictEqual(tokenSides(css, change.name), change[side]);
36086
+ } catch (error) {
36087
+ if (error instanceof FrameboardError) return false;
36088
+ throw error;
36089
+ }
36090
+ }
36091
+ /** Writes `side` of a token change, refusing a sheet that changed between its read and the rename. */
36092
+ async function rewriteToken(change, side) {
36093
+ const css = await readFile(change.path, "utf8");
36094
+ const written = setTokenSides(css, change.name, change[side]);
36095
+ if (writeTokenSheet(change.path, contentHash(css), written) === "stale") throw new FrameboardError("undo-overtaken", `An agent changed ${change.name} after your edit, so that step was dropped.`, { change: change.kind });
36096
+ }
36097
+ /**
36098
+ * Writes a hand edit's element to the other side through a temporary file and
36099
+ * a rename, reading the file again just before the rename. A write landing
36100
+ * before that read is not overwritten: the rewrite is made once more from the
36101
+ * fresh bytes, and refused once they change again or no longer hold the
36102
+ * element. Bytes that fail a UTF-8 round trip are refused too, since decoding
36103
+ * would rewrite each invalid byte outside the element. The change keeps where
36104
+ * the element was found, through `keep`, so the next side lands on it.
36105
+ */
36106
+ async function rewriteFrame(change, rewrite) {
36107
+ const temp = join(dirname(change.path), `.${basename(change.path)}.${process.pid}.tmp`);
36108
+ let source = await readText(change.path);
36109
+ for (let attempt = 0; source !== void 0 && attempt < 2; attempt += 1) {
36110
+ const written = rewrite(source);
36111
+ if (!written) break;
36112
+ await writeFile(temp, written.html);
36113
+ const now = await readText(change.path);
36114
+ if (now === source) {
36115
+ await rename(temp, change.path);
36116
+ written.keep();
36117
+ return contentHash(written.html);
36118
+ }
36119
+ source = now;
36120
+ }
36121
+ await rm(temp, { force: true });
36122
+ throw new FrameboardError("undo-overtaken", `An agent changed ${basename(change.path, FRAME_EXTENSION)} after your edit, so that step was dropped.`, { change: change.kind });
36123
+ }
36124
+ /** A frame file's text, or undefined when its bytes do not survive a UTF-8 round trip. */
36125
+ async function readText(path) {
36126
+ const bytes = await readFile(path);
36127
+ const text = bytes.toString("utf8");
36128
+ return Buffer.from(text, "utf8").equals(bytes) ? text : void 0;
36129
+ }
36130
+ /**
36131
+ * The journal one board write reports into, building the changes of one
36132
+ * step. A path it takes out waits in the step's trash folder.
36133
+ */
36134
+ var StepJournal = class {
36135
+ root;
36136
+ id;
36137
+ changes = [];
36138
+ constructor(root, id) {
36139
+ this.root = root;
36140
+ this.id = id;
36141
+ }
36142
+ entry(page, frame, before, after) {
36143
+ const layout = join(page, LAYOUT_FILE);
36144
+ this.changes.push({
36145
+ kind: "entry",
36146
+ layout,
36147
+ frame,
36148
+ before,
36149
+ after
36150
+ });
36151
+ }
36152
+ section(page, section, before, after) {
36153
+ const layout = join(page, LAYOUT_FILE);
36154
+ this.changes.push({
36155
+ kind: "section",
36156
+ layout,
36157
+ section,
36158
+ before,
36159
+ after
36160
+ });
36161
+ }
36162
+ pages(project, before, after) {
36163
+ const file = join(project, PROJECT_FILE);
36164
+ this.changes.push({
36165
+ kind: "pages",
36166
+ file,
36167
+ before,
36168
+ after
36169
+ });
36170
+ }
36171
+ async moved(from, to) {
36172
+ await rename(from, to);
36173
+ this.changes.push({
36174
+ kind: "moved",
36175
+ from,
36176
+ to
36177
+ });
36178
+ }
36179
+ /** The element a hand edit rewrote in a frame file, which this journal does not write. */
36180
+ element(path, ref, span) {
36181
+ this.changes.push({
36182
+ kind: "element",
36183
+ path,
36184
+ ref,
36185
+ span
36186
+ });
36187
+ }
36188
+ /** The element a placement tool wrote into a frame file, which this journal does not write. */
36189
+ inserted(path, ref, span) {
36190
+ this.changes.push({
36191
+ kind: "inserted",
36192
+ path,
36193
+ ref,
36194
+ span,
36195
+ present: "after"
36196
+ });
36197
+ }
36198
+ /** The element a hand delete took out of a frame file, which this journal does not write. */
36199
+ deletedElement(path, ref, span) {
36200
+ this.changes.push({
36201
+ kind: "inserted",
36202
+ path,
36203
+ ref,
36204
+ span,
36205
+ present: "before"
36206
+ });
36207
+ }
36208
+ /** The element a hand move took to another gap of a frame file, which this journal does not write. */
36209
+ relocated(path, ref, span) {
36210
+ this.changes.push({
36211
+ kind: "relocated",
36212
+ path,
36213
+ ref,
36214
+ span
36215
+ });
36216
+ }
36217
+ /** One token's project declarations a hand token edit rewrote, which this journal does not write. */
36218
+ token(path, name, before, after) {
36219
+ this.changes.push({
36220
+ kind: "token",
36221
+ path,
36222
+ name,
36223
+ before,
36224
+ after
36225
+ });
36226
+ }
36227
+ async created(path) {
36228
+ this.changes.push({
36229
+ kind: "path",
36230
+ path,
36231
+ present: "after",
36232
+ hash: await hashPath(path),
36233
+ slot: this.#slot()
36234
+ });
36235
+ }
36236
+ async removed(path) {
36237
+ const hash = await hashPath(path);
36238
+ const slot = this.#slot();
36239
+ await takeOut(path, slot);
36240
+ this.changes.push({
36241
+ kind: "path",
36242
+ path,
36243
+ present: "before",
36244
+ hash,
36245
+ slot
36246
+ });
36247
+ }
36248
+ #slot() {
36249
+ return trashSlot(this.root, this.id, this.changes.length);
36250
+ }
36251
+ };
36252
+ /**
36253
+ * A hash over a file's bytes, or over every file in a folder with its path.
36254
+ * Dot-named entries, locks, and temp files are left out, as the scanner
36255
+ * leaves them, so a lock taken and released reads as no change.
36256
+ */
36257
+ async function hashPath(path) {
36258
+ const hash = createHash("sha256");
36259
+ const walk = async (at, name) => {
36260
+ if ((await stat(at)).isDirectory()) {
36261
+ hash.update(`d:${name}\0`);
36262
+ const children = (await readdir(at)).filter(isHashed).sort();
36263
+ for (const child of children) await walk(join(at, child), `${name}/${child}`);
36264
+ } else {
36265
+ hash.update(`f:${name}\0`);
36266
+ hash.update(await readFile(at));
36267
+ hash.update("\0");
36268
+ }
36269
+ };
36270
+ await walk(path, ".");
36271
+ return hash.digest("hex");
36272
+ }
36273
+ function isHashed(name) {
36274
+ return !name.startsWith(".") && !name.endsWith(".lock") && !name.endsWith(".tmp");
36275
+ }
36276
+ /**
36277
+ * Whether the path exists under exactly this name, read from its folder's
36278
+ * listing, so a case-only rename on a case-insensitive volume tells the two
36279
+ * names apart.
36280
+ */
36281
+ async function exists(path) {
36282
+ try {
36283
+ return (await readdir(dirname(path))).includes(basename(path));
36284
+ } catch (error) {
36285
+ if (isCode(error, "ENOENT")) return false;
36286
+ throw error;
36287
+ }
36288
+ }
36289
+ const OPEN = async () => {};
36290
+ /**
36291
+ * The developer's undo and redo stacks, in memory, holding the board's own
36292
+ * writes and never an agent's. Undo and redo run one at a time, each
36293
+ * checking every change of a step under its records' locks before writing
36294
+ * any, and refusing with `undo-overtaken` and dropping the step when an
36295
+ * agent has since changed one.
36296
+ */
36297
+ var History = class {
36298
+ root;
36299
+ onChange;
36300
+ onWrite;
36301
+ #undo = [];
36302
+ #redo = [];
36303
+ #nextId = 1;
36304
+ #turn = Promise.resolve();
36305
+ constructor(root, onChange = () => {}, onWrite = () => {}) {
36306
+ this.root = root;
36307
+ this.onChange = onChange;
36308
+ this.onWrite = onWrite;
36309
+ }
36310
+ counts() {
36311
+ return {
36312
+ undo: this.#undo.length,
36313
+ redo: this.#redo.length
36314
+ };
36315
+ }
36316
+ /** A journal for one write, to pass into the board verb and then record. */
36317
+ journal() {
36318
+ return new StepJournal(this.root, this.#nextId++);
36319
+ }
36320
+ /** Pushes a write's step, clearing redo. A write that changed nothing records nothing. */
36321
+ record(step) {
36322
+ if (step.changes.length === 0) return;
36323
+ this.#undo.push(step);
36324
+ if (this.#undo.length > 100) this.#undo.shift();
36325
+ this.#redo = [];
36326
+ this.onChange(this.counts());
36327
+ this.onWrite(step, "after");
36328
+ }
36329
+ /**
36330
+ * The refs the top undo or redo step would write, without popping it, so a
36331
+ * route can refuse a claimed frame before the step is taken. These are the
36332
+ * step's frames, and the page or project folder and frame file each move
36333
+ * or removal names, since a page or project step names no frames.
36334
+ */
36335
+ peek(side) {
36336
+ const step = (side === "undo" ? this.#undo : this.#redo).at(-1);
36337
+ if (!step) return [];
36338
+ const refs = step.changes.flatMap((change) => {
36339
+ if (change.kind === "moved") return [change.from, change.to];
36340
+ if (change.kind === "path") return [change.path];
36341
+ return [];
36342
+ }).flatMap((path) => {
36343
+ const inBoard = relative(this.root, path);
36344
+ if (inBoard === "" || inBoard.startsWith("..") || isAbsolute(inBoard)) return [];
36345
+ const ref = inBoard.split(sep).join("/");
36346
+ return [ref.endsWith(".html") ? ref.slice(0, -5) : ref];
36347
+ });
36348
+ return [.../* @__PURE__ */ new Set([...step.frames, ...refs])];
36349
+ }
36350
+ /**
36351
+ * Undoes the top step. `gate` reads what `peek` names of that step in turn,
36352
+ * before it is taken, so a refusal it throws leaves the step on its stack
36353
+ * and a quick second undo never checks one step and takes another.
36354
+ */
36355
+ undo(gate = OPEN) {
36356
+ return this.#inTurn(() => this.#move(this.#undo, this.#redo, "before", gate));
36357
+ }
36358
+ /** Redoes the top step, gated as `undo` is. */
36359
+ redo(gate = OPEN) {
36360
+ return this.#inTurn(() => this.#move(this.#redo, this.#undo, "after", gate));
36361
+ }
36362
+ /** Takes the top step of `from`, writes `to` side of it, and pushes it onto `onto`. */
36363
+ async #move(from, onto, to, gate) {
36364
+ const empty = () => new FrameboardError("nothing-to-undo", `There is nothing to ${to === "before" ? "undo" : "redo"}.`);
36365
+ if (from.length === 0) throw empty();
36366
+ await gate(this.peek(from === this.#undo ? "undo" : "redo"));
36367
+ const step = from.pop();
36368
+ if (!step) throw empty();
36369
+ const was = to === "before" ? "after" : "before";
36370
+ const hashes = {};
36371
+ const locks = step.changes.flatMap(lockPaths).filter((path) => existsSync(dirname(path)));
36372
+ try {
36373
+ await withLocks(locks, async () => {
36374
+ for (const change of step.changes) if (!await holds(change, was)) throw new FrameboardError("undo-overtaken", `An agent changed ${nameOf(change)} after your edit, so that step was dropped.`, { change: change.kind });
36375
+ const ordered = to === "before" ? [...step.changes].reverse() : step.changes;
36376
+ for (const change of ordered) {
36377
+ const hash = await restore(change, to);
36378
+ if (hash !== void 0 && "ref" in change) hashes[change.ref] = hash;
36379
+ }
36380
+ });
36381
+ } catch (error) {
36382
+ if (!(error instanceof FrameboardError && error.code === "undo-overtaken")) from.push(step);
36383
+ this.onChange(this.counts());
36384
+ throw error;
36385
+ }
36386
+ onto.push(step);
36387
+ this.onChange(this.counts());
36388
+ this.onWrite(step, to);
36389
+ const answer = {
36390
+ page: step.page?.[to] ?? null,
36391
+ frames: step.frames
36392
+ };
36393
+ return Object.keys(hashes).length > 0 ? {
36394
+ ...answer,
36395
+ hashes
36396
+ } : answer;
36397
+ }
36398
+ #inTurn(task) {
36399
+ const run = this.#turn.then(task);
36400
+ this.#turn = run.catch(() => {});
36401
+ return run;
36402
+ }
36403
+ };
36404
+ /** What a refusal names as overtaken, being a frame, a section, a page, or the page order. */
36405
+ function nameOf(change) {
36406
+ if (change.kind === "entry") return change.frame;
36407
+ if (change.kind === "section") return `section ${change.section}`;
36408
+ if (change.kind === "pages") return "the page order";
36409
+ if (change.kind === "token") return change.name;
36410
+ const path = change.kind === "moved" ? change.to : change.path;
36411
+ return basename(path, FRAME_EXTENSION);
36412
+ }
36413
+ // src/server/notes/anchor.ts
36414
+ /**
36415
+ * The anchor for element `index` of a frame, refusing `stale-address` when
36416
+ * the file changed since the board rendered it at `renderedAt`, since the
36417
+ * index the board counted belongs to the file it showed.
36418
+ */
36419
+ async function anchorFor(framePath, index, renderedAt) {
36420
+ const [bytes, { mtimeMs }] = await Promise.all([readFile(framePath), stat(framePath)]);
36421
+ if (new Date(mtimeMs).toISOString() !== renderedAt || index >= parseFrame(bytes.toString("utf8")).elements.length) throw new FrameboardError("stale-address", `The frame changed since the board showed it, so element ${index} may be another one. Pick it again.`, {
36422
+ path: framePath,
36423
+ index
36424
+ });
36425
+ return {
36426
+ index,
36427
+ hash: contentHash(bytes)
36428
+ };
36429
+ }
36430
+ /**
36431
+ * The element an anchor points at while the frame file hashes as `hash`: its
36432
+ * pinned index under the pinned hash, the index a board write carried it to
36433
+ * under a hash it has followed, else null, being the frame itself.
36434
+ */
36435
+ function indexAt(anchor, hash) {
36436
+ if (hash === null) return null;
36437
+ if (hash === anchor.hash) return anchor.index;
36438
+ return anchor.known?.[hash] ?? null;
36439
+ }
36440
+ /**
36441
+ * The element each anchored note still points at, by note id, as `indexAt`
36442
+ * reads it under the frame file's current hash. A frame note has no entry.
36443
+ */
36444
+ async function resolveAnchors(pageDir, notes) {
36445
+ const frames = [...new Set(notes.filter((note) => note.anchor).map((note) => note.frame))];
36446
+ const hashes = new Map(await Promise.all(frames.map(async (frame) => [frame, await hashOf(join(pageDir, `${frame}${FRAME_EXTENSION}`))])));
36447
+ const resolved = {};
36448
+ for (const note of notes) {
36449
+ if (!note.anchor) continue;
36450
+ resolved[note.id] = indexAt(note.anchor, hashes.get(note.frame) ?? null);
36451
+ }
36452
+ return resolved;
36453
+ }
36454
+ async function hashOf(path) {
36455
+ try {
36456
+ return contentHash(await readFile(path));
36457
+ } catch (error) {
36458
+ if (isCode(error, "ENOENT")) return null;
36459
+ throw error;
36460
+ }
36461
+ }
36462
+ /**
36463
+ * The one line a follower prints per note. It opens with `frameboard note`,
36464
+ * which the skill tells the agent to act on, and names the verbs that answer
36465
+ * it. Text is collapsed onto one line, stripped of control characters so it
36466
+ * cannot drive the terminal, and cut at 200 characters. Image paths sit
36467
+ * between the text and the hints, so the prefix and the hints never move.
36468
+ */
36469
+ function noteLine({ id, ref, element, text, images = [] }) {
36470
+ const where = element === null ? ref : `${ref} element ${element}`;
36471
+ const attached = images.length === 0 ? "" : ` (images: ${images.map(flatten).join(", ")})`;
36472
+ return `frameboard note ${id} on ${where}: ${collapse(text)}${attached} (reply: frameboard notes reply ${id} "<text>", close: frameboard notes done ${id})`;
36473
+ }
36474
+ function collapse(text) {
36475
+ const flat = flatten(text);
36476
+ return flat.length > 200 ? `${flat.slice(0, 200)}...` : flat;
36477
+ }
36478
+ function flatten(text) {
36479
+ return text.replace(/\s+/g, " ").replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim();
36480
+ }
36481
+ // src/server/notes/store.ts
36482
+ const NOTES_FILE$2 = "notes.json";
36483
+ const notesSpec = {
36484
+ schema: notesFileSchema,
36485
+ invalidCode: "notes-invalid",
36486
+ empty: () => ({
36487
+ version: 1,
36488
+ notes: []
36489
+ })
36490
+ };
36491
+ /** `n_` and 8 random hex characters. */
36492
+ function newNoteId() {
36493
+ return `n_${randomBytes(4).toString("hex")}`;
36494
+ }
36495
+ function notesPath(root, project, page) {
36496
+ return join(root, project, page, NOTES_FILE$2);
36497
+ }
36498
+ function readNotes(path) {
36499
+ return readRecord(path, notesSpec);
36500
+ }
36501
+ /** Reads, changes, and writes a page's notes under its lock, refusing a file that does not parse. */
36502
+ function updateNotes(path, change) {
36503
+ return updateRecord(path, notesSpec, change);
36504
+ }
36505
+ /** Every page in the board, as the place its notes file sits. */
36506
+ async function listPageNotes(root) {
36507
+ const projects = await listProjects(root);
36508
+ return (await Promise.all(projects.map(async (project) => (await listPageFolders(join(root, project))).map((page) => ({
36509
+ project,
36510
+ page,
36511
+ path: notesPath(root, project, page)
36512
+ }))))).flat();
36513
+ }
36514
+ /**
36515
+ * The page holding a note id, scanning every page of the board. A page whose
36516
+ * file does not parse cannot be read for the id, so when no other page holds
36517
+ * it the first such page's `notes-invalid` is thrown rather than a missing note.
36518
+ */
36519
+ async function findNote(root, id) {
36520
+ let unreadable;
36521
+ for (const place of await listPageNotes(root)) {
36522
+ let file;
36523
+ try {
36524
+ file = await readNotes(place.path);
36525
+ } catch (error) {
36526
+ if (!(error instanceof FrameboardError)) throw error;
36527
+ unreadable ??= error;
36528
+ continue;
36529
+ }
36530
+ const note = file.notes.find((candidate) => candidate.id === id);
36531
+ if (note) return {
36532
+ ...place,
36533
+ file,
36534
+ note
36535
+ };
36536
+ }
36537
+ if (unreadable) throw unreadable;
36538
+ throw new FrameboardError("note-not-found", `No note ${id} in this board.`, { id });
36539
+ }
36540
+ /** The root of the thread a note belongs to, being the note itself when it is one. */
36541
+ function rootOf(file, id) {
36542
+ const note = file.notes.find((candidate) => candidate.id === id);
36543
+ const root = note?.thread ? file.notes.find((candidate) => candidate.id === note.thread) : note;
36544
+ if (!root) throw new FrameboardError("note-not-found", `No note ${id} in this page.`, { id });
36545
+ return root;
36546
+ }
36547
+ /** Adds a root note numbered one past the page's highest, so a number is never reused. */
36548
+ function addRoot(file, fields, { now, id }) {
36549
+ const number = Math.max(0, ...file.notes.map((note) => note.number ?? 0)) + 1;
36550
+ const at = now.toISOString();
36551
+ const note = {
36552
+ id,
36553
+ number,
36554
+ frame: fields.frame,
36555
+ anchor: fields.anchor,
36556
+ text: fields.text,
36557
+ ...withImages(fields.images),
36558
+ from: "developer",
36559
+ author: fields.author,
36560
+ session: null,
36561
+ to: fields.to,
36562
+ state: fields.to === null ? "open" : "queued",
36563
+ thread: null,
36564
+ createdAt: at,
36565
+ updatedAt: at
36566
+ };
36567
+ return {
36568
+ ...file,
36569
+ notes: [...file.notes, note]
36570
+ };
36571
+ }
36572
+ /** Appends a reply to the thread `to` belongs to, reopening nothing a reply does not name. */
36573
+ function addReply(file, replyTo, fields, { now, id }) {
36574
+ const root = rootOf(file, replyTo);
36575
+ const at = now.toISOString();
36576
+ const reply = {
36577
+ id,
36578
+ number: null,
36579
+ frame: root.frame,
36580
+ anchor: root.anchor,
36581
+ text: fields.text,
36582
+ ...withImages(fields.images),
36583
+ from: fields.from,
36584
+ author: fields.author,
36585
+ session: fields.session,
36586
+ to: null,
36587
+ state: "open",
36588
+ thread: root.id,
36589
+ createdAt: at,
36590
+ updatedAt: at
36591
+ };
36592
+ const notes = file.notes.map((note) => note.id === root.id && fields.to !== void 0 ? {
36593
+ ...note,
36594
+ to: fields.to,
36595
+ state: "queued",
36596
+ updatedAt: at
36597
+ } : note);
36598
+ return {
36599
+ ...file,
36600
+ notes: [...notes, reply]
36601
+ };
36602
+ }
36603
+ /** A note with no images carries no key, so it reads as one written before images. */
36604
+ function withImages(images) {
36605
+ return images === void 0 || images.length === 0 ? {} : { images };
36606
+ }
36607
+ /** Sets the state of the thread `id` belongs to, and its addressee when one is given. */
36608
+ function setState(file, id, state, now, to) {
36609
+ const root = rootOf(file, id);
36610
+ return {
36611
+ ...file,
36612
+ notes: file.notes.map((note) => note.id === root.id ? {
36613
+ ...note,
36614
+ state,
36615
+ ...to === void 0 ? {} : { to },
36616
+ updatedAt: now.toISOString()
36617
+ } : note)
36618
+ };
36619
+ }
36620
+ /** Takes one message out, for a write whose send failed after it landed. */
36621
+ function removeNote(file, id) {
36622
+ return {
36623
+ ...file,
36624
+ notes: file.notes.filter((note) => note.id !== id)
36625
+ };
36626
+ }
36627
+ /**
36628
+ * Carries each note anchored on `frame` across a write the board made from
36629
+ * the bytes `before` names to the bytes `after` names, recording the index
36630
+ * `remap` gives its element. A note not resolving at `before`, or whose
36631
+ * element the write took out, is left as it is, so it falls back to the
36632
+ * frame. Each anchor keeps the last `HISTORY_CAP` hashes, since no undo
36633
+ * reaches further. Writes nothing when no note follows, and leaves a notes
36634
+ * file that does not parse, since the frame write already landed.
36635
+ */
36636
+ async function followEdit(path, frame, before, after, remap) {
36637
+ let file;
36638
+ try {
36639
+ file = await readNotes(path);
36640
+ } catch (error) {
36641
+ if (error instanceof FrameboardError) return;
36642
+ throw error;
36643
+ }
36644
+ if (!file.notes.some((note) => followed(note, frame, before, after, remap))) return;
36645
+ await updateNotes(path, (current) => ({
36646
+ ...current,
36647
+ notes: current.notes.map((note) => followed(note, frame, before, after, remap) ?? note)
36648
+ }));
36649
+ }
36650
+ /** The note with `after` added to its anchor, or undefined when it does not follow the write. */
36651
+ function followed(note, frame, before, after, remap) {
36652
+ if (note.frame !== frame || !note.anchor || after === note.anchor.hash) return;
36653
+ const was = indexAt(note.anchor, before);
36654
+ const index = was === null ? null : remap(was);
36655
+ if (index === null) return void 0;
36656
+ const { [after]: _, ...rest } = note.anchor.known ?? {};
36657
+ const known = Object.fromEntries([...Object.entries(rest), [after, index]].slice(-100));
36658
+ return {
36659
+ ...note,
36660
+ anchor: {
36661
+ ...note.anchor,
36662
+ known
36663
+ }
36664
+ };
36665
+ }
36666
+ /** A note as an agent reads it, without the hashes its anchor followed, which only the board resolves. */
36667
+ function forAgent(note) {
36668
+ if (!note.anchor?.known) return note;
36669
+ const { known: _, ...anchor } = note.anchor;
36670
+ return {
36671
+ ...note,
36672
+ anchor
36673
+ };
36674
+ }
36675
+ /** A page's notes as the board draws them, an unreadable file reading as none. */
36676
+ async function pageView(root, place) {
36677
+ let file;
36678
+ try {
36679
+ file = await readNotes(place.path);
36680
+ } catch (error) {
36681
+ if (error instanceof FrameboardError) return [];
36682
+ throw error;
36683
+ }
36684
+ const elements = await resolveAnchors(join(root, place.project, place.page), file.notes);
36685
+ return file.notes.map((note) => ({
36686
+ ...note,
36687
+ element: elements[note.id] ?? null
36688
+ }));
36689
+ }
36690
+ /** Every page holding notes, by `<project>/<page>` ref, as the board draws them. */
36691
+ async function boardView(root) {
36692
+ const pages = await Promise.all((await listPageNotes(root)).map(async (place) => [`${place.project}/${place.page}`, await pageView(root, place)]));
36693
+ return Object.fromEntries(pages.filter(([, notes]) => notes.length > 0));
36694
+ }
36695
+ /**
36696
+ * The root notes queued to a session, read from disk, each with the line its
36697
+ * follower prints, carrying the thread's newest developer message.
36698
+ */
36699
+ async function queuedFor(root, session) {
36700
+ const deliveries = [];
36701
+ for (const place of await listPageNotes(root)) {
36702
+ const notes = await pageView(root, place);
36703
+ for (const note of notes) {
36704
+ if (note.thread !== null || note.state !== "queued") continue;
36705
+ if (note.to !== session) continue;
36706
+ deliveries.push(toDelivery(place, notes, note));
36707
+ }
36708
+ }
36709
+ return deliveries;
36710
+ }
36711
+ /** A root note as a follower would receive it, read from its page whatever its state. */
36712
+ async function deliveryOf(root, place, rootId) {
36713
+ const notes = await pageView(root, place);
36714
+ const note = notes.find((each) => each.id === rootId && each.thread === null);
36715
+ if (!note) throw new FrameboardError("note-not-found", `No note ${rootId} in this page.`, { id: rootId });
36716
+ return toDelivery(place, notes, note);
36717
+ }
36718
+ function toDelivery(place, notes, note) {
36719
+ const ref = `${place.project}/${place.page}/${note.frame}`;
36720
+ const newest = notes.filter((each) => (each.id === note.id || each.thread === note.id) && each.from === "developer").at(-1);
36721
+ const { element, ...stored } = note;
36722
+ const message = newest ?? note;
36723
+ const pageDir = dirname(place.path);
36724
+ return {
36725
+ note: forAgent(stored),
36726
+ ref,
36727
+ line: noteLine({
36728
+ id: note.id,
36729
+ ref,
36730
+ element,
36731
+ text: message.text,
36732
+ images: message.images?.map((image) => join(pageDir, image))
36733
+ })
36734
+ };
36735
+ }
36736
+ /** Marks a root note delivered, while it is still queued to that session. */
36737
+ async function markDelivered(root, id, session, now) {
36738
+ await updateNotes((await findNote(root, id)).path, (file) => {
36739
+ const note = file.notes.find((each) => each.id === id);
36740
+ return note?.state === "queued" && note.to === session ? setState(file, id, "delivered", now) : file;
36741
+ });
36742
+ }
36743
+ // src/shared/records/edit.ts
36744
+ const hash = string$1().regex(/^[0-9a-f]{64}$/);
36745
+ /** What `edit` returns: the frame it wrote, the element, and the hash the next edit is made from. */
36746
+ const editResultSchema = object$1({
36747
+ ref: string$1(),
36748
+ /** The element's index in the file as written, which moves once the edit was found again by its bytes. */
36749
+ index: int$1().min(0),
36750
+ hash,
36751
+ /** The hash the edit was written over, which differs from the one sent once the edit was found again. */
36752
+ from: hash.optional()
36753
+ });
36754
+ object$1({
36755
+ ref: string$1(),
36756
+ index: int$1().min(0),
36757
+ hash
36758
+ });
36759
+ object$1({
36760
+ ref: string$1(),
36761
+ hash
36762
+ });
36763
+ object$1({
36764
+ ref: string$1(),
36765
+ index: int$1().min(0),
36766
+ hash
36767
+ });
36768
+ /** A size a placement wrote where no rule set one. */
36769
+ const placedSizeSchema = _enum$1(["width", "height"]);
36770
+ object$1({
36771
+ ref: string$1(),
36772
+ index: int$1().min(0),
36773
+ hash,
36774
+ sized: array$1(placedSizeSchema)
36775
+ });
36776
+ // src/server/routes/edit.ts
36777
+ const value = string$1().max(1e4);
36778
+ const name$1 = string$1().min(1).max(256);
36779
+ /** A dragged shape's side in CSS pixels. */
36780
+ const side = int$1().min(1).max(1e4);
36781
+ const editSchema$1 = object$1({
36782
+ ref: string$1().min(1).max(1024),
36783
+ index: int$1().min(0),
36784
+ hash: string$1().regex(/^[0-9a-f]{64}$/),
36785
+ change: discriminatedUnion("kind", [
36786
+ object$1({
36787
+ kind: literal("style"),
36788
+ property: name$1,
36789
+ value
36790
+ }),
36791
+ object$1({
36792
+ kind: literal("attribute"),
36793
+ name: name$1,
36794
+ value
36795
+ }),
36796
+ object$1({
36797
+ kind: literal("text"),
36798
+ value
36799
+ }),
36800
+ object$1({
36801
+ kind: literal("styles"),
36802
+ declarations: array$1(object$1({
36803
+ property: name$1,
36804
+ value
36805
+ })).max(16)
36806
+ })
36807
+ ])
36808
+ });
36809
+ const insertSchema = object$1({
36810
+ ref: string$1().min(1).max(1024),
36811
+ hash: string$1().regex(/^[0-9a-f]{64}$/),
36812
+ parent: int$1().min(0),
36813
+ before: int$1().min(0).nullable(),
36814
+ element: discriminatedUnion("kind", [
36815
+ object$1({ kind: literal("text") }),
36816
+ object$1({
36817
+ kind: literal("rectangle"),
36818
+ width: side.optional(),
36819
+ height: side.optional()
36820
+ }),
36821
+ object$1({
36822
+ kind: literal("ellipse"),
36823
+ width: side.optional(),
36824
+ height: side.optional()
36825
+ }),
36826
+ object$1({
36827
+ kind: literal("divider"),
36828
+ vertical: boolean$1()
36829
+ }),
36830
+ object$1({
36831
+ kind: literal("asset"),
36832
+ path: string$1().min(1).max(1024),
36833
+ width: side,
36834
+ height: side
36835
+ })
36836
+ ])
36837
+ });
36838
+ const removeSchema = object$1({
36839
+ ref: string$1().min(1).max(1024),
36840
+ index: int$1().min(0),
36841
+ hash: string$1().regex(/^[0-9a-f]{64}$/)
36842
+ });
36843
+ const moveSchema$1 = object$1({
36844
+ ref: string$1().min(1).max(1024),
36845
+ hash: string$1().regex(/^[0-9a-f]{64}$/),
36846
+ index: int$1().min(0),
36847
+ parent: int$1().min(0),
36848
+ before: int$1().min(0).nullable()
36849
+ });
36850
+ /** A spot in CSS pixels, bounded well past any frame. */
36851
+ const offset = number().min(-1e5).max(1e5);
36852
+ const placeSchema = object$1({
36853
+ ref: string$1().min(1).max(1024),
36854
+ hash: string$1().regex(/^[0-9a-f]{64}$/),
36855
+ index: int$1().min(0),
36856
+ spot: object$1({
36857
+ left: offset,
36858
+ top: offset,
36859
+ width: side.optional(),
36860
+ height: side.optional()
36861
+ }).nullable(),
36862
+ /** Back in flow, the sizes to drop, being ones a placement wrote that nothing changed since. */
36863
+ drop: array$1(placedSizeSchema).max(2).optional()
36864
+ });
36865
+ /**
36866
+ * A hand edit of one element, a placed element, and a deleted one, each behind
36867
+ * `requireWriter` and refused on a frame another session holds.
36868
+ *
36869
+ * The edit's body mirrors
36870
+ * `edit`'s flags with the hash required, since the board always holds the
36871
+ * one it rendered, plus a `styles` change the CLI never sends, which writes
36872
+ * several declarations as one step. It writes through `editFrameFile`, which finds the element
36873
+ * again in a frame an agent wrote since from the source `version` kept, and
36874
+ * records the edited element's span as one step. It answers the `edit`
36875
+ * record with the index written and the hash written over. Each refusal the
36876
+ * writer returns answers 409 with its code, `stale-address` among them.
36877
+ *
36878
+ * The insert takes an element kind, never markup, and writes that kind's one
36879
+ * tag into the gap `parent` and `before` name, painted from the project's
36880
+ * tokens through `sheets`, and records it as one step. It answers the frame,
36881
+ * the new element's index, and the hash written. A hash the file no longer
36882
+ * has answers 409 `stale-address` with nothing written, since the gap's
36883
+ * indices name nothing past an agent's write, and a retried insert lands once.
36884
+ * A rectangle or an ellipse takes an optional width and height a drag drew.
36885
+ * An asset names a file under the project's `assets/` and the size it
36886
+ * shows at, and the server picks its tag from the file's kind. A file
36887
+ * outside that folder or not there answers 409 `asset-missing`, and one that
36888
+ * is no image, GIF, SVG, or video `asset-not-placeable`, each writing nothing.
36889
+ *
36890
+ * The remove takes out the element at `index`, with what it holds, from the
36891
+ * bytes `hash` names, and records it as one step whose undo puts it back
36892
+ * under its parent. It answers the frame and the hash written, and refuses a
36893
+ * moved file as `stale-address` the way the insert does.
36894
+ *
36895
+ * The move takes one element by index and the gap it goes into, both read
36896
+ * in the frame as the hash names it, and records it as one step an undo
36897
+ * puts back byte for byte. It answers the element's new index and the hash
36898
+ * written, and refuses as the insert does, with `invalid-container` for a
36899
+ * gap inside the element itself.
36900
+ *
36901
+ * The place takes one element by index and a spot in CSS pixels against its
36902
+ * containing block, or null to put it back in the flow, read in the frame as
36903
+ * the hash names it, with `drop` naming the sizes back in flow takes off. It
36904
+ * writes the element's start tag, and its static parent's first, and records
36905
+ * both as one step, so one undo restores both. It answers the element's
36906
+ * index, the hash written, and the sizes a placement wrote, refuses as the move
36907
+ * does, and refuses `reanchors-descendant` where a positioned parent would
36908
+ * move another element anchored above it.
36909
+ *
36910
+ * Each landed write carries the notes pinned on the frame's elements to the
36911
+ * bytes it wrote, through the writer's remap, so a pin stays on its element.
36912
+ */
36913
+ function editRoutes(root, access, history, version, sheets) {
36914
+ const app = new Hono();
36915
+ /** Carries the frame's notes from `before` to `after`, a write that changed no byte carrying none. */
36916
+ const follow = (frame, before, after, remap) => before === after ? Promise.resolve() : followEdit(notesPath(root, frame.project, frame.page), frame.name, before, after, remap);
36917
+ app.post("/api/frames/edit", requireWriter(access), async (c) => {
36918
+ const body = await parseBody$1(c.req.raw, editSchema$1);
36919
+ const frame = await resolveFrameRef(root, body.ref, { cwd: root });
36920
+ const ref = `${frame.project}/${frame.page}/${frame.name}`;
36921
+ await refuseClaimed(root, [ref], /* @__PURE__ */ new Date());
36922
+ const was = contentHash(await readFile(frame.path)) !== body.hash ? await version?.(ref, body.hash) ?? null : null;
36923
+ const result = editFrameFile(frame.path, {
36924
+ index: body.index,
36925
+ hash: body.hash
36926
+ }, body.change, (hash) => hash === body.hash ? was : null);
36927
+ if (!result.ok) return c.json({
36928
+ ok: false,
36929
+ error: {
36930
+ code: result.reason,
36931
+ message: result.detail,
36932
+ details: {
36933
+ ref,
36934
+ index: body.index,
36935
+ ..."moved" in result ? { moved: result.moved } : {}
36936
+ }
36937
+ }
36938
+ }, 409);
36939
+ if (result.span.before !== result.span.after) {
36940
+ const journal = history.journal();
36941
+ journal.element(frame.path, ref, result.span);
36942
+ history.record({
36943
+ id: journal.id,
36944
+ changes: journal.changes,
36945
+ page: null,
36946
+ frames: [ref]
36947
+ });
36948
+ }
36949
+ await follow(frame, result.from, result.hash, result.remap);
36950
+ const data = {
36951
+ ref,
36952
+ index: result.index,
36953
+ hash: result.hash,
36954
+ from: result.from
36955
+ };
36956
+ return c.json({
36957
+ ok: true,
36958
+ data
36959
+ });
36960
+ });
36961
+ app.post("/api/frames/insert", requireWriter(access), async (c) => {
36962
+ const body = await parseBody$1(c.req.raw, insertSchema);
36963
+ const frame = await resolveFrameRef(root, body.ref, { cwd: root });
36964
+ const ref = `${frame.project}/${frame.page}/${frame.name}`;
36965
+ await refuseClaimed(root, [ref], /* @__PURE__ */ new Date());
36966
+ const tokens = sheets ? readTokenTable(root, sheets(frame.project)).tokens : [];
36967
+ let element;
36968
+ if (body.element.kind !== "asset") element = body.element;
36969
+ else {
35671
36970
  const asset = await resolveAsset(join(root, frame.project), body.element.path);
35672
36971
  if (!asset.ok) return c.json({
35673
36972
  ok: false,
@@ -35708,6 +37007,7 @@ function editRoutes(root, access, history, version, sheets) {
35708
37007
  page: null,
35709
37008
  frames: [ref]
35710
37009
  });
37010
+ await follow(frame, body.hash, result.hash, result.remap);
35711
37011
  const data = {
35712
37012
  ref,
35713
37013
  index: result.index,
@@ -35743,6 +37043,7 @@ function editRoutes(root, access, history, version, sheets) {
35743
37043
  page: null,
35744
37044
  frames: [ref]
35745
37045
  });
37046
+ await follow(frame, body.hash, result.hash, result.remap);
35746
37047
  const data = {
35747
37048
  ref,
35748
37049
  hash: result.hash
@@ -35781,6 +37082,7 @@ function editRoutes(root, access, history, version, sheets) {
35781
37082
  page: null,
35782
37083
  frames: [ref]
35783
37084
  });
37085
+ await follow(frame, body.hash, result.hash, result.remap);
35784
37086
  const data = {
35785
37087
  ref,
35786
37088
  index: result.index,
@@ -35821,6 +37123,7 @@ function editRoutes(root, access, history, version, sheets) {
35821
37123
  frames: [ref]
35822
37124
  });
35823
37125
  }
37126
+ await follow(frame, body.hash, result.hash, result.remap);
35824
37127
  const data = {
35825
37128
  ref,
35826
37129
  index: body.index,
@@ -36564,7 +37867,7 @@ function isElement(node) {
36564
37867
  return "tagName" in node;
36565
37868
  }
36566
37869
  // src/server/routes/frames.ts
36567
- const NOTES_FILE$2 = "notes.json";
37870
+ const NOTES_FILE$1 = "notes.json";
36568
37871
  /** Where the look route serves the board's token sheet, whichever file stands in for it. */
36569
37872
  const BOARD_SHEET_URL = "/frameboard/tokens.css";
36570
37873
  const CONTENT_TYPES$1 = {
@@ -36671,7 +37974,7 @@ async function resolveFile(root, [project, page, ...rest]) {
36671
37974
  }
36672
37975
  }
36673
37976
  function isRecord$1(name) {
36674
- return name === "layout.json" || name === NOTES_FILE$2;
37977
+ return name === "layout.json" || name === NOTES_FILE$1;
36675
37978
  }
36676
37979
  // src/server/routes/look.ts
36677
37980
  const CONTENT_TYPES = {
@@ -36747,46 +38050,6 @@ async function readOrNull(path) {
36747
38050
  return null;
36748
38051
  }
36749
38052
  }
36750
- // src/server/notes/anchor.ts
36751
- /**
36752
- * The anchor for element `index` of a frame, refusing `stale-address` when
36753
- * the file changed since the board rendered it at `renderedAt`, since the
36754
- * index the board counted belongs to the file it showed.
36755
- */
36756
- async function anchorFor(framePath, index, renderedAt) {
36757
- const [bytes, { mtimeMs }] = await Promise.all([readFile(framePath), stat(framePath)]);
36758
- if (new Date(mtimeMs).toISOString() !== renderedAt || index >= parseFrame(bytes.toString("utf8")).elements.length) throw new FrameboardError("stale-address", `The frame changed since the board showed it, so element ${index} may be another one. Pick it again.`, {
36759
- path: framePath,
36760
- index
36761
- });
36762
- return {
36763
- index,
36764
- hash: contentHash(bytes)
36765
- };
36766
- }
36767
- /**
36768
- * The element each anchored note still points at, by note id: its index while
36769
- * the frame file hashes as it did when pinned, else null, being the frame
36770
- * itself. A frame note has no entry.
36771
- */
36772
- async function resolveAnchors(pageDir, notes) {
36773
- const frames = [...new Set(notes.filter((note) => note.anchor).map((note) => note.frame))];
36774
- const hashes = new Map(await Promise.all(frames.map(async (frame) => [frame, await hashOf(join(pageDir, `${frame}${FRAME_EXTENSION}`))])));
36775
- const resolved = {};
36776
- for (const note of notes) {
36777
- if (!note.anchor) continue;
36778
- resolved[note.id] = hashes.get(note.frame) === note.anchor.hash ? note.anchor.index : null;
36779
- }
36780
- return resolved;
36781
- }
36782
- async function hashOf(path) {
36783
- try {
36784
- return contentHash(await readFile(path));
36785
- } catch (error) {
36786
- if (isCode(error, "ENOENT")) return null;
36787
- throw error;
36788
- }
36789
- }
36790
38053
  // src/server/notes/dispatch.ts
36791
38054
  /** The `serve` environment variable holding the command a dispatched note runs. */
36792
38055
  const DISPATCH_ENV = "FRAMEBOARD_DISPATCH";
@@ -36922,290 +38185,6 @@ async function assertStored(pageDir, images) {
36922
38185
  const missing = images.filter((_, index) => found[index] === null);
36923
38186
  if (missing.length > 0) throw new FrameboardError("usage", `The note names images its page does not hold: ${missing.join(", ")}. Upload each one first.`, { missing });
36924
38187
  }
36925
- // src/shared/records/notes.ts
36926
- /** Where a note on one element points, in the edit address's terms. */
36927
- const noteAnchorSchema = looseObject({
36928
- /** The element's `querySelectorAll('*')` index, skipping injected elements. */
36929
- index: int$1().min(0),
36930
- /** The frame file's `contentHash` when the note was pinned. */
36931
- hash: string$1()
36932
- });
36933
- const noteSchema = looseObject({
36934
- /** `n_` and 8 hex characters, unique across the board. */
36935
- id: string$1(),
36936
- /** The page's ordinal on a root note, never reused. A reply carries null. */
36937
- number: int$1().min(1).nullable(),
36938
- /** The frame's name in this page. */
36939
- frame: string$1(),
36940
- /** Null for a note on the whole frame. */
36941
- anchor: noteAnchorSchema.nullable(),
36942
- text: string$1(),
36943
- /** Images saved with the message, relative to its page, as `.notes/<file>`. Absent on a note with none. */
36944
- images: array$1(string$1()).optional(),
36945
- from: _enum$1(["developer", "agent"]),
36946
- /** Who signed it, as git names them, stamped by the server. */
36947
- author: string$1().nullable(),
36948
- /** The agent's session id on an agent reply. */
36949
- session: string$1().nullable(),
36950
- /** The session a root note is sent to. */
36951
- to: string$1().nullable(),
36952
- /** A root note's delivery state. A reply carries `open`. */
36953
- state: _enum$1([
36954
- "open",
36955
- "queued",
36956
- "delivered",
36957
- "done"
36958
- ]),
36959
- /** The root note's id on a reply, else null. */
36960
- thread: string$1().nullable(),
36961
- createdAt: string$1(),
36962
- updatedAt: string$1()
36963
- });
36964
- /** `<project>/<page>/notes.json`. */
36965
- const notesFileSchema = looseObject({
36966
- version: literal(1),
36967
- notes: array$1(noteSchema)
36968
- });
36969
- /** A session following its inbox on the live socket. */
36970
- const listenerSchema = object$1({
36971
- session: string$1(),
36972
- /** What the board shows for it, never used to address it. */
36973
- tag: string$1(),
36974
- since: string$1()
36975
- });
36976
- /**
36977
- * The one line a follower prints per note. It opens with `frameboard note`,
36978
- * which the skill tells the agent to act on, and names the verbs that answer
36979
- * it. Text is collapsed onto one line, stripped of control characters so it
36980
- * cannot drive the terminal, and cut at 200 characters. Image paths sit
36981
- * between the text and the hints, so the prefix and the hints never move.
36982
- */
36983
- function noteLine({ id, ref, element, text, images = [] }) {
36984
- const where = element === null ? ref : `${ref} element ${element}`;
36985
- const attached = images.length === 0 ? "" : ` (images: ${images.map(flatten).join(", ")})`;
36986
- return `frameboard note ${id} on ${where}: ${collapse(text)}${attached} (reply: frameboard notes reply ${id} "<text>", close: frameboard notes done ${id})`;
36987
- }
36988
- function collapse(text) {
36989
- const flat = flatten(text);
36990
- return flat.length > 200 ? `${flat.slice(0, 200)}...` : flat;
36991
- }
36992
- function flatten(text) {
36993
- return text.replace(/\s+/g, " ").replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim();
36994
- }
36995
- // src/server/notes/store.ts
36996
- const NOTES_FILE$1 = "notes.json";
36997
- const notesSpec = {
36998
- schema: notesFileSchema,
36999
- invalidCode: "notes-invalid",
37000
- empty: () => ({
37001
- version: 1,
37002
- notes: []
37003
- })
37004
- };
37005
- /** `n_` and 8 random hex characters. */
37006
- function newNoteId() {
37007
- return `n_${randomBytes(4).toString("hex")}`;
37008
- }
37009
- function notesPath(root, project, page) {
37010
- return join(root, project, page, NOTES_FILE$1);
37011
- }
37012
- function readNotes(path) {
37013
- return readRecord(path, notesSpec);
37014
- }
37015
- /** Reads, changes, and writes a page's notes under its lock, refusing a file that does not parse. */
37016
- function updateNotes(path, change) {
37017
- return updateRecord(path, notesSpec, change);
37018
- }
37019
- /** Every page in the board, as the place its notes file sits. */
37020
- async function listPageNotes(root) {
37021
- const projects = await listProjects(root);
37022
- return (await Promise.all(projects.map(async (project) => (await listPageFolders(join(root, project))).map((page) => ({
37023
- project,
37024
- page,
37025
- path: notesPath(root, project, page)
37026
- }))))).flat();
37027
- }
37028
- /**
37029
- * The page holding a note id, scanning every page of the board. A page whose
37030
- * file does not parse cannot be read for the id, so when no other page holds
37031
- * it the first such page's `notes-invalid` is thrown rather than a missing note.
37032
- */
37033
- async function findNote(root, id) {
37034
- let unreadable;
37035
- for (const place of await listPageNotes(root)) {
37036
- let file;
37037
- try {
37038
- file = await readNotes(place.path);
37039
- } catch (error) {
37040
- if (!(error instanceof FrameboardError)) throw error;
37041
- unreadable ??= error;
37042
- continue;
37043
- }
37044
- const note = file.notes.find((candidate) => candidate.id === id);
37045
- if (note) return {
37046
- ...place,
37047
- file,
37048
- note
37049
- };
37050
- }
37051
- if (unreadable) throw unreadable;
37052
- throw new FrameboardError("note-not-found", `No note ${id} in this board.`, { id });
37053
- }
37054
- /** The root of the thread a note belongs to, being the note itself when it is one. */
37055
- function rootOf(file, id) {
37056
- const note = file.notes.find((candidate) => candidate.id === id);
37057
- const root = note?.thread ? file.notes.find((candidate) => candidate.id === note.thread) : note;
37058
- if (!root) throw new FrameboardError("note-not-found", `No note ${id} in this page.`, { id });
37059
- return root;
37060
- }
37061
- /** Adds a root note numbered one past the page's highest, so a number is never reused. */
37062
- function addRoot(file, fields, { now, id }) {
37063
- const number = Math.max(0, ...file.notes.map((note) => note.number ?? 0)) + 1;
37064
- const at = now.toISOString();
37065
- const note = {
37066
- id,
37067
- number,
37068
- frame: fields.frame,
37069
- anchor: fields.anchor,
37070
- text: fields.text,
37071
- ...withImages(fields.images),
37072
- from: "developer",
37073
- author: fields.author,
37074
- session: null,
37075
- to: fields.to,
37076
- state: fields.to === null ? "open" : "queued",
37077
- thread: null,
37078
- createdAt: at,
37079
- updatedAt: at
37080
- };
37081
- return {
37082
- ...file,
37083
- notes: [...file.notes, note]
37084
- };
37085
- }
37086
- /** Appends a reply to the thread `to` belongs to, reopening nothing a reply does not name. */
37087
- function addReply(file, replyTo, fields, { now, id }) {
37088
- const root = rootOf(file, replyTo);
37089
- const at = now.toISOString();
37090
- const reply = {
37091
- id,
37092
- number: null,
37093
- frame: root.frame,
37094
- anchor: root.anchor,
37095
- text: fields.text,
37096
- ...withImages(fields.images),
37097
- from: fields.from,
37098
- author: fields.author,
37099
- session: fields.session,
37100
- to: null,
37101
- state: "open",
37102
- thread: root.id,
37103
- createdAt: at,
37104
- updatedAt: at
37105
- };
37106
- const notes = file.notes.map((note) => note.id === root.id && fields.to !== void 0 ? {
37107
- ...note,
37108
- to: fields.to,
37109
- state: "queued",
37110
- updatedAt: at
37111
- } : note);
37112
- return {
37113
- ...file,
37114
- notes: [...notes, reply]
37115
- };
37116
- }
37117
- /** A note with no images carries no key, so it reads as one written before images. */
37118
- function withImages(images) {
37119
- return images === void 0 || images.length === 0 ? {} : { images };
37120
- }
37121
- /** Sets the state of the thread `id` belongs to, and its addressee when one is given. */
37122
- function setState(file, id, state, now, to) {
37123
- const root = rootOf(file, id);
37124
- return {
37125
- ...file,
37126
- notes: file.notes.map((note) => note.id === root.id ? {
37127
- ...note,
37128
- state,
37129
- ...to === void 0 ? {} : { to },
37130
- updatedAt: now.toISOString()
37131
- } : note)
37132
- };
37133
- }
37134
- /** Takes one message out, for a write whose send failed after it landed. */
37135
- function removeNote(file, id) {
37136
- return {
37137
- ...file,
37138
- notes: file.notes.filter((note) => note.id !== id)
37139
- };
37140
- }
37141
- /** A page's notes as the board draws them, an unreadable file reading as none. */
37142
- async function pageView(root, place) {
37143
- let file;
37144
- try {
37145
- file = await readNotes(place.path);
37146
- } catch (error) {
37147
- if (error instanceof FrameboardError) return [];
37148
- throw error;
37149
- }
37150
- const elements = await resolveAnchors(join(root, place.project, place.page), file.notes);
37151
- return file.notes.map((note) => ({
37152
- ...note,
37153
- element: elements[note.id] ?? null
37154
- }));
37155
- }
37156
- /** Every page holding notes, by `<project>/<page>` ref, as the board draws them. */
37157
- async function boardView(root) {
37158
- const pages = await Promise.all((await listPageNotes(root)).map(async (place) => [`${place.project}/${place.page}`, await pageView(root, place)]));
37159
- return Object.fromEntries(pages.filter(([, notes]) => notes.length > 0));
37160
- }
37161
- /**
37162
- * The root notes queued to a session, read from disk, each with the line its
37163
- * follower prints, carrying the thread's newest developer message.
37164
- */
37165
- async function queuedFor(root, session) {
37166
- const deliveries = [];
37167
- for (const place of await listPageNotes(root)) {
37168
- const notes = await pageView(root, place);
37169
- for (const note of notes) {
37170
- if (note.thread !== null || note.state !== "queued") continue;
37171
- if (note.to !== session) continue;
37172
- deliveries.push(toDelivery(place, notes, note));
37173
- }
37174
- }
37175
- return deliveries;
37176
- }
37177
- /** A root note as a follower would receive it, read from its page whatever its state. */
37178
- async function deliveryOf(root, place, rootId) {
37179
- const notes = await pageView(root, place);
37180
- const note = notes.find((each) => each.id === rootId && each.thread === null);
37181
- if (!note) throw new FrameboardError("note-not-found", `No note ${rootId} in this page.`, { id: rootId });
37182
- return toDelivery(place, notes, note);
37183
- }
37184
- function toDelivery(place, notes, note) {
37185
- const ref = `${place.project}/${place.page}/${note.frame}`;
37186
- const newest = notes.filter((each) => (each.id === note.id || each.thread === note.id) && each.from === "developer").at(-1);
37187
- const { element, ...stored } = note;
37188
- const message = newest ?? note;
37189
- const pageDir = dirname(place.path);
37190
- return {
37191
- note: stored,
37192
- ref,
37193
- line: noteLine({
37194
- id: note.id,
37195
- ref,
37196
- element,
37197
- text: message.text,
37198
- images: message.images?.map((image) => join(pageDir, image))
37199
- })
37200
- };
37201
- }
37202
- /** Marks a root note delivered, while it is still queued to that session. */
37203
- async function markDelivered(root, id, session, now) {
37204
- await updateNotes((await findNote(root, id)).path, (file) => {
37205
- const note = file.notes.find((each) => each.id === id);
37206
- return note?.state === "queued" && note.to === session ? setState(file, id, "delivered", now) : file;
37207
- });
37208
- }
37209
38188
  // src/server/routes/notes.ts
37210
38189
  const STATUS$1 = {
37211
38190
  usage: 400,
@@ -37841,12 +38820,12 @@ async function writeStarterSheet(root, ref, look, { tokens, journal } = {}) {
37841
38820
  const project = await resolveProject(root, ref);
37842
38821
  const sheets = tokenSheetPaths(root, project.name, tokens);
37843
38822
  const existing = sheets.project ?? sheets.board;
37844
- if (existing) refuse$1(project.name, existing);
38823
+ if (existing) refuse(project.name, existing);
37845
38824
  const path = join(project.path, TOKEN_FILE);
37846
38825
  try {
37847
38826
  await writeFile(path, starterSheet(look), { flag: "wx" });
37848
38827
  } catch (error) {
37849
- if (isCode(error, "EEXIST")) refuse$1(project.name, path);
38828
+ if (isCode(error, "EEXIST")) refuse(project.name, path);
37850
38829
  throw error;
37851
38830
  }
37852
38831
  await journal?.created(path);
@@ -37856,7 +38835,7 @@ async function writeStarterSheet(root, ref, look, { tokens, journal } = {}) {
37856
38835
  ...look
37857
38836
  };
37858
38837
  }
37859
- function refuse$1(project, sheet) {
38838
+ function refuse(project, sheet) {
37860
38839
  throw new FrameboardError("tokens-exist", `${project} already renders with the token sheet ${sheet}, so no starter sheet was written.`, {
37861
38840
  project,
37862
38841
  sheet
@@ -38410,228 +39389,13 @@ function themeOf(value, usage) {
38410
39389
  if (!isTheme$1(value)) throw new FrameboardError("usage", usage, { theme: value ?? "" });
38411
39390
  return value;
38412
39391
  }
38413
- // src/server/look/token-edit.ts
38414
- const NAME = /^--[\w-]+$/;
38415
- const UNSAFE_VALUE = /[;{}\n\r]|\/\*/;
38416
- /**
38417
- * The project sheet with `edit` applied, every byte outside the token's
38418
- * declarations left as it stood. `board` is the token's declarations in the
38419
- * board sheet. A one-theme edit keeps the other theme rendering as it did,
38420
- * pinning its old value under that theme's rule when the new declaration
38421
- * would reach it, since a project `:root` ties a board dark rule on
38422
- * specificity and wins by coming later. Refuses `invalid-edit` for a name or
38423
- * value that is not one declaration, a reset of a token the board does not
38424
- * set, and a sheet that does not parse.
38425
- */
38426
- function editTokenCss(css, board, edit) {
38427
- if (!NAME.test(edit.name)) refuse(`${edit.name} is not a custom property.`);
38428
- const root = parseSheet(css);
38429
- const own = sidesIn(root, edit.name);
38430
- if ("reset" in edit) {
38431
- if (Object.keys(board).length === 0 || Object.keys(own).length === 0) refuse(`${edit.name} has no board value under the project's, so there is nothing to reset to.`);
38432
- return writeSides(root, edit.name, {});
38433
- }
38434
- const value = edit.value.trim();
38435
- if (value === "" || UNSAFE_VALUE.test(edit.value)) refuse(`${JSON.stringify(edit.value)} is not one declaration value.`);
38436
- const next = { ...own };
38437
- if (edit.side === "dark") next.dark = value;
38438
- else if (edit.side === "light") {
38439
- if (next.light !== void 0) next.light = value;
38440
- else next.base = value;
38441
- const darkWas = shown(board, own).dark;
38442
- if (shown(board, next).dark !== darkWas && darkWas !== void 0) next.dark = darkWas;
38443
- } else {
38444
- next.base = value;
38445
- if (next.light !== void 0) next.light = value;
38446
- if (next.dark !== void 0) next.dark = value;
38447
- }
38448
- const written = writeSides(root, edit.name, next);
38449
- let readBack;
38450
- try {
38451
- readBack = sidesIn(postcss_default.parse(written), edit.name);
38452
- } catch {
38453
- readBack = void 0;
38454
- }
38455
- if (!isDeepStrictEqual(readBack, next)) refuse(`${JSON.stringify(edit.value)} would leave the sheet unreadable.`);
38456
- return written;
38457
- }
38458
- /**
38459
- * The sheet with the token's declarations made exactly `sides`, as undo
38460
- * restores them. A side present replaces the last declaration on that side,
38461
- * or is added to that side's rule, and a side absent takes out every
38462
- * declaration on it, dropping a rule it leaves empty.
38463
- */
38464
- function setTokenSides(css, name, sides) {
38465
- return writeSides(parseSheet(css), name, sides);
38466
- }
38467
- /** The token's declarations in a sheet, the last on each side winning, as the table reads them. */
38468
- function tokenSides(css, name) {
38469
- return sidesIn(parseSheet(css), name);
38470
- }
38471
- /**
38472
- * Writes the project sheet at `path` through a temporary file and a rename,
38473
- * reading the sheet again just before the rename and leaving it as it is
38474
- * when its hash is no longer `hash`. A null `hash` means the sheet did not
38475
- * exist, so it is created only while none does. Takes no lock, since an
38476
- * agent's raw write never takes one.
38477
- */
38478
- function writeTokenSheet(path, hash, css) {
38479
- if (hash === null) try {
38480
- writeFileSync(path, css, { flag: "wx" });
38481
- return "created";
38482
- } catch (error) {
38483
- if (isCode(error, "EEXIST")) return "stale";
38484
- throw error;
38485
- }
38486
- const temp = join(dirname(path), `.${basename(path)}.${process.pid}.tmp`);
38487
- writeFileSync(temp, css);
38488
- if (hashOrNull(path) !== hash) {
38489
- rmSync(temp, { force: true });
38490
- return "stale";
38491
- }
38492
- renameSync(temp, path);
38493
- return "written";
38494
- }
38495
- /** A sheet's content hash, or null when it does not exist. */
38496
- function hashOrNull(path) {
38497
- try {
38498
- return contentHash(readFileSync(path));
38499
- } catch (error) {
38500
- if (isCode(error, "ENOENT")) return null;
38501
- throw error;
38502
- }
38503
- }
38504
- /** The light and dark values a token renders with, the project's sides over the board's. */
38505
- function shown(board, project) {
38506
- return {
38507
- light: project.light ?? project.base ?? board.light ?? board.base,
38508
- dark: project.dark ?? project.base ?? board.dark ?? board.base
38509
- };
38510
- }
38511
- function parseSheet(css) {
38512
- try {
38513
- return postcss_default.parse(css);
38514
- } catch (error) {
38515
- return refuse(`The project token sheet does not parse: ${error instanceof postcss_default.CssSyntaxError ? error.reason : String(error)}.`);
38516
- }
38517
- }
38518
- /** Every declaration of `name` in a rule the table reads, by side, in sheet order. */
38519
- function declsIn(root, name) {
38520
- const found = {
38521
- base: [],
38522
- light: [],
38523
- dark: []
38524
- };
38525
- root.walkRules((rule) => {
38526
- const side = sideOf(rule);
38527
- if (!side) return;
38528
- rule.each((node) => {
38529
- if (node.type === "decl" && node.prop === name) found[side].push(node);
38530
- });
38531
- });
38532
- return found;
38533
- }
38534
- function sidesIn(root, name) {
38535
- const sides = {};
38536
- for (const [side, decls] of Object.entries(declsIn(root, name))) {
38537
- const last = decls.at(-1);
38538
- if (last) sides[side] = last.value.trim();
38539
- }
38540
- return sides;
38541
- }
38542
- function writeSides(root, name, sides) {
38543
- const found = declsIn(root, name);
38544
- for (const side of [
38545
- "dark",
38546
- "base",
38547
- "light"
38548
- ]) {
38549
- const value = sides[side];
38550
- const decls = found[side];
38551
- const last = decls.at(-1);
38552
- if (value === void 0) for (const decl of decls) {
38553
- const rule = decl.parent;
38554
- decl.remove();
38555
- if (rule && rule.nodes?.length === 0) rule.remove();
38556
- }
38557
- else if (last) {
38558
- if (last.value.trim() !== value) last.value = value;
38559
- } else ruleFor(root, side, side === "dark" ? void 0 : firstTopLevel(root, declsIn(root, name).dark)).append(postcss_default.decl({
38560
- prop: name,
38561
- value,
38562
- raws: declRaws(root)
38563
- }));
38564
- }
38565
- return root.toString();
38566
- }
38567
- /** The earliest top-level node holding any of `decls`, undefined for none. */
38568
- function firstTopLevel(root, decls) {
38569
- let first;
38570
- for (const decl of decls) {
38571
- let node = decl;
38572
- while (node.parent && node.parent !== root) node = node.parent;
38573
- const top = node;
38574
- if (!first || root.index(top) < root.index(first)) first = top;
38575
- }
38576
- return first;
38577
- }
38578
- /** The spacing of the sheet's first declaration, so an added one reads like its neighbors. */
38579
- function declRaws(root) {
38580
- let sample;
38581
- root.walkDecls((decl) => {
38582
- sample = decl;
38583
- return false;
38584
- });
38585
- return {
38586
- before: sample?.raws.before ?? "\n ",
38587
- between: sample?.raws.between ?? ": "
38588
- };
38589
- }
38590
- const NEW_SELECTOR = {
38591
- base: ":root",
38592
- light: "[data-theme='light']",
38593
- dark: "[data-theme='dark']"
38594
- };
38595
- /**
38596
- * The top-level rule a new declaration on `side` goes into: the last such
38597
- * rule outside any at-rule, else a new one. A new `:root` or light rule goes
38598
- * ahead of every other rule, so a dark rule that ties it on specificity
38599
- * still comes later and wins in dark, and a new dark rule goes last. With
38600
- * `before`, the token's first dark declaration, a rule must come ahead of
38601
- * it, and a new one goes just before it when none does.
38602
- */
38603
- function ruleFor(root, side, before) {
38604
- const last = root.nodes.filter((node) => node.type === "rule" && sideOf(node) === side && (!before || root.index(node) < root.index(before))).at(-1);
38605
- if (last) return last;
38606
- const rule = postcss_default.rule({
38607
- selector: NEW_SELECTOR[side],
38608
- raws: {
38609
- between: " ",
38610
- semicolon: true,
38611
- after: "\n"
38612
- }
38613
- });
38614
- const first = before ?? root.nodes.find((node) => node.type === "rule");
38615
- if (side !== "dark" && first) {
38616
- const spacing = first.raws.before ?? "";
38617
- root.insertBefore(first, rule);
38618
- rule.raws.before = spacing;
38619
- first.raws.before = "\n\n";
38620
- } else {
38621
- rule.raws.before = root.nodes.length > 0 ? "\n\n" : "";
38622
- root.append(rule);
38623
- if (!root.raws.after?.includes("\n")) root.raws.after = "\n";
38624
- }
38625
- return rule;
38626
- }
38627
- function refuse(message) {
38628
- throw new FrameboardError("invalid-edit", message);
38629
- }
38630
39392
  // src/server/routes/tokens.ts
38631
39393
  const common = {
38632
39394
  project: string$1().min(1).max(256),
38633
39395
  name: string$1().min(1).max(256),
38634
- /** The project sheet's hash as the tab read it, null when it had none. */
39396
+ /** The sheet the edit writes, the project's own when absent. */
39397
+ sheet: _enum$1(["project", "board"]).default("project"),
39398
+ /** That sheet's hash as the tab read it, null when it had none. */
38635
39399
  hash: string$1().regex(/^[0-9a-f]{64}$/).nullable()
38636
39400
  };
38637
39401
  const editSchema = union([object$1({
@@ -38649,15 +39413,19 @@ const editSchema = union([object$1({
38649
39413
  /**
38650
39414
  * The Theme tab's token write, behind `requireWriter`. `POST
38651
39415
  * /api/tokens/edit` sets one token the project's sheets list on one theme or
38652
- * both, or resets a token the project overrides back to the board's value,
38653
- * writing the project's `tokens.css` alone and creating it when the project
38654
- * has none. The board sheet and a `--tokens` sheet are never written. A
38655
- * `hash` the project sheet no longer has, or a sheet created since the tab
38656
- * read none, answers 409 `stale-tokens` with nothing written, which also
38657
- * lands a retried edit once. A name the sheets do not list, a value that is
38658
- * not one declaration, a reset with no board value, and a project sheet that
38659
- * does not parse answer 409 `invalid-edit`. A landed edit records one step
38660
- * and answers the token's values after it with the hash written.
39416
+ * both in the sheet `sheet` names. `project`, the default, writes the
39417
+ * project's `tokens.css`, creating it when the project has none, and a reset
39418
+ * there takes the project's override back to the board's value. `board`
39419
+ * writes the board's sheet, which every project without an override follows,
39420
+ * for a token that sheet already sets. A `hash` the named sheet no longer
39421
+ * has, or a project sheet created since the tab read none, answers 409
39422
+ * `stale-tokens` with nothing written, which also lands a retried edit once.
39423
+ * A name the sheets do not list, a value that is not one declaration, a
39424
+ * reset with no board value, and a sheet that does not parse answer 409
39425
+ * `invalid-edit`, as does a board edit that is a reset, names a token the
39426
+ * board sheet does not set, or meets a `--tokens` sheet outside the board
39427
+ * folder, which belongs to whatever handed it over. A landed edit records
39428
+ * one step and answers the token's values after it with the hash written.
38661
39429
  */
38662
39430
  function tokenRoutes(root, access, history, look) {
38663
39431
  const app = new Hono();
@@ -38665,9 +39433,14 @@ function tokenRoutes(root, access, history, look) {
38665
39433
  const body = await parseBody$1(c.req.raw, editSchema);
38666
39434
  const project = await resolveProject(root, body.project);
38667
39435
  const sheets = look.sheets(project.name);
38668
- const path = join(project.path, TOKEN_FILE);
38669
39436
  if (!readTokenTable(root, sheets).tokens.some((row) => row.name === body.name)) throw new FrameboardError("invalid-edit", `${project.name}'s token sheets set no ${body.name}.`, { name: body.name });
38670
- const css = readProjectSheet(path, body.hash, project.name);
39437
+ const target = body.sheet === "board" ? boardTarget(root, sheets.board, "reset" in body) : {
39438
+ path: join(project.path, TOKEN_FILE),
39439
+ under: boardSides(sheets.board, body.name)
39440
+ };
39441
+ const refuseStale = () => stale(project.name, body.sheet);
39442
+ const css = readSheet(target.path, body.hash, refuseStale);
39443
+ if (body.sheet === "board" && Object.keys(tokenSides(css, body.name)).length === 0) throw new FrameboardError("invalid-edit", `The board token sheet sets no ${body.name}, so it has no board value to change.`, { name: body.name });
38671
39444
  const edit = "reset" in body ? {
38672
39445
  name: body.name,
38673
39446
  reset: true
@@ -38676,12 +39449,12 @@ function tokenRoutes(root, access, history, look) {
38676
39449
  side: body.side,
38677
39450
  value: body.value
38678
39451
  };
38679
- const written = editTokenCss(css, boardSides(sheets.board, body.name), edit);
38680
- const outcome = writeTokenSheet(path, body.hash, written);
38681
- if (outcome === "stale") stale(project.name);
39452
+ const written = editTokenCss(css, target.under, edit);
39453
+ const outcome = writeTokenSheet(target.path, body.hash, written);
39454
+ if (outcome === "stale") refuseStale();
38682
39455
  const journal = history.journal();
38683
- if (outcome === "created") await journal.created(path);
38684
- else journal.token(path, body.name, tokenSides(css, body.name), tokenSides(written, body.name));
39456
+ if (outcome === "created") await journal.created(target.path);
39457
+ else journal.token(target.path, body.name, tokenSides(css, body.name), tokenSides(written, body.name));
38685
39458
  history.record({
38686
39459
  id: journal.id,
38687
39460
  changes: journal.changes,
@@ -38695,6 +39468,7 @@ function tokenRoutes(root, access, history, look) {
38695
39468
  light: row?.light ?? null,
38696
39469
  dark: row?.dark ?? null,
38697
39470
  hash: contentHash(written),
39471
+ sheet: body.sheet,
38698
39472
  created: outcome === "created"
38699
39473
  };
38700
39474
  return c.json({
@@ -38705,14 +39479,25 @@ function tokenRoutes(root, access, history, look) {
38705
39479
  app.onError(answerRefusal);
38706
39480
  return app;
38707
39481
  }
38708
- /** The project sheet's text as `hash` names it, empty for a null hash, refusing a sheet that moved since. */
38709
- function readProjectSheet(path, hash, project) {
39482
+ /** The board sheet as an edit target, refusing a reset, a board with no sheet, and a sheet outside the board folder. */
39483
+ function boardTarget(root, board, reset) {
39484
+ if (reset) throw new FrameboardError("invalid-edit", "A board token has no value under it to reset to.");
39485
+ if (!board) throw new FrameboardError("invalid-edit", "The board has no token sheet.");
39486
+ const inside = relative(root, board);
39487
+ if (inside.startsWith("..") || isAbsolute(inside)) throw new FrameboardError("invalid-edit", `${board} sits outside the board folder, so it belongs to whatever handed it over and stays read-only here.`, { path: board });
39488
+ return {
39489
+ path: board,
39490
+ under: {}
39491
+ };
39492
+ }
39493
+ /** The sheet's text as `hash` names it, empty for a null hash, refusing a sheet that moved since. */
39494
+ function readSheet(path, hash, refuseStale) {
38710
39495
  const now = hashOrNull(path);
38711
- if (now !== hash) stale(project);
39496
+ if (now !== hash) refuseStale();
38712
39497
  if (now === null) return "";
38713
39498
  const bytes = readFileSync(path);
38714
39499
  const text = bytes.toString("utf8");
38715
- if (!Buffer.from(text, "utf8").equals(bytes)) throw new FrameboardError("invalid-edit", "The project token sheet is not UTF-8, so it was left as it is.");
39500
+ if (!Buffer.from(text, "utf8").equals(bytes)) throw new FrameboardError("invalid-edit", "The token sheet is not UTF-8, so it was left as it is.");
38716
39501
  return text;
38717
39502
  }
38718
39503
  /** The token's declarations in the board sheet, none when it has no sheet or one that does not parse. */
@@ -38725,8 +39510,11 @@ function boardSides(board, name) {
38725
39510
  throw error;
38726
39511
  }
38727
39512
  }
38728
- function stale(project) {
38729
- throw new FrameboardError("stale-tokens", `${project}'s token sheet changed since the Theme tab read it, so nothing was written.`, { project });
39513
+ function stale(project, sheet) {
39514
+ throw new FrameboardError("stale-tokens", `${sheet === "board" ? "The board" : `${project}'s`} token sheet changed since the Theme tab read it, so nothing was written.`, {
39515
+ project,
39516
+ sheet
39517
+ });
38730
39518
  }
38731
39519
  // src/server/app.ts
38732
39520
  const LOOPBACK_NAMES = /* @__PURE__ */ new Set(["127.0.0.1", "localhost"]);
@@ -38751,7 +39539,7 @@ function boardHostGuard(port) {
38751
39539
  await next();
38752
39540
  };
38753
39541
  }
38754
- function createApp({ clientDir, root, port, actions, tickets, openRoute, renderFrame, facesDir, tokens, delivery, dispatch, history, selection, checks, thumbnails, measure, frameVersion, settledVersion, assetUsage }) {
39542
+ function createApp({ clientDir, root, port, actions, tickets, openRoute, renderFrame, clipboard = null, facesDir, tokens, delivery, dispatch, history, selection, checks, thumbnails, measure, frameVersion, settledVersion, assetUsage }) {
38755
39543
  const app = new Hono();
38756
39544
  const given = tokens ?? null;
38757
39545
  app.use("*", async (c, next) => {
@@ -38767,7 +39555,8 @@ function createApp({ clientDir, root, port, actions, tickets, openRoute, renderF
38767
39555
  app.get("/api/health", (c) => c.json({
38768
39556
  version,
38769
39557
  root,
38770
- tokens: given
39558
+ tokens: given,
39559
+ clipboard: clipboard?.backend ?? null
38771
39560
  }));
38772
39561
  app.route("/", accessRoutes(actions.access, tickets, { openRoute }));
38773
39562
  app.route("/", apiRoutes(root, actions, frames.look, history));
@@ -38780,6 +39569,7 @@ function createApp({ clientDir, root, port, actions, tickets, openRoute, renderF
38780
39569
  app.route("/", tokenRoutes(root, actions.access, history, frames.look));
38781
39570
  app.route("/", editRoutes(root, actions.access, history, settledVersion, frames.look.sheets));
38782
39571
  app.route("/", pngRoutes(root, renderFrame));
39572
+ app.route("/", clipboardRoutes(root, actions.access, renderFrame, clipboard));
38783
39573
  if (checks) app.route("/", checkRoutes(actions.access, checks));
38784
39574
  if (thumbnails) app.route("/", thumbnailRoutes(root, thumbnails));
38785
39575
  app.route("/", frames.routes);
@@ -41457,7 +42247,7 @@ function contentFormat() {
41457
42247
  `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.`,
41458
42248
  `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.`,
41459
42249
  `A frame is any *${FRAME_EXTENSION} file directly in a page, named by its stem.`,
41460
- `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.`,
42250
+ `A page's notes sit in its ${NOTES_FILE$2}, 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.`,
41461
42251
  `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}.`,
41462
42252
  `Dot-named folders, *${LOCK_SUFFIX} files, and *${TEMP_SUFFIX} files belong to Frameboard and are never content.`
41463
42253
  ],
@@ -41624,7 +42414,8 @@ function registerEdit(program, context) {
41624
42414
  const { io } = context;
41625
42415
  act(addVerb(program, "edit", "Set one inline style declaration, attribute, or text on one element of a frame, leaving every other byte", { project: true }).argument("<frame-ref>", "a frame ref, <page>/<frame> or <project>/<page>/<frame>, or a path to its .html file").requiredOption("--index <n>", "the element's index in document order", parseInteger(0)).option("--hash <hex>", "the frame hash the index was read from, refused once the file differs", parseHash).option("--style <property=value>", "set one declaration, or drop it with an empty value").option("--attr <name=value>", "set one attribute").option("--text <value>", "replace the text of an element holding text alone"), context, async ([ref = ""], options) => {
41626
42416
  const change = changeOf(options);
41627
- const frame = await resolveFrameRef(await boardOf(options, io), ref, {
42417
+ const root = await boardOf(options, io);
42418
+ const frame = await resolveFrameRef(root, ref, {
41628
42419
  project: options.project,
41629
42420
  cwd: io.cwd
41630
42421
  });
@@ -41637,6 +42428,7 @@ function registerEdit(program, context) {
41637
42428
  ref: frameRef,
41638
42429
  index: options.index
41639
42430
  });
42431
+ if (result.hash !== result.from) await followEdit(notesPath(root, frame.project, frame.page), frame.name, result.from, result.hash, result.remap);
41640
42432
  return {
41641
42433
  data: {
41642
42434
  ref: frameRef,
@@ -41676,7 +42468,7 @@ function registerEditing(program, context) {
41676
42468
  const now = /* @__PURE__ */ new Date();
41677
42469
  if (options.release) {
41678
42470
  const session = sessionOf(options.session);
41679
- const released = await release(root, session, ref ? await canonicalRef(root, ref, options, io.cwd) : void 0, now);
42471
+ const released = await release$1(root, session, ref ? await canonicalRef(root, ref, options, io.cwd) : void 0, now);
41680
42472
  return {
41681
42473
  data: { released },
41682
42474
  human: released.length === 0 ? `${session} held no claim to release` : `Released ${released.map((each) => each.frame).join(", ")}`
@@ -45640,7 +46432,7 @@ function registerNotes(program, context) {
45640
46432
  const pageDir = join(root, place.project, place.page);
45641
46433
  const elements = await resolveAnchors(pageDir, kept);
45642
46434
  listed.push(...kept.map((note) => ({
45643
- ...note,
46435
+ ...forAgent(note),
45644
46436
  ref: `${place.project}/${place.page}/${note.frame}`,
45645
46437
  element: elements[note.id] ?? null,
45646
46438
  ...note.images?.length ? { imagePaths: note.images.map((image) => join(pageDir, image)) } : {}
@@ -45664,7 +46456,7 @@ function registerNotes(program, context) {
45664
46456
  id: replyId
45665
46457
  }))).notes.find((note) => note.id === replyId);
45666
46458
  return {
45667
- data: { note: reply },
46459
+ data: { note: reply && forAgent(reply) },
45668
46460
  human: `Replied to ${reply?.thread ?? id} on ${found.project}/${found.page}/${found.note.frame}`
45669
46461
  };
45670
46462
  });
@@ -45672,8 +46464,9 @@ function registerNotes(program, context) {
45672
46464
  const found = await noteIn(await boardOf(options, io), id, options.project);
45673
46465
  const file = await updateNotes(found.path, (current) => setState(current, id, "done", /* @__PURE__ */ new Date()));
45674
46466
  const rootId = found.note.thread ?? found.note.id;
46467
+ const closed = file.notes.find((note) => note.id === rootId);
45675
46468
  return {
45676
- data: { note: file.notes.find((note) => note.id === rootId) },
46469
+ data: { note: closed && forAgent(closed) },
45677
46470
  human: `Closed ${rootId}`
45678
46471
  };
45679
46472
  });
@@ -46413,507 +47206,6 @@ function createClaimsPush(root, { broadcast, inTurn, now = () => /* @__PURE__ */
46413
47206
  }
46414
47207
  };
46415
47208
  }
46416
- // src/server/history/trash.ts
46417
- const TRASH_FOLDER = "trash";
46418
- /**
46419
- * Where the `index`th path a step takes out waits. The trash sits in `.run/`
46420
- * inside the board root, so taking a path out is a rename on one volume, and
46421
- * the watcher and scanner already skip the dot folder.
46422
- */
46423
- function trashSlot(root, step, index) {
46424
- return join(root, RUN_FOLDER, TRASH_FOLDER, String(step), String(index));
46425
- }
46426
- async function takeOut(path, slot) {
46427
- await mkdir(dirname(slot), { recursive: true });
46428
- await rename(path, slot);
46429
- }
46430
- /** Emptied when the server starts and stops, since the history it serves lives in memory. */
46431
- async function emptyTrash(root) {
46432
- await rm(join(root, RUN_FOLDER, TRASH_FOLDER), {
46433
- recursive: true,
46434
- force: true
46435
- });
46436
- }
46437
- // src/server/history/changes.ts
46438
- /** The records a change writes, whose locks are held while it is checked and written. */
46439
- function lockPaths(change) {
46440
- if (change.kind === "entry" || change.kind === "section") return [change.layout];
46441
- if (change.kind === "pages") return [change.file];
46442
- return [];
46443
- }
46444
- /**
46445
- * Whether the board still stands as `side` of the change left it, read
46446
- * under the record's lock. A change that no longer holds was overtaken, and
46447
- * so was one whose record an agent left unreadable, since writing it back
46448
- * would overwrite that file and keeping the step would block every older one.
46449
- */
46450
- async function holds(change, side) {
46451
- try {
46452
- return await reads(change, side);
46453
- } catch (error) {
46454
- if (error instanceof FrameboardError && UNREADABLE.has(error.code)) return false;
46455
- throw error;
46456
- }
46457
- }
46458
- const UNREADABLE = /* @__PURE__ */ new Set(["layout-invalid", "project-file-invalid"]);
46459
- async function reads(change, side) {
46460
- switch (change.kind) {
46461
- case "entry": {
46462
- const stored = (await readRecord(change.layout, layoutSpec)).frames[change.frame];
46463
- return isDeepStrictEqual(stored, withMeasured(change[side], stored));
46464
- }
46465
- case "section": {
46466
- const file = await readRecord(change.layout, layoutSpec);
46467
- return isDeepStrictEqual(file.sections?.[change.section], change[side]);
46468
- }
46469
- case "pages": {
46470
- const file = await readRecord(change.file, {
46471
- ...projectSpec,
46472
- empty: emptyProject
46473
- });
46474
- return isDeepStrictEqual(file.pages, change[side]);
46475
- }
46476
- case "moved": {
46477
- const [present, absent] = side === "after" ? [change.to, change.from] : [change.from, change.to];
46478
- return await exists(present) && !await exists(absent);
46479
- }
46480
- case "path": return change.present === side ? await exists(change.path) && await hashPath(change.path) === change.hash : !await exists(change.path) && await exists(change.slot);
46481
- case "element": return await exists(change.path) && holdsSpan(await readFile(change.path, "utf8"), change.span, side);
46482
- case "inserted": return await exists(change.path) && holdsInserted(await readFile(change.path, "utf8"), change.span, side === change.present ? "after" : "before");
46483
- case "token": return await exists(change.path) && holdsToken(change, side);
46484
- case "relocated": return await exists(change.path) && relocateMoved(await readFile(change.path, "utf8"), change.span, OTHER[side]) !== void 0;
46485
- }
46486
- }
46487
- /**
46488
- * The entry a step holds, taking the stored size on each axis both it and the
46489
- * stored entry hug, since the server measures that size and the developer
46490
- * never set it, so a measure after a hand move neither overtakes the step nor
46491
- * is reverted by it.
46492
- */
46493
- function withMeasured(entry, stored) {
46494
- if (!entry || !stored) return entry;
46495
- return {
46496
- ...entry,
46497
- ...entry.hugWidth && stored.hugWidth ? { width: stored.width } : {},
46498
- ...entry.hugHeight && stored.hugHeight ? { height: stored.height } : {}
46499
- };
46500
- }
46501
- const OTHER = {
46502
- before: "after",
46503
- after: "before"
46504
- };
46505
- /**
46506
- * Writes `side` of a change back, under the record's lock, once `holds` read
46507
- * the other side. A hand edit's change answers the frame's content hash as it
46508
- * left it, and every other kind answers undefined.
46509
- */
46510
- async function restore(change, side) {
46511
- switch (change.kind) {
46512
- case "entry": {
46513
- const file = await readRecord(change.layout, layoutSpec);
46514
- const frames = { ...file.frames };
46515
- const entry = withMeasured(change[side], frames[change.frame]);
46516
- if (entry) frames[change.frame] = entry;
46517
- else delete frames[change.frame];
46518
- await writeRecord(change.layout, {
46519
- ...file,
46520
- frames
46521
- });
46522
- return;
46523
- }
46524
- case "section": {
46525
- const file = await readRecord(change.layout, layoutSpec);
46526
- const sections = { ...file.sections };
46527
- const entry = change[side];
46528
- if (entry) sections[change.section] = entry;
46529
- else delete sections[change.section];
46530
- await writeRecord(change.layout, {
46531
- ...file,
46532
- sections
46533
- });
46534
- return;
46535
- }
46536
- case "pages": {
46537
- const file = await readRecord(change.file, {
46538
- ...projectSpec,
46539
- empty: emptyProject
46540
- });
46541
- await writeRecord(change.file, {
46542
- ...file,
46543
- pages: change[side]
46544
- });
46545
- return;
46546
- }
46547
- case "moved":
46548
- if (side === "before") await rename(change.to, change.from);
46549
- else await rename(change.from, change.to);
46550
- return;
46551
- case "path":
46552
- if (change.present === side) await rename(change.slot, change.path);
46553
- else await takeOut(change.path, change.slot);
46554
- return;
46555
- case "element": return rewriteFrame(change, (source) => {
46556
- const swapped = swapSpan(source, change.span, OTHER[side]);
46557
- return swapped && {
46558
- html: swapped.html,
46559
- keep: () => {
46560
- change.span = swapped.span;
46561
- }
46562
- };
46563
- });
46564
- case "inserted": return rewriteFrame(change, (source) => {
46565
- const written = side === change.present ? restoreInserted(source, change.span) : removeInserted(source, change.span);
46566
- return written && {
46567
- html: written.html,
46568
- keep: () => {
46569
- change.span = written.span;
46570
- }
46571
- };
46572
- });
46573
- case "relocated": return rewriteFrame(change, (source) => {
46574
- const written = relocateMoved(source, change.span, side);
46575
- return written && {
46576
- html: written.html,
46577
- keep: () => {
46578
- change.span = written.span;
46579
- }
46580
- };
46581
- });
46582
- case "token": return rewriteToken(change, side);
46583
- }
46584
- }
46585
- /** Whether the sheet sets the token exactly as `side` holds it, false for a sheet that no longer parses. */
46586
- async function holdsToken(change, side) {
46587
- try {
46588
- const css = await readFile(change.path, "utf8");
46589
- return isDeepStrictEqual(tokenSides(css, change.name), change[side]);
46590
- } catch (error) {
46591
- if (error instanceof FrameboardError) return false;
46592
- throw error;
46593
- }
46594
- }
46595
- /** Writes `side` of a token change, refusing a sheet that changed between its read and the rename. */
46596
- async function rewriteToken(change, side) {
46597
- const css = await readFile(change.path, "utf8");
46598
- const written = setTokenSides(css, change.name, change[side]);
46599
- if (writeTokenSheet(change.path, contentHash(css), written) === "stale") throw new FrameboardError("undo-overtaken", `An agent changed ${change.name} after your edit, so that step was dropped.`, { change: change.kind });
46600
- }
46601
- /**
46602
- * Writes a hand edit's element to the other side through a temporary file and
46603
- * a rename, reading the file again just before the rename. A write landing
46604
- * before that read is not overwritten: the rewrite is made once more from the
46605
- * fresh bytes, and refused once they change again or no longer hold the
46606
- * element. Bytes that fail a UTF-8 round trip are refused too, since decoding
46607
- * would rewrite each invalid byte outside the element. The change keeps where
46608
- * the element was found, through `keep`, so the next side lands on it.
46609
- */
46610
- async function rewriteFrame(change, rewrite) {
46611
- const temp = join(dirname(change.path), `.${basename(change.path)}.${process.pid}.tmp`);
46612
- let source = await readText(change.path);
46613
- for (let attempt = 0; source !== void 0 && attempt < 2; attempt += 1) {
46614
- const written = rewrite(source);
46615
- if (!written) break;
46616
- await writeFile(temp, written.html);
46617
- const now = await readText(change.path);
46618
- if (now === source) {
46619
- await rename(temp, change.path);
46620
- written.keep();
46621
- return contentHash(written.html);
46622
- }
46623
- source = now;
46624
- }
46625
- await rm(temp, { force: true });
46626
- throw new FrameboardError("undo-overtaken", `An agent changed ${basename(change.path, FRAME_EXTENSION)} after your edit, so that step was dropped.`, { change: change.kind });
46627
- }
46628
- /** A frame file's text, or undefined when its bytes do not survive a UTF-8 round trip. */
46629
- async function readText(path) {
46630
- const bytes = await readFile(path);
46631
- const text = bytes.toString("utf8");
46632
- return Buffer.from(text, "utf8").equals(bytes) ? text : void 0;
46633
- }
46634
- /**
46635
- * The journal one board write reports into, building the changes of one
46636
- * step. A path it takes out waits in the step's trash folder.
46637
- */
46638
- var StepJournal = class {
46639
- root;
46640
- id;
46641
- changes = [];
46642
- constructor(root, id) {
46643
- this.root = root;
46644
- this.id = id;
46645
- }
46646
- entry(page, frame, before, after) {
46647
- const layout = join(page, LAYOUT_FILE);
46648
- this.changes.push({
46649
- kind: "entry",
46650
- layout,
46651
- frame,
46652
- before,
46653
- after
46654
- });
46655
- }
46656
- section(page, section, before, after) {
46657
- const layout = join(page, LAYOUT_FILE);
46658
- this.changes.push({
46659
- kind: "section",
46660
- layout,
46661
- section,
46662
- before,
46663
- after
46664
- });
46665
- }
46666
- pages(project, before, after) {
46667
- const file = join(project, PROJECT_FILE);
46668
- this.changes.push({
46669
- kind: "pages",
46670
- file,
46671
- before,
46672
- after
46673
- });
46674
- }
46675
- async moved(from, to) {
46676
- await rename(from, to);
46677
- this.changes.push({
46678
- kind: "moved",
46679
- from,
46680
- to
46681
- });
46682
- }
46683
- /** The element a hand edit rewrote in a frame file, which this journal does not write. */
46684
- element(path, ref, span) {
46685
- this.changes.push({
46686
- kind: "element",
46687
- path,
46688
- ref,
46689
- span
46690
- });
46691
- }
46692
- /** The element a placement tool wrote into a frame file, which this journal does not write. */
46693
- inserted(path, ref, span) {
46694
- this.changes.push({
46695
- kind: "inserted",
46696
- path,
46697
- ref,
46698
- span,
46699
- present: "after"
46700
- });
46701
- }
46702
- /** The element a hand delete took out of a frame file, which this journal does not write. */
46703
- deletedElement(path, ref, span) {
46704
- this.changes.push({
46705
- kind: "inserted",
46706
- path,
46707
- ref,
46708
- span,
46709
- present: "before"
46710
- });
46711
- }
46712
- /** The element a hand move took to another gap of a frame file, which this journal does not write. */
46713
- relocated(path, ref, span) {
46714
- this.changes.push({
46715
- kind: "relocated",
46716
- path,
46717
- ref,
46718
- span
46719
- });
46720
- }
46721
- /** One token's project declarations a hand token edit rewrote, which this journal does not write. */
46722
- token(path, name, before, after) {
46723
- this.changes.push({
46724
- kind: "token",
46725
- path,
46726
- name,
46727
- before,
46728
- after
46729
- });
46730
- }
46731
- async created(path) {
46732
- this.changes.push({
46733
- kind: "path",
46734
- path,
46735
- present: "after",
46736
- hash: await hashPath(path),
46737
- slot: this.#slot()
46738
- });
46739
- }
46740
- async removed(path) {
46741
- const hash = await hashPath(path);
46742
- const slot = this.#slot();
46743
- await takeOut(path, slot);
46744
- this.changes.push({
46745
- kind: "path",
46746
- path,
46747
- present: "before",
46748
- hash,
46749
- slot
46750
- });
46751
- }
46752
- #slot() {
46753
- return trashSlot(this.root, this.id, this.changes.length);
46754
- }
46755
- };
46756
- /**
46757
- * A hash over a file's bytes, or over every file in a folder with its path.
46758
- * Dot-named entries, locks, and temp files are left out, as the scanner
46759
- * leaves them, so a lock taken and released reads as no change.
46760
- */
46761
- async function hashPath(path) {
46762
- const hash = createHash("sha256");
46763
- const walk = async (at, name) => {
46764
- if ((await stat(at)).isDirectory()) {
46765
- hash.update(`d:${name}\0`);
46766
- const children = (await readdir(at)).filter(isHashed).sort();
46767
- for (const child of children) await walk(join(at, child), `${name}/${child}`);
46768
- } else {
46769
- hash.update(`f:${name}\0`);
46770
- hash.update(await readFile(at));
46771
- hash.update("\0");
46772
- }
46773
- };
46774
- await walk(path, ".");
46775
- return hash.digest("hex");
46776
- }
46777
- function isHashed(name) {
46778
- return !name.startsWith(".") && !name.endsWith(".lock") && !name.endsWith(".tmp");
46779
- }
46780
- /**
46781
- * Whether the path exists under exactly this name, read from its folder's
46782
- * listing, so a case-only rename on a case-insensitive volume tells the two
46783
- * names apart.
46784
- */
46785
- async function exists(path) {
46786
- try {
46787
- return (await readdir(dirname(path))).includes(basename(path));
46788
- } catch (error) {
46789
- if (isCode(error, "ENOENT")) return false;
46790
- throw error;
46791
- }
46792
- }
46793
- const OPEN = async () => {};
46794
- /**
46795
- * The developer's undo and redo stacks, in memory, holding the board's own
46796
- * writes and never an agent's. Undo and redo run one at a time, each
46797
- * checking every change of a step under its records' locks before writing
46798
- * any, and refusing with `undo-overtaken` and dropping the step when an
46799
- * agent has since changed one.
46800
- */
46801
- var History = class {
46802
- root;
46803
- onChange;
46804
- onWrite;
46805
- #undo = [];
46806
- #redo = [];
46807
- #nextId = 1;
46808
- #turn = Promise.resolve();
46809
- constructor(root, onChange = () => {}, onWrite = () => {}) {
46810
- this.root = root;
46811
- this.onChange = onChange;
46812
- this.onWrite = onWrite;
46813
- }
46814
- counts() {
46815
- return {
46816
- undo: this.#undo.length,
46817
- redo: this.#redo.length
46818
- };
46819
- }
46820
- /** A journal for one write, to pass into the board verb and then record. */
46821
- journal() {
46822
- return new StepJournal(this.root, this.#nextId++);
46823
- }
46824
- /** Pushes a write's step, clearing redo. A write that changed nothing records nothing. */
46825
- record(step) {
46826
- if (step.changes.length === 0) return;
46827
- this.#undo.push(step);
46828
- if (this.#undo.length > 100) this.#undo.shift();
46829
- this.#redo = [];
46830
- this.onChange(this.counts());
46831
- this.onWrite(step, "after");
46832
- }
46833
- /**
46834
- * The refs the top undo or redo step would write, without popping it, so a
46835
- * route can refuse a claimed frame before the step is taken. These are the
46836
- * step's frames, and the page or project folder and frame file each move
46837
- * or removal names, since a page or project step names no frames.
46838
- */
46839
- peek(side) {
46840
- const step = (side === "undo" ? this.#undo : this.#redo).at(-1);
46841
- if (!step) return [];
46842
- const refs = step.changes.flatMap((change) => {
46843
- if (change.kind === "moved") return [change.from, change.to];
46844
- if (change.kind === "path") return [change.path];
46845
- return [];
46846
- }).flatMap((path) => {
46847
- const inBoard = relative(this.root, path);
46848
- if (inBoard === "" || inBoard.startsWith("..") || isAbsolute(inBoard)) return [];
46849
- const ref = inBoard.split(sep).join("/");
46850
- return [ref.endsWith(".html") ? ref.slice(0, -5) : ref];
46851
- });
46852
- return [.../* @__PURE__ */ new Set([...step.frames, ...refs])];
46853
- }
46854
- /**
46855
- * Undoes the top step. `gate` reads what `peek` names of that step in turn,
46856
- * before it is taken, so a refusal it throws leaves the step on its stack
46857
- * and a quick second undo never checks one step and takes another.
46858
- */
46859
- undo(gate = OPEN) {
46860
- return this.#inTurn(() => this.#move(this.#undo, this.#redo, "before", gate));
46861
- }
46862
- /** Redoes the top step, gated as `undo` is. */
46863
- redo(gate = OPEN) {
46864
- return this.#inTurn(() => this.#move(this.#redo, this.#undo, "after", gate));
46865
- }
46866
- /** Takes the top step of `from`, writes `to` side of it, and pushes it onto `onto`. */
46867
- async #move(from, onto, to, gate) {
46868
- const empty = () => new FrameboardError("nothing-to-undo", `There is nothing to ${to === "before" ? "undo" : "redo"}.`);
46869
- if (from.length === 0) throw empty();
46870
- await gate(this.peek(from === this.#undo ? "undo" : "redo"));
46871
- const step = from.pop();
46872
- if (!step) throw empty();
46873
- const was = to === "before" ? "after" : "before";
46874
- const hashes = {};
46875
- const locks = step.changes.flatMap(lockPaths).filter((path) => existsSync(dirname(path)));
46876
- try {
46877
- await withLocks(locks, async () => {
46878
- for (const change of step.changes) if (!await holds(change, was)) throw new FrameboardError("undo-overtaken", `An agent changed ${nameOf(change)} after your edit, so that step was dropped.`, { change: change.kind });
46879
- const ordered = to === "before" ? [...step.changes].reverse() : step.changes;
46880
- for (const change of ordered) {
46881
- const hash = await restore(change, to);
46882
- if (hash !== void 0 && "ref" in change) hashes[change.ref] = hash;
46883
- }
46884
- });
46885
- } catch (error) {
46886
- if (!(error instanceof FrameboardError && error.code === "undo-overtaken")) from.push(step);
46887
- this.onChange(this.counts());
46888
- throw error;
46889
- }
46890
- onto.push(step);
46891
- this.onChange(this.counts());
46892
- this.onWrite(step, to);
46893
- const answer = {
46894
- page: step.page?.[to] ?? null,
46895
- frames: step.frames
46896
- };
46897
- return Object.keys(hashes).length > 0 ? {
46898
- ...answer,
46899
- hashes
46900
- } : answer;
46901
- }
46902
- #inTurn(task) {
46903
- const run = this.#turn.then(task);
46904
- this.#turn = run.catch(() => {});
46905
- return run;
46906
- }
46907
- };
46908
- /** What a refusal names as overtaken, being a frame, a section, a page, or the page order. */
46909
- function nameOf(change) {
46910
- if (change.kind === "entry") return change.frame;
46911
- if (change.kind === "section") return `section ${change.section}`;
46912
- if (change.kind === "pages") return "the page order";
46913
- if (change.kind === "token") return change.name;
46914
- const path = change.kind === "moved" ? change.to : change.path;
46915
- return basename(path, FRAME_EXTENSION);
46916
- }
46917
47209
  // node_modules/readdirp/index.js
46918
47210
  const EntryTypes = {
46919
47211
  FILE_TYPE: "files",
@@ -51035,6 +51327,7 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
51035
51327
  history,
51036
51328
  selection,
51037
51329
  renderFrame,
51330
+ clipboard: clipboardFiles(),
51038
51331
  thumbnails,
51039
51332
  measure,
51040
51333
  frameVersion: tracker.version,
@@ -51271,7 +51564,7 @@ async function pushNotes(root, paths, hub, delivery) {
51271
51564
  const parts = relative(root, path).split(sep);
51272
51565
  const [project, page, file] = parts;
51273
51566
  if (parts.length !== 3 || !project || !page || !file) continue;
51274
- const notes = file === NOTES_FILE$1;
51567
+ const notes = file === NOTES_FILE$2;
51275
51568
  if (!notes && !file.endsWith(".html")) continue;
51276
51569
  const key = `${project}/${page}`;
51277
51570
  pages.set(key, {