aboutsummaryrefslogtreecommitdiff
path: root/dev/cdp.js
blob: 9ba513391f6e667bfc98287e62b93ee1c24f84ac (plain)
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
// Minimal Chrome DevTools Protocol client for headless smoke tests (Node 22, no deps).
// Usage from another script:
//   const { launch } = require('./cdp.js');
//   const b = await launch(); const page = await b.newPage('http://localhost:8080/');
//   await page.eval('1+1'); await page.screenshot('out.png'); await b.close();
const { spawn } = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function launch({ port = 9333, width = 1440, height = 900 } = {}) {
  const userDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cdp-'));
  const proc = spawn('chromium', [
    '--headless=new', '--disable-gpu', '--no-sandbox', '--no-first-run', '--disable-dev-shm-usage',
    '--hide-scrollbars', `--remote-debugging-port=${port}`, `--user-data-dir=${userDir}`,
    `--window-size=${width},${height}`, 'about:blank',
  ], { stdio: 'ignore' });
  let info;
  for (let i = 0; i < 50; i++) {
    try {
      info = await (await fetch(`http://127.0.0.1:${port}/json/version`)).json();
      break;
    } catch { await sleep(200); }
  }
  if (!info) throw new Error('chromium did not start');
  const ws = new WebSocket(info.webSocketDebuggerUrl);
  await new Promise((r, j) => { ws.onopen = r; ws.onerror = j; });
  let id = 0;
  const pending = new Map();
  const listeners = [];
  ws.onmessage = (m) => {
    const msg = JSON.parse(m.data);
    if (msg.id && pending.has(msg.id)) {
      const { resolve, reject, timer } = pending.get(msg.id);
      clearTimeout(timer);
      pending.delete(msg.id);
      if (msg.error) reject(new Error(`${msg.error.message}`));
      else resolve(msg.result);
    } else if (msg.method) {
      for (const l of listeners) l(msg);
    }
  };
  const send = (method, params = {}, sessionId, timeout = 30000) => new Promise((resolve, reject) => {
    const mid = ++id;
    const timer = setTimeout(() => { pending.delete(mid); reject(new Error(`CDP timeout: ${method}`)); }, timeout);
    pending.set(mid, { resolve, reject, timer });
    ws.send(JSON.stringify({ id: mid, method, params, sessionId }));
  });

  async function newPage(url) {
    const { targetId } = await send('Target.createTarget', { url: 'about:blank' });
    const { sessionId } = await send('Target.attachToTarget', { targetId, flatten: true });
    const s = (m, p, t) => send(m, p, sessionId, t);
    const logs = [];
    listeners.push((msg) => {
      if (msg.sessionId !== sessionId) return;
      if (msg.method === 'Runtime.consoleAPICalled') {
        logs.push(`[${msg.params.type}] ${msg.params.args.map((a) => a.value ?? a.description ?? '').join(' ')}`);
      } else if (msg.method === 'Runtime.exceptionThrown') {
        const d = msg.params.exceptionDetails;
        logs.push(`[exception] ${d.exception?.description || d.text} @${d.url}:${d.lineNumber}`);
      } else if (msg.method === 'Log.entryAdded') {
        logs.push(`[log ${msg.params.entry.level}] ${msg.params.entry.text} ${msg.params.entry.url || ''}`);
      }
    });
    await s('Runtime.enable');
    await s('Log.enable');
    await s('Page.enable');
    await s('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });
    const loaded = new Promise((r) => listeners.push((msg) => { if (msg.sessionId === sessionId && msg.method === 'Page.loadEventFired') r(); }));
    await s('Page.navigate', { url });
    await loaded;
    const page = {
      logs,
      send: s,
      async eval(expr, { awaitPromise = true } = {}) {
        const r = await s('Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise });
        if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || r.exceptionDetails.text);
        return r.result.value;
      },
      async screenshot(file) {
        const { data } = await s('Page.captureScreenshot', { format: 'png' });
        fs.writeFileSync(file, Buffer.from(data, 'base64'));
      },
      async mouse(type, x, y, opts = {}) {
        await s('Input.dispatchMouseEvent', { type, x, y, button: opts.button || 'left', buttons: type === 'mouseReleased' ? 0 : 1, clickCount: opts.clickCount || 1, modifiers: opts.modifiers || 0 });
      },
      async drag(points, opts = {}) {
        const [first, ...rest] = points;
        await page.mouse('mouseMoved', first[0], first[1], opts);
        await page.mouse('mousePressed', first[0], first[1], opts);
        for (const [x, y] of rest) await page.mouse('mouseMoved', x, y, opts);
        const last = points[points.length - 1];
        await page.mouse('mouseReleased', last[0], last[1], opts);
      },
      async click(x, y, opts = {}) {
        await page.mouse('mouseMoved', x, y, opts);
        await page.mouse('mousePressed', x, y, opts);
        await page.mouse('mouseReleased', x, y, opts);
      },
      async key(key, { code, modifiers = 0, text } = {}) {
        const base = { key, code: code || key, modifiers, windowsVirtualKeyCode: key.length === 1 ? key.toUpperCase().charCodeAt(0) : 0 };
        await s('Input.dispatchKeyEvent', { type: text ? 'keyDown' : 'rawKeyDown', ...base, text });
        await s('Input.dispatchKeyEvent', { type: 'keyUp', ...base });
      },
      async type(text) { await s('Input.insertText', { text }); },
    };
    return page;
  }

  return {
    newPage,
    async close() {
      try { await send('Browser.close'); } catch { /* ignore */ }
      proc.kill();
    },
  };
}

module.exports = { launch, sleep };