@gnawbit/tabretake 0.4.2 → 0.5.1

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
@@ -1,39 +1,77 @@
1
1
  import { mkdir, writeFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { parseCommand } from "./lib/options.mjs";
3
+ import { parseCommand, parseHttpUrl } from "./lib/options.mjs";
4
4
  import { createReporter } from "./lib/report.mjs";
5
5
  import { resolveTheme } from "./lib/themes.mjs";
6
6
  import { extractPlan } from "./plan.mjs";
7
7
 
8
- export function buildAutoSteps(elements) {
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
+
26
+ 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) }));
14
35
 
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");
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";
42
+
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
  }
@@ -66,26 +112,17 @@ export async function init(argv) {
66
112
  const { values } = parseCommand("init", argv);
67
113
  const reporter = createReporter("init", values.json);
68
114
 
69
- if (!values.url) throw new Error("Provide --url https://your-app.com");
70
- let url;
71
- try {
72
- url = new URL(values.url);
73
- } catch {
74
- throw new Error("Use a complete http:// or https:// URL");
75
- }
76
- if (!["http:", "https:"].includes(url.protocol)) {
77
- throw new Error("Use a complete http:// or https:// URL");
78
- }
115
+ const url = parseHttpUrl(values.url);
79
116
 
80
117
  let steps = [{ action: "wait", ms: 1500 }];
81
118
  if (values.auto) {
82
119
  reporter.log("Scanning page to generate interactive steps (--auto)...");
83
120
  try {
84
- const { elements } = await extractPlan(url.href, { browser: values.browser });
121
+ const { elements } = await extractPlan(url.href, { browser: values.browser, includeHints: true });
85
122
  steps = buildAutoSteps(elements);
86
123
  reporter.log(`Generated ${steps.length} step(s) from discovered interactive controls.`);
87
124
  } catch (err) {
88
- reporter.warn(`Could not scan page for --auto (${err.message}); falling back to starter.`);
125
+ reporter.warn(`Could not scan page for --auto (${err.message}); falling back to starter.${err.hint ? ` ${err.hint}` : ""}`);
89
126
  }
90
127
  }
91
128
 
@@ -3,14 +3,45 @@ 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";
7
+ import { commandError } from "./report.mjs";
6
8
  import { VALID_BROWSERS, findSystemBrowser } from "./system-browser.mjs";
9
+ import { hexToRgb } from "./themes.mjs";
10
+ import { waitForEnter } from "./tty.mjs";
7
11
 
8
12
  export { VALID_BROWSERS, findSystemBrowser };
9
13
 
14
+ function classifyBrowserError(error, mode) {
15
+ const text = String(error?.message || error || "");
16
+ if (/Host system is missing dependencies|error while loading shared libraries|lib[a-z0-9_.-]+\.so/i.test(text)) {
17
+ return commandError("BROWSER_DEPS_MISSING", "Browser failed to start because required system libraries are missing.", {
18
+ hint: "Run tabretake setup --with-deps to install required browser system libraries.",
19
+ });
20
+ }
21
+ if (/Executable doesn't exist|Chromium distribution .* is not found|cannot find .*(?:chrome|msedge|chromium)/i.test(text)) {
22
+ if (mode === "chrome" || mode === "msedge") {
23
+ const label = mode === "chrome" ? "Google Chrome" : "Microsoft Edge";
24
+ return commandError("BROWSER_MISSING", `${label} is not installed or could not be found.`, {
25
+ hint: `Install ${label}, or omit --browser ${mode} to use automatic browser detection / tabretake setup.`,
26
+ });
27
+ }
28
+ if (mode === "chromium") {
29
+ return commandError("BROWSER_MISSING", "Playwright Chromium is not installed.", {
30
+ hint: "Run tabretake setup (or tabretake setup --with-deps on Linux) to install Chromium.",
31
+ });
32
+ }
33
+ return commandError("BROWSER_MISSING", "No usable browser found (Playwright Chromium, Google Chrome, or Microsoft Edge).", {
34
+ hint: "Run tabretake setup (or tabretake setup --with-deps on Linux) to install Chromium, or install Chrome/Edge.",
35
+ });
36
+ }
37
+ return error;
38
+ }
39
+
10
40
  export async function launchBrowser({
11
41
  headless = true,
12
42
  proxy,
13
43
  browser = "auto",
44
+ scale = 1,
14
45
  launch = (opts) => chromium.launch(opts),
15
46
  hasBundledChromium = () => existsSync(chromium.executablePath()),
16
47
  } = {}) {
@@ -19,45 +50,71 @@ export async function launchBrowser({
19
50
  throw new Error(`Unsupported --browser "${mode}". Choose auto, chromium, chrome or msedge.`);
20
51
  }
21
52
 
53
+ const args = ["--disable-blink-features=AutomationControlled"];
54
+ if (Number(scale) > 1) {
55
+ args.push(`--force-device-scale-factor=${Number(scale)}`);
56
+ }
57
+
22
58
  const base = {
23
59
  headless,
24
60
  proxy: proxy ? { server: proxy } : undefined,
25
- args: ["--disable-blink-features=AutomationControlled"],
61
+ args,
62
+ };
63
+
64
+ const runLaunch = async (opts, errorMode) => {
65
+ try {
66
+ return await launch(opts);
67
+ } catch (error) {
68
+ throw classifyBrowserError(error, errorMode);
69
+ }
26
70
  };
27
71
 
28
72
  if (mode === "chrome" || mode === "msedge") {
29
- return launch({ ...base, channel: mode });
73
+ return runLaunch({ ...base, channel: mode }, mode);
30
74
  }
31
75
 
32
76
  if (mode === "chromium" || hasBundledChromium()) {
33
- return launch(base);
77
+ return runLaunch(base, mode);
34
78
  }
35
79
 
80
+ let depsError = null;
81
+ let fallbackError = null;
36
82
  for (const channel of ["chrome", "msedge"]) {
37
83
  try {
38
- return await launch({ ...base, channel });
39
- } catch {
40
- // Continue trying next installed system browser channel.
84
+ return await runLaunch({ ...base, channel }, mode);
85
+ } catch (error) {
86
+ if (error.code === "BROWSER_DEPS_MISSING") depsError ||= error;
87
+ else if (error.code !== "BROWSER_MISSING") fallbackError ||= error;
41
88
  }
42
89
  }
43
90
 
44
- return launch(base);
91
+ if (depsError) throw depsError;
92
+ if (fallbackError) throw fallbackError;
93
+ throw commandError("BROWSER_MISSING", "No usable browser found (Playwright Chromium, Google Chrome, or Microsoft Edge).", {
94
+ hint: "Run tabretake setup (or tabretake setup --with-deps on Linux) to install Chromium, or install Chrome/Edge.",
95
+ });
45
96
  }
46
97
 
47
98
  export async function newContext(browser, options) {
48
99
  const {
49
100
  viewport = { width: 1440, height: 810 },
101
+ scale = 1,
50
102
  videoDir,
51
103
  storageState,
52
104
  } = options;
105
+ const deviceScaleFactor = Number(scale) || 1;
53
106
 
54
107
  const context = await browser.newContext({
55
108
  viewport,
109
+ deviceScaleFactor,
56
110
  storageState: storageState || undefined,
57
111
  recordVideo: videoDir
58
112
  ? {
59
113
  dir: videoDir,
60
- size: { width: viewport.width, height: viewport.height },
114
+ size: {
115
+ width: viewport.width * deviceScaleFactor,
116
+ height: viewport.height * deviceScaleFactor,
117
+ },
61
118
  }
62
119
  : undefined,
63
120
  });
@@ -91,12 +148,19 @@ export async function openRecordedPage(
91
148
  }
92
149
  }
93
150
 
151
+ function accentRgba(hex, alpha) {
152
+ const { r, g, b } = hexToRgb(hex, "#6c5ce7");
153
+ return `rgba(${r},${g},${b},${alpha})`;
154
+ }
155
+
94
156
  /**
95
157
  * Draws a fake cursor + click ripple on top of the page, so the recording
96
158
  * looks like a human is using it.
97
159
  */
98
- export async function installCursor(page) {
99
- await page.addInitScript(() => {
160
+ export async function installCursor(page, { accent = "#6c5ce7" } = {}) {
161
+ const rippleBg = accentRgba(accent, 0.35);
162
+ const rippleBorder = accentRgba(accent, 0.85);
163
+ await page.addInitScript(({ rippleBg, rippleBorder }) => {
100
164
  if (window.__tabretakeCursorInstalled) return;
101
165
  window.__tabretakeCursorInstalled = true;
102
166
 
@@ -108,7 +172,7 @@ export async function installCursor(page) {
108
172
  }
109
173
  #__tabretake_ripple {
110
174
  position: fixed; width: 14px; height: 14px; border-radius: 50%;
111
- background: rgba(108,92,231,.35); border: 2px solid rgba(255,255,255,.9);
175
+ background: ${rippleBg}; border: 2px solid ${rippleBorder};
112
176
  z-index: 2147483646; pointer-events: none;
113
177
  transform: translate(-50%,-50%) scale(.2); opacity: 0;
114
178
  }
@@ -116,7 +180,6 @@ export async function installCursor(page) {
116
180
 
117
181
  const style = document.createElement("style");
118
182
  style.textContent = CSS;
119
- document.documentElement.appendChild(style);
120
183
 
121
184
  const cursor = document.createElement("div");
122
185
  cursor.id = "__tabretake_cursor";
@@ -125,18 +188,28 @@ export async function installCursor(page) {
125
188
  <path d="M4 2L20.5 12.2L12.6 13.7L9.1 21.2L4 2Z"
126
189
  fill="#fff" stroke="#111" stroke-width="1.4" stroke-linejoin="round"/>
127
190
  </svg>`;
128
- document.documentElement.appendChild(cursor);
129
191
 
130
192
  const move = (x, y) => {
131
193
  cursor.style.transform = `translate(${x - 2}px, ${y - 2}px)`;
132
194
  };
133
195
 
196
+ const mount = () => {
197
+ if (!document.documentElement || document.getElementById("__tabretake_cursor")) return;
198
+ document.documentElement.appendChild(style);
199
+ document.documentElement.appendChild(cursor);
200
+ move(window.innerWidth / 2, window.innerHeight / 2);
201
+ };
202
+ if (document.documentElement) mount();
203
+ window.addEventListener("DOMContentLoaded", mount, { once: true });
204
+
134
205
  const ripple = (x, y) => {
206
+ const root = document.body || document.documentElement;
207
+ if (!root) return;
135
208
  const r = document.createElement("div");
136
209
  r.id = "__tabretake_ripple";
137
210
  r.style.left = `${x}px`;
138
211
  r.style.top = `${y}px`;
139
- document.documentElement.appendChild(r);
212
+ root.appendChild(r);
140
213
  r.animate(
141
214
  [
142
215
  { transform: "translate(-50%,-50%) scale(.2)", opacity: 1 },
@@ -149,8 +222,7 @@ export async function installCursor(page) {
149
222
 
150
223
  window.addEventListener("mousemove", (e) => move(e.clientX, e.clientY), true);
151
224
  window.addEventListener("mousedown", (e) => ripple(e.clientX, e.clientY), true);
152
- move(window.innerWidth / 2, window.innerHeight / 2);
153
- });
225
+ }, { rippleBg, rippleBorder });
154
226
  }
155
227
 
156
228
  export async function resolveLocator(page, step) {
@@ -258,6 +330,42 @@ export async function dragBy(page, locator, dx, dy = 0, steps = 24, pause = 600)
258
330
  return { x: endX, y: endY };
259
331
  }
260
332
 
333
+ export async function selectOption(page, locator, value, pause = 500, timeout = 20000) {
334
+ const deadline = Date.now() + timeout;
335
+ const remaining = () => {
336
+ const ms = deadline - Date.now();
337
+ if (ms <= 0) throw new errors.TimeoutError("Timed out waiting for an actionable select target.");
338
+ return ms;
339
+ };
340
+ await locator.waitFor({ state: "visible", timeout: remaining() });
341
+ await locator.scrollIntoViewIfNeeded({ timeout: remaining() });
342
+ const box = await locator.boundingBox({ timeout: remaining() });
343
+ if (!box) throw new Error("Element has no bounding box");
344
+
345
+ const x = box.x + box.width / 2;
346
+ const y = box.y + box.height / 2;
347
+ await page.mouse.move(x, y, { steps: 16 });
348
+ await page.waitForTimeout(100);
349
+
350
+ const target = String(value ?? "");
351
+ const matched = await locator.evaluate((el, raw) => {
352
+ if (el.tagName !== "SELECT") return null;
353
+ const opts = [...el.options];
354
+ const byValue = opts.find((o) => o.value === raw);
355
+ if (byValue) return { value: byValue.value };
356
+ const byLabel = opts.find((o) => (o.label || o.textContent || "").trim() === raw);
357
+ if (byLabel) return { value: byLabel.value };
358
+ return null;
359
+ }, target);
360
+
361
+ if (!matched) {
362
+ throw Object.assign(new Error("Could not find a matching option for select step."), { code: "TARGET_NOT_FOUND" });
363
+ }
364
+ await locator.selectOption(matched, { timeout: remaining() });
365
+ await page.waitForTimeout(pause);
366
+ return { x, y };
367
+ }
368
+
261
369
  export async function hover(page, locator, pause = 500) {
262
370
  await locator.scrollIntoViewIfNeeded();
263
371
  const box = await locator.boundingBox();
@@ -268,3 +376,25 @@ export async function hover(page, locator, pause = 500) {
268
376
  await page.waitForTimeout(pause);
269
377
  return { x, y };
270
378
  }
379
+
380
+ export async function loginAndSave(url, {
381
+ proxy,
382
+ viewport,
383
+ browser: browserMode,
384
+ statePath = path.resolve("auth.json"),
385
+ } = {}) {
386
+ const browser = await launchBrowser({ headless: false, proxy, browser: browserMode });
387
+ try {
388
+ const context = await newContext(browser, { viewport });
389
+ const page = await context.newPage();
390
+ await navigate(page, url, { allowAuthErrors: true });
391
+ console.log("\nA browser window is open. Log in, then come back here.");
392
+ await waitForEnter("Press Enter when you are logged in... ");
393
+ await context.storageState({ path: statePath });
394
+ console.log(`Saved login state to ${statePath}\n`);
395
+ await context.close();
396
+ return statePath;
397
+ } finally {
398
+ await browser.close();
399
+ }
400
+ }
@@ -2,7 +2,7 @@ import { readFile } from "node:fs/promises";
2
2
  import { readFileSync } from "node:fs";
3
3
  import Ajv from "ajv";
4
4
 
5
- export const configSchema = JSON.parse(readFileSync(new URL("../../schemas/story.schema.json", import.meta.url), "utf8"));
5
+ const configSchema = JSON.parse(readFileSync(new URL("../../schemas/story.schema.json", import.meta.url), "utf8"));
6
6
  const ajv = new Ajv({ allErrors: true, strictRequired: false });
7
7
  ajv.addFormat("uri", (value) => {
8
8
  try { new URL(value); return true; } catch { return false; }
@@ -3,7 +3,7 @@ import ffmpegInstaller from "@ffmpeg-installer/ffmpeg";
3
3
  import ffprobeInstaller from "@ffprobe-installer/ffprobe";
4
4
 
5
5
  export const FFMPEG = ffmpegInstaller.path;
6
- export const FFPROBE = ffprobeInstaller.path;
6
+ const FFPROBE = ffprobeInstaller.path;
7
7
 
8
8
  export function run(bin, args, { capture = false } = {}) {
9
9
  return new Promise((resolve, reject) => {
@@ -44,17 +44,14 @@ export async function probe(file) {
44
44
  return JSON.parse(stdout);
45
45
  }
46
46
 
47
- export async function duration(file) {
48
- const info = await probe(file);
49
- return Number(info.format?.duration || 0);
50
- }
51
-
52
- export async function videoSize(file) {
47
+ export async function probeVideoMeta(file) {
53
48
  const info = await probe(file);
54
49
  const stream = (info.streams || []).find((s) => s.codec_type === "video");
55
- return {
56
- width: Number(stream?.width || 0),
57
- height: Number(stream?.height || 0),
58
- duration: Number(info.format?.duration || 0),
59
- };
50
+ const width = Number(stream?.width || 0);
51
+ const height = Number(stream?.height || 0);
52
+ const duration = Number(info.format?.duration || 0);
53
+ if (!width || !height || !duration) {
54
+ throw new Error(`Could not read video metadata: ${file}`);
55
+ }
56
+ return { width, height, duration };
60
57
  }