@open-take/runtime 0.2.6 → 0.2.8

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.
@@ -1,12 +1,12 @@
1
1
  import { homedir, tmpdir } from "node:os";
2
- import { dirname, join, resolve } from "node:path";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
3
  import { resolveFfmpeg, resolveFfprobe } from "@open-take/compositor";
4
4
  import { spawn } from "node:child_process";
5
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
5
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, statSync, writeFileSync } from "node:fs";
6
6
  import { createRequire } from "node:module";
7
7
 
8
8
  //#region src/cdp.ts
9
- const sleep$2 = (ms) => new Promise((r) => setTimeout(r, ms));
9
+ const sleep$3 = (ms) => new Promise((r) => setTimeout(r, ms));
10
10
  const require = createRequire(import.meta.url);
11
11
  const CHROME_CACHE = join(homedir(), ".open-take", "browsers");
12
12
  const BUILDID_FILE = join(homedir(), ".open-take", "chrome-build.json");
@@ -122,14 +122,26 @@ var CDP = class CDP {
122
122
  /** Launch headless Chrome, return a CDP session bound to its page target. */
123
123
  async function launchBrowser(opts) {
124
124
  const chrome = await ensureChrome(opts.chromePath);
125
- const userDir = mkdtempSync(join(tmpdir(), "open-take-cdp-"));
125
+ const ephemeral = !opts.userDataDir;
126
+ if (opts.userDataDir) mkdirSync(opts.userDataDir, { recursive: true });
127
+ const userDir = opts.userDataDir ?? mkdtempSync(join(tmpdir(), "open-take-cdp-"));
128
+ if (!ephemeral) rmSync(join(userDir, "DevToolsActivePort"), { force: true });
129
+ if (!ephemeral) {
130
+ const holder = singletonHolderPid(userDir);
131
+ if (holder != null && pidAlive(holder)) throw new Error(`profile in use: a Chrome (pid ${holder}) is already running on ${userDir} — quit it first (e.g. the \`open-take auth\` window)`);
132
+ for (const f of [
133
+ "SingletonLock",
134
+ "SingletonCookie",
135
+ "SingletonSocket"
136
+ ]) rmSync(join(userDir, f), { force: true });
137
+ }
126
138
  const dsf = opts.deviceScaleFactor ?? 1;
127
139
  const proc = spawn(chrome, [
128
140
  "--remote-debugging-port=0",
129
141
  `--user-data-dir=${userDir}`,
130
142
  `--window-size=${opts.width},${opts.height}`,
131
143
  ...dsf !== 1 ? [`--force-device-scale-factor=${dsf}`] : [],
132
- "--headless=new",
144
+ ...opts.headless === false ? [] : ["--headless=new"],
133
145
  "--no-sandbox",
134
146
  "--password-store=basic",
135
147
  "--use-mock-keychain",
@@ -151,16 +163,22 @@ async function launchBrowser(opts) {
151
163
  stderr += d;
152
164
  });
153
165
  const close = async () => {
154
- const exited = new Promise((res) => {
155
- if (proc.exitCode != null) return res();
156
- proc.once("exit", () => res());
157
- setTimeout(res, 2e3);
166
+ const exitWithin = (ms) => new Promise((res) => {
167
+ if (proc.exitCode != null) return res(true);
168
+ const tm = setTimeout(() => res(false), ms);
169
+ proc.once("exit", () => {
170
+ clearTimeout(tm);
171
+ res(true);
172
+ });
158
173
  });
159
174
  try {
160
- proc.kill("SIGKILL");
175
+ if (!ephemeral) {
176
+ proc.kill("SIGTERM");
177
+ if (!await exitWithin(4e3)) proc.kill("SIGKILL");
178
+ } else proc.kill("SIGKILL");
161
179
  } catch {}
162
- await exited;
163
- rmSync(userDir, {
180
+ await exitWithin(2e3);
181
+ if (ephemeral) rmSync(userDir, {
164
182
  recursive: true,
165
183
  force: true,
166
184
  maxRetries: 5,
@@ -181,6 +199,23 @@ async function launchBrowser(opts) {
181
199
  throw new Error(`open-take(hi-fps): browser launch failed: ${e.message}\n${stderr.slice(-600)}`);
182
200
  }
183
201
  }
202
+ function singletonHolderPid(userDir) {
203
+ try {
204
+ const target = readlinkSync(join(userDir, "SingletonLock"));
205
+ const pid = Number(target.split("-").pop());
206
+ return Number.isFinite(pid) && pid > 0 ? pid : null;
207
+ } catch {
208
+ return null;
209
+ }
210
+ }
211
+ function pidAlive(pid) {
212
+ try {
213
+ process.kill(pid, 0);
214
+ return true;
215
+ } catch {
216
+ return false;
217
+ }
218
+ }
184
219
  async function readDevtoolsPort(userDir, proc) {
185
220
  const file = join(userDir, "DevToolsActivePort");
186
221
  for (let i = 0; i < 100; i++) {
@@ -190,7 +225,7 @@ async function readDevtoolsPort(userDir, proc) {
190
225
  const port = Number(line);
191
226
  if (Number.isFinite(port) && port > 0) return port;
192
227
  }
193
- await sleep$2(50);
228
+ await sleep$3(50);
194
229
  }
195
230
  throw new Error("timed out waiting for DevToolsActivePort");
196
231
  }
@@ -204,7 +239,7 @@ async function pageTargetWs(port) {
204
239
  id: page.id
205
240
  };
206
241
  } catch {}
207
- await sleep$2(100);
242
+ await sleep$3(100);
208
243
  }
209
244
  throw new Error("no page target appeared");
210
245
  }
@@ -239,7 +274,7 @@ async function fitViewport(cdp, targetId, vw, vh) {
239
274
  height
240
275
  }
241
276
  });
242
- await sleep$2(120);
277
+ await sleep$3(120);
243
278
  inner = await readInner();
244
279
  }
245
280
  return inner;
@@ -356,7 +391,7 @@ const makeFrameDir = () => mkdtempSync(join(tmpdir(), "open-take-frames-"));
356
391
 
357
392
  //#endregion
358
393
  //#region src/capture.ts
359
- const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
394
+ const sleep$2 = (ms) => new Promise((r) => setTimeout(r, ms));
360
395
  function findBox(o) {
361
396
  if (!o || typeof o !== "object") return null;
362
397
  const r = o;
@@ -428,6 +463,15 @@ function boxByTextJs(text) {
428
463
  const t = JSON.stringify(text);
429
464
  return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('button,a,[role=button],[role=link],[role=menuitem],[aria-label],[title],img[alt],li,[draggable=true]'));function name(e){return (e.getAttribute('aria-label')||e.getAttribute('title')||e.getAttribute('alt')||e.textContent||'').replace(/\\s+/g,' ').trim();}var m=els.filter(function(e){return name(e)===t;})[0]||els.filter(function(e){return name(e).indexOf(t)!==-1;})[0];if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});r=m.getBoundingClientRect();}return JSON.stringify({x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)});})()`;
430
465
  }
466
+ const CLOSEST_ANCHOR_JS = "var a=m.closest('a[href]')||m.querySelector('a[href]');if(!a||!a.href)return 'NOTFOUND';return a.href;";
467
+ function hrefSelectorJs(selector) {
468
+ const s = JSON.stringify(selector);
469
+ return `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';${CLOSEST_ANCHOR_JS}})()`;
470
+ }
471
+ function hrefByTextJs(text) {
472
+ const t = JSON.stringify(text);
473
+ return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('a,button,[role=link],[role=button],[aria-label],[title]'));function name(e){return (e.getAttribute('aria-label')||e.getAttribute('title')||e.textContent||'').replace(/\\s+/g,' ').trim();}var m=els.filter(function(e){return name(e)===t;})[0]||els.filter(function(e){return name(e).indexOf(t)!==-1;})[0];if(!m)return 'NOTFOUND';${CLOSEST_ANCHOR_JS}})()`;
474
+ }
431
475
  function scrollDeltaSelectorJs(selector) {
432
476
  const s = JSON.stringify(selector);
433
477
  return `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();return JSON.stringify({dy:Math.round(r.top+r.height/2-window.innerHeight/2)});})()`;
@@ -502,7 +546,7 @@ async function ffprobe(path) {
502
546
  }
503
547
  /** Drive `plan` against the live app over CDP, return the ground-truth log. */
504
548
  async function captureTake(plan, opts) {
505
- const { captureTakeCDP: captureTakeCDP$1 } = await import("./cdp-capture-eKyYWSuf.js");
549
+ const { captureTakeCDP: captureTakeCDP$1 } = await import("./cdp-capture-nGRiRSVD.js");
506
550
  return captureTakeCDP$1(plan, {
507
551
  ...opts,
508
552
  fps: opts.fps ?? 60
@@ -520,7 +564,9 @@ async function inspectPage(url, opts = {}) {
520
564
  const browser = await launchBrowser({
521
565
  width: vw,
522
566
  height: vh,
523
- chromePath: opts.chromePath
567
+ chromePath: opts.chromePath,
568
+ ...opts.userDataDir ? { userDataDir: opts.userDataDir } : {},
569
+ ...opts.headless === false ? { headless: false } : {}
524
570
  });
525
571
  try {
526
572
  const { cdp } = browser;
@@ -528,7 +574,7 @@ async function inspectPage(url, opts = {}) {
528
574
  await cdp.send("Runtime.enable");
529
575
  const inner = await fitViewport(cdp, browser.targetId, vw, vh);
530
576
  await cdp.send("Page.navigate", { url });
531
- await sleep$1(opts.warmupMs ?? 1500);
577
+ await sleep$2(opts.warmupMs ?? 1500);
532
578
  const evalRaw = async (expr) => {
533
579
  const r = await cdp.send("Runtime.evaluate", {
534
580
  expression: expr,
@@ -558,9 +604,294 @@ async function inspectPage(url, opts = {}) {
558
604
  }
559
605
  }
560
606
 
607
+ //#endregion
608
+ //#region src/nav.ts
609
+ /**
610
+ * Resolve a navigate step to one absolute URL, or null when it cannot be.
611
+ *
612
+ * Precedence is `href` > `url` > `current`: a destination READ FROM THE PAGE
613
+ * beats one written in the plan, because it is the one that reflects what the
614
+ * app just did. `current` last means `{ query }` on its own is "reload this
615
+ * same page with these params" rather than an error.
616
+ */
617
+ function resolveNavigateUrl(t) {
618
+ const base = safeUrl(t.current);
619
+ const raw = t.href || t.url || t.current;
620
+ if (!raw) return null;
621
+ const dest = safeUrl(raw, base);
622
+ if (!dest) return null;
623
+ for (const [k, v] of Object.entries(t.query ?? {})) dest.searchParams.set(k, v);
624
+ return dest.toString();
625
+ }
626
+ function safeUrl(raw, base) {
627
+ try {
628
+ return new URL(raw, base);
629
+ } catch {
630
+ return void 0;
631
+ }
632
+ }
633
+
634
+ //#endregion
635
+ //#region src/settle.ts
636
+ const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
637
+ /** Extra time a hold may spend waiting for a busy page, per beat. Generous
638
+ * enough for a slow round-trip, short enough that a page which NEVER goes
639
+ * quiet (a live clock, a polling dashboard) costs a bounded, reported amount
640
+ * rather than stretching the take without explanation. */
641
+ const DEFAULT_SETTLE_BUDGET_MS = 1200;
642
+ /** The page must have been still this long to count as settled — one paint
643
+ * plus slack, so a mutation and the layout it triggers aren't read as two
644
+ * separate quiet periods. */
645
+ const QUIET_MS = 120;
646
+ const POLL_MS = 60;
647
+ /** A pending setTimeout longer than this is the page's own heartbeat (a poll
648
+ * loop, a session timer), not this beat finishing. Counting it would make the
649
+ * page look permanently busy. */
650
+ const TIMER_MAX_MS = 2e3;
651
+ /** Grace on a timer's own deadline before it stops counting as pending. Errs
652
+ * SHORT on purpose: expiring early costs the old behaviour (a beat that may
653
+ * be captured a touch soon), expiring late costs dead air in the cut on
654
+ * every remaining beat — a much worse trade. */
655
+ const TIMER_SLACK_MS = 250;
656
+ /** A <canvas>/<video> covering this much of the frame makes the probe
657
+ * effectively blind for that beat: the element never changes size, position
658
+ * or attributes no matter what is painted inside it, so "the page is done"
659
+ * is unanswerable. Set low on purpose — a needless note costs a line of
660
+ * output, a missed one costs an author trusting a quiet run that proved
661
+ * nothing. */
662
+ const PAINT_BLIND_FRAC = .2;
663
+ /** Installed once per document; keeps `t` at the last moment anything moved. */
664
+ const PROBE_INSTALL_JS = `(() => {
665
+ if (window.__openTakeActivity) return;
666
+ const TIMER_MAX = ${TIMER_MAX_MS}, TIMER_SLACK = ${TIMER_SLACK_MS};
667
+ const A = { t: 0, net: 0, timers: 0 };
668
+ const touch = () => { A.t = performance.now(); };
669
+ touch();
670
+ try {
671
+ new MutationObserver(touch).observe(document, {
672
+ subtree: true, childList: true, attributes: true, characterData: true,
673
+ });
674
+ } catch (e) {}
675
+ try {
676
+ const of = window.fetch;
677
+ if (typeof of === "function")
678
+ window.fetch = function () {
679
+ A.net++; touch();
680
+ let p;
681
+ try { p = of.apply(window, arguments); } catch (e) { A.net--; throw e; }
682
+ return Promise.resolve(p).then(
683
+ (r) => { A.net--; touch(); return r; },
684
+ (e) => { A.net--; touch(); throw e; },
685
+ );
686
+ };
687
+ } catch (e) {}
688
+ try {
689
+ const os = XMLHttpRequest.prototype.send;
690
+ if (typeof os === "function")
691
+ XMLHttpRequest.prototype.send = function () {
692
+ A.net++; touch();
693
+ // send() throws on API misuse (send before open, send after abort) and
694
+ // then NO request exists, so loadend never fires — without this the
695
+ // increment is permanent and the page reads busy for the rest of the
696
+ // take. Same guard the fetch branch above already has.
697
+ try { this.addEventListener("loadend", () => { A.net--; touch(); }); } catch (e) {}
698
+ try { return os.apply(this, arguments); } catch (e) { A.net--; touch(); throw e; }
699
+ };
700
+ } catch (e) {}
701
+ try {
702
+ const st = window.setTimeout, ct = window.clearTimeout, ci = window.clearInterval;
703
+ // id -> the moment it must have fired by. Counting by DEADLINE rather than
704
+ // by cancellation bookkeeping is what makes this safe: a timer we never see
705
+ // cancelled (clearInterval on a setTimeout id, an id coerced through a
706
+ // dataset attribute, any API we did not wrap) simply expires and stops
707
+ // counting. Chasing every cancellation path would leave one uncounted, and
708
+ // ONE stuck entry means every remaining beat of the take waits the whole
709
+ // budget for nothing.
710
+ const live = new Map();
711
+ const forget = function (id) { live.delete(Number(id)); };
712
+ A.pending = function () {
713
+ const now = performance.now();
714
+ live.forEach(function (due, id) { if (due <= now) live.delete(id); });
715
+ A.timers = live.size;
716
+ return live.size;
717
+ };
718
+ window.setTimeout = function (fn, delay) {
719
+ const d = Number(delay) || 0;
720
+ // a string body keeps the original semantics (wrapping would stop the
721
+ // code ever running), and a long delay is a heartbeat, not this beat
722
+ if (typeof fn !== "function" || d > TIMER_MAX) return st.apply(window, arguments);
723
+ const rest = Array.prototype.slice.call(arguments, 2);
724
+ let id;
725
+ const wrapped = function () {
726
+ forget(id); touch();
727
+ return fn.apply(this, arguments);
728
+ };
729
+ id = st.apply(window, [wrapped, d].concat(rest));
730
+ live.set(Number(id), performance.now() + d + TIMER_SLACK);
731
+ touch();
732
+ return id;
733
+ };
734
+ // Both cancellers, and both coerce their argument the way the platform
735
+ // does — clearInterval legally cancels a setTimeout (one timer map), and
736
+ // clearTimeout(String(id)) is what you get back out of a dataset.
737
+ window.clearTimeout = function (id) { forget(id); return ct.apply(window, arguments); };
738
+ window.clearInterval = function (id) { forget(id); return ci.apply(window, arguments); };
739
+ } catch (e) {}
740
+ window.__openTakeActivity = A;
741
+ })()`;
742
+ /** Reads the probe. Returns a JSON string so one Runtime.evaluate round-trip
743
+ * carries the whole answer (returnByValue on a plain object also works, but
744
+ * the rest of this package already speaks the JSON-string convention). */
745
+ const PROBE_READ_JS = `(() => {
746
+ const A = window.__openTakeActivity;
747
+ if (!A) return JSON.stringify({ ok: false });
748
+ let anims = 0;
749
+ try {
750
+ for (const a of document.getAnimations()) {
751
+ if (a.playState !== "running") continue;
752
+ let it = 1;
753
+ try { it = a.effect.getTiming().iterations; } catch (e) {}
754
+ if (it === Infinity) continue; // ambient — never settles, never counted
755
+ anims++;
756
+ }
757
+ } catch (e) {}
758
+ // The largest <canvas>/<video> as a fraction of the viewport, clipped to it
759
+ // (an offscreen or scrolled-away surface is not what the viewer is watching).
760
+ let paint = 0;
761
+ try {
762
+ const area = innerWidth * innerHeight;
763
+ if (area > 0)
764
+ for (const el of document.querySelectorAll("canvas,video")) {
765
+ const r = el.getBoundingClientRect();
766
+ const w = Math.max(0, Math.min(r.right, innerWidth) - Math.max(r.left, 0));
767
+ const h = Math.max(0, Math.min(r.bottom, innerHeight) - Math.max(r.top, 0));
768
+ if (w * h > paint * area) paint = (w * h) / area;
769
+ }
770
+ } catch (e) {}
771
+ const timers = typeof A.pending === "function" ? A.pending() : (A.timers | 0);
772
+ const busy = A.net > 0 || timers > 0 || anims > 0 || document.readyState !== "complete";
773
+ return JSON.stringify({
774
+ ok: true,
775
+ quietMs: busy ? 0 : Math.max(0, performance.now() - A.t),
776
+ net: A.net,
777
+ timers,
778
+ anims,
779
+ paint,
780
+ });
781
+ })()`;
782
+ /** Install the activity probe for the current document AND every future one
783
+ * (a plan may navigate mid-take). Never throws — a capture must not fail
784
+ * because a diagnostic could not be attached. */
785
+ async function installActivityProbe(cdp) {
786
+ await cdp.send("Page.addScriptToEvaluateOnNewDocument", { source: PROBE_INSTALL_JS }).catch(() => {});
787
+ await cdp.send("Runtime.evaluate", { expression: PROBE_INSTALL_JS }).catch(() => {});
788
+ }
789
+ async function readProbe(cdp) {
790
+ try {
791
+ const r = await cdp.send("Runtime.evaluate", {
792
+ expression: PROBE_READ_JS,
793
+ returnByValue: true
794
+ });
795
+ const v = r.result?.value;
796
+ if (typeof v !== "string") return null;
797
+ const p = JSON.parse(v);
798
+ if (!p.ok) return null;
799
+ return {
800
+ quietMs: p.quietMs ?? 0,
801
+ net: p.net ?? 0,
802
+ timers: p.timers ?? 0,
803
+ anims: p.anims ?? 0,
804
+ paint: p.paint ?? 0
805
+ };
806
+ } catch {
807
+ return null;
808
+ }
809
+ }
810
+ /**
811
+ * Hold for `heldMs` (the editorial beat — always run in full), then keep
812
+ * waiting while the page is still working, up to `budgetMs`.
813
+ *
814
+ * `budgetMs <= 0` reduces this to the old fixed sleep exactly — the escape
815
+ * hatch for a page that never goes quiet (`CaptureOpts.settleBudgetMs: 0`),
816
+ * and what the unit tests use to pin the legacy timing.
817
+ */
818
+ async function settle(cdp, heldMs, opts = {}) {
819
+ const budget = opts.budgetMs ?? DEFAULT_SETTLE_BUDGET_MS;
820
+ await sleep$1(Math.max(0, heldMs));
821
+ if (!(budget > 0)) return {
822
+ heldMs,
823
+ waitedMs: 0,
824
+ reason: "budget",
825
+ paintFrac: 0
826
+ };
827
+ const t0 = Date.now();
828
+ let paintFrac = 0;
829
+ for (;;) {
830
+ const p = await readProbe(cdp);
831
+ const waitedMs = Date.now() - t0;
832
+ if (!p) return {
833
+ heldMs,
834
+ waitedMs,
835
+ reason: "unavailable",
836
+ paintFrac
837
+ };
838
+ paintFrac = Math.max(paintFrac, p.paint);
839
+ if (p.quietMs >= QUIET_MS) return {
840
+ heldMs,
841
+ waitedMs,
842
+ reason: "idle",
843
+ paintFrac
844
+ };
845
+ if (waitedMs >= budget) return {
846
+ heldMs,
847
+ waitedMs,
848
+ reason: "budget",
849
+ paintFrac
850
+ };
851
+ await sleep$1(POLL_MS);
852
+ }
853
+ }
854
+ /** How many beats in a row may spend the WHOLE budget without the page ever
855
+ * settling before the waiting is written off. */
856
+ const SETTLE_GIVE_UP_STREAK = 2;
857
+ /**
858
+ * Budget policy across one take. Some pages never go quiet — a one-second
859
+ * clock, a poll loop, a streaming widget — and no DOM signal can tell that
860
+ * apart from real work. So do not try: once a run of beats has each spent the
861
+ * entire budget with no result, the waiting is provably not helping, and
862
+ * paying it on every remaining beat would add more dead air than the whole
863
+ * demo is long. Give up once, loudly, and let the author set settleMs by eye.
864
+ */
865
+ function makeBudgetGovernor(budgetMs, giveUpStreak = SETTLE_GIVE_UP_STREAK) {
866
+ let budget = budgetMs;
867
+ let streak = 0;
868
+ return {
869
+ get budgetMs() {
870
+ return budget;
871
+ },
872
+ get gaveUp() {
873
+ return budget <= 0 && budgetMs > 0;
874
+ },
875
+ record(reason) {
876
+ if (reason === "idle") {
877
+ streak = 0;
878
+ return false;
879
+ }
880
+ if (reason !== "budget" || budget <= 0) return false;
881
+ if (++streak < giveUpStreak) return false;
882
+ budget = 0;
883
+ return true;
884
+ }
885
+ };
886
+ }
887
+
561
888
  //#endregion
562
889
  //#region src/cdp-capture.ts
563
890
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
891
+ /** Report a settle wait only past this — a couple of polls is the probe
892
+ * confirming quiet, not the page being slow, and a log full of 60ms notes
893
+ * would bury the beat that actually needed a second. */
894
+ const SETTLE_NOTE_MS = 150;
564
895
  const smoother = (u) => {
565
896
  const clamped = Math.max(0, Math.min(1, u));
566
897
  return clamped * clamped * clamped * (clamped * (clamped * 6 - 15) + 10);
@@ -585,6 +916,22 @@ async function evalAny(cdp, js) {
585
916
  if (v == null || v === "NOTFOUND") return null;
586
917
  return evalValue(typeof v === "string" ? v : JSON.stringify(v));
587
918
  }
919
+ async function evalString(cdp, js) {
920
+ const r = await cdp.send("Runtime.evaluate", {
921
+ expression: js,
922
+ returnByValue: true,
923
+ awaitPromise: true
924
+ });
925
+ const v = r.result?.value;
926
+ return typeof v === "string" && v !== "NOTFOUND" && v !== "" ? v : null;
927
+ }
928
+ async function awaitFonts(cdp) {
929
+ await Promise.race([cdp.send("Runtime.evaluate", {
930
+ expression: "document.fonts.ready.then(() => true)",
931
+ awaitPromise: true,
932
+ returnByValue: true
933
+ }).catch(() => {}), sleep(3e3)]);
934
+ }
588
935
  const center = (b) => ({
589
936
  x: Math.round(b.x + b.w / 2),
590
937
  y: Math.round(b.y + b.h / 2)
@@ -798,18 +1145,18 @@ async function captureTakeCDP(plan, opts) {
798
1145
  width: vw,
799
1146
  height: vh,
800
1147
  chromePath: opts.chromePath,
801
- deviceScaleFactor: scale
1148
+ deviceScaleFactor: scale,
1149
+ ...opts.userDataDir ? { userDataDir: opts.userDataDir } : {},
1150
+ ...opts.headless === false ? { headless: false } : {}
802
1151
  });
803
1152
  const { cdp } = browser;
804
1153
  await cdp.send("Page.enable");
805
1154
  await cdp.send("Runtime.enable");
806
1155
  const inner = await fitViewport(cdp, browser.targetId, vw, vh);
1156
+ await installActivityProbe(cdp);
807
1157
  await navigate(cdp, plan.url);
808
- await Promise.race([cdp.send("Runtime.evaluate", {
809
- expression: "document.fonts.ready.then(() => true)",
810
- awaitPromise: true,
811
- returnByValue: true
812
- }).catch(() => {}), sleep(3e3)]);
1158
+ await installActivityProbe(cdp);
1159
+ await awaitFonts(cdp);
813
1160
  const screencast = new Screencast(cdp, frameDir);
814
1161
  const t0 = Date.now();
815
1162
  await screencast.start(t0, {
@@ -846,6 +1193,10 @@ async function captureTakeCDP(plan, opts) {
846
1193
  };
847
1194
  const events = [];
848
1195
  const skipped = [];
1196
+ const settleWaits = [];
1197
+ const governor = makeBudgetGovernor(opts.settleBudgetMs ?? DEFAULT_SETTLE_BUDGET_MS);
1198
+ let paintedFrac = 0;
1199
+ let paintNoted = false;
849
1200
  for (let stepIdx = 0; stepIdx < plan.steps.length; stepIdx++) {
850
1201
  const step = plan.steps[stepIdx];
851
1202
  const skip = (action, target, reason) => {
@@ -857,17 +1208,68 @@ async function captureTakeCDP(plan, opts) {
857
1208
  });
858
1209
  console.error(`captureTakeCDP: ${action} ${reason}, skipped: ${JSON.stringify(target)}`);
859
1210
  };
1211
+ const hold = async (defaultMs) => {
1212
+ const heldMs = ("settleMs" in step ? step.settleMs : void 0) ?? defaultMs;
1213
+ const r = await settle(cdp, heldMs, { budgetMs: governor.budgetMs });
1214
+ paintedFrac = Math.max(paintedFrac, r.paintFrac);
1215
+ if (paintedFrac >= PAINT_BLIND_FRAC && !paintNoted) {
1216
+ paintNoted = true;
1217
+ console.error(`captureTakeCDP: a <canvas>/<video> covers ~${Math.round(paintedFrac * 100)}% of the frame — the settle probe reads page STRUCTURE and cannot see what is painted inside one, so on beats whose payoff is drawn there, settleMs is doing the whole job. Set those by eye and check \`frames\`.`);
1218
+ }
1219
+ if (governor.record(r.reason)) console.error("captureTakeCDP: this page never goes quiet (consecutive beats spent the whole settle budget) — settle waiting is OFF for the rest of the take; set each beat's settleMs explicitly instead");
1220
+ if (r.waitedMs < SETTLE_NOTE_MS) return;
1221
+ const waitedMs = Math.round(r.waitedMs);
1222
+ settleWaits.push({
1223
+ step: stepIdx,
1224
+ action: step.action,
1225
+ heldMs,
1226
+ waitedMs,
1227
+ reason: r.reason
1228
+ });
1229
+ console.error(`captureTakeCDP: step ${stepIdx} (${step.action}) held ${heldMs}ms, then waited ${waitedMs}ms more for the page to settle (${r.reason})`);
1230
+ };
860
1231
  if (step.action === "wait") {
861
1232
  await sleep(step.ms);
862
1233
  continue;
863
1234
  }
