@acertijosapps/electron-viewer 0.0.0-stage → 1.1.0
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/LICENSE +20 -0
- package/README.md +247 -2
- package/bin/electron-viewer.js +112 -0
- package/lib/cdp.js +112 -0
- package/lib/electron.js +920 -0
- package/mcp/server.js +418 -0
- package/media/viewer.jpg +0 -0
- package/package.json +59 -4
- package/public/index.html +63 -0
- package/public/style.css +246 -0
- package/public/viewer.js +507 -0
- package/server.js +428 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 AcertijosApps
|
|
4
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
in the Software without restriction, including without limitation the rights
|
|
7
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
furnished to do so, subject to the following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
copies or substantial portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
16
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
17
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
18
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
19
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,248 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @acertijosapps/electron-viewer
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Live viewer for Electron apps in the browser, plus an MCP server so an AI agent can drive them.
|
|
4
|
+
Built for the browser pane of AI coding tools (such as Claude Code): you and the agent watch and
|
|
5
|
+
control the same app window, in real time.
|
|
6
|
+
|
|
7
|
+
<img src="https://unpkg.com/@acertijosapps/electron-viewer/media/viewer.jpg" width="560" alt="Electron Viewer showing the example app: window selector and launch button on top, the live window in the middle, and the reload, DevTools, window size, touch and screenshot controls at the bottom" />
|
|
8
|
+
|
|
9
|
+
- **Live video**: `Page.startScreencast` from the Chrome DevTools Protocol (CDP) over WebSocket. It keeps
|
|
10
|
+
streaming while the app window is covered or minimized.
|
|
11
|
+
- **Real input**: mouse move and hover, click, double click, right click, drag, wheel and full keyboard
|
|
12
|
+
passthrough (including ⌘C/⌘V/⌘A on macOS, IME and dictation).
|
|
13
|
+
- **Touch**: a touch mode in the viewer turns the pointer into a finger, and the agent can tap, swipe,
|
|
14
|
+
long press and pinch, for touch-first and kiosk apps.
|
|
15
|
+
- **Every app and window**: launch your project with `electron .` from the viewer, or attach to any app
|
|
16
|
+
started with `--remote-debugging-port`. Apps on ports 9222–9231 are found automatically.
|
|
17
|
+
- **Main process too**: launched apps also expose their main process (Node inspector), so the agent can
|
|
18
|
+
run code there, resize the real window and open DevTools.
|
|
19
|
+
- **MCP server**: the same actions as tools, plus JavaScript in the renderer and main process, the
|
|
20
|
+
accessibility tree with click-ready coordinates, and console logs.
|
|
21
|
+
- **Nothing to add to your app**: no preload, no dependency, no code changes.
|
|
22
|
+
|
|
23
|
+
## Requirements
|
|
24
|
+
|
|
25
|
+
- Node.js 18 or later.
|
|
26
|
+
- An Electron app. To launch it from the viewer, the project must have `electron` in its
|
|
27
|
+
`node_modules` (`npm install --save-dev electron`); if its binary hasn't been downloaded yet, the
|
|
28
|
+
viewer downloads it on the first launch.
|
|
29
|
+
- Works on macOS, Linux and Windows.
|
|
30
|
+
|
|
31
|
+
## Quick start
|
|
32
|
+
|
|
33
|
+
From your Electron project folder:
|
|
34
|
+
|
|
35
|
+
```sh
|
|
36
|
+
npx @acertijosapps/electron-viewer@1.1.0
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Open <http://localhost:8094> and click **Launch**. The viewer runs `electron .` on free debugging
|
|
40
|
+
ports (CDP from 9222, Node inspector from 9229). Deep link to a window: `?window=<target id>`.
|
|
41
|
+
|
|
42
|
+
If your app is started by another tool (electron-vite, Electron Forge, a custom script), give the viewer
|
|
43
|
+
your own start command. `{cdpPort}` and `{inspectPort}` are replaced with free debugging ports, and the
|
|
44
|
+
Launch button (and `launch_app`) runs it in the project folder:
|
|
45
|
+
|
|
46
|
+
```sh
|
|
47
|
+
npx @acertijosapps/electron-viewer@1.1.0 --launch-cmd "yarn dev --remoteDebuggingPort {cdpPort} --inspect {inspectPort}"
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
That line is for electron-vite; for an npm script that ends in `electron .`, pass the flags after `--`:
|
|
51
|
+
`--launch-cmd "npm start -- --remote-debugging-port={cdpPort} --inspect={inspectPort}"`. The command is
|
|
52
|
+
only read from the command line or `ELECTRON_VIEWER_LAUNCH_CMD`, never from the HTTP API or the MCP.
|
|
53
|
+
|
|
54
|
+
Or start the app yourself with the flags and the viewer finds it:
|
|
55
|
+
|
|
56
|
+
```sh
|
|
57
|
+
electron --remote-debugging-port=9222 --inspect=9229 .
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Apps on CDP ports 9222–9231 are found automatically, and so is their main process when its inspector is
|
|
61
|
+
on 9229–9238. `--inspect` is optional; without it you get everything except the main-process features
|
|
62
|
+
(`evaluate_main`, real window resizing and in-app DevTools). To attach on other ports, use the form in
|
|
63
|
+
the viewer or `--attach` and `--inspect`.
|
|
64
|
+
|
|
65
|
+
```text
|
|
66
|
+
electron-viewer [options] Start the viewer
|
|
67
|
+
electron-viewer mcp [options] Start the MCP server on stdio
|
|
68
|
+
|
|
69
|
+
--project <dir> Project to launch with "electron ." (default: current folder)
|
|
70
|
+
--launch-cmd <cmd> Launch with this shell command instead; {cdpPort} and {inspectPort}
|
|
71
|
+
are replaced with the debugging ports
|
|
72
|
+
-p, --port <port> Viewer port (default 8094, env PORT)
|
|
73
|
+
--host <host> Interface to bind (default 127.0.0.1, env HOST)
|
|
74
|
+
--attach <port> Attach at startup to an app on this CDP port
|
|
75
|
+
--inspect <port> With --attach: the app's main process inspector port
|
|
76
|
+
--viewer-url <url> Viewer the MCP talks to (default http://localhost:8094)
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Other environment variables: `MAX_DIM` (longest side of the streamed frames, default 1920), `QUALITY`
|
|
80
|
+
(JPEG quality, default 80), `SCREENSHOT_MAX` (longest side of MCP screenshots, default 1024),
|
|
81
|
+
`CDP_PORT` / `INSPECT_PORT` (first ports to scan and launch on, default 9222 / 9229) and
|
|
82
|
+
`ELECTRON_VIEWER_STATE_DIR` (where launched and attached apps are remembered, default
|
|
83
|
+
`~/.cache/electron-viewer`).
|
|
84
|
+
|
|
85
|
+
## Use it with an AI agent (MCP)
|
|
86
|
+
|
|
87
|
+
Claude Code:
|
|
88
|
+
|
|
89
|
+
```sh
|
|
90
|
+
claude mcp add electron-viewer -- npx -y @acertijosapps/electron-viewer@1.1.0 mcp
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Any other MCP client:
|
|
94
|
+
|
|
95
|
+
```json
|
|
96
|
+
{
|
|
97
|
+
"mcpServers": {
|
|
98
|
+
"electron-viewer": {
|
|
99
|
+
"command": "npx",
|
|
100
|
+
"args": ["-y", "@acertijosapps/electron-viewer@1.1.0", "mcp"]
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Also listed in the [official MCP Registry](https://registry.modelcontextprotocol.io) as
|
|
107
|
+
`io.github.acertijosapps/electron-viewer`.
|
|
108
|
+
|
|
109
|
+
The examples pin an exact version. The viewer and the MCP can run code in your app, so pin the version
|
|
110
|
+
you reviewed instead of letting `npx` fetch whatever was published last, and update it on purpose.
|
|
111
|
+
|
|
112
|
+
Keep the viewer running (`npx @acertijosapps/electron-viewer@1.1.0`) to watch what the agent does. Without
|
|
113
|
+
it, the MCP drives the app over CDP directly. Apps launched by either one are visible to the other.
|
|
114
|
+
|
|
115
|
+
| Tool | What it does |
|
|
116
|
+
| --- | --- |
|
|
117
|
+
| `list_windows` | Running apps (with `main` when the main process is reachable) and their windows |
|
|
118
|
+
| `launch_app` | Run `electron .` in the project on free debugging ports and wait for the first window |
|
|
119
|
+
| `attach` | Attach to an app on a CDP port, optionally with its inspector port |
|
|
120
|
+
| `screenshot` | PNG of the window content, longest side ≤ 1024 px |
|
|
121
|
+
| `click` | Left, right or middle click; `count: 2` for a double click; optional modifiers |
|
|
122
|
+
| `drag` | Press, move in steps and release: a real drag |
|
|
123
|
+
| `hover` | Move the mouse without clicking |
|
|
124
|
+
| `tap` | One-finger tap (touch events, `pointerType: "touch"`) |
|
|
125
|
+
| `swipe` | One-finger swipe: scrolls touch lists and drives swipe gestures |
|
|
126
|
+
| `long_press` | Hold one finger down for a while, 800 ms by default |
|
|
127
|
+
| `pinch` | Two-finger pinch around a point; `scale` > 1 zooms in, < 1 zooms out |
|
|
128
|
+
| `scroll` | Mouse wheel at a point, deltas in CSS px |
|
|
129
|
+
| `type_text` | Insert text into the focused element (any Unicode) |
|
|
130
|
+
| `press_key` | Enter, Tab, Escape, arrows, F1–F12… or any character, with modifiers |
|
|
131
|
+
| `resize_window` | Resize the content area: the real window with the main process, an emulated viewport when the window can't reach the size (or with `emulate: true`) |
|
|
132
|
+
| `reload` | Reload the window's page |
|
|
133
|
+
| `evaluate` | Run JavaScript in the window's page and return the value |
|
|
134
|
+
| `evaluate_main` | Run JavaScript in the main process, with `require('electron')` available |
|
|
135
|
+
| `get_accessibility_tree` | Roles, names, values and states; interactive elements carry their normalized center |
|
|
136
|
+
| `get_console_logs` | Console messages and exceptions from renderer windows and the main process, or the raw stdout |
|
|
137
|
+
|
|
138
|
+
Coordinates are normalized to `0–1` over the content screenshot (`x = pixel_x / image_width`), so they
|
|
139
|
+
hold at any window size. `window` is optional when only one window is open; it takes the target id
|
|
140
|
+
from `list_windows` or part of the window title.
|
|
141
|
+
|
|
142
|
+
### In the Claude Code browser pane
|
|
143
|
+
|
|
144
|
+
Add the viewer to `.claude/launch.json` and open it with `preview_start electron-viewer`:
|
|
145
|
+
|
|
146
|
+
```json
|
|
147
|
+
{
|
|
148
|
+
"version": "0.0.1",
|
|
149
|
+
"configurations": [
|
|
150
|
+
{
|
|
151
|
+
"name": "electron-viewer",
|
|
152
|
+
"runtimeExecutable": "npx",
|
|
153
|
+
"runtimeArgs": ["-y", "@acertijosapps/electron-viewer@1.1.0"],
|
|
154
|
+
"port": 8094,
|
|
155
|
+
"autoPort": false
|
|
156
|
+
}
|
|
157
|
+
]
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## HTTP API
|
|
162
|
+
|
|
163
|
+
The MCP uses the viewer's API; you can call it too. `window` (target id or part of the title) goes in
|
|
164
|
+
the query string or the body and is optional with a single window. The server only listens on
|
|
165
|
+
127.0.0.1, only accepts a local `Host` and origin, and `POST` requests require
|
|
166
|
+
`content-type: application/json`, so other websites can't drive your apps.
|
|
167
|
+
|
|
168
|
+
| Endpoint | |
|
|
169
|
+
| --- | --- |
|
|
170
|
+
| `GET /api/windows` | `[{ id, name, cdpPort, inspectPort, main, windows: [{ id, title, url }] }]` |
|
|
171
|
+
| `GET /api/project` | The project the viewer launches and whether it has Electron installed |
|
|
172
|
+
| `GET /api/screenshot?max=<px>` | PNG; viewport size in `X-Viewport-Width` / `X-Viewport-Height` |
|
|
173
|
+
| `GET /api/ax-tree?interactiveOnly=true` | `{ tree }` |
|
|
174
|
+
| `GET /api/logs?level=&source=&limit=` | `{ logs }` or `{ stdout }` |
|
|
175
|
+
| `POST /api/launch` | `{ project? }` |
|
|
176
|
+
| `POST /api/attach` | `{ port, inspectPort? }` |
|
|
177
|
+
| `POST /api/click` | `{ x, y, button?, count?, modifiers? }` |
|
|
178
|
+
| `POST /api/drag` | `{ x1, y1, x2, y2, ms? }` |
|
|
179
|
+
| `POST /api/hover` | `{ x, y }` |
|
|
180
|
+
| `POST /api/tap` | `{ x, y }` |
|
|
181
|
+
| `POST /api/swipe` | `{ x1, y1, x2, y2, ms? }` |
|
|
182
|
+
| `POST /api/long-press` | `{ x, y, ms? }` |
|
|
183
|
+
| `POST /api/pinch` | `{ x?, y?, scale, ms? }` |
|
|
184
|
+
| `POST /api/scroll` | `{ x, y, dx, dy }` |
|
|
185
|
+
| `POST /api/text` | `{ text }` |
|
|
186
|
+
| `POST /api/key` | `{ key, modifiers? }` |
|
|
187
|
+
| `POST /api/resize` | `{ width, height, emulate? }` (0 × 0 restores the window size) |
|
|
188
|
+
| `POST /api/reload` | `{ ignoreCache? }` |
|
|
189
|
+
| `POST /api/evaluate` | `{ expression }` |
|
|
190
|
+
| `POST /api/evaluate-main` | `{ expression, app? }` |
|
|
191
|
+
| `POST /api/devtools` | Toggles DevTools; without the main process returns the DevTools `url` |
|
|
192
|
+
|
|
193
|
+
## How it works
|
|
194
|
+
|
|
195
|
+
- Everything goes through CDP with `ws`: no Playwright, no Puppeteer, nothing injected into the app.
|
|
196
|
+
The renderer is reached through `--remote-debugging-port` (one `page` target per window) and the
|
|
197
|
+
main process through the Node inspector (`--inspect`), where the console API provides `require`.
|
|
198
|
+
- One screencast session per window, shared by every viewer tab and stopped when the last one closes.
|
|
199
|
+
The last frame is kept for late joiners. Focus and page lifecycle are emulated while someone is
|
|
200
|
+
watching, so a covered or minimized window keeps painting.
|
|
201
|
+
- Viewer input is queued in order and mouse moves are coalesced to one per animation frame. A hidden
|
|
202
|
+
textarea holds the focus: keys are sent with `Input.dispatchKeyEvent`, and text that arrives without
|
|
203
|
+
key events (IME, dictation) with `Input.insertText`. On macOS, ⌘A, ⌘C, ⌘V, ⌘X and ⌘Z are sent as
|
|
204
|
+
editing commands, because the native menu that normally handles them never sees CDP events.
|
|
205
|
+
- Touch goes through `Input.dispatchTouchEvent`. The first touch action on a window also turns on touch
|
|
206
|
+
emulation (`navigator.maxTouchPoints` 5, `pointer: coarse`) until the viewer or MCP that sent it exits.
|
|
207
|
+
- Each process keeps one connection per window and per main process, which also collects console
|
|
208
|
+
messages and exceptions (the last 1000 per app).
|
|
209
|
+
- For an app with no known inspector, each Node inspector on ports 9229–9238 is asked once, read only,
|
|
210
|
+
whether it is Electron and which CDP port its app listens on. Any other Node process started with
|
|
211
|
+
`--inspect` in that range gets one short connection (it logs `Debugger attached.`) and is left alone.
|
|
212
|
+
- Launched and attached apps are remembered in `~/.cache/electron-viewer`, so the viewer and the MCP see
|
|
213
|
+
the same apps. Launched apps write their output to a log file there and keep running if the viewer
|
|
214
|
+
or MCP exits.
|
|
215
|
+
|
|
216
|
+
## Limitations
|
|
217
|
+
|
|
218
|
+
- CDP only sees web content. Native UI (title bar, menus, dialogs, tray, notifications) isn't shown or
|
|
219
|
+
clickable; use `evaluate_main` to drive it from the main process. Capturing it would mean capturing the
|
|
220
|
+
screen, and with it any other window on top of the app, so the viewer doesn't.
|
|
221
|
+
- Synchronous dialogs (`dialog.showMessageBoxSync`) block the main process: `evaluate_main` waits until
|
|
222
|
+
the dialog is closed.
|
|
223
|
+
- Each `WebContentsView` is a separate CDP target, so it is listed as its own window. `<webview>` tags are
|
|
224
|
+
not listed.
|
|
225
|
+
- A long press reaches the app as a held touch, so apps that time `touchstart` themselves see it, but
|
|
226
|
+
Chromium on desktop doesn't turn it into a context menu. The viewer's touch mode is one finger; use
|
|
227
|
+
`pinch` for two.
|
|
228
|
+
- No audio.
|
|
229
|
+
- A `--launch-cmd` must pass the ports on to Electron; how depends on the tool. Launched apps keep running
|
|
230
|
+
when the viewer exits; close them from the app (or its terminal).
|
|
231
|
+
|
|
232
|
+
## Contributing
|
|
233
|
+
|
|
234
|
+
Branching model (`main` · `beta`), Conventional Commits and releases are described in
|
|
235
|
+
[CONTRIBUTING.md](./CONTRIBUTING.md); changes are listed in [CHANGELOG.md](./CHANGELOG.md). The
|
|
236
|
+
example app in [`example/`](./example) is there to try changes.
|
|
237
|
+
|
|
238
|
+
## Author
|
|
239
|
+
|
|
240
|
+
Made by [AcertijosApps](https://acertijosapps.com/librerias). See the rest of our libraries at
|
|
241
|
+
[acertijosapps.com/librerias](https://acertijosapps.com/librerias).
|
|
242
|
+
|
|
243
|
+
Questions or proposals: [acertijos.contacto@gmail.com](mailto:acertijos.contacto@gmail.com) or open an
|
|
244
|
+
[issue](https://github.com/acertijosapps/electron-viewer/issues).
|
|
245
|
+
|
|
246
|
+
## License
|
|
247
|
+
|
|
248
|
+
MIT
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// CLI del paquete: `electron-viewer` arranca el visor; `electron-viewer mcp`, el MCP por stdio.
|
|
3
|
+
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { readFileSync } from 'node:fs';
|
|
6
|
+
|
|
7
|
+
const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
8
|
+
|
|
9
|
+
const HELP = `electron-viewer ${version}
|
|
10
|
+
|
|
11
|
+
Live viewer for Electron apps in the browser, plus an MCP server to drive them.
|
|
12
|
+
|
|
13
|
+
Usage:
|
|
14
|
+
electron-viewer [options] Start the viewer (http://localhost:8094)
|
|
15
|
+
electron-viewer mcp [options] Start the MCP server on stdio
|
|
16
|
+
|
|
17
|
+
Common options:
|
|
18
|
+
--project <dir> Electron project to launch with "electron ." (default:
|
|
19
|
+
current folder, env ELECTRON_VIEWER_PROJECT)
|
|
20
|
+
--launch-cmd <cmd> Launch with this shell command instead (env
|
|
21
|
+
ELECTRON_VIEWER_LAUNCH_CMD); {cdpPort} and {inspectPort}
|
|
22
|
+
are replaced with the debugging ports, e.g.
|
|
23
|
+
"yarn dev --remoteDebuggingPort {cdpPort} --inspect {inspectPort}"
|
|
24
|
+
|
|
25
|
+
Viewer options:
|
|
26
|
+
-p, --port <port> Port to listen on (default: 8094, env PORT)
|
|
27
|
+
--host <host> Interface to bind (default: 127.0.0.1, env HOST)
|
|
28
|
+
--attach <port> Attach at startup to an app already running with
|
|
29
|
+
--remote-debugging-port=<port>
|
|
30
|
+
--inspect <port> With --attach: the app's main process inspector
|
|
31
|
+
(--inspect=<port>), for evaluate_main, DevTools and
|
|
32
|
+
real window resizing
|
|
33
|
+
|
|
34
|
+
MCP options:
|
|
35
|
+
--viewer-url <url> Viewer to talk to (default: http://localhost:8094,
|
|
36
|
+
env ELECTRON_VIEWER_URL). Without a running viewer the
|
|
37
|
+
MCP drives the app over CDP directly.
|
|
38
|
+
|
|
39
|
+
-h, --help Show this help
|
|
40
|
+
-v, --version Show the version
|
|
41
|
+
|
|
42
|
+
Apps are found on CDP ports 9222-9231. Launched apps get the first free CDP port
|
|
43
|
+
from 9222 and inspector port from 9229.
|
|
44
|
+
`;
|
|
45
|
+
|
|
46
|
+
function fail(message) {
|
|
47
|
+
console.error(`electron-viewer: ${message}\nRun "electron-viewer --help" for usage.`);
|
|
48
|
+
process.exit(2);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const args = process.argv.slice(2);
|
|
52
|
+
const command = args[0] && !args[0].startsWith('-') ? args.shift() : 'viewer';
|
|
53
|
+
if (!['viewer', 'mcp'].includes(command)) fail(`unknown command "${command}"`);
|
|
54
|
+
|
|
55
|
+
const portValue = (flag, v) => {
|
|
56
|
+
if (!/^\d+$/.test(v) || Number(v) < 1 || Number(v) > 65535) fail(`invalid port "${v}" for ${flag}`);
|
|
57
|
+
return v;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
for (let i = 0; i < args.length; i++) {
|
|
61
|
+
const arg = args[i];
|
|
62
|
+
const [flag, inline] = arg.includes('=') ? arg.split(/=(.*)/s) : [arg];
|
|
63
|
+
const value = () => {
|
|
64
|
+
const v = inline ?? args[++i];
|
|
65
|
+
if (v === undefined || v.startsWith('-')) fail(`${flag} needs a value`);
|
|
66
|
+
return v;
|
|
67
|
+
};
|
|
68
|
+
switch (flag) {
|
|
69
|
+
case '-h':
|
|
70
|
+
case '--help':
|
|
71
|
+
process.stdout.write(HELP);
|
|
72
|
+
process.exit(0);
|
|
73
|
+
break;
|
|
74
|
+
case '-v':
|
|
75
|
+
case '--version':
|
|
76
|
+
console.log(version);
|
|
77
|
+
process.exit(0);
|
|
78
|
+
break;
|
|
79
|
+
case '-p':
|
|
80
|
+
case '--port':
|
|
81
|
+
process.env.PORT = portValue(flag, value());
|
|
82
|
+
break;
|
|
83
|
+
case '--host':
|
|
84
|
+
process.env.HOST = value();
|
|
85
|
+
break;
|
|
86
|
+
case '--project':
|
|
87
|
+
process.env.ELECTRON_VIEWER_PROJECT = path.resolve(value());
|
|
88
|
+
break;
|
|
89
|
+
case '--launch-cmd': {
|
|
90
|
+
const cmd = value();
|
|
91
|
+
if (!cmd.includes('{cdpPort}')) fail('--launch-cmd must include {cdpPort}');
|
|
92
|
+
process.env.ELECTRON_VIEWER_LAUNCH_CMD = cmd;
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
case '--attach':
|
|
96
|
+
process.env.ELECTRON_VIEWER_ATTACH = portValue(flag, value());
|
|
97
|
+
break;
|
|
98
|
+
case '--inspect':
|
|
99
|
+
process.env.ELECTRON_VIEWER_INSPECT = portValue(flag, value());
|
|
100
|
+
break;
|
|
101
|
+
case '--viewer-url':
|
|
102
|
+
process.env.ELECTRON_VIEWER_URL = value();
|
|
103
|
+
break;
|
|
104
|
+
default:
|
|
105
|
+
fail(`unknown option "${arg}"`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (process.env.ELECTRON_VIEWER_INSPECT && !process.env.ELECTRON_VIEWER_ATTACH) fail('--inspect needs --attach');
|
|
110
|
+
|
|
111
|
+
// Los módulos arrancan al importarse; las opciones ya quedaron en process.env.
|
|
112
|
+
await import(command === 'mcp' ? '../mcp/server.js' : '../server.js');
|
package/lib/cdp.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Cliente mínimo de Chrome DevTools Protocol sobre WebSocket. Sirve igual para un target del
|
|
2
|
+
// renderer (`--remote-debugging-port`) que para el inspector de Node del proceso main (`--inspect`).
|
|
3
|
+
|
|
4
|
+
import { EventEmitter } from 'node:events';
|
|
5
|
+
import WebSocket from 'ws';
|
|
6
|
+
|
|
7
|
+
const CONNECT_TIMEOUT_MS = 5000;
|
|
8
|
+
const COMMAND_TIMEOUT_MS = 30000;
|
|
9
|
+
|
|
10
|
+
export class CdpError extends Error {}
|
|
11
|
+
|
|
12
|
+
export class CdpClient extends EventEmitter {
|
|
13
|
+
static connect(wsUrl, { timeout = CONNECT_TIMEOUT_MS } = {}) {
|
|
14
|
+
return new Promise((resolve, reject) => {
|
|
15
|
+
// Sin Origin: Chromium rechaza orígenes que no estén en --remote-allow-origins.
|
|
16
|
+
const ws = new WebSocket(wsUrl, { perMessageDeflate: false, maxPayload: 256 * 1024 * 1024 });
|
|
17
|
+
const timer = setTimeout(() => {
|
|
18
|
+
ws.terminate();
|
|
19
|
+
reject(new CdpError(`Timed out connecting to ${wsUrl}`));
|
|
20
|
+
}, timeout);
|
|
21
|
+
ws.once('open', () => {
|
|
22
|
+
clearTimeout(timer);
|
|
23
|
+
resolve(new CdpClient(ws));
|
|
24
|
+
});
|
|
25
|
+
ws.once('error', (err) => {
|
|
26
|
+
clearTimeout(timer);
|
|
27
|
+
reject(new CdpError(`Could not connect to ${wsUrl}: ${err.message}`));
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
constructor(ws) {
|
|
33
|
+
super();
|
|
34
|
+
this.ws = ws;
|
|
35
|
+
this.nextId = 1;
|
|
36
|
+
this.pending = new Map();
|
|
37
|
+
this.closed = false;
|
|
38
|
+
ws.on('message', (data) => this.onMessage(data));
|
|
39
|
+
ws.on('close', () => this.onClose());
|
|
40
|
+
ws.on('error', () => {}); // el cierre llega después por 'close'
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
onMessage(data) {
|
|
44
|
+
let msg;
|
|
45
|
+
try {
|
|
46
|
+
msg = JSON.parse(data.toString());
|
|
47
|
+
} catch {
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (msg.id) {
|
|
51
|
+
const p = this.pending.get(msg.id);
|
|
52
|
+
if (!p) return;
|
|
53
|
+
this.pending.delete(msg.id);
|
|
54
|
+
clearTimeout(p.timer);
|
|
55
|
+
if (msg.error) p.reject(new CdpError(`${p.method}: ${msg.error.message}`));
|
|
56
|
+
else p.resolve(msg.result);
|
|
57
|
+
} else if (msg.method) {
|
|
58
|
+
this.emit(msg.method, msg.params);
|
|
59
|
+
this.emit('event', msg.method, msg.params);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
onClose() {
|
|
64
|
+
this.closed = true;
|
|
65
|
+
for (const p of this.pending.values()) {
|
|
66
|
+
clearTimeout(p.timer);
|
|
67
|
+
p.reject(new CdpError(`${p.method}: connection closed`));
|
|
68
|
+
}
|
|
69
|
+
this.pending.clear();
|
|
70
|
+
this.emit('close');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
send(method, params = {}, { timeout = COMMAND_TIMEOUT_MS } = {}) {
|
|
74
|
+
if (this.closed) return Promise.reject(new CdpError(`${method}: connection closed`));
|
|
75
|
+
const id = this.nextId++;
|
|
76
|
+
return new Promise((resolve, reject) => {
|
|
77
|
+
const timer = setTimeout(() => {
|
|
78
|
+
this.pending.delete(id);
|
|
79
|
+
reject(new CdpError(`${method}: no answer within ${timeout / 1000} s`));
|
|
80
|
+
}, timeout);
|
|
81
|
+
this.pending.set(id, { resolve, reject, timer, method });
|
|
82
|
+
this.ws.send(JSON.stringify({ id, method, params }));
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
close() {
|
|
87
|
+
if (!this.closed) this.ws.close();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// GET a un endpoint HTTP del depurador (/json/list, /json/version).
|
|
92
|
+
export async function fetchJson(port, route, { timeout = 1500 } = {}) {
|
|
93
|
+
const res = await fetch(`http://127.0.0.1:${port}${route}`, { signal: AbortSignal.timeout(timeout) });
|
|
94
|
+
if (!res.ok) throw new CdpError(`HTTP ${res.status} from port ${port}${route}`);
|
|
95
|
+
return res.json();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Evalúa una expresión y devuelve su valor, o lanza con el mensaje de la excepción.
|
|
99
|
+
export async function evaluate(client, expression, { awaitPromise = true, commandLineAPI = false, timeout } = {}) {
|
|
100
|
+
const { result, exceptionDetails } = await client.send(
|
|
101
|
+
'Runtime.evaluate',
|
|
102
|
+
{ expression, awaitPromise, returnByValue: true, includeCommandLineAPI: commandLineAPI, userGesture: true },
|
|
103
|
+
{ timeout },
|
|
104
|
+
);
|
|
105
|
+
if (exceptionDetails) {
|
|
106
|
+
const ex = exceptionDetails.exception;
|
|
107
|
+
// Un `throw 'texto'` o un rechazo con string no trae description, solo value.
|
|
108
|
+
const message = ex?.description || (ex && 'value' in ex ? String(ex.value) : exceptionDetails.text) || 'Evaluation failed';
|
|
109
|
+
throw Object.assign(new CdpError(message.split('\n')[0].replace(/^Error: /, '')), { status: 400, stack: message });
|
|
110
|
+
}
|
|
111
|
+
return result.type === 'undefined' ? undefined : result.value ?? result.description ?? null;
|
|
112
|
+
}
|