@open-take/runtime 0.2.7 → 0.2.9

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;
@@ -401,9 +436,10 @@ function evalValue(raw) {
401
436
  }
402
437
  return deepParse(top);
403
438
  }
439
+ const NAME_JS = "function names(e){var raw=[e.getAttribute('aria-label'),e.textContent,e.getAttribute('title'),e.getAttribute('alt'),e.getAttribute('placeholder')];var out=[];for(var i=0;i<raw.length;i++){var s=(raw[i]||'').replace(/\\s+/g,' ').trim();if(s&&out.indexOf(s)===-1)out.push(s);}return out;}function dispName(e){var a=[e.getAttribute('aria-label'),e.textContent,e.getAttribute('title'),e.getAttribute('alt')];for(var i=0;i<a.length;i++){var s=(a[i]||'').replace(/\\s+/g,' ').trim();if(s)return s;}return '';}function pick(els,t){var i,n,j;for(i=0;i<els.length;i++){if(names(els[i]).indexOf(t)!==-1)return els[i];}for(i=0;i<els.length;i++){n=names(els[i]);for(j=0;j<n.length;j++){if(n[j].indexOf(t)!==-1)return els[i];}}return null;}";
404
440
  function clickByTextJs(text) {
405
441
  const t = JSON.stringify(text);
406
- return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('button,a,[role=button],[role=link],[role=menuitem],input[type=submit],input[type=button]'));function name(e){return (e.getAttribute('aria-label')||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();}var b={x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};m.click();return JSON.stringify(b);})()`;
442
+ return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('button,a,[role=button],[role=link],[role=menuitem],input[type=submit],input[type=button]'));` + NAME_JS + "var m=pick(els,t);if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});r=m.getBoundingClientRect();}var b={x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};m.click();return JSON.stringify(b);})()";
407
443
  }
408
444
  function clickBySelectorJs(selector) {
409
445
  const s = JSON.stringify(selector);
@@ -411,7 +447,7 @@ function clickBySelectorJs(selector) {
411
447
  }
412
448
  function focusFieldByTextJs(text) {
413
449
  const t = JSON.stringify(text);
414
- return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('input,textarea,[contenteditable],[contenteditable=true],[role=textbox],[role=searchbox]'));function name(e){return (e.getAttribute('aria-label')||e.getAttribute('placeholder')||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();}var b={x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};m.focus();m.click();m.focus();return JSON.stringify(b);})()`;
450
+ return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('input,textarea,[contenteditable],[contenteditable=true],[role=textbox],[role=searchbox]'));` + NAME_JS + "var m=pick(els,t);if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});r=m.getBoundingClientRect();}var b={x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};m.focus();m.click();m.focus();return JSON.stringify(b);})()";
415
451
  }