1235
+ if (step.action === "navigate") {
1236
+ const spec = step.hrefFrom;
1237
+ let href = null;
1238
+ if (spec) {
1239
+ const target = spec.text ?? spec.selector;
1240
+ if (!target) {
1241
+ skip("navigate", void 0, "hrefFrom has neither `selector` nor `text`");
1242
+ continue;
1243
+ }
1244
+ href = spec.selector ? await evalString(cdp, hrefSelectorJs(spec.selector)) : await evalString(cdp, hrefByTextJs(spec.text));
1245
+ if (!href) {
1246
+ skip("navigate", target, "no link with an href found");
1247
+ continue;
1248
+ }
1249
+ }
1250
+ const current = await evalString(cdp, "location.href") ?? plan.url;
1251
+ const dest = resolveNavigateUrl({
1252
+ current,
1253
+ url: step.url,
1254
+ href,
1255
+ query: step.query
1256
+ });
1257
+ if (!dest) {
1258
+ skip("navigate", step.url ?? href ?? current, "destination is not a resolvable URL");
1259
+ continue;
1260
+ }
1261
+ await navigate(cdp, dest);
1262
+ await awaitFonts(cdp);
1263
+ await hold(1200);
1264
+ continue;
1265
+ }
864
1266
  if (step.action === "type") {
865
1267
  const label$1 = step.text ?? step.selector;
866
1268
  const tMs$1 = Date.now() - t0;
867
1269
  const box$1 = step.text ? await evalBox(cdp, focusFieldByTextJs(step.text)) : step.selector ? await evalBox(cdp, focusSelectorJs(step.selector)) : null;
868
1270
  if (!box$1) {
869
1271
  skip("type", label$1, "target not found");
870
- await sleep(step.settleMs ?? 600);
1272
+ await hold(600);
871
1273
  continue;
872
1274
  }
873
1275
  if (step.clear) await evalAny(cdp, selectAllInFocusedJs());
@@ -891,7 +1293,7 @@ async function captureTakeCDP(plan, opts) {
891
1293
  durationMs: Date.now() - tType,
892
1294
  ...step.zoom ? { zoom: step.zoom } : {}
893
1295
  });
