#!/usr/bin/env node import { readFileSync, realpathSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { formatHelp, formatIndex, resolveApiName, type ApiReference } from './agent-docs/api-format.js'; export interface CliIo { guidePath: string; apiPath: string; version: string; stdout: (text: string) => void; stderr: (text: string) => void; } const USAGE = `Usage: npx browserclaw skill Print the usage guide for the installed browserclaw version skill --path Print the path of that guide file help [name] List every method, or show one, for example: help page.click --version Print the installed browserclaw version `; function readText(path: string, io: CliIo): string | undefined { try { return readFileSync(path, 'utf8'); } catch (err) { io.stderr(`browserclaw: cannot read ${path}: ${err instanceof Error ? err.message : String(err)}\n`); return undefined; } } function help(args: readonly string[], io: CliIo): number { const json = readText(io.apiPath, io); if (json === undefined) return 1; const ref = JSON.parse(json) as ApiReference; if (args.length === 0) { io.stdout(formatIndex(ref)); return 0; } const input = args.join(' '); const result = resolveApiName(ref, input); if ('entry' in result) { io.stdout(formatHelp(result.entry)); return 0; } if ('candidates' in result) { io.stderr( `"${input}" matches several APIs: ${result.candidates.join(', ')}. Run npx browserclaw help .\n`, ); return 1; } const hint = result.matches.length > 0 ? `Close matches: ${result.matches.join(', ')}` : 'Run npx browserclaw help for the list'; io.stderr(`unknown API "${input}". ${hint}\n`); return 1; } export function runCli(argv: readonly string[], io: CliIo): number { const [command, ...rest] = argv; if (argv.length === 0 || command === '--help' || command === '-h') { io.stdout(USAGE); return 0; } if (command === '--version' && rest.length === 0) { io.stdout(`${io.version}\n`); return 0; } if (command === 'skill' && rest.length === 0) { const guide = readText(io.guidePath, io); if (guide === undefined) return 1; io.stdout(guide); return 0; } if (command === 'skill' && rest.length === 1 && rest[0] === '--path') { io.stdout(`${io.guidePath}\n`); return 0; } if (command === 'help') return help(rest, io); io.stderr(USAGE); return 2; } export function main(argv: readonly string[]): void { const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string }; process.exitCode = runCli(argv, { guidePath: fileURLToPath(new URL('./guide.md', import.meta.url)), apiPath: fileURLToPath(new URL('./api.json', import.meta.url)), version: pkg.version, stdout: (text) => process.stdout.write(text), stderr: (text) => process.stderr.write(text), }); } const entry = process.argv.at(1); if (entry !== undefined && realpathSync(entry) === fileURLToPath(import.meta.url)) main(process.argv.slice(2));