416
452
  function focusSelectorJs(selector) {
417
453
  const s = JSON.stringify(selector);
@@ -426,7 +462,16 @@ function boxSelectorJs(selector) {
426
462
  }
427
463
  function boxByTextJs(text) {
428
464
  const t = JSON.stringify(text);
429
- 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)});})()`;
465
+ 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]'));` + NAME_JS + "var m=pick(els,t);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)});})()";
466
+ }
467
+ const CLOSEST_ANCHOR_JS = "var a=m.closest('a[href]')||m.querySelector('a[href]');if(!a||!a.href)return 'NOTFOUND';return a.href;";
468
+ function hrefSelectorJs(selector) {
469
+ const s = JSON.stringify(selector);
470
+ return `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';${CLOSEST_ANCHOR_JS}})()`;
471
+ }
472
+ function hrefByTextJs(text) {
473
+ const t = JSON.stringify(text);
474
+ return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('a,button,[role=link],[role=button],[aria-label],[title]'));` + NAME_JS + `var m=pick(els,t);if(!m)return 'NOTFOUND';${CLOSEST_ANCHOR_JS}})()`;
430
475
  }
431
476
  function scrollDeltaSelectorJs(selector) {
432
477
  const s = JSON.stringify(selector);
@@ -434,7 +479,7 @@ function scrollDeltaSelectorJs(selector) {
434
479
  }
435
480
  function scrollDeltaByTextJs(text) {
436
481
  const t = JSON.stringify(text);
437
- return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('button,a,[role=button],[role=link],[role=heading],[aria-label],[title],h1,h2,h3,li,section,p'));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';var r=m.getBoundingClientRect();return JSON.stringify({dy:Math.round(r.top+r.height/2-window.innerHeight/2)});})()`;
482
+ return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('button,a,[role=button],[role=link],[role=heading],[aria-label],[title],h1,h2,h3,li,section,p'));` + NAME_JS + "var m=pick(els,t);if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();return JSON.stringify({dy:Math.round(r.top+r.height/2-window.innerHeight/2)});})()";
438
483
  }
439
484
  function sampleAlong(pts, u) {
440
485
  if (pts.length === 1) return pts[0];
@@ -502,14 +547,14 @@ async function ffprobe(path) {
502
547
  }
503
548
  /** Drive `plan` against the live app over CDP, return the ground-truth log. */
504
549
  async function captureTake(plan, opts) {
505
- const { captureTakeCDP: captureTakeCDP$1 } = await import("./cdp-capture-eKyYWSuf.js");
550
+ const { captureTakeCDP: captureTakeCDP$1 } = await import("./cdp-capture-Bg8hckzO.js");
506
551
  return captureTakeCDP$1(plan, {
507
552
  ...opts,
508
553
  fps: opts.fps ?? 60
509
554
  });
510
555
  }
511
556
  function listInteractiveJs() {
512
- return "(function(){function nm(e){return (e.getAttribute('aria-label')||e.textContent||'').replace(/\\s+/g,' ').trim();}var sel='button,a,[role=button],[role=link],[role=menuitem],[role=tab],[role=switch],[role=checkbox],input,select,textarea';var els=Array.prototype.slice.call(document.querySelectorAll(sel));var vw=window.innerWidth,vh=window.innerHeight;var out=[];var seen={};for(var i=0;i<els.length;i++){var e=els[i];var n=nm(e);var ph=e.getAttribute('placeholder');var r=e.getBoundingClientRect();if(r.width<6||r.height<6)continue;if(!n&&!ph)continue;var label=n||('['+(ph||e.tagName.toLowerCase())+']');var key=label+'@'+Math.round(r.x)+','+Math.round(r.y);if(seen[key])continue;seen[key]=1;var iv=r.top<vh&&r.bottom>0&&r.left<vw&&r.right>0;out.push({name:label,tag:e.tagName.toLowerCase(),role:e.getAttribute('role')||null,href:e.getAttribute('href')||null,inView:iv,x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)});}out.sort(function(a,b){return (b.inView?1:0)-(a.inView?1:0);});return JSON.stringify(out.slice(0,60));})()";
557
+ return `(function(){` + NAME_JS + "var sel='button,a,[role=button],[role=link],[role=menuitem],[role=tab],[role=switch],[role=checkbox],input,select,textarea';var els=Array.prototype.slice.call(document.querySelectorAll(sel));var vw=window.innerWidth,vh=window.innerHeight;var out=[];var seen={};for(var i=0;i<els.length;i++){var e=els[i];var n=dispName(e);var ph=e.getAttribute('placeholder');var r=e.getBoundingClientRect();if(r.width<6||r.height<6)continue;if(!n&&!ph)continue;var label=n||('['+(ph||e.tagName.toLowerCase())+']');var key=label+'@'+Math.round(r.x)+','+Math.round(r.y);if(seen[key])continue;seen[key]=1;var iv=r.top<vh&&r.bottom>0&&r.left<vw&&r.right>0;out.push({name:label,tag:e.tagName.toLowerCase(),role:e.getAttribute('role')||null,href:e.getAttribute('href')||null,inView:iv,x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)});}out.sort(function(a,b){return (b.inView?1:0)-(a.inView?1:0);});return JSON.stringify(out.slice(0,60));})()";
513
558
  }
514
559
  /** Open `url`, return its interactive elements (accessible name + bbox) —
515
560
  * what an agent uses to choose a demo flow. Pure CDP, same as capture, so
@@ -520,7 +565,9 @@ async function inspectPage(url, opts = {}) {
520
565
  const browser = await launchBrowser({
521
566
  width: vw,
522
567
  height: vh,
523
- chromePath: opts.chromePath
568
+ chromePath: opts.chromePath,
569
+ ...opts.userDataDir ? { userDataDir: opts.userDataDir } : {},
570
+ ...opts.headless === false ? { headless: false } : {}
524
571
  });
525
572
  try {
526
573
  const { cdp } = browser;
@@ -528,7 +575,7 @@ async function inspectPage(url, opts = {}) {
528
575
  await cdp.send("Runtime.enable");
529
576
  const inner = await fitViewport(cdp, browser.targetId, vw, vh);
530
577
  await cdp.send("Page.navigate", { url });
531
- await sleep$1(opts.warmupMs ?? 1500);
578
+ await sleep$2(opts.warmupMs ?? 1500);
532
579
  const evalRaw = async (expr) => {
533
580
  const r = await cdp.send("Runtime.evaluate", {
534
581
  expression: expr,
@@ -558,9 +605,294 @@ async function inspectPage(url, opts = {}) {
558
605
  }
559
606
  }
560
607
 
608
+ //#endregion
609
+ //#region src/nav.ts
610
+ /**
611
+ * Resolve a navigate step to one absolute URL, or null when it cannot be.
612
+ *
613
+ * Precedence is `href` > `url` > `current`: a destination READ FROM THE PAGE
614
+ * beats one written in the plan, because it is the one that reflects what the
615
+ * app just did. `current` last means `{ query }` on its own is "reload this
616
+ * same page with these params" rather than an error.
617
+ */
618
+ function resolveNavigateUrl(t) {
619
+ const base = safeUrl(t.current);
620
+ const raw = t.href || t.url || t.current;
621
+ if (!raw) return null;
622
+ const dest = safeUrl(raw, base);
623
+ if (!dest) return null;
624
+ for (const [k, v] of Object.entries(t.query ?? {})) dest.searchParams.set(k, v);
625
+ return dest.toString();
626
+ }
627
+ function safeUrl(raw, base) {
628
+ try {
629
+ return new URL(raw, base);
630
+ } catch {
631
+ return void 0;
632
+ }
633
+ }
634
+
635
+ //#endregion
636
+ //#region src/settle.ts
637
+ const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
638
+ /** Extra time a hold may spend waiting for a busy page, per beat. Generous
639
+ * enough for a slow round-trip, short enough that a page which NEVER goes
640
+ * quiet (a live clock, a polling dashboard) costs a bounded, reported amount
641
+ * rather than stretching the take without explanation. */
642
+ const DEFAULT_SETTLE_BUDGET_MS = 1200;
643
+ /** The page must have been still this long to count as settled — one paint
644
+ * plus slack, so a mutation and the layout it triggers aren't read as two
645
+ * separate quiet periods. */
646
+ const QUIET_MS = 120;
647
+ const POLL_MS = 60;
648
+ /** A pending setTimeout longer than this is the page's own heartbeat (a poll
649
+ * loop, a session timer), not this beat finishing. Counting it would make the
650
+ * page look permanently busy. */
651
+ const TIMER_MAX_MS = 2e3;
652
+ /** Grace on a timer's own deadline before it stops counting as pending. Errs
653
+ * SHORT on purpose: expiring early costs the old behaviour (a beat that may
654
+ * be captured a touch soon), expiring late costs dead air in the cut on
655
+ * every remaining beat — a much worse trade. */
656
+ const TIMER_SLACK_MS = 250;
657
+ /** A <canvas>/<video> covering this much of the frame makes the probe
658
+ * effectively blind for that beat: the element never changes size, position
659
+ * or attributes no matter what is painted inside it, so "the page is done"
660
+ * is unanswerable. Set low on purpose — a needless note costs a line of
661
+ * output, a missed one costs an author trusting a quiet run that proved
662
+ * nothing. */
663
+ const PAINT_BLIND_FRAC = .2;
664
+ /** Installed once per document; keeps `t` at the last moment anything moved. */
665
+ const PROBE_INSTALL_JS = `(() => {
666
+ if (window.__openTakeActivity) return;
667
+ const TIMER_MAX = ${TIMER_MAX_MS}, TIMER_SLACK = ${TIMER_SLACK_MS};
668
+ const A = { t: 0, net: 0, timers: 0 };
669
+ const touch = () => { A.t = performance.now(); };
670
+ touch();
671
+ try {
672
+ new MutationObserver(touch).observe(document, {
673
+ subtree: true, childList: true, attributes: true, characterData: true,
674
+ });
675
+ } catch (e) {}
676
+ try {
677
+ const of = window.fetch;
678
+ if (typeof of === "function")
679
+ window.fetch = function () {
680
+ A.net++; touch();
681
+ let p;
682
+ try { p = of.apply(window, arguments); } catch (e) { A.net--; throw e; }
683
+ return Promise.resolve(p).then(
684
+ (r) => { A.net--; touch(); return r; },
685
+ (e) => { A.net--; touch(); throw e; },
686
+ );
687
+ };
688
+ } catch (e) {}
689
+ try {
690
+ const os = XMLHttpRequest.prototype.send;
691
+ if (typeof os === "function")
692
+ XMLHttpRequest.prototype.send = function () {
693
+ A.net++; touch();
694
+ // send() throws on API misuse (send before open, send after abort) and
695
+ // then NO request exists, so loadend never fires — without this the
696
+ // increment is permanent and the page reads busy for the rest of the
697
+ // take. Same guard the fetch branch above already has.
698
+ try { this.addEventListener("loadend", () => { A.net--; touch(); }); } catch (e) {}
699
+ try { return os.apply(this, arguments); } catch (e) { A.net--; touch(); throw e; }
700
+ };
701
+ } catch (e) {}
702
+ try {
703
+ const st = window.setTimeout, ct = window.clearTimeout, ci = window.clearInterval;
704
+ // id -> the moment it must have fired by. Counting by DEADLINE rather than
705
+ // by cancellation bookkeeping is what makes this safe: a timer we never see
706
+ // cancelled (clearInterval on a setTimeout id, an id coerced through a
707
+ // dataset attribute, any API we did not wrap) simply expires and stops
708
+ // counting. Chasing every cancellation path would leave one uncounted, and
709
+ // ONE stuck entry means every remaining beat of the take waits the whole
710
+ // budget for nothing.
711
+ const live = new Map();
712
+ const forget = function (id) { live.delete(Number(id)); };
713
+ A.pending = function () {
714
+ const now = performance.now();
715
+ live.forEach(function (due, id) { if (due <= now) live.delete(id); });
716
+ A.timers = live.size;
717
+ return live.size;
718
+ };
719
+ window.setTimeout = function (fn, delay) {
720
+ const d = Number(delay) || 0;
721
+ // a string body keeps the original semantics (wrapping would stop the
722
+ // code ever running), and a long delay is a heartbeat, not this beat
723
+ if (typeof fn !== "function" || d > TIMER_MAX) return st.apply(window, arguments);
724
+ const rest = Array.prototype.slice.call(arguments, 2);
725
+ let id;
726
+ const wrapped = function () {
727
+ forget(id); touch();
728
+ return fn.apply(this, arguments);
729
+ };
730
+ id = st.apply(window, [wrapped, d].concat(rest));
731
+ live.set(Number(id), performance.now() + d + TIMER_SLACK);
732
+ touch();
733
+ return id;
734
+ };
735
+ // Both cancellers, and both coerce their argument the way the platform
736
+ // does — clearInterval legally cancels a setTimeout (one timer map), and
737
+ // clearTimeout(String(id)) is what you get back out of a dataset.
738
+ window.clearTimeout = function (id) { forget(id); return ct.apply(window, arguments); };
739
+ window.clearInterval = function (id) { forget(id); return ci.apply(window, arguments); };
740
+ } catch (e) {}
741
+ window.__openTakeActivity = A;
742
+ })()`;
743
+ /** Reads the probe. Returns a JSON string so one Runtime.evaluate round-trip
744
+ * carries the whole answer (returnByValue on a plain object also works, but
745
+ * the rest of this package already speaks the JSON-string convention). */
746
+ const PROBE_READ_JS = `(() => {
747
+ const A = window.__openTakeActivity;
748
+ if (!A) return JSON.stringify({ ok: false });
749
+ let anims = 0;
750
+ try {
751
+ for (const a of document.getAnimations()) {
752
+ if (a.playState !== "running") continue;
753
+ let it = 1;
754
+ try { it = a.effect.getTiming().iterations; } catch (e) {}
755
+ if (it === Infinity) continue; // ambient — never settles, never counted
756
+ anims++;
757
+ }
758
+ } catch (e) {}
759
+ // The largest <canvas>/<video> as a fraction of the viewport, clipped to it
760
+ // (an offscreen or scrolled-away surface is not what the viewer is watching).
761
+ let paint = 0;
762
+ try {
763
+ const area = innerWidth * innerHeight;
764
+ if (area > 0)
765
+ for (const el of document.querySelectorAll("canvas,video")) {
766
+ const r = el.getBoundingClientRect();
767
+ const w = Math.max(0, Math.min(r.right, innerWidth) - Math.max(r.left, 0));
768
+ const h = Math.max(0, Math.min(r.bottom, innerHeight) - Math.max(r.top, 0));
769
+ if (w * h > paint * area) paint = (w * h) / area;
770
+ }
771
+ } catch (e) {}
772
+ const timers = typeof A.pending === "function" ? A.pending() : (A.timers | 0);
773
+ const busy = A.net > 0 || timers > 0 || anims > 0 || document.readyState !== "complete";
774
+ return JSON.stringify({
775
+ ok: true,
776
+ quietMs: busy ? 0 : Math.max(0, performance.now() - A.t),
777
+ net: A.net,
778
+ timers,
779
+ anims,
780
+ paint,
781
+ });
782
+ })()`;
783
+ /** Install the activity probe for the current document AND every future one
784
+ * (a plan may navigate mid-take). Never throws — a capture must not fail
785
+ * because a diagnostic could not be attached. */
786
+ async function installActivityProbe(cdp) {
787
+ await cdp.send("Page.addScriptToEvaluateOnNewDocument", { source: PROBE_INSTALL_JS }).catch(() => {});
788
+ await cdp.send("Runtime.evaluate", { expression: PROBE_INSTALL_JS }).catch(() => {});
789
+ }
790
+ async function readProbe(cdp) {
791
+ try {
792
+ const r = await cdp.send("Runtime.evaluate", {
793
+ expression: PROBE_READ_JS,
794
+ returnByValue: true
795
+ });
796
+ const v = r.result?.value;
797
+ if (typeof v !== "string") return null;
798
+ const p = JSON.parse(v);
799
+ if (!p.ok) return null;
800
+ return {
801
+ quietMs: p.quietMs ?? 0,
802
+ net: p.net ?? 0,
803
+ timers: p.timers ?? 0,
804
+ anims: p.anims ?? 0,
805
+ paint: p.paint ?? 0
806
+ };
807
+ } catch {
808
+ return null;
809
+ }
810
+ }
811
+ /**
812
+ * Hold for `heldMs` (the editorial beat — always run in full), then keep
813
+ * waiting while the page is still working, up to `budgetMs`.
814
+ *
815
+ * `budgetMs <= 0` reduces this to the old fixed sleep exactly — the escape
816
+ * hatch for a page that never goes quiet (`CaptureOpts.settleBudgetMs: 0`),
817
+ * and what the unit tests use to pin the legacy timing.
818
+ */
819
+ async function settle(cdp, heldMs, opts = {}) {
820
+ const budget = opts.budgetMs ?? DEFAULT_SETTLE_BUDGET_MS;
821
+ await sleep$1(Math.max(0, heldMs));
822
+ if (!(budget > 0)) return {
823
+ heldMs,
824
+ waitedMs: 0,
825
+ reason: "budget",
826
+ paintFrac: 0
827
+ };
828
+ const t0 = Date.now();
829
+ let paintFrac = 0;
830
+ for (;;) {
831
+ const p = await readProbe(cdp);
832
+ const waitedMs = Date.now() - t0;
833
+ if (!p) return {
834
+ heldMs,
835
+ waitedMs,
836
+ reason: "unavailable",
837
+ paintFrac
838
+ };
839
+ paintFrac = Math.max(paintFrac, p.paint);
840
+ if (p.quietMs >= QUIET_MS) return {
841
+ heldMs,
842
+ waitedMs,
843
+ reason: "idle",
844
+ paintFrac
845
+ };
846
+ if (waitedMs >= budget) return {
847
+ heldMs,
848
+ waitedMs,
849
+ reason: "budget",
850
+ paintFrac
851
+ };
852
+ await sleep$1(POLL_MS);
853
+ }
854
+ }
855
+ /** How many beats in a row may spend the WHOLE budget without the page ever
856
+ * settling before the waiting is written off. */
857
+ const SETTLE_GIVE_UP_STREAK = 2;
858
+ /**
859
+ * Budget policy across one take. Some pages never go quiet — a one-second
860
+ * clock, a poll loop, a streaming widget — and no DOM signal can tell that
861
+ * apart from real work. So do not try: once a run of beats has each spent the
862
+ * entire budget with no result, the waiting is provably not helping, and
863
+ * paying it on every remaining beat would add more dead air than the whole
864
+ * demo is long. Give up once, loudly, and let the author set settleMs by eye.
865
+ */
866
+ function makeBudgetGovernor(budgetMs, giveUpStreak = SETTLE_GIVE_UP_STREAK) {
867
+ let budget = budgetMs;
868
+ let streak = 0;
869
+ return {
870
+ get budgetMs() {
871
+ return budget;
872
+ },
873
+ get gaveUp() {
874
+ return budget <= 0 && budgetMs > 0;
875
+ },
876
+ record(reason) {
877
+ if (reason === "idle") {
878
+ streak = 0;
879
+ return false;
880
+ }
881
+ if (reason !== "budget" || budget <= 0) return false;
882
+ if (++streak < giveUpStreak) return false;
883
+ budget = 0;
884
+ return true;
885
+ }
886
+ };
887
+ }
888
+
561
889
  //#endregion
562
890
  //#region src/cdp-capture.ts
563
891
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
892
+ /** Report a settle wait only past this — a couple of polls is the probe
893
+ * confirming quiet, not the page being slow, and a log full of 60ms notes
894
+ * would bury the beat that actually needed a second. */
895
+ const SETTLE_NOTE_MS = 150;
564
896
  const smoother = (u) => {
565
897
  const clamped = Math.max(0, Math.min(1, u));
566
898
  return clamped * clamped * clamped * (clamped * (clamped * 6 - 15) + 10);
@@ -585,6 +917,22 @@ async function evalAny(cdp, js) {
585
917
  if (v == null || v === "NOTFOUND") return null;
586
918
  return evalValue(typeof v === "string" ? v : JSON.stringify(v));
587
919
  }
920
+ async function evalString(cdp, js) {
921
+ const r = await cdp.send("Runtime.evaluate", {
922
+ expression: js,
923
+ returnByValue: true,
924
+ awaitPromise: true
925
+ });
926
+ const v = r.result?.value;
927
+ return typeof v === "string" && v !== "NOTFOUND" && v !== "" ? v : null;
928
+ }
929
+ async function awaitFonts(cdp) {
930
+ await Promise.race([cdp.send("Runtime.evaluate", {
931
+ expression: "document.fonts.ready.then(() => true)",
932
+ awaitPromise: true,
933
+ returnByValue: true
934
+ }).catch(() => {}), sleep(3e3)]);
935
+ }
588
936
  const center = (b) => ({
589
937
  x: Math.round(b.x + b.w / 2),
590
938
  y: Math.round(b.y + b.h / 2)
@@ -798,18 +1146,18 @@ async function captureTakeCDP(plan, opts) {
798
1146
  width: vw,
799
1147
  height: vh,
800
1148
  chromePath: opts.chromePath,
801
- deviceScaleFactor: scale
1149
+ deviceScaleFactor: scale,
1150
+ ...opts.userDataDir ? { userDataDir: opts.userDataDir } : {},
1151
+ ...opts.headless === false ? { headless: false } : {}
802
1152
  });
803
1153
  const { cdp } = browser;
804
1154
  await cdp.send("Page.enable");
805
1155
  await cdp.send("Runtime.enable");
806
1156
  const inner = await fitViewport(cdp, browser.targetId, vw, vh);
1157
+ await installActivityProbe(cdp);
807
1158
  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)]);
1159
+ await installActivityProbe(cdp);
1160
+ await awaitFonts(cdp);
813
1161
  const screencast = new Screencast(cdp, frameDir);
814
1162
  const t0 = Date.now();
815
1163
  await screencast.start(t0, {
@@ -846,6 +1194,10 @@ async function captureTakeCDP(plan, opts) {
846
1194
  };
847
1195
  const events = [];
848
1196
  const skipped = [];
1197
+ const settleWaits = [];
1198
+ const governor = makeBudgetGovernor(opts.settleBudgetMs ?? DEFAULT_SETTLE_BUDGET_MS);
1199
+ let paintedFrac = 0;
1200
+ let paintNoted = false;
849
1201
  for (let stepIdx = 0; stepIdx < plan.steps.length; stepIdx++) {
850
1202
  const step = plan.steps[stepIdx];
851
1203
  const skip = (action, target, reason) => {
@@ -857,17 +1209,68 @@ async function captureTakeCDP(plan, opts) {
857
1209
  });
858
1210
  console.error(`captureTakeCDP: ${action} ${reason}, skipped: ${JSON.stringify(target)}`);
859
1211
  };
1212
+ const hold = async (defaultMs) => {
1213
+ const heldMs = ("settleMs" in step ? step.settleMs : void 0) ?? defaultMs;
1214
+ const r = await settle(cdp, heldMs, { budgetMs: governor.budgetMs });
1215
+ paintedFrac = Math.max(paintedFrac, r.paintFrac);
1216
+ if (paintedFrac >= PAINT_BLIND_FRAC && !paintNoted) {
1217
+ paintNoted = true;
1218
+ 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\`.`);
1219
+ }
1220
+ 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");
1221
+ if (r.waitedMs < SETTLE_NOTE_MS) return;
1222
+ const waitedMs = Math.round(r.waitedMs);
1223
+ settleWaits.push({
1224
+ step: stepIdx,
1225
+ action: step.action,
1226
+ heldMs,
1227
+ waitedMs,
1228
+ reason: r.reason
1229
+ });
1230
+ console.error(`captureTakeCDP: step ${stepIdx} (${step.action}) held ${heldMs}ms, then waited ${waitedMs}ms more for the page to settle (${r.reason})`);
1231
+ };
860
1232
  if (step.action === "wait") {
861
1233
  await sleep(step.ms);
862
1234
  continue;
863
1235
  }
