@open-take/runtime 0.4.3 → 0.5.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.
@@ -0,0 +1,3 @@
1
+ import { captureTakeCDP } from "./cdp-capture-BQWdcQvD.js";
2
+
3
+ export { captureTakeCDP };
@@ -279,12 +279,34 @@ async function fitViewport(cdp, targetId, vw, vh) {
279
279
  }
280
280
  return inner;
281
281
  }
282
+ function captureCadence(frames) {
283
+ const ordered = [...frames].sort((a, b) => a.offMs - b.offMs);
284
+ const intervals = ordered.slice(1).map((frame, i) => frame.offMs - ordered[i].offMs).sort((a, b) => a - b);
285
+ const rounded = (n) => Math.round(n * 1e3) / 1e3;
286
+ const sources = new Set(frames.map((frame) => frame.timestampSource ?? "arrival"));
287
+ return {
288
+ frameCount: frames.length,
289
+ timestampSource: sources.size > 1 ? "mixed" : sources.has("frame-swap") ? "frame-swap" : "arrival",
290
+ frameOffsetsMs: ordered.map((frame) => rounded(frame.offMs)),
291
+ arrivalOffsetsMs: ordered.map((frame) => rounded(frame.arrivalMs ?? frame.offMs)),
292
+ medianIntervalMs: rounded(intervals[Math.floor(intervals.length / 2)] ?? 0),
293
+ p95IntervalMs: rounded(intervals[Math.max(0, Math.ceil(intervals.length * .95) - 1)] ?? 0),
294
+ maxIntervalMs: rounded(intervals.at(-1) ?? 0),
295
+ maxArrivalDelayMs: rounded(frames.reduce((max, frame) => Math.max(max, (frame.arrivalMs ?? frame.offMs) - frame.offMs), 0)),
296
+ outOfOrderFrames: frames.filter((frame, i) => i > 0 && frame.offMs < frames[i - 1].offMs).length,
297
+ note: "Delivered-frame timing, not unique image content or a smoothness score. Static pages may send no frames; inspect image changes within active action windows. Encoded fps is separate."
298
+ };
299
+ }
282
300
  var Screencast = class {
283
301
  cdp;
284
302
  dir;
285
303
  t0 = 0;
286
304
  n = 0;
305
+ lastArrivalAt = 0;
287
306
  frames = [];
307
+ get idleForMs() {
308
+ return Date.now() - this.lastArrivalAt;
309
+ }
288
310
  constructor(cdp, dir) {
289
311
  this.cdp = cdp;
290
312
  this.dir = dir;
@@ -292,15 +314,22 @@ var Screencast = class {
292
314
  /** Begin capture. `t0` (Date.now) anchors every frame + event onto one clock. */
293
315
  async start(t0, opts) {
294
316
  this.t0 = t0;
317
+ this.lastArrivalAt = t0;
295
318
  this.cdp.on("Page.screencastFrame", (p) => {
296
- const off = Date.now() - this.t0;
319
+ const arrived = Date.now();
320
+ this.lastArrivalAt = arrived;
321
+ const swap = p.metadata?.timestamp;
322
+ const hasSwap = typeof swap === "number" && Number.isFinite(swap);
323
+ const off = Math.max(0, hasSwap ? swap * 1e3 - this.t0 : arrived - this.t0);
297
324
  const file = join(this.dir, `f-${String(this.n++).padStart(5, "0")}.jpg`);
325
+ this.cdp.send("Page.screencastFrameAck", { sessionId: p.sessionId }).catch(() => {});
298
326
  writeFileSync(file, Buffer.from(p.data, "base64"));
299
327
  this.frames.push({
300
328
  file,
301
- offMs: off
329
+ offMs: off,
330
+ arrivalMs: arrived - this.t0,
331
+ timestampSource: hasSwap ? "frame-swap" : "arrival"
302
332
  });
303
- this.cdp.send("Page.screencastFrameAck", { sessionId: p.sessionId }).catch(() => {});
304
333
  });
305
334
  await this.cdp.send("Page.startScreencast", {
306
335
  format: "jpeg",
@@ -314,22 +343,40 @@ var Screencast = class {
314
343
  await this.cdp.send("Page.stopScreencast").catch(() => {});
315
344
  }
316
345
  };
346
+ /** Refresh idle surfaces without interrupting pages already producing frames.
347
+ * Never queue another expensive screenshot behind a slow/in-flight request. */
348
+ async function pumpIdleRaster(cdp, screencast, active, paused) {
349
+ let pending = false;
350
+ while (active()) {
351
+ if (!paused() && !pending && screencast.idleForMs >= 200) {
352
+ pending = true;
353
+ cdp.send("Page.captureScreenshot", {
354
+ format: "jpeg",
355
+ quality: 1
356
+ }).catch(() => {}).finally(() => {
357
+ pending = false;
358
+ });
359
+ }
360
+ await sleep$3(45);
361
+ }
362
+ }
317
363
  async function encodeFrames(frames, endMs, outPath, fps, ffmpegBin) {
318
364
  if (frames.length === 0) throw new Error("open-take(hi-fps): no frames captured");
365
+ frames = [...frames].sort((a, b) => a.offMs - b.offMs);
319
366
  const bin = ffmpegBin ?? await resolveFfmpeg();
320
- const dir = frames[0].file.slice(0, frames[0].file.lastIndexOf("/"));
367
+ const dir = dirname(frames[0].file);
321
368
  const listPath = join(dir, "frames.concat");
322
369
  const lines = [];
323
370
  const bounds = [
324
371
  0,
325
372
  ...frames.slice(1).map((f) => f.offMs),
326
- Math.max(endMs, frames[frames.length - 1].offMs + 33)
373
+ Math.max(endMs, frames[frames.length - 1].offMs + 1e3 / fps)
327
374
  ];
328
375
  for (let i = 0; i < frames.length; i++) {
329
376
  const dur = Math.max(.001, (bounds[i + 1] - bounds[i]) / 1e3);
330
- lines.push(`file '${frames[i].file}'`, `duration ${dur.toFixed(4)}`);
377
+ lines.push(`file '${frames[i].file}'`, "option framerate 1000", `duration ${dur.toFixed(6)}`);
331
378
  }
332
- lines.push(`file '${frames[frames.length - 1].file}'`);
379
+ lines.push(`file '${frames[frames.length - 1].file}'`, "option framerate 1000");
333
380
  writeFileSync(listPath, lines.join("\n"));
334
381
  const isWebm = /\.webm$/i.test(outPath);
335
382
  const codec = isWebm ? [
@@ -437,7 +484,8 @@ function evalValue(raw) {
437
484
  return deepParse(top);
438
485
  }
439
486
  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;}";
440
- const CLICK_TAIL_JS = "if(m.tagName==='SELECT')return 'SELECTINERT';var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center',behavior:'instant'});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)};var cx=Math.round(r.x+r.width/2),cy=Math.round(r.y+r.height/2);var hit=(r.width>0&&r.height>0&&document.elementFromPoint)?document.elementFromPoint(cx,cy):null;if(hit&&(hit===m||(m.contains&&m.contains(hit)))){b.cx=cx;b.cy=cy;return JSON.stringify(b);}m.click();return JSON.stringify(b);";
487
+ const HITTABLE_JS = "function hittable(m,r){var cx=Math.round(r.x+r.width/2),cy=Math.round(r.y+r.height/2);if(!(r.width>0&&r.height>0&&document.elementFromPoint))return null;var hit=document.elementFromPoint(cx,cy);var ok=!!hit&&(hit===m||(m.contains&&m.contains(hit)));if(!ok&&document.elementsFromPoint){var top=document.elementsFromPoint(cx,cy)[0];ok=!!top&&(top===m||(m.contains&&m.contains(top)));}return ok?{cx:cx,cy:cy}:null;}";
488
+ const CLICK_TAIL_JS = `if(m.tagName==='SELECT')return 'SELECTINERT';` + HITTABLE_JS + "var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center',behavior:'instant'});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)};var p=hittable(m,r);if(p){b.cx=p.cx;b.cy=p.cy;return JSON.stringify(b);}m.click();return JSON.stringify(b);";
441
489
  const CLICK_CANDIDATES = "button,a,[role=button],[role=link],[role=menuitem],input[type=submit],input[type=button]";
442
490
  const FIELD_CANDIDATES = "input,textarea,[contenteditable],[contenteditable=true],[role=textbox],[role=searchbox]";
443
491
  const BOX_CANDIDATES = "button,a,[role=button],[role=link],[role=menuitem],[aria-label],[title],img[alt],li,[draggable=true]";
@@ -450,13 +498,20 @@ function clickBySelectorJs(selector) {
450
498
  const s = JSON.stringify(selector);
451
499
  return `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';` + CLICK_TAIL_JS + `})()`;
452
500
  }
501
+ const FOCUS_STATE_JS = "function deepActive(){var a=document.activeElement;while(a&&a.shadowRoot&&a.shadowRoot.activeElement){a=a.shadowRoot.activeElement;}return a;}function editable(a){if(!a)return false;if(a.isContentEditable)return true;return typeof a.value==='string'&&!a.readOnly&&!a.disabled;}function withinTarget(a){var n=a;while(n){if(n===m||(m.contains&&m.contains(n)))return true;var rn=n.getRootNode?n.getRootNode():null;n=n.parentElement||((rn&&rn.host)?rn.host:null);}return false;}var ae=deepActive();var ok=!!ae&&(ae!==document.body||m===document.body)&&editable(ae)&&(withinTarget(ae)||(ae.isContentEditable&&ae.contains&&ae.contains(m)));";
502
+ const FOCUS_TAIL_JS = HITTABLE_JS + "var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center',behavior:'instant'});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();" + FOCUS_STATE_JS + "b.f=ok?1:0;if(!ok){b.hit=hittable(m,m.getBoundingClientRect())?1:0;}return JSON.stringify(b);";
453
503
  function focusFieldByTextJs(text) {
454
504
  const t = JSON.stringify(text);
455
- return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('${FIELD_CANDIDATES}'));` + 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);})()";
505
+ return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('${FIELD_CANDIDATES}'));` + NAME_JS + "var m=pick(els,t);if(!m)return 'NOTFOUND';" + FOCUS_TAIL_JS + `})()`;
456
506
  }
457
507
  function focusSelectorJs(selector) {
458
508
  const s = JSON.stringify(selector);
459
- return `(function(){var m=document.querySelector(${s});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);})()`;
509
+ return `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';` + FOCUS_TAIL_JS + `})()`;
510
+ }
511
+ function verifyFocusJs(target) {
512
+ if (!target.text && !target.selector) return `'0'`;
513
+ const resolve$1 = target.text ? `var els=Array.prototype.slice.call(document.querySelectorAll('${FIELD_CANDIDATES}'));` + NAME_JS + `var m=pick(els,${JSON.stringify(target.text)});` : `var m=document.querySelector(${JSON.stringify(target.selector ?? "")});`;
514
+ return `(function(){${resolve$1}if(!m)return '0';` + FOCUS_STATE_JS + "if(ok)return '1';return (!!ae&&ae!==document.body&&editable(ae))?'1':'0';})()";
460
515
  }
461
516
  function selectAllInFocusedJs() {
462
517
  return "(function(){var el=document.activeElement;if(!el)return 'NOFOCUS';if(typeof el.select==='function'&&typeof el.value==='string'){el.select();return 'SEL';}if(el.isContentEditable){var r=document.createRange();r.selectNodeContents(el);var s=window.getSelection();s.removeAllRanges();s.addRange(r);return 'SEL';}return 'NOSEL';})()";
@@ -552,7 +607,7 @@ async function ffprobe(path) {
552
607
  }
553
608
  /** Drive `plan` against the live app over CDP, return the ground-truth log. */
554
609
  async function captureTake(plan, opts) {
555
- const { captureTakeCDP: captureTakeCDP$1 } = await import("./cdp-capture-DvXJ9UbJ.js");
610
+ const { captureTakeCDP: captureTakeCDP$1 } = await import("./cdp-capture-B7j40ImW.js");
556
611
  return captureTakeCDP$1(plan, {
557
612
  ...opts,
558
613
  fps: opts.fps ?? 60
@@ -1433,15 +1488,7 @@ async function captureTakeCDP(plan, opts) {
1433
1488
  });
1434
1489
  let pumping = true;
1435
1490
  let pumpPaused = false;
1436
- const pump = (async () => {
1437
- while (pumping) {
1438
- if (!pumpPaused) await Promise.race([cdp.send("Page.captureScreenshot", {
1439
- format: "jpeg",
1440
- quality: 1
1441
- }).catch(() => {}), sleep(150)]);
1442
- await sleep(45);
1443
- }
1444
- })();
1491
+ const pump = opts.rasterRefresh === "off" ? Promise.resolve() : pumpIdleRaster(cdp, screencast, () => pumping, () => pumpPaused);
1445
1492
  await sleep(opts.warmupMs ?? 900);
1446
1493
  const resolvePoint = async (spec) => {
1447
1494
  if (spec.point) return {
@@ -1542,13 +1589,44 @@ async function captureTakeCDP(plan, opts) {
1542
1589
  }
1543
1590
  if (step.action === "type") {
1544
1591
  const label$1 = step.text ?? step.selector;
1545
- const tMs$1 = Date.now() - t0;
1546
- const box$1 = step.text ? await evalBox(cdp, focusFieldByTextJs(step.text)) : step.selector ? await evalBox(cdp, focusSelectorJs(step.selector)) : null;
1592
+ let tMs$1 = Date.now() - t0;
1593
+ const focusRaw = step.text ? await evalAny(cdp, focusFieldByTextJs(step.text)) : step.selector ? await evalAny(cdp, focusSelectorJs(step.selector)) : null;
1594
+ const box$1 = focusRaw ? findBox(focusRaw) : null;
1547
1595
  if (!box$1) {
1548
1596
  skip("type", label$1, "target not found");
1549
1597
  await hold(600);
1550
1598
  continue;
1551
1599
  }
1600
+ let focused = focusRaw.f === 1;
1601
+ if (!focused && focusRaw.hit !== 1) {
1602
+ skip("type", label$1, "focus never reached the target — its centre is covered, so no click could arm it");
1603
+ await hold(600);
1604
+ continue;
1605
+ }
1606
+ if (!focused) {
1607
+ const pt$1 = center(box$1);
1608
+ pumpPaused = true;
1609
+ await sleep(160);
1610
+ tMs$1 = Date.now() - t0;
1611
+ mouse(cdp, "mouseMoved", pt$1.x, pt$1.y, 0).catch(() => {});
1612
+ mouse(cdp, "mousePressed", pt$1.x, pt$1.y, 1).catch(() => {});
1613
+ await sleep(60);
1614
+ mouse(cdp, "mouseReleased", pt$1.x, pt$1.y, 0).catch(() => {});
1615
+ await sleep(120);
1616
+ pumpPaused = false;
1617
+ for (let poll = 0; poll < 3 && !focused; poll++) {
1618
+ await sleep(250);
1619
+ focused = await evalString(cdp, verifyFocusJs({
1620
+ text: step.text,
1621
+ selector: step.selector
1622
+ })) === "1";
1623
+ }
1624
+ }
1625
+ if (!focused) {
1626
+ skip("type", label$1, "focus never reached the target — typing would go nowhere");
1627
+ await hold(600);
1628
+ continue;
1629
+ }
1552
1630
  if (process.env.OPEN_TAKE_CI && await evalString(cdp, credentialFieldProbeJs()) === "secret") {
1553
1631
  skip("type", label$1, "refusing to type into a credential field (OPEN_TAKE_CI)");
1554
1632
  await hold(600);
@@ -1558,11 +1636,13 @@ async function captureTakeCDP(plan, opts) {
1558
1636
  const chars = [...step.value];
1559
1637
  const cjk = chars.filter((c) => /[\u2E80-\u9FFF\uAC00-\uD7AF\uF900-\uFAFF\uFF66-\uFF9F]/.test(c)).length;
1560
1638
  const auto = Math.min(90, Math.max(28, Math.round(1100 / Math.max(1, chars.length)))) * (cjk * 2 > chars.length ? 1.4 : 1);
1561
- const perChar = Math.round(step.perCharMs ?? auto);
1562
- const tType = Date.now();
1563
- for (const ch of chars) {
1564
- await cdp.send("Input.insertText", { text: ch });
1565
- await sleep(perChar);
1639
+ if (step.perCharMs === 0) await cdp.send("Input.insertText", { text: step.value });
1640
+ else {
1641
+ const perChar = Math.round(step.perCharMs ?? auto);
1642
+ for (const ch of chars) {
1643
+ await cdp.send("Input.insertText", { text: ch });
1644
+ await sleep(perChar);
1645
+ }
1566
1646
  }
1567
1647
  events.push({
1568
1648
  kind: "type",
@@ -1573,7 +1653,7 @@ async function captureTakeCDP(plan, opts) {
1573
1653
  note: step.note,
1574
1654
  ...step.caption ? { caption: step.caption } : {},
1575
1655
  text: step.value,
1576
- durationMs: Date.now() - tType,
1656
+ durationMs: Date.now() - t0 - tMs$1,
1577
1657
  ...step.zoom ? { zoom: step.zoom } : {}
1578
1658
  });
1579
1659
  await hold(900);
@@ -1976,6 +2056,10 @@ async function captureTakeCDP(plan, opts) {
1976
2056
  },
1977
2057
  events,
1978
2058
  tEndMs,
2059
+ captureCadence: {
2060
+ ...captureCadence(screencast.frames),
2061
+ rasterRefresh: opts.rasterRefresh ?? "idle"
2062
+ },
1979
2063
  ...skipped.length ? { skipped } : {},
1980
2064
  ...precheck.length ? { precheck } : {},
1981
2065
  ...settleWaits.length ? { settleWaits } : {},
@@ -2037,4 +2121,4 @@ async function navigate(cdp, url) {
2037
2121
 
2038
2122
  //#endregion
2039
2123
  export { PrecheckRefusal, captureTake, captureTakeCDP, ensureChrome, inspectPage, planTargets, precheckPlan, resolveChrome, resolveNavigateUrl };
2040
- //# sourceMappingURL=cdp-capture-iGdBAriK.js.map
2124
+ //# sourceMappingURL=cdp-capture-BQWdcQvD.js.map