Skip to content

The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.

refactor(ego-browser): align helper API to Playwright naming and units

0x0546bd844ee15
diff --git a/package/ego-browser/README.md b/package/ego-browser/README.md
index b0d9f48..a63bcad 100644
--- a/package/ego-browser/README.md
+++ b/package/ego-browser/README.md
@@ -67,13 +67,13 @@ src/
driver/
pointer.ts click, hover, drag, scroll, scrollBy
observe.ts snapshot, captureScreenshot, elementCenter
- keyboard.ts typeText, pressKey, fillInput, dispatchKey
+ keyboard.ts insertText, pressKey, fillInput, dispatchKey
nav.ts tabs, gotoUrl, openOrReuseTab, closeTab
load.ts waitForLoad and load orchestration
waits.ts waitForElement, waitForNetworkIdle, wait
- files.ts uploadFile
+ files.ts setInputFiles
http.ts serverFetch, browserFetch
- cdp-eval.ts cdp() and js() raw eval
+ cdp-eval.ts cdp() and evaluate() raw eval
learning/ site-learnings discovery and manifest validation
scripts/
build.mjs esbuild bundling
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/adversarial.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/adversarial.mjs
index bd924f7..ffe03b7 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/adversarial.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/adversarial.mjs
@@ -5,7 +5,7 @@ export const adversarialCases = [
name: "adversarial stale ref falls back after replacement",
body: homeCase(`
${buttonRefSetup()}
- await js(\`
+ await evaluate(\`
const oldButton = document.querySelector('#click-button');
const replacement = oldButton.cloneNode(true);
replacement.addEventListener('click', (event) => {
@@ -27,12 +27,12 @@ export const adversarialCases = [
{
name: "adversarial js serialization boundaries",
body: homeCase(`
- assert(Number.isNaN(await js("NaN")), "js decodes NaN unserializable value");
- assertEqual(await js("Infinity"), Infinity, "js decodes positive Infinity");
- assertEqual(await js("-Infinity"), -Infinity, "js decodes negative Infinity");
- assert(Object.is(await js("-0"), -0), "js preserves negative zero");
+ assert(Number.isNaN(await evaluate("NaN")), "js decodes NaN unserializable value");
+ assertEqual(await evaluate("Infinity"), Infinity, "js decodes positive Infinity");
+ assertEqual(await evaluate("-Infinity"), -Infinity, "js decodes negative Infinity");
+ assert(Object.is(await evaluate("-0"), -0), "js preserves negative zero");
assert(
- (await js("12345678901234567890n")) === 12345678901234567890n,
+ (await evaluate("12345678901234567890n")) === 12345678901234567890n,
"js decodes BigInt unserializable value"
);
`),
@@ -40,12 +40,12 @@ export const adversarialCases = [
{
name: "adversarial js wrapping boundaries",
body: homeCase(`
- assertEqual(await js("Promise.resolve(42)"), 42, "js awaits promise values");
- assertEqual(await js("'return is inside a string'"), "return is inside a string", "js does not wrap return inside strings");
- assertEqual(await js("// return is inside a comment\\n1 + 4"), 5, "js does not wrap return inside comments");
- assertEqual(await js("const returned = 1; returned + 1"), 2, "js does not treat returned as return keyword");
+ assertEqual(await evaluate("Promise.resolve(42)"), 42, "js awaits promise values");
+ assertEqual(await evaluate("'return is inside a string'"), "return is inside a string", "js does not wrap return inside strings");
+ assertEqual(await evaluate("// return is inside a comment\\n1 + 4"), 5, "js does not wrap return inside comments");
+ assertEqual(await evaluate("const returned = 1; returned + 1"), 2, "js does not treat returned as return keyword");
await assertRejects(
- () => js("throw 'primitive boom'"),
+ () => evaluate("throw 'primitive boom'"),
"primitive boom",
"js reports thrown primitive values"
);
@@ -54,9 +54,9 @@ export const adversarialCases = [
{
name: "adversarial fetch origin follows current page",
body: homeCase(`
- await gotoAndWait(baseUrl + "/nav-target", { timeout: 10 });
+ await goto(baseUrl + "/nav-target", { timeout: 10000 });
assertEqual(await browserFetch("/api/text", { timeout: 5 }), "server text fixture", "browserFetch resolves relative URLs against current page origin after navigation");
- await gotoAndWait(baseUrl + "/", { timeout: 10 });
+ await goto(baseUrl + "/", { timeout: 10000 });
assertEqual(await browserFetch("/api/text", { timeout: 5 }), "server text fixture", "browserFetch still resolves after navigating back home");
`),
},
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/canvas.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/canvas.mjs
index affb91c..a64dff7 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/canvas.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/canvas.mjs
@@ -1,11 +1,11 @@
import { homeCase } from "./shared.mjs";
/* Canvas drawing helper: returns a drawAt function that maps canvas-relative
- fractions (0–1) to viewport coordinates for dragMouse. This adapts to the
+ fractions (0–1) to viewport coordinates for drag. This adapts to the
actual rendered canvas size instead of assuming fixed 400×300. */
function canvasSetup() {
return `
- const canvasRect = await js(\`(() => {
+ const canvasRect = await evaluate(\`(() => {
const c = document.querySelector("#draw-canvas");
const r = c.getBoundingClientRect();
return { left: r.left, top: r.top, w: r.width, h: r.height };
@@ -37,24 +37,24 @@ export const canvasCases = [
${canvasSetup()}
/* Draw a horizontal line across the middle of the canvas. */
- await dragMouse([drawAt(0.05, 0.5), drawAt(0.5, 0.5), drawAt(0.95, 0.5)], { delayMs: 10 });
+ await drag([drawAt(0.05, 0.5), drawAt(0.5, 0.5), drawAt(0.95, 0.5)], { delay: 10 });
await waitForJsValue("window.__fixtureState.canvasStrokes", 1, "single drag creates one stroke");
await waitForJsCondition("window.__fixtureState.canvasPoints >= 3", "stroke has at least 3 points");
assertEqual(
- await js("return window.__fixtureState.canvasDrawing"),
+ await evaluate("return window.__fixtureState.canvasDrawing"),
false,
"canvas drawing state resets after mouseup"
);
/* Verify pixels were drawn at three positions along the stroke path. */
- assert(await js("return " + ${JSON.stringify(pixelDrawn(0.15, 0.5))}), "pixels drawn at stroke start region");
- assert(await js("return " + ${JSON.stringify(pixelDrawn(0.5, 0.5))}), "pixels drawn at stroke midpoint");
- assert(await js("return " + ${JSON.stringify(pixelDrawn(0.85, 0.5))}), "pixels drawn at stroke end region");
+ assert(await evaluate("return " + ${JSON.stringify(pixelDrawn(0.15, 0.5))}), "pixels drawn at stroke start region");
+ assert(await evaluate("return " + ${JSON.stringify(pixelDrawn(0.5, 0.5))}), "pixels drawn at stroke midpoint");
+ assert(await evaluate("return " + ${JSON.stringify(pixelDrawn(0.85, 0.5))}), "pixels drawn at stroke end region");
/* Verify the last recorded point is near the end of the stroke. */
- const lastPoint = await js("return window.__fixtureState.canvasLastPoint");
- const lastFrac = lastPoint.x / await js("return document.querySelector('#draw-canvas').width");
+ const lastPoint = await evaluate("return window.__fixtureState.canvasLastPoint");
+ const lastFrac = lastPoint.x / await evaluate("return document.querySelector('#draw-canvas').width");
assert(lastFrac > 0.8, "canvas last point x is near stroke end");
`),
},
@@ -64,18 +64,18 @@ export const canvasCases = [
${canvasSetup()}
/* Stroke 1: horizontal line in the upper third. */
- await dragMouse([drawAt(0.1, 0.25), drawAt(0.5, 0.25), drawAt(0.9, 0.25)], { delayMs: 15 });
+ await drag([drawAt(0.1, 0.25), drawAt(0.5, 0.25), drawAt(0.9, 0.25)], { delay: 15 });
await waitForJsValue("window.__fixtureState.canvasStrokes", 1, "first stroke registered");
- assert(await js("return " + ${JSON.stringify(pixelDrawn(0.5, 0.25))}), "pixels drawn on first stroke path");
+ assert(await evaluate("return " + ${JSON.stringify(pixelDrawn(0.5, 0.25))}), "pixels drawn on first stroke path");
/* Stroke 2: horizontal line in the lower third. */
- await wait(0.1);
- await dragMouse([drawAt(0.1, 0.75), drawAt(0.5, 0.75), drawAt(0.9, 0.75)], { delayMs: 15 });
+ await waitForTimeout(100);
+ await drag([drawAt(0.1, 0.75), drawAt(0.5, 0.75), drawAt(0.9, 0.75)], { delay: 15 });
await waitForJsValue("window.__fixtureState.canvasStrokes", 2, "second stroke registered");
await waitForJsCondition("window.__fixtureState.canvasPoints >= 6", "two strokes have at least 6 points total");
/* Verify pixels on second stroke — check a small area around the expected point. */
- const secondStrokeFound = await js(\`(() => {
+ const secondStrokeFound = await evaluate(\`(() => {
const c = document.querySelector("#draw-canvas");
const ctx = c.getContext("2d");
const cx = Math.round(0.5 * c.width);
@@ -89,7 +89,7 @@ export const canvasCases = [
assert(secondStrokeFound, "pixels drawn on second stroke path");
/* Verify a point between the strokes has no pixels (strokes don't bleed). */
- const gapAlpha = await js(
+ const gapAlpha = await evaluate(
"return document.querySelector('#draw-canvas').getContext('2d').getImageData(" +
"Math.round(document.querySelector('#draw-canvas').width / 2), " +
"Math.round(document.querySelector('#draw-canvas').height / 2), 1, 1).data[3]"
@@ -97,10 +97,10 @@ export const canvasCases = [
assertEqual(gapAlpha, 0, "no pixels between the two strokes at the gap");
/* Stroke 3: vertical line. */
- await wait(0.1);
- await dragMouse([drawAt(0.3, 0.1), drawAt(0.3, 0.5), drawAt(0.3, 0.9)], { delayMs: 15 });
+ await waitForTimeout(100);
+ await drag([drawAt(0.3, 0.1), drawAt(0.3, 0.5), drawAt(0.3, 0.9)], { delay: 15 });
await waitForJsValue("window.__fixtureState.canvasStrokes", 3, "third stroke registered");
- assert(await js("return " + ${JSON.stringify(pixelDrawn(0.3, 0.5))}), "pixels drawn on vertical stroke");
+ assert(await evaluate("return " + ${JSON.stringify(pixelDrawn(0.3, 0.5))}), "pixels drawn on vertical stroke");
`),
},
{
@@ -109,24 +109,24 @@ export const canvasCases = [
${canvasSetup()}
/* Draw a zigzag with 5 points: left → right-up → left-down → right-up → right. */
- await dragMouse(
+ await drag(
[drawAt(0.08, 0.5), drawAt(0.3, 0.17), drawAt(0.5, 0.83), drawAt(0.75, 0.17), drawAt(0.93, 0.5)],
- { delayMs: 15 }
+ { delay: 15 }
);
await waitForJsValue("window.__fixtureState.canvasStrokes", 1, "zigzag is a single stroke");
await waitForJsCondition("window.__fixtureState.canvasPoints >= 5", "zigzag has at least 5 points");
/* Verify pixels at multiple segments of the zigzag path. */
- assert(await js("return " + ${JSON.stringify(pixelDrawn(0.08, 0.5))}), "pixels at zigzag start");
- assert(await js("return " + ${JSON.stringify(pixelDrawn(0.3, 0.17))}), "pixels at zigzag peak 1");
- assert(await js("return " + ${JSON.stringify(pixelDrawn(0.5, 0.83))}), "pixels at zigzag valley");
- assert(await js("return " + ${JSON.stringify(pixelDrawn(0.75, 0.17))}), "pixels at zigzag peak 2");
- assert(await js("return " + ${JSON.stringify(pixelDrawn(0.93, 0.5))}), "pixels at zigzag end");
+ assert(await evaluate("return " + ${JSON.stringify(pixelDrawn(0.08, 0.5))}), "pixels at zigzag start");
+ assert(await evaluate("return " + ${JSON.stringify(pixelDrawn(0.3, 0.17))}), "pixels at zigzag peak 1");
+ assert(await evaluate("return " + ${JSON.stringify(pixelDrawn(0.5, 0.83))}), "pixels at zigzag valley");
+ assert(await evaluate("return " + ${JSON.stringify(pixelDrawn(0.75, 0.17))}), "pixels at zigzag peak 2");
+ assert(await evaluate("return " + ${JSON.stringify(pixelDrawn(0.93, 0.5))}), "pixels at zigzag end");
/* Verify drawing is complete. */
assertEqual(
- await js("return window.__fixtureState.canvasDrawing"),
+ await evaluate("return window.__fixtureState.canvasDrawing"),
false,
"zigzag drawing state is complete"
);
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/environment.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/environment.mjs
index 4121755..3e4d88c 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/environment.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/environment.mjs
@@ -43,12 +43,12 @@ export function environmentCase() {
cliLog(JSON.stringify({ capabilityWarning: { method: "Browser.getVersion", message: error?.message || String(error) } }));
}
- await fillInput("#text-input", "dirty", { timeout: 3 });
- assertEqual(await js("return document.querySelector('#text-input').value"), "dirty", "environment can dirty fixture state");
+ await fill("#text-input", "dirty", { timeout: 3000 });
+ assertEqual(await evaluate("return document.querySelector('#text-input').value"), "dirty", "environment can dirty fixture state");
home = await resetHome();
- assertEqual(await js("return document.querySelector('#text-input').value"), "initial", "resetHome restores deterministic fixture state");
+ assertEqual(await evaluate("return document.querySelector('#text-input').value"), "initial", "resetHome restores deterministic fixture state");
- const envShot = await captureScreenshot(environmentScreenshotPath, { full: false });
+ const envShot = await screenshot({ path: environmentScreenshotPath, fullPage: false });
assertEqual(envShot, environmentScreenshotPath, "environment screenshot uses artifact path");
const envShotStat = await stat(envShot);
assert(envShotStat.size > 0, "environment screenshot artifact is non-empty");
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs
index f028249..a7a1b60 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs
@@ -16,36 +16,34 @@ export function helperSurfaceCase() {
"switchTab",
"openOrReuseTab",
"closeTab",
- "gotoUrl",
- "gotoAndWait",
+ "goto",
"ensureRealTab",
"iframeTarget",
"snapshot",
"snapshotRaw",
"snapshotText",
- "captureScreenshot",
+ "screenshot",
"elementCenter",
"drainEvents",
"click",
- "doubleClick",
+ "dblclick",
"hover",
- "dragMouse",
+ "drag",
"scroll",
"scrollBy",
"scrollToBottomUntil",
- "pressKey",
- "typeText",
- "fillInput",
+ "press",
+ "insertText",
+ "fill",
"dispatchKey",
- "uploadFile",
- "wait",
- "waitForLoad",
- "waitForElement",
- "waitForNetworkIdle",
+ "setInputFiles",
+ "waitForTimeout",
+ "waitForLoadState",
+ "waitForSelector",
"serverFetch",
"browserFetch",
"cdp",
- "js",
+ "evaluate",
"help",
];
for (const name of expectedHelpers) {
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/interactions.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/interactions.mjs
index 2b3219e..62e5867 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/interactions.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/interactions.mjs
@@ -8,7 +8,7 @@ export const interactionsCases = [
in the ego-lite browser. Simulate the full pointer event lifecycle via
JS to verify the fixture handlers and state tracking work correctly. */
- const pointerResult = await js(\`(() => {
+ const pointerResult = await evaluate(\`(() => {
const area = document.querySelector("#pointer-area");
const rect = area.getBoundingClientRect();
const cx = rect.left + rect.width / 2;
@@ -45,7 +45,7 @@ export const interactionsCases = [
/* Verify that pressure values are tracked correctly across different
pointer event phases (hover=0, active=0.5). */
- const pressureResult = await js(\`(() => {
+ const pressureResult = await evaluate(\`(() => {
const area = document.querySelector("#pointer-area");
const rect = area.getBoundingClientRect();
const cx = rect.left + rect.width / 2;
@@ -75,7 +75,7 @@ export const interactionsCases = [
Simulate the full event sequence via JS to verify the fixture handlers
and state tracking work correctly. */
- const dndResult = await js(\`(() => {
+ const dndResult = await evaluate(\`(() => {
const source = document.querySelector("#dnd-source");
const target = document.querySelector("#dnd-target");
const dt = new DataTransfer();
@@ -119,7 +119,7 @@ export const interactionsCases = [
/* Simulate a cancelled drag: dragstart fires but no drop target receives
the drop event, then dragend fires. */
- await js(\`(() => {
+ await evaluate(\`(() => {
const source = document.querySelector("#dnd-source");
const dt = new DataTransfer();
source.dispatchEvent(new DragEvent("dragstart", {
@@ -131,11 +131,11 @@ export const interactionsCases = [
})()\`);
assertEqual(
- await js("return window.__fixtureState.dndDropped"),
+ await evaluate("return window.__fixtureState.dndDropped"),
false,
"cancelled drag leaves dndDropped as false"
);
- const statusText = await js("return document.querySelector('#dnd-status').textContent");
+ const statusText = await evaluate("return document.querySelector('#dnd-status').textContent");
assertIncludes(statusText, "cancelled", "dnd status shows drag cancelled");
`),
},
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/keyboard-regression.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/keyboard-regression.mjs
index 6d44b26..338d91f 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/keyboard-regression.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/keyboard-regression.mjs
@@ -3,48 +3,48 @@ export function keyboardRegressionCase() {
await useOrCreateTaskSpace(taskName);
await resetHome();
- /* Issue 1: fillInput on type=email replaces the prior value without crashing.
+ /* Issue 1: fill on type=email replaces the prior value without crashing.
Before the fix, clearFirst's setSelectionRange threw InvalidStateError on
- type=email/number inputs and the whole fillInput rejected, writing nothing. */
- await js("document.querySelector('#email-input').value = '[email protected]'; window.__fixtureState.valueEvents['email-input'] = []; return true;");
- await fillInput("#email-input", "[email protected]", { timeout: 3 });
- const emailValue = await js("return document.querySelector('#email-input').value");
- assertEqual(emailValue, "[email protected]", "fillInput replaces type=email value (Issue 1)");
- const emailEvents = await js("return (window.__fixtureState.valueEvents['email-input'] || []).join(',')");
- assertIncludes(emailEvents, "input", "fillInput fires input on type=email (Issue 1)");
- assertIncludes(emailEvents, "change", "fillInput fires change on type=email (Issue 1)");
+ type=email/number inputs and the whole fill rejected, writing nothing. */
+ await evaluate("document.querySelector('#email-input').value = '[email protected]'; window.__fixtureState.valueEvents['email-input'] = []; return true;");
+ await fill("#email-input", "[email protected]", { timeout: 3000 });
+ const emailValue = await evaluate("return document.querySelector('#email-input').value");
+ assertEqual(emailValue, "[email protected]", "fill replaces type=email value (Issue 1)");
+ const emailEvents = await evaluate("return (window.__fixtureState.valueEvents['email-input'] || []).join(',')");
+ assertIncludes(emailEvents, "input", "fill fires input on type=email (Issue 1)");
+ assertIncludes(emailEvents, "change", "fill fires change on type=email (Issue 1)");
/* Issue 1: same setSelectionRange crash on type=number. */
- await js("document.querySelector('#number-input').value = '123'; return true;");
- await fillInput("#number-input", "456", { timeout: 3 });
- const numberValue = await js("return document.querySelector('#number-input').value");
- assertEqual(numberValue, "456", "fillInput replaces type=number value (Issue 1)");
+ await evaluate("document.querySelector('#number-input').value = '123'; return true;");
+ await fill("#number-input", "456", { timeout: 3000 });
+ const numberValue = await evaluate("return document.querySelector('#number-input').value");
+ assertEqual(numberValue, "456", "fill replaces type=number value (Issue 1)");
/* Issue 2: non-bare selectors resolve through the unified element-resolver.
Before the fix, the CSS path fed 'xpath=...' straight into querySelector
and threw SyntaxError. */
- await fillInput('xpath=//input[@id="text-input"]', "via-xpath", { timeout: 3 });
- const xpathValue = await js("return document.querySelector('#text-input').value");
- assertEqual(xpathValue, "via-xpath", "fillInput resolves xpath= selector (Issue 2)");
+ await fill('xpath=//input[@id="text-input"]', "via-xpath", { timeout: 3000 });
+ const xpathValue = await evaluate("return document.querySelector('#text-input').value");
+ assertEqual(xpathValue, "via-xpath", "fill resolves xpath= selector (Issue 2)");
/* Issue 2: dispatchKey shares the same resolver path. */
- await js("window.__fixtureState.keys = []; return true;");
+ await evaluate("window.__fixtureState.keys = []; return true;");
await dispatchKey('xpath=//input[@id="text-input"]', "Enter", "keydown");
- const keys = await js("return window.__fixtureState.keys.join(',')");
+ const keys = await evaluate("return window.__fixtureState.keys.join(',')");
assertIncludes(keys, "Enter", "dispatchKey resolves xpath= selector (Issue 2)");
- /* Issue 2: uploadFile shares the same resolver path (the pilot covered
- fillInput/dispatchKey but left uploadFile out). */
- await uploadFile('xpath=//input[@id="file-input"]', uploadPath);
- const xpathFile = await js("return Array.from(document.querySelector('#file-input').files).map((file) => file.name).join(',')");
- assertEqual(xpathFile, "fixture-upload.txt", "uploadFile resolves xpath= selector (Issue 2)");
+ /* Issue 2: setInputFiles shares the same resolver path (the pilot covered
+ fill/dispatchKey but left setInputFiles out). */
+ await setInputFiles('xpath=//input[@id="file-input"]', uploadPath);
+ const xpathFile = await evaluate("return Array.from(document.querySelector('#file-input').files).map((file) => file.name).join(',')");
+ assertEqual(xpathFile, "fixture-upload.txt", "setInputFiles resolves xpath= selector (Issue 2)");
- /* fillInput must persist on a react-style controlled input, whose native
+ /* fill must persist on a react-style controlled input, whose native
value-setter writeback fights synthetic value changes. */
- await fillInput("#controlled-input", "hello-react", { timeout: 3 });
- const controlledValue = await js("return document.querySelector('#controlled-input').value");
- assertEqual(controlledValue, "hello-react", "fillInput persists value on a react-style controlled input");
- const controlledState = await js("return document.querySelector('#controlled-state').textContent");
+ await fill("#controlled-input", "hello-react", { timeout: 3000 });
+ const controlledValue = await evaluate("return document.querySelector('#controlled-input').value");
+ assertEqual(controlledValue, "hello-react", "fill persists value on a react-style controlled input");
+ const controlledState = await evaluate("return document.querySelector('#controlled-state').textContent");
assert(controlledState.startsWith("hello-react"), "controlled state mirror reflects the filled value");
`;
}
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/keyboard.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/keyboard.mjs
index 573ce92..f4cdb53 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/keyboard.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/keyboard.mjs
@@ -3,67 +3,66 @@ export function keyboardCase() {
await useOrCreateTaskSpace(taskName);
await resetHome();
- await fillInput("#text-input", "filled", { timeout: 3 });
- let value = await js("return document.querySelector('#text-input').value");
- assertEqual(value, "filled", "fillInput writes text");
+ await fill("#text-input", "filled", { timeout: 3000 });
+ let value = await evaluate("return document.querySelector('#text-input').value");
+ assertEqual(value, "filled", "fill writes text");
- await fillInput("loc=css:#text-area", "area text", { timeout: 3 });
- const areaValue = await js("return document.querySelector('#text-area').value");
- assertEqual(areaValue, "area text", "fillInput supports textarea through loc=css");
+ await fill("loc=css:#text-area", "area text", { timeout: 3000 });
+ const areaValue = await evaluate("return document.querySelector('#text-area').value");
+ assertEqual(areaValue, "area text", "fill supports textarea through loc=css");
- await js("const el = document.querySelector('#append-input'); el.focus(); el.setSelectionRange(el.value.length, el.value.length); return el.value");
- await fillInput("#append-input", "-suffix", { clearFirst: false, timeout: 3 });
- const appended = await js("return document.querySelector('#append-input').value");
- assertEqual(appended, "base-suffix", "fillInput clearFirst:false preserves existing input value");
+ await evaluate("const el = document.querySelector('#append-input'); el.focus(); el.setSelectionRange(el.value.length, el.value.length); return el.value");
+ await fill("#append-input", "-suffix", { clearFirst: false, timeout: 3 });
+ const appended = await evaluate("return document.querySelector('#append-input').value");
+ assertEqual(appended, "base-suffix", "fill clearFirst:false preserves existing input value");
- await js("return document.querySelector('#text-input').focus()");
- await typeText(" text");
- value = await js("return document.querySelector('#text-input').value");
- assertEqual(value, "filled text", "typeText appends focused text");
+ await evaluate("return document.querySelector('#text-input').focus()");
+ await insertText(" text");
+ value = await evaluate("return document.querySelector('#text-input').value");
+ assertEqual(value, "filled text", "insertText appends focused text");
- await fillInput("#text-input", "abc", { timeout: 3 });
- await js("const el = document.querySelector('#text-input'); el.focus(); el.setSelectionRange(el.value.length, el.value.length); return el.value");
- await pressKey("Backspace");
+ await fill("#text-input", "abc", { timeout: 3000 });
+ await evaluate("const el = document.querySelector('#text-input'); el.focus(); el.setSelectionRange(el.value.length, el.value.length); return el.value");
+ await press("Backspace");
await waitForJsValue(
"document.querySelector('#text-input').value",
"ab",
- "pressKey Backspace edits the focused input",
+ "press Backspace edits the focused input",
"window.__fixtureState.keyEvents"
);
- const activeAfterPress = await js("return document.activeElement?.id || ''");
- assertEqual(activeAfterPress, "text-input", "pressKey keeps the focused input active");
+ const activeAfterPress = await evaluate("return document.activeElement?.id || ''");
+ assertEqual(activeAfterPress, "text-input", "press keeps the focused input active");
await dispatchKey("#text-input", "Escape", "keydown");
- let keys = await js("return window.__fixtureState.keys.join(',')");
+ let keys = await evaluate("return window.__fixtureState.keys.join(',')");
assertIncludes(keys, "Escape", "dispatchKey dispatches synthetic keyboard input");
- await fillInput("#text-input", "select me", { timeout: 3 });
- const selectAllModifier = process.platform === "darwin" ? 4 : 2;
- await pressKey("a", selectAllModifier);
- await typeText("selected");
+ await fill("#text-input", "select me", { timeout: 3000 });
+ await press("ControlOrMeta+a");
+ await insertText("selected");
await waitForJsValue(
"document.querySelector('#text-input').value",
"selected",
- "pressKey supports platform select-all modifiers"
+ "press supports platform select-all modifiers"
);
- await uploadFile("#file-input", uploadPath);
- let fileName = await js("return Array.from(document.querySelector('#file-input').files).map((file) => file.name).join(',')");
- assertEqual(fileName, "fixture-upload.txt", "uploadFile attaches a single file");
+ await setInputFiles("#file-input", uploadPath);
+ let fileName = await evaluate("return Array.from(document.querySelector('#file-input').files).map((file) => file.name).join(',')");
+ assertEqual(fileName, "fixture-upload.txt", "setInputFiles attaches a single file");
- await uploadFile("#file-input", [uploadPath, uploadPathTwo]);
- fileName = await js("return Array.from(document.querySelector('#file-input').files).map((file) => file.name).join(',')");
- assertEqual(fileName, "fixture-upload.txt,fixture-upload-two.txt", "uploadFile attaches multiple files");
+ await setInputFiles("#file-input", [uploadPath, uploadPathTwo]);
+ fileName = await evaluate("return Array.from(document.querySelector('#file-input').files).map((file) => file.name).join(',')");
+ assertEqual(fileName, "fixture-upload.txt,fixture-upload-two.txt", "setInputFiles attaches multiple files");
await assertRejects(
- () => fillInput("#missing-input", "nope", { timeout: 0.2 }),
+ () => fill("#missing-input", "nope", { timeout: 200 }),
"element not found",
- "fillInput reports missing elements"
+ "fill reports missing elements"
);
await assertRejects(
- () => uploadFile("#missing-file-input", uploadPath),
+ () => setInputFiles("#missing-file-input", uploadPath),
"Element not found",
- "uploadFile reports missing file inputs"
+ "setInputFiles reports missing file inputs"
);
await assertRejects(
() => dispatchKey("#missing-input", "Enter"),
@@ -74,18 +73,18 @@ export function keyboardCase() {
/* contentEditable typing */
cliLog(JSON.stringify({ keyboardStep: "contentEditable" }));
await click("#rich-editor");
- await js("document.querySelector('#rich-editor').focus(); document.querySelector('#rich-editor').textContent = ''; return true;");
- await typeText("hello world");
- const editorText = await js("return document.querySelector('#rich-editor').textContent");
- assertIncludes(editorText, "hello world", "typeText inserts text into contentEditable element");
+ await evaluate("document.querySelector('#rich-editor').focus(); document.querySelector('#rich-editor').textContent = ''; return true;");
+ await insertText("hello world");
+ const editorText = await evaluate("return document.querySelector('#rich-editor').textContent");
+ assertIncludes(editorText, "hello world", "insertText inserts text into contentEditable element");
/* rapid Backspace sequence */
cliLog(JSON.stringify({ keyboardStep: "rapid backspace" }));
- await fillInput("#text-input", "test", { timeout: 3 });
- await js("const el = document.querySelector('#text-input'); el.focus(); el.setSelectionRange(el.value.length, el.value.length); return el.value");
- await pressKey("Backspace");
- await pressKey("Backspace");
- await pressKey("Backspace");
+ await fill("#text-input", "test", { timeout: 3000 });
+ await evaluate("const el = document.querySelector('#text-input'); el.focus(); el.setSelectionRange(el.value.length, el.value.length); return el.value");
+ await press("Backspace");
+ await press("Backspace");
+ await press("Backspace");
await waitForJsValue(
"document.querySelector('#text-input').value",
"t",
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/navigation.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/navigation.mjs
index 0044220..6af39f4 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/navigation.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/navigation.mjs
@@ -22,7 +22,7 @@ export function navigationCase() {
const realTabListed = (await listTabs()).some((t) => t.targetId === real.targetId);
assert(realTabListed, "ensureRealTab target appears in listTabs");
- const reused = await openOrReuseTab(baseUrl + "/", { wait: true, timeout: 10 });
+ const reused = await openOrReuseTab(baseUrl + "/", { wait: true, timeout: 10000 });
assertEqual(reused.reused, true, "openOrReuseTab reuses exact home URL");
const byOrigin = await openOrReuseTab(baseUrl + "/not-opened", {
@@ -46,13 +46,13 @@ export function navigationCase() {
const secondary = await openOrReuseTab(baseUrl + "/secondary", {
wait: true,
- timeout: 10,
+ timeout: 10000,
});
await switchTab(secondary);
- assert(await waitForLoad({ timeout: 10 }), "secondary tab loads before target-id evaluation");
- const secondaryTitleViaTarget = await js("return document.title", secondary.targetId);
+ assert(await waitForLoadState("load", { timeout: 10000 }), "secondary tab loads before target-id evaluation");
+ const secondaryTitleViaTarget = await evaluate("return document.title", secondary.targetId);
assertEqual(secondaryTitleViaTarget, "ego-lite secondary", "js evaluates against explicit target id");
- const homeTitleViaTarget = await js("return document.title", home.targetId);
+ const homeTitleViaTarget = await evaluate("return document.title", home.targetId);
assertEqual(homeTitleViaTarget, "ego-lite helper e2e", "js target id leaves current tab independent");
const secondaryByIncludes = await openOrReuseTab("/secondary", {
@@ -70,7 +70,7 @@ export function navigationCase() {
const closeCurrent = await openOrReuseTab(baseUrl + "/secondary?close=current", {
wait: true,
- timeout: 10,
+ timeout: 10000,
});
await switchTab(closeCurrent);
const currentClosedId = await closeTab();
@@ -86,19 +86,19 @@ export function navigationCase() {
"closeTab validates empty target id"
);
- await gotoUrl(baseUrl + "/nav-target");
- assert(await waitForLoad({ timeout: 10 }), "waitForLoad observes gotoUrl navigation");
+ await goto(baseUrl + "/nav-target", { waitUntil: "commit" });
+ assert(await waitForLoadState("load", { timeout: 10000 }), "waitForLoadState observes goto navigation");
const navInfo = await pageInfo();
- assertEqual(navInfo.title, "ego-lite nav target", "gotoUrl navigates current tab");
+ assertEqual(navInfo.title, "ego-lite nav target", "goto navigates current tab");
- const noWaitNav = await gotoAndWait(baseUrl + "/nav-target?no-wait=1", {
- wait: false,
+ const noWaitNav = await goto(baseUrl + "/nav-target?no-wait=1", {
+ waitUntil: "commit",
});
- assertEqual(noWaitNav.loaded, false, "gotoAndWait supports wait:false");
- assert(await waitForLoad({ timeout: 10 }), "waitForLoad can follow wait:false navigation");
+ assertEqual(noWaitNav.loaded, false, "goto supports waitUntil:commit");
+ assert(await waitForLoadState("load", { timeout: 10000 }), "waitForLoadState can follow waitUntil:commit navigation");
- const nav = await gotoAndWait(baseUrl + "/", { timeout: 10, settle: 0.1 });
- assert(nav.loaded, "gotoAndWait returns loaded true");
+ const nav = await goto(baseUrl + "/", { timeout: 10000, settle: 100 });
+ assert(nav.loaded, "goto returns loaded true");
const frame = await iframeTarget("/frame.html");
assert(frame === null || (typeof frame === "string" && frame.length > 0), "iframeTarget returns a non-empty session id or null");
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/observation.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/observation.mjs
index 3b3f5b6..c680fe7 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/observation.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/observation.mjs
@@ -82,28 +82,28 @@ export function observationCase() {
"elementCenter reports missing elements"
);
- const screenshotPath = await captureScreenshot(undefined, { full: false });
+ const screenshotPath = await screenshot({ path: undefined, fullPage: false });
const screenshotStat = await stat(screenshotPath);
- assert(screenshotStat.size > 100, "captureScreenshot writes a non-trivial png");
+ assert(screenshotStat.size > 100, "screenshot writes a non-trivial png");
const screenshotBuf = await readFile(screenshotPath);
assertEqual(screenshotBuf[0], 137, "screenshot starts with PNG magic byte 137");
assertEqual(screenshotBuf[1], 80, "screenshot has PNG header byte P (80)");
- const explicitPath = await captureScreenshot(explicitScreenshotPath, { full: false });
- assertEqual(explicitPath, explicitScreenshotPath, "captureScreenshot returns explicit path");
+ const explicitPath = await screenshot({ path: explicitScreenshotPath, fullPage: false });
+ assertEqual(explicitPath, explicitScreenshotPath, "screenshot returns explicit path");
const explicitStat = await stat(explicitPath);
- assert(explicitStat.size > 0, "captureScreenshot writes explicit path");
+ assert(explicitStat.size > 0, "screenshot writes explicit path");
- const fullScreenshotPath = await captureScreenshot(undefined, { full: true });
+ const fullScreenshotPath = await screenshot({ path: undefined, fullPage: true });
const fullScreenshotStat = await stat(fullScreenshotPath);
- assert(fullScreenshotStat.size > 0, "captureScreenshot supports full page");
+ assert(fullScreenshotStat.size > 0, "screenshot supports full page");
- const rawScreenshotPath = await captureScreenshot(undefined, {
+ const rawScreenshotPath = await screenshot({ path: undefined,
raw: true,
clip: { x: 0, y: 0, width: 120, height: 120, scale: 1 },
});
const rawScreenshotStat = await stat(rawScreenshotPath);
- assert(rawScreenshotStat.size > 0, "captureScreenshot supports raw clips");
+ assert(rawScreenshotStat.size > 0, "screenshot supports raw clips");
await cdp("Network.enable");
await browserFetch("/api/text", { timeout: 5 });
@@ -115,13 +115,13 @@ export function observationCase() {
/* dynamic DOM — add element, verify snapshot picks it up */
cliLog(JSON.stringify({ observationStep: "dynamic DOM" }));
await click("#remove-element");
- await wait(0.1);
+ await waitForTimeout(100);
const textBefore = await snapshotText({ scope: "full_page" });
assert(!String(textBefore).includes("Dynamic!"), "snapshot text does not contain dynamic element before creation");
await click("#add-element");
- await waitForElement("#dynamic-element", { timeout: 3, visible: true });
- await wait(0.2);
+ await waitForSelector("#dynamic-element", { timeout: 3000, state: "visible" });
+ await waitForTimeout(200);
const textAfter = await snapshotText({ scope: "full_page" });
assertIncludes(String(textAfter), "Dynamic!", "snapshot text includes dynamically created element");
@@ -129,13 +129,13 @@ export function observationCase() {
cliLog(JSON.stringify({ observationStep: "iframe" }));
const frameTarget = await iframeTarget("/frame.html");
if (frameTarget) {
- const iframeMarkerText = await js(
+ const iframeMarkerText = await evaluate(
"return document.querySelector('#iframe-marker')?.textContent",
frameTarget
);
assertEqual(iframeMarkerText, "iframe target", "js evaluates inside iframe using targetId");
- const iframeTitle = await js("return document.title", frameTarget);
+ const iframeTitle = await evaluate("return document.title", frameTarget);
assertEqual(iframeTitle, "ego-lite iframe", "js reads iframe page title via targetId");
} else {
cliLog(JSON.stringify({ iframeWarning: "iframe target not available, skipping iframe tests" }));
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/pointer.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/pointer.mjs
index 0759203..785ade8 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/pointer.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/pointer.mjs
@@ -4,7 +4,7 @@ export function pointerClickCase() {
await resetHome();
cliLog(JSON.stringify({ pointerStep: "click ready" }));
- assertEqual(await js("return window.__fixtureState.clicks"), 0, "click fixture starts at zero");
+ assertEqual(await evaluate("return window.__fixtureState.clicks"), 0, "click fixture starts at zero");
await click("#click-button", { label: "click helper e2e" });
await waitForJsValue(
"window.__fixtureState.clicks",
@@ -21,7 +21,7 @@ export function pointerClickCase() {
await click("xpath=//*[@id='click-button']");
await waitForJsValue("window.__fixtureState.clicks", 5, "click xpath fires a page click");
const buttonCenter = await elementCenter("#click-button");
- const hitElement = await js(
+ const hitElement = await evaluate(
"return document.elementFromPoint(" +
JSON.stringify(buttonCenter.x) +
"," +
@@ -37,16 +37,16 @@ export function pointerClickCase() {
await waitForJsValue("window.__fixtureState.clicks", 6, "click tuple coordinates fires a page click");
await click({ x: buttonCenter.x, y: buttonCenter.y });
await waitForJsValue("window.__fixtureState.clicks", 7, "click object coordinates fires a page click");
- await click("#click-button", { clicks: 2 });
+ await click("#click-button", { clickCount: 2 });
await waitForJsValue("window.__fixtureState.clicks", 8, "click count option fires a page click");
await waitForJsValue("window.__fixtureState.lastClickDetail", 2, "click count option sets DOM click detail");
- const doubleClicksBefore = await js("return window.__fixtureState.doubleClicks");
- await doubleClick("#click-button");
- await waitForJsValue("window.__fixtureState.clicks", 9, "doubleClick fires a page click");
- await waitForJsValue("window.__fixtureState.lastClickDetail", 2, "doubleClick sets DOM click detail");
+ const doubleClicksBefore = await evaluate("return window.__fixtureState.doubleClicks");
+ await dblclick("#click-button");
+ await waitForJsValue("window.__fixtureState.clicks", 9, "dblclick fires a page click");
+ await waitForJsValue("window.__fixtureState.lastClickDetail", 2, "dblclick sets DOM click detail");
await waitForJsCondition(
"window.__fixtureState.doubleClicks > " + JSON.stringify(doubleClicksBefore),
- "doubleClick fires a DOM dblclick"
+ "dblclick fires a DOM dblclick"
);
`;
}
@@ -57,16 +57,16 @@ export function pointerHoverDragCase() {
await resetHome();
cliLog(JSON.stringify({ pointerStep: "hover drag ready" }));
- await js("window.__fixtureState.hovered = false; return true;");
+ await evaluate("window.__fixtureState.hovered = false; return true;");
await hover("#hover-zone");
await waitForJsValue("window.__fixtureState.hovered", true, "hover css fires mouseover");
- await js("window.__fixtureState.hovered = false; return true;");
+ await evaluate("window.__fixtureState.hovered = false; return true;");
await hover({ selector: "#hover-zone" });
await waitForJsValue("window.__fixtureState.hovered", true, "hover selector object fires mouseover");
- await js("window.__fixtureState.dragged = false; return true;");
- await dragMouse(["#drag-source", "#drag-target"], { delayMs: 10 });
- await waitForJsValue("window.__fixtureState.dragged", true, "dragMouse fires drag source and target events");
+ await evaluate("window.__fixtureState.dragged = false; return true;");
+ await drag(["#drag-source", "#drag-target"], { delay: 10 });
+ await waitForJsValue("window.__fixtureState.dragged", true, "drag fires drag source and target events");
`;
}
@@ -76,15 +76,15 @@ export function scrollHelpersCase() {
await resetHome();
cliLog(JSON.stringify({ pointerStep: "scroll ready" }));
- await js(
+ await evaluate(
"const inner = document.querySelector('#inner-scroll');" +
"inner.scrollTop = 0;" +
"inner.scrollIntoView({ block: 'center', inline: 'nearest' });" +
"return true;"
);
- await wait(0.1);
+ await waitForTimeout(100);
const innerCenter = await elementCenter("#inner-scroll");
- const innerHit = await js(
+ const innerHit = await evaluate(
"const el = document.elementFromPoint(" +
JSON.stringify(innerCenter.x) +
"," +
@@ -105,7 +105,7 @@ export function scrollHelpersCase() {
}
await resetHome();
- const wheelPoint = await js(
+ const wheelPoint = await evaluate(
"const rect = document.querySelector('#scroll-area').getBoundingClientRect();" +
"return { x: Math.min(Math.max(rect.left + 20, 10), innerWidth - 10), y: Math.min(Math.max(rect.top + 20, 10), innerHeight - 10) };"
);
@@ -123,7 +123,7 @@ export function scrollHelpersCase() {
}
await resetHome();
- const objectWheelPoint = await js(
+ const objectWheelPoint = await evaluate(
"const rect = document.querySelector('#scroll-area').getBoundingClientRect();" +
"return { x: Math.min(Math.max(rect.left + 30, 10), innerWidth - 10), y: Math.min(Math.max(rect.top + 30, 10), innerHeight - 10) };"
);
@@ -191,9 +191,9 @@ export function pointerValidationCase() {
await resetHome();
await assertRejects(
- () => dragMouse(["#drag-source"]),
+ () => drag(["#drag-source"]),
"at least two points",
- "dragMouse validates minimum path length"
+ "drag validates minimum path length"
);
await assertRejects(
() => click({ x: "bad", y: 1 }),
@@ -206,9 +206,9 @@ export function pointerValidationCase() {
"click validates mouse buttons"
);
await assertRejects(
- () => dragMouse(["#drag-source", "#drag-target"], { button: "sideways" }),
+ () => drag(["#drag-source", "#drag-target"], { button: "sideways" }),
"unsupported mouse button",
- "dragMouse validates mouse buttons"
+ "drag validates mouse buttons"
);
await assertRejects(
() => scrollBy({ dy: "bad" }),
@@ -229,17 +229,17 @@ export function pointerInteractionRegressionCase() {
await resetHome();
cliLog(JSON.stringify({ pointerStep: "interaction regression ready" }));
- const rightClickBefore = await js("return window.__fixtureState.pointerEvents.length");
+ const rightClickBefore = await evaluate("return window.__fixtureState.pointerEvents.length");
await click("#context-menu-zone", { button: "right" });
- const rightClickAfter = await js("return window.__fixtureState.pointerEvents.length");
+ const rightClickAfter = await evaluate("return window.__fixtureState.pointerEvents.length");
assert(rightClickAfter > rightClickBefore, "click with button:right dispatches mouse events on the target");
- const rightMouseDown = await js(
+ const rightMouseDown = await evaluate(
"return window.__fixtureState.pointerEvents.some(function(e) { return e.type === 'mousedown' && e.target === 'context-menu-zone'; })"
);
assert(rightMouseDown, "right-click produces a mousedown event on the context-menu-zone");
await resetHome();
- const clicksBefore = await js("return window.__fixtureState.clicks");
+ const clicksBefore = await evaluate("return window.__fixtureState.clicks");
await click("#click-button");
await click("#click-button");
await click("#click-button");
@@ -252,7 +252,7 @@ export function pointerInteractionRegressionCase() {
"window.__fixtureState.pointerEvents"
);
- await js("document.querySelector('#checkbox').checked = false; window.__fixtureState.checkboxChecked = false; return true;");
+ await evaluate("document.querySelector('#checkbox').checked = false; window.__fixtureState.checkboxChecked = false; return true;");
await click("#checkbox");
await waitForJsValue("window.__fixtureState.checkboxChecked", true, "first click checks the checkbox");
await click("#checkbox");
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/runtime-regression.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/runtime-regression.mjs
index 0750817..a76fc44 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/runtime-regression.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/runtime-regression.mjs
@@ -3,22 +3,22 @@ export function runtimeRegressionCase() {
await useOrCreateTaskSpace(taskName);
await resetHome();
- /* Issue 2: waitForElement shares the unified resolver — xpath= must resolve a
+ /* Issue 2: waitForSelector shares the unified resolver — xpath= must resolve a
static element (official runtime.mjs only exercises CSS selectors here). */
assertEqual(
- await waitForElement('xpath=//button[@id="click-button"]', { timeout: 4 }),
+ await waitForSelector('xpath=//button[@id="click-button"]', { timeout: 4000 }),
true,
- "waitForElement resolves xpath= selector (Issue 2)"
+ "waitForSelector resolves xpath= selector (Issue 2)"
);
- /* Resolver failure classes on waitForElement: a permanent (ambiguous) selector
+ /* Resolver failure classes on waitForSelector: a permanent (ambiguous) selector
fails fast; a transient (missing) one polls until the timeout, then returns
false. Official only covers the happy path. */
const permStart = Date.now();
await assertRejects(
- () => waitForElement("loc=css:.duplicate-action", { timeout: 5 }),
+ () => waitForSelector("loc=css:.duplicate-action", { timeout: 5000 }),
"matched 2",
- "waitForElement throws on a permanent ambiguity error"
+ "waitForSelector throws on a permanent ambiguity error"
);
assert(
Date.now() - permStart < 2500,
@@ -27,9 +27,9 @@ export function runtimeRegressionCase() {
const missStart = Date.now();
assertEqual(
- await waitForElement("#no-such-element-xyz", { timeout: 1 }),
+ await waitForSelector("#no-such-element-xyz", { timeout: 1000 }),
false,
- "waitForElement returns false for a transient missing element"
+ "waitForSelector returns false for a transient missing element"
);
assert(
Date.now() - missStart >= 700,
@@ -39,13 +39,13 @@ export function runtimeRegressionCase() {
/* js runs in the page, not the heredoc: caller closure variables are NOT
captured. 'outer' is referenced only inside the serialized function. */
const outer = 100;
- const closureType = await js(function () {
+ const closureType = await evaluate(function () {
return typeof outer;
});
assertEqual(closureType, "undefined", "js does not capture caller closure variables");
/* js rejects invalid input types (neither string nor function). */
- await assertRejectsAny(() => js(123), "js rejects non-string/function input");
+ await assertRejectsAny(() => evaluate(123), "js rejects non-string/function input");
/* serverFetch returns the body and respects exact content length, including
lower boundary values (n=0, n=1) that were previously only tested in the
@@ -75,17 +75,17 @@ export function runtimeRegressionCase() {
"browserFetch reports 4xx HTTP errors"
);
- /* waitForLoad blocks until a slow-arriving document loads. Navigates away, so
+ /* waitForLoadState blocks until a slow-arriving document loads. Navigates away, so
keep this last. */
const slowStart = Date.now();
- await gotoUrl(baseUrl + "/slow-page?ms=1200");
+ await goto(baseUrl + "/slow-page?ms=1200", { waitUntil: "commit" });
assert(
- await waitForLoad({ timeout: 8 }),
- "waitForLoad resolves true once the slow document arrives"
+ await waitForLoadState("load", { timeout: 8000 }),
+ "waitForLoadState resolves true once the slow document arrives"
);
assert(
Date.now() - slowStart >= 1000,
- "waitForLoad blocks until the slow document loads"
+ "waitForLoadState blocks until the slow document loads"
);
`;
}
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/runtime.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/runtime.mjs
index a32da3c..5ac6f02 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/runtime.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/runtime.mjs
@@ -4,21 +4,21 @@ export function waitHelpersCase() {
await resetHome();
const waitedAt = Date.now();
- await wait(0.1);
- assert(Date.now() - waitedAt >= 50, "wait pauses for a measurable duration");
+ await waitForTimeout(100);
+ assert(Date.now() - waitedAt >= 50, "waitForTimeout pauses for a measurable duration");
assert(
- await waitForElement("#delayed", { timeout: 3, visible: true }),
- "waitForElement observes delayed visible element"
+ await waitForSelector("#delayed", { timeout: 3000, state: "visible" }),
+ "waitForSelector observes delayed visible element"
);
assertEqual(
- await waitForElement("#does-not-exist", { timeout: 0.2 }),
+ await waitForSelector("#does-not-exist", { timeout: 200 }),
false,
- "waitForElement returns false for missing elements"
+ "waitForSelector returns false for missing elements"
);
assertEqual(
- await waitForElement("#never-visible", { timeout: 0.4, visible: true }),
+ await waitForSelector("#never-visible", { timeout: 400, state: "visible" }),
false,
- "waitForElement visible:true rejects hidden elements"
+ "waitForSelector state:visible rejects hidden elements"
);
`;
}
@@ -99,7 +99,7 @@ export function cdpJsHelpCase() {
await resetHome();
await cdp("Network.enable");
- await js(
+ await evaluate(
"window.__slowText = '';" +
"fetch('/api/slow?ms=300&case=network-idle-' + Date.now())" +
".then((response) => response.text())" +
@@ -107,10 +107,10 @@ export function cdpJsHelpCase() {
"return true;"
);
assert(
- await waitForNetworkIdle({ timeout: 5, idleMs: 100 }),
- "waitForNetworkIdle waits for an in-flight slow fetch"
+ await waitForLoadState("networkidle", { timeout: 5000, idleMs: 100 }),
+ "waitForLoadState networkidle waits for an in-flight slow fetch"
);
- assertEqual(await js("return window.__slowText"), "slow fixture", "waitForNetworkIdle leaves the slow fetch complete");
+ assertEqual(await evaluate("return window.__slowText"), "slow fixture", "waitForLoadState networkidle leaves the slow fetch complete");
const evalResult = await cdp("Runtime.evaluate", {
expression: "document.title",
@@ -124,27 +124,27 @@ export function cdpJsHelpCase() {
"cdp reports unsupported methods"
);
- const title = await js("return document.title");
+ const title = await evaluate("return document.title");
assertEqual(title, "ego-lite helper e2e", "js returns evaluated value");
- const wrappedReturn = await js("const title = document.title; return title;");
+ const wrappedReturn = await evaluate("const title = document.title; return title;");
assertEqual(wrappedReturn, "ego-lite helper e2e", "js wraps top-level return statements");
- const arithmetic = await js("1 + 2");
+ const arithmetic = await evaluate("1 + 2");
assertEqual(arithmetic, 3, "js evaluates expression values");
- const titleFromFunction = await js(() => document.title);
+ const titleFromFunction = await evaluate(() => document.title);
assertEqual(titleFromFunction, "ego-lite helper e2e", "js supports function input");
await assertRejects(
- () => js("throw new Error('js boom')"),
+ () => evaluate("throw new Error('js boom')"),
"js boom",
"js reports page exceptions"
);
- const helpText = help("click", "fillInput");
+ const helpText = help("click", "fill");
assertIncludes(helpText, "click", "help returns helper documentation");
- assertIncludes(helpText, "fillInput", "help returns multiple helper docs");
+ assertIncludes(helpText, "fill", "help returns multiple helper docs");
const unknownHelp = help("missingHelperForE2E");
assertIncludes(unknownHelp, "Unknown helper", "help reports unknown helpers");
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/workflows.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/workflows.mjs
index 1ba982f..66545e6 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/workflows.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/workflows.mjs
@@ -17,7 +17,7 @@ export const workflowCases = [
/* Step 2: click the nav link to navigate within the current tab. */
await click("#nav-link");
- assert(await waitForLoad({ timeout: 10 }), "workflow: nav-target page loads");
+ assert(await waitForLoadState("load", { timeout: 10000 }), "workflow: nav-target page loads");
const navInfo = await pageInfo();
assertEqual(navInfo.title, "ego-lite nav target", "workflow: page title changes after navigation");
assertIncludes(navInfo.url, "/nav-target", "workflow: URL reflects nav-target");
@@ -25,11 +25,11 @@ export const workflowCases = [
/* Step 3: open a secondary page in a new tab. */
const secondary = await openOrReuseTab(baseUrl + "/secondary", {
wait: true,
- timeout: 10,
+ timeout: 10000,
});
assertEqual(secondary.reused, false, "workflow: secondary tab is new");
await switchTab(secondary);
- const secTitle = await js("return document.title");
+ const secTitle = await evaluate("return document.title");
assertEqual(secTitle, "ego-lite secondary", "workflow: secondary tab title is correct");
/* Step 4: switch back to the nav-target tab and verify its state persisted. */
@@ -37,12 +37,12 @@ export const workflowCases = [
const navTab = tabs.find((t) => String(t.url || "").includes("/nav-target"));
assert(navTab, "workflow: nav-target tab still exists in tab list");
await switchTab(navTab.targetId);
- const navTitleAfterSwitch = await js("return document.title");
+ const navTitleAfterSwitch = await evaluate("return document.title");
assertEqual(navTitleAfterSwitch, "ego-lite nav target", "workflow: nav-target title persists across tab switches");
- /* Step 5: navigate back home via gotoUrl and verify clean state. */
- await gotoUrl(baseUrl + "/");
- assert(await waitForLoad({ timeout: 10 }), "workflow: home page reloads");
+ /* Step 5: navigate back home via goto and verify clean state. */
+ await goto(baseUrl + "/", { waitUntil: "commit" });
+ assert(await waitForLoadState("load", { timeout: 10000 }), "workflow: home page reloads");
const backHomeInfo = await pageInfo();
assertEqual(backHomeInfo.title, "ego-lite helper e2e", "workflow: home title restored after multi-tab navigation");
@@ -55,7 +55,7 @@ export const workflowCases = [
do {
remaining = await listTabs({ includeChrome: false });
if (remaining.length < tabsBeforeClose) break;
- await wait(0.1);
+ await waitForTimeout(100);
} while (Date.now() < deadline);
assert(remaining.length < tabsBeforeClose, "workflow: tab count decreased after closing secondary");
@@ -68,47 +68,47 @@ export const workflowCases = [
name: "workflow form interaction chain",
body: homeCase(`
/* Step 1: fill a text input and verify the value. */
- await fillInput("#text-input", "hello", { timeout: 3 });
+ await fill("#text-input", "hello", { timeout: 3000 });
assertEqual(
- await js("return document.querySelector('#text-input').value"),
+ await evaluate("return document.querySelector('#text-input').value"),
"hello",
- "workflow: fillInput sets text value"
+ "workflow: fill sets text value"
);
- /* Step 2: append more text with typeText. */
+ /* Step 2: append more text with insertText. */
await click("#text-input");
- await typeText(" world");
+ await insertText(" world");
assertEqual(
- await js("return document.querySelector('#text-input').value"),
+ await evaluate("return document.querySelector('#text-input').value"),
"hello world",
- "workflow: typeText appends to existing value"
+ "workflow: insertText appends to existing value"
);
- /* Step 3: select-all then overwrite using fillInput (which clears first). */
- await fillInput("#text-input", "replaced", { timeout: 3 });
+ /* Step 3: select-all then overwrite using fill (which clears first). */
+ await fill("#text-input", "replaced", { timeout: 3000 });
assertEqual(
- await js("return document.querySelector('#text-input').value"),
+ await evaluate("return document.querySelector('#text-input').value"),
"replaced",
- "workflow: fillInput replaces entire value"
+ "workflow: fill replaces entire value"
);
/* Step 4: fill the textarea and verify independently. */
- await fillInput("#text-area", "area content", { timeout: 3 });
+ await fill("#text-area", "area content", { timeout: 3000 });
assertEqual(
- await js("return document.querySelector('#text-area').value"),
+ await evaluate("return document.querySelector('#text-area').value"),
"area content",
"workflow: textarea value set independently"
);
/* Text input should not have been affected by textarea fill. */
assertEqual(
- await js("return document.querySelector('#text-input').value"),
+ await evaluate("return document.querySelector('#text-input').value"),
"replaced",
"workflow: text input unchanged after textarea fill"
);
/* Step 5: toggle checkbox and verify state. */
assertEqual(
- await js("return window.__fixtureState.checkboxChecked"),
+ await evaluate("return window.__fixtureState.checkboxChecked"),
false,
"workflow: checkbox starts unchecked"
);
@@ -125,17 +125,17 @@ export const workflowCases = [
/* Step 7: interact with dynamic DOM — add element, verify, remove, verify. */
await click("#add-element");
- const appeared = await waitForElement("#dynamic-element", { timeout: 3, visible: true });
+ const appeared = await waitForSelector("#dynamic-element", { timeout: 3000, state: "visible" });
assertEqual(appeared, true, "workflow: dynamically added element becomes visible");
- const dynText = await js("return document.querySelector('#dynamic-element')?.textContent");
+ const dynText = await evaluate("return document.querySelector('#dynamic-element')?.textContent");
assertIncludes(dynText, "Dynamic", "workflow: dynamic element has expected text");
await click("#remove-element");
- const gone = await waitForElement("#dynamic-element", { timeout: 3 });
+ const gone = await waitForSelector("#dynamic-element", { timeout: 3000 });
assertEqual(gone, false, "workflow: dynamically removed element disappears");
/* Step 8: verify the click counter tracked only #click-button clicks (none in this workflow). */
- const totalClicks = await js("return window.__fixtureState.clicks");
+ const totalClicks = await evaluate("return window.__fixtureState.clicks");
assertEqual(totalClicks, 0, "workflow: click counter only tracks #click-button, not form interactions");
`),
},
@@ -159,7 +159,7 @@ export const workflowCases = [
/* Step 3: modify the DOM, then verify the snapshot reflects the new element. */
await click("#add-element");
- await waitForElement("#dynamic-element", { timeout: 3, visible: true });
+ await waitForSelector("#dynamic-element", { timeout: 3000, state: "visible" });
const textAfterAdd = await snapshotText({ scope: "full_page" });
assertIncludes(String(textAfterAdd), "Dynamic!", "workflow: snapshot text includes dynamic element after mutation");
@@ -170,16 +170,16 @@ export const workflowCases = [
/* Step 5: remove the dynamic element and verify the ref becomes stale. */
await click("#remove-element");
- await waitForElement("#dynamic-element", { timeout: 3 });
+ await waitForSelector("#dynamic-element", { timeout: 3000 });
// The dynamic element is gone; trying to click its stale ref should
// either fall back (if another element matches the role/name) or fail.
// We just verify the element is truly removed.
- const dynExists = await js("return !!document.querySelector('#dynamic-element')");
+ const dynExists = await evaluate("return !!document.querySelector('#dynamic-element')");
assertEqual(dynExists, false, "workflow: dynamic element removed from DOM");
/* Step 6: take a screenshot and verify the file is created. */
const screenshotPath = join(artifactDir, "workflow-shot.png");
- await captureScreenshot(screenshotPath);
+ await screenshot({ path: screenshotPath });
const screenshotStat = await stat(screenshotPath);
assert(screenshotStat.size > 0, "workflow: screenshot file is non-empty");
diff --git a/package/ego-browser/scripts/real-browser-e2e/preamble.mjs b/package/ego-browser/scripts/real-browser-e2e/preamble.mjs
index 512050f..3e3373e 100644
--- a/package/ego-browser/scripts/real-browser-e2e/preamble.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/preamble.mjs
@@ -129,16 +129,16 @@ async function waitForJsValue(
const deadline = Date.now() + 2000;
let last;
while (Date.now() <= deadline) {
- last = await js(expression);
+ last = await evaluate(expression);
if (last === expected) {
logAssertion("pass", message);
return last;
}
- await wait(0.05);
+ await waitForTimeout(50);
}
let detail = "";
if (debugExpression) {
- detail = "; debug=" + JSON.stringify(await js(debugExpression));
+ detail = "; debug=" + JSON.stringify(await evaluate(debugExpression));
}
logAssertion("fail", message, {
expected: formatAssertionValue(expected),
@@ -160,16 +160,16 @@ async function waitForJsCondition(expression, message, debugExpression = null) {
const deadline = Date.now() + 2000;
let last;
while (Date.now() <= deadline) {
- last = await js(expression);
+ last = await evaluate(expression);
if (last) {
logAssertion("pass", message);
return last;
}
- await wait(0.05);
+ await waitForTimeout(50);
}
let detail = "";
if (debugExpression) {
- detail = "; debug=" + JSON.stringify(await js(debugExpression));
+ detail = "; debug=" + JSON.stringify(await evaluate(debugExpression));
}
logAssertion("fail", message, {
actual: formatAssertionValue(last),
@@ -209,11 +209,11 @@ async function setStableViewport() {
deviceScaleFactor: 1,
mobile: false,
}).catch(() => {});
- await wait(0.1);
+ await waitForTimeout(100);
}
async function hitTestClickButton() {
- return js(
+ return evaluate(
"const el = document.querySelector('#click-button');" +
"if (!el) return '';" +
"const r = el.getBoundingClientRect();" +
@@ -237,15 +237,15 @@ async function resetHome() {
await closeFixtureTabs();
const tab = await openOrReuseTab(baseUrl + "/?e2e-reset=" + Date.now(), {
wait: true,
- timeout: 10,
+ timeout: 10000,
});
await switchTab(tab.targetId);
await setStableViewport();
- const nav = await gotoAndWait(baseUrl + "/", { timeout: 10 });
+ const nav = await goto(baseUrl + "/", { timeout: 10000 });
assert(nav.loaded, "home page loaded");
await setStableViewport();
assert(
- await waitForElement("#click-button", { timeout: 3, visible: true }),
+ await waitForSelector("#click-button", { timeout: 3000, state: "visible" }),
"home fixture click button is visible",
);
for (let i = 0; i < 10; i += 1) {
diff --git a/package/ego-browser/src/cdp-eval.test.mjs b/package/ego-browser/src/cdp-eval.test.mjs
index c2e8cb7..4f4db8c 100644
--- a/package/ego-browser/src/cdp-eval.test.mjs
+++ b/package/ego-browser/src/cdp-eval.test.mjs
@@ -5,7 +5,7 @@ import {
hasReturnStatement,
decodeUnserializableJsValue,
runtimeValue,
- js,
+ evaluate,
cdp,
} from "../dist/src/cdp-eval.js";
import { setOverrides } from "../dist/src/state.js";
@@ -318,10 +318,10 @@ test("cdp tracks Network domain state on enable", async () => {
});
/* ------------------------------------------------------------------ */
-/* js() — expression evaluation with auto-wrapping */
+/* evaluate() — expression evaluation with auto-wrapping */
/* ------------------------------------------------------------------ */
-test("js auto-wraps expressions with return in an IIFE", async () => {
+test("evaluate auto-wraps expressions with return in an IIFE", async () => {
let capturedExpression;
const restore = setOverrides({
cdpOverride: async (method, params) => {
@@ -333,7 +333,7 @@ test("js auto-wraps expressions with return in an IIFE", async () => {
},
});
try {
- const result = await js("return 42");
+ const result = await evaluate("return 42");
assert.equal(result, 42);
assert.match(capturedExpression, /^\(function\(\)\{/);
} finally {
@@ -341,7 +341,7 @@ test("js auto-wraps expressions with return in an IIFE", async () => {
}
});
-test("js passes plain expressions without IIFE wrapping", async () => {
+test("evaluate passes plain expressions without IIFE wrapping", async () => {
let capturedExpression;
const restore = setOverrides({
cdpOverride: async (method, params) => {
@@ -353,7 +353,7 @@ test("js passes plain expressions without IIFE wrapping", async () => {
},
});
try {
- const result = await js("1 + 2");
+ const result = await evaluate("1 + 2");
assert.equal(result, 3);
assert.equal(capturedExpression, "1 + 2");
} finally {
@@ -361,7 +361,7 @@ test("js passes plain expressions without IIFE wrapping", async () => {
}
});
-test("js does not wrap when expression already starts with paren", async () => {
+test("evaluate does not wrap when expression already starts with paren", async () => {
let capturedExpression;
const restore = setOverrides({
cdpOverride: async (method, params) => {
@@ -373,14 +373,14 @@ test("js does not wrap when expression already starts with paren", async () => {
},
});
try {
- await js("(function(){ return 10 })()");
+ await evaluate("(function(){ return 10 })()");
assert.equal(capturedExpression, "(function(){ return 10 })()");
} finally {
restore();
}
});
-test("js converts a function argument to a string call", async () => {
+test("evaluate converts a function argument to a string call", async () => {
let capturedExpression;
const restore = setOverrides({
cdpOverride: async (method, params) => {
@@ -392,7 +392,7 @@ test("js converts a function argument to a string call", async () => {
},
});
try {
- await js(function () {
+ await evaluate(function () {
return 1;
});
assert.match(capturedExpression, /^\(function\s*\(\)/);
@@ -402,18 +402,18 @@ test("js converts a function argument to a string call", async () => {
}
});
-test("js rejects non-string/non-function input", async () => {
+test("evaluate rejects non-string/non-function input", async () => {
await assert.rejects(
- () => js(123),
+ () => evaluate(123),
/expects a string expression or function/,
);
await assert.rejects(
- () => js(null),
+ () => evaluate(null),
/expects a string expression or function/,
);
});
-test("js propagates page exceptions", async () => {
+test("evaluate propagates page exceptions", async () => {
const restore = setOverrides({
cdpOverride: async (method, params) => {
if (method === "Runtime.evaluate") {
@@ -435,13 +435,13 @@ test("js propagates page exceptions", async () => {
},
});
try {
- await assert.rejects(() => js("x"), /ReferenceError/);
+ await assert.rejects(() => evaluate("x"), /ReferenceError/);
} finally {
restore();
}
});
-test("js attaches to a target session when targetId is given", async () => {
+test("evaluate attaches to a target session when targetId is given", async () => {
const calls = [];
const restore = setOverrides({
cdpOverride: async (method, params, sessionId) => {
@@ -456,7 +456,7 @@ test("js attaches to a target session when targetId is given", async () => {
},
});
try {
- const result = await js("document.title", "target-abc");
+ const result = await evaluate("document.title", "target-abc");
assert.equal(result, "iframe-result");
// First call should be attachToTarget, second should be evaluate with the session
assert.equal(calls[0][0], "Target.attachToTarget");
diff --git a/package/ego-browser/src/cdp-eval.ts b/package/ego-browser/src/cdp-eval.ts
index 141d730..c3f1e90 100644
--- a/package/ego-browser/src/cdp-eval.ts
+++ b/package/ego-browser/src/cdp-eval.ts
@@ -35,24 +35,24 @@ export async function cdp(method, params: any = {}, sessionId = undefined) {
* @param {string} [targetId] Optional target id to attach and evaluate in.
* @returns {Promise<any>} Runtime.evaluate return-by-value result.
*/
-export async function js(expression, targetId = undefined) {
+export async function evaluate(expression, targetId = undefined) {
if (typeof expression === "function") {
const source = expression.toString();
if (!hasWarnedAboutFunctionJs) {
hasWarnedAboutFunctionJs = true;
process.stderr.write(
- `[ego-browser] js() received a function and auto-wrapped it (${jsSnippet(source, 80)}).\n` +
- ` js() is a thin wrapper over CDP Runtime.evaluate; it takes a string expression,\n` +
+ `[ego-browser] evaluate() received a function and auto-wrapped it (${jsSnippet(source, 80)}).\n` +
+ ` evaluate() is a thin wrapper over CDP Runtime.evaluate; it takes a string expression,\n` +
` not a Puppeteer/Playwright-style callable. Auto-wrap does NOT capture closure\n` +
` variables and has NO args channel.\n` +
` Prefer:\n` +
- ` js(\`<expression>\`) // pure expression or explicit IIFE\n`,
+ ` evaluate(\`<expression>\`) // pure expression or explicit IIFE\n`,
);
}
expression = `(${source})()`;
} else if (typeof expression !== "string") {
throw new TypeError(
- `js() expects a string expression or function, got ${expression === null ? "null" : typeof expression}`,
+ `evaluate() expects a string expression or function, got ${expression === null ? "null" : typeof expression}`,
);
}
const sessionId = targetId
diff --git a/package/ego-browser/src/driver/files.ts b/package/ego-browser/src/driver/files.ts
index 046a411..8042015 100644
--- a/package/ego-browser/src/driver/files.ts
+++ b/package/ego-browser/src/driver/files.ts
@@ -7,7 +7,7 @@ import { withHandle } from "./element-ops.js";
* @param {string|string[]} path Absolute file path or paths to upload.
* @returns {Promise<void>}
*/
-export async function uploadFile(selector, path) {
+export async function setInputFiles(selector, path) {
const files = Array.isArray(path) ? path : [path];
await withHandle(selector, async ({ objectId, sessionId }) => {
await cdp("DOM.setFileInputFiles", { files, objectId }, sessionId);
diff --git a/package/ego-browser/src/driver/keyboard.test.mjs b/package/ego-browser/src/driver/keyboard.test.mjs
index c3be78a..a19722d 100644
--- a/package/ego-browser/src/driver/keyboard.test.mjs
+++ b/package/ego-browser/src/driver/keyboard.test.mjs
@@ -2,9 +2,9 @@ import test from "node:test";
import assert from "node:assert/strict";
import { setOverrides } from "../../dist/src/state.js";
-import { pressKey } from "../../dist/src/driver/keyboard.js";
+import { press } from "../../dist/src/driver/keyboard.js";
-test("pressKey maps Command+A to the selectAll editing command", async () => {
+test("press maps Command+A to the selectAll editing command", async () => {
const calls = [];
const restore = setOverrides({
cdpOverride(method, params, sessionId) {
@@ -13,7 +13,7 @@ test("pressKey maps Command+A to the selectAll editing command", async () => {
},
});
try {
- await pressKey("a", 4);
+ await press("Meta+a");
} finally {
restore();
}
@@ -44,7 +44,7 @@ test("pressKey maps Command+A to the selectAll editing command", async () => {
});
});
-test("pressKey maps Control+A to the selectAll editing command", async () => {
+test("press maps Control+A to the selectAll editing command", async () => {
const calls = [];
const restore = setOverrides({
cdpOverride(method, params, sessionId) {
@@ -53,7 +53,7 @@ test("pressKey maps Control+A to the selectAll editing command", async () => {
},
});
try {
- await pressKey("a", 2);
+ await press("Control+a");
} finally {
restore();
}
@@ -61,7 +61,7 @@ test("pressKey maps Control+A to the selectAll editing command", async () => {
assert.deepEqual(calls[0].params.commands, ["selectAll"]);
});
-test("pressKey does not map modified Command+A variants to selectAll", async () => {
+test("press does not map modified Command+A variants to selectAll", async () => {
const calls = [];
const restore = setOverrides({
cdpOverride(method, params, sessionId) {
@@ -70,7 +70,7 @@ test("pressKey does not map modified Command+A variants to selectAll", async ()
},
});
try {
- await pressKey("a", 12);
+ await press("Shift+Meta+a");
} finally {
restore();
}
@@ -78,7 +78,7 @@ test("pressKey does not map modified Command+A variants to selectAll", async ()
assert.equal(calls[0].params.commands, undefined);
});
-test("pressKey leaves ordinary printable keys unchanged", async () => {
+test("press leaves ordinary printable keys unchanged", async () => {
const calls = [];
const restore = setOverrides({
cdpOverride(method, params, sessionId) {
@@ -87,7 +87,7 @@ test("pressKey leaves ordinary printable keys unchanged", async () => {
},
});
try {
- await pressKey("x");
+ await press("x");
} finally {
restore();
}
@@ -113,7 +113,7 @@ test("pressKey leaves ordinary printable keys unchanged", async () => {
});
});
-test("pressKey maps Backspace and Delete to editing commands", async () => {
+test("press maps Backspace and Delete to editing commands", async () => {
const calls = [];
const restore = setOverrides({
cdpOverride(method, params, sessionId) {
@@ -122,8 +122,8 @@ test("pressKey maps Backspace and Delete to editing commands", async () => {
},
});
try {
- await pressKey("Backspace");
- await pressKey("Delete");
+ await press("Backspace");
+ await press("Delete");
} finally {
restore();
}
@@ -132,7 +132,7 @@ test("pressKey maps Backspace and Delete to editing commands", async () => {
assert.deepEqual(calls[2].params.commands, ["deleteForward"]);
});
-test("pressKey triggers probe fallback when CDP dispatch is not trusted", async () => {
+test("press triggers probe fallback when CDP dispatch is not trusted", async () => {
// Enable canProbeInputFallback() by providing ego runtime
const originalEgo = globalThis.ego;
globalThis.ego = { sendCDPMessage: () => {} };
@@ -156,7 +156,7 @@ test("pressKey triggers probe fallback when CDP dispatch is not trusted", async
},
});
try {
- await pressKey("a");
+ await press("a");
} finally {
restore();
if (originalEgo === undefined) delete globalThis.ego;
@@ -188,7 +188,7 @@ test("pressKey triggers probe fallback when CDP dispatch is not trusted", async
);
});
-test("pressKey skips probe fallback when CDP dispatch is trusted", async () => {
+test("press skips probe fallback when CDP dispatch is trusted", async () => {
const originalEgo = globalThis.ego;
globalThis.ego = { sendCDPMessage: () => {} };
let evaluateCallCount = 0;
@@ -208,7 +208,7 @@ test("pressKey skips probe fallback when CDP dispatch is trusted", async () => {
},
});
try {
- await pressKey("x");
+ await press("x");
} finally {
restore();
if (originalEgo === undefined) delete globalThis.ego;
diff --git a/package/ego-browser/src/driver/keyboard.ts b/package/ego-browser/src/driver/keyboard.ts
index 1e5682c..13515a9 100644
--- a/package/ego-browser/src/driver/keyboard.ts
+++ b/package/ego-browser/src/driver/keyboard.ts
@@ -1,9 +1,9 @@
import { cdp } from "../cdp-eval.js";
import { browserCdp } from "../browser-runtime.js";
import { withHandle, resolveAndCall } from "./element-ops.js";
-import { waitForElement } from "./waits.js";
+import { waitForSelector } from "./waits.js";
-type FillInputOptions = {
+type FillOptions = {
clearFirst?: boolean;
timeout?: number;
};
@@ -62,13 +62,46 @@ function editingCommandsForKey(key, modifiers) {
return undefined;
}
+const MODIFIER_BITS: Record<string, number> = {
+ Alt: 1,
+ Control: 2,
+ Meta: 4,
+ Shift: 8,
+};
+
+/**
+ * Parse a Playwright-style key combo ("Control+a", "Shift+Tab") into a base key
+ * and a CDP modifier bitfield. Modifiers: Control, Shift, Alt, Meta, ControlOrMeta.
+ */
+function parseKeyCombo(combo: string) {
+ const parts = combo.split("+");
+ let key = parts.pop() ?? combo;
+ if (key === "" && parts.length > 0) {
+ key = "+"; // a trailing "+" means the literal plus key, e.g. "Shift++"
+ }
+ let modifiers = 0;
+ for (const name of parts) {
+ if (name === "ControlOrMeta") {
+ modifiers |=
+ process.platform === "darwin" ? META_MODIFIER : CTRL_MODIFIER;
+ continue;
+ }
+ const bit = MODIFIER_BITS[name];
+ if (bit === undefined) {
+ throw new Error(`press: unknown key modifier ${JSON.stringify(name)}`);
+ }
+ modifiers |= bit;
+ }
+ return { key, modifiers };
+}
+
/**
- * Dispatch a key press through CDP.
- * @param {string} key Key name such as Enter, Tab, ArrowLeft, or a single printable character.
- * @param {number} [modifiers=0] CDP modifier bitfield: Alt=1, Ctrl=2, Meta/Cmd=4, Shift=8.
+ * Dispatch a key press through CDP. Combine modifiers with "+".
+ * @param {string} keyCombo Key or modifier+key combo: "Enter", "a", "Control+a", "Shift+Tab". Modifiers: Control, Shift, Alt, Meta, ControlOrMeta.
* @returns {Promise<void>}
*/
-export async function pressKey(key, modifiers = 0) {
+export async function press(keyCombo) {
+ const { key, modifiers } = parseKeyCombo(keyCombo);
const { vk, code, text } = keyDefinition(key);
const base = {
key,
@@ -107,28 +140,22 @@ export async function pressKey(key, modifiers = 0) {
* @param {string} text Text to insert.
* @returns {Promise<void>}
*/
-export async function typeText(text) {
+export async function insertText(text) {
await cdp("Input.insertText", { text });
}
/**
- * Focus an input, optionally clear it, type text, and fire input/change events.
+ * Focus an input, optionally clear it, write a value, and fire input/change events.
* @param {string} selector CSS selector / @ref / loc= / xpath= for the input-like element.
- * @param {string} text Text to write.
- * @param {{clearFirst?: boolean, timeout?: number}} [options]
+ * @param {string} value Text to write.
+ * @param {{clearFirst?: boolean, timeout?: number}} [options] clearFirst defaults to true (Playwright fill always clears); clearFirst:false appends (ego-browser extension). timeout in milliseconds.
* @returns {Promise<void>}
*/
-export async function fillInput(
- selector,
- text,
- options: FillInputOptions = {},
-) {
+export async function fill(selector, value, options: FillOptions = {}) {
const clearFirst = options.clearFirst ?? true;
const timeout = options.timeout ?? 0;
- if (timeout > 0 && !(await waitForElement(selector, { timeout }))) {
- throw new Error(
- `fillInput: element not found: ${JSON.stringify(selector)}`,
- );
+ if (timeout > 0 && !(await waitForSelector(selector, { timeout }))) {
+ throw new Error(`fill: element not found: ${JSON.stringify(selector)}`);
}
await withHandle(selector, async ({ objectId, sessionId }) => {
const focusSource = clearFirst
@@ -157,7 +184,7 @@ export async function fillInput(
sessionId,
);
}
- await cdp("Input.insertText", { text }, sessionId);
+ await cdp("Input.insertText", { text: value }, sessionId);
await cdp(
"Runtime.callFunctionOn",
{
diff --git a/package/ego-browser/src/driver/load.ts b/package/ego-browser/src/driver/load.ts
index 0143cce..d300894 100644
--- a/package/ego-browser/src/driver/load.ts
+++ b/package/ego-browser/src/driver/load.ts
@@ -1,4 +1,4 @@
-import { cdp, js } from "../cdp-eval.js";
+import { cdp, evaluate } from "../cdp-eval.js";
import { state } from "../state.js";
export type WaitForLoadOptions = {
@@ -6,8 +6,8 @@ export type WaitForLoadOptions = {
};
export async function waitForDocumentLoad(options: WaitForLoadOptions = {}) {
- const timeout = options.timeout ?? 15.0;
- const deadline = state.now() + timeout * 1000;
+ const timeout = options.timeout ?? 15000;
+ const deadline = state.now() + timeout;
while (state.now() < deadline) {
let committed = true;
try {
@@ -17,7 +17,7 @@ export async function waitForDocumentLoad(options: WaitForLoadOptions = {}) {
} catch {
// Page.getFrameTree may not be supported in some sessions; fall back to readyState only.
}
- if (committed && (await js("document.readyState")) === "complete") {
+ if (committed && (await evaluate("document.readyState")) === "complete") {
return true;
}
await state.sleep(300);
diff --git a/package/ego-browser/src/driver/nav.ts b/package/ego-browser/src/driver/nav.ts
index eba53a0..701b9d1 100644
--- a/package/ego-browser/src/driver/nav.ts
+++ b/package/ego-browser/src/driver/nav.ts
@@ -7,7 +7,7 @@ import {
pendingDialog,
setPreferredTarget,
} from "../browser-runtime.js";
-import { cdp, js } from "../cdp-eval.js";
+import { cdp, evaluate } from "../cdp-eval.js";
import { assertNoEgoError } from "../ego-errors.js";
import { state } from "../state.js";
import { waitForDocumentLoad } from "./load.js";
@@ -28,10 +28,10 @@ type TabInfo = {
index?: number;
};
-type GotoAndWaitOptions = {
+type GotoOptions = {
+ waitUntil?: "load" | "domcontentloaded" | "commit";
timeout?: number;
settle?: number;
- wait?: boolean;
};
type ListTabsOptions = {
@@ -50,32 +50,22 @@ type OpenOrReuseTabOptions = {
type TabTarget = string | { targetId: string };
/**
- * Navigate the current tab to a URL using CDP Page.navigate.
+ * Navigate the current tab to a URL and, by default, wait for it to load.
* @param {string} url Absolute or browser-supported URL to load.
- * @returns {Promise<object>} CDP Page.navigate result.
- */
-export async function gotoUrl(url) {
- return cdp("Page.navigate", { url });
-}
-
-/**
- * Navigate the current tab and wait for load/settle in one call.
- * @param {string} url Absolute or browser-supported URL to load.
- * @param {{timeout?: number, settle?: number, wait?: boolean}} [options]
+ * @param {{waitUntil?: "load"|"domcontentloaded"|"commit", timeout?: number, settle?: number}} [options]
+ * `waitUntil: "commit"` returns once navigation is issued without waiting for the document to load.
+ * `timeout` and `settle` are in milliseconds.
* @returns {Promise<{navigation: object, loaded: boolean}>}
*/
-export async function gotoAndWait(
- url: string,
- options: GotoAndWaitOptions = {},
-) {
- const navigation = await gotoUrl(url);
+export async function goto(url: string, options: GotoOptions = {}) {
+ const navigation = await cdp("Page.navigate", { url });
const loaded =
- options.wait === false
+ options.waitUntil === "commit"
? false
- : await waitForDocumentLoad({ timeout: options.timeout ?? 20 });
+ : await waitForDocumentLoad({ timeout: options.timeout ?? 20000 });
const settle = Number(options.settle ?? 0);
if (settle > 0) {
- await state.sleep(settle * 1000);
+ await state.sleep(settle);
}
return { navigation, loaded };
}
@@ -94,7 +84,7 @@ export async function pageInfo() {
}
const expression =
"JSON.stringify({url:location.href,title:document.title,w:innerWidth,h:innerHeight,sx:scrollX,sy:scrollY,pw:document.documentElement.scrollWidth,ph:document.documentElement.scrollHeight})";
- return JSON.parse(await js(expression));
+ return JSON.parse(await evaluate(expression));
}
/**
@@ -180,17 +170,17 @@ export async function openOrReuseTab(
if (existing) {
await switchTab(existing.targetId);
if (options.wait) {
- await waitForDocumentLoad({ timeout: options.timeout ?? 20 });
+ await waitForDocumentLoad({ timeout: options.timeout ?? 20000 });
}
const settle = Number(options.settle ?? 0);
if (settle > 0) {
- await state.sleep(settle * 1000);
+ await state.sleep(settle);
}
return { ...existing, active: true, reused: true };
}
const targetId = await newTab(url);
if (options.wait !== false) {
- await waitForDocumentLoad({ timeout: options.timeout ?? 20 });
+ await waitForDocumentLoad({ timeout: options.timeout ?? 20000 });
}
const settle = Number(options.settle ?? 0);
if (settle > 0) {
diff --git a/package/ego-browser/src/driver/observe.test.mjs b/package/ego-browser/src/driver/observe.test.mjs
index 7bc9837..e670ba0 100644
--- a/package/ego-browser/src/driver/observe.test.mjs
+++ b/package/ego-browser/src/driver/observe.test.mjs
@@ -5,7 +5,7 @@ import {
browserCdp,
invalidateSession,
} from "../../dist/src/browser-runtime.js";
-import { captureScreenshot } from "../../dist/src/driver/observe.js";
+import { screenshot } from "../../dist/src/driver/observe.js";
import { setOverrides } from "../../dist/src/state.js";
function withCdpRuntime(fn) {
@@ -59,7 +59,7 @@ function withCdpRuntime(fn) {
});
}
-test("captureScreenshot skips page metric JavaScript while a native dialog is pending", async () => {
+test("screenshot skips page metric JavaScript while a native dialog is pending", async () => {
const writes = [];
const restore = setOverrides({
async writeFile(path, data) {
@@ -76,16 +76,16 @@ test("captureScreenshot skips page metric JavaScript while a native dialog is pe
});
sent.length = 0;
- await captureScreenshot("/tmp/ego-browser-dialog-shot.png");
+ await screenshot({ path: "/tmp/ego-browser-dialog-shot.png" });
assert.equal(
sent.some((request) => request.method === "Runtime.evaluate"),
false,
);
- const screenshot = sent.find(
+ const shot = sent.find(
(request) => request.method === "Page.captureScreenshot",
);
- assert.deepEqual(screenshot.params, {
+ assert.deepEqual(shot.params, {
format: "png",
captureBeyondViewport: false,
});
diff --git a/package/ego-browser/src/driver/observe.ts b/package/ego-browser/src/driver/observe.ts
index 96bf3e9..8bcd860 100644
--- a/package/ego-browser/src/driver/observe.ts
+++ b/package/ego-browser/src/driver/observe.ts
@@ -2,7 +2,7 @@ import { join } from "node:path";
import { tmpdir } from "node:os";
import { state } from "../state.js";
-import { cdp, js } from "../cdp-eval.js";
+import { cdp, evaluate } from "../cdp-eval.js";
import { pageInfo } from "./nav.js";
import {
browserEgo,
@@ -34,8 +34,9 @@ type ScreenshotClip = {
scale?: number;
};
-type CaptureScreenshotOptions = {
- full?: boolean;
+type ScreenshotOptions = {
+ path?: string;
+ fullPage?: boolean;
raw?: boolean;
clip?: ScreenshotClip;
};
@@ -93,14 +94,11 @@ export async function elementCenter(selectorOrRef) {
// other's shots in the shared tmpdir, and successive shots in one run distinct.
let screenshotSeq = 0;
-export async function captureScreenshot(
- path = join(
- tmpdir(),
- `ego-browser-shot-${process.pid}-${++screenshotSeq}.png`,
- ),
- options: CaptureScreenshotOptions = {},
-) {
- const full = options.full ?? false;
+export async function screenshot(options: ScreenshotOptions = {}) {
+ const path =
+ options.path ??
+ join(tmpdir(), `ego-browser-shot-${process.pid}-${++screenshotSeq}.png`);
+ const full = options.fullPage ?? false;
const raw = options.raw ?? false;
const params: any = {
format: "png",
@@ -115,14 +113,14 @@ export async function captureScreenshot(
await ensureSession();
}
if (!pendingDialog()) {
- const dpr = Number(await js("window.devicePixelRatio")) || 1;
+ const dpr = Number(await evaluate("window.devicePixelRatio")) || 1;
const cssScale = 1 / dpr;
if (options.clip) {
params.clip = { scale: cssScale, ...options.clip };
} else {
const info = await pageInfo();
if ("dialog" in info) {
- return captureScreenshot(path, { ...options, raw: true });
+ return screenshot({ ...options, path, raw: true });
}
params.clip = {
x: 0,
diff --git a/package/ego-browser/src/driver/pointer.ts b/package/ego-browser/src/driver/pointer.ts
index 8b7c36b..56d728d 100644
--- a/package/ego-browser/src/driver/pointer.ts
+++ b/package/ego-browser/src/driver/pointer.ts
@@ -1,4 +1,4 @@
-import { cdp, js } from "../cdp-eval.js";
+import { cdp, evaluate } from "../cdp-eval.js";
import { browserCdp } from "../browser-runtime.js";
import { elementCenter } from "./observe.js";
import { resolveAndCall } from "./element-ops.js";
@@ -17,12 +17,11 @@ export type MouseTarget =
type ClickOptions = {
button?: MouseButton;
clickCount?: number;
- clicks?: number;
label?: string;
};
-type DragMouseOptions = {
+type DragOptions = {
button?: MouseButton;
- delayMs?: number;
+ delay?: number;
label?: string;
};
type HoverOptions = {
@@ -81,14 +80,14 @@ const INPUT_DISPATCH_TIMEOUT_MS = 1000;
/**
* Click a mouse target.
* @param {MouseTarget} target CSS selector, @ref, viewport point, or selector-relative point.
- * @param {{button?: "left"|"middle"|"right", clickCount?: number, clicks?: number, label?: string}} [options]
+ * @param {{button?: "left"|"middle"|"right", clickCount?: number, label?: string}} [options]
* @returns {Promise<void>}
*/
export async function click(target: MouseTarget, options: ClickOptions = {}) {
const point = await resolveMouseTarget(target);
const button = options.button || "left";
const buttons = pressedButtons(button);
- const clickCount = options.clickCount ?? options.clicks ?? 1;
+ const clickCount = options.clickCount ?? 1;
maybeHighlight(point, options.label);
const probeId = await installClickProbe(point);
let dispatchError: unknown = null;
@@ -123,7 +122,7 @@ export async function click(target: MouseTarget, options: ClickOptions = {}) {
* @param {{button?: "left"|"middle"|"right", label?: string}} [options]
* @returns {Promise<void>}
*/
-export async function doubleClick(
+export async function dblclick(
target: MouseTarget,
options: ClickOptions = {},
) {
@@ -154,15 +153,12 @@ export async function hover(target: MouseTarget, options: HoverOptions = {}) {
/**
* Drag the mouse through a sequence of targets while holding a button.
* @param {MouseTarget[]} points Ordered drag path. Must contain at least two targets.
- * @param {{button?: "left"|"middle"|"right", delayMs?: number, label?: string}} [options]
+ * @param {{button?: "left"|"middle"|"right", delay?: number, label?: string}} [options]
* @returns {Promise<void>}
*/
-export async function dragMouse(
- points: MouseTarget[],
- options: DragMouseOptions = {},
-) {
+export async function drag(points: MouseTarget[], options: DragOptions = {}) {
if (!Array.isArray(points) || points.length < 2) {
- throw new Error("dragMouse requires at least two points");
+ throw new Error("drag requires at least two points");
}
const resolved: Point[] = [];
for (const point of points) {
@@ -192,7 +188,7 @@ export async function dragMouse(
buttons,
},
);
- await inputEventDelay(options.delayMs > 0 ? options.delayMs : undefined);
+ await inputEventDelay(options.delay > 0 ? options.delay : undefined);
}
await dispatchMouse(
{ ...last, sessionId: last.sessionId ?? first.sessionId },
@@ -529,7 +525,7 @@ export async function scrollBy(
options: ScrollByOptions = {},
) {
const params = scrollByParams(amount, options);
- return js(`(() => {
+ return evaluate(`(() => {
window.scrollBy({
left: ${JSON.stringify(params.left)},
top: ${JSON.stringify(params.top)},
@@ -699,7 +695,7 @@ function scrollByParams(
}
async function scrollState(): Promise<ScrollState> {
- return js(`(() => {
+ return evaluate(`(() => {
const doc = document.documentElement;
const body = document.body;
const height = Math.max(
@@ -731,7 +727,7 @@ async function conditionMet(
return Boolean(await condition(state));
}
if (typeof condition === "string") {
- return Boolean(await js(`Boolean(${condition})`));
+ return Boolean(await evaluate(`Boolean(${condition})`));
}
throw new TypeError(
`scrollToBottomUntil condition must be a function or string, got ${typeof condition}`,
diff --git a/package/ego-browser/src/driver/waits.test.mjs b/package/ego-browser/src/driver/waits.test.mjs
index 1336309..82926c8 100644
--- a/package/ego-browser/src/driver/waits.test.mjs
+++ b/package/ego-browser/src/driver/waits.test.mjs
@@ -3,9 +3,9 @@ import assert from "node:assert/strict";
import { setOverrides } from "../../dist/src/state.js";
import { cdp } from "../../dist/src/cdp-eval.js";
-import { waitForNetworkIdle } from "../../dist/src/driver/waits.js";
+import { waitForLoadState } from "../../dist/src/driver/waits.js";
-test("waitForNetworkIdle enables the Network domain and disables it afterwards", async () => {
+test("waitForLoadState enables the Network domain and disables it afterwards", async () => {
// Regression: nothing used to enable the Network domain, so the helper could
// report "idle" without ever being able to observe traffic.
const methods = [];
@@ -21,7 +21,7 @@ test("waitForNetworkIdle enables the Network domain and disables it afterwards",
},
});
try {
- const result = await waitForNetworkIdle({ timeout: 5 });
+ const result = await waitForLoadState("networkidle", { timeout: 5000 });
assert.equal(result, true, "no traffic for idleMs resolves true");
} finally {
restore();
@@ -38,7 +38,7 @@ test("waitForNetworkIdle enables the Network domain and disables it afterwards",
);
});
-test("waitForNetworkIdle leaves a caller-enabled Network domain enabled", async () => {
+test("waitForLoadState leaves a caller-enabled Network domain enabled", async () => {
const methods = [];
let t = 0;
const restore = setOverrides({
@@ -54,7 +54,7 @@ test("waitForNetworkIdle leaves a caller-enabled Network domain enabled", async
try {
await cdp("Network.enable"); // the caller owns the domain
methods.length = 0;
- const result = await waitForNetworkIdle({ timeout: 5 });
+ const result = await waitForLoadState("networkidle", { timeout: 5000 });
assert.equal(result, true);
} finally {
restore();
@@ -65,7 +65,7 @@ test("waitForNetworkIdle leaves a caller-enabled Network domain enabled", async
);
});
-test("waitForNetworkIdle survives a bridge that rejects Network.enable", async () => {
+test("waitForLoadState survives a bridge that rejects Network.enable", async () => {
let t = 0;
const restore = setOverrides({
cdpOverride: async (method) => {
@@ -80,7 +80,7 @@ test("waitForNetworkIdle survives a bridge that rejects Network.enable", async (
},
});
try {
- const result = await waitForNetworkIdle({ timeout: 5 });
+ const result = await waitForLoadState("networkidle", { timeout: 5000 });
assert.equal(result, true, "falls back to passive observation");
} finally {
restore();
diff --git a/package/ego-browser/src/driver/waits.ts b/package/ego-browser/src/driver/waits.ts
index 878c6f7..023ac12 100644
--- a/package/ego-browser/src/driver/waits.ts
+++ b/package/ego-browser/src/driver/waits.ts
@@ -2,50 +2,58 @@ import { state } from "../state.js";
import { cdp } from "../cdp-eval.js";
import { resolveHandle, releaseHandle } from "./element-ops.js";
import { ElementResolutionError } from "../element-resolver.js";
-import { type WaitForLoadOptions, waitForDocumentLoad } from "./load.js";
+import { waitForDocumentLoad } from "./load.js";
import { drainEvents } from "./observe.js";
-type WaitForElementOptions = {
+type WaitForSelectorOptions = {
timeout?: number;
- visible?: boolean;
+ state?: "visible" | "attached";
};
-type WaitForNetworkIdleOptions = {
+type WaitForLoadStateOptions = {
timeout?: number;
idleMs?: number;
};
/**
- * Sleep for a fixed number of seconds.
- * @param {number} [seconds=1.0] Seconds to wait.
+ * Sleep for a fixed number of milliseconds.
+ * @param {number} [ms=1000] Milliseconds to wait.
* @returns {Promise<void>}
*/
-export async function wait(seconds = 1.0) {
- await state.sleep(seconds * 1000);
+export async function waitForTimeout(ms = 1000) {
+ await state.sleep(ms);
}
/**
- * Wait until document.readyState is complete.
- * @param {{timeout?: number}} [options]
- * @returns {Promise<boolean>} True when loaded before timeout.
+ * Wait for a page load state. `"networkidle"` waits until network traffic goes
+ * idle; any other state waits until document.readyState is complete.
+ * @param {"load"|"domcontentloaded"|"networkidle"} [loadState="load"] Load state to wait for.
+ * @param {{timeout?: number, idleMs?: number}} [options] timeout in milliseconds; idleMs only applies to "networkidle".
+ * @returns {Promise<boolean>} True when the state was reached before timeout.
*/
-export async function waitForLoad(options: WaitForLoadOptions = {}) {
- return waitForDocumentLoad(options);
+export async function waitForLoadState(
+ loadState: "load" | "domcontentloaded" | "networkidle" = "load",
+ options: WaitForLoadStateOptions = {},
+) {
+ if (loadState === "networkidle") {
+ return waitForNetworkIdle(options);
+ }
+ return waitForDocumentLoad({ timeout: options.timeout });
}
/**
* Wait until an element exists, optionally requiring visibility.
* @param {string} selector CSS selector / @ref / loc= / xpath= to poll.
- * @param {{timeout?: number, visible?: boolean}} [options]
+ * @param {{timeout?: number, state?: "visible"|"attached"}} [options] timeout in milliseconds; state defaults to "attached".
* @returns {Promise<boolean>} True when found before timeout.
*/
-export async function waitForElement(
+export async function waitForSelector(
selector: string,
- options: WaitForElementOptions = {},
+ options: WaitForSelectorOptions = {},
) {
- const timeout = options.timeout ?? 10.0;
- const visible = options.visible ?? false;
- const deadline = state.now() + timeout * 1000;
+ const timeout = options.timeout ?? 10000;
+ const requireVisible = options.state === "visible";
+ const deadline = state.now() + timeout;
const visibilityFn =
"function(){if(typeof this.checkVisibility==='function')return this.checkVisibility({checkOpacity:true,checkVisibilityCSS:true});const s=getComputedStyle(this);return s.display!=='none'&&s.visibility!=='hidden'&&s.opacity!=='0';}";
while (state.now() < deadline) {
@@ -60,7 +68,7 @@ export async function waitForElement(
throw err; // permanent (bad selector / ambiguous) or unknown error — fail loud.
}
try {
- if (!visible) return true;
+ if (!requireVisible) return true;
const response = await cdp(
"Runtime.callFunctionOn",
{
@@ -83,22 +91,21 @@ export async function waitForElement(
}
/**
- * Wait until network events are idle.
+ * Wait until network events are idle. Module-private; reachable through
+ * waitForLoadState("networkidle").
* Enables the CDP Network domain for the duration of the wait so that network
* events are actually delivered (previously nothing enabled the domain, so this
* could report "idle" without ever observing traffic). If the caller had
* already enabled the domain, it is left enabled on return. Best-effort: if
* the runtime does not deliver Network events, an idle window of idleMs still
* resolves true.
- * @param {{timeout?: number, idleMs?: number}} [options]
+ * @param {{timeout?: number, idleMs?: number}} [options] timeout & idleMs in milliseconds.
* @returns {Promise<boolean>} True when idle before timeout.
*/
-export async function waitForNetworkIdle(
- options: WaitForNetworkIdleOptions = {},
-) {
- const timeout = options.timeout ?? 10.0;
+async function waitForNetworkIdle(options: WaitForLoadStateOptions = {}) {
+ const timeout = options.timeout ?? 10000;
const idleMs = options.idleMs ?? 500;
- const deadline = state.now() + timeout * 1000;
+ const deadline = state.now() + timeout;
let lastActivity = state.now();
const inflight = new Set();
const ownsNetworkDomain = !state.networkDomainEnabled;
diff --git a/package/ego-browser/src/element-resolver.ts b/package/ego-browser/src/element-resolver.ts
index cfebdcc..31faf35 100644
--- a/package/ego-browser/src/element-resolver.ts
+++ b/package/ego-browser/src/element-resolver.ts
@@ -536,7 +536,7 @@ function boxModelCenter(model: any = {}) {
if (content.length < 8) {
// Returning a fake (0,0) here would silently click the viewport corner.
// Treat a missing/degenerate box model as "element not ready" so callers
- // with retry semantics (waitForElement, ref fallback) can poll.
+ // with retry semantics (waitForSelector, ref fallback) can poll.
throw new ElementResolutionError(
"Element has no box model (not rendered or zero-sized)",
"transient",
diff --git a/package/ego-browser/src/helpers.ts b/package/ego-browser/src/helpers.ts
index 212548a..5e624e9 100644
--- a/package/ego-browser/src/helpers.ts
+++ b/package/ego-browser/src/helpers.ts
@@ -5,7 +5,7 @@ import { pathToFileURL } from "node:url";
import { setOverrides, state } from "./state.js";
import { assertNoEgoError, isEgoUserControlError } from "./ego-errors.js";
import { help as helpRuntime, formatHelp } from "./help-runtime.js";
-import { cdp, decodeUnserializableJsValue, js } from "./cdp-eval.js";
+import { cdp, decodeUnserializableJsValue, evaluate } from "./cdp-eval.js";
import * as pointer from "./driver/pointer.js";
import * as keyboard from "./driver/keyboard.js";
import * as nav from "./driver/nav.js";
@@ -22,22 +22,17 @@ import {
} from "./learning/index.js";
export { NAME } from "./state.js";
-export { cdp, js } from "./cdp-eval.js";
+export { cdp, evaluate } from "./cdp-eval.js";
export {
click,
- doubleClick,
+ dblclick,
hover,
- dragMouse,
+ drag,
scroll,
scrollBy,
scrollToBottomUntil,
} from "./driver/pointer.js";
-export {
- pressKey,
- typeText,
- fillInput,
- dispatchKey,
-} from "./driver/keyboard.js";
+export { press, insertText, fill, dispatchKey } from "./driver/keyboard.js";
export {
INTERNAL_URL_PREFIXES,
pageInfo,
@@ -46,8 +41,7 @@ export {
switchTab,
openOrReuseTab,
closeTab,
- gotoUrl,
- gotoAndWait,
+ goto,
ensureRealTab,
iframeTarget,
} from "./driver/nav.js";
@@ -55,17 +49,16 @@ export {
snapshot,
snapshotRaw,
snapshotText,
- captureScreenshot,
+ screenshot,
elementCenter,
drainEvents,
} from "./driver/observe.js";
export {
- wait,
- waitForLoad,
- waitForElement,
- waitForNetworkIdle,
+ waitForTimeout,
+ waitForLoadState,
+ waitForSelector,
} from "./driver/waits.js";
-export { uploadFile } from "./driver/files.js";
+export { setInputFiles } from "./driver/files.js";
export { browserFetch, serverFetch } from "./http.js";
/**
@@ -372,7 +365,7 @@ export async function waitForAgentControl(
if (Date.now() >= deadline) {
throw new Error(`waitForAgentControl timed out after ${timeout}s`);
}
- await waits.wait(interval);
+ await waits.waitForTimeout(interval * 1000);
}
}
@@ -469,7 +462,7 @@ export async function runSiteBrowserTool(siteId, toolName, args: any = {}) {
const source = await loadBrowserToolSource(siteId, toolName, {
agentWorkspace: state.agentWorkspace(),
});
- return js(wrapBrowserTool(source, args));
+ return evaluate(wrapBrowserTool(source, args));
}
/**
@@ -495,7 +488,7 @@ export function helperContext(extra: any = {}) {
...waits,
...files,
cdp,
- js,
+ evaluate,
serverFetch,
browserFetch,
siteSkills,
diff --git a/package/ego-browser/src/http.ts b/package/ego-browser/src/http.ts
index 4179384..0f33b75 100644
--- a/package/ego-browser/src/http.ts
+++ b/package/ego-browser/src/http.ts
@@ -1,4 +1,4 @@
-import { js } from "./cdp-eval.js";
+import { evaluate } from "./cdp-eval.js";
/**
* Fetch text from Node with a browser-like User-Agent.
@@ -11,10 +11,12 @@ export async function serverFetch(url, options: any = {}) {
const response = await fetch(url, {
...fetchOptions,
headers: { "User-Agent": "Mozilla/5.0", ...headers },
- signal: AbortSignal.timeout(timeout * 1000)
+ signal: AbortSignal.timeout(timeout * 1000),
});
if (!response.ok) {
- throw new Error(`${fetchOptions.method || "GET"} ${url} failed: HTTP ${response.status}`);
+ throw new Error(
+ `${fetchOptions.method || "GET"} ${url} failed: HTTP ${response.status}`,
+ );
}
return response.text();
}
@@ -28,7 +30,7 @@ export async function serverFetch(url, options: any = {}) {
export async function browserFetch(url, options: any = {}) {
const { timeout = 20.0, ...fetchOptions } = options;
const payload = JSON.stringify({ url, options: fetchOptions, timeout });
- return js(`(async () => {
+ return evaluate(`(async () => {
const { url, options, timeout } = ${payload};
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout * 1000);
diff --git a/package/ego-browser/src/run.ts b/package/ego-browser/src/run.ts
index df026c6..92621b8 100644
--- a/package/ego-browser/src/run.ts
+++ b/package/ego-browser/src/run.ts
@@ -41,7 +41,7 @@ Read the ego-browser skill for the default workflow and examples.
Typical usage:
ego-browser <<'JS'
- await waitForLoad()
+ await waitForLoadState()
cliLog(await pageInfo())
JS
diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.md
index 35af228..7113a62 100644
--- a/skills/ego-browser/SKILL.md
+++ b/skills/ego-browser/SKILL.md
@@ -8,7 +8,7 @@ metadata:
# ego-browser
-ego-browser gives AI agents a CLI-accessible Node.js runtime, with built-in helpers — snapshotText, click, js, cdp, and more — that agents call directly inside JS scripts to observe pages, interact with UI, evaluate browser-side JavaScript, and drive a real browser for any web automation task.
+ego-browser gives AI agents a CLI-accessible Node.js runtime, with built-in helpers — snapshotText, click, evaluate, cdp, and more — that agents call directly inside JS scripts to observe pages, interact with UI, evaluate browser-side JavaScript, and drive a real browser for any web automation task.
For setup, install, or connection problems, read `references/install.md`.
@@ -34,14 +34,14 @@ The heredoc body runs as a Node.js script that controls the selected ego-browser
## Common helpers
- Task spaces: `listTaskSpaces`, `useOrCreateTaskSpace`, `claimTaskSpace`, `handOffTaskSpace`, `takeOverTaskSpace`, `waitForAgentControl`, `completeTaskSpace`
-- Navigation / state: `listTabs`, `openOrReuseTab`, `closeTab`, `gotoAndWait`, `currentTab`, `switchTab`, `gotoUrl`, `pageInfo`, `ensureRealTab`
-- Observation: `snapshotText`, `captureScreenshot`, `drainEvents`
-- Scroll / mouse: `scrollBy`, `scrollToBottomUntil`, `scroll`, `click`, `doubleClick`, `hover`, `dragMouse`
-- Keyboard & input: `typeText`, `fillInput`, `pressKey`, `dispatchKey`
-- File: `uploadFile`
-- Wait: `wait`, `waitForLoad`, `waitForElement`, `waitForNetworkIdle`
+- Navigation / state: `listTabs`, `openOrReuseTab`, `closeTab`, `goto`, `currentTab`, `switchTab`, `pageInfo`, `ensureRealTab`
+- Observation: `snapshotText`, `screenshot`, `drainEvents`
+- Scroll / mouse: `scrollBy`, `scrollToBottomUntil`, `scroll`, `click`, `dblclick`, `hover`, `drag`
+- Keyboard & input: `insertText`, `fill`, `press`, `dispatchKey`
+- File: `setInputFiles`
+- Wait: `waitForTimeout`, `waitForLoadState`, `waitForSelector`
- Fetch: `serverFetch`, `browserFetch`
-- CDP / evaluate: `js`, `cdp`
+- CDP / evaluate: `evaluate`, `cdp`
- Output: `cliLog`, `help`
Notes:
@@ -117,7 +117,7 @@ An "inactive", "not assigned to an agent", or similar task-space error is also a
// DOM scroll
await scrollBy(900)
await scrollToBottomUntil(
- async () => await js(String.raw`document.querySelectorAll('article').length`) >= 20,
+ async () => await evaluate(String.raw`document.querySelectorAll('article').length`) >= 20,
{ step: 900, wait: 1, maxSteps: 20 }
)
@@ -125,9 +125,9 @@ await scrollToBottomUntil(
await scroll({ dy: 900 })
```
-Element-target helpers such as `click`, `doubleClick`, `hover`, `dragMouse`, `fillInput`, `uploadFile`, and `waitForElement` accept the same selector/ref surface: raw CSS, `xpath=...`, `@N` / `ref=N`, and `loc=...` values from `snapshotText()` (`loc=css:...`, `loc=role:...`, `loc=href:...`). `@N` refs are for ego-browser helpers only; they are not valid selectors inside `document.querySelector(...)`.
+Element-target helpers such as `click`, `dblclick`, `hover`, `drag`, `fill`, `setInputFiles`, and `waitForSelector` accept the same selector/ref surface: raw CSS, `xpath=...`, `@N` / `ref=N`, and `loc=...` values from `snapshotText()` (`loc=css:...`, `loc=role:...`, `loc=href:...`). `@N` refs are for ego-browser helpers only; they are not valid selectors inside `document.querySelector(...)`.
-`click`, `doubleClick`, `hover`, and `dragMouse` share these target formats. Coordinates are in CSS pixels:
+`click`, `dblclick`, `hover`, and `drag` share these target formats. Coordinates are in CSS pixels:
- `string` — CSS selector, `xpath=...`, `@N` / `ref=N`, or `loc=...`; clicks the element's center.
- `[x, y]` or `{x, y}` — viewport coordinates.
@@ -142,23 +142,23 @@ await click([420, 260])
await click({ x: 420, y: 260 })
await click({ selector: 'canvas#stage', x: 12, y: 8 })
await hover('@5', { label: 'hover to reveal menu' })
-await dragMouse([from, to], { label: 'drag card' })
+await drag([from, to], { label: 'drag card' })
```
-### uploadFile
+### setInputFiles
```js
-await uploadFile('input[type="file"]', "/absolute/path/to/file.pdf")
+await setInputFiles('input[type="file"]', "/absolute/path/to/file.pdf")
```
-### js
+### evaluate
-`js()` is essentially `Runtime.evaluate` and takes a string. You can pass a function, but doing so triggers a one-time warning and wraps it via `.toString()` — closures are not captured and there is no argument channel. Do not use `js()` the way you would Puppeteer / Playwright's `page.evaluate(fn, ...args)`.
+`evaluate()` is essentially `Runtime.evaluate` and takes a string. You can pass a function, but doing so triggers a one-time warning and wraps it via `.toString()` — closures are not captured and there is no argument channel. Do not use `evaluate()` the way you would Puppeteer / Playwright's `page.evaluate(fn, ...args)`.
-When you need to run multi-step logic inside the browser, wrap it in a single self-invoking closure and return once — don't split it across multiple `await js()` calls:
+When you need to run multi-step logic inside the browser, wrap it in a single self-invoking closure and return once — don't split it across multiple `await evaluate()` calls:
```js
-const data = await js(String.raw`(() => {
+const data = await evaluate(String.raw`(() => {
const items = [...document.querySelectorAll('article')]
return items.map(el => ({
text: el.innerText,
@@ -172,22 +172,22 @@ const data = await js(String.raw`(() => {
ego-browser has three main workflows. Pick the workflow that fits the page and task before acting.
-Use the semantic workflow first for ordinary websites with real DOM controls. For canvas-like productivity apps and rich editors — including Google Docs, Google Sheets, Lark/Feishu Docs, Notion, Figma, whiteboards, maps, and other virtualized editors — use the visual workflow first for the main editing surface. These apps often expose toolbars, title inputs, hidden textareas, offscreen iframes, or canvas layers in the DOM that do not represent the actual user-editable document or grid. Do not rely on `await fillInput(...)`, DOM selectors, or `snapshotText()` refs for the main editing surface unless a small write probe proves the text lands in the intended place.
+Use the semantic workflow first for ordinary websites with real DOM controls. For canvas-like productivity apps and rich editors — including Google Docs, Google Sheets, Lark/Feishu Docs, Notion, Figma, whiteboards, maps, and other virtualized editors — use the visual workflow first for the main editing surface. These apps often expose toolbars, title inputs, hidden textareas, offscreen iframes, or canvas layers in the DOM that do not represent the actual user-editable document or grid. Do not rely on `await fill(...)`, DOM selectors, or `snapshotText()` refs for the main editing surface unless a small write probe proves the text lands in the intended place.
-Before writing substantial content into a rich editor, perform a tiny write probe, then verify it with `await captureScreenshot()`, an export/readback path, or another reliable visual/state check. If the probe appears in the title bar, toolbar search, hidden input, or any wrong field, stop using DOM/input helpers for that surface and switch to screenshot-guided mouse actions plus real keyboard operations.
+Before writing substantial content into a rich editor, perform a tiny write probe, then verify it with `await screenshot()`, an export/readback path, or another reliable visual/state check. If the probe appears in the title bar, toolbar search, hidden input, or any wrong field, stop using DOM/input helpers for that surface and switch to screenshot-guided mouse actions plus real keyboard operations.
1. **Semantic workflow: `snapshotText()` + refs / locators** — default for most pages with normal text, links, buttons, forms, tables, and lists.
- Reuse or create a task space: `const task = await useOrCreateTaskSpace(name)`.
- - Open or switch pages with `await openOrReuseTab(url, { wait: true })`; use `await gotoAndWait(url, { timeout, settle })` only when navigating inside the current tab.
+ - Open or switch pages with `await openOrReuseTab(url, { wait: true })`; use `await goto(url, { timeout, settle })` only when navigating inside the current tab.
- Observe with `await snapshotText()` to get a full-page semantic tree annotated with `[ref=N, loc=..., url=...]`.
- - Act with `await click('@N')`, `await fillInput('@N', ...)`, or stable `loc=...` values. Use direct DOM logic only when it is simpler than helper calls.
- - After meaningful clicks, input, or navigation, observe again with `await snapshotText()`, `await pageInfo()`, or `await captureScreenshot()` before assuming success.
+ - Act with `await click('@N')`, `await fill('@N', ...)`, or stable `loc=...` values. Use direct DOM logic only when it is simpler than helper calls.
+ - After meaningful clicks, input, or navigation, observe again with `await snapshotText()`, `await pageInfo()`, or `await screenshot()` before assuming success.
-2. **Visual workflow: `await captureScreenshot()` + coordinate/keyboard actions** — use when the page is primarily visual, canvas-like, heavily virtualized, or when accessibility / semantic structure is incomplete.
- - Inspect the screenshot, act with viewport coordinates such as `await click([x, y])`, `await doubleClick([x, y])`, `await pressKey(...)`, and `await typeText(...)`, then verify with another screenshot or a reliable export/readback path.
+2. **Visual workflow: `await screenshot()` + coordinate/keyboard actions** — use when the page is primarily visual, canvas-like, heavily virtualized, or when accessibility / semantic structure is incomplete.
+ - Inspect the screenshot, act with viewport coordinates such as `await click([x, y])`, `await dblclick([x, y])`, `await press(...)`, and `await insertText(...)`, then verify with another screenshot or a reliable export/readback path.
- Prefer this path for rich editors, spreadsheets, visual menus, map/canvas UIs, drag interactions, and targets that are obvious visually but poor in the DOM/AX tree.
-3. **Direct DOM / CDP workflow: `await js(...)` / `await cdp(...)`** — use when you need browser state, compact data extraction, custom DOM traversal, or raw browser capabilities.
+3. **Direct DOM / CDP workflow: `await evaluate(...)` / `await cdp(...)`** — use when you need browser state, compact data extraction, custom DOM traversal, or raw browser capabilities.
- Keep browser-side logic in one explicit IIFE and return once.
- Use `await cdp(...)` for browser protocol operations that helpers do not cover.
@@ -196,14 +196,14 @@ These workflows can be combined. A task may take multiple heredoc rounds when th
## Caveats
-- `wait(...)` and `timeout` values are in **seconds**; only parameters whose names end in `Ms` are milliseconds.
+- Time values are in **milliseconds** (Playwright-style): `waitForTimeout(ms)`, and `timeout` / `settle` on `goto`, `waitForLoadState`, `waitForSelector`, `openOrReuseTab`. Exceptions still in **seconds**: `serverFetch` / `browserFetch` `timeout`, `waitForAgentControl` `interval` / `timeout`, and `scrollToBottomUntil`'s `wait`.
- `snapshotText()` defaults to `scope: 'full_page'`, covering the whole page. Use the default in almost every case; only pass `scope: 'only_within_viewport'` when the task needs only visible content.
- `@N` refs are only valid for the most recent `snapshotText` call — every call rebuilds the refMap. Ref numbers come from the CDP `backendNodeId`, so the same element keeps the same number across calls; but to use `@N`, N must appear in the latest snapshotText output. An element scrolled out of the viewport, a DOM re-render, or a previous call with `scope:'only_within_viewport'` that didn't cover the element will all cause `Unknown ref`. For elements you need to reference long-term, use the `loc=...` value from snapshotText output as a stable selector, or write a CSS selector directly.
-- `js()` returns the evaluated result, not a JSON string — don't wrap it with `JSON.parse(...)`.
-- Inside a `js(...)` template string, regex backslashes must be doubled (e.g. `\\d`, `\\s`), or use `String.raw`.
-- If the source passed to `js()` contains a top-level `return`, it will be auto-wrapped in an IIFE; `return` inside nested callbacks can also trigger this accidentally. For complex expressions, prefer the explicit `(() => { ... })()` form.
-- If `await pageInfo()` reports `w: 0` or `h: 0`, do not continue coordinate actions or screenshots until the viewport is fixed. Try switching to the real tab, reloading, or using CDP viewport metrics, then verify with `await pageInfo()` and `await captureScreenshot()`.
-- Code in the heredoc body runs in Node.js; code inside `js(...)` runs in the browser page. Navigation, waits, and `cliLog(...)` belong in the heredoc body; `document`, `window`, and page selectors belong inside `js(...)`.
+- `evaluate()` returns the evaluated result, not a JSON string — don't wrap it with `JSON.parse(...)`.
+- Inside a `evaluate(...)` template string, regex backslashes must be doubled (e.g. `\\d`, `\\s`), or use `String.raw`.
+- If the source passed to `evaluate()` contains a top-level `return`, it will be auto-wrapped in an IIFE; `return` inside nested callbacks can also trigger this accidentally. For complex expressions, prefer the explicit `(() => { ... })()` form.
+- If `await pageInfo()` reports `w: 0` or `h: 0`, do not continue coordinate actions or screenshots until the viewport is fixed. Try switching to the real tab, reloading, or using CDP viewport metrics, then verify with `await pageInfo()` and `await screenshot()`.
+- Code in the heredoc body runs in Node.js; code inside `evaluate(...)` runs in the browser page. Navigation, waits, and `cliLog(...)` belong in the heredoc body; `document`, `window`, and page selectors belong inside `evaluate(...)`.
- Always call `completeTaskSpace(name, { keep })` when the task is done — do not leave the space hanging. Default to `{ keep: false }`; use `{ keep: true }` only for the concrete live-page cases described in Task spaces.
- When the user explicitly asks to use ego-browser, assume both `ego-browser` and the repo runtime are ready. Do not pre-check `which ego-browser`, `node -v`, package metadata, or help output. Only investigate environment issues if the first run produces an error.
- If the first run reports `command not found` / a missing environment (most likely ego lite isn't installed yet), or the user explicitly asks to install ego lite, first read `references/install.md` and follow its flow to complete the install, then return to the original task — do not give up, and do not keep retrying the same heredoc.