@marver-design/marver 0.26.0 → 0.27.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.
Files changed (96) hide show
  1. package/CHANGELOG.md +158 -0
  2. package/README.md +10 -5
  3. package/dist/{anchor-check-Dg5xpNnU.mjs → anchor-check-ChdDqL5z.mjs} +1 -1
  4. package/dist/{audio-CmSRYFEs.mjs → audio-Dw1lfMdb.mjs} +14 -0
  5. package/dist/{bake-DtVlm0_F.mjs → bake-DM_uWgAA.mjs} +1 -1
  6. package/dist/{boards-DYG22tOe.mjs → boards-DlTcpF47.mjs} +1 -1
  7. package/dist/{build-C_gUgcdC.mjs → build-DZnFysGU.mjs} +4 -4
  8. package/dist/{capture-CrqvU_jh.mjs → capture-vadKjuCo.mjs} +2 -1
  9. package/dist/cli.mjs +28 -16
  10. package/dist/{comments-BqXua-XL.mjs → comments-DxOkCSNE.mjs} +4 -4
  11. package/dist/{daemon-DZo6o3rU.mjs → daemon-BSA0lV8d.mjs} +400 -274
  12. package/dist/detect-C0wpaePX.mjs +125 -0
  13. package/dist/dev-eQJhWsqg.mjs +1273 -0
  14. package/dist/dev-lock-C_FC70Mu.mjs +65 -0
  15. package/dist/exclusive-B1RtpeeP.mjs +150 -0
  16. package/dist/{init-D8DtrK_F.mjs → init-COD0x48i.mjs} +5 -3
  17. package/dist/{link-BNzLvdhI.mjs → link-DDXZVGtv.mjs} +20 -8
  18. package/dist/ls-D7O1G505.mjs +38 -0
  19. package/dist/{marks-NQi0wZJ4.mjs → marks-CWM3WJjc.mjs} +1 -1
  20. package/dist/perf-BWzQwZqj.mjs +369 -0
  21. package/dist/perf-BoDSkbEb.mjs +429 -0
  22. package/dist/perf-jam-D55U3FZK.mjs +242 -0
  23. package/dist/{plugin-CTD0rydA.mjs → plugin-C-E7omsh.mjs} +425 -66
  24. package/dist/{poster-ChjXGTS5.mjs → poster-Bx83ZYVK.mjs} +2 -1
  25. package/dist/{profile-WU9qcbIo.mjs → profile-Bh5Y5zpW.mjs} +1 -1
  26. package/dist/{publish-bakes-CEP_2NRc.mjs → publish-bakes-aljgm45S.mjs} +2 -2
  27. package/dist/{queue-BuiCKSX1.mjs → queue-CAM_vNmX.mjs} +3 -3
  28. package/dist/recover-t9Pno3u9.mjs +66 -0
  29. package/dist/{session-qZWKt_VA.mjs → session-BAaJsK5c.mjs} +1 -1
  30. package/dist/{share--oFJ1bCI.mjs → share-W5H3BNvP.mjs} +1 -1
  31. package/dist/shot-DoHLl6ig.mjs +139 -0
  32. package/dist/{shot-DqcxJibP.mjs → shot-LFhC-WYD.mjs} +343 -19
  33. package/dist/slots-DCDo3N0x.mjs +471 -0
  34. package/dist/speech-worker.mjs +40 -5
  35. package/dist/{sync-DKk-yT1V.mjs → sync-BQVlHZpx.mjs} +4 -3
  36. package/dist/{work-F5u-twpJ.mjs → work-Bp1p39kq.mjs} +4 -2
  37. package/dist/{work-VvX_JIgl.mjs → work-BroFwnup.mjs} +4 -2
  38. package/docs/boards-and-folders.md +3 -1
  39. package/docs/jam-session.md +78 -7
  40. package/docs/live-jam.md +8 -0
  41. package/docs/performance.md +262 -0
  42. package/package.json +2 -2
  43. package/src/client/content/index.tsx +3 -0
  44. package/src/client/content/video.tsx +6 -2
  45. package/src/client/frame-host/bridge.js +22 -6
  46. package/src/client/frame-host/inspect.js +8 -3
  47. package/src/client/frame-host/keys.js +6 -2
  48. package/src/client/frame-host/main.tsx +17 -5
  49. package/src/client/shell/App.tsx +188 -29
  50. package/src/client/shell/BoardList.tsx +5 -5
  51. package/src/client/shell/Comments.tsx +3 -2
  52. package/src/client/shell/JamSurface.tsx +13 -5
  53. package/src/client/shell/LockedApp.tsx +5 -5
  54. package/src/client/shell/Play.tsx +27 -15
  55. package/src/client/shell/Toolbar.tsx +17 -5
  56. package/src/client/shell/api.ts +206 -0
  57. package/src/client/shell/canvas/Canvas.tsx +30 -3
  58. package/src/client/shell/canvas/FrameNode.tsx +15 -5
  59. package/src/client/shell/canvas/admission.ts +8 -1
  60. package/src/client/shell/canvas/camera-broadcast.ts +15 -5
  61. package/src/client/shell/canvas/ctl.ts +2 -0
  62. package/src/client/shell/canvas/frame-registry.ts +28 -2
  63. package/src/client/shell/canvas/sleep.ts +4 -1
  64. package/src/client/shell/comments-store.ts +12 -4
  65. package/src/client/shell/goto.ts +22 -10
  66. package/src/client/shell/icons.tsx +2 -0
  67. package/src/client/shell/jam-capture.ts +96 -16
  68. package/src/client/shell/jam-keys.ts +51 -18
  69. package/src/client/shell/jam-lane.tsx +46 -5
  70. package/src/client/shell/jam-panel.tsx +66 -13
  71. package/src/client/shell/jam-queue.ts +3 -3
  72. package/src/client/shell/jam-session.tsx +14 -8
  73. package/src/client/shell/jam-state.ts +48 -6
  74. package/src/client/shell/jam-surface-parts.tsx +10 -6
  75. package/src/client/shell/jam-voice.ts +7 -5
  76. package/src/client/shell/legacy-links.ts +2 -2
  77. package/src/client/shell/main.tsx +4 -0
  78. package/src/client/shell/notes.ts +8 -1
  79. package/src/client/shell/perf.ts +69 -58
  80. package/src/client/shell/recorder-core.ts +183 -0
  81. package/src/client/shell/recorder.ts +565 -0
  82. package/src/client/shell/store.ts +268 -103
  83. package/src/client/shell/styles.css +54 -9
  84. package/src/client/stage/main.tsx +2 -0
  85. package/templates/AGENTS-embedded.md +22 -4
  86. package/templates/AGENTS-studio.md +22 -4
  87. package/templates/demo/dark.tsx +1 -1
  88. package/templates/demo/welcome.tsx +1 -1
  89. package/templates/instructions/jam.md +5 -3
  90. package/templates/instructions/welcome.md +6 -3
  91. package/dist/config-Cf7EjAMf.mjs +0 -292
  92. package/dist/dev-_Nlsc6v9.mjs +0 -742
  93. package/dist/dev-lock-DWSpa6nj.mjs +0 -179
  94. package/dist/perf-D6VmmJ2q.mjs +0 -68
  95. package/dist/perf-DPbLGhhO.mjs +0 -49
  96. 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-D55U3FZK.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,
