frameboard 0.23.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) {
@@ -9496,7 +9497,7 @@ async function isDirectory(path) {
9496
9497
  }
9497
9498
  }
9498
9499
  // package.json
9499
- var version$1 = "0.23.0";
9500
+ var version$1 = "0.24.0";
9500
9501
  var dependencies = { "playwright-core": "1.64.1" };
9501
9502
  // src/shared/version.ts
9502
9503
  const version = version$1;
@@ -13976,7 +13977,7 @@ async function claim(root, fields, now) {
13976
13977
  * Drops a session's claim on one frame, or every claim it holds when no
13977
13978
  * frame is named, returning what it dropped.
13978
13979
  */
13979
- async function release(root, session, frame, now) {
13980
+ async function release$1(root, session, frame, now) {
13980
13981
  const dropped = [];
13981
13982
  await ensureRunFolder(root);
13982
13983
  await updateRecord(claimsPath(root), claimsSpec, (file) => {
@@ -28213,7 +28214,7 @@ const boxesBodySchema = object$1({
28213
28214
  sections: boxesSchema.optional(),
28214
28215
  expectedSections: boxesSchema.optional()
28215
28216
  });
28216
- const STATUS$4 = {
28217
+ const STATUS$5 = {
28217
28218
  usage: 400,
28218
28219
  "invalid-name": 400,
28219
28220
  "project-required": 400,
@@ -28276,7 +28277,7 @@ function apiRoutes(root, actions, look, history) {
28276
28277
  code: error.code,
28277
28278
  message: error.message
28278
28279
  }
28279
- }, STATUS$4[error.code] ?? 500);
28280
+ }, STATUS$5[error.code] ?? 500);
28280
28281
  }
28281
28282
  return c.json({
28282
28283
  ok: true,
@@ -28344,7 +28345,7 @@ function apiRoutes(root, actions, look, history) {
28344
28345
  message: error.message,
28345
28346
  details: error.details
28346
28347
  }
28347
- }, STATUS$4[error.code] ?? 500);
28348
+ }, STATUS$5[error.code] ?? 500);
28348
28349
  }
28349
28350
  });
28350
28351
  return app;
@@ -28740,6 +28741,192 @@ function checkRoutes(access, checks) {
28740
28741
  });
28741
28742
  return app;
28742
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
+ }
28743
28930
  // node_modules/@bramus/specificity/dist/index.js
28744
28931
  var Jn = Object.create;
28745
28932
  var te = Object.defineProperty;
@@ -35261,6 +35448,7 @@ function placeElement(source, index, spot, facts, drop = []) {
35261
35448
  };
35262
35449
  }
35263
35450
  // src/server/edit/frame-file.ts
35451
+ const identity = (index) => index;
35264
35452
  function stale$1(path) {
35265
35453
  return refuse$2("stale-address", `${basename(path)} changed after this edit was made, so nothing was written`);
35266
35454
  }
@@ -35304,7 +35492,8 @@ function editFrameFile(path, address, change, sourceAt) {
35304
35492
  hash: contentHash(applied.html),
35305
35493
  from: hash,
35306
35494
  index,
35307
- span: applied.span
35495
+ span: applied.span,
35496
+ remap: identity
35308
35497
  };
35309
35498
  }
35310
35499
  /**
@@ -35325,7 +35514,8 @@ function insertFrameFile(path, hash, placement, markup) {
35325
35514
  ok: true,
35326
35515
  hash: contentHash(inserted.html),
35327
35516
  index: inserted.index,
35328
- span: inserted.span
35517
+ span: inserted.span,
35518
+ remap: shiftedPast(inserted.index, subtreeSize(inserted.html, inserted.index))
35329
35519
  };
35330
35520
  }
35331
35521
  /**
@@ -35343,7 +35533,8 @@ function removeFrameFile(path, hash, index) {
35343
35533
  return {
35344
35534
  ok: true,
35345
35535
  hash: contentHash(removed.html),
35346
- span: removed.span
35536
+ span: removed.span,
35537
+ remap: takenOut(index, subtreeSize(read.source, index))
35347
35538
  };
35348
35539
  }
35349
35540
  /**
@@ -35362,7 +35553,8 @@ function moveFrameFile(path, hash, index, placement) {
35362
35553
  ok: true,
35363
35554
  hash: contentHash(moved.html),
35364
35555
  index: moved.index,
35365
- span: moved.span
35556
+ span: moved.span,
35557
+ remap: carried(index, moved.index, subtreeSize(read.source, index))
35366
35558
  };
35367
35559
  }
35368
35560
  /**
@@ -35383,9 +35575,37 @@ function placeFrameFile(path, hash, index, spot, facts, drop = []) {
35383
35575
  ok: true,
35384
35576
  hash: contentHash(placed.html),
35385
35577
  spans: placed.spans,
35386
- sized: placed.sized
35578
+ sized: placed.sized,
35579
+ remap: identity
35580
+ };
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);
35387
35601
  };
35388
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
+ }
35389
35609
  /**
35390
35610
  * A frame file's text and hash. Bytes that do not survive a UTF-8 round trip
35391
35611
  * are refused, since decoding would rewrite every invalid byte.
@@ -35415,272 +35635,1337 @@ function replaceFile(path, hash, html) {
35415
35635
  renameSync(temp, path);
35416
35636
  return true;
35417
35637
  }
35418
- // src/shared/records/edit.ts
35419
- const hash = string$1().regex(/^[0-9a-f]{64}$/);
35420
- /** What `edit` returns: the frame it wrote, the element, and the hash the next edit is made from. */
35421
- const editResultSchema = object$1({
35422
- ref: string$1(),
35423
- /** The element's index in the file as written, which moves once the edit was found again by its bytes. */
35424
- index: int$1().min(0),
35425
- hash,
35426
- /** The hash the edit was written over, which differs from the one sent once the edit was found again. */
35427
- from: hash.optional()
35428
- });
35429
- object$1({
35430
- 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. */
35431
35642
  index: int$1().min(0),
35432
- 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()
35433
35650
  });
35434
- object$1({
35435
- ref: string$1(),
35436
- 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()
35437
35681
  });
