@gnawbit/tabretake 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/scripts/init.mjs CHANGED
@@ -5,35 +5,73 @@ import { createReporter } from "./lib/report.mjs";
5
5
  import { resolveTheme } from "./lib/themes.mjs";
6
6
  import { extractPlan } from "./plan.mjs";
7
7
 
8
+ function scoreElement(el) {
9
+ const hints = el._hints || {};
10
+ let score = 0;
11
+ if (hints.isDestructive) score -= 100;
12
+ if (hints.emptyHref) score -= 80;
13
+ if (hints.hiddenContainer) score -= 90;
14
+ if (hints.inNav) score -= 40;
15
+ if (hints.inMain) score += 30;
16
+ if (hints.inForm) score += 25;
17
+ if (hints.isPrimary) score += 45;
18
+ if (hints.isSearch && !hints.inForm) score -= 15;
19
+ if (el.tag === "button" || el.role === "button") score += 20;
20
+ if (el.tag === "input" || el.tag === "textarea" || el.role === "textbox") score += 25;
21
+ if (el.tag === "select") score += 22;
22
+ if (el.text || el.label) score += 5;
23
+ return score;
24
+ }
25
+
8
26
  export function buildAutoSteps(elements) {
9
27
  const steps = [{ action: "wait", ms: 600 }];
10
- const interactive = (elements || []).filter((el) => {
11
- if (el.type === "password" || el.type === "hidden") return false;
12
- return Boolean(el.selector && (el.text || el.label || el.placeholder || el.name));
13
- });
28
+ const interactive = (elements || [])
29
+ .filter((el) => {
30
+ if (el.type === "password" || el.type === "hidden" || el.type === "checkbox" || el.type === "radio") return false;
31
+ if (el._hints?.isDestructive || el._hints?.emptyHref) return false;
32
+ return Boolean(el.selector && (el.text || el.label || el.placeholder || el.name));
33
+ })
34
+ .map((el, index) => ({ el, index, score: scoreElement(el) }));
35
+
36
+ const isTextInput = (el) =>
37
+ el.tag === "input" || el.tag === "textarea" || el.role === "textbox";
38
+ const isSelect = (el) => el.tag === "select" && Array.isArray(el.options) &&
39
+ el.options.some((o) => !o.disabled && o.value !== "");
40
+ const isButton = (el) =>
41
+ el.tag === "button" || el.tag === "a" || el.role === "button" || el.role === "link";
14
42
 
15
- const inputs = interactive.filter((el) => el.tag === "input" || el.tag === "textarea" || el.role === "textbox");
16
- const buttons = interactive.filter((el) => el.tag === "button" || el.tag === "a" || el.role === "button" || el.role === "link");
43
+ const byScoreThenOrder = (a, b) => (b.score - a.score) || (a.index - b.index);
44
+ const inputs = interactive.filter(({ el }) => isTextInput(el)).sort(byScoreThenOrder);
45
+ const selects = interactive.filter(({ el }) => isSelect(el)).sort(byScoreThenOrder);
46
+ const buttons = interactive.filter(({ el }) => isButton(el)).sort(byScoreThenOrder);
17
47
 
18
48
  const chosen = [];
19
- if (inputs.length > 0) {
20
- chosen.push(inputs[0]);
21
- }
22
- for (const btn of buttons) {
23
- if (chosen.length >= 3) break;
24
- if (!chosen.some((c) => c.selector === btn.selector)) {
25
- chosen.push(btn);
49
+ const addChosen = (entry) => {
50
+ if (!entry || chosen.length >= 3) return;
51
+ if (!chosen.some((c) => c.el.selector === entry.el.selector)) {
52
+ chosen.push(entry);
26
53
  }
54
+ };
55
+
56
+ // Prefer primary non-search inputs first; if only topbar search exists and a primary CTA exists, put the primary CTA first.
57
+ const primaryBtn = buttons.find(({ el }) => el._hints?.isPrimary && !el._hints?.inNav);
58
+ const nonSearchInput = inputs.find(({ el }) => !el._hints?.isSearch);
59
+ if (nonSearchInput) {
60
+ addChosen(nonSearchInput);
61
+ addChosen(selects[0]);
62
+ addChosen(primaryBtn || buttons[0]);
63
+ } else {
64
+ addChosen(primaryBtn);
65
+ addChosen(selects[0]);
66
+ addChosen(inputs[0]);
67
+ for (const btn of buttons) addChosen(btn);
27
68
  }
28
- for (const el of interactive) {
29
- if (chosen.length >= 3) break;
30
- if (!chosen.some((c) => c.selector === el.selector)) {
31
- chosen.push(el);
32
- }
69
+ for (const item of [...interactive].sort(byScoreThenOrder)) {
70
+ addChosen(item);
33
71
  }
34
72
 
35
- for (const el of chosen) {
36
- if (el.tag === "input" || el.tag === "textarea" || el.role === "textbox") {
73
+ for (const [idx, { el }] of chosen.sort((a, b) => a.index - b.index).entries()) {
74
+ if (isTextInput(el)) {
37
75
  const caption = el.label || el.placeholder || (el.name ? `Enter ${el.name}` : "Input demo text");
38
76
  steps.push({
39
77
  action: "type",
@@ -42,6 +80,16 @@ export function buildAutoSteps(elements) {
42
80
  pause: 400,
43
81
  caption: `Input: ${caption}`,
44
82
  });
83
+ } else if (isSelect(el)) {
84
+ const opt = el.options.find((o) => !o.disabled && o.value !== "") || el.options.find((o) => !o.disabled);
85
+ const caption = el.label || opt?.label || "Choose option";
86
+ steps.push({
87
+ action: "select",
88
+ selector: el.selector,
89
+ value: opt.value,
90
+ pause: 500,
91
+ caption: `Select: ${caption}`,
92
+ });
45
93
  } else {
46
94
  const caption = el.text || el.label || (el.role ? `${el.role}` : "Click target");
47
95
  steps.push({
@@ -51,13 +99,11 @@ export function buildAutoSteps(elements) {
51
99
  caption: `Click: ${caption}`,
52
100
  });
53
101
  }
54
- steps.push({ action: "wait", ms: 600 });
102
+ steps.push({ action: "wait", ms: idx === chosen.length - 1 ? 1200 : 600 });
55
103
  }
56
104
 
57
105
  if (steps.length === 1) {
58
106
  steps.push({ action: "wait", ms: 1500 });
59
- } else {
60
- steps.push({ action: "wait", ms: 1200 });
61
107
  }
62
108
  return steps;
63
109
  }
@@ -81,7 +127,7 @@ export async function init(argv) {
81
127
  if (values.auto) {
82
128
  reporter.log("Scanning page to generate interactive steps (--auto)...");
83
129
  try {
84
- const { elements } = await extractPlan(url.href, { browser: values.browser });
130
+ const { elements } = await extractPlan(url.href, { browser: values.browser, includeHints: true });
85
131
  steps = buildAutoSteps(elements);
86
132
  reporter.log(`Generated ${steps.length} step(s) from discovered interactive controls.`);
87
133
  } catch (err) {
@@ -3,7 +3,9 @@ import { chmod, copyFile, mkdir } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { chromium, errors } from "playwright";
5
5
  import { FFMPEG } from "./ffmpeg.mjs";
6
+ import { navigate } from "./navigation.mjs";
6
7
  import { VALID_BROWSERS, findSystemBrowser } from "./system-browser.mjs";
8
+ import { waitForEnter } from "./tty.mjs";
7
9
 
8
10
  export { VALID_BROWSERS, findSystemBrowser };
9
11
 
@@ -11,6 +13,7 @@ export async function launchBrowser({
11
13
  headless = true,
12
14
  proxy,
13
15
  browser = "auto",
16
+ scale = 1,
14
17
  launch = (opts) => chromium.launch(opts),
15
18
  hasBundledChromium = () => existsSync(chromium.executablePath()),
16
19
  } = {}) {
@@ -19,10 +22,15 @@ export async function launchBrowser({
19
22
  throw new Error(`Unsupported --browser "${mode}". Choose auto, chromium, chrome or msedge.`);
20
23
  }
21
24
 
25
+ const args = ["--disable-blink-features=AutomationControlled"];
26
+ if (Number(scale) > 1) {
27
+ args.push(`--force-device-scale-factor=${Number(scale)}`);
28
+ }
29
+
22
30
  const base = {
23
31
  headless,
24
32
  proxy: proxy ? { server: proxy } : undefined,
25
- args: ["--disable-blink-features=AutomationControlled"],
33
+ args,
26
34
  };
27
35
 
28
36
  if (mode === "chrome" || mode === "msedge") {
@@ -47,17 +55,23 @@ export async function launchBrowser({
47
55
  export async function newContext(browser, options) {
48
56
  const {
49
57
  viewport = { width: 1440, height: 810 },
58
+ scale = 1,
50
59
  videoDir,
51
60
  storageState,
52
61
  } = options;
62
+ const deviceScaleFactor = Number(scale) || 1;
53
63
 
54
64
  const context = await browser.newContext({
55
65
  viewport,
66
+ deviceScaleFactor,
56
67
  storageState: storageState || undefined,
57
68
  recordVideo: videoDir
58
69
  ? {
59
70
  dir: videoDir,
60
- size: { width: viewport.width, height: viewport.height },
71
+ size: {
72
+ width: viewport.width * deviceScaleFactor,
73
+ height: viewport.height * deviceScaleFactor,
74
+ },
61
75
  }
62
76
  : undefined,
63
77
  });
@@ -91,12 +105,22 @@ export async function openRecordedPage(
91
105
  }
92
106
  }
93
107
 
108
+ function accentRgba(hex, alpha) {
109
+ const clean = String(hex || "#6c5ce7").replace("#", "");
110
+ const full = clean.length === 3 ? clean.split("").map((c) => c + c).join("") : clean;
111
+ const n = Number.parseInt(full, 16);
112
+ if (!Number.isFinite(n)) return `rgba(108,92,231,${alpha})`;
113
+ return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${alpha})`;
114
+ }
115
+
94
116
  /**
95
117
  * Draws a fake cursor + click ripple on top of the page, so the recording
96
118
  * looks like a human is using it.
97
119
  */
98
- export async function installCursor(page) {
99
- await page.addInitScript(() => {
120
+ export async function installCursor(page, { accent = "#6c5ce7" } = {}) {
121
+ const rippleBg = accentRgba(accent, 0.35);
122
+ const rippleBorder = accentRgba(accent, 0.85);
123
+ await page.addInitScript(({ rippleBg, rippleBorder }) => {
100
124
  if (window.__tabretakeCursorInstalled) return;
101
125
  window.__tabretakeCursorInstalled = true;
102
126
 
@@ -108,7 +132,7 @@ export async function installCursor(page) {
108
132
  }
109
133
  #__tabretake_ripple {
110
134
  position: fixed; width: 14px; height: 14px; border-radius: 50%;
111
- background: rgba(108,92,231,.35); border: 2px solid rgba(255,255,255,.9);
135
+ background: ${rippleBg}; border: 2px solid ${rippleBorder};
112
136
  z-index: 2147483646; pointer-events: none;
113
137
  transform: translate(-50%,-50%) scale(.2); opacity: 0;
114
138
  }
@@ -116,7 +140,6 @@ export async function installCursor(page) {
116
140
 
117
141
  const style = document.createElement("style");
118
142
  style.textContent = CSS;
119
- document.documentElement.appendChild(style);
120
143
 
121
144
  const cursor = document.createElement("div");
122
145
  cursor.id = "__tabretake_cursor";
@@ -125,18 +148,28 @@ export async function installCursor(page) {
125
148
  <path d="M4 2L20.5 12.2L12.6 13.7L9.1 21.2L4 2Z"
126
149
  fill="#fff" stroke="#111" stroke-width="1.4" stroke-linejoin="round"/>
127
150
  </svg>`;
128
- document.documentElement.appendChild(cursor);
129
151
 
130
152
  const move = (x, y) => {
131
153
  cursor.style.transform = `translate(${x - 2}px, ${y - 2}px)`;
132
154
  };
133
155
 
156
+ const mount = () => {
157
+ if (!document.documentElement || document.getElementById("__tabretake_cursor")) return;
158
+ document.documentElement.appendChild(style);
159
+ document.documentElement.appendChild(cursor);
160
+ move(window.innerWidth / 2, window.innerHeight / 2);
161
+ };
162
+ if (document.documentElement) mount();
163
+ window.addEventListener("DOMContentLoaded", mount, { once: true });
164
+
134
165
  const ripple = (x, y) => {
166
+ const root = document.body || document.documentElement;
167
+ if (!root) return;
135
168
  const r = document.createElement("div");
136
169
  r.id = "__tabretake_ripple";
137
170
  r.style.left = `${x}px`;
138
171
  r.style.top = `${y}px`;
139
- document.documentElement.appendChild(r);
172
+ root.appendChild(r);
140
173
  r.animate(
141
174
  [
142
175
  { transform: "translate(-50%,-50%) scale(.2)", opacity: 1 },
@@ -149,8 +182,7 @@ export async function installCursor(page) {
149
182
 
150
183
  window.addEventListener("mousemove", (e) => move(e.clientX, e.clientY), true);
151
184
  window.addEventListener("mousedown", (e) => ripple(e.clientX, e.clientY), true);
152
- move(window.innerWidth / 2, window.innerHeight / 2);
153
- });
185
+ }, { rippleBg, rippleBorder });
154
186
  }
155
187
 
156
188
  export async function resolveLocator(page, step) {
@@ -258,6 +290,42 @@ export async function dragBy(page, locator, dx, dy = 0, steps = 24, pause = 600)
258
290
  return { x: endX, y: endY };
259
291
  }
260
292
 
293
+ export async function selectOption(page, locator, value, pause = 500, timeout = 20000) {
294
+ const deadline = Date.now() + timeout;
295
+ const remaining = () => {
296
+ const ms = deadline - Date.now();
297
+ if (ms <= 0) throw new errors.TimeoutError("Timed out waiting for an actionable select target.");
298
+ return ms;
299
+ };
300
+ await locator.waitFor({ state: "visible", timeout: remaining() });
301
+ await locator.scrollIntoViewIfNeeded({ timeout: remaining() });
302
+ const box = await locator.boundingBox({ timeout: remaining() });
303
+ if (!box) throw new Error("Element has no bounding box");
304
+
305
+ const x = box.x + box.width / 2;
306
+ const y = box.y + box.height / 2;
307
+ await page.mouse.move(x, y, { steps: 16 });
308
+ await page.waitForTimeout(100);
309
+
310
+ const target = String(value ?? "");
311
+ const matched = await locator.evaluate((el, raw) => {
312
+ if (el.tagName !== "SELECT") return null;
313
+ const opts = [...el.options];
314
+ const byValue = opts.find((o) => o.value === raw);
315
+ if (byValue) return { value: byValue.value };
316
+ const byLabel = opts.find((o) => (o.label || o.textContent || "").trim() === raw);
317
+ if (byLabel) return { value: byLabel.value };
318
+ return null;
319
+ }, target);
320
+
321
+ if (!matched) {
322
+ throw Object.assign(new Error("Could not find a matching option for select step."), { code: "TARGET_NOT_FOUND" });
323
+ }
324
+ await locator.selectOption(matched, { timeout: remaining() });
325
+ await page.waitForTimeout(pause);
326
+ return { x, y };
327
+ }
328
+
261
329
  export async function hover(page, locator, pause = 500) {
262
330
  await locator.scrollIntoViewIfNeeded();
263
331
  const box = await locator.boundingBox();
@@ -268,3 +336,25 @@ export async function hover(page, locator, pause = 500) {
268
336
  await page.waitForTimeout(pause);
269
337
  return { x, y };
270
338
  }
339
+
340
+ export async function loginAndSave(url, {
341
+ proxy,
342
+ viewport,
343
+ browser: browserMode,
344
+ statePath = path.resolve("auth.json"),
345
+ } = {}) {
346
+ const browser = await launchBrowser({ headless: false, proxy, browser: browserMode });
347
+ try {
348
+ const context = await newContext(browser, { viewport });
349
+ const page = await context.newPage();
350
+ await navigate(page, url, { allowAuthErrors: true });
351
+ console.log("\nA browser window is open. Log in, then come back here.");
352
+ await waitForEnter("Press Enter when you are logged in... ");
353
+ await context.storageState({ path: statePath });
354
+ console.log(`Saved login state to ${statePath}\n`);
355
+ await context.close();
356
+ return statePath;
357
+ } finally {
358
+ await browser.close();
359
+ }
360
+ }
@@ -33,6 +33,61 @@ export const commandOptions = {
33
33
  viewport: { type: "string" },
34
34
  headed: { type: "boolean", default: false },
35
35
  browser: { type: "string", default: "auto" },
36
+ scale: { type: "string" },
37
+ },
38
+ run: {
39
+ json: { type: "boolean", default: false },
40
+ config: { type: "string" },
41
+ url: { type: "string" },
42
+ out: { type: "string" },
43
+ login: { type: "boolean", default: false },
44
+ "storage-state": { type: "string" },
45
+ "save-state": { type: "string" },
46
+ proxy: { type: "string" },
47
+ viewport: { type: "string" },
48
+ headed: { type: "boolean", default: false },
49
+ browser: { type: "string", default: "auto" },
50
+ scale: { type: "string" },
51
+ "no-gif": { type: "boolean", default: false },
52
+ "no-captions": { type: "boolean", default: false },
53
+ vertical: { type: "boolean", default: false },
54
+ zoom: { type: "string", default: "1.28" },
55
+ "vertical-zoom": { type: "string" },
56
+ "zoom-duration": { type: "string" },
57
+ "poster-at": { type: "string" },
58
+ preset: { type: "string" },
59
+ },
60
+ capture: {
61
+ json: { type: "boolean", default: false },
62
+ url: { type: "string" },
63
+ out: { type: "string", default: "demo.json" },
64
+ login: { type: "boolean", default: false },
65
+ "storage-state": { type: "string" },
66
+ "save-state": { type: "string" },
67
+ proxy: { type: "string" },
68
+ viewport: { type: "string" },
69
+ browser: { type: "string", default: "auto" },
70
+ preset: { type: "string" },
71
+ scale: { type: "string" },
72
+ force: { type: "boolean", default: false },
73
+ run: { type: "boolean", default: false },
74
+ "media-out": { type: "string" },
75
+ "no-gif": { type: "boolean", default: false },
76
+ "no-captions": { type: "boolean", default: false },
77
+ vertical: { type: "boolean", default: false },
78
+ zoom: { type: "string", default: "1.28" },
79
+ "vertical-zoom": { type: "string" },
80
+ "zoom-duration": { type: "string" },
81
+ "poster-at": { type: "string" },
82
+ },
83
+ mark: {
84
+ json: { type: "boolean", default: false },
85
+ video: { type: "string" },
86
+ out: { type: "string", default: "story-video.json" },
87
+ preset: { type: "string" },
88
+ port: { type: "string", default: "0" },
89
+ "media-out": { type: "string" },
90
+ "no-open": { type: "boolean", default: false },
36
91
  },
37
92
  render: {
38
93
  json: { type: "boolean", default: false },
@@ -72,3 +127,12 @@ commandOptions.preview = {
72
127
  export function parseCommand(command, argv) {
73
128
  return parseArgs({ args: argv, options: commandOptions[command], strict: true, allowPositionals: false });
74
129
  }
130
+
131
+ export function parseViewport(value, fallback = { width: 1440, height: 810 }) {
132
+ if (value === undefined) return fallback;
133
+ if (!/^[1-9]\d*x[1-9]\d*$/.test(value)) {
134
+ throw new Error("--viewport must be WIDTHxHEIGHT with positive integers");
135
+ }
136
+ const [width, height] = value.split("x").map(Number);
137
+ return { width, height };
138
+ }
@@ -17,6 +17,7 @@ export function requireInteractiveLogin(values) {
17
17
  export function createReporter(command, json) {
18
18
  return {
19
19
  log: (...args) => (json ? console.error : console.log)(...args),
20
+ warn: (...args) => console.error(...args),
20
21
  async success({ artifacts, ...details }) {
21
22
  if (!json) return;
22
23
  const files = await Promise.all(artifacts.map(async (artifact) => {