frameboard 0.43.0 → 0.44.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
@@ -3065,7 +3065,9 @@ const EXIT_CODES = {
3065
3065
  "result-not-found": 3,
3066
3066
  "no-provider": 3,
3067
3067
  "source-failed": 13,
3068
- "provider-failed": 13
3068
+ "provider-failed": 13,
3069
+ "asset-not-found": 3,
3070
+ "asset-held": 4
3069
3071
  };
3070
3072
  var FrameboardError = class extends Error {
3071
3073
  code;
@@ -4327,7 +4329,7 @@ function datetime$1(args) {
4327
4329
  return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
4328
4330
  }
4329
4331
  const anyString = /^[\s\S]{0,}$/;
4330
- const integer$1 = /^-?\d+$/;
4332
+ const integer$2 = /^-?\d+$/;
4331
4333
  const number$1 = /^-?\d+(?:\.\d+)?$/;
4332
4334
  const boolean$2 = /^(?:true|false)$/i;
4333
4335
  const lowercase = /^[^A-Z]*$/;
@@ -5726,6 +5728,114 @@ function handleIntersectionResults(result, left, right) {
5726
5728
  result.value = merged.data;
5727
5729
  return result;
5728
5730
  }
5731
+ const $ZodTuple = /*@__PURE__*/ $constructor("$ZodTuple", (inst, def) => {
5732
+ $ZodType.init(inst, def);
5733
+ const items = def.items;
5734
+ const memo = globalConfig.memoizer;
5735
+ memo?.attach(inst);
5736
+ inst._zod.parse = (payload, ctx) => {
5737
+ const input = payload.value;
5738
+ if (!Array.isArray(input)) {
5739
+ payload.issues.push({
5740
+ input,
5741
+ inst,
5742
+ expected: "tuple",
5743
+ code: "invalid_type"
5744
+ });
5745
+ return payload;
5746
+ }
5747
+ payload.value = memo ? memo.alloc(inst, payload, [], ctx) : [];
5748
+ const proms = [];
5749
+ const optinStart = getTupleOptStart(items, "optin");
5750
+ const optoutStart = getTupleOptStart(items, "optout");
5751
+ if (!def.rest) {
5752
+ if (input.length < optinStart) {
5753
+ payload.issues.push({
5754
+ code: "too_small",
5755
+ minimum: optinStart,
5756
+ inclusive: true,
5757
+ input,
5758
+ inst,
5759
+ origin: "array"
5760
+ });
5761
+ return payload;
5762
+ }
5763
+ if (input.length > items.length) payload.issues.push({
5764
+ code: "too_big",
5765
+ maximum: items.length,
5766
+ inclusive: true,
5767
+ input,
5768
+ inst,
5769
+ origin: "array"
5770
+ });
5771
+ }
5772
+ const itemResults = new Array(items.length);
5773
+ const abortEarly = def.rest ? ctx?.abortEarly : void 0;
5774
+ let itemAborted = false;
5775
+ for (let i = 0; i < items.length; i++) {
5776
+ const r = items[i]._zod.run({
5777
+ value: input[i],
5778
+ issues: []
5779
+ }, ctx);
5780
+ if (r instanceof Promise) proms.push(r.then((rr) => {
5781
+ itemResults[i] = rr;
5782
+ }));
5783
+ else {
5784
+ itemResults[i] = r;
5785
+ if (abortEarly && !itemAborted && r.issues.length) itemAborted = aborted(r);
5786
+ }
5787
+ }
5788
+ if (def.rest && !itemAborted) {
5789
+ let i = items.length - 1;
5790
+ const rest = input.slice(items.length);
5791
+ let seen = payload.issues.length;
5792
+ for (const el of rest) {
5793
+ if (abortEarly && payload.issues.length !== seen) {
5794
+ if (aborted(payload, seen)) break;
5795
+ seen = payload.issues.length;
5796
+ }
5797
+ i++;
5798
+ const result = def.rest._zod.run({
5799
+ value: el,
5800
+ issues: []
5801
+ }, ctx);
5802
+ if (result instanceof Promise) proms.push(result.then((r) => handleTupleResult(r, payload, i)));
5803
+ else handleTupleResult(result, payload, i);
5804
+ }
5805
+ }
5806
+ if (proms.length) return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));
5807
+ return handleTupleResults(itemResults, payload, items, input, optoutStart);
5808
+ };
5809
+ });
5810
+ function getTupleOptStart(items, key) {
5811
+ for (let i = items.length - 1; i >= 0; i--) if (!(key === "optin" ? items[i]._zod.optin !== void 0 : items[i]._zod.optout === "optional")) return i + 1;
5812
+ return 0;
5813
+ }
5814
+ function handleTupleResult(result, final, index) {
5815
+ if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues));
5816
+ final.value[index] = result.value;
5817
+ }
5818
+ function handleTupleResults(itemResults, final, items, input, optoutStart) {
5819
+ for (let i = 0; i < items.length; i++) {
5820
+ const r = itemResults[i];
5821
+ const isPresent = i < input.length;
5822
+ if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") {
5823
+ final.value.length = i;
5824
+ break;
5825
+ }
5826
+ if (r.issues.length) {
5827
+ if (!isPresent && i >= optoutStart) {
5828
+ final.value.length = i;
5829
+ break;
5830
+ }
5831
+ final.issues.push(...prefixIssues(i, r.issues));
5832
+ }
5833
+ final.value[i] = r.value;
5834
+ }
5835
+ for (let i = final.value.length - 1; i >= input.length; i--) if (items[i]._zod.optout === "optional" && final.value[i] === void 0) final.value.length = i;
5836
+ else break;
5837
+ return final;
5838
+ }
5729
5839
  const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => {
5730
5840
  $ZodType.init(inst, def);
5731
5841
  const memo = globalConfig.memoizer;
@@ -7887,7 +7997,7 @@ function stringifyKeyNames(bySchema, json, visited) {
7887
7997
  else if (typeof rest.const === "number") rest.const = String(rest.const);
7888
7998
  if (!numericType) return rest;
7889
7999
  rest.type = "string";
7890
- if (!values) rest.pattern = (types.includes("number") ? number$1 : integer$1).source;
8000
+ if (!values) rest.pattern = (types.includes("number") ? number$1 : integer$2).source;
7891
8001
  return rest;
7892
8002
  }
7893
8003
  /** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */
@@ -8180,7 +8290,7 @@ const decode = /* @__PURE__ */ _decode(ZodRealError);
8180
8290
  const encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError);
8181
8291
  const decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError);
8182
8292
  const safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError);
8183
- const safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError);
8293
+ const safeDecode$1 = /* @__PURE__ */ _safeDecode(ZodRealError);
8184
8294
  const safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
8185
8295
  const safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
8186
8296
  // node_modules/zod/v4/classic/schemas.js
@@ -8341,7 +8451,7 @@ const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => {
8341
8451
  return safeEncode(this, data, params);
8342
8452
  },
8343
8453
  safeDecode(data, params) {
8344
- return safeDecode(this, data, params);
8454
+ return safeDecode$1(this, data, params);
8345
8455
  },
8346
8456
  async safeEncodeAsync(data, params) {
8347
8457
  return safeEncodeAsync(this, data, params);
@@ -8839,6 +8949,39 @@ function intersection(left, right) {
8839
8949
  right
8840
8950
  });
8841
8951
  }
