@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.
Files changed (165) hide show
  1. package/CDP.md +1 -1
  2. package/CDP.zh-CN.md +1 -1
  3. package/CLI-ELECTRON.md +2 -2
  4. package/CLI-EXPLORER.md +4 -4
  5. package/README.md +35 -58
  6. package/README.zh-CN.md +36 -60
  7. package/SKILL.md +10 -8
  8. package/TESTING.md +7 -7
  9. package/dist/browser/daemon-client.d.ts +37 -0
  10. package/dist/browser/daemon-client.js +82 -0
  11. package/dist/browser/discover.d.ts +11 -34
  12. package/dist/browser/discover.js +15 -205
  13. package/dist/browser/errors.d.ts +6 -20
  14. package/dist/browser/errors.js +24 -63
  15. package/dist/browser/index.d.ts +2 -12
  16. package/dist/browser/index.js +2 -12
  17. package/dist/browser/mcp.d.ts +9 -21
  18. package/dist/browser/mcp.js +70 -285
  19. package/dist/browser/page.d.ts +36 -7
  20. package/dist/browser/page.js +212 -81
  21. package/dist/browser.test.js +10 -231
  22. package/dist/cli-manifest.json +561 -14
  23. package/dist/clis/apple-podcasts/episodes.d.ts +1 -0
  24. package/dist/clis/apple-podcasts/episodes.js +28 -0
  25. package/dist/clis/apple-podcasts/search.d.ts +1 -0
  26. package/dist/clis/apple-podcasts/search.js +29 -0
  27. package/dist/clis/apple-podcasts/top.d.ts +1 -0
  28. package/dist/clis/apple-podcasts/top.js +34 -0
  29. package/dist/clis/apple-podcasts/utils.d.ts +11 -0
  30. package/dist/clis/apple-podcasts/utils.js +30 -0
  31. package/dist/clis/apple-podcasts/utils.test.d.ts +1 -0
  32. package/dist/clis/apple-podcasts/utils.test.js +57 -0
  33. package/dist/clis/chatwise/history.js +18 -1
  34. package/dist/clis/discord-app/channels.js +33 -21
  35. package/dist/clis/neteasemusic/like.d.ts +1 -0
  36. package/dist/clis/neteasemusic/like.js +25 -0
  37. package/dist/clis/neteasemusic/lyrics.d.ts +1 -0
  38. package/dist/clis/neteasemusic/lyrics.js +47 -0
  39. package/dist/clis/neteasemusic/next.d.ts +1 -0
  40. package/dist/clis/neteasemusic/next.js +26 -0
  41. package/dist/clis/neteasemusic/play.d.ts +1 -0
  42. package/dist/clis/neteasemusic/play.js +26 -0
  43. package/dist/clis/neteasemusic/playing.d.ts +1 -0
  44. package/dist/clis/neteasemusic/playing.js +59 -0
  45. package/dist/clis/neteasemusic/playlist.d.ts +1 -0
  46. package/dist/clis/neteasemusic/playlist.js +46 -0
  47. package/dist/clis/neteasemusic/prev.d.ts +1 -0
  48. package/dist/clis/neteasemusic/prev.js +25 -0
  49. package/dist/clis/neteasemusic/search.d.ts +1 -0
  50. package/dist/clis/neteasemusic/search.js +52 -0
  51. package/dist/clis/neteasemusic/status.d.ts +1 -0
  52. package/dist/clis/neteasemusic/status.js +16 -0
  53. package/dist/clis/neteasemusic/volume.d.ts +1 -0
  54. package/dist/clis/neteasemusic/volume.js +54 -0
  55. package/dist/clis/twitter/accept.d.ts +1 -0
  56. package/dist/clis/twitter/accept.js +202 -0
  57. package/dist/clis/twitter/followers.js +30 -22
  58. package/dist/clis/twitter/following.js +19 -14
  59. package/dist/clis/twitter/notifications.js +29 -22
  60. package/dist/clis/twitter/reply-dm.d.ts +1 -0
  61. package/dist/clis/twitter/reply-dm.js +181 -0
  62. package/dist/clis/twitter/search.js +50 -12
  63. package/dist/clis/weread/book.d.ts +1 -0
  64. package/dist/clis/weread/book.js +26 -0
  65. package/dist/clis/weread/highlights.d.ts +1 -0
  66. package/dist/clis/weread/highlights.js +23 -0
  67. package/dist/clis/weread/notebooks.d.ts +1 -0
  68. package/dist/clis/weread/notebooks.js +21 -0
  69. package/dist/clis/weread/notes.d.ts +1 -0
  70. package/dist/clis/weread/notes.js +29 -0
  71. package/dist/clis/weread/ranking.d.ts +1 -0
  72. package/dist/clis/weread/ranking.js +28 -0
  73. package/dist/clis/weread/search.d.ts +1 -0
  74. package/dist/clis/weread/search.js +25 -0
  75. package/dist/clis/weread/shelf.d.ts +1 -0
  76. package/dist/clis/weread/shelf.js +24 -0
  77. package/dist/clis/weread/utils.d.ts +20 -0
  78. package/dist/clis/weread/utils.js +72 -0
  79. package/dist/clis/weread/utils.test.d.ts +1 -0
  80. package/dist/clis/weread/utils.test.js +85 -0
  81. package/dist/daemon.d.ts +13 -0
  82. package/dist/daemon.js +187 -0
  83. package/dist/doctor.d.ts +10 -65
  84. package/dist/doctor.js +49 -602
  85. package/dist/doctor.test.js +30 -170
  86. package/dist/main.js +12 -41
  87. package/dist/pipeline/executor.test.js +1 -0
  88. package/dist/pipeline/steps/browser.js +2 -2
  89. package/dist/pipeline/steps/intercept.js +1 -2
  90. package/dist/runtime.d.ts +1 -4
  91. package/dist/runtime.js +1 -4
  92. package/dist/setup.d.ts +6 -0
  93. package/dist/setup.js +46 -160
  94. package/dist/types.d.ts +6 -0
  95. package/extension/dist/background.js +484 -0
  96. package/extension/icons/icon-128.png +0 -0
  97. package/extension/icons/icon-16.png +0 -0
  98. package/extension/icons/icon-32.png +0 -0
  99. package/extension/icons/icon-48.png +0 -0
  100. package/extension/manifest.json +31 -0
  101. package/extension/package.json +16 -0
  102. package/extension/src/background.ts +370 -0
  103. package/extension/src/cdp.ts +125 -0
  104. package/extension/src/protocol.ts +57 -0
  105. package/extension/store-assets/screenshot-1280x800.png +0 -0
  106. package/extension/tsconfig.json +15 -0
  107. package/extension/vite.config.ts +18 -0
  108. package/package.json +5 -5
  109. package/src/browser/daemon-client.ts +113 -0
  110. package/src/browser/discover.ts +18 -232
  111. package/src/browser/errors.ts +30 -100
  112. package/src/browser/index.ts +2 -13
  113. package/src/browser/mcp.ts +81 -282
  114. package/src/browser/page.ts +223 -83
  115. package/src/browser.test.ts +9 -239
  116. package/src/clis/apple-podcasts/episodes.ts +28 -0
  117. package/src/clis/apple-podcasts/search.ts +29 -0
  118. package/src/clis/apple-podcasts/top.ts +34 -0
  119. package/src/clis/apple-podcasts/utils.test.ts +72 -0
  120. package/src/clis/apple-podcasts/utils.ts +37 -0
  121. package/src/clis/chatgpt/README.md +1 -1
  122. package/src/clis/chatgpt/README.zh-CN.md +1 -1
  123. package/src/clis/chatwise/history.ts +15 -1
  124. package/src/clis/discord-app/channels.ts +33 -21
  125. package/src/clis/neteasemusic/README.md +31 -0
  126. package/src/clis/neteasemusic/README.zh-CN.md +31 -0
  127. package/src/clis/neteasemusic/like.ts +28 -0
  128. package/src/clis/neteasemusic/lyrics.ts +53 -0
  129. package/src/clis/neteasemusic/next.ts +30 -0
  130. package/src/clis/neteasemusic/play.ts +30 -0
  131. package/src/clis/neteasemusic/playing.ts +62 -0
  132. package/src/clis/neteasemusic/playlist.ts +51 -0
  133. package/src/clis/neteasemusic/prev.ts +29 -0
  134. package/src/clis/neteasemusic/search.ts +58 -0
  135. package/src/clis/neteasemusic/status.ts +18 -0
  136. package/src/clis/neteasemusic/volume.ts +61 -0
  137. package/src/clis/twitter/accept.ts +213 -0
  138. package/src/clis/twitter/followers.ts +36 -29
  139. package/src/clis/twitter/following.ts +25 -20
  140. package/src/clis/twitter/notifications.ts +34 -27
  141. package/src/clis/twitter/reply-dm.ts +193 -0
  142. package/src/clis/twitter/search.ts +53 -13
  143. package/src/clis/weread/book.ts +28 -0
  144. package/src/clis/weread/highlights.ts +25 -0
  145. package/src/clis/weread/notebooks.ts +23 -0
  146. package/src/clis/weread/notes.ts +31 -0
  147. package/src/clis/weread/ranking.ts +29 -0
  148. package/src/clis/weread/search.ts +26 -0
  149. package/src/clis/weread/shelf.ts +26 -0
  150. package/src/clis/weread/utils.test.ts +104 -0
  151. package/src/clis/weread/utils.ts +74 -0
  152. package/src/daemon.ts +217 -0
  153. package/src/doctor.test.ts +32 -193
  154. package/src/doctor.ts +58 -669
  155. package/src/main.ts +11 -34
  156. package/src/pipeline/executor.test.ts +1 -0
  157. package/src/pipeline/steps/browser.ts +2 -2
  158. package/src/pipeline/steps/intercept.ts +1 -2
  159. package/src/runtime.ts +2 -6
  160. package/src/setup.ts +47 -183
  161. package/src/types.ts +1 -0
  162. package/tests/e2e/public-commands.test.ts +68 -1
  163. package/dist/clis/grok/debug.d.ts +0 -1
  164. package/dist/clis/grok/debug.js +0 -45
  165. package/src/clis/grok/debug.ts +0 -49
