@marver-design/marver 0.26.0 → 0.26.1

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.
Files changed (44) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +2 -2
  3. package/dist/{anchor-check-Dg5xpNnU.mjs → anchor-check-l-ny3UzH.mjs} +1 -1
  4. package/dist/{audio-CmSRYFEs.mjs → audio-Dw1lfMdb.mjs} +14 -0
  5. package/dist/{bake-DtVlm0_F.mjs → bake-C-awKgLA.mjs} +1 -1
  6. package/dist/{build-C_gUgcdC.mjs → build-BDRiO_mP.mjs} +3 -3
  7. package/dist/{capture-CrqvU_jh.mjs → capture-vadKjuCo.mjs} +2 -1
  8. package/dist/cli.mjs +6 -6
  9. package/dist/{daemon-DZo6o3rU.mjs → daemon-DL6Fwq6D.mjs} +394 -270
  10. package/dist/{dev-_Nlsc6v9.mjs → dev-Bw_qYWWq.mjs} +24 -11
  11. package/dist/{marks-NQi0wZJ4.mjs → marks-DyWMv_Z1.mjs} +1 -1
  12. package/dist/perf-C75MZ73h.mjs +167 -0
  13. package/dist/perf-jam-BU3TVrZu.mjs +239 -0
  14. package/dist/{plugin-CTD0rydA.mjs → plugin-DkGmZs_r.mjs} +42 -22
  15. package/dist/{poster-ChjXGTS5.mjs → poster-BdtSKMDm.mjs} +2 -1
  16. package/dist/{publish-bakes-CEP_2NRc.mjs → publish-bakes-9RzRToXV.mjs} +2 -2
  17. package/dist/{queue-BuiCKSX1.mjs → queue-29ok5_eZ.mjs} +2 -2
  18. package/dist/{session-qZWKt_VA.mjs → session-BAaJsK5c.mjs} +1 -1
  19. package/dist/{shot-DqcxJibP.mjs → shot-DQeR_Pfn.mjs} +337 -19
  20. package/dist/shot-XQV7HC9A.mjs +139 -0
  21. package/dist/speech-worker.mjs +40 -5
  22. package/docs/jam-session.md +24 -7
  23. package/docs/live-jam.md +8 -0
  24. package/package.json +1 -1
  25. package/src/client/frame-host/inspect.js +8 -3
  26. package/src/client/frame-host/keys.js +6 -2
  27. package/src/client/shell/App.tsx +8 -4
  28. package/src/client/shell/JamSurface.tsx +9 -3
  29. package/src/client/shell/Play.tsx +11 -7
  30. package/src/client/shell/Toolbar.tsx +5 -4
  31. package/src/client/shell/canvas/FrameNode.tsx +3 -2
  32. package/src/client/shell/icons.tsx +2 -0
  33. package/src/client/shell/jam-capture.ts +77 -11
  34. package/src/client/shell/jam-keys.ts +47 -18
  35. package/src/client/shell/jam-lane.tsx +46 -5
  36. package/src/client/shell/jam-panel.tsx +63 -13
  37. package/src/client/shell/jam-state.ts +48 -6
  38. package/src/client/shell/jam-surface-parts.tsx +10 -6
  39. package/src/client/shell/store.ts +14 -5
  40. package/src/client/shell/styles.css +28 -8
  41. package/src/client/stage/main.tsx +2 -0
  42. package/templates/instructions/jam.md +5 -3
  43. package/dist/perf-D6VmmJ2q.mjs +0 -68
  44. package/dist/shot-CNbHoZ6H.mjs +0 -86
@@ -1,9 +1,11 @@
1
1
  import { a as ROUTE, o as slideSize } from "./cli.mjs";
2
+ import { t as logJam } from "./perf-jam-BU3TVrZu.mjs";
2
3
  import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
4
  import { join } from "node:path";
4
5
  import { randomBytes } from "node:crypto";
5
6
  import { availableParallelism, tmpdir } from "node:os";
6
7
  import { execFileSync, spawn } from "node:child_process";
8
+ import { createInflate } from "node:zlib";
7
9
  //#region src/server/cdp.ts