35438
- object$1({
35439
- ref: string$1(),
35440
- index: int$1().min(0),
35441
- hash
35682
+ /** `<project>/<page>/notes.json`. */
35683
+ const notesFileSchema = looseObject({
35684
+ version: literal(1),
35685
+ notes: array$1(noteSchema)
35442
35686
  });
35443
- /** A size a placement wrote where no rule set one. */
35444
- const placedSizeSchema = _enum$1(["width", "height"]);
35445
- object$1({
35446
- ref: string$1(),
35447
- index: int$1().min(0),
35448
- hash,
35449
- 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()
35450
35693
  });
35451
- // src/server/routes/envelope.ts
35452
- /** The status each refusal of a structure or history write answers with. */
35453
- const STATUS$3 = {
35454
- usage: 400,
35455
- "invalid-name": 400,
35456
- "project-required": 400,
35457
- "project-not-found": 404,
35458
- "page-not-found": 404,
35459
- "frame-not-found": 404,
35460
- "section-not-found": 404,
35461
- "name-taken": 409,
35462
- "stale-layout": 409,
35463
- "frame-claimed": 409,
35464
- "undo-overtaken": 409,
35465
- "nothing-to-undo": 409,
35466
- "tokens-exist": 409,
35467
- "stale-tokens": 409,
35468
- "invalid-edit": 409,
35469
- "frame-locked": 423,
35470
- "layout-invalid": 422,
35471
- "project-file-invalid": 422,
35472
- "fit-unbounded": 422,
35473
- "lock-timeout": 503,
35474
- "browser-not-found": 503
35475
- };
35694
+ // src/server/look/token-edit.ts
35695
+ const NAME = /^--[\w-]+$/;
35696
+ const UNSAFE_VALUE = /[;{}\n\r]|\/\*/;
35476
35697
  /**
35477
- * Answers a refusal in the CLI's `{ ok, error }` envelope, for a route
35478
- * 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.
35479
35707
  */
35480
- function answerRefusal(error, c) {
35481
- if (!(error instanceof FrameboardError)) throw error;
35482
- return c.json({
35483
- ok: false,
35484
- error: {
35485
- code: error.code,
35486
- message: error.message,
35487
- details: error.details
35488
- }
35489
- }, 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;
35490
35739
  }
35491
- /** The request's JSON body as the schema reads it, or `usage` naming what failed. */
35492
- async function parseBody$1(request, schema) {
35493
- const parsed = schema.safeParse(await request.json().catch(() => null));
35494
- if (!parsed.success) throw new FrameboardError("usage", `The body ${parsed.error.message}`);
35495
- 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);
35496
35752
  }
35497
- // src/server/routes/edit.ts
35498
- const value = string$1().max(1e4);
35499
- const name$1 = string$1().min(1).max(256);
35500
- /** A dragged shape's side in CSS pixels. */
35501
- const side = int$1().min(1).max(1e4);
35502
- const editSchema$1 = object$1({
35503
- ref: string$1().min(1).max(1024),
35504
- index: int$1().min(0),
35505
- hash: string$1().regex(/^[0-9a-f]{64}$/),
35506
- change: discriminatedUnion("kind", [
35507
- object$1({
35508
- kind: literal("style"),
35509
- property: name$1,
35510
- value
35511
- }),
35512
- object$1({
35513
- kind: literal("attribute"),
35514
- name: name$1,
35515
- value
35516
- }),
35517
- object$1({
35518
- kind: literal("text"),
35519
- value
35520
- }),
35521
- object$1({
35522
- kind: literal("styles"),
35523
- declarations: array$1(object$1({
35524
- property: name$1,
35525
- value
35526
- })).max(16)
35527
- })
35528
- ])
35529
- });
35530
- const insertSchema = object$1({
35531
- ref: string$1().min(1).max(1024),
35532
- hash: string$1().regex(/^[0-9a-f]{64}$/),
35533
- parent: int$1().min(0),
35534
- before: int$1().min(0).nullable(),
35535
- element: discriminatedUnion("kind", [
35536
- object$1({ kind: literal("text") }),
35537
- object$1({
35538
- kind: literal("rectangle"),
35539
- width: side.optional(),
35540
- height: side.optional()
35541
- }),
35542
- object$1({
35543
- kind: literal("ellipse"),
35544
- width: side.optional(),
35545
- height: side.optional()
35546
- }),
35547
- object$1({
35548
- kind: literal("divider"),
35549
- vertical: boolean$1()
35550
- }),
35551
- object$1({
35552
- kind: literal("asset"),
35553
- path: string$1().min(1).max(1024),
35554
- width: side,
35555
- height: side
35556
- })
35557
- ])
35558
- });
35559
- const removeSchema = object$1({
35560
- ref: string$1().min(1).max(1024),
35561
- index: int$1().min(0),
35562
- hash: string$1().regex(/^[0-9a-f]{64}$/)
35563
- });
35564
- const moveSchema$1 = object$1({
35565
- ref: string$1().min(1).max(1024),
35566
- hash: string$1().regex(/^[0-9a-f]{64}$/),
35567
- index: int$1().min(0),
35568
- parent: int$1().min(0),
35569
- before: int$1().min(0).nullable()
35570
- });
35571
- /** A spot in CSS pixels, bounded well past any frame. */
35572
- const offset = number().min(-1e5).max(1e5);
35573
- const placeSchema = object$1({
35574
- ref: string$1().min(1).max(1024),
35575
- hash: string$1().regex(/^[0-9a-f]{64}$/),
35576
- index: int$1().min(0),
35577
- spot: object$1({
35578
- left: offset,
35579
- top: offset,
35580
- width: side.optional(),
35581
- height: side.optional()
35582
- }).nullable(),
35583
- /** Back in flow, the sizes to drop, being ones a placement wrote that nothing changed since. */
35584
- drop: array$1(placedSizeSchema).max(2).optional()
35585
- });
35586
35753
  /**
35587
- * A hand edit of one element, a placed element, and a deleted one, each behind
35588
- * `requireWriter` and refused on a frame another session holds.
35589
- *
35590
- * The edit's body mirrors
35591
- * `edit`'s flags with the hash required, since the board always holds the
35592
- * one it rendered, plus a `styles` change the CLI never sends, which writes
35593
- * several declarations as one step. It writes through `editFrameFile`, which finds the element
35594
- * again in a frame an agent wrote since from the source `version` kept, and
35595
- * records the edited element's span as one step. It answers the `edit`
35596
- * record with the index written and the hash written over. Each refusal the
35597
- * writer returns answers 409 with its code, `stale-address` among them.
35598
- *
35599
- * The insert takes an element kind, never markup, and writes that kind's one
35600
- * tag into the gap `parent` and `before` name, painted from the project's
35601
- * tokens through `sheets`, and records it as one step. It answers the frame,
35602
- * the new element's index, and the hash written. A hash the file no longer
35603
- * has answers 409 `stale-address` with nothing written, since the gap's
35604
- * indices name nothing past an agent's write, and a retried insert lands once.
35605
- * A rectangle or an ellipse takes an optional width and height a drag drew.
35606
- * An asset names a file under the project's `assets/` and the size it
35607
- * shows at, and the server picks its tag from the file's kind. A file
35608
- * outside that folder or not there answers 409 `asset-missing`, and one that
35609
- * is no image, GIF, SVG, or video `asset-not-placeable`, each writing nothing.
35610
- *
35611
- * The remove takes out the element at `index`, with what it holds, from the
35612
- * bytes `hash` names, and records it as one step whose undo puts it back
35613
- * under its parent. It answers the frame and the hash written, and refuses a
35614
- * moved file as `stale-address` the way the insert does.
35615
- *
35616
- * The move takes one element by index and the gap it goes into, both read
35617
- * in the frame as the hash names it, and records it as one step an undo
35618
- * puts back byte for byte. It answers the element's new index and the hash
35619
- * written, and refuses as the insert does, with `invalid-container` for a
35620
- * gap inside the element itself.
35621
- *
35622
- * The place takes one element by index and a spot in CSS pixels against its
35623
- * containing block, or null to put it back in the flow, read in the frame as
35624
- * the hash names it, with `drop` naming the sizes back in flow takes off. It
35625
- * writes the element's start tag, and its static parent's first, and records
35626
- * both as one step, so one undo restores both. It answers the element's
35627
- * index, the hash written, and the sizes a placement wrote, refuses as the move
35628
- * does, and refuses `reanchors-descendant` where a positioned parent would
35629
- * 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.
35630
35759
  */
35631
- function editRoutes(root, access, history, version, sheets) {
35632
- const app = new Hono();
35633
- app.post("/api/frames/edit", requireWriter(access), async (c) => {
35634
- const body = await parseBody$1(c.req.raw, editSchema$1);
35635
- const frame = await resolveFrameRef(root, body.ref, { cwd: root });
35636
- const ref = `${frame.project}/${frame.page}/${frame.name}`;
35637
- await refuseClaimed(root, [ref], /* @__PURE__ */ new Date());
35638
- const was = contentHash(await readFile(frame.path)) !== body.hash ? await version?.(ref, body.hash) ?? null : null;
35639
- const result = editFrameFile(frame.path, {
35640
- index: body.index,
35641
- hash: body.hash
35642
- }, body.change, (hash) => hash === body.hash ? was : null);
35643
- if (!result.ok) return c.json({
35644
- ok: false,
35645
- error: {
35646
- code: result.reason,
35647
- message: result.detail,
35648
- details: {
35649
- ref,
35650
- index: body.index,
35651
- ..."moved" in result ? { moved: result.moved } : {}
35652
- }
35653
- }
35654
- }, 409);
35655
- if (result.span.before !== result.span.after) {
35656
- const journal = history.journal();
35657
- journal.element(frame.path, ref, result.span);
35658
- history.record({
35659
- id: journal.id,
35660
- changes: journal.changes,
35661
- page: null,
35662
- frames: [ref]
35663
- });
35664
- }
35665
- const data = {
35666
- ref,
35667
- index: result.index,
35668
- hash: result.hash,
35669
- from: result.from
35670
- };
35671
- return c.json({
35672
- ok: true,
35673
- 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);
35674
35812
  });
35675
35813
  });
35676
- app.post("/api/frames/insert", requireWriter(access), async (c) => {
35677
- const body = await parseBody$1(c.req.raw, insertSchema);
35678
- const frame = await resolveFrameRef(root, body.ref, { cwd: root });
35679
- const ref = `${frame.project}/${frame.page}/${frame.name}`;
35680
- await refuseClaimed(root, [ref], /* @__PURE__ */ new Date());
35681
- const tokens = sheets ? readTokenTable(root, sheets(frame.project)).tokens : [];
35682
- let element;
35683
- if (body.element.kind !== "asset") element = body.element;
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;
35684
36969
  else {
35685
36970
  const asset = await resolveAsset(join(root, frame.project), body.element.path);
35686
36971
  if (!asset.ok) return c.json({
@@ -35722,6 +37007,7 @@ function editRoutes(root, access, history, version, sheets) {
35722
37007
  page: null,
35723
37008
  frames: [ref]
35724
37009
  });
37010
+ await follow(frame, body.hash, result.hash, result.remap);
35725
37011
  const data = {
35726
37012
  ref,
35727
37013
  index: result.index,
@@ -35757,6 +37043,7 @@ function editRoutes(root, access, history, version, sheets) {
35757
37043
  page: null,
35758
37044
  frames: [ref]
35759
37045
  });
37046
+ await follow(frame, body.hash, result.hash, result.remap);
35760
37047
  const data = {
35761
37048
  ref,
35762
37049
  hash: result.hash
@@ -35795,6 +37082,7 @@ function editRoutes(root, access, history, version, sheets) {
35795
37082
  page: null,
35796
37083
  frames: [ref]
35797
37084
  });
37085
+ await follow(frame, body.hash, result.hash, result.remap);
35798
37086
  const data = {
35799
37087
  ref,
35800
37088
  index: result.index,
@@ -35835,6 +37123,7 @@ function editRoutes(root, access, history, version, sheets) {
35835
37123
  frames: [ref]
35836
37124
  });
35837
37125
  }
37126
+ await follow(frame, body.hash, result.hash, result.remap);
35838
37127
  const data = {
35839
37128
  ref,
35840
37129
  index: body.index,
@@ -36578,7 +37867,7 @@ function isElement(node) {
36578
37867
  return "tagName" in node;
36579
37868
  }
36580
37869
  // src/server/routes/frames.ts
36581
- const NOTES_FILE$2 = "notes.json";
37870
+ const NOTES_FILE$1 = "notes.json";
36582
37871
  /** Where the look route serves the board's token sheet, whichever file stands in for it. */
36583
37872
  const BOARD_SHEET_URL = "/frameboard/tokens.css";
36584
37873
  const CONTENT_TYPES$1 = {
@@ -36685,7 +37974,7 @@ async function resolveFile(root, [project, page, ...rest]) {
36685
37974
  }
36686
37975
  }
36687
37976
  function isRecord$1(name) {
36688
- return name === "layout.json" || name === NOTES_FILE$2;
37977
+ return name === "layout.json" || name === NOTES_FILE$1;
36689
37978
  }
36690
37979
  // src/server/routes/look.ts
36691
37980
  const CONTENT_TYPES = {
@@ -36761,46 +38050,6 @@ async function readOrNull(path) {
36761
38050
  return null;
36762
38051
  }
36763
38052
  }
36764
- // src/server/notes/anchor.ts
36765
- /**
36766
- * The anchor for element `index` of a frame, refusing `stale-address` when
36767
- * the file changed since the board rendered it at `renderedAt`, since the
36768
- * index the board counted belongs to the file it showed.
36769
- */
36770
- async function anchorFor(framePath, index, renderedAt) {
36771
- const [bytes, { mtimeMs }] = await Promise.all([readFile(framePath), stat(framePath)]);
36772
- 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.`, {
36773
- path: framePath,
36774
- index
36775
- });
36776
- return {
36777
- index,
36778
- hash: contentHash(bytes)
36779
- };
36780
- }
36781
- /**
36782
- * The element each anchored note still points at, by note id: its index while
36783
- * the frame file hashes as it did when pinned, else null, being the frame
36784
- * itself. A frame note has no entry.
36785
- */
36786
- async function resolveAnchors(pageDir, notes) {
36787
- const frames = [...new Set(notes.filter((note) => note.anchor).map((note) => note.frame))];
36788
- const hashes = new Map(await Promise.all(frames.map(async (frame) => [frame, await hashOf(join(pageDir, `${frame}${FRAME_EXTENSION}`))])));
36789
- const resolved = {};
36790
- for (const note of notes) {
36791
- if (!note.anchor) continue;
36792
- resolved[note.id] = hashes.get(note.frame) === note.anchor.hash ? note.anchor.index : null;
36793
- }
36794
- return resolved;
36795
- }
36796
- async function hashOf(path) {
36797
- try {
36798
- return contentHash(await readFile(path));
36799
- } catch (error) {
36800
- if (isCode(error, "ENOENT")) return null;
36801
- throw error;
36802
- }
36803
- }
36804
38053
  // src/server/notes/dispatch.ts
36805
38054
  /** The `serve` environment variable holding the command a dispatched note runs. */
36806
38055
  const DISPATCH_ENV = "FRAMEBOARD_DISPATCH";
@@ -36936,290 +38185,6 @@ async function assertStored(pageDir, images) {
36936
38185
  const missing = images.filter((_, index) => found[index] === null);
36937
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 });
36938
38187
  }
36939
- // src/shared/records/notes.ts
36940
- /** Where a note on one element points, in the edit address's terms. */
36941
- const noteAnchorSchema = looseObject({
36942
- /** The element's `querySelectorAll('*')` index, skipping injected elements. */
36943
- index: int$1().min(0),
36944
- /** The frame file's `contentHash` when the note was pinned. */
36945
- hash: string$1()
36946
- });
36947
- const noteSchema = looseObject({
36948
- /** `n_` and 8 hex characters, unique across the board. */
36949
- id: string$1(),
36950
- /** The page's ordinal on a root note, never reused. A reply carries null. */
36951
- number: int$1().min(1).nullable(),
36952
- /** The frame's name in this page. */
36953
- frame: string$1(),
36954
- /** Null for a note on the whole frame. */
36955
- anchor: noteAnchorSchema.nullable(),
36956
- text: string$1(),
36957
- /** Images saved with the message, relative to its page, as `.notes/<file>`. Absent on a note with none. */
36958
- images: array$1(string$1()).optional(),
36959
- from: _enum$1(["developer", "agent"]),
36960
- /** Who signed it, as git names them, stamped by the server. */
36961
- author: string$1().nullable(),
36962
- /** The agent's session id on an agent reply. */
36963
- session: string$1().nullable(),
36964
- /** The session a root note is sent to. */
36965
- to: string$1().nullable(),
36966
- /** A root note's delivery state. A reply carries `open`. */
36967
- state: _enum$1([
36968
- "open",
36969
- "queued",
36970
- "delivered",
36971
- "done"
36972
- ]),
36973
- /** The root note's id on a reply, else null. */
36974
- thread: string$1().nullable(),
36975
- createdAt: string$1(),
36976
- updatedAt: string$1()
36977
- });
36978
- /** `<project>/<page>/notes.json`. */
36979
- const notesFileSchema = looseObject({
36980
- version: literal(1),
36981
- notes: array$1(noteSchema)
36982
- });
36983
- /** A session following its inbox on the live socket. */
36984
- const listenerSchema = object$1({
36985
- session: string$1(),
36986
- /** What the board shows for it, never used to address it. */
36987
- tag: string$1(),
36988
- since: string$1()
36989
- });
36990
- /**
36991
- * The one line a follower prints per note. It opens with `frameboard note`,
36992
- * which the skill tells the agent to act on, and names the verbs that answer
36993
- * it. Text is collapsed onto one line, stripped of control characters so it
36994
- * cannot drive the terminal, and cut at 200 characters. Image paths sit
36995
- * between the text and the hints, so the prefix and the hints never move.
36996
- */
36997
- function noteLine({ id, ref, element, text, images = [] }) {
36998
- const where = element === null ? ref : `${ref} element ${element}`;
36999
- const attached = images.length === 0 ? "" : ` (images: ${images.map(flatten).join(", ")})`;
37000
- return `frameboard note ${id} on ${where}: ${collapse(text)}${attached} (reply: frameboard notes reply ${id} "<text>", close: frameboard notes done ${id})`;
37001
- }
37002
- function collapse(text) {
37003
- const flat = flatten(text);
37004
- return flat.length > 200 ? `${flat.slice(0, 200)}...` : flat;
37005
- }
37006
- function flatten(text) {
37007
- return text.replace(/\s+/g, " ").replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim();
37008
- }
37009
- // src/server/notes/store.ts
37010
- const NOTES_FILE$1 = "notes.json";
37011
- const notesSpec = {
37012
- schema: notesFileSchema,
37013
- invalidCode: "notes-invalid",
37014
- empty: () => ({
37015
- version: 1,
37016
- notes: []
37017
- })
37018
- };
37019
- /** `n_` and 8 random hex characters. */
37020
- function newNoteId() {
37021
- return `n_${randomBytes(4).toString("hex")}`;
37022
- }
37023
- function notesPath(root, project, page) {
37024
- return join(root, project, page, NOTES_FILE$1);
37025
- }
37026
- function readNotes(path) {
37027
- return readRecord(path, notesSpec);
37028
- }
37029
- /** Reads, changes, and writes a page's notes under its lock, refusing a file that does not parse. */
37030
- function updateNotes(path, change) {
37031
- return updateRecord(path, notesSpec, change);
37032
- }
37033
- /** Every page in the board, as the place its notes file sits. */
37034
- async function listPageNotes(root) {
37035
- const projects = await listProjects(root);
37036
- return (await Promise.all(projects.map(async (project) => (await listPageFolders(join(root, project))).map((page) => ({
37037
- project,
37038
- page,
37039
- path: notesPath(root, project, page)
37040
- }))))).flat();
37041
- }
37042
- /**
37043
- * The page holding a note id, scanning every page of the board. A page whose
37044
- * file does not parse cannot be read for the id, so when no other page holds
37045
- * it the first such page's `notes-invalid` is thrown rather than a missing note.
37046
- */
37047
- async function findNote(root, id) {
37048
- let unreadable;
37049
- for (const place of await listPageNotes(root)) {
37050
- let file;
37051
- try {
37052
- file = await readNotes(place.path);
37053
- } catch (error) {
37054
- if (!(error instanceof FrameboardError)) throw error;
37055
- unreadable ??= error;
37056
- continue;
37057
- }
37058
- const note = file.notes.find((candidate) => candidate.id === id);
37059
- if (note) return {
37060
- ...place,
37061
- file,
37062
- note
37063
- };
37064
- }
37065
- if (unreadable) throw unreadable;
37066
- throw new FrameboardError("note-not-found", `No note ${id} in this board.`, { id });
37067
- }
37068
- /** The root of the thread a note belongs to, being the note itself when it is one. */
37069
- function rootOf(file, id) {
37070
- const note = file.notes.find((candidate) => candidate.id === id);
37071
- const root = note?.thread ? file.notes.find((candidate) => candidate.id === note.thread) : note;
37072
- if (!root) throw new FrameboardError("note-not-found", `No note ${id} in this page.`, { id });
37073
- return root;
37074
- }
37075
- /** Adds a root note numbered one past the page's highest, so a number is never reused. */
37076
- function addRoot(file, fields, { now, id }) {
37077
- const number = Math.max(0, ...file.notes.map((note) => note.number ?? 0)) + 1;
37078
- const at = now.toISOString();
37079
- const note = {
37080
- id,
37081
- number,
37082
- frame: fields.frame,
37083
- anchor: fields.anchor,
37084
- text: fields.text,
37085
- ...withImages(fields.images),
37086
- from: "developer",
37087
- author: fields.author,
37088
- session: null,
37089
- to: fields.to,
37090
- state: fields.to === null ? "open" : "queued",
37091
- thread: null,
37092
- createdAt: at,
37093
- updatedAt: at
37094
- };
37095
- return {
37096
- ...file,
37097
- notes: [...file.notes, note]
37098
- };
37099
- }
37100
- /** Appends a reply to the thread `to` belongs to, reopening nothing a reply does not name. */
37101
- function addReply(file, replyTo, fields, { now, id }) {
37102
- const root = rootOf(file, replyTo);
37103
- const at = now.toISOString();
37104
- const reply = {
37105
- id,
37106
- number: null,
37107
- frame: root.frame,
37108
- anchor: root.anchor,
37109
- text: fields.text,
37110
- ...withImages(fields.images),
37111
- from: fields.from,
37112
- author: fields.author,
37113
- session: fields.session,
37114
- to: null,
37115
- state: "open",
37116
- thread: root.id,
37117
- createdAt: at,
37118
- updatedAt: at
37119
- };
37120
- const notes = file.notes.map((note) => note.id === root.id && fields.to !== void 0 ? {
37121
- ...note,
37122
- to: fields.to,
37123
- state: "queued",
37124
- updatedAt: at
37125
- } : note);
37126
- return {
37127
- ...file,
37128
- notes: [...notes, reply]
37129
- };
37130
- }
37131
- /** A note with no images carries no key, so it reads as one written before images. */
37132
- function withImages(images) {
37133
- return images === void 0 || images.length === 0 ? {} : { images };
37134
- }
37135
- /** Sets the state of the thread `id` belongs to, and its addressee when one is given. */
37136
- function setState(file, id, state, now, to) {
37137
- const root = rootOf(file, id);
37138
- return {
37139
- ...file,
37140
- notes: file.notes.map((note) => note.id === root.id ? {
37141
- ...note,
37142
- state,
37143
- ...to === void 0 ? {} : { to },
37144
- updatedAt: now.toISOString()
37145
- } : note)
37146
- };
37147
- }
37148
- /** Takes one message out, for a write whose send failed after it landed. */
37149
- function removeNote(file, id) {
37150
- return {
37151
- ...file,
37152
- notes: file.notes.filter((note) => note.id !== id)
37153
- };
37154
- }
37155
- /** A page's notes as the board draws them, an unreadable file reading as none. */
37156
- async function pageView(root, place) {
37157
- let file;
37158
- try {
37159
- file = await readNotes(place.path);
37160
- } catch (error) {
37161
- if (error instanceof FrameboardError) return [];
37162
- throw error;
37163
- }
37164
- const elements = await resolveAnchors(join(root, place.project, place.page), file.notes);
37165
- return file.notes.map((note) => ({
37166
- ...note,
37167
- element: elements[note.id] ?? null
37168
- }));
37169
- }
37170
- /** Every page holding notes, by `<project>/<page>` ref, as the board draws them. */
37171
- async function boardView(root) {
37172
- const pages = await Promise.all((await listPageNotes(root)).map(async (place) => [`${place.project}/${place.page}`, await pageView(root, place)]));
37173
- return Object.fromEntries(pages.filter(([, notes]) => notes.length > 0));
37174
- }
37175
- /**
37176
- * The root notes queued to a session, read from disk, each with the line its
37177
- * follower prints, carrying the thread's newest developer message.
37178
- */
37179
- async function queuedFor(root, session) {
37180
- const deliveries = [];
37181
- for (const place of await listPageNotes(root)) {
37182
- const notes = await pageView(root, place);
37183
- for (const note of notes) {
37184
- if (note.thread !== null || note.state !== "queued") continue;
37185
- if (note.to !== session) continue;
37186
- deliveries.push(toDelivery(place, notes, note));
37187
- }
37188
- }
37189
- return deliveries;
37190
- }
37191
- /** A root note as a follower would receive it, read from its page whatever its state. */
37192
- async function deliveryOf(root, place, rootId) {
37193
- const notes = await pageView(root, place);
37194
- const note = notes.find((each) => each.id === rootId && each.thread === null);
37195
- if (!note) throw new FrameboardError("note-not-found", `No note ${rootId} in this page.`, { id: rootId });
37196
- return toDelivery(place, notes, note);
37197
- }
37198
- function toDelivery(place, notes, note) {
37199
- const ref = `${place.project}/${place.page}/${note.frame}`;
37200
- const newest = notes.filter((each) => (each.id === note.id || each.thread === note.id) && each.from === "developer").at(-1);
37201
- const { element, ...stored } = note;
37202
- const message = newest ?? note;
37203
- const pageDir = dirname(place.path);
37204
- return {
37205
- note: stored,
37206
- ref,
37207
- line: noteLine({
37208
- id: note.id,
37209
- ref,
37210
- element,
37211
- text: message.text,
37212
- images: message.images?.map((image) => join(pageDir, image))
37213
- })
37214
- };
37215
- }
37216
- /** Marks a root note delivered, while it is still queued to that session. */
37217
- async function markDelivered(root, id, session, now) {
37218
- await updateNotes((await findNote(root, id)).path, (file) => {
37219
- const note = file.notes.find((each) => each.id === id);
37220
- return note?.state === "queued" && note.to === session ? setState(file, id, "delivered", now) : file;
37221
- });
37222
- }
37223
38188
  // src/server/routes/notes.ts
37224
38189
  const STATUS$1 = {
37225
38190
  usage: 400,
@@ -37855,12 +38820,12 @@ async function writeStarterSheet(root, ref, look, { tokens, journal } = {}) {
37855
38820
  const project = await resolveProject(root, ref);
37856
38821
  const sheets = tokenSheetPaths(root, project.name, tokens);
37857
38822
  const existing = sheets.project ?? sheets.board;
37858
- if (existing) refuse$1(project.name, existing);
38823
+ if (existing) refuse(project.name, existing);
37859
38824
  const path = join(project.path, TOKEN_FILE);
37860
38825
  try {
37861
38826
  await writeFile(path, starterSheet(look), { flag: "wx" });
37862
38827
  } catch (error) {
37863
- if (isCode(error, "EEXIST")) refuse$1(project.name, path);
38828
+ if (isCode(error, "EEXIST")) refuse(project.name, path);
37864
38829
  throw error;
37865
38830
  }
37866
38831
  await journal?.created(path);
@@ -37870,7 +38835,7 @@ async function writeStarterSheet(root, ref, look, { tokens, journal } = {}) {
37870
38835
  ...look
37871
38836
  };
37872
38837
  }
37873
- function refuse$1(project, sheet) {
38838
+ function refuse(project, sheet) {
37874
38839
  throw new FrameboardError("tokens-exist", `${project} already renders with the token sheet ${sheet}, so no starter sheet was written.`, {
37875
38840
  project,
37876
38841
  sheet
@@ -38424,224 +39389,6 @@ function themeOf(value, usage) {
38424
39389
  if (!isTheme$1(value)) throw new FrameboardError("usage", usage, { theme: value ?? "" });
38425
39390
  return value;
38426
39391
  }
38427
- // src/server/look/token-edit.ts
38428
- const NAME = /^--[\w-]+$/;
38429
- const UNSAFE_VALUE = /[;{}\n\r]|\/\*/;
38430
- /**
38431
- * The project or board sheet with `edit` applied, every byte outside the
38432
- * token's declarations left as it stood. `board` is the token's declarations
38433
- * in the board sheet under it, none when `css` is the board sheet itself. A
38434
- * one-theme edit keeps the other theme rendering as it did,
38435
- * pinning its old value under that theme's rule when the new declaration
38436
- * would reach it, since a project `:root` ties a board dark rule on
38437
- * specificity and wins by coming later. Refuses `invalid-edit` for a name or
38438
- * value that is not one declaration, a reset of a token the board does not
38439
- * set, and a sheet that does not parse.
38440
- */
38441
- function editTokenCss(css, board, edit) {
38442
- if (!NAME.test(edit.name)) refuse(`${edit.name} is not a custom property.`);
38443
- const root = parseSheet(css);
38444
- const own = sidesIn(root, edit.name);
38445
- if ("reset" in edit) {
38446
- 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.`);
38447
- return writeSides(root, edit.name, {});
38448
- }
38449
- const value = edit.value.trim();
38450
- if (value === "" || UNSAFE_VALUE.test(edit.value)) refuse(`${JSON.stringify(edit.value)} is not one declaration value.`);
38451
- const next = { ...own };
38452
- if (edit.side === "dark") next.dark = value;
38453
- else if (edit.side === "light") {
38454
- if (next.light !== void 0) next.light = value;
38455
- else next.base = value;
38456
- const darkWas = shown(board, own).dark;
38457
- if (shown(board, next).dark !== darkWas && darkWas !== void 0) next.dark = darkWas;
38458
- } else {
38459
- next.base = value;
38460
- if (next.light !== void 0) next.light = value;
38461
- if (next.dark !== void 0) next.dark = value;
38462
- }
38463
- const written = writeSides(root, edit.name, next);
38464
- let readBack;
38465
- try {
38466
- readBack = sidesIn(postcss_default.parse(written), edit.name);
38467
- } catch {
38468
- readBack = void 0;
38469
- }
38470
- if (!isDeepStrictEqual(readBack, next)) refuse(`${JSON.stringify(edit.value)} would leave the sheet unreadable.`);
38471
- return written;
38472
- }
38473
- /**
38474
- * The sheet with the token's declarations made exactly `sides`, as undo
38475
- * restores them. A side present replaces the last declaration on that side,
38476
- * or is added to that side's rule, and a side absent takes out every
38477
- * declaration on it, dropping a rule it leaves empty.
38478
- */
38479
- function setTokenSides(css, name, sides) {
38480
- return writeSides(parseSheet(css), name, sides);
38481
- }
38482
- /** The token's declarations in a sheet, the last on each side winning, as the table reads them. */
38483
- function tokenSides(css, name) {
38484
- return sidesIn(parseSheet(css), name);
38485
- }
38486
- /**
38487
- * Writes the token sheet at `path` through a temporary file and a rename,
38488
- * reading the sheet again just before the rename and leaving it as it is
38489
- * when its hash is no longer `hash`. A null `hash` means the sheet did not
38490
- * exist, so it is created only while none does. Takes no lock, since an
38491
- * agent's raw write never takes one.
38492
- */
38493
- function writeTokenSheet(path, hash, css) {
38494
- if (hash === null) try {
38495
- writeFileSync(path, css, { flag: "wx" });
38496
- return "created";
38497
- } catch (error) {
38498
- if (isCode(error, "EEXIST")) return "stale";
38499
- throw error;
38500
- }
38501
- const temp = join(dirname(path), `.${basename(path)}.${process.pid}.tmp`);
38502
- writeFileSync(temp, css);
38503
- if (hashOrNull(path) !== hash) {
38504
- rmSync(temp, { force: true });
38505
- return "stale";
38506
- }
38507
- renameSync(temp, path);
38508
- return "written";
38509
- }
38510
- /** A sheet's content hash, or null when it does not exist. */
38511
- function hashOrNull(path) {
38512
- try {
38513
- return contentHash(readFileSync(path));
38514
- } catch (error) {
38515
- if (isCode(error, "ENOENT")) return null;
38516
- throw error;
38517
- }
38518
- }
38519
- /** The light and dark values a token renders with, the project's sides over the board's. */
38520
- function shown(board, project) {
38521
- return {
38522
- light: project.light ?? project.base ?? board.light ?? board.base,
38523
- dark: project.dark ?? project.base ?? board.dark ?? board.base
38524
- };
38525
- }
38526
- function parseSheet(css) {
38527
- try {
38528
- return postcss_default.parse(css);
38529
- } catch (error) {
38530
- return refuse(`The token sheet does not parse: ${error instanceof postcss_default.CssSyntaxError ? error.reason : String(error)}.`);
38531
- }
38532
- }
38533
- /** Every declaration of `name` in a rule the table reads, by side, in sheet order. */
38534
- function declsIn(root, name) {
38535
- const found = {
38536
- base: [],
38537
- light: [],
38538
- dark: []
38539
- };
38540
- root.walkRules((rule) => {
38541
- const side = sideOf(rule);
38542
- if (!side) return;
38543
- rule.each((node) => {
38544
- if (node.type === "decl" && node.prop === name) found[side].push(node);
38545
- });
38546
- });
38547
- return found;
38548
- }
38549
- function sidesIn(root, name) {
38550
- const sides = {};
38551
- for (const [side, decls] of Object.entries(declsIn(root, name))) {
38552
- const last = decls.at(-1);
38553
- if (last) sides[side] = last.value.trim();
38554
- }
38555
- return sides;
38556
- }
38557
- function writeSides(root, name, sides) {
38558
- const found = declsIn(root, name);
38559
- for (const side of [
38560
- "dark",
38561
- "base",
38562
- "light"
38563
- ]) {
38564
- const value = sides[side];
38565
- const decls = found[side];
38566
- const last = decls.at(-1);
38567
- if (value === void 0) for (const decl of decls) {
38568
- const rule = decl.parent;
38569
- decl.remove();
38570
- if (rule && rule.nodes?.length === 0) rule.remove();
38571
- }
38572
- else if (last) {
38573
- if (last.value.trim() !== value) last.value = value;
38574
- } else ruleFor(root, side, side === "dark" ? void 0 : firstTopLevel(root, declsIn(root, name).dark)).append(postcss_default.decl({
38575
- prop: name,
38576
- value,
38577
- raws: declRaws(root)
38578
- }));
38579
- }
38580
- return root.toString();
38581
- }
38582
- /** The earliest top-level node holding any of `decls`, undefined for none. */
38583
- function firstTopLevel(root, decls) {
38584
- let first;
38585
- for (const decl of decls) {
38586
- let node = decl;
38587
- while (node.parent && node.parent !== root) node = node.parent;
38588
- const top = node;
38589
- if (!first || root.index(top) < root.index(first)) first = top;
38590
- }
38591
- return first;
38592
- }
38593
- /** The spacing of the sheet's first declaration, so an added one reads like its neighbors. */
38594
- function declRaws(root) {
38595
- let sample;
38596
- root.walkDecls((decl) => {
38597
- sample = decl;
38598
- return false;
38599
- });
38600
- return {
38601
- before: sample?.raws.before ?? "\n ",
38602
- between: sample?.raws.between ?? ": "
38603
- };
38604
- }
38605
- const NEW_SELECTOR = {
38606
- base: ":root",
38607
- light: "[data-theme='light']",
38608
- dark: "[data-theme='dark']"
38609
- };
38610
- /**
38611
- * The top-level rule a new declaration on `side` goes into: the last such
38612
- * rule outside any at-rule, else a new one. A new `:root` or light rule goes
38613
- * ahead of every other rule, so a dark rule that ties it on specificity
38614
- * still comes later and wins in dark, and a new dark rule goes last. With
38615
- * `before`, the token's first dark declaration, a rule must come ahead of
38616
- * it, and a new one goes just before it when none does.
38617
- */
38618
- function ruleFor(root, side, before) {
38619
- const last = root.nodes.filter((node) => node.type === "rule" && sideOf(node) === side && (!before || root.index(node) < root.index(before))).at(-1);
38620
- if (last) return last;
38621
- const rule = postcss_default.rule({
38622
- selector: NEW_SELECTOR[side],
38623
- raws: {
38624
- between: " ",
38625
- semicolon: true,
38626
- after: "\n"
38627
- }
38628
- });
38629
- const first = before ?? root.nodes.find((node) => node.type === "rule");
38630
- if (side !== "dark" && first) {
38631
- const spacing = first.raws.before ?? "";
38632
- root.insertBefore(first, rule);
38633
- rule.raws.before = spacing;
38634
- first.raws.before = "\n\n";
38635
- } else {
38636
- rule.raws.before = root.nodes.length > 0 ? "\n\n" : "";
38637
- root.append(rule);
38638
- if (!root.raws.after?.includes("\n")) root.raws.after = "\n";
38639
- }
38640
- return rule;
38641
- }
38642
- function refuse(message) {
38643
- throw new FrameboardError("invalid-edit", message);
38644
- }
38645
39392
  // src/server/routes/tokens.ts
38646
39393
  const common = {
38647
39394
  project: string$1().min(1).max(256),
@@ -38792,7 +39539,7 @@ function boardHostGuard(port) {
38792
39539
  await next();
38793
39540
  };
38794
39541
  }
38795
- 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 }) {
38796
39543
  const app = new Hono();
38797
39544
  const given = tokens ?? null;
38798
39545
  app.use("*", async (c, next) => {
@@ -38808,7 +39555,8 @@ function createApp({ clientDir, root, port, actions, tickets, openRoute, renderF
38808
39555
  app.get("/api/health", (c) => c.json({
38809
39556
  version,
38810
39557
  root,
38811
- tokens: given
39558
+ tokens: given,
39559
+ clipboard: clipboard?.backend ?? null
38812
39560
  }));
38813
39561
  app.route("/", accessRoutes(actions.access, tickets, { openRoute }));
38814
39562
  app.route("/", apiRoutes(root, actions, frames.look, history));
@@ -38821,6 +39569,7 @@ function createApp({ clientDir, root, port, actions, tickets, openRoute, renderF
38821
39569
  app.route("/", tokenRoutes(root, actions.access, history, frames.look));
38822
39570
  app.route("/", editRoutes(root, actions.access, history, settledVersion, frames.look.sheets));
38823
39571
  app.route("/", pngRoutes(root, renderFrame));
39572
+ app.route("/", clipboardRoutes(root, actions.access, renderFrame, clipboard));
38824
39573
  if (checks) app.route("/", checkRoutes(actions.access, checks));
38825
39574
  if (thumbnails) app.route("/", thumbnailRoutes(root, thumbnails));
38826
39575
  app.route("/", frames.routes);
@@ -41498,7 +42247,7 @@ function contentFormat() {
41498
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.`,
41499
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.`,
41500
42249
  `A frame is any *${FRAME_EXTENSION} file directly in a page, named by its stem.`,
41501
- `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.`,
41502
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}.`,
41503
42252
  `Dot-named folders, *${LOCK_SUFFIX} files, and *${TEMP_SUFFIX} files belong to Frameboard and are never content.`
41504
42253
  ],
@@ -41665,7 +42414,8 @@ function registerEdit(program, context) {
41665
42414
  const { io } = context;
41666
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) => {
41667
42416
  const change = changeOf(options);
41668
- const frame = await resolveFrameRef(await boardOf(options, io), ref, {
42417
+ const root = await boardOf(options, io);
42418
+ const frame = await resolveFrameRef(root, ref, {
41669
42419
  project: options.project,
41670
42420
  cwd: io.cwd
41671
42421
  });
@@ -41678,6 +42428,7 @@ function registerEdit(program, context) {
41678
42428
  ref: frameRef,
41679
42429
  index: options.index
41680
42430
  });
42431
+ if (result.hash !== result.from) await followEdit(notesPath(root, frame.project, frame.page), frame.name, result.from, result.hash, result.remap);
41681
42432
  return {
41682
42433
  data: {
41683
42434
  ref: frameRef,
@@ -41717,7 +42468,7 @@ function registerEditing(program, context) {
41717
42468
  const now = /* @__PURE__ */ new Date();
41718
42469
  if (options.release) {
41719
42470
  const session = sessionOf(options.session);
41720
- 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);
41721
42472
  return {
41722
42473
  data: { released },
41723
42474
  human: released.length === 0 ? `${session} held no claim to release` : `Released ${released.map((each) => each.frame).join(", ")}`
@@ -45681,7 +46432,7 @@ function registerNotes(program, context) {
45681
46432
  const pageDir = join(root, place.project, place.page);
45682
46433
  const elements = await resolveAnchors(pageDir, kept);
45683
46434
  listed.push(...kept.map((note) => ({
45684
- ...note,
46435
+ ...forAgent(note),
45685
46436
  ref: `${place.project}/${place.page}/${note.frame}`,
45686
46437
  element: elements[note.id] ?? null,
45687
46438
  ...note.images?.length ? { imagePaths: note.images.map((image) => join(pageDir, image)) } : {}
@@ -45705,7 +46456,7 @@ function registerNotes(program, context) {
45705
46456
  id: replyId
45706
46457
  }))).notes.find((note) => note.id === replyId);
45707
46458
  return {
45708
- data: { note: reply },
46459
+ data: { note: reply && forAgent(reply) },
45709
46460
  human: `Replied to ${reply?.thread ?? id} on ${found.project}/${found.page}/${found.note.frame}`
45710
46461
  };
45711
46462
  });
@@ -45713,8 +46464,9 @@ function registerNotes(program, context) {
45713
46464
  const found = await noteIn(await boardOf(options, io), id, options.project);
45714
46465
  const file = await updateNotes(found.path, (current) => setState(current, id, "done", /* @__PURE__ */ new Date()));
45715
46466
  const rootId = found.note.thread ?? found.note.id;
46467
+ const closed = file.notes.find((note) => note.id === rootId);
45716
46468
  return {
45717
- data: { note: file.notes.find((note) => note.id === rootId) },
46469
+ data: { note: closed && forAgent(closed) },
45718
46470
  human: `Closed ${rootId}`
45719
46471
  };
45720
46472
  });
@@ -46454,507 +47206,6 @@ function createClaimsPush(root, { broadcast, inTurn, now = () => /* @__PURE__ */
46454
47206
  }
46455
47207
  };
46456
47208
  }
46457
- // src/server/history/trash.ts
46458
- const TRASH_FOLDER = "trash";
46459
- /**
46460
- * Where the `index`th path a step takes out waits. The trash sits in `.run/`
46461
- * inside the board root, so taking a path out is a rename on one volume, and
46462
- * the watcher and scanner already skip the dot folder.
46463
- */
46464
- function trashSlot(root, step, index) {
46465
- return join(root, RUN_FOLDER, TRASH_FOLDER, String(step), String(index));
46466
- }
46467
- async function takeOut(path, slot) {
46468
- await mkdir(dirname(slot), { recursive: true });
46469
- await rename(path, slot);
46470
- }
46471
- /** Emptied when the server starts and stops, since the history it serves lives in memory. */
46472
- async function emptyTrash(root) {
46473
- await rm(join(root, RUN_FOLDER, TRASH_FOLDER), {
46474
- recursive: true,
46475
- force: true
46476
- });
46477
- }
46478
- // src/server/history/changes.ts
46479
- /** The records a change writes, whose locks are held while it is checked and written. */
46480
- function lockPaths(change) {
46481
- if (change.kind === "entry" || change.kind === "section") return [change.layout];
46482
- if (change.kind === "pages") return [change.file];
46483
- return [];
46484
- }
46485
- /**
46486
- * Whether the board still stands as `side` of the change left it, read
46487
- * under the record's lock. A change that no longer holds was overtaken, and
46488
- * so was one whose record an agent left unreadable, since writing it back
46489
- * would overwrite that file and keeping the step would block every older one.
46490
- */
46491
- async function holds(change, side) {
46492
- try {
46493
- return await reads(change, side);
46494
- } catch (error) {
46495
- if (error instanceof FrameboardError && UNREADABLE.has(error.code)) return false;
46496
- throw error;
46497
- }
46498
- }
46499
- const UNREADABLE = /* @__PURE__ */ new Set(["layout-invalid", "project-file-invalid"]);
46500
- async function reads(change, side) {
46501
- switch (change.kind) {
46502
- case "entry": {
46503
- const stored = (await readRecord(change.layout, layoutSpec)).frames[change.frame];
46504
- return isDeepStrictEqual(stored, withMeasured(change[side], stored));
46505
- }
46506
- case "section": {
46507
- const file = await readRecord(change.layout, layoutSpec);
46508
- return isDeepStrictEqual(file.sections?.[change.section], change[side]);
46509
- }
46510
- case "pages": {
46511
- const file = await readRecord(change.file, {
46512
- ...projectSpec,
46513
- empty: emptyProject
46514
- });
46515
- return isDeepStrictEqual(file.pages, change[side]);
46516
- }
46517
- case "moved": {
46518
- const [present, absent] = side === "after" ? [change.to, change.from] : [change.from, change.to];
46519
- return await exists(present) && !await exists(absent);
46520
- }
46521
- case "path": return change.present === side ? await exists(change.path) && await hashPath(change.path) === change.hash : !await exists(change.path) && await exists(change.slot);
46522
- case "element": return await exists(change.path) && holdsSpan(await readFile(change.path, "utf8"), change.span, side);
46523
- case "inserted": return await exists(change.path) && holdsInserted(await readFile(change.path, "utf8"), change.span, side === change.present ? "after" : "before");
46524
- case "token": return await exists(change.path) && holdsToken(change, side);
46525
- case "relocated": return await exists(change.path) && relocateMoved(await readFile(change.path, "utf8"), change.span, OTHER[side]) !== void 0;
46526
- }
46527
- }
46528
- /**
46529
- * The entry a step holds, taking the stored size on each axis both it and the
46530
- * stored entry hug, since the server measures that size and the developer
46531
- * never set it, so a measure after a hand move neither overtakes the step nor
46532
- * is reverted by it.
46533
- */
46534
- function withMeasured(entry, stored) {
46535
- if (!entry || !stored) return entry;
46536
- return {
46537
- ...entry,
46538
- ...entry.hugWidth && stored.hugWidth ? { width: stored.width } : {},
46539
- ...entry.hugHeight && stored.hugHeight ? { height: stored.height } : {}
46540
- };
46541
- }
46542
- const OTHER = {
46543
- before: "after",
46544
- after: "before"
46545
- };
46546
- /**
46547
- * Writes `side` of a change back, under the record's lock, once `holds` read
46548
- * the other side. A hand edit's change answers the frame's content hash as it
46549
- * left it, and every other kind answers undefined.
46550
- */
46551
- async function restore(change, side) {
46552
- switch (change.kind) {
46553
- case "entry": {
46554
- const file = await readRecord(change.layout, layoutSpec);
46555
- const frames = { ...file.frames };
46556
- const entry = withMeasured(change[side], frames[change.frame]);
46557
- if (entry) frames[change.frame] = entry;
46558
- else delete frames[change.frame];
46559
- await writeRecord(change.layout, {
46560
- ...file,
46561
- frames
46562
- });
46563
- return;
46564
- }
46565
- case "section": {
46566
- const file = await readRecord(change.layout, layoutSpec);
46567
- const sections = { ...file.sections };
46568
- const entry = change[side];
46569
- if (entry) sections[change.section] = entry;
46570
- else delete sections[change.section];
46571
- await writeRecord(change.layout, {
46572
- ...file,
46573
- sections
46574
- });
46575
- return;
46576
- }
46577
- case "pages": {
46578
- const file = await readRecord(change.file, {
46579
- ...projectSpec,
46580
- empty: emptyProject
46581
- });
46582
- await writeRecord(change.file, {
46583
- ...file,
46584
- pages: change[side]
46585
- });
46586
- return;
46587
- }
46588
- case "moved":
46589
- if (side === "before") await rename(change.to, change.from);
46590
- else await rename(change.from, change.to);
46591
- return;
46592
- case "path":
46593
- if (change.present === side) await rename(change.slot, change.path);
46594
- else await takeOut(change.path, change.slot);
46595
- return;
46596
- case "element": return rewriteFrame(change, (source) => {
46597
- const swapped = swapSpan(source, change.span, OTHER[side]);
46598
- return swapped && {
46599
- html: swapped.html,
46600
- keep: () => {
46601
- change.span = swapped.span;
46602
- }
46603
- };
46604
- });
46605
- case "inserted": return rewriteFrame(change, (source) => {
46606
- const written = side === change.present ? restoreInserted(source, change.span) : removeInserted(source, change.span);
46607
- return written && {
46608
- html: written.html,
46609
- keep: () => {
46610
- change.span = written.span;
46611
- }
46612
- };
46613
- });
46614
- case "relocated": return rewriteFrame(change, (source) => {
46615
- const written = relocateMoved(source, change.span, side);
46616
- return written && {
46617
- html: written.html,
46618
- keep: () => {
46619
- change.span = written.span;
46620
- }
46621
- };
46622
- });
46623
- case "token": return rewriteToken(change, side);
46624
- }
46625
- }
46626
- /** Whether the sheet sets the token exactly as `side` holds it, false for a sheet that no longer parses. */
46627
- async function holdsToken(change, side) {
46628
- try {
46629
- const css = await readFile(change.path, "utf8");
46630
- return isDeepStrictEqual(tokenSides(css, change.name), change[side]);
46631
- } catch (error) {
46632
- if (error instanceof FrameboardError) return false;
46633
- throw error;
46634
- }
46635
- }
46636
- /** Writes `side` of a token change, refusing a sheet that changed between its read and the rename. */
46637
- async function rewriteToken(change, side) {
46638
- const css = await readFile(change.path, "utf8");
46639
- const written = setTokenSides(css, change.name, change[side]);
46640
- 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 });
46641
- }
46642
- /**
46643
- * Writes a hand edit's element to the other side through a temporary file and
46644
- * a rename, reading the file again just before the rename. A write landing
46645
- * before that read is not overwritten: the rewrite is made once more from the
46646
- * fresh bytes, and refused once they change again or no longer hold the
46647
- * element. Bytes that fail a UTF-8 round trip are refused too, since decoding
46648
- * would rewrite each invalid byte outside the element. The change keeps where
46649
- * the element was found, through `keep`, so the next side lands on it.
46650
- */
46651
- async function rewriteFrame(change, rewrite) {
46652
- const temp = join(dirname(change.path), `.${basename(change.path)}.${process.pid}.tmp`);
46653
- let source = await readText(change.path);
46654
- for (let attempt = 0; source !== void 0 && attempt < 2; attempt += 1) {
46655
- const written = rewrite(source);
46656
- if (!written) break;
46657
- await writeFile(temp, written.html);
46658
- const now = await readText(change.path);
46659
- if (now === source) {
46660
- await rename(temp, change.path);
46661
- written.keep();
46662
- return contentHash(written.html);
46663
- }
46664
- source = now;
46665
- }
46666
- await rm(temp, { force: true });
46667
- throw new FrameboardError("undo-overtaken", `An agent changed ${basename(change.path, FRAME_EXTENSION)} after your edit, so that step was dropped.`, { change: change.kind });
46668
- }
46669
- /** A frame file's text, or undefined when its bytes do not survive a UTF-8 round trip. */
46670
- async function readText(path) {
46671
- const bytes = await readFile(path);
46672
- const text = bytes.toString("utf8");
46673
- return Buffer.from(text, "utf8").equals(bytes) ? text : void 0;
46674
- }
46675
- /**
46676
- * The journal one board write reports into, building the changes of one
46677
- * step. A path it takes out waits in the step's trash folder.
46678
- */
46679
- var StepJournal = class {
46680
- root;
46681
- id;
46682
- changes = [];
46683
- constructor(root, id) {
46684
- this.root = root;
46685
- this.id = id;
46686
- }
46687
- entry(page, frame, before, after) {
46688
- const layout = join(page, LAYOUT_FILE);
46689
- this.changes.push({
46690
- kind: "entry",
46691
- layout,
46692
- frame,
46693
- before,
46694
- after
46695
- });
46696
- }
46697
- section(page, section, before, after) {
46698
- const layout = join(page, LAYOUT_FILE);
46699
- this.changes.push({
46700
- kind: "section",
46701
- layout,
46702
- section,
46703
- before,
46704
- after
46705
- });
46706
- }
46707
- pages(project, before, after) {
46708
- const file = join(project, PROJECT_FILE);
46709
- this.changes.push({
46710
- kind: "pages",
46711
- file,
46712
- before,
46713
- after
46714
- });
46715
- }
46716
- async moved(from, to) {
46717
- await rename(from, to);
46718
- this.changes.push({
46719
- kind: "moved",
46720
- from,
46721
- to
46722
- });
46723
- }
46724
- /** The element a hand edit rewrote in a frame file, which this journal does not write. */
46725
- element(path, ref, span) {
46726
- this.changes.push({
46727
- kind: "element",
46728
- path,
46729
- ref,
46730
- span
46731
- });
46732
- }
46733
- /** The element a placement tool wrote into a frame file, which this journal does not write. */
46734
- inserted(path, ref, span) {
46735
- this.changes.push({
46736
- kind: "inserted",
46737
- path,
46738
- ref,
46739
- span,
46740
- present: "after"
46741
- });
46742
- }
46743
- /** The element a hand delete took out of a frame file, which this journal does not write. */
46744
- deletedElement(path, ref, span) {
46745
- this.changes.push({
46746
- kind: "inserted",
46747
- path,
46748
- ref,
46749
- span,
46750
- present: "before"
46751
- });
46752
- }
46753
- /** The element a hand move took to another gap of a frame file, which this journal does not write. */
46754
- relocated(path, ref, span) {
46755
- this.changes.push({
46756
- kind: "relocated",
46757
- path,
46758
- ref,
46759
- span
46760
- });
46761
- }
46762
- /** One token's project declarations a hand token edit rewrote, which this journal does not write. */
46763
- token(path, name, before, after) {
46764
- this.changes.push({
46765
- kind: "token",
46766
- path,
46767
- name,
46768
- before,
46769
- after
46770
- });
46771
- }
46772
- async created(path) {
46773
- this.changes.push({
46774
- kind: "path",
46775
- path,
46776
- present: "after",
46777
- hash: await hashPath(path),
46778
- slot: this.#slot()
46779
- });
46780
- }
46781
- async removed(path) {
46782
- const hash = await hashPath(path);
46783
- const slot = this.#slot();
46784
- await takeOut(path, slot);
46785
- this.changes.push({
46786
- kind: "path",
46787
- path,
46788
- present: "before",
46789
- hash,
46790
- slot
46791
- });
46792
- }
46793
- #slot() {
46794
- return trashSlot(this.root, this.id, this.changes.length);
46795
- }
46796
- };
46797
- /**
46798
- * A hash over a file's bytes, or over every file in a folder with its path.
46799
- * Dot-named entries, locks, and temp files are left out, as the scanner
46800
- * leaves them, so a lock taken and released reads as no change.
46801
- */
46802
- async function hashPath(path) {
46803
- const hash = createHash("sha256");
46804
- const walk = async (at, name) => {
46805
- if ((await stat(at)).isDirectory()) {
46806
- hash.update(`d:${name}\0`);
46807
- const children = (await readdir(at)).filter(isHashed).sort();
46808
- for (const child of children) await walk(join(at, child), `${name}/${child}`);
46809
- } else {
46810
- hash.update(`f:${name}\0`);
46811
- hash.update(await readFile(at));
46812
- hash.update("\0");
46813
- }
46814
- };
46815
- await walk(path, ".");
46816
- return hash.digest("hex");
46817
- }
46818
- function isHashed(name) {
46819
- return !name.startsWith(".") && !name.endsWith(".lock") && !name.endsWith(".tmp");
46820
- }
46821
- /**
46822
- * Whether the path exists under exactly this name, read from its folder's
46823
- * listing, so a case-only rename on a case-insensitive volume tells the two
46824
- * names apart.
46825
- */
46826
- async function exists(path) {
46827
- try {
46828
- return (await readdir(dirname(path))).includes(basename(path));
46829
- } catch (error) {
46830
- if (isCode(error, "ENOENT")) return false;
46831
- throw error;
46832
- }
46833
- }
46834
- const OPEN = async () => {};
46835
- /**
46836
- * The developer's undo and redo stacks, in memory, holding the board's own
46837
- * writes and never an agent's. Undo and redo run one at a time, each
46838
- * checking every change of a step under its records' locks before writing
46839
- * any, and refusing with `undo-overtaken` and dropping the step when an
46840
- * agent has since changed one.
46841
- */
46842
- var History = class {
46843
- root;
46844
- onChange;
46845
- onWrite;
46846
- #undo = [];
46847
- #redo = [];
46848
- #nextId = 1;
46849
- #turn = Promise.resolve();
46850
- constructor(root, onChange = () => {}, onWrite = () => {}) {
46851
- this.root = root;
46852
- this.onChange = onChange;
46853
- this.onWrite = onWrite;
46854
- }
46855
- counts() {
46856
- return {
46857
- undo: this.#undo.length,
46858
- redo: this.#redo.length
46859
- };
46860
- }
46861
- /** A journal for one write, to pass into the board verb and then record. */
46862
- journal() {
46863
- return new StepJournal(this.root, this.#nextId++);
46864
- }
46865
- /** Pushes a write's step, clearing redo. A write that changed nothing records nothing. */
46866
- record(step) {
46867
- if (step.changes.length === 0) return;
46868
- this.#undo.push(step);
46869
- if (this.#undo.length > 100) this.#undo.shift();
46870
- this.#redo = [];
46871
- this.onChange(this.counts());
46872
- this.onWrite(step, "after");
46873
- }
46874
- /**
46875
- * The refs the top undo or redo step would write, without popping it, so a
46876
- * route can refuse a claimed frame before the step is taken. These are the
46877
- * step's frames, and the page or project folder and frame file each move
46878
- * or removal names, since a page or project step names no frames.
46879
- */
46880
- peek(side) {
46881
- const step = (side === "undo" ? this.#undo : this.#redo).at(-1);
46882
- if (!step) return [];
46883
- const refs = step.changes.flatMap((change) => {
46884
- if (change.kind === "moved") return [change.from, change.to];
46885
- if (change.kind === "path") return [change.path];
46886
- return [];
46887
- }).flatMap((path) => {
46888
- const inBoard = relative(this.root, path);
46889
- if (inBoard === "" || inBoard.startsWith("..") || isAbsolute(inBoard)) return [];
46890
- const ref = inBoard.split(sep).join("/");
46891
- return [ref.endsWith(".html") ? ref.slice(0, -5) : ref];
46892
- });
46893
- return [.../* @__PURE__ */ new Set([...step.frames, ...refs])];
46894
- }
46895
- /**
46896
- * Undoes the top step. `gate` reads what `peek` names of that step in turn,
46897
- * before it is taken, so a refusal it throws leaves the step on its stack
46898
- * and a quick second undo never checks one step and takes another.
46899
- */
46900
- undo(gate = OPEN) {
46901
- return this.#inTurn(() => this.#move(this.#undo, this.#redo, "before", gate));
46902
- }
46903
- /** Redoes the top step, gated as `undo` is. */
46904
- redo(gate = OPEN) {
46905
- return this.#inTurn(() => this.#move(this.#redo, this.#undo, "after", gate));
46906
- }
46907
- /** Takes the top step of `from`, writes `to` side of it, and pushes it onto `onto`. */
46908
- async #move(from, onto, to, gate) {
46909
- const empty = () => new FrameboardError("nothing-to-undo", `There is nothing to ${to === "before" ? "undo" : "redo"}.`);
46910
- if (from.length === 0) throw empty();
46911
- await gate(this.peek(from === this.#undo ? "undo" : "redo"));
46912
- const step = from.pop();
46913
- if (!step) throw empty();
46914
- const was = to === "before" ? "after" : "before";
46915
- const hashes = {};
46916
- const locks = step.changes.flatMap(lockPaths).filter((path) => existsSync(dirname(path)));
46917
- try {
46918
- await withLocks(locks, async () => {
46919
- 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 });
46920
- const ordered = to === "before" ? [...step.changes].reverse() : step.changes;
46921
- for (const change of ordered) {
46922
- const hash = await restore(change, to);
46923
- if (hash !== void 0 && "ref" in change) hashes[change.ref] = hash;
46924
- }
46925
- });
46926
- } catch (error) {
46927
- if (!(error instanceof FrameboardError && error.code === "undo-overtaken")) from.push(step);
46928
- this.onChange(this.counts());
46929
- throw error;
46930
- }
46931
- onto.push(step);
46932
- this.onChange(this.counts());
46933
- this.onWrite(step, to);
46934
- const answer = {
46935
- page: step.page?.[to] ?? null,
46936
- frames: step.frames
46937
- };
46938
- return Object.keys(hashes).length > 0 ? {
46939
- ...answer,
46940
- hashes
46941
- } : answer;
46942
- }
46943
- #inTurn(task) {
46944
- const run = this.#turn.then(task);
46945
- this.#turn = run.catch(() => {});
46946
- return run;
46947
- }
46948
- };
46949
- /** What a refusal names as overtaken, being a frame, a section, a page, or the page order. */
46950
- function nameOf(change) {
46951
- if (change.kind === "entry") return change.frame;
46952
- if (change.kind === "section") return `section ${change.section}`;
46953
- if (change.kind === "pages") return "the page order";
46954
- if (change.kind === "token") return change.name;
46955
- const path = change.kind === "moved" ? change.to : change.path;
46956
- return basename(path, FRAME_EXTENSION);
46957
- }
46958
47209
  // node_modules/readdirp/index.js
46959
47210
  const EntryTypes = {
46960
47211
  FILE_TYPE: "files",
@@ -51076,6 +51327,7 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
51076
51327
  history,
51077
51328
  selection,
51078
51329
  renderFrame,
51330
+ clipboard: clipboardFiles(),
51079
51331
  thumbnails,
51080
51332
  measure,
51081
51333
  frameVersion: tracker.version,
@@ -51312,7 +51564,7 @@ async function pushNotes(root, paths, hub, delivery) {
51312
51564
  const parts = relative(root, path).split(sep);
51313
51565
  const [project, page, file] = parts;
51314
51566
  if (parts.length !== 3 || !project || !page || !file) continue;
51315
- const notes = file === NOTES_FILE$1;
51567
+ const notes = file === NOTES_FILE$2;
51316
51568
  if (!notes && !file.endsWith(".html")) continue;
51317
51569
  const key = `${project}/${page}`;
51318
51570
  pages.set(key, {