1236
+ if (step.action === "navigate") {
1237
+ const spec = step.hrefFrom;
1238
+ let href = null;
1239
+ if (spec) {
1240
+ const target = spec.text ?? spec.selector;
1241
+ if (!target) {
1242
+ skip("navigate", void 0, "hrefFrom has neither `selector` nor `text`");
1243
+ continue;
1244
+ }
1245
+ href = spec.selector ? await evalString(cdp, hrefSelectorJs(spec.selector)) : await evalString(cdp, hrefByTextJs(spec.text));
1246
+ if (!href) {
1247
+ skip("navigate", target, "no link with an href found");
1248
+ continue;
1249
+ }
1250
+ }
1251
+ const current = await evalString(cdp, "location.href") ?? plan.url;
1252
+ const dest = resolveNavigateUrl({
1253
+ current,
1254
+ url: step.url,
1255
+ href,
1256
+ query: step.query
1257
+ });
1258
+ if (!dest) {
1259
+ skip("navigate", step.url ?? href ?? current, "destination is not a resolvable URL");
1260
+ continue;
1261
+ }
1262
+ await navigate(cdp, dest);
1263
+ await awaitFonts(cdp);
1264
+ await hold(1200);
1265
+ continue;
1266
+ }
864
1267
  if (step.action === "type") {
865
1268
  const label$1 = step.text ?? step.selector;
866
1269
  const tMs$1 = Date.now() - t0;
867
1270
  const box$1 = step.text ? await evalBox(cdp, focusFieldByTextJs(step.text)) : step.selector ? await evalBox(cdp, focusSelectorJs(step.selector)) : null;
868
1271
  if (!box$1) {
869
1272
  skip("type", label$1, "target not found");
870
- await sleep(step.settleMs ?? 600);
1273
+ await hold(600);
871
1274
  continue;
872
1275
  }
873
1276
  if (step.clear) await evalAny(cdp, selectAllInFocusedJs());
@@ -891,7 +1294,7 @@ async function captureTakeCDP(plan, opts) {
891
1294
  durationMs: Date.now() - tType,
892
1295
  ...step.zoom ? { zoom: step.zoom } : {}
893
1296
  });