8952
+ const ZodTuple = /*@__PURE__*/ $constructor("ZodTuple", (inst, def) => {
8953
+ _ensureDefaultMemoizer();
8954
+ $ZodTuple.init(inst, def);
8955
+ ZodType.init(inst, def);
8956
+ inst._zod.processJSONSchema = (ctx, json, params) => tupleProcessor(inst, ctx, json, params);
8957
+ }, {
8958
+ rest(rest) {
8959
+ return this.clone({
8960
+ ...this._zod.def,
8961
+ rest
8962
+ });
8963
+ },
8964
+ partial() {
8965
+ const def = this._zod.def;
8966
+ if (def.checks?.length) throw new Error(".partial() cannot be used on tuple schemas containing refinements");
8967
+ return this.clone({
8968
+ ...def,
8969
+ items: def.items.map((item) => new ZodOptional({
8970
+ type: "optional",
8971
+ innerType: item
8972
+ }))
8973
+ });
8974
+ }
8975
+ });
8976
+ function tuple(items, _paramsOrRest, _params) {
8977
+ const hasRest = _paramsOrRest instanceof $ZodType;
8978
+ return new ZodTuple({
8979
+ type: "tuple",
8980
+ items,
8981
+ rest: hasRest ? _paramsOrRest : null,
8982
+ ...normalizeParams(hasRest ? _params : _paramsOrRest)
8983
+ });
8984
+ }
8842
8985
  const ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => {
8843
8986
  _ensureDefaultMemoizer();
8844
8987
  $ZodRecord.init(inst, def);
@@ -9084,347 +9227,6 @@ function superRefine(fn, params) {
9084
9227
  function datetime(params) {
9085
9228
  return /* @__PURE__ */ _isoDateTime(ZodISODateTime, params);
9086
9229
  }
9087
- // src/shared/frame-device.ts
9088
- /**
9089
- * The devices the board can draw around a frame. A frame's width picks the
9090
- * first three, and a frame names a foldable.
9091
- */
9092
- const DEVICES = [
9093
- "phone",
9094
- "tablet",
9095
- "laptop",
9096
- "foldable"
9097
- ];
9098
- /** The laptop lid's chin below the screen, past the border its sides hold. */
9099
- const LAPTOP_CHIN = 28;
9100
- /** The laptop's base below the chin, reaching past the lid on each side by its share of the lid's width. */
9101
- const LAPTOP_BASE = {
9102
- height: 14,
9103
- reach: .06,
9104
- radius: 10
9105
- };
9106
- /**
9107
- * Bezels measured off a current Pro phone and 13-inch tablet, the laptop
9108
- * scaled off the picked mock, and the foldable's body less its glass. The
9109
- * tablet's and the foldable's screen radii are guesses no source gives.
9110
- */
9111
- const BEZELS = {
9112
- phone: {
9113
- border: 16,
9114
- bottom: 16,
9115
- screenRadius: 62,
9116
- bodyRadius: 78
9117
- },
9118
- tablet: {
9119
- border: 44,
9120
- bottom: 44,
9121
- screenRadius: 18,
9122
- bodyRadius: 62
9123
- },
9124
- laptop: {
9125
- border: 20,
9126
- bottom: LAPTOP_CHIN + LAPTOP_BASE.height,
9127
- screenRadius: 10,
9128
- bodyRadius: 30
9129
- },
9130
- foldable: {
9131
- border: 20,
9132
- bottom: 20,
9133
- screenRadius: 48,
9134
- bodyRadius: 68
9135
- }
9136
- };
9137
- /**
9138
- * A device's screen corners as a CSS `border-radius`, which the body and every
9139
- * box drawn on its screen share. A laptop's screen meets its chin, so only
9140
- * its top corners round.
9141
- */
9142
- function screenCorners(device) {
9143
- const { screenRadius } = BEZELS[device];
9144
- return device === "laptop" ? `${screenRadius}px ${screenRadius}px 0 0` : `${screenRadius}px`;
9145
- }
9146
- /**
9147
- * The narrowest width each device draws around, widest first, so a frame
9148
- * takes the first one it reaches. Under the phone's width no device fits.
9149
- */
9150
- const DEVICE_WIDTHS = [
9151
- ["laptop", 1024],
9152
- ["tablet", 480],
9153
- ["phone", 320]
9154
- ];
9155
- /** The device a frame this wide draws inside, null under 320 where none fits. */
9156
- function deviceForWidth(width) {
9157
- return DEVICE_WIDTHS.find(([, least]) => width >= least)?.[0] ?? null;
9158
- }
9159
- /**
9160
- * The body's colors, fixed in both themes, since the board draws hardware
9161
- * rather than chrome: the body, the hairline around it, and the island.
9162
- */
9163
- const BEZEL_COLORS = {
9164
- body: "#17181b",
9165
- base: "#2c2e33",
9166
- edge: "#45484f",
9167
- island: "#050506",
9168
- homeBar: "rgba(128, 128, 128, 0.6)",
9169
- button: "#2a2c31",
9170
- islandText: "#ffffff",
9171
- islandLive: "#34c759"
9172
- };
9173
- /**
9174
- * The phone's island, a generic pill standing in for a size no source gives,
9175
- * and the home bar, each centered on the screen and drawn over the frame.
9176
- */
9177
- const PHONE_ISLAND = {
9178
- width: 81,
9179
- height: 30,
9180
- top: 14
9181
- };
9182
- const HOME_BAR = {
9183
- width: 140,
9184
- height: 5,
9185
- bottom: 8
9186
- };
9187
- /** The island's two widths, the compact pill and the wide one a call or a timer shows. */
9188
- const ISLANDS = ["compact", "wide"];
9189
- /** A layout entry's `island` as an island, compact for none or a value no reader knows. */
9190
- function islandOf(value) {
9191
- return value === "wide" ? "wide" : "compact";
9192
- }
9193
- /** The wide island's width, scaled off the picked mock's ratio to the compact one. */
9194
- const WIDE_ISLAND_WIDTH = 126;
9195
- /** The phone's island at its picked width, the wide one holding a timer. */
9196
- function phoneIsland(island) {
9197
- return island === "wide" ? {
9198
- ...PHONE_ISLAND,
9199
- width: WIDE_ISLAND_WIDTH
9200
- } : { ...PHONE_ISLAND };
9201
- }
9202
- /** What the wide island shows, a running timer no frame sets, and the heights of the level bars beside it. */
9203
- const WIDE_ISLAND_TIMER = "0:42";
9204
- const WIDE_ISLAND_LEVEL = [
9205
- 5,
9206
- 9,
9207
- 7
9208
- ];
9209
- /**
9210
- * The phone's side buttons, each from the body's top edge, scaled off the
9211
- * picked mock: the action button and two volume buttons on the left, and
9212
- * the side button on the right.
9213
- */
9214
- const PHONE_BUTTONS = [
9215
- {
9216
- side: "left",
9217
- top: 142,
9218
- height: 33
9219
- },
9220
- {
9221
- side: "left",
9222
- top: 195,
9223
- height: 59
9224
- },
9225
- {
9226
- side: "left",
9227
- top: 266,
9228
- height: 59
9229
- },
9230
- {
9231
- side: "right",
9232
- top: 222,
9233
- height: 95
9234
- }
9235
- ];
9236
- /**
9237
- * The phone's status bar, ending 10 below the island so a page under it
9238
- * clears the island, its time and marks in the island's band `side` in from
9239
- * each edge, past the screen's corner arc.
9240
- */
9241
- const STATUS_BAR = {
9242
- height: PHONE_ISLAND.top + PHONE_ISLAND.height + 10,
9243
- band: {
9244
- top: PHONE_ISLAND.top,
9245
- height: PHONE_ISLAND.height
9246
- },
9247
- side: 40,
9248
- time: "9:41",
9249
- font: 16
9250
- };
9251
- /** The face the status bar and the wide island draw in, a system face every surface holds. */
9252
- const STATUS_FONT = "system-ui, -apple-system, sans-serif";
9253
- /** The status bar's signal bars, shortest first, and its battery, each in points. */
9254
- const SIGNAL_BARS = [
9255
- 4,
9256
- 6.5,
9257
- 9,
9258
- 11.5
9259
- ];
9260
- const BATTERY = {
9261
- width: 25,
9262
- height: 12,
9263
- radius: 3.5,
9264
- cap: 2
9265
- };
9266
- /** The height the device's status bar takes off the top of a frame's box, 0 for any device but the phone. */
9267
- function topInset(device) {
9268
- return device === "phone" ? STATUS_BAR.height : 0;
9269
- }
9270
- /**
9271
- * The page's box inside a frame's box, the box less the status bar while a
9272
- * phone shows and the box itself on every other device or none. A frame's
9273
- * box keeps the screen's size, and every surface reads the page through this.
9274
- */
9275
- function pageBox(box, device) {
9276
- const inset = topInset(device);
9277
- return {
9278
- x: box.x,
9279
- y: box.y + inset,
9280
- width: box.width,
9281
- height: Math.max(0, box.height - inset)
9282
- };
9283
- }
9284
- /** The page's corners as a CSS `border-radius`, square on top under a phone's status bar. */
9285
- function pageCorners(device) {
9286
- if (device !== "phone") return screenCorners(device);
9287
- const { screenRadius } = BEZELS.phone;
9288
- return `0 0 ${screenRadius}px ${screenRadius}px`;
9289
- }
9290
- /**
9291
- * The fill a page shows at its top and its text color, read off its root and
9292
- * then its body as the browser paints the canvas. Self-contained, so a
9293
- * browser runs it in the page by its source alone.
9294
- */
9295
- function pageColors(doc = document) {
9296
- const view = doc.defaultView;
9297
- const read = (element) => element && view ? view.getComputedStyle(element) : null;
9298
- const root = read(doc.documentElement);
9299
- const body = read(doc.body);
9300
- const painted = (color) => color !== void 0 && color !== "transparent" && !/^rgba\(.*,\s*0\)$/.test(color);
9301
- return {
9302
- fill: [root?.backgroundColor, body?.backgroundColor].find(painted) ?? null,
9303
- ink: body?.color ?? root?.color ?? "CanvasText"
9304
- };
9305
- }
9306
- /** The ways a foldable is held, each a screen the frame's box takes the size of. */
9307
- const POSES = [
9308
- "closed",
9309
- "half",
9310
- "open"
9311
- ];
9312
- /**
9313
- * Each pose's screen in points, the cover display closed and the inner one
9314
- * half open and open. The published pixel counts at three pixels to a point,
9315
- * a scale no source states for this device.
9316
- */
9317
- const POSE_SIZES = {
9318
- closed: {
9319
- width: 466,
9320
- height: 678
9321
- },
9322
- half: {
9323
- width: 890,
9324
- height: 626
9325
- },
9326
- open: {
9327
- width: 890,
9328
- height: 626
9329
- }
9330
- };
9331
- /** A layout entry's `pose` as a pose, closed for none or a value no reader knows. */
9332
- function poseOf(value) {
9333
- return POSES.find((pose) => pose === value) ?? "closed";
9334
- }
9335
- /** The pose a frame this wide starts in, closed or open, whichever moves its box least. */
9336
- function nearestPose(width) {
9337
- return Math.abs(width - POSE_SIZES.closed.width) <= Math.abs(width - POSE_SIZES.open.width) ? "closed" : "open";
9338
- }
9339
- /**
9340
- * The foldable's island, a generic pill, centered on the cover screen and on
9341
- * the right half of the inner one, a place no source gives.
9342
- */
9343
- const FOLDABLE_ISLAND = {
9344
- width: 100,
9345
- height: 30,
9346
- top: 14
9347
- };
9348
- /** Where the island's center sits across a pose's screen, as a share of its width. */
9349
- function islandCenter(pose) {
9350
- return pose === "closed" ? .5 : .75;
9351
- }
9352
- /**
9353
- * The band drawn down the middle of the inner screen, a faint crease open
9354
- * and a shaded fold half open, null on the cover screen, which has no fold.
9355
- */
9356
- function foldBand(pose) {
9357
- if (pose === "closed") return null;
9358
- if (pose === "open") return {
9359
- width: 26,
9360
- background: "linear-gradient(90deg, transparent, rgba(0,0,0,.05) 35%, rgba(0,0,0,.11) 50%, rgba(255,255,255,.5) 56%, transparent)"
9361
- };
9362
- return {
9363
- width: 150,
9364
- background: "linear-gradient(90deg, transparent, rgba(0,0,0,.10) 30%, rgba(0,0,0,.34) 49%, rgba(0,0,0,.34) 51%, rgba(0,0,0,.08) 70%, transparent)"
9365
- };
9366
- }
9367
- /**
9368
- * The laptop's chin and base, each a box from the frame's top left, which
9369
- * the board and the PNG draw as positioned boxes, since one spread around
9370
- * the screen cannot draw a body wider below than above.
9371
- */
9372
- function laptopParts({ width, height }) {
9373
- const { border } = BEZELS.laptop;
9374
- const lid = width + 2 * border;
9375
- const reach = baseReach(width);
9376
- return {
9377
- chin: {
9378
- x: -border,
9379
- y: height,
9380
- width: lid,
9381
- height: LAPTOP_CHIN
9382
- },
9383
- base: {
9384
- x: -border - reach,
9385
- y: height + LAPTOP_CHIN,
9386
- width: lid + 2 * reach,
9387
- height: LAPTOP_BASE.height
9388
- }
9389
- };
9390
- }
9391
- /** How far a device's parts stand past its body's sides, a laptop's base or a phone's buttons. */
9392
- function sideReach(device, width) {
9393
- if (device === "laptop") return baseReach(width);
9394
- return device === "phone" ? 4 : 0;
9395
- }
9396
- function baseReach(width) {
9397
- return Math.round((width + 2 * BEZELS.laptop.border) * LAPTOP_BASE.reach);
9398
- }
9399
- /**
9400
- * The `box-shadow` drawing a device's body, with a hairline on the board so a
9401
- * dark body reads on a dark canvas, and no drop shadow in an export.
9402
- */
9403
- function bezelShadow(device, { board = true } = {}) {
9404
- const { border } = BEZELS[device];
9405
- if (!board) return [`0 0 0 ${border - 1}px ${BEZEL_COLORS.body}`, `0 0 0 ${border}px ${BEZEL_COLORS.edge}`].join(", ");
9406
- return [
9407
- `0 0 0 ${border}px ${BEZEL_COLORS.body}`,
9408
- `0 0 0 calc(${border}px + 1px / var(--zoom, 1)) ${BEZEL_COLORS.edge}`,
9409
- `0 ${border}px ${border * 3}px rgba(0, 0, 0, 0.3)`
9410
- ].join(", ");
9411
- }
9412
- /**
9413
- * The box a device's body covers around a frame's box, the box itself with
9414
- * none. A laptop's base reaches past its lid and a phone's buttons past its
9415
- * sides, so their sides grow by more than their top.
9416
- */
9417
- function bezelBox(box, device) {
9418
- if (!device) return { ...box };
9419
- const { border, bottom } = BEZELS[device];
9420
- const side = border + sideReach(device, box.width);
9421
- return {
9422
- x: box.x - side,
9423
- y: box.y - border,
9424
- width: box.width + 2 * side,
9425
- height: box.height + border + bottom
9426
- };
9427
- }
9428
9230
  // src/shared/frame-sizes.ts
9429
9231
  /** The current iPhone, iPad Air portrait, and a common laptop viewport. */
9430
9232
  const FRAME_SIZES = {
@@ -9605,6 +9407,347 @@ function presetAt(width) {
9605
9407
  function referenceHeight(width) {
9606
9408
  return FRAME_SIZES[presetAt(width) ?? "desktop"].height;
9607
9409
  }
9410
+ // src/shared/frame-device.ts
9411
+ /**
9412
+ * The devices the board can draw around a frame. A frame's width picks the
9413
+ * first three, and a frame names a foldable.
9414
+ */
9415
+ const DEVICES = [
9416
+ "phone",
9417
+ "tablet",
9418
+ "laptop",
9419
+ "foldable"
9420
+ ];
9421
+ /** The laptop lid's chin below the screen, past the border its sides hold. */
9422
+ const LAPTOP_CHIN = 28;
9423
+ /** The laptop's base below the chin, reaching past the lid on each side by its share of the lid's width. */
9424
+ const LAPTOP_BASE = {
9425
+ height: 14,
9426
+ reach: .06,
9427
+ radius: 10
9428
+ };
9429
+ /**
9430
+ * Bezels measured off a current Pro phone and 13-inch tablet, the laptop
9431
+ * scaled off the picked mock, and the foldable's body less its glass. The
9432
+ * tablet's and the foldable's screen radii are guesses no source gives.
9433
+ */
9434
+ const BEZELS = {
9435
+ phone: {
9436
+ border: 16,
9437
+ bottom: 16,
9438
+ screenRadius: 62,
9439
+ bodyRadius: 78
9440
+ },
9441
+ tablet: {
9442
+ border: 44,
9443
+ bottom: 44,
9444
+ screenRadius: 18,
9445
+ bodyRadius: 62
9446
+ },
9447
+ laptop: {
9448
+ border: 20,
9449
+ bottom: LAPTOP_CHIN + LAPTOP_BASE.height,
9450
+ screenRadius: 10,
9451
+ bodyRadius: 30
9452
+ },
9453
+ foldable: {
9454
+ border: 20,
9455
+ bottom: 20,
9456
+ screenRadius: 48,
9457
+ bodyRadius: 68
9458
+ }
9459
+ };
9460
+ /**
9461
+ * A device's screen corners as a CSS `border-radius`, which the body and every
9462
+ * box drawn on its screen share. A laptop's screen meets its chin, so only
9463
+ * its top corners round.
9464
+ */
9465
+ function screenCorners(device) {
9466
+ const { screenRadius } = BEZELS[device];
9467
+ return device === "laptop" ? `${screenRadius}px ${screenRadius}px 0 0` : `${screenRadius}px`;
9468
+ }
9469
+ /**
9470
+ * The narrowest width each device draws around, widest first, so a frame
9471
+ * takes the first one it reaches. Under the phone's width no device fits.
9472
+ */
9473
+ const DEVICE_WIDTHS = [
9474
+ ["laptop", 1024],
9475
+ ["tablet", 480],
9476
+ ["phone", 320]
9477
+ ];
9478
+ /** The device a frame this wide draws inside, null under 320 where none fits. */
9479
+ function deviceForWidth(width) {
9480
+ return DEVICE_WIDTHS.find(([, least]) => width >= least)?.[0] ?? null;
9481
+ }
9482
+ /**
9483
+ * The body's colors, fixed in both themes, since the board draws hardware
9484
+ * rather than chrome: the body, the hairline around it, and the island.
9485
+ */
9486
+ const BEZEL_COLORS = {
9487
+ body: "#17181b",
9488
+ base: "#2c2e33",
9489
+ edge: "#45484f",
9490
+ island: "#050506",
9491
+ homeBar: "rgba(128, 128, 128, 0.6)",
9492
+ button: "#2a2c31",
9493
+ islandText: "#ffffff",
9494
+ islandLive: "#34c759"
9495
+ };
9496
+ /**
9497
+ * The phone's island, a generic pill standing in for a size no source gives,
9498
+ * and the home bar, each centered on the screen and drawn over the frame.
9499
+ */
9500
+ const PHONE_ISLAND = {
9501
+ width: 81,
9502
+ height: 30,
9503
+ top: 14
9504
+ };
9505
+ const HOME_BAR = {
9506
+ width: 140,
9507
+ height: 5,
9508
+ bottom: 8
9509
+ };
9510
+ /** The island's two widths, the compact pill and the wide one a call or a timer shows. */
9511
+ const ISLANDS = ["compact", "wide"];
9512
+ /** A layout entry's `island` as an island, compact for none or a value no reader knows. */
9513
+ function islandOf(value) {
9514
+ return value === "wide" ? "wide" : "compact";
9515
+ }
9516
+ /** The wide island's width, scaled off the picked mock's ratio to the compact one. */
9517
+ const WIDE_ISLAND_WIDTH = 126;
9518
+ /** The phone's island at its picked width, the wide one holding a timer. */
9519
+ function phoneIsland(island) {
9520
+ return island === "wide" ? {
9521
+ ...PHONE_ISLAND,
9522
+ width: WIDE_ISLAND_WIDTH
9523
+ } : { ...PHONE_ISLAND };
9524
+ }
9525
+ /** What the wide island shows, a running timer no frame sets, and the heights of the level bars beside it. */
9526
+ const WIDE_ISLAND_TIMER = "0:42";
9527
+ const WIDE_ISLAND_LEVEL = [
9528
+ 5,
9529
+ 9,
9530
+ 7
9531
+ ];
9532
+ /**
9533
+ * The phone's side buttons, each from the body's top edge, scaled off the
9534
+ * picked mock: the action button and two volume buttons on the left, and
9535
+ * the side button on the right.
9536
+ */
9537
+ const PHONE_BUTTONS = [
9538
+ {
9539
+ side: "left",
9540
+ top: 142,
9541
+ height: 33
9542
+ },
9543
+ {
9544
+ side: "left",
9545
+ top: 195,
9546
+ height: 59
9547
+ },
9548
+ {
9549
+ side: "left",
9550
+ top: 266,
9551
+ height: 59
9552
+ },
9553
+ {
9554
+ side: "right",
9555
+ top: 222,
9556
+ height: 95
9557
+ }
9558
+ ];
9559
+ /**
9560
+ * The phone's status bar, ending 10 below the island so a page under it
9561
+ * clears the island, its time and marks in the island's band `side` in from
9562
+ * each edge, past the screen's corner arc.
9563
+ */
9564
+ const STATUS_BAR = {
9565
+ height: PHONE_ISLAND.top + PHONE_ISLAND.height + 10,
9566
+ band: {
9567
+ top: PHONE_ISLAND.top,
9568
+ height: PHONE_ISLAND.height
9569
+ },
9570
+ side: 40,
9571
+ time: "9:41",
9572
+ font: 16
9573
+ };
9574
+ /** The face the status bar and the wide island draw in, a system face every surface holds. */
9575
+ const STATUS_FONT = "system-ui, -apple-system, sans-serif";
9576
+ /** The status bar's signal bars, shortest first, and its battery, each in points. */
9577
+ const SIGNAL_BARS = [
9578
+ 4,
9579
+ 6.5,
9580
+ 9,
9581
+ 11.5
9582
+ ];
9583
+ const BATTERY = {
9584
+ width: 25,
9585
+ height: 12,
9586
+ radius: 3.5,
9587
+ cap: 2
9588
+ };
9589
+ /** The height the device's status bar takes off the top of a frame's box, 0 for any device but the phone. */
9590
+ function topInset(device) {
9591
+ return device === "phone" ? STATUS_BAR.height : 0;
9592
+ }
9593
+ /**
9594
+ * The page's box inside a frame's box, the box less the status bar while a
9595
+ * phone shows and the box itself on every other device or none. A frame's
9596
+ * box keeps the screen's size, and every surface reads the page through this.
9597
+ */
9598
+ function pageBox(box, device) {
9599
+ const inset = topInset(device);
9600
+ return {
9601
+ x: box.x,
9602
+ y: box.y + inset,
9603
+ width: box.width,
9604
+ height: Math.max(0, box.height - inset)
9605
+ };
9606
+ }
9607
+ /** The page's corners as a CSS `border-radius`, square on top under a phone's status bar. */
9608
+ function pageCorners(device) {
9609
+ if (device !== "phone") return screenCorners(device);
9610
+ const { screenRadius } = BEZELS.phone;
9611
+ return `0 0 ${screenRadius}px ${screenRadius}px`;
9612
+ }
9613
+ /**
9614
+ * The fill a page shows at its top and its text color, read off its root and
9615
+ * then its body as the browser paints the canvas. Self-contained, so a
9616
+ * browser runs it in the page by its source alone.
9617
+ */
9618
+ function pageColors(doc = document) {
9619
+ const view = doc.defaultView;
9620
+ const read = (element) => element && view ? view.getComputedStyle(element) : null;
9621
+ const root = read(doc.documentElement);
9622
+ const body = read(doc.body);
9623
+ const painted = (color) => color !== void 0 && color !== "transparent" && !/^rgba\(.*,\s*0\)$/.test(color);
9624
+ return {
9625
+ fill: [root?.backgroundColor, body?.backgroundColor].find(painted) ?? null,
9626
+ ink: body?.color ?? root?.color ?? "CanvasText"
9627
+ };
9628
+ }
9629
+ /** The ways a foldable is held, each a screen the frame's box takes the size of. */
9630
+ const POSES = [
9631
+ "closed",
9632
+ "half",
9633
+ "open"
9634
+ ];
9635
+ /**
9636
+ * Each pose's screen in points, the cover display closed and the inner one
9637
+ * half open and open. The published pixel counts at three pixels to a point,
9638
+ * a scale no source states for this device.
9639
+ */
9640
+ const POSE_SIZES = {
9641
+ closed: {
9642
+ width: 466,
9643
+ height: 678
9644
+ },
9645
+ half: {
9646
+ width: 890,
9647
+ height: 626
9648
+ },
9649
+ open: {
9650
+ width: 890,
9651
+ height: 626
9652
+ }
9653
+ };
9654
+ /** A layout entry's `pose` as a pose, closed for none or a value no reader knows. */
9655
+ function poseOf(value) {
9656
+ return POSES.find((pose) => pose === value) ?? "closed";
9657
+ }
9658
+ /** The pose a frame this wide starts in, closed or open, whichever moves its box least. */
9659
+ function nearestPose(width) {
9660
+ return Math.abs(width - POSE_SIZES.closed.width) <= Math.abs(width - POSE_SIZES.open.width) ? "closed" : "open";
9661
+ }
9662
+ /**
9663
+ * The foldable's island, a generic pill, centered on the cover screen and on
9664
+ * the right half of the inner one, a place no source gives.
9665
+ */
9666
+ const FOLDABLE_ISLAND = {
9667
+ width: 100,
9668
+ height: 30,
9669
+ top: 14
9670
+ };
9671
+ /** Where the island's center sits across a pose's screen, as a share of its width. */
9672
+ function islandCenter(pose) {
9673
+ return pose === "closed" ? .5 : .75;
9674
+ }
9675
+ /**
9676
+ * The band drawn down the middle of the inner screen, a faint crease open
9677
+ * and a shaded fold half open, null on the cover screen, which has no fold.
9678
+ */
9679
+ function foldBand(pose) {
9680
+ if (pose === "closed") return null;
9681
+ if (pose === "open") return {
9682
+ width: 26,
9683
+ background: "linear-gradient(90deg, transparent, rgba(0,0,0,.05) 35%, rgba(0,0,0,.11) 50%, rgba(255,255,255,.5) 56%, transparent)"
9684
+ };
9685
+ return {
9686
+ width: 150,
9687
+ background: "linear-gradient(90deg, transparent, rgba(0,0,0,.10) 30%, rgba(0,0,0,.34) 49%, rgba(0,0,0,.34) 51%, rgba(0,0,0,.08) 70%, transparent)"
9688
+ };
9689
+ }
9690
+ /**
9691
+ * The laptop's chin and base, each a box from the frame's top left, which
9692
+ * the board and the PNG draw as positioned boxes, since one spread around
9693
+ * the screen cannot draw a body wider below than above.
9694
+ */
9695
+ function laptopParts({ width, height }) {
9696
+ const { border } = BEZELS.laptop;
9697
+ const lid = width + 2 * border;
9698
+ const reach = baseReach(width);
9699
+ return {
9700
+ chin: {
9701
+ x: -border,
9702
+ y: height,
9703
+ width: lid,
9704
+ height: LAPTOP_CHIN
9705
+ },
9706
+ base: {
9707
+ x: -border - reach,
9708
+ y: height + LAPTOP_CHIN,
9709
+ width: lid + 2 * reach,
9710
+ height: LAPTOP_BASE.height
9711
+ }
9712
+ };
9713
+ }
9714
+ /** How far a device's parts stand past its body's sides, a laptop's base or a phone's buttons. */
9715
+ function sideReach(device, width) {
9716
+ if (device === "laptop") return baseReach(width);
9717
+ return device === "phone" ? 4 : 0;
9718
+ }
9719
+ function baseReach(width) {
9720
+ return Math.round((width + 2 * BEZELS.laptop.border) * LAPTOP_BASE.reach);
9721
+ }
9722
+ /**
9723
+ * The `box-shadow` drawing a device's body, with a hairline on the board so a
9724
+ * dark body reads on a dark canvas, and no drop shadow in an export.
9725
+ */
9726
+ function bezelShadow(device, { board = true } = {}) {
9727
+ const { border } = BEZELS[device];
9728
+ if (!board) return [`0 0 0 ${border - 1}px ${BEZEL_COLORS.body}`, `0 0 0 ${border}px ${BEZEL_COLORS.edge}`].join(", ");
9729
+ return [
9730
+ `0 0 0 ${border}px ${BEZEL_COLORS.body}`,
9731
+ `0 0 0 calc(${border}px + 1px / var(--zoom, 1)) ${BEZEL_COLORS.edge}`,
9732
+ `0 ${border}px ${border * 3}px rgba(0, 0, 0, 0.3)`
9733
+ ].join(", ");
9734
+ }
9735
+ /**
9736
+ * The box a device's body covers around a frame's box, the box itself with
9737
+ * none. A laptop's base reaches past its lid and a phone's buttons past its
9738
+ * sides, so their sides grow by more than their top.
9739
+ */
9740
+ function bezelBox(box, device) {
9741
+ if (!device) return { ...box };
9742
+ const { border, bottom } = BEZELS[device];
9743
+ const side = border + sideReach(device, box.width);
9744
+ return {
9745
+ x: box.x - side,
9746
+ y: box.y - border,
9747
+ width: box.width + 2 * side,
9748
+ height: box.height + border + bottom
9749
+ };
9750
+ }
9608
9751
  // src/shared/frame-widths.ts
9609
9752
  /**
9610
9753
  * A layout entry's `widths` as a clean list, anything malformed reading as
@@ -24591,7 +24734,7 @@ const STEP = /^(?:from|to|\d+(?:\.\d+)?%)(?:\s*,\s*(?:from|to|\d+(?:\.\d+)?%))*$
24591
24734
  * it in its own document, a value that could load a file included.
24592
24735
  */
24593
24736
  function readTransitionSheet(name, css) {
24594
- if (!isOwnTransitionName(name)) return refused([{
24737
+ if (!isOwnTransitionName(name)) return refused$1([{
24595
24738
  message: `${name} is no transition name. Name the file in lowercase kebab case, and not after a built-in transition, none, or page`,
24596
24739
  location: null
24597
24740
  }]);
@@ -24601,7 +24744,7 @@ function readTransitionSheet(name, css) {
24601
24744
  } catch (error) {
24602
24745
  if (!(error instanceof CssSyntaxError)) throw error;
24603
24746
  const at = offsetOf(css, error.line ?? 1, error.column ?? 1);
24604
- return refused([{
24747
+ return refused$1([{
24605
24748
  message: `The stylesheet does not parse: ${error.reason}`,
24606
24749
  location: {
24607
24750
  line: error.line ?? 1,
@@ -24628,7 +24771,7 @@ function readTransitionSheet(name, css) {
24628
24771
  message: "@keyframes enter is missing",
24629
24772
  location: null
24630
24773
  });
24631
- if (!enter || problems.length > 0) return refused(problems);
24774
+ if (!enter || problems.length > 0) return refused$1(problems);
24632
24775
  const leave = held.get("leave");
24633
24776
  return {
24634
24777
  ok: true,
@@ -24636,7 +24779,7 @@ function readTransitionSheet(name, css) {
24636
24779
  leave: leave ? bodyOf(leave) : null
24637
24780
  };
24638
24781
  }
24639
- function refused(problems) {
24782
+ function refused$1(problems) {
24640
24783
  return {
24641
24784
  ok: false,
24642
24785
  problems
@@ -25172,7 +25315,7 @@ async function isDirectory(path) {
25172
25315
  }
25173
25316
  }
25174
25317
  // package.json
25175
- var version$1 = "0.43.0";
25318
+ var version$1 = "0.44.0";
25176
25319
  var dependencies = { "playwright-core": "1.65.0" };
25177
25320
  var peerDependencies = { "oxfmt": "0.78.0" };
25178
25321
  // src/shared/version.ts
@@ -30971,6 +31114,293 @@ const bodyLimit = (options) => {
30971
31114
  return next();
30972
31115
  };
30973
31116
  };
31117
+ // src/server/checks/links.ts
31118
+ const LINK_RULES = [
31119
+ {
31120
+ id: "outside-link",
31121
+ tier: "exact",
31122
+ severity: "error",
31123
+ description: "A frame loads files from its own page folder and its project's assets/ folder alone, never from a sibling page or the server root"
31124
+ },
31125
+ {
31126
+ id: "network",
31127
+ tier: "exact",
31128
+ severity: "error",
31129
+ description: "A frame loads nothing over the network, while a navigation link passes"
31130
+ },
31131
+ {
31132
+ id: "missing-file",
31133
+ tier: "exact",
31134
+ severity: "error",
31135
+ description: "Every local file a frame loads exists"
31136
+ }
31137
+ ];
31138
+ const finding$12 = findingFor(LINK_RULES);
31139
+ /** The attributes a `<model-viewer>` loads a file through, which `docs` states beside the rule. */
31140
+ const MODEL_LOADS = [
31141
+ "src",
31142
+ "poster",
31143
+ "environment-image",
31144
+ "skybox-image"
31145
+ ];
31146
+ /**
31147
+ * The attributes that load a resource, by element. An `a href` navigates
31148
+ * rather than loads, so it is left out.
31149
+ */
31150
+ const RESOURCE_ATTRIBUTES = {
31151
+ link: ["href"],
31152
+ script: ["src"],
31153
+ img: ["src", "srcset"],
31154
+ source: ["src", "srcset"],
31155
+ video: ["src", "poster"],
31156
+ audio: ["src"],
31157
+ track: ["src"],
31158
+ iframe: ["src"],
31159
+ embed: ["src"],
31160
+ object: ["data"],
31161
+ input: ["src"],
31162
+ image: ["href", "xlink:href"],
31163
+ use: ["href", "xlink:href"],
31164
+ "model-viewer": [...MODEL_LOADS]
31165
+ };
31166
+ /** The lighting a viewer builds itself, which `environment-image` names in place of a file. */
31167
+ const BUILT_IN_ENVIRONMENTS = /* @__PURE__ */ new Set(["neutral", "legacy"]);
31168
+ /** `outside-link`, `network`, and `missing-file` over every load a frame makes. */
31169
+ function checkLinks(source) {
31170
+ return frameLoads(source).flatMap((load) => judge(source, load));
31171
+ }
31172
+ /**
31173
+ * Every resource a frame loads, from its elements' attributes and inline
31174
+ * styles and from each sheet it renders with, unjudged. The link check and the
31175
+ * asset usage count read this one list, so they never disagree on a load.
31176
+ */
31177
+ function frameLoads(source) {
31178
+ const framePath = boardPath(source.root, source.path);
31179
+ const loads = [];
31180
+ for (const element of source.elements) {
31181
+ for (const name of RESOURCE_ATTRIBUTES[element.name] ?? []) {
31182
+ const value = element.attribs[name];
31183
+ if (value === void 0) continue;
31184
+ if (name === "environment-image" && BUILT_IN_ENVIRONMENTS.has(value)) continue;
31185
+ const urls = name === "srcset" ? srcsetUrls(value) : [value];
31186
+ for (const url of urls) loads.push({
31187
+ url,
31188
+ base: source.pageDir,
31189
+ path: framePath,
31190
+ location: attributeLocation(element, name),
31191
+ via: `<${element.name} ${name}>`
31192
+ });
31193
+ }
31194
+ const style = element.attribs.style;
31195
+ if (style !== void 0) for (const { url } of cssUrls(`x{${style}}`)) loads.push({
31196
+ url,
31197
+ base: source.pageDir,
31198
+ path: framePath,
31199
+ location: attributeLocation(element, "style"),
31200
+ via: `a style attribute's url()`
31201
+ });
31202
+ }
31203
+ for (const sheet of source.sheets) loads.push(...sheetLoads(source, sheet));
31204
+ return loads;
31205
+ }
31206
+ function sheetLoads(source, sheet) {
31207
+ const path = boardPath(source.root, sheet.path);
31208
+ const text = sheet.origin === "style" ? source.html : sheet.css;
31209
+ return cssUrls(sheet.css).map(({ url, start, end, kind }) => ({
31210
+ url,
31211
+ base: sheetBase(sheet),
31212
+ path,
31213
+ location: locate$1(text, sheet.offset + start, sheet.offset + end),
31214
+ via: kind === "import" ? "@import" : "url()"
31215
+ }));
31216
+ }
31217
+ function judge(source, load) {
31218
+ const url = load.url.trim();
31219
+ if (url === "" || url.startsWith("#") || /^(data|blob|about):/i.test(url)) return [];
31220
+ const fields = {
31221
+ frame: source.ref,
31222
+ path: load.path,
31223
+ location: load.location
31224
+ };
31225
+ if (hasScheme(url)) return [finding$12("network", {
31226
+ ...fields,
31227
+ message: `${load.via} loads ${url} over the network. Save the file into the page folder or the project's assets/ and link it there.`
31228
+ })];
31229
+ const target = localTarget(url, load.base);
31230
+ if (target === null || !allowed(source, target)) return [finding$12("outside-link", {
31231
+ ...fields,
31232
+ message: `${load.via} loads ${url}, outside this page's folder and the project's assets/. Move the file into one of them.`
31233
+ })];
31234
+ if (!existsSync(target)) return [finding$12("missing-file", {
31235
+ ...fields,
31236
+ message: `${load.via} loads ${url}, which does not exist.`
31237
+ })];
31238
+ return [];
31239
+ }
31240
+ /**
31241
+ * Inside the page folder or the project's `assets/`, both by path and, for a
31242
+ * file that exists, by realpath, so a symlink out of the project is caught.
31243
+ */
31244
+ function allowed(source, target) {
31245
+ const assets = assetsDirOf(source);
31246
+ if (!isInside(source.pageDir, target) && !isInside(assets, target)) return false;
31247
+ if (!existsSync(target)) return true;
31248
+ const real = realpathSync(target);
31249
+ const projectDir = realpathSync(source.projectDir);
31250
+ return isInside(realpathSync(source.pageDir), real) || isInside(join(projectDir, "assets"), real);
31251
+ }
31252
+ function srcsetUrls(value) {
31253
+ return value.split(",").map((candidate) => candidate.trim().split(/\s+/)[0] ?? "").filter((url) => url !== "");
31254
+ }
31255
+ /** Every `url()` and `@import` in a sheet. A sheet that does not parse loads nothing. */
31256
+ function cssUrls(css) {
31257
+ const urls = [];
31258
+ let root;
31259
+ try {
31260
+ root = postcss_default.parse(css);
31261
+ } catch {
31262
+ return urls;
31263
+ }
31264
+ root.walk((node) => {
31265
+ const start = node.source?.start?.offset ?? 0;
31266
+ const end = node.source?.end?.offset ?? start;
31267
+ if (node.type === "atrule" && node.name.toLowerCase() === "import") {
31268
+ const url = importUrl(node.params);
31269
+ if (url !== null) urls.push({
31270
+ url,
31271
+ start,
31272
+ end,
31273
+ kind: "import"
31274
+ });
31275
+ } else if (node.type === "decl") for (const match of node.value.matchAll(/url\(\s*(['"]?)(.*?)\1\s*\)/gi)) urls.push({
31276
+ url: match[2] ?? "",
31277
+ start,
31278
+ end,
31279
+ kind: "url"
31280
+ });
31281
+ });
31282
+ return urls;
31283
+ }
31284
+ // src/server/board/asset-usage.ts
31285
+ /**
31286
+ * A per-project cache of how many frames link each asset, counted from the
31287
+ * same loads the link check judges. A frame counts once per file, and only a
31288
+ * link resolving inside the project's `assets/` counts.
31289
+ */
31290
+ function createAssetUsage(root) {
31291
+ const cache = /* @__PURE__ */ new Map();
31292
+ return {
31293
+ counts: (project) => {
31294
+ const cached = cache.get(project);
31295
+ if (cached) return cached;
31296
+ const built = countProject(root, project);
31297
+ cache.set(project, built);
31298
+ built.catch(() => {
31299
+ if (cache.get(project) === built) cache.delete(project);
31300
+ });
31301
+ return built;
31302
+ },
31303
+ drop: (paths) => {
31304
+ for (const path of paths) {
31305
+ const inside = relative(root, path);
31306
+ if (inside === "") {
31307
+ cache.clear();
31308
+ return;
31309
+ }
31310
+ if (inside.startsWith("..")) continue;
31311
+ const project = inside.split(sep)[0];
31312
+ if (project) cache.delete(project);
31313
+ }
31314
+ }
31315
+ };
31316
+ }
31317
+ async function countProject(root, project) {
31318
+ const projectDir = join(root, project);
31319
+ const counts = /* @__PURE__ */ new Map();
31320
+ for (const page of await listPageFolders(projectDir)) for (const name of await listFrames(join(projectDir, page))) for (const path of linkedAssets(root, project, page, name)) counts.set(path, (counts.get(path) ?? 0) + 1);
31321
+ return counts;
31322
+ }
31323
+ /**
31324
+ * The asset paths one frame links, each once, read from its file as it stands
31325
+ * rather than from a cached count. A frame gone between the listing and the
31326
+ * read links none.
31327
+ */
31328
+ function linkedAssets(root, project, page, name) {
31329
+ const linked = /* @__PURE__ */ new Set();
31330
+ let source;
31331
+ try {
31332
+ source = readFrame$1({
31333
+ root,
31334
+ project,
31335
+ page,
31336
+ name
31337
+ });
31338
+ } catch {
31339
+ return linked;
31340
+ }
31341
+ const assets = assetsDirOf(source);
31342
+ for (const load of frameLoads(source)) {
31343
+ const target = localTarget(load.url, load.base);
31344
+ if (target === null || target === assets || !isInside(assets, target)) continue;
31345
+ linked.add(relative(assets, target).split(sep).join("/"));
31346
+ }
31347
+ return linked;
31348
+ }
31349
+ // src/server/board/asset-links.ts
31350
+ /** Every frame in the project linking the file at `path` under its `assets/`. */
31351
+ async function framesLinking(root, project, path) {
31352
+ const projectDir = join(root, project);
31353
+ const frames = [];
31354
+ for (const page of await listPageFolders(projectDir)) for (const name of await listFrames(join(projectDir, page))) if (linkedAssets(root, project, page, name).has(path)) frames.push({
31355
+ root,
31356
+ project,
31357
+ page,
31358
+ name
31359
+ });
31360
+ return frames;
31361
+ }
31362
+ /**
31363
+ * The frame's markup with each load of `from` pointed at `to`, or null when no load in its own file names it.
31364
+ * A linked sheet's load, or a URL written through an entity or escape, stays for the link check to report.
31365
+ */
31366
+ function rewriteAssetLinks(source, from, to) {
31367
+ const framePath = boardPath(source.root, source.path);
31368
+ const edits = /* @__PURE__ */ new Map();
31369
+ for (const load of frameLoads(source)) {
31370
+ if (load.path !== framePath || load.location === null) continue;
31371
+ if (localTarget(load.url, load.base) !== from) continue;
31372
+ const { startOffset: start, endOffset: end } = load.location;
31373
+ edits.set(`${start}:${end}:${load.url}`, {
31374
+ start,
31375
+ end,
31376
+ url: load.url
31377
+ });
31378
+ }
31379
+ let html = source.html;
31380
+ let changed = false;
31381
+ const ordered = [...edits.values()].sort((a, b) => b.start - a.start);
31382
+ for (const { start, end, url } of ordered) {
31383
+ const written = html.slice(start, end).replace(urlPattern(url), (_, lead) => {
31384
+ changed = true;
31385
+ return `${lead}${renamedUrl(url, basename(to))}`;
31386
+ });
31387
+ html = html.slice(0, start) + written + html.slice(end);
31388
+ }
31389
+ return changed ? html : null;
31390
+ }
31391
+ /** The URL as a whole token, so `a.jpg` never matches inside `a.jpg-2.jpg`. */
31392
+ function urlPattern(url) {
31393
+ const escaped = url.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
31394
+ return new RegExp(`(^|["'(\\s,=])${escaped}(?=$|["')\\s,])`, "g");
31395
+ }
31396
+ /** The URL with its last path segment swapped for `name`, keeping its query and fragment. */
31397
+ function renamedUrl(url, name) {
31398
+ const cut = url.search(/[?#]/);
31399
+ const path = cut === -1 ? url : url.slice(0, cut);
31400
+ const rest = cut === -1 ? "" : url.slice(cut);
31401
+ const slash = path.lastIndexOf("/");
31402
+ return `${path.slice(0, slash + 1)}${encodeURIComponent(name)}${rest}`;
31403
+ }
30974
31404
  // src/shared/asset-kinds.ts
30975
31405
  const ASSET_KINDS = [
30976
31406
  "image",
@@ -31075,8 +31505,51 @@ const imageFindSchema = object$1({
31075
31505
  licenses: array$1(string$1()),
31076
31506
  results: array$1(imageResultSchema)
31077
31507
  });
31078
- /** The `<file>.license.json` beside every saved image, saying where it came from. */
31079
- const licenseFileSchema = discriminatedUnion("origin", [object$1({
31508
+ /** The texture sizes Poly Haven serves a model at, smallest first. */
31509
+ const MODEL_SIZES = [
31510
+ "1k",
31511
+ "2k",
31512
+ "4k",
31513
+ "8k",
31514
+ "16k"
31515
+ ];
31516
+ /** One Poly Haven model a search found, numbered from 1 in the order the ranking put it. */
31517
+ const modelResultSchema = object$1({
31518
+ number: int$1().min(1),
31519
+ /** Poly Haven's own id, which `--save` takes in place of the number. */
31520
+ id: string$1(),
31521
+ name: string$1(),
31522
+ authors: array$1(string$1()),
31523
+ categories: array$1(string$1()),
31524
+ tags: array$1(string$1()),
31525
+ license: literal("cc0"),
31526
+ /** The model's page on polyhaven.com. */
31527
+ landingUrl: string$1(),
31528
+ thumbnail: string$1().nullable(),
31529
+ polycount: int$1().nullable(),
31530
+ /** Poly Haven's x, y, and z extent in millimetres, z pointing up. */
31531
+ dimensionsMm: tuple([
31532
+ number(),
31533
+ number(),
31534
+ number()
31535
+ ]).nullable(),
31536
+ /** The texture sizes `--size` may ask for, smallest first. */
31537
+ sizes: array$1(_enum$1(MODEL_SIZES)),
31538
+ downloadCount: int$1().nullable()
31539
+ });
31540
+ /** What `model find` answers without `--save`, writing nothing. */
31541
+ const modelFindSchema = object$1({
31542
+ version: literal(1),
31543
+ query: string$1(),
31544
+ /** Who serves the results, which every surface listing them names. */
31545
+ source: object$1({
31546
+ name: literal("Poly Haven"),
31547
+ url: string$1()
31548
+ }),
31549
+ results: array$1(modelResultSchema)
31550
+ });
31551
+ /** The `<file>.license.json` beside every saved image or model, saying where it came from. */
31552
+ const licenseFileSchema = discriminatedUnion("origin", [discriminatedUnion("source", [object$1({
31080
31553
  version: literal(1),
31081
31554
  origin: literal("found"),
31082
31555
  source: literal("openverse"),
@@ -31095,6 +31568,23 @@ const licenseFileSchema = discriminatedUnion("origin", [object$1({
31095
31568
  /** ISO 8601. */
31096
31569
  savedAt: string$1()
31097
31570
  }), object$1({
31571
+ version: literal(1),
31572
+ origin: literal("found"),
31573
+ source: literal("polyhaven"),
31574
+ id: string$1(),
31575
+ /** The search that found it, null when it was saved by id. */
31576
+ query: string$1().nullable(),
31577
+ title: string$1(),
31578
+ /** Recorded though CC0 asks no credit, since where a file came from outlives that question. */
31579
+ authors: array$1(string$1()),
31580
+ license: literal("cc0"),
31581
+ licenseUrl: string$1(),
31582
+ landingUrl: string$1(),
31583
+ /** The glTF the GLB was packed from. */
31584
+ url: string$1(),
31585
+ size: _enum$1(MODEL_SIZES),
31586
+ savedAt: string$1()
31587
+ })]), object$1({
31098
31588
  version: literal(1),
31099
31589
  origin: literal("generated"),
31100
31590
  provider: _enum$1(IMAGE_PROVIDERS),
@@ -31115,6 +31605,8 @@ const savedImageSchema = object$1({
31115
31605
  licensePath: string$1(),
31116
31606
  license: licenseFileSchema
31117
31607
  });
31608
+ /** A model saved into a project's `assets/` as one `.glb`, with the license file written beside it. */
31609
+ const savedModelSchema = savedImageSchema;
31118
31610
  /** What `image generate` answers, with `saved` null on a dry run. */
31119
31611
  const imageGenerateSchema = object$1({
31120
31612
  version: literal(1),
@@ -31227,22 +31719,11 @@ async function walk(folder, prefix, real, into) {
31227
31719
  * folder reads `asset-missing` and an unshowable file `asset-not-placeable`.
31228
31720
  */
31229
31721
  async function resolveAsset(projectDir, path) {
31230
- const missing = {
31722
+ if (await confinedAsset(projectDir, path) === null) return {
31231
31723
  ok: false,
31232
31724
  code: "asset-missing",
31233
31725
  message: `assets/${path} is not a file in the project's assets folder`
31234
31726
  };
31235
- const segments = path.split("/");
31236
- if (segments.some((segment) => segment === "" || segment.startsWith(".") || isScratch(segment))) return missing;
31237
- const folder = join(projectDir, ASSETS_FOLDER);
31238
- try {
31239
- const real = await realpath(folder);
31240
- const target = await realpath(join(folder, ...segments));
31241
- if (!target.startsWith(real + sep) || !(await stat(target)).isFile()) return missing;
31242
- } catch (error) {
31243
- if (isCode(error, "ENOENT") || isCode(error, "ENOTDIR")) return missing;
31244
- throw error;
31245
- }
31246
31727
  const kind = assetKind(path);
31247
31728
  if (!isPlaceableKind(kind)) return {
31248
31729
  ok: false,
@@ -31254,10 +31735,165 @@ async function resolveAsset(projectDir, path) {
31254
31735
  kind
31255
31736
  };
31256
31737
  }
31738
+ /**
31739
+ * The absolute path of a file under the project's `assets/`, or null for a
31740
+ * path naming a dot, lock, or temp segment, or whose real path leaves the
31741
+ * folder or is not a file.
31742
+ */
31743
+ async function confinedAsset(projectDir, path) {
31744
+ const segments = path.split("/");
31745
+ if (segments.some((segment) => segment === "" || segment.startsWith(".") || isScratch(segment))) return null;
31746
+ const folder = join(projectDir, ASSETS_FOLDER);
31747
+ const file = join(folder, ...segments);
31748
+ try {
31749
+ const real = await realpath(folder);
31750
+ const target = await realpath(file);
31751
+ if (!target.startsWith(real + sep) || !(await stat(target)).isFile()) return null;
31752
+ } catch (error) {
31753
+ if (isCode(error, "ENOENT") || isCode(error, "ENOTDIR")) return null;
31754
+ throw error;
31755
+ }
31756
+ return file;
31757
+ }
31758
+ /**
31759
+ * A file a hand write may change, refusing `asset-not-found` for one
31760
+ * `confinedAsset` refuses, a license file, or a kit's file, which the Theme
31761
+ * tab owns.
31762
+ */
31763
+ async function writableAsset(projectDir, path) {
31764
+ const file = path.split("/")[0] === "kits" || path.endsWith(".license.json") ? null : await confinedAsset(projectDir, path);
31765
+ if (file === null) throw new FrameboardError("asset-not-found", `assets/${path} is not a file in the project's assets folder.`, { path });
31766
+ return file;
31767
+ }
31768
+ /** The license file beside an asset, when it has one. */
31769
+ function licenseOf(file) {
31770
+ const license = `${file}${LICENSE_FILE_SUFFIX}`;
31771
+ return existsSync(license) ? license : null;
31772
+ }
31773
+ /**
31774
+ * Deletes an asset and its license file, each taken out through the journal
31775
+ * where one is given, so an undo brings both back.
31776
+ */
31777
+ async function removeAsset(projectDir, path, { journal } = {}) {
31778
+ const file = await writableAsset(projectDir, path);
31779
+ for (const each of [file, licenseOf(file)]) {
31780
+ if (each === null) continue;
31781
+ if (journal) await journal.removed(each);
31782
+ else await rm(each);
31783
+ }
31784
+ return {
31785
+ path,
31786
+ frames: []
31787
+ };
31788
+ }
31257
31789
  function isScratch(name) {
31258
31790
  return name.endsWith(".lock") || name.endsWith(".tmp");
31259
31791
  }
31260
31792
  /**
31793
+ * Writes an upload's bytes under an asset's path and takes its license out, since it named the old bytes.
31794
+ * Refuses `asset-type-refused` for an upload a drop refuses or of another kind, which frames would change under.
31795
+ */
31796
+ async function replaceAsset(projectDir, path, upload, { journal } = {}) {
31797
+ const file = await writableAsset(projectDir, path);
31798
+ const refusal = uploadRefusal(upload) ?? (assetKind(upload.name) === assetKind(path) ? null : `${upload.name} is not the same kind of file as ${path}, so it cannot replace it.`);
31799
+ if (refusal !== null) throw new FrameboardError("asset-type-refused", refusal, { path });
31800
+ const temp = join(dirname(file), `${randomBytes(6).toString("hex")}${TEMP_SUFFIX}`);
31801
+ await writeFile(temp, upload.bytes, { flag: "wx" });
31802
+ try {
31803
+ const license = licenseOf(file);
31804
+ if (journal) {
31805
+ await journal.replaced(file, temp);
31806
+ if (license !== null) await journal.removed(license);
31807
+ } else {
31808
+ await rename(temp, file);
31809
+ if (license !== null) await rm(license);
31810
+ }
31811
+ } finally {
31812
+ await rm(temp, { force: true });
31813
+ }
31814
+ return {
31815
+ path,
31816
+ frames: []
31817
+ };
31818
+ }
31819
+ /**
31820
+ * Renames an asset and its license and repoints every linking frame, writing nothing until the gate passes,
31821
+ * and puts written frames back when a later write fails, so no project is left half renamed.
31822
+ * Refuses `invalid-name` off the name rule or for a new extension, and `name-taken` for a name held in any case.
31823
+ */
31824
+ async function renameAsset(root, project, path, name, { journal, gate = async () => {} } = {}) {
31825
+ const file = await writableAsset(join(root, project), path);
31826
+ const folder = dirname(file);
31827
+ const from = basename(file);
31828
+ const renamed = [...path.split("/").slice(0, -1), name].join("/");
31829
+ if (name === from) return {
31830
+ path,
31831
+ frames: []
31832
+ };
31833
+ if (!isValidName(name) || isScratch(name) || name.endsWith(".license.json") || extensionOf(name) !== extensionOf(from)) throw new FrameboardError("invalid-name", `${name} is not a name ${from} can take. Use letters, digits, dots, dashes, and underscores, keep the .${extensionOf(from)} ending, and stay within 64 characters.`, {
31834
+ path,
31835
+ name
31836
+ });
31837
+ const taken = (await readdir(folder)).find((entry) => entry !== from && entry !== `${from}.license.json` && (namesCollide(entry, name) || namesCollide(entry, `${name}.license.json`)));
31838
+ if (taken !== void 0) throw new FrameboardError("name-taken", `assets/${[...path.split("/").slice(0, -1), taken].join("/")} already exists. Pick another name.`, {
31839
+ path,
31840
+ name
31841
+ });
31842
+ const frames = await framesLinking(root, project, path);
31843
+ const ref = ({ page, name: frame }) => `${project}/${page}/${frame}`;
31844
+ await gate(frames.map(ref));
31845
+ const target = join(folder, name);
31846
+ const rewrites = frames.flatMap((frame) => {
31847
+ const source = readFrame$1(frame);
31848
+ if (!Buffer.from(source.html, "utf8").equals(readFileSync(source.path))) throw new FrameboardError("invalid-utf8", `${ref(frame)} is not UTF-8, so the rename cannot point its links at ${name}. Nothing was renamed.`, { frame: ref(frame) });
31849
+ const after = rewriteAssetLinks(source, file, target);
31850
+ return after === null ? [] : [{
31851
+ path: source.path,
31852
+ ref: ref(frame),
31853
+ before: source.html,
31854
+ after
31855
+ }];
31856
+ });
31857
+ const written = [];
31858
+ const license = licenseOf(file);
31859
+ try {
31860
+ for (const rewrite of rewrites) {
31861
+ await writeFrameWhole(rewrite.path, rewrite.before, rewrite.after);
31862
+ written.push(rewrite);
31863
+ }
31864
+ if (journal) {
31865
+ for (const each of written) journal.rewritten(each.path, each.ref, each.before, each.after);
31866
+ await journal.moved(file, target);
31867
+ if (license !== null) await journal.moved(license, `${target}${LICENSE_FILE_SUFFIX}`);
31868
+ } else {
31869
+ await rename(file, target);
31870
+ if (license !== null) await rename(license, `${target}${LICENSE_FILE_SUFFIX}`);
31871
+ }
31872
+ } catch (error) {
31873
+ for (const each of written.toReversed()) await writeFrameWhole(each.path, each.after, each.before).catch(() => {});
31874
+ throw error;
31875
+ }
31876
+ return {
31877
+ path: renamed,
31878
+ frames: written.map((each) => each.ref)
31879
+ };
31880
+ }
31881
+ /**
31882
+ * Writes a frame file whole through a temp file, refusing with
31883
+ * `stale-address` when the file no longer holds `before`, so an agent's
31884
+ * write that landed since is never overwritten.
31885
+ */
31886
+ async function writeFrameWhole(path, before, after) {
31887
+ const temp = join(dirname(path), `.${basename(path)}.${randomBytes(6).toString("hex")}${TEMP_SUFFIX}`);
31888
+ await writeFile(temp, after);
31889
+ try {
31890
+ if (await readFile(path, "utf8") !== before) throw new FrameboardError("stale-address", `An agent changed ${basename(path)} while the rename read it, so nothing was renamed. Try again.`, { path });
31891
+ await rename(temp, path);
31892
+ } finally {
31893
+ await rm(temp, { force: true });
31894
+ }
31895
+ }
31896
+ /**
31261
31897
  * Writes each upload under the first free name, hard-linking a temp file so a
31262
31898
  * name an agent took in between is never overwritten.
31263
31899
  */
@@ -31354,17 +31990,609 @@ function splitName(name) {
31354
31990
  extension
31355
31991
  };
31356
31992
  }
31993
+ /** The files in a project's `assets/` by path, empty when the folder is missing. */
31994
+ const assetListSchema = object$1({ files: array$1(object$1({
31995
+ /** Relative to the project's `assets/`, with `/` between segments. */
31996
+ path: string$1(),
31997
+ kind: _enum$1(ASSET_KINDS),
31998
+ /** Bytes. */
31999
+ size: number().int().nonnegative(),
32000
+ /** How many frames link the file, each counted once, absent where the server counts none. */
32001
+ frames: number().int().nonnegative().optional()
32002
+ })) });
32003
+ const assetAddResultSchema = object$1({
32004
+ /** Each landed file with the name it was dropped as and the name it took. */
32005
+ added: array$1(object$1({
32006
+ name: string$1(),
32007
+ path: string$1()
32008
+ })),
32009
+ /** Each file left out, by its dropped name, with the error code that says why. */
32010
+ refused: array$1(object$1({
32011
+ name: string$1(),
32012
+ code: string$1(),
32013
+ message: string$1()
32014
+ }))
32015
+ });
32016
+ /** A rename's body: the file's new name in its own folder, keeping its extension. */
32017
+ const assetRenameSchema = object$1({ name: string$1().min(1) });
32018
+ /** A hand asset write's answer: the file's path after it, and each frame ref it rewrote. */
32019
+ const assetWriteResultSchema = object$1({
32020
+ path: string$1(),
32021
+ frames: array$1(string$1())
32022
+ });
32023
+ const assetFramesSchema = object$1({
32024
+ path: string$1(),
32025
+ frames: array$1(string$1())
32026
+ });
32027
+ object$1({ transitions: array$1(object$1({
32028
+ name: string$1(),
32029
+ css: string$1()
32030
+ })) });
32031
+ // src/server/routes/envelope.ts
32032
+ /** The status each refusal of a structure or history write answers with. */
32033
+ const STATUS$5 = {
32034
+ usage: 400,
32035
+ "invalid-name": 400,
32036
+ "project-required": 400,
32037
+ "project-not-found": 404,
32038
+ "page-not-found": 404,
32039
+ "frame-not-found": 404,
32040
+ "section-not-found": 404,
32041
+ "asset-not-found": 404,
32042
+ "name-taken": 409,
32043
+ "stale-layout": 409,
32044
+ "stale-address": 409,
32045
+ "invalid-utf8": 422,
32046
+ "frame-claimed": 409,
32047
+ "asset-held": 409,
32048
+ "asset-type-refused": 400,
32049
+ "undo-overtaken": 409,
32050
+ "nothing-to-undo": 409,
32051
+ "tokens-exist": 409,
32052
+ "stale-tokens": 409,
32053
+ "invalid-edit": 409,
32054
+ "frame-locked": 423,
32055
+ "layout-invalid": 422,
32056
+ "project-file-invalid": 422,
32057
+ "fit-unbounded": 422,
32058
+ "fit-scroll": 422,
32059
+ "claims-invalid": 422,
32060
+ "lock-timeout": 503,
32061
+ "browser-not-found": 503
32062
+ };
32063
+ /**
32064
+ * Answers a refusal in the CLI's `{ ok, error }` envelope, for a route
32065
+ * module's `onError`. Anything else is a fault and goes on to Hono.
32066
+ */
32067
+ function answerRefusal(error, c) {
32068
+ if (!(error instanceof FrameboardError)) throw error;
32069
+ return c.json({
32070
+ ok: false,
32071
+ error: {
32072
+ code: error.code,
32073
+ message: error.message,
32074
+ details: error.details
32075
+ }
32076
+ }, STATUS$5[error.code] ?? 500);
32077
+ }
32078
+ /** The request's JSON body as the schema reads it, or `usage` naming what failed. */
32079
+ async function parseBody$1(request, schema) {
32080
+ const parsed = schema.safeParse(await request.json().catch(() => null));
32081
+ if (!parsed.success) throw new FrameboardError("usage", `The body ${parsed.error.message}`);
32082
+ return parsed.data;
32083
+ }
32084
+ // src/server/checks/tokens.ts
32085
+ /**
32086
+ * Where a project's token sheets sit, the address file read by plain
32087
+ * `JSON.parse`, since the write hook cannot afford its schema.
32088
+ */
32089
+ function tokenSheetPaths(root, project, tokens) {
32090
+ const own = join(root, project, TOKEN_FILE);
32091
+ return {
32092
+ board: boardSheetPath(root, tokens),
32093
+ project: existsSync(own) ? own : null
32094
+ };
32095
+ }
32096
+ /** The board's token sheet alone, resolved the way `tokenSheetPaths` resolves it. */
32097
+ function boardSheetPath(root, tokens = recordedTokens(root)) {
32098
+ const board = tokens ?? join(root, "tokens.css");
32099
+ return existsSync(board) ? board : null;
32100
+ }
32101
+ /** The `--tokens` path the board's running server recorded, or null. */
32102
+ function recordedTokens(root) {
32103
+ try {
32104
+ const parsed = JSON.parse(readFileSync(join(root, RUN_FOLDER, ADDRESS_FILE), "utf8"));
32105
+ const tokens = typeof parsed === "object" && parsed !== null && "tokens" in parsed ? parsed.tokens : void 0;
32106
+ return typeof tokens === "string" ? tokens : null;
32107
+ } catch {
32108
+ return null;
32109
+ }
32110
+ }
32111
+ /**
32112
+ * The kit a frame's layout entry names, null for none or a layout that does
32113
+ * not read, parsed plainly as the address file is.
32114
+ */
32115
+ function frameKit({ root, project, page, name }) {
32116
+ try {
32117
+ return kitOf(keyOf$1(keyOf$1(keyOf$1(JSON.parse(readFileSync(join(root, project, page, LAYOUT_FILE), "utf8")), "frames"), name), "kit"));
32118
+ } catch {
32119
+ return null;
32120
+ }
32121
+ }
32122
+ /** An object's own key, undefined for a value holding none. */
32123
+ function keyOf$1(value, key) {
32124
+ return typeof value === "object" && value !== null && Object.hasOwn(value, key) ? value[key] : void 0;
32125
+ }
32126
+ /**
32127
+ * The kit sheets a frame draws with, as paths under its project in cascade
32128
+ * order: a project-wide kit's where `assets/kit/` holds `kit.json`, then the
32129
+ * tokens and stylesheet of the kit the frame names, each that exists.
32130
+ */
32131
+ function kitSheetFiles(root, project, kit) {
32132
+ const wide = [ASSETS_FOLDER, "kit"];
32133
+ const named = kitOf(kit);
32134
+ return [...existsSync(join(root, project, ...wide, "kit.json")) ? [[...wide, KIT_SHEET]] : [], ...named ? [TOKEN_FILE, KIT_SHEET].map((file) => [
32135
+ ASSETS_FOLDER,
32136
+ PROJECT_KITS,
32137
+ named,
32138
+ file
32139
+ ]) : []].filter((file) => existsSync(join(root, project, ...file))).map((file) => file.join("/"));
32140
+ }
32141
+ /**
32142
+ * The sheets the frame route imports ahead of a frame, being the board's
32143
+ * tokens, the project's, then its kit sheets, which the cascade reads ahead
32144
+ * of the frame's own. `kit` is the kit the frame names, null for a plain one.
32145
+ */
32146
+ function tokenSheets(root, project, tokens, kit = null) {
32147
+ return readSheets(root, project, tokenSheetPaths(root, project, tokens), kit);
32148
+ }
32149
+ /** `tokenSheets` for a caller already holding the project's sheet paths. */
32150
+ function readSheets(root, project, paths, kit) {
32151
+ const kitSheets = kitSheetFiles(root, project, kit).map((file) => join(root, project, file));
32152
+ return [
32153
+ paths.board,
32154
+ paths.project,
32155
+ ...kitSheets
32156
+ ].filter((path) => path !== null).map((path) => ({
32157
+ css: readFileSync(path, "utf8"),
32158
+ origin: "token",
32159
+ path,
32160
+ offset: 0
32161
+ }));
32162
+ }
32163
+ // src/shared/board-urls.ts
32164
+ /** Where the server serves a frame's file, with each name encoded as its own segment. */
32165
+ function frameUrl(ref) {
32166
+ const [project = "", page = "", frame = ""] = ref.split("/");
32167
+ return `/frames/${encodeURIComponent(project)}/${encodeURIComponent(page)}/${encodeURIComponent(frame)}.html`;
32168
+ }
32169
+ /** The board route showing one page of a project. */
32170
+ function boardUrl(project, page) {
32171
+ return `/p/${encodeURIComponent(project)}/${encodeURIComponent(page)}`;
32172
+ }
32173
+ // src/shared/theme.ts
32174
+ const THEMES = ["light", "dark"];
32175
+ /** The query a frame is served with, which its injected script sets `data-theme` from. */
32176
+ const THEME_QUERY = "theme";
32177
+ /**
32178
+ * The attribute on every element the frame route injects. A reader counting
32179
+ * a live frame's elements skips the ones carrying it, so the live index
32180
+ * matches the file's.
32181
+ */
32182
+ const LOOK_MARKER = "data-frameboard";
32183
+ /**
32184
+ * The attribute on the injected style holding the SHA-256 hex of the bytes
32185
+ * the route served, so a live frame names the exact file an edit addresses.
32186
+ */
32187
+ const RENDERED_HASH = "data-hash";
32188
+ function isTheme$1(value) {
32189
+ return value === "light" || value === "dark";
32190
+ }
32191
+ /**
32192
+ * Shows a frame's root in `theme`, using nothing outside its own body, since
32193
+ * the frame route embeds its source.
32194
+ */
32195
+ function setFrameTheme(root, theme) {
32196
+ root.setAttribute("data-theme", theme);
32197
+ root.style.colorScheme = theme;
32198
+ root.classList.toggle("dark", theme === "dark");
32199
+ root.classList.toggle("light", theme === "light");
32200
+ }
32201
+ /**
32202
+ * Where a frame is served in one theme, with `version` naming the reload so
32203
+ * a changed file loads fresh, and `at` naming a version an agent's write
32204
+ * replaced by its content hash.
32205
+ */
32206
+ function frameThemeUrl(ref, theme, version, at) {
32207
+ const query = new URLSearchParams({ [THEME_QUERY]: theme });
32208
+ if (version !== void 0) query.set("v", String(version));
32209
+ if (at !== void 0) query.set("at", at);
32210
+ return `${frameUrl(ref)}?${query}`;
32211
+ }
32212
+ // src/server/look/inject.ts
32213
+ const BOM = [
32214
+ 239,
32215
+ 187,
32216
+ 191
32217
+ ];
32218
+ /**
32219
+ * Shows the frame's root in the theme the frame was served with, through the
32220
+ * same `setFrameTheme` the board calls on a theme change, then removes
32221
+ * itself, so the one injected element a live frame keeps is the stylesheet.
32222
+ */
32223
+ const THEME_SCRIPT = `(function(s,t){if(t==='light'||t==='dark')(${setFrameTheme.toString()})(document.documentElement,t);s.remove()})(document.currentScript,new URLSearchParams(location.search).get(${JSON.stringify(THEME_QUERY)}))`;
32224
+ /** Where the look route serves the frame bridge's script, under the running release. */
32225
+ const BRIDGE_URL = `/frameboard/bridge/v${version}/frame-bridge.js`;
32226
+ /**
32227
+ * The frame route's injected `head`, one stylesheet carrying `hash` as its one
32228
+ * other attribute, since another element would shift every live index. Given
32229
+ * no `bridge`, as a kit preview's policy allows none, it loads no bridge.
32230
+ */
32231
+ function frameHead(sheets, hash, bridge) {
32232
+ const imports = sheets.map((url) => `@import url(${JSON.stringify(url)});`);
32233
+ const script = bridge === void 0 ? "" : `<script ${LOOK_MARKER} src=${JSON.stringify(bridge)}><\/script>`;
32234
+ return `<style ${LOOK_MARKER} ${RENDERED_HASH}="${hash}">${imports.join("")}</style><script ${LOOK_MARKER}>${THEME_SCRIPT}<\/script>${script}`;
32235
+ }
32236
+ /**
32237
+ * Splices `head` where the browser starts its `head`, keeping every byte of
32238
+ * the file around it.
32239
+ */
32240
+ function injectHead(bytes, head) {
32241
+ const offset = headOffset(bytes);
32242
+ const inserted = new TextEncoder().encode(head);
32243
+ const out = new Uint8Array(bytes.length + inserted.length);
32244
+ out.set(bytes.subarray(0, offset));
32245
+ out.set(inserted, offset);
32246
+ out.set(bytes.subarray(offset), offset + inserted.length);
32247
+ return out;
32248
+ }
32249
+ /**
32250
+ * The splice offset, decoded as Latin-1 so parse5's offsets are byte offsets.
32251
+ */
32252
+ function headOffset(bytes) {
32253
+ const bom = BOM.every((byte, index) => bytes[index] === byte);
32254
+ const text = Buffer.from(bytes).toString("latin1");
32255
+ const document = parse$3(bom ? ` ${text.slice(3)}` : text, { sourceCodeLocationInfo: true });
32256
+ const html = document.childNodes.find(isElement);
32257
+ const stated = (html?.childNodes.find((node) => isElement(node) && node.tagName === "head"))?.sourceCodeLocation?.startTag ?? html?.sourceCodeLocation?.startTag;
32258
+ if (stated) return stated.endOffset;
32259
+ return document.childNodes.find((node) => node.nodeName === "#documentType")?.sourceCodeLocation?.endOffset ?? (bom ? BOM.length : 0);
32260
+ }
32261
+ function isElement(node) {
32262
+ return "tagName" in node;
32263
+ }
32264
+ // src/shared/faces.ts
32265
+ const FACES = [
32266
+ {
32267
+ family: "Geist",
32268
+ package: "@fontsource-variable/geist",
32269
+ packageFamily: "Geist Variable",
32270
+ folder: "geist",
32271
+ weights: {
32272
+ min: 100,
32273
+ max: 900
32274
+ },
32275
+ fallback: "sans-serif",
32276
+ startsLook: true
32277
+ },
32278
+ {
32279
+ family: "Geist Mono",
32280
+ package: "@fontsource-variable/geist-mono",
32281
+ packageFamily: "Geist Mono Variable",
32282
+ folder: "geist-mono",
32283
+ weights: {
32284
+ min: 100,
32285
+ max: 900
32286
+ },
32287
+ fallback: "monospace",
32288
+ startsLook: true
32289
+ },
32290
+ {
32291
+ family: "Inter",
32292
+ package: "@fontsource-variable/inter",
32293
+ packageFamily: "Inter Variable",
32294
+ folder: "inter",
32295
+ weights: {
32296
+ min: 100,
32297
+ max: 900
32298
+ },
32299
+ fallback: "sans-serif",
32300
+ startsLook: true
32301
+ },
32302
+ {
32303
+ family: "Source Serif 4",
32304
+ package: "@fontsource-variable/source-serif-4",
32305
+ packageFamily: "Source Serif 4 Variable",
32306
+ folder: "source-serif-4",
32307
+ weights: {
32308
+ min: 200,
32309
+ max: 900
32310
+ },
32311
+ fallback: "serif",
32312
+ startsLook: true
32313
+ },
32314
+ {
32315
+ family: "Caveat",
32316
+ package: "@fontsource-variable/caveat",
32317
+ packageFamily: "Caveat Variable",
32318
+ folder: "caveat",
32319
+ weights: {
32320
+ min: 400,
32321
+ max: 700
32322
+ },
32323
+ fallback: "cursive",
32324
+ startsLook: false
32325
+ }
32326
+ ];
32327
+ /** Where the server serves the faces folder. */
32328
+ const FACES_URL = "/frameboard/faces";
32329
+ /**
32330
+ * The sheet a frame imports to get one face, under the running release so
32331
+ * the server can answer it as cached for good.
32332
+ */
32333
+ function faceSheetUrl(face) {
32334
+ return `${FACES_URL}/v${version}/${face.folder}/index.css`;
32335
+ }
32336
+ /** The stack naming a face then its fallback, as `'Geist Mono', monospace`. */
32337
+ function faceStack(face) {
32338
+ return `${/\s/.test(face.family) ? `'${face.family}'` : face.family}, ${face.fallback}`;
32339
+ }
32340
+ // src/server/routes/frames.ts
32341
+ const NOTES_FILE$2 = "notes.json";
32342
+ /** Where the look route serves the board's token sheet, whichever file stands in for it. */
32343
+ const BOARD_SHEET_URL = "/frameboard/tokens.css";
32344
+ const CONTENT_TYPES$2 = {
32345
+ ".html": "text/html; charset=utf-8",
32346
+ ".css": "text/css; charset=utf-8",
32347
+ ".js": "text/javascript; charset=utf-8",
32348
+ ".mjs": "text/javascript; charset=utf-8",
32349
+ ".json": "application/json; charset=utf-8",
32350
+ ".txt": "text/plain; charset=utf-8",
32351
+ ".svg": "image/svg+xml",
32352
+ ".png": "image/png",
32353
+ ".jpg": "image/jpeg",
32354
+ ".jpeg": "image/jpeg",
32355
+ ".gif": "image/gif",
32356
+ ".webp": "image/webp",
32357
+ ".avif": "image/avif",
32358
+ ".ico": "image/x-icon",
32359
+ ".woff": "font/woff",
32360
+ ".woff2": "font/woff2",
32361
+ ".ttf": "font/ttf",
32362
+ ".otf": "font/otf",
32363
+ ".mp4": "video/mp4",
32364
+ ".webm": "video/webm",
32365
+ ".mov": "video/quicktime",
32366
+ ".m4v": "video/x-m4v",
32367
+ ".mp3": "audio/mpeg",
32368
+ ".wav": "audio/wav",
32369
+ ".ogg": "audio/ogg",
32370
+ ".m4a": "audio/mp4",
32371
+ ".glb": "model/gltf-binary",
32372
+ ".gltf": "model/gltf+json"
32373
+ };
32374
+ /**
32375
+ * Serves the board's frames so relative links resolve unrewritten, its own
32376
+ * handler since it must refuse records, dot-named, and escaping paths, all as
32377
+ * 404 so nothing tells a caller what exists.
32378
+ */
32379
+ function frameRoutes(root, look, version, base = "") {
32380
+ const app = new Hono();
32381
+ app.get("/frames/*", async (c) => {
32382
+ const parts = decodeSegments(new URL(c.req.url).pathname.slice(8).split("/"));
32383
+ const file = parts && await resolveFile(root, parts);
32384
+ if (!file) return c.notFound();
32385
+ const [project = "", page = "", name = ""] = parts;
32386
+ const isFrame = page !== "assets" && parts.length === 3 && extname(file).toLowerCase() === ".html";
32387
+ const contentType = CONTENT_TYPES$2[extname(file).toLowerCase()] ?? "application/octet-stream";
32388
+ const at = c.req.query("at");
32389
+ const rangeHeader = c.req.header("Range");
32390
+ if (!isFrame && at === void 0 && rangeHeader !== void 0) {
32391
+ const { size } = await stat(file);
32392
+ const range = parseRange(rangeHeader, size);
32393
+ if (range === "unsatisfiable") return c.body(null, 416, {
32394
+ "Content-Range": `bytes */${size}`,
32395
+ "Accept-Ranges": "bytes",
32396
+ "Cache-Control": "no-store"
32397
+ });
32398
+ if (range) {
32399
+ const headers = {
32400
+ "Content-Type": contentType,
32401
+ "Content-Length": String(range.end - range.start + 1),
32402
+ "Content-Range": `bytes ${range.start}-${range.end}/${size}`,
32403
+ "Accept-Ranges": "bytes",
32404
+ "Cache-Control": "no-store"
32405
+ };
32406
+ if (c.req.method === "HEAD") return c.body(null, 206, headers);
32407
+ const stream = Readable.toWeb(createReadStream(file, range));
32408
+ return c.body(stream, 206, headers);
32409
+ }
32410
+ }
32411
+ if (!isFrame && at === void 0) {
32412
+ const tag = weakTag(await stat(file, { bigint: true }));
32413
+ const revalidate = {
32414
+ ETag: tag,
32415
+ "Cache-Control": "no-cache"
32416
+ };
32417
+ if (matchesTag(c.req.header("If-None-Match"), tag)) return c.body(null, 304, revalidate);
32418
+ const headers = {
32419
+ "Content-Type": contentType,
32420
+ "Accept-Ranges": "bytes",
32421
+ ...revalidate
32422
+ };
32423
+ if (c.req.method === "HEAD") return c.body(null, 200, headers);
32424
+ return c.body(new Uint8Array(await readFile(file)), 200, headers);
32425
+ }
32426
+ let bytes;
32427
+ if (at === void 0) bytes = new Uint8Array(await readFile(file));
32428
+ else {
32429
+ const ref = `${project}/${page}/${name.slice(0, -5)}`;
32430
+ const held = isFrame ? version?.(ref, at) ?? null : null;
32431
+ if (held === null) return c.notFound();
32432
+ bytes = new TextEncoder().encode(held);
32433
+ }
32434
+ const kit = isFrame ? frameKit({
32435
+ root,
32436
+ project,
32437
+ page,
32438
+ name: name.slice(0, -5)
32439
+ }) : null;
32440
+ const body = injectHead(bytes, frameHead(sheetUrls(project, look.sheets(project), kitSheetFiles(root, project, kit)).map((url) => `${base}${url}`), contentHash(bytes), `${base}${BRIDGE_URL}`));
32441
+ return c.body(body, 200, {
32442
+ "Content-Type": contentType,
32443
+ "Cache-Control": "no-store"
32444
+ });
32445
+ });
32446
+ return app;
32447
+ }
32448
+ /**
32449
+ * A weak validator from a file's size and nanosecond mtime, so a check costs
32450
+ * one stat rather than a read of every byte. A same-size rewrite inside one
32451
+ * timestamp tick keeps its tag, which a coarse mount makes likelier.
32452
+ */
32453
+ function weakTag({ size, mtimeNs }) {
32454
+ return `W/"${size.toString(16)}-${mtimeNs.toString(16)}"`;
32455
+ }
32456
+ /** Whether an `If-None-Match` header names `tag`, compared weakly per RFC 9110. */
32457
+ function matchesTag(header, tag) {
32458
+ if (header === void 0) return false;
32459
+ if (header.trim() === "*") return true;
32460
+ const opaque = tag.replace(/^W\//, "");
32461
+ return header.split(",").some((listed) => listed.trim().replace(/^W\//, "") === opaque);
32462
+ }
32463
+ /**
32464
+ * The bytes a single range names, null for a header to ignore, which RFC 9110
32465
+ * allows for an unsupported range such as a multi-range.
32466
+ */
32467
+ function parseRange(header, size) {
32468
+ const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
32469
+ if (!match) return null;
32470
+ const [, first = "", last = ""] = match;
32471
+ if (first === "") {
32472
+ if (last === "") return null;
32473
+ const suffix = Number(last);
32474
+ if (suffix === 0) return "unsatisfiable";
32475
+ if (size === 0) return null;
32476
+ return {
32477
+ start: Math.max(0, size - suffix),
32478
+ end: size - 1
32479
+ };
32480
+ }
32481
+ const start = Number(first);
32482
+ const end = last === "" ? size - 1 : Number(last);
32483
+ if (last !== "" && end < start) return null;
32484
+ if (start >= size) return "unsatisfiable";
32485
+ return {
32486
+ start,
32487
+ end: Math.min(end, size - 1)
32488
+ };
32489
+ }
32490
+ /**
32491
+ * The sheets a frame imports, being every face, then the board's tokens, then
32492
+ * the project's, then its kit sheets, which read the tokens and still lose to
32493
+ * the frame's own sheets. `kitFiles` come as `kitSheetFiles` answers them.
32494
+ */
32495
+ function sheetUrls(project, sheets, kitFiles) {
32496
+ const folder = `/frames/${encodeURIComponent(project)}`;
32497
+ return [
32498
+ ...FACES.map(faceSheetUrl),
32499
+ ...sheets.board ? [BOARD_SHEET_URL] : [],
32500
+ ...sheets.project ? [`${folder}/${TOKEN_FILE}`] : [],
32501
+ ...kitFiles.map((file) => `${folder}/${file.split("/").map(encodeURIComponent).join("/")}`)
32502
+ ];
32503
+ }
32504
+ function decodeSegments(segments) {
32505
+ const decoded = [];
32506
+ for (const segment of segments) {
32507
+ let name;
32508
+ try {
32509
+ name = decodeURIComponent(segment);
32510
+ } catch {
32511
+ return null;
32512
+ }
32513
+ if (name === "" || name.startsWith(".") || /[/\\\0]/.test(name)) return null;
32514
+ decoded.push(name);
32515
+ }
32516
+ return decoded;
32517
+ }
32518
+ /** The realpath of the file a request names, or null when it is refused or missing. */
32519
+ async function resolveFile(root, [project, page, ...rest]) {
32520
+ if (!project || !page) return null;
32521
+ const projectSheet = rest.length === 0 && page === "tokens.css";
32522
+ if (rest.length === 0 && !projectSheet) return null;
32523
+ if (page !== "assets" && !projectSheet && (rest.length > 1 || isRecord$6(rest[0] ?? ""))) return null;
32524
+ try {
32525
+ const projectDir = await realpath(join(root, project));
32526
+ if (!projectDir.startsWith(root + sep)) return null;
32527
+ const file = await realpath(join(projectDir, page, ...rest));
32528
+ if (!file.startsWith(projectDir + sep)) return null;
32529
+ if (!servableInProject(relative(projectDir, file).split(sep))) return null;
32530
+ return (await stat(file)).isFile() ? file : null;
32531
+ } catch {
32532
+ return null;
32533
+ }
32534
+ }
32535
+ /**
32536
+ * Whether the route may serve a file, read off its real path, so a symlink to
32537
+ * a record or a dot-named path is refused.
32538
+ */
32539
+ function servableInProject(segments) {
32540
+ if (segments.some((segment) => segment.startsWith("."))) return false;
32541
+ const [first = "", name = ""] = segments;
32542
+ if (segments.length === 1) return first === TOKEN_FILE;
32543
+ return first === "assets" || !isRecord$6(name);
32544
+ }
32545
+ function isRecord$6(name) {
32546
+ return name === "layout.json" || name === NOTES_FILE$2;
32547
+ }
31357
32548
  // src/server/routes/assets.ts
31358
32549
  /** The most a drop may carry, multipart overhead included. */
31359
32550
  const ASSET_BODY_LIMIT = 67108864;
31360
32551
  /**
31361
32552
  * A project's `assets/` routes, the drop held in memory, so the body limit is
31362
- * its only bound.
32553
+ * its only bound. A rename, replace, or delete names its file after
32554
+ * `assets/` in the URL, each segment encoded, and records one undo step.
31363
32555
  */
31364
- function assetsRoutes(root, access, { limit = ASSET_BODY_LIMIT, usage } = {}) {
32556
+ function assetsRoutes(root, access, history, { limit = ASSET_BODY_LIMIT, usage } = {}) {
31365
32557
  const app = new Hono();
31366
32558
  const authorized = requireWriter(access);
31367
32559
  const path = "/api/projects/:project/assets";
32560
+ const file = `${path}/*`;
32561
+ const limited = bodyLimit({
32562
+ maxSize: limit,
32563
+ onError: (c) => c.json({
32564
+ ok: false,
32565
+ error: {
32566
+ code: "asset-too-large",
32567
+ message: `A drop may carry ${limit / 1024 / 1024} MiB at most. Nothing was written.`
32568
+ }
32569
+ }, 413)
32570
+ });
32571
+ /** The project folder and the file's path under `assets/`, refusing a missing project or a path segment that leaves the folder. */
32572
+ const target = (url, project) => {
32573
+ const projectDir = projectFolder(root, project);
32574
+ if (projectDir === null) throw new FrameboardError("project-not-found", `No project named ${project} in this board.`);
32575
+ const prefix = `/api/projects/${encodeURIComponent(project)}/assets/`;
32576
+ const raw = new URL(url).pathname;
32577
+ const segments = raw.startsWith(prefix) ? decodeSegments(raw.slice(prefix.length).split("/")) : null;
32578
+ if (segments === null || segments.length === 0) throw new FrameboardError("asset-not-found", "Name a file in the project's assets folder.");
32579
+ return {
32580
+ projectDir,
32581
+ asset: segments.join("/")
32582
+ };
32583
+ };
32584
+ /** Runs one write with a fresh journal and records it as a step that moves no page. */
32585
+ const recorded = async (write) => {
32586
+ const journal = history.journal();
32587
+ const result = await write(journal);
32588
+ history.record({
32589
+ id: journal.id,
32590
+ changes: journal.changes,
32591
+ page: null,
32592
+ frames: result.frames
32593
+ });
32594
+ return result;
32595
+ };
31368
32596
  app.get(path, async (c) => {
31369
32597
  const projectDir = projectFolder(root, c.req.param("project"));
31370
32598
  if (projectDir === null) return c.json(notFound$1(c.req.param("project")), 404);
@@ -31390,16 +32618,7 @@ function assetsRoutes(root, access, { limit = ASSET_BODY_LIMIT, usage } = {}) {
31390
32618
  data
31391
32619
  });
31392
32620
  });
31393
- app.post(path, authorized, bodyLimit({
31394
- maxSize: limit,
31395
- onError: (c) => c.json({
31396
- ok: false,
31397
- error: {
31398
- code: "asset-too-large",
31399
- message: `A drop may carry ${limit / 1024 / 1024} MiB at most. Nothing was written.`
31400
- }
31401
- }, 413)
31402
- }), async (c) => {
32621
+ app.post(path, authorized, limited, async (c) => {
31403
32622
  const projectDir = projectFolder(root, c.req.param("project"));
31404
32623
  if (projectDir === null) return c.json(notFound$1(c.req.param("project")), 404);
31405
32624
  const sent = [(await c.req.parseBody({ all: true }).catch(() => ({}))).files].flat().filter((v) => v instanceof File);
@@ -31419,8 +32638,66 @@ function assetsRoutes(root, access, { limit = ASSET_BODY_LIMIT, usage } = {}) {
31419
32638
  data: await addAssets(projectDir, uploads)
31420
32639
  });
31421
32640
  });
32641
+ app.get(file, async (c) => {
32642
+ const project = c.req.param("project");
32643
+ const { asset } = target(c.req.url, project);
32644
+ const data = {
32645
+ path: asset,
32646
+ frames: (await framesLinking(root, project, asset)).map(({ page, name }) => `${project}/${page}/${name}`)
32647
+ };
32648
+ return c.json({
32649
+ ok: true,
32650
+ data
32651
+ });
32652
+ });
32653
+ app.delete(file, authorized, async (c) => {
32654
+ const { projectDir, asset } = target(c.req.url, c.req.param("project"));
32655
+ const data = await recorded((journal) => removeAsset(projectDir, asset, { journal }));
32656
+ return c.json({
32657
+ ok: true,
32658
+ data
32659
+ });
32660
+ });
32661
+ app.patch(file, authorized, async (c) => {
32662
+ const project = c.req.param("project");
32663
+ const { asset } = target(c.req.url, project);
32664
+ const { name } = await parseBody$1(c.req.raw, assetRenameSchema);
32665
+ const data = await recorded((journal) => renameAsset(root, project, asset, name, {
32666
+ journal,
32667
+ gate: (refs) => refuseHeld(root, asset, refs)
32668
+ }));
32669
+ return c.json({
32670
+ ok: true,
32671
+ data
32672
+ });
32673
+ });
32674
+ app.put(file, authorized, limited, async (c) => {
32675
+ const { projectDir, asset } = target(c.req.url, c.req.param("project"));
32676
+ const sent = (await c.req.parseBody().catch(() => ({}))).file;
32677
+ if (!(sent instanceof File)) throw new FrameboardError("usage", "Send multipart/form-data with one file in the \"file\" field.");
32678
+ const upload = {
32679
+ name: sent.name,
32680
+ bytes: new Uint8Array(await sent.arrayBuffer())
32681
+ };
32682
+ const data = await recorded((journal) => replaceAsset(projectDir, asset, upload, { journal }));
32683
+ return c.json({
32684
+ ok: true,
32685
+ data
32686
+ });
32687
+ });
32688
+ app.onError(answerRefusal);
31422
32689
  return app;
31423
32690
  }
32691
+ /** Refuses `asset-held` naming the session, when another session holds a frame the rename would rewrite. */
32692
+ async function refuseHeld(root, asset, refs) {
32693
+ try {
32694
+ await refuseClaimed(root, refs, /* @__PURE__ */ new Date());
32695
+ } catch (error) {
32696
+ if (!(error instanceof FrameboardError) || error.code !== "frame-claimed") throw error;
32697
+ const { tag, frame } = error.details;
32698
+ throw new FrameboardError("asset-held", `${String(tag)} is editing ${String(frame)}, which links assets/${asset}, so it was not renamed. Try again once it finishes.`, error.details);
32699
+ }
32700
+ }
31424
32701
  function projectFolder(root, project) {
31425
32702
  const folder = join(root, project);
31426
32703
  return isValidName(project) && existsSync(folder) ? folder : null;
@@ -31471,54 +32748,6 @@ function checkRoutes(access, checks) {
31471
32748
  });
31472
32749
  return app;
31473
32750
  }
31474
- // src/server/routes/envelope.ts
31475
- /** The status each refusal of a structure or history write answers with. */
31476
- const STATUS$5 = {
31477
- usage: 400,
31478
- "invalid-name": 400,
31479
- "project-required": 400,
31480
- "project-not-found": 404,
31481
- "page-not-found": 404,
31482
- "frame-not-found": 404,
31483
- "section-not-found": 404,
31484
- "name-taken": 409,
31485
- "stale-layout": 409,
31486
- "frame-claimed": 409,
31487
- "undo-overtaken": 409,
31488
- "nothing-to-undo": 409,
31489
- "tokens-exist": 409,
31490
- "stale-tokens": 409,
31491
- "invalid-edit": 409,
31492
- "frame-locked": 423,
31493
- "layout-invalid": 422,
31494
- "project-file-invalid": 422,
31495
- "fit-unbounded": 422,
31496
- "fit-scroll": 422,
31497
- "claims-invalid": 422,
31498
- "lock-timeout": 503,
31499
- "browser-not-found": 503
31500
- };
31501
- /**
31502
- * Answers a refusal in the CLI's `{ ok, error }` envelope, for a route
31503
- * module's `onError`. Anything else is a fault and goes on to Hono.
31504
- */
31505
- function answerRefusal(error, c) {
31506
- if (!(error instanceof FrameboardError)) throw error;
31507
- return c.json({
31508
- ok: false,
31509
- error: {
31510
- code: error.code,
31511
- message: error.message,
31512
- details: error.details
31513
- }
31514
- }, STATUS$5[error.code] ?? 500);
31515
- }
31516
- /** The request's JSON body as the schema reads it, or `usage` naming what failed. */
31517
- async function parseBody$1(request, schema) {
31518
- const parsed = schema.safeParse(await request.json().catch(() => null));
31519
- if (!parsed.success) throw new FrameboardError("usage", `The body ${parsed.error.message}`);
31520
- return parsed.data;
31521
- }
31522
32751
  // src/server/routes/claims.ts
31523
32752
  const ReleaseBody = object$1({ frame: string$1().min(1) });
31524
32753
  /**
@@ -31685,85 +32914,6 @@ function clipboardRoutes(root, access, render, clipboard) {
31685
32914
  });
31686
32915
  return app;
31687
32916
  }
31688
- // src/server/checks/tokens.ts
31689
- /**
31690
- * Where a project's token sheets sit, the address file read by plain
31691
- * `JSON.parse`, since the write hook cannot afford its schema.
31692
- */
31693
- function tokenSheetPaths(root, project, tokens) {
31694
- const own = join(root, project, TOKEN_FILE);
31695
- return {
31696
- board: boardSheetPath(root, tokens),
31697
- project: existsSync(own) ? own : null
31698
- };
31699
- }
31700
- /** The board's token sheet alone, resolved the way `tokenSheetPaths` resolves it. */
31701
- function boardSheetPath(root, tokens = recordedTokens(root)) {
31702
- const board = tokens ?? join(root, "tokens.css");
31703
- return existsSync(board) ? board : null;
31704
- }
31705
- /** The `--tokens` path the board's running server recorded, or null. */
31706
- function recordedTokens(root) {
31707
- try {
31708
- const parsed = JSON.parse(readFileSync(join(root, RUN_FOLDER, ADDRESS_FILE), "utf8"));
31709
- const tokens = typeof parsed === "object" && parsed !== null && "tokens" in parsed ? parsed.tokens : void 0;
31710
- return typeof tokens === "string" ? tokens : null;
31711
- } catch {
31712
- return null;
31713
- }
31714
- }
31715
- /**
31716
- * The kit a frame's layout entry names, null for none or a layout that does
31717
- * not read, parsed plainly as the address file is.
31718
- */
31719
- function frameKit({ root, project, page, name }) {
31720
- try {
31721
- return kitOf(keyOf$1(keyOf$1(keyOf$1(JSON.parse(readFileSync(join(root, project, page, LAYOUT_FILE), "utf8")), "frames"), name), "kit"));
31722
- } catch {
31723
- return null;
31724
- }
31725
- }
31726
- /** An object's own key, undefined for a value holding none. */
31727
- function keyOf$1(value, key) {
31728
- return typeof value === "object" && value !== null && Object.hasOwn(value, key) ? value[key] : void 0;
31729
- }
31730
- /**
31731
- * The kit sheets a frame draws with, as paths under its project in cascade
31732
- * order: a project-wide kit's where `assets/kit/` holds `kit.json`, then the
31733
- * tokens and stylesheet of the kit the frame names, each that exists.
31734
- */
31735
- function kitSheetFiles(root, project, kit) {
31736
- const wide = [ASSETS_FOLDER, "kit"];
31737
- const named = kitOf(kit);
31738
- return [...existsSync(join(root, project, ...wide, "kit.json")) ? [[...wide, KIT_SHEET]] : [], ...named ? [TOKEN_FILE, KIT_SHEET].map((file) => [
31739
- ASSETS_FOLDER,
31740
- PROJECT_KITS,
31741
- named,
31742
- file
31743
- ]) : []].filter((file) => existsSync(join(root, project, ...file))).map((file) => file.join("/"));
31744
- }
31745
- /**
31746
- * The sheets the frame route imports ahead of a frame, being the board's
31747
- * tokens, the project's, then its kit sheets, which the cascade reads ahead
31748
- * of the frame's own. `kit` is the kit the frame names, null for a plain one.
31749
- */
31750
- function tokenSheets(root, project, tokens, kit = null) {
31751
- return readSheets(root, project, tokenSheetPaths(root, project, tokens), kit);
31752
- }
31753
- /** `tokenSheets` for a caller already holding the project's sheet paths. */
31754
- function readSheets(root, project, paths, kit) {
31755
- const kitSheets = kitSheetFiles(root, project, kit).map((file) => join(root, project, file));
31756
- return [
31757
- paths.board,
31758
- paths.project,
31759
- ...kitSheets
31760
- ].filter((path) => path !== null).map((path) => ({
31761
- css: readFileSync(path, "utf8"),
31762
- origin: "token",
31763
- path,
31764
- offset: 0
31765
- }));
31766
- }
31767
32917
  // src/server/edit/start-tag.ts
31768
32918
  function isSpace(char) {
31769
32919
  return char === " " || char === " " || char === "\n" || char === "\f" || char === "\r";
@@ -37956,82 +39106,6 @@ function attribute$1(element, name) {
37956
39106
  const VIEWER_TAG = "model-viewer";
37957
39107
  /** The viewer's script as a project's `assets/` holds it, copied in with the first model placed. */
37958
39108
  const VIEWER_FILE = "model-viewer.min.js";
37959
- // src/shared/faces.ts
37960
- const FACES = [
37961
- {
37962
- family: "Geist",
37963
- package: "@fontsource-variable/geist",
37964
- packageFamily: "Geist Variable",
37965
- folder: "geist",
37966
- weights: {
37967
- min: 100,
37968
- max: 900
37969
- },
37970
- fallback: "sans-serif",
37971
- startsLook: true
37972
- },
37973
- {
37974
- family: "Geist Mono",
37975
- package: "@fontsource-variable/geist-mono",
37976
- packageFamily: "Geist Mono Variable",
37977
- folder: "geist-mono",
37978
- weights: {
37979
- min: 100,
37980
- max: 900
37981
- },
37982
- fallback: "monospace",
37983
- startsLook: true
37984
- },
37985
- {
37986
- family: "Inter",
37987
- package: "@fontsource-variable/inter",
37988
- packageFamily: "Inter Variable",
37989
- folder: "inter",
37990
- weights: {
37991
- min: 100,
37992
- max: 900
37993
- },
37994
- fallback: "sans-serif",
37995
- startsLook: true
37996
- },
37997
- {
37998
- family: "Source Serif 4",
37999
- package: "@fontsource-variable/source-serif-4",
38000
- packageFamily: "Source Serif 4 Variable",
38001
- folder: "source-serif-4",
38002
- weights: {
38003
- min: 200,
38004
- max: 900
38005
- },
38006
- fallback: "serif",
38007
- startsLook: true
38008
- },
38009
- {
38010
- family: "Caveat",
38011
- package: "@fontsource-variable/caveat",
38012
- packageFamily: "Caveat Variable",
38013
- folder: "caveat",
38014
- weights: {
38015
- min: 400,
38016
- max: 700
38017
- },
38018
- fallback: "cursive",
38019
- startsLook: false
38020
- }
38021
- ];
38022
- /** Where the server serves the faces folder. */
38023
- const FACES_URL = "/frameboard/faces";
38024
- /**
38025
- * The sheet a frame imports to get one face, under the running release so
38026
- * the server can answer it as cached for good.
38027
- */
38028
- function faceSheetUrl(face) {
38029
- return `${FACES_URL}/v${version}/${face.folder}/index.css`;
38030
- }
38031
- /** The stack naming a face then its fallback, as `'Geist Mono', monospace`. */
38032
- function faceStack(face) {
38033
- return `${/\s/.test(face.family) ? `'${face.family}'` : face.family}, ${face.fallback}`;
38034
- }
38035
39109
  // src/shared/starter-tokens.ts
38036
39110
  /**
38037
39111
  * The looks a new project can start from, each accent paired by hand with a
@@ -40246,6 +41320,8 @@ async function reads(change, side) {
40246
41320
  return await exists(present) && !await exists(absent);
40247
41321
  }
40248
41322
  case "path": return change.present === side ? await exists(change.path) && await hashPath(change.path) === change.hash : !await exists(change.path) && await exists(change.slot);
41323
+ case "replaced": return await exists(change.path) && await exists(change.slot) && await hashPath(change.path) === change.hashes[side];
41324
+ case "rewritten": return await exists(change.path) && await readText(change.path) === change[side];
40249
41325
  case "element": return await exists(change.path) && holdsSpan(await readFile(change.path, "utf8"), change.span, side);
40250
41326
  case "inserted": return await exists(change.path) && holdsInserted(await readFile(change.path, "utf8"), change.span, side === change.present ? "after" : "before");
40251
41327
  case "deleted": return await exists(change.path) && chainDeleted(await readFile(change.path, "utf8"), change, OTHER[side]) !== void 0;
@@ -40337,6 +41413,13 @@ async function restore(change, side) {
40337
41413
  if (change.present === side) await rename(change.slot, change.path);
40338
41414
  else await takeOut(change.path, change.slot);
40339
41415
  return;
41416
+ case "replaced":
41417
+ await swapWithSlot(change.path, change.slot);
41418
+ return;
41419
+ case "rewritten": return rewriteFrame(change, (source) => source === change[OTHER[side]] ? {
41420
+ html: change[side],
41421
+ keep: () => {}
41422
+ } : void 0);
40340
41423
  case "element": return rewriteFrame(change, (source) => {
40341
41424
  const swapped = swapSpan(source, change.span, OTHER[side]);
40342
41425
  return swapped && {
@@ -40376,6 +41459,13 @@ async function restore(change, side) {
40376
41459
  case "token": return rewriteToken(change, side);
40377
41460
  }
40378
41461
  }
41462
+ /** Trades the file's bytes for the ones its slot holds, keeping the others in the slot. */
41463
+ async function swapWithSlot(path, slot) {
41464
+ const aside = `${slot}.swap`;
41465
+ await rename(path, aside);
41466
+ await rename(slot, path);
41467
+ await rename(aside, slot);
41468
+ }
40379
41469
  /**
40380
41470
  * The frame with a delete's chain restored or taken out again, undefined when
40381
41471
  * any one's bytes or gap no longer read.
@@ -40515,6 +41605,16 @@ var StepJournal = class {
40515
41605
  span
40516
41606
  });
40517
41607
  }
41608
+ /** A frame file a hand write rewrote whole on each side, which this journal does not write. */
41609
+ rewritten(path, ref, before, after) {
41610
+ this.changes.push({
41611
+ kind: "rewritten",
41612
+ path,
41613
+ ref,
41614
+ before,
41615
+ after
41616
+ });
41617
+ }
40518
41618
  /** The element a placement tool wrote into a frame file, which this journal does not write. */
40519
41619
  inserted(path, ref, span) {
40520
41620
  this.changes.push({
@@ -40572,6 +41672,23 @@ var StepJournal = class {
40572
41672
  slot: this.#slot()
40573
41673
  });
40574
41674
  }
41675
+ /** Puts the file at `from` in place of `path`, keeping the bytes it replaced in a trash slot. */
41676
+ async replaced(path, from) {
41677
+ const before = await hashPath(path);
41678
+ const after = await hashPath(from);
41679
+ const slot = this.#slot();
41680
+ await takeOut(path, slot);
41681
+ await rename(from, path);
41682
+ this.changes.push({
41683
+ kind: "replaced",
41684
+ path,
41685
+ slot,
41686
+ hashes: {
41687
+ before,
41688
+ after
41689
+ }
41690
+ });
41691
+ }
40575
41692
  async removed(path) {
40576
41693
  const hash = await hashPath(path);
40577
41694
  const slot = this.#slot();
@@ -40837,7 +41954,7 @@ function flatten(text) {
40837
41954
  return text.replace(/\s+/g, " ").replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim();
40838
41955
  }
40839
41956
  // src/server/notes/store.ts
40840
- const NOTES_FILE$2 = "notes.json";
41957
+ const NOTES_FILE$1 = "notes.json";
40841
41958
  const notesSpec = {
40842
41959
  schema: notesFileSchema,
40843
41960
  invalidCode: "notes-invalid",
@@ -40851,7 +41968,7 @@ function newNoteId() {
40851
41968
  return `n_${randomBytes(4).toString("hex")}`;
40852
41969
  }
40853
41970
  function notesPath(root, project, page) {
40854
- return join(root, project, page, NOTES_FILE$2);
41971
+ return join(root, project, page, NOTES_FILE$1);
40855
41972
  }
40856
41973
  function readNotes(path) {
40857
41974
  return readRecord(path, notesSpec);
@@ -42331,315 +43448,6 @@ async function savedNames(kits) {
42331
43448
  return [];
42332
43449
  }
42333
43450
  }
42334
- // src/shared/board-urls.ts
42335
- /** Where the server serves a frame's file, with each name encoded as its own segment. */
42336
- function frameUrl(ref) {
42337
- const [project = "", page = "", frame = ""] = ref.split("/");
42338
- return `/frames/${encodeURIComponent(project)}/${encodeURIComponent(page)}/${encodeURIComponent(frame)}.html`;
42339
- }
42340
- /** The board route showing one page of a project. */
42341
- function boardUrl(project, page) {
42342
- return `/p/${encodeURIComponent(project)}/${encodeURIComponent(page)}`;
42343
- }
42344
- // src/shared/theme.ts
42345
- const THEMES = ["light", "dark"];
42346
- /** The query a frame is served with, which its injected script sets `data-theme` from. */
42347
- const THEME_QUERY = "theme";
42348
- /**
42349
- * The attribute on every element the frame route injects. A reader counting
42350
- * a live frame's elements skips the ones carrying it, so the live index
42351
- * matches the file's.
42352
- */
42353
- const LOOK_MARKER = "data-frameboard";
42354
- /**
42355
- * The attribute on the injected style holding the SHA-256 hex of the bytes
42356
- * the route served, so a live frame names the exact file an edit addresses.
42357
- */
42358
- const RENDERED_HASH = "data-hash";
42359
- function isTheme$1(value) {
42360
- return value === "light" || value === "dark";
42361
- }
42362
- /**
42363
- * Shows a frame's root in `theme`, using nothing outside its own body, since
42364
- * the frame route embeds its source.
42365
- */
42366
- function setFrameTheme(root, theme) {
42367
- root.setAttribute("data-theme", theme);
42368
- root.style.colorScheme = theme;
42369
- root.classList.toggle("dark", theme === "dark");
42370
- root.classList.toggle("light", theme === "light");
42371
- }
42372
- /**
42373
- * Where a frame is served in one theme, with `version` naming the reload so
42374
- * a changed file loads fresh, and `at` naming a version an agent's write
42375
- * replaced by its content hash.
42376
- */
42377
- function frameThemeUrl(ref, theme, version, at) {
42378
- const query = new URLSearchParams({ [THEME_QUERY]: theme });
42379
- if (version !== void 0) query.set("v", String(version));
42380
- if (at !== void 0) query.set("at", at);
42381
- return `${frameUrl(ref)}?${query}`;
42382
- }
42383
- // src/server/look/inject.ts
42384
- const BOM = [
42385
- 239,
42386
- 187,
42387
- 191
42388
- ];
42389
- /**
42390
- * Shows the frame's root in the theme the frame was served with, through the
42391
- * same `setFrameTheme` the board calls on a theme change, then removes
42392
- * itself, so the one injected element a live frame keeps is the stylesheet.
42393
- */
42394
- const THEME_SCRIPT = `(function(s,t){if(t==='light'||t==='dark')(${setFrameTheme.toString()})(document.documentElement,t);s.remove()})(document.currentScript,new URLSearchParams(location.search).get(${JSON.stringify(THEME_QUERY)}))`;
42395
- /** Where the look route serves the frame bridge's script, under the running release. */
42396
- const BRIDGE_URL = `/frameboard/bridge/v${version}/frame-bridge.js`;
42397
- /**
42398
- * The frame route's injected `head`, one stylesheet carrying `hash` as its one
42399
- * other attribute, since another element would shift every live index. Given
42400
- * no `bridge`, as a kit preview's policy allows none, it loads no bridge.
42401
- */
42402
- function frameHead(sheets, hash, bridge) {
42403
- const imports = sheets.map((url) => `@import url(${JSON.stringify(url)});`);
42404
- const script = bridge === void 0 ? "" : `<script ${LOOK_MARKER} src=${JSON.stringify(bridge)}><\/script>`;
42405
- return `<style ${LOOK_MARKER} ${RENDERED_HASH}="${hash}">${imports.join("")}</style><script ${LOOK_MARKER}>${THEME_SCRIPT}<\/script>${script}`;
42406
- }
42407
- /**
42408
- * Splices `head` where the browser starts its `head`, keeping every byte of
42409
- * the file around it.
42410
- */
42411
- function injectHead(bytes, head) {
42412
- const offset = headOffset(bytes);
42413
- const inserted = new TextEncoder().encode(head);
42414
- const out = new Uint8Array(bytes.length + inserted.length);
42415
- out.set(bytes.subarray(0, offset));
42416
- out.set(inserted, offset);
42417
- out.set(bytes.subarray(offset), offset + inserted.length);
42418
- return out;
42419
- }
42420
- /**
42421
- * The splice offset, decoded as Latin-1 so parse5's offsets are byte offsets.
42422
- */
42423
- function headOffset(bytes) {
42424
- const bom = BOM.every((byte, index) => bytes[index] === byte);
42425
- const text = Buffer.from(bytes).toString("latin1");
42426
- const document = parse$3(bom ? ` ${text.slice(3)}` : text, { sourceCodeLocationInfo: true });
42427
- const html = document.childNodes.find(isElement);
42428
- const stated = (html?.childNodes.find((node) => isElement(node) && node.tagName === "head"))?.sourceCodeLocation?.startTag ?? html?.sourceCodeLocation?.startTag;
42429
- if (stated) return stated.endOffset;
42430
- return document.childNodes.find((node) => node.nodeName === "#documentType")?.sourceCodeLocation?.endOffset ?? (bom ? BOM.length : 0);
42431
- }
42432
- function isElement(node) {
42433
- return "tagName" in node;
42434
- }
42435
- // src/server/routes/frames.ts
42436
- const NOTES_FILE$1 = "notes.json";
42437
- /** Where the look route serves the board's token sheet, whichever file stands in for it. */
42438
- const BOARD_SHEET_URL = "/frameboard/tokens.css";
42439
- const CONTENT_TYPES$2 = {
42440
- ".html": "text/html; charset=utf-8",
42441
- ".css": "text/css; charset=utf-8",
42442
- ".js": "text/javascript; charset=utf-8",
42443
- ".mjs": "text/javascript; charset=utf-8",
42444
- ".json": "application/json; charset=utf-8",
42445
- ".txt": "text/plain; charset=utf-8",
42446
- ".svg": "image/svg+xml",
42447
- ".png": "image/png",
42448
- ".jpg": "image/jpeg",
42449
- ".jpeg": "image/jpeg",
42450
- ".gif": "image/gif",
42451
- ".webp": "image/webp",
42452
- ".avif": "image/avif",
42453
- ".ico": "image/x-icon",
42454
- ".woff": "font/woff",
42455
- ".woff2": "font/woff2",
42456
- ".ttf": "font/ttf",
42457
- ".otf": "font/otf",
42458
- ".mp4": "video/mp4",
42459
- ".webm": "video/webm",
42460
- ".mov": "video/quicktime",
42461
- ".m4v": "video/x-m4v",
42462
- ".mp3": "audio/mpeg",
42463
- ".wav": "audio/wav",
42464
- ".ogg": "audio/ogg",
42465
- ".m4a": "audio/mp4",
42466
- ".glb": "model/gltf-binary",
42467
- ".gltf": "model/gltf+json"
42468
- };
42469
- /**
42470
- * Serves the board's frames so relative links resolve unrewritten, its own
42471
- * handler since it must refuse records, dot-named, and escaping paths, all as
42472
- * 404 so nothing tells a caller what exists.
42473
- */
42474
- function frameRoutes(root, look, version, base = "") {
42475
- const app = new Hono();
42476
- app.get("/frames/*", async (c) => {
42477
- const parts = decodeSegments(new URL(c.req.url).pathname.slice(8).split("/"));
42478
- const file = parts && await resolveFile(root, parts);
42479
- if (!file) return c.notFound();
42480
- const [project = "", page = "", name = ""] = parts;
42481
- const isFrame = page !== "assets" && parts.length === 3 && extname(file).toLowerCase() === ".html";
42482
- const contentType = CONTENT_TYPES$2[extname(file).toLowerCase()] ?? "application/octet-stream";
42483
- const at = c.req.query("at");
42484
- const rangeHeader = c.req.header("Range");
42485
- if (!isFrame && at === void 0 && rangeHeader !== void 0) {
42486
- const { size } = await stat(file);
42487
- const range = parseRange(rangeHeader, size);
42488
- if (range === "unsatisfiable") return c.body(null, 416, {
42489
- "Content-Range": `bytes */${size}`,
42490
- "Accept-Ranges": "bytes",
42491
- "Cache-Control": "no-store"
42492
- });
42493
- if (range) {
42494
- const headers = {
42495
- "Content-Type": contentType,
42496
- "Content-Length": String(range.end - range.start + 1),
42497
- "Content-Range": `bytes ${range.start}-${range.end}/${size}`,
42498
- "Accept-Ranges": "bytes",
42499
- "Cache-Control": "no-store"
42500
- };
42501
- if (c.req.method === "HEAD") return c.body(null, 206, headers);
42502
- const stream = Readable.toWeb(createReadStream(file, range));
42503
- return c.body(stream, 206, headers);
42504
- }
42505
- }
42506
- if (!isFrame && at === void 0) {
42507
- const tag = weakTag(await stat(file, { bigint: true }));
42508
- const revalidate = {
42509
- ETag: tag,
42510
- "Cache-Control": "no-cache"
42511
- };
42512
- if (matchesTag(c.req.header("If-None-Match"), tag)) return c.body(null, 304, revalidate);
42513
- const headers = {
42514
- "Content-Type": contentType,
42515
- "Accept-Ranges": "bytes",
42516
- ...revalidate
42517
- };
42518
- if (c.req.method === "HEAD") return c.body(null, 200, headers);
42519
- return c.body(new Uint8Array(await readFile(file)), 200, headers);
42520
- }
42521
- let bytes;
42522
- if (at === void 0) bytes = new Uint8Array(await readFile(file));
42523
- else {
42524
- const ref = `${project}/${page}/${name.slice(0, -5)}`;
42525
- const held = isFrame ? version?.(ref, at) ?? null : null;
42526
- if (held === null) return c.notFound();
42527
- bytes = new TextEncoder().encode(held);
42528
- }
42529
- const kit = isFrame ? frameKit({
42530
- root,
42531
- project,
42532
- page,
42533
- name: name.slice(0, -5)
42534
- }) : null;
42535
- const body = injectHead(bytes, frameHead(sheetUrls(project, look.sheets(project), kitSheetFiles(root, project, kit)).map((url) => `${base}${url}`), contentHash(bytes), `${base}${BRIDGE_URL}`));
42536
- return c.body(body, 200, {
42537
- "Content-Type": contentType,
42538
- "Cache-Control": "no-store"
42539
- });
42540
- });
42541
- return app;
42542
- }
42543
- /**
42544
- * A weak validator from a file's size and nanosecond mtime, so a check costs
42545
- * one stat rather than a read of every byte. A same-size rewrite inside one
42546
- * timestamp tick keeps its tag, which a coarse mount makes likelier.
42547
- */
42548
- function weakTag({ size, mtimeNs }) {
42549
- return `W/"${size.toString(16)}-${mtimeNs.toString(16)}"`;
42550
- }
42551
- /** Whether an `If-None-Match` header names `tag`, compared weakly per RFC 9110. */
42552
- function matchesTag(header, tag) {
42553
- if (header === void 0) return false;
42554
- if (header.trim() === "*") return true;
42555
- const opaque = tag.replace(/^W\//, "");
42556
- return header.split(",").some((listed) => listed.trim().replace(/^W\//, "") === opaque);
42557
- }
42558
- /**
42559
- * The bytes a single range names, null for a header to ignore, which RFC 9110
42560
- * allows for an unsupported range such as a multi-range.
42561
- */
42562
- function parseRange(header, size) {
42563
- const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
42564
- if (!match) return null;
42565
- const [, first = "", last = ""] = match;
42566
- if (first === "") {
42567
- if (last === "") return null;
42568
- const suffix = Number(last);
42569
- if (suffix === 0) return "unsatisfiable";
42570
- if (size === 0) return null;
42571
- return {
42572
- start: Math.max(0, size - suffix),
42573
- end: size - 1
42574
- };
42575
- }
42576
- const start = Number(first);
42577
- const end = last === "" ? size - 1 : Number(last);
42578
- if (last !== "" && end < start) return null;
42579
- if (start >= size) return "unsatisfiable";
42580
- return {
42581
- start,
42582
- end: Math.min(end, size - 1)
42583
- };
42584
- }
42585
- /**
42586
- * The sheets a frame imports, being every face, then the board's tokens, then
42587
- * the project's, then its kit sheets, which read the tokens and still lose to
42588
- * the frame's own sheets. `kitFiles` come as `kitSheetFiles` answers them.
42589
- */
42590
- function sheetUrls(project, sheets, kitFiles) {
42591
- const folder = `/frames/${encodeURIComponent(project)}`;
42592
- return [
42593
- ...FACES.map(faceSheetUrl),
42594
- ...sheets.board ? [BOARD_SHEET_URL] : [],
42595
- ...sheets.project ? [`${folder}/${TOKEN_FILE}`] : [],
42596
- ...kitFiles.map((file) => `${folder}/${file.split("/").map(encodeURIComponent).join("/")}`)
42597
- ];
42598
- }
42599
- function decodeSegments(segments) {
42600
- const decoded = [];
42601
- for (const segment of segments) {
42602
- let name;
42603
- try {
42604
- name = decodeURIComponent(segment);
42605
- } catch {
42606
- return null;
42607
- }
42608
- if (name === "" || name.startsWith(".") || /[/\\\0]/.test(name)) return null;
42609
- decoded.push(name);
42610
- }
42611
- return decoded;
42612
- }
42613
- /** The realpath of the file a request names, or null when it is refused or missing. */
42614
- async function resolveFile(root, [project, page, ...rest]) {
42615
- if (!project || !page) return null;
42616
- const projectSheet = rest.length === 0 && page === "tokens.css";
42617
- if (rest.length === 0 && !projectSheet) return null;
42618
- if (page !== "assets" && !projectSheet && (rest.length > 1 || isRecord$4(rest[0] ?? ""))) return null;
42619
- try {
42620
- const projectDir = await realpath(join(root, project));
42621
- if (!projectDir.startsWith(root + sep)) return null;
42622
- const file = await realpath(join(projectDir, page, ...rest));
42623
- if (!file.startsWith(projectDir + sep)) return null;
42624
- if (!servableInProject(relative(projectDir, file).split(sep))) return null;
42625
- return (await stat(file)).isFile() ? file : null;
42626
- } catch {
42627
- return null;
42628
- }
42629
- }
42630
- /**
42631
- * Whether the route may serve a file, read off its real path, so a symlink to
42632
- * a record or a dot-named path is refused.
42633
- */
42634
- function servableInProject(segments) {
42635
- if (segments.some((segment) => segment.startsWith("."))) return false;
42636
- const [first = "", name = ""] = segments;
42637
- if (segments.length === 1) return first === TOKEN_FILE;
42638
- return first === "assets" || !isRecord$4(name);
42639
- }
42640
- function isRecord$4(name) {
42641
- return name === "layout.json" || name === NOTES_FILE$1;
42642
- }
42643
43451
  // src/server/routes/kits.ts
42644
43452
  const name$1 = string$1().min(1).max(256);
42645
43453
  /**
@@ -43020,7 +43828,7 @@ const STATUS$2 = {
43020
43828
  "dispatch-failed": 502,
43021
43829
  "lock-timeout": 503
43022
43830
  };
43023
- const text$1 = string$1().trim().min(1).max(1e5);
43831
+ const text$2 = string$1().trim().min(1).max(1e5);
43024
43832
  const session = string$1().min(1).max(256);
43025
43833
  /** Page-relative paths an upload answered, each checked against the page on write. */
43026
43834
  const images = array$1(string$1().max(256)).max(32).optional();
@@ -43033,7 +43841,7 @@ const oneAddressee = {
43033
43841
  const pinSchema = object$1({
43034
43842
  /** The frame ref, `<project>/<page>/<frame>`. */
43035
43843
  frame: string$1().min(1).max(1024),
43036
- text: text$1,
43844
+ text: text$2,
43037
43845
  images,
43038
43846
  /** The element's index, given with the `modifiedAt` the board rendered it at. */
43039
43847
  element: int$1().min(0).optional(),
@@ -43042,7 +43850,7 @@ const pinSchema = object$1({
43042
43850
  dispatch
43043
43851
  }).refine(oneAddressee.check, oneAddressee.message);
43044
43852
  const replySchema = object$1({
43045
- text: text$1,
43853
+ text: text$2,
43046
43854
  images,
43047
43855
  to: session.optional(),
43048
43856
  dispatch
@@ -43425,7 +44233,7 @@ function previewRoutes(root, access, slot, { address = networkAddress } = {}) {
43425
44233
  // src/server/sourcing/save.ts
43426
44234
  /** The most bytes one download takes, so a runaway response never fills memory. */
43427
44235
  const DOWNLOAD_LIMIT = 67108864;
43428
- const IMAGE_TYPES = {
44236
+ const IMAGE_TYPES$1 = {
43429
44237
  "image/jpeg": "jpg",
43430
44238
  "image/png": "png",
43431
44239
  "image/webp": "webp",
@@ -43439,7 +44247,7 @@ const IMAGE_TYPES = {
43439
44247
  */
43440
44248
  function imageExtension(mediaType, url) {
43441
44249
  const type = mediaType?.split(";")[0]?.trim().toLowerCase() ?? "";
43442
- const fromType = IMAGE_TYPES[type];
44250
+ const fromType = IMAGE_TYPES$1[type];
43443
44251
  if (fromType !== void 0) return fromType;
43444
44252
  if (url === null) return null;
43445
44253
  const name = new URL(url).pathname.split("/").at(-1) ?? "";
@@ -43452,6 +44260,23 @@ function imageExtension(mediaType, url) {
43452
44260
  * failed request, a body past `limit`, or a file that is no image.
43453
44261
  */
43454
44262
  async function downloadImage(url, send, limit = DOWNLOAD_LIMIT) {
44263
+ const { bytes, mediaType, status } = await download(url, send, limit);
44264
+ const extension = imageExtension(mediaType, url);
44265
+ if (extension === null) throw new FrameboardError("source-failed", "The download is not an image a frame shows.", {
44266
+ url,
44267
+ status
44268
+ });
44269
+ return {
44270
+ bytes,
44271
+ extension
44272
+ };
44273
+ }
44274
+ /**
44275
+ * Downloads one file whole into memory, carrying the Frameboard user agent.
44276
+ * Refuses `source-failed` on a failed request or a body past `limit`, with
44277
+ * the URL and the status in the details.
44278
+ */
44279
+ async function download(url, send, limit = DOWNLOAD_LIMIT) {
43455
44280
  const failed = (message, status) => new FrameboardError("source-failed", message, {
43456
44281
  url,
43457
44282
  status
@@ -43460,22 +44285,19 @@ async function downloadImage(url, send, limit = DOWNLOAD_LIMIT) {
43460
44285
  try {
43461
44286
  response = await send(url, { headers: { "User-Agent": `frameboard/${version}` } });
43462
44287
  } catch (error) {
43463
- throw failed(`The image did not download: ${error instanceof Error ? error.message : String(error)}`, null);
44288
+ throw failed(`${url} did not download: ${error instanceof Error ? error.message : String(error)}`, null);
43464
44289
  }
43465
- if (!response.ok) throw failed(`The image host answered ${response.status}.`, response.status);
43466
- const extension = imageExtension(response.headers.get("content-type"), url);
43467
- if (extension === null) throw failed("The download is not an image a frame shows.", response.status);
43468
- let bytes;
44290
+ if (!response.ok) throw failed(`The host of ${url} answered ${response.status}.`, response.status);
43469
44291
  try {
43470
- bytes = await readCapped(response, limit);
44292
+ return {
44293
+ bytes: await readCapped(response, limit),
44294
+ mediaType: response.headers.get("content-type"),
44295
+ status: response.status
44296
+ };
43471
44297
  } catch (error) {
43472
44298
  if (error instanceof FrameboardError) throw error;
43473
- throw failed(`The image stopped downloading: ${error instanceof Error ? error.message : String(error)}`, response.status);
44299
+ throw failed(`${url} stopped downloading: ${error instanceof Error ? error.message : String(error)}`, response.status);
43474
44300
  }
43475
- return {
43476
- bytes,
43477
- extension
43478
- };
43479
44301
  }
43480
44302
  /** Reads the body chunk by chunk and stops once it passes `limit`, whatever length the host declared. */
43481
44303
  async function readCapped(response, limit) {
@@ -43501,15 +44323,15 @@ async function readCapped(response, limit) {
43501
44323
  return bytes;
43502
44324
  }
43503
44325
  function tooLarge(limit) {
43504
- return new FrameboardError("source-failed", `The image is past ${limit / 1024 / 1024} MiB.`, { limit });
44326
+ return new FrameboardError("source-failed", `The download is past ${limit / 1024 / 1024} MiB.`, { limit });
43505
44327
  }
43506
44328
  /**
43507
44329
  * The stem a saved file takes: `--name` when given, else the query or prompt
43508
- * as a lowercase dashed name, else `image`. Refuses `invalid-name` for a
43509
- * `--name` breaking the board name rule.
44330
+ * as a lowercase dashed name, else `fallback`. Refuses `invalid-name` for
44331
+ * a `--name` breaking the board name rule.
43510
44332
  */
43511
- function savedStem(name, text) {
43512
- if (name === void 0) return folderName(text) || "image";
44333
+ function savedStem(name, text, fallback = "image") {
44334
+ if (name === void 0) return folderName(text) || fallback;
43513
44335
  if (!isValidName(name)) throw new FrameboardError("invalid-name", `--name ${name} breaks the board's name rule, ${NAME_PATTERN.source}.`, { name });
43514
44336
  return name;
43515
44337
  }
@@ -43518,13 +44340,24 @@ function savedStem(name, text) {
43518
44340
  * from the stem, then its license file as `<landed name>.license.json`. A
43519
44341
  * license file that fails to land takes the image back out.
43520
44342
  */
43521
- async function saveImage(project, stem, image, license) {
44343
+ function saveImage(project, stem, image, license) {
44344
+ return saveWithLicense(project, `${stem}.${image.extension}`, image.bytes, license);
44345
+ }
44346
+ /**
44347
+ * Writes a packed model into the project's `assets/` as `<stem>.glb`, or the
44348
+ * first free name from it, with its license file beside it as `saveImage`
44349
+ * writes an image's.
44350
+ */
44351
+ function saveModel(project, stem, glb, license) {
44352
+ return saveWithLicense(project, `${stem}.glb`, glb, license);
44353
+ }
44354
+ async function saveWithLicense(project, name, bytes, license) {
43522
44355
  const { added, refused } = await addAssets(project.path, [{
43523
- name: `${stem}.${image.extension}`,
43524
- bytes: image.bytes
44356
+ name,
44357
+ bytes
43525
44358
  }]);
43526
44359
  const landed = added[0];
43527
- if (landed === void 0) throw new FrameboardError("asset-type-refused", refused[0]?.message ?? "The image was refused.");
44360
+ if (landed === void 0) throw new FrameboardError("asset-type-refused", refused[0]?.message ?? `${name} was refused.`);
43528
44361
  const folder = join(project.path, ASSETS_FOLDER);
43529
44362
  const licensePath = `${landed.path}${LICENSE_FILE_SUFFIX}`;
43530
44363
  const temp = join(folder, `${randomBytes(6).toString("hex")}${TEMP_SUFFIX}`);
@@ -43755,11 +44588,11 @@ const google = {
43755
44588
  };
43756
44589
  /** The first image the interaction output, from `output_image` or else its model output steps. */
43757
44590
  function imageOf(body) {
43758
- if (!isRecord$3(body)) return null;
44591
+ if (!isRecord$4(body)) return null;
43759
44592
  const blocks = [body.output_image];
43760
- for (const step of Array.isArray(body.steps) ? body.steps : []) if (isRecord$3(step) && step.type === "model_output") blocks.push(...Array.isArray(step.content) ? step.content : []);
44593
+ for (const step of Array.isArray(body.steps) ? body.steps : []) if (isRecord$4(step) && step.type === "model_output") blocks.push(...Array.isArray(step.content) ? step.content : []);
43761
44594
  for (const block of blocks) {
43762
- if (!isRecord$3(block) || typeof block.data !== "string") continue;
44595
+ if (!isRecord$4(block) || typeof block.data !== "string") continue;
43763
44596
  if (block.type !== void 0 && block.type !== "image") continue;
43764
44597
  return {
43765
44598
  data: block.data,
@@ -43769,10 +44602,10 @@ function imageOf(body) {
43769
44602
  return null;
43770
44603
  }
43771
44604
  function messageOf(body) {
43772
- if (isRecord$3(body) && isRecord$3(body.error)) return typeof body.error.message === "string" ? body.error.message : "the request was refused";
44605
+ if (isRecord$4(body) && isRecord$4(body.error)) return typeof body.error.message === "string" ? body.error.message : "the request was refused";
43773
44606
  return "the request was refused";
43774
44607
  }
43775
- function isRecord$3(value) {
44608
+ function isRecord$4(value) {
43776
44609
  return typeof value === "object" && value !== null;
43777
44610
  }
43778
44611
  // src/server/sourcing/generate.ts
@@ -43833,8 +44666,8 @@ async function searchImages(query, options, send) {
43833
44666
  url.searchParams.set("q", query);
43834
44667
  url.searchParams.set("license", licensesFor(options).join(","));
43835
44668
  url.searchParams.set("page_size", String(20));
43836
- const body = await request(url, send);
43837
- return (isRecord$2(body) && Array.isArray(body.results) ? body.results : []).map(toImage).filter((image) => image !== null).map((image, index) => ({
44669
+ const body = await request$1(url, send);
44670
+ return (isRecord$3(body) && Array.isArray(body.results) ? body.results : []).map(toImage).filter((image) => image !== null).map((image, index) => ({
43838
44671
  number: index + 1,
43839
44672
  ...image
43840
44673
  }));
@@ -43845,7 +44678,7 @@ async function searchImages(query, options, send) {
43845
44678
  */
43846
44679
  async function imageById(id, options, send) {
43847
44680
  const missing = (reason) => new FrameboardError("result-not-found", reason, { id });
43848
- const image = toImage(await request(new URL(`${encodeURIComponent(id)}/`, OPENVERSE_API), send, missing));
44681
+ const image = toImage(await request$1(new URL(`${encodeURIComponent(id)}/`, OPENVERSE_API), send, missing));
43849
44682
  if (image === null) throw missing(`Openverse holds no image ${id}.`);
43850
44683
  const allowed = licensesFor(options);
43851
44684
  if (!allowed.includes(image.license)) throw new FrameboardError("result-not-found", `Openverse image ${id} is under ${image.license}, outside ${allowed.join(", ")}. Pass --credited to allow a license that asks for credit.`, {
@@ -43875,7 +44708,7 @@ function foundLicense(image, query, savedAt) {
43875
44708
  savedAt: savedAt.toISOString()
43876
44709
  };
43877
44710
  }
43878
- async function request(url, send, missing) {
44711
+ async function request$1(url, send, missing) {
43879
44712
  let response;
43880
44713
  try {
43881
44714
  response = await send(url, { headers: { "User-Agent": `frameboard/${version}` } });
@@ -43901,34 +44734,34 @@ async function request(url, send, missing) {
43901
44734
  }
43902
44735
  /** Openverse's snake_case result as the record's fields, null when it lacks an id, a license, or a URL. */
43903
44736
  function toImage(raw) {
43904
- if (!isRecord$2(raw)) return null;
43905
- const id = text(raw.id);
43906
- const license = text(raw.license);
43907
- const url = text(raw.url);
44737
+ if (!isRecord$3(raw)) return null;
44738
+ const id = text$1(raw.id);
44739
+ const license = text$1(raw.license);
44740
+ const url = text$1(raw.url);
43908
44741
  if (id === null || license === null || url === null) return null;
43909
44742
  return {
43910
44743
  id,
43911
- title: text(raw.title),
43912
- creator: text(raw.creator),
43913
- creatorUrl: text(raw.creator_url),
44744
+ title: text$1(raw.title),
44745
+ creator: text$1(raw.creator),
44746
+ creatorUrl: text$1(raw.creator_url),
43914
44747
  license,
43915
- licenseVersion: text(raw.license_version),
43916
- licenseUrl: text(raw.license_url),
43917
- attribution: text(raw.attribution),
43918
- landingUrl: text(raw.foreign_landing_url),
44748
+ licenseVersion: text$1(raw.license_version),
44749
+ licenseUrl: text$1(raw.license_url),
44750
+ attribution: text$1(raw.attribution),
44751
+ landingUrl: text$1(raw.foreign_landing_url),
43919
44752
  url,
43920
- thumbnail: text(raw.thumbnail),
43921
- width: integer(raw.width),
43922
- height: integer(raw.height)
44753
+ thumbnail: text$1(raw.thumbnail),
44754
+ width: integer$1(raw.width),
44755
+ height: integer$1(raw.height)
43923
44756
  };
43924
44757
  }
43925
- function isRecord$2(value) {
44758
+ function isRecord$3(value) {
43926
44759
  return typeof value === "object" && value !== null;
43927
44760
  }
43928
- function text(value) {
44761
+ function text$1(value) {
43929
44762
  return typeof value === "string" && value !== "" ? value : null;
43930
44763
  }
43931
- function integer(value) {
44764
+ function integer$1(value) {
43932
44765
  return typeof value === "number" && Number.isSafeInteger(value) ? value : null;
43933
44766
  }
43934
44767
  // src/server/routes/sourcing.ts
@@ -44296,7 +45129,7 @@ const BINDING_RULES = [{
44296
45129
  severity: "warning",
44297
45130
  description: "A control's data-binds names a selector matching an element in its frame, then a custom property opening with \"--\""
44298
45131
  }];
44299
- const finding$12 = findingFor(BINDING_RULES);
45132
+ const finding$11 = findingFor(BINDING_RULES);
44300
45133
  /**
44301
45134
  * `binding-target`, one finding per control whose `data-binds` tunes nothing,
44302
45135
  * a warning since the frame still renders.
@@ -44308,7 +45141,7 @@ function checkBindings(source) {
44308
45141
  if (value === void 0) return [];
44309
45142
  const problem = problemOf(value, source);
44310
45143
  if (problem === null) return [];
44311
- return [finding$12("binding-target", {
45144
+ return [finding$11("binding-target", {
44312
45145
  frame: source.ref,
44313
45146
  path,
44314
45147
  location: attributeLocation(element, BINDS_ATTRIBUTE),
@@ -44337,7 +45170,7 @@ const BOARD_ROUTE_RULES = [{
44337
45170
  severity: "error",
44338
45171
  description: "A frame's scripts and event handlers name no path under /api/, which on the board's origin reaches the board's own server"
44339
45172
  }];
44340
- const finding$11 = findingFor(BOARD_ROUTE_RULES);
45173
+ const finding$10 = findingFor(BOARD_ROUTE_RULES);
44341
45174
  /**
44342
45175
  * A quoted `/api/` path, so prose in a comment does not match, while a path
44343
45176
  * built at runtime passes, since the rule catches mistakes, not deliberate calls.
@@ -44350,7 +45183,7 @@ const BOARD_ROUTE = /(['"`])((?:(?:[a-z][a-z0-9+.-]*:)?\/\/[^/'"`\s]*)?\/api\/[^
44350
45183
  function checkBoardRoutes(source) {
44351
45184
  return frameCode(source).flatMap((code) => [...code.text.matchAll(BOARD_ROUTE)].map((match) => {
44352
45185
  const start = code.offset === null ? null : code.offset + match.index;
44353
- return finding$11("board-route", {
45186
+ return finding$10("board-route", {
44354
45187
  frame: source.ref,
44355
45188
  path: boardPath(source.root, code.path),
44356
45189
  message: `${code.via} names ${match[2]}, a route of the board's own server, which a frame on the board's origin reaches. Mock an app's calls with data kept in the script, or list board-route in the project's checks.off if its frames mean to call /api/.`,
@@ -44404,7 +45237,7 @@ const CONTRAST_RULES = [{
44404
45237
  configKey: "minContrast",
44405
45238
  description: "Text contrasts with the solid color behind it at a lower ratio than the project sets, 4.5 being WCAG's, with large text held to two thirds of it. Text over an image, a gradient, or an effect is not measured."
44406
45239
  }];
44407
- const finding$10 = findingFor(CONTRAST_RULES);
45240
+ const finding$9 = findingFor(CONTRAST_RULES);
44408
45241
  /** WCAG's large text is 18 pt, or 14 pt bold, which hold 3:1 against 4.5:1. */
44409
45242
  const LARGE_SHARE = 2 / 3;
44410
45243
  /**
@@ -44422,7 +45255,7 @@ async function checkContrast(page, target, minContrast) {
44422
45255
  const others = under.length - 1;
44423
45256
  const rest = others === 0 ? "" : `, and ${others} more ${others === 1 ? "element is" : "elements are"} under it`;
44424
45257
  const minimum = worst.large ? `${formatRatio(worst.minimum)}:1 minimum for large text` : `${formatRatio(worst.minimum)}:1 minimum`;
44425
- return [finding$10("min-contrast", {
45258
+ return [finding$9("min-contrast", {
44426
45259
  frame: target.ref,
44427
45260
  path: target.path,
44428
45261
  message: `${target.ref} sets text in <${worst.tag}> at element ${worst.index} at ${floorRatio(worst.ratio)}:1, ${worst.foreground} on ${worst.background}, under the project's ${minimum}${rest}.`
@@ -44595,7 +45428,7 @@ const DECLARATION_RULES = [{
44595
45428
  severity: "warning",
44596
45429
  description: "A declaration the page's own CSS parser drops, being a misspelled property, a value it cannot read, or a sheet that stops parsing"
44597
45430
  }];
44598
- const finding$9 = findingFor(DECLARATION_RULES);
45431
+ const finding$8 = findingFor(DECLARATION_RULES);
44599
45432
  /**
44600
45433
  * At-rules whose blocks hold descriptors rather than properties, which
44601
45434
  * `CSS.supports` cannot answer, and `@supports`, whose block is a
@@ -44617,7 +45450,7 @@ async function checkDeclarations(page, source) {
44617
45450
  const path = boardPath(source.root, sheet.path);
44618
45451
  const text = sheet.origin === "style" ? source.html : sheet.css;
44619
45452
  const { root, errors } = parseSheet$1(sheet.css);
44620
- for (const error of errors) findings.push(finding$9("dropped-declaration", {
45453
+ for (const error of errors) findings.push(finding$8("dropped-declaration", {
44621
45454
  frame: source.ref,
44622
45455
  path,
44623
45456
  message: breakMessage(error),
@@ -44656,7 +45489,7 @@ async function checkDeclarations(page, source) {
44656
45489
  const supported = await page.evaluate((pairs) => pairs.map(([property, value]) => CSS.supports(property, value)), written.map((each) => [each.property, each.value]));
44657
45490
  written.forEach((each, index) => {
44658
45491
  if (supported[index]) return;
44659
- findings.push(finding$9("dropped-declaration", {
45492
+ findings.push(finding$8("dropped-declaration", {
44660
45493
  frame: source.ref,
44661
45494
  path: each.path,
44662
45495
  message: `The browser drops ${each.property}: ${each.value}, since it reads no such property or no such value for it. Check the spelling of both, and the unit of a length, such as 12px.`,
@@ -44696,7 +45529,7 @@ const FONT_SIZE_RULES = [{
44696
45529
  configKey: "minFontSize",
44697
45530
  description: "Text renders smaller than the project sets as its minimum size in pixels"
44698
45531
  }];
44699
- const finding$8 = findingFor(FONT_SIZE_RULES);
45532
+ const finding$7 = findingFor(FONT_SIZE_RULES);
44700
45533
  /**
44701
45534
  * Reports text under `minFontSize` pixels, naming the smallest element and
44702
45535
  * how many more fall under, at most one finding per frame.
@@ -44707,7 +45540,7 @@ async function checkFontSize(page, target, minFontSize) {
44707
45540
  const smallest = under.reduce((least, text) => text.size < least.size ? text : least);
44708
45541
  const others = under.length - 1;
44709
45542
  const rest = others === 0 ? "" : `, and ${others} more ${others === 1 ? "element is" : "elements are"} under it`;
44710
- return [finding$8("min-font-size", {
45543
+ return [finding$7("min-font-size", {
44711
45544
  frame: target.ref,
44712
45545
  path: target.path,
44713
45546
  message: `${target.ref} sets text at ${smallest.size} px in <${smallest.tag}> at element ${smallest.index}, under the project's ${minFontSize} px minimum${rest}.`
@@ -45884,7 +46717,7 @@ const LAYOUT_RULES = [
45884
46717
  description: "Content sizes itself off the viewport height rather than holding a height of its own, a warning since a full-height screen does it on purpose"
45885
46718
  }
45886
46719
  ];
45887
- const finding$7 = findingFor(LAYOUT_RULES);
46720
+ const finding$6 = findingFor(LAYOUT_RULES);
45888
46721
  /**
45889
46722
  * The slack a reading takes before it counts, so a subpixel edge rounding up
45890
46723
  * is never a finding. One pixel matches what the groundwork spike measured.
@@ -45929,7 +46762,7 @@ function clipped(target, read) {
45929
46762
  if (!tall && !wide) return null;
45930
46763
  const past = shown.filter((box) => tall && box.bottom > height + SLACK_PX || wide && box.right > width + SLACK_PX);
45931
46764
  const reach = [tall ? `${bottom} px tall in its ${height} px height` : null, wide ? `${right} px wide in its ${width} px width` : null].filter((part) => part !== null).join(" and ");
45932
- return finding$7("clipped", {
46765
+ return finding$6("clipped", {
45933
46766
  frame: target.ref,
45934
46767
  path: target.path,
45935
46768
  message: `${target.ref} is ${reach}, so the board cuts it off${offenders(past, "past the box")}. ${clippedAdvice(tall, wide, width)}`
@@ -45945,7 +46778,7 @@ function scrollbar(target, read) {
45945
46778
  const [first] = scrolling;
45946
46779
  if (!first) return null;
45947
46780
  const by = Math.max(first.overflowX, first.overflowY);
45948
- return finding$7("scrollbar", {
46781
+ return finding$6("scrollbar", {
45949
46782
  frame: target.ref,
45950
46783
  path: target.path,
45951
46784
  message: `${target.ref} scrolls inside ${element(first)}, whose content is ${by} px past its box${more(scrolling.length - 1, "scrolls", "scroll")}. Size it to its content, or set overflow to hidden.`
@@ -45955,7 +46788,7 @@ function viewport(target, atBox, atTall, boxRead, tallRead) {
45955
46788
  if (atTall <= atBox + SLACK_PX) return null;
45956
46789
  const before = new Map(boxRead.boxes.map((box) => [box.index, box.height]));
45957
46790
  const grown = tallRead.boxes.filter((box) => box.height > (before.get(box.index) ?? box.height) + SLACK_PX);
45958
- return finding$7("viewport", {
46791
+ return finding$6("viewport", {
45959
46792
  frame: target.ref,
45960
46793
  path: target.path,
45961
46794
  message: `${target.ref} grows with the viewport, measuring ${atBox} px at its ${target.box.height} px height and ${atTall} px at twice that${offenders(grown, "growing")}. Give it a height of its own unless it is a full-height screen on purpose.`
@@ -46087,7 +46920,7 @@ const SCROLL_EFFECT_RULES = [{
46087
46920
  severity: "warning",
46088
46921
  description: "A frame whose height hugs its content holds an effect driven by scrolling, being position: sticky, a window or document scroll listener, or a scroll or view timeline, which never runs since the frame never scrolls"
46089
46922
  }];
46090
- const finding$6 = findingFor(SCROLL_EFFECT_RULES);
46923
+ const finding$5 = findingFor(SCROLL_EFFECT_RULES);
46091
46924
  /**
46092
46925
  * `scroll-effect`, at most one finding on a hugging frame, counting listeners
46093
46926
  * on the window or document alone, so a missed one costs a hint, never an error.
@@ -46096,7 +46929,7 @@ async function checkScrollEffect(page, target) {
46096
46929
  if (target.scroll || !target.hugHeight) return [];
46097
46930
  const trigger = await page.evaluate(readScrollStyles) ?? await readListener(page);
46098
46931
  if (!trigger) return [];
46099
- return [finding$6("scroll-effect", {
46932
+ return [finding$5("scroll-effect", {
46100
46933
  frame: target.ref,
46101
46934
  path: target.path,
46102
46935
  message: `${target.ref} ${describe$7(trigger)}, which needs the frame to scroll, but its height hugs the content so it never does. Run frame resize --scroll to hold a screen height and scroll past it.`
@@ -46170,7 +47003,7 @@ const CUSTOM_PROPERTY_RULES = [{
46170
47003
  severity: "warning",
46171
47004
  description: "A var() with no fallback names a custom property no token sheet, frame sheet, style attribute, or script write declares"
46172
47005
  }];
46173
- const finding$5 = findingFor(CUSTOM_PROPERTY_RULES);
47006
+ const finding$4 = findingFor(CUSTOM_PROPERTY_RULES);
46174
47007
  /** A `var()` naming its property, with no fallback after a comma. */
46175
47008
  const BARE_VAR = /var\(\s*(--[\w-]+)\s*\)/g;
46176
47009
  /**
@@ -46222,7 +47055,7 @@ function checkUnknownTokens(source, tokens) {
46222
47055
  if (element.name !== "script") continue;
46223
47056
  for (const name of scriptWrites(scriptText(element, source))) declared.add(name);
46224
47057
  }
46225
- return uses.filter((use) => !declared.has(use.name)).map((use) => finding$5("unknown-token", {
47058
+ return uses.filter((use) => !declared.has(use.name)).map((use) => finding$4("unknown-token", {
46226
47059
  frame: source.ref,
46227
47060
  path: use.path,
46228
47061
  message: `var(${use.name}) names a custom property nothing declares, so the declaration resolves to nothing. Use a token the project's tokens.css declares, or give it a fallback, such as var(${use.name}, red). If a script sets it at runtime under a name the check cannot read, the fallback is the way out.`,
@@ -46277,7 +47110,7 @@ const FONT_RULES = [
46277
47110
  description: "Every text element's first family is one of the project's allowed fonts"
46278
47111
  }
46279
47112
  ];
46280
- const finding$4 = findingFor(FONT_RULES);
47113
+ const finding$3 = findingFor(FONT_RULES);
46281
47114
  const GENERIC_FAMILIES = /* @__PURE__ */ new Set([
46282
47115
  "serif",
46283
47116
  "sans-serif",
@@ -46320,7 +47153,7 @@ function checkFonts(source, cascade, config) {
46320
47153
  else if (allowed && !allowed.includes(family.toLowerCase())) push(unlisted, family, element);
46321
47154
  }
46322
47155
  const path = boardPath(source.root, source.path);
46323
- const at = (rule, elements, message) => finding$4(rule, {
47156
+ const at = (rule, elements, message) => finding$3(rule, {
46324
47157
  frame: source.ref,
46325
47158
  path,
46326
47159
  message: `${message} ${described(elements)}`,
@@ -46349,173 +47182,6 @@ function push(map, key, element) {
46349
47182
  if (list) list.push(element);
46350
47183
  else map.set(key, [element]);
46351
47184
  }
46352
- // src/server/checks/links.ts
46353
- const LINK_RULES = [
46354
- {
46355
- id: "outside-link",
46356
- tier: "exact",
46357
- severity: "error",
46358
- description: "A frame loads files from its own page folder and its project's assets/ folder alone, never from a sibling page or the server root"
46359
- },
46360
- {
46361
- id: "network",
46362
- tier: "exact",
46363
- severity: "error",
46364
- description: "A frame loads nothing over the network, while a navigation link passes"
46365
- },
46366
- {
46367
- id: "missing-file",
46368
- tier: "exact",
46369
- severity: "error",
46370
- description: "Every local file a frame loads exists"
46371
- }
46372
- ];
46373
- const finding$3 = findingFor(LINK_RULES);
46374
- /** The attributes a `<model-viewer>` loads a file through, which `docs` states beside the rule. */
46375
- const MODEL_LOADS = [
46376
- "src",
46377
- "poster",
46378
- "environment-image",
46379
- "skybox-image"
46380
- ];
46381
- /**
46382
- * The attributes that load a resource, by element. An `a href` navigates
46383
- * rather than loads, so it is left out.
46384
- */
46385
- const RESOURCE_ATTRIBUTES = {
46386
- link: ["href"],
46387
- script: ["src"],
46388
- img: ["src", "srcset"],
46389
- source: ["src", "srcset"],
46390
- video: ["src", "poster"],
46391
- audio: ["src"],
46392
- track: ["src"],
46393
- iframe: ["src"],
46394
- embed: ["src"],
46395
- object: ["data"],
46396
- input: ["src"],
46397
- image: ["href", "xlink:href"],
46398
- use: ["href", "xlink:href"],
46399
- "model-viewer": [...MODEL_LOADS]
46400
- };
46401
- /** The lighting a viewer builds itself, which `environment-image` names in place of a file. */
46402
- const BUILT_IN_ENVIRONMENTS = /* @__PURE__ */ new Set(["neutral", "legacy"]);
46403
- /** `outside-link`, `network`, and `missing-file` over every load a frame makes. */
46404
- function checkLinks(source) {
46405
- return frameLoads(source).flatMap((load) => judge(source, load));
46406
- }
46407
- /**
46408
- * Every resource a frame loads, from its elements' attributes and inline
46409
- * styles and from each sheet it renders with, unjudged. The link check and the
46410
- * asset usage count read this one list, so they never disagree on a load.
46411
- */
46412
- function frameLoads(source) {
46413
- const framePath = boardPath(source.root, source.path);
46414
- const loads = [];
46415
- for (const element of source.elements) {
46416
- for (const name of RESOURCE_ATTRIBUTES[element.name] ?? []) {
46417
- const value = element.attribs[name];
46418
- if (value === void 0) continue;
46419
- if (name === "environment-image" && BUILT_IN_ENVIRONMENTS.has(value)) continue;
46420
- const urls = name === "srcset" ? srcsetUrls(value) : [value];
46421
- for (const url of urls) loads.push({
46422
- url,
46423
- base: source.pageDir,
46424
- path: framePath,
46425
- location: attributeLocation(element, name),
46426
- via: `<${element.name} ${name}>`
46427
- });
46428
- }
46429
- const style = element.attribs.style;
46430
- if (style !== void 0) for (const { url } of cssUrls(`x{${style}}`)) loads.push({
46431
- url,
46432
- base: source.pageDir,
46433
- path: framePath,
46434
- location: attributeLocation(element, "style"),
46435
- via: `a style attribute's url()`
46436
- });
46437
- }
46438
- for (const sheet of source.sheets) loads.push(...sheetLoads(source, sheet));
46439
- return loads;
46440
- }
46441
- function sheetLoads(source, sheet) {
46442
- const path = boardPath(source.root, sheet.path);
46443
- const text = sheet.origin === "style" ? source.html : sheet.css;
46444
- return cssUrls(sheet.css).map(({ url, start, end, kind }) => ({
46445
- url,
46446
- base: sheetBase(sheet),
46447
- path,
46448
- location: locate$1(text, sheet.offset + start, sheet.offset + end),
46449
- via: kind === "import" ? "@import" : "url()"
46450
- }));
46451
- }
46452
- function judge(source, load) {
46453
- const url = load.url.trim();
46454
- if (url === "" || url.startsWith("#") || /^(data|blob|about):/i.test(url)) return [];
46455
- const fields = {
46456
- frame: source.ref,
46457
- path: load.path,
46458
- location: load.location
46459
- };
46460
- if (hasScheme(url)) return [finding$3("network", {
46461
- ...fields,
46462
- message: `${load.via} loads ${url} over the network. Save the file into the page folder or the project's assets/ and link it there.`
46463
- })];
46464
- const target = localTarget(url, load.base);
46465
- if (target === null || !allowed(source, target)) return [finding$3("outside-link", {
46466
- ...fields,
46467
- message: `${load.via} loads ${url}, outside this page's folder and the project's assets/. Move the file into one of them.`
46468
- })];
46469
- if (!existsSync(target)) return [finding$3("missing-file", {
46470
- ...fields,
46471
- message: `${load.via} loads ${url}, which does not exist.`
46472
- })];
46473
- return [];
46474
- }
46475
- /**
46476
- * Inside the page folder or the project's `assets/`, both by path and, for a
46477
- * file that exists, by realpath, so a symlink out of the project is caught.
46478
- */
46479
- function allowed(source, target) {
46480
- const assets = assetsDirOf(source);
46481
- if (!isInside(source.pageDir, target) && !isInside(assets, target)) return false;
46482
- if (!existsSync(target)) return true;
46483
- const real = realpathSync(target);
46484
- const projectDir = realpathSync(source.projectDir);
46485
- return isInside(realpathSync(source.pageDir), real) || isInside(join(projectDir, "assets"), real);
46486
- }
46487
- function srcsetUrls(value) {
46488
- return value.split(",").map((candidate) => candidate.trim().split(/\s+/)[0] ?? "").filter((url) => url !== "");
46489
- }
46490
- /** Every `url()` and `@import` in a sheet. A sheet that does not parse loads nothing. */
46491
- function cssUrls(css) {
46492
- const urls = [];
46493
- let root;
46494
- try {
46495
- root = postcss_default.parse(css);
46496
- } catch {
46497
- return urls;
46498
- }
46499
- root.walk((node) => {
46500
- const start = node.source?.start?.offset ?? 0;
46501
- const end = node.source?.end?.offset ?? start;
46502
- if (node.type === "atrule" && node.name.toLowerCase() === "import") {
46503
- const url = importUrl(node.params);
46504
- if (url !== null) urls.push({
46505
- url,
46506
- start,
46507
- end,
46508
- kind: "import"
46509
- });
46510
- } else if (node.type === "decl") for (const match of node.value.matchAll(/url\(\s*(['"]?)(.*?)\1\s*\)/gi)) urls.push({
46511
- url: match[2] ?? "",
46512
- start,
46513
- end,
46514
- kind: "url"
46515
- });
46516
- });
46517
- return urls;
46518
- }
46519
47185
  // src/server/checks/structure.ts
46520
47186
  const STRUCTURE_RULES = [
46521
47187
  {
@@ -46832,8 +47498,8 @@ function readConfig(root, project) {
46832
47498
  } catch {
46833
47499
  return {};
46834
47500
  }
46835
- const checks = isRecord$1(parsed) ? parsed.checks : void 0;
46836
- if (!isRecord$1(checks)) return {};
47501
+ const checks = isRecord$2(parsed) ? parsed.checks : void 0;
47502
+ if (!isRecord$2(checks)) return {};
46837
47503
  const config = {};
46838
47504
  if (Array.isArray(checks.allowedFonts) && checks.allowedFonts.every((font) => typeof font === "string")) config.allowedFonts = checks.allowedFonts;
46839
47505
  if (typeof checks.noUppercase === "boolean") config.noUppercase = checks.noUppercase;
@@ -46842,7 +47508,7 @@ function readConfig(root, project) {
46842
47508
  if (Array.isArray(checks.off) && checks.off.every((rule) => typeof rule === "string")) config.off = checks.off;
46843
47509
  return config;
46844
47510
  }
46845
- function isRecord$1(value) {
47511
+ function isRecord$2(value) {
46846
47512
  return typeof value === "object" && value !== null && !Array.isArray(value);
46847
47513
  }
46848
47514
  // src/server/checks/outranked.ts
@@ -48141,7 +48807,7 @@ function createApp({ clientDir, root, port, actions, tickets, openRoute, renderF
48141
48807
  app.route("/", structureRoutes(root, actions.access, history, measure, given));
48142
48808
  app.route("/", historyRoutes(actions.access, history));
48143
48809
  app.route("/", notesRoutes(root, actions.access, delivery, dispatch));
48144
- app.route("/", assetsRoutes(root, actions.access, { usage: assetUsage }));
48810
+ app.route("/", assetsRoutes(root, actions.access, history, { usage: assetUsage }));
48145
48811
  app.route("/", sourcingRoutes(root, actions.access));
48146
48812
  app.route("/", elementsRoutes(root, actions.access, selection, given));
48147
48813
  app.route("/", findRoutes(root));
@@ -48794,7 +49460,7 @@ async function requestBoard(address, path, init, timeoutMs = REQUEST_TIMEOUT_MS)
48794
49460
  }
48795
49461
  const envelope = await response.json().catch(() => null);
48796
49462
  const refusal = envelope?.error;
48797
- if (!response.ok && isErrorCode(refusal?.code) && typeof refusal?.message === "string") throw new FrameboardError(refusal.code, refusal.message, isRecord(refusal.details) ? refusal.details : {});
49463
+ if (!response.ok && isErrorCode(refusal?.code) && typeof refusal?.message === "string") throw new FrameboardError(refusal.code, refusal.message, isRecord$1(refusal.details) ? refusal.details : {});
48798
49464
  if (!response.ok || !envelope) throw new FrameboardError("internal", `The frameboard server at ${address.url} refused ${path} with ${response.status}.`, {
48799
49465
  url: address.url,
48800
49466
  status: response.status
@@ -48804,7 +49470,7 @@ async function requestBoard(address, path, init, timeoutMs = REQUEST_TIMEOUT_MS)
48804
49470
  function isErrorCode(code) {
48805
49471
  return typeof code === "string" && Object.hasOwn(EXIT_CODES, code);
48806
49472
  }
48807
- function isRecord(value) {
49473
+ function isRecord$1(value) {
48808
49474
  return typeof value === "object" && value !== null && !Array.isArray(value);
48809
49475
  }
48810
49476
  // src/cli/commands/check.ts
@@ -48934,33 +49600,6 @@ function describe$5(result, { count = true } = {}) {
48934
49600
  else if (browser?.reason === "browser-not-found") lines.push(`Browser rules did not run, since the board server could not launch Playwright's headless shell. Install it with ${installCommands().npx}.`);
48935
49601
  return lines.join("\n");
48936
49602
  }
48937
- /** The files in a project's `assets/` by path, empty when the folder is missing. */
48938
- const assetListSchema = object$1({ files: array$1(object$1({
48939
- /** Relative to the project's `assets/`, with `/` between segments. */
48940
- path: string$1(),
48941
- kind: _enum$1(ASSET_KINDS),
48942
- /** Bytes. */
48943
- size: number().int().nonnegative(),
48944
- /** How many frames link the file, each counted once, absent where the server counts none. */
48945
- frames: number().int().nonnegative().optional()
48946
- })) });
48947
- const assetAddResultSchema = object$1({
48948
- /** Each landed file with the name it was dropped as and the name it took. */
48949
- added: array$1(object$1({
48950
- name: string$1(),
48951
- path: string$1()
48952
- })),
48953
- /** Each file left out, by its dropped name, with the error code that says why. */
48954
- refused: array$1(object$1({
48955
- name: string$1(),
48956
- code: string$1(),
48957
- message: string$1()
48958
- }))
48959
- });
48960
- object$1({ transitions: array$1(object$1({
48961
- name: string$1(),
48962
- css: string$1()
48963
- })) });
48964
49603
  // src/shared/records/list.ts
48965
49604
  const recordErrorSchema = object$1({
48966
49605
  path: string$1(),
@@ -49556,6 +50195,9 @@ const RECORDS = {
49556
50195
  claim: claimSchema,
49557
50196
  assetList: assetListSchema,
49558
50197
  assetAdd: assetAddResultSchema,
50198
+ assetRename: assetRenameSchema,
50199
+ assetWrite: assetWriteResultSchema,
50200
+ assetFrames: assetFramesSchema,
49559
50201
  elements: elementTreeSchema,
49560
50202
  selection: selectionResultSchema,
49561
50203
  find: findResultSchema,
@@ -49567,8 +50209,312 @@ const RECORDS = {
49567
50209
  savedImage: savedImageSchema,
49568
50210
  licenseFile: licenseFileSchema,
49569
50211
  imageGenerate: imageGenerateSchema,
49570
- imageDoctor: imageDoctorSchema
50212
+ imageDoctor: imageDoctorSchema,
50213
+ modelFind: modelFindSchema,
50214
+ savedModel: savedModelSchema
50215
+ };
50216
+ // src/server/sourcing/pack-glb.ts
50217
+ const GLB_MAGIC = 1179937895;
50218
+ const GLB_VERSION = 2;
50219
+ const JSON_CHUNK = 1313821514;
50220
+ const BIN_CHUNK = 5130562;
50221
+ const CHUNK_HEADER_BYTES = 8;
50222
+ /** The texture formats a glTF viewer reads with no extension named. */
50223
+ const IMAGE_TYPES = {
50224
+ jpg: "image/jpeg",
50225
+ jpeg: "image/jpeg",
50226
+ png: "image/png"
50227
+ };
50228
+ /**
50229
+ * Packs a glTF and the files `files` holds by the URI it names into one GLB
50230
+ * naming no outside file. Refuses `source-failed` for anything it cannot pack
50231
+ * whole rather than writing a file a viewer cannot load.
50232
+ */
50233
+ function packGlb(gltf, files) {
50234
+ const buffers = listOf(gltf.buffers);
50235
+ if (buffers.length > 1) throw refused(`The glTF names ${buffers.length} buffers, and one packs.`);
50236
+ const parts = [];
50237
+ let length = 0;
50238
+ const append = (bytes) => {
50239
+ const offset = length;
50240
+ parts.push({
50241
+ bytes,
50242
+ offset
50243
+ });
50244
+ length = align(offset + bytes.byteLength);
50245
+ return offset;
50246
+ };
50247
+ const buffer = buffers[0];
50248
+ if (buffer !== void 0) {
50249
+ const declared = buffer.byteLength;
50250
+ if (typeof declared !== "number") throw refused("The glTF buffer states no byteLength.");
50251
+ const bytes = fileFor(buffer.uri, files);
50252
+ if (bytes.byteLength < declared) throw refused(`The buffer holds ${bytes.byteLength} bytes, short of the ${declared} the glTF states.`);
50253
+ append(bytes.subarray(0, declared));
50254
+ }
50255
+ const packedViews = [...listOf(gltf.bufferViews)];
50256
+ const images = listOf(gltf.images).map((image) => {
50257
+ if (image.uri === void 0) return image;
50258
+ const bytes = fileFor(image.uri, files);
50259
+ const mimeType = mimeTypeOf(image);
50260
+ const byteOffset = append(bytes);
50261
+ packedViews.push({
50262
+ buffer: 0,
50263
+ byteOffset,
50264
+ byteLength: bytes.byteLength
50265
+ });
50266
+ const { uri: _uri, ...rest } = image;
50267
+ return {
50268
+ ...rest,
50269
+ bufferView: packedViews.length - 1,
50270
+ mimeType
50271
+ };
50272
+ });
50273
+ const json = { ...gltf };
50274
+ delete json.buffers;
50275
+ delete json.bufferViews;
50276
+ if (length > 0) json.buffers = [{ byteLength: length }];
50277
+ if (packedViews.length > 0) json.bufferViews = packedViews;
50278
+ if (gltf.images !== void 0) json.images = images;
50279
+ return container(json, parts, length);
50280
+ }
50281
+ function container(json, parts, binLength) {
50282
+ const text = new TextEncoder().encode(JSON.stringify(json));
50283
+ const jsonLength = align(text.byteLength);
50284
+ const binChunk = binLength === 0 ? 0 : CHUNK_HEADER_BYTES + binLength;
50285
+ const total = 20 + jsonLength + binChunk;
50286
+ const glb = new Uint8Array(total);
50287
+ const view = new DataView(glb.buffer);
50288
+ view.setUint32(0, GLB_MAGIC, true);
50289
+ view.setUint32(4, GLB_VERSION, true);
50290
+ view.setUint32(8, total, true);
50291
+ view.setUint32(12, jsonLength, true);
50292
+ view.setUint32(16, JSON_CHUNK, true);
50293
+ glb.set(text, 20);
50294
+ glb.fill(32, 20 + text.byteLength, 20 + jsonLength);
50295
+ if (binChunk === 0) return glb;
50296
+ const binStart = 20 + jsonLength;
50297
+ view.setUint32(binStart, binLength, true);
50298
+ view.setUint32(binStart + 4, BIN_CHUNK, true);
50299
+ const dataStart = binStart + CHUNK_HEADER_BYTES;
50300
+ for (const part of parts) glb.set(part.bytes, dataStart + part.offset);
50301
+ return glb;
50302
+ }
50303
+ function fileFor(uri, files) {
50304
+ if (typeof uri !== "string" || uri === "") throw refused("The glTF names a buffer or image with no uri.");
50305
+ if (uri.startsWith("data:")) throw refused("The glTF carries a data URI, which this packer does not read.");
50306
+ const bytes = files.get(uri) ?? files.get(safeDecode(uri));
50307
+ if (bytes === void 0) throw refused(`The glTF names ${uri}, which was not downloaded.`);
50308
+ return bytes;
50309
+ }
50310
+ function mimeTypeOf(image) {
50311
+ if (typeof image.mimeType === "string") {
50312
+ if (Object.values(IMAGE_TYPES).includes(image.mimeType)) return image.mimeType;
50313
+ throw refused(`The glTF names a texture of type ${image.mimeType}.`);
50314
+ }
50315
+ const uri = String(image.uri);
50316
+ const extension = uri.slice(uri.lastIndexOf(".") + 1).toLowerCase();
50317
+ const type = IMAGE_TYPES[extension];
50318
+ if (type === void 0) throw refused(`The texture ${uri} is neither JPEG nor PNG.`);
50319
+ return type;
50320
+ }
50321
+ function listOf(value) {
50322
+ return Array.isArray(value) ? value.filter((each) => typeof each === "object" && each !== null) : [];
50323
+ }
50324
+ function safeDecode(uri) {
50325
+ try {
50326
+ return decodeURIComponent(uri);
50327
+ } catch {
50328
+ return uri;
50329
+ }
50330
+ }
50331
+ function align(length) {
50332
+ return Math.ceil(length / 4) * 4;
50333
+ }
50334
+ function refused(message) {
50335
+ return new FrameboardError("source-failed", message, { source: "polyhaven" });
50336
+ }
50337
+ // src/server/sourcing/polyhaven.ts
50338
+ const POLYHAVEN_API = "https://api.polyhaven.com/";
50339
+ /** Named on every listing, which Poly Haven's API terms ask of any surface showing its content. */
50340
+ const POLYHAVEN_SOURCE = {
50341
+ name: "Poly Haven",
50342
+ url: "https://polyhaven.com"
49571
50343
  };
50344
+ const CC0_URL = "https://creativecommons.org/publicdomain/zero/1.0/";
50345
+ /** Poly Haven's `type` for a model, beside 0 for an HDRI and 1 for a texture. */
50346
+ const MODEL_TYPE = 2;
50347
+ /**
50348
+ * Poly Haven has no search, so this ranks its whole list here: by distinct
50349
+ * query words matching the name, tags, or categories, then download count,
50350
+ * then id, numbered from 1 and empty when no word matches.
50351
+ */
50352
+ async function searchModels(query, send) {
50353
+ const url = new URL("assets", POLYHAVEN_API);
50354
+ url.searchParams.set("t", "models");
50355
+ const body = await request(url, send);
50356
+ const words = new Set(wordsOf(query));
50357
+ const scored = Object.entries(isRecord(body) ? body : {}).map(([id, raw]) => toModel(id, raw)).filter((model) => model !== null).map((model) => {
50358
+ const own = new Set([
50359
+ model.name,
50360
+ ...model.tags,
50361
+ ...model.categories
50362
+ ].flatMap(wordsOf));
50363
+ return {
50364
+ model,
50365
+ score: [...words].filter((word) => own.has(word)).length
50366
+ };
50367
+ }).filter(({ score }) => score > 0);
50368
+ scored.sort((a, b) => b.score - a.score || (b.model.downloadCount ?? 0) - (a.model.downloadCount ?? 0) || a.model.id.localeCompare(b.model.id));
50369
+ return scored.slice(0, 20).map(({ model }, index) => ({
50370
+ number: index + 1,
50371
+ ...model
50372
+ }));
50373
+ }
50374
+ /**
50375
+ * One model by its Poly Haven id, refusing `result-not-found` for an id
50376
+ * Poly Haven does not hold or one naming a texture or an HDRI.
50377
+ */
50378
+ async function modelById(id, send) {
50379
+ const missing = new FrameboardError("result-not-found", `Poly Haven holds no model ${id}.`, { id });
50380
+ const model = toModel(id, await request(new URL(`info/${encodeURIComponent(id)}`, POLYHAVEN_API), send, missing));
50381
+ if (model === null) throw missing;
50382
+ return model;
50383
+ }
50384
+ /**
50385
+ * Downloads every file of one model at `size` into memory and packs them as
50386
+ * one GLB, so a failed download leaves nothing to write. Refuses `usage` with
50387
+ * the sizes offered, and `source-failed` on a failed download or pack.
50388
+ */
50389
+ async function fetchModel(id, size, send) {
50390
+ const body = await request(new URL(`files/${encodeURIComponent(id)}`, POLYHAVEN_API), send);
50391
+ const gltf = isRecord(body) && isRecord(body.gltf) ? body.gltf : {};
50392
+ const entryAt = (each) => {
50393
+ const sized = gltf[each];
50394
+ return isRecord(sized) && isRecord(sized.gltf) ? sized.gltf : null;
50395
+ };
50396
+ const sizes = MODEL_SIZES.filter((each) => entryAt(each) !== null);
50397
+ const entry = entryAt(size);
50398
+ if (sizes.length === 0) throw new FrameboardError("source-failed", `Poly Haven serves ${id} as no glTF, so it cannot be saved as a GLB.`, {
50399
+ source: "polyhaven",
50400
+ id,
50401
+ status: null
50402
+ });
50403
+ if (entry === null) throw new FrameboardError("usage", `Poly Haven serves ${id} at ${sizes.join(", ")}, not ${size}.`, {
50404
+ id,
50405
+ size,
50406
+ sizes
50407
+ });
50408
+ const gltfUrl = text(entry.url);
50409
+ if (gltfUrl === null) throw malformed(id);
50410
+ const includes = Object.entries(isRecord(entry.include) ? entry.include : {});
50411
+ const [main, ...files] = await Promise.all([download(gltfUrl, send), ...includes.map(([, file]) => {
50412
+ const fileUrl = isRecord(file) ? text(file.url) : null;
50413
+ if (fileUrl === null) throw malformed(id);
50414
+ return download(fileUrl, send);
50415
+ })]);
50416
+ let json;
50417
+ try {
50418
+ json = JSON.parse(new TextDecoder().decode(main?.bytes));
50419
+ } catch {
50420
+ throw malformed(id);
50421
+ }
50422
+ if (!isRecord(json)) throw malformed(id);
50423
+ const byUri = new Map(includes.map(([uri], index) => [uri, files[index]?.bytes ?? /* @__PURE__ */ new Uint8Array()]));
50424
+ return {
50425
+ bytes: packGlb(json, byUri),
50426
+ url: gltfUrl
50427
+ };
50428
+ }
50429
+ /** The license file for a Poly Haven model, `query` null when it was saved by id. */
50430
+ function polyhavenLicense(model, query, packed, savedAt) {
50431
+ return {
50432
+ version: 1,
50433
+ origin: "found",
50434
+ source: "polyhaven",
50435
+ id: model.id,
50436
+ query,
50437
+ title: model.name,
50438
+ authors: model.authors,
50439
+ license: "cc0",
50440
+ licenseUrl: CC0_URL,
50441
+ landingUrl: model.landingUrl,
50442
+ url: packed.url,
50443
+ size: packed.size,
50444
+ savedAt: savedAt.toISOString()
50445
+ };
50446
+ }
50447
+ async function request(url, send, missing) {
50448
+ let response;
50449
+ try {
50450
+ response = await send(url, { headers: { "User-Agent": `frameboard/${version}` } });
50451
+ } catch (error) {
50452
+ throw new FrameboardError("source-failed", `Poly Haven did not answer: ${error instanceof Error ? error.message : String(error)}`, {
50453
+ source: "polyhaven",
50454
+ status: null
50455
+ });
50456
+ }
50457
+ if (response.status === 404 && missing) throw missing;
50458
+ if (!response.ok) throw new FrameboardError("source-failed", `Poly Haven answered ${response.status}.`, {
50459
+ source: "polyhaven",
50460
+ status: response.status
50461
+ });
50462
+ try {
50463
+ return await response.json();
50464
+ } catch {
50465
+ throw new FrameboardError("source-failed", "Poly Haven answered something other than JSON.", {
50466
+ source: "polyhaven",
50467
+ status: response.status
50468
+ });
50469
+ }
50470
+ }
50471
+ /** Poly Haven's snake_case asset as the record's fields, null for anything but a model with a name. */
50472
+ function toModel(id, raw) {
50473
+ if (!isRecord(raw) || raw.type !== MODEL_TYPE) return null;
50474
+ const name = text(raw.name);
50475
+ if (name === null) return null;
50476
+ const largest = Array.isArray(raw.max_resolution) ? Math.max(0, ...raw.max_resolution.filter((each) => typeof each === "number")) : 0;
50477
+ const dimensions = Array.isArray(raw.dimensions) ? raw.dimensions.filter((each) => typeof each === "number") : [];
50478
+ return {
50479
+ id,
50480
+ name,
50481
+ authors: isRecord(raw.authors) ? Object.keys(raw.authors) : [],
50482
+ categories: texts(raw.categories),
50483
+ tags: texts(raw.tags),
50484
+ license: "cc0",
50485
+ landingUrl: `${POLYHAVEN_SOURCE.url}/a/${encodeURIComponent(id)}`,
50486
+ thumbnail: text(raw.thumbnail_url),
50487
+ polycount: integer(raw.polycount),
50488
+ dimensionsMm: dimensions.length === 3 ? [
50489
+ dimensions[0] ?? 0,
50490
+ dimensions[1] ?? 0,
50491
+ dimensions[2] ?? 0
50492
+ ] : null,
50493
+ sizes: MODEL_SIZES.filter((each) => Number.parseInt(each) * 1024 <= largest),
50494
+ downloadCount: integer(raw.download_count)
50495
+ };
50496
+ }
50497
+ function malformed(id) {
50498
+ return new FrameboardError("source-failed", `Poly Haven's file list for ${id} names no glTF to download.`, {
50499
+ source: "polyhaven",
50500
+ status: null
50501
+ });
50502
+ }
50503
+ function wordsOf(value) {
50504
+ return value.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
50505
+ }
50506
+ function isRecord(value) {
50507
+ return typeof value === "object" && value !== null && !Array.isArray(value);
50508
+ }
50509
+ function text(value) {
50510
+ return typeof value === "string" && value !== "" ? value : null;
50511
+ }
50512
+ function texts(value) {
50513
+ return Array.isArray(value) ? value.filter((each) => typeof each === "string") : [];
50514
+ }
50515
+ function integer(value) {
50516
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : null;
50517
+ }
49572
50518
  // src/cli/docs/content-format.ts
49573
50519
  /** The content format `docs` prints, built from the constants the verbs run on. */
49574
50520
  function contentFormat() {
@@ -49578,7 +50524,7 @@ function contentFormat() {
49578
50524
  `A project is any folder in the board whose name does not open with a dot. Its ${PROJECT_FILE} lists page names in display order, and pages it does not list follow by name.`,
49579
50525
  `A page is any folder in a project except ${ASSETS_FOLDER}/ and dot-named ones. Its ${LAYOUT_FILE} holds each frame's box, stacking order, and flags.`,
49580
50526
  `A frame is any *${FRAME_EXTENSION} file directly in a page, named by its stem.`,
49581
- `A page's notes sit in its ${NOTES_FILE$2}, never in a frame. A note pins to a frame or to one element by index and the frame file's hash, and reads at the frame once the file changes. Read them with notes, answer with notes reply, and close them with notes done. A note's images sit in its page's ${NOTES_FOLDER}/ folder, and its images field lists them relative to the page.`,
50527
+ `A page's notes sit in its ${NOTES_FILE$1}, never in a frame. A note pins to a frame or to one element by index and the frame file's hash, and reads at the frame once the file changes. Read them with notes, answer with notes reply, and close them with notes done. A note's images sit in its page's ${NOTES_FOLDER}/ folder, and its images field lists them relative to the page.`,
49582
50528
  `serve reuses a board the walk finds, and otherwise creates ${DEFAULT_BOARD_FOLDER}/ in the working folder with project ${START_PROJECT} and empty page ${START_PAGE}, and records its address in ${RUN_FOLDER}/${ADDRESS_FILE}.`,
49583
50529
  `Dot-named folders, *${LOCK_SUFFIX} files, and *${TEMP_SUFFIX} files belong to Frameboard and are never content.`
49584
50530
  ],
@@ -49611,7 +50557,7 @@ function contentFormat() {
49611
50557
  present: [
49612
50558
  `A page's slide transition sits on the present key of its ${LAYOUT_FILE} as { transition: { name, direction, ms } }, and a frame's entry may hold its own transition, which wins as that slide arrives. name is one of ${TRANSITIONS.join(", ")}, or one of the project's own. direction is one of ${DIRECTIONS.join(", ")}, taken by ${DIRECTED.join(" and ")} alone and defaulting to left. ms runs ${TRANSITION_MS.min} to ${TRANSITION_MS.max}, a frame's taking its page's when absent and the page's defaulting to 500. Any other value reads as none and is kept on write. The board draws a transition itself and never writes it into a frame file.`,
49613
50559
  `A project adds its own transition as a stylesheet at ${ASSETS_FOLDER}/${TRANSITIONS_FOLDER}/<name>${TRANSITION_FILE_EXTENSION}, set by <name> as a built-in is. The name is lowercase kebab case and never a built-in name, none, or page. The file holds @keyframes enter, which the arriving slide plays, optionally @keyframes leave, which the leaving slide plays or else holds still, and nothing else: no other rule or at-rule, and no url(), quoted string, or backslash escape in a value. The board plays those two keyframes over the transition's ms and never loads the file itself. It takes --ms and no direction, so a second file covers a second direction. A file breaking any of this is refused whole, reported by check and the write hook as transition-file, left out of list --json's transitions on its project, and a page or frame naming it cuts. Turning transition-file off silences the finding and the file stays refused.`,
49614
- `A frame's entry may hold speakerNotes, what the presenter means to say over the slide: plain text up to ${SPEAKER_NOTES_MAX} characters with its line breaks kept and no markup read. It lives on the entry alone and never enters the frame file, so a rewrite of the file keeps it, and a duplicate or a move to another page carries it. list --json reports it on the frame, absent when it holds none, and any value other than text reads as none and is kept on write. frame speaker-notes <frame-ref> prints it, frame speaker-notes <frame-ref> <text> sets it, refusing usage past the limit rather than cutting it, and --clear or blank text removes it. Present mode never shows it.`,
50560
+ `A frame's entry may hold speakerNotes, what the presenter means to say over the slide: plain text up to ${SPEAKER_NOTES_MAX} characters with its line breaks kept and no markup read. It lives on the entry alone and never enters the frame file, so a rewrite of the file keeps it, and a duplicate or a move to another page carries it. list --json reports it on the frame, absent when it holds none, and any value other than text reads as none and is kept on write. frame speaker-notes <frame-ref> prints it, frame speaker-notes <frame-ref> <text> sets it, refusing usage past the limit rather than cutting it, and --clear or blank text removes it. The board shows it in a strip under each slide while the Slides tab's Notes button shows notes, and the presenter view's window shows it beside the slide, while the slide the audience sees never does.`,
49615
50561
  "page transition <page-ref> <name> sets the page's, and none clears it so slides cut. frame transition <frame-ref> <name> sets a frame's, and page clears it so the frame takes its page's. Both take --ms and --direction, refuse usage on a name that is neither built in nor the project's own with the known names in the error's details, and write only layout.json.",
49616
50562
  `A step is an element present mode holds back until a press reveals it, marked by three attributes on that element and nothing else. ${STEP_ATTRIBUTES.step}="<n>" is a positive integer, and steps show in number order with equal numbers together and gaps closed. ${STEP_ATTRIBUTES.effect} is one of ${STEP_EFFECTS.join(", ")}, defaulting to appear. ${STEP_ATTRIBUTES.start} is one of ${STEP_STARTS.join(", ")}, defaulting to click, where with shows the step beside the one before it and after shows it once that one finishes. Set them with edit --attr. Edit, Play, capture, and an exported PNG show every step.`
49617
50563
  ],
@@ -49639,7 +50585,8 @@ function contentFormat() {
49639
50585
  `A frame shows a 3D model through one <${VIEWER_TAG} src="../${ASSETS_FOLDER}/<file>.glb" alt=""> element, sized by its own width and height as an image is. It reads .glb and .gltf alone, and a .gltf carries its buffers and images inside itself. A drop refuses ${FOREIGN_MODELS.join(", ")}, so export any of those from Blender through File, Export, glTF 2.0 as a glTF Binary (.glb).`,
49640
50586
  `The element draws only in a frame whose head loads the viewer, as ${VIEWER_SCRIPT}. Placing a model on the board copies ${VIEWER_FILE} into the project's ${ASSETS_FOLDER}/ once and adds that tag to a head loading no viewer, and removing the last model leaves both. The file ships with the tool at ${shippedViewerPath()}, so copy it to the project's ${ASSETS_FOLDER}/${VIEWER_FILE} before writing the element in a project that holds none. A frame loads nothing over the network, so never link the viewer from a CDN.`,
49641
50587
  `Every staging control is an attribute on the element, set with edit --attr. camera-orbit="<theta>deg <phi>deg <radius>" places the camera, across and then down from the top, and defaults to 0deg 75deg auto. The viewer holds the camera inside max-camera-orbit, so state both once the radius passes the model's own framing, as camera-orbit="30deg 70deg 6m" max-camera-orbit="auto auto 6m". orientation="<roll>deg <pitch>deg <yaw>deg" turns the model itself, scale="<x> <y> <z>" sizes it, animation-name picks one of its clips, and autoplay starts it. The board's Model section writes these same attributes, the angle as both orbit attributes in one undo step, and a double-click on a selected model turns it by drag.`,
49642
- `check reports missing-file at error for a ${VIEWER_TAG} whose ${MODEL_LOADS.join(", ")} names no file, as it does for the viewer script. capture waits for each model to draw inside the frame's load budget and holds its clip at the start, and --at seeks every clip to that moment, so two captures match. A model that fails to load, or is still loading when the budget ends, never refuses: the image lists it under models with state error or pending.`
50588
+ `check reports missing-file at error for a ${VIEWER_TAG} whose ${MODEL_LOADS.join(", ")} names no file, as it does for the viewer script. capture waits for each model to draw inside the frame's load budget and holds its clip at the start, and --at seeks every clip to that moment, so two captures match. A model that fails to load, or is still loading when the budget ends, never refuses: the image lists it under models with state error or pending.`,
50589
+ `model find searches ${POLYHAVEN_SOURCE.name}'s CC0 models, which ask no credit, and writes nothing. ${POLYHAVEN_SOURCE.name} has no search, so it reads the whole list in one request and ranks it here: by how many distinct query words match a word of the name, the tags, or the categories, then by download count, then by id, listing up to 20 numbered from 1 and none for a query matching nothing. Its results and human output name ${POLYHAVEN_SOURCE.name}, as its terms ask of any surface showing its content. --save <number> runs the search again, and --save <id> saves that ${POLYHAVEN_SOURCE.name} model with no search. A saved model is one .glb packed from the glTF, its buffer, and its textures, at 1k textures unless --size names one of ${MODEL_SIZES.join(", ")}, refusing usage with the sizes it offers for one the model lacks. A larger size weighs more, about 1 MB at 1k and 40 MB at 8k for a stool. Every file is held whole before anything is written, and its license file records the authors and the model's page.`
49643
50590
  ],
49644
50591
  assets: `A frame links files in its own page folder or in its project's ${ASSETS_FOLDER}/ folder. frame duplicate and frame move carry the ${FRAME_EXTENSION} file alone, so keep files shared between frames or pages in ${ASSETS_FOLDER}/.`,
49645
50592
  look: [
@@ -50240,7 +51187,7 @@ function registerImage(program, context) {
50240
51187
  const saved = await saveImage(project, stem, await downloadImage(chosen.image.url, send), foundLicense(chosen.image, chosen.query, /* @__PURE__ */ new Date()));
50241
51188
  return {
50242
51189
  data: saved,
50243
- human: savedLine(saved)
51190
+ human: savedLine$1(saved)
50244
51191
  };
50245
51192
  });
50246
51193
  act(addVerb(image, "generate", "Generate an image on the first provider whose key is set and save it into the project's assets, spending on that key unless --dry-run", { project: true }).argument("<prompt>", "what the image shows").option("--provider <name>", `run on this provider, one of ${IMAGE_PROVIDERS.join(", ")}, rather than the first ready`).option("--width <px>", "the width asked for", parseInteger(1), 1024).option("--height <px>", "the height asked for", parseInteger(1), 1024).option("--dry-run", "answer the provider, size, and price, and make no request").option("--name <stem>", "the saved file name without its extension, the prompt by default"), context, async ([prompt = ""], options) => {
@@ -50284,7 +51231,7 @@ function registerImage(program, context) {
50284
51231
  ...record,
50285
51232
  saved
50286
51233
  },
50287
- human: `Generated on ${priced}. ${savedLine(saved)}`
51234
+ human: `Generated on ${priced}. ${savedLine$1(saved)}`
50288
51235
  };
50289
51236
  });
50290
51237
  act(addVerb(image, "doctor", "Report the GPU, a local ComfyUI server, and which provider keys are set, installing nothing"), context, async () => {
@@ -50322,7 +51269,7 @@ function registerImage(program, context) {
50322
51269
  };
50323
51270
  }
50324
51271
  }
50325
- function savedLine(saved) {
51272
+ function savedLine$1(saved) {
50326
51273
  return `Saved assets/${saved.path} into ${saved.project}, its license in assets/${saved.licensePath}`;
50327
51274
  }
50328
51275
  // node_modules/ws/lib/constants.js
@@ -54212,6 +55159,66 @@ function describe$2({ root, projects }) {
54212
55159
  }
54213
55160
  return lines.join("\n");
54214
55161
  }
55162
+ // src/cli/commands/model.ts
55163
+ const CREDIT = `Models from ${POLYHAVEN_SOURCE.name}, ${POLYHAVEN_SOURCE.url}, CC0`;
55164
+ function registerModel(program, context) {
55165
+ const { io } = context;
55166
+ const send = io.fetch ?? fetch;
55167
+ act(addVerb(program.command("model").description("Find a public domain 3D model and save it into a project's assets as one GLB with its license"), "find", "Search Poly Haven's CC0 models, writing nothing unless --save names a result", { project: true }).argument("<query>", "what the model shows").option("--save <number-or-id>", "save the result with this number, or the Poly Haven model with this id, into the project's assets").option("--size <size>", `the texture size saved, one of ${MODEL_SIZES.join(", ")}, 1k by default`, parseSize).option("--name <stem>", "the saved file name without its extension, the query by default"), context, async ([query = ""], options) => {
55168
+ if (options.save === void 0) {
55169
+ for (const flag of ["name", "size"]) if (options[flag] !== void 0) throw new FrameboardError("usage", `--${flag} needs --save.`);
55170
+ const results = await searchModels(query, send);
55171
+ return {
55172
+ data: {
55173
+ version: 1,
55174
+ query,
55175
+ source: { ...POLYHAVEN_SOURCE },
55176
+ results
55177
+ },
55178
+ human: results.length === 0 ? `No ${POLYHAVEN_SOURCE.name} model matches ${query}` : [...results.map((each) => `${each.number}\t${each.sizes.at(-1) ?? "-"}\t${each.name}\t${each.id}`), CREDIT].join("\n")
55179
+ };
55180
+ }
55181
+ const stem = savedStem(options.name, query, "model");
55182
+ const project = await resolveProject(await boardOf(options, io), options.project);
55183
+ const size = options.size ?? "1k";
55184
+ const chosen = await pick(query, options.save);
55185
+ const packed = await fetchModel(chosen.model.id, size, send);
55186
+ const saved = await saveModel(project, stem, packed.bytes, polyhavenLicense(chosen.model, chosen.query, {
55187
+ url: packed.url,
55188
+ size
55189
+ }, /* @__PURE__ */ new Date()));
55190
+ return {
55191
+ data: saved,
55192
+ human: savedLine(saved)
55193
+ };
55194
+ });
55195
+ /** The model `--save` names: a number reruns the search, anything else is an id. */
55196
+ async function pick(query, save) {
55197
+ if (!/^\d+$/.test(save)) return {
55198
+ model: await modelById(save, send),
55199
+ query: null
55200
+ };
55201
+ const number = Number(save);
55202
+ const results = await searchModels(query, send);
55203
+ const found = results.find((each) => each.number === number);
55204
+ if (found === void 0) throw new FrameboardError("result-not-found", `The search for ${query} found ${results.length} results, so there is no result ${number}.`, {
55205
+ number,
55206
+ results: results.length
55207
+ });
55208
+ return {
55209
+ model: found,
55210
+ query
55211
+ };
55212
+ }
55213
+ }
55214
+ function parseSize(value) {
55215
+ const size = MODEL_SIZES.find((each) => each === value);
55216
+ if (size === void 0) throw new InvalidArgumentError(`Expected one of ${MODEL_SIZES.join(", ")}.`);
55217
+ return size;
55218
+ }
55219
+ function savedLine(saved) {
55220
+ return `Saved assets/${saved.path} into ${saved.project} from ${POLYHAVEN_SOURCE.name}, its license in assets/${saved.licensePath}`;
55221
+ }
54215
55222
  // src/cli/commands/notes.ts
54216
55223
  function registerNotes(program, context) {
54217
55224
  const { io } = context;
@@ -55330,71 +56337,6 @@ function createTickets(now = Date.now) {
55330
56337
  }
55331
56338
  };
55332
56339
  }
55333
- // src/server/board/asset-usage.ts
55334
- /**
55335
- * A per-project cache of how many frames link each asset, counted from the
55336
- * same loads the link check judges. A frame counts once per file, and only a
55337
- * link resolving inside the project's `assets/` counts.
55338
- */
55339
- function createAssetUsage(root) {
55340
- const cache = /* @__PURE__ */ new Map();
55341
- return {
55342
- counts: (project) => {
55343
- const cached = cache.get(project);
55344
- if (cached) return cached;
55345
- const built = countProject(root, project);
55346
- cache.set(project, built);
55347
- built.catch(() => {
55348
- if (cache.get(project) === built) cache.delete(project);
55349
- });
55350
- return built;
55351
- },
55352
- drop: (paths) => {
55353
- for (const path of paths) {
55354
- const inside = relative(root, path);
55355
- if (inside === "") {
55356
- cache.clear();
55357
- return;
55358
- }
55359
- if (inside.startsWith("..")) continue;
55360
- const project = inside.split(sep)[0];
55361
- if (project) cache.delete(project);
55362
- }
55363
- }
55364
- };
55365
- }
55366
- async function countProject(root, project) {
55367
- const projectDir = join(root, project);
55368
- const counts = /* @__PURE__ */ new Map();
55369
- for (const page of await listPageFolders(projectDir)) for (const name of await listFrames(join(projectDir, page))) for (const path of linkedAssets(root, project, page, name)) counts.set(path, (counts.get(path) ?? 0) + 1);
55370
- return counts;
55371
- }
55372
- /**
55373
- * The asset paths one frame links, each once, read from its file as it stands
55374
- * rather than from a cached count. A frame gone between the listing and the
55375
- * read links none.
55376
- */
55377
- function linkedAssets(root, project, page, name) {
55378
- const linked = /* @__PURE__ */ new Set();
55379
- let source;
55380
- try {
55381
- source = readFrame$1({
55382
- root,
55383
- project,
55384
- page,
55385
- name
55386
- });
55387
- } catch {
55388
- return linked;
55389
- }
55390
- const assets = assetsDirOf(source);
55391
- for (const load of frameLoads(source)) {
55392
- const target = localTarget(load.url, load.base);
55393
- if (target === null || target === assets || !isInside(assets, target)) continue;
55394
- linked.add(relative(assets, target).split(sep).join("/"));
55395
- }
55396
- return linked;
55397
- }
55398
56340
  // src/server/capture/thumbnails.ts
55399
56341
  const THUMBNAILS_FOLDER = "thumbnails";
55400
56342
  /**
@@ -58988,11 +59930,13 @@ function frameNameOf(name) {
58988
59930
  }
58989
59931
  /**
58990
59932
  * Hugging frames newly placed, measured without a reload, since placing writes
58991
- * `layout.json` alone, which reloads nothing.
59933
+ * `layout.json` alone, which reloads nothing. `unmeasured` names frames
59934
+ * `previous` holds placed that no batch measured, read as unplaced.
58992
59935
  */
58993
- function placedRefs(previous, next, paths) {
59936
+ function placedRefs(previous, next, paths, unmeasured = []) {
58994
59937
  const written = paths && new Set(paths);
58995
- const before = new Set(previous.projects.flatMap((project) => project.pages.flatMap((page) => page.frames.filter((frame) => frame.placed).map((frame) => frame.ref))));
59938
+ const pending = new Set(unmeasured);
59939
+ const before = new Set(previous.projects.flatMap((project) => project.pages.flatMap((page) => page.frames.filter((frame) => frame.placed && !pending.has(frame.ref)).map((frame) => frame.ref))));
58996
59940
  return next.projects.flatMap((project) => project.pages.filter((page) => !written || written.has(join(page.path, "layout.json"))).flatMap((page) => page.frames.filter((frame) => frame.placed && (frame.hugWidth || frame.hugHeight) && !before.has(frame.ref)).map((frame) => frame.ref)));
58997
59941
  }
58998
59942
  /**
@@ -59265,9 +60209,10 @@ function send(socket, message) {
59265
60209
  // src/server/live/hug.ts
59266
60210
  /**
59267
60211
  * The server's hug step, writing through `setMeasured`, with an unbounded,
59268
- * empty, or failing frame keeping its box.
60212
+ * empty, or failing frame keeping its box. A failing one is reported through
60213
+ * `report`, the server's log unless a test stands in, since nothing retries it.
59269
60214
  */
59270
- function createHug({ root, measure }) {
60215
+ function createHug({ root, measure, report = (line) => console.error(line) }) {
59271
60216
  let queue = Promise.resolve();
59272
60217
  let closed = false;
59273
60218
  const run = async (board, refs, parts) => {
@@ -59279,6 +60224,7 @@ function createHug({ root, measure }) {
59279
60224
  try {
59280
60225
  size = await measureParts(measure, frame, parts);
59281
60226
  } catch (error) {
60227
+ report(`frameboard: ${frame.ref} keeps its box, since its measure failed: ${failureOf(error)}`);
59282
60228
  if (error instanceof FrameboardError && error.code === "browser-not-found") break;
59283
60229
  continue;
59284
60230
  }
@@ -59322,6 +60268,14 @@ function createHug({ root, measure }) {
59322
60268
  };
59323
60269
  }
59324
60270
  /**
60271
+ * A board error's code and message, or another error's first line, since a
60272
+ * browser error goes on to its call log.
60273
+ */
60274
+ function failureOf(error) {
60275
+ if (error instanceof FrameboardError) return `${error.code}: ${error.message}`;
60276
+ return (error instanceof Error ? error.message : String(error)).split("\n", 1)[0] ?? "";
60277
+ }
60278
+ /**
59325
60279
  * Reads the parts a run asks for, a linked width only on a frame hugging its
59326
60280
  * height. An empty body at the frame's own box, or at every linked width,
59327
60281
  * reads nothing for that part, so the box it stands in for holds.
@@ -59909,7 +60863,10 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
59909
60863
  settling.set(timer, release);
59910
60864
  };
59911
60865
  const shown = { board: null };
59912
- const scanned = { board: null };
60866
+ const scanned = {
60867
+ board: null,
60868
+ unmeasured: []
60869
+ };
59913
60870
  let moved = [];
59914
60871
  const recentlyMoved = () => {
59915
60872
  moved = moved.filter(({ at }) => Date.now() - at < MOVED_MS);
@@ -60132,6 +61089,7 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
60132
61089
  let latest = scanned.board ?? board;
60133
61090
  if (trails) {
60134
61091
  latest = await scanBoard(root);
61092
+ scanned.unmeasured = placedRefs(scanned.board ?? board, latest, void 0, scanned.unmeasured);
60135
61093
  scanned.board = latest;
60136
61094
  hub.broadcast({
60137
61095
  type: "board",
@@ -60222,10 +61180,12 @@ async function pushBatch(root, tokens, paths, { hub, findings, rendered, deliver
60222
61180
  try {
60223
61181
  await landReserved(root, /* @__PURE__ */ new Date()).catch(() => []);
60224
61182
  board = await scanBoard(root);
60225
- const previous = scanned.board;
60226
- scanned.board = board;
61183
+ const { board: previous, unmeasured } = scanned;
60227
61184
  own = ownFileRefs(board, paths);
60228
- placed = previous ? placedRefs(previous, board, paths).filter((ref) => !own.includes(ref)) : [];
61185
+ placed = previous ? placedRefs(previous, board, paths, unmeasured).filter((ref) => !own.includes(ref)) : [];
61186
+ const measuring = /* @__PURE__ */ new Set([...own, ...placed]);
61187
+ scanned.board = board;
61188
+ scanned.unmeasured = previous ? placedRefs(previous, board, void 0, unmeasured).filter((ref) => !measuring.has(ref)) : [];
60229
61189
  relisted = previous ? relistedRefs(previous, board) : [];
60230
61190
  rekitted = previous ? rekittedRefs(previous, board) : [];
60231
61191
  if (await hug.now(board, [...own, ...placed]).catch(() => false)) {
@@ -60355,7 +61315,7 @@ async function pushNotes(root, paths, hub, delivery) {
60355
61315
  const parts = relative(root, path).split(sep);
60356
61316
  const [project, page, file] = parts;
60357
61317
  if (parts.length !== 3 || !project || !page || !file) continue;
60358
- const notes = file === NOTES_FILE$2;
61318
+ const notes = file === NOTES_FILE$1;
60359
61319
  if (!notes && !file.endsWith(".html")) continue;
60360
61320
  const key = `${project}/${page}`;
60361
61321
  pages.set(key, {
@@ -60687,6 +61647,7 @@ function createProgram(context) {
60687
61647
  registerProject(program, context);
60688
61648
  registerKit(program, context);
60689
61649
  registerImage(program, context);
61650
+ registerModel(program, context);
60690
61651
  registerPage(program, context);
60691
61652
  registerFrame(program, faced);
60692
61653
  registerEdit(program, context);