import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import ts from 'typescript'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { generateApiReference } from './agent-docs/api-reference.js'; import { renderGuide } from './agent-docs/guide.js'; import { runCli, type CliIo } from './cli.js'; const root = path.resolve(import.meta.dirname, '..'); const version = (JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')) as { version: string }).version; let dir: string; let guide: string; beforeAll(() => { dir = mkdtempSync(path.join(tmpdir(), 'browserclaw-cli-')); guide = renderGuide(readFileSync(path.join(root, 'docs/agent-guide.md'), 'utf8'), version); writeFileSync(path.join(dir, 'guide.md'), guide); writeFileSync(path.join(dir, 'api.json'), JSON.stringify(generateApiReference(root))); }, 60_000); afterAll(() => { rmSync(dir, { recursive: true, force: true }); }); function run(...argv: string[]): { code: number; stdout: string; stderr: string } { const out = { stdout: '', stderr: '' }; const io: CliIo = { guidePath: path.join(dir, 'guide.md'), apiPath: path.join(dir, 'api.json'), version, stdout: (text) => { out.stdout += text; }, stderr: (text) => { out.stderr += text; }, }; return { code: runCli(argv, io), ...out }; } function importsOf(file: string): string[] { const source = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest); return source.statements.flatMap((s) => (ts.isImportDeclaration(s) || ts.isExportDeclaration(s)) && s.moduleSpecifier !== undefined && ts.isStringLiteral(s.moduleSpecifier) ? [s.moduleSpecifier.text] : [], ); } describe('browserclaw CLI', () => { it('skill prints the guide file unchanged', () => { const result = run('skill'); expect(result).toEqual({ code: 0, stdout: guide, stderr: '' }); }); it('skill --path prints the absolute guide path', () => { const result = run('skill', '--path'); expect(result.code).toBe(0); expect(result.stdout).toBe(`${path.join(dir, 'guide.md')}\n`); expect(path.isAbsolute(result.stdout.trim())).toBe(true); }); it('--version prints the package version', () => { expect(run('--version')).toEqual({ code: 0, stdout: `${version}\n`, stderr: '' }); }); it('no arguments prints usage and exits 0', () => { for (const argv of [[], ['--help'], ['-h']]) { const result = run(...argv); expect(result.code).toBe(0); expect(result.stdout).toMatch(/^Usage: npx browserclaw /); expect(result.stdout.trimEnd().split('\n').length).toBeLessThan(10); } }); it('an unknown command prints usage to stderr and exits 2', () => { for (const argv of [['bogus'], ['skill', '--bogus']]) { const result = run(...argv); expect(result.code).toBe(2); expect(result.stdout).toBe(''); expect(result.stderr).toMatch(/^Usage: npx browserclaw /); } }); it('help lists every API with a one-line summary', () => { const result = run('help'); expect(result.code).toBe(0); const ref = generateApiReference(root); for (const entry of ref.entries) { const line = result.stdout .split('\n') .find((l) => l.trimStart().startsWith(`${entry.name}(`) || l.trim().startsWith(`${entry.name} `)); expect(line, entry.name).toBeDefined(); expect(line).toContain(entry.summary); } expect(result.stdout).toMatch(/^\s+page\.click\(ref, opts\?\) {2}Click an element by ref\.$/m); }); it('help page.click prints signature, summary and options', () => { const result = run('help', 'page.click'); expect(result.code).toBe(0); const lines = result.stdout.split('\n'); expect(lines[0]).toBe('page.click(ref: string, opts?: ClickOptions): Promise'); expect(lines[2]).toBe('Click an element by ref.'); expect(result.stdout).toContain('Options (ClickOptions):'); expect(result.stdout).toMatch(/^ {2}timeoutMs\? +number +Timeout in milliseconds\. Default: `8000`$/m); expect(result.stdout).toContain("await page.click('e2', { doubleClick: true });"); }); it('help page.select prints both call forms', () => { const result = run('help', 'page.select'); expect(result.code).toBe(0); expect(result.stdout.split('\n')[0]).toBe('page.select(ref: string, ...values: string[]): Promise'); expect(result.stdout).toContain("await page.select('e5', 'Option A', 'Option B');"); }); it('help launch lists the ssrfPolicy keys', () => { const result = run('help', 'launch'); expect(result.code).toBe(0); expect(result.stdout.split('\n')[0]).toBe('BrowserClaw.launch(opts?: LaunchOptions): Promise'); for (const key of ['dangerouslyAllowPrivateNetwork', 'allowedHostnames', 'hostnameAllowlist', 'blockedHostnames']) expect(result.stdout).toMatch(new RegExp(`^ {6}${key}\\? `, 'm')); expect(run('help', 'browser.launch').stdout).toBe(result.stdout); }); it('help with an unknown name exits 1 and suggests close matches', () => { const result = run('help', 'page.clik'); expect(result.code).toBe(1); expect(result.stdout).toBe(''); expect(result.stderr).toBe( 'unknown API "page.clik". Close matches: page.click, page.clickByRole, page.clickBySelector, page.clickByText\n', ); expect(run('help', 'zzzzzzzz').stderr).toBe('unknown API "zzzzzzzz". Run npx browserclaw help for the list\n'); }); it('help with an ambiguous short name lists the candidates', () => { const result = run('help', 'url'); expect(result.code).toBe(1); expect(result.stderr).toContain('"url" matches several APIs: browser.url, page.url.'); }); it('src/cli.ts and its transitive local imports import only node: builtins', () => { const seen = new Set(); const visit = (file: string): void => { if (seen.has(file)) return; seen.add(file); for (const spec of importsOf(file)) { if (spec.startsWith('.')) visit(path.resolve(path.dirname(file), spec.replace(/\.js$/, '.ts'))); else expect(spec, `${path.relative(root, file)} imports ${spec}`).toMatch(/^node:/); } }; visit(path.join(root, 'src/cli.ts')); expect([...seen].map((f) => path.relative(root, f)).sort()).toEqual(['src/agent-docs/api-format.ts', 'src/cli.ts']); expect(importsOf(path.join(root, 'src/agent-docs/api-format.ts'))).toEqual([]); }); });