@@ -41,12 +43,18 @@ const PROFILE_PREFIXES = ["mv-shot-", "mv-browser-"];
41
43
  function containerFlags(platform, uid) {
42
44
  return platform === "linux" && uid === 0 ? ["--no-sandbox", "--disable-dev-shm-usage"] : [];
43
45
  }
46
+ const FOREGROUND = [
47
+ "--disable-backgrounding-occluded-windows",
48
+ "--disable-renderer-backgrounding",
49
+ "--disable-background-timer-throttling"
50
+ ];
44
51
  const FLAGS = [
45
52
  ...process.env.MV_CHROME_HEADED ? [] : ["--headless=new"],
46
53
  "--hide-scrollbars",
47
54
  "--no-first-run",
48
55
  "--no-default-browser-check",
49
56
  "--disable-extensions",
57
+ ...FOREGROUND,
50
58
  ...containerFlags(process.platform, process.getuid?.()),
51
59
  ...process.env.MV_CHROME_FLAGS?.split(" ").filter(Boolean) ?? []
52
60
  ];
@@ -259,6 +267,153 @@ var Browser = class Browser {
259
267
  }
260
268
  };
261
269
  //#endregion
270
+ //#region src/server/stale.ts
271
+ /**
272
+ * A guard for one known corruption of headless Chrome's screenshots (#14, #24) - not a proof that a picture is right.
273
+ *
274
+ * `Page.captureScreenshot` with a clip resizes the tab's native view to clip x scale, asks for a redraw and copies the
275
+ * view's surface; when the copy wins the race against the resize it gets the old surface, smaller than asked, and
276
+ * Chrome fills the request by tiling it (page_handler.cc: ScreenshotCaptured -> SkBitmapOperations::CreateTiledBitmap).
277
+ * 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.
278
+ *
279
+ * The image is streamed row by row - inflated, unfiltered, the last h0 rows kept - and the check stops at the first row
280
+ * that breaks the repeat: a real picture costs its first row or two, and only a true repeat is read to the end (two
281
+ * identical panels over different content are clean). What it reads is what Chrome writes: 8-bit RGB/RGBA, not
282
+ * interlaced, filters 0-4, alpha compared too; anything else, or a deadline passed, is 'unknown' - never 'clean'.
283
+ */
284
+ const SIG = Buffer.from([
285
+ 137,
286
+ 80,
287
+ 78,
288
+ 71,
289
+ 13,
290
+ 10,
291
+ 26,
292
+ 10
293
+ ]);
294
+ /** Is this PNG the native view's old surface (w0 x h0 device px) tiled to the requested size? `deadline` (epoch ms):
295
+ * past it the check gives up ('unknown'). */
296
+ async function staleSurface(png, w0, h0, deadline = Infinity) {
297
+ if (!(w0 > 0 && h0 > 0) || png.length < 33 || !png.subarray(0, 8).equals(SIG)) return "unknown";
298
+ let pos = 8;
299
+ let w = 0, h = 0, channels = 0, ended = false;
300
+ const idat = [];
301
+ while (pos + 12 <= png.length) {
302
+ const len = png.readUInt32BE(pos);
303
+ const type = png.toString("latin1", pos + 4, pos + 8);
304
+ if (pos + 12 + len > png.length) return "unknown";
305
+ const data = png.subarray(pos + 8, pos + 8 + len);
306
+ if (pos === 8) {
307
+ if (type !== "IHDR" || len !== 13) return "unknown";
308
+ w = data.readUInt32BE(0);
309
+ h = data.readUInt32BE(4);
310
+ const depth = data[8], colour = data[9], compression = data[10], filtering = data[11], interlace = data[12];
311
+ if (depth !== 8 || colour !== 2 && colour !== 6 || compression !== 0 || filtering !== 0 || interlace !== 0 || !w || !h) return "unknown";
312
+ channels = colour === 6 ? 4 : 3;
313
+ } else if (type === "IDAT") idat.push(data);
314
+ else if (type === "IEND") {
315
+ ended = len === 0 && pos + 12 === png.length;
316
+ break;
317
+ }
318
+ pos += 12 + len;
319
+ }
320
+ if (!channels || !idat.length || !ended) return "unknown";
321
+ if (w <= w0 && h <= h0) return "clean";
322
+ const stride = w * channels;
323
+ const wide = w > w0, tall = h > h0;
324
+ const th = Math.min(h, h0), tw = Math.min(w, w0), shift = w0 * channels, n = (w - w0) * channels;
325
+ const ring = tall ? Array.from({ length: h0 }, () => Buffer.alloc(stride)) : [];
326
+ let prev = Buffer.alloc(stride), cur = Buffer.alloc(stride);
327
+ const first = Buffer.alloc(channels);
328
+ let varied = false;
329
+ /** One unfiltered row: true to go on, a verdict to stop. */
330
+ const check = (y, row) => {
331
+ if (y === 0) row.copy(first, 0, 0, channels);
332
+ if (y < th && !varied) {
333
+ for (let x = 0; x < tw; x++) if (row.compare(first, 0, channels, x * channels, (x + 1) * channels) !== 0) {
334
+ varied = true;
335
+ break;
336
+ }
337
+ }
338
+ if (wide && row.compare(row, 0, n, shift, shift + n) !== 0) return "clean";
339
+ if (tall) {
340
+ const slot = ring[y % h0];
341
+ if (y >= h0 && !row.equals(slot)) return "clean";
342
+ row.copy(slot);
343
+ }
344
+ if (y === th - 1 && !varied) return "clean";
345
+ return y === h - 1 ? "stale" : true;
346
+ };
347
+ return new Promise((resolve) => {
348
+ const z = createInflate();
349
+ let done = false;
350
+ const finish = (v) => {
351
+ if (done) return;
352
+ done = true;
353
+ z.removeAllListeners();
354
+ z.on("error", () => {});
355
+ z.destroy();
356
+ resolve(v);
357
+ };
358
+ const raw = Buffer.alloc(stride + 1);
359
+ let fill = 0, y = 0;
360
+ z.on("data", (c) => {
361
+ if (done) return;
362
+ if (Date.now() > deadline) return finish("unknown");
363
+ let i = 0;
364
+ while (i < c.length && !done) {
365
+ const take = Math.min(stride + 1 - fill, c.length - i);
366
+ c.copy(raw, fill, i, i + take);
367
+ fill += take;
368
+ i += take;
369
+ if (fill < stride + 1) break;
370
+ fill = 0;
371
+ if (!unfilterRow(raw, prev, cur, channels)) return finish("unknown");
372
+ const v = check(y, cur);
373
+ if (v !== true) return finish(v);
374
+ const t = prev;
375
+ prev = cur;
376
+ cur = t;
377
+ y++;
378
+ }
379
+ });
380
+ z.on("end", () => finish("unknown"));
381
+ z.on("error", () => finish("unknown"));
382
+ let k = 0;
383
+ const feed = () => {
384
+ while (!done && k < idat.length) if (!z.write(idat[k++])) {
385
+ z.once("drain", feed);
386
+ return;
387
+ }
388
+ if (!done && k >= idat.length) z.end();
389
+ };
390
+ feed();
391
+ });
392
+ }
393
+ /** One row of PNG filter 0-4 (`raw[0]` the filter byte) into `out`, given the row above; false on any other filter. */
394
+ function unfilterRow(raw, up, out, bpp) {
395
+ const f = raw[0];
396
+ if (f > 4) return false;
397
+ const len = out.length;
398
+ for (let i = 0; i < len; i++) {
399
+ const x = raw[i + 1];
400
+ const a = i >= bpp ? out[i - bpp] : 0;
401
+ const b = up[i];
402
+ const c = i >= bpp ? up[i - bpp] : 0;
403
+ let v;
404
+ if (f === 0) v = x;
405
+ else if (f === 1) v = x + a;
406
+ else if (f === 2) v = x + b;
407
+ else if (f === 3) v = x + (a + b >> 1);
408
+ else {
409
+ const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c);
410
+ v = x + (pa <= pb && pa <= pc ? a : pb <= pc ? b : c);
411
+ }
412
+ out[i] = v & 255;
413
+ }
414
+ return true;
415
+ }
416
+ //#endregion
262
417
  //#region src/server/shot.ts