8
10
  /**
9
11
  * A headless Chrome driven over CDP through Chrome's own debugging PIPE - fds 3 (we write,
@@ -259,6 +261,153 @@ var Browser = class Browser {
259
261
  }
260
262
  };
261
263
  //#endregion
264
+ //#region src/server/stale.ts
265
+ /**
266
+ * A guard for one known corruption of headless Chrome's screenshots (#14, #24) - not a proof that a picture is right.
267
+ *
268
+ * `Page.captureScreenshot` with a clip resizes the tab's native view to clip x scale, asks for a redraw and copies the
269
+ * view's surface; when the copy wins the race against the resize it gets the old surface, smaller than asked, and
270
+ * Chrome fills the request by tiling it (page_handler.cc: ScreenshotCaptured -> SkBitmapOperations::CreateTiledBitmap).
271
+ * So every pixel (x, y) of a stale picture equals pixel (x mod w0, y mod h0), w0 x h0 being the native view in device px.
272
+ *
273
+ * The image is streamed row by row - inflated, unfiltered, the last h0 rows kept - and the check stops at the first row
274
+ * that breaks the repeat: a real picture costs its first row or two, and only a true repeat is read to the end (two
275
+ * identical panels over different content are clean). What it reads is what Chrome writes: 8-bit RGB/RGBA, not
276
+ * interlaced, filters 0-4, alpha compared too; anything else, or a deadline passed, is 'unknown' - never 'clean'.
277
+ */
278
+ const SIG = Buffer.from([
279
+ 137,
280
+ 80,
281
+ 78,
282
+ 71,
283
+ 13,
284
+ 10,
285
+ 26,
286
+ 10
287
+ ]);
288
+ /** Is this PNG the native view's old surface (w0 x h0 device px) tiled to the requested size? `deadline` (epoch ms):
289
+ * past it the check gives up ('unknown'). */
290
+ async function staleSurface(png, w0, h0, deadline = Infinity) {
291
+ if (!(w0 > 0 && h0 > 0) || png.length < 33 || !png.subarray(0, 8).equals(SIG)) return "unknown";
292
+ let pos = 8;
293
+ let w = 0, h = 0, channels = 0, ended = false;
294
+ const idat = [];
295
+ while (pos + 12 <= png.length) {
296
+ const len = png.readUInt32BE(pos);
297
+ const type = png.toString("latin1", pos + 4, pos + 8);
298
+ if (pos + 12 + len > png.length) return "unknown";
299
+ const data = png.subarray(pos + 8, pos + 8 + len);
300
+ if (pos === 8) {
301
+ if (type !== "IHDR" || len !== 13) return "unknown";
302
+ w = data.readUInt32BE(0);
303
+ h = data.readUInt32BE(4);
304
+ const depth = data[8], colour = data[9], compression = data[10], filtering = data[11], interlace = data[12];
305
+ if (depth !== 8 || colour !== 2 && colour !== 6 || compression !== 0 || filtering !== 0 || interlace !== 0 || !w || !h) return "unknown";
306
+ channels = colour === 6 ? 4 : 3;
307
+ } else if (type === "IDAT") idat.push(data);
308
+ else if (type === "IEND") {
309
+ ended = len === 0 && pos + 12 === png.length;
310
+ break;
311
+ }
312
+ pos += 12 + len;
313
+ }
314
+ if (!channels || !idat.length || !ended) return "unknown";
315
+ if (w <= w0 && h <= h0) return "clean";
316
+ const stride = w * channels;
317
+ const wide = w > w0, tall = h > h0;
318
+ const th = Math.min(h, h0), tw = Math.min(w, w0), shift = w0 * channels, n = (w - w0) * channels;
319
+ const ring = tall ? Array.from({ length: h0 }, () => Buffer.alloc(stride)) : [];
320
+ let prev = Buffer.alloc(stride), cur = Buffer.alloc(stride);
321
+ const first = Buffer.alloc(channels);
322
+ let varied = false;
323
+ /** One unfiltered row: true to go on, a verdict to stop. */
324
+ const check = (y, row) => {
325
+ if (y === 0) row.copy(first, 0, 0, channels);
326
+ if (y < th && !varied) {
327
+ for (let x = 0; x < tw; x++) if (row.compare(first, 0, channels, x * channels, (x + 1) * channels) !== 0) {
328
+ varied = true;
329
+ break;
330
+ }
331
+ }
332
+ if (wide && row.compare(row, 0, n, shift, shift + n) !== 0) return "clean";
333
+ if (tall) {
334
+ const slot = ring[y % h0];
335
+ if (y >= h0 && !row.equals(slot)) return "clean";
336
+ row.copy(slot);
337
+ }
338
+ if (y === th - 1 && !varied) return "clean";
339
+ return y === h - 1 ? "stale" : true;
340
+ };
341
+ return new Promise((resolve) => {
342
+ const z = createInflate();
343
+ let done = false;
344
+ const finish = (v) => {
345
+ if (done) return;
346
+ done = true;
347
+ z.removeAllListeners();
348
+ z.on("error", () => {});
349
+ z.destroy();
350
+ resolve(v);
351
+ };
352
+ const raw = Buffer.alloc(stride + 1);
353
+ let fill = 0, y = 0;
354
+ z.on("data", (c) => {
355
+ if (done) return;
356
+ if (Date.now() > deadline) return finish("unknown");
357
+ let i = 0;
358
+ while (i < c.length && !done) {
359
+ const take = Math.min(stride + 1 - fill, c.length - i);
360
+ c.copy(raw, fill, i, i + take);
361
+ fill += take;
362
+ i += take;
363
+ if (fill < stride + 1) break;
364
+ fill = 0;
365
+ if (!unfilterRow(raw, prev, cur, channels)) return finish("unknown");
366
+ const v = check(y, cur);
367
+ if (v !== true) return finish(v);
368
+ const t = prev;
369
+ prev = cur;
370
+ cur = t;
371
+ y++;
372
+ }
373
+ });
374
+ z.on("end", () => finish("unknown"));
375
+ z.on("error", () => finish("unknown"));
376
+ let k = 0;
377
+ const feed = () => {
378
+ while (!done && k < idat.length) if (!z.write(idat[k++])) {
379
+ z.once("drain", feed);
380
+ return;
381
+ }
382
+ if (!done && k >= idat.length) z.end();
383
+ };
384
+ feed();
385
+ });
386
+ }
387
+ /** One row of PNG filter 0-4 (`raw[0]` the filter byte) into `out`, given the row above; false on any other filter. */
388
+ function unfilterRow(raw, up, out, bpp) {
389
+ const f = raw[0];
390
+ if (f > 4) return false;
391
+ const len = out.length;
392
+ for (let i = 0; i < len; i++) {
393
+ const x = raw[i + 1];
394
+ const a = i >= bpp ? out[i - bpp] : 0;
395
+ const b = up[i];
396
+ const c = i >= bpp ? up[i - bpp] : 0;
397
+ let v;
398
+ if (f === 0) v = x;
399
+ else if (f === 1) v = x + a;
400
+ else if (f === 2) v = x + b;
401
+ else if (f === 3) v = x + (a + b >> 1);
402
+ else {
403
+ const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c);
404
+ v = x + (pa <= pb && pa <= pc ? a : pb <= pc ? b : c);
405
+ }
406
+ out[i] = v & 255;
407
+ }
408
+ return true;
409
+ }
410
+ //#endregion
262
411
  //#region src/server/shot.ts