894
- await sleep(step.settleMs ?? 900);
1296
+ await hold(900);
895
1297
  continue;
896
1298
  }
897
1299
  if (step.action === "drag") {
@@ -912,7 +1314,7 @@ async function captureTakeCDP(plan, opts) {
912
1314
  const label$1 = step.note ?? step.text ?? step.selector;
913
1315
  if (!from || !to) {
914
1316
  skip("drag", label$1, "endpoint not found");
915
- await sleep(step.settleMs ?? 600);
1317
+ await hold(600);
916
1318
  continue;
917
1319
  }
918
1320
  const path = pathPts.length ? pathPts : [from, to];
@@ -951,7 +1353,115 @@ async function captureTakeCDP(plan, opts) {
951
1353
  ease: dragEase,
952
1354
  ...step.zoom ? { zoom: step.zoom } : {}
953
1355
  });
954
- await sleep(step.settleMs ?? 1100);
1356
+ await hold(1100);
1357
+ continue;
1358
+ }
1359
+ if (step.action === "dropFiles") {
1360
+ const label$1 = step.note ?? step.paths.map((p) => basename(p)).join(", ");
1361
+ if (!step.paths.length) {
1362
+ skip("dropFiles", label$1, "no files given (empty paths)");
1363
+ await hold(600);
1364
+ continue;
1365
+ }
1366
+ const absPaths = step.paths.map((p) => resolve(p));
1367
+ const missing = absPaths.filter((p) => !existsSync(p));
1368
+ if (missing.length) {
1369
+ skip("dropFiles", label$1, `file not found: ${missing.join(", ")}`);
1370
+ await hold(600);
1371
+ continue;
1372
+ }
1373
+ const files = absPaths.map((p) => {
1374
+ const st = statSync(p);
1375
+ return {
1376
+ name: basename(p),
1377
+ size: st.size
1378
+ };
1379
+ });
1380
+ let to;
1381
+ if (step.to || step.toSelector || step.toText) {
1382
+ const found = await resolvePoint({
1383
+ point: step.to,
1384
+ selector: step.toSelector,
1385
+ text: step.toText
1386
+ });
1387
+ if (!found) {
1388
+ skip("dropFiles", label$1, "drop target not found");
1389
+ await hold(600);
1390
+ continue;
1391
+ }
1392
+ to = found;
1393
+ } else to = {
1394
+ x: Math.round(inner[0] / 2),
1395
+ y: Math.round(inner[1] / 2)
1396
+ };
1397
+ const from = step.from ? {
1398
+ x: Math.round(step.from.x),
1399
+ y: Math.round(step.from.y)
1400
+ } : {
1401
+ x: inner[0] - 28,
1402
+ y: Math.round(inner[1] * .18)
1403
+ };
1404
+ const pathPts = (step.path ?? []).map((p) => ({
1405
+ x: Math.round(p.x),
1406
+ y: Math.round(p.y)
1407
+ }));
1408
+ const path = pathPts.length ? pathPts : [from, to];
1409
+ const target = step.durationMs ?? 1400;
1410
+ const dragEase = opts.dragEasing ?? "smooth";
1411
+ const easeParam = dragEase === "smooth" ? smoother : (u) => u;
1412
+ const data = {
1413
+ items: [],
1414
+ files: absPaths,
1415
+ dragOperationsMask: 1
1416
+ };
1417
+ const dragEvt = (type, p) => cdp.send("Input.dispatchDragEvent", {
1418
+ type,
1419
+ x: Math.round(p.x),
1420
+ y: Math.round(p.y),
1421
+ data
1422
+ });
1423
+ const n = Math.max(12, Math.round(target / 16));
1424
+ const tMs$1 = Date.now() - t0;
1425
+ pumpPaused = true;
1426
+ await sleep(160);
1427
+ const tCarry = Date.now();
1428
+ const last = path[path.length - 1];
1429
+ let carriedMs;
1430
+ try {
1431
+ await dragEvt("dragEnter", path[0]);
1432
+ for (let k = 1; k <= n; k++) {
1433
+ const p = sampleAlong(path, easeParam(k / n));
1434
+ dragEvt("dragOver", p).catch(() => {});
1435
+ const due = tCarry + target * k / n;
1436
+ const slack = due - Date.now();
1437
+ if (slack > 0) await sleep(slack);
1438
+ }
1439
+ await dragEvt("dragOver", last).catch(() => {});
1440
+ await dragEvt("drop", last);
1441
+ carriedMs = Date.now() - tCarry;
1442
+ } catch (e) {
1443
+ pumpPaused = false;
1444
+ skip("dropFiles", label$1, `drag dispatch failed: ${e.message}`);
1445
+ await hold(600);
1446
+ continue;
1447
+ }
1448
+ await sleep(120);
1449
+ pumpPaused = false;
1450
+ events.push({
1451
+ kind: "dropFiles",
1452
+ x: path[0].x,
1453
+ y: path[0].y,
1454
+ to: last,
1455
+ path,
1456
+ tMs: tMs$1,
1457
+ sel: label$1,
1458
+ note: step.note,
1459
+ durationMs: carriedMs,
1460
+ ease: dragEase,
1461
+ files,
1462
+ ...step.zoom ? { zoom: step.zoom } : {}
1463
+ });
1464
+ await hold(1600);
955
1465
  continue;
956
1466
  }