263
418
  /**
264
419
  * Frame screenshots without a dependency - the system's own Chrome, driven over CDP through
@@ -314,6 +469,17 @@ function planShot(frame, viewports, override = {}) {
314
469
  fullHeight: false
315
470
  };
316
471
  }
472
+ /** A shot's timing line (spec 27a Part D): its frame, scale, time, retakes - kept on a failure too - and an outcome code. */
473
+ function shotEvent(frameId, askedScale, result) {
474
+ return {
475
+ kind: "shot",
476
+ frame: frameId,
477
+ scale: result.ok ? result.scale : askedScale,
478
+ ms: result.ms,
479
+ recaptures: result.recaptures ?? 0,
480
+ 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"
481
+ };
482
+ }
317
483
  /** Resolve a frame from the manifest and screenshot it - the shared core behind BOTH
318
484
  * transports (the HTTP /api/shot endpoint and the file-drop inbox), so they validate and
319
485
  * name output identically. `origin` is the dev server's own base URL. */
@@ -334,8 +500,8 @@ async function shootFrame(opts) {
334
500
  };
335
501
  const plan = planShot(frame, viewports, size);
336
502
  if (frame.kind !== "html") try {
337
- const { scanAssetRefs } = await import("./build-C_gUgcdC.mjs");
338
- const { ensurePoster } = await import("./poster-ChjXGTS5.mjs");
503
+ const { scanAssetRefs } = await import("./build-DZnFysGU.mjs");
504
+ const { ensurePoster } = await import("./poster-Bx83ZYVK.mjs");
339
505
  const refs = scanAssetRefs(readFileSync(join(root, frame.file), "utf8"), frame.file);
340
506
  for (const r of refs) if (r.endsWith(".poster.png")) await ensurePoster(join(root, "design", "assets"), r.slice(0, -11));
341
507
  } catch {}
