@jackwener/opencli 0.9.8 → 1.0.1
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/CDP.md +1 -1
- package/CDP.zh-CN.md +1 -1
- package/CLI-ELECTRON.md +2 -2
- package/CLI-EXPLORER.md +4 -4
- package/README.md +35 -58
- package/README.zh-CN.md +36 -60
- package/SKILL.md +10 -8
- package/TESTING.md +7 -7
- package/dist/browser/daemon-client.d.ts +37 -0
- package/dist/browser/daemon-client.js +82 -0
- package/dist/browser/discover.d.ts +11 -34
- package/dist/browser/discover.js +15 -205
- package/dist/browser/errors.d.ts +6 -20
- package/dist/browser/errors.js +24 -63
- package/dist/browser/index.d.ts +2 -12
- package/dist/browser/index.js +2 -12
- package/dist/browser/mcp.d.ts +9 -21
- package/dist/browser/mcp.js +70 -285
- package/dist/browser/page.d.ts +36 -7
- package/dist/browser/page.js +212 -81
- package/dist/browser.test.js +10 -231
- package/dist/cli-manifest.json +561 -14
- package/dist/clis/apple-podcasts/episodes.d.ts +1 -0
- package/dist/clis/apple-podcasts/episodes.js +28 -0
- package/dist/clis/apple-podcasts/search.d.ts +1 -0
- package/dist/clis/apple-podcasts/search.js +29 -0
- package/dist/clis/apple-podcasts/top.d.ts +1 -0
- package/dist/clis/apple-podcasts/top.js +34 -0
- package/dist/clis/apple-podcasts/utils.d.ts +11 -0
- package/dist/clis/apple-podcasts/utils.js +30 -0
- package/dist/clis/apple-podcasts/utils.test.d.ts +1 -0
- package/dist/clis/apple-podcasts/utils.test.js +57 -0
- package/dist/clis/chatwise/history.js +18 -1
- package/dist/clis/discord-app/channels.js +33 -21
- package/dist/clis/neteasemusic/like.d.ts +1 -0
- package/dist/clis/neteasemusic/like.js +25 -0
- package/dist/clis/neteasemusic/lyrics.d.ts +1 -0
- package/dist/clis/neteasemusic/lyrics.js +47 -0
- package/dist/clis/neteasemusic/next.d.ts +1 -0
- package/dist/clis/neteasemusic/next.js +26 -0
- package/dist/clis/neteasemusic/play.d.ts +1 -0
- package/dist/clis/neteasemusic/play.js +26 -0
- package/dist/clis/neteasemusic/playing.d.ts +1 -0
- package/dist/clis/neteasemusic/playing.js +59 -0
- package/dist/clis/neteasemusic/playlist.d.ts +1 -0
- package/dist/clis/neteasemusic/playlist.js +46 -0
- package/dist/clis/neteasemusic/prev.d.ts +1 -0
- package/dist/clis/neteasemusic/prev.js +25 -0
- package/dist/clis/neteasemusic/search.d.ts +1 -0
- package/dist/clis/neteasemusic/search.js +52 -0
- package/dist/clis/neteasemusic/status.d.ts +1 -0
- package/dist/clis/neteasemusic/status.js +16 -0
- package/dist/clis/neteasemusic/volume.d.ts +1 -0
- package/dist/clis/neteasemusic/volume.js +54 -0
- package/dist/clis/twitter/accept.d.ts +1 -0
- package/dist/clis/twitter/accept.js +202 -0
- package/dist/clis/twitter/followers.js +30 -22
- package/dist/clis/twitter/following.js +19 -14
- package/dist/clis/twitter/notifications.js +29 -22
- package/dist/clis/twitter/reply-dm.d.ts +1 -0
- package/dist/clis/twitter/reply-dm.js +181 -0
- package/dist/clis/twitter/search.js +50 -12
- package/dist/clis/weread/book.d.ts +1 -0
- package/dist/clis/weread/book.js +26 -0
- package/dist/clis/weread/highlights.d.ts +1 -0
- package/dist/clis/weread/highlights.js +23 -0
- package/dist/clis/weread/notebooks.d.ts +1 -0
- package/dist/clis/weread/notebooks.js +21 -0
- package/dist/clis/weread/notes.d.ts +1 -0
- package/dist/clis/weread/notes.js +29 -0
- package/dist/clis/weread/ranking.d.ts +1 -0
- package/dist/clis/weread/ranking.js +28 -0
- package/dist/clis/weread/search.d.ts +1 -0
- package/dist/clis/weread/search.js +25 -0
- package/dist/clis/weread/shelf.d.ts +1 -0
- package/dist/clis/weread/shelf.js +24 -0
- package/dist/clis/weread/utils.d.ts +20 -0
- package/dist/clis/weread/utils.js +72 -0
- package/dist/clis/weread/utils.test.d.ts +1 -0
- package/dist/clis/weread/utils.test.js +85 -0
- package/dist/daemon.d.ts +13 -0
- package/dist/daemon.js +187 -0
- package/dist/doctor.d.ts +10 -65
- package/dist/doctor.js +49 -602
- package/dist/doctor.test.js +30 -170
- package/dist/main.js +12 -41
- package/dist/pipeline/executor.test.js +1 -0
- package/dist/pipeline/steps/browser.js +2 -2
- package/dist/pipeline/steps/intercept.js +1 -2
- package/dist/runtime.d.ts +1 -4
- package/dist/runtime.js +1 -4
- package/dist/setup.d.ts +6 -0
- package/dist/setup.js +46 -160
- package/dist/types.d.ts +6 -0
- package/extension/dist/background.js +484 -0
- package/extension/icons/icon-128.png +0 -0
- package/extension/icons/icon-16.png +0 -0
- package/extension/icons/icon-32.png +0 -0
- package/extension/icons/icon-48.png +0 -0
- package/extension/manifest.json +31 -0
- package/extension/package.json +16 -0
- package/extension/src/background.ts +370 -0
- package/extension/src/cdp.ts +125 -0
- package/extension/src/protocol.ts +57 -0
- package/extension/store-assets/screenshot-1280x800.png +0 -0
- package/extension/tsconfig.json +15 -0
- package/extension/vite.config.ts +18 -0
- package/package.json +5 -5
- package/src/browser/daemon-client.ts +113 -0
- package/src/browser/discover.ts +18 -232
- package/src/browser/errors.ts +30 -100
- package/src/browser/index.ts +2 -13
- package/src/browser/mcp.ts +81 -282
- package/src/browser/page.ts +223 -83
- package/src/browser.test.ts +9 -239
- package/src/clis/apple-podcasts/episodes.ts +28 -0
- package/src/clis/apple-podcasts/search.ts +29 -0
- package/src/clis/apple-podcasts/top.ts +34 -0
- package/src/clis/apple-podcasts/utils.test.ts +72 -0
- package/src/clis/apple-podcasts/utils.ts +37 -0
- package/src/clis/chatgpt/README.md +1 -1
- package/src/clis/chatgpt/README.zh-CN.md +1 -1
- package/src/clis/chatwise/history.ts +15 -1
- package/src/clis/discord-app/channels.ts +33 -21
- package/src/clis/neteasemusic/README.md +31 -0
- package/src/clis/neteasemusic/README.zh-CN.md +31 -0
- package/src/clis/neteasemusic/like.ts +28 -0
- package/src/clis/neteasemusic/lyrics.ts +53 -0
- package/src/clis/neteasemusic/next.ts +30 -0
- package/src/clis/neteasemusic/play.ts +30 -0
- package/src/clis/neteasemusic/playing.ts +62 -0
- package/src/clis/neteasemusic/playlist.ts +51 -0
- package/src/clis/neteasemusic/prev.ts +29 -0
- package/src/clis/neteasemusic/search.ts +58 -0
- package/src/clis/neteasemusic/status.ts +18 -0
- package/src/clis/neteasemusic/volume.ts +61 -0
- package/src/clis/twitter/accept.ts +213 -0
- package/src/clis/twitter/followers.ts +36 -29
- package/src/clis/twitter/following.ts +25 -20
- package/src/clis/twitter/notifications.ts +34 -27
- package/src/clis/twitter/reply-dm.ts +193 -0
- package/src/clis/twitter/search.ts +53 -13
- package/src/clis/weread/book.ts +28 -0
- package/src/clis/weread/highlights.ts +25 -0
- package/src/clis/weread/notebooks.ts +23 -0
- package/src/clis/weread/notes.ts +31 -0
- package/src/clis/weread/ranking.ts +29 -0
- package/src/clis/weread/search.ts +26 -0
- package/src/clis/weread/shelf.ts +26 -0
- package/src/clis/weread/utils.test.ts +104 -0
- package/src/clis/weread/utils.ts +74 -0
- package/src/daemon.ts +217 -0
- package/src/doctor.test.ts +32 -193
- package/src/doctor.ts +58 -669
- package/src/main.ts +11 -34
- package/src/pipeline/executor.test.ts +1 -0
- package/src/pipeline/steps/browser.ts +2 -2
- package/src/pipeline/steps/intercept.ts +1 -2
- package/src/runtime.ts +2 -6
- package/src/setup.ts +47 -183
- package/src/types.ts +1 -0
- package/tests/e2e/public-commands.test.ts +68 -1
- package/dist/clis/grok/debug.d.ts +0 -1
- package/dist/clis/grok/debug.js +0 -45
- package/src/clis/grok/debug.ts +0 -49
package/src/browser/page.ts
CHANGED
|
@@ -1,139 +1,252 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Page abstraction
|
|
2
|
+
* Page abstraction — implements IPage by sending commands to the daemon.
|
|
3
|
+
*
|
|
4
|
+
* All browser operations are ultimately 'exec' (JS evaluation via CDP)
|
|
5
|
+
* plus a few native Chrome Extension APIs (tabs, cookies, navigate).
|
|
6
|
+
*
|
|
7
|
+
* IMPORTANT: After goto(), we remember the tabId returned by the navigate
|
|
8
|
+
* action and pass it to all subsequent commands. This avoids the issue
|
|
9
|
+
* where resolveTabId() in the extension picks a chrome:// or
|
|
10
|
+
* chrome-extension:// tab that can't be debugged.
|
|
3
11
|
*/
|
|
4
12
|
|
|
5
13
|
import { formatSnapshot } from '../snapshotFormatter.js';
|
|
6
|
-
import { normalizeEvaluateSource } from '../pipeline/template.js';
|
|
7
|
-
import { generateInterceptorJs, generateReadInterceptedJs } from '../interceptor.js';
|
|
8
14
|
import type { IPage } from '../types.js';
|
|
9
|
-
import {
|
|
15
|
+
import { sendCommand } from './daemon-client.js';
|
|
10
16
|
|
|
11
17
|
/**
|
|
12
|
-
* Page
|
|
18
|
+
* Page — implements IPage by talking to the daemon via HTTP.
|
|
13
19
|
*/
|
|
14
20
|
export class Page implements IPage {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
async call(method: string, params: Record<string, unknown> = {}): Promise<any> {
|
|
18
|
-
const resp = await this._request(method, params);
|
|
19
|
-
if (resp.error) throw new Error(`page.${method}: ${(resp.error as any).message ?? JSON.stringify(resp.error)}`);
|
|
20
|
-
// Extract text content from MCP result
|
|
21
|
-
const result = resp.result as any;
|
|
22
|
-
|
|
23
|
-
if (result?.isError) {
|
|
24
|
-
const errorText = result.content?.find((c: any) => c.type === 'text')?.text || 'Unknown MCP Error';
|
|
25
|
-
throw new BrowserConnectError(
|
|
26
|
-
errorText,
|
|
27
|
-
'Please check if the browser is running or if the Playwright MCP / CDP connection is configured correctly.'
|
|
28
|
-
);
|
|
29
|
-
}
|
|
21
|
+
/** Active tab ID, set after navigate and used in all subsequent commands */
|
|
22
|
+
private _tabId: number | undefined;
|
|
30
23
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
// Some versions of the MCP return error text without the `isError` boolean flag
|
|
37
|
-
if (typeof text === 'string' && text.trim().startsWith('### Error')) {
|
|
38
|
-
throw new BrowserConnectError(
|
|
39
|
-
text.trim(),
|
|
40
|
-
'Please check if the browser is running or if the Playwright MCP / CDP connection is configured correctly.'
|
|
41
|
-
);
|
|
42
|
-
}
|
|
24
|
+
/** Helper: spread tabId into command params if we have one */
|
|
25
|
+
private _tabOpt(): { tabId: number } | Record<string, never> {
|
|
26
|
+
return this._tabId !== undefined ? { tabId: this._tabId } : {};
|
|
27
|
+
}
|
|
43
28
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
if (resultMarker !== -1) {
|
|
53
|
-
text = text.slice(resultMarker + '### Result\n'.length).trim();
|
|
54
|
-
}
|
|
55
|
-
try { return JSON.parse(text); } catch { return text; }
|
|
56
|
-
}
|
|
29
|
+
async goto(url: string): Promise<void> {
|
|
30
|
+
const result = await sendCommand('navigate', {
|
|
31
|
+
url,
|
|
32
|
+
...this._tabOpt(),
|
|
33
|
+
}) as { tabId?: number };
|
|
34
|
+
// Remember the tabId for subsequent exec calls
|
|
35
|
+
if (result?.tabId) {
|
|
36
|
+
this._tabId = result.tabId;
|
|
57
37
|
}
|
|
58
|
-
return result;
|
|
59
38
|
}
|
|
60
39
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
40
|
+
/** Close the automation window in the extension */
|
|
41
|
+
async closeWindow(): Promise<void> {
|
|
42
|
+
try {
|
|
43
|
+
await sendCommand('close-window', {});
|
|
44
|
+
} catch {
|
|
45
|
+
// Window may already be closed or daemon may be down
|
|
46
|
+
}
|
|
65
47
|
}
|
|
66
48
|
|
|
67
49
|
async evaluate(js: string): Promise<any> {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
return this.call('tools/call', { name: 'browser_evaluate', arguments: { function: normalized } });
|
|
50
|
+
const code = wrapForEval(js);
|
|
51
|
+
return sendCommand('exec', { code, ...this._tabOpt() });
|
|
71
52
|
}
|
|
72
53
|
|
|
73
54
|
async snapshot(opts: { interactive?: boolean; compact?: boolean; maxDepth?: number; raw?: boolean } = {}): Promise<any> {
|
|
74
|
-
const
|
|
55
|
+
const maxDepth = Math.max(1, Math.min(Number(opts.maxDepth) || 50, 200));
|
|
56
|
+
const code = `
|
|
57
|
+
(async () => {
|
|
58
|
+
function buildTree(node, depth) {
|
|
59
|
+
if (depth > ${maxDepth}) return '';
|
|
60
|
+
const role = node.getAttribute?.('role') || node.tagName?.toLowerCase() || 'generic';
|
|
61
|
+
const name = node.getAttribute?.('aria-label') || node.getAttribute?.('alt') || node.textContent?.trim().slice(0, 80) || '';
|
|
62
|
+
const isInteractive = ['a', 'button', 'input', 'select', 'textarea'].includes(node.tagName?.toLowerCase()) || node.getAttribute?.('tabindex') != null;
|
|
63
|
+
|
|
64
|
+
${opts.interactive ? 'if (!isInteractive && !node.children?.length) return "";' : ''}
|
|
65
|
+
|
|
66
|
+
let indent = ' '.repeat(depth);
|
|
67
|
+
let line = indent + role;
|
|
68
|
+
if (name) line += ' "' + name.replace(/"/g, '\\\\"') + '"';
|
|
69
|
+
if (node.tagName?.toLowerCase() === 'a' && node.href) line += ' [' + node.href + ']';
|
|
70
|
+
if (node.tagName?.toLowerCase() === 'input') line += ' [' + (node.type || 'text') + ']';
|
|
71
|
+
|
|
72
|
+
let result = line + '\\n';
|
|
73
|
+
if (node.children) {
|
|
74
|
+
for (const child of node.children) {
|
|
75
|
+
result += buildTree(child, depth + 1);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return result;
|
|
79
|
+
}
|
|
80
|
+
return buildTree(document.body, 0);
|
|
81
|
+
})()
|
|
82
|
+
`;
|
|
83
|
+
const raw = await sendCommand('exec', { code, ...this._tabOpt() });
|
|
75
84
|
if (opts.raw) return raw;
|
|
76
85
|
if (typeof raw === 'string') return formatSnapshot(raw, opts);
|
|
77
86
|
return raw;
|
|
78
87
|
}
|
|
79
88
|
|
|
80
89
|
async click(ref: string): Promise<void> {
|
|
81
|
-
|
|
90
|
+
const safeRef = JSON.stringify(ref);
|
|
91
|
+
const code = `
|
|
92
|
+
(() => {
|
|
93
|
+
const ref = ${safeRef};
|
|
94
|
+
const el = document.querySelector('[data-ref="' + ref + '"]')
|
|
95
|
+
|| document.querySelectorAll('a, button, input, [role="button"], [tabindex]')[parseInt(ref, 10) || 0];
|
|
96
|
+
if (!el) throw new Error('Element not found: ' + ref);
|
|
97
|
+
el.scrollIntoView({ behavior: 'instant', block: 'center' });
|
|
98
|
+
el.click();
|
|
99
|
+
return 'clicked';
|
|
100
|
+
})()
|
|
101
|
+
`;
|
|
102
|
+
await sendCommand('exec', { code, ...this._tabOpt() });
|
|
82
103
|
}
|
|
83
104
|
|
|
84
105
|
async typeText(ref: string, text: string): Promise<void> {
|
|
85
|
-
|
|
106
|
+
const safeRef = JSON.stringify(ref);
|
|
107
|
+
const safeText = JSON.stringify(text);
|
|
108
|
+
const code = `
|
|
109
|
+
(() => {
|
|
110
|
+
const ref = ${safeRef};
|
|
111
|
+
const el = document.querySelector('[data-ref="' + ref + '"]')
|
|
112
|
+
|| document.querySelectorAll('input, textarea, [contenteditable]')[parseInt(ref, 10) || 0];
|
|
113
|
+
if (!el) throw new Error('Element not found: ' + ref);
|
|
114
|
+
el.focus();
|
|
115
|
+
el.value = ${safeText};
|
|
116
|
+
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
117
|
+
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
118
|
+
return 'typed';
|
|
119
|
+
})()
|
|
120
|
+
`;
|
|
121
|
+
await sendCommand('exec', { code, ...this._tabOpt() });
|
|
86
122
|
}
|
|
87
123
|
|
|
88
124
|
async pressKey(key: string): Promise<void> {
|
|
89
|
-
|
|
125
|
+
const code = `
|
|
126
|
+
(() => {
|
|
127
|
+
const el = document.activeElement || document.body;
|
|
128
|
+
el.dispatchEvent(new KeyboardEvent('keydown', { key: ${JSON.stringify(key)}, bubbles: true }));
|
|
129
|
+
el.dispatchEvent(new KeyboardEvent('keyup', { key: ${JSON.stringify(key)}, bubbles: true }));
|
|
130
|
+
return 'pressed';
|
|
131
|
+
})()
|
|
132
|
+
`;
|
|
133
|
+
await sendCommand('exec', { code, ...this._tabOpt() });
|
|
90
134
|
}
|
|
91
135
|
|
|
92
136
|
async wait(options: number | { text?: string; time?: number; timeout?: number }): Promise<void> {
|
|
93
137
|
if (typeof options === 'number') {
|
|
94
|
-
await
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
138
|
+
await new Promise(resolve => setTimeout(resolve, options * 1000));
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (options.time) {
|
|
142
|
+
await new Promise(resolve => setTimeout(resolve, options.time! * 1000));
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (options.text) {
|
|
146
|
+
const timeout = (options.timeout ?? 30) * 1000;
|
|
147
|
+
const code = `
|
|
148
|
+
new Promise((resolve, reject) => {
|
|
149
|
+
const deadline = Date.now() + ${timeout};
|
|
150
|
+
const check = () => {
|
|
151
|
+
if (document.body.innerText.includes(${JSON.stringify(options.text)})) return resolve('found');
|
|
152
|
+
if (Date.now() > deadline) return reject(new Error('Text not found: ' + ${JSON.stringify(options.text)}));
|
|
153
|
+
setTimeout(check, 200);
|
|
154
|
+
};
|
|
155
|
+
check();
|
|
156
|
+
})
|
|
157
|
+
`;
|
|
158
|
+
await sendCommand('exec', { code, ...this._tabOpt() });
|
|
98
159
|
}
|
|
99
160
|
}
|
|
100
161
|
|
|
101
162
|
async tabs(): Promise<any> {
|
|
102
|
-
return
|
|
163
|
+
return sendCommand('tabs', { op: 'list' });
|
|
103
164
|
}
|
|
104
165
|
|
|
105
166
|
async closeTab(index?: number): Promise<void> {
|
|
106
|
-
await
|
|
167
|
+
await sendCommand('tabs', { op: 'close', ...(index !== undefined ? { index } : {}) });
|
|
107
168
|
}
|
|
108
169
|
|
|
109
170
|
async newTab(): Promise<void> {
|
|
110
|
-
await
|
|
171
|
+
await sendCommand('tabs', { op: 'new' });
|
|
111
172
|
}
|
|
112
173
|
|
|
113
174
|
async selectTab(index: number): Promise<void> {
|
|
114
|
-
await
|
|
175
|
+
await sendCommand('tabs', { op: 'select', index });
|
|
115
176
|
}
|
|
116
177
|
|
|
117
178
|
async networkRequests(includeStatic: boolean = false): Promise<any> {
|
|
118
|
-
|
|
179
|
+
const code = `
|
|
180
|
+
(() => {
|
|
181
|
+
const entries = performance.getEntriesByType('resource');
|
|
182
|
+
return entries
|
|
183
|
+
${includeStatic ? '' : '.filter(e => !["img", "font", "css", "script"].some(t => e.initiatorType === t))'}
|
|
184
|
+
.map(e => ({
|
|
185
|
+
url: e.name,
|
|
186
|
+
type: e.initiatorType,
|
|
187
|
+
duration: Math.round(e.duration),
|
|
188
|
+
size: e.transferSize || 0,
|
|
189
|
+
}));
|
|
190
|
+
})()
|
|
191
|
+
`;
|
|
192
|
+
return sendCommand('exec', { code, ...this._tabOpt() });
|
|
119
193
|
}
|
|
120
194
|
|
|
121
|
-
|
|
122
|
-
|
|
195
|
+
/**
|
|
196
|
+
* Console messages are not available in lightweight daemon mode.
|
|
197
|
+
* Would require CDP Runtime.consoleAPICalled event listener.
|
|
198
|
+
* @returns Always returns empty array.
|
|
199
|
+
*/
|
|
200
|
+
async consoleMessages(_level: string = 'info'): Promise<any> {
|
|
201
|
+
return [];
|
|
123
202
|
}
|
|
124
203
|
|
|
125
|
-
|
|
126
|
-
|
|
204
|
+
/**
|
|
205
|
+
* Capture a screenshot via CDP Page.captureScreenshot.
|
|
206
|
+
* @param options.format - 'png' (default) or 'jpeg'
|
|
207
|
+
* @param options.quality - JPEG quality 0-100
|
|
208
|
+
* @param options.fullPage - capture full scrollable page
|
|
209
|
+
* @param options.path - save to file path (returns base64 if omitted)
|
|
210
|
+
*/
|
|
211
|
+
async screenshot(options: {
|
|
212
|
+
format?: 'png' | 'jpeg';
|
|
213
|
+
quality?: number;
|
|
214
|
+
fullPage?: boolean;
|
|
215
|
+
path?: string;
|
|
216
|
+
} = {}): Promise<string> {
|
|
217
|
+
const base64 = await sendCommand('screenshot', {
|
|
218
|
+
format: options.format,
|
|
219
|
+
quality: options.quality,
|
|
220
|
+
fullPage: options.fullPage,
|
|
221
|
+
...this._tabOpt(),
|
|
222
|
+
}) as string;
|
|
223
|
+
|
|
224
|
+
if (options.path) {
|
|
225
|
+
const fs = await import('node:fs');
|
|
226
|
+
const path = await import('node:path');
|
|
227
|
+
const dir = path.dirname(options.path);
|
|
228
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
229
|
+
fs.writeFileSync(options.path, Buffer.from(base64, 'base64'));
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
return base64;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async scroll(direction: string = 'down', amount: number = 500): Promise<void> {
|
|
236
|
+
const dx = direction === 'left' ? -amount : direction === 'right' ? amount : 0;
|
|
237
|
+
const dy = direction === 'up' ? -amount : direction === 'down' ? amount : 0;
|
|
238
|
+
await sendCommand('exec', {
|
|
239
|
+
code: `window.scrollBy(${dx}, ${dy})`,
|
|
240
|
+
...this._tabOpt(),
|
|
241
|
+
});
|
|
127
242
|
}
|
|
128
243
|
|
|
129
244
|
async autoScroll(options: { times?: number; delayMs?: number } = {}): Promise<void> {
|
|
130
245
|
const times = options.times ?? 3;
|
|
131
246
|
const delayMs = options.delayMs ?? 2000;
|
|
132
|
-
const
|
|
133
|
-
async () => {
|
|
134
|
-
|
|
135
|
-
const maxWaitMs = ${delayMs};
|
|
136
|
-
for (let i = 0; i < maxTimes; i++) {
|
|
247
|
+
const code = `
|
|
248
|
+
(async () => {
|
|
249
|
+
for (let i = 0; i < ${times}; i++) {
|
|
137
250
|
const lastHeight = document.body.scrollHeight;
|
|
138
251
|
window.scrollTo(0, lastHeight);
|
|
139
252
|
await new Promise(resolve => {
|
|
@@ -142,22 +255,22 @@ export class Page implements IPage {
|
|
|
142
255
|
if (document.body.scrollHeight > lastHeight) {
|
|
143
256
|
clearTimeout(timeoutId);
|
|
144
257
|
observer.disconnect();
|
|
145
|
-
setTimeout(resolve, 100);
|
|
258
|
+
setTimeout(resolve, 100);
|
|
146
259
|
}
|
|
147
260
|
});
|
|
148
261
|
observer.observe(document.body, { childList: true, subtree: true });
|
|
149
|
-
timeoutId = setTimeout(() => {
|
|
150
|
-
observer.disconnect();
|
|
151
|
-
resolve(null);
|
|
152
|
-
}, maxWaitMs);
|
|
262
|
+
timeoutId = setTimeout(() => { observer.disconnect(); resolve(null); }, ${delayMs});
|
|
153
263
|
});
|
|
154
264
|
}
|
|
155
|
-
}
|
|
265
|
+
})()
|
|
156
266
|
`;
|
|
157
|
-
await this.
|
|
267
|
+
await sendCommand('exec', { code, ...this._tabOpt() });
|
|
158
268
|
}
|
|
159
269
|
|
|
160
270
|
async installInterceptor(pattern: string): Promise<void> {
|
|
271
|
+
const { generateInterceptorJs } = await import('../interceptor.js');
|
|
272
|
+
// Must use evaluate() so wrapForEval() converts the arrow function into an IIFE;
|
|
273
|
+
// sendCommand('exec') sends the code as-is, and CDP never executes a bare arrow.
|
|
161
274
|
await this.evaluate(generateInterceptorJs(JSON.stringify(pattern), {
|
|
162
275
|
arrayName: '__opencli_xhr',
|
|
163
276
|
patchGuard: '__opencli_interceptor_patched',
|
|
@@ -165,7 +278,34 @@ export class Page implements IPage {
|
|
|
165
278
|
}
|
|
166
279
|
|
|
167
280
|
async getInterceptedRequests(): Promise<any[]> {
|
|
281
|
+
const { generateReadInterceptedJs } = await import('../interceptor.js');
|
|
282
|
+
// Same as installInterceptor: must go through evaluate() for IIFE wrapping
|
|
168
283
|
const result = await this.evaluate(generateReadInterceptedJs('__opencli_xhr'));
|
|
169
|
-
return result || [];
|
|
284
|
+
return (result as any[]) || [];
|
|
170
285
|
}
|
|
171
286
|
}
|
|
287
|
+
|
|
288
|
+
// ─── Helpers ─────────────────────────────────────────────────────────
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Wrap JS code for CDP Runtime.evaluate:
|
|
292
|
+
* - Already an IIFE `(...)()` → send as-is
|
|
293
|
+
* - Arrow/function literal → wrap as IIFE `(code)()`
|
|
294
|
+
* - `new Promise(...)` or raw expression → send as-is (expression)
|
|
295
|
+
*/
|
|
296
|
+
function wrapForEval(js: string): string {
|
|
297
|
+
const code = js.trim();
|
|
298
|
+
if (!code) return 'undefined';
|
|
299
|
+
|
|
300
|
+
// Already an IIFE: `(async () => { ... })()` or `(function() {...})()`
|
|
301
|
+
if (/^\([\s\S]*\)\s*\(.*\)\s*$/.test(code)) return code;
|
|
302
|
+
|
|
303
|
+
// Arrow function: `() => ...` or `async () => ...`
|
|
304
|
+
if (/^(async\s+)?(\([^)]*\)|[A-Za-z_]\w*)\s*=>/.test(code)) return `(${code})()`;
|
|
305
|
+
|
|
306
|
+
// Function declaration: `function ...` or `async function ...`
|
|
307
|
+
if (/^(async\s+)?function[\s(]/.test(code)) return `(${code})()`;
|
|
308
|
+
|
|
309
|
+
// Everything else: bare expression, `new Promise(...)`, etc. → evaluate directly
|
|
310
|
+
return code;
|
|
311
|
+
}
|
package/src/browser.test.ts
CHANGED
|
@@ -1,24 +1,7 @@
|
|
|
1
1
|
import { afterEach, describe, it, expect, vi } from 'vitest';
|
|
2
|
-
import
|
|
3
|
-
import * as path from 'node:path';
|
|
4
|
-
import { PlaywrightMCP, __test__ } from './browser/index.js';
|
|
5
|
-
|
|
6
|
-
afterEach(() => {
|
|
7
|
-
__test__.resetMcpServerPathCache();
|
|
8
|
-
__test__.setMcpDiscoveryTestHooks();
|
|
9
|
-
delete process.env.OPENCLI_MCP_SERVER_PATH;
|
|
10
|
-
});
|
|
2
|
+
import { BrowserBridge, __test__ } from './browser/index.js';
|
|
11
3
|
|
|
12
4
|
describe('browser helpers', () => {
|
|
13
|
-
it('creates JSON-RPC requests with unique ids', () => {
|
|
14
|
-
const first = __test__.createJsonRpcRequest('tools/call', { name: 'browser_tabs' });
|
|
15
|
-
const second = __test__.createJsonRpcRequest('tools/call', { name: 'browser_snapshot' });
|
|
16
|
-
|
|
17
|
-
expect(second.id).toBe(first.id + 1);
|
|
18
|
-
expect(first.message).toContain(`"id":${first.id}`);
|
|
19
|
-
expect(second.message).toContain(`"id":${second.id}`);
|
|
20
|
-
});
|
|
21
|
-
|
|
22
5
|
it('extracts tab entries from string snapshots', () => {
|
|
23
6
|
const entries = __test__.extractTabEntries('Tab 0 https://example.com\nTab 1 Chrome Extension');
|
|
24
7
|
|
|
@@ -57,225 +40,14 @@ describe('browser helpers', () => {
|
|
|
57
40
|
expect(__test__.appendLimited('12345', '67890', 8)).toBe('34567890');
|
|
58
41
|
});
|
|
59
42
|
|
|
60
|
-
it('builds extension MCP args in local mode (no CI)', () => {
|
|
61
|
-
const savedCI = process.env.CI;
|
|
62
|
-
delete process.env.CI;
|
|
63
|
-
try {
|
|
64
|
-
expect(__test__.buildMcpArgs({
|
|
65
|
-
mcpPath: '/tmp/cli.js',
|
|
66
|
-
executablePath: '/mnt/c/Program Files/Google/Chrome/Application/chrome.exe',
|
|
67
|
-
})).toEqual([
|
|
68
|
-
'/tmp/cli.js',
|
|
69
|
-
'--extension',
|
|
70
|
-
'--executable-path',
|
|
71
|
-
'/mnt/c/Program Files/Google/Chrome/Application/chrome.exe',
|
|
72
|
-
]);
|
|
73
|
-
|
|
74
|
-
expect(__test__.buildMcpArgs({
|
|
75
|
-
mcpPath: '/tmp/cli.js',
|
|
76
|
-
})).toEqual([
|
|
77
|
-
'/tmp/cli.js',
|
|
78
|
-
'--extension',
|
|
79
|
-
]);
|
|
80
|
-
} finally {
|
|
81
|
-
if (savedCI !== undefined) {
|
|
82
|
-
process.env.CI = savedCI;
|
|
83
|
-
} else {
|
|
84
|
-
delete process.env.CI;
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
});
|
|
88
|
-
|
|
89
|
-
it('builds standalone MCP args in CI mode', () => {
|
|
90
|
-
const savedCI = process.env.CI;
|
|
91
|
-
process.env.CI = 'true';
|
|
92
|
-
try {
|
|
93
|
-
// CI mode: no --extension — browser launches in standalone headed mode
|
|
94
|
-
expect(__test__.buildMcpArgs({
|
|
95
|
-
mcpPath: '/tmp/cli.js',
|
|
96
|
-
})).toEqual([
|
|
97
|
-
'/tmp/cli.js',
|
|
98
|
-
]);
|
|
99
|
-
|
|
100
|
-
expect(__test__.buildMcpArgs({
|
|
101
|
-
mcpPath: '/tmp/cli.js',
|
|
102
|
-
executablePath: '/usr/bin/chromium',
|
|
103
|
-
})).toEqual([
|
|
104
|
-
'/tmp/cli.js',
|
|
105
|
-
'--executable-path',
|
|
106
|
-
'/usr/bin/chromium',
|
|
107
|
-
]);
|
|
108
|
-
} finally {
|
|
109
|
-
if (savedCI !== undefined) {
|
|
110
|
-
process.env.CI = savedCI;
|
|
111
|
-
} else {
|
|
112
|
-
delete process.env.CI;
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
});
|
|
116
|
-
|
|
117
|
-
it('builds a direct node launch spec when a local MCP path is available', () => {
|
|
118
|
-
const savedCI = process.env.CI;
|
|
119
|
-
delete process.env.CI;
|
|
120
|
-
try {
|
|
121
|
-
expect(__test__.buildMcpLaunchSpec({
|
|
122
|
-
mcpPath: '/tmp/cli.js',
|
|
123
|
-
executablePath: '/usr/bin/google-chrome',
|
|
124
|
-
})).toEqual({
|
|
125
|
-
command: 'node',
|
|
126
|
-
args: ['/tmp/cli.js', '--extension', '--executable-path', '/usr/bin/google-chrome'],
|
|
127
|
-
usedNpxFallback: false,
|
|
128
|
-
});
|
|
129
|
-
} finally {
|
|
130
|
-
if (savedCI !== undefined) {
|
|
131
|
-
process.env.CI = savedCI;
|
|
132
|
-
} else {
|
|
133
|
-
delete process.env.CI;
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
});
|
|
137
|
-
|
|
138
|
-
it('falls back to npx bootstrap when no MCP path is available', () => {
|
|
139
|
-
const savedCI = process.env.CI;
|
|
140
|
-
delete process.env.CI;
|
|
141
|
-
try {
|
|
142
|
-
expect(__test__.buildMcpLaunchSpec({
|
|
143
|
-
mcpPath: null,
|
|
144
|
-
})).toEqual({
|
|
145
|
-
command: 'npx',
|
|
146
|
-
args: ['-y', '@playwright/mcp@latest', '--extension'],
|
|
147
|
-
usedNpxFallback: true,
|
|
148
|
-
});
|
|
149
|
-
} finally {
|
|
150
|
-
if (savedCI !== undefined) {
|
|
151
|
-
process.env.CI = savedCI;
|
|
152
|
-
} else {
|
|
153
|
-
delete process.env.CI;
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
});
|
|
157
|
-
|
|
158
43
|
it('times out slow promises', async () => {
|
|
159
44
|
await expect(__test__.withTimeoutMs(new Promise(() => {}), 10, 'timeout')).rejects.toThrow('timeout');
|
|
160
45
|
});
|
|
161
|
-
|
|
162
|
-
it('prefers OPENCLI_MCP_SERVER_PATH over discovered locations', () => {
|
|
163
|
-
process.env.OPENCLI_MCP_SERVER_PATH = '/env/mcp/cli.js';
|
|
164
|
-
const existsSync = vi.fn((candidate: any) => candidate === '/env/mcp/cli.js');
|
|
165
|
-
const execSync = vi.fn();
|
|
166
|
-
__test__.setMcpDiscoveryTestHooks({ existsSync, execSync: execSync as any });
|
|
167
|
-
|
|
168
|
-
expect(__test__.findMcpServerPath()).toBe('/env/mcp/cli.js');
|
|
169
|
-
expect(execSync).not.toHaveBeenCalled();
|
|
170
|
-
expect(existsSync).toHaveBeenCalledWith('/env/mcp/cli.js');
|
|
171
|
-
});
|
|
172
|
-
|
|
173
|
-
it('discovers global @playwright/mcp from the current Node runtime prefix', () => {
|
|
174
|
-
const originalExecPath = process.execPath;
|
|
175
|
-
const runtimeExecPath = '/opt/homebrew/Cellar/node/25.2.1/bin/node';
|
|
176
|
-
const runtimeGlobalMcp = '/opt/homebrew/Cellar/node/25.2.1/lib/node_modules/@playwright/mcp/cli.js';
|
|
177
|
-
Object.defineProperty(process, 'execPath', {
|
|
178
|
-
value: runtimeExecPath,
|
|
179
|
-
configurable: true,
|
|
180
|
-
});
|
|
181
|
-
|
|
182
|
-
const existsSync = vi.fn((candidate: any) => candidate === runtimeGlobalMcp);
|
|
183
|
-
const execSync = vi.fn();
|
|
184
|
-
__test__.setMcpDiscoveryTestHooks({ existsSync, execSync: execSync as any });
|
|
185
|
-
|
|
186
|
-
try {
|
|
187
|
-
expect(__test__.findMcpServerPath()).toBe(runtimeGlobalMcp);
|
|
188
|
-
expect(execSync).not.toHaveBeenCalled();
|
|
189
|
-
expect(existsSync).toHaveBeenCalledWith(runtimeGlobalMcp);
|
|
190
|
-
} finally {
|
|
191
|
-
Object.defineProperty(process, 'execPath', {
|
|
192
|
-
value: originalExecPath,
|
|
193
|
-
configurable: true,
|
|
194
|
-
});
|
|
195
|
-
}
|
|
196
|
-
});
|
|
197
|
-
|
|
198
|
-
it('falls back to npm root -g when runtime prefix lookup misses', () => {
|
|
199
|
-
const originalExecPath = process.execPath;
|
|
200
|
-
const runtimeExecPath = '/opt/homebrew/Cellar/node/25.2.1/bin/node';
|
|
201
|
-
const runtimeGlobalMcp = '/opt/homebrew/Cellar/node/25.2.1/lib/node_modules/@playwright/mcp/cli.js';
|
|
202
|
-
const npmRootGlobal = '/Users/jakevin/.nvm/versions/node/v22.14.0/lib/node_modules';
|
|
203
|
-
const npmGlobalMcp = '/Users/jakevin/.nvm/versions/node/v22.14.0/lib/node_modules/@playwright/mcp/cli.js';
|
|
204
|
-
Object.defineProperty(process, 'execPath', {
|
|
205
|
-
value: runtimeExecPath,
|
|
206
|
-
configurable: true,
|
|
207
|
-
});
|
|
208
|
-
|
|
209
|
-
const existsSync = vi.fn((candidate: any) => candidate === npmGlobalMcp);
|
|
210
|
-
const execSync = vi.fn((command: string) => {
|
|
211
|
-
if (String(command).includes('npm root -g')) return `${npmRootGlobal}\n` as any;
|
|
212
|
-
throw new Error(`unexpected command: ${String(command)}`);
|
|
213
|
-
});
|
|
214
|
-
__test__.setMcpDiscoveryTestHooks({ existsSync, execSync: execSync as any });
|
|
215
|
-
|
|
216
|
-
try {
|
|
217
|
-
expect(__test__.findMcpServerPath()).toBe(npmGlobalMcp);
|
|
218
|
-
expect(execSync).toHaveBeenCalledOnce();
|
|
219
|
-
expect(existsSync).toHaveBeenCalledWith(runtimeGlobalMcp);
|
|
220
|
-
expect(existsSync).toHaveBeenCalledWith(npmGlobalMcp);
|
|
221
|
-
} finally {
|
|
222
|
-
Object.defineProperty(process, 'execPath', {
|
|
223
|
-
value: originalExecPath,
|
|
224
|
-
configurable: true,
|
|
225
|
-
});
|
|
226
|
-
}
|
|
227
|
-
});
|
|
228
|
-
|
|
229
|
-
it('returns null when new global discovery paths are unavailable', () => {
|
|
230
|
-
const originalExecPath = process.execPath;
|
|
231
|
-
const runtimeExecPath = '/opt/homebrew/Cellar/node/25.2.1/bin/node';
|
|
232
|
-
Object.defineProperty(process, 'execPath', {
|
|
233
|
-
value: runtimeExecPath,
|
|
234
|
-
configurable: true,
|
|
235
|
-
});
|
|
236
|
-
|
|
237
|
-
const existsSync = vi.fn(() => false);
|
|
238
|
-
const execSync = vi.fn((command: string) => {
|
|
239
|
-
if (String(command).includes('npm root -g')) return '/missing/global/node_modules\n' as any;
|
|
240
|
-
throw new Error(`missing command: ${String(command)}`);
|
|
241
|
-
});
|
|
242
|
-
__test__.setMcpDiscoveryTestHooks({ existsSync, execSync: execSync as any });
|
|
243
|
-
|
|
244
|
-
try {
|
|
245
|
-
expect(__test__.findMcpServerPath()).toBeNull();
|
|
246
|
-
} finally {
|
|
247
|
-
Object.defineProperty(process, 'execPath', {
|
|
248
|
-
value: originalExecPath,
|
|
249
|
-
configurable: true,
|
|
250
|
-
});
|
|
251
|
-
}
|
|
252
|
-
});
|
|
253
|
-
|
|
254
|
-
it('ignores non-server playwright cli paths discovered from fallback scans', () => {
|
|
255
|
-
const wrongCli = '/root/.npm/_npx/e41f203b7505f1fb/node_modules/playwright/lib/mcp/terminal/cli.js';
|
|
256
|
-
const npxCacheBase = path.join(os.homedir(), '.npm', '_npx');
|
|
257
|
-
|
|
258
|
-
const existsSync = vi.fn((candidate: any) => {
|
|
259
|
-
const value = String(candidate);
|
|
260
|
-
return value === npxCacheBase || value === wrongCli;
|
|
261
|
-
});
|
|
262
|
-
|
|
263
|
-
const execSync = vi.fn((command: string) => {
|
|
264
|
-
if (String(command).includes('npm root -g')) return '/missing/global/node_modules\n' as any;
|
|
265
|
-
if (String(command).includes('--package=@playwright/mcp which mcp-server-playwright')) return `${wrongCli}\n` as any;
|
|
266
|
-
if (String(command).includes('which mcp-server-playwright')) return '' as any;
|
|
267
|
-
if (String(command).includes(`find "${npxCacheBase}"`)) return `${wrongCli}\n` as any;
|
|
268
|
-
throw new Error(`unexpected command: ${String(command)}`);
|
|
269
|
-
});
|
|
270
|
-
__test__.setMcpDiscoveryTestHooks({ existsSync, execSync: execSync as any });
|
|
271
|
-
|
|
272
|
-
expect(__test__.findMcpServerPath()).toBeNull();
|
|
273
|
-
});
|
|
274
46
|
});
|
|
275
47
|
|
|
276
|
-
describe('
|
|
48
|
+
describe('BrowserBridge state', () => {
|
|
277
49
|
it('transitions to closed after close()', async () => {
|
|
278
|
-
const mcp = new
|
|
50
|
+
const mcp = new BrowserBridge();
|
|
279
51
|
|
|
280
52
|
expect(mcp.state).toBe('idle');
|
|
281
53
|
|
|
@@ -285,25 +57,23 @@ describe('PlaywrightMCP state', () => {
|
|
|
285
57
|
});
|
|
286
58
|
|
|
287
59
|
it('rejects connect() after the session has been closed', async () => {
|
|
288
|
-
const mcp = new
|
|
60
|
+
const mcp = new BrowserBridge();
|
|
289
61
|
await mcp.close();
|
|
290
62
|
|
|
291
|
-
await expect(mcp.connect()).rejects.toThrow('
|
|
63
|
+
await expect(mcp.connect()).rejects.toThrow('Session is closed');
|
|
292
64
|
});
|
|
293
65
|
|
|
294
66
|
it('rejects connect() while already connecting', async () => {
|
|
295
|
-
const mcp = new
|
|
67
|
+
const mcp = new BrowserBridge();
|
|
296
68
|
(mcp as any)._state = 'connecting';
|
|
297
69
|
|
|
298
|
-
await expect(mcp.connect()).rejects.toThrow('
|
|
70
|
+
await expect(mcp.connect()).rejects.toThrow('Already connecting');
|
|
299
71
|
});
|
|
300
72
|
|
|
301
73
|
it('rejects connect() while closing', async () => {
|
|
302
|
-
const mcp = new
|
|
74
|
+
const mcp = new BrowserBridge();
|
|
303
75
|
(mcp as any)._state = 'closing';
|
|
304
76
|
|
|
305
|
-
await expect(mcp.connect()).rejects.toThrow('
|
|
77
|
+
await expect(mcp.connect()).rejects.toThrow('Session is closing');
|
|
306
78
|
});
|
|
307
|
-
|
|
308
|
-
|
|
309
79
|
});
|