@gnawbit/tabretake 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,60 @@
1
+ import { spawn } from "node:child_process";
2
+ import ffmpegInstaller from "@ffmpeg-installer/ffmpeg";
3
+ import ffprobeInstaller from "@ffprobe-installer/ffprobe";
4
+
5
+ export const FFMPEG = ffmpegInstaller.path;
6
+ export const FFPROBE = ffprobeInstaller.path;
7
+
8
+ export function run(bin, args, { capture = false } = {}) {
9
+ return new Promise((resolve, reject) => {
10
+ const child = spawn(bin, args, {
11
+ windowsHide: true,
12
+ stdio: ["ignore", capture ? "pipe" : "inherit", "pipe"],
13
+ });
14
+
15
+ let stdout = "";
16
+ let stderr = "";
17
+
18
+ if (child.stdout) child.stdout.on("data", (d) => (stdout += d.toString()));
19
+ child.stderr.on("data", (d) => (stderr += d.toString()));
20
+ child.on("error", reject);
21
+ child.on("close", (code) => {
22
+ if (code === 0) return resolve({ stdout, stderr });
23
+ reject(
24
+ new Error(
25
+ `${bin} exited with code ${code}\n${stderr.slice(-4000) || stdout.slice(-4000)}`,
26
+ ),
27
+ );
28
+ });
29
+ });
30
+ }
31
+
32
+ export function ffmpeg(args) {
33
+ return run(FFMPEG, ["-y", "-hide_banner", "-loglevel", "error", ...args], {
34
+ capture: true,
35
+ });
36
+ }
37
+
38
+ export async function probe(file) {
39
+ const { stdout } = await run(
40
+ FFPROBE,
41
+ ["-v", "error", "-print_format", "json", "-show_format", "-show_streams", file],
42
+ { capture: true },
43
+ );
44
+ return JSON.parse(stdout);
45
+ }
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) {
53
+ const info = await probe(file);
54
+ 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
+ };
60
+ }
@@ -0,0 +1,36 @@
1
+ import { existsSync } from "node:fs";
2
+
3
+ const LATIN_CANDIDATES = [
4
+ "C:/Windows/Fonts/segoeui.ttf",
5
+ "C:/Windows/Fonts/arial.ttf",
6
+ "C:/Windows/Fonts/Segoe UI.ttf",
7
+ "/System/Library/Fonts/Helvetica.ttc",
8
+ "/System/Library/Fonts/Supplemental/Arial.ttf",
9
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
10
+ "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
11
+ ];
12
+
13
+ const CJK_CANDIDATES = [
14
+ "C:/Windows/Fonts/msyh.ttc",
15
+ "C:/Windows/Fonts/msyhbd.ttc",
16
+ "C:/Windows/Fonts/simhei.ttf",
17
+ "C:/Windows/Fonts/simsun.ttc",
18
+ "/System/Library/Fonts/PingFang.ttc",
19
+ "/System/Library/Fonts/STHeiti Medium.ttc",
20
+ "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
21
+ "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
22
+ "/usr/share/fonts/opentype/noto/NotoSansCJKsc-Regular.otf",
23
+ "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
24
+ ];
25
+
26
+ export function findCjkFont() {
27
+ return CJK_CANDIDATES.find((p) => existsSync(p)) || null;
28
+ }
29
+
30
+ export function findFont() {
31
+ return LATIN_CANDIDATES.find((p) => existsSync(p)) || findCjkFont();
32
+ }
33
+
34
+ export function hasCjk(text) {
35
+ return /[\u3400-\u9fff\uf900-\ufaff]/.test(String(text || ""));
36
+ }
@@ -0,0 +1,14 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ const pkg = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
4
+ export const version = pkg.version;
5
+ export const name = pkg.name;
6
+ export const schemaVersion = 1;
7
+ export const nodeRange = pkg.engines.node;
8
+
9
+ export function supportsNodeVersion(value) {
10
+ const minimum = nodeRange.slice(2).split(".").map(Number);
11
+ const current = value.split(".").map(Number);
12
+ const index = minimum.findIndex((part, i) => part !== current[i]);
13
+ return index < 0 || current[index] > minimum[index];
14
+ }
@@ -0,0 +1,26 @@
1
+ import { commandError } from "./report.mjs";
2
+
3
+ // Keep URLs (which may contain credentials or tokens) out of error reports.
4
+ export async function navigate(page, url, { allowAuthErrors = false } = {}) {
5
+ let response;
6
+ try {
7
+ response = await page.goto(url, { waitUntil: "domcontentloaded", timeout: 45000 });
8
+ } catch (error) {
9
+ throw commandError("PAGE_UNREACHABLE", error.name === "TimeoutError"
10
+ ? "The target page did not finish loading in time."
11
+ : "Could not open the target page.", {
12
+ hint: "Check the target URL, start the app if it is local, and verify browser network/proxy access before retrying. doctor checks dependencies, not page access.",
13
+ });
14
+ }
15
+ const status = response?.status();
16
+ // A login page may return 401/403 before the user signs in manually.
17
+ if (status >= 400 && !(allowAuthErrors && (status === 401 || status === 403))) {
18
+ throw commandError("PAGE_HTTP_ERROR", `The target page returned HTTP ${status}.`, {
19
+ status,
20
+ hint: status === 401 || status === 403
21
+ ? "Check page permissions and login state. Use interactive --login if needed, then pass --storage-state; do not bypass access controls."
22
+ : "Check the target URL and app/server response. Retry after the page is available.",
23
+ });
24
+ }
25
+ return response;
26
+ }
@@ -0,0 +1,65 @@
1
+ import { parseArgs } from "node:util";
2
+
3
+ export const commandOptions = {
4
+ setup: { "with-deps": { type: "boolean", default: false } },
5
+ init: {
6
+ json: { type: "boolean", default: false },
7
+ url: { type: "string" },
8
+ out: { type: "string", default: "demo.json" },
9
+ },
10
+ plan: {
11
+ json: { type: "boolean", default: false },
12
+ url: { type: "string" },
13
+ out: { type: "string", default: "plan.json" },
14
+ login: { type: "boolean", default: false },
15
+ "storage-state": { type: "string" },
16
+ proxy: { type: "string" },
17
+ viewport: { type: "string" },
18
+ headless: { type: "boolean", default: true },
19
+ },
20
+ record: {
21
+ json: { type: "boolean", default: false },
22
+ config: { type: "string" },
23
+ url: { type: "string" },
24
+ out: { type: "string" },
25
+ login: { type: "boolean", default: false },
26
+ "storage-state": { type: "string" },
27
+ "save-state": { type: "string" },
28
+ proxy: { type: "string" },
29
+ viewport: { type: "string" },
30
+ headed: { type: "boolean", default: false },
31
+ },
32
+ render: {
33
+ json: { type: "boolean", default: false },
34
+ config: { type: "string" },
35
+ video: { type: "string" },
36
+ out: { type: "string" },
37
+ "no-gif": { type: "boolean", default: false },
38
+ "no-captions": { type: "boolean", default: false },
39
+ vertical: { type: "boolean", default: false },
40
+ zoom: { type: "string", default: "1.28" },
41
+ "zoom-duration": { type: "string" },
42
+ "poster-at": { type: "string" },
43
+ },
44
+ serve: {
45
+ port: { type: "string", default: "4173" },
46
+ dir: { type: "string", default: "examples/site" },
47
+ },
48
+ demo: {
49
+ out: { type: "string", default: "demo" },
50
+ port: { type: "string", default: "4173" },
51
+ story: { type: "string", default: "onboarding" },
52
+ },
53
+ doctor: { json: { type: "boolean", default: false } },
54
+ capabilities: { json: { type: "boolean", default: false } },
55
+ validate: { config: { type: "string" }, json: { type: "boolean", default: false } },
56
+ };
57
+
58
+ commandOptions.preview = {
59
+ ...commandOptions.record,
60
+ headless: { type: "boolean", default: false },
61
+ };
62
+
63
+ export function parseCommand(command, argv) {
64
+ return parseArgs({ args: argv, options: commandOptions[command], strict: true, allowPositionals: false });
65
+ }
@@ -0,0 +1,42 @@
1
+ import { stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { schemaVersion, version } from "./metadata.mjs";
4
+
5
+ export function commandError(code, message, details = {}) {
6
+ return Object.assign(new Error(message), { code, ...details });
7
+ }
8
+
9
+ export function requireInteractiveLogin(values) {
10
+ if (values.login && (values.json || !process.stdin.isTTY)) {
11
+ throw commandError("INTERACTIVE_LOGIN_REQUIRED", "Manual login requires an interactive terminal without --json.", {
12
+ hint: "Run plan or record with --login interactively, then pass --storage-state auth.json on automated runs.",
13
+ });
14
+ }
15
+ }
16
+
17
+ export function createReporter(command, json) {
18
+ return {
19
+ log: (...args) => (json ? console.error : console.log)(...args),
20
+ async success({ artifacts, ...details }) {
21
+ if (!json) return;
22
+ const files = await Promise.all(artifacts.map(async (artifact) => {
23
+ const file = path.resolve(artifact.path);
24
+ const info = await stat(file);
25
+ if (!info.isFile() || info.size === 0) throw commandError("ARTIFACT_MISSING", "An expected artifact is missing or empty.");
26
+ return { ...artifact, path: file, bytes: info.size };
27
+ }));
28
+ console.log(JSON.stringify({ schemaVersion, version, command, ok: true, ...details, artifacts: files }));
29
+ },
30
+ };
31
+ }
32
+
33
+ export function errorReport(command, error) {
34
+ return { schemaVersion, version, command, ok: false, error: {
35
+ code: error.code || "COMMAND_FAILED",
36
+ message: error.message || String(error),
37
+ hint: error.hint || "Check the reported input; use doctor --json to diagnose runtime dependencies.",
38
+ ...(error.issues ? { issues: error.issues } : {}),
39
+ ...(error.step ? { step: error.step } : {}),
40
+ ...(error.status ? { status: error.status } : {}),
41
+ } };
42
+ }
@@ -0,0 +1,18 @@
1
+ import readline from "node:readline";
2
+
3
+ export function waitForEnter(message) {
4
+ if (!process.stdin.isTTY) {
5
+ throw new Error("Manual login requires an interactive terminal; pass --storage-state for automated runs.");
6
+ }
7
+
8
+ return new Promise((resolve) => {
9
+ const rl = readline.createInterface({
10
+ input: process.stdin,
11
+ output: process.stdout,
12
+ });
13
+ rl.question(message, () => {
14
+ rl.close();
15
+ resolve();
16
+ });
17
+ });
18
+ }
@@ -0,0 +1,214 @@
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { parseCommand } from "./lib/options.mjs";
4
+ import { launchBrowser, newContext } from "./lib/browser.mjs";
5
+ import { waitForEnter } from "./lib/tty.mjs";
6
+ import { createReporter, requireInteractiveLogin } from "./lib/report.mjs";
7
+ import { navigate } from "./lib/navigation.mjs";
8
+
9
+ function parseViewport(value) {
10
+ if (!value) return { width: 1440, height: 810 };
11
+ const [w, h] = value.split("x").map(Number);
12
+ return { width: w || 1440, height: h || 810 };
13
+ }
14
+
15
+ export async function plan(argv) {
16
+ const { values } = parseCommand("plan", argv);
17
+ requireInteractiveLogin(values);
18
+ const reporter = createReporter("plan", values.json);
19
+
20
+ if (!values.url) throw new Error("Missing --url");
21
+
22
+ const viewport = parseViewport(values.viewport);
23
+ const outPath = path.resolve(values.out);
24
+ const outDir = path.dirname(outPath);
25
+
26
+ await mkdir(outDir, { recursive: true });
27
+
28
+ let storageState = values["storage-state"];
29
+ if (values.login) {
30
+ storageState = await loginAndSave(values.url, { proxy: values.proxy, viewport });
31
+ }
32
+
33
+ const browser = await launchBrowser({
34
+ headless: values.headless || !values.login,
35
+ proxy: values.proxy,
36
+ });
37
+
38
+ let manifest;
39
+ try {
40
+ const context = await newContext(browser, { viewport, storageState });
41
+ const page = await context.newPage();
42
+
43
+ await navigate(page, values.url);
44
+ await page.waitForLoadState("networkidle", { timeout: 15000 }).catch(() => {});
45
+ await page.waitForTimeout(800);
46
+
47
+ const screenshotPath = path.join(outDir, "plan.png");
48
+ await page.screenshot({ path: screenshotPath });
49
+
50
+ const title = await page.title();
51
+ const elements = await page.evaluate(() => {
52
+ function cssPath(el) {
53
+ if (!el || el.nodeType !== 1) return "";
54
+ if (el.id) return `#${CSS.escape(el.id)}`;
55
+ const parts = [];
56
+ let node = el;
57
+ while (node && node.nodeType === 1 && parts.length < 5) {
58
+ let part = node.tagName.toLowerCase();
59
+ if (node.classList && node.classList.length) {
60
+ part +=
61
+ "." +
62
+ [...node.classList]
63
+ .slice(0, 2)
64
+ .map((c) => CSS.escape(c))
65
+ .join(".");
66
+ }
67
+ const parent = node.parentElement;
68
+ if (parent) {
69
+ const siblings = [...parent.children].filter(
70
+ (c) => c.tagName === node.tagName,
71
+ );
72
+ if (siblings.length > 1) {
73
+ part += `:nth-of-type(${siblings.indexOf(node) + 1})`;
74
+ }
75
+ }
76
+ parts.unshift(part);
77
+ if (node.id) {
78
+ parts[0] = `#${CSS.escape(node.id)}`;
79
+ break;
80
+ }
81
+ node = parent;
82
+ }
83
+ return parts.join(" > ");
84
+ }
85
+
86
+ function normalizeText(value) {
87
+ return (value || "").replace(/\s+/g, " ").trim();
88
+ }
89
+
90
+ function labelText(node) {
91
+ if (!node) return "";
92
+ const copy = node.cloneNode(true);
93
+ copy.querySelectorAll("input, textarea, select, button, script, style")
94
+ .forEach((control) => control.remove());
95
+ return normalizeText(copy.textContent);
96
+ }
97
+
98
+ function controlLabel(el) {
99
+ const referenced = (el.getAttribute("aria-labelledby") || "")
100
+ .split(/\s+/).filter(Boolean)
101
+ .map((id) => labelText(document.getElementById(id))).filter(Boolean)
102
+ .join(" ");
103
+ return referenced || normalizeText(el.getAttribute("aria-label")) ||
104
+ [...(el.labels || [])].map(labelText).filter(Boolean).join(" ");
105
+ }
106
+
107
+ const nodes = [
108
+ ...document.querySelectorAll(
109
+ 'a, button, input, textarea, select, [role=button], [role=link], [role=tab], [role=textbox], [contenteditable="true"], [contenteditable=""], [contenteditable="plaintext-only"]',
110
+ ),
111
+ ];
112
+
113
+ return nodes
114
+ .map((el) => {
115
+ const rect = el.getBoundingClientRect();
116
+ const style = getComputedStyle(el);
117
+ const visible =
118
+ rect.width > 2 &&
119
+ rect.height > 2 &&
120
+ style.visibility !== "hidden" &&
121
+ style.display !== "none" &&
122
+ Number(style.opacity || 1) > 0.05;
123
+
124
+ const label = controlLabel(el);
125
+ const text = (
126
+ label || el.innerText ||
127
+ (el.type === "password" ? "" : el.value) ||
128
+ el.getAttribute("aria-label") ||
129
+ el.getAttribute("placeholder") ||
130
+ el.getAttribute("title") ||
131
+ ""
132
+ )
133
+ .replace(/\s+/g, " ")
134
+ .trim()
135
+ .slice(0, 140);
136
+
137
+ return {
138
+ tag: el.tagName.toLowerCase(),
139
+ type: el.getAttribute("type") || "",
140
+ role: el.getAttribute("role") || "",
141
+ text,
142
+ label,
143
+ name: el.getAttribute("name") || "",
144
+ placeholder: el.getAttribute("placeholder") || "",
145
+ ...(el.tagName === "SELECT" ? {
146
+ options: [...el.options].map((option) => ({
147
+ label: normalizeText(option.label),
148
+ value: option.value,
149
+ disabled: el.matches(":disabled") || option.disabled ||
150
+ Boolean(option.closest("optgroup")?.disabled),
151
+ })),
152
+ } : {}),
153
+ x: Math.round(rect.x),
154
+ y: Math.round(rect.y),
155
+ width: Math.round(rect.width),
156
+ height: Math.round(rect.height),
157
+ selector: cssPath(el),
158
+ visible,
159
+ };
160
+ })
161
+ .filter((el) => el.visible)
162
+ .slice(0, 300);
163
+ });
164
+
165
+ const result = {
166
+ url: values.url,
167
+ title,
168
+ viewport,
169
+ screenshot: screenshotPath,
170
+ generatedAt: new Date().toISOString(),
171
+ elements,
172
+ };
173
+
174
+ await writeFile(outPath, JSON.stringify(result, null, 2), "utf8");
175
+
176
+ reporter.log(`\nSaved plan to ${outPath}`);
177
+ reporter.log(`Screenshot: ${screenshotPath}`);
178
+ if (!values.json) reporter.log(`Title: ${title}`);
179
+ reporter.log(`Interactive elements: ${elements.length}\n`);
180
+ for (const el of elements.slice(0, 25)) {
181
+ const label = el.text || el.placeholder || el.name || "(no text)";
182
+ if (!values.json) reporter.log(
183
+ ` <${el.tag}${el.type ? ` type=${el.type}` : ""}> ${JSON.stringify(label)} @ ${el.selector}`,
184
+ );
185
+ }
186
+ if (!values.json && elements.length > 25) reporter.log(` ... and ${elements.length - 25} more`);
187
+
188
+ await context.close();
189
+ manifest = { elementCount: elements.length, artifacts: [
190
+ { kind: "plan", path: outPath }, { kind: "screenshot", path: screenshotPath },
191
+ ] };
192
+ } finally {
193
+ await browser.close();
194
+ }
195
+ await reporter.success(manifest);
196
+ }
197
+
198
+ async function loginAndSave(url, { proxy, viewport }) {
199
+ const browser = await launchBrowser({ headless: false, proxy });
200
+ try {
201
+ const context = await newContext(browser, { viewport });
202
+ const page = await context.newPage();
203
+ await navigate(page, url, { allowAuthErrors: true });
204
+ console.log("\nA browser window is open. Log in, then come back here.");
205
+ await waitForEnter("Press Enter when you are logged in... ");
206
+ const statePath = path.resolve("auth.json");
207
+ await context.storageState({ path: statePath });
208
+ console.log(`Saved login state to ${statePath}\n`);
209
+ await context.close();
210
+ return statePath;
211
+ } finally {
212
+ await browser.close();
213
+ }
214
+ }