@@ -357,9 +523,13 @@ async function shootFrame(opts) {
357
523
  scale
358
524
  };
359
525
  const result = browser ? await captureIn(req, browser) : await capture(req);
526
+ logJam(root, shotEvent(frameId, scale, result));
360
527
  if (!result.ok) {
361
528
  rmSync(tmp, { force: true });
362
- return result;
529
+ return {
530
+ ok: false,
531
+ error: result.error
532
+ };
363
533
  }
364
534
  const rel = relFor(result.scale);
365
535
  try {
@@ -386,7 +556,8 @@ async function shootFrame(opts) {
386
556
  scale: result.scale,
387
557
  ...result.truncated ? { truncated: true } : {},
388
558
  ...result.unsettled ? { unsettled: true } : {},
389
- ...result.note ? { note: result.note } : {}
559
+ ...result.note ? { note: result.note } : {},
560
+ recaptures: result.recaptures
390
561
  };
391
562
  }
392
563
  function manifestFrame(root, frameId) {
@@ -673,13 +844,46 @@ const AREA = 64e6;
673
844
  const fits = (w, h, dsf) => w * dsf <= 16384 && h * dsf <= 16384 && w * h * dsf * dsf <= 64e6;
674
845
  /** The tallest CSS height a full-height capture of `width` can hold at `dsf`. */
675
846
  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) {
847
+ /** The windows live captures hold, per browser, until their tab is closed - and how many live captures have a window
848
+ * nobody could name. A capture sizes its window only when it is surely its own: no other live capture in it, and no
849
+ * live capture whose window is unknown. */
850
+ const live = /* @__PURE__ */ new WeakMap();
851
+ const liveFor = (b) => {
852
+ let l = live.get(b);
853
+ if (!l) {
854
+ l = {
855
+ windows: /* @__PURE__ */ new Map(),
856
+ unknown: 0
857
+ };
858
+ live.set(b, l);
859
+ }
860
+ return l;
861
+ };
862
+ /** Test seams - never set outside tests: what an attempt returns (to inject Chrome's stale surface), whether a capture
863
+ * gets its own window and may size it, each sizing seen, and a shorter watchdog. */
864
+ const shotSeams = {};
865
+ /** A retake, or the 1x attempt, starts only with this much of the shot's deadline left. */
866
+ const RETRY_LEFT = 3e3;
867
+ const STALE = "Chrome returned a stale surface (the picture came back tiled) - shoot it again";
868
+ /** One capture in a browser it may share; the result carries the capture's own time (`ms` - not its wait for a
869
+ * browser slot), which `shootFrame` logs and never passes on. */
870
+ async function captureIn(req, b) {
871
+ const t0 = performance.now();
872
+ return {
873
+ ...await captureOnce(req, b),
874
+ ms: Math.round(performance.now() - t0)
875
+ };
876
+ }
877
+ async function captureOnce({ url, width, height, out, fullHeight = false, timeoutMs = 3e4, scale: wantScale = 2, clip }, b) {
878
+ let recaptures = 0;
677
879
  let scale = Math.min(4, Math.max(1, Math.round(wantScale)));
678
880
  while (scale > 1 && !fits(width, height, scale)) scale--;
679
881
  const me = {};
680
882
  let watchdog;
681
883
  let targetId;
682
884
  let sessionId;
885
+ let windowId;
886
+ let registered = null;
683
887
  let off = () => {};
684
888
  try {
685
889
  let lastException = "";
@@ -690,15 +894,74 @@ async function captureIn({ url, width, height, out, fullHeight = false, timeoutM
690
894
  timer = setTimeout(() => rej(/* @__PURE__ */ new Error(`${method} timed out`)), ms);
691
895
  })]).finally(() => clearTimeout(timer));
692
896
  };
