import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { createServer, type Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { chromium } from 'playwright-core';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { BrowserClaw } from './browser.js';
import type { LaunchOptions } from './types.js';
const executablePath = [chromium.executablePath(), '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'].find(
(candidate) => candidate !== '' && existsSync(candidate),
);
const TODO_PAGE = `
TodoMVC
`;
function listen(server: Server, port = 0): Promise {
return new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(port, '127.0.0.1', () => {
resolve((server.address() as AddressInfo).port);
});
});
}
async function freePort(): Promise {
const probe = createServer();
const port = await listen(probe);
await new Promise((resolve) => probe.close(resolve));
return port;
}
type ExampleFn = (browserClaw: unknown, console: unknown) => Promise;
async function asyncFunctionSample(): Promise {
await Promise.resolve();
}
const AsyncFunction = asyncFunctionSample.constructor as unknown as new (...args: string[]) => ExampleFn;
describe.skipIf(executablePath === undefined)('agent guide example (real Chromium)', () => {
let server: Server;
let origin: string;
const profiles: string[] = [];
const launched: BrowserClaw[] = [];
beforeAll(async () => {
server = createServer((_req, res) => {
res.writeHead(200, { 'content-type': 'text/html' });
res.end(TODO_PAGE);
});
origin = `http://localhost:${String(await listen(server))}`;
});
afterAll(async () => {
for (const browser of launched)
await browser.stop().catch((err: unknown) => {
console.warn(`[browserclaw] cleanup stop failed: ${err instanceof Error ? err.message : String(err)}`);
});
for (const dir of profiles) rmSync(dir, { recursive: true, force: true });
server.closeAllConnections();
await new Promise((resolve) => server.close(resolve));
});
it("the guide's first example runs unchanged against a local TodoMVC", async () => {
const guide = readFileSync(path.resolve(import.meta.dirname, '../docs/agent-guide.md'), 'utf8');
const block = /```javascript\n([\s\S]*?)\n```/.exec(guide)?.[1] ?? '';
const [importLine, ...rest] = block.split('\n');
expect(importLine).toBe("import { BrowserClaw } from 'browserclaw';");
const logs: string[] = [];
const shim = {
launch: async (opts: LaunchOptions) => {
const userDataDir = mkdtempSync(path.join(tmpdir(), 'browserclaw-guide-'));
profiles.push(userDataDir);
const browser = await BrowserClaw.launch({
...opts,
url: opts.url?.replace('https://demo.playwright.dev/todomvc', `${origin}/todomvc`),
headless: true,
userDataDir,
cdpPort: await freePort(),
noSandbox: process.platform === 'linux',
executablePath,
ssrfPolicy: { allowedHostnames: ['localhost'] },
});
launched.push(browser);
return browser;
},
};
const capture = {
log: (...args: unknown[]) => {
logs.push(args.map(String).join(' '));
},
};
await new AsyncFunction('BrowserClaw', 'console', rest.join('\n'))(shim, capture);
expect(logs).toEqual(['Verified: added one Buy milk item']);
expect(launched).toHaveLength(1);
}, 60_000);
});