All files browser.ts

91.01% Statements 81/89
89.18% Branches 33/37
85.71% Functions 18/21
91.01% Lines 81/89

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203          7x 7x 7x       7x               1x 1x           1x       2x 1x 1x 1x 1x         44x 12x   32x       9x 9x 8x       3x 3x 2x 2x       1x 1x       4x 4x                               4x 4x 4x 3x       4x 4x       4x 4x 3x       2x 2x 1x       2x 2x 1x       3x 3x 2x       3x 3x       3x 1x   2x       5x 5x       28x 28x   4x 3x     2x 1x     1x       2x 1x     2x 1x     2x 1x     2x 1x     2x 1x     2x 1x     2x 1x     2x 1x     2x 1x     1x 1x     2x 1x               13x        
import { resolve } from 'node:path';
import { type Browser, type BrowserContext, type Page, webkit } from 'playwright';
import type { BrowserCommand, BrowserOptions, CommandResponse, ElementInfo } from './types.js';
 
export class ClaudeBrowser {
  private browser: Browser | null = null;
  private context: BrowserContext | null = null;
  private page: Page | null = null;
  private options: Required<BrowserOptions>;
 
  constructor(options: BrowserOptions = {}) {
    this.options = {
      headless: options.headless ?? true,
      width: options.width ?? 1280,
      height: options.height ?? 800,
    };
  }
 
  async launch(): Promise<void> {
    this.browser = await webkit.launch({ headless: this.options.headless });
    this.context = await this.browser.newContext({
      viewport: {
        width: this.options.width,
        height: this.options.height,
      },
    });
    this.page = await this.context.newPage();
  }
 
  async close(): Promise<void> {
    if (this.browser) {
      await this.browser.close();
      this.browser = null;
      this.context = null;
      this.page = null;
    }
  }
 
  private ensurePage(): Page {
    if (!this.page) {
      throw new Error('Browser not launched. Call launch() first.');
    }
    return this.page;
  }
 
  async goto(url: string): Promise<{ url: string; title: string }> {
    const page = this.ensurePage();
    await page.goto(url, { waitUntil: 'networkidle' });
    return { url: page.url(), title: await page.title() };
  }
 
  async click(selector: string): Promise<{ url: string }> {
    const page = this.ensurePage();
    await page.click(selector);
    await page.waitForLoadState('networkidle').catch(() => {});
    return { url: page.url() };
  }
 
  async type(selector: string, text: string): Promise<void> {
    const page = this.ensurePage();
    await page.fill(selector, text);
  }
 
  async query(selector: string): Promise<ElementInfo[]> {
    const page = this.ensurePage();
    return page.$$eval(selector, (nodes) =>
      nodes.map((el) => {
        const attrs: Record<string, string> = {};
        for (const attr of el.attributes) {
          attrs[attr.name] = attr.value;
        }
        return {
          tag: el.tagName.toLowerCase(),
          text: el.textContent?.trim().slice(0, 200) || '',
          attributes: attrs,
        };
      })
    );
  }
 
  async screenshot(path?: string, fullPage = false): Promise<{ path: string; buffer?: Buffer }> {
    const page = this.ensurePage();
    const resolvedPath = resolve(path || 'screenshot.png');
    const buffer = await page.screenshot({ path: resolvedPath, fullPage });
    return { path: resolvedPath, buffer };
  }
 
  async getUrl(): Promise<{ url: string; title: string }> {
    const page = this.ensurePage();
    return { url: page.url(), title: await page.title() };
  }
 
  async getHtml(full = false): Promise<string> {
    const page = this.ensurePage();
    const html = await page.content();
    return full ? html : html.slice(0, 10000);
  }
 
  async back(): Promise<{ url: string }> {
    const page = this.ensurePage();
    await page.goBack();
    return { url: page.url() };
  }
 
  async forward(): Promise<{ url: string }> {
    const page = this.ensurePage();
    await page.goForward();
    return { url: page.url() };
  }
 
  async reload(): Promise<{ url: string }> {
    const page = this.ensurePage();
    await page.reload();
    return { url: page.url() };
  }
 
  async wait(ms = 1000): Promise<void> {
    const page = this.ensurePage();
    await page.waitForTimeout(ms);
  }
 
  async newPage(): Promise<void> {
    if (!this.context) {
      throw new Error('Browser not launched. Call launch() first.');
    }
    this.page = await this.context.newPage();
  }
 
  async eval(script: string): Promise<unknown> {
    const page = this.ensurePage();
    return page.evaluate(script);
  }
 
  async executeCommand(cmd: BrowserCommand): Promise<CommandResponse> {
    try {
      switch (cmd.cmd) {
        case 'goto': {
          const result = await this.goto(cmd.url);
          return { ok: true, ...result };
        }
        case 'click': {
          const result = await this.click(cmd.selector);
          return { ok: true, ...result };
        }
        case 'type': {
          await this.type(cmd.selector, cmd.text);
          return { ok: true };
        }
        case 'query': {
          const elements = await this.query(cmd.selector);
          return { ok: true, count: elements.length, elements };
        }
        case 'screenshot': {
          const result = await this.screenshot(cmd.path, cmd.fullPage);
          return { ok: true, path: result.path };
        }
        case 'url': {
          const result = await this.getUrl();
          return { ok: true, ...result };
        }
        case 'html': {
          const html = await this.getHtml(cmd.full);
          return { ok: true, html };
        }
        case 'back': {
          const result = await this.back();
          return { ok: true, ...result };
        }
        case 'forward': {
          const result = await this.forward();
          return { ok: true, ...result };
        }
        case 'reload': {
          const result = await this.reload();
          return { ok: true, ...result };
        }
        case 'wait': {
          await this.wait(cmd.ms);
          return { ok: true };
        }
        case 'newpage': {
          await this.newPage();
          return { ok: true };
        }
        case 'close': {
          await this.close();
          return { ok: true };
        }
        case 'eval': {
          const result = await this.eval(cmd.script);
          return { ok: true, result };
        }
        default: {
          const _exhaustive: never = cmd;
          return { ok: false, error: `Unknown command: ${(_exhaustive as { cmd: string }).cmd}` };
        }
      }
    } catch (err) {
      return { ok: false, error: (err as Error).message };
    }
  }
}