@open-take/runtime 0.5.2 → 0.6.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/index.js CHANGED
@@ -1,12 +1,13 @@
1
- import { PrecheckRefusal, captureTake, captureTakeCDP, ensureChrome, inspectPage, planTargets, precheckPlan, resolveChrome, resolveNavigateUrl } from "./cdp-capture-BfIdK33k.js";
2
- import { appendFile, copyFile, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
1
+ import { BOX_CANDIDATES, CDP, CLICK_CANDIDATES, CLICK_FALLBACK_CANDIDATES, DEFAULT_SETTLE_BUDGET_MS, FIELD_CANDIDATES, HITTABLE_JS, NAME_JS, PrecheckRefusal, UNREACHABLE_JS, awaitFonts, captureDomState, captureTake, captureTakeCDP, closeFidelityPage, dragCadence, ensureChrome, finalizeDomStates, fitViewport, inspectPage, installActivityProbe, isCdpStall, launchBrowser, measureParts, measureStateDirs, navigate, openFidelityPage, originAllowed, planTargets, precheckPlan, pressChord, renderState, resolveChrome, resolveNavigateUrl, runBuffer, selectAllInFocusedJs, settle } from "./cdp-capture-DfJeA-uY.js";
2
+ import { createReadStream, existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
3
+ import { appendFile, copyFile, cp, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
3
4
  import { homedir, tmpdir } from "node:os";
4
5
  import { basename, dirname, extname, join, normalize, relative, resolve, sep } from "node:path";
5
- import { FINISH, LOOKS, MOTION, ZOOM_LEVELS, analyzeLaunchStory, analyzeMotionQuality, auditCursor, composeMotionStory, finishName, formatIssues, formatIssues as formatIssues$1, formatLaunchIssues, launchStarter, lookName, math, motionName, planComposition, renderLaunch, renderTake, resolveFfmpeg, resolveFfprobe, validateComposition, validateComposition as validateComposition$1, validateLaunchAssets, zoomLevelName } from "@open-take/compositor";
6
+ import { FINISH, LOOKS, MOTION, SRGB_TAGS, VIEWER_TOOLS, ZOOM_LEVELS, adHost, analyzeLaunchStory, analyzeMotionQuality, auditCursor, cardsOf, changedLine, checkFilm, checkViewer, componentsLine, composeMotionStory, contentOf, diffStates, elementLabel, exampleSource, filmBeats, filmGallery, filmInitLines, filmListen, filmLook, filmPicture, filmProbe, filmReport, filmSheet, filmStills, filmStudy, finishName, followedLine, formatComponents, formatFilmBeats, formatFilmCheck, formatFilmListen, formatFilmLook, formatFilmProbe, formatFilmReport, formatFilmStudy, formatIssues, formatIssues as formatIssues$1, formatLaunchIssues, formatMaterials, gatherComponents, imageFileSize, initFilm, launchStarter, lookName, matchStates, materialsFromProbe, materialsProbeExpression, materialsSummary, math, motionName, muxFilm, pageKey, pageMaterialNote, partFilesLine, partsLine, patchFilm, planComposition, prepareViewer, readComponentSource, readMaterials, readPageMaterial, readStateIndex, renderFilm, renderLaunch, renderTake, resolveFfmpeg, resolveFfprobe, subtree, validateComposition, validateComposition as validateComposition$1, validateLaunchAssets, viewerCommand, viewerRounds, writeComponents, writePartFiles, zoomLevelName } from "@open-take/compositor";
6
7
  import { spawn } from "node:child_process";
7
- import { createReadStream, existsSync, mkdirSync, realpathSync, statSync } from "node:fs";
8
+ import { createHash } from "node:crypto";
9
+ import { fileURLToPath, pathToFileURL } from "node:url";
8
10
  import { createServer } from "node:http";
9
- import { fileURLToPath } from "node:url";
10
11
 
11
12
  //#region src/frame-diff.ts
12
13
  const ANALYSIS_W$1 = 960;
@@ -53,7 +54,7 @@ function regionGap(a, b) {
53
54
  }
54
55
  /** Group kept cells into regions: 8-connected components, then components
55
56
  * whose boxes lie within MERGE_GAP_CELLS of one another are one region. */
56
- function regionsOf(kept, cw, ch) {
57
+ function regionsOf$1(kept, cw, ch) {
57
58
  const seen = new Uint8Array(kept.length);
58
59
  const regions = [];
59
60
  for (let start = 0; start < kept.length; start++) {
@@ -177,7 +178,7 @@ function diffFrames(before, after, w, h, ambient, anchor) {
177
178
  coverage: 0,
178
179
  regions: []
179
180
  };
180
- const toBox = (r) => ({
181
+ const toBox$1 = (r) => ({
181
182
  x: r.x0 * CELL,
182
183
  y: r.y0 * CELL,
183
184
  w: Math.min((r.x1 + 1) * CELL, w) - r.x0 * CELL,
@@ -185,15 +186,15 @@ function diffFrames(before, after, w, h, ambient, anchor) {
185
186
  });
186
187
  const distToAnchor = (r) => {
187
188
  if (!anchor) return 0;
188
- const b = toBox(r);
189
+ const b = toBox$1(r);
189
190
  return Math.hypot(b.x + b.w / 2 - anchor.x, b.y + b.h / 2 - anchor.y);
190
191
  };
191
- const regions = regionsOf(kept, cw, ch).sort((a, b) => b.cells - a.cells || distToAnchor(a) - distToAnchor(b));
192
+ const regions = regionsOf$1(kept, cw, ch).sort((a, b) => b.cells - a.cells || distToAnchor(a) - distToAnchor(b));
192
193
  return {
193
194
  coverage: keptCount / (cw * ch),
194
- box: toBox(regions[0]),
195
+ box: toBox$1(regions[0]),
195
196
  regions: regions.map((r) => ({
196
- box: toBox(r),
197
+ box: toBox$1(r),
197
198
  coverage: r.cells / (cw * ch)
198
199
  }))
199
200
  };
@@ -281,8 +282,10 @@ async function annotateCaptureLog(log, videoPath, opts = {}) {
281
282
  } : void 0;
282
283
  const d = diffFrames(fa, fb, aw, ah, fc, anchor);
283
284
  const attachBox = d.box && (box || (d.regions[0]?.coverage ?? 0) >= MIN_NO_BOX_COVERAGE);
285
+ const result = await measureResult(bin, videoPath, e, ceil * 1e3, aw, ah, mx, my, fa);
284
286
  events[i] = {
285
287
  ...e,
288
+ ...result ? { result } : {},
286
289
  changeCoverage: Math.round(d.coverage * 1e3) / 1e3,
287
290
  ...attachBox && d.box ? { effectBox: {
288
291
  x: Math.round(d.box.x * mx),
@@ -294,17 +297,325 @@ async function annotateCaptureLog(log, videoPath, opts = {}) {
294
297
  if (opts.logProgress) {
295
298
  const eb = events[i].effectBox;
296
299
  const subThreshold = events[i].changeCoverage === 0 && !eb ? " (sub-threshold — a subtle effect can score 0; judge by frames)" : "";
297
- process.stderr.write(`frame-diff [${i}] ${e.kind ?? "click"}@${e.tMs}ms coverage=${events[i].changeCoverage}${eb ? ` effect=(${eb.x},${eb.y} ${eb.w}x${eb.h})` : ""}${eb && d.regions.length > 1 ? ` (+${d.regions.length - 1} smaller region${d.regions.length > 2 ? "s" : ""} elsewhere)` : ""}${subThreshold}\n`);
300
+ process.stderr.write(`frame-diff [${i}] ${e.kind ?? "click"}@${e.tMs}ms coverage=${events[i].changeCoverage}${eb ? ` effect=(${eb.x},${eb.y} ${eb.w}x${eb.h})` : ""}${eb && d.regions.length > 1 ? ` (+${d.regions.length - 1} smaller region${d.regions.length > 2 ? "s" : ""} elsewhere)` : ""}${subThreshold}${events[i].result ? ` result +${events[i].result.atMs - e.tMs}ms (done +${events[i].result.doneMs - e.tMs}ms)` : ""}\n`);
298
301
  }
299
302
  }
300
- return {
303
+ const annotated = {
301
304
  ...log,
302
305
  events
303
306
  };
307
+ return log.states ? await measureStateSeams(annotated, videoPath, join(dirname(videoPath), log.states.dir), { ffmpegBin: bin }) : annotated;
308
+ } catch {
309
+ return log;
310
+ }
311
+ }
312
+ /** how long after an action (+durationMs) its result is looked for (ms) —
313
+ * bounded so one beat with a long wait cannot decode the whole recording */
314
+ const RESULT_MAX_MS = 4e3;
315
+ /** "the result shows": this share of the pixels that finally changed has changed */
316
+ const RESULT_AT_FRAC = .5;
317
+ /** "the result is done": from here on this share of them looks as they end up */
318
+ const RESULT_DONE_FRAC = .9;
319
+ /** a pixel counts as part of the result when it changed by more than this
320
+ * grey level. Well above PIXEL_DELTA on purpose: an encoder refining a
321
+ * still page (a new keyframe, measured on a real take) moves hundreds of
322
+ * text-edge pixels by 16–40 levels and almost none past 64, while a real
323
+ * change moves them by far more. */
324
+ const RESULT_DELTA = 48;
325
+ /** fewer result pixels than this is not a result */
326
+ const RESULT_MIN_PX = 12;
327
+ /** two frames whose plain difference is only the pixels that changed by more
328
+ * than RESULT_DELTA — what diffFrames should group into regions when
329
+ * compression noise must not count */
330
+ function strongPair(a, b) {
331
+ const blank = new Uint8Array(a.length);
332
+ const mask = new Uint8Array(a.length);
333
+ for (let i = 0; i < a.length; i++) {
334
+ const d = a[i] - b[i];
335
+ if (d > RESULT_DELTA || d < -RESULT_DELTA) mask[i] = 255;
336
+ }
337
+ return [blank, mask];
338
+ }
339
+ /**
340
+ * Pure: in frames of one region over time (first = just before the input,
341
+ * last = how it ends up), the first frame showing at least half of the final
342
+ * change (`at`) and the first from which the region stays as it ends up
343
+ * (`done`), as frame indices. Only pixels that changed by more than
344
+ * RESULT_DELTA count. Null when the first and last frames are alike.
345
+ */
346
+ function resultFrames(frames) {
347
+ if (frames.length < 2) return null;
348
+ const first = frames[0];
349
+ const last = frames[frames.length - 1];
350
+ const changed = [];
351
+ for (let i = 0; i < first.length; i++) {
352
+ const d = first[i] - last[i];
353
+ if (d > RESULT_DELTA || d < -RESULT_DELTA) changed.push(i);
354
+ }
355
+ if (changed.length < RESULT_MIN_PX) return null;
356
+ const half = RESULT_DELTA / 2;
357
+ let at = -1;
358
+ const settled = [];
359
+ for (const f of frames) {
360
+ let shown = 0;
361
+ let alike = 0;
362
+ for (const i of changed) {
363
+ const fromFirst = f[i] - first[i];
364
+ const fromLast = f[i] - last[i];
365
+ if (fromFirst > half || fromFirst < -half) shown++;
366
+ if (fromLast <= half && fromLast >= -half) alike++;
367
+ }
368
+ if (at < 0 && shown / changed.length >= RESULT_AT_FRAC) at = settled.length;
369
+ settled.push(alike / changed.length >= RESULT_DONE_FRAC);
370
+ }
371
+ let done = frames.length - 1;
372
+ for (let k = frames.length - 1; k >= 0 && settled[k]; k--) done = k;
373
+ if (at < 0) at = frames.length - 1;
374
+ return {
375
+ at,
376
+ done: Math.max(at, done)
377
+ };
378
+ }
379
+ /** Every frame of [fromS, toS) of `videoPath`, scaled to aw×ah and cropped to
380
+ * `crop` (raster px), grayscale, with each frame's time (s). Undefined on any
381
+ * failure. */
382
+ function decodeWindow(bin, videoPath, fromS, toS, aw, ah, crop) {
383
+ return new Promise((res) => {
384
+ const size = crop.w * crop.h;
385
+ const args = [
386
+ "-hide_banner",
387
+ "-nostats",
388
+ "-loglevel",
389
+ "info",
390
+ "-ss",
391
+ fromS.toFixed(3),
392
+ "-t",
393
+ Math.max(.001, toS - fromS).toFixed(3),
394
+ "-i",
395
+ videoPath,
396
+ "-vf",
397
+ `scale=${aw}:${ah},crop=${crop.w}:${crop.h}:${crop.x}:${crop.y},showinfo`,
398
+ "-fps_mode",
399
+ "passthrough",
400
+ "-f",
401
+ "rawvideo",
402
+ "-pix_fmt",
403
+ "gray",
404
+ "-"
405
+ ];
406
+ const c = spawn(bin, args, { stdio: [
407
+ "ignore",
408
+ "pipe",
409
+ "pipe"
410
+ ] });
411
+ const chunks = [];
412
+ let err = "";
413
+ c.stdout.on("data", (b) => chunks.push(b));
414
+ c.stderr.on("data", (b) => {
415
+ err += b.toString();
416
+ });
417
+ c.on("error", () => res(void 0));
418
+ c.on("close", (code) => {
419
+ if (code !== 0) return res(void 0);
420
+ const buf = Buffer.concat(chunks);
421
+ const times = [...err.matchAll(/pts_time:\s*([-\d.e]+)/g)].map((m) => fromS + Number(m[1]));
422
+ const count = Math.floor(buf.length / size);
423
+ if (!count || times.length < count) return res(void 0);
424
+ const frames = [];
425
+ for (let k = 0; k < count; k++) frames.push(new Uint8Array(buf.subarray(k * size, (k + 1) * size)));
426
+ res({
427
+ frames,
428
+ times: times.slice(0, count)
429
+ });
430
+ });
431
+ });
432
+ }
433
+ /** When the result of `e` showed (see CaptureEventBase.result), or undefined. */
434
+ async function measureResult(bin, videoPath, e, untilMs, aw, ah, mx, my, before) {
435
+ const durationMs = "durationMs" in e && e.durationMs != null ? e.durationMs : 0;
436
+ const fromS = Math.max(0, (e.tMs - BEFORE_MS) / 1e3);
437
+ const toS = Math.min(untilMs, e.tMs + durationMs + RESULT_MAX_MS) / 1e3;
438
+ if (toS <= fromS + .05) return void 0;
439
+ const end = await grabFrame(bin, videoPath, toS, aw, ah);
440
+ if (!end) return void 0;
441
+ const box = "box" in e && e.box != null ? e.box : void 0;
442
+ const anchor = box ? {
443
+ x: (box.x + box.w / 2) / mx,
444
+ y: (box.y + box.h / 2) / my
445
+ } : void 0;
446
+ const [blank, strong] = strongPair(before, end);
447
+ const d = diffFrames(blank, strong, aw, ah, void 0, anchor);
448
+ if (!d.box) return void 0;
449
+ if (!box && (d.regions[0]?.coverage ?? 0) < MIN_NO_BOX_COVERAGE) return void 0;
450
+ const ctl = box && {
451
+ x: box.x / mx,
452
+ y: box.y / my,
453
+ w: box.w / mx,
454
+ h: box.h / my
455
+ };
456
+ const apart = (b) => !ctl || b.x >= ctl.x + ctl.w || ctl.x >= b.x + b.w || b.y >= ctl.y + ctl.h || ctl.y >= b.y + b.h;
457
+ const region = d.regions.find((g) => apart(g.box))?.box ?? d.box;
458
+ const win = await decodeWindow(bin, videoPath, fromS, toS + .02, aw, ah, region);
459
+ if (!win) return void 0;
460
+ const r = resultFrames(win.frames);
461
+ if (!r) return void 0;
462
+ const atMs = Math.round(win.times[r.at] * 1e3);
463
+ if (atMs < e.tMs) return void 0;
464
+ return {
465
+ atMs,
466
+ doneMs: Math.round(win.times[r.done] * 1e3),
467
+ box: {
468
+ x: Math.round(region.x * mx),
469
+ y: Math.round(region.y * my),
470
+ w: Math.round(region.w * mx),
471
+ h: Math.round(region.h * my)
472
+ }
473
+ };
474
+ }
475
+ /** how far (CSS px) the search for the best shift reaches */
476
+ const SEAM_REACH = 12;
477
+ /** mean |a−b| over the part of a w×h frame both cover when b is shifted by
478
+ * (dx, dy), leaving out `margin` px at every edge */
479
+ function meanDiffAt(a, b, w, h, dx, dy, margin, step = 1) {
480
+ let sum = 0;
481
+ let n = 0;
482
+ for (let y = margin; y < h - margin; y += step) {
483
+ const ya = y * w;
484
+ const yb = (y - dy) * w;
485
+ for (let x = margin; x < w - margin; x += step) {
486
+ const d = a[ya + x] - b[yb + x - dx];
487
+ sum += d < 0 ? -d : d;
488
+ n++;
489
+ }
490
+ }
491
+ return n ? sum / n : 255;
492
+ }
493
+ /** the minimum of a parabola through three samples at −1, 0, +1, as an offset */
494
+ const vertex = (l, c, r) => {
495
+ const den = l - 2 * c + r;
496
+ return den > 0 ? Math.max(-.5, Math.min(.5, (l - r) / (2 * den))) : 0;
497
+ };
498
+ /**
499
+ * Pure: where `state` (a w×h grey frame) sits in `video` (same size): the
500
+ * shift (dx, dy) in px — a state point p shows at p + (dx, dy) — found
501
+ * coarse (every 2 px over ±reach) then fine (±1 px, sub-pixel by a parabola),
502
+ * with the mean difference and the share of pixels still differing by more
503
+ * than RESULT_DELTA at the nearest whole shift.
504
+ */
505
+ function alignFrames(video, state, w, h, reach = SEAM_REACH) {
506
+ const margin = reach + 2;
507
+ let bx = 0;
508
+ let by = 0;
509
+ let coarse = meanDiffAt(video, state, w, h, 0, 0, margin, 2);
510
+ for (let dy = -reach; dy <= reach; dy += 2) for (let dx = -reach; dx <= reach; dx += 2) {
511
+ const m = meanDiffAt(video, state, w, h, dx, dy, margin, 2);
512
+ if (m < coarse - 1e-9) [coarse, bx, by] = [
513
+ m,
514
+ dx,
515
+ dy
516
+ ];
517
+ }
518
+ let best = meanDiffAt(video, state, w, h, bx, by, margin);
519
+ for (let moved = true; moved;) {
520
+ moved = false;
521
+ for (const [dx, dy] of [
522
+ [bx - 1, by],
523
+ [bx + 1, by],
524
+ [bx, by - 1],
525
+ [bx, by + 1]
526
+ ]) {
527
+ if (Math.abs(dx) > reach + 1 || Math.abs(dy) > reach + 1) continue;
528
+ const m = meanDiffAt(video, state, w, h, dx, dy, margin);
529
+ if (m < best - 1e-9) {
530
+ [best, bx, by] = [
531
+ m,
532
+ dx,
533
+ dy
534
+ ];
535
+ moved = true;
536
+ }
537
+ }
538
+ }
539
+ const at = (dx, dy) => meanDiffAt(video, state, w, h, dx, dy, margin);
540
+ const sx = vertex(at(bx - 1, by), best, at(bx + 1, by));
541
+ const sy = vertex(at(bx, by - 1), best, at(bx, by + 1));
542
+ let differ = 0;
543
+ let total = 0;
544
+ for (let y = margin; y < h - margin; y++) for (let x = margin; x < w - margin; x++) {
545
+ const d = video[y * w + x] - state[(y - by) * w + x - bx];
546
+ if (d > RESULT_DELTA || d < -RESULT_DELTA) differ++;
547
+ total++;
548
+ }
549
+ const round = (v, k) => Math.round(v * k) / k;
550
+ return {
551
+ dx: round(bx + sx, 100),
552
+ dy: round(by + sy, 100),
553
+ meanDiff: round(best, 100),
554
+ diffFrac: round(total ? differ / total : 1, 1e4)
555
+ };
556
+ }
557
+ /** Grey pixels of a still image (the state's live.png), scaled to w×h. */
558
+ const grabImage = (bin, file, w, h) => grabFrame(bin, file, 0, w, h);
559
+ /**
560
+ * Each saved state's `seam` (see CaptureLog.states): the recording's frame at
561
+ * the state's time against the state's `live.png`, at the viewport's CSS
562
+ * size. A state without its screenshot, or a frame that cannot be read, is
563
+ * left as it was. Never throws.
564
+ */
565
+ async function measureStateSeams(log, videoPath, statesDir, opts = {}) {
566
+ try {
567
+ if (!log.states?.items.length) return log;
568
+ const bin = opts.ffmpegBin ?? await resolveFfmpeg();
569
+ const w = log.viewport.w;
570
+ const h = log.viewport.h;
571
+ if (!(w > 0) || !(h > 0)) return log;
572
+ const items = [];
573
+ for (const item of log.states.items) {
574
+ const live = join(statesDir, item.id, "live.png");
575
+ if (item.moving || !existsSync(live)) {
576
+ items.push(item);
577
+ continue;
578
+ }
579
+ const [v, s] = await Promise.all([grabFrame(bin, videoPath, item.tMs / 1e3, w, h), grabImage(bin, live, w, h)]);
580
+ items.push(v && s ? {
581
+ ...item,
582
+ seam: alignFrames(v, s, w, h)
583
+ } : item);
584
+ }
585
+ return {
586
+ ...log,
587
+ states: {
588
+ ...log.states,
589
+ items
590
+ }
591
+ };
304
592
  } catch {
305
593
  return log;
306
594
  }
307
595
  }
596
+ /**
597
+ * Re-read a kept take's recording for the readings above — each action's
598
+ * `result` and each state's `seam` (plus the effect boxes, recomputed the
599
+ * same way) — and write them into its capture.json. For takes made before
600
+ * they were recorded; `settledMs` comes from the live page and cannot be
601
+ * added afterwards. Returns what changed, in counts.
602
+ */
603
+ async function measureTake(takeDir, opts = {}) {
604
+ const { readFile: readFile$1, writeFile: writeFile$1 } = await import("node:fs/promises");
605
+ const logPath = join(takeDir, "capture.json");
606
+ const video = join(takeDir, "capture.mp4");
607
+ if (!existsSync(logPath) || !existsSync(video)) throw new Error(`no recording at ${takeDir} (capture.json and capture.mp4 are needed)`);
608
+ const log = JSON.parse(await readFile$1(logPath, "utf8"));
609
+ const out = await annotateCaptureLog(log, video, opts);
610
+ await writeFile$1(logPath, JSON.stringify(out, null, 2));
611
+ const saved = out.states?.items.filter((s) => !s.moving) ?? [];
612
+ return {
613
+ results: out.events.filter((e) => e.result).length,
614
+ actions: out.events.length,
615
+ seams: saved.filter((s) => s.seam).length,
616
+ states: saved.length
617
+ };
618
+ }
308
619
 
309
620
  //#endregion
310
621
  //#region src/take.ts
@@ -440,10 +751,10 @@ function beatTitle(e) {
440
751
  if (e.kind === "press" && e.keys) return e.keys;
441
752
  return e.kind;
442
753
  }
443
- const trunc = (s, n) => s.length > n ? `${s.slice(0, n - 1)}…` : s;
754
+ const trunc$1 = (s, n) => s.length > n ? `${s.slice(0, n - 1)}…` : s;
444
755
  /** "click Open menu" — the shared beat vocabulary (beat sheet rows, frames rows). */
445
756
  function beatLabel(e) {
446
- return `${KIND_LABEL[e.kind]} ${trunc(beatTitle(e), 24)}`;
757
+ return `${KIND_LABEL[e.kind]} ${trunc$1(beatTitle(e), 24)}`;
447
758
  }
448
759
  function fmtTime(ms) {
449
760
  const s = Math.max(0, Math.round(ms / 1e3));
@@ -468,7 +779,7 @@ function buildBeatSheet(comp, name) {
468
779
  comp.events.forEach((e, i) => {
469
780
  const num = String(i + 1).padStart(2, " ");
470
781
  const kind = KIND_LABEL[e.kind].padEnd(6, " ");
471
- const title = trunc(beatTitle(e), 24).padEnd(25, " ");
782
+ const title = trunc$1(beatTitle(e), 24).padEnd(25, " ");
472
783
  lines.push(` ${num} ${fmtTime(e.tMs)} ${kind} ${title} ${zoomText(e)}`);
473
784
  });
474
785
  const last = comp.events[n - 1];
@@ -517,7 +828,7 @@ function buildBadges(comp) {
517
828
  badges.push({
518
829
  fromMs: starts[i],
519
830
  toMs: to,
520
- text: `BEAT ${i + 1}/${n} · ${KIND_LABEL[e.kind]} ${trunc(beatTitle(e), 24)} · ${zoomText(e)}`
831
+ text: `BEAT ${i + 1}/${n} · ${KIND_LABEL[e.kind]} ${trunc$1(beatTitle(e), 24)} · ${zoomText(e)}`
521
832
  });
522
833
  if (last && to < comp.durationMs + 1e3) badges.push({
523
834
  fromMs: to,
@@ -865,7 +1176,7 @@ async function renderBeforeAfter(take, opts = {}) {
865
1176
  src
866
1177
  ];
867
1178
  if (win) args.push("-ss", String(win[0] / 1e3), "-t", String((win[1] - win[0]) / 1e3));
868
- args.push("-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p", "-an", out);
1179
+ args.push("-vf", SRGB_TAGS, "-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p", "-an", out);
869
1180
  await ffmpeg(args);
870
1181
  };
871
1182
  const before = takeFile(take, "ab.before.mp4");
@@ -924,7 +1235,7 @@ async function concatWithGaps(clips, outPath, v) {
924
1235
  seq.push(`[${i}:v]`);
925
1236
  if (i < clips.length - 1) seq.push(gapUses > 1 ? `[g${i}]` : `[${gapIdx}:v]`);
926
1237
  });
927
- const filter = `${split}${seq.join("")}concat=n=${seq.length}:v=1:a=0[v]`;
1238
+ const filter = `${split}${seq.join("")}concat=n=${seq.length}:v=1:a=0,${SRGB_TAGS}[v]`;
928
1239
  args.push("-filter_complex", filter, "-map", "[v]", "-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p", "-r", String(v.fps), "-an", resolve(outPath));
929
1240
  await ffmpeg(args);
930
1241
  }
@@ -1246,23 +1557,10 @@ async function staticTailIssue(deliveredMp4, insetFrac) {
1246
1557
  fix: "shorten the last beat's settleMs, or add a closing beat that earns the tail"
1247
1558
  };
1248
1559
  }
1249
- function runBuf(bin, args) {
1250
- return new Promise((res, rej) => {
1251
- const c = spawn(bin, args, { stdio: [
1252
- "ignore",
1253
- "pipe",
1254
- "ignore"
1255
- ] });
1256
- const chunks = [];
1257
- c.stdout.on("data", (b) => chunks.push(b));
1258
- c.on("error", rej);
1259
- c.on("close", (code) => code === 0 ? res(Buffer.concat(chunks)) : rej(new Error(`${bin} exited ${code}`)));
1260
- });
1261
- }
1262
1560
  async function probeVideo(path) {
1263
1561
  try {
1264
1562
  const bin = await resolveFfprobe();
1265
- const out = (await runBuf(bin, [
1563
+ const out = (await runBuffer(bin, [
1266
1564
  "-v",
1267
1565
  "error",
1268
1566
  "-select_streams",
@@ -1302,7 +1600,7 @@ function raster(meta) {
1302
1600
  async function grayFrame(bin, path, tS, aw, ah, cropFrac) {
1303
1601
  try {
1304
1602
  const crop = cropFrac != null && cropFrac < 1 ? `crop=floor(iw*${cropFrac.toFixed(3)}/2)*2:floor(ih*${cropFrac.toFixed(3)}/2)*2,` : "";
1305
- const buf = await runBuf(bin, [
1603
+ const buf = await runBuffer(bin, [
1306
1604
  "-v",
1307
1605
  "error",
1308
1606
  "-ss",
@@ -1327,7 +1625,7 @@ async function grayFrame(bin, path, tS, aw, ah, cropFrac) {
1327
1625
  /** decode grayscale frames from t=0 on a `stepMs` grid over the first `spanS`
1328
1626
  * seconds, in ONE ffmpeg pass (frame k sits at k·stepMs) */
1329
1627
  async function grayStrip(bin, path, spanS, stepMs, aw, ah) {
1330
- const buf = await runBuf(bin, [
1628
+ const buf = await runBuffer(bin, [
1331
1629
  "-v",
1332
1630
  "error",
1333
1631
  "-i",
@@ -1924,6 +2222,153 @@ async function ciTake(opts) {
1924
2222
  }
1925
2223
  }
1926
2224
 
2225
+ //#endregion
2226
+ //#region src/components.ts
2227
+ /** parts.json is there and was measured with full values (each part's
2228
+ * `text`, which the probe has written since it kept values whole) */
2229
+ function partsCurrent(dir) {
2230
+ try {
2231
+ const f = JSON.parse(readFileSync(join(dir, "parts.json"), "utf8"));
2232
+ return Array.isArray(f.parts) && f.parts.every((p) => typeof p.text === "string");
2233
+ } catch {
2234
+ return false;
2235
+ }
2236
+ }
2237
+ const writtenSince = (p, t) => {
2238
+ try {
2239
+ return statSync(p).mtimeMs >= t;
2240
+ } catch {
2241
+ return false;
2242
+ }
2243
+ };
2244
+ /** Measure what is missing, gather, and write `<root>/components.json`. */
2245
+ async function inventoryComponents(opts) {
2246
+ const source = readComponentSource(opts.path);
2247
+ if (opts.state && !source.states.some((s) => s.id === opts.state)) throw new Error(`components: no saved screen ${opts.state} here (it has ${source.states.map((s) => s.id).join(", ") || "none"})`);
2248
+ const scope = source.states.filter((s) => !opts.state || s.id === opts.state);
2249
+ const need = scope.filter((s) => typeof readStateIndex(s.dir) !== "string" && (opts.minArea != null || !partsCurrent(s.dir)));
2250
+ const measured = [];
2251
+ const failed = [];
2252
+ let measureMs = 0;
2253
+ if (need.length && opts.measure !== false) {
2254
+ const t0 = Date.now();
2255
+ const first = readStateIndex(need[0].dir);
2256
+ const vp = typeof first === "string" ? {
2257
+ w: 1920,
2258
+ h: 1080
2259
+ } : first.viewport;
2260
+ const browser = await launchBrowser({
2261
+ width: vp.w,
2262
+ height: vp.h,
2263
+ chromePath: await ensureChrome(opts.chromePath)
2264
+ });
2265
+ const idOf = new Map(need.map((s) => [s.dir, s.id]));
2266
+ const budgetMs = Math.max(6e4, need.length * 2e4);
2267
+ let timer;
2268
+ const stalled = new Promise((res) => {
2269
+ timer = setTimeout(() => res("stalled"), budgetMs);
2270
+ });
2271
+ try {
2272
+ const r = await Promise.race([measureStateDirs({
2273
+ browser,
2274
+ dirs: need.map((s) => s.dir),
2275
+ ...opts.minArea != null ? { minArea: opts.minArea } : {}
2276
+ }), stalled]);
2277
+ if (r === "stalled") for (const s of need) if (writtenSince(join(s.dir, "parts.json"), t0)) measured.push(s.id);
2278
+ else failed.push({
2279
+ state: s.id,
2280
+ why: `Chrome stopped answering — measuring stopped after ${Math.round(budgetMs / 1e3)} s; run it again to measure the rest`
2281
+ });
2282
+ else {
2283
+ for (const m of r.measured) measured.push(idOf.get(m.dir) ?? m.dir);
2284
+ for (const f of r.failed) failed.push({
2285
+ state: idOf.get(f.dir) ?? f.dir,
2286
+ why: f.why
2287
+ });
2288
+ }
2289
+ } finally {
2290
+ clearTimeout(timer);
2291
+ await browser.close();
2292
+ }
2293
+ measureMs = Date.now() - t0;
2294
+ }
2295
+ const file = gatherComponents(source);
2296
+ const path = opts.write === false ? void 0 : writeComponents(file, source.root);
2297
+ let parts;
2298
+ const flat = source.states.some((s) => resolve(dirname(s.dir)) === resolve(source.root));
2299
+ if (path && !flat && scope.some((s) => existsSync(join(s.dir, "parts-dom.json")))) try {
2300
+ parts = writePartFiles(file, source, join(source.root, "parts"));
2301
+ } catch (e) {
2302
+ console.error(`components: no part files (${e.message})`);
2303
+ }
2304
+ return {
2305
+ file,
2306
+ ...path ? { path } : {},
2307
+ ...parts ? { parts } : {},
2308
+ source,
2309
+ measured,
2310
+ measureMs,
2311
+ failed
2312
+ };
2313
+ }
2314
+
2315
+ //#endregion
2316
+ //#region src/defect-report.ts
2317
+ const DEFECTS_OPEN = "--- open-take defects v1 ---";
2318
+ const DEFECTS_CLOSE = "--- end open-take defects ---";
2319
+ const NOTE = "Deterministic gate findings, measured against the live app and the recorded take — facts, not opinions. error = the gate refuses this take; warn = suspect — fix it or state why it stays.";
2320
+ const REPAIR = "Relay this block VERBATIM to the author of the plan and ask for the ENTIRE corrected plan (same JSON shape): fix exactly what the defects name and keep every other editorial decision unchanged. Then re-run the same command. At most two repair rounds — a take still defective after two needs a human, not a third round.";
2321
+ const asDefects = (gate, issues) => issues.map((i) => ({
2322
+ gate,
2323
+ severity: i.severity,
2324
+ path: i.path,
2325
+ message: i.message,
2326
+ ...i.fix ? { fix: i.fix } : {}
2327
+ }));
2328
+ /** capture-time skipped steps as defects — error-severity: the beat is gone
2329
+ * from the video, which is exactly what the strict exit refuses. The fix
2330
+ * copy follows the reason: a focus skip means the target RESOLVED and the
2331
+ * not-found copy ("point the target at an element that exists") would send
2332
+ * the repair round at the wrong dimension. */
2333
+ const skippedDefects = (skipped) => skipped.map((s) => ({
2334
+ gate: "capture",
2335
+ severity: "error",
2336
+ path: `steps[${s.step}]`,
2337
+ message: `${s.action} ${JSON.stringify(s.target ?? "")}: step SKIPPED at capture (${s.reason}) — the video is missing this beat`,
2338
+ fix: s.reason.startsWith("focus never reached") ? "the target resolved but never took focus — have an earlier step click/open the control that arms this field, retarget the step at the element that actually receives the text, or drop the step; then re-make" : "point the target at an element that exists when this step runs (a pre-capture warning above may name the impostor or the late binding), or drop the step; then re-make"
2339
+ }));
2340
+ /** Settle underruns whose beat DID go quiet carry a measured number the
2341
+ * author can copy — the one defect class where the fix is literally a
2342
+ * value. Beats that never settled (`reason: "budget"`) are excluded: telling
2343
+ * an author to raise settleMs toward a number that satisfies nothing is a
2344
+ * ratchet, and the human summary already explains that case. */
2345
+ const settleDefects = (settleWaits) => settleWaits.filter((w) => w.reason === "idle").map((w) => ({
2346
+ gate: "capture",
2347
+ severity: "warn",
2348
+ path: `steps[${w.step}].settleMs`,
2349
+ message: `${w.action}: held ${w.heldMs}ms but the page needed ~${w.heldMs + w.waitedMs}ms to go quiet — the capture waited, the plan under-budgeted`,
2350
+ fix: `set this step's settleMs to ${w.heldMs + w.waitedMs}`
2351
+ }));
2352
+ function buildDefectReport(opts) {
2353
+ return {
2354
+ format: "open-take-defects/1",
2355
+ verb: opts.verb,
2356
+ verdict: opts.verdict,
2357
+ exitCode: opts.exitCode,
2358
+ ...opts.plan ? { plan: opts.plan } : {},
2359
+ ...opts.master ? { master: opts.master } : {},
2360
+ errors: opts.defects.filter((d) => d.severity === "error").length,
2361
+ warns: opts.defects.filter((d) => d.severity === "warn").length,
2362
+ defects: opts.defects,
2363
+ note: NOTE,
2364
+ repair: REPAIR
2365
+ };
2366
+ }
2367
+ /** the fixed stdout section — everything between the sentinels is one JSON
2368
+ * object, so the driving agent extracts it with two line matches and no
2369
+ * scraping of the prose above it */
2370
+ const renderDefectBlock = (report) => `\n${DEFECTS_OPEN}\n${JSON.stringify(report, null, 1)}\n${DEFECTS_CLOSE}\n`;
2371
+
1927
2372
  //#endregion
1928
2373
  //#region src/edit-server.ts
1929
2374
  const CONTENT_TYPE = {
@@ -2902,7 +3347,7 @@ const isStr = (v) => typeof v === "string" && v.length > 0;
2902
3347
  const isNum = (v) => typeof v === "number" && Number.isFinite(v);
2903
3348
  const isPoint = (v) => isObj(v) && isNum(v.x) && isNum(v.y);
2904
3349
  /** Render a value into a message. Truncated: plans embed whole paragraphs. */
2905
- const show = (v) => {
3350
+ const show$1 = (v) => {
2906
3351
  const s = v === void 0 ? "undefined" : JSON.stringify(v) ?? String(v);
2907
3352
  return s.length > 48 ? `${s.slice(0, 45)}…` : s;
2908
3353
  };
@@ -2967,39 +3412,39 @@ function lintPlan(plan) {
2967
3412
  fix
2968
3413
  });
2969
3414
  if (!isObj(plan)) {
2970
- err("plan", `plan is not an object (got ${show(plan)}) — a TakePlan is {"url":"<the running app>","steps":[…]}`, "start from {\"url\":\"http://localhost:3000\",\"steps\":[{\"action\":\"click\",\"text\":\"Get started\"}]}");
3415
+ err("plan", `plan is not an object (got ${show$1(plan)}) — a TakePlan is {"url":"<the running app>","steps":[…]}`, "start from {\"url\":\"http://localhost:3000\",\"steps\":[{\"action\":\"click\",\"text\":\"Get started\"}]}");
2971
3416
  return issues;
2972
3417
  }
2973
- if (!isStr(plan.url)) err("url", plan.url === void 0 ? "url is missing — the running app the take opens" : `url must be a non-empty string (got ${show(plan.url)}) — the running app the take opens`, "set url to the app's address, e.g. \"http://localhost:3000\"");
3418
+ if (!isStr(plan.url)) err("url", plan.url === void 0 ? "url is missing — the running app the take opens" : `url must be a non-empty string (got ${show$1(plan.url)}) — the running app the take opens`, "set url to the app's address, e.g. \"http://localhost:3000\"");
2974
3419
  const vp = plan.viewport;
2975
- if (vp !== void 0 && !(isObj(vp) && Number.isInteger(vp.width) && Number.isInteger(vp.height))) err("viewport", `viewport must be {"width":<int>,"height":<int>} in CSS px (got ${show(vp)})`, isObj(vp) && isNum(vp.width) && isNum(vp.height) ? `rewrite as {"width":${Math.round(vp.width)},"height":${Math.round(vp.height)}}` : "use e.g. {\"width\":1280,\"height\":800}, or drop viewport for the default");
3420
+ if (vp !== void 0 && !(isObj(vp) && Number.isInteger(vp.width) && Number.isInteger(vp.height))) err("viewport", `viewport must be {"width":<int>,"height":<int>} in CSS px (got ${show$1(vp)})`, isObj(vp) && isNum(vp.width) && isNum(vp.height) ? `rewrite as {"width":${Math.round(vp.width)},"height":${Math.round(vp.height)}}` : "use e.g. {\"width\":1280,\"height\":800}, or drop viewport for the default");
2976
3421
  const sc = plan.startCursor;
2977
- if (sc !== void 0 && !isPoint(sc)) err("startCursor", `startCursor must be a point {"x":<px>,"y":<px>} in viewport CSS px (got ${show(sc)})`, "use e.g. {\"x\":640,\"y\":400}, or drop startCursor for the default");
3422
+ if (sc !== void 0 && !isPoint(sc)) err("startCursor", `startCursor must be a point {"x":<px>,"y":<px>} in viewport CSS px (got ${show$1(sc)})`, "use e.g. {\"x\":640,\"y\":400}, or drop startCursor for the default");
2978
3423
  const steps = plan.steps;
2979
3424
  let stepsMisspelled = false;
2980
3425
  for (const k of Object.keys(plan)) {
2981
3426
  if (PLAN_FIELDS.includes(k)) continue;
2982
- const near = nearestField(k, PLAN_FIELDS);
2983
- if (near === "steps" && !Array.isArray(steps)) {
3427
+ const near$1 = nearestField(k, PLAN_FIELDS);
3428
+ if (near$1 === "steps" && !Array.isArray(steps)) {
2984
3429
  stepsMisspelled = true;
2985
3430
  err(k, `\`${k}\` looks like a misspelling of \`steps\` — as written the plan has no steps array, so there is nothing to drive`, `rename \`${k}\` to \`steps\``);
2986
- } else warn(k, `\`${k}\` is not a TakePlan field — nothing reads it`, near ? `rename \`${k}\` to \`${near}\`` : `remove it — a plan's fields are: ${PLAN_FIELDS.join(", ")}`);
3431
+ } else warn(k, `\`${k}\` is not a TakePlan field — nothing reads it`, near$1 ? `rename \`${k}\` to \`${near$1}\`` : `remove it — a plan's fields are: ${PLAN_FIELDS.join(", ")}`);
2987
3432
  }
2988
3433
  if (!Array.isArray(steps) || steps.length === 0) {
2989
- if (!stepsMisspelled) err("steps", steps === void 0 ? "steps is missing — a plan drives at least one step" : `steps must be a non-empty array (got ${show(steps)})`, "add a steps array, e.g. [{\"action\":\"click\",\"text\":\"Get started\"}]");
3434
+ if (!stepsMisspelled) err("steps", steps === void 0 ? "steps is missing — a plan drives at least one step" : `steps must be a non-empty array (got ${show$1(steps)})`, "add a steps array, e.g. [{\"action\":\"click\",\"text\":\"Get started\"}]");
2990
3435
  return issues;
2991
3436
  }
2992
3437
  for (let i = 0; i < steps.length; i++) {
2993
3438
  const s = steps[i];
2994
3439
  const p = `steps[${i}]`;
2995
3440
  if (!isObj(s)) {
2996
- err(p, `step is not an object (got ${show(s)}) — every step is {"action":"<name>", …}`, `actions: ${ACTIONS.join(", ")}`);
3441
+ err(p, `step is not an object (got ${show$1(s)}) — every step is {"action":"<name>", …}`, `actions: ${ACTIONS.join(", ")}`);
2997
3442
  continue;
2998
3443
  }
2999
3444
  const a = s.action;
3000
3445
  if (typeof a !== "string" || !ACTIONS.includes(a)) {
3001
- const near = typeof a === "string" ? nearestField(a, ACTIONS) : void 0;
3002
- err(`${p}.action`, a === void 0 ? `step has no action — the vocabulary is ${ACTIONS.join(" | ")}` : `unknown action ${show(a)} — the vocabulary is ${ACTIONS.join(" | ")}`, near ? `did you mean "${near}"?` : `pick one of: ${ACTIONS.join(", ")}`);
3446
+ const near$1 = typeof a === "string" ? nearestField(a, ACTIONS) : void 0;
3447
+ err(`${p}.action`, a === void 0 ? `step has no action — the vocabulary is ${ACTIONS.join(" | ")}` : `unknown action ${show$1(a)} — the vocabulary is ${ACTIONS.join(" | ")}`, near$1 ? `did you mean "${near$1}"?` : `pick one of: ${ACTIONS.join(", ")}`);
3003
3448
  continue;
3004
3449
  }
3005
3450
  const action = a;
@@ -3016,23 +3461,23 @@ function lintPlan(plan) {
3016
3461
  warn(`${p}.zoom`, `a ${action} step takes no \`zoom\` — it plays full-view by design${action === "scroll" ? " (the content pans; the camera holds)" : ""}, so this is never read`, "remove it");
3017
3462
  continue;
3018
3463
  }
3019
- const near = nearestField(k, fields);
3020
- if (near && required.includes(near) && s[near] === void 0) {
3021
- covered.add(near);
3022
- if (near === "selector" || near === "text") {
3464
+ const near$1 = nearestField(k, fields);
3465
+ if (near$1 && required.includes(near$1) && s[near$1] === void 0) {
3466
+ covered.add(near$1);
3467
+ if (near$1 === "selector" || near$1 === "text") {
3023
3468
  covered.add("selector");
3024
3469
  covered.add("text");
3025
3470
  }
3026
- err(`${p}.${k}`, `\`${k}\` looks like a misspelling of \`${near}\` — a ${action} step requires \`${near}\`, and as written it is missing while \`${k}\` is never read`, `rename \`${k}\` to \`${near}\``);
3027
- } else warn(`${p}.${k}`, `\`${k}\` is not a field of a ${action} step — the engine never reads it, so it changes nothing`, near ? `rename \`${k}\` to \`${near}\`` : `remove it — a ${action} step's fields are: ${fields.join(", ")}`);
3471
+ err(`${p}.${k}`, `\`${k}\` looks like a misspelling of \`${near$1}\` — a ${action} step requires \`${near$1}\`, and as written it is missing while \`${k}\` is never read`, `rename \`${k}\` to \`${near$1}\``);
3472
+ } else warn(`${p}.${k}`, `\`${k}\` is not a field of a ${action} step — the engine never reads it, so it changes nothing`, near$1 ? `rename \`${k}\` to \`${near$1}\`` : `remove it — a ${action} step's fields are: ${fields.join(", ")}`);
3028
3473
  }
3029
- if (fields.includes("zoom") && s.zoom !== void 0 && !(typeof s.zoom === "string" && ZOOMS.includes(s.zoom))) err(`${p}.zoom`, `zoom must be one of "never" | "auto" | "always" (got ${show(s.zoom)})`, "\"auto\" lets the heuristic decide; \"never\" keeps full view; \"always\" forces the fit-zoom");
3474
+ if (fields.includes("zoom") && s.zoom !== void 0 && !(typeof s.zoom === "string" && ZOOMS.includes(s.zoom))) err(`${p}.zoom`, `zoom must be one of "never" | "auto" | "always" (got ${show$1(s.zoom)})`, "\"auto\" lets the heuristic decide; \"never\" keeps full view; \"always\" forces the fit-zoom");
3030
3475
  const target = isStr(s.selector) || isStr(s.text);
3031
3476
  const needTarget = () => {
3032
3477
  if (target || covered.has("text")) return;
3033
3478
  const misTyped = s.selector !== void 0 ? "selector" : s.text !== void 0 ? "text" : null;
3034
3479
  if (misTyped) {
3035
- err(`${p}.${misTyped}`, `\`${misTyped}\` must be a string (got ${show(s[misTyped])}) — the engine's locator only takes strings`, `quote it: "${misTyped}":"…"`);
3480
+ err(`${p}.${misTyped}`, `\`${misTyped}\` must be a string (got ${show$1(s[misTyped])}) — the engine's locator only takes strings`, `quote it: "${misTyped}":"…"`);
3036
3481
  return;
3037
3482
  }
3038
3483
  const what = action === "type" ? "the field to type into" : action === "select" ? "the <select> to pick from" : "a target element";
@@ -3049,38 +3494,38 @@ function lintPlan(plan) {
3049
3494
  needTarget();
3050
3495
  if (covered.has("value")) break;
3051
3496
  const what = action === "type" ? "the string to type" : "the option to pick (its value, or its visible label)";
3052
- if (s.value === void 0) err(`${p}.value`, `${action} step has no \`value\` — \`value\` is ${what}; the TARGET element goes in \`selector\` (CSS) or \`text\` (its accessible name). Content written into \`text\` makes the engine search for an element NAMED that content — not found, so the step is skipped`, isStr(s.text) ? `if ${show(s.text)} is the content, rewrite as {"action":"${action}","value":${JSON.stringify(s.text)},"text":"<the target's accessible name>"} (or \`selector\`: its CSS)` : `add value (${what})`);
3053
- else if (typeof s.value !== "string") err(`${p}.value`, `value must be a string — ${what} (got ${show(s.value)})`, `rewrite as "value": ${JSON.stringify(String(s.value))}`);
3497
+ if (s.value === void 0) err(`${p}.value`, `${action} step has no \`value\` — \`value\` is ${what}; the TARGET element goes in \`selector\` (CSS) or \`text\` (its accessible name). Content written into \`text\` makes the engine search for an element NAMED that content — not found, so the step is skipped`, isStr(s.text) ? `if ${show$1(s.text)} is the content, rewrite as {"action":"${action}","value":${JSON.stringify(s.text)},"text":"<the target's accessible name>"} (or \`selector\`: its CSS)` : `add value (${what})`);
3498
+ else if (typeof s.value !== "string") err(`${p}.value`, `value must be a string — ${what} (got ${show$1(s.value)})`, `rewrite as "value": ${JSON.stringify(String(s.value))}`);
3054
3499
  break;
3055
3500
  }
3056
3501
  case "press":
3057
- if (!covered.has("keys") && !isStr(s.keys)) err(`${p}.keys`, s.keys === void 0 ? "press step has no `keys` — the chord to press: a named key (\"Enter\", \"Escape\", \"ArrowDown\") or a \"+\"-joined combo (\"Meta+k\", \"Control+Shift+p\")" : `keys must be a single chord string (got ${show(s.keys)}) — a named key ("Enter") or a "+"-joined combo ("Meta+k")`, "add keys, e.g. {\"action\":\"press\",\"keys\":\"Enter\"}");
3502
+ if (!covered.has("keys") && !isStr(s.keys)) err(`${p}.keys`, s.keys === void 0 ? "press step has no `keys` — the chord to press: a named key (\"Enter\", \"Escape\", \"ArrowDown\") or a \"+\"-joined combo (\"Meta+k\", \"Control+Shift+p\")" : `keys must be a single chord string (got ${show$1(s.keys)}) — a named key ("Enter") or a "+"-joined combo ("Meta+k")`, "add keys, e.g. {\"action\":\"press\",\"keys\":\"Enter\"}");
3058
3503
  break;
3059
3504
  case "scroll":
3060
3505
  if (s.dy !== void 0 && !isNum(s.dy)) {
3061
3506
  const n = toInt(s.dy);
3062
- err(`${p}.dy`, `dy must be a number of viewport px, positive = down (got ${show(s.dy)})`, n !== void 0 ? `set dy to ${n} (a number, not a string)` : "set dy to a number, e.g. 600");
3507
+ err(`${p}.dy`, `dy must be a number of viewport px, positive = down (got ${show$1(s.dy)})`, n !== void 0 ? `set dy to ${n} (a number, not a string)` : "set dy to a number, e.g. 600");
3063
3508
  } else if (s.dy === void 0 && !isStr(s.toSelector) && !isStr(s.toText)) err(p, "scroll step has none of `toSelector`/`toText`/`dy` — nothing names where to scroll", "add `dy` (viewport px, positive = down), or `toSelector`/`toText` to scroll until that element is centred");
3064
3509
  break;
3065
3510
  case "drag": {
3066
3511
  const pathOk = Array.isArray(s.path) && s.path.length > 0 && s.path.every(isPoint);
3067
- if (s.path !== void 0 && !pathOk) err(`${p}.path`, `path must be a non-empty array of viewport points {"x":<px>,"y":<px>} (got ${show(s.path)})`, "e.g. \"path\":[{\"x\":200,\"y\":300},{\"x\":420,\"y\":180}]");
3512
+ if (s.path !== void 0 && !pathOk) err(`${p}.path`, `path must be a non-empty array of viewport points {"x":<px>,"y":<px>} (got ${show$1(s.path)})`, "e.g. \"path\":[{\"x\":200,\"y\":300},{\"x\":420,\"y\":180}]");
3068
3513
  const fromBad = s.from !== void 0 && !isPoint(s.from);
3069
- if (fromBad) err(`${p}.from`, `from must be a viewport point {"x":<px>,"y":<px>} (got ${show(s.from)})`, "e.g. \"from\":{\"x\":320,\"y\":240}");
3514
+ if (fromBad) err(`${p}.from`, `from must be a viewport point {"x":<px>,"y":<px>} (got ${show$1(s.from)})`, "e.g. \"from\":{\"x\":320,\"y\":240}");
3070
3515
  const toBad = s.to !== void 0 && !isPoint(s.to);
3071
- if (toBad) err(`${p}.to`, `to must be a viewport point {"x":<px>,"y":<px>} (got ${show(s.to)})`, "e.g. \"to\":{\"x\":760,\"y\":420}");
3516
+ if (toBad) err(`${p}.to`, `to must be a viewport point {"x":<px>,"y":<px>} (got ${show$1(s.to)})`, "e.g. \"to\":{\"x\":760,\"y\":420}");
3072
3517
  if (!fromBad && s.from === void 0 && !target && s.path === void 0 && !covered.has("text")) err(p, "drag step has no start — give `selector`/`text` (the element to pick up) or `from` (a viewport point), else the step is skipped", "add e.g. \"from\":{\"x\":320,\"y\":240}, or name the element to pick up");
3073
3518
  if (!toBad && s.to === void 0 && !isStr(s.toSelector) && !isStr(s.toText) && s.path === void 0) err(p, "drag step has no end — give `toSelector`/`toText` (the drop target) or `to` (a viewport point), else the step is skipped", "add e.g. \"to\":{\"x\":760,\"y\":420}, or name the drop target");
3074
3519
  break;
3075
3520
  }
3076
3521
  case "dropFiles": {
3077
3522
  const pathsOk = Array.isArray(s.paths) && s.paths.length > 0 && s.paths.every((x) => isStr(x));
3078
- if (!covered.has("paths") && !pathsOk) err(`${p}.paths`, s.paths === void 0 ? "dropFiles step has no `paths` — the real files to drag in: a non-empty array of file paths (resolved against the process cwd)" : `paths must be a non-empty array of file-path strings (got ${show(s.paths)})`, "add paths, e.g. {\"action\":\"dropFiles\",\"paths\":[\"./assets/logo.png\"],\"toText\":\"Drop files here\"}");
3523
+ if (!covered.has("paths") && !pathsOk) err(`${p}.paths`, s.paths === void 0 ? "dropFiles step has no `paths` — the real files to drag in: a non-empty array of file paths (resolved against the process cwd)" : `paths must be a non-empty array of file-path strings (got ${show$1(s.paths)})`, "add paths, e.g. {\"action\":\"dropFiles\",\"paths\":[\"./assets/logo.png\"],\"toText\":\"Drop files here\"}");
3079
3524
  break;
3080
3525
  }
3081
3526
  case "navigate":
3082
- if (s.hrefFrom !== void 0 && !(isObj(s.hrefFrom) && (isStr(s.hrefFrom.selector) || isStr(s.hrefFrom.text)))) err(`${p}.hrefFrom`, `hrefFrom names the link whose href to follow and needs \`selector\` or \`text\` (got ${show(s.hrefFrom)}) — without one the step is skipped`, "use \"hrefFrom\":{\"text\":\"<the link's accessible name>\"}");
3083
- if (s.query !== void 0 && !(isObj(s.query) && Object.values(s.query).every((v) => isStr(v)))) err(`${p}.query`, `query must be an object of string params (got ${show(s.query)}) — anything else appends garbage to the destination URL`, "use e.g. \"query\":{\"speed\":\"3\"}");
3527
+ if (s.hrefFrom !== void 0 && !(isObj(s.hrefFrom) && (isStr(s.hrefFrom.selector) || isStr(s.hrefFrom.text)))) err(`${p}.hrefFrom`, `hrefFrom names the link whose href to follow and needs \`selector\` or \`text\` (got ${show$1(s.hrefFrom)}) — without one the step is skipped`, "use \"hrefFrom\":{\"text\":\"<the link's accessible name>\"}");
3528
+ if (s.query !== void 0 && !(isObj(s.query) && Object.values(s.query).every((v) => isStr(v)))) err(`${p}.query`, `query must be an object of string params (got ${show$1(s.query)}) — anything else appends garbage to the destination URL`, "use e.g. \"query\":{\"speed\":\"3\"}");
3084
3529
  break;
3085
3530
  }
3086
3531
  }
@@ -3093,7 +3538,7 @@ function lintWait(s, p, err, warn) {
3093
3538
  carrier = unknown.find((k) => toInt(s[k]) !== void 0);
3094
3539
  const n = carrier ? toInt(s[carrier]) : toInt(s.ms);
3095
3540
  if (carrier) err(`${p}.${carrier}`, `\`${carrier}\` looks like it means \`ms\`, but ${WAIT_SHAPE} — so this wait silently does not happen`, `rewrite as {"action":"wait","ms":${n}}`);
3096
- else if (s.ms !== void 0) err(`${p}.ms`, `ms must be an integer count of milliseconds (got ${show(s.ms)}) — ${WAIT_SHAPE}`, n !== void 0 ? `rewrite as {"action":"wait","ms":${n}}` : "set ms to a whole number of milliseconds, e.g. 800");
3541
+ else if (s.ms !== void 0) err(`${p}.ms`, `ms must be an integer count of milliseconds (got ${show$1(s.ms)}) — ${WAIT_SHAPE}`, n !== void 0 ? `rewrite as {"action":"wait","ms":${n}}` : "set ms to a whole number of milliseconds, e.g. 800");
3097
3542
  else err(`${p}.ms`, `wait step has no \`ms\` — ${WAIT_SHAPE}, so this wait silently does not happen`, "add ms, e.g. {\"action\":\"wait\",\"ms\":800}");
3098
3543
  }
3099
3544
  for (const k of unknown) {
@@ -3103,70 +3548,446 @@ function lintWait(s, p, err, warn) {
3103
3548
  }
3104
3549
 
3105
3550
  //#endregion
3106
- //#region src/notes.ts
3107
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
3108
- const fileSize = async (p) => (await stat(p).catch(() => null))?.size ?? 0;
3109
- const readBytes = async (p) => await readFile(p).catch(() => Buffer.alloc(0));
3110
- const readCursor = async (p) => {
3111
- const n = Number((await readFile(p, "utf8").catch(() => "")).trim());
3112
- return Number.isFinite(n) && n >= 0 ? n : 0;
3551
+ //#region src/materials.ts
3552
+ /** Most image files fetched for one page, how long each may take, and how
3553
+ * large one may be. Past them an image is listed with its URL and why. */
3554
+ const FETCH_MAX = 120;
3555
+ const FETCH_TIMEOUT_MS = 15e3;
3556
+ const FETCH_MAX_BYTES = 25 * 1024 * 1024;
3557
+ const FETCH_PARALLEL = 6;
3558
+ /** all of a page's fetches together */
3559
+ const FETCH_BUDGET_MS = 6e4;
3560
+ /** the sheet: px per column, and the most page px it shows */
3561
+ const SHEET_COLUMN_PX = 360;
3562
+ const SHEET_MAX_PAGE_PX = 24e3;
3563
+ /** Read the page open in `cdp` with the materials probe (read-only). */
3564
+ async function readPageMaterials(cdp) {
3565
+ const r = await cdp.send("Runtime.evaluate", {
3566
+ expression: materialsProbeExpression(),
3567
+ returnByValue: true
3568
+ });
3569
+ const raw = r.result?.value;
3570
+ if (typeof raw !== "string") throw new Error(`the materials probe returned nothing (${r.exceptionDetails?.text ?? "?"})`);
3571
+ const res = JSON.parse(raw);
3572
+ if ("error" in res) throw new Error(`the materials probe failed: ${res.error.split("\n")[0]}`);
3573
+ return res;
3574
+ }
3575
+ const EXT = {
3576
+ "image/jpeg": "jpg",
3577
+ "image/jpg": "jpg",
3578
+ "image/png": "png",
3579
+ "image/gif": "gif",
3580
+ "image/webp": "webp",
3581
+ "image/avif": "avif",
3582
+ "image/svg+xml": "svg",
3583
+ "image/x-icon": "ico",
3584
+ "image/vnd.microsoft.icon": "ico",
3585
+ "image/bmp": "bmp"
3113
3586
  };
3114
- /** `- opening is too slow` → `opening is too slow`; blank lines and stray text
3115
- * are tolerated. Notes are free text in any language — never parsed for meaning. */
3116
- const parseNotes = (buf) => buf.toString("utf8").split("\n").map((l) => l.replace(/^-\s*/, "").trim()).filter((l) => l.length > 0);
3117
- /** The notes appended since the last read, and how many the log holds.
3118
- * Advances the cursor unless `peek`, so a note is delivered exactly once. */
3119
- async function readNotes(take, opts = {}) {
3120
- const buf = await readBytes(take.notesPath);
3121
- const saved = await readCursor(take.notesCursorPath);
3122
- const from = opts.all || saved > buf.length ? 0 : saved;
3123
- const end = buf.lastIndexOf(10) + 1;
3124
- const slice = end > from ? buf.subarray(from, end) : Buffer.alloc(0);
3125
- const cursor = Math.max(from, end);
3126
- if (!opts.peek && cursor !== saved) await writeFile(take.notesCursorPath, `${cursor}\n`).catch(() => {});
3127
- return {
3128
- notes: parseNotes(slice),
3129
- total: parseNotes(buf).length,
3130
- cursor
3131
- };
3587
+ /** a file's extension from its bytes, else its stated type */
3588
+ function extOf(buf, type) {
3589
+ if (buf.length >= 4 && buf.readUInt32BE(0) === 2303741511) return "png";
3590
+ if (buf.length >= 3 && buf[0] === 255 && buf[1] === 216) return "jpg";
3591
+ if (buf.length >= 3 && buf.toString("latin1", 0, 3) === "GIF") return "gif";
3592
+ if (buf.length >= 12 && buf.toString("latin1", 8, 12) === "WEBP") return "webp";
3593
+ if (buf.length >= 12 && /^ftypavi[fs]$/.test(buf.toString("latin1", 4, 12))) return "avif";
3594
+ if (/<svg\b/i.test(buf.toString("utf8", 0, Math.min(buf.length, 2048)))) return "svg";
3595
+ return EXT[type.split(";")[0].trim().toLowerCase()] ?? null;
3132
3596
  }
3133
- /** Block until at least one unread note exists, then return it (and consume
3134
- * it). Returns immediately when the log already has unread notes — a waiter
3135
- * started after the user typed still delivers, which is what makes restarting
3136
- * one between rounds lossless. */
3137
- async function waitForNotes(take, opts = {}) {
3138
- const timeoutMs = opts.timeoutMs ?? 30 * 6e4;
3139
- const pollMs = opts.pollMs ?? 500;
3140
- const settleMs = opts.settleMs ?? 800;
3141
- const deadline = Date.now() + timeoutMs;
3142
- let last = await readNotes(take, opts);
3143
- if (last.notes.length) return {
3144
- ...last,
3145
- timedOut: false
3597
+ /**
3598
+ * Save what `materialsFromProbe` named for each image — fetch a URL, decode
3599
+ * a data: URL, write an svg's markup, point at a file:// one already in the
3600
+ * assets — into `assetsDir` (content-named, shared), and fill each image's
3601
+ * `file`, `fileSize`, `bytes` or `notSaved`; the page's og:image too.
3602
+ */
3603
+ async function saveMaterialFiles(args) {
3604
+ const t0 = Date.now();
3605
+ const { file, stateDir, assetsDir } = args;
3606
+ mkdirSync(assetsDir, { recursive: true });
3607
+ const rel$1 = (p) => relative(stateDir, p).split(sep).join("/");
3608
+ const keep = (buf, ext) => {
3609
+ const name = `${createHash("sha1").update(buf).digest("hex")}.${ext}`;
3610
+ const path = join(assetsDir, name);
3611
+ if (!existsSync(path)) writeFileSync(path, buf);
3612
+ const size = imageFileSize(buf);
3613
+ return {
3614
+ file: rel$1(path),
3615
+ ...size ? { fileSize: size } : {},
3616
+ bytes: buf.length
3617
+ };
3146
3618
  };
3147
- let seen = await fileSize(take.notesPath);
3148
- while (!opts.signal?.aborted && Date.now() < deadline) {
3149
- await sleep(Math.min(pollMs, Math.max(0, deadline - Date.now())));
3150
- if (opts.signal?.aborted) break;
3151
- if (await fileSize(take.notesPath) === seen) continue;
3152
- if (settleMs > 0) await sleep(settleMs);
3153
- last = await readNotes(take, {
3154
- ...opts,
3155
- all: false
3619
+ const deadline = t0 + FETCH_BUDGET_MS;
3620
+ let fetches = 0;
3621
+ const fetched = new Map();
3622
+ const fetchOne = (url) => {
3623
+ let p = fetched.get(url);
3624
+ if (!p) {
3625
+ p = (async () => {
3626
+ if (url.startsWith("file:")) {
3627
+ const path = fileURLToPath(url);
3628
+ if (!existsSync(path)) return { notSaved: "its saved file is not there" };
3629
+ const buf = readFileSync(path);
3630
+ const size = imageFileSize(buf);
3631
+ return {
3632
+ file: rel$1(path),
3633
+ ...size ? { fileSize: size } : {},
3634
+ bytes: buf.length
3635
+ };
3636
+ }
3637
+ if (!/^https?:/i.test(url)) return { notSaved: "not a URL that can be fetched" };
3638
+ if (adHost(url)) return { notSaved: "an ad or tracking host" };
3639
+ if (++fetches > FETCH_MAX) return { notSaved: `past the ${FETCH_MAX} files fetched per page` };
3640
+ const left = deadline - Date.now();
3641
+ if (left <= 0) return { notSaved: `past the ${FETCH_BUDGET_MS / 1e3} s spent fetching this page's images` };
3642
+ try {
3643
+ const res = await fetch(url, {
3644
+ headers: {
3645
+ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36",
3646
+ accept: "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
3647
+ referer: file.url
3648
+ },
3649
+ signal: AbortSignal.timeout(Math.min(FETCH_TIMEOUT_MS, left))
3650
+ });
3651
+ if (!res.ok) return { notSaved: `HTTP ${res.status}` };
3652
+ const type = res.headers.get("content-type") ?? "";
3653
+ const len = Number(res.headers.get("content-length") ?? 0);
3654
+ if (len > FETCH_MAX_BYTES) return { notSaved: `${Math.round(len / 1048576)} MB` };
3655
+ const buf = Buffer.from(await res.arrayBuffer());
3656
+ if (buf.length > FETCH_MAX_BYTES) return { notSaved: `${Math.round(buf.length / 1048576)} MB` };
3657
+ const ext = extOf(buf, type);
3658
+ if (!ext) return { notSaved: `not an image (${type.split(";")[0] || "no type"})` };
3659
+ return keep(buf, ext);
3660
+ } catch (e) {
3661
+ const why = e.name === "TimeoutError" ? "the fetch timed out" : e.message;
3662
+ return { notSaved: `not fetched (${why})` };
3663
+ }
3664
+ })();
3665
+ fetched.set(url, p);
3666
+ }
3667
+ return p;
3668
+ };
3669
+ const jobs = [];
3670
+ file.images.forEach((im, i) => {
3671
+ const s = args.save[i];
3672
+ if (!s) {
3673
+ im.notSaved = im.kind === "canvas" ? "drawn by the page's script (a canvas)" : im.kind === "video" ? "a video (not fetched), no poster" : file.read === "saved screen" ? "not in the saved screen (the page had not loaded it)" : "no source that can be fetched";
3674
+ return;
3675
+ }
3676
+ jobs.push(async () => {
3677
+ let r;
3678
+ if ("markup" in s) r = keep(Buffer.from(s.markup, "utf8"), "svg");
3679
+ else if ("data" in s) {
3680
+ const m = /^data:([^;,]*)(;base64)?,(.*)$/s.exec(s.data);
3681
+ if (!m) r = { notSaved: "an unreadable data: URL" };
3682
+ else {
3683
+ const buf = m[2] ? Buffer.from(m[3], "base64") : Buffer.from(decodeURIComponent(m[3]), "utf8");
3684
+ const ext = extOf(buf, m[1] ?? "");
3685
+ r = ext ? keep(buf, ext) : { notSaved: `not an image (${m[1] || "no type"})` };
3686
+ }
3687
+ } else r = await fetchOne(s.url);
3688
+ Object.assign(im, r);
3156
3689
  });
3157
- seen = await fileSize(take.notesPath);
3158
- if (last.notes.length) return {
3159
- ...last,
3160
- timedOut: false
3161
- };
3690
+ });
3691
+ if (file.meta.ogImage) jobs.push(async () => {
3692
+ const r = await fetchOne(file.meta.ogImage);
3693
+ if ("file" in r) file.meta.ogImageFile = r.file;
3694
+ });
3695
+ let next = 0;
3696
+ await Promise.all(Array.from({ length: Math.min(FETCH_PARALLEL, jobs.length) }, async () => {
3697
+ while (next < jobs.length) await jobs[next++]();
3698
+ }));
3699
+ file.ms.files = Date.now() - t0;
3700
+ }
3701
+ /**
3702
+ * The page open in `cdp` (a restored state.html, laid out) drawn top to
3703
+ * bottom, small, cut into columns side by side: `<stateDir>/sheet.jpg`.
3704
+ * The picture is taken beyond the viewport (nothing scrolls); a page taller
3705
+ * than SHEET_MAX_PAGE_PX shows its first that many px. Without ffmpeg the
3706
+ * sheet is one column, as a PNG.
3707
+ */
3708
+ async function takeSheet(cdp, opts) {
3709
+ const r = await cdp.send("Runtime.evaluate", {
3710
+ expression: "Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0, innerHeight)",
3711
+ returnByValue: true
3712
+ });
3713
+ const pageH = Math.max(1, Math.round(r.result?.value ?? 0));
3714
+ const covered = Math.min(pageH, SHEET_MAX_PAGE_PX);
3715
+ const scale = SHEET_COLUMN_PX / opts.vw;
3716
+ const shot = await cdp.send("Page.captureScreenshot", {
3717
+ format: "png",
3718
+ captureBeyondViewport: true,
3719
+ clip: {
3720
+ x: 0,
3721
+ y: 0,
3722
+ width: opts.vw,
3723
+ height: covered,
3724
+ scale
3725
+ }
3726
+ }, { timeoutMs: 12e4 });
3727
+ const png = Buffer.from(shot.data, "base64");
3728
+ const [w, h] = imageFileSize(png) ?? [SHEET_COLUMN_PX, Math.round(covered * scale)];
3729
+ const columns = opts.ffmpeg ? Math.max(1, Math.min(8, Math.round(Math.sqrt(1.6 * h / w)))) : 1;
3730
+ if (columns === 1) {
3731
+ const name = opts.ffmpeg ? "sheet.jpg" : "sheet.png";
3732
+ if (opts.ffmpeg) await toJpeg(opts.ffmpeg, png, join(opts.stateDir, name), "null");
3733
+ else await writeFile(join(opts.stateDir, name), png);
3734
+ return sheetInfo(name, 1, covered, scale, covered);
3162
3735
  }
3163
- return {
3164
- ...last,
3165
- notes: [],
3166
- timedOut: true
3167
- };
3736
+ const ch = Math.ceil(h / columns);
3737
+ const gap = 12;
3738
+ const parts = [`[0]split=${columns}${Array.from({ length: columns }, (_, k) => `[s${k}]`).join("")}`];
3739
+ for (let k = 0; k < columns; k++) {
3740
+ const y = k * ch;
3741
+ const hk = Math.max(1, Math.min(ch, h - y));
3742
+ parts.push(`[s${k}]crop=${w}:${hk}:0:${y},pad=${w + (k < columns - 1 ? gap : 0)}:${ch}:0:0:color=0x9a9a9a[c${k}]`);
3743
+ }
3744
+ parts.push(`${Array.from({ length: columns }, (_, k) => `[c${k}]`).join("")}hstack=inputs=${columns}`);
3745
+ await toJpeg(opts.ffmpeg, png, join(opts.stateDir, "sheet.jpg"), parts.join(";"));
3746
+ return sheetInfo("sheet.jpg", columns, Math.ceil(covered / columns), scale, covered);
3168
3747
  }
3169
- const rel = (p) => p.replace(`${process.cwd()}/`, "");
3748
+ const sheetInfo = (file, columns, columnPx, scale, coveredPx) => ({
3749
+ file,
3750
+ columns,
3751
+ columnPx,
3752
+ scale: Math.round(scale * 1e4) / 1e4,
3753
+ coveredPx,
3754
+ from: "saved screen"
3755
+ });
3756
+ async function toJpeg(ffmpeg$1, png, out, graph) {
3757
+ const dir = await mkdtemp(join(tmpdir(), "open-take-sheet-"));
3758
+ try {
3759
+ const src = join(dir, "page.png");
3760
+ await writeFile(src, png);
3761
+ await runBuffer(ffmpeg$1, [
3762
+ "-v",
3763
+ "error",
3764
+ "-y",
3765
+ "-i",
3766
+ src,
3767
+ ...graph === "null" ? [] : ["-filter_complex", graph],
3768
+ "-frames:v",
3769
+ "1",
3770
+ "-q:v",
3771
+ "3",
3772
+ out
3773
+ ]);
3774
+ } finally {
3775
+ await rm(dir, {
3776
+ recursive: true,
3777
+ force: true
3778
+ });
3779
+ }
3780
+ }
3781
+ function writeMaterials(file, stateDir) {
3782
+ const path = join(stateDir, "materials.json");
3783
+ writeFileSync(path, `${JSON.stringify(file, null, 2)}\n`);
3784
+ return path;
3785
+ }
3786
+ /** One page read live (a shoot): pick, save and write — never throws past a
3787
+ * line in `note`; null when it could not be written. */
3788
+ async function finishPageMaterials(args) {
3789
+ try {
3790
+ const { file, save } = materialsFromProbe(args.res, {
3791
+ state: args.id,
3792
+ read: "live"
3793
+ });
3794
+ await saveMaterialFiles({
3795
+ file,
3796
+ save,
3797
+ stateDir: args.stateDir,
3798
+ assetsDir: args.assetsDir
3799
+ });
3800
+ if (args.sheet) {
3801
+ const { ms,...sheet } = args.sheet;
3802
+ file.sheet = sheet;
3803
+ if (ms != null) file.ms.sheet = ms;
3804
+ }
3805
+ const path = writeMaterials(file, args.stateDir);
3806
+ return {
3807
+ id: args.id,
3808
+ dir: args.stateDir,
3809
+ file,
3810
+ path
3811
+ };
3812
+ } catch (e) {
3813
+ args.note(`shoot: no materials.json for ${args.id} (${e.message})`);
3814
+ return null;
3815
+ }
3816
+ }
3817
+ /** `open-take materials`: the materials.json of each page a source's saved
3818
+ * screens show — read from a state.html where a page has none. */
3819
+ async function inventoryMaterials(opts) {
3820
+ let source;
3821
+ try {
3822
+ source = readComponentSource(opts.path);
3823
+ } catch (e) {
3824
+ throw new Error(e.message.replace(/^components:/, "materials:"));
3825
+ }
3826
+ if (opts.state && !source.states.some((s) => s.id === opts.state)) throw new Error(`materials: no saved screen ${opts.state} here (it has ${source.states.map((s) => s.id).join(", ") || "none"})`);
3827
+ const scoped = opts.state ? {
3828
+ ...source,
3829
+ states: source.states.filter((s) => s.id === opts.state)
3830
+ } : source;
3831
+ const { pages, missing } = readMaterials(scoped);
3832
+ const read = [];
3833
+ const failed = [];
3834
+ if (missing.length && opts.measure !== false) {
3835
+ const first = readStateIndex(missing[0].dir);
3836
+ const vp = typeof first === "string" ? {
3837
+ w: 1920,
3838
+ h: 1080
3839
+ } : first.viewport;
3840
+ const browser = await launchBrowser({
3841
+ width: vp.w,
3842
+ height: vp.h,
3843
+ chromePath: await ensureChrome(opts.chromePath)
3844
+ });
3845
+ let ffmpeg$1;
3846
+ try {
3847
+ ffmpeg$1 = await resolveFfmpeg();
3848
+ } catch {}
3849
+ let page = null;
3850
+ try {
3851
+ for (const m of missing) {
3852
+ const index = readStateIndex(m.dir);
3853
+ if (typeof index === "string") {
3854
+ failed.push({
3855
+ state: m.id,
3856
+ why: index
3857
+ });
3858
+ continue;
3859
+ }
3860
+ const { w, h } = index.viewport;
3861
+ try {
3862
+ page = page ?? await openFidelityPage(browser, w, h);
3863
+ await page.cdp.send("Emulation.setDeviceMetricsOverride", {
3864
+ width: w,
3865
+ height: h,
3866
+ deviceScaleFactor: 1,
3867
+ mobile: false
3868
+ });
3869
+ await renderState(page.cdp, join(m.dir, "state.html"), w, h);
3870
+ const res = await readPageMaterials(page.cdp);
3871
+ res.url = index.url;
3872
+ res.title = index.title || res.title;
3873
+ const { file, save } = materialsFromProbe(res, {
3874
+ state: m.id,
3875
+ read: "saved screen"
3876
+ });
3877
+ await saveMaterialFiles({
3878
+ file,
3879
+ save,
3880
+ stateDir: m.dir,
3881
+ assetsDir: join(m.dir, "..", "assets")
3882
+ });
3883
+ const t0 = Date.now();
3884
+ file.sheet = await takeSheet(page.cdp, {
3885
+ stateDir: m.dir,
3886
+ vw: w,
3887
+ ffmpeg: ffmpeg$1
3888
+ });
3889
+ file.ms.sheet = Date.now() - t0;
3890
+ pages.push({
3891
+ id: m.id,
3892
+ dir: m.dir,
3893
+ file,
3894
+ path: writeMaterials(file, m.dir)
3895
+ });
3896
+ read.push(m.id);
3897
+ } catch (e) {
3898
+ failed.push({
3899
+ state: m.id,
3900
+ why: e.message
3901
+ });
3902
+ if (page && isCdpStall(e)) {
3903
+ await closeFidelityPage(browser, page);
3904
+ page = null;
3905
+ }
3906
+ }
3907
+ }
3908
+ } finally {
3909
+ if (page) await closeFidelityPage(browser, page);
3910
+ await browser.close();
3911
+ }
3912
+ } else for (const m of missing) failed.push({
3913
+ state: m.id,
3914
+ why: "no materials.json (not read: Chrome off)"
3915
+ });
3916
+ const order = new Map(source.states.map((s, i) => [s.id, i]));
3917
+ pages.sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0));
3918
+ return {
3919
+ pages,
3920
+ source,
3921
+ read,
3922
+ failed
3923
+ };
3924
+ }
3925
+
3926
+ //#endregion
3927
+ //#region src/notes.ts
3928
+ const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
3929
+ const fileSize = async (p) => (await stat(p).catch(() => null))?.size ?? 0;
3930
+ const readBytes = async (p) => await readFile(p).catch(() => Buffer.alloc(0));
3931
+ const readCursor = async (p) => {
3932
+ const n = Number((await readFile(p, "utf8").catch(() => "")).trim());
3933
+ return Number.isFinite(n) && n >= 0 ? n : 0;
3934
+ };
3935
+ /** `- opening is too slow` → `opening is too slow`; blank lines and stray text
3936
+ * are tolerated. Notes are free text in any language — never parsed for meaning. */
3937
+ const parseNotes = (buf) => buf.toString("utf8").split("\n").map((l) => l.replace(/^-\s*/, "").trim()).filter((l) => l.length > 0);
3938
+ /** The notes appended since the last read, and how many the log holds.
3939
+ * Advances the cursor unless `peek`, so a note is delivered exactly once. */
3940
+ async function readNotes(take, opts = {}) {
3941
+ const buf = await readBytes(take.notesPath);
3942
+ const saved = await readCursor(take.notesCursorPath);
3943
+ const from = opts.all || saved > buf.length ? 0 : saved;
3944
+ const end = buf.lastIndexOf(10) + 1;
3945
+ const slice = end > from ? buf.subarray(from, end) : Buffer.alloc(0);
3946
+ const cursor = Math.max(from, end);
3947
+ if (!opts.peek && cursor !== saved) await writeFile(take.notesCursorPath, `${cursor}\n`).catch(() => {});
3948
+ return {
3949
+ notes: parseNotes(slice),
3950
+ total: parseNotes(buf).length,
3951
+ cursor
3952
+ };
3953
+ }
3954
+ /** Block until at least one unread note exists, then return it (and consume
3955
+ * it). Returns immediately when the log already has unread notes — a waiter
3956
+ * started after the user typed still delivers, which is what makes restarting
3957
+ * one between rounds lossless. */
3958
+ async function waitForNotes(take, opts = {}) {
3959
+ const timeoutMs = opts.timeoutMs ?? 30 * 6e4;
3960
+ const pollMs = opts.pollMs ?? 500;
3961
+ const settleMs = opts.settleMs ?? 800;
3962
+ const deadline = Date.now() + timeoutMs;
3963
+ let last = await readNotes(take, opts);
3964
+ if (last.notes.length) return {
3965
+ ...last,
3966
+ timedOut: false
3967
+ };
3968
+ let seen = await fileSize(take.notesPath);
3969
+ while (!opts.signal?.aborted && Date.now() < deadline) {
3970
+ await sleep$1(Math.min(pollMs, Math.max(0, deadline - Date.now())));
3971
+ if (opts.signal?.aborted) break;
3972
+ if (await fileSize(take.notesPath) === seen) continue;
3973
+ if (settleMs > 0) await sleep$1(settleMs);
3974
+ last = await readNotes(take, {
3975
+ ...opts,
3976
+ all: false
3977
+ });
3978
+ seen = await fileSize(take.notesPath);
3979
+ if (last.notes.length) return {
3980
+ ...last,
3981
+ timedOut: false
3982
+ };
3983
+ }
3984
+ return {
3985
+ ...last,
3986
+ notes: [],
3987
+ timedOut: true
3988
+ };
3989
+ }
3990
+ const rel = (p) => p.replace(`${process.cwd()}/`, "");
3170
3991
  /** The wake-up message. Written for an agent reading a finished background
3171
3992
  * command: what came in, and the one thing it must re-read before editing. */
3172
3993
  function formatNotes(take, res, opts = {}) {
@@ -3174,127 +3995,2504 @@ function formatNotes(take, res, opts = {}) {
3174
3995
  if (opts.waited && res.timedOut) return `no notes · ${take.name} (waited out)\n`;
3175
3996
  return res.total ? `no new notes · ${take.name} (${res.total} already read in ${rel(take.notesPath)})\n` : `no notes yet · ${take.name} (${rel(take.notesPath)})\n`;
3176
3997
  }
3177
- const head = `${res.notes.length} new note${res.notes.length > 1 ? "s" : ""} from the editor · ${take.name}`;
3178
- return [
3179
- head,
3180
- ...res.notes.map((n) => `- ${n}`),
3181
- `(re-read ${rel(take.compositionPath)} before editing it — the editor may have changed it too)`,
3182
- ""
3183
- ].join("\n");
3998
+ const head = `${res.notes.length} new note${res.notes.length > 1 ? "s" : ""} from the editor · ${take.name}`;
3999
+ return [
4000
+ head,
4001
+ ...res.notes.map((n) => `- ${n}`),
4002
+ `(re-read ${rel(take.compositionPath)} before editing it — the editor may have changed it too)`,
4003
+ ""
4004
+ ].join("\n");
4005
+ }
4006
+
4007
+ //#endregion
4008
+ //#region src/post-shoot.ts
4009
+ /** `make` withholds the healing re-render from a take that skipped steps
4010
+ * under strict: the skipped-steps exit 2 fires regardless of anything a
4011
+ * re-render could fix, so the render minutes buy nothing. */
4012
+ const healingWithheld = (skippedSteps, strict) => skippedSteps > 0 && strict;
4013
+ const countErrors = (issues) => issues.filter((i) => i.severity === "error").length;
4014
+ async function runPostShootGates(io) {
4015
+ const gate = async (name, run$1) => {
4016
+ try {
4017
+ return {
4018
+ issues: await run$1(),
4019
+ crashed: false
4020
+ };
4021
+ } catch (e) {
4022
+ io.warn(`${name} did not run: ${e instanceof Error ? e.message : e}`);
4023
+ return {
4024
+ issues: [],
4025
+ crashed: true
4026
+ };
4027
+ }
4028
+ };
4029
+ const pass = async () => ({
4030
+ check: await gate("take checks", io.checkTake),
4031
+ cursor: await gate("cursor audit", io.auditCursor)
4032
+ });
4033
+ const verdict = (p, reRendered) => {
4034
+ const issues = [...p.check.issues, ...p.cursor.issues];
4035
+ return {
4036
+ issues,
4037
+ errors: countErrors(issues),
4038
+ reRendered,
4039
+ crashed: [...p.check.crashed ? ["take checks"] : [], ...p.cursor.crashed ? ["cursor audit"] : []]
4040
+ };
4041
+ };
4042
+ const first = await pass();
4043
+ io.onFindings([...first.check.issues, ...first.cursor.issues], "post-shoot");
4044
+ const firstCursorErrors = countErrors(first.cursor.issues);
4045
+ if (!(firstCursorErrors > 0 && io.reRender)) return verdict(first, false);
4046
+ io.log("the cursor audit failed — re-rendering once from the frozen capture (a transient renderer misdraw heals; a repeat means the renderer disagrees with its own math) …");
4047
+ try {
4048
+ await io.reRender();
4049
+ } catch (e) {
4050
+ io.warn(`the re-render failed (${e instanceof Error ? e.message : e}) — keeping the first audit's findings`);
4051
+ return verdict(first, false);
4052
+ }
4053
+ const second = await pass();
4054
+ const carried = {
4055
+ check: second.check.crashed ? first.check : second.check,
4056
+ cursor: second.cursor.crashed ? first.cursor : second.cursor
4057
+ };
4058
+ io.onFindings([...carried.check.issues, ...carried.cursor.issues], "re-audit");
4059
+ io.log(second.cursor.crashed ? "re-audit could not re-measure the cursor — keeping the first audit's findings (a re-render that cannot be verified is not a heal)" : countErrors(second.cursor.issues) > 0 ? "re-audit: the drawn cursor is STILL off — the renderer disagrees with its own math on this take; that needs a look, not another retry" : "re-audit: cursor clean — the misdraw was transient; the delivered mp4 is now the re-render");
4060
+ return verdict(carried, true);
4061
+ }
4062
+
4063
+ //#endregion
4064
+ //#region src/steady.ts
4065
+ /** two readings this far apart, all equal, with nothing finite running */
4066
+ const STEADY_QUIET_MS = 100;
4067
+ const SAMPLE_MS = 50;
4068
+ /** text nodes read per screen; a page with more is read up to here */
4069
+ const MAX_TEXTS = 4e3;
4070
+ /** an expression for the page: the Screen, as a JSON string */
4071
+ const SCREEN_JS = `(() => {
4072
+ const vw = innerWidth, vh = innerHeight, out = [];
4073
+ const on = (r) => r.width >= 1 && r.height >= 1 && r.right > 0 && r.bottom > 0 && r.left < vw && r.top < vh;
4074
+ const shows = (el) => {
4075
+ if (typeof el.checkVisibility === "function")
4076
+ return el.checkVisibility({ opacityProperty: true, visibilityProperty: true });
4077
+ const cs = getComputedStyle(el);
4078
+ return cs.visibility === "visible" && cs.display !== "none";
4079
+ };
4080
+ try {
4081
+ if (document.body) {
4082
+ const range = document.createRange();
4083
+ const w = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
4084
+ for (let n = w.nextNode(); n && out.length < ${MAX_TEXTS}; n = w.nextNode()) {
4085
+ const v = (n.nodeValue || "").trim();
4086
+ if (!v) continue;
4087
+ const el = n.parentElement;
4088
+ if (!el || /^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE)$/.test(el.tagName) || !shows(el)) continue;
4089
+ range.selectNodeContents(n);
4090
+ const r = Array.from(range.getClientRects()).find(on);
4091
+ if (r) out.push([v.slice(0, 200), Math.round(r.left), Math.round(r.top)]);
4092
+ }
4093
+ for (const el of document.querySelectorAll("input:not([type=hidden]):not([type=password]),textarea")) {
4094
+ const v = String(el.value || "").trim();
4095
+ if (!v || out.length >= ${MAX_TEXTS}) continue;
4096
+ const r = el.getBoundingClientRect();
4097
+ if (on(r) && shows(el)) out.push([v.slice(0, 200), Math.round(r.left), Math.round(r.top)]);
4098
+ }
4099
+ }
4100
+ } catch (e) {}
4101
+ let a = 0;
4102
+ try {
4103
+ for (const an of document.getAnimations()) {
4104
+ if (an.playState !== "running") continue;
4105
+ let it = 1;
4106
+ try { it = an.effect.getTiming().iterations; } catch (e) {}
4107
+ if (it === Infinity) continue;
4108
+ const el = an.effect && an.effect.target;
4109
+ if (el && typeof el.getBoundingClientRect === "function" && !on(el.getBoundingClientRect())) continue;
4110
+ a++;
4111
+ }
4112
+ } catch (e) {}
4113
+ return JSON.stringify({ t: out, sx: scrollX, sy: scrollY, a });
4114
+ })()`;
4115
+ const sameScreen = (a, b) => {
4116
+ if (a.sx !== b.sx || a.sy !== b.sy || a.t.length !== b.t.length) return false;
4117
+ for (let i = 0; i < a.t.length; i++) {
4118
+ const x = a.t[i];
4119
+ const y = b.t[i];
4120
+ if (x[0] !== y[0] || x[1] !== y[1] || x[2] !== y[2]) return false;
4121
+ }
4122
+ return true;
4123
+ };
4124
+ /** What changed between two readings of the screen, the moment before a
4125
+ * still and the moment after it. `texts`: the texts that read differently —
4126
+ * paired by order when both readings hold as many texts (a number that
4127
+ * grows a digit moves but keeps its place in the page), else the ones only
4128
+ * one reading holds, paired in order; `moved`: the same text drawn
4129
+ * elsewhere, or the page scrolled. */
4130
+ function screenChange(a, b) {
4131
+ const texts = [];
4132
+ let moved = a.sx !== b.sx || a.sy !== b.sy;
4133
+ const at = (e, s) => ({
4134
+ x: e[1] + s.sx,
4135
+ y: e[2] + s.sy
4136
+ });
4137
+ if (a.t.length === b.t.length) a.t.forEach((x, i) => {
4138
+ const y = b.t[i];
4139
+ if (x[0] !== y[0]) texts.push({
4140
+ ...at(x, a),
4141
+ before: x[0],
4142
+ after: y[0]
4143
+ });
4144
+ else if (x[1] !== y[1] || x[2] !== y[2]) moved = true;
4145
+ });
4146
+ else {
4147
+ const key = (e) => `${e[0]}\u0000${e[1]}\u0000${e[2]}`;
4148
+ const inB = new Set(b.t.map(key));
4149
+ const inA = new Set(a.t.map(key));
4150
+ const onlyA = a.t.filter((e) => !inB.has(key(e)));
4151
+ const onlyB = b.t.filter((e) => !inA.has(key(e)));
4152
+ for (let i = 0; i < Math.max(onlyA.length, onlyB.length); i++) {
4153
+ const x = onlyA[i];
4154
+ const y = onlyB[i];
4155
+ texts.push({
4156
+ ...x ? at(x, a) : at(y, b),
4157
+ before: x?.[0] ?? "",
4158
+ after: y?.[0] ?? ""
4159
+ });
4160
+ }
4161
+ }
4162
+ return {
4163
+ texts,
4164
+ moved,
4165
+ animations: a.a
4166
+ };
4167
+ }
4168
+ /** Read the screen every SAMPLE_MS until it holds still for STEADY_QUIET_MS
4169
+ * with nothing finite running on it, or `budgetMs` runs out. `read` gives
4170
+ * one reading (null: the page could not be read — a navigation — and the
4171
+ * reading starts over). It only ever adds time; a page that is steady at
4172
+ * once costs STEADY_QUIET_MS. */
4173
+ async function waitSteady(read, budgetMs, o = {}) {
4174
+ const now = o.now ?? Date.now;
4175
+ const sleep$2 = o.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
4176
+ const start = now();
4177
+ let prev = await read();
4178
+ let since = now();
4179
+ let changed = !prev || prev.a > 0;
4180
+ for (;;) {
4181
+ const t = now();
4182
+ if (prev && prev.a === 0 && t - since >= STEADY_QUIET_MS) return {
4183
+ steady: true,
4184
+ waitedMs: t - start,
4185
+ changed
4186
+ };
4187
+ if (t - start >= budgetMs) return {
4188
+ steady: false,
4189
+ waitedMs: t - start,
4190
+ changed
4191
+ };
4192
+ await sleep$2(SAMPLE_MS);
4193
+ const cur = await read();
4194
+ if (!cur || !prev || cur.a > 0 || !sameScreen(prev, cur)) {
4195
+ since = now();
4196
+ changed = true;
4197
+ }
4198
+ prev = cur;
4199
+ }
4200
+ }
4201
+
4202
+ //#endregion
4203
+ //#region src/shoot.ts
4204
+ /** how long a target may take to appear and become reachable */
4205
+ const TARGET_WAIT_MS = 5e3;
4206
+ /** how long a page may take to show anything at all */
4207
+ const OPEN_WAIT_MS = 15e3;
4208
+ /** how long, once it shows something, a page with scripts may take to attach
4209
+ * its input handlers. Pays out in full only on a page whose scripts never
4210
+ * listen for input (a static page with analytics), so it is short. */
4211
+ const HANDLERS_WAIT_MS = 3e3;
4212
+ /** a fresh page's trailing requests (fonts, analytics, lazy chunks) */
4213
+ const OPEN_SETTLE_MS = 3e3;
4214
+ /** how long, once it shows something, a page may go on arriving — its own
4215
+ * scripts, styles, fonts and data still coming, or what it shows still
4216
+ * growing — before s.open stops waiting for it */
4217
+ const ARRIVE_WAIT_MS = 45e3;
4218
+ /** what it shows has to hold this long to count as arrived */
4219
+ const ARRIVE_QUIET_MS = 1e3;
4220
+ /** a data request open longer than this is a stream or a long poll, not the
4221
+ * page still building itself */
4222
+ const STREAM_MS = 8e3;
4223
+ /** a URL's site, roughly: its host's last two labels ("app.example.com" and
4224
+ * "cdn.example.com" are one site) */
4225
+ function siteOf(url) {
4226
+ try {
4227
+ return new URL(url).hostname.split(".").slice(-2).join(".");
4228
+ } catch {
4229
+ return "";
4230
+ }
4231
+ }
4232
+ /** the requests a page builds itself from */
4233
+ const BUILDS = new Set([
4234
+ "Document",
4235
+ "Script",
4236
+ "Stylesheet",
4237
+ "Font",
4238
+ "Fetch",
4239
+ "XHR"
4240
+ ]);
4241
+ /** what is in the viewport, as a few numbers that change while a page builds */
4242
+ const ARRIVING_JS = "(function(){var vw=innerWidth,vh=innerHeight,n=0,c=0;var all=document.body?document.body.getElementsByTagName('*'):[];for(var i=0;i<all.length&&i<20000;i++){var r=all[i].getBoundingClientRect();if(r.width>0&&r.height>0&&r.right>0&&r.bottom>0&&r.left<vw&&r.top<vh){n++;if(/^(BUTTON|INPUT|SELECT|TEXTAREA|A|CANVAS|SVG)$/i.test(all[i].tagName))c++;}}var t=document.body?document.body.innerText.length:0;return n+'/'+c+'/'+t;})()";
4243
+ /** a mouse event's acknowledgement can be withheld for seconds in headless
4244
+ * while the button is held and nothing paints (see cdp-capture's drag); the
4245
+ * events stay ordered on the socket, so waiting longer buys nothing */
4246
+ const ACK_MS = 150;
4247
+ /** a link click or an Enter starts a navigation a moment after the input:
4248
+ * long enough for Chrome to say so before the settle reads the old page */
4249
+ const NAV_GRACE_MS = 50;
4250
+ const NAV_WAIT_MS = 15e3;
4251
+ /** a drag with no stills on the way still moves in small steps, at about
4252
+ * 60 per second: canvases draw and sliders follow only a moving pointer */
4253
+ const DRAG_STEP_PX = 10;
4254
+ const DRAG_STEP_MS = 16;
4255
+ /** how long the still an action ends on (or s.still) may wait for the screen
4256
+ * to stop changing: a product's count-up commonly runs 1–2 s */
4257
+ const STEADY_MS = 3e3;
4258
+ /** the same, per still on the way (a keystroke's, a drag step's) */
4259
+ const STEADY_STEP_MS = 2e3;
4260
+ /** steps in a row whose wait ran out before the rest of the call stops
4261
+ * waiting: the page keeps changing while the button is held or the keys go
4262
+ * on, and every step would pay the whole budget for nothing */
4263
+ const STEADY_GIVE_UP = 3;
4264
+ /** a call whose steps waited this long in all says so */
4265
+ const STEADY_TELL_MS = 5e3;
4266
+ /** the changed texts a still's `moving` lists */
4267
+ const MOVING_TEXTS = 8;
4268
+ /** what a page listens to when it can be driven */
4269
+ const INPUT_EVENTS = new Set([
4270
+ "click",
4271
+ "dblclick",
4272
+ "auxclick",
4273
+ "contextmenu",
4274
+ "mousedown",
4275
+ "mouseup",
4276
+ "pointerdown",
4277
+ "pointerup",
4278
+ "touchstart",
4279
+ "touchend",
4280
+ "keydown",
4281
+ "keyup",
4282
+ "keypress",
4283
+ "beforeinput",
4284
+ "input",
4285
+ "change",
4286
+ "submit"
4287
+ ]);
4288
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
4289
+ /** `p`'s value, or undefined once `ms` have passed — with its timer cleared,
4290
+ * since a live one holds the process open */
4291
+ function within(p, ms) {
4292
+ let timer;
4293
+ return Promise.race([p, new Promise((r) => {
4294
+ timer = setTimeout(() => r(void 0), ms);
4295
+ })]).finally(() => clearTimeout(timer));
4296
+ }
4297
+ const r2 = (v) => Math.round(v * 100) / 100;
4298
+ const secs$1 = (ms) => `${Math.round(ms / 100) / 10} s`;
4299
+ const show = (t) => typeof t === "string" ? JSON.stringify(t) : t == null ? "null" : `{ x: ${t.x}, y: ${t.y} }`;
4300
+ /** a still's name as a file name: whatever a file system dislikes becomes "-" */
4301
+ function stillFile(index, name) {
4302
+ const slug = name.replace(/[^\p{L}\p{N}_.-]+/gu, "-").replace(/^-+|-+$/g, "") || "still";
4303
+ return `${String(index).padStart(3, "0")}-${slug}.png`;
4304
+ }
4305
+ const PUNCT = {
4306
+ "-": ["Minus", 189],
4307
+ "=": ["Equal", 187],
4308
+ "[": ["BracketLeft", 219],
4309
+ "]": ["BracketRight", 221],
4310
+ "\\": ["Backslash", 220],
4311
+ ";": ["Semicolon", 186],
4312
+ "'": ["Quote", 222],
4313
+ ",": ["Comma", 188],
4314
+ ".": ["Period", 190],
4315
+ "/": ["Slash", 191],
4316
+ "`": ["Backquote", 192]
4317
+ };
4318
+ const SHIFTED = {
4319
+ "!": "1",
4320
+ "@": "2",
4321
+ "#": "3",
4322
+ $: "4",
4323
+ "%": "5",
4324
+ "^": "6",
4325
+ "&": "7",
4326
+ "*": "8",
4327
+ "(": "9",
4328
+ ")": "0",
4329
+ _: "-",
4330
+ "+": "=",
4331
+ "{": "[",
4332
+ "}": "]",
4333
+ "|": "\\",
4334
+ ":": ";",
4335
+ "\"": "'",
4336
+ "<": ",",
4337
+ ">": ".",
4338
+ "?": "/",
4339
+ "~": "`"
4340
+ };
4341
+ function keyFor(ch) {
4342
+ if (ch === "\n") return {
4343
+ key: "Enter",
4344
+ code: "Enter",
4345
+ vk: 13,
4346
+ text: "\r"
4347
+ };
4348
+ if (ch === " ") return {
4349
+ key: " ",
4350
+ code: "Space",
4351
+ vk: 32,
4352
+ text: " "
4353
+ };
4354
+ if (/^[a-z]$/i.test(ch)) {
4355
+ const up = ch.toUpperCase();
4356
+ return {
4357
+ key: ch,
4358
+ code: `Key${up}`,
4359
+ vk: up.charCodeAt(0),
4360
+ text: ch,
4361
+ ...ch === up ? { shift: true } : {}
4362
+ };
4363
+ }
4364
+ const base = SHIFTED[ch] ?? ch;
4365
+ const shift = ch in SHIFTED ? { shift: true } : {};
4366
+ if (/^[0-9]$/.test(base)) return {
4367
+ key: ch,
4368
+ code: `Digit${base}`,
4369
+ vk: base.charCodeAt(0),
4370
+ text: ch,
4371
+ ...shift
4372
+ };
4373
+ const p = PUNCT[base];
4374
+ return p ? {
4375
+ key: ch,
4376
+ code: p[0],
4377
+ vk: p[1],
4378
+ text: ch,
4379
+ ...shift
4380
+ } : null;
4381
+ }
4382
+ const LOCATE_JS = NAME_JS + `function shown(e){return e.getClientRects().length>0;}function innermost(l){for(var i=0;i<l.length;i++){var n=l[i+1];if(!n||!l[i].contains(n))return l[i];}return null;}function byName(t,kind){var sets={click:[${JSON.stringify(CLICK_CANDIDATES)},${JSON.stringify(CLICK_FALLBACK_CANDIDATES)}],field:[${JSON.stringify(FIELD_CANDIDATES)}],box:[${JSON.stringify(BOX_CANDIDATES)}]}[kind]||[];var c=[];for(var s=0;s<sets.length;s++){c=c.concat(Array.prototype.slice.call(document.querySelectorAll(sets[s])).filter(shown));}function exact(e){return names(e).indexOf(t)!==-1;}function part(e){var n=names(e);for(var j=0;j<n.length;j++){if(n[j].indexOf(t)!==-1)return true;}return false;}var m=c.find(exact);if(m)return m;var all=Array.prototype.slice.call(document.body?document.body.querySelectorAll('*'):[]).filter(function(e){return !/^(SCRIPT|STYLE|TEMPLATE|NOSCRIPT)$/.test(e.tagName)&&shown(e);});return innermost(all.filter(exact))||c.find(part)||innermost(all.filter(part));}function locate(q,kind){if(q.slice(0,5)==='text='){var t=q.slice(5).replace(/\\s+/g,' ').trim();var C=window.__openTakeShoot||(window.__openTakeShoot={});var k=kind+'\\n'+t,h=C[k];if(h&&h.isConnected&&shown(h)&&names(h).some(function(n){return n.indexOf(t)!==-1;}))return {el:h};var m=byName(t,kind);if(m)C[k]=m;return m?{el:m}:null;}var l;try{l=document.querySelectorAll(q);}catch(e){return {err:String(e&&e.message||e)};}for(var i=0;i<l.length;i++){if(shown(l[i]))return {el:l[i]};}return null;}`;
4383
+ /** What s.save reads of its target in the page: the element as SVG (with the
4384
+ * computed paint and type of every node inlined, so it stands on its own), a
4385
+ * canvas's PNG, an image's source bytes, a value or text — or only its box,
4386
+ * for a picture taken from the screen. */
4387
+ const SAVE_STYLE = [
4388
+ "fill",
4389
+ "fill-opacity",
4390
+ "fill-rule",
4391
+ "stroke",
4392
+ "stroke-width",
4393
+ "stroke-opacity",
4394
+ "stroke-linecap",
4395
+ "stroke-linejoin",
4396
+ "stroke-dasharray",
4397
+ "opacity",
4398
+ "color",
4399
+ "stop-color",
4400
+ "stop-opacity",
4401
+ "font-family",
4402
+ "font-size",
4403
+ "font-weight",
4404
+ "font-style",
4405
+ "letter-spacing",
4406
+ "text-anchor",
4407
+ "dominant-baseline",
4408
+ "visibility"
4409
+ ];
4410
+ function saveJs(target, as) {
4411
+ return `(async function(){${LOCATE_JS}var f=locate(${JSON.stringify(target)},'box');if(!f)return null;if(f.err)return JSON.stringify({err:f.err});var e=f.el,r=e.getBoundingClientRect(),tag=e.tagName.toLowerCase(),as=${JSON.stringify(as ?? "")};var box={x:r.left,y:r.top,w:r.width,h:r.height};var text=(typeof e.value==='string'?e.value:(e.innerText||e.textContent||''));function b64(buf){var s='',u=new Uint8Array(buf);for(var i=0;i<u.length;i+=32768)s+=String.fromCharCode.apply(null,u.subarray(i,i+32768));return btoa(s);}if(!as)as=tag==='svg'?'svg':tag==='canvas'?'png':tag==='img'?'image':(typeof e.value==='string'||/^(pre|code|output|samp|kbd)$/.test(tag))?'text':'picture';if(as==='svg'){var svg=tag==='svg'?e:e.querySelector('svg');if(!svg)return JSON.stringify({err:'no <svg> in it'});var c=svg.cloneNode(true),src=[svg].concat([].slice.call(svg.querySelectorAll('*'))),dst=[c].concat([].slice.call(c.querySelectorAll('*')));var P=${JSON.stringify(SAVE_STYLE)};for(var i=0;i<src.length;i++){var cs=getComputedStyle(src[i]),st='';for(var j=0;j<P.length;j++){var v=cs.getPropertyValue(P[j]);if(v)st+=P[j]+':'+v+';';}dst[i].setAttribute('style',st+(dst[i].getAttribute('style')||''));}var sr=svg.getBoundingClientRect();c.setAttribute('xmlns','http://www.w3.org/2000/svg');if(!c.getAttribute('width'))c.setAttribute('width',String(Math.round(sr.width)));if(!c.getAttribute('height'))c.setAttribute('height',String(Math.round(sr.height)));return JSON.stringify({kind:'svg',data:new XMLSerializer().serializeToString(c),w:sr.width,h:sr.height});}if(as==='png'){if(tag!=='canvas')return JSON.stringify({err:'it is not a <canvas> (as: "picture" takes its box)'});try{return JSON.stringify({kind:'png',b64:e.toDataURL('image/png').split(',')[1],w:r.width,h:r.height});}catch(x){return JSON.stringify({kind:'picture',box:box,why:'the canvas is tainted (drawn from another site), so its box is pictured'});}}if(as==='image'){var im=tag==='img'?e:e.querySelector('img');if(!im)return JSON.stringify({err:'no <img> in it'});try{var res=await fetch(im.currentSrc||im.src);var buf=await res.arrayBuffer();return JSON.stringify({kind:'image',b64:b64(buf),mime:res.headers.get('content-type')||'',src:im.currentSrc||im.src,w:r.width,h:r.height});}catch(x){return JSON.stringify({kind:'picture',box:box,why:'its source could not be read from the page, so its box is pictured'});}}if(as==='text')return JSON.stringify({kind:'text',data:text});e.scrollIntoView({block:'nearest',inline:'nearest'});r=e.getBoundingClientRect();return JSON.stringify({kind:'picture',box:{x:r.left,y:r.top,w:r.width,h:r.height},text:text.slice(0,400)});})()`;
4412
+ }
4413
+ /** Resolve a target for an action. `scroll`: bring it into view first when
4414
+ * any of it is outside — instantly, so the box and the click that follows
4415
+ * describe the same layout (see capture.ts's CLICK_TAIL_JS). */
4416
+ function findJs(target, kind, scroll) {
4417
+ return `(function(){${LOCATE_JS}${HITTABLE_JS}${UNREACHABLE_JS}var f=locate(${JSON.stringify(target)},${JSON.stringify(kind)});if(!f)return null;if(f.err)return JSON.stringify({err:f.err});var m=f.el,r=m.getBoundingClientRect();` + (scroll ? "if(r.top<0||r.left<0||r.bottom>innerHeight||r.right>innerWidth){m.scrollIntoView({block:'center',inline:'center',behavior:'instant'});r=m.getBoundingClientRect();}" : "") + "var p=hittable(m,r);return JSON.stringify({x:r.x,y:r.y,w:r.width,h:r.height,tag:m.tagName,disabled:m.matches(':disabled'),hit:!!p,why:p?undefined:unreachable(m)});})()";
4418
+ }
4419
+ /** the scroll offset and the page box of every tracked target, in one read */
4420
+ function geometryJs(tracked) {
4421
+ return `(function(){${LOCATE_JS}var K=${JSON.stringify(tracked)},b={};for(var i=0;i<K.length;i++){var f=locate(K[i][0],K[i][1]);if(!f||f.err)continue;var r=f.el.getBoundingClientRect();b[K[i][0]]=[r.x+scrollX,r.y+scrollY,r.width,r.height];}return JSON.stringify({sx:scrollX,sy:scrollY,b:b});})()`;
4422
+ }
4423
+ /** Where the caret is: whether the focused element takes typing, and whether
4424
+ * it belongs to the target (across shadow roots, or as the editable host
4425
+ * wrapping it). The same predicate as capture.ts's FOCUS_STATE_JS. */
4426
+ function focusJs(target) {
4427
+ const find = target == null ? "null" : `locate(${JSON.stringify(target)},'field')`;
4428
+ return `(function(){${LOCATE_JS}var f=${find},m=f&&f.el;var a=document.activeElement;while(a&&a.shadowRoot&&a.shadowRoot.activeElement)a=a.shadowRoot.activeElement;var ed=!!a&&a!==document.body&&(a.isContentEditable||(typeof a.value==='string'&&!a.readOnly&&!a.matches(':disabled')));function inside(n){while(n){if(n===m)return true;var rn=n.getRootNode?n.getRootNode():null;n=n.parentElement||(rn&&rn.host?rn.host:null);}return false;}var own=!!m&&!!a&&(inside(a)||(a.isContentEditable&&a.contains(m)));return JSON.stringify({editable:ed,own:own});})()`;
4429
+ }
4430
+ /** Whether the page shows anything in the viewport — laid-out text, or a
4431
+ * picture, a canvas, a control — and whether it has scripts to hydrate (a
4432
+ * JSON-LD or template block runs nothing, so it does not count). */
4433
+ const SHOWS_JS = "(function(){var vw=innerWidth,vh=innerHeight,shows=false,run=0;for(var j=0;j<document.scripts.length;j++){var ty=(document.scripts[j].type||'').trim().toLowerCase();if(!ty||ty==='module'||/^(text|application)\\/(x-)?(java|ecma)script$/.test(ty))run++;}function seen(r){return r.width>0&&r.height>0&&r.right>0&&r.bottom>0&&r.left<vw&&r.top<vh;}var root=document.body||document.documentElement;if(root){var w=document.createTreeWalker(root,NodeFilter.SHOW_TEXT),n,k=0;while(!shows&&k++<20000&&(n=w.nextNode())){if(!n.data.trim())continue;var p=n.parentElement;if(p&&/^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE)$/.test(p.tagName))continue;var g=document.createRange();g.selectNodeContents(n);if(seen(g.getBoundingClientRect()))shows=true;}if(!shows){var e=root.querySelectorAll('img,svg,canvas,video,iframe,object,embed,input,button,select,textarea');for(var i=0;i<e.length&&!shows;i++){if(seen(e[i].getBoundingClientRect()))shows=true;}}}return JSON.stringify({shows:shows,scripts:run,url:location.href,title:document.title});})()";
4434
+ /** a frame later than any input already sent, and its rAF work (where many
4435
+ * editors draw) done: what the next screenshot shows has caught up */
4436
+ const FRAME_JS = "new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(1))))";
4437
+ /** Run a shoot script against a fresh Chrome and write its stills and
4438
+ * shots.json into `outDir`. A script that throws rejects with its own
4439
+ * message (and where in the script it came from). */
4440
+ async function runShoot(opts) {
4441
+ const out = resolve(opts.outDir);
4442
+ const stage = join(out, ".shoot");
4443
+ const note = opts.onNote ?? ((line) => process.stderr.write(`${line}\n`));
4444
+ const { run: run$1, file } = await loadScript(opts.script);
4445
+ const width = opts.width ?? 1920;
4446
+ const height = opts.height ?? 1080;
4447
+ const scale = opts.scale ?? 2;
4448
+ for (const [what, v] of [["width", width], ["height", height]]) if (!Number.isInteger(v) || v < 64 || v > 8192) throw new Error(`shoot: the viewport ${what} must be whole CSS px, 64–8192 (got ${v})`);
4449
+ if (!(scale > 0 && scale <= 4)) throw new Error(`shoot: scale must be above 0 and at most 4 (got ${scale})`);
4450
+ await mkdir(out, { recursive: true });
4451
+ await rm(stage, {
4452
+ recursive: true,
4453
+ force: true
4454
+ });
4455
+ await mkdir(stage, { recursive: true });
4456
+ let browser = null;
4457
+ let raw = null;
4458
+ const stills = [];
4459
+ const kept = [];
4460
+ const outputs = [];
4461
+ /** each page's material, read live with the first screen kept on it */
4462
+ const scans = [];
4463
+ let items = [];
4464
+ let materials = [];
4465
+ let viewport = {
4466
+ w: width,
4467
+ h: height
4468
+ };
4469
+ try {
4470
+ browser = await launchBrowser({
4471
+ width,
4472
+ height,
4473
+ chromePath: opts.chromePath,
4474
+ deviceScaleFactor: scale,
4475
+ ...opts.userDataDir ? { userDataDir: opts.userDataDir } : {},
4476
+ ...opts.headless === false ? { headless: false } : {}
4477
+ });
4478
+ const { cdp, port, targetId } = browser;
4479
+ await cdp.send("Page.enable");
4480
+ await cdp.send("Runtime.enable");
4481
+ const inner = await fitViewport(cdp, targetId, width, height);
4482
+ viewport = {
4483
+ w: inner[0],
4484
+ h: inner[1]
4485
+ };
4486
+ if (inner[0] !== width || inner[1] !== height) note(`shoot: the window would only give a ${inner[0]}×${inner[1]} viewport (asked ${width}×${height}); the stills are that size`);
4487
+ await installActivityProbe(cdp);
4488
+ const version = await (await fetch(`http://127.0.0.1:${port}/json/version`)).json();
4489
+ raw = await CDP.connect(`ws://127.0.0.1:${port}/devtools/page/${targetId}`);
4490
+ const s = await shoot({
4491
+ cdp,
4492
+ raw,
4493
+ wsEndpoint: version.webSocketDebuggerUrl,
4494
+ viewport,
4495
+ scale,
4496
+ out,
4497
+ stage,
4498
+ stills,
4499
+ note,
4500
+ states: opts.states,
4501
+ steady: opts.steady !== false,
4502
+ kept,
4503
+ outputs,
4504
+ ...opts.materials !== false ? { scans } : {}
4505
+ });
4506
+ let failed = null;
4507
+ try {
4508
+ await run$1(s);
4509
+ } catch (e) {
4510
+ failed = scriptFailure(e, file);
4511
+ }
4512
+ items = await finishStates(browser, stage, kept, stills, viewport, note, opts.components !== false, scans);
4513
+ materials = await finishMaterials(stage, scans, items, note);
4514
+ if (failed != null) {
4515
+ const partial = {
4516
+ viewport,
4517
+ scale,
4518
+ steady: opts.steady !== false,
4519
+ stills,
4520
+ ...logStates(items),
4521
+ ...outputs.length ? { outputs } : {},
4522
+ error: failed
4523
+ };
4524
+ await writeFile(join(stage, "shots.json"), `${JSON.stringify(partial, null, 2)}\n`);
4525
+ if (stills.length) note(`shoot: the ${stills.length} still(s) taken before it stopped are in ${stage}`);
4526
+ throw new Error(`shoot: ${failed}`);
4527
+ }
4528
+ } finally {
4529
+ raw?.close();
4530
+ await browser?.close();
4531
+ }
4532
+ const log = {
4533
+ viewport,
4534
+ scale,
4535
+ steady: opts.steady !== false,
4536
+ stills,
4537
+ ...logStates(items),
4538
+ ...outputs.length ? { outputs } : {}
4539
+ };
4540
+ await writeFile(join(stage, "shots.json"), `${JSON.stringify(log, null, 2)}\n`);
4541
+ let inventory = null;
4542
+ let parts = null;
4543
+ if (items.length && opts.components !== false) try {
4544
+ const source = readComponentSource(stage);
4545
+ inventory = gatherComponents(source);
4546
+ writeComponents(inventory, stage);
4547
+ try {
4548
+ parts = writePartFiles(inventory, source, join(stage, "parts"));
4549
+ } catch (e) {
4550
+ note(`shoot: no part files (${e.message})`);
4551
+ }
4552
+ } catch (e) {
4553
+ inventory = null;
4554
+ note(`shoot: no components.json (${e.message})`);
4555
+ }
4556
+ await replaceShoot(out, stage, [
4557
+ ...stills.map((st) => st.file),
4558
+ ...outputs.map((o) => o.file),
4559
+ ...items.map((it) => `states/${it.id}`),
4560
+ ...inventory ? ["components.json"] : [],
4561
+ ...parts ? ["parts"] : []
4562
+ ]);
4563
+ return {
4564
+ log,
4565
+ path: join(out, "shots.json"),
4566
+ ...inventory ? { components: {
4567
+ file: inventory,
4568
+ path: join(out, "components.json")
4569
+ } } : {},
4570
+ ...parts ? { parts: {
4571
+ ...parts,
4572
+ dir: join(out, "parts"),
4573
+ index: join(out, "parts", "index.json")
4574
+ } } : {},
4575
+ ...materials.length ? { materials: placedMaterials(out, materials) } : {}
4576
+ };
4577
+ }
4578
+ /** Each page's material list, written beside its saved screen; one that
4579
+ * cannot be is a line. Screens that did not finish are skipped. */
4580
+ async function finishMaterials(stage, scans, items, note) {
4581
+ const pages = [];
4582
+ for (const sc of scans) {
4583
+ if (!items.some((i) => i.id === sc.id)) continue;
4584
+ const page = await finishPageMaterials({
4585
+ res: sc.res,
4586
+ id: sc.id,
4587
+ stateDir: join(stage, "states", sc.id),
4588
+ assetsDir: join(stage, "states", "assets"),
4589
+ ...sc.sheet ? { sheet: sc.sheet } : {},
4590
+ note
4591
+ });
4592
+ if (page) pages.push(page);
4593
+ }
4594
+ return pages;
4595
+ }
4596
+ /** the material lists as they are once the shoot is in place in `out` */
4597
+ function placedMaterials(out, staged) {
4598
+ const ids = new Set(staged.map((p) => p.id));
4599
+ return readMaterials({
4600
+ kind: "states",
4601
+ root: out,
4602
+ states: [...ids].map((id) => ({
4603
+ id,
4604
+ dir: join(out, "states", id)
4605
+ }))
4606
+ }).pages;
4607
+ }
4608
+ const logStates = (items) => items.length ? { states: {
4609
+ dir: "states",
4610
+ items
4611
+ } } : {};
4612
+ /** The saved screens the stills kept, made whole (state.html, index.json)
4613
+ * and checked against their moment, in the browser that took them. Nothing
4614
+ * here fails the shoot: a screen that cannot be finished is a line. */
4615
+ async function finishStates(browser, stage, kept, stills, viewport, note, parts, scans = []) {
4616
+ if (!kept.length) return [];
4617
+ let done;
4618
+ let ffmpeg$1;
4619
+ if (scans.length) ffmpeg$1 = await resolveFfmpeg().catch(() => void 0);
4620
+ try {
4621
+ done = await finalizeDomStates({
4622
+ browser,
4623
+ statesDir: join(stage, "states"),
4624
+ states: kept,
4625
+ vw: viewport.w,
4626
+ vh: viewport.h,
4627
+ parts,
4628
+ ...scans.length ? { afterRender: async (cdp, raw) => {
4629
+ const sc = scans.find((x) => x.id === raw.id);
4630
+ if (!sc) return;
4631
+ const t0 = Date.now();
4632
+ try {
4633
+ const sheet = await takeSheet(cdp, {
4634
+ stateDir: raw.dir,
4635
+ vw: viewport.w,
4636
+ ffmpeg: ffmpeg$1
4637
+ });
4638
+ sc.sheet = {
4639
+ ...sheet,
4640
+ ms: Date.now() - t0
4641
+ };
4642
+ } catch (e) {
4643
+ throw new Error(`no sheet of the page (${e.message})`);
4644
+ }
4645
+ } } : {}
4646
+ });
4647
+ } catch (e) {
4648
+ note(`shoot: the saved screens could not be finished (${e.message})`);
4649
+ done = kept.map((k) => ({
4650
+ id: k.id,
4651
+ tMs: k.tMs,
4652
+ fidelity: {
4653
+ psnr: 0,
4654
+ diffFrac: 1,
4655
+ ok: false
4656
+ }
4657
+ }));
4658
+ }
4659
+ const items = done.map((d) => {
4660
+ const still = stills.find((st) => st.state === d.id);
4661
+ return {
4662
+ id: d.id,
4663
+ still: still?.file ?? "",
4664
+ t: still?.t ?? Math.round(d.tMs) / 1e3,
4665
+ fidelity: d.fidelity ?? {
4666
+ psnr: 0,
4667
+ diffFrac: 1,
4668
+ ok: false
4669
+ },
4670
+ ...still?.moving ? { moving: true } : {}
4671
+ };
4672
+ });
4673
+ const bad = items.filter((i) => !i.fidelity.ok).map((i) => i.id);
4674
+ if (bad.length) note(`shoot: ${bad.length} of ${items.length} saved screen(s) did not re-render as shot (${bad.join(", ")}) — their stills are fine; \`open-take film picture <state.html>\` shows one as it renders`);
4675
+ return items;
4676
+ }
4677
+ /** A saved screen's id: the still's name, made a safe folder name, and new
4678
+ * in this shoot ("assets" holds their shared files). */
4679
+ function stateId(name, taken) {
4680
+ const base = name.replace(/[^\p{L}\p{N}_.-]+/gu, "-").replace(/^[-.]+|-+$/g, "") || "still";
4681
+ const free = (id) => !taken.has(id) && id !== "assets";
4682
+ if (free(base)) return base;
4683
+ for (let i = 2;; i++) if (free(`${base}-${i}`)) return `${base}-${i}`;
4684
+ }
4685
+ /** One line on what a shoot kept: how many stills kept their saved screen —
4686
+ * or, when none did, what keeps one. Information, printed with the result. */
4687
+ function shootStatesLine(log) {
4688
+ const n = log.stills.length;
4689
+ const kept = log.states?.items ?? [];
4690
+ if (!kept.length) return `kept ${n} still${n === 1 ? "" : "s"}; no saved screens — { state: true } on a still (or --states) also keeps the interface itself, for screen() / lift() / isolate() in kit/media.js (skill film material)`;
4691
+ const ok = kept.filter((i) => i.fidelity.ok).length;
4692
+ return `saved screens: ${kept.length} of ${n} still${n === 1 ? "" : "s"} in ${log.states.dir}/ (${ok} re-render as shot) — screen() / lift() / isolate() in kit/media.js take states/<id>/state.html (skill film material); --no-states or { state: false } keeps none`;
4693
+ }
4694
+ /** One line on the stills taken while what was on screen was still changing
4695
+ * and the ones the shoot waited for; null when there were none. */
4696
+ function shootSteadyLine(log) {
4697
+ const moving = log.stills.filter((s) => s.moving);
4698
+ const waited = log.stills.filter((s) => (s.steadyMs ?? 0) > 0);
4699
+ if (!moving.length && !waited.length) return null;
4700
+ const n = log.stills.length;
4701
+ const names = moving.slice(0, 6).map((s) => s.name);
4702
+ const changed = moving.flatMap((s) => s.moving.texts).slice(0, 3);
4703
+ const ms = waited.reduce((a, s) => a + s.steadyMs, 0);
4704
+ return [moving.length ? `${moving.length} of ${n} still${n === 1 ? "" : "s"} taken while the screen was still changing (moving in shots.json): ${names.join(", ")}${moving.length > names.length ? ", …" : ""}${changed.length ? ` — e.g. ${changed.map((c) => `${JSON.stringify(c.before)} → ${JSON.stringify(c.after)}`).join(", ")}` : ""}` : `no still taken while the screen was changing`, waited.length ? `${waited.length} waited for it to stop, ${secs$1(ms)} in all (steadyMs); steady: false / --no-steady takes stills without waiting` : null].filter(Boolean).join("; ");
4705
+ }
4706
+ /** Put the shoot staged in `stage` (its stills and saved screens, `names` —
4707
+ * "states/<id>" is a screen's folder — and its shots.json) in place of the
4708
+ * last one in `out`, but only once all of it is in place —
4709
+ * the last one is moved aside first, and put back if anything of the new one
4710
+ * cannot go where it belongs. Nothing of the last one is deleted unless the
4711
+ * new one is whole in place: what cannot be put back stays aside, in a
4712
+ * directory of this run's own, and the error says where. `move` is rename;
4713
+ * a test makes it fail. */
4714
+ async function replaceShoot(out, stage, names, move = rename) {
4715
+ const aside = await mkdtemp(join(out, ".shoot-previous-"));
4716
+ const previous = [];
4717
+ const placed = [];
4718
+ const into = async (from, to) => {
4719
+ await mkdir(dirname(to), { recursive: true });
4720
+ await move(from, to);
4721
+ };
4722
+ try {
4723
+ await mergeAssets(join(stage, "states", "assets"), join(out, "states", "assets"));
4724
+ await moveAside(out, aside, previous, into);
4725
+ for (const name of [...names, "shots.json"]) {
4726
+ await into(join(stage, name), join(out, name));
4727
+ placed.push(name);
4728
+ }
4729
+ } catch (e) {
4730
+ const why = e instanceof Error ? e.message : String(e);
4731
+ const left = [];
4732
+ for (const name of placed.reverse()) await into(join(out, name), join(stage, name)).catch(() => left.push(name));
4733
+ const stuck = [];
4734
+ for (const name of previous) if (left.includes(name)) stuck.push(name);
4735
+ else await into(join(aside, name), join(out, name)).catch(() => stuck.push(name));
4736
+ if (!stuck.length) await rm(aside, {
4737
+ recursive: true,
4738
+ force: true
4739
+ }).catch(() => {});
4740
+ throw new Error(`shoot: the new shoot could not replace the last one (${why}) — ${stuck.length ? `the last one could not all be put back: ${stuck.join(", ")} ${stuck.length === 1 ? "is" : "are"} in ${aside}` : "the last one is back in place"}, the new one is in ${stage}${left.length ? ` (but for ${left.join(", ")}, left in ${out})` : ""}`);
4741
+ }
4742
+ await rm(aside, {
4743
+ recursive: true,
4744
+ force: true
4745
+ });
4746
+ await rm(stage, {
4747
+ recursive: true,
4748
+ force: true
4749
+ });
4750
+ }
4751
+ async function loadScript(script) {
4752
+ if (typeof script === "function") return { run: script };
4753
+ const file = resolve(script);
4754
+ if (!existsSync(file)) throw new Error(`shoot: no script at ${file}`);
4755
+ let mod;
4756
+ try {
4757
+ mod = await import(`${pathToFileURL(file).href}?shoot=${Date.now()}`);
4758
+ } catch (e) {
4759
+ throw new Error(`shoot: ${basename(file)} did not load — ${scriptFailure(e, file)}`);
4760
+ }
4761
+ if (typeof mod.default !== "function") throw new Error(`shoot: ${basename(file)} has no default export — write \`export default async (s) => { … }\``);
4762
+ return {
4763
+ run: mod.default,
4764
+ file
4765
+ };
4766
+ }
4767
+ /** the error's message, and the line of the script it came from */
4768
+ function scriptFailure(e, file) {
4769
+ const err = e instanceof Error ? e : new Error(String(e));
4770
+ if (!file || !err.stack) return err.message;
4771
+ const href = pathToFileURL(file).href;
4772
+ const line = err.stack.split("\n").find((l) => l.includes(href) || l.includes(file));
4773
+ const at = line?.match(/:(\d+):(\d+)\)?\s*$/) ?? line?.match(/:(\d+)\s*$/);
4774
+ return at ? `${err.message} (${basename(file)}:${at.slice(1).filter(Boolean).join(":")})` : err.message;
4775
+ }
4776
+ /** Move the previous shoot's stills (exactly the files its log names) and its
4777
+ * log into `aside`, adding each to `moved` as it goes, so that what was moved
4778
+ * can be put back even if the rest cannot. Anything else in the directory is
4779
+ * the author's and stays where it is. */
4780
+ async function moveAside(out, aside, moved, move) {
4781
+ let old;
4782
+ try {
4783
+ old = JSON.parse(await readFile(join(out, "shots.json"), "utf8"));
4784
+ } catch {
4785
+ return;
4786
+ }
4787
+ const names = (Array.isArray(old.stills) ? old.stills : []).map((st) => st?.file).filter((f) => typeof f === "string" && /^\d{3,}-[^/\\]+\.png$/.test(f));
4788
+ const screens = (Array.isArray(old.states?.items) ? old.states.items : []).map((it) => it?.id).filter((id) => typeof id === "string" && /^[^/\\.][^/\\]*$/.test(id) && id !== "assets").map((id) => `states/${id}`);
4789
+ const saved = (Array.isArray(old.outputs) ? old.outputs : []).map((o) => o?.file).filter((f) => typeof f === "string" && /^outputs\/[A-Za-z0-9][A-Za-z0-9._-]*$/.test(f));
4790
+ const parts = existsSync(join(out, "parts", "index.json")) ? ["parts"] : [];
4791
+ for (const name of [
4792
+ ...names,
4793
+ ...saved,
4794
+ ...screens,
4795
+ ...parts,
4796
+ "components.json",
4797
+ "shots.json"
4798
+ ]) {
4799
+ if (!existsSync(join(out, name))) continue;
4800
+ await move(join(out, name), join(aside, name));
4801
+ moved.push(name);
4802
+ }
4803
+ }
4804
+ /** The folders in `<out>/states/` the last shoot's log does not name: a
4805
+ * new screen of the same name could not go there, so its id steers round
4806
+ * them. */
4807
+ async function foreignStates(out) {
4808
+ const dirs = await readdir(join(out, "states"), { withFileTypes: true }).catch(() => []);
4809
+ let own = [];
4810
+ try {
4811
+ const old = JSON.parse(await readFile(join(out, "shots.json"), "utf8"));
4812
+ if (Array.isArray(old.states?.items)) own = old.states.items.map((it) => it?.id);
4813
+ } catch {}
4814
+ return new Set(dirs.filter((d) => d.isDirectory() && !own.includes(d.name)).map((d) => d.name));
4815
+ }
4816
+ /** Move the files of `from` that `to` lacks into it (a missing `from` is
4817
+ * nothing to do). */
4818
+ async function mergeAssets(from, to) {
4819
+ if (!existsSync(from)) return;
4820
+ await mkdir(to, { recursive: true });
4821
+ for (const name of await readdir(from)) if (!existsSync(join(to, name))) await rename(join(from, name), join(to, name));
4822
+ }
4823
+ async function shoot(ctx) {
4824
+ const { cdp, raw, viewport, stills, note, kept } = ctx;
4825
+ const stateIds = await foreignStates(ctx.out);
4826
+ const t0 = Date.now();
4827
+ let cursor = {
4828
+ x: r2(viewport.w * .25),
4829
+ y: r2(viewport.h * .9)
4830
+ };
4831
+ let down = false;
4832
+ const tracked = new Map();
4833
+ const noted = new Set();
4834
+ const once = (key$1, line) => {
4835
+ if (noted.has(key$1)) return;
4836
+ noted.add(key$1);
4837
+ note(line);
4838
+ };
4839
+ const follow = (p) => {
4840
+ if (typeof p.x === "number" && typeof p.y === "number") cursor = {
4841
+ x: p.x,
4842
+ y: p.y
4843
+ };
4844
+ if (p.type === "mousePressed") down = true;
4845
+ if (p.type === "mouseReleased") down = false;
4846
+ };
4847
+ const tree = await cdp.send("Page.getFrameTree");
4848
+ const main = tree.frameTree.frame.id;
4849
+ let loading = false;
4850
+ let stopped = [];
4851
+ cdp.on("Page.frameStartedLoading", (p) => {
4852
+ if (p.frameId === main) loading = true;
4853
+ });
4854
+ cdp.on("Page.frameStoppedLoading", (p) => {
4855
+ if (p.frameId !== main) return;
4856
+ loading = false;
4857
+ for (const r of stopped.splice(0)) r();
4858
+ });
4859
+ const fetching = new Map();
4860
+ await cdp.send("Network.enable").catch(() => {});
4861
+ cdp.on("Network.requestWillBeSent", (p) => {
4862
+ if (BUILDS.has(p.type ?? "")) fetching.set(p.requestId, {
4863
+ type: p.type,
4864
+ at: Date.now(),
4865
+ site: siteOf(p.request?.url ?? "")
4866
+ });
4867
+ });
4868
+ for (const ev of ["Network.loadingFinished", "Network.loadingFailed"]) cdp.on(ev, (p) => {
4869
+ fetching.delete(p.requestId);
4870
+ });
4871
+ const pageErrors = [];
4872
+ cdp.on("Runtime.exceptionThrown", (p) => {
4873
+ const d = p.exceptionDetails;
4874
+ pageErrors.push((d?.exception?.description ?? d?.text ?? "an error").split("\n")[0]);
4875
+ });
4876
+ const evaluate = async (expression, what) => {
4877
+ const r = await cdp.send("Runtime.evaluate", {
4878
+ expression,
4879
+ returnByValue: true,
4880
+ awaitPromise: true
4881
+ });
4882
+ if (r.exceptionDetails) {
4883
+ const d = r.exceptionDetails;
4884
+ throw new Error(`${what}: ${(d.exception?.description ?? d.text ?? "it threw").split("\n")[0]}`);
4885
+ }
4886
+ return r.result?.value;
4887
+ };
4888
+ const mouse = async (type, x, y, ackMs = ACK_MS) => {
4889
+ const params = {
4890
+ type,
4891
+ x,
4892
+ y,
4893
+ button: type === "mouseMoved" && !down ? "none" : "left",
4894
+ buttons: type === "mouseReleased" || type === "mouseMoved" && !down ? 0 : 1,
4895
+ ...type === "mouseMoved" ? {} : { clickCount: 1 }
4896
+ };
4897
+ follow(params);
4898
+ const sent = cdp.send("Input.dispatchMouseEvent", params).catch(() => {});
4899
+ if (ackMs > 0) await within(sent, ackMs);
4900
+ };
4901
+ const key = async (ch) => {
4902
+ const k = keyFor(ch);
4903
+ if (!k) {
4904
+ await cdp.send("Input.insertText", { text: ch });
4905
+ return;
4906
+ }
4907
+ const base = {
4908
+ modifiers: k.shift ? 8 : 0,
4909
+ key: k.key,
4910
+ code: k.code,
4911
+ windowsVirtualKeyCode: k.vk,
4912
+ nativeVirtualKeyCode: k.vk
4913
+ };
4914
+ await cdp.send("Input.dispatchKeyEvent", {
4915
+ type: "keyDown",
4916
+ ...base,
4917
+ text: k.text,
4918
+ unmodifiedText: k.text
4919
+ });
4920
+ await cdp.send("Input.dispatchKeyEvent", {
4921
+ type: "keyUp",
4922
+ ...base
4923
+ });
4924
+ };
4925
+ /** the input just sent may have started a navigation: return on the new page */
4926
+ const arrive = async () => {
4927
+ await sleep(NAV_GRACE_MS);
4928
+ if (!loading) return;
4929
+ await within(new Promise((r) => stopped.push(r)), NAV_WAIT_MS);
4930
+ stopped = [];
4931
+ await awaitFonts(cdp);
4932
+ };
4933
+ const settleFor = async (opt, fallback, input) => {
4934
+ const on = opt ?? fallback;
4935
+ if (on === false || on === 0) return;
4936
+ const budgetMs = typeof on === "number" ? on : DEFAULT_SETTLE_BUDGET_MS;
4937
+ if (input) await arrive();
4938
+ let r = await settle(cdp, 0, { budgetMs });
4939
+ if (input && loading) {
4940
+ await arrive();
4941
+ r = await settle(cdp, 0, { budgetMs });
4942
+ }
4943
+ if (r.reason === "budget") once("quiet", `shoot: the page did not go quiet within ${budgetMs} ms (a clock, a poll, a stream?) — every settle on it costs that much; pass settle: false where the moment does not need it`);
4944
+ };
4945
+ /** pages whose material could not be read (not tried again) */
4946
+ const unread = new Set();
4947
+ /** the interface as the still shows it, kept as a saved screen (the same
4948
+ * read-only capture as `make --states`); a page that cannot be read keeps
4949
+ * the still without one */
4950
+ const keepState = async (still) => {
4951
+ const id = stateId(still.name, stateIds);
4952
+ try {
4953
+ kept.push(await captureDomState(cdp, {
4954
+ statesDir: join(ctx.stage, "states"),
4955
+ id,
4956
+ tMs: Math.round(still.t * 1e3),
4957
+ vw: viewport.w,
4958
+ vh: viewport.h,
4959
+ dpr: ctx.scale
4960
+ }));
4961
+ stateIds.add(id);
4962
+ still.state = id;
4963
+ } catch (e) {
4964
+ await rm(join(ctx.stage, "states", id), {
4965
+ recursive: true,
4966
+ force: true
4967
+ }).catch(() => {});
4968
+ note(`shoot: ${still.file} kept no saved screen (${e.message}) — the still is fine`);
4969
+ return;
4970
+ }
4971
+ const url = pageKey(kept[kept.length - 1].probe.url);
4972
+ if (ctx.scans && !ctx.scans.some((sc) => sc.url === url) && !unread.has(url)) try {
4973
+ const res = await within(readPageMaterials(cdp), 15e3);
4974
+ if (!res) throw new Error("the page did not answer within 15 s");
4975
+ ctx.scans.push({
4976
+ id,
4977
+ url,
4978
+ res
4979
+ });
4980
+ } catch (e) {
4981
+ unread.add(url);
4982
+ note(`shoot: the material of ${url} was not read (${e.message})`);
4983
+ }
4984
+ };
4985
+ /** what is on screen now (steady.ts); null while the page cannot be read */
4986
+ const readScreen = async () => {
4987
+ try {
4988
+ return JSON.parse(await evaluate(SCREEN_JS, "s.still"));
4989
+ } catch {
4990
+ return null;
4991
+ }
4992
+ };
4993
+ /** how long a call's stills may wait for the screen to hold still (0: not at all) */
4994
+ const steadyBudget = (what, o, step) => {
4995
+ const v = o.steady ?? (o.settle === false || o.settle === 0 ? false : ctx.steady);
4996
+ if (typeof v === "number" && !(v >= 0 && Number.isFinite(v))) throw new Error(`${what}: steady is true, false or ms to wait at most (got ${v})`);
4997
+ if (v === false || v === 0) return 0;
4998
+ return typeof v === "number" ? v : step ? STEADY_STEP_MS : STEADY_MS;
4999
+ };
5000
+ /** the last capture's wait for a steady screen (null: it did not wait) */
5001
+ let lastSteady = null;
5002
+ /** one PNG and its log entry */
5003
+ const capture = async (name, action, state, onTheWay = false, steadyMs = 0) => {
5004
+ await within(evaluate(FRAME_JS, "s.still").catch(() => {}), 500);
5005
+ lastSteady = steadyMs > 0 ? await waitSteady(readScreen, steadyMs) : null;
5006
+ const t = Math.round(Date.now() - t0) / 1e3;
5007
+ let geo = null;
5008
+ for (let i = 0; !geo; i++) try {
5009
+ geo = JSON.parse(await evaluate(geometryJs([...tracked]), "s.still"));
5010
+ } catch (e) {
5011
+ if (i >= 5) throw e;
5012
+ await sleep(100);
5013
+ }
5014
+ const before = await readScreen();
5015
+ const shot = await within(cdp.send("Page.captureScreenshot", { format: "png" }), 6e4);
5016
+ if (!shot) throw new Error(`s.still(${JSON.stringify(name)}): the page did not paint within 60 s`);
5017
+ const afterShot = await readScreen();
5018
+ const change = before && afterShot ? screenChange(before, afterShot) : null;
5019
+ const file = stillFile(stills.length, name);
5020
+ await writeFile(join(ctx.stage, file), Buffer.from(shot.data, "base64"));
5021
+ const g = geo;
5022
+ const boxes = {};
5023
+ for (const [k, [x, y, width, height]] of Object.entries(g.b)) boxes[k] = {
5024
+ x: r2(x),
5025
+ y: r2(y),
5026
+ width: r2(width),
5027
+ height: r2(height)
5028
+ };
5029
+ const still = {
5030
+ file,
5031
+ name,
5032
+ t,
5033
+ cursor: {
5034
+ x: r2(cursor.x + g.sx),
5035
+ y: r2(cursor.y + g.sy)
5036
+ },
5037
+ scroll: {
5038
+ x: r2(g.sx),
5039
+ y: r2(g.sy)
5040
+ },
5041
+ boxes,
5042
+ ...action ? { action } : {},
5043
+ ...down ? { down: true } : {},
5044
+ ...lastSteady?.changed ? { steadyMs: Math.round(lastSteady.waitedMs) } : {},
5045
+ ...change && (change.texts.length || change.moved || change.animations) ? { moving: {
5046
+ texts: change.texts.slice(0, MOVING_TEXTS).map((c) => ({
5047
+ x: r2(c.x),
5048
+ y: r2(c.y),
5049
+ before: c.before,
5050
+ after: c.after
5051
+ })),
5052
+ ...change.texts.length > MOVING_TEXTS ? { more: change.texts.length - MOVING_TEXTS } : {},
5053
+ ...change.moved ? { moved: true } : {},
5054
+ animations: change.animations
5055
+ } } : {}
5056
+ };
5057
+ stills.push(still);
5058
+ if (state ?? ctx.states ?? !onTheWay) await keepState(still);
5059
+ return still;
5060
+ };
5061
+ /** a still the shoot waited for and that still caught the screen changing */
5062
+ const tellUnsteady = (still) => {
5063
+ if (lastSteady && !lastSteady.steady && still.moving) once("steady", `shoot: ${still.file}: what is on screen was still changing after ${secs$1(lastSteady.waitedMs)} (a clock, a ticker, a long animation?) — it is marked moving in shots.json; steady: <ms> waits longer, steady: false (--no-steady) takes stills without waiting`);
5064
+ return still;
5065
+ };
5066
+ /** The stills on the way (each, every) wait for a steady screen one by one.
5067
+ * That is the default because a step still is shown as what the product
5068
+ * says at that point of the drag or the typing: a count-up restarting
5069
+ * from 0 on every change gives, without the wait, a run of stills whose
5070
+ * numbers jump back and forth (2,576 → 993 → 2,705 → 1,305) — values the
5071
+ * product never rests on, in a flipbook the viewer reads as the result.
5072
+ * The input itself is not disturbed: the button stays held, the field
5073
+ * keeps its caret, and the next step goes on from where this one is. The
5074
+ * cost is time between steps (the log's `t` spreads out); steady: false
5075
+ * keeps the old timing — every step as it comes, its in-between values
5076
+ * included as material — and `moving` marks the steps taken changing
5077
+ * either way. A page that keeps changing while held (a hold-to-fill,
5078
+ * a live preview) would pay the whole budget at every step, so after
5079
+ * STEADY_GIVE_UP waits in a row run out, the rest of the call's steps are
5080
+ * taken as they come, and a line says so. */
5081
+ const stepper = (what, o) => {
5082
+ let wait = steadyBudget(what, o, true);
5083
+ const first = wait;
5084
+ let outInARow = 0;
5085
+ let spent = 0;
5086
+ let waited = 0;
5087
+ let gaveUp = false;
5088
+ return {
5089
+ get wait() {
5090
+ return wait;
5091
+ },
5092
+ took() {
5093
+ const r = lastSteady;
5094
+ if (!r) return;
5095
+ waited++;
5096
+ spent += r.waitedMs;
5097
+ if (r.steady) outInARow = 0;
5098
+ else if (++outInARow >= STEADY_GIVE_UP && !gaveUp) {
5099
+ gaveUp = true;
5100
+ wait = 0;
5101
+ }
5102
+ },
5103
+ done() {
5104
+ if (gaveUp) note(`${what}: the screen was still changing after ${STEADY_GIVE_UP} steps in a row (${secs$1(first)} each) — the rest of its steps were taken as they came (marked moving in shots.json where they were changing); steady: <ms> sets the wait, steady: false takes every step at once`);
5105
+ else if (spent >= STEADY_TELL_MS) note(`${what}: its ${waited} steps waited ${secs$1(spent)} in all for the screen to stop changing (steadyMs in shots.json); a larger step, or steady: false, takes them sooner`);
5106
+ }
5107
+ };
5108
+ };
5109
+ const after = async (what, o, action, name) => {
5110
+ const wait = steadyBudget(what, o, false);
5111
+ await settleFor(o.settle, true, true);
5112
+ if (o.still === false) return null;
5113
+ return tellUnsteady(await capture(name, action, o.state, false, wait));
5114
+ };
5115
+ /** wait for the target to appear (and, `reach`, to be hittable and enabled) */
5116
+ const find = async (what, target, kind, timeoutMs, o) => {
5117
+ const deadline = Date.now() + timeoutMs;
5118
+ let last = null;
5119
+ for (;;) {
5120
+ const json = await evaluate(findJs(target, kind, o.scroll), what);
5121
+ if (json) {
5122
+ const f = JSON.parse(json);
5123
+ if (f.err) throw new Error(`${what}: ${JSON.stringify(target)} is not a valid selector (${f.err})`);
5124
+ if (!o.reach || f.hit && !f.disabled) return f;
5125
+ last = f;
5126
+ }
5127
+ if (Date.now() >= deadline) {
5128
+ if (!last) throw new Error(`${what}: nothing on the page matches ${JSON.stringify(target)} (waited ${secs$1(timeoutMs)})`);
5129
+ throw new Error(`${what}: ${JSON.stringify(target)} ${last.disabled ? "stayed disabled" : `cannot be reached — ${last.why}`} (waited ${secs$1(timeoutMs)}); a point { x, y } clicks wherever you say`);
5130
+ }
5131
+ await sleep(100);
5132
+ }
5133
+ };
5134
+ /** where the mouse goes for a target: a given point, or the centre of the element */
5135
+ const point = async (what, target, kind, o = {}) => {
5136
+ if (typeof target !== "string") {
5137
+ if (!Number.isFinite(target?.x) || !Number.isFinite(target?.y)) throw new Error(`${what}: a point needs numbers { x, y } (viewport CSS px)`);
5138
+ return {
5139
+ x: target.x,
5140
+ y: target.y
5141
+ };
5142
+ }
5143
+ const f = await find(what, target, kind, o.timeoutMs ?? TARGET_WAIT_MS, {
5144
+ reach: o.reach ?? true,
5145
+ scroll: o.scroll ?? true
5146
+ });
5147
+ tracked.set(target, kind);
5148
+ return {
5149
+ x: r2(f.x + f.w / 2),
5150
+ y: r2(f.y + f.h / 2),
5151
+ tag: f.tag
5152
+ };
5153
+ };
5154
+ const click = async (x, y) => {
5155
+ await mouse("mouseMoved", x, y);
5156
+ await mouse("mousePressed", x, y);
5157
+ await sleep(40);
5158
+ await mouse("mouseReleased", x, y);
5159
+ };
5160
+ const waitFor = async (what, cond, timeoutMs) => {
5161
+ if (typeof cond === "number") {
5162
+ await sleep(cond);
5163
+ return;
5164
+ }
5165
+ const deadline = Date.now() + timeoutMs;
5166
+ for (;;) {
5167
+ if (typeof cond === "string") {
5168
+ const json = await evaluate(findJs(cond, "box", false), what);
5169
+ const f = json ? JSON.parse(json) : null;
5170
+ if (f?.err) throw new Error(`${what}: ${JSON.stringify(cond)} is not a valid selector (${f.err})`);
5171
+ if (f) return;
5172
+ } else if (await cond()) return;
5173
+ if (Date.now() >= deadline) throw new Error(`${what}: ${typeof cond === "string" ? `${JSON.stringify(cond)} never appeared` : "the condition never held"} (waited ${secs$1(timeoutMs)})`);
5174
+ await sleep(100);
5175
+ }
5176
+ };
5177
+ /** input handlers the page has attached anywhere (-1: could not tell) */
5178
+ const inputHandlers = async () => {
5179
+ const group = "open-take-shoot";
5180
+ try {
5181
+ let n = 0;
5182
+ for (const [expression, depth] of [["document", -1], ["window", 0]]) {
5183
+ const r = await cdp.send("Runtime.evaluate", {
5184
+ expression,
5185
+ objectGroup: group
5186
+ });
5187
+ if (!r.result?.objectId) continue;
5188
+ const l = await cdp.send("DOMDebugger.getEventListeners", {
5189
+ objectId: r.result.objectId,
5190
+ depth,
5191
+ pierce: true
5192
+ });
5193
+ n += (l.listeners ?? []).filter((x) => INPUT_EVENTS.has(x.type)).length;
5194
+ }
5195
+ return n;
5196
+ } catch {
5197
+ return -1;
5198
+ } finally {
5199
+ await cdp.send("Runtime.releaseObjectGroup", { objectGroup: group }).catch(() => {});
5200
+ }
5201
+ };
5202
+ const listeners = new Map();
5203
+ const exit = {
5204
+ send: (method, params = {}) => {
5205
+ if (method === "Input.dispatchMouseEvent") follow(params);
5206
+ return raw.send(method, params);
5207
+ },
5208
+ on: (event, fn) => {
5209
+ let set = listeners.get(event);
5210
+ if (!set) {
5211
+ const fns = new Set();
5212
+ raw.on(event, (p) => {
5213
+ for (const f$1 of fns) f$1(p);
5214
+ });
5215
+ listeners.set(event, fns);
5216
+ set = fns;
5217
+ }
5218
+ const f = fn;
5219
+ set.add(f);
5220
+ return () => {
5221
+ set.delete(f);
5222
+ };
5223
+ }
5224
+ };
5225
+ return {
5226
+ async open(url, o = {}) {
5227
+ const what = `s.open(${JSON.stringify(url)})`;
5228
+ if (!originAllowed(url)) throw new Error(`${what}: outside OPEN_TAKE_ALLOWED_ORIGINS`);
5229
+ const before = pageErrors.length;
5230
+ const failed = await navigate(cdp, url);
5231
+ if (failed) throw new Error(`${what}: the page did not answer (${failed}) — is the app running?`);
5232
+ await awaitFonts(cdp);
5233
+ const timeoutMs = o.timeoutMs ?? OPEN_WAIT_MS;
5234
+ const deadline = Date.now() + timeoutMs;
5235
+ let page = {
5236
+ url,
5237
+ title: ""
5238
+ };
5239
+ let shownAt = 0;
5240
+ let hydrated = false;
5241
+ for (;;) {
5242
+ const p = JSON.parse(await evaluate(SHOWS_JS, what));
5243
+ page = {
5244
+ url: p.url,
5245
+ title: p.title
5246
+ };
5247
+ if (p.shows) {
5248
+ shownAt ||= Date.now();
5249
+ if (p.scripts === 0 || await inputHandlers() !== 0) {
5250
+ hydrated = true;
5251
+ break;
5252
+ }
5253
+ if (Date.now() - shownAt >= HANDLERS_WAIT_MS) break;
5254
+ }
5255
+ if (Date.now() >= deadline) break;
5256
+ await sleep(150);
5257
+ }
5258
+ if (!shownAt) throw new Error(`${what}: the page shows nothing after ${secs$1(timeoutMs)} — did its script fail, or does it need a login (--profile)?`);
5259
+ const arriveMs = Math.max(timeoutMs, ARRIVE_WAIT_MS);
5260
+ const from = Date.now();
5261
+ let grewAt = from;
5262
+ let most = [
5263
+ -1,
5264
+ -1,
5265
+ -1
5266
+ ];
5267
+ for (;;) {
5268
+ const now = Date.now();
5269
+ const sig = (await evaluate(ARRIVING_JS, what).catch(() => "0/0/0")).split("/").map(Number);
5270
+ if (sig[0] > most[0] + 2 || sig[1] > most[1] || sig[2] > most[2] + 20) grewAt = now;
5271
+ most = most.map((m, i) => Math.max(m, sig[i]));
5272
+ const own = siteOf(page.url);
5273
+ const pending = [...fetching.values()].filter((f) => f.site === own && (f.type !== "Fetch" && f.type !== "XHR" || now - f.at < STREAM_MS)).length;
5274
+ if (!loading && pending === 0 && now - grewAt >= ARRIVE_QUIET_MS) break;
5275
+ if (now - from >= arriveMs) {
5276
+ note(`${what}: the page was still arriving after ${secs$1(arriveMs)} (${pending ? `${pending} request(s) to its own site in flight` : "what it shows still growing"}) — taken as it is; ready: "<selector>" waits for a part of it`);
5277
+ break;
5278
+ }
5279
+ await sleep(200);
5280
+ }
5281
+ if (!hydrated && await inputHandlers() !== 0) hydrated = true;
5282
+ if (!hydrated) note(`${what}: the page's scripts attached no click, key or pointer handlers within ${secs$1(HANDLERS_WAIT_MS)} — fine for a static page; an app has not hydrated, and clicks on it will do nothing`);
5283
+ if (o.ready != null) await waitFor(what, o.ready, timeoutMs);
5284
+ await settleFor(o.settle === true ? OPEN_SETTLE_MS : o.settle, OPEN_SETTLE_MS, false);
5285
+ const errors = pageErrors.slice(before);
5286
+ if (errors.length) note(`${what}: the page threw while loading — ${errors.slice(0, 3).join(" · ")}`);
5287
+ return {
5288
+ url: page.url,
5289
+ title: page.title,
5290
+ errors
5291
+ };
5292
+ },
5293
+ async still(name = "still", o = {}) {
5294
+ const wait = steadyBudget(`s.still(${JSON.stringify(name)})`, o, false);
5295
+ await settleFor(o.settle, false, false);
5296
+ return tellUnsteady(await capture(name, void 0, o.state, false, wait));
5297
+ },
5298
+ async click(target, o = {}) {
5299
+ const what = `s.click(${show(target)})`;
5300
+ const p = await point(what, target, "click", o);
5301
+ if (p.tag === "SELECT") throw new Error(`${what}: a native <select> does not open in headless Chrome — set it with s.evaluate (el.value = …, then dispatch a "change" event)`);
5302
+ await click(p.x, p.y);
5303
+ return after(what, o, "click", o.name ?? "click");
5304
+ },
5305
+ async type(target, text, o = {}) {
5306
+ const what = `s.type(${show(target)}, ${JSON.stringify(text)})`;
5307
+ if (typeof text !== "string") throw new Error(`${what}: the text must be a string`);
5308
+ if (target != null) {
5309
+ const own = typeof target === "string" ? JSON.parse(await evaluate(focusJs(target), what)) : null;
5310
+ if (own?.editable && own.own) tracked.set(target, "field");
5311
+ else {
5312
+ const p = await point(what, target, "field", o);
5313
+ await click(p.x, p.y);
5314
+ let editable = false;
5315
+ for (let i$1 = 0; i$1 < 8 && !editable; i$1++) {
5316
+ if (i$1) await sleep(100);
5317
+ editable = JSON.parse(await evaluate(focusJs(null), what)).editable;
5318
+ }
5319
+ if (!editable) throw new Error(`${what}: clicking it put no caret anywhere — is it a field? (null types into whatever has focus)`);
5320
+ }
5321
+ }
5322
+ if (o.clear) await evaluate(selectAllInFocusedJs(), what);
5323
+ const name = o.name ?? "type";
5324
+ const steps = stepper(what, o);
5325
+ let i = 0;
5326
+ for (const ch of text.replace(/\r\n?/g, "\n")) {
5327
+ await key(ch);
5328
+ if (!o.each) continue;
5329
+ await capture(`${name}-${++i}`, "type", o.state, true, steps.wait);
5330
+ steps.took();
5331
+ }
5332
+ steps.done();
5333
+ return after(what, o, "type", name);
5334
+ },
5335
+ async drag(target, dest, o = {}) {
5336
+ const what = `s.drag(${show(target)})`;
5337
+ const every = o.every;
5338
+ if (every != null && !(every > 0)) throw new Error(`${what}: every is px between stills, above 0`);
5339
+ const from = await point(what, target, "box", o);
5340
+ let to;
5341
+ if (dest && "to" in dest && dest.to != null) to = await point(what, dest.to, "box", {
5342
+ ...o,
5343
+ reach: false,
5344
+ scroll: false
5345
+ });
5346
+ else {
5347
+ const d = dest;
5348
+ const dx = d?.dx ?? 0;
5349
+ const dy = d?.dy ?? 0;
5350
+ if (!Number.isFinite(dx) || !Number.isFinite(dy) || !dx && !dy) throw new Error(`${what}: say where to — { dx, dy } in CSS px, or { to: target }`);
5351
+ to = {
5352
+ x: from.x + dx,
5353
+ y: from.y + dy
5354
+ };
5355
+ }
5356
+ const dist = Math.hypot(to.x - from.x, to.y - from.y);
5357
+ const step = every ?? DRAG_STEP_PX;
5358
+ const n = Math.max(1, Math.ceil(dist / step - 1e-9));
5359
+ const name = o.name ?? "drag";
5360
+ const steps = stepper(what, o);
5361
+ await mouse("mouseMoved", from.x, from.y);
5362
+ await mouse("mousePressed", from.x, from.y);
5363
+ for (let i = 1; i <= n; i++) {
5364
+ const u = dist > 0 ? Math.min(1, i * step / dist) : 1;
5365
+ mouse("mouseMoved", r2(from.x + (to.x - from.x) * u), r2(from.y + (to.y - from.y) * u), 0);
5366
+ if (every != null) {
5367
+ await capture(`${name}-${i}`, "drag", o.state, true, steps.wait);
5368
+ steps.took();
5369
+ } else await sleep(DRAG_STEP_MS);
5370
+ }
5371
+ steps.done();
5372
+ await mouse("mouseReleased", to.x, to.y);
5373
+ return after(what, o, "drag", name);
5374
+ },
5375
+ async move(target, o = {}) {
5376
+ const what = `s.move(${show(target)})`;
5377
+ const p = await point(what, target, "box", o);
5378
+ await mouse("mouseMoved", p.x, p.y);
5379
+ return after(what, o, "move", o.name ?? "move");
5380
+ },
5381
+ async press(keys, o = {}) {
5382
+ if (typeof keys !== "string" || !keys.trim()) throw new Error(`s.press: name a key, e.g. "Enter" or "Meta+k"`);
5383
+ await pressChord(cdp, keys);
5384
+ return after(`s.press(${JSON.stringify(keys)})`, o, "press", o.name ?? "press");
5385
+ },
5386
+ async track(targets) {
5387
+ for (const t of [targets].flat()) {
5388
+ if (typeof t !== "string" || !t) throw new Error(`s.track: targets are selectors or text=… strings`);
5389
+ if (!t.startsWith("text=")) {
5390
+ const bad = await evaluate(`(function(){try{document.querySelector(${JSON.stringify(t)});return null;}catch(e){return String(e&&e.message||e);}})()`, "s.track");
5391
+ if (bad) throw new Error(`s.track: ${JSON.stringify(t)} is not a valid selector (${bad})`);
5392
+ }
5393
+ if (!tracked.has(t)) tracked.set(t, "box");
5394
+ }
5395
+ },
5396
+ async wait(what, o = {}) {
5397
+ await waitFor(`s.wait(${typeof what === "function" ? "…" : JSON.stringify(what)})`, what, o.timeoutMs ?? 1e4);
5398
+ },
5399
+ async evaluate(fn, ...args) {
5400
+ const expression = typeof fn === "function" ? `(${fn.toString()})(...${JSON.stringify(args)})` : String(fn);
5401
+ return evaluate(expression, "s.evaluate");
5402
+ },
5403
+ async inject(js) {
5404
+ const source = typeof js === "function" ? `(${js.toString()})()` : String(js);
5405
+ await cdp.send("Page.addScriptToEvaluateOnNewDocument", { source });
5406
+ },
5407
+ async save(name, what, o = {}) {
5408
+ const label = `s.save(${JSON.stringify(name)})`;
5409
+ if (typeof name !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,80}$/.test(name) || /\.\./.test(name)) throw new Error(`${label}: the name is a file name of letters, digits, . _ - (no folders)`);
5410
+ if (ctx.outputs.some((x) => x.name === name)) throw new Error(`${label}: this shoot already saved one by that name`);
5411
+ await mkdir(join(ctx.stage, "outputs"), { recursive: true });
5412
+ const t = Math.round(Date.now() - t0) / 1e3;
5413
+ const page = JSON.parse(await evaluate(SHOWS_JS, label));
5414
+ const after$1 = stills.at(-1)?.name;
5415
+ const base = {
5416
+ name,
5417
+ t,
5418
+ url: page.url,
5419
+ ...after$1 ? {
5420
+ still: stills.length - 1,
5421
+ after: after$1
5422
+ } : {}
5423
+ };
5424
+ const put = async (ext, data, rest) => {
5425
+ const file = `outputs/${name}.${ext}`;
5426
+ await writeFile(join(ctx.stage, file), data);
5427
+ const out = {
5428
+ ...base,
5429
+ file,
5430
+ bytes: data.length,
5431
+ ...rest
5432
+ };
5433
+ ctx.outputs.push(out);
5434
+ return out;
5435
+ };
5436
+ if (what && typeof what === "object" && "download" in what) {
5437
+ if (typeof what.download !== "function") throw new Error(`${label}: { download } is a function that makes the page download (a click on its export button)`);
5438
+ const dir = join(ctx.stage, "outputs", `.download-${name}`);
5439
+ await mkdir(dir, { recursive: true });
5440
+ await cdp.send("Page.setDownloadBehavior", {
5441
+ behavior: "allow",
5442
+ downloadPath: dir
5443
+ });
5444
+ let suggested = "";
5445
+ let done = null;
5446
+ const finished = new Promise((r$1) => {
5447
+ done = r$1;
5448
+ });
5449
+ let listening = true;
5450
+ cdp.on("Page.downloadWillBegin", (p) => {
5451
+ if (listening) suggested = p.suggestedFilename ?? "";
5452
+ });
5453
+ cdp.on("Page.downloadProgress", (p) => {
5454
+ if (listening && (p.state === "completed" || p.state === "canceled")) done?.();
5455
+ });
5456
+ try {
5457
+ await what.download();
5458
+ const ok = await within(finished.then(() => true), o.timeoutMs ?? 15e3);
5459
+ if (!ok) throw new Error(`${label}: the page downloaded nothing within ${secs$1(o.timeoutMs ?? 15e3)}`);
5460
+ } finally {
5461
+ listening = false;
5462
+ await cdp.send("Page.setDownloadBehavior", { behavior: "default" }).catch(() => {});
5463
+ }
5464
+ const got = (await readdir(dir)).filter((f) => !f.endsWith(".crdownload"));
5465
+ if (!got.length) throw new Error(`${label}: the download did not finish`);
5466
+ const data = await readFile(join(dir, got[0]));
5467
+ await rm(dir, {
5468
+ recursive: true,
5469
+ force: true
5470
+ });
5471
+ const ext = (suggested || got[0]).match(/\.([A-Za-z0-9]{1,8})$/)?.[1]?.toLowerCase() ?? "bin";
5472
+ return put(ext, data, {
5473
+ kind: "download",
5474
+ ...suggested ? { filename: suggested } : {}
5475
+ });
5476
+ }
5477
+ if (typeof what !== "string") throw new Error(`${label}: what to save is a target (a selector or text=<name>) or { download }`);
5478
+ const deadline = Date.now() + (o.timeoutMs ?? TARGET_WAIT_MS);
5479
+ let json = null;
5480
+ for (;;) {
5481
+ json = await evaluate(saveJs(what, o.as), label);
5482
+ if (json || Date.now() >= deadline) break;
5483
+ await sleep(100);
5484
+ }
5485
+ if (!json) throw new Error(`${label}: ${JSON.stringify(what)} never appeared`);
5486
+ const r = JSON.parse(json);
5487
+ if (r.err) throw new Error(`${label}: ${JSON.stringify(what)}: ${r.err}`);
5488
+ if (r.why) note(`${label}: ${r.why}`);
5489
+ const size = r.w != null && r.h != null ? {
5490
+ w: r2(r.w),
5491
+ h: r2(r.h)
5492
+ } : {};
5493
+ const target = { target: what };
5494
+ if (r.kind === "svg") return put("svg", Buffer.from(r.data, "utf8"), {
5495
+ kind: "svg",
5496
+ ...target,
5497
+ ...size
5498
+ });
5499
+ if (r.kind === "png") return put("png", Buffer.from(r.b64, "base64"), {
5500
+ kind: "png",
5501
+ ...target,
5502
+ ...size
5503
+ });
5504
+ if (r.kind === "image") {
5505
+ const ext = {
5506
+ "image/png": "png",
5507
+ "image/jpeg": "jpg",
5508
+ "image/webp": "webp",
5509
+ "image/gif": "gif",
5510
+ "image/svg+xml": "svg",
5511
+ "image/avif": "avif"
5512
+ }[(r.mime ?? "").split(";")[0].trim()] ?? "img";
5513
+ return put(ext, Buffer.from(r.b64, "base64"), {
5514
+ kind: "image",
5515
+ ...target,
5516
+ ...size
5517
+ });
5518
+ }
5519
+ if (r.kind === "text") return put("txt", Buffer.from(r.data ?? "", "utf8"), {
5520
+ kind: "text",
5521
+ ...target,
5522
+ text: (r.data ?? "").slice(0, 400)
5523
+ });
5524
+ const b = r.box;
5525
+ if (!(b.w > 0 && b.h > 0)) throw new Error(`${label}: ${JSON.stringify(what)} has no size on screen`);
5526
+ const shot = await within(cdp.send("Page.captureScreenshot", {
5527
+ format: "png",
5528
+ clip: {
5529
+ x: b.x,
5530
+ y: b.y,
5531
+ width: b.w,
5532
+ height: b.h,
5533
+ scale: 1
5534
+ }
5535
+ }), 6e4);
5536
+ if (!shot) throw new Error(`${label}: the page did not paint within 60 s`);
5537
+ return put("png", Buffer.from(shot.data, "base64"), {
5538
+ kind: "picture",
5539
+ ...target,
5540
+ w: r2(b.w),
5541
+ h: r2(b.h),
5542
+ ...r.text ? { text: r.text } : {}
5543
+ });
5544
+ },
5545
+ cdp: exit,
5546
+ wsEndpoint: ctx.wsEndpoint,
5547
+ get cursor() {
5548
+ return { ...cursor };
5549
+ },
5550
+ set cursor(p) {
5551
+ if (!Number.isFinite(p?.x) || !Number.isFinite(p?.y)) throw new Error("s.cursor: { x, y } in viewport CSS px");
5552
+ cursor = {
5553
+ x: p.x,
5554
+ y: p.y
5555
+ };
5556
+ },
5557
+ get stills() {
5558
+ return stills;
5559
+ },
5560
+ viewport,
5561
+ scale: ctx.scale,
5562
+ out: ctx.out
5563
+ };
5564
+ }
5565
+ /** Open `url` the way `s.open` does and keep that moment as a saved screen
5566
+ * in `<dir>/states/<name>/` (state.html, index.json, live.png), its shared
5567
+ * files in `<dir>/states/assets/` — `film init --url`. A screen already
5568
+ * there under that name is replaced once the new one is in hand. */
5569
+ async function shootHome(opts) {
5570
+ const dir = resolve(opts.dir);
5571
+ const name = opts.name ?? "home";
5572
+ if (stateId(name, new Set()) !== name) throw new Error(`shoot: ${JSON.stringify(name)} is not a folder name a saved screen can have`);
5573
+ await mkdir(dir, { recursive: true });
5574
+ const work = await mkdtemp(join(dir, ".shoot-home-"));
5575
+ try {
5576
+ let page = {
5577
+ url: opts.url,
5578
+ title: ""
5579
+ };
5580
+ const { log } = await runShoot({
5581
+ script: async (s) => {
5582
+ page = await s.open(opts.url, {
5583
+ ...opts.ready ? { ready: opts.ready } : {},
5584
+ ...opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}
5585
+ });
5586
+ await s.still(name, { state: true });
5587
+ },
5588
+ outDir: work,
5589
+ ...opts.width ? { width: opts.width } : {},
5590
+ ...opts.height ? { height: opts.height } : {},
5591
+ ...opts.scale ? { scale: opts.scale } : {},
5592
+ ...opts.chromePath ? { chromePath: opts.chromePath } : {},
5593
+ ...opts.userDataDir ? { userDataDir: opts.userDataDir } : {},
5594
+ ...opts.onNote ? { onNote: opts.onNote } : {},
5595
+ ...opts.components === false ? { components: false } : {},
5596
+ ...opts.materials === false ? { materials: false } : {},
5597
+ ...opts.steady === false ? { steady: false } : {}
5598
+ });
5599
+ const item = log.states?.items.find((i) => i.id === name);
5600
+ const moving = log.stills.find((s) => s.state === name)?.moving;
5601
+ if (!item) throw new Error(`shoot: ${opts.url} gave no saved screen`);
5602
+ const states = join(dir, "states");
5603
+ await mergeAssets(join(work, "states", "assets"), join(states, "assets"));
5604
+ const to = join(states, name);
5605
+ if (existsSync(to)) await rename(to, join(work, "previous"));
5606
+ await rename(join(work, "states", name), to);
5607
+ let components;
5608
+ let parts;
5609
+ const note = opts.onNote ?? ((l) => process.stderr.write(`${l}\n`));
5610
+ if (opts.components !== false && existsSync(join(to, "parts.json"))) try {
5611
+ const source = readComponentSource(to);
5612
+ const file = gatherComponents(source);
5613
+ components = {
5614
+ file,
5615
+ path: writeComponents(file, to)
5616
+ };
5617
+ try {
5618
+ parts = writePartFiles(file, source, join(dir, "parts"));
5619
+ } catch (e) {
5620
+ note(`shoot: no part files for ${name} (${e.message})`);
5621
+ }
5622
+ } catch (e) {
5623
+ note(`shoot: no components.json for ${name} (${e.message})`);
5624
+ }
5625
+ const materials = opts.materials === false ? void 0 : readMaterials({
5626
+ kind: "state",
5627
+ root: to,
5628
+ states: [{
5629
+ id: name,
5630
+ dir: to
5631
+ }]
5632
+ }).pages[0];
5633
+ return {
5634
+ dir: to,
5635
+ url: page.url,
5636
+ title: page.title,
5637
+ fidelity: item.fidelity,
5638
+ ...components ? { components } : {},
5639
+ ...parts ? { parts } : {},
5640
+ ...materials ? { materials } : {},
5641
+ ...moving ? { moving } : {}
5642
+ };
5643
+ } finally {
5644
+ await rm(work, {
5645
+ recursive: true,
5646
+ force: true
5647
+ });
5648
+ }
3184
5649
  }
3185
5650
 
3186
5651
  //#endregion
3187
- //#region src/post-shoot.ts
3188
- /** `make` withholds the healing re-render from a take that skipped steps
3189
- * under strict: the skipped-steps exit 2 fires regardless of anything a
3190
- * re-render could fix, so the render minutes buy nothing. */
3191
- const healingWithheld = (skippedSteps, strict) => skippedSteps > 0 && strict;
3192
- const countErrors = (issues) => issues.filter((i) => i.severity === "error").length;
3193
- async function runPostShootGates(io) {
3194
- const gate = async (name, run$1) => {
3195
- try {
3196
- return {
3197
- issues: await run$1(),
3198
- crashed: false
3199
- };
3200
- } catch (e) {
3201
- io.warn(`${name} did not run: ${e instanceof Error ? e.message : e}`);
3202
- return {
3203
- issues: [],
3204
- crashed: true
3205
- };
5652
+ //#region src/states-list.ts
5653
+ const area = (b) => Math.max(0, b[2]) * Math.max(0, b[3]);
5654
+ const contains = (b, x, y) => x >= b[0] && x <= b[0] + b[2] && y >= b[1] && y <= b[1] + b[3];
5655
+ const near = (u, v) => Math.abs(u - v) <= 2;
5656
+ const overlap = (a, b) => {
5657
+ const w = Math.min(a[0] + a[2], b[0] + b[2]) - Math.max(a[0], b[0]);
5658
+ const h = Math.min(a[1] + a[3], b[1] + b[3]) - Math.max(a[1], b[1]);
5659
+ return Math.max(0, w) * Math.max(0, h);
5660
+ };
5661
+ const toBox = (b) => [
5662
+ b.x,
5663
+ b.y,
5664
+ b.w,
5665
+ b.h
5666
+ ];
5667
+ const pathKey = (p) => p.join(".");
5668
+ const parentKey = (e) => pathKey(e.path.slice(0, -1));
5669
+ const isAncestorPath = (p, q) => p.length < q.length && p.every((v, i) => q[i] === v);
5670
+ const labelOf = (e) => elementLabel(e).trim();
5671
+ const dedup = (xs) => [...new Set(xs)];
5672
+ const joinTexts = (xs) => xs.map((x) => x.replace(/\s*·\s*$/, "").trim()).filter(Boolean).join(" · ");
5673
+ function indexed(index) {
5674
+ const byId = new Map(index.elements.map((e) => [e.id, e]));
5675
+ const byPath = new Map(index.elements.map((e) => [pathKey(e.path), e]));
5676
+ const children = new Map();
5677
+ const order = new Map();
5678
+ index.elements.forEach((e, i) => {
5679
+ order.set(e.id, i);
5680
+ const parent = byPath.get(parentKey(e));
5681
+ if (!parent || parent === e) return;
5682
+ const list = children.get(parent.id) ?? [];
5683
+ list.push(e);
5684
+ children.set(parent.id, list);
5685
+ });
5686
+ return {
5687
+ index,
5688
+ byId,
5689
+ byPath,
5690
+ children,
5691
+ order,
5692
+ cards: cardsOf(index, byPath)
5693
+ };
5694
+ }
5695
+ /** The element under a point: the smallest interactive one, else the
5696
+ * smallest of any kind. */
5697
+ function elementAt(index, x, y) {
5698
+ let best;
5699
+ for (const e of index.elements) {
5700
+ if (!contains(e.box, x, y)) continue;
5701
+ if (!best) {
5702
+ best = e;
5703
+ continue;
3206
5704
  }
5705
+ const better = e.interactive ? !best.interactive || area(e.box) < area(best.box) : !best.interactive && area(e.box) < area(best.box);
5706
+ if (better) best = e;
5707
+ }
5708
+ return best;
5709
+ }
5710
+ const SEMANTIC = {
5711
+ header: "header",
5712
+ nav: "nav",
5713
+ aside: "sidebar",
5714
+ main: "main",
5715
+ footer: "footer",
5716
+ dialog: "dialog",
5717
+ form: "form"
5718
+ };
5719
+ /** What to call a region: its landmark tag when it has one, else where it
5720
+ * sits on the page. */
5721
+ function regionName(e, vw, vh) {
5722
+ const [x, y, w, h] = e.box;
5723
+ const wide = w >= .8 * vw;
5724
+ const tall = h >= .6 * vh;
5725
+ const position = wide && h <= .25 * vh ? y <= .1 * vh ? "top bar" : y + h >= .9 * vh ? "bottom bar" : "band" : tall && w <= .35 * vw ? x <= .1 * vw ? "left rail" : x + w >= .9 * vw ? "right rail" : "column" : w >= .5 * vw && h >= .5 * vh ? "main" : "panel";
5726
+ const semantic = SEMANTIC[e.tag] ?? (e.role === "navigation" ? "nav" : e.role === "dialog" ? "dialog" : void 0);
5727
+ const name = semantic ?? position;
5728
+ return e.fixed ? `${name} (fixed)` : name;
5729
+ }
5730
+ /** What text cannot show: a stage, a filmstrip, an embed. */
5731
+ const HOLDS_TAGS = [
5732
+ "canvas",
5733
+ "video",
5734
+ "iframe",
5735
+ "img"
5736
+ ];
5737
+ /** "canvas · 18 img" — the paint surfaces and images inside an element, or "". */
5738
+ function holdsOf(index, id) {
5739
+ const counts = new Map();
5740
+ for (const e of subtree(index, id)) if (e.id !== id) counts.set(e.tag, (counts.get(e.tag) ?? 0) + 1);
5741
+ const parts = [];
5742
+ for (const tag of HOLDS_TAGS) {
5743
+ const n = counts.get(tag);
5744
+ if (n) parts.push(n === 1 ? tag : `${n} ${tag}`);
5745
+ }
5746
+ return parts.join(" · ");
5747
+ }
5748
+ function regionsOf(ix, stateId$1) {
5749
+ const { w, h } = ix.index.viewport;
5750
+ const out = [];
5751
+ for (const id of ix.index.layers) {
5752
+ const e = ix.byId.get(id);
5753
+ if (!e) continue;
5754
+ out.push({
5755
+ id,
5756
+ ref: `${stateId$1}:${id}`,
5757
+ name: regionName(e, w, h),
5758
+ tag: e.tag,
5759
+ box: e.box,
5760
+ ...e.fixed ? { fixed: true } : {},
5761
+ summary: joinTexts(contentOf(ix.index, id)),
5762
+ ...holdsOf(ix.index, id) ? { holds: holdsOf(ix.index, id) } : {}
5763
+ });
5764
+ }
5765
+ return out;
5766
+ }
5767
+ const deltaOf = (c) => [
5768
+ c.b.box[0] - c.a.box[0],
5769
+ c.b.box[1] - c.a.box[1],
5770
+ c.b.box[2] - c.a.box[2],
5771
+ c.b.box[3] - c.a.box[3]
5772
+ ];
5773
+ const sameDelta = (p, q) => p.every((v, i) => near(v, q[i]));
5774
+ /** The changes from `A` to `B`, grouped: an added subtree is one line at its
5775
+ * outermost added element; an existing element whose children were mostly
5776
+ * swapped is one "was → now" line; a run of three or more same-tag siblings
5777
+ * is one line; a wrapper that moved exactly as one of its children did is
5778
+ * left out, and so is a child that merely rode along with its parent. */
5779
+ function summarizeChanges(A, B, aId, bId) {
5780
+ const a = A.index;
5781
+ const b = B.index;
5782
+ const raw = diffStates(a, b);
5783
+ const back = new Map();
5784
+ for (const [ia, ib] of matchStates(a, b)) back.set(ib, ia);
5785
+ const added = new Set();
5786
+ const removed = new Set();
5787
+ const changed = new Map();
5788
+ for (const c of raw) if (c.kind === "added") added.add(c.b.id);
5789
+ else if (c.kind === "removed") removed.add(c.a.id);
5790
+ else changed.set(c.b.id, c);
5791
+ const coveredA = new Set();
5792
+ const coveredB = new Set();
5793
+ const coverA = (id) => {
5794
+ for (const e of subtree(a, id)) coveredA.add(e.id);
3207
5795
  };
3208
- const pass = async () => ({
3209
- check: await gate("take checks", io.checkTake),
3210
- cursor: await gate("cursor audit", io.auditCursor)
5796
+ const coverB = (id) => {
5797
+ for (const e of subtree(b, id)) coveredB.add(e.id);
5798
+ };
5799
+ const rawIn = (index, id, set) => subtree(index, id).filter((e) => set.has(e.id)).length;
5800
+ const lines = [];
5801
+ const refA = (id) => `${aId}:${id}`;
5802
+ const refB = (id) => `${bId}:${id}`;
5803
+ const roleOf = (e) => e.role ? { role: e.role } : {};
5804
+ const addedRoots = new Map();
5805
+ for (const e of b.elements) {
5806
+ if (!added.has(e.id)) continue;
5807
+ const parent = B.byPath.get(parentKey(e));
5808
+ if (parent && parent !== e && added.has(parent.id)) continue;
5809
+ const key = parent && parent !== e ? parent.id : "";
5810
+ const list = addedRoots.get(key) ?? [];
5811
+ list.push(e);
5812
+ addedRoots.set(key, list);
5813
+ }
5814
+ for (const [parentId, allRoots] of addedRoots) {
5815
+ const roots = allRoots.filter((r) => !coveredB.has(r.id));
5816
+ if (!roots.length) continue;
5817
+ const parent = parentId ? B.byId.get(parentId) : void 0;
5818
+ const parentA = parent ? A.byId.get(back.get(parent.id) ?? "") : void 0;
5819
+ if (parent && parentA) {
5820
+ const oldKids = A.children.get(parentA.id) ?? [];
5821
+ const newKids = B.children.get(parent.id) ?? [];
5822
+ const gone = oldKids.filter((k) => removed.has(k.id)).length;
5823
+ const swapped = oldKids.length === 0 || gone * 2 >= oldKids.length && roots.length * 2 >= newKids.length;
5824
+ if (swapped) {
5825
+ const content = joinTexts(contentOf(b, parent.id));
5826
+ const was = joinTexts(contentOf(a, parentA.id));
5827
+ const ch = changed.get(parent.id);
5828
+ lines.push({
5829
+ kind: "replaced",
5830
+ ref: refB(parent.id),
5831
+ id: parent.id,
5832
+ state: bId,
5833
+ tag: content ? parent.tag : roots[0].tag,
5834
+ ...roleOf(parent),
5835
+ box: parent.box,
5836
+ ...ch && (ch.moved || ch.resized) ? { from: ch.a.box } : {},
5837
+ content,
5838
+ was,
5839
+ ...B.cards.has(parent.id) ? { card: true } : {},
5840
+ ...content ? {} : { count: roots.length },
5841
+ covers: rawIn(b, parent.id, added) + rawIn(a, parentA.id, removed) + subtree(b, parent.id).filter((e) => changed.has(e.id)).length,
5842
+ priority: content || was ? 0 : 2,
5843
+ order: B.order.get(parent.id)
5844
+ });
5845
+ coverB(parent.id);
5846
+ coverA(parentA.id);
5847
+ continue;
5848
+ }
5849
+ }
5850
+ if (parent && roots.length >= 3 && roots.every((r) => r.tag === roots[0].tag)) {
5851
+ const content = joinTexts(dedup(roots.flatMap((r) => contentOf(b, r.id))));
5852
+ lines.push({
5853
+ kind: "added",
5854
+ ref: refB(parent.id),
5855
+ id: parent.id,
5856
+ state: bId,
5857
+ tag: roots[0].tag,
5858
+ box: parent.box,
5859
+ content,
5860
+ count: roots.length,
5861
+ covers: roots.reduce((n, r) => n + subtree(b, r.id).length, 0),
5862
+ priority: content ? 0 : 2,
5863
+ order: B.order.get(roots[0].id)
5864
+ });
5865
+ for (const r of roots) coverB(r.id);
5866
+ continue;
5867
+ }
5868
+ for (const r of roots) {
5869
+ const content = joinTexts(contentOf(b, r.id));
5870
+ lines.push({
5871
+ kind: "added",
5872
+ ref: refB(r.id),
5873
+ id: r.id,
5874
+ state: bId,
5875
+ tag: r.tag,
5876
+ ...roleOf(r),
5877
+ box: r.box,
5878
+ content,
5879
+ ...B.cards.has(r.id) ? { card: true } : {},
5880
+ covers: subtree(b, r.id).length,
5881
+ priority: content || r.interactive ? 0 : 2,
5882
+ order: B.order.get(r.id)
5883
+ });
5884
+ coverB(r.id);
5885
+ }
5886
+ }
5887
+ const removedRoots = new Map();
5888
+ for (const e of a.elements) {
5889
+ if (!removed.has(e.id) || coveredA.has(e.id)) continue;
5890
+ const parent = A.byPath.get(parentKey(e));
5891
+ if (parent && parent !== e && removed.has(parent.id)) continue;
5892
+ const key = parent && parent !== e ? parent.id : "";
5893
+ const list = removedRoots.get(key) ?? [];
5894
+ list.push(e);
5895
+ removedRoots.set(key, list);
5896
+ }
5897
+ const offset = b.elements.length;
5898
+ for (const [parentId, roots] of removedRoots) {
5899
+ const parent = parentId ? A.byId.get(parentId) : void 0;
5900
+ if (parent && roots.length >= 3 && roots.every((r) => r.tag === roots[0].tag)) {
5901
+ const content = joinTexts(dedup(roots.flatMap((r) => contentOf(a, r.id))));
5902
+ lines.push({
5903
+ kind: "removed",
5904
+ ref: refA(parent.id),
5905
+ id: parent.id,
5906
+ state: aId,
5907
+ tag: roots[0].tag,
5908
+ box: parent.box,
5909
+ content,
5910
+ count: roots.length,
5911
+ covers: roots.reduce((n, r) => n + subtree(a, r.id).length, 0),
5912
+ priority: content ? 0 : 2,
5913
+ order: offset + A.order.get(roots[0].id)
5914
+ });
5915
+ for (const r of roots) coverA(r.id);
5916
+ continue;
5917
+ }
5918
+ for (const r of roots) {
5919
+ const content = joinTexts(contentOf(a, r.id));
5920
+ lines.push({
5921
+ kind: "removed",
5922
+ ref: refA(r.id),
5923
+ id: r.id,
5924
+ state: aId,
5925
+ tag: r.tag,
5926
+ ...roleOf(r),
5927
+ box: r.box,
5928
+ content,
5929
+ ...A.cards.has(r.id) ? { card: true } : {},
5930
+ covers: subtree(a, r.id).length,
5931
+ priority: content || r.interactive ? 0 : 2,
5932
+ order: offset + A.order.get(r.id)
5933
+ });
5934
+ coverA(r.id);
5935
+ }
5936
+ }
5937
+ const printedMoves = [];
5938
+ for (const c of raw) if (c.kind === "changed" && coveredB.has(c.b.id) && (c.moved || c.resized)) printedMoves.push({
5939
+ e: c.b,
5940
+ d: deltaOf(c)
3211
5941
  });
3212
- const verdict = (p, reRendered) => {
3213
- const issues = [...p.check.issues, ...p.cursor.issues];
3214
- return {
3215
- issues,
3216
- errors: countErrors(issues),
3217
- reRendered,
3218
- crashed: [...p.check.crashed ? ["take checks"] : [], ...p.cursor.crashed ? ["cursor audit"] : []]
3219
- };
5942
+ for (const c of raw) {
5943
+ if (c.kind !== "changed" || coveredB.has(c.b.id)) continue;
5944
+ const oldLabel = labelOf(c.a);
5945
+ const newLabel = labelOf(c.b);
5946
+ let text = c.text;
5947
+ if (text) for (const o of raw) {
5948
+ if (o.kind !== "changed" || !o.text || o === c || !isAncestorPath(o.b.path, c.b.path)) continue;
5949
+ if (labelOf(o.a).includes(oldLabel) && labelOf(o.b).includes(newLabel)) {
5950
+ text = false;
5951
+ break;
5952
+ }
5953
+ }
5954
+ let motion = c.moved || c.resized;
5955
+ const d = deltaOf(c);
5956
+ if (c.moved) {
5957
+ const rides = printedMoves.some((m) => isAncestorPath(m.e.path, c.b.path) && near(m.d[0], d[0]) && near(m.d[1], d[1]) && (!c.resized || near(m.d[2], d[2]) && near(m.d[3], d[3])));
5958
+ if (rides) motion = false;
5959
+ } else if (c.resized) {
5960
+ const followsContent = raw.some((o) => o.kind === "changed" && o !== c && !o.moved && o.resized && isAncestorPath(c.b.path, o.b.path) && sameDelta(deltaOf(o), d));
5961
+ if (followsContent) motion = false;
5962
+ }
5963
+ if (!text && !motion) continue;
5964
+ if (motion) printedMoves.push({
5965
+ e: c.b,
5966
+ d
5967
+ });
5968
+ const aText = c.a.text?.trim() ?? "";
5969
+ const visible = text && c.b.interactive && aText && aText === (c.b.text?.trim() ?? "") ? aText : void 0;
5970
+ const card = B.cards.has(c.b.id);
5971
+ lines.push({
5972
+ kind: "changed",
5973
+ ref: refB(c.b.id),
5974
+ id: c.b.id,
5975
+ state: bId,
5976
+ tag: c.b.tag,
5977
+ ...roleOf(c.b),
5978
+ box: c.b.box,
5979
+ ...motion ? { from: c.a.box } : {},
5980
+ ...text ? {
5981
+ was: oldLabel,
5982
+ content: newLabel
5983
+ } : {},
5984
+ ...visible ? { visible } : {},
5985
+ ...card ? { card: true } : {},
5986
+ covers: 1,
5987
+ priority: text ? 0 : newLabel || c.b.interactive || card ? 1 : 2,
5988
+ order: B.order.get(c.b.id)
5989
+ });
5990
+ }
5991
+ lines.sort((p, q) => p.order - q.order);
5992
+ return lines.map(({ order: _order,...line }) => line);
5993
+ }
5994
+ /** Pixels changed over a region no element change touches: a canvas
5995
+ * repaint, a CSS-only restyle — the film must use the recording there. */
5996
+ function pixelsUnexplained(effect, changes, page) {
5997
+ const box = toBox(effect);
5998
+ const size = area(box);
5999
+ if (size < .02 * page) return false;
6000
+ let covered = 0;
6001
+ for (const c of changes) {
6002
+ covered += overlap(box, c.box);
6003
+ if (c.from) covered += overlap(box, c.from);
6004
+ }
6005
+ return covered < .05 * size;
6006
+ }
6007
+ /** Kinds whose anchor is on the thing they act on (a scroll's or a press's
6008
+ * anchor is just where the cursor rests). */
6009
+ const POINT_KINDS = new Set([
6010
+ "click",
6011
+ "type",
6012
+ "drag",
6013
+ "hover",
6014
+ "look",
6015
+ "dropFiles"
6016
+ ]);
6017
+ function describeAction(e, i, items, indexOf) {
6018
+ const kind = e.kind ?? "click";
6019
+ const afterIdx = e.state ? items.findIndex((s) => s.id === e.state) : -1;
6020
+ let before;
6021
+ if (afterIdx > 0) before = items[afterIdx - 1].id;
6022
+ else for (const it of items) if (it.tMs <= e.tMs) before = it.id;
6023
+ const beforeIndex = indexOf(before);
6024
+ const point = e.kind === "dropFiles" ? e.to : {
6025
+ x: e.x,
6026
+ y: e.y
3220
6027
  };
3221
- const first = await pass();
3222
- io.onFindings([...first.check.issues, ...first.cursor.issues], "post-shoot");
3223
- const firstCursorErrors = countErrors(first.cursor.issues);
3224
- if (!(firstCursorErrors > 0 && io.reRender)) return verdict(first, false);
3225
- io.log("the cursor audit failed — re-rendering once from the frozen capture (a transient renderer misdraw heals; a repeat means the renderer disagrees with its own math) …");
6028
+ let el;
6029
+ let by = "capture";
6030
+ if (e.target && beforeIndex) el = beforeIndex.elements.find((x) => x.id === e.target);
6031
+ if (!el && beforeIndex && POINT_KINDS.has(kind)) {
6032
+ el = elementAt(beforeIndex, point.x, point.y);
6033
+ by = "point";
6034
+ }
6035
+ const durationMs = "durationMs" in e && e.durationMs > 0 ? e.durationMs : void 0;
6036
+ return {
6037
+ id: `a${i + 1}`,
6038
+ kind,
6039
+ ...e.sel ? { label: e.sel } : {},
6040
+ tMs: e.tMs,
6041
+ ...durationMs ? { endMs: e.tMs + durationMs } : {},
6042
+ x: e.x,
6043
+ y: e.y,
6044
+ ..."to" in e && e.to ? { to: e.to } : {},
6045
+ ...e.box ? { box: e.box } : {},
6046
+ ...before ? { before } : {},
6047
+ ...e.state ? { after: e.state } : {},
6048
+ ...el && before ? { target: {
6049
+ state: before,
6050
+ id: el.id,
6051
+ ref: `${before}:${el.id}`,
6052
+ tag: el.tag,
6053
+ ...el.role ? { role: el.role } : {},
6054
+ label: labelOf(el),
6055
+ box: el.box,
6056
+ by
6057
+ } } : {},
6058
+ ...e.effectBox ? { effectBox: e.effectBox } : {},
6059
+ ...e.changeCoverage != null ? { changeCoverage: e.changeCoverage } : {},
6060
+ ...e.result ? { result: e.result } : {},
6061
+ ...e.settledMs != null ? { settledMs: e.settledMs } : {},
6062
+ ...e.kind === "type" ? { text: e.text } : {},
6063
+ ...e.kind === "press" ? { keys: e.keys } : {},
6064
+ ...e.kind === "scroll" ? { dy: e.dy } : {},
6065
+ ...e.kind === "dropFiles" ? { files: e.files.map((f) => f.name) } : {},
6066
+ ...e.caption ? { caption: e.caption } : {},
6067
+ ...e.note ? { note: e.note } : {}
6068
+ };
6069
+ }
6070
+ /** Everything `open-take states` prints, as data. `takeDir` is the take's
6071
+ * working dir (`<name>.take/`). Throws when the take has no saved states. */
6072
+ function describeTake(takeDir) {
6073
+ const dir = resolve(takeDir);
6074
+ const logPath = join(dir, "capture.json");
6075
+ let log;
3226
6076
  try {
3227
- await io.reRender();
6077
+ log = JSON.parse(readFileSync(logPath, "utf8"));
3228
6078
  } catch (e) {
3229
- io.warn(`the re-render failed (${e instanceof Error ? e.message : e}) — keeping the first audit's findings`);
3230
- return verdict(first, false);
6079
+ throw new Error(e.code === "ENOENT" ? `no capture log at ${logPath} — not a take produced by \`make\` (or the wrong path)` : `unreadable capture log ${logPath}: ${e.message}`);
3231
6080
  }
3232
- const second = await pass();
3233
- const carried = {
3234
- check: second.check.crashed ? first.check : second.check,
3235
- cursor: second.cursor.crashed ? first.cursor : second.cursor
6081
+ const items = log.states?.items ?? [];
6082
+ if (!items.length) throw new Error(`${basename(dir)} has no saved states — re-record it with \`open-take make --states\` (the recording then also saves the page's structure after the warmup and after every step)`);
6083
+ const statesDir = join(dir, log.states?.dir || "states");
6084
+ const loaded = new Map();
6085
+ for (const it of items) {
6086
+ const read = readStateIndex(join(statesDir, it.id));
6087
+ loaded.set(it.id, typeof read === "string" ? read : indexed(read));
6088
+ }
6089
+ const indexOf = (id) => {
6090
+ const v = id ? loaded.get(id) : void 0;
6091
+ return typeof v === "object" ? v.index : void 0;
6092
+ };
6093
+ const actions = log.events.map((e, i) => describeAction(e, i, items, indexOf));
6094
+ const afterOf = new Map(actions.filter((x) => x.after).map((x) => [x.after, x]));
6095
+ const page = log.viewport.w * log.viewport.h;
6096
+ const states = [];
6097
+ let ok = 0;
6098
+ const failed = [];
6099
+ const moving = [];
6100
+ const missing = [];
6101
+ items.forEach((it, k) => {
6102
+ const ix = loaded.get(it.id);
6103
+ const action = afterOf.get(it.id);
6104
+ const base = {
6105
+ id: it.id,
6106
+ tMs: it.tMs,
6107
+ ...it.step != null ? { step: it.step } : {},
6108
+ ...action ? { after: action.id } : {},
6109
+ status: "ok"
6110
+ };
6111
+ if (it.moving) {
6112
+ states.push({
6113
+ ...base,
6114
+ status: "moving"
6115
+ });
6116
+ moving.push(it.id);
6117
+ return;
6118
+ }
6119
+ if (typeof ix === "string") {
6120
+ states.push({
6121
+ ...base,
6122
+ status: "missing",
6123
+ error: ix
6124
+ });
6125
+ missing.push(it.id);
6126
+ return;
6127
+ }
6128
+ const fidelity = ix.index.fidelity ?? it.fidelity;
6129
+ const status = fidelity && !fidelity.ok ? "failed" : "ok";
6130
+ if (status === "ok") ok++;
6131
+ else failed.push(it.id);
6132
+ let prev;
6133
+ let prevId = "";
6134
+ for (let j = k - 1; j >= 0 && typeof prev !== "object"; j--) {
6135
+ prev = loaded.get(items[j].id);
6136
+ prevId = items[j].id;
6137
+ }
6138
+ const changes = typeof prev === "object" ? summarizeChanges(prev, ix, prevId, it.id) : void 0;
6139
+ states.push({
6140
+ ...base,
6141
+ status,
6142
+ ...fidelity ? { fidelity } : {},
6143
+ url: ix.index.url,
6144
+ title: ix.index.title,
6145
+ elements: ix.index.elements.length,
6146
+ regions: regionsOf(ix, it.id),
6147
+ ...changes ? { changes } : {},
6148
+ ...action?.effectBox ? { pixels: {
6149
+ box: action.effectBox,
6150
+ ...action.changeCoverage != null ? { coverage: action.changeCoverage } : {},
6151
+ unexplained: pixelsUnexplained(action.effectBox, changes ?? [], page)
6152
+ } } : {}
6153
+ });
6154
+ });
6155
+ const first = [...loaded.values()].find((v) => typeof v === "object");
6156
+ return {
6157
+ take: basename(dir),
6158
+ dir: statesDir,
6159
+ viewport: {
6160
+ ...log.viewport,
6161
+ ...first ? { dpr: first.index.viewport.dpr } : {}
6162
+ },
6163
+ fidelity: {
6164
+ ok,
6165
+ total: ok + failed.length,
6166
+ failed,
6167
+ moving,
6168
+ missing
6169
+ },
6170
+ actions,
6171
+ states
3236
6172
  };
3237
- io.onFindings([...carried.check.issues, ...carried.cursor.issues], "re-audit");
3238
- io.log(second.cursor.crashed ? "re-audit could not re-measure the cursor — keeping the first audit's findings (a re-render that cannot be verified is not a heal)" : countErrors(second.cursor.issues) > 0 ? "re-audit: the drawn cursor is STILL off — the renderer disagrees with its own math on this take; that needs a look, not another retry" : "re-audit: cursor clean — the misdraw was transient; the delivered mp4 is now the re-render");
3239
- return verdict(carried, true);
3240
6173
  }
3241
-
3242
- //#endregion
3243
- //#region src/defect-report.ts
3244
- const DEFECTS_OPEN = "--- open-take defects v1 ---";
3245
- const DEFECTS_CLOSE = "--- end open-take defects ---";
3246
- const NOTE = "Deterministic gate findings, measured against the live app and the recorded take — facts, not opinions. error = the gate refuses this take; warn = suspect — fix it or state why it stays.";
3247
- const REPAIR = "Relay this block VERBATIM to the author of the plan and ask for the ENTIRE corrected plan (same JSON shape): fix exactly what the defects name and keep every other editorial decision unchanged. Then re-run the same command. At most two repair rounds — a take still defective after two needs a human, not a third round.";
3248
- const asDefects = (gate, issues) => issues.map((i) => ({
3249
- gate,
3250
- severity: i.severity,
3251
- path: i.path,
3252
- message: i.message,
3253
- ...i.fix ? { fix: i.fix } : {}
3254
- }));
3255
- /** capture-time skipped steps as defects — error-severity: the beat is gone
3256
- * from the video, which is exactly what the strict exit refuses. The fix
3257
- * copy follows the reason: a focus skip means the target RESOLVED and the
3258
- * not-found copy ("point the target at an element that exists") would send
3259
- * the repair round at the wrong dimension. */
3260
- const skippedDefects = (skipped) => skipped.map((s) => ({
3261
- gate: "capture",
3262
- severity: "error",
3263
- path: `steps[${s.step}]`,
3264
- message: `${s.action} ${JSON.stringify(s.target ?? "")}: step SKIPPED at capture (${s.reason}) — the video is missing this beat`,
3265
- fix: s.reason.startsWith("focus never reached") ? "the target resolved but never took focus — have an earlier step click/open the control that arms this field, retarget the step at the element that actually receives the text, or drop the step; then re-make" : "point the target at an element that exists when this step runs (a pre-capture warning above may name the impostor or the late binding), or drop the step; then re-make"
3266
- }));
3267
- /** Settle underruns whose beat DID go quiet carry a measured number the
3268
- * author can copy — the one defect class where the fix is literally a
3269
- * value. Beats that never settled (`reason: "budget"`) are excluded: telling
3270
- * an author to raise settleMs toward a number that satisfies nothing is a
3271
- * ratchet, and the human summary already explains that case. */
3272
- const settleDefects = (settleWaits) => settleWaits.filter((w) => w.reason === "idle").map((w) => ({
3273
- gate: "capture",
3274
- severity: "warn",
3275
- path: `steps[${w.step}].settleMs`,
3276
- message: `${w.action}: held ${w.heldMs}ms but the page needed ~${w.heldMs + w.waitedMs}ms to go quiet — the capture waited, the plan under-budgeted`,
3277
- fix: `set this step's settleMs to ${w.heldMs + w.waitedMs}`
3278
- }));
3279
- function buildDefectReport(opts) {
6174
+ /** One state as a film would carve it: each region, the cards inside it, and
6175
+ * under each the interactive and text-bearing elements with their boxes. */
6176
+ function outlineState(data, id) {
6177
+ const state = data.states.find((s) => s.id === id);
6178
+ if (!state) throw new Error(`no state ${id} in ${data.take} — it has ${data.states.map((s) => s.id).join(", ")}`);
6179
+ const read = readStateIndex(join(data.dir, id));
6180
+ if (typeof read === "string") throw new Error(read);
6181
+ const ix = indexed(read);
6182
+ const index = ix.index;
6183
+ const regionIds = new Set(index.layers);
6184
+ const ref = (e) => `${id}:${e.id}`;
6185
+ const nearest = (e, pick) => {
6186
+ let cur = ix.byPath.get(parentKey(e));
6187
+ while (cur && cur !== e) {
6188
+ if (pick(cur)) return cur;
6189
+ const up = ix.byPath.get(parentKey(cur));
6190
+ if (!up || up === cur) break;
6191
+ cur = up;
6192
+ }
6193
+ return void 0;
6194
+ };
6195
+ const isCard = (e) => ix.cards.has(e.id) && !regionIds.has(e.id);
6196
+ const isRegion = (e) => regionIds.has(e.id);
6197
+ const cardNode = new Map();
6198
+ for (const e of index.elements) if (isCard(e)) cardNode.set(e.id, {
6199
+ ref: ref(e),
6200
+ id: e.id,
6201
+ tag: e.tag,
6202
+ ...e.role ? { role: e.role } : {},
6203
+ box: e.box,
6204
+ content: joinTexts(contentOf(index, e.id)),
6205
+ ...holdsOf(index, e.id) ? { holds: holdsOf(index, e.id) } : {},
6206
+ cards: [],
6207
+ leaves: []
6208
+ });
6209
+ const regions = [];
6210
+ const regionNode = new Map();
6211
+ for (const r of regionsOf(ix, id)) {
6212
+ const node = {
6213
+ ...r,
6214
+ cards: [],
6215
+ leaves: []
6216
+ };
6217
+ regions.push(node);
6218
+ regionNode.set(r.id, node);
6219
+ }
6220
+ const elsewhere = {
6221
+ cards: [],
6222
+ leaves: []
6223
+ };
6224
+ const home = (e) => {
6225
+ const card = nearest(e, isCard);
6226
+ if (card) return cardNode.get(card.id);
6227
+ const region = nearest(e, isRegion);
6228
+ return region ? regionNode.get(region.id) : elsewhere;
6229
+ };
6230
+ for (const e of index.elements) {
6231
+ if (isRegion(e)) continue;
6232
+ if (isCard(e)) {
6233
+ home(e).cards.push(cardNode.get(e.id));
6234
+ continue;
6235
+ }
6236
+ const label = labelOf(e);
6237
+ const surface = PAINT_TAGS.has(e.tag);
6238
+ if (!e.interactive && !label && !surface) continue;
6239
+ if (!e.interactive && e.role === "img" && !surface) continue;
6240
+ if (!e.interactive && label) {
6241
+ const above = nearest(e, (x) => !!labelOf(x) && !isCard(x) && !isRegion(x));
6242
+ if (above && labelOf(above).includes(label)) continue;
6243
+ }
6244
+ const text = e.text?.trim() ?? "";
6245
+ const visible = text && e.name && !e.name.includes(text) ? text : void 0;
6246
+ home(e).leaves.push({
6247
+ ref: ref(e),
6248
+ id: e.id,
6249
+ tag: e.tag,
6250
+ ...e.role ? { role: e.role } : {},
6251
+ label,
6252
+ ...visible ? { visible } : {},
6253
+ box: e.box,
6254
+ ...e.interactive ? { interactive: true } : {}
6255
+ });
6256
+ }
6257
+ const hoist = (cards) => cards.map((c) => {
6258
+ const inner = hoist(c.cards);
6259
+ const only = inner[0];
6260
+ return only && inner.length === 1 && !c.leaves.length && !c.holds ? only : {
6261
+ ...c,
6262
+ cards: inner
6263
+ };
6264
+ });
6265
+ for (const r of regions) r.cards = hoist(r.cards);
6266
+ elsewhere.cards = hoist(elsewhere.cards);
3280
6267
  return {
3281
- format: "open-take-defects/1",
3282
- verb: opts.verb,
3283
- verdict: opts.verdict,
3284
- exitCode: opts.exitCode,
3285
- ...opts.plan ? { plan: opts.plan } : {},
3286
- ...opts.master ? { master: opts.master } : {},
3287
- errors: opts.defects.filter((d) => d.severity === "error").length,
3288
- warns: opts.defects.filter((d) => d.severity === "warn").length,
3289
- defects: opts.defects,
3290
- note: NOTE,
3291
- repair: REPAIR
6268
+ state,
6269
+ regions,
6270
+ ...elsewhere.cards.length || elsewhere.leaves.length ? { elsewhere } : {}
3292
6271
  };
3293
6272
  }
3294
- /** the fixed stdout section — everything between the sentinels is one JSON
3295
- * object, so the driving agent extracts it with two line matches and no
3296
- * scraping of the prose above it */
3297
- const renderDefectBlock = (report) => `\n${DEFECTS_OPEN}\n${JSON.stringify(report, null, 1)}\n${DEFECTS_CLOSE}\n`;
6273
+ const PAINT_TAGS = new Set([
6274
+ "canvas",
6275
+ "video",
6276
+ "iframe"
6277
+ ]);
6278
+ const WIDTH = 100;
6279
+ const secs = (ms) => `${(ms / 1e3).toFixed(2)}s`;
6280
+ const boxStr = (b) => `[${b.map((v) => Math.round(v)).join(",")}]`;
6281
+ const trunc = (s, n) => s.length <= n ? s : `${s.slice(0, n - 1).trimEnd()}…`;
6282
+ const quote = (s, n) => JSON.stringify(trunc(s, n));
6283
+ /** `prefix` then `parts` flowed with " · ", continuation lines indented to
6284
+ * the prefix. */
6285
+ function flow(prefix, parts) {
6286
+ const out = [];
6287
+ const indent = " ".repeat(prefix.length);
6288
+ let line = prefix;
6289
+ let empty = true;
6290
+ for (const p of parts) {
6291
+ if (!empty && line.length + 3 + p.length > WIDTH) {
6292
+ out.push(`${line} ·`);
6293
+ line = indent + p;
6294
+ } else line = empty ? line + p : `${line} · ${p}`;
6295
+ empty = false;
6296
+ }
6297
+ out.push(line);
6298
+ return out;
6299
+ }
6300
+ function motionText(from, to) {
6301
+ const moved = !near(from[0], to[0]) || !near(from[1], to[1]);
6302
+ const dw = to[2] - from[2];
6303
+ const dh = to[3] - from[3];
6304
+ const resized = !near(dw, 0) || !near(dh, 0);
6305
+ if (moved) return `${resized ? "moved + resized" : "moved"} ${boxStr(from)} → ${boxStr(to)}`;
6306
+ if (near(dw, 0)) return `${dh > 0 ? "grew" : "shrank"} ${from[3]} → ${to[3]} px tall`;
6307
+ if (near(dh, 0)) return `${dw > 0 ? "grew" : "shrank"} ${from[2]} → ${to[2]} px wide`;
6308
+ return `resized ${boxStr(from)} → ${boxStr(to)}`;
6309
+ }
6310
+ function changeText(l) {
6311
+ const card = l.card ? " card" : "";
6312
+ const box = boxStr(l.box);
6313
+ const motion = l.from ? motionText(l.from, l.box) : "";
6314
+ const content = l.content ? ` ${quote(l.content, 100)}` : "";
6315
+ switch (l.kind) {
6316
+ case "added": return l.count ? `+ ${l.count} ${l.tag} in ${l.ref} ${box}${content}` : `+ ${l.ref}${card} ${l.content ? "" : `${l.tag} `}${box}${content}`;
6317
+ case "removed": return l.count ? `- ${l.count} ${l.tag} from ${l.ref} ${box}${content}` : `- ${l.ref}${card} ${l.content ? "" : `${l.tag} `}${box}${content}`;
6318
+ case "replaced": {
6319
+ const tail = motion ? ` · ${motion}` : "";
6320
+ if (!l.was) return l.count ? `+ ${l.count} ${l.tag} in ${l.ref} ${box}${content}${tail}` : `+ ${l.ref}${card} ${box}${content}${tail}`;
6321
+ return `~ ${l.ref}${card} ${box} ${quote(l.was, 50)} → ${quote(l.content ?? "", 100)}${tail}`;
6322
+ }
6323
+ case "changed": {
6324
+ const parts = [];
6325
+ if (l.was != null) parts.push(l.visible ? `${quote(l.visible, 40)} named ${quote(l.was, 50)} → ${quote(l.content ?? "", 50)}` : `${quote(l.was, 50)} → ${quote(l.content ?? "", 60)}`);
6326
+ if (motion) parts.push(motion);
6327
+ else parts.push(box);
6328
+ return `~ ${l.ref}${card} ${parts.join(" · ")}`;
6329
+ }
6330
+ }
6331
+ }
6332
+ function statusText(s) {
6333
+ if (s.status === "missing") return `MISSING — ${s.error}`;
6334
+ if (s.status === "moving") return "MOVING — not saved: the page never went quiet here; use the recording";
6335
+ if (s.status === "failed") return `FIDELITY FAILED ${s.fidelity?.psnr.toFixed(1)} dB — use the recording here`;
6336
+ return "ok";
6337
+ }
6338
+ function stateHeading(s, first) {
6339
+ const what = s.after ? `after ${s.after}` : first ? "start" : s.step != null ? `after step ${s.step + 1} (no action)` : "no action";
6340
+ return `${s.id.padEnd(3)} ${what} · ${secs(s.tMs)} · ${statusText(s)}`;
6341
+ }
6342
+ const regionSignature = (regions) => regions.map((r) => `${r.name}${boxStr(r.box)}`).join("|");
6343
+ const holdsText = (holds) => holds ? ` (${holds})` : "";
6344
+ function regionLines(regions) {
6345
+ const parts = regions.map((r) => `${r.id} ${r.name}${r.summary ? ` ${quote(r.summary, 36)}` : ""}${holdsText(r.holds)}`);
6346
+ return flow(" regions ", parts);
6347
+ }
6348
+ function actionText(x) {
6349
+ const label = x.label ? quote(x.label, 48) : "";
6350
+ let head;
6351
+ let prep = "on";
6352
+ switch (x.kind) {
6353
+ case "type":
6354
+ head = `type ${quote(x.text ?? "", 40)}`;
6355
+ prep = "into";
6356
+ break;
6357
+ case "press":
6358
+ head = `press ${x.keys ?? ""}${label ? ` (reveals ${label})` : ""}`;
6359
+ break;
6360
+ case "scroll":
6361
+ head = `scroll ${(x.dy ?? 0) < 0 ? "up" : "down"} ${Math.abs(x.dy ?? 0)}px`;
6362
+ break;
6363
+ case "dropFiles":
6364
+ head = `drop ${x.files?.join(", ") ?? ""}`;
6365
+ prep = "onto";
6366
+ break;
6367
+ case "drag":
6368
+ head = `drag ${label} → (${x.to?.x},${x.to?.y})`.replace(" ", " ");
6369
+ prep = "from";
6370
+ break;
6371
+ default: head = `${x.kind}${label ? ` ${label}` : ""}`;
6372
+ }
6373
+ const time = x.endMs ? `${secs(x.tMs)}–${secs(x.endMs)}` : secs(x.tMs);
6374
+ let target = "";
6375
+ if (x.target) {
6376
+ const t = x.target;
6377
+ const name = t.label && t.label !== x.label ? ` ${quote(t.label, 40)}` : "";
6378
+ const role = t.label ? "" : ` (${t.role ?? t.tag})`;
6379
+ target = ` · ${prep} ${t.ref}${name}${role}`;
6380
+ }
6381
+ const result = x.result ? ` · result showed ${secs(x.result.atMs)}${x.result.doneMs > x.result.atMs ? `–${secs(x.result.doneMs)}` : ""} (measured)` : x.settledMs != null ? ` · page quiet ${secs(x.settledMs)} (estimated)` : "";
6382
+ return `${x.id.padEnd(3)} ${head} · ${time}${target}${result}`;
6383
+ }
6384
+ /** The listing (or, with `state`, one state's outline) as text. */
6385
+ function formatTakeStates(data, opts = {}) {
6386
+ if (opts.state) return formatOutline(outlineState(data, opts.state));
6387
+ const cap = 8;
6388
+ const n = data.states.length;
6389
+ const { ok, total, failed, moving, missing } = data.fidelity;
6390
+ const saved = n - moving.length;
6391
+ const out = [
6392
+ `${data.take} — ${saved} saved state${saved === 1 ? "" : "s"} · page ${data.viewport.w}×${data.viewport.h} CSS px · fidelity ${ok}/${total} ok${failed.length ? ` (${failed.join(", ")} FAILED)` : ""}` + (moving.length ? ` · ${moving.join(", ")} moving, not saved` : "") + (missing.length ? ` · ${missing.join(", ")} missing` : ""),
6393
+ `ids are per state: name an element together with its state (s3:e32) · --state <id> outlines one state`,
6394
+ ""
6395
+ ];
6396
+ const timeline = [...data.states.map((state) => ({
6397
+ at: state.tMs,
6398
+ state
6399
+ })), ...data.actions.map((action) => ({
6400
+ at: action.tMs,
6401
+ action
6402
+ }))];
6403
+ timeline.sort((p, q) => p.at - q.at || ("action" in p ? -1 : 1));
6404
+ let lastRegions;
6405
+ let lastPage;
6406
+ let first = true;
6407
+ for (const entry of timeline) {
6408
+ if ("action" in entry) {
6409
+ out.push(actionText(entry.action));
6410
+ continue;
6411
+ }
6412
+ const s = entry.state;
6413
+ out.push(stateHeading(s, first));
6414
+ first = false;
6415
+ if (s.status === "missing") continue;
6416
+ const page = `${s.url ?? ""} ${s.title ? quote(s.title, 60) : ""}`.trim();
6417
+ if (page && page !== lastPage) {
6418
+ out.push(` page ${page}`);
6419
+ lastPage = page;
6420
+ }
6421
+ if (s.regions?.length) {
6422
+ const sig = regionSignature(s.regions);
6423
+ if (sig !== lastRegions) {
6424
+ out.push(...regionLines(s.regions));
6425
+ lastRegions = sig;
6426
+ }
6427
+ }
6428
+ const changes = s.changes ?? [];
6429
+ const shown = [...changes].map((c, i) => ({
6430
+ c,
6431
+ i
6432
+ })).sort((p, q) => p.c.priority - q.c.priority || p.i - q.i).slice(0, cap).sort((p, q) => p.i - q.i).map((x) => x.c);
6433
+ for (const c of shown) out.push(` ${changeText(c)}`);
6434
+ if (changes.length > shown.length) out.push(` … ${changes.length - shown.length} more`);
6435
+ if (s.pixels) out.push(` pixels ${boxStr(toBox(s.pixels.box))}${s.pixels.unexplained ? " — no element changed there: a paint or style change, only the recording shows it" : ""}`);
6436
+ else if (!changes.length && s.changes) out.push(" no change");
6437
+ }
6438
+ return out.join("\n");
6439
+ }
6440
+ function leafText(l) {
6441
+ const role = l.role && l.role !== "img" ? l.role : l.interactive || !l.label ? l.tag : void 0;
6442
+ const label = l.visible ? ` ${quote(l.visible, 24)} named ${quote(l.label, 40)}` : l.label ? ` ${quote(l.label, 40)}` : "";
6443
+ return `${l.id}${role ? ` ${role}` : ""}${label} ${boxStr(l.box)}`;
6444
+ }
6445
+ const LEAF_CAP = 12;
6446
+ const CARD_CAP = 8;
6447
+ function outlineLines(node, depth, out) {
6448
+ const indent = " ".repeat(depth * 2 + 5);
6449
+ const num = (id) => Number(id.slice(1));
6450
+ const cards = node.cards.slice(0, CARD_CAP);
6451
+ const leaves = node.leaves.slice(0, LEAF_CAP);
6452
+ const items = [...cards.map((c) => ({
6453
+ at: num(c.id),
6454
+ card: c
6455
+ })), ...leaves.map((l) => ({
6456
+ at: num(l.id),
6457
+ leaf: l
6458
+ }))].sort((p, q) => p.at - q.at);
6459
+ let run$1 = [];
6460
+ const flush = () => {
6461
+ if (run$1.length) out.push(...flow(indent, run$1));
6462
+ run$1 = [];
6463
+ };
6464
+ for (const item of items) {
6465
+ if ("leaf" in item) {
6466
+ run$1.push(leafText(item.leaf));
6467
+ continue;
6468
+ }
6469
+ flush();
6470
+ const c = item.card;
6471
+ const role = c.role && c.role !== "img" ? `${c.role} ` : "";
6472
+ out.push(`${indent}card ${c.id} ${role}${boxStr(c.box)}${c.content ? ` ${quote(c.content, 90)}` : ""}${holdsText(c.holds)}`);
6473
+ outlineLines(c, depth + 1, out);
6474
+ }
6475
+ if (node.leaves.length > LEAF_CAP) run$1.push(`… ${node.leaves.length - LEAF_CAP} more`);
6476
+ flush();
6477
+ if (node.cards.length > CARD_CAP) out.push(`${indent}… ${node.cards.length - CARD_CAP} more cards`);
6478
+ }
6479
+ function formatOutline(o) {
6480
+ const s = o.state;
6481
+ const out = [
6482
+ `${stateHeading(s, s.id === "s0")} · ${s.elements ?? 0} elements${s.title ? ` · ${quote(s.title, 60)}` : ""}${s.url ? ` ${s.url}` : ""}`,
6483
+ `regions back → front · card = a group a film might show on its own (≥2 labels, 0.3–20% of the page) · name elements as ${s.id}:e<N>`,
6484
+ ""
6485
+ ];
6486
+ for (const r of o.regions) {
6487
+ out.push(`${r.id.padEnd(4)} ${r.name} ${boxStr(r.box)}${r.summary ? ` ${quote(r.summary, 80)}` : ""}${holdsText(r.holds)}`);
6488
+ outlineLines(r, 0, out);
6489
+ }
6490
+ if (o.elsewhere) {
6491
+ out.push("— outside every region");
6492
+ outlineLines(o.elsewhere, 0, out);
6493
+ }
6494
+ return out.join("\n");
6495
+ }
3298
6496
 
3299
6497
  //#endregion
3300
6498
  //#region src/index.ts
@@ -3316,6 +6514,16 @@ async function loadCaptureLogSibling(capturePath) {
3316
6514
  }
3317
6515
  async function makeTake(plan, opts) {
3318
6516
  const work = await mkdtemp(join(tmpdir(), "open-take-"));
6517
+ try {
6518
+ return await makeTakeIn(work, plan, opts);
6519
+ } finally {
6520
+ await rm(work, {
6521
+ recursive: true,
6522
+ force: true
6523
+ });
6524
+ }
6525
+ }
6526
+ async function makeTakeIn(work, plan, opts) {
3319
6527
  const tmpVideo = join(work, "capture.mp4");
3320
6528
  const chromePath = await ensureChrome(opts.capture?.chromePath);
3321
6529
  const raw = await captureTake(plan, {
@@ -3328,6 +6536,25 @@ async function makeTake(plan, opts) {
3328
6536
  await mkdir(dirname(take.mp4Path), { recursive: true });
3329
6537
  await ensureTakeDir(take);
3330
6538
  await copyFile(tmpVideo, capturePath);
6539
+ const statesDst = join(take.dir, "states");
6540
+ await rm(statesDst, {
6541
+ recursive: true,
6542
+ force: true
6543
+ });
6544
+ const statesSrc = join(work, "states");
6545
+ if (raw.states && existsSync(statesSrc)) await cp(statesSrc, statesDst, { recursive: true });
6546
+ for (const name of [
6547
+ "product-audio.wav",
6548
+ "product-sound.json",
6549
+ "product-sounds"
6550
+ ]) {
6551
+ await rm(join(take.dir, name), {
6552
+ recursive: true,
6553
+ force: true
6554
+ });
6555
+ const src = join(work, name);
6556
+ if (existsSync(src)) await cp(src, join(take.dir, name), { recursive: true });
6557
+ }
3331
6558
  try {
3332
6559
  opts.onCaptureReady?.(capturePath);
3333
6560
  } catch {}
@@ -3337,6 +6564,25 @@ async function makeTake(plan, opts) {
3337
6564
  url: plan.url
3338
6565
  };
3339
6566
  await writeFile(captureLogPath, JSON.stringify(log, null, 2));
6567
+ const componentsPath = join(take.dir, "components.json");
6568
+ await rm(componentsPath, { force: true });
6569
+ let components;
6570
+ let parts;
6571
+ if (log.states?.items.length && opts.capture?.components !== false) try {
6572
+ const source = readComponentSource(take.dir);
6573
+ const file = gatherComponents(source);
6574
+ components = {
6575
+ file,
6576
+ path: writeComponents(file, take.dir)
6577
+ };
6578
+ try {
6579
+ parts = writePartFiles(file, source, join(take.dir, "parts"));
6580
+ } catch (e) {
6581
+ console.error(`make: no part files (${e.message})`);
6582
+ }
6583
+ } catch (e) {
6584
+ console.error(`make: no components.json (${e.message})`);
6585
+ }
3340
6586
  const captureFps = opts.capture?.fps ?? 60;
3341
6587
  const planOpts = opts.planOpts?.output?.fps == null ? {
3342
6588
  ...opts.planOpts,
@@ -3346,6 +6592,27 @@ async function makeTake(plan, opts) {
3346
6592
  }
3347
6593
  } : opts.planOpts;
3348
6594
  const composition = planComposition(log, planOpts);
6595
+ if (opts.render === false) {
6596
+ await writeFile(take.compositionPath, JSON.stringify(composition, null, 2));
6597
+ await rm(take.mp4Path, { force: true });
6598
+ return {
6599
+ mp4Path: take.mp4Path,
6600
+ rendered: false,
6601
+ compositionPath: take.compositionPath,
6602
+ takeDir: take.dir,
6603
+ capturePath,
6604
+ captureLogPath,
6605
+ composition,
6606
+ skipped: log.skipped ?? [],
6607
+ precheck: log.precheck ?? [],
6608
+ settleWaits: log.settleWaits ?? [],
6609
+ ...log.paintedFrac != null ? { paintedFrac: log.paintedFrac } : {},
6610
+ dragCadence: dragCadence(log.events, log.captureCadence?.frameOffsetsMs ?? [], log.captureCadence?.arrivalOffsetsMs),
6611
+ warnings: [],
6612
+ ...components ? { components } : {},
6613
+ ...parts ? { parts } : {}
6614
+ };
6615
+ }
3349
6616
  const { mp4Path, compositionPath, warnings } = await renderTake({
3350
6617
  composition: opts.draft ? toDraft(composition) : composition,
3351
6618
  videoPath: capturePath,
@@ -3359,6 +6626,7 @@ async function makeTake(plan, opts) {
3359
6626
  if (opts.draft) await writeFile(compositionPath, JSON.stringify(composition, null, 2));
3360
6627
  return {
3361
6628
  mp4Path,
6629
+ rendered: true,
3362
6630
  compositionPath,
3363
6631
  takeDir: take.dir,
3364
6632
  capturePath,
@@ -3368,7 +6636,10 @@ async function makeTake(plan, opts) {
3368
6636
  precheck: log.precheck ?? [],
3369
6637
  settleWaits: log.settleWaits ?? [],
3370
6638
  ...log.paintedFrac != null ? { paintedFrac: log.paintedFrac } : {},
3371
- warnings
6639
+ dragCadence: dragCadence(log.events, log.captureCadence?.frameOffsetsMs ?? [], log.captureCadence?.arrivalOffsetsMs),
6640
+ warnings,
6641
+ ...components ? { components } : {},
6642
+ ...parts ? { parts } : {}
3372
6643
  };
3373
6644
  }
3374
6645
  /** Refine: re-render an EDITED composition over a saved capture — no app
@@ -3439,5 +6710,5 @@ async function renderCompositionFile(opts) {
3439
6710
  }
3440
6711
 
3441
6712
  //#endregion
3442
- export { CI_ALLOWED_TOOLS, CI_DISALLOWED_TOOLS, DEFECTS_CLOSE, DEFECTS_OPEN, PrecheckRefusal, SAY_IT_CARD, TAKE_DIR_SUFFIX, annotateCaptureLog, appBootEnv, asDefects, auditCursor, authProfile, beatLabel, buildAgentArgs, buildBadges, buildBeatSheet, buildCiBrief, buildDefectReport, buildFramePlan, buildFrameSheet, captureLogPathFor, captureTake, captureTakeCDP, checkLaunchFile, checkTake, ciAllowedOrigins, ciTake, composeLaunchFile, diffFrames, emitGithubOutputs, emitStepSummary, ensureChrome, ensureTakeDir, formatIssues, formatNotes, healingWithheld, initLaunchProject, inspectPage, lintPlan, loadCaptureLogSibling, makeTake, openPath, planTargets, precheckPlan, probeDurationS, profileDir, reRenderInPlace, readNotes, renderAbReel, renderBeforeAfter, renderComposition, renderCompositionFile, renderDefectBlock, renderDraft, renderFrames, renderLaunchFile, renderReview, renderTeaserGif, requireTakeFiles, resolveChrome, resolveNavigateUrl, resolveTakePaths, revealPath, runAgent, runPostShootGates, settleDefects, skippedDefects, stagePrev, startApp, startEditServer, takeFile, toDraft, validateComposition, waitForHttp, waitForNotes };
6713
+ export { CI_ALLOWED_TOOLS, CI_DISALLOWED_TOOLS, DEFECTS_CLOSE, DEFECTS_OPEN, PrecheckRefusal, SAY_IT_CARD, TAKE_DIR_SUFFIX, VIEWER_TOOLS, alignFrames, annotateCaptureLog, appBootEnv, asDefects, auditCursor, authProfile, beatLabel, buildAgentArgs, buildBadges, buildBeatSheet, buildCiBrief, buildDefectReport, buildFramePlan, buildFrameSheet, captureLogPathFor, captureTake, captureTakeCDP, changedLine, checkFilm, checkLaunchFile, checkTake, checkViewer, ciAllowedOrigins, ciTake, componentsLine, composeLaunchFile, describeTake, diffFrames, dragCadence, emitGithubOutputs, emitStepSummary, ensureChrome, ensureTakeDir, exampleSource, filmBeats, filmGallery, filmInitLines, filmListen, filmLook, filmPicture, filmProbe, filmReport, filmSheet, filmStills, filmStudy, followedLine, formatComponents, formatFilmBeats, formatFilmCheck, formatFilmListen, formatFilmLook, formatFilmProbe, formatFilmReport, formatFilmStudy, formatIssues, formatMaterials, formatNotes, formatTakeStates, healingWithheld, initFilm, initLaunchProject, inspectPage, inventoryComponents, inventoryMaterials, lintPlan, loadCaptureLogSibling, makeTake, materialsSummary, measureParts, measureStateDirs, measureStateSeams, measureTake, muxFilm, openPath, outlineState, pageMaterialNote, partFilesLine, partsLine, patchFilm, planTargets, precheckPlan, prepareViewer, probeDurationS, profileDir, reRenderInPlace, readNotes, readPageMaterial, renderAbReel, renderBeforeAfter, renderComposition, renderCompositionFile, renderDefectBlock, renderDraft, renderFilm, renderFrames, renderLaunchFile, renderReview, renderTeaserGif, requireTakeFiles, resolveChrome, resolveNavigateUrl, resolveTakePaths, resultFrames, revealPath, runAgent, runPostShootGates, runShoot, settleDefects, shootHome, shootStatesLine, shootSteadyLine, skippedDefects, stagePrev, startApp, startEditServer, takeFile, toDraft, validateComposition, viewerCommand, viewerRounds, waitForHttp, waitForNotes };
3443
6714
  //# sourceMappingURL=index.js.map