263
412
  /**
264
413
  * Frame screenshots without a dependency - the system's own Chrome, driven over CDP through
@@ -314,6 +463,17 @@ function planShot(frame, viewports, override = {}) {
314
463
  fullHeight: false
315
464
  };
316
465
  }
466
+ /** A shot's timing line (spec 27a Part D): its frame, scale, time, retakes - kept on a failure too - and an outcome code. */
467
+ function shotEvent(frameId, askedScale, result) {
468
+ return {
469
+ kind: "shot",
470
+ frame: frameId,
471
+ scale: result.ok ? result.scale : askedScale,
472
+ ms: result.ms,
473
+ recaptures: result.recaptures ?? 0,
474
+ outcome: result.ok ? /not checked for a stale surface/.test(result.note ?? "") ? "unchecked" : "ok" : result.error === STALE ? "stale" : /timed out/.test(result.error) ? "timeout" : "error"
475
+ };
476
+ }
317
477
  /** Resolve a frame from the manifest and screenshot it - the shared core behind BOTH
318
478
  * transports (the HTTP /api/shot endpoint and the file-drop inbox), so they validate and
319
479
  * name output identically. `origin` is the dev server's own base URL. */
@@ -334,8 +494,8 @@ async function shootFrame(opts) {
334
494
  };