894
- await sleep(step.settleMs ?? 900);
1297
+ await hold(900);
895
1298
  continue;
896
1299
  }
897
1300
  if (step.action === "drag") {
@@ -912,7 +1315,7 @@ async function captureTakeCDP(plan, opts) {
912
1315
  const label$1 = step.note ?? step.text ?? step.selector;
913
1316
  if (!from || !to) {
914
1317
  skip("drag", label$1, "endpoint not found");
915
- await sleep(step.settleMs ?? 600);
1318
+ await hold(600);
916
1319
  continue;
917
1320
  }
918
1321
  const path = pathPts.length ? pathPts : [from, to];
@@ -951,7 +1354,115 @@ async function captureTakeCDP(plan, opts) {
951
1354
  ease: dragEase,
952
1355
  ...step.zoom ? { zoom: step.zoom } : {}
953
1356
  });
954
- await sleep(step.settleMs ?? 1100);
1357
+ await hold(1100);
1358
+ continue;
1359
+ }
1360
+ if (step.action === "dropFiles") {
1361
+ const label$1 = step.note ?? step.paths.map((p) => basename(p)).join(", ");
1362
+ if (!step.paths.length) {
1363
+ skip("dropFiles", label$1, "no files given (empty paths)");
1364
+ await hold(600);
1365
+ continue;
1366
+ }
1367
+ const absPaths = step.paths.map((p) => resolve(p));
1368
+ const missing = absPaths.filter((p) => !existsSync(p));
1369
+ if (missing.length) {
1370
+ skip("dropFiles", label$1, `file not found: ${missing.join(", ")}`);
1371
+ await hold(600);
1372
+ continue;
1373
+ }
1374
+ const files = absPaths.map((p) => {
1375
+ const st = statSync(p);
1376
+ return {
1377
+ name: basename(p),
1378
+ size: st.size
1379
+ };
1380
+ });
1381
+ let to;
1382
+ if (step.to || step.toSelector || step.toText) {
1383
+ const found = await resolvePoint({
1384
+ point: step.to,
1385
+ selector: step.toSelector,
1386
+ text: step.toText
1387
+ });
1388
+ if (!found) {
1389
+ skip("dropFiles", label$1, "drop target not found");
1390
+ await hold(600);
1391
+ continue;
1392
+ }
1393
+ to = found;
1394
+ } else to = {
1395
+ x: Math.round(inner[0] / 2),
1396
+ y: Math.round(inner[1] / 2)
1397
+ };
1398
+ const from = step.from ? {
1399
+ x: Math.round(step.from.x),
1400
+ y: Math.round(step.from.y)
1401
+ } : {
1402
+ x: inner[0] - 28,
1403
+ y: Math.round(inner[1] * .18)
1404
+ };
1405
+ const pathPts = (step.path ?? []).map((p) => ({
1406
+ x: Math.round(p.x),
1407
+ y: Math.round(p.y)
1408
+ }));
1409
+ const path = pathPts.length ? pathPts : [from, to];
1410
+ const target = step.durationMs ?? 1400;
1411
+ const dragEase = opts.dragEasing ?? "smooth";
1412
+ const easeParam = dragEase === "smooth" ? smoother : (u) => u;
1413
+ const data = {
1414
+ items: [],
1415
+ files: absPaths,
1416
+ dragOperationsMask: 1
1417
+ };
1418
+ const dragEvt = (type, p) => cdp.send("Input.dispatchDragEvent", {
1419
+ type,
1420
+ x: Math.round(p.x),
1421
+ y: Math.round(p.y),
1422
+ data
1423
+ });
1424
+ const n = Math.max(12, Math.round(target / 16));
1425
+ const tMs$1 = Date.now() - t0;
1426
+ pumpPaused = true;
1427
+ await sleep(160);
1428
+ const tCarry = Date.now();
1429
+ const last = path[path.length - 1];
1430
+ let carriedMs;
1431
+ try {
1432
+ await dragEvt("dragEnter", path[0]);
1433
+ for (let k = 1; k <= n; k++) {
1434
+ const p = sampleAlong(path, easeParam(k / n));
1435
+ dragEvt("dragOver", p).catch(() => {});
1436
+ const due = tCarry + target * k / n;
1437
+ const slack = due - Date.now();
1438
+ if (slack > 0) await sleep(slack);
1439
+ }
1440
+ await dragEvt("dragOver", last).catch(() => {});
1441
+ await dragEvt("drop", last);
1442
+ carriedMs = Date.now() - tCarry;
1443
+ } catch (e) {
1444
+ pumpPaused = false;
1445
+ skip("dropFiles", label$1, `drag dispatch failed: ${e.message}`);
1446
+ await hold(600);
1447
+ continue;
1448
+ }
1449
+ await sleep(120);
1450
+ pumpPaused = false;
1451
+ events.push({
1452
+ kind: "dropFiles",
1453
+ x: path[0].x,
1454
+ y: path[0].y,
1455
+ to: last,
1456
+ path,
1457
+ tMs: tMs$1,
1458
+ sel: label$1,
1459
+ note: step.note,
1460
+ durationMs: carriedMs,
1461
+ ease: dragEase,
1462
+ files,
1463
+ ...step.zoom ? { zoom: step.zoom } : {}
1464
+ });
1465
+ await hold(1600);
955
1466
  continue;
956
1467
  }