693
- const hardBy = Date.now() + timeoutMs + 15e3;
694
- watchdog = setTimeout(() => b.abort(me, "the shot timed out"), timeoutMs + 15e3);
897
+ const watchMs = shotSeams.watchdogMs ?? timeoutMs + 15e3;
898
+ const hardBy = Date.now() + watchMs;
899
+ watchdog = setTimeout(() => b.abort(me, "the shot timed out"), watchMs);
900
+ const left = () => hardBy - Date.now();
901
+ const bounded = (p, ms) => {
902
+ let t;
903
+ return Promise.race([p.catch(() => null), new Promise((r) => {
904
+ t = setTimeout(() => r(null), Math.max(1, ms));
905
+ })]).finally(() => clearTimeout(t));
906
+ };
695
907
  const RESERVE = 21e3;
696
908
  const discretionary = () => hardBy - RESERVE - Date.now();
697
- targetId = (await send("Target.createTarget", { url: "about:blank" })).targetId;
909
+ targetId = (await send("Target.createTarget", {
910
+ url: "about:blank",
911
+ newWindow: shotSeams.newWindow ?? true
912
+ })).targetId;
698
913
  sessionId = (await send("Target.attachToTarget", {
699
914
  targetId,
700
915
  flatten: true
701
916
  })).sessionId;