335
495
  const plan = planShot(frame, viewports, size);
336
496
  if (frame.kind !== "html") try {
337
- const { scanAssetRefs } = await import("./build-C_gUgcdC.mjs");
338
- const { ensurePoster } = await import("./poster-ChjXGTS5.mjs");
497
+ const { scanAssetRefs } = await import("./build-BDRiO_mP.mjs");
498
+ const { ensurePoster } = await import("./poster-BdtSKMDm.mjs");
339
499
  const refs = scanAssetRefs(readFileSync(join(root, frame.file), "utf8"), frame.file);
340
500
  for (const r of refs) if (r.endsWith(".poster.png")) await ensurePoster(join(root, "design", "assets"), r.slice(0, -11));
341
501
  } catch {}
@@ -357,9 +517,13 @@ async function shootFrame(opts) {
357
517
  scale
358
518
  };
359
519
  const result = browser ? await captureIn(req, browser) : await capture(req);
520
+ logJam(root, shotEvent(frameId, scale, result));
360
521
  if (!result.ok) {
361
522
  rmSync(tmp, { force: true });
362
- return result;
523
+ return {
524
+ ok: false,
525
+ error: result.error
526
+ };
363
527
  }
364
528
  const rel = relFor(result.scale);
365
529
  try {
@@ -386,7 +550,8 @@ async function shootFrame(opts) {
386
550
  scale: result.scale,
387
551
  ...result.truncated ? { truncated: true } : {},
388
552
  ...result.unsettled ? { unsettled: true } : {},
389
- ...result.note ? { note: result.note } : {}
553
+ ...result.note ? { note: result.note } : {},
554
+ recaptures: result.recaptures
390
555
  };
391
556
  }
