@gnawbit/tabretake 0.0.0-stage → 0.4.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.
@@ -0,0 +1,76 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { readFileSync } from "node:fs";
3
+ import Ajv from "ajv";
4
+
5
+ export const configSchema = JSON.parse(readFileSync(new URL("../../schemas/story.schema.json", import.meta.url), "utf8"));
6
+ const ajv = new Ajv({ allErrors: true, strictRequired: false });
7
+ ajv.addFormat("uri", (value) => {
8
+ try { new URL(value); return true; } catch { return false; }
9
+ });
10
+ ajv.addSchema(configSchema);
11
+ const validators = Object.fromEntries(["story", "marks", "record"].map((kind) => [
12
+ kind, ajv.getSchema(`${configSchema.$id}#/definitions/${kind}`),
13
+ ]));
14
+ const pointer = (part) => String(part).replace(/~/g, "~0").replace(/\//g, "~1");
15
+
16
+ export function inspectConfig(config, { kind } = {}) {
17
+ const detected = config && typeof config === "object" && !Array.isArray(config)
18
+ ? ("marks" in config ? "marks" : "events" in config ? "record" : "story") : "story";
19
+ kind ||= detected;
20
+ const validate = validators[kind];
21
+ if (!validate) throw new Error(`Unknown config kind: ${kind}`);
22
+ const ok = validate(config);
23
+ const errors = ok ? [] : validate.errors.filter((error) => error.keyword !== "if").map((error) => {
24
+ const property = error.params.missingProperty ?? error.params.additionalProperty;
25
+ return {
26
+ code: "INVALID_CONFIG",
27
+ path: (error.instancePath + (property === undefined ? "" : `/${pointer(property)}`)) || "/",
28
+ message: error.message,
29
+ hint: "Correct this field using schemas/story.schema.json, then run validate again.",
30
+ };
31
+ });
32
+ if (ok) {
33
+ const duration = config.duration;
34
+ const settings = kind === "record" ? config.config : config;
35
+ const poster = settings?.posterAt;
36
+ if (duration !== undefined && poster !== undefined && poster >= duration) {
37
+ errors.push({ code: "INVALID_CONFIG", path: kind === "record" ? "/config/posterAt" : "/posterAt",
38
+ message: "must be less than duration", hint: "Choose a poster time inside the output timeline." });
39
+ }
40
+ if (kind === "record") {
41
+ config.events.forEach((event, index) => {
42
+ if (event.tEnd !== undefined && event.tEnd < event.t) errors.push({
43
+ code: "INVALID_CONFIG", path: `/events/${index}/tEnd`, message: "must be at least t",
44
+ hint: "Use milliseconds for both event timestamps.",
45
+ });
46
+ });
47
+ }
48
+ }
49
+ return { ok: errors.length === 0, kind, errors };
50
+ }
51
+
52
+ export function assertConfig(config, options) {
53
+ const result = inspectConfig(config, options);
54
+ if (!result.ok) {
55
+ const error = new Error(`Invalid config: ${result.errors.map((e) => `${e.path} ${e.message}`).join("; ")}`);
56
+ error.code = "INVALID_CONFIG";
57
+ error.issues = result.errors;
58
+ throw error;
59
+ }
60
+ return config;
61
+ }
62
+
63
+ export async function readConfig(file) {
64
+ let source;
65
+ try { source = await readFile(file, "utf8"); } catch {
66
+ const error = new Error("Could not read config file; check --config and file permissions.");
67
+ error.code = "CONFIG_READ_FAILED";
68
+ throw error;
69
+ }
70
+ try { return JSON.parse(source); } catch {
71
+ // Do not echo source snippets, which may include typed values or credentials.
72
+ const error = new Error("Config is not valid JSON; check quotes, commas and brackets.");
73
+ error.code = "INVALID_JSON";
74
+ throw error;
75
+ }
76
+ }
@@ -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,67 @@
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
+ auto: { type: "boolean", default: false },
10
+ },
11
+ plan: {
12
+ json: { type: "boolean", default: false },
13
+ url: { type: "string" },
14
+ out: { type: "string", default: "plan.json" },
15
+ login: { type: "boolean", default: false },
16
+ "storage-state": { type: "string" },
17
+ proxy: { type: "string" },
18
+ viewport: { type: "string" },
19
+ headless: { type: "boolean", default: true },
20
+ },
21
+ record: {
22
+ json: { type: "boolean", default: false },
23
+ config: { type: "string" },
24
+ url: { type: "string" },
25
+ out: { type: "string" },
26
+ login: { type: "boolean", default: false },
27
+ "storage-state": { type: "string" },
28
+ "save-state": { type: "string" },
29
+ proxy: { type: "string" },
30
+ viewport: { type: "string" },
31
+ headed: { type: "boolean", default: false },
32
+ },
33
+ render: {
34
+ json: { type: "boolean", default: false },
35
+ config: { type: "string" },
36
+ video: { type: "string" },
37
+ out: { type: "string" },
38
+ "no-gif": { type: "boolean", default: false },
39
+ "no-captions": { type: "boolean", default: false },
40
+ vertical: { type: "boolean", default: false },
41
+ zoom: { type: "string", default: "1.28" },
42
+ "vertical-zoom": { type: "string" },
43
+ "zoom-duration": { type: "string" },
44
+ "poster-at": { type: "string" },
45
+ },
46
+ serve: {
47
+ port: { type: "string", default: "4173" },
48
+ dir: { type: "string", default: "examples/site" },
49
+ },
50
+ demo: {
51
+ out: { type: "string", default: "demo" },
52
+ port: { type: "string", default: "4173" },
53
+ story: { type: "string", default: "onboarding" },
54
+ },
55
+ doctor: { json: { type: "boolean", default: false } },
56
+ capabilities: { json: { type: "boolean", default: false } },
57
+ validate: { config: { type: "string" }, json: { type: "boolean", default: false } },
58
+ };
59
+
60
+ commandOptions.preview = {
61
+ ...commandOptions.record,
62
+ headless: { type: "boolean", default: false },
63
+ };
64
+
65
+ export function parseCommand(command, argv) {
66
+ return parseArgs({ args: argv, options: commandOptions[command], strict: true, allowPositionals: false });
67
+ }
@@ -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,235 @@
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 collectElements(page) {
16
+ return page.evaluate(() => {
17
+ function cssPath(el) {
18
+ if (!el || el.nodeType !== 1) return "";
19
+ if (el.id) return `#${CSS.escape(el.id)}`;
20
+ const parts = [];
21
+ let node = el;
22
+ while (node && node.nodeType === 1 && parts.length < 5) {
23
+ let part = node.tagName.toLowerCase();
24
+ if (node.classList && node.classList.length) {
25
+ part +=
26
+ "." +
27
+ [...node.classList]
28
+ .slice(0, 2)
29
+ .map((c) => CSS.escape(c))
30
+ .join(".");
31
+ }
32
+ const parent = node.parentElement;
33
+ if (parent) {
34
+ const siblings = [...parent.children].filter(
35
+ (c) => c.tagName === node.tagName,
36
+ );
37
+ if (siblings.length > 1) {
38
+ part += `:nth-of-type(${siblings.indexOf(node) + 1})`;
39
+ }
40
+ }
41
+ parts.unshift(part);
42
+ if (node.id) {
43
+ parts[0] = `#${CSS.escape(node.id)}`;
44
+ break;
45
+ }
46
+ node = parent;
47
+ }
48
+ return parts.join(" > ");
49
+ }
50
+
51
+ function normalizeText(value) {
52
+ return (value || "").replace(/\s+/g, " ").trim();
53
+ }
54
+
55
+ function labelText(node) {
56
+ if (!node) return "";
57
+ const copy = node.cloneNode(true);
58
+ copy.querySelectorAll("input, textarea, select, button, script, style")
59
+ .forEach((control) => control.remove());
60
+ return normalizeText(copy.textContent);
61
+ }
62
+
63
+ function controlLabel(el) {
64
+ const referenced = (el.getAttribute("aria-labelledby") || "")
65
+ .split(/\s+/).filter(Boolean)
66
+ .map((id) => labelText(document.getElementById(id))).filter(Boolean)
67
+ .join(" ");
68
+ return referenced || normalizeText(el.getAttribute("aria-label")) ||
69
+ [...(el.labels || [])].map(labelText).filter(Boolean).join(" ");
70
+ }
71
+
72
+ const nodes = [
73
+ ...document.querySelectorAll(
74
+ 'a, button, input, textarea, select, [role=button], [role=link], [role=tab], [role=textbox], [contenteditable="true"], [contenteditable=""], [contenteditable="plaintext-only"]',
75
+ ),
76
+ ];
77
+
78
+ return nodes
79
+ .map((el) => {
80
+ const rect = el.getBoundingClientRect();
81
+ const style = getComputedStyle(el);
82
+ const visible =
83
+ rect.width > 2 &&
84
+ rect.height > 2 &&
85
+ style.visibility !== "hidden" &&
86
+ style.display !== "none" &&
87
+ Number(style.opacity || 1) > 0.05;
88
+
89
+ const label = controlLabel(el);
90
+ const text = (
91
+ label || el.innerText ||
92
+ (el.type === "password" ? "" : el.value) ||
93
+ el.getAttribute("aria-label") ||
94
+ el.getAttribute("placeholder") ||
95
+ el.getAttribute("title") ||
96
+ ""
97
+ )
98
+ .replace(/\s+/g, " ")
99
+ .trim()
100
+ .slice(0, 140);
101
+
102
+ return {
103
+ tag: el.tagName.toLowerCase(),
104
+ type: el.getAttribute("type") || "",
105
+ role: el.getAttribute("role") || "",
106
+ text,
107
+ label,
108
+ name: el.getAttribute("name") || "",
109
+ placeholder: el.getAttribute("placeholder") || "",
110
+ ...(el.tagName === "SELECT" ? {
111
+ options: [...el.options].map((option) => ({
112
+ label: normalizeText(option.label),
113
+ value: option.value,
114
+ disabled: el.matches(":disabled") || option.disabled ||
115
+ Boolean(option.closest("optgroup")?.disabled),
116
+ })),
117
+ } : {}),
118
+ x: Math.round(rect.x),
119
+ y: Math.round(rect.y),
120
+ width: Math.round(rect.width),
121
+ height: Math.round(rect.height),
122
+ selector: cssPath(el),
123
+ visible,
124
+ };
125
+ })
126
+ .filter((el) => el.visible)
127
+ .slice(0, 300);
128
+ });
129
+ }
130
+
131
+ export async function extractPlan(url, { viewport = { width: 1440, height: 810 }, proxy, storageState, headless = true } = {}) {
132
+ const browser = await launchBrowser({ headless, proxy });
133
+ try {
134
+ const context = await newContext(browser, { viewport, storageState });
135
+ const page = await context.newPage();
136
+ await navigate(page, url);
137
+ await page.waitForLoadState("networkidle", { timeout: 15000 }).catch(() => {});
138
+ await page.waitForTimeout(800);
139
+ const title = await page.title();
140
+ const elements = await collectElements(page);
141
+ await context.close();
142
+ return { title, elements };
143
+ } finally {
144
+ await browser.close();
145
+ }
146
+ }
147
+
148
+ export async function plan(argv) {
149
+ const { values } = parseCommand("plan", argv);
150
+ requireInteractiveLogin(values);
151
+ const reporter = createReporter("plan", values.json);
152
+
153
+ if (!values.url) throw new Error("Missing --url");
154
+
155
+ const viewport = parseViewport(values.viewport);
156
+ const outPath = path.resolve(values.out);
157
+ const outDir = path.dirname(outPath);
158
+
159
+ await mkdir(outDir, { recursive: true });
160
+
161
+ let storageState = values["storage-state"];
162
+ if (values.login) {
163
+ storageState = await loginAndSave(values.url, { proxy: values.proxy, viewport });
164
+ }
165
+
166
+ const browser = await launchBrowser({
167
+ headless: values.headless || !values.login,
168
+ proxy: values.proxy,
169
+ });
170
+
171
+ let manifest;
172
+ try {
173
+ const context = await newContext(browser, { viewport, storageState });
174
+ const page = await context.newPage();
175
+
176
+ await navigate(page, values.url);
177
+ await page.waitForLoadState("networkidle", { timeout: 15000 }).catch(() => {});
178
+ await page.waitForTimeout(800);
179
+
180
+ const screenshotPath = path.join(outDir, "plan.png");
181
+ await page.screenshot({ path: screenshotPath });
182
+
183
+ const title = await page.title();
184
+ const elements = await collectElements(page);
185
+
186
+ const result = {
187
+ url: values.url,
188
+ title,
189
+ viewport,
190
+ screenshot: screenshotPath,
191
+ generatedAt: new Date().toISOString(),
192
+ elements,
193
+ };
194
+
195
+ await writeFile(outPath, JSON.stringify(result, null, 2), "utf8");
196
+
197
+ reporter.log(`\nSaved plan to ${outPath}`);
198
+ reporter.log(`Screenshot: ${screenshotPath}`);
199
+ if (!values.json) reporter.log(`Title: ${title}`);
200
+ reporter.log(`Interactive elements: ${elements.length}\n`);
201
+ for (const el of elements.slice(0, 25)) {
202
+ const label = el.text || el.placeholder || el.name || "(no text)";
203
+ if (!values.json) reporter.log(
204
+ ` <${el.tag}${el.type ? ` type=${el.type}` : ""}> ${JSON.stringify(label)} @ ${el.selector}`,
205
+ );
206
+ }
207
+ if (!values.json && elements.length > 25) reporter.log(` ... and ${elements.length - 25} more`);
208
+
209
+ await context.close();
210
+ manifest = { elementCount: elements.length, artifacts: [
211
+ { kind: "plan", path: outPath }, { kind: "screenshot", path: screenshotPath },
212
+ ] };
213
+ } finally {
214
+ await browser.close();
215
+ }
216
+ await reporter.success(manifest);
217
+ }
218
+
219
+ async function loginAndSave(url, { proxy, viewport }) {
220
+ const browser = await launchBrowser({ headless: false, proxy });
221
+ try {
222
+ const context = await newContext(browser, { viewport });
223
+ const page = await context.newPage();
224
+ await navigate(page, url, { allowAuthErrors: true });
225
+ console.log("\nA browser window is open. Log in, then come back here.");
226
+ await waitForEnter("Press Enter when you are logged in... ");
227
+ const statePath = path.resolve("auth.json");
228
+ await context.storageState({ path: statePath });
229
+ console.log(`Saved login state to ${statePath}\n`);
230
+ await context.close();
231
+ return statePath;
232
+ } finally {
233
+ await browser.close();
234
+ }
235
+ }