@yanzc/claude-pro 0.9.0 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +342 -320
- package/package.json +1 -2
- package/src/agent.js +240 -62
- package/src/agents.js +3 -2
- package/src/api.js +83 -41
- package/src/browser/broker.js +367 -0
- package/src/browser/cdp.js +114 -0
- package/src/browser/render.js +242 -0
- package/src/browser/session.js +948 -0
- package/src/browser/snapshot.js +212 -0
- package/src/cache.js +1 -1
- package/src/checkpoints.js +1 -0
- package/src/commands.js +177 -71
- package/src/compaction.js +75 -0
- package/src/config.js +153 -153
- package/src/context.js +45 -18
- package/src/filestate.js +2 -1
- package/src/gateway.js +208 -164
- package/src/hooks.js +2 -2
- package/src/keepalive.js +1 -1
- package/src/main.js +52 -40
- package/src/mcp.js +2 -2
- package/src/peers.js +1 -10
- package/src/print.js +9 -3
- package/src/prompt-profiles.js +0 -6
- package/src/prompts.js +6 -62
- package/src/ratelimit.js +3 -5
- package/src/remote.js +26 -10
- package/src/restart.js +3 -0
- package/src/runtime.js +33 -10
- package/src/selfcheck.js +3 -3
- package/src/session.js +93 -3
- package/src/supervisor.js +10 -1
- package/src/tools/bash.js +19 -18
- package/src/tools/browser.js +365 -0
- package/src/tools/code.js +430 -0
- package/src/tools/effort.js +3 -4
- package/src/tools/files.js +92 -19
- package/src/tools/index.js +6 -0
- package/src/tools/notebook.js +11 -4
- package/src/tools/processes.js +274 -0
- package/src/tools/search.js +104 -21
- package/src/tools/web.js +316 -46
- package/src/trace.js +0 -4
- package/src/ui/ansi.js +92 -13
- package/src/ui/dialogs.js +16 -54
- package/src/ui/editor.js +231 -34
- package/src/ui/markdown.js +1 -2
- package/src/ui/render.js +1 -2
- package/src/ui/repl.js +246 -119
- package/src/ui/screen.js +139 -31
- package/src/updater.js +135 -165
- package/src/utils/clipboard.js +5 -3
- package/src/utils/paths.js +15 -17
- package/src/utils/shell.js +75 -21
- package/.env.example +0 -29
- package/src/verify.js +0 -57
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// One Chrome DevTools Protocol connection over Node's own WebSocket: commands with their replies, events, and the
|
|
2
|
+
// sessions of attached targets (flatten mode, one socket for all of them). No dependency.
|
|
3
|
+
|
|
4
|
+
export class CdpError extends Error {}
|
|
5
|
+
|
|
6
|
+
export const abortError = () => Object.assign(new Error('aborted'), { name: 'AbortError' });
|
|
7
|
+
|
|
8
|
+
export class Cdp {
|
|
9
|
+
// Opens the socket. A browser whose remote debugging was turned on in its settings (edge://inspect,
|
|
10
|
+
// chrome://inspect, Chrome and Edge 144+) holds the handshake until the user allows it in a dialog: `onWaiting`
|
|
11
|
+
// is called when it takes longer than a moment, so the user can be told what to click.
|
|
12
|
+
static connect(url, { signal, timeoutMs = 120_000, onWaiting } = {}) {
|
|
13
|
+
return new Promise((resolve, reject) => {
|
|
14
|
+
if (signal?.aborted) return reject(abortError());
|
|
15
|
+
const ws = new WebSocket(url);
|
|
16
|
+
let settled = false;
|
|
17
|
+
const waiting = setTimeout(() => onWaiting?.(), 1500);
|
|
18
|
+
const timer = setTimeout(() => fail(new CdpError(`the browser did not accept the connection within ${timeoutMs / 1000} s (nobody allowed remote debugging?)`)), timeoutMs);
|
|
19
|
+
const onAbort = () => fail(abortError());
|
|
20
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
21
|
+
function cleanup() { clearTimeout(waiting); clearTimeout(timer); signal?.removeEventListener('abort', onAbort); }
|
|
22
|
+
function fail(err) {
|
|
23
|
+
if (settled) return;
|
|
24
|
+
settled = true;
|
|
25
|
+
cleanup();
|
|
26
|
+
try { ws.close(); } catch { /* not open */ }
|
|
27
|
+
reject(err);
|
|
28
|
+
}
|
|
29
|
+
ws.onopen = () => {
|
|
30
|
+
if (settled) { try { ws.close(); } catch { /* gone */ } return; }
|
|
31
|
+
settled = true;
|
|
32
|
+
cleanup();
|
|
33
|
+
resolve(new Cdp(ws));
|
|
34
|
+
};
|
|
35
|
+
ws.onerror = (e) => fail(new CdpError(`cannot connect to the browser: ${e?.message || e?.error?.message || 'connection refused or declined'}`));
|
|
36
|
+
ws.onclose = (e) => fail(new CdpError(`the browser refused the connection${e?.code && e.code !== 1006 ? ` (${e.code}${e.reason ? ` ${e.reason}` : ''})` : ''}: remote debugging was declined or turned off`));
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
constructor(ws) {
|
|
41
|
+
this.ws = ws;
|
|
42
|
+
this.nextId = 1;
|
|
43
|
+
this.pending = new Map(); // id -> {resolve, reject, done, method}
|
|
44
|
+
this.handlers = new Set(); // (method, params, sessionId) => void
|
|
45
|
+
this.closed = false;
|
|
46
|
+
this.closeReason = '';
|
|
47
|
+
ws.onmessage = (m) => this.receive(m.data);
|
|
48
|
+
ws.onclose = () => this.shutdown('the browser closed the connection');
|
|
49
|
+
ws.onerror = () => {};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
receive(data) {
|
|
53
|
+
let msg;
|
|
54
|
+
try { msg = JSON.parse(typeof data === 'string' ? data : Buffer.from(data).toString('utf8')); } catch { return; }
|
|
55
|
+
if (msg.id !== undefined) {
|
|
56
|
+
const p = this.pending.get(msg.id);
|
|
57
|
+
if (!p) return;
|
|
58
|
+
this.pending.delete(msg.id);
|
|
59
|
+
p.done();
|
|
60
|
+
if (msg.error) p.reject(new CdpError(`${p.method}: ${msg.error.message}${msg.error.data ? ` (${msg.error.data})` : ''}`));
|
|
61
|
+
else p.resolve(msg.result || {});
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
for (const h of [...this.handlers]) {
|
|
65
|
+
try { h(msg.method, msg.params || {}, msg.sessionId); } catch { /* one handler's bug must not stop the others */ }
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// A command; `sessionId` sends it to an attached target. Rejects when the reply does not come in `timeoutMs`
|
|
70
|
+
// (0: no limit), when `signal` aborts, or when the connection closes.
|
|
71
|
+
send(method, params = {}, { sessionId, timeoutMs = 30_000, signal } = {}) {
|
|
72
|
+
if (this.closed) return Promise.reject(new CdpError(`${method}: ${this.closeReason}`));
|
|
73
|
+
if (signal?.aborted) return Promise.reject(abortError());
|
|
74
|
+
const id = this.nextId++;
|
|
75
|
+
return new Promise((resolve, reject) => {
|
|
76
|
+
let timer = null;
|
|
77
|
+
const onAbort = () => { this.pending.delete(id); done(); reject(abortError()); };
|
|
78
|
+
const done = () => { if (timer) clearTimeout(timer); signal?.removeEventListener('abort', onAbort); };
|
|
79
|
+
if (timeoutMs) timer = setTimeout(() => { this.pending.delete(id); done(); reject(new CdpError(`${method}: no reply within ${timeoutMs / 1000} s`)); }, timeoutMs);
|
|
80
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
81
|
+
this.pending.set(id, { resolve, reject, done, method });
|
|
82
|
+
try {
|
|
83
|
+
this.ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
|
|
84
|
+
} catch (e) {
|
|
85
|
+
this.pending.delete(id);
|
|
86
|
+
done();
|
|
87
|
+
reject(new CdpError(`${method}: ${e.message}`));
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Events of the browser and of every attached session; returns the function that removes the handler.
|
|
93
|
+
// When the connection closes, handlers get ('Cdp.closed', {reason}).
|
|
94
|
+
on(handler) {
|
|
95
|
+
this.handlers.add(handler);
|
|
96
|
+
return () => this.handlers.delete(handler);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
shutdown(reason) {
|
|
100
|
+
if (this.closed) return;
|
|
101
|
+
this.closed = true;
|
|
102
|
+
this.closeReason = reason;
|
|
103
|
+
for (const p of this.pending.values()) { p.done(); p.reject(new CdpError(`${p.method}: ${reason}`)); }
|
|
104
|
+
this.pending.clear();
|
|
105
|
+
for (const h of [...this.handlers]) {
|
|
106
|
+
try { h('Cdp.closed', { reason }); } catch { /* closing anyway */ }
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
close() {
|
|
111
|
+
try { this.ws.close(); } catch { /* already closed */ }
|
|
112
|
+
this.shutdown('closed by claude-pro');
|
|
113
|
+
}
|
|
114
|
+
}
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
// Pages for WebFetch that a plain request does not get: a page that needs JavaScript to show its text, or a server
|
|
2
|
+
// that refuses what is not a browser (Akamai's "Access Denied"). They are opened in a headless Chrome (or Edge), one
|
|
3
|
+
// per claude-pro process, started with the first such page and closed after a minute without one. It talks over a
|
|
4
|
+
// pipe (--remote-debugging-pipe), not a port: no other program can drive it, and it exits by itself when this
|
|
5
|
+
// process ends, however that happens (two seconds after a hard kill, measured). Its profile is a fresh one in the
|
|
6
|
+
// temp directory: no cookies or logins of the user's.
|
|
7
|
+
// A check that wants a person (Cloudflare's "Just a moment...", a CAPTCHA) is not got past: such a page comes back
|
|
8
|
+
// with `challenge` set, for the caller to send the model to the Browser tool, where the user can pass it.
|
|
9
|
+
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import os from 'node:os';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { spawn } from 'node:child_process';
|
|
14
|
+
import { Cdp, abortError } from './cdp.js';
|
|
15
|
+
import { browserExecutables } from './session.js';
|
|
16
|
+
import { killTree, killTreeSync, processAlive } from '../utils/shell.js';
|
|
17
|
+
|
|
18
|
+
export const renderLimits = {
|
|
19
|
+
startMs: 20_000,
|
|
20
|
+
navigationMs: 25_000, // until the server answers
|
|
21
|
+
loadMs: 15_000, // then until the load event, at most (some pages never stop loading)
|
|
22
|
+
challengeMs: 15_000, // a browser check that runs by itself (a script that sets a cookie and reloads)
|
|
23
|
+
settleMs: 5_000, // then until the network is quiet, for a page that builds itself with scripts
|
|
24
|
+
idleMs: 60_000, // the browser closes after this long without a page
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const PROFILE_PREFIX = 'claude-pro-render-';
|
|
28
|
+
// The title of a check page: one that goes on to the page by itself, or that wants a person.
|
|
29
|
+
export const CHECK_TITLE = /^\s*(?:just a moment|attention required|checking (?:your|if the site connection is secure)|please wait|one more step|ddos-guard)/i;
|
|
30
|
+
// What the page shows, and whether it is a check page (Cloudflare's, or one with the same title).
|
|
31
|
+
const PAGE_STATE = `JSON.stringify({
|
|
32
|
+
title: document.title,
|
|
33
|
+
check: ${CHECK_TITLE}.test(document.title)
|
|
34
|
+
|| !!document.querySelector('#challenge-form, #challenge-running, #cf-challenge-running, script[src*="/cdn-cgi/challenge-platform/"], iframe[src*="challenges.cloudflare.com"]'),
|
|
35
|
+
})`;
|
|
36
|
+
|
|
37
|
+
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
38
|
+
if (signal?.aborted) return reject(abortError());
|
|
39
|
+
const t = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve(); }, ms);
|
|
40
|
+
const onAbort = () => { clearTimeout(t); reject(abortError()); };
|
|
41
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
// Until `done()` or `ms` have passed (not an error: what the page shows then is taken).
|
|
45
|
+
async function until(done, ms, signal) {
|
|
46
|
+
for (const end = Date.now() + ms; !done() && Date.now() < end;) await sleep(100, signal);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// The DevTools protocol over the browser's pipe, as the WebSocket Cdp expects: messages separated by NUL bytes,
|
|
50
|
+
// fd 3 to the browser and fd 4 from it.
|
|
51
|
+
class PipeSocket {
|
|
52
|
+
constructor(input, output) {
|
|
53
|
+
this.input = input;
|
|
54
|
+
this.onmessage = null;
|
|
55
|
+
this.onclose = null;
|
|
56
|
+
this.onerror = null;
|
|
57
|
+
let buf = '';
|
|
58
|
+
output.setEncoding('utf8');
|
|
59
|
+
output.on('data', (d) => {
|
|
60
|
+
buf += d;
|
|
61
|
+
for (let i = buf.indexOf('\0'); i >= 0; i = buf.indexOf('\0')) {
|
|
62
|
+
const msg = buf.slice(0, i);
|
|
63
|
+
buf = buf.slice(i + 1);
|
|
64
|
+
this.onmessage?.({ data: msg });
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
const closed = () => { if (this.closed) return; this.closed = true; this.onclose?.({}); };
|
|
68
|
+
output.on('close', closed);
|
|
69
|
+
output.on('error', closed);
|
|
70
|
+
input.on('error', closed);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
send(text) { this.input.write(`${text}\0`); }
|
|
74
|
+
close() { try { this.input.end(); } catch { /* gone */ } }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// A profile removed; while a file of it is still held (a browser whose end Windows holds up, below), tried again
|
|
78
|
+
// every 15 s for two minutes, then left to the next browser's sweep.
|
|
79
|
+
function removeDir(dir, tries = 8) {
|
|
80
|
+
fs.rm(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 }, (err) => {
|
|
81
|
+
if (err && tries > 1) setTimeout(() => removeDir(dir, tries - 1), 15_000).unref();
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Profiles left behind: those of processes that are gone (one killed outright, or one that exited before its
|
|
86
|
+
// browser had let go of the files), and this process's own earlier ones (its browser is not running now).
|
|
87
|
+
function sweepProfiles() {
|
|
88
|
+
let names = [];
|
|
89
|
+
try { names = fs.readdirSync(os.tmpdir()); } catch { return; }
|
|
90
|
+
for (const name of names) {
|
|
91
|
+
const pid = Number(new RegExp(`^${PROFILE_PREFIX}(\\d+)-`).exec(name)?.[1]);
|
|
92
|
+
if (!pid || (pid !== process.pid && processAlive(pid))) continue;
|
|
93
|
+
removeDir(path.join(os.tmpdir(), name));
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
let browser = null; // {child, cdp, dir, ua, meta, busy, idleTimer}
|
|
98
|
+
let starting = null;
|
|
99
|
+
let exitHook = false;
|
|
100
|
+
|
|
101
|
+
async function launch(signal) {
|
|
102
|
+
const exe = browserExecutables().find((p) => p && fs.existsSync(p));
|
|
103
|
+
if (!exe) throw new Error('no Chrome or Edge is installed to open it in');
|
|
104
|
+
sweepProfiles();
|
|
105
|
+
if (!exitHook) {
|
|
106
|
+
// A process that exits on purpose (a restart, the end of a -p run) ends it at once, crash reporter included
|
|
107
|
+
// (see closeRenderer). Its profile goes with the next browser's sweep.
|
|
108
|
+
exitHook = true;
|
|
109
|
+
process.once('exit', () => { if (browser) killTreeSync(browser.child); });
|
|
110
|
+
}
|
|
111
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), `${PROFILE_PREFIX}${process.pid}-`));
|
|
112
|
+
const child = spawn(exe, [
|
|
113
|
+
'--headless=new', '--remote-debugging-pipe', `--user-data-dir=${dir}`, '--no-first-run', '--no-default-browser-check',
|
|
114
|
+
'--disable-blink-features=AutomationControlled', '--disable-extensions', '--mute-audio', '--hide-scrollbars',
|
|
115
|
+
// nothing of its own in the background (component and safe-browsing downloads, sync, translation): a throwaway
|
|
116
|
+
// browser for pages, which then also has less to finish when it is closed
|
|
117
|
+
'--disable-background-networking', '--disable-component-update', '--disable-sync', '--disable-default-apps',
|
|
118
|
+
'--disable-features=OptimizationHints,Translate,MediaRouter', '--metrics-recording-only',
|
|
119
|
+
'--window-size=1366,900', 'about:blank',
|
|
120
|
+
], { stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe'], windowsHide: true });
|
|
121
|
+
const failed = new Promise((_, reject) => child.once('error', (e) => reject(new Error(`could not start ${path.basename(exe)}: ${e.message}`))));
|
|
122
|
+
failed.catch(() => {});
|
|
123
|
+
const cdp = new Cdp(new PipeSocket(child.stdio[3], child.stdio[4]));
|
|
124
|
+
try {
|
|
125
|
+
const version = await Promise.race([failed, cdp.send('Browser.getVersion', {}, { timeoutMs: renderLimits.startMs, signal })]);
|
|
126
|
+
await cdp.send('Browser.setDownloadBehavior', { behavior: 'deny' }, { timeoutMs: 5000 }).catch(() => {});
|
|
127
|
+
// As the browser it is: without "Headless" in its name, which servers turn away (in the client hints too).
|
|
128
|
+
const ua = version.userAgent.replace(/Headless(?=Chrome|Edg)/g, '');
|
|
129
|
+
const full = /\/([\d.]+)/.exec(version.product)?.[1] || '0';
|
|
130
|
+
const major = full.split('.')[0];
|
|
131
|
+
const brand = /msedge/i.test(exe) ? 'Microsoft Edge' : /chrome/i.test(exe) ? 'Google Chrome' : null;
|
|
132
|
+
const brands = (v) => [{ brand: 'Chromium', version: v }, ...(brand ? [{ brand, version: v }] : []), { brand: 'Not_A Brand', version: v === major ? '24' : '24.0.0.0' }];
|
|
133
|
+
const platform = process.platform === 'win32' ? 'Windows' : process.platform === 'darwin' ? 'macOS' : 'Linux';
|
|
134
|
+
const meta = { brands: brands(major), fullVersionList: brands(full), platform, platformVersion: '', architecture: process.arch === 'arm64' ? 'arm' : 'x86', bitness: '64', model: '', mobile: false };
|
|
135
|
+
return { child, cdp, dir, ua, meta, busy: 0, idleTimer: null };
|
|
136
|
+
} catch (e) {
|
|
137
|
+
cdp.close();
|
|
138
|
+
killTree(child).finally(() => removeDir(dir));
|
|
139
|
+
throw e;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function ensureBrowser(signal) {
|
|
144
|
+
if (browser && !browser.cdp.closed) return browser;
|
|
145
|
+
browser = null;
|
|
146
|
+
starting ??= launch(signal).then((b) => {
|
|
147
|
+
browser = b;
|
|
148
|
+
// its pipe broke (the browser crashed, or it stopped answering): whatever is left of it goes, the next page
|
|
149
|
+
// starts another
|
|
150
|
+
b.cdp.on((method) => {
|
|
151
|
+
if (method !== 'Cdp.closed' || browser !== b) return;
|
|
152
|
+
browser = null;
|
|
153
|
+
killTree(b.child).finally(() => removeDir(b.dir));
|
|
154
|
+
});
|
|
155
|
+
return b;
|
|
156
|
+
}).finally(() => { starting = null; });
|
|
157
|
+
return starting;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function scheduleClose(b) {
|
|
161
|
+
clearTimeout(b.idleTimer);
|
|
162
|
+
if (b.busy) return;
|
|
163
|
+
b.idleTimer = setTimeout(() => { if (browser === b && !b.busy) closeRenderer(); }, renderLimits.idleMs);
|
|
164
|
+
b.idleTimer.unref?.();
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// The headless browser, closed now: after a minute without a page, or when the program ends (a -p run would wait
|
|
168
|
+
// for its pipe).
|
|
169
|
+
export function closeRenderer() {
|
|
170
|
+
const b = browser;
|
|
171
|
+
browser = null;
|
|
172
|
+
if (!b) return;
|
|
173
|
+
clearTimeout(b.idleTimer);
|
|
174
|
+
b.cdp.close();
|
|
175
|
+
// Its whole process tree at once: a throwaway browser has nothing to save, and its crash reporter (started on
|
|
176
|
+
// Windows whatever the switches) otherwise stayed, at times, for many seconds after the browser, holding a file of
|
|
177
|
+
// the profile. Even killed, a browser may take Windows 20 to 60 s to end (seen in about one run in five: its
|
|
178
|
+
// termination waits for file I/O, likely the virus scanner on the new profile's files); the profile is removed
|
|
179
|
+
// once it has (removeDir).
|
|
180
|
+
killTree(b.child).finally(() => removeDir(b.dir));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// `url` opened in the headless browser: {html, finalUrl, title, status, statusText, challenge}. `status` is the
|
|
184
|
+
// main document's (a check page's 403 that went on to the page by itself is the page's 200 by then); `challenge`:
|
|
185
|
+
// the page is still a check page, one that wants a person. Throws when the page cannot be opened at all (a network
|
|
186
|
+
// error the browser reports, no browser installed).
|
|
187
|
+
export async function renderPage(url, { signal } = {}) {
|
|
188
|
+
const b = await ensureBrowser(signal);
|
|
189
|
+
b.busy++;
|
|
190
|
+
clearTimeout(b.idleTimer);
|
|
191
|
+
let targetId = null;
|
|
192
|
+
let off = null;
|
|
193
|
+
try {
|
|
194
|
+
({ targetId } = await b.cdp.send('Target.createTarget', { url: 'about:blank' }, { signal, timeoutMs: 10_000 }));
|
|
195
|
+
const { sessionId } = await b.cdp.send('Target.attachToTarget', { targetId, flatten: true }, { signal, timeoutMs: 10_000 });
|
|
196
|
+
const send = (method, params = {}, timeoutMs = 15_000) => b.cdp.send(method, params, { sessionId, signal, timeoutMs });
|
|
197
|
+
let status = null;
|
|
198
|
+
let statusText = '';
|
|
199
|
+
let loaded = false;
|
|
200
|
+
let quiet = false;
|
|
201
|
+
off = b.cdp.on((method, params, sid) => {
|
|
202
|
+
if (sid !== sessionId) return;
|
|
203
|
+
if (method === 'Network.responseReceived' && params.type === 'Document' && params.frameId === targetId) {
|
|
204
|
+
status = params.response?.status ?? status;
|
|
205
|
+
statusText = params.response?.statusText || '';
|
|
206
|
+
} else if (method === 'Page.loadEventFired') loaded = true;
|
|
207
|
+
else if (method === 'Page.lifecycleEvent' && params.frameId === targetId) {
|
|
208
|
+
if (params.name === 'init') quiet = false; // a new document (a check page that reloads to the page)
|
|
209
|
+
else if (params.name === 'networkIdle') quiet = true;
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
await send('Network.enable');
|
|
213
|
+
await send('Network.setUserAgentOverride', { userAgent: b.ua, acceptLanguage: 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7', userAgentMetadata: b.meta });
|
|
214
|
+
await send('Page.enable');
|
|
215
|
+
await send('Page.setLifecycleEventsEnabled', { enabled: true });
|
|
216
|
+
const nav = await send('Page.navigate', { url }, renderLimits.navigationMs);
|
|
217
|
+
if (nav.errorText) throw new Error(`the browser could not open it: ${nav.errorText}`);
|
|
218
|
+
await until(() => loaded, renderLimits.loadMs, signal);
|
|
219
|
+
// null between two documents (a check page reloading to the page): the state is not known then
|
|
220
|
+
const state = async () => {
|
|
221
|
+
try { return JSON.parse((await send('Runtime.evaluate', { expression: PAGE_STATE, returnByValue: true })).result.value); } catch (e) {
|
|
222
|
+
if (signal?.aborted) throw e;
|
|
223
|
+
return null;
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
let page = (await state()) || { title: '', check: false };
|
|
227
|
+
for (const end = Date.now() + renderLimits.challengeMs; page.check && Date.now() < end;) {
|
|
228
|
+
await sleep(500, signal);
|
|
229
|
+
page = (await state()) || page;
|
|
230
|
+
}
|
|
231
|
+
await until(() => quiet, renderLimits.settleMs, signal);
|
|
232
|
+
const { result } = await send('Runtime.evaluate', { expression: `JSON.stringify({ html: document.documentElement ? document.documentElement.outerHTML : '', url: location.href, state: ${PAGE_STATE} })`, returnByValue: true }, 30_000);
|
|
233
|
+
const out = JSON.parse(result.value);
|
|
234
|
+
const last = JSON.parse(out.state);
|
|
235
|
+
return { html: out.html, finalUrl: out.url, title: last.title, status: status ?? 200, statusText, challenge: last.check };
|
|
236
|
+
} finally {
|
|
237
|
+
off?.();
|
|
238
|
+
if (targetId) b.cdp.send('Target.closeTarget', { targetId }, { timeoutMs: 5000 }).catch(() => {});
|
|
239
|
+
b.busy--;
|
|
240
|
+
scheduleClose(b);
|
|
241
|
+
}
|
|
242
|
+
}
|