feat: per-call human_config, timeout forwarding, humanized scrollIntoViewIfNeeded (#183)

This commit is contained in:
lilos
2026-04-28 20:34:17 +02:00
committed by GitHub
parent ee346a6a57
commit 661b873dad
12 changed files with 1485 additions and 220 deletions
+77 -31
View File
@@ -48,16 +48,16 @@
import type { Browser, Page, Frame, CDPSession, ElementHandle, BrowserContext } from 'puppeteer-core';
import type { HumanConfig } from '../human/config.js';
import { resolveConfig, rand, randRange, sleep } from '../human/config.js';
import { resolveConfig, mergeConfig, rand, randRange, sleep } from '../human/config.js';
import { RawMouse, RawKeyboard, humanMove, humanClick, clickTarget, humanIdle } from '../human/mouse.js';
import { humanType } from './keyboard.js';
import { scrollToElement, smoothWheel } from './scroll.js';
import { scrollToElement, humanScrollIntoView, smoothWheel } from './scroll.js';
export type { HumanConfig } from '../human/config.js';
export { resolveConfig } from '../human/config.js';
export { resolveConfig, mergeConfig } from '../human/config.js';
export { humanMove, humanClick, clickTarget, humanIdle } from '../human/mouse.js';
export { humanType } from './keyboard.js';
export { scrollToElement } from './scroll.js';
export { scrollToElement, humanScrollIntoView } from './scroll.js';
// ============================================================================
@@ -329,52 +329,55 @@ function patchPage(page: Page, cfg: HumanConfig, cursor: CursorState): void {
// ==== click (with clickCount support for dblclick) ====
const humanClickFn = async (selector: string, options?: any) => {
await ensureCursorInit();
if (cfg.idle_between_actions) {
await humanIdle(raw, rand(cfg.idle_between_duration[0], cfg.idle_between_duration[1]), cursor.x, cursor.y, cfg);
const callCfg = mergeConfig(cfg, options?.human_config);
if (callCfg.idle_between_actions) {
await humanIdle(raw, rand(callCfg.idle_between_duration[0], callCfg.idle_between_duration[1]), cursor.x, cursor.y, callCfg);
}
const { box, cursorX, cursorY } = await scrollToElement(page, raw, selector, cursor.x, cursor.y, cfg);
const { box, cursorX, cursorY } = await scrollToElement(page, raw, selector, cursor.x, cursor.y, callCfg, options?.timeout);
cursor.x = cursorX;
cursor.y = cursorY;
const isInput = await isInputElement(stealth, page, selector);
const target = clickTarget(box, isInput, cfg);
await humanMove(raw, cursor.x, cursor.y, target.x, target.y, cfg);
const target = clickTarget(box, isInput, callCfg);
await humanMove(raw, cursor.x, cursor.y, target.x, target.y, callCfg);
cursor.x = target.x;
cursor.y = target.y;
const clickCount = options?.clickCount ?? options?.count ?? 1;
if (clickCount >= 2) {
await humanClick(raw, isInput, cfg);
await humanClick(raw, isInput, callCfg);
await sleep(rand(40, 90));
await raw.down({ clickCount: 2 });
await sleep(rand(30, 60));
await raw.up({ clickCount: 2 });
} else {
await humanClick(raw, isInput, cfg);
await humanClick(raw, isInput, callCfg);
}
};
// ==== hover ====
const humanHoverFn = async (selector: string, options?: any) => {
await ensureCursorInit();
if (cfg.idle_between_actions) {
await humanIdle(raw, rand(cfg.idle_between_duration[0], cfg.idle_between_duration[1]), cursor.x, cursor.y, cfg);
const callCfg = mergeConfig(cfg, options?.human_config);
if (callCfg.idle_between_actions) {
await humanIdle(raw, rand(callCfg.idle_between_duration[0], callCfg.idle_between_duration[1]), cursor.x, cursor.y, callCfg);
}
const { box, cursorX, cursorY } = await scrollToElement(page, raw, selector, cursor.x, cursor.y, cfg);
const { box, cursorX, cursorY } = await scrollToElement(page, raw, selector, cursor.x, cursor.y, callCfg, options?.timeout);
cursor.x = cursorX;
cursor.y = cursorY;
const target = clickTarget(box, false, cfg);
await humanMove(raw, cursor.x, cursor.y, target.x, target.y, cfg);
const target = clickTarget(box, false, callCfg);
await humanMove(raw, cursor.x, cursor.y, target.x, target.y, callCfg);
cursor.x = target.x;
cursor.y = target.y;
};
// ==== type ====
const humanTypeFn = async (selector: string, text: string, options?: any) => {
await sleep(randRange(cfg.field_switch_delay));
await humanClickFn(selector);
const callCfg = mergeConfig(cfg, options?.human_config);
await sleep(randRange(callCfg.field_switch_delay));
await humanClickFn(selector, options);
await sleep(rand(100, 250));
const cdp = await ensureCdp();
await humanType(page, rawKb, text, cfg, cdp);
await humanType(page, rawKb, text, callCfg, cdp);
};
// ==== select ====
@@ -577,6 +580,9 @@ function patchSingleElementHandle(
const origElDragAndDrop = (el as any).dragAndDrop?.bind(el);
const origElSelect = (el as any).select?.bind(el);
const origElDrop = (el as any).drop?.bind(el);
// Puppeteer v22+ adds ElementHandle.scrollIntoView(); earlier versions
// expose it implicitly via evaluate(node => node.scrollIntoView()).
const origElScrollIntoView = (el as any).scrollIntoView?.bind(el);
// --- Nested selectors ---
const origEl$ = el.$.bind(el);
@@ -603,20 +609,34 @@ function patchSingleElementHandle(
return child;
};
// --- Helper: get box and move cursor ---
const moveToElement = async () => {
// --- Helper: get box and move cursor. Accepts a per-call ``callCfg``
// so type/fill overrides like ``el.type(text, { human_config: {...} })``
// carry through to mouse timing for that single call. Also scrolls into
// view first so off-screen elements work (#129, #137 follow-up).
const moveToElement = async (callCfg: HumanConfig = cfg) => {
await (page as any)._ensureCursorInit();
try {
const { cursorX, cursorY } = await humanScrollIntoView(
page, raw,
() => el.boundingBox().then(b => b ?? null),
cursor.x, cursor.y, callCfg,
);
cursor.x = cursorX;
cursor.y = cursorY;
} catch { /* let boundingBox() decide */ }
const box = await el.boundingBox();
if (!box) return null;
const isInp = await isInputElementHandle(stealth, el);
const target = clickTarget(box, isInp, cfg);
const target = clickTarget(box, isInp, callCfg);
if (cfg.idle_between_actions) {
await humanIdle(raw, rand(cfg.idle_between_duration[0], cfg.idle_between_duration[1]), cursor.x, cursor.y, cfg);
if (callCfg.idle_between_actions) {
await humanIdle(raw, rand(callCfg.idle_between_duration[0], callCfg.idle_between_duration[1]), cursor.x, cursor.y, callCfg);
}
await humanMove(raw, cursor.x, cursor.y, target.x, target.y, cfg);
await humanMove(raw, cursor.x, cursor.y, target.x, target.y, callCfg);
cursor.x = target.x;
cursor.y = target.y;
return { box, isInp };
@@ -624,18 +644,19 @@ function patchSingleElementHandle(
// --- el.click() ---
(el as any).click = async (options?: any) => {
const info = await moveToElement();
const callCfg = mergeConfig(cfg, options?.human_config);
const info = await moveToElement(callCfg);
if (!info) return origElClick(options);
const clickCount = options?.clickCount ?? options?.count ?? 1;
if (clickCount >= 2) {
await humanClick(raw, info.isInp, cfg);
await humanClick(raw, info.isInp, callCfg);
await sleep(rand(40, 90));
await raw.down({ clickCount: 2 });
await sleep(rand(30, 60));
await raw.up({ clickCount: 2 });
} else {
await humanClick(raw, info.isInp, cfg);
await humanClick(raw, info.isInp, callCfg);
}
};
@@ -647,14 +668,39 @@ function patchSingleElementHandle(
// --- el.type() ---
(el as any).type = async (text: string, options?: any) => {
const info = await moveToElement();
const callCfg = mergeConfig(cfg, options?.human_config);
const info = await moveToElement(callCfg);
if (!info) return origElType(text, options);
await humanClick(raw, info.isInp, cfg);
await humanClick(raw, info.isInp, callCfg);
await sleep(rand(100, 250));
const cdp = await stealth.getCdpSession().catch(() => null);
await humanType(page, rawKb, text, cfg, cdp);
await humanType(page, rawKb, text, callCfg, cdp);
};
// --- el.scrollIntoView() ---
// Puppeteer-only equivalent of Playwright's scrollIntoViewIfNeeded.
// Replaces the native snap-scroll (a strong bot signal) with the same
// accelerate → cruise → decelerate → overshoot wheel sequence used by
// page.click(). Only patched when the underlying ElementHandle exposes
// ``scrollIntoView`` (Puppeteer v22+).
if (origElScrollIntoView) {
(el as any).scrollIntoView = async (options?: any) => {
const callCfg = mergeConfig(cfg, options?.human_config);
await (page as any)._ensureCursorInit();
try {
const { cursorX, cursorY } = await humanScrollIntoView(
page, raw,
() => el.boundingBox().then(b => b ?? null),
cursor.x, cursor.y, callCfg,
);
cursor.x = cursorX;
cursor.y = cursorY;
} catch {
return origElScrollIntoView(options);
}
};
}
// --- el.press() ---
if (origElPress) {
(el as any).press = async (key: string, options?: any) => {
+59 -18
View File
@@ -5,7 +5,7 @@
* Changes from Playwright version:
* - page.viewport() instead of page.viewportSize()
* - page.$(selector) + el.boundingBox() instead of page.locator().boundingBox()
* - No timeout parameter on boundingBox()
* - boundingBox() has no timeout param — we poll page.$() up to ``timeout`` ms
*/
import type { Page } from 'puppeteer-core';
@@ -55,22 +55,40 @@ export async function smoothWheel(
}
}
async function getElementBox(page: Page, selector: string): Promise<ElementBounds | null> {
try {
const el = await page.$(selector);
if (!el) return null;
const box = await el.boundingBox();
if (!box) return null;
return { x: box.x, y: box.y, width: box.width, height: box.height };
} catch {
return null;
/**
* Poll ``page.$(selector)`` for up to ``timeout`` ms, returning the element's
* bounding box when found. ``timeout`` defaults to 2000ms when not specified.
*/
async function getElementBox(
page: Page,
selector: string,
timeout: number = 2000,
): Promise<ElementBounds | null> {
const start = Date.now();
const pollInterval = 100;
while (true) {
try {
const el = await page.$(selector);
if (el) {
const box = await el.boundingBox();
if (box) return { x: box.x, y: box.y, width: box.width, height: box.height };
}
} catch { /* keep polling */ }
if (Date.now() - start >= timeout) return null;
await sleep(pollInterval);
}
}
export async function scrollToElement(
/**
* Humanized scrolling that takes an arbitrary ``getBox`` callable.
* Used by both ``scrollToElement`` (selector-based) and the ElementHandle
* ``scrollIntoView`` patch.
*/
export async function humanScrollIntoView(
page: Page,
raw: RawMouse,
selector: string,
getBox: () => Promise<ElementBounds | null>,
cursorX: number,
cursorY: number,
cfg: HumanConfig,
@@ -78,11 +96,11 @@ export async function scrollToElement(
const viewport = page.viewport();
if (!viewport) throw new Error('Viewport size not available');
let box = await getElementBox(page, selector);
let box = await getBox();
if (!box) {
await sleep(200);
box = await getElementBox(page, selector);
if (!box) throw new Error(`Element not found: ${selector}`);
box = await getBox();
if (!box) throw new Error('Element not found while scrolling into view');
}
if (isInViewport(box, viewport.height, cfg)) {
@@ -134,7 +152,7 @@ export async function scrollToElement(
await sleep(pause);
if (i % 3 === 2 || i === totalClicks - 1) {
box = await getElementBox(page, selector);
box = await getBox();
if (box && isInViewport(box, viewport.height, cfg)) {
break;
}
@@ -159,8 +177,31 @@ export async function scrollToElement(
await sleep(randRange(cfg.scroll_settle_delay));
box = await getElementBox(page, selector);
if (!box) throw new Error(`Element lost after scrolling: ${selector}`);
box = await getBox();
if (!box) throw new Error('Element lost after scrolling into view');
return { box, cursorX, cursorY };
}
/**
* Selector-based humanized scroll (Puppeteer).
*
* ``timeout`` controls how long we poll ``page.$(selector)`` before giving up,
* so callers like ``page.click('#x', { timeout: 5000 })`` can wait longer for
* slow-loading elements (#137). Default stays 2000ms when not specified.
*/
export async function scrollToElement(
page: Page,
raw: RawMouse,
selector: string,
cursorX: number,
cursorY: number,
cfg: HumanConfig,
timeout?: number,
): Promise<{ box: ElementBounds; cursorX: number; cursorY: number }> {
return humanScrollIntoView(
page, raw,
() => getElementBox(page, selector, timeout),
cursorX, cursorY, cfg,
);
}
+16
View File
@@ -201,6 +201,22 @@ export function resolveConfig(
return { ...base, ...overrides };
}
/**
* Merge a partial overrides object on top of an existing HumanConfig.
* Returns a new object the original ``cfg`` is never mutated.
*
* Used by per-call overrides such as ``page.type(sel, text, { human_config: { typing_delay: 30 } })``
* so the same patched page can type different fields at different speeds
* without re-patching.
*/
export function mergeConfig(
cfg: HumanConfig,
overrides?: Partial<HumanConfig> | null,
): HumanConfig {
if (!overrides) return cfg;
return { ...cfg, ...overrides };
}
// ---------------------------------------------------------------------------
// Utility: random number in range
+67 -16
View File
@@ -18,9 +18,10 @@
import type { Page, Frame, ElementHandle, CDPSession } from 'playwright-core';
import type { HumanConfig } from './config.js';
import { rand, randRange, sleep } from './config.js';
import { rand, randRange, sleep, mergeConfig } from './config.js';
import { RawMouse, RawKeyboard, humanMove, humanClick, clickTarget, humanIdle } from './mouse.js';
import { humanType } from './keyboard.js';
import { humanScrollIntoView } from './scroll.js';
// --- Platform-aware select-all shortcut ---
const SELECT_ALL = process.platform === 'darwin' ? 'Meta+a' : 'Control+a';
@@ -102,6 +103,7 @@ export function patchSingleElementHandle(
const origElSetChecked = (el as any).setChecked?.bind(el);
const origElTap = el.tap.bind(el);
const origElFocus = el.focus.bind(el);
const origElScrollIntoViewIfNeeded = (el as any).scrollIntoViewIfNeeded?.bind(el);
// Nested selectors
const origEl$ = el.$.bind(el);
@@ -130,22 +132,42 @@ export function patchSingleElementHandle(
};
// --- Helper: get bounding box and move cursor to element ---
const moveToElement = async () => {
// Accepts a per-call ``callCfg`` so type/fill overrides like
// ``el.type(text, { human_config: { typing_delay: 30 } })`` carry through to
// mouse movement & idle timing for that single call.
// Also scrolls the element into view first so off-screen elements work
// (#129, #137 follow-up): otherwise boundingBox() returns null and we'd
// silently fall back to the unpatched native method.
const moveToElement = async (callCfg: HumanConfig = cfg) => {
// Ensure cursor is initialized
const ensureCursorInit = (page as any)._ensureCursorInit;
if (ensureCursorInit) await ensureCursorInit();
// Scroll into view first so boundingBox() returns coordinates even when
// the element starts below the fold. Best-effort — if humanScrollIntoView
// throws (e.g. detached element), we let boundingBox() decide whether to
// proceed or fall back to the original method.
try {
const { cursorX, cursorY } = await humanScrollIntoView(
page, raw,
() => el.boundingBox(),
cursor.x, cursor.y, callCfg,
);
cursor.x = cursorX;
cursor.y = cursorY;
} catch { /* let boundingBox() decide */ }
const box = await el.boundingBox();
if (!box) return null;
const isInp = await isInputElementHandle(stealth, el);
const target = clickTarget(box, isInp, cfg);
const target = clickTarget(box, isInp, callCfg);
if (cfg.idle_between_actions) {
await humanIdle(raw, rand(cfg.idle_between_duration[0], cfg.idle_between_duration[1]), cursor.x, cursor.y, cfg);
if (callCfg.idle_between_actions) {
await humanIdle(raw, rand(callCfg.idle_between_duration[0], callCfg.idle_between_duration[1]), cursor.x, cursor.y, callCfg);
}
await humanMove(raw, cursor.x, cursor.y, target.x, target.y, cfg);
await humanMove(raw, cursor.x, cursor.y, target.x, target.y, callCfg);
cursor.x = target.x;
cursor.y = target.y;
return { box, isInp };
@@ -153,14 +175,16 @@ export function patchSingleElementHandle(
// --- el.click() ---
(el as any).click = async (options?: any) => {
const info = await moveToElement();
const callCfg = mergeConfig(cfg, options?.human_config);
const info = await moveToElement(callCfg);
if (!info) return origElClick(options);
await humanClick(raw, info.isInp, cfg);
await humanClick(raw, info.isInp, callCfg);
};
// --- el.dblclick() ---
(el as any).dblclick = async (options?: any) => {
const info = await moveToElement();
const callCfg = mergeConfig(cfg, options?.human_config);
const info = await moveToElement(callCfg);
if (!info) return origElDblclick(options);
await raw.down({ clickCount: 2 });
await sleep(rand(30, 60));
@@ -169,27 +193,30 @@ export function patchSingleElementHandle(
// --- el.hover() ---
(el as any).hover = async (options?: any) => {
const info = await moveToElement();
const callCfg = mergeConfig(cfg, options?.human_config);
const info = await moveToElement(callCfg);
if (!info) return origElHover(options);
// Just move — no click
};
// --- el.type() ---
(el as any).type = async (text: string, options?: any) => {
const info = await moveToElement();
const callCfg = mergeConfig(cfg, options?.human_config);
const info = await moveToElement(callCfg);
if (!info) return origElType(text, options);
await humanClick(raw, info.isInp, cfg);
await humanClick(raw, info.isInp, callCfg);
await sleep(rand(100, 250));
let cdpSession: CDPSession | null = null;
try { cdpSession = await stealth?.getCdpSession(); } catch {}
await humanType(page, rawKb, text, cfg, cdpSession);
await humanType(page, rawKb, text, callCfg, cdpSession);
};
// --- el.fill() ---
(el as any).fill = async (value: string, options?: any) => {
const info = await moveToElement();
const callCfg = mergeConfig(cfg, options?.human_config);
const info = await moveToElement(callCfg);
if (!info) return origElFill(value, options);
await humanClick(raw, info.isInp, cfg);
await humanClick(raw, info.isInp, callCfg);
await sleep(rand(100, 250));
// Clear existing content
await originals.keyboardPress(SELECT_ALL);
@@ -198,7 +225,7 @@ export function patchSingleElementHandle(
await sleep(rand(50, 150));
let cdpSession: CDPSession | null = null;
try { cdpSession = await stealth?.getCdpSession(); } catch {}
await humanType(page, rawKb, value, cfg, cdpSession);
await humanType(page, rawKb, value, callCfg, cdpSession);
};
// --- el.press() ---
@@ -268,6 +295,30 @@ export function patchSingleElementHandle(
await moveToElement(); // human-like Bézier cursor movement
await origElFocus(); // programmatic focus, no click
};
// --- el.scrollIntoViewIfNeeded() ---
// Playwright's native version snaps the page — a strong bot signal.
// Replace with the same accelerate → cruise → decelerate → overshoot
// wheel sequence used by page.click() etc. Falls back to the native
// method if the element is detached or scrolling fails.
if (origElScrollIntoViewIfNeeded) {
(el as any).scrollIntoViewIfNeeded = async (options?: any) => {
const callCfg = mergeConfig(cfg, options?.human_config);
const ensureCursorInit = (page as any)._ensureCursorInit;
if (ensureCursorInit) await ensureCursorInit();
try {
const { cursorX, cursorY } = await humanScrollIntoView(
page, raw,
() => el.boundingBox(),
cursor.x, cursor.y, callCfg,
);
cursor.x = cursorX;
cursor.y = cursorY;
} catch {
return origElScrollIntoViewIfNeeded(options);
}
};
}
}
+34 -28
View File
@@ -23,16 +23,16 @@
*/
import type { Browser, BrowserContext, Page, Frame, CDPSession } from 'playwright-core';
import { HumanConfig, resolveConfig, rand, randRange, sleep } from './config.js';
import { HumanConfig, resolveConfig, mergeConfig, rand, randRange, sleep } from './config.js';
import { RawMouse, RawKeyboard, humanMove, humanClick, clickTarget, humanIdle } from './mouse.js';
import { humanType } from './keyboard.js';
import { scrollToElement } from './scroll.js';
import { scrollToElement, humanScrollIntoView } from './scroll.js';
import { patchPageElementHandles, patchFrameElementHandles, patchSingleElementHandle } from './elementhandle.js';
export { HumanConfig, resolveConfig } from './config.js';
export { HumanConfig, resolveConfig, mergeConfig } from './config.js';
export { humanMove, humanClick, clickTarget, humanIdle } from './mouse.js';
export { humanType } from './keyboard.js';
export { scrollToElement } from './scroll.js';
export { scrollToElement, humanScrollIntoView } from './scroll.js';
export { patchSingleElementHandle } from './elementhandle.js';
// --- Platform-aware select-all shortcut (macOS uses Meta, others use Control) ---
@@ -305,32 +305,34 @@ function patchPage(page: Page, cfg: HumanConfig, cursor: CursorState): void {
// --- click ---
const humanClickFn = async (selector: string, options?: any) => {
await ensureCursorInit();
if (cfg.idle_between_actions) {
await humanIdle(raw, rand(cfg.idle_between_duration[0], cfg.idle_between_duration[1]), cursor.x, cursor.y, cfg);
const callCfg = mergeConfig(cfg, options?.human_config);
if (callCfg.idle_between_actions) {
await humanIdle(raw, rand(callCfg.idle_between_duration[0], callCfg.idle_between_duration[1]), cursor.x, cursor.y, callCfg);
}
const { box, cursorX, cursorY } = await scrollToElement(page, raw, selector, cursor.x, cursor.y, cfg);
const { box, cursorX, cursorY } = await scrollToElement(page, raw, selector, cursor.x, cursor.y, callCfg, options?.timeout);
cursor.x = cursorX;
cursor.y = cursorY;
const isInput = await isInputElement(stealth, page, selector);
const target = clickTarget(box, isInput, cfg);
await humanMove(raw, cursor.x, cursor.y, target.x, target.y, cfg);
const target = clickTarget(box, isInput, callCfg);
await humanMove(raw, cursor.x, cursor.y, target.x, target.y, callCfg);
cursor.x = target.x;
cursor.y = target.y;
await humanClick(raw, isInput, cfg);
await humanClick(raw, isInput, callCfg);
};
// --- dblclick ---
const humanDblclickFn = async (selector: string, options?: any) => {
await ensureCursorInit();
if (cfg.idle_between_actions) {
await humanIdle(raw, rand(cfg.idle_between_duration[0], cfg.idle_between_duration[1]), cursor.x, cursor.y, cfg);
const callCfg = mergeConfig(cfg, options?.human_config);
if (callCfg.idle_between_actions) {
await humanIdle(raw, rand(callCfg.idle_between_duration[0], callCfg.idle_between_duration[1]), cursor.x, cursor.y, callCfg);
}
const { box, cursorX, cursorY } = await scrollToElement(page, raw, selector, cursor.x, cursor.y, cfg);
const { box, cursorX, cursorY } = await scrollToElement(page, raw, selector, cursor.x, cursor.y, callCfg, options?.timeout);
cursor.x = cursorX;
cursor.y = cursorY;
const isInput = await isInputElement(stealth, page, selector);
const target = clickTarget(box, isInput, cfg);
await humanMove(raw, cursor.x, cursor.y, target.x, target.y, cfg);
const target = clickTarget(box, isInput, callCfg);
await humanMove(raw, cursor.x, cursor.y, target.x, target.y, callCfg);
cursor.x = target.x;
cursor.y = target.y;
await raw.down({ clickCount: 2 });
@@ -341,38 +343,41 @@ function patchPage(page: Page, cfg: HumanConfig, cursor: CursorState): void {
// --- hover ---
const humanHoverFn = async (selector: string, options?: any) => {
await ensureCursorInit();
if (cfg.idle_between_actions) {
await humanIdle(raw, rand(cfg.idle_between_duration[0], cfg.idle_between_duration[1]), cursor.x, cursor.y, cfg);
const callCfg = mergeConfig(cfg, options?.human_config);
if (callCfg.idle_between_actions) {
await humanIdle(raw, rand(callCfg.idle_between_duration[0], callCfg.idle_between_duration[1]), cursor.x, cursor.y, callCfg);
}
const { box, cursorX, cursorY } = await scrollToElement(page, raw, selector, cursor.x, cursor.y, cfg);
const { box, cursorX, cursorY } = await scrollToElement(page, raw, selector, cursor.x, cursor.y, callCfg, options?.timeout);
cursor.x = cursorX;
cursor.y = cursorY;
const target = clickTarget(box, false, cfg);
await humanMove(raw, cursor.x, cursor.y, target.x, target.y, cfg);
const target = clickTarget(box, false, callCfg);
await humanMove(raw, cursor.x, cursor.y, target.x, target.y, callCfg);
cursor.x = target.x;
cursor.y = target.y;
};
// --- type ---
const humanTypeFn = async (selector: string, text: string, options?: any) => {
await sleep(randRange(cfg.field_switch_delay));
await humanClickFn(selector);
const callCfg = mergeConfig(cfg, options?.human_config);
await sleep(randRange(callCfg.field_switch_delay));
await humanClickFn(selector, options);
await sleep(rand(100, 250));
const cdp = await ensureCdp();
await humanType(page, rawKb, text, cfg, cdp);
await humanType(page, rawKb, text, callCfg, cdp);
};
// --- fill (clears existing content first) ---
const humanFillFn = async (selector: string, value: string, options?: any) => {
await sleep(randRange(cfg.field_switch_delay));
await humanClickFn(selector);
const callCfg = mergeConfig(cfg, options?.human_config);
await sleep(randRange(callCfg.field_switch_delay));
await humanClickFn(selector, options);
await sleep(rand(100, 250));
await originals.keyboardPress(SELECT_ALL);
await sleep(rand(30, 80));
await originals.keyboardPress('Backspace');
await sleep(rand(50, 150));
const cdp = await ensureCdp();
await humanType(page, rawKb, value, cfg, cdp);
await humanType(page, rawKb, value, callCfg, cdp);
};
// --- clear ---
@@ -426,12 +431,13 @@ function patchPage(page: Page, cfg: HumanConfig, cursor: CursorState): void {
// --- pressSequentially ---
const humanPressSequentiallyFn = async (selector: string, text: string, options?: any) => {
const callCfg = mergeConfig(cfg, options?.human_config);
if (!await isSelectorFocused(stealth, page, selector)) {
await humanClickFn(selector);
await humanClickFn(selector, options);
}
await sleep(rand(100, 250));
const cdp = await ensureCdp();
await humanType(page, rawKb, text, cfg, cdp);
await humanType(page, rawKb, text, callCfg, cdp);
};
// --- tap ---
+44 -10
View File
@@ -38,10 +38,17 @@ async function smoothWheel(raw: RawMouse, delta: number, cfg: HumanConfig): Prom
}
}
export async function scrollToElement(
/**
* Humanized scrolling that takes an arbitrary ``getBox`` callable.
*
* Used by both ``scrollToElement`` (selector-based) and the ElementHandle
* ``scrollIntoViewIfNeeded`` patch so the same accelerate cruise
* decelerate overshoot behavior runs everywhere.
*/
export async function humanScrollIntoView(
page: Page,
raw: RawMouse,
selector: string,
getBox: () => Promise<ElementBounds | null>,
cursorX: number,
cursorY: number,
cfg: HumanConfig,
@@ -49,11 +56,11 @@ export async function scrollToElement(
const viewport = page.viewportSize();
if (!viewport) throw new Error('Viewport size not available');
let box = await getElementBox(page, selector);
let box = await getBox();
if (!box) {
await sleep(200);
box = await getElementBox(page, selector);
if (!box) throw new Error(`Element not found: ${selector}`);
box = await getBox();
if (!box) throw new Error('Element not found while scrolling into view');
}
if (isInViewport(box, viewport.height, cfg)) {
@@ -107,7 +114,7 @@ export async function scrollToElement(
// Check visibility every 3 steps
if (i % 3 === 2 || i === totalClicks - 1) {
box = await getElementBox(page, selector);
box = await getBox();
if (box && isInViewport(box, viewport.height, cfg)) {
break;
}
@@ -133,16 +140,43 @@ export async function scrollToElement(
// Settle
await sleep(randRange(cfg.scroll_settle_delay));
box = await getElementBox(page, selector);
if (!box) throw new Error(`Element lost after scrolling: ${selector}`);
box = await getBox();
if (!box) throw new Error('Element lost after scrolling into view');
return { box, cursorX, cursorY };
}
async function getElementBox(page: Page, selector: string): Promise<ElementBounds | null> {
/**
* Selector-based humanized scroll.
*
* ``timeout`` is forwarded to Playwright's ``boundingBox({ timeout })`` so
* callers like ``page.click('#x', { timeout: 5000 })`` can wait longer for
* slow-loading elements (#137). Default stays 2000ms when not specified.
*/
export async function scrollToElement(
page: Page,
raw: RawMouse,
selector: string,
cursorX: number,
cursorY: number,
cfg: HumanConfig,
timeout?: number,
): Promise<{ box: ElementBounds; cursorX: number; cursorY: number }> {
return humanScrollIntoView(
page, raw,
() => getElementBox(page, selector, timeout),
cursorX, cursorY, cfg,
);
}
async function getElementBox(
page: Page,
selector: string,
timeout: number = 2000,
): Promise<ElementBounds | null> {
const el = page.locator(selector).first();
try {
const box = await el.boundingBox({ timeout: 2000 });
const box = await el.boundingBox({ timeout });
return box;
} catch {
return null;