frameboard 0.31.0 → 0.33.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
@@ -14,7 +14,7 @@ import { fileURLToPath, pathToFileURL } 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, release, tmpdir, type } from "node:os";
17
+ import { homedir, networkInterfaces, release, tmpdir, type } from "node:os";
18
18
  // \0rolldown/runtime.js
19
19
  var __create = Object.create;
20
20
  var __defProp = Object.defineProperty;
@@ -3056,7 +3056,10 @@ const EXIT_CODES = {
3056
3056
  "formatter-not-found": 9,
3057
3057
  "references-stale": 14,
3058
3058
  "page-file-load": 10,
3059
- "image-missing": 10
3059
+ "image-missing": 10,
3060
+ "motion-missing": 10,
3061
+ "motion-unbounded": 10,
3062
+ "no-network-address": 3
3060
3063
  };
3061
3064
  var FrameboardError = class extends Error {
3062
3065
  code;
@@ -3179,10 +3182,7 @@ async function acquire(lock, timeoutMs) {
3179
3182
  if (!isCode(error, "EEXIST")) throw error;
3180
3183
  }
3181
3184
  const stale = await staleContent(lock);
3182
- if (stale !== null) {
3183
- await breakLock(lock, stale);
3184
- continue;
3185
- }
3185
+ if (stale !== null && await breakLock(lock, stale)) continue;
3186
3186
  if (Date.now() >= deadline) throw new FrameboardError("lock-timeout", `Another writer held ${lock} for more than ${timeoutMs} ms.`, { path: lock });
3187
3187
  await setTimeout$1(LOCK_POLL_MS);
3188
3188
  }
@@ -3205,26 +3205,72 @@ async function staleContent(lock) {
3205
3205
  return Number.isInteger(pid) && !isAlive(pid) ? text : null;
3206
3206
  }
3207
3207
  /**
3208
- * Breaks a stale lock by renaming it aside, so of two waiters judging one
3209
- * lock stale only the first rename wins. A waiter whose rename caught a fresh
3210
- * lock instead, taken since it judged, puts that lock back.
3208
+ * Breaks a stale lock under a guard, so one writer at a time re-reads the
3209
+ * lock and retires it only while it still holds the content judged stale.
3210
+ * Without the guard, a second breaker could rename aside the lock a first
3211
+ * one had just taken, and put it back after its owner released it, leaving
3212
+ * a lock nobody holds. A guard a crashed breaker left behind ages out like a
3213
+ * lock. False while another breaker holds the guard, so the caller waits.
3211
3214
  */