957
1468
  if (step.action === "scroll") {
@@ -962,7 +1473,7 @@ async function captureTakeCDP(plan, opts) {
962
1473
  if (r && typeof r.dy === "number") dy = r.dy;
963
1474
  else {
964
1475
  skip("scroll", step.toText ?? step.toSelector, "target not found");
965
- await sleep(step.settleMs ?? 600);
1476
+ await hold(600);
966
1477
  continue;
967
1478
  }
968
1479
  } else dy = step.dy ?? Math.round(vh * .8);
@@ -988,7 +1499,7 @@ async function captureTakeCDP(plan, opts) {
988
1499
  durationMs: Date.now() - tScroll,
989
1500
  note: step.note
990
1501
  });
991
- await sleep(step.settleMs ?? 800);
1502
+ await hold(800);
992
1503
  continue;
993
1504
  }
994
1505
  if (step.action === "hover") {
@@ -997,7 +1508,7 @@ async function captureTakeCDP(plan, opts) {
997
1508
  const box$1 = step.text ? await evalBox(cdp, boxByTextJs(step.text)) : step.selector ? await evalBox(cdp, boxSelectorJs(step.selector)) : null;
998
1509
  if (!box$1) {
999
1510
  skip("hover", label$1, "target not found");
1000
- await sleep(step.settleMs ?? 600);
1511
+ await hold(600);
1001
1512
  continue;
1002
1513
  }
1003
1514
  const c = center(box$1);
@@ -1014,7 +1525,7 @@ async function captureTakeCDP(plan, opts) {
1014
1525
  ...step.zoom ? { zoom: step.zoom } : {}
1015
1526
  });
1016
1527
  await sleep(dwell);
1017
- await sleep(step.settleMs ?? 300);
1528
+ await hold(900);
1018
1529
  continue;
1019
1530
  }