@@ -1,139 +1,252 @@
1
1
  /**
2
- * Page abstraction wrapping JSON-RPC calls to Playwright MCP.
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 { BrowserConnectError } from '../errors.js';
15
+ import { sendCommand } from './daemon-client.js';
10
16
 
11
17
  /**
12
- * Page abstraction wrapping JSON-RPC calls to Playwright MCP.
18
+ * Page implements IPage by talking to the daemon via HTTP.
13
19
  */
14
20
  export class Page implements IPage {
15
- constructor(private _request: (method: string, params?: Record<string, unknown>) => Promise<Record<string, unknown>>) {}
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
- if (result?.content) {
32
- const textParts = result.content.filter((c: any) => c.type === 'text');
33
- if (textParts.length >= 1) {
34
- let text = textParts[textParts.length - 1].text; // Usually the main output is in the last text block
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
- // MCP browser_evaluate returns: "[JSON]\n### Ran Playwright code\n```js\n...\n```"
45
- // Strip the "### Ran Playwright code" suffix to get clean JSON
46
- const codeMarker = text.indexOf('### Ran Playwright code');
47
- if (codeMarker !== -1) {
48
- text = text.slice(0, codeMarker).trim();
49
- }
50
- // Also handle "### Result\n[JSON]" format (some MCP versions)
51
- const resultMarker = text.indexOf('### Result\n');
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
- // --- High-level methods ---
62
-
63
- async goto(url: string): Promise<void> {
64
- await this.call('tools/call', { name: 'browser_navigate', arguments: { url } });
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
- // Normalize IIFE format to function format expected by MCP browser_evaluate
69
- const normalized = normalizeEvaluateSource(js);
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 raw = await this.call('tools/call', { name: 'browser_snapshot', arguments: {} });
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
- await this.call('tools/call', { name: 'browser_click', arguments: { element: 'click target', ref } });
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
- await this.call('tools/call', { name: 'browser_type', arguments: { element: 'type target', ref, text } });
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
- await this.call('tools/call', { name: 'browser_press_key', arguments: { key } });
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 this.call('tools/call', { name: 'browser_wait_for', arguments: { time: options } });
95
- } else {
96
- // Pass directly to native wait_for, which supports natively awaiting text strings without heavy DOM polling
97
- await this.call('tools/call', { name: 'browser_wait_for', arguments: options });
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 this.call('tools/call', { name: 'browser_tabs', arguments: { action: 'list' } });
163
+ return sendCommand('tabs', { op: 'list' });
103
164
  }
104
165
 
105
166
  async closeTab(index?: number): Promise<void> {
106
- await this.call('tools/call', { name: 'browser_tabs', arguments: { action: 'close', ...(index !== undefined ? { index } : {}) } });
167
+ await sendCommand('tabs', { op: 'close', ...(index !== undefined ? { index } : {}) });
107
168
  }
108
169
 
109
170
  async newTab(): Promise<void> {
110
- await this.call('tools/call', { name: 'browser_tabs', arguments: { action: 'new' } });
171
+ await sendCommand('tabs', { op: 'new' });
111
172
  }
112
173
 
113
174
  async selectTab(index: number): Promise<void> {
114
- await this.call('tools/call', { name: 'browser_tabs', arguments: { action: 'select', index } });
175
+ await sendCommand('tabs', { op: 'select', index });
115
176
  }
116
177
 
117
178
  async networkRequests(includeStatic: boolean = false): Promise<any> {
118
- return this.call('tools/call', { name: 'browser_network_requests', arguments: { includeStatic } });
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
- async consoleMessages(level: string = 'info'): Promise<any> {
122
- return this.call('tools/call', { name: 'browser_console_messages', arguments: { level } });
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
- async scroll(direction: string = 'down', _amount: number = 500): Promise<void> {
126
- await this.call('tools/call', { name: 'browser_press_key', arguments: { key: direction === 'down' ? 'PageDown' : 'PageUp' } });
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 js = `
133
- async () => {
134
- const maxTimes = ${times};
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); // Small debounce for rendering
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.evaluate(js);
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
+ }
@@ -1,24 +1,7 @@
1
1
  import { afterEach, describe, it, expect, vi } from 'vitest';
2
- import * as os from 'node:os';
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('PlaywrightMCP state', () => {
48
+ describe('BrowserBridge state', () => {
277
49
  it('transitions to closed after close()', async () => {
278
- const mcp = new PlaywrightMCP();
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 PlaywrightMCP();
60
+ const mcp = new BrowserBridge();
289
61
  await mcp.close();
290
62
 
291
- await expect(mcp.connect()).rejects.toThrow('Playwright MCP session is closed');
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 PlaywrightMCP();
67
+ const mcp = new BrowserBridge();
296
68
  (mcp as any)._state = 'connecting';
297
69
 
298
- await expect(mcp.connect()).rejects.toThrow('Playwright MCP is already connecting');
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 PlaywrightMCP();
74
+ const mcp = new BrowserBridge();
303
75
  (mcp as any)._state = 'closing';
304
76
 
305
- await expect(mcp.connect()).rejects.toThrow('Playwright MCP is closing');
77
+ await expect(mcp.connect()).rejects.toThrow('Session is closing');
306
78
  });
307
-
308
-
309
79
  });