3212
3215
  async function breakLock(lock, judged) {
3213
- const aside = `${lock.slice(0, -5)}.${randomBytes(4).toString("hex")}.broken${LOCK_SUFFIX}`;
3216
+ const guard = `${lock.slice(0, -5)}.break${LOCK_SUFFIX}`;
3217
+ const nonce = randomBytes(8).toString("hex");
3214
3218
  try {
3215
- await rename(lock, aside);
3219
+ const handle = await open(guard, "wx");
3220
+ await handle.writeFile(nonce);
3221
+ await handle.close();
3222
+ } catch (error) {
3223
+ if (!isCode(error, "EEXIST")) throw error;
3224
+ await clearAgedGuard(guard);
3225
+ return false;
3226
+ }
3227
+ try {
3228
+ if (await readOrNull$1(lock) === judged) await retire(lock, judged);
3229
+ return true;
3230
+ } finally {
3231
+ if (await readOrNull$1(guard) === nonce) await rm(guard, { force: true });
3232
+ }
3233
+ }
3234
+ async function clearAgedGuard(guard) {
3235
+ let text;
3236
+ let modifiedAt;
3237
+ try {
3238
+ [text, {mtimeMs: modifiedAt}] = await Promise.all([readFile(guard, "utf8"), stat(guard)]);
3216
3239
  } catch (error) {
3217
3240
  if (isCode(error, "ENOENT")) return;
3218
3241
  throw error;
3219
3242
  }
3243
+ if (Date.now() - modifiedAt > LOCK_STALE_MS) await retire(guard, text);
3244
+ }
3245
+ /**
3246
+ * Removes a file by renaming it aside, so of two writers retiring it only
3247
+ * the first rename wins. A rename that caught a newer file, written since
3248
+ * the content was judged, puts that file back.
3249
+ */
3250
+ async function retire(path, judged) {
3251
+ const aside = `${path.slice(0, -5)}.${randomBytes(4).toString("hex")}.broken${LOCK_SUFFIX}`;
3220
3252
  try {
3221
- if (await readFile(aside, "utf8") !== judged) await link(aside, lock).catch((error) => {
3253
+ await rename(path, aside);
3254
+ } catch (error) {
3255
+ if (isCode(error, "ENOENT")) return;
3256
+ throw error;
3257
+ }
3258
+ try {
3259
+ if (await readFile(aside, "utf8") !== judged) await link(aside, path).catch((error) => {
3222
3260
  if (!isCode(error, "EEXIST")) throw error;
3223
3261
  });
3224
3262
  } finally {
3225
3263
  await rm(aside, { force: true });
3226
3264
  }
3227
3265
  }
3266
+ async function readOrNull$1(path) {
3267
+ try {
3268
+ return await readFile(path, "utf8");
3269
+ } catch (error) {
3270
+ if (isCode(error, "ENOENT")) return null;
3271
+ throw error;
3272
+ }
3273
+ }
3228
3274
  /** Removes the lock only while it still holds this writer's nonce. */
3229
3275
  async function release$2(lock, nonce) {
3230
3276
  try {
@@ -9034,6 +9080,87 @@ function superRefine(fn, params) {
9034
9080
  function datetime(params) {
9035
9081
  return /* @__PURE__ */ _isoDateTime(ZodISODateTime, params);
9036
9082
  }
9083
+ // src/shared/frame-device.ts
9084
+ /** The devices the board can draw around a frame. */
9085
+ const DEVICES = ["phone", "tablet"];
9086
+ /**
9087
+ * The phone's border is a current Pro's body less its display, 71.9 mm
9088
+ * across holding 1206 pixels at 460 ppi, which is 16 points a side. The
9089
+ * tablet's is a 13-inch Pro's, 215.5 mm across holding 2064 pixels at 264
9090
+ * ppi, which is 44. The tablet's screen radius is a guess no source backs.
9091
+ */
9092
+ const BEZELS = {
9093
+ phone: {
9094
+ border: 16,
9095
+ screenRadius: 62,
9096
+ bodyRadius: 78
9097
+ },
9098
+ tablet: {
9099
+ border: 44,
9100
+ screenRadius: 18,
9101
+ bodyRadius: 62
9102
+ }
9103
+ };
9104
+ /**
9105
+ * The body's colors, fixed in both themes, since the board draws hardware
9106
+ * rather than chrome: the body, the hairline around it, and the island.
9107
+ */
9108
+ const BEZEL_COLORS = {
9109
+ body: "#17181b",
9110
+ edge: "#45484f",
9111
+ island: "#050506",
9112
+ homeBar: "rgba(128, 128, 128, 0.6)"
9113
+ };
9114
+ /**
9115
+ * The phone's island, a generic pill standing in for a size no source gives,
9116
+ * and the home bar, each centered on the screen and drawn over the frame.
9117
+ */
9118
+ const PHONE_ISLAND = {
9119
+ width: 81,
9120
+ height: 30,
9121
+ top: 14
9122
+ };
9123
+ const HOME_BAR = {
9124
+ width: 140,
9125
+ height: 5,
9126
+ bottom: 8
9127
+ };
9128
+ /**
9129
+ * The CSS `box-shadow` drawing a device's body: a spread the border wide
9130
+ * around a box rounded to the screen radius, which also covers the frame's
9131
+ * corners past that radius, so the body's outer radius is the screen's plus
9132
+ * the border. On the board a hairline edge one screen pixel wide rings it at
9133
+ * any zoom, so a dark body still reads on a dark canvas, under a drop shadow.
9134
+ * The export keeps the body to the border, its last pixel the edge, and
9135
+ * leaves out the drop shadow, which would fall past the PNG's edge.
9136
+ */
9137
+ function bezelShadow(device, { board = true } = {}) {
9138
+ const { border } = BEZELS[device];
9139
+ if (!board) return [`0 0 0 ${border - 1}px ${BEZEL_COLORS.body}`, `0 0 0 ${border}px ${BEZEL_COLORS.edge}`].join(", ");
9140
+ return [
9141
+ `0 0 0 ${border}px ${BEZEL_COLORS.body}`,
9142
+ `0 0 0 calc(${border}px + 1px / var(--zoom, 1)) ${BEZEL_COLORS.edge}`,
9143
+ `0 ${border}px ${border * 3}px rgba(0, 0, 0, 0.3)`
9144
+ ].join(", ");
9145
+ }
9146
+ /**
9147
+ * A layout entry's `device` value, or null for anything but a known device,
9148
+ * so a value no reader understands reads as a frame with no device.
9149
+ */
9150
+ function deviceOf(value) {
9151
+ return DEVICES.find((device) => device === value) ?? null;
9152
+ }
9153
+ /** The box a device's body covers around a frame's box, the box itself with none. */
9154
+ function bezelBox(box, device) {
9155
+ if (!device) return { ...box };
9156
+ const { border } = BEZELS[device];
9157
+ return {
9158
+ x: box.x - border,
9159
+ y: box.y - border,
9160
+ width: box.width + 2 * border,
9161
+ height: box.height + 2 * border
9162
+ };
9163
+ }
9037
9164
  // src/shared/frame-sizes.ts
9038
9165
  /** The current iPhone, iPad Air portrait, and a common laptop viewport. */
9039
9166
  const FRAME_SIZES = {
@@ -9089,6 +9216,13 @@ const DEVICE_SIZES = [
9089
9216
  width: 393,
9090
9217
  height: 852
9091
9218
  },
9219
+ {
9220
+ name: "iphone-18-pro",
9221
+ label: "iPhone 18 Pro",
9222
+ group: "phone",
9223
+ width: 402,
9224
+ height: 874
9225
+ },
9092
9226
  {
9093
9227
  name: "android",
9094
9228
  label: "Android",
@@ -9158,6 +9292,20 @@ const DEVICE_SIZES = [
9158
9292
  group: "social",
9159
9293
  width: 1200,
9160
9294
  height: 627
9295
+ },
9296
+ {
9297
+ name: "video-landscape",
9298
+ label: "Video landscape",
9299
+ group: "video",
9300
+ width: 1920,
9301
+ height: 1080
9302
+ },
9303
+ {
9304
+ name: "video-portrait",
9305
+ label: "Video portrait",
9306
+ group: "video",
9307
+ width: 1080,
9308
+ height: 1920
9161
9309
  }
9162
9310
  ];
9163
9311
  /** Every size name, the three presets first, then the devices. */
@@ -9239,16 +9387,21 @@ function linkedBoxes(box, widths) {
9239
9387
  }
9240
9388
  return boxes;
9241
9389
  }
9242
- /** The box holding a frame and every linked width it draws, the frame's own with none. */
9243
- function drawnExtent(box, widths) {
9244
- const boxes = linkedBoxes(box, widths);
9245
- const last = boxes.at(-1);
9246
- if (!last) return { ...box };
9390
+ /**
9391
+ * The box holding a frame, the device body drawn around it, and every linked
9392
+ * width it draws, the frame's own with neither. Linked widths draw no device.
9393
+ */
9394
+ function drawnExtent(box, widths, device) {
9395
+ const boxes = [bezelBox(box, device), ...linkedBoxes(box, widths)];
9396
+ const left = Math.min(...boxes.map(({ x }) => x));
9397
+ const top = Math.min(...boxes.map(({ y }) => y));
9398
+ const right = Math.max(...boxes.map(({ x, width }) => x + width));
9399
+ const bottom = Math.max(...boxes.map(({ y, height }) => y + height));
9247
9400
  return {
9248
- x: box.x,
9249
- y: box.y,
9250
- width: last.x + last.width - box.x,
9251
- height: Math.max(box.height, ...boxes.map(({ height }) => height))
9401
+ x: left,
9402
+ y: top,
9403
+ width: right - left,
9404
+ height: bottom - top
9252
9405
  };
9253
9406
  }
9254
9407
  // src/shared/records/board.ts
@@ -9284,7 +9437,8 @@ const layoutEntrySchema = looseObject({
9284
9437
  widths: union([array$1(looseObject({
9285
9438
  width: int$1().min(1),
9286
9439
  height: int$1().min(1)
9287
- })), unknown()]).optional()
9440
+ })), unknown()]).optional(),
9441
+ device: unknown().optional()
9288
9442
  });
9289
9443
  /** A named box grouping the frames whose center it holds, which it never lists. */
9290
9444
  const sectionEntrySchema = looseObject({
@@ -9415,6 +9569,7 @@ function placeFrames(frames, names) {
9415
9569
  continue;
9416
9570
  }
9417
9571
  const scroll = entry.scroll ?? false;
9572
+ const device = deviceOf(entry.device);
9418
9573
  placements.set(name, {
9419
9574
  box: {
9420
9575
  x: entry.x,
@@ -9429,6 +9584,7 @@ function placeFrames(frames, names) {
9429
9584
  hugHeight: !scroll && (entry.hugHeight ?? false),
9430
9585
  scroll,
9431
9586
  widths: widthsOf(entry.widths),
9587
+ ...device ? { device } : {},
9432
9588
  placed: true
9433
9589
  });
9434
9590
  }
@@ -9447,8 +9603,8 @@ function placeFrames(frames, names) {
9447
9603
  * the first unplaced file, placing any other past the placed frames alone.
9448
9604
  */
9449
9605
  function placeNext(placed) {
9450
- const right = Math.max(...placed.map(({ box, widths }) => {
9451
- const extent = drawnExtent(box, widths);
9606
+ const right = Math.max(...placed.map(({ box, widths, device }) => {
9607
+ const extent = drawnExtent(box, widths, device);
9452
9608
  return extent.x + extent.width + 80;
9453
9609
  }), 0);
9454
9610
  const order = Math.max(...placed.map((placement) => placement.order + 1), 0);
@@ -9633,7 +9789,7 @@ async function isDirectory(path) {
9633
9789
  }
9634
9790
  }
9635
9791
  // package.json
9636
- var version$1 = "0.31.0";
9792
+ var version$1 = "0.33.0";
9637
9793
  var dependencies = { "playwright-core": "1.65.0" };
9638
9794
  var peerDependencies = { "oxfmt": "0.77.0" };
9639
9795
  // src/shared/version.ts
@@ -10147,7 +10303,8 @@ async function addFrame(root, ref, options) {
10147
10303
  },
10148
10304
  ...hugs,
10149
10305
  scroll,
10150
- widths
10306
+ widths,
10307
+ ...options.device ? { device: options.device } : {}
10151
10308
  });
10152
10309
  layout.renumber();
10153
10310
  }, journal);
@@ -10257,32 +10414,34 @@ async function renameFrame(root, ref, newName, options) {
10257
10414
  async function resizeFrame(root, ref, options) {
10258
10415
  const size = sizeOf(options);
10259
10416
  if (Object.keys(size).length === 0 && options.scroll === void 0 && options.widths === void 0) throw new FrameboardError("usage", "Pass --size, --width, --height, --scroll, --no-scroll, --widths, or --no-widths to resize a frame.");
10260
- return updatePlacement(root, ref, options, (placement, frameRef) => {
10261
- const scroll = options.scroll ?? placement.scroll;
10262
- const width = size.width ?? placement.box.width;
10263
- const drops = scroll && placement.hugHeight && size.height === void 0;
10264
- const hugWidth = !scroll && placement.hugWidth && size.width === void 0;
10265
- const widths = linkedWidths(frameRef, options.widths ?? placement.widths.map((linked) => linked.width), {
10266
- width,
10267
- hugWidth,
10268
- held: placement.widths
10269
- });
10270
- return {
10271
- ...placement,
10272
- box: {
10273
- ...placement.box,
10274
- ...size,
10275
- ...drops ? { height: referenceHeight(width) } : {}
10276
- },
10277
- hugWidth,
10278
- hugHeight: !scroll && placement.hugHeight && size.height === void 0,
10279
- scroll,
10280
- widths: scroll && placement.hugHeight ? widths.map((linked) => ({
10281
- ...linked,
10282
- height: referenceHeight(linked.width)
10283
- })) : widths
10284
- };
10417
+ return updatePlacement(root, ref, options, (placement, frameRef) => resizedPlacement(placement, frameRef, size, options));
10418
+ }
10419
+ /** The placement `resizeFrame` writes, for the size it read off its options. */
10420
+ function resizedPlacement(placement, frameRef, size, options) {
10421
+ const scroll = options.scroll ?? placement.scroll;
10422
+ const width = size.width ?? placement.box.width;
10423
+ const drops = scroll && placement.hugHeight && size.height === void 0;
10424
+ const hugWidth = !scroll && placement.hugWidth && size.width === void 0;
10425
+ const widths = linkedWidths(frameRef, options.widths ?? placement.widths.map((linked) => linked.width), {
10426
+ width,
10427
+ hugWidth,
10428
+ held: placement.widths
10285
10429
  });
10430
+ return {
10431
+ ...placement,
10432
+ box: {
10433
+ ...placement.box,
10434
+ ...size,
10435
+ ...drops ? { height: referenceHeight(width) } : {}
10436
+ },
10437
+ hugWidth,
10438
+ hugHeight: !scroll && placement.hugHeight && size.height === void 0,
10439
+ scroll,
10440
+ widths: scroll && placement.hugHeight ? widths.map((linked) => ({
10441
+ ...linked,
10442
+ height: referenceHeight(linked.width)
10443
+ })) : widths
10444
+ };
10286
10445
  }
10287
10446
  /**
10288
10447
  * The linked widths a verb writes, keeping the height each one already held
@@ -10311,9 +10470,9 @@ function linkedWidths(ref, requested, { width, hugWidth, held }) {
10311
10470
  height: held.find((each) => each.width === linked)?.height ?? referenceHeight(linked)
10312
10471
  }));
10313
10472
  }
10314
- /** The x a copy placed beside a frame takes, past the row of linked widths it draws. */
10315
- function pastExtent({ box, widths }) {
10316
- const extent = drawnExtent(box, widths);
10473
+ /** The x a copy placed beside a frame takes, past its device and the row of linked widths it draws. */
10474
+ function pastExtent({ box, widths, device }) {
10475
+ const extent = drawnExtent(box, widths, device);
10317
10476
  return extent.x + extent.width + 80;
10318
10477
  }
10319
10478
  /**
@@ -10325,18 +10484,73 @@ function pastExtent({ box, widths }) {
10325
10484
  async function fitHeight(root, ref, height, options) {
10326
10485
  return updatePlacement(root, ref, options, (placement) => {
10327
10486
  if (placement.scroll) throw fitScrollError(ref);
10328
- return {
10329
- ...placement,
10330
- box: {
10331
- ...placement.box,
10332
- height
10333
- },
10334
- hugHeight: true,
10335
- widths: placement.widths.map((linked) => ({
10336
- ...linked,
10337
- height: options.widths?.find((each) => each.width === linked.width)?.height ?? linked.height
10338
- }))
10339
- };
10487
+ return fittedPlacement(placement, height, options.widths);
10488
+ });
10489
+ }
10490
+ /** A placement hugging its measured height, each listed linked width taking its own. */
10491
+ function fittedPlacement(placement, height, widths) {
10492
+ return {
10493
+ ...placement,
10494
+ box: {
10495
+ ...placement.box,
10496
+ height
10497
+ },
10498
+ hugHeight: true,
10499
+ widths: placement.widths.map((linked) => ({
10500
+ ...linked,
10501
+ height: widths?.find((each) => each.width === linked.width)?.height ?? linked.height
10502
+ }))
10503
+ };
10504
+ }
10505
+ /**
10506
+ * Sets how each frame holds its height in one write under one lock, all of
10507
+ * them or none. `fixed` keeps the box and clears hugging and scroll. `fit`
10508
+ * takes the measured height and hugs it, clearing scroll. `scroll` fixes both
10509
+ * axes as `frame resize --scroll` does. Every frame is checked before any is
10510
+ * set: one moved or sized since its `expected` refuses `stale-layout`, leaving
10511
+ * out an axis the frame hugs, since the server measures that one, and a `fit`
10512
+ * without `measured` refuses `usage`.
10513
+ */
10514
+ async function setHeightModes(root, targets, mode, options) {
10515
+ const frames = await Promise.all(targets.map(async (target) => ({
10516
+ target,
10517
+ frame: await resolveFrameRef(root, target.ref, options)
10518
+ })));
10519
+ await withLayouts(frames.map(({ frame }) => pageDir(frame)), async (layouts) => {
10520
+ const next = frames.map(({ target, frame }) => {
10521
+ const layout = layoutAt(layouts, pageDir(frame));
10522
+ const placement = layout.placement(frame.name);
10523
+ const frameRef = refOf$1(frame);
10524
+ refuseStale(frameRef, placement, target.expected);
10525
+ return {
10526
+ layout,
10527
+ name: frame.name,
10528
+ placement: heightPlacement(placement, frameRef, mode, target.measured)
10529
+ };
10530
+ });
10531
+ for (const { layout, name, placement } of next) layout.set(name, placement);
10532
+ }, options.journal);
10533
+ return Promise.all(frames.map(({ frame }) => frameRecord(root, frame.project, frame.page, frame.name)));
10534
+ }
10535
+ function heightPlacement(placement, frameRef, mode, measured) {
10536
+ if (mode === "scroll") return resizedPlacement(placement, frameRef, {}, { scroll: true });
10537
+ if (mode === "fixed") return {
10538
+ ...placement,
10539
+ hugHeight: false,
10540
+ scroll: false
10541
+ };
10542
+ if (!measured) throw new FrameboardError("usage", `Fitting ${frameRef} needs its measured height.`, { ref: frameRef });
10543
+ return {
10544
+ ...fittedPlacement(placement, measured.height, measured.widths),
10545
+ scroll: false
10546
+ };
10547
+ }
10548
+ function refuseStale(ref, placement, expected) {
10549
+ const { box } = placement;
10550
+ if (!(box.x === expected.x && box.y === expected.y && (placement.hugWidth || box.width === expected.width) && (placement.hugHeight || box.height === expected.height))) throw new FrameboardError("stale-layout", `${ref} moved since this edit began, so nothing was written.`, {
10551
+ ref,
10552
+ stored: boxOf(box),
10553
+ expected
10340
10554
  });
10341
10555
  }
10342
10556
  /** The refusal a fit of a scroll frame answers, before or after measuring. */
@@ -10498,6 +10712,20 @@ async function setFrameFlag(root, ref, flag, { on, ...options }) {
10498
10712
  [flag]: on
10499
10713
  }));
10500
10714
  }
10715
+ /**
10716
+ * Sets the device the board draws around a frame, or clears it with null.
10717
+ * The frame's file and box are left as they stand, since the bezel wraps
10718
+ * whatever size the frame is.
10719
+ */
10720
+ async function setFrameDevice(root, ref, device, options) {
10721
+ return updatePlacement(root, ref, options, (placement) => {
10722
+ const { device: _held, ...rest } = placement;
10723
+ return device ? {
10724
+ ...rest,
10725
+ device
10726
+ } : rest;
10727
+ });
10728
+ }
10501
10729
  async function deleteFrame(root, ref, options) {
10502
10730
  const { journal } = options;
10503
10731
  const frame = await resolveFrameRef(root, ref, options);
@@ -10591,9 +10819,11 @@ var PageLayout = class {
10591
10819
  * written once it is on or when the entry holds it, and a scroll entry
10592
10820
  * writes both hug flags false, since it fixes both axes. `widths` is
10593
10821
  * written while it lists one and removed once it lists none, and a held
10594
- * value no reader understands is left as it stands.
10822
+ * value no reader understands is left as it stands. `device` is written
10823
+ * while the frame holds one and removed once it is cleared, leaving a held
10824
+ * value no reader understands as `widths` does.
10595
10825
  */
10596
- set(name, { box, order, hidden, locked, scroll, widths, hugWidth: hugsWidth, hugHeight: hugsHeight }) {
10826
+ set(name, { box, order, hidden, locked, scroll, widths, device, hugWidth: hugsWidth, hugHeight: hugsHeight }) {
10597
10827
  const hugWidth = hugsWidth && !scroll;
10598
10828
  const hugHeight = hugsHeight && !scroll;
10599
10829
  const held = this.file.frames[name];
@@ -10612,9 +10842,11 @@ var PageLayout = class {
10612
10842
  ...widths.length > 0 ? { widths: widths.map(({ width, height }) => ({
10613
10843
  width,
10614
10844
  height
10615
- })) } : {}
10845
+ })) } : {},
10846
+ ...device ? { device } : {}
10616
10847
  };
10617
10848
  if (widths.length === 0 && widthsOf(held?.widths).length > 0) delete entry.widths;
10849
+ if (!device && deviceOf(held?.device)) delete entry.device;
10618
10850
  this.file.frames[name] = entry;
10619
10851
  this.changed = true;
10620
10852
  }
@@ -36445,15 +36677,7 @@ function starterSheet({ accent, font }) {
36445
36677
  }
36446
36678
  // src/server/edit/insert.ts
36447
36679
  const SHAPE_SIZE = 100;
36448
- const FILL_TOKENS = [
36449
- "--muted",
36450
- "--secondary",
36451
- "--accent"
36452
- ];
36453
- const LINE_TOKEN = "--border";
36454
36680
  const TEXT_FONT_TOKEN = "--font-text";
36455
- /** Raw on purpose, so the check names it once the project sets no color token. */
36456
- const RAW_GREY = "#d9d9d9";
36457
36681
  const PAINT_VALUE = /^(?:var\(--[\w-]+\)|#[0-9a-f]{6})$/i;
36458
36682
  /** Elements no new element can sit inside, by what the parser does with one there. */
36459
36683
  const CLOSED = /* @__PURE__ */ new Set([
@@ -36481,21 +36705,6 @@ const CLOSED = /* @__PURE__ */ new Set([
36481
36705
  "head"
36482
36706
  ]);
36483
36707
  /**
36484
- * A shape's fill, being the first of the muted, secondary, and accent tokens
36485
- * the project sets, else its first color token, and its line, being the
36486
- * border token else that first color token. With no color token at all, both
36487
- * are a raw grey.
36488
- */
36489
- function shapePaint(tokens) {
36490
- const names = new Set(tokens.map((row) => row.name));
36491
- const firstColor = tokens.find((row) => row.group === "color")?.name;
36492
- const paint = (name) => name === void 0 ? RAW_GREY : `var(${name})`;
36493
- return {
36494
- fill: paint(FILL_TOKENS.find((name) => names.has(name)) ?? firstColor),
36495
- line: paint(names.has(LINE_TOKEN) ? LINE_TOKEN : firstColor)
36496
- };
36497
- }
36498
- /**
36499
36708
  * The family placed text sets, being the project's text font token, else
36500
36709
  * Geist, so a frame with no font of its own still passes `default-font`.
36501
36710
  */
@@ -37472,8 +37681,11 @@ function editFrameFile(path, address, change, sourceAt) {
37472
37681
  * Edits several elements of a frame file as one write, each found again and
37473
37682
  * verified as `editFrameFile` does one, in the order sent through the bytes
37474
37683
  * the one before it left. Any refusal writes nothing, so a batch never lands
37475
- * in part, and naming one element twice is refused since one undo could not
37476
- * put both spans back.
37684
+ * in part. Naming one element twice is refused, since one undo could not
37685
+ * put both spans back, except for a text change beside one style change.
37686
+ * That pair answers one span over the whole element, both changes in it,
37687
+ * since an undo checks every span against the bytes as they stand and the
37688
+ * text's own span no longer reads once the style wrote its start tag.
37477
37689
  */
37478
37690
  function editFrameFileAll(path, hash, edits, sourceAt) {
37479
37691
  const read = readSource(path);
@@ -37491,7 +37703,7 @@ function editFrameFileAll(path, hash, edits, sourceAt) {
37491
37703
  if (!found) return collided(path, was, index, source);
37492
37704
  indexes.push(found.index);
37493
37705
  }
37494
- if (new Set(indexes).size !== indexes.length) return refuse$2("invalid-edit", "a batch names one element twice");
37706
+ if (!namedOnceEach(indexes, edits)) return refuse$2("invalid-edit", "a batch names one element twice");
37495
37707
  let html = source;
37496
37708
  const spans = [];
37497
37709
  for (const [at, { change }] of edits.entries()) {
@@ -37506,11 +37718,46 @@ function editFrameFileAll(path, hash, edits, sourceAt) {
37506
37718
  hash: contentHash(html),
37507
37719
  from: read.hash,
37508
37720
  indexes,
37509
- spans,
37721
+ spans: mergedTwice(source, html, indexes, spans),
37510
37722
  remap: identity
37511
37723
  };
37512
37724
  }
37513
37725
  /**
37726
+ * The spans of a batch with the two of an element named twice put together
37727
+ * as one over the whole element, from its bytes in `source` to its bytes in
37728
+ * `html`, at the place the first of the two held.
37729
+ */
37730
+ function mergedTwice(source, html, indexes, spans) {
37731
+ const twice = indexes.filter((index, at) => indexes.indexOf(index) !== at);
37732
+ if (twice.length === 0) return [...spans];
37733
+ const was = parseFrame(source).elements;
37734
+ const now = parseFrame(html).elements;
37735
+ return spans.flatMap((span, at) => {
37736
+ const index = indexes[at] ?? -1;
37737
+ if (!twice.includes(index)) return [span];
37738
+ if (indexes.indexOf(index) !== at) return [];
37739
+ const before = was[index];
37740
+ const after = now[index];
37741
+ if (!before || !after) return [span];
37742
+ return [{
37743
+ scope: "element",
37744
+ index,
37745
+ count: now.length,
37746
+ before: spanText(source, before, "element"),
37747
+ after: spanText(html, after, "element")
37748
+ }];
37749
+ });
37750
+ }
37751
+ /**
37752
+ * Whether each element a batch names is named once, or twice only as one
37753
+ * `text` change and one `style` or `styles` change.
37754
+ */
37755
+ function namedOnceEach(indexes, edits) {
37756
+ const kinds = /* @__PURE__ */ new Map();
37757
+ for (const [at, index] of indexes.entries()) kinds.set(index, [...kinds.get(index) ?? [], edits[at]?.change.kind ?? ""]);
37758
+ return [...kinds.values()].every((named) => named.length === 1 || named.length === 2 && named.filter((kind) => kind === "text").length === 1 && named.some((kind) => kind === "style" || kind === "styles"));
37759
+ }
37760
+ /**
37514
37761
  * Writes one new element into a frame file the way `editFrameFile` writes an
37515
37762
  * edit, through a temporary file and a rename after reading the file again.
37516
37763
  * A hash the file no longer has is refused as stale with no search, since the
@@ -39255,6 +39502,31 @@ object$1({
39255
39502
  hash,
39256
39503
  count: int$1().min(0)
39257
39504
  });
39505
+ // src/shared/shape-paint.ts
39506
+ const FILL_TOKENS = [
39507
+ "--muted",
39508
+ "--secondary",
39509
+ "--accent"
39510
+ ];
39511
+ const LINE_TOKEN = "--border";
39512
+ /** Raw on purpose, so the check names it once the project sets no color token. */
39513
+ const RAW_GREY = "#d9d9d9";
39514
+ /**
39515
+ * A shape's fill, being the first of the muted, secondary, and accent tokens
39516
+ * the project sets, else its first color token, and its line, being the
39517
+ * border token else that first color token. With no color token at all, both
39518
+ * are a raw grey. The server writes it on a placed shape, and the board
39519
+ * draws a dragged shape's preview in it.
39520
+ */
39521
+ function shapePaint(tokens) {
39522
+ const names = new Set(tokens.map((row) => row.name));
39523
+ const firstColor = tokens.find((row) => row.group === "color")?.name;
39524
+ const paint = (name) => name === void 0 ? RAW_GREY : `var(${name})`;
39525
+ return {
39526
+ fill: paint(FILL_TOKENS.find((name) => names.has(name)) ?? firstColor),
39527
+ line: paint(names.has(LINE_TOKEN) ? LINE_TOKEN : firstColor)
39528
+ };
39529
+ }
39258
39530
  // src/server/routes/edit.ts
39259
39531
  const value = string$1().max(1e4);
39260
39532
  const name$1 = string$1().min(1).max(256);
@@ -40374,9 +40646,11 @@ const CONTENT_TYPES$1 = {
40374
40646
  * each use, so an edit shows on the next load and an unchanged file answers
40375
40647
  * 304 with no body. A frame path carrying `?at=<hash>` serves the
40376
40648
  * version `version` holds under that hash in its place, with the same head,
40377
- * and any other path carrying it answers 404.
40649
+ * and any other path carrying it answers 404. `base` prefixes the sheet URLs
40650
+ * the head imports, for a listener serving these routes under a path of its
40651
+ * own, since the head names them from the server's root.
40378
40652
  */
40379
- function frameRoutes(root, look, version) {
40653
+ function frameRoutes(root, look, version, base = "") {
40380
40654
  const app = new Hono();
40381
40655
  app.get("/frames/*", async (c) => {
40382
40656
  const parts = decodeSegments(new URL(c.req.url).pathname.slice(8).split("/"));
@@ -40431,7 +40705,7 @@ function frameRoutes(root, look, version) {
40431
40705
  if (held === null) return c.notFound();
40432
40706
  bytes = new TextEncoder().encode(held);
40433
40707
  }
40434
- const body = injectHead(bytes, frameHead(sheetUrls(project, look.sheets(project)), contentHash(bytes)));
40708
+ const body = injectHead(bytes, frameHead(sheetUrls(project, look.sheets(project)).map((url) => `${base}${url}`), contentHash(bytes)));
40435
40709
  return c.body(body, 200, {
40436
40710
  "Content-Type": contentType,
40437
40711
  "Cache-Control": "no-store"
@@ -40510,18 +40784,31 @@ async function resolveFile(root, [project, page, ...rest]) {
40510
40784
  if (!project || !page) return null;
40511
40785
  const projectSheet = rest.length === 0 && page === "tokens.css";
40512
40786
  if (rest.length === 0 && !projectSheet) return null;
40513
- if (page !== "assets" && !projectSheet && (rest.length > 1 || isRecord$1(rest[0] ?? ""))) return null;
40787
+ if (page !== "assets" && !projectSheet && (rest.length > 1 || isRecord$2(rest[0] ?? ""))) return null;
40514
40788
  try {
40515
40789
  const projectDir = await realpath(join(root, project));
40516
40790
  if (!projectDir.startsWith(root + sep)) return null;
40517
40791
  const file = await realpath(join(projectDir, page, ...rest));
40518
40792
  if (!file.startsWith(projectDir + sep)) return null;
40793
+ if (!servableInProject(relative(projectDir, file).split(sep))) return null;
40519
40794
  return (await stat(file)).isFile() ? file : null;
40520
40795
  } catch {
40521
40796
  return null;
40522
40797
  }
40523
40798
  }
40524
- function isRecord$1(name) {
40799
+ /**
40800
+ * Whether a file the request reached is one the route may serve, read off
40801
+ * where it really sits in its project rather than the name asked for, so a
40802
+ * symlink in `assets/` naming a record or a dot-named path is refused as the
40803
+ * name itself would be.
40804
+ */
40805
+ function servableInProject(segments) {
40806
+ if (segments.some((segment) => segment.startsWith("."))) return false;
40807
+ const [first = "", name = ""] = segments;
40808
+ if (segments.length === 1) return first === TOKEN_FILE;
40809
+ return first === "assets" || !isRecord$2(name);
40810
+ }
40811
+ function isRecord$2(name) {
40525
40812
  return name === "layout.json" || name === NOTES_FILE$1;
40526
40813
  }
40527
40814
  // src/server/routes/look.ts
@@ -40539,15 +40826,17 @@ const CONTENT_TYPES = {
40539
40826
  * `--tokens` sheet, null for none, or absent to read the one a running
40540
40827
  * server recorded in the address file on each request. `version` serves the
40541
40828
  * frame versions an agent write replaced, absent where nothing holds them.
40829
+ * `base` prefixes the sheet URLs a served frame imports, for a listener that
40830
+ * serves these routes under a path of its own.
40542
40831
  */
40543
- function servedFrames(root, { facesDir, tokens, version }) {
40832
+ function servedFrames(root, { facesDir, tokens, version, base }) {
40544
40833
  const look = { sheets: (project) => tokenSheetPaths(root, project, tokens) };
40545
40834
  const routes = new Hono();
40546
40835
  routes.route("/", lookRoutes({
40547
40836
  facesDir,
40548
40837
  boardSheet: () => boardSheetPath(root, tokens)
40549
40838
  }));
40550
- routes.route("/", frameRoutes(root, look, version));
40839
+ routes.route("/", frameRoutes(root, look, version, base));
40551
40840
  return {
40552
40841
  look,
40553
40842
  routes
@@ -40993,6 +41282,8 @@ const STATUS = {
40993
41282
  "font-missing": 422,
40994
41283
  "image-missing": 422,
40995
41284
  "capture-too-large": 422,
41285
+ "motion-missing": 422,
41286
+ "motion-unbounded": 422,
40996
41287
  "browser-not-found": 503
40997
41288
  };
40998
41289
  /** The route's scale when none is asked for, matching Copy as PNG. */
@@ -41000,23 +41291,36 @@ const DEFAULT_SCALE = 2;
41000
41291
  /**
41001
41292
  * `GET /api/frames/png?ref=<frame-ref>&theme=<light|dark>&scale=<1|2|3>`, a
41002
41293
  * frame rendered at `scale` times its layout size, twice when no scale is
41003
- * given. It takes no token, since the image shows only
41294
+ * given. An added `filmstrip=<n>` of 2 or more renders `n` moments of its
41295
+ * timeline in one row instead, refusing a frame with no timeline as
41296
+ * `motion-missing` and one that never ends as `motion-unbounded`. An added
41297
+ * `device=1` draws a frame holding a device inside its body, and leaves a
41298
+ * frame holding none as it is. A filmstrip draws no device, so the two
41299
+ * together refuse as `usage`. It takes no token, since the image shows only
41004
41300
  * what the frame route already serves, and a refusal answers the CLI's
41005
41301
  * `{ ok, error }` envelope.
41006
41302
  */
41007
- function pngRoutes(root, render) {
41303
+ function pngRoutes(root, render, renderFilmstrip) {
41008
41304
  const app = new Hono();
41009
41305
  app.get("/api/frames/png", async (c) => {
41010
41306
  try {
41011
41307
  const ref = c.req.query("ref") ?? "";
41012
41308
  const theme = c.req.query("theme") ?? "";
41013
41309
  const scale = parseScale$1(c.req.query("scale"));
41014
- if (ref === "" || !isTheme(theme) || scale === null) throw new FrameboardError("usage", "Ask for /api/frames/png?ref=<frame-ref>&theme=<light|dark>&scale=<1|2|3>.", {
41310
+ const filmstrip = parseFilmstrip(c.req.query("filmstrip"));
41311
+ const device = parseDevice(c.req.query("device"));
41312
+ if (ref === "" || !isTheme(theme) || scale === null || filmstrip === null || device === null || device && filmstrip !== void 0) throw new FrameboardError("usage", "Ask for /api/frames/png?ref=<frame-ref>&theme=<light|dark>&scale=<1|2|3>, adding either &filmstrip=<n> of 2 or more for a filmstrip or &device=1 for the frame inside its device.", {
41015
41313
  ref,
41016
41314
  theme,
41017
- scale: c.req.query("scale") ?? null
41315
+ scale: c.req.query("scale") ?? null,
41316
+ filmstrip: c.req.query("filmstrip") ?? null,
41317
+ device: c.req.query("device") ?? null
41018
41318
  });
41019
- const bytes = await render(await readFrame$1(root, ref, { cwd: root }), theme, scale);
41319
+ const { device: held, ...frame } = await readFrame$1(root, ref, { cwd: root });
41320
+ const bytes = filmstrip === void 0 ? await render(device && held ? {
41321
+ ...frame,
41322
+ device: held
41323
+ } : frame, theme, scale) : await renderFilmstrip(frame, theme, scale, filmstrip);
41020
41324
  return c.body(new Uint8Array(bytes), 200, {
41021
41325
  "Content-Type": "image/png",
41022
41326
  "Cache-Control": "no-store"
@@ -41043,6 +41347,115 @@ function parseScale$1(value) {
41043
41347
  if (value === "1" || value === "2" || value === "3") return Number(value);
41044
41348
  return null;
41045
41349
  }
41350
+ function parseDevice(value) {
41351
+ if (value === void 0) return false;
41352
+ return value === "1" ? true : null;
41353
+ }
41354
+ function parseFilmstrip(value) {
41355
+ if (value === void 0) return void 0;
41356
+ if (!/^[1-9][0-9]*$/.test(value)) return null;
41357
+ const count = Number(value);
41358
+ return count >= 2 ? count : null;
41359
+ }
41360
+ // src/server/preview/address.ts
41361
+ /**
41362
+ * The private IPv4 ranges a home or office network hands out, in the order a
41363
+ * phone is likeliest to share: Wi-Fi routers mostly give 192.168, and 172.16
41364
+ * to 172.31 is where container and VM bridges sit.
41365
+ */
41366
+ const PRIVATE_RANGES = [
41367
+ ([a, b]) => a === 192 && b === 168,
41368
+ ([a]) => a === 10,
41369
+ ([a, b = 0]) => a === 172 && b >= 16 && b <= 31
41370
+ ];
41371
+ /**
41372
+ * This machine's IPv4 address on a local network, the one a phone on the same
41373
+ * Wi-Fi can reach, or null when the machine has none. A loopback, a
41374
+ * link-local, or a public address is never picked.
41375
+ */
41376
+ function networkAddress(interfaces = networkInterfaces()) {
41377
+ const candidates = Object.values(interfaces).flatMap((infos) => infos ?? []).filter((info) => info.family === "IPv4" && !info.internal).map((info) => info.address);
41378
+ for (const inRange of PRIVATE_RANGES) {
41379
+ const found = candidates.find((address) => inRange(address.split(".").map(Number)));
41380
+ if (found !== void 0) return found;
41381
+ }
41382
+ return null;
41383
+ }
41384
+ /** The link a phone opens, landing on one frame of the project the listener serves. */
41385
+ function previewLink({ address, port, token, project, page, frame }) {
41386
+ return `http://${address}:${port}/v/${token}/frames/${[
41387
+ project,
41388
+ page,
41389
+ `${frame}${FRAME_EXTENSION}`
41390
+ ].map(encodeURIComponent).join("/")}`;
41391
+ }
41392
+ // src/server/routes/preview.ts
41393
+ /** The port a phone link asks for first, which a machine's one-time route forwards. */
41394
+ const PREVIEW_PORT = 4400;
41395
+ const StartBody = object$1({
41396
+ ref: string$1().min(1),
41397
+ port: number().int().min(0).max(65535).optional()
41398
+ });
41399
+ const StopBody = object$1({ token: string$1().min(1).optional() });
41400
+ /**
41401
+ * `POST /api/preview` with `{ ref, port? }` starts the phone listener for the
41402
+ * frame's project and answers the link landing on that frame, ending any
41403
+ * link already open. `DELETE /api/preview` with `{ token? }` ends it, or only
41404
+ * the listener holding `token`. Both sit behind `requireWriter`, since a
41405
+ * start opens a port to the local network. A machine with no local network
41406
+ * address refuses `no-network-address` and starts nothing.
41407
+ */
41408
+ function previewRoutes(root, access, slot, { address = networkAddress } = {}) {
41409
+ const app = new Hono();
41410
+ app.onError((error, c) => {
41411
+ if (error instanceof FrameboardError && error.code === "no-network-address") return c.json({
41412
+ ok: false,
41413
+ error: {
41414
+ code: error.code,
41415
+ message: error.message,
41416
+ details: {}
41417
+ }
41418
+ }, 503);
41419
+ return answerRefusal(error, c);
41420
+ });
41421
+ app.use("/api/preview", requireWriter(access));
41422
+ app.post("/api/preview", async (c) => {
41423
+ const { ref, port = PREVIEW_PORT } = await parseBody$1(c.req.raw, StartBody);
41424
+ const frame = await resolveFrameRef(root, ref, { cwd: root });
41425
+ const host = address();
41426
+ if (host === null) throw new FrameboardError("no-network-address", "This machine has no address on a local network, so a phone cannot reach it. Join the Wi-Fi the phone is on and try again.");
41427
+ const listener = await slot.start(frame.project, host, port);
41428
+ return c.json({
41429
+ ok: true,
41430
+ data: {
41431
+ url: previewLink({
41432
+ address: host,
41433
+ port: listener.port,
41434
+ token: listener.token,
41435
+ project: frame.project,
41436
+ page: frame.page,
41437
+ frame: frame.name
41438
+ }),
41439
+ address: host,
41440
+ port: listener.port,
41441
+ token: listener.token,
41442
+ project: frame.project,
41443
+ ref: `${frame.project}/${frame.page}/${frame.name}`
41444
+ }
41445
+ });
41446
+ });
41447
+ app.delete("/api/preview", async (c) => {
41448
+ const body = await c.req.json().catch(() => ({}));
41449
+ const parsed = StopBody.safeParse(body);
41450
+ if (!parsed.success) throw new FrameboardError("usage", `The body ${parsed.error.message}`);
41451
+ const stopped = await slot.stop(parsed.data.token);
41452
+ return c.json({
41453
+ ok: true,
41454
+ data: { stopped }
41455
+ });
41456
+ });
41457
+ return app;
41458
+ }
41046
41459
  // src/server/board/paste.ts
41047
41460
  /** Reads each frame's file and placement under its page's lock, in the order given. */
41048
41461
  async function holdFrames(root, refs, options) {
@@ -41248,7 +41661,20 @@ const frameDuplicateSchema = object$1({
41248
41661
  y: coordinate
41249
41662
  }).optional()
41250
41663
  });
41251
- const frameSchema = object$1({ ref });
41664
+ const frameHeightSchema = object$1({
41665
+ refs,
41666
+ mode: _enum$1([
41667
+ "fixed",
41668
+ "fit",
41669
+ "scroll"
41670
+ ]),
41671
+ expected: record(ref, object$1({
41672
+ x: coordinate,
41673
+ y: coordinate,
41674
+ width: int$1().min(1),
41675
+ height: int$1().min(1)
41676
+ })).refine((boxes) => Object.keys(boxes).length <= 1e3)
41677
+ });
41252
41678
  const pasteSchema = object$1({
41253
41679
  ref,
41254
41680
  at: object$1({
@@ -41256,6 +41682,10 @@ const pasteSchema = object$1({
41256
41682
  y: coordinate
41257
41683
  }).optional()
41258
41684
  });
41685
+ const frameDeviceSchema = object$1({
41686
+ refs,
41687
+ device: _enum$1(DEVICES).nullable()
41688
+ });
41259
41689
  const frameFlagSchema = object$1({
41260
41690
  refs,
41261
41691
  flag: _enum$1(["hidden", "locked"]),
@@ -41530,43 +41960,67 @@ function structureRoutes(root, access, history, measure, tokens = null) {
41530
41960
  data: frames
41531
41961
  });
41532
41962
  });
41963
+ /** Sets or clears the device drawn around each frame, in one step, leaving every frame file alone. */
41964
+ app.post("/api/frame/device", async (c) => {
41965
+ const body = await parseBody$1(c.req.raw, frameDeviceSchema);
41966
+ const frames = await eachFrame(body.refs, (frame, journal) => setFrameDevice(root, frame, body.device, {
41967
+ cwd,
41968
+ journal
41969
+ }), (records) => records.map((record) => record.ref));
41970
+ return c.json({
41971
+ ok: true,
41972
+ data: frames
41973
+ });
41974
+ });
41533
41975
  /**
41534
- * Sets one frame's height to its content's own and turns its height
41535
- * hugging on, as `frame fit` does, refusing a frame whose content sizes
41536
- * itself off the viewport. The width is reported, never changed.
41976
+ * Sets how each frame holds its height, `fixed`, `fit`, or `scroll`, in one
41977
+ * step. `expected` holds each frame's box as the caller saw it, keyed by the
41978
+ * ref the body names, and a frame changed since refuses `stale-layout`
41979
+ * before any frame is written. A locked or claimed frame refuses the whole
41980
+ * write, and `fit` measures each frame and its linked widths on the warm
41981
+ * browser first, refusing `browser-not-found` where none runs.
41537
41982
  */
41538
- app.post("/api/frame/fit", async (c) => {
41539
- const body = await parseBody$1(c.req.raw, frameSchema);
41540
- await refuseLocked([body.ref]);
41541
- await refuseHeldFrames([body.ref]);
41542
- if (!measure) throw new FrameboardError("browser-not-found", "Fit height needs the board server's browser, and none runs here.");
41543
- const frame = await readFrame$1(root, body.ref, { cwd });
41544
- if (frame.scroll) throw fitScrollError(frame.ref);
41545
- const measured = await measure(frame);
41546
- const widths = [];
41547
- for (const { width } of frame.widths) {
41548
- const linked = await measure(frame, {
41549
- width,
41550
- height: referenceHeight(width)
41551
- });
41552
- widths.push({
41553
- width,
41554
- height: linked.height
41555
- });
41983
+ app.post("/api/frame/height", async (c) => {
41984
+ const body = await parseBody$1(c.req.raw, frameHeightSchema);
41985
+ const targets = body.refs.map((ref) => {
41986
+ const expected = body.expected[ref];
41987
+ if (!expected) throw new FrameboardError("usage", `The body gives ${ref} no expected box.`, { ref });
41988
+ return {
41989
+ ref,
41990
+ expected
41991
+ };
41992
+ });
41993
+ await refuseLocked(body.refs);
41994
+ await refuseHeldFrames(body.refs);
41995
+ if (body.mode === "fit") {
41996
+ if (!measure) throw new FrameboardError("browser-not-found", "Fit height needs the board server's browser, and none runs here.");
41997
+ for (const target of targets) {
41998
+ const frame = await readFrame$1(root, target.ref, { cwd });
41999
+ const content = await measure(frame);
42000
+ const widths = [];
42001
+ for (const { width } of frame.widths) {
42002
+ const linked = await measure(frame, {
42003
+ width,
42004
+ height: referenceHeight(width)
42005
+ });
42006
+ widths.push({
42007
+ width,
42008
+ height: linked.height
42009
+ });
42010
+ }
42011
+ target.measured = {
42012
+ height: content.height,
42013
+ widths
42014
+ };
42015
+ }
41556
42016
  }
41557
- const fit = await recorded((journal) => fitHeight(root, frame.ref, measured.height, {
42017
+ const frames = await recorded((journal) => setHeightModes(root, targets, body.mode, {
41558
42018
  cwd,
41559
- journal,
41560
- widths
41561
- }), (record) => onFrames([record.ref]));
42019
+ journal
42020
+ }), (records) => onFrames(records.map((record) => record.ref)));
41562
42021
  return c.json({
41563
42022
  ok: true,
41564
- data: {
41565
- frame: fit,
41566
- contentHeight: measured.height,
41567
- contentWidth: measured.contentWidth,
41568
- tooWide: measured.contentWidth > fit.box.width
41569
- }
42023
+ data: frames
41570
42024
  });
41571
42025
  });
41572
42026
  app.post("/api/frame/delete", async (c) => {
@@ -41959,7 +42413,7 @@ function boardHostGuard(port) {
41959
42413
  await next();
41960
42414
  };
41961
42415
  }
41962
- function createApp({ clientDir, root, port, actions, tickets, openRoute, renderFrame, clipboard = null, facesDir, tokens, delivery, dispatch, history, selection, checks, thumbnails, measure, frameVersion, settledVersion, assetUsage }) {
42416
+ function createApp({ clientDir, root, port, actions, tickets, openRoute, renderFrame, renderFilmstrip, clipboard = null, facesDir, tokens, delivery, dispatch, history, selection, checks, thumbnails, measure, frameVersion, settledVersion, assetUsage, preview }) {
41963
42417
  const app = new Hono();
41964
42418
  const given = tokens ?? null;
41965
42419
  app.use("*", async (c, next) => {
@@ -41989,10 +42443,11 @@ function createApp({ clientDir, root, port, actions, tickets, openRoute, renderF
41989
42443
  app.route("/", claimsRoutes(root, actions.access));
41990
42444
  app.route("/", tokenRoutes(root, actions.access, history, frames.look));
41991
42445
  app.route("/", editRoutes(root, actions.access, history, settledVersion, frames.look.sheets));
41992
- app.route("/", pngRoutes(root, renderFrame));
42446
+ app.route("/", pngRoutes(root, renderFrame, renderFilmstrip));
41993
42447
  app.route("/", clipboardRoutes(root, actions.access, renderFrame, clipboard));
41994
42448
  if (checks) app.route("/", checkRoutes(actions.access, checks));
41995
42449
  if (thumbnails) app.route("/", thumbnailRoutes(root, thumbnails));
42450
+ if (preview) app.route("/", previewRoutes(root, actions.access, preview));
41996
42451
  app.route("/", frames.routes);
41997
42452
  app.use("*", serveStatic({ root: clientDir }));
41998
42453
  app.get("/p/*", serveStatic({
@@ -42092,6 +42547,13 @@ async function withFrameHost(board, purpose, run) {
42092
42547
  await host.close();
42093
42548
  }
42094
42549
  }
42550
+ // src/shared/capture-limits.ts
42551
+ /** Chromium's screenshot surface stops at this many pixels on either side. */
42552
+ const MAX_COMPOSITE_SIDE = 16384;
42553
+ /** A filmstrip's width in CSS pixels: `count` copies of the frame in a row, one margin around and between them. */
42554
+ function filmstripWidth(frameWidth, count) {
42555
+ return count * frameWidth + (count + 1) * 40;
42556
+ }
42095
42557
  // src/server/capture/animation-settle.ts
42096
42558
  /**
42097
42559
  * Waits, within `timeoutMs`, until every running animation and transition
@@ -42346,11 +42808,134 @@ async function waitForImages(timeoutMs) {
42346
42808
  });
42347
42809
  return unsettled;
42348
42810
  }
42811
+ // src/shared/motion.ts
42812
+ /**
42813
+ * Finds the timeline a page's motion runs on, taking `__hf` alone when
42814
+ * present, else every `__timelines` entry, else the page's animations, and
42815
+ * resolves null when none registers within `timeoutMs`.
42816
+ *
42817
+ * Capture evaluates this in a page by its source text and the board calls it
42818
+ * on an iframe's window, so it reads nothing outside its own body and takes
42819
+ * its clock, frames, and document from `view`, never the caller's realm.
42820
+ */
42821
+ async function readMotionIn(view, timeoutMs) {
42822
+ const end = view.performance.now() + timeoutMs;
42823
+ const nextFrame = () => new Promise((done) => view.requestAnimationFrame(() => done()));
42824
+ const seconds = (value) => typeof value === "number" && Number.isFinite(value) ? Math.round(value * 1e3) : null;
42825
+ const read = () => {
42826
+ const hf = view.__hf;
42827
+ const hfDuration = seconds(hf?.duration);
42828
+ if (typeof hf?.seek === "function" && hfDuration !== null && hfDuration > 0) return {
42829
+ source: "hf",
42830
+ duration: hfDuration
42831
+ };
42832
+ const registry = view.__timelines;
42833
+ const timelines = Object.values(registry ?? {}).filter((timeline) => typeof timeline?.seek === "function");
42834
+ if (timelines.length > 0) {
42835
+ const finite = timelines.map((timeline) => seconds(typeof timeline.duration === "function" ? timeline.duration.call(timeline) : timeline.duration)).filter((length) => length !== null);
42836
+ return {
42837
+ source: "timelines",
42838
+ duration: finite.length === 0 ? null : Math.max(...finite)
42839
+ };
42840
+ }
42841
+ const animations = view.document.getAnimations();
42842
+ if (animations.length > 0) {
42843
+ const ends = animations.map((animation) => animation.effect?.getComputedTiming().endTime).filter((endTime) => typeof endTime === "number" && Number.isFinite(endTime));
42844
+ return {
42845
+ source: "css",
42846
+ duration: ends.length === 0 ? null : Math.round(Math.max(...ends))
42847
+ };
42848
+ }
42849
+ return null;
42850
+ };
42851
+ await nextFrame();
42852
+ for (;;) {
42853
+ const motion = read();
42854
+ if (motion !== null || view.performance.now() >= end) return motion;
42855
+ await nextFrame();
42856
+ }
42857
+ }
42858
+ /**
42859
+ * Holds the page at `ms`, clamped to the timeline's end, and resolves with
42860
+ * the moment it holds once a frame has painted it. HyperFrames and GSAP take
42861
+ * seconds, and the conversion happens here alone. Self-contained for the
42862
+ * same reason as `readMotionIn`.
42863
+ */
42864
+ async function holdMotionIn(view, { motion, ms }) {
42865
+ const at = motion.duration === null ? ms : Math.min(Math.max(ms, 0), motion.duration);
42866
+ if (motion.source === "hf") await view.__hf.seek(at / 1e3);
42867
+ else if (motion.source === "timelines") {
42868
+ const registry = view.__timelines;
42869
+ for (const timeline of Object.values(registry)) {
42870
+ if (typeof timeline?.seek !== "function") continue;
42871
+ timeline.pause?.();
42872
+ await timeline.seek(at / 1e3);
42873
+ }
42874
+ } else for (const animation of view.document.getAnimations()) {
42875
+ animation.pause();
42876
+ animation.currentTime = at;
42877
+ }
42878
+ await new Promise((done) => view.requestAnimationFrame(() => view.requestAnimationFrame(() => done())));
42879
+ return at;
42880
+ }
42881
+ /**
42882
+ * `count` moments spaced evenly from 0 to the timeline's end inclusive.
42883
+ * Refuses `motion-unbounded` when every animation repeats forever, since no
42884
+ * end exists to space them across.
42885
+ */
42886
+ function filmstripMoments(ref, motion, count) {
42887
+ const { duration } = motion;
42888
+ if (duration === null) throw new FrameboardError("motion-unbounded", `${ref} only runs animations that repeat forever, so a filmstrip has no end to space its moments across. Name the moments with --at instead.`, {
42889
+ ref,
42890
+ source: motion.source
42891
+ });
42892
+ return Array.from({ length: count }, (_, index) => Math.round(duration * index / (count - 1)));
42893
+ }
42894
+ // src/server/capture/seek.ts
42895
+ /**
42896
+ * Stops the page's animation clock, through the DevTools Animation domain,
42897
+ * before the page loads. A CSS animation with no fill that ended during the
42898
+ * load would otherwise drop out of `document.getAnimations()` before the seek
42899
+ * reads it. Script timelines run on their own clocks and keep running.
42900
+ */
42901
+ async function holdAnimationClock(page) {
42902
+ const session = await page.context().newCDPSession(page);
42903
+ await session.send("Animation.enable");
42904
+ await session.send("Animation.setPlaybackRate", { playbackRate: 0 });
42905
+ }
42906
+ /**
42907
+ * Finds the timeline a frame's motion runs on, taking `window.__hf` alone
42908
+ * when present, else every `window.__timelines` entry, else the page's
42909
+ * animations. A script loading its timeline late gets until `timeoutMs` to
42910
+ * register one, and a frame showing none by then refuses `motion-missing`,
42911
+ * since a scene stepped by a script timer cannot be held at a moment.
42912
+ */
42913
+ async function findMotion(page, ref, timeoutMs) {
42914
+ const found = await page.evaluate(inPage(readMotionIn, timeoutMs));
42915
+ if (found === null) throw new FrameboardError("motion-missing", `${ref} shows no animation, transition, window.__hf, or window.__timelines to seek, so it has no moment to capture. A scene a script steps on a timer cannot be held still.`, { ref });
42916
+ return found;
42917
+ }
42918
+ /**
42919
+ * Holds the frame at `ms`, clamped to the timeline's end, and resolves with
42920
+ * the moment it holds once a frame has painted it.
42921
+ */
42922
+ function seekMotion(page, motion, ms) {
42923
+ return page.evaluate(inPage(holdMotionIn, {
42924
+ motion,
42925
+ ms
42926
+ }));
42927
+ }
42928
+ /**
42929
+ * The expression calling a shared window function on the page's own
42930
+ * `window`, by its source text, since Playwright sends a page only text and
42931
+ * the board imports the same function to call on an iframe's window.
42932
+ */
42933
+ function inPage(run, arg) {
42934
+ return `(${run.toString()})(window, ${JSON.stringify(arg)})`;
42935
+ }
42349
42936
  // src/server/capture/render.ts
42350
42937
  /** How long a frame has to load, its faces and images included, before its capture fails. */
42351
42938
  const LOAD_TIMEOUT_MS = 1e4;
42352
- /** Chromium's screenshot surface stops at this many pixels on either side. */
42353
- const MAX_COMPOSITE_SIDE = 16384;
42354
42939
  /**
42355
42940
  * Loads a frame in its own browser context at its layout size, in the theme
42356
42941
  * asked for, and resolves once it has loaded, its faces have settled, and its
@@ -42358,9 +42943,9 @@ const MAX_COMPOSITE_SIDE = 16384;
42358
42943
  * the default, a missing face refuses `font-missing`, an image that failed or
42359
42944
  * outran the budget refuses `image-missing`, and either closes the context.
42360
42945
  * It then waits, on what is left of the budget, for running animations with
42361
- * a finite end to finish, and never refuses for one.
42946
+ * a finite end to finish, and never refuses for one, unless `motion` is `hold`.
42362
42947
  */
42363
- async function openFrame(browser, { baseUrl, ref, box, theme, scale = 1, fonts = "require", timeoutMs = LOAD_TIMEOUT_MS }) {
42948
+ async function openFrame(browser, { baseUrl, ref, box, theme, scale = 1, fonts = "require", timeoutMs = LOAD_TIMEOUT_MS, motion = "settle" }) {
42364
42949
  const context = await browser.newContext({
42365
42950
  viewport: {
42366
42951
  width: box.width,
@@ -42373,6 +42958,7 @@ async function openFrame(browser, { baseUrl, ref, box, theme, scale = 1, fonts =
42373
42958
  const deadline = Date.now() + timeoutMs;
42374
42959
  try {
42375
42960
  const page = await context.newPage();
42961
+ if (motion === "hold") await holdAnimationClock(page);
42376
42962
  await page.goto(new URL(frameThemeUrl(ref, theme), baseUrl).href, {
42377
42963
  timeout: timeoutMs,
42378
42964
  waitUntil: "domcontentloaded"
@@ -42385,7 +42971,7 @@ async function openFrame(browser, { baseUrl, ref, box, theme, scale = 1, fonts =
42385
42971
  await page.evaluate(() => document.fonts.ready.then(() => void 0));
42386
42972
  if (fonts === "require") await assertFontsPresent(page, ref);
42387
42973
  await settleImages(page, ref, fonts, deadline - Date.now());
42388
- if (fonts === "require") await settleAnimations(page, deadline - Date.now());
42974
+ if (fonts === "require" && motion === "settle") await settleAnimations(page, deadline - Date.now());
42389
42975
  return {
42390
42976
  page,
42391
42977
  close
@@ -42446,45 +43032,93 @@ function createWarmRenderer({ baseUrl, browser, scale: defaultScale }) {
42446
43032
  let queue = Promise.resolve();
42447
43033
  return (frame, theme, scale = defaultScale) => {
42448
43034
  const run = queue.then(async () => {
42449
- assertScreenshotFits(frame.ref, frame.box, scale);
42450
- const opened = await openFrame(await browser.get(), {
43035
+ assertScreenshotFits(frame.ref, bezelBox({
43036
+ x: 0,
43037
+ y: 0,
43038
+ ...frame.box
43039
+ }, frame.device), scale);
43040
+ const open = await browser.get();
43041
+ const opened = await openFrame(open, {
42451
43042
  baseUrl: baseUrl(),
42452
43043
  ref: frame.ref,
42453
43044
  box: frame.box,
42454
43045
  theme,
42455
43046
  scale
42456
43047
  });
43048
+ let shot;
42457
43049
  try {
42458
- return await opened.page.screenshot({
43050
+ shot = await opened.page.screenshot({
42459
43051
  animations: "disabled",
42460
43052
  caret: "hide"
42461
43053
  });
42462
43054
  } finally {
42463
43055
  await opened.close();
42464
43056
  }
43057
+ return frame.device ? drawBezel(open, shot, frame.box, frame.device, scale) : shot;
42465
43058
  });
42466
43059
  queue = run.catch(() => {});
42467
43060
  return run;
42468
43061
  };
42469
43062
  }
43063
+ /**
43064
+ * A frame's shot drawn inside a device's body, as the board draws it, on a
43065
+ * page the size of the body, so the PNG holds the body and nothing past it.
43066
+ */
43067
+ async function drawBezel(browser, shot, box, device, scale) {
43068
+ const { border, screenRadius } = BEZELS[device];
43069
+ const outer = bezelBox({
43070
+ x: 0,
43071
+ y: 0,
43072
+ ...box
43073
+ }, device);
43074
+ const context = await browser.newContext({
43075
+ viewport: {
43076
+ width: outer.width,
43077
+ height: outer.height
43078
+ },
43079
+ deviceScaleFactor: scale
43080
+ });
43081
+ try {
43082
+ const page = await context.newPage();
43083
+ const marks = device === "phone" ? `<span style="${pill(PHONE_ISLAND.width, PHONE_ISLAND.height, BEZEL_COLORS.island)}top:${PHONE_ISLAND.top}px"></span><span style="${pill(HOME_BAR.width, HOME_BAR.height, BEZEL_COLORS.homeBar)}bottom:${HOME_BAR.bottom}px"></span>` : "";
43084
+ await page.setContent(`<!doctype html><html><body style="margin:0;background:transparent"><div style="position:absolute;left:${border}px;top:${border}px;width:${box.width}px;height:${box.height}px"><img alt="" src="data:image/png;base64,${shot.toString("base64")}" style="display:block;width:100%;height:100%"><div style="position:absolute;inset:0;border-radius:${screenRadius}px;box-shadow:${bezelShadow(device, { board: false })}">${marks}</div></div></body></html>`, { waitUntil: "load" });
43085
+ return await page.screenshot({
43086
+ omitBackground: true,
43087
+ caret: "hide"
43088
+ });
43089
+ } finally {
43090
+ await context.close();
43091
+ }
43092
+ }
43093
+ function pill(width, height, color) {
43094
+ return `position:absolute;left:50%;transform:translateX(-50%);width:${width}px;height:${height}px;border-radius:${height / 2}px;background:${color};`;
43095
+ }
43096
+ // src/server/capture/images.ts
42470
43097
  const SCREENSHOT = {
42471
43098
  animations: "disabled",
42472
43099
  caret: "hide"
42473
43100
  };
43101
+ const HELD_SCREENSHOT = {
43102
+ animations: "allow",
43103
+ caret: "hide"
43104
+ };
42474
43105
  /**
42475
43106
  * The file name of one image, `<name>.<theme>.png` at 1x so a path an agent
42476
43107
  * saved stays true, and `<name>.<theme>@<n>x.png` at any other scale. A shot
42477
43108
  * scrolled down takes `.scroll-<px>` after the name, the offset asked for,
42478
- * and a linked width takes `@<width>` ahead of both.
43109
+ * and a linked width takes `@<width>` ahead of both. A timed shot takes
43110
+ * `.at-<ms>`, the moment asked for, and a filmstrip `.filmstrip-<n>`, each
43111
+ * after the width.
42479
43112
  */
42480
- function imageName(name, theme, scale, scroll, width) {
43113
+ function imageName(name, theme, scale, scroll, width, moment) {
42481
43114
  const named = width === void 0 ? name : `${name}@${width}`;
42482
- const stem = scroll === void 0 ? named : `${named}.scroll-${scroll}`;
43115
+ const scrolled = scroll === void 0 ? named : `${named}.scroll-${scroll}`;
43116
+ const stem = moment === void 0 ? scrolled : "at" in moment ? `${scrolled}.at-${moment.at}` : `${scrolled}.filmstrip-${moment.filmstrip}`;
42483
43117
  return scale === 1 ? `${stem}.${theme}.png` : `${stem}.${theme}@${scale}x.png`;
42484
43118
  }
42485
43119
  /** Where one frame's capture in one theme lands under `out`. */
42486
- function frameImagePath(out, frame, theme, scale = 1, scroll, width) {
42487
- return join(out, frame.project, frame.page, imageName(frame.name, theme, scale, scroll, width));
43120
+ function frameImagePath(out, frame, theme, scale = 1, scroll, width, moment) {
43121
+ return join(out, frame.project, frame.page, imageName(frame.name, theme, scale, scroll, width, moment));
42488
43122
  }
42489
43123
  /** Where a page's composite in one theme lands under `out`. */
42490
43124
  function compositeImagePath(out, page, theme, scale = 1) {
@@ -42497,7 +43131,7 @@ function compositeImagePath(out, page, theme, scale = 1) {
42497
43131
  * `capture-too-large` past Chromium's screenshot limit.
42498
43132
  */
42499
43133
  function compositeBounds(page, frames, scale = 1) {
42500
- const extents = frames.map(({ box, widths }) => drawnExtent(box, widths ?? []));
43134
+ const extents = frames.map(({ box, widths, device }) => drawnExtent(box, widths ?? [], device));
42501
43135
  const left = Math.min(...extents.map((box) => box.x));
42502
43136
  const top = Math.min(...extents.map((box) => box.y));
42503
43137
  const right = Math.max(...extents.map((box) => box.x + box.width));
@@ -42522,6 +43156,26 @@ function compositeBounds(page, frames, scale = 1) {
42522
43156
  };
42523
43157
  }
42524
43158
  /**
43159
+ * A filmstrip's size: `count` copies of the frame's box in one row, one
43160
+ * margin around and between them. Refuses `capture-too-large` past
43161
+ * Chromium's screenshot limit.
43162
+ */
43163
+ function filmstripBounds(ref, box, count, scale = 1) {
43164
+ const width = filmstripWidth(box.width, count);
43165
+ const height = box.height + 80;
43166
+ if (width * scale > 16384 || height * scale > 16384) throw new FrameboardError("capture-too-large", `A filmstrip of ${count} frames of ${ref}${scale === 1 ? "" : ` at ${scale}x`} would be ${width * scale} by ${height * scale} px, past the ${MAX_COMPOSITE_SIDE} px a browser screenshot holds. Ask for fewer frames or a smaller scale.`, {
43167
+ ref,
43168
+ width,
43169
+ height,
43170
+ scale,
43171
+ max: MAX_COMPOSITE_SIDE
43172
+ });
43173
+ return {
43174
+ width,
43175
+ height
43176
+ };
43177
+ }
43178
+ /**
42525
43179
  * Captures each frame in each theme at its layout size times `scale`, one PNG
42526
43180
  * apiece, and again at each linked width it lists, at the height that width
42527
43181
  * holds. Every image renders before any is written, so a refusal on one frame
@@ -42581,6 +43235,136 @@ async function captureComposite(browser, { baseUrl, page, frames, themes, out, s
42581
43235
  }
42582
43236
  return writeImages(rendered);
42583
43237
  }
43238
+ /**
43239
+ * Captures one frame held at set moments of its timeline, in each theme and
43240
+ * at each width it shows at, or the one `width` names. `timing.at` writes one
43241
+ * PNG per moment, and `timing.filmstrip` one PNG per view and theme holding that many
43242
+ * moments spaced from 0 to the timeline's end. A frame with no seekable
43243
+ * timeline refuses `motion-missing`, and a filmstrip of one that never ends
43244
+ * `motion-unbounded`. Every image renders before any is written.
43245
+ */
43246
+ async function captureMotionImages(browser, { baseUrl, frame, themes, out, scale = 1, width, timing, motionTimeoutMs = LOAD_TIMEOUT_MS }) {
43247
+ const rendered = [];
43248
+ let found = null;
43249
+ for (const view of viewsOf(frame, width)) {
43250
+ const linked = view.width === frame.box.width ? void 0 : view.width;
43251
+ for (const theme of themes) {
43252
+ if ("filmstrip" in timing) {
43253
+ const strip = await renderFilmstrip(browser, {
43254
+ baseUrl,
43255
+ frame: {
43256
+ ref: frame.ref,
43257
+ box: view
43258
+ },
43259
+ theme,
43260
+ scale,
43261
+ count: timing.filmstrip,
43262
+ motionTimeoutMs
43263
+ });
43264
+ found ??= strip.motion;
43265
+ rendered.push({
43266
+ ref: frame.ref,
43267
+ theme,
43268
+ path: frameImagePath(out, frame, theme, scale, void 0, linked, { filmstrip: strip.moments.length }),
43269
+ width: strip.width,
43270
+ height: strip.height,
43271
+ scale,
43272
+ moments: strip.moments,
43273
+ bytes: strip.bytes
43274
+ });
43275
+ continue;
43276
+ }
43277
+ const shots = await holdShots(browser, {
43278
+ baseUrl,
43279
+ ref: frame.ref,
43280
+ view,
43281
+ theme,
43282
+ scale,
43283
+ motionTimeoutMs,
43284
+ moments: () => timing.at
43285
+ });
43286
+ found ??= shots.motion;
43287
+ shots.held.forEach(({ held, bytes }, index) => {
43288
+ rendered.push({
43289
+ ref: frame.ref,
43290
+ theme,
43291
+ path: frameImagePath(out, frame, theme, scale, void 0, linked, { at: timing.at[index] ?? held }),
43292
+ width: view.width,
43293
+ height: view.height,
43294
+ scale,
43295
+ at: held,
43296
+ bytes
43297
+ });
43298
+ });
43299
+ }
43300
+ }
43301
+ return {
43302
+ images: await writeImages(rendered),
43303
+ motion: found
43304
+ };
43305
+ }
43306
+ /**
43307
+ * One frame's filmstrip in one theme: `count` moments spaced from 0 to the
43308
+ * timeline's end, held one by one and laid in a row on the theme's canvas
43309
+ * color. Refuses `motion-missing` for a frame with no seekable timeline and
43310
+ * `motion-unbounded` for one that never ends, and `capture-too-large` before
43311
+ * opening the frame for a strip past the screenshot limit.
43312
+ */
43313
+ async function renderFilmstrip(browser, { baseUrl, frame, theme, scale = 1, count, motionTimeoutMs = LOAD_TIMEOUT_MS }) {
43314
+ const view = {
43315
+ width: frame.box.width,
43316
+ height: frame.box.height
43317
+ };
43318
+ const strip = filmstripBounds(frame.ref, view, count, scale);
43319
+ const { motion, held } = await holdShots(browser, {
43320
+ baseUrl,
43321
+ ref: frame.ref,
43322
+ view,
43323
+ theme,
43324
+ scale,
43325
+ motionTimeoutMs,
43326
+ moments: (found) => filmstripMoments(frame.ref, found, count)
43327
+ });
43328
+ return {
43329
+ bytes: await renderComposite(browser, strip, theme, held.map(({ bytes }, index) => `<img src="data:image/png;base64,${bytes.toString("base64")}" style="position:absolute;left:${40 + index * (view.width + 40)}px;top:40px;width:${view.width}px;height:${view.height}px">`), scale),
43330
+ width: strip.width,
43331
+ height: strip.height,
43332
+ moments: held.map((shot) => shot.held),
43333
+ motion
43334
+ };
43335
+ }
43336
+ /**
43337
+ * Opens one frame with its animation clock held, finds its timeline, and
43338
+ * shoots it at each moment `moments` picks from what it found.
43339
+ */
43340
+ async function holdShots(browser, { baseUrl, ref, view, theme, scale, motionTimeoutMs, moments }) {
43341
+ assertScreenshotFits(ref, view, scale);
43342
+ const opened = await openFrame(browser, {
43343
+ baseUrl,
43344
+ ref,
43345
+ box: view,
43346
+ theme,
43347
+ scale,
43348
+ motion: "hold"
43349
+ });
43350
+ try {
43351
+ const motion = await findMotion(opened.page, ref, motionTimeoutMs);
43352
+ const held = [];
43353
+ for (const moment of moments(motion)) {
43354
+ const at = await seekMotion(opened.page, motion, moment);
43355
+ held.push({
43356
+ held: at,
43357
+ bytes: await opened.page.screenshot(HELD_SCREENSHOT)
43358
+ });
43359
+ }
43360
+ return {
43361
+ motion,
43362
+ held
43363
+ };
43364
+ } finally {
43365
+ await opened.close();
43366
+ }
43367
+ }
42584
43368
  async function renderFrame(browser, baseUrl, frame, view, theme, scale, scroll) {
42585
43369
  const box = {
42586
43370
  width: view.width,
@@ -42638,6 +43422,27 @@ async function writeImages(rendered) {
42638
43422
  }));
42639
43423
  return rendered.map(({ bytes: _bytes, ...image }) => image);
42640
43424
  }
43425
+ /**
43426
+ * Renders filmstrips on a server's warm browser one at a time. The queue is
43427
+ * its own, so Copy as PNG and a plain export never wait behind a strip of
43428
+ * many moments.
43429
+ */
43430
+ function createWarmFilmstripRenderer({ baseUrl, browser }) {
43431
+ let queue = Promise.resolve();
43432
+ return (frame, theme, scale, count) => {
43433
+ const run = queue.then(async () => {
43434
+ return (await renderFilmstrip(await browser.get(), {
43435
+ baseUrl: baseUrl(),
43436
+ frame,
43437
+ theme,
43438
+ scale,
43439
+ count
43440
+ })).bytes;
43441
+ });
43442
+ queue = run.catch(() => {});
43443
+ return run;
43444
+ };
43445
+ }
42641
43446
  // src/cli/commands/capture.ts
42642
43447
  function registerCapture(program, context) {
42643
43448
  const { io } = context;
@@ -42645,10 +43450,14 @@ function registerCapture(program, context) {
42645
43450
  "light",
42646
43451
  "dark",
42647
43452
  "both"
42648
- ]).default("both")).addOption(new Option("--scale <n>", "device pixels per CSS pixel, adding @<n>x to the file name past 1").default(1).argParser(parseScale)).option("--scroll <px>", "shoot a scroll frame this far down, clamped to the end of its page, adding .scroll-<px> to the file name", parseInteger(0)).option("--out <dir>", "the folder images land in, defaulting to the board's .run/captures/"), context, async ([ref], options) => {
43453
+ ]).default("both")).addOption(new Option("--scale <n>", "device pixels per CSS pixel, adding @<n>x to the file name past 1").default(1).argParser(parseScale)).option("--scroll <px>", "shoot a scroll frame this far down, clamped to the end of its page, adding .scroll-<px> to the file name", parseInteger(0)).option("--at <ms,...>", "hold the frame at each of these moments of its timeline, in ms, one image apiece, adding .at-<ms> to the file name", parseMoments).option("--filmstrip <n>", "one image of n moments spaced from the start of the timeline to its end, adding .filmstrip-<n> to the file name", parseInteger(2)).option("--out <dir>", "the folder images land in, defaulting to the board's .run/captures/"), context, async ([ref], options) => {
42649
43454
  if (ref === void 0 === (options.page === void 0)) throw new FrameboardError("usage", "Pass a frame ref or --page <page-ref>, exactly one of the two.");
42650
43455
  if (options.composite && options.page === void 0) throw new FrameboardError("usage", "--composite needs --page.");
42651
43456
  if (options.scroll !== void 0 && options.page !== void 0) throw new FrameboardError("usage", "--scroll shoots one frame, so pass a frame ref rather than --page.");
43457
+ const timing = options.at !== void 0 ? { at: options.at } : options.filmstrip !== void 0 ? { filmstrip: options.filmstrip } : void 0;
43458
+ if (options.at !== void 0 && options.filmstrip !== void 0) throw new FrameboardError("usage", "Pass --at or --filmstrip, not both.");
43459
+ if (timing !== void 0 && options.page !== void 0) throw new FrameboardError("usage", "--at and --filmstrip seek one frame, so pass a frame ref rather than --page.");
43460
+ if (timing !== void 0 && options.scroll !== void 0) throw new FrameboardError("usage", "--at and --filmstrip shoot the frame at the top, so drop --scroll.");
42652
43461
  const root = await boardOf(options, io);
42653
43462
  const refOptions = {
42654
43463
  project: options.project,
@@ -42693,6 +43502,26 @@ function registerCapture(program, context) {
42693
43502
  const frame = await readFrame$1(root, ref ?? "", refOptions);
42694
43503
  if (options.scroll !== void 0 && !frame.scroll) throw new FrameboardError("usage", `${frame.ref} holds no scroll key, so it has nothing to scroll. Set it with frame resize --scroll first.`, { ref: frame.ref });
42695
43504
  const out = await outOf();
43505
+ if (timing !== void 0) {
43506
+ const { images, motion } = await withFrameHost({
43507
+ root,
43508
+ facesDir: context.facesDir
43509
+ }, "capture", (browser, baseUrl) => captureMotionImages(browser, {
43510
+ baseUrl,
43511
+ frame,
43512
+ themes,
43513
+ out,
43514
+ scale: options.scale,
43515
+ timing
43516
+ }));
43517
+ return {
43518
+ data: {
43519
+ images,
43520
+ ...motion === null ? {} : { motion }
43521
+ },
43522
+ human: describe$7(images)
43523
+ };
43524
+ }
42696
43525
  const images = await withFrameHost({
42697
43526
  root,
42698
43527
  facesDir: context.facesDir
@@ -42714,6 +43543,11 @@ function parseScale(value) {
42714
43543
  if (value !== "1" && value !== "2" && value !== "3") throw new InvalidArgumentError("Expected 1, 2, or 3.");
42715
43544
  return Number(value);
42716
43545
  }
43546
+ function parseMoments(value) {
43547
+ const moments = value.split(",").map((part) => part.trim());
43548
+ if (!moments.every((part) => /^\d+$/.test(part) && Number.isSafeInteger(Number(part)))) throw new InvalidArgumentError("Expected whole milliseconds, comma separated, such as 0,500,1000.");
43549
+ return [...new Set(moments.map(Number))];
43550
+ }
42717
43551
  async function pageOf(root, ref, options) {
42718
43552
  const resolved = await resolvePageRef(root, ref, options);
42719
43553
  const { pages } = await readPageOrder(join(root, resolved.project));
@@ -43400,8 +44234,8 @@ function readConfig(root, project) {
43400
44234
  } catch {
43401
44235
  return {};
43402
44236
  }
43403
- const checks = isRecord(parsed) ? parsed.checks : void 0;
43404
- if (!isRecord(checks)) return {};
44237
+ const checks = isRecord$1(parsed) ? parsed.checks : void 0;
44238
+ if (!isRecord$1(checks)) return {};
43405
44239
  const config = {};
43406
44240
  if (Array.isArray(checks.allowedFonts) && checks.allowedFonts.every((font) => typeof font === "string")) config.allowedFonts = checks.allowedFonts;
43407
44241
  if (typeof checks.noUppercase === "boolean") config.noUppercase = checks.noUppercase;
@@ -43409,7 +44243,7 @@ function readConfig(root, project) {
43409
44243
  if (typeof checks.minContrast === "number" && checks.minContrast >= 1) config.minContrast = checks.minContrast;
43410
44244
  return config;
43411
44245
  }
43412
- function isRecord(value) {
44246
+ function isRecord$1(value) {
43413
44247
  return typeof value === "object" && value !== null && !Array.isArray(value);
43414
44248
  }
43415
44249
  // src/server/checks/browser/contrast.ts
@@ -43769,7 +44603,10 @@ const HUG_MAX_WIDTH = FRAME_SIZES.desktop.width;
43769
44603
  * height of the box's width, never the box's own height, so content sized off
43770
44604
  * the window height reads one height however tall the frame already is.
43771
44605
  * Readings that differ mean the content sizes itself off the viewport, which
43772
- * has no height of its own to fit, so that refuses `fit-unbounded`. Finite
44606
+ * has no height of its own to fit, so that refuses `fit-unbounded`. A fresh
44607
+ * page then loads at the width and height it would answer, and content
44608
+ * drawing another height there, as a block sized once off the window height,
44609
+ * refuses the same way. Finite
43773
44610
  * animations finish before the first reading, so an entrance is read at its
43774
44611
  * settled size.
43775
44612
  */
@@ -43785,6 +44622,7 @@ async function measureContent(browser, { baseUrl, ref, box, hugWidth, fonts }) {
43785
44622
  theme: "light",
43786
44623
  fonts
43787
44624
  });
44625
+ let size;
43788
44626
  try {
43789
44627
  const { page } = opened;
43790
44628
  await page.evaluate(finishAnimations);
@@ -43810,7 +44648,7 @@ async function measureContent(browser, { baseUrl, ref, box, hugWidth, fonts }) {
43810
44648
  ref,
43811
44649
  heights: [short.height, current.height]
43812
44650
  });
43813
- return {
44651
+ size = {
43814
44652
  width,
43815
44653
  height: short.height,
43816
44654
  contentWidth: current.width,
@@ -43819,6 +44657,39 @@ async function measureContent(browser, { baseUrl, ref, box, hugWidth, fonts }) {
43819
44657
  } finally {
43820
44658
  await opened.close();
43821
44659
  }
44660
+ if (size.empty || size.width === box.width && size.height === reference) return size;
44661
+ const confirmed = await readFreshAt(browser, {
44662
+ baseUrl,
44663
+ ref,
44664
+ box: {
44665
+ width: size.width,
44666
+ height: size.height
44667
+ }
44668
+ });
44669
+ if (confirmed.height !== size.height) throw new FrameboardError("fit-unbounded", `${ref} measures ${size.height} px but draws ${confirmed.height} px when opened at that height, so it sizes itself off the viewport it loads in, as a block set once from innerHeight does, and has no content height to fit. Size it by hand with frame resize, or with frame resize --scroll if it is meant to scroll.`, {
44670
+ ref,
44671
+ heights: [size.height, confirmed.height]
44672
+ });
44673
+ return size;
44674
+ }
44675
+ /**
44676
+ * Reads a frame's content in a page loaded fresh at `box`, animations
44677
+ * finished. It loads under `fonts: 'wait'` whatever the first open took, since
44678
+ * that open already refused a missing face or image, and `require` would wait
44679
+ * out a long entrance a second time on the load budget.
44680
+ */
44681
+ async function readFreshAt(browser, options) {
44682
+ const opened = await openFrame(browser, {
44683
+ ...options,
44684
+ theme: "light",
44685
+ fonts: "wait"
44686
+ });
44687
+ try {
44688
+ await opened.page.evaluate(finishAnimations);
44689
+ return await opened.page.evaluate(readContentSize);
44690
+ } finally {
44691
+ await opened.close();
44692
+ }
43822
44693
  }
43823
44694
  /**
43824
44695
  * Sets a frame's height to its content's own height at its layout width and
@@ -44544,6 +45415,17 @@ function postToBoard(address, path, body, { timeoutMs = REQUEST_TIMEOUT_MS } = {
44544
45415
  body: JSON.stringify(body)
44545
45416
  }, timeoutMs);
44546
45417
  }
45418
+ /** Deletes through a running board server's write route with the address file's token. */
45419
+ function deleteFromBoard(address, path, body) {
45420
+ return requestBoard(address, path, {
45421
+ method: "DELETE",
45422
+ headers: {
45423
+ authorization: `Bearer ${address.token}`,
45424
+ "content-type": "application/json"
45425
+ },
45426
+ body: JSON.stringify(body)
45427
+ });
45428
+ }
44547
45429
  /** Reads a running board server's route, resolving the `data` of its envelope. */
44548
45430
  function getFromBoard(address, path) {
44549
45431
  return requestBoard(address, path, { method: "GET" });
@@ -44559,12 +45441,20 @@ async function requestBoard(address, path, init, timeoutMs = REQUEST_TIMEOUT_MS)
44559
45441
  throw new FrameboardError("server-not-running", `The frameboard server at ${address.url} did not answer. Run frameboard serve to restart it.`, { url: address.url }, { cause: error });
44560
45442
  }
44561
45443
  const envelope = await response.json().catch(() => null);
45444
+ const refusal = envelope?.error;
45445
+ if (!response.ok && isErrorCode(refusal?.code) && typeof refusal?.message === "string") throw new FrameboardError(refusal.code, refusal.message, isRecord(refusal.details) ? refusal.details : {});
44562
45446
  if (!response.ok || !envelope) throw new FrameboardError("internal", `The frameboard server at ${address.url} refused ${path} with ${response.status}.`, {
44563
45447
  url: address.url,
44564
45448
  status: response.status
44565
45449
  });
44566
45450
  return envelope.data;
44567
45451
  }
45452
+ function isErrorCode(code) {
45453
+ return typeof code === "string" && Object.hasOwn(EXIT_CODES, code);
45454
+ }
45455
+ function isRecord(value) {
45456
+ return typeof value === "object" && value !== null && !Array.isArray(value);
45457
+ }
44568
45458
  // src/cli/commands/check.ts
44569
45459
  const BROWSER_TIMEOUT_MS = 12e4;
44570
45460
  const NOT_FRAME = /* @__PURE__ */ new Set([
@@ -44745,6 +45635,8 @@ const frameRecordSchema = object$1({
44745
45635
  width: number(),
44746
45636
  height: number()
44747
45637
  })),
45638
+ /** The device the board draws around the frame, absent when it has none. */
45639
+ device: _enum$1(DEVICES).optional(),
44748
45640
  placed: boolean$1(),
44749
45641
  modifiedAt: string$1()
44750
45642
  });
@@ -44791,18 +45683,34 @@ const listResultSchema = object$1({
44791
45683
  // src/shared/records/capture.ts
44792
45684
  const themeSchema$1 = _enum$1(["light", "dark"]);
44793
45685
  /** What `capture` returns: every PNG it wrote, one per frame and theme, or one per theme for a composite. */
44794
- const captureResultSchema = object$1({ images: array$1(object$1({
44795
- ref: string$1(),
44796
- theme: themeSchema$1,
44797
- path: string$1(),
44798
- /** The layout box in CSS pixels, whatever the scale. */
44799
- width: int$1().min(1),
44800
- height: int$1().min(1),
44801
- /** Device pixels per CSS pixel, so the file is `width * scale` wide. */
44802
- scale: int$1().min(1).max(3),
44803
- /** How far down a `--scroll` shot reached, absent on a shot taken at the top. */
44804
- scrollY: int$1().min(0).optional()
44805
- })) });
45686
+ const captureResultSchema = object$1({
45687
+ images: array$1(object$1({
45688
+ ref: string$1(),
45689
+ theme: themeSchema$1,
45690
+ path: string$1(),
45691
+ /** The layout box in CSS pixels, whatever the scale. */
45692
+ width: int$1().min(1),
45693
+ height: int$1().min(1),
45694
+ /** Device pixels per CSS pixel, so the file is `width * scale` wide. */
45695
+ scale: int$1().min(1).max(3),
45696
+ /** How far down a `--scroll` shot reached, absent on a shot taken at the top. */
45697
+ scrollY: int$1().min(0).optional(),
45698
+ /** The moment in ms an `--at` shot holds, clamped to the timeline's end. */
45699
+ at: int$1().min(0).optional(),
45700
+ /** The moment in ms each `--filmstrip` frame holds, left to right. */
45701
+ moments: array$1(int$1().min(0)).optional()
45702
+ })),
45703
+ /** The timeline an `--at` or `--filmstrip` capture seeked, absent on any other. */
45704
+ motion: object$1({
45705
+ source: _enum$1([
45706
+ "hf",
45707
+ "timelines",
45708
+ "css"
45709
+ ]),
45710
+ /** Its length in ms, or null when every animation repeats forever. */
45711
+ duration: int$1().min(0).nullable()
45712
+ }).optional()
45713
+ });
44806
45714
  /** What `frame fit` returns: the frame as resized, the height it measured, and its width against the layout's. */
44807
45715
  const fitResultSchema = object$1({
44808
45716
  frame: frameRecordSchema,
@@ -45141,6 +46049,27 @@ const inspectResultSchema = object$1({
45141
46049
  editable: boolean$1(),
45142
46050
  elements: array$1(inspectedElementSchema)
45143
46051
  });
46052
+ // src/shared/records/preview.ts
46053
+ /**
46054
+ * What `preview` returns on a start: the link a phone on the same network
46055
+ * opens, landing on one frame, which serves that frame's whole project read
46056
+ * only. The link ends when another start replaces it, when `preview --stop`
46057
+ * runs, when the board card showing it closes, or when the board stops.
46058
+ */
46059
+ const previewStartSchema = object$1({
46060
+ url: string$1(),
46061
+ /** This machine's address on the local network, which the link names. */
46062
+ address: string$1(),
46063
+ /** The port the listener bound on every interface, the one asked for unless it was taken. */
46064
+ port: int$1(),
46065
+ /** The secret in the link's path, new on every start. */
46066
+ token: string$1(),
46067
+ project: string$1(),
46068
+ /** The frame the link lands on, `<project>/<page>/<frame>`. */
46069
+ ref: string$1()
46070
+ });
46071
+ /** What `preview --stop` returns: whether a link was running to end. */
46072
+ const previewStopSchema = object$1({ stopped: boolean$1() });
45144
46073
  // src/shared/records/references.ts
45145
46074
  /** What `references sync` returns, each path relative to the folder and sorted. */
45146
46075
  const referencesSyncSchema = object$1({
@@ -45215,7 +46144,9 @@ const RECORDS = {
45215
46144
  selection: selectionResultSchema,
45216
46145
  find: findResultSchema,
45217
46146
  referencesSync: referencesSyncSchema,
45218
- referencesCheck: referencesCheckSchema
46147
+ referencesCheck: referencesCheckSchema,
46148
+ previewStart: previewStartSchema,
46149
+ previewStop: previewStopSchema
45219
46150
  };
45220
46151
  // src/cli/docs/content-format.ts
45221
46152
  /** The content format `docs` prints, built from the constants the verbs run on. */
@@ -45243,6 +46174,7 @@ function contentFormat() {
45243
46174
  "hidden, locked, hugWidth, hugHeight, and scroll read as false when absent, and an axis whose hug flag is false holds the size its entry states.",
45244
46175
  `scroll marks a frame that holds a fixed screen height and scrolls past it, such as a page with a sticky section. It fixes both axes, so either hug flag beside it reads as false, frame fit refuses it, and serve never measures it. frame add --scroll sets it, taking the height given or else the preset height of the width (${FRAME_SIZES.desktop.height} px at ${FRAME_SIZES.desktop.width}). frame resize --scroll sets it on a placed frame, dropping a hugging height to that preset height unless a height is given and keeping a fixed height as it stands, so resize a frame fixed past a screen with --height too. frame resize --no-scroll clears it, keeping the box.`,
45245
46176
  `widths lists the extra widths one frame file also shows at, as { width, height } objects, each drawn 80 px past the last in a row beside the frame at its y, so a responsive page is one file rather than a copy per width. Each width follows the frame's own height mode: it hugs its content at that width while hugHeight is on, and otherwise holds its height, the preset height of its width when first set and on frame resize --scroll. A value of any other shape reads as none. frame add --widths 834,390 and frame resize --widths set it, refusing a repeated width, the frame's own width, or a frame hugging its width, and frame resize --no-widths clears it. capture writes <frame>@<width>.<theme>.png beside <frame>.<theme>.png, check reports a browser finding at a linked width with that width and prints it as <path>@<width>, and a frames.json value of <project>/<page>/<frame>@<width> syncs that width's images.`,
46177
+ `device names the device the board draws around the frame, phone or tablet, as a body ${BEZELS.phone.border} or ${BEZELS.tablet.border} px past the box on every side. It never changes the frame file or its size, the body wraps whatever box the frame holds, and a frame placed beside one lands 80 px past the body. Linked widths draw no device. Any other value reads as none and is kept on write. frame add --device and frame device <frame-ref> <phone|tablet|none> set it, and none clears it.`,
45246
46178
  `An axis that hugs takes its size from the frame's content: a running serve measures it after each write to the frame file and when frame add places a file already written, its width at most ${FRAME_SIZES.desktop.width} px, and writes width and height alone, never a flag. Content sized off the viewport keeps the box it has.`,
45247
46179
  "frame add with no size hugs both axes, --size or --width fixes the width and hugs the height, and --height fixes the height alone, its box standing in until serve measures. frame resize and a hand resize fix each axis they set, and frame fit sets the height and turns hugHeight on.",
45248
46180
  "Frames sort by order, then name, and a write that changes order renumbers the page from 0.",
@@ -45567,7 +46499,7 @@ async function reservationsOf(root, refs, options, cwd, now) {
45567
46499
  async function rightOf(root, frame, live) {
45568
46500
  const page = await scanPage(root, frame.project, frame.page, 0);
45569
46501
  const prefix = `${frame.project}/${frame.page}/`;
45570
- const boxes = [...page.frames.map((each) => drawnExtent(each.box, each.widths)), ...live.flatMap((each) => each.box && each.frame.startsWith(prefix) ? [each.box] : [])];
46502
+ const boxes = [...page.frames.map((each) => drawnExtent(each.box, each.widths, each.device)), ...live.flatMap((each) => each.box && each.frame.startsWith(prefix) ? [each.box] : [])];
45571
46503
  return Math.max(...boxes.map((box) => box.x + box.width + 80), 0);
45572
46504
  }
45573
46505
  function describe$4(claims, now) {
@@ -45581,6 +46513,7 @@ function describe$4(claims, now) {
45581
46513
  // src/cli/commands/frame.ts
45582
46514
  const FRAME_REF = "a frame ref, <page>/<frame> or <project>/<page>/<frame>, or a path to its .html file";
45583
46515
  const ANY_INTEGER = parseInteger(Number.MIN_SAFE_INTEGER);
46516
+ const DEVICE_HELP = "the device the board draws around the frame, leaving the frame file and its size as they are";
45584
46517
  const WIDTHS_HELP = "the extra widths the frame also shows at, a comma list such as 834,390, each drawn beside it and hugging or holding its height as the frame does";
45585
46518
  const POSITIVE = parseInteger(1);
45586
46519
  /** A comma list of positive integers, each checked as `--width` checks one. */
@@ -45599,7 +46532,7 @@ function registerFrame(program, context) {
45599
46532
  data: record,
45600
46533
  human: `${what} ${record.ref}`
45601
46534
  });
45602
- act(withPosition(withSize(verb("add", "Place a frame past every frame, as written when its file exists and with a skeleton file only when none does, so write the file first to show no empty box. Each axis no size names hugs its content, so a preset or --width fixes the width and the height hugs.").option("--scroll", SCROLL_HELP).option("--widths <list>", WIDTHS_HELP, parseWidths))), context, async ([ref = ""], options) => done(await addFrame(await boardOf(options, io), ref, {
46535
+ act(withPosition(withSize(verb("add", "Place a frame past every frame, as written when its file exists and with a skeleton file only when none does, so write the file first to show no empty box. Each axis no size names hugs its content, so a preset or --width fixes the width and the height hugs.").option("--scroll", SCROLL_HELP).option("--widths <list>", WIDTHS_HELP, parseWidths).addOption(new Option("--device <device>", DEVICE_HELP).choices(DEVICES)))), context, async ([ref = ""], options) => done(await addFrame(await boardOf(options, io), ref, {
45603
46536
  ...options,
45604
46537
  cwd: io.cwd
45605
46538
  }), "Added"));
@@ -45656,6 +46589,13 @@ function registerFrame(program, context) {
45656
46589
  human: `Deleted frame ${result.deleted}`
45657
46590
  };
45658
46591
  });
46592
+ act(verb("device", "Set the device the board draws around a frame, or clear it with none, leaving the frame file and its size as they are").addArgument(new Argument("<device>", "the device, or none to clear it").choices([...DEVICES, "none"])), context, async ([ref = "", device = ""], options) => {
46593
+ const record = await setFrameDevice(await boardOf(options, io), ref, deviceOf(device), {
46594
+ ...options,
46595
+ cwd: io.cwd
46596
+ });
46597
+ return done(record, record.device ? `Set ${record.device} on` : "Cleared the device on");
46598
+ });
45659
46599
  for (const [name, flag] of [["hide", "hidden"], ["lock", "locked"]]) act(verb(name, `Set a frame ${flag}, or clear it with --off`).option("--off", `clear ${flag}`), context, async ([ref = ""], options) => done(await setFrameFlag(await boardOf(options, io), ref, flag, {
45660
46600
  ...options,
45661
46601
  on: !options.off,
@@ -49680,6 +50620,428 @@ function registerPage(program, context) {
49680
50620
  };
49681
50621
  });
49682
50622
  }
50623
+ // src/shared/qr.ts
50624
+ /** Error correction codewords per block at level M, indexed by version. */
50625
+ const ECC_PER_BLOCK = [
50626
+ -1,
50627
+ 10,
50628
+ 16,
50629
+ 26,
50630
+ 18,
50631
+ 24,
50632
+ 16,
50633
+ 18,
50634
+ 22,
50635
+ 22,
50636
+ 26,
50637
+ 30,
50638
+ 22,
50639
+ 22,
50640
+ 24,
50641
+ 24,
50642
+ 28,
50643
+ 28,
50644
+ 26,
50645
+ 26,
50646
+ 26,
50647
+ 26,
50648
+ 28,
50649
+ 28,
50650
+ 28,
50651
+ 28,
50652
+ 28,
50653
+ 28,
50654
+ 28,
50655
+ 28,
50656
+ 28,
50657
+ 28,
50658
+ 28,
50659
+ 28,
50660
+ 28,
50661
+ 28,
50662
+ 28,
50663
+ 28,
50664
+ 28,
50665
+ 28,
50666
+ 28
50667
+ ];
50668
+ /** Error correction blocks at level M, indexed by version. */
50669
+ const BLOCKS = [
50670
+ -1,
50671
+ 1,
50672
+ 1,
50673
+ 1,
50674
+ 2,
50675
+ 2,
50676
+ 4,
50677
+ 4,
50678
+ 4,
50679
+ 5,
50680
+ 5,
50681
+ 5,
50682
+ 8,
50683
+ 9,
50684
+ 9,
50685
+ 10,
50686
+ 10,
50687
+ 11,
50688
+ 13,
50689
+ 14,
50690
+ 16,
50691
+ 17,
50692
+ 17,
50693
+ 18,
50694
+ 20,
50695
+ 21,
50696
+ 23,
50697
+ 25,
50698
+ 26,
50699
+ 28,
50700
+ 29,
50701
+ 31,
50702
+ 33,
50703
+ 35,
50704
+ 37,
50705
+ 38,
50706
+ 40,
50707
+ 43,
50708
+ 45,
50709
+ 47,
50710
+ 49
50711
+ ];
50712
+ const MAX_VERSION = 40;
50713
+ /**
50714
+ * The modules of the smallest code holding `text` as UTF-8, with its mask
50715
+ * picked by the standard's penalty score. A text past what version 40 holds
50716
+ * throws, which no link reaches.
50717
+ */
50718
+ function qrModules(text) {
50719
+ const data = new TextEncoder().encode(text);
50720
+ const version = smallestVersion(data.length);
50721
+ const codewords = addErrorCorrection(dataCodewords(data, version), version);
50722
+ const grid = new Grid(version * 4 + 17);
50723
+ drawFunctionPatterns(grid, version);
50724
+ drawCodewords(grid, codewords);
50725
+ let best = null;
50726
+ for (let mask = 0; mask < 8; mask++) {
50727
+ const masked = grid.copy();
50728
+ applyMask(masked, mask);
50729
+ drawFormatBits(masked, mask);
50730
+ const penalty = penaltyScore(masked.modules);
50731
+ if (!best || penalty < best.penalty) best = {
50732
+ penalty,
50733
+ modules: masked.modules
50734
+ };
50735
+ }
50736
+ return best?.modules ?? [];
50737
+ }
50738
+ var Grid = class Grid {
50739
+ size;
50740
+ modules;
50741
+ reserved;
50742
+ constructor(size, modules, reserved) {
50743
+ this.size = size;
50744
+ this.modules = modules ?? Array.from({ length: size }, () => Array(size).fill(false));
50745
+ this.reserved = reserved ?? Array.from({ length: size }, () => Array(size).fill(false));
50746
+ }
50747
+ /** Sets a function module, which no data bit or mask touches. */
50748
+ setFunction(x, y, dark) {
50749
+ this.set(x, y, dark);
50750
+ const row = this.reserved[y];
50751
+ if (row) row[x] = true;
50752
+ }
50753
+ set(x, y, dark) {
50754
+ const row = this.modules[y];
50755
+ if (row) row[x] = dark;
50756
+ }
50757
+ get(x, y) {
50758
+ return this.modules[y]?.[x] ?? false;
50759
+ }
50760
+ isReserved(x, y) {
50761
+ return this.reserved[y]?.[x] ?? false;
50762
+ }
50763
+ copy() {
50764
+ return new Grid(this.size, this.modules.map((row) => [...row]), this.reserved);
50765
+ }
50766
+ };
50767
+ /** The data codewords a version holds at level M. */
50768
+ function dataCapacity(version) {
50769
+ return Math.floor(rawModules(version) / 8) - (ECC_PER_BLOCK[version] ?? 0) * (BLOCKS[version] ?? 0);
50770
+ }
50771
+ /** The modules left for codewords once the function patterns are drawn. */
50772
+ function rawModules(version) {
50773
+ let result = (16 * version + 128) * version + 64;
50774
+ if (version >= 2) {
50775
+ const align = Math.floor(version / 7) + 2;
50776
+ result -= (25 * align - 10) * align - 55;
50777
+ if (version >= 7) result -= 36;
50778
+ }
50779
+ return result;
50780
+ }
50781
+ function smallestVersion(bytes) {
50782
+ for (let version = 1; version <= MAX_VERSION; version++) if (4 + (version <= 9 ? 8 : 16) + bytes * 8 <= dataCapacity(version) * 8) return version;
50783
+ throw new Error(`A QR code holds no text of ${bytes} bytes`);
50784
+ }
50785
+ /** Mode, count, bytes, terminator, then the alternating pad bytes. */
50786
+ function dataCodewords(data, version) {
50787
+ const bits = [];
50788
+ const push = (value, length) => {
50789
+ for (let i = length - 1; i >= 0; i--) bits.push(value >>> i & 1);
50790
+ };
50791
+ push(4, 4);
50792
+ push(data.length, version <= 9 ? 8 : 16);
50793
+ for (const byte of data) push(byte, 8);
50794
+ const capacity = dataCapacity(version) * 8;
50795
+ push(0, Math.min(4, capacity - bits.length));
50796
+ push(0, (8 - bits.length % 8) % 8);
50797
+ for (let pad = 236; bits.length < capacity; pad ^= 253) push(pad, 8);
50798
+ const codewords = [];
50799
+ for (let i = 0; i < bits.length; i += 8) codewords.push(bits.slice(i, i + 8).reduce((byte, bit) => byte << 1 | bit, 0));
50800
+ return codewords;
50801
+ }
50802
+ /** Splits the data into blocks, appends each block's ECC, and interleaves them. */
50803
+ function addErrorCorrection(data, version) {
50804
+ const blockCount = BLOCKS[version] ?? 1;
50805
+ const eccLength = ECC_PER_BLOCK[version] ?? 0;
50806
+ const raw = Math.floor(rawModules(version) / 8);
50807
+ const shortBlocks = blockCount - raw % blockCount;
50808
+ const shortLength = Math.floor(raw / blockCount);
50809
+ const divisor = reedSolomonDivisor(eccLength);
50810
+ const blocks = [];
50811
+ for (let i = 0, at = 0; i < blockCount; i++) {
50812
+ const length = shortLength - eccLength + (i < shortBlocks ? 0 : 1);
50813
+ const block = data.slice(at, at + length);
50814
+ at += length;
50815
+ const ecc = reedSolomonRemainder(block, divisor);
50816
+ if (i < shortBlocks) block.push(-1);
50817
+ blocks.push([...block, ...ecc]);
50818
+ }
50819
+ const result = [];
50820
+ for (let i = 0; i < (blocks[0]?.length ?? 0); i++) blocks.forEach((block, index) => {
50821
+ if (!(i === shortLength - eccLength && index < shortBlocks)) result.push(block[i] ?? 0);
50822
+ });
50823
+ return result;
50824
+ }
50825
+ function reedSolomonDivisor(degree) {
50826
+ const result = Array(degree).fill(0);
50827
+ result[degree - 1] = 1;
50828
+ let root = 1;
50829
+ for (let i = 0; i < degree; i++) {
50830
+ for (let j = 0; j < degree; j++) {
50831
+ result[j] = multiply(result[j] ?? 0, root);
50832
+ if (j + 1 < degree) result[j] = (result[j] ?? 0) ^ (result[j + 1] ?? 0);
50833
+ }
50834
+ root = multiply(root, 2);
50835
+ }
50836
+ return result;
50837
+ }
50838
+ function reedSolomonRemainder(data, divisor) {
50839
+ const result = divisor.map(() => 0);
50840
+ for (const byte of data) {
50841
+ const factor = byte ^ (result.shift() ?? 0);
50842
+ result.push(0);
50843
+ divisor.forEach((coefficient, i) => {
50844
+ result[i] = (result[i] ?? 0) ^ multiply(coefficient, factor);
50845
+ });
50846
+ }
50847
+ return result;
50848
+ }
50849
+ /** Multiplication in GF(2^8) modulo the QR polynomial 0x11D. */
50850
+ function multiply(x, y) {
50851
+ let z = 0;
50852
+ for (let i = 7; i >= 0; i--) {
50853
+ z = z << 1 ^ (z >>> 7) * 285;
50854
+ z ^= (y >>> i & 1) * x;
50855
+ }
50856
+ return z;
50857
+ }
50858
+ function drawFunctionPatterns(grid, version) {
50859
+ const { size } = grid;
50860
+ for (let i = 0; i < size; i++) {
50861
+ grid.setFunction(6, i, i % 2 === 0);
50862
+ grid.setFunction(i, 6, i % 2 === 0);
50863
+ }
50864
+ drawFinder(grid, 3, 3);
50865
+ drawFinder(grid, size - 4, 3);
50866
+ drawFinder(grid, 3, size - 4);
50867
+ const positions = alignmentPositions(version, size);
50868
+ const last = positions.length - 1;
50869
+ positions.forEach((x, i) => {
50870
+ positions.forEach((y, j) => {
50871
+ if (!(i === 0 && j === 0 || i === 0 && j === last || i === last && j === 0)) drawAlignment(grid, x, y);
50872
+ });
50873
+ });
50874
+ drawFormatBits(grid, 0);
50875
+ drawVersionBits(grid, version);
50876
+ }
50877
+ function drawFinder(grid, cx, cy) {
50878
+ for (let dy = -4; dy <= 4; dy++) for (let dx = -4; dx <= 4; dx++) {
50879
+ const x = cx + dx;
50880
+ const y = cy + dy;
50881
+ if (x < 0 || y < 0 || x >= grid.size || y >= grid.size) continue;
50882
+ const distance = Math.max(Math.abs(dx), Math.abs(dy));
50883
+ grid.setFunction(x, y, distance !== 2 && distance !== 4);
50884
+ }
50885
+ }
50886
+ function drawAlignment(grid, cx, cy) {
50887
+ for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) grid.setFunction(cx + dx, cy + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
50888
+ }
50889
+ function alignmentPositions(version, size) {
50890
+ if (version === 1) return [];
50891
+ const count = Math.floor(version / 7) + 2;
50892
+ const step = Math.floor((version * 8 + count * 3 + 5) / (count * 4 - 4)) * 2;
50893
+ const result = [6];
50894
+ for (let position = size - 7; result.length < count; position -= step) result.splice(1, 0, position);
50895
+ return result;
50896
+ }
50897
+ function drawFormatBits(grid, mask) {
50898
+ const data = 0 | mask;
50899
+ let remainder = data;
50900
+ for (let i = 0; i < 10; i++) remainder = remainder << 1 ^ (remainder >>> 9) * 1335;
50901
+ const bits = (data << 10 | remainder) ^ 21522;
50902
+ const bit = (i) => (bits >>> i & 1) !== 0;
50903
+ const { size } = grid;
50904
+ for (let i = 0; i <= 5; i++) grid.setFunction(8, i, bit(i));
50905
+ grid.setFunction(8, 7, bit(6));
50906
+ grid.setFunction(8, 8, bit(7));
50907
+ grid.setFunction(7, 8, bit(8));
50908
+ for (let i = 9; i < 15; i++) grid.setFunction(14 - i, 8, bit(i));
50909
+ for (let i = 0; i < 8; i++) grid.setFunction(size - 1 - i, 8, bit(i));
50910
+ for (let i = 8; i < 15; i++) grid.setFunction(8, size - 15 + i, bit(i));
50911
+ grid.setFunction(8, size - 8, true);
50912
+ }
50913
+ function drawVersionBits(grid, version) {
50914
+ if (version < 7) return;
50915
+ let remainder = version;
50916
+ for (let i = 0; i < 12; i++) remainder = remainder << 1 ^ (remainder >>> 11) * 7973;
50917
+ const bits = version << 12 | remainder;
50918
+ for (let i = 0; i < 18; i++) {
50919
+ const dark = (bits >>> i & 1) !== 0;
50920
+ const a = grid.size - 11 + i % 3;
50921
+ const b = Math.floor(i / 3);
50922
+ grid.setFunction(a, b, dark);
50923
+ grid.setFunction(b, a, dark);
50924
+ }
50925
+ }
50926
+ /** Places the codewords in the two-column zigzag from the bottom right. */
50927
+ function drawCodewords(grid, codewords) {
50928
+ const { size } = grid;
50929
+ let i = 0;
50930
+ for (let right = size - 1; right >= 1; right -= 2) {
50931
+ if (right === 6) right = 5;
50932
+ for (let vertical = 0; vertical < size; vertical++) for (let j = 0; j < 2; j++) {
50933
+ const x = right - j;
50934
+ const y = (right + 1 & 2) === 0 ? size - 1 - vertical : vertical;
50935
+ if (grid.isReserved(x, y) || i >= codewords.length * 8) continue;
50936
+ grid.set(x, y, ((codewords[i >>> 3] ?? 0) >>> 7 - (i & 7) & 1) !== 0);
50937
+ i++;
50938
+ }
50939
+ }
50940
+ }
50941
+ const MASKS = [
50942
+ (x, y) => (x + y) % 2 === 0,
50943
+ (_x, y) => y % 2 === 0,
50944
+ (x) => x % 3 === 0,
50945
+ (x, y) => (x + y) % 3 === 0,
50946
+ (x, y) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0,
50947
+ (x, y) => x * y % 2 + x * y % 3 === 0,
50948
+ (x, y) => (x * y % 2 + x * y % 3) % 2 === 0,
50949
+ (x, y) => ((x + y) % 2 + x * y % 3) % 2 === 0
50950
+ ];
50951
+ function applyMask(grid, mask) {
50952
+ const flips = MASKS[mask];
50953
+ if (!flips) return;
50954
+ for (let y = 0; y < grid.size; y++) for (let x = 0; x < grid.size; x++) if (!grid.isReserved(x, y) && flips(x, y)) grid.set(x, y, !grid.get(x, y));
50955
+ }
50956
+ /**
50957
+ * The standard's four penalty rules, summed, lower being easier to scan. The
50958
+ * standard leaves the finder-like rule's edges open, so it is counted inside
50959
+ * the line, as the `qrcode` package does, which keeps both picking one mask.
50960
+ */
50961
+ function penaltyScore(modules) {
50962
+ const size = modules.length;
50963
+ const at = (x, y) => modules[y]?.[x] ?? false;
50964
+ let result = 0;
50965
+ for (const horizontal of [true, false]) for (let a = 0; a < size; a++) {
50966
+ let run = 0;
50967
+ let previous = null;
50968
+ let window = 0;
50969
+ for (let b = 0; b < size; b++) {
50970
+ const dark = horizontal ? at(b, a) : at(a, b);
50971
+ if (dark === previous) run++;
50972
+ else {
50973
+ if (run >= 5) result += run - 2;
50974
+ run = 1;
50975
+ previous = dark;
50976
+ }
50977
+ window = window << 1 & 2047 | (dark ? 1 : 0);
50978
+ if (b >= 10 && (window === 1488 || window === 93)) result += 40;
50979
+ }
50980
+ if (run >= 5) result += run - 2;
50981
+ }
50982
+ for (let y = 0; y < size - 1; y++) for (let x = 0; x < size - 1; x++) {
50983
+ const dark = at(x, y);
50984
+ if (dark === at(x + 1, y) && dark === at(x, y + 1) && dark === at(x + 1, y + 1)) result += 3;
50985
+ }
50986
+ const dark = modules.flat().filter(Boolean).length;
50987
+ return result + Math.abs(Math.ceil(dark * 100 / (size * size) / 5) - 10) * 10;
50988
+ }
50989
+ // src/cli/commands/preview.ts
50990
+ /** The light modules a scanner wants around a code, at least four by the standard. */
50991
+ const QUIET_ZONE = 4;
50992
+ function registerPreview(program, context) {
50993
+ const { io } = context;
50994
+ act(addVerb(program, "preview", "Open a frame's project on a phone on the same network, read only, through a link and a code the running board serves", { project: true }).argument("[frame-ref]", "the frame the link lands on, <page>/<frame>, <project>/<page>/<frame>, or a path to its .html file").option("--port <n>", `the port the link asks for first, taking a free one when it is taken (default: ${PREVIEW_PORT})`, parsePort).option("--stop", "end the open link, so no phone reaches the board"), context, async (args, options) => {
50995
+ const [ref] = args;
50996
+ const root = await boardOf(options, io);
50997
+ if (options.stop && ref !== void 0) throw new FrameboardError("usage", "Pass a frame ref to open a link, or --stop to end one, not both.");
50998
+ if (!options.stop && ref === void 0) throw new FrameboardError("usage", "Name the frame the link lands on, or pass --stop to end the open link.");
50999
+ const frame = ref === void 0 ? null : await resolveFrameRef(root, ref, {
51000
+ project: options.project,
51001
+ cwd: io.cwd
51002
+ });
51003
+ const live = await findLiveServer(root);
51004
+ if (!live) throw new FrameboardError("server-not-running", `No frameboard server is running for ${root}. Run frameboard serve first.`, { root });
51005
+ if (frame === null) {
51006
+ const data = await deleteFromBoard(live, "/api/preview", {});
51007
+ return {
51008
+ data,
51009
+ human: data.stopped ? "Ended the phone link" : "No phone link was open"
51010
+ };
51011
+ }
51012
+ const data = await postToBoard(live, "/api/preview", {
51013
+ ref: `${frame.project}/${frame.page}/${frame.name}`,
51014
+ ...options.port === void 0 ? {} : { port: options.port }
51015
+ });
51016
+ return {
51017
+ data,
51018
+ human: [
51019
+ terminalCode(qrModules(data.url)),
51020
+ data.url,
51021
+ `Scan on the same Wi-Fi. It opens ${data.project} read only until the board stops or frameboard preview --stop runs.`
51022
+ ].join("\n")
51023
+ };
51024
+ });
51025
+ }
51026
+ /**
51027
+ * The code drawn two rows to a line in half blocks, black on a forced white
51028
+ * ground, so it scans on a dark terminal as on a light one.
51029
+ */
51030
+ function terminalCode(modules) {
51031
+ const size = modules.length + 8;
51032
+ const dark = (x, y) => modules[y - QUIET_ZONE]?.[x - QUIET_ZONE] ?? false;
51033
+ const lines = [];
51034
+ for (let y = 0; y < size; y += 2) {
51035
+ let line = "";
51036
+ for (let x = 0; x < size; x++) {
51037
+ const top = dark(x, y);
51038
+ const bottom = dark(x, y + 1);
51039
+ line += top && bottom ? "█" : top ? "▀" : bottom ? "▄" : " ";
51040
+ }
51041
+ lines.push(`\x1b[30;47m${line}\x1b[0m`);
51042
+ }
51043
+ return lines.join("\n");
51044
+ }
49683
51045
  // src/cli/commands/project.ts
49684
51046
  function registerProject(program, context) {
49685
51047
  const { io } = context;
@@ -54427,6 +55789,159 @@ function createDelivery({ pending, markDelivered, onListeners, now }) {
54427
55789
  listeners
54428
55790
  };
54429
55791
  }
55792
+ // src/server/preview/listener.ts
55793
+ /** Where every phone link starts, ahead of its token. */
55794
+ const LINK_PREFIX = "/v/";
55795
+ /** The bytes of a link's token, 96 bits, which keeps the code small. */
55796
+ const TOKEN_BYTES = 12;
55797
+ /**
55798
+ * The phone link's read-only app: GET and HEAD under `/v/<token>/` for one
55799
+ * project's frames and assets at `frames/<project>/...` and the faces and
55800
+ * board sheet at `frameboard/...`, each answered by the board's own frame and
55801
+ * look routes, so their refusals of board records, dot-named paths, and
55802
+ * escaping paths hold here unrestated. Anything else answers 404, so nothing
55803
+ * tells a caller what exists. It carries no Host check, since a phone names
55804
+ * the machine's address, and the token is what keeps other pages out.
55805
+ */
55806
+ function previewApp(token, options) {
55807
+ const base = `${LINK_PREFIX}${token}`;
55808
+ const served = servedFrames(options.root, {
55809
+ facesDir: options.facesDir,
55810
+ tokens: options.tokens ?? null,
55811
+ base
55812
+ }).routes;
55813
+ const app = new Hono();
55814
+ app.use("*", async (c, next) => {
55815
+ await next();
55816
+ c.res = withHeader(c.res, "Referrer-Policy", "no-referrer");
55817
+ });
55818
+ app.all("*", async (c) => {
55819
+ const method = c.req.method;
55820
+ if (method !== "GET" && method !== "HEAD") return c.notFound();
55821
+ const url = new URL(c.req.url);
55822
+ const inner = innerPath(url.pathname, token, options.project);
55823
+ if (inner === null) return c.notFound();
55824
+ const headers = new Headers();
55825
+ for (const name of ["range", "if-none-match"]) {
55826
+ const value = c.req.header(name);
55827
+ if (value !== void 0) headers.set(name, value);
55828
+ }
55829
+ const theme = url.searchParams.get("theme");
55830
+ const query = theme === null ? "" : `?${new URLSearchParams({ theme })}`;
55831
+ return served.fetch(new Request(`http://preview${inner}${query}`, {
55832
+ method,
55833
+ headers
55834
+ }));
55835
+ });
55836
+ return app;
55837
+ }
55838
+ /**
55839
+ * The board path a phone path stands for, or null when it names another
55840
+ * token, another project, or anything outside the frames and the look.
55841
+ */
55842
+ function innerPath(pathname, token, project) {
55843
+ if (!pathname.startsWith(LINK_PREFIX)) return null;
55844
+ const [given = "", ...rest] = pathname.slice(3).split("/");
55845
+ if (!sameToken(given, token)) return null;
55846
+ const inner = `/${rest.join("/")}`;
55847
+ if (inner === "/frameboard/tokens.css" || inner.startsWith(`/frameboard/faces/`)) return inner;
55848
+ const [area, named, ...within] = rest;
55849
+ if (area !== "frames" || within.length === 0) return null;
55850
+ let decoded;
55851
+ try {
55852
+ decoded = decodeURIComponent(named ?? "");
55853
+ } catch {
55854
+ return null;
55855
+ }
55856
+ return decoded === project ? inner : null;
55857
+ }
55858
+ /** The response with one header set, copied first since a forwarded one may be immutable. */
55859
+ function withHeader(response, name, value) {
55860
+ const headers = new Headers(response.headers);
55861
+ headers.set(name, value);
55862
+ return new Response(response.body, {
55863
+ status: response.status,
55864
+ statusText: response.statusText,
55865
+ headers
55866
+ });
55867
+ }
55868
+ function sameToken(given, token) {
55869
+ const a = Buffer.from(given);
55870
+ const b = Buffer.from(token);
55871
+ return a.length === b.length && timingSafeEqual(a, b);
55872
+ }
55873
+ /**
55874
+ * Starts the phone listener on `host`, the machine's local network address,
55875
+ * at `port`, or on a free port when that one is taken, with a fresh token.
55876
+ * Binding the one address rather than every interface keeps the listener off
55877
+ * any other network the machine sits on. The board's own listener is
55878
+ * untouched, staying on loopback behind its Host check.
55879
+ */
55880
+ async function startPreviewListener(options) {
55881
+ const token = randomBytes(TOKEN_BYTES).toString("base64url");
55882
+ const app = previewApp(token, options);
55883
+ let server;
55884
+ try {
55885
+ server = await bind(app, options.host, options.port);
55886
+ } catch (error) {
55887
+ if (!(error.code === "EADDRINUSE") || options.port === 0) throw error;
55888
+ server = await bind(app, options.host, 0);
55889
+ }
55890
+ const { port } = server.address();
55891
+ return {
55892
+ token,
55893
+ host: options.host,
55894
+ port,
55895
+ project: options.project,
55896
+ close: () => new Promise((resolve) => {
55897
+ server.close(() => resolve());
55898
+ server.closeAllConnections();
55899
+ })
55900
+ };
55901
+ }
55902
+ function bind(app, hostname, port) {
55903
+ return new Promise((resolve, reject) => {
55904
+ const created = serve({
55905
+ fetch: app.fetch,
55906
+ hostname,
55907
+ port
55908
+ }, () => resolve(created));
55909
+ created.once("error", reject);
55910
+ });
55911
+ }
55912
+ /**
55913
+ * Holds the board's phone listener, running each start and stop in turn so
55914
+ * two never race to bind. The board ends it with `stop()` as it closes.
55915
+ */
55916
+ function createPreviewSlot(options) {
55917
+ let running = null;
55918
+ let turn = Promise.resolve();
55919
+ const inTurn = (work) => {
55920
+ const next = turn.then(work, work);
55921
+ turn = next.catch(() => void 0);
55922
+ return next;
55923
+ };
55924
+ const end = async (token) => {
55925
+ if (!running || token !== void 0 && running.token !== token) return false;
55926
+ const ending = running;
55927
+ running = null;
55928
+ await ending.close();
55929
+ return true;
55930
+ };
55931
+ return {
55932
+ start: (project, host, port) => inTurn(async () => {
55933
+ await end();
55934
+ running = await startPreviewListener({
55935
+ ...options,
55936
+ project,
55937
+ host,
55938
+ port
55939
+ });
55940
+ return running;
55941
+ }),
55942
+ stop: (token) => inTurn(() => end(token))
55943
+ };
55944
+ }
54430
55945
  // src/server/start.ts
54431
55946
  const HOSTNAME = "127.0.0.1";
54432
55947
  /**
@@ -54513,6 +56028,7 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
54513
56028
  scanning = run.catch(() => {});
54514
56029
  return run;
54515
56030
  };
56031
+ let closing;
54516
56032
  const findings = createBoardFindings(root, tokens ?? null);
54517
56033
  const delivery = createDelivery({
54518
56034
  pending: (session) => queuedFor(root, session),
@@ -54626,6 +56142,10 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
54626
56142
  browser,
54627
56143
  scale: 2
54628
56144
  });
56145
+ const renderFilmstrip = createWarmFilmstripRenderer({
56146
+ baseUrl,
56147
+ browser
56148
+ });
54629
56149
  const thumbnails = createThumbnailStore({
54630
56150
  root,
54631
56151
  run: randomUUID().slice(0, 8),
@@ -54680,6 +56200,11 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
54680
56200
  measure
54681
56201
  });
54682
56202
  const assetUsage = createAssetUsage(root);
56203
+ const preview = createPreviewSlot({
56204
+ root,
56205
+ facesDir,
56206
+ tokens
56207
+ });
54683
56208
  const app = createApp({
54684
56209
  clientDir,
54685
56210
  facesDir,
@@ -54693,7 +56218,9 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
54693
56218
  history,
54694
56219
  selection,
54695
56220
  renderFrame,
56221
+ renderFilmstrip,
54696
56222
  clipboard: clipboardFiles(),
56223
+ preview,
54697
56224
  thumbnails,
54698
56225
  measure,
54699
56226
  frameVersion: tracker.version,
@@ -54795,24 +56322,33 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
54795
56322
  token = next;
54796
56323
  },
54797
56324
  boardUrl,
54798
- close: async () => {
54799
- rendered.close();
54800
- hug.close();
54801
- claims.close();
54802
- for (const [timer, release] of settling) {
54803
- clearTimeout(timer);
54804
- release();
54805
- }
54806
- await Promise.all([
54807
- watcher.close(),
54808
- hub.close(),
54809
- browser.close(),
54810
- emptyTrash(root)
54811
- ]);
54812
- await new Promise((done, fail) => {
54813
- server.close((error) => error ? fail(error) : done());
54814
- server.closeAllConnections();
54815
- });
56325
+ close: () => {
56326
+ closing ??= (async () => {
56327
+ rendered.close();
56328
+ hug.close();
56329
+ claims.close();
56330
+ for (const [timer, release] of settling) {
56331
+ clearTimeout(timer);
56332
+ release();
56333
+ }
56334
+ await Promise.all([
56335
+ watcher.close(),
56336
+ hub.close(),
56337
+ browser.close(),
56338
+ emptyTrash(root),
56339
+ preview.stop()
56340
+ ]);
56341
+ await new Promise((done, fail) => {
56342
+ server.close((error) => error ? fail(error) : done());
56343
+ server.closeAllConnections();
56344
+ });
56345
+ let tail;
56346
+ do {
56347
+ tail = scanning;
56348
+ await tail;
56349
+ } while (tail !== scanning);
56350
+ })();
56351
+ return closing;
54816
56352
  }
54817
56353
  };
54818
56354
  }
@@ -55249,6 +56785,7 @@ function createProgram(context) {
55249
56785
  registerServe(program, faced);
55250
56786
  registerShow(program, context);
55251
56787
  registerOpen(program, context);
56788
+ registerPreview(program, context);
55252
56789
  registerSelection(program, context);
55253
56790
  registerList(program, context);
55254
56791
  registerProject(program, context);