1020
1531
  if (step.action === "press") {
@@ -1047,7 +1558,7 @@ async function captureTakeCDP(plan, opts) {
1047
1558
  ...step.zoom ? { zoom: step.zoom } : {}
1048
1559
  });
1049
1560
  await sleep(dwell);
1050
- await sleep(step.settleMs ?? 400);
1561
+ await hold(900);
1051
1562
  continue;
1052
1563
  }
1053
1564
  const label = step.text ?? step.selector;
@@ -1063,7 +1574,7 @@ async function captureTakeCDP(plan, opts) {
1063
1574
  ...step.zoom ? { zoom: step.zoom } : {}
1064
1575
  });
1065
1576
  else skip("click", label, "target not found");
1066
- await sleep(step.settleMs ?? 1300);
1577
+ await hold(1300);
1067
1578
  }
1068
1579
  const tEndMs = Date.now() - t0;
1069
1580
  await sleep(400);
@@ -1088,7 +1599,10 @@ async function captureTakeCDP(plan, opts) {
1088
1599
  y: Math.round(inner[1] * .9)
1089
1600
  },
1090
1601
  events,
1091
- tEndMs
1602
+ tEndMs,
1603
+ ...skipped.length ? { skipped } : {},
1604
+ ...settleWaits.length ? { settleWaits } : {},
1605
+ ...paintedFrac >= PAINT_BLIND_FRAC ? { paintedFrac: Math.round(paintedFrac * 100) / 100 } : {}
1092
1606
  };
1093
1607
  } finally {
1094
1608
  await browser?.close();
@@ -1110,5 +1624,5 @@ async function navigate(cdp, url) {
1110
1624
  }
1111
1625
 
1112
1626
  //#endregion
1113
- export { captureTake, captureTakeCDP, ensureChrome, inspectPage, resolveChrome };
1114
- //# sourceMappingURL=cdp-capture-DXTkPLLF.js.map
1627
+ export { captureTake, captureTakeCDP, ensureChrome, inspectPage, resolveChrome, resolveNavigateUrl };
1628
+ //# sourceMappingURL=cdp-capture-BA3qT1Tg.js.map