392
557
  function manifestFrame(root, frameId) {
@@ -673,13 +838,46 @@ const AREA = 64e6;
673
838
  const fits = (w, h, dsf) => w * dsf <= 16384 && h * dsf <= 16384 && w * h * dsf * dsf <= 64e6;
674
839
  /** The tallest CSS height a full-height capture of `width` can hold at `dsf`. */
675
840
  const capFor = (width, dsf) => Math.max(1, Math.min(Math.floor(SURFACE / dsf), Math.floor(AREA / (width * dsf * dsf))));
676
- async function captureIn({ url, width, height, out, fullHeight = false, timeoutMs = 3e4, scale: wantScale = 2, clip }, b) {
841
+ /** The windows live captures hold, per browser, until their tab is closed - and how many live captures have a window
842
+ * nobody could name. A capture sizes its window only when it is surely its own: no other live capture in it, and no
843
+ * live capture whose window is unknown. */
844
+ const live = /* @__PURE__ */ new WeakMap();
845
+ const liveFor = (b) => {
846
+ let l = live.get(b);
847
+ if (!l) {
848
+ l = {
849
+ windows: /* @__PURE__ */ new Map(),
850
+ unknown: 0
851
+ };
852
+ live.set(b, l);
853
+ }
854
+ return l;
855
+ };
856
+ /** Test seams - never set outside tests: what an attempt returns (to inject Chrome's stale surface), whether a capture
857
+ * gets its own window and may size it, each sizing seen, and a shorter watchdog. */
858
+ const shotSeams = {};
859
+ /** A retake, or the 1x attempt, starts only with this much of the shot's deadline left. */
860
+ const RETRY_LEFT = 3e3;
861
+ const STALE = "Chrome returned a stale surface (the picture came back tiled) - shoot it again";
862
+ /** One capture in a browser it may share; the result carries the capture's own time (`ms` - not its wait for a
863
+ * browser slot), which `shootFrame` logs and never passes on. */
864
+ async function captureIn(req, b) {
865
+ const t0 = performance.now();
866
+ return {
867
+ ...await captureOnce(req, b),
868
+ ms: Math.round(performance.now() - t0)
869
+ };
870
+ }
871
+ async function captureOnce({ url, width, height, out, fullHeight = false, timeoutMs = 3e4, scale: wantScale = 2, clip }, b) {
872
+ let recaptures = 0;
677
873
  let scale = Math.min(4, Math.max(1, Math.round(wantScale)));
678
874
  while (scale > 1 && !fits(width, height, scale)) scale--;
679
875
  const me = {};
680
876
  let watchdog;
681
877
  let targetId;
682
878
  let sessionId;
879
+ let windowId;
880
+ let registered = null;
683
881
  let off = () => {};
684
882
  try {
685
883
  let lastException = "";
@@ -690,15 +888,74 @@ async function captureIn({ url, width, height, out, fullHeight = false, timeoutM
690
888
  timer = setTimeout(() => rej(/* @__PURE__ */ new Error(`${method} timed out`)), ms);
691
889
  })]).finally(() => clearTimeout(timer));
692
890
  };
693
- const hardBy = Date.now() + timeoutMs + 15e3;
694
- watchdog = setTimeout(() => b.abort(me, "the shot timed out"), timeoutMs + 15e3);
891
+ const watchMs = shotSeams.watchdogMs ?? timeoutMs + 15e3;
892
+ const hardBy = Date.now() + watchMs;
893
+ watchdog = setTimeout(() => b.abort(me, "the shot timed out"), watchMs);
894
+ const left = () => hardBy - Date.now();
895
+ const bounded = (p, ms) => {
896
+ let t;
897
+ return Promise.race([p.catch(() => null), new Promise((r) => {
898
+ t = setTimeout(() => r(null), Math.max(1, ms));
899
+ })]).finally(() => clearTimeout(t));
900
+ };
695
901
  const RESERVE = 21e3;
696
902
  const discretionary = () => hardBy - RESERVE - Date.now();
697
- targetId = (await send("Target.createTarget", { url: "about:blank" })).targetId;
903
+ targetId = (await send("Target.createTarget", {
904
+ url: "about:blank",
905
+ newWindow: shotSeams.newWindow ?? true
906
+ })).targetId;
698
907
  sessionId = (await send("Target.attachToTarget", {
699
908
  targetId,
700
909
  flatten: true
701
910
  })).sessionId;
911
+ const lv = liveFor(b);
912
+ const win = shotSeams.noWindow ? null : await bounded(send("Browser.getWindowForTarget", { targetId }), 1e3);
913
+ if (typeof win?.windowId === "number") {
914
+ windowId = win.windowId;
915
+ lv.windows.set(windowId, (lv.windows.get(windowId) ?? 0) + 1);
916
+ registered = "window";
917
+ } else {
918
+ lv.unknown++;
919
+ registered = "unknown";
920
+ }
921
+ let view = null;
922
+ const v0 = (await bounded(send("Runtime.evaluate", {
923
+ expression: "[innerWidth, innerHeight, devicePixelRatio]",
924
+ returnByValue: true
925
+ }, sessionId), 1e3))?.result?.value;
926
+ if (windowId !== void 0 && Array.isArray(v0) && v0.length === 3 && v0.every((x) => typeof x === "number" && x > 0) && typeof win?.bounds?.width === "number" && typeof win?.bounds?.height === "number") view = {
927
+ dpr: v0[2],
928
+ decoW: win.bounds.width - v0[0],
929
+ decoH: win.bounds.height - v0[1]
930
+ };
931
+ const viewNow = async () => {
932
+ if (!view || windowId === void 0) return null;
933
+ const r = await bounded(send("Browser.getWindowBounds", { windowId }), Math.min(1e3, left()));
934
+ const bw = r?.bounds?.width, bh = r?.bounds?.height;
935
+ return typeof bw === "number" && typeof bh === "number" ? {
936
+ w: Math.round((bw - view.decoW) * view.dpr),
937
+ h: Math.round((bh - view.decoH) * view.dpr)
938
+ } : null;
939
+ };
940
+ if (!fullHeight && !clip && view && windowId !== void 0 && shotSeams.resize !== false && lv.windows.get(windowId) === 1 && lv.unknown === 0) {
941
+ const cw = Math.round(width * scale / view.dpr), ch = Math.round(height * scale / view.dpr);
942
+ shotSeams.onResize?.(windowId);
943
+ const ok = await bounded(send("Browser.setWindowBounds", {
944
+ windowId,
945
+ bounds: {
946
+ width: cw + view.decoW,
947
+ height: ch + view.decoH
948
+ }
949
+ }).then(() => true), 1e3) === true;
950
+ for (const by = Date.now() + 500; ok && Date.now() < by;) {
951
+ const v = (await bounded(send("Runtime.evaluate", {
952
+ expression: "[innerWidth, innerHeight]",
953
+ returnByValue: true
954
+ }, sessionId), by - Date.now()))?.result?.value;
955
+ if (v && v[0] === cw && v[1] === ch) break;
956
+ await new Promise((r2) => setTimeout(r2, 20));
957
+ }
958
+ }
702
959
  off = b.on((m) => {
703
960
  if (m.sessionId === sessionId && m.method === "Runtime.exceptionThrown") {
704
961
  const d = m.params?.exceptionDetails;
@@ -897,18 +1154,71 @@ async function captureIn({ url, width, height, out, fullHeight = false, timeoutM
897
1154
  capW = Math.max(1, Math.round(box.w));
898
1155
  capH = Math.max(1, Math.round(box.h));
899
1156
  }
900
- const shot = await sendD("Page.captureScreenshot", {
901
- format: "png",
902
- captureBeyondViewport: true,
903
- clip: {
904
- x: capX,
905
- y: capY,
1157
+ let attempt = 0;
1158
+ const take = async () => {
1159
+ const v = await viewNow();
1160
+ const shot = await sendD("Page.captureScreenshot", {
1161
+ format: "png",
1162
+ captureBeyondViewport: true,
1163
+ clip: {
1164
+ x: capX,
1165
+ y: capY,
1166
+ width: capW,
1167
+ height: capH,
1168
+ scale: 1
1169
+ }
1170
+ }, Math.max(1e3, Math.min(15e3, left() - 500)));
1171
+ let png = Buffer.from(String(shot.data), "base64");
1172
+ if (shotSeams.capture) png = shotSeams.capture(png, {
1173
+ attempt,
1174
+ view: v,
1175
+ windowId
1176
+ });
1177
+ attempt++;
1178
+ return {
1179
+ png,
1180
+ view: v
1181
+ };
1182
+ };
1183
+ const twoFrames = () => sendD("Runtime.evaluate", {
1184
+ expression: "new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(true))))",
1185
+ awaitPromise: true,
1186
+ returnByValue: true
1187
+ }, Math.max(1, Math.min(1e3, left() - RETRY_LEFT))).catch(() => null);
1188
+ const judge = (a) => a.view ? staleSurface(a.png, a.view.w, a.view.h, hardBy - 1e3) : Promise.resolve("unknown");
1189
+ let shotNow = await take();
1190
+ let verdict = await judge(shotNow);
1191
+ const retryLeft = shotSeams.retryLeftMs ?? RETRY_LEFT;
1192
+ while (verdict === "stale" && recaptures < 2 && left() > retryLeft) {
1193
+ recaptures++;
1194
+ await twoFrames();
1195
+ shotNow = await take();
1196
+ verdict = await judge(shotNow);
1197
+ }
1198
+ if (verdict === "stale" && fullHeight && scale > 1 && left() > retryLeft) {
1199
+ const was = scale;
1200
+ await sendD("Emulation.setDeviceMetricsOverride", {
906
1201
  width: capW,
907
1202
  height: capH,
908
- scale: 1
1203
+ deviceScaleFactor: 1,
1204
+ mobile: false
1205
+ }, Math.max(1, Math.min(5e3, left() - 1e3)));
1206
+ await twoFrames();
1207
+ recaptures++;
1208
+ shotNow = await take();
1209
+ verdict = await judge(shotNow);
1210
+ if (verdict !== "stale") {
1211
+ scale = 1;
1212
+ note = `${note ? note + "; " : ""}came back tiled at ${was}x - captured at 1x`;
909
1213
  }
910
- }, 15e3);
911
- writeFileSync(out, Buffer.from(String(shot.data), "base64"));
1214
+ }
1215
+ if (verdict === "stale") return {
1216
+ ok: false,
1217
+ error: STALE,
1218
+ recaptures
1219
+ };
1220
+ if (verdict === "unknown") note = `${note ? note + "; " : ""}not checked for a stale surface`;
1221
+ writeFileSync(out, shotNow.png);
912
1222
  const unsettled = !settled;
913
1223
  if (unsettled) note = `${note ? note + "; " : ""}captured before the frame settled - images, charts or diagrams may be missing; shoot it alone or lower MARVER_SHOT_CONCURRENCY`;
914
1224
  return {
@@ -918,12 +1228,14 @@ async function captureIn({ url, width, height, out, fullHeight = false, timeoutM
918
1228
  scale,
919
1229
  ...truncated ? { truncated: true } : {},
920
1230
  ...unsettled ? { unsettled: true } : {},
921
- ...note ? { note } : {}
1231
+ ...note ? { note } : {},
1232
+ recaptures
922
1233
  };
923
1234
  } catch (err) {
924
1235
  return {
925
1236
  ok: false,
926
- error: err.message
1237
+ error: err.message,
1238
+ ...recaptures ? { recaptures } : {}
927
1239
  };
928
1240
  } finally {
929
1241
  if (watchdog) clearTimeout(watchdog);
@@ -935,6 +1247,12 @@ async function captureIn({ url, width, height, out, fullHeight = false, timeoutM
935
1247
  })]);
936
1248
  clearTimeout(t);
937
1249
  }
1250
+ const lv = liveFor(b);
1251
+ if (registered === "window" && windowId !== void 0) {
1252
+ const n = (lv.windows.get(windowId) ?? 1) - 1;
1253
+ if (n > 0) lv.windows.set(windowId, n);
1254
+ else lv.windows.delete(windowId);
1255
+ } else if (registered === "unknown") lv.unknown = Math.max(0, lv.unknown - 1);
938
1256
  b.abort(me, "the shot finished");
939
1257
  }
940
1258
  }
@@ -0,0 +1,139 @@
1
+ import { r as NAME } from "./cli.mjs";
2
+ import { i as readDevInfo } from "./work-F5u-twpJ.mjs";
3
+ import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { randomBytes } from "node:crypto";
6
+ //#region src/cli/shot.ts
7
+ /**
8
+ * `marver shot <scene/frame> [...]`, `--scene <name>`, `--all` - render frames headless and
9
+ * print the PNG paths, one per line, in the order asked.
10
+ *
11
+ * The shell-ful agents' door into the same verify loop jam teaches: build, shoot, LOOK. One
12
+ * frame goes through /api/shot; several, a scene or everything go through /api/shots as ONE
13
+ * operation (one browser, several frames at a time), so shooting a scene costs about what
14
+ * shooting a frame did. shot.ts (server) has the capture story.
15
+ */
16
+ /** The fetch never reached the server: refused, unreachable, or forbidden by a sandbox (Codex's blocks the network,
17
+ * localhost included). Only these move a shot to the file inbox - never an HTTP answer, never a failure after the
18
+ * request went out. */
19
+ const CONNECT = /* @__PURE__ */ new Set([
20
+ "ECONNREFUSED",
21
+ "EPERM",
22
+ "EACCES",
23
+ "EHOSTUNREACH",
24
+ "ENETUNREACH",
25
+ "EADDRNOTAVAIL"
26
+ ]);
27
+ function cannotConnect(err) {
28
+ const cause = err?.cause;
29
+ if (!cause) return false;
30
+ if (Array.isArray(cause.errors) && cause.errors.length) return cause.errors.every((e) => !!e?.code && CONNECT.has(e.code));
31
+ return !!cause.code && CONNECT.has(cause.code);
32
+ }
33
+ /** The same request through the file inbox the dev server watches (design/.local/shots): a name of its own, written
34
+ * whole, its own result read and both files removed. Waiting stops at `ms` - it does not cancel; a request still
35
+ * unclaimed then is removed, so it never runs later. */
36
+ async function viaInbox(root, spec, ms) {
37
+ const inbox = join(root, "design", ".local", "shots");
38
+ const name = `cli-${randomBytes(8).toString("hex")}`;
39
+ const request = join(inbox, `${name}.request.json`), result = join(inbox, `${name}.result.json`);
40
+ try {
41
+ const tmp = join(inbox, `.${name}.tmp`);
42
+ writeFileSync(tmp, JSON.stringify(spec));
43
+ renameSync(tmp, request);
44
+ } catch (err) {
45
+ throw new Error(`could not reach \`${NAME} dev\` (the network is blocked here) and could not write to design/.local/shots - ${err.message}`);
46
+ }
47
+ for (const by = Date.now() + ms; Date.now() < by;) {
48
+ if (existsSync(result)) try {
49
+ const data = JSON.parse(readFileSync(result, "utf8"));
50
+ rmSync(result, { force: true });
51
+ return data;
52
+ } catch {}
53
+ await new Promise((r) => setTimeout(r, 150));
54
+ }
55
+ rmSync(request, { force: true });
56
+ throw new Error(`stopped waiting for \`${NAME} dev\` after ${Math.round(ms / 1e3)} s (asked through design/.local/shots - the network is blocked here)`);
57
+ }
58
+ async function shotCommand(root, frames, opts) {
59
+ const usage = `${NAME} shot <scene/frame ...> | --scene <name> | --all [--theme <name>] [--scale 1-4] [--json]`;
60
+ if ([
61
+ frames.length > 0,
62
+ !!opts.scene,
63
+ !!opts.all
64
+ ].filter(Boolean).length !== 1) throw new Error(`name the frames, one way: ${usage}`);
65
+ const info = readDevInfo(root);
66
+ if (!info) throw new Error(`\`${NAME} dev\` is not running in this repo (design/.local/dev.json not found) - start it first.`);
67
+ const scale = opts.scale != null ? Number(opts.scale) : void 0;
68
+ const theme = opts.theme;
69
+ const single = frames.length === 1 && !opts.scene && !opts.all;
70
+ const sel = single ? { frame: frames[0] } : opts.all ? { all: true } : opts.scene ? { scene: opts.scene } : { frames };
71
+ let data;
72
+ try {
73
+ let res;
74
+ if (single) {
75
+ const qs = new URLSearchParams({
76
+ frame: frames[0],
77
+ ...theme ? { theme } : {},
78
+ ...scale != null ? { scale: String(scale) } : {}
79
+ });
80
+ res = await fetch(`http://localhost:${info.port}/__mv/api/shot?${qs}`, { headers: { "x-mv-work": info.token } });
81
+ } else res = await fetch(`http://localhost:${info.port}/__mv/api/shots`, {
82
+ method: "POST",
83
+ headers: {
84
+ "x-mv-work": info.token,
85
+ "content-type": "application/json"
86
+ },
87
+ body: JSON.stringify({
88
+ ...sel,
89
+ ...theme ? { theme } : {},
90
+ ...scale != null ? { scale } : {}
91
+ })
92
+ });
93
+ data = await res.json().catch(() => ({}));
94
+ if (!res.ok) throw Object.assign(new Error(data.error ?? `shot failed (${res.status})`), { answered: true });
95
+ } catch (err) {
96
+ if (err.answered) throw err;
97
+ if (!cannotConnect(err)) throw new Error(`could not reach \`${NAME} dev\` on port ${info.port} - is it still running?`);
98
+ const waitMs = Number(process.env.MARVER_SHOT_INBOX_WAIT_MS) > 0 ? Number(process.env.MARVER_SHOT_INBOX_WAIT_MS) : single ? 12e4 : 6e5;
99
+ data = await viaInbox(root, {
100
+ ...sel,
101
+ ...theme ? { theme } : {},
102
+ ...scale != null ? { scale } : {}
103
+ }, waitMs);
104
+ if (data.ok === false) throw new Error(String(data.error ?? "shot failed"));
105
+ }
106
+ const one = data;
107
+ const results = single ? [one.path ? {
108
+ frame: frames[0],
109
+ ok: true,
110
+ path: one.path,
111
+ width: one.width,
112
+ height: one.height,
113
+ scale: one.scale,
114
+ ...one.truncated ? { truncated: true } : {},
115
+ ...one.unsettled ? { unsettled: true } : {},
116
+ ...one.note ? { note: one.note } : {},
117
+ recaptures: one.recaptures ?? 0
118
+ } : {
119
+ frame: frames[0],
120
+ ok: false,
121
+ error: one.error ?? "shot failed"
122
+ }] : data.results ?? [];
123
+ if (opts.json) {
124
+ console.log(JSON.stringify({ results }, null, 2));
125
+ if (results.some((r) => !r.ok)) process.exitCode = 1;
126
+ return;
127
+ }
128
+ let failed = false;
129
+ for (const r of results) if (r.ok) {
130
+ console.log(r.path);
131
+ if (r.note) console.error(`${r.frame}: ${r.note}`);
132
+ } else {
133
+ failed = true;
134
+ console.error(`${r.frame}: ${r.error}`);
135
+ }
136
+ if (failed) process.exitCode = 1;
137
+ }
138
+ //#endregion
139
+ export { shotCommand };