957
1467
  if (step.action === "scroll") {
@@ -962,7 +1472,7 @@ async function captureTakeCDP(plan, opts) {
962
1472
  if (r && typeof r.dy === "number") dy = r.dy;
963
1473
  else {
964
1474
  skip("scroll", step.toText ?? step.toSelector, "target not found");
965
- await sleep(step.settleMs ?? 600);
1475
+ await hold(600);
966
1476
  continue;
967
1477
  }
968
1478
  } else dy = step.dy ?? Math.round(vh * .8);
@@ -988,7 +1498,7 @@ async function captureTakeCDP(plan, opts) {
988
1498
  durationMs: Date.now() - tScroll,
989
1499
  note: step.note
990
1500
  });
991
- await sleep(step.settleMs ?? 800);
1501
+ await hold(800);
992
1502
  continue;
993
1503
  }
994
1504
  if (step.action === "hover") {
@@ -997,7 +1507,7 @@ async function captureTakeCDP(plan, opts) {
997
1507
  const box$1 = step.text ? await evalBox(cdp, boxByTextJs(step.text)) : step.selector ? await evalBox(cdp, boxSelectorJs(step.selector)) : null;
998
1508
  if (!box$1) {
999
1509
  skip("hover", label$1, "target not found");
1000
- await sleep(step.settleMs ?? 600);
1510
+ await hold(600);
1001
1511
  continue;
1002
1512
  }
1003
1513
  const c = center(box$1);
@@ -1014,7 +1524,7 @@ async function captureTakeCDP(plan, opts) {
1014
1524
  ...step.zoom ? { zoom: step.zoom } : {}
1015
1525
  });
1016
1526
  await sleep(dwell);
1017
- await sleep(step.settleMs ?? 300);
1527
+ await hold(900);
1018
1528
  continue;
1019
1529
  }