917
+ const lv = liveFor(b);
918
+ const win = shotSeams.noWindow ? null : await bounded(send("Browser.getWindowForTarget", { targetId }), 1e3);
919
+ if (typeof win?.windowId === "number") {
920
+ windowId = win.windowId;
921
+ lv.windows.set(windowId, (lv.windows.get(windowId) ?? 0) + 1);
922
+ registered = "window";
923
+ } else {
924
+ lv.unknown++;
925
+ registered = "unknown";
926
+ }
927
+ let view = null;
928
+ const v0 = (await bounded(send("Runtime.evaluate", {
929
+ expression: "[innerWidth, innerHeight, devicePixelRatio]",
930
+ returnByValue: true
931
+ }, sessionId), 1e3))?.result?.value;
932
+ 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 = {
933
+ dpr: v0[2],
934
+ decoW: win.bounds.width - v0[0],
935
+ decoH: win.bounds.height - v0[1]
936
+ };
937
+ const viewNow = async () => {
938
+ if (!view || windowId === void 0) return null;
939
+ const r = await bounded(send("Browser.getWindowBounds", { windowId }), Math.min(1e3, left()));
940
+ const bw = r?.bounds?.width, bh = r?.bounds?.height;
941
+ return typeof bw === "number" && typeof bh === "number" ? {
942
+ w: Math.round((bw - view.decoW) * view.dpr),
943
+ h: Math.round((bh - view.decoH) * view.dpr)
944
+ } : null;
945
+ };
946
+ if (!fullHeight && !clip && view && windowId !== void 0 && shotSeams.resize !== false && lv.windows.get(windowId) === 1 && lv.unknown === 0) {
947
+ const cw = Math.round(width * scale / view.dpr), ch = Math.round(height * scale / view.dpr);
948
+ shotSeams.onResize?.(windowId);
949
+ const ok = await bounded(send("Browser.setWindowBounds", {
950
+ windowId,
951
+ bounds: {
952
+ width: cw + view.decoW,
953
+ height: ch + view.decoH
954
+ }
955
+ }).then(() => true), 1e3) === true;
956
+ for (const by = Date.now() + 500; ok && Date.now() < by;) {
957
+ const v = (await bounded(send("Runtime.evaluate", {
958
+ expression: "[innerWidth, innerHeight]",
959
+ returnByValue: true
960
+ }, sessionId), by - Date.now()))?.result?.value;
961
+ if (v && v[0] === cw && v[1] === ch) break;
962
+ await new Promise((r2) => setTimeout(r2, 20));
963
+ }
964
+ }
702
965
  off = b.on((m) => {
703
966
  if (m.sessionId === sessionId && m.method === "Runtime.exceptionThrown") {
704
967
  const d = m.params?.exceptionDetails;
@@ -897,18 +1160,71 @@ async function captureIn({ url, width, height, out, fullHeight = false, timeoutM
897
1160
  capW = Math.max(1, Math.round(box.w));
898
1161
  capH = Math.max(1, Math.round(box.h));
899
1162
  }
900
- const shot = await sendD("Page.captureScreenshot", {
901
- format: "png",
902
- captureBeyondViewport: true,
903
- clip: {
904
- x: capX,
905
- y: capY,
1163
+ let attempt = 0;
1164
+ const take = async () => {
1165
+ const v = await viewNow();
1166
+ const shot = await sendD("Page.captureScreenshot", {
1167
+ format: "png",
1168
+ captureBeyondViewport: true,
1169
+ clip: {
1170
+ x: capX,
1171
+ y: capY,
1172
+ width: capW,
1173
+ height: capH,
1174
+ scale: 1
1175
+ }
1176
+ }, Math.max(1e3, Math.min(15e3, left() - 500)));
1177
+ let png = Buffer.from(String(shot.data), "base64");
1178
+ if (shotSeams.capture) png = shotSeams.capture(png, {
1179
+ attempt,
1180
+ view: v,
1181
+ windowId
1182
+ });
1183
+ attempt++;
1184
+ return {
1185
+ png,
1186
+ view: v
1187
+ };
1188
+ };
1189
+ const twoFrames = () => sendD("Runtime.evaluate", {
1190
+ expression: "new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(true))))",
1191
+ awaitPromise: true,
1192
+ returnByValue: true
1193
+ }, Math.max(1, Math.min(1e3, left() - RETRY_LEFT))).catch(() => null);
1194
+ const judge = (a) => a.view ? staleSurface(a.png, a.view.w, a.view.h, hardBy - 1e3) : Promise.resolve("unknown");
1195
+ let shotNow = await take();
1196
+ let verdict = await judge(shotNow);
1197
+ const retryLeft = shotSeams.retryLeftMs ?? RETRY_LEFT;
1198
+ while (verdict === "stale" && recaptures < 2 && left() > retryLeft) {
1199
+ recaptures++;
1200
+ await twoFrames();
1201
+ shotNow = await take();
1202
+ verdict = await judge(shotNow);
1203
+ }
1204
+ if (verdict === "stale" && fullHeight && scale > 1 && left() > retryLeft) {
1205
+ const was = scale;
1206
+ await sendD("Emulation.setDeviceMetricsOverride", {
906
1207
  width: capW,
907
1208
  height: capH,
908
- scale: 1
1209
+ deviceScaleFactor: 1,
1210
+ mobile: false
1211
+ }, Math.max(1, Math.min(5e3, left() - 1e3)));
1212
+ await twoFrames();
1213
+ recaptures++;
1214
+ shotNow = await take();
1215
+ verdict = await judge(shotNow);
1216
+ if (verdict !== "stale") {
1217
+ scale = 1;
1218
+ note = `${note ? note + "; " : ""}came back tiled at ${was}x - captured at 1x`;
909
1219
  }
910
- }, 15e3);
911
- writeFileSync(out, Buffer.from(String(shot.data), "base64"));
1220
+ }
1221
+ if (verdict === "stale") return {
1222
+ ok: false,
1223
+ error: STALE,
1224
+ recaptures
1225
+ };
1226
+ if (verdict === "unknown") note = `${note ? note + "; " : ""}not checked for a stale surface`;
1227
+ writeFileSync(out, shotNow.png);
912
1228
  const unsettled = !settled;
913
1229
  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
1230
  return {
@@ -918,12 +1234,14 @@ async function captureIn({ url, width, height, out, fullHeight = false, timeoutM
918
1234
  scale,
919
1235
  ...truncated ? { truncated: true } : {},
920
1236
  ...unsettled ? { unsettled: true } : {},
921
- ...note ? { note } : {}
1237
+ ...note ? { note } : {},
1238
+ recaptures
922
1239
  };
923
1240
  } catch (err) {
924
1241
  return {
925
1242
  ok: false,
926
- error: err.message
1243
+ error: err.message,
1244
+ ...recaptures ? { recaptures } : {}
927
1245
  };
928
1246
  } finally {
929
1247
  if (watchdog) clearTimeout(watchdog);
@@ -935,6 +1253,12 @@ async function captureIn({ url, width, height, out, fullHeight = false, timeoutM
935
1253
  })]);
936
1254
  clearTimeout(t);
937
1255
  }
1256
+ const lv = liveFor(b);
1257
+ if (registered === "window" && windowId !== void 0) {
1258
+ const n = (lv.windows.get(windowId) ?? 1) - 1;
1259
+ if (n > 0) lv.windows.set(windowId, n);
1260
+ else lv.windows.delete(windowId);
1261
+ } else if (registered === "unknown") lv.unknown = Math.max(0, lv.unknown - 1);
938
1262
  b.abort(me, "the shot finished");
939
1263
  }
940
1264
  }