1020
1530
  if (step.action === "press") {
@@ -1047,7 +1557,7 @@ async function captureTakeCDP(plan, opts) {
1047
1557
  ...step.zoom ? { zoom: step.zoom } : {}
1048
1558
  });
1049
1559
  await sleep(dwell);
1050
- await sleep(step.settleMs ?? 400);
1560
+ await hold(900);
1051
1561
  continue;
1052
1562
  }
1053
1563
  const label = step.text ?? step.selector;
@@ -1063,7 +1573,7 @@ async function captureTakeCDP(plan, opts) {
1063
1573
  ...step.zoom ? { zoom: step.zoom } : {}
1064
1574
  });
1065
1575
  else skip("click", label, "target not found");
1066
- await sleep(step.settleMs ?? 1300);
1576
+ await hold(1300);
1067
1577
  }
1068
1578
  const tEndMs = Date.now() - t0;
1069
1579
  await sleep(400);
@@ -1088,7 +1598,10 @@ async function captureTakeCDP(plan, opts) {
1088
1598
  y: Math.round(inner[1] * .9)
1089
1599
  },
1090
1600
  events,
1091
- tEndMs
1601
+ tEndMs,
1602
+ ...skipped.length ? { skipped } : {},
1603
+ ...settleWaits.length ? { settleWaits } : {},
1604
+ ...paintedFrac >= PAINT_BLIND_FRAC ? { paintedFrac: Math.round(paintedFrac * 100) / 100 } : {}
1092
1605
  };
1093
1606
  } finally {
1094
1607
  await browser?.close();
@@ -1110,5 +1623,5 @@ async function navigate(cdp, url) {
1110
1623
  }
1111
1624
 
1112
1625
  //#endregion
1113
- export { captureTake, captureTakeCDP, ensureChrome, inspectPage, resolveChrome };
1114
- //# sourceMappingURL=cdp-capture-DXTkPLLF.js.map
1626
+ export { captureTake, captureTakeCDP, ensureChrome, inspectPage, resolveChrome, resolveNavigateUrl };
1627
+ //# sourceMappingURL=cdp-capture-Coui4-Wt.js.map