@web-auto/camo 0.1.26 → 0.2.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 (117) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +586 -586
  3. package/bin/browser-service.mjs +11 -11
  4. package/bin/camo.mjs +22 -22
  5. package/package.json +48 -48
  6. package/scripts/build.mjs +19 -19
  7. package/scripts/bump-version.mjs +34 -34
  8. package/scripts/check-file-size.mjs +80 -80
  9. package/scripts/file-size-policy.json +12 -2
  10. package/scripts/install.mjs +76 -76
  11. package/scripts/release.sh +54 -54
  12. package/src/autoscript/action-providers/index.mjs +6 -6
  13. package/src/autoscript/impact-engine.mjs +78 -78
  14. package/src/autoscript/runtime.mjs +1017 -1017
  15. package/src/autoscript/schema.mjs +376 -376
  16. package/src/cli.mjs +405 -405
  17. package/src/commands/attach.mjs +141 -141
  18. package/src/commands/autoscript.mjs +1011 -1011
  19. package/src/commands/browser.mjs +1255 -1257
  20. package/src/commands/container.mjs +401 -401
  21. package/src/commands/cookies.mjs +69 -69
  22. package/src/commands/create.mjs +98 -98
  23. package/src/commands/devtools.mjs +349 -349
  24. package/src/commands/events.mjs +152 -152
  25. package/src/commands/highlight-mode.mjs +24 -24
  26. package/src/commands/init.mjs +68 -68
  27. package/src/commands/lifecycle.mjs +275 -275
  28. package/src/commands/mouse.mjs +45 -45
  29. package/src/commands/profile.mjs +46 -46
  30. package/src/commands/record.mjs +115 -115
  31. package/src/commands/system.mjs +14 -14
  32. package/src/commands/window.mjs +123 -123
  33. package/src/container/change-notifier.mjs +362 -362
  34. package/src/container/element-filter.mjs +143 -143
  35. package/src/container/index.mjs +3 -3
  36. package/src/container/runtime-core/checkpoint.mjs +209 -209
  37. package/src/container/runtime-core/index.mjs +21 -21
  38. package/src/container/runtime-core/operations/index.mjs +774 -774
  39. package/src/container/runtime-core/operations/selector-scripts.mjs +277 -277
  40. package/src/container/runtime-core/operations/tab-pool.mjs +746 -746
  41. package/src/container/runtime-core/operations/viewport.mjs +189 -189
  42. package/src/container/runtime-core/search.mjs +190 -190
  43. package/src/container/runtime-core/subscription.mjs +224 -224
  44. package/src/container/runtime-core/utils.mjs +94 -94
  45. package/src/container/runtime-core/validation.mjs +127 -184
  46. package/src/container/runtime-core.mjs +1 -1
  47. package/src/container/subscription-registry.mjs +459 -459
  48. package/src/core/actions.mjs +561 -561
  49. package/src/core/browser.mjs +266 -266
  50. package/src/core/index.mjs +52 -52
  51. package/src/core/utils.mjs +91 -91
  52. package/src/events/daemon-entry.mjs +33 -33
  53. package/src/events/daemon.mjs +80 -80
  54. package/src/events/progress-log.mjs +109 -109
  55. package/src/events/ws-server.mjs +239 -239
  56. package/src/lib/client.mjs +200 -200
  57. package/src/lifecycle/cleanup.mjs +83 -83
  58. package/src/lifecycle/lock.mjs +126 -126
  59. package/src/lifecycle/session-registry.mjs +279 -279
  60. package/src/lifecycle/session-view.mjs +76 -76
  61. package/src/lifecycle/session-watchdog.mjs +281 -281
  62. package/src/services/browser-service/index.js +671 -674
  63. package/src/services/browser-service/internal/BrowserSession.input.test.js +389 -389
  64. package/src/services/browser-service/internal/BrowserSession.js +325 -336
  65. package/src/services/browser-service/internal/ElementRegistry.js +60 -60
  66. package/src/services/browser-service/internal/ProfileLock.js +84 -84
  67. package/src/services/browser-service/internal/SessionManager.js +184 -184
  68. package/src/services/browser-service/internal/SessionManager.test.js +39 -39
  69. package/src/services/browser-service/internal/browser-session/cookies.js +144 -144
  70. package/src/services/browser-service/internal/browser-session/input-ops.js +222 -219
  71. package/src/services/browser-service/internal/browser-session/input-pipeline.js +144 -144
  72. package/src/services/browser-service/internal/browser-session/logging.js +46 -46
  73. package/src/services/browser-service/internal/browser-session/navigation.js +38 -38
  74. package/src/services/browser-service/internal/browser-session/page-hooks.js +442 -442
  75. package/src/services/browser-service/internal/browser-session/page-management.js +302 -336
  76. package/src/services/browser-service/internal/browser-session/page-management.test.js +148 -148
  77. package/src/services/browser-service/internal/browser-session/recording.js +198 -198
  78. package/src/services/browser-service/internal/browser-session/runtime-events.js +61 -61
  79. package/src/services/browser-service/internal/browser-session/session-core.js +84 -84
  80. package/src/services/browser-service/internal/browser-session/session-state.js +38 -38
  81. package/src/services/browser-service/internal/browser-session/types.js +14 -14
  82. package/src/services/browser-service/internal/browser-session/utils.js +95 -95
  83. package/src/services/browser-service/internal/browser-session/viewport-manager.js +46 -46
  84. package/src/services/browser-service/internal/browser-session/viewport.js +215 -215
  85. package/src/services/browser-service/internal/container-matcher.js +851 -851
  86. package/src/services/browser-service/internal/container-registry.js +182 -182
  87. package/src/services/browser-service/internal/engine-manager.js +259 -259
  88. package/src/services/browser-service/internal/fingerprint.js +203 -203
  89. package/src/services/browser-service/internal/heartbeat.js +137 -137
  90. package/src/services/browser-service/internal/logging.js +46 -46
  91. package/src/services/browser-service/internal/page-runtime/runtime.js +1317 -1317
  92. package/src/services/browser-service/internal/pageRuntime.js +28 -28
  93. package/src/services/browser-service/internal/runtimeInjector.js +31 -31
  94. package/src/services/browser-service/internal/service-process-logger.js +140 -140
  95. package/src/services/browser-service/internal/state-bus.js +45 -45
  96. package/src/services/browser-service/internal/storage-paths.js +42 -42
  97. package/src/services/browser-service/internal/ws-server.js +1194 -1194
  98. package/src/services/browser-service/internal/ws-server.test.js +58 -58
  99. package/src/services/browser-service/server.mjs +6 -6
  100. package/src/services/controller/cli-bridge.js +93 -93
  101. package/src/services/controller/container-index.js +50 -50
  102. package/src/services/controller/container-storage.js +36 -36
  103. package/src/services/controller/controller-actions.js +207 -207
  104. package/src/services/controller/controller.js +1138 -1138
  105. package/src/services/controller/selectors.js +54 -54
  106. package/src/services/controller/transport.js +125 -125
  107. package/src/utils/args.mjs +26 -26
  108. package/src/utils/browser-service.mjs +544 -544
  109. package/src/utils/command-log.mjs +64 -64
  110. package/src/utils/config.mjs +214 -214
  111. package/src/utils/fingerprint.mjs +181 -181
  112. package/src/utils/help.mjs +216 -216
  113. package/src/utils/js-policy.mjs +13 -13
  114. package/src/utils/ws-client.mjs +30 -30
  115. package/src/container/runtime-core/operations/tab-pool.mjs.bak +0 -762
  116. package/src/container/runtime-core/operations/tab-pool.mjs.syntax-error +0 -762
  117. package/src/services/browser-service/index.js.bak +0 -671
@@ -1,674 +1,671 @@
1
- import http from 'http';
2
- import { fileURLToPath } from 'node:url';
3
- import os from 'node:os';
4
- import { spawnSync } from 'node:child_process';
5
- import { SessionManager, SESSION_CLOSED_EVENT, } from './internal/SessionManager.js';
6
- import { BrowserWsServer } from './internal/ws-server.js';
7
- import { logDebug } from './internal/logging.js';
8
- import { installServiceProcessLogger } from './internal/service-process-logger.js';
9
- import { startHeartbeatWriter } from './internal/heartbeat.js';
10
- import { appendCommandLog } from '../../utils/command-log.mjs';
11
- const clients = new Set();
12
- const autoLoops = new Map();
13
- function readNumber(value) {
14
- if (!value)
15
- return null;
16
- const parsed = Number(value);
17
- if (!Number.isFinite(parsed) || parsed <= 0)
18
- return null;
19
- return parsed;
20
- }
21
- function readPositiveNumber(value) {
22
- const parsed = Number(value);
23
- if (!Number.isFinite(parsed) || parsed <= 0)
24
- return null;
25
- return parsed;
26
- }
27
- function getDisplayMetrics() {
28
- const envWidth = readNumber(process.env.CAMO_SCREEN_WIDTH || process.env.CAMO_SCREEN_WIDTH);
29
- const envHeight = readNumber(process.env.CAMO_SCREEN_HEIGHT || process.env.CAMO_SCREEN_HEIGHT);
30
- if (envWidth && envHeight) {
31
- return { width: envWidth, height: envHeight, source: 'env' };
32
- }
33
- if (os.platform() === 'darwin') {
34
- try {
35
- const sp = spawnSync('system_profiler', ['SPDisplaysDataType', '-json'], { encoding: 'utf8' });
36
- const spJson = sp.status === 0 && sp.stdout ? JSON.parse(sp.stdout) : null;
37
- let width = null;
38
- let height = null;
39
- const displays = spJson?.SPDisplaysDataType;
40
- if (Array.isArray(displays) && displays.length > 0) {
41
- const first = displays[0];
42
- const gpus = first?._items;
43
- const maybe = Array.isArray(gpus) && gpus.length > 0 ? gpus[0] : first;
44
- const resStr = maybe?.spdisplays_ndrvs?.[0]?._spdisplays_resolution || maybe?._spdisplays_resolution;
45
- if (typeof resStr === 'string') {
46
- const m = resStr.match(/(\d+)\s*x\s*(\d+)/i);
47
- if (m) {
48
- width = readNumber(m[1]);
49
- height = readNumber(m[2]);
50
- }
51
- }
52
- }
53
- const osascript = spawnSync('osascript', [
54
- '-l',
55
- 'JavaScript',
56
- '-e',
57
- `ObjC.import('AppKit');
58
- const s = $.NSScreen.mainScreen;
59
- const f = s.frame;
60
- const v = s.visibleFrame;
61
- JSON.stringify({
62
- width: Number(f.size.width),
63
- height: Number(f.size.height),
64
- workWidth: Number(v.size.width),
65
- workHeight: Number(v.size.height)
66
- });`,
67
- ], { encoding: 'utf8' });
68
- const vf = osascript.status === 0 && osascript.stdout ? JSON.parse(osascript.stdout.trim()) : null;
69
- const finalW = readNumber(vf?.width) || width;
70
- const finalH = readNumber(vf?.height) || height;
71
- const workWidth = readNumber(vf?.workWidth);
72
- const workHeight = readNumber(vf?.workHeight);
73
- if (!finalW || !finalH)
74
- return null;
75
- return {
76
- width: finalW,
77
- height: finalH,
78
- ...(workWidth ? { workWidth } : {}),
79
- ...(workHeight ? { workHeight } : {}),
80
- source: 'darwin',
81
- };
82
- }
83
- catch {
84
- return null;
85
- }
86
- }
87
- if (os.platform() !== 'win32')
88
- return null;
89
- try {
90
- const script = [
91
- 'Add-Type -AssemblyName System.Windows.Forms;',
92
- '$screen=[System.Windows.Forms.Screen]::PrimaryScreen;',
93
- '$b=$screen.Bounds;',
94
- '$w=$screen.WorkingArea;',
95
- '$video=Get-CimInstance Win32_VideoController | Select-Object -First 1;',
96
- '$nw=$null;$nh=$null;',
97
- 'if ($video) { $nw=$video.CurrentHorizontalResolution; $nh=$video.CurrentVerticalResolution }',
98
- '$o=[pscustomobject]@{width=$b.Width;height=$b.Height;workWidth=$w.Width;workHeight=$w.Height;nativeWidth=$nw;nativeHeight=$nh};',
99
- '$o | ConvertTo-Json -Compress',
100
- ].join(' ');
101
- const res = spawnSync('powershell', ['-NoProfile', '-Command', script], {
102
- encoding: 'utf8',
103
- windowsHide: true,
104
- });
105
- if (res.status !== 0 || !res.stdout)
106
- return null;
107
- const payload = JSON.parse(res.stdout.trim());
108
- const nativeWidth = readNumber(payload?.nativeWidth);
109
- const nativeHeight = readNumber(payload?.nativeHeight);
110
- const width = readNumber(payload?.width) || nativeWidth || null;
111
- const height = readNumber(payload?.height) || nativeHeight || null;
112
- const workWidth = readNumber(payload?.workWidth);
113
- const workHeight = readNumber(payload?.workHeight);
114
- if (!width || !height)
115
- return null;
116
- return {
117
- width,
118
- height,
119
- ...(workWidth ? { workWidth } : {}),
120
- ...(workHeight ? { workHeight } : {}),
121
- ...(nativeWidth ? { nativeWidth } : {}),
122
- ...(nativeHeight ? { nativeHeight } : {}),
123
- source: 'win32',
124
- };
125
- }
126
- catch {
127
- return null;
128
- }
129
- }
130
- function resolveStartViewport(args) {
131
- const explicitWidth = readPositiveNumber(args?.width ?? args?.viewportWidth ?? args?.viewport?.width);
132
- const explicitHeight = readPositiveNumber(args?.height ?? args?.viewportHeight ?? args?.viewport?.height);
133
- if (explicitWidth && explicitHeight) {
134
- return {
135
- width: Math.floor(explicitWidth),
136
- height: Math.floor(explicitHeight),
137
- };
138
- }
139
- if (Boolean(args?.headless))
140
- return null;
141
- const display = getDisplayMetrics();
142
- if (!display)
143
- return null;
144
- const reserveRaw = Number(process.env.CAMO_WINDOW_VERTICAL_RESERVE ?? process.env.CAMO_WINDOW_VERTICAL_RESERVE ?? 0);
145
- const reserve = Number.isFinite(reserveRaw) ? Math.max(0, Math.min(240, Math.floor(reserveRaw))) : 0;
146
- const baseWidth = readPositiveNumber(display.workWidth) || readPositiveNumber(display.width);
147
- const baseHeight = readPositiveNumber(display.workHeight) || readPositiveNumber(display.height);
148
- if (!baseWidth || !baseHeight)
149
- return null;
150
- return {
151
- width: Math.max(960, Math.floor(baseWidth)),
152
- height: Math.max(700, Math.floor(baseHeight - reserve)),
153
- };
154
- }
155
- export async function startBrowserService(opts = {}) {
156
- const { logEvent } = installServiceProcessLogger({ serviceName: 'browser-service' });
157
- const host = opts.host || process.env.CAMO_BROWSER_HTTP_HOST || '127.0.0.1';
158
- const port = Number(opts.port || process.env.CAMO_BROWSER_HTTP_PORT || 7704);
159
- const sessionManager = new SessionManager();
160
- const enableWs = opts.enableWs ?? process.env.CAMO_BROWSER_DISABLE_WS !== '1';
161
- const wsHost = opts.wsHost || process.env.CAMO_WS_HOST || '127.0.0.1';
162
- const wsPort = Number(opts.wsPort || process.env.CAMO_WS_PORT || 8765);
163
- const autoExit = process.env.CAMO_BROWSER_AUTO_EXIT === '1';
164
- const heartbeat = startHeartbeatWriter({ initialStatus: 'idle' });
165
- let heartbeatStatus = 'idle';
166
- let hasActiveSession = false;
167
- const setHeartbeatStatus = (next) => {
168
- if (heartbeatStatus === next)
169
- return;
170
- heartbeatStatus = next;
171
- heartbeat.setStatus(next);
172
- };
173
- const markSessionStarted = () => {
174
- hasActiveSession = true;
175
- setHeartbeatStatus('running');
176
- };
177
- const markAllSessionsClosed = () => {
178
- if (!hasActiveSession)
179
- return;
180
- setHeartbeatStatus('stopped');
181
- };
182
- logDebug('browser-service', 'start', { host, port, wsHost, wsPort, enableWs, autoExit });
183
- let wsServer = null;
184
- const server = http.createServer((req, res) => {
185
- void (async () => {
186
- const url = new URL(req.url || '/', `http://${req.headers.host}`);
187
- res.setHeader('Access-Control-Allow-Origin', '*');
188
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
189
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
190
- if (req.method === 'OPTIONS') {
191
- res.writeHead(200);
192
- res.end();
193
- return;
194
- }
195
- if (url.pathname === '/health') {
196
- res.writeHead(200, { 'Content-Type': 'application/json' });
197
- res.end(JSON.stringify({ ok: true }));
198
- return;
199
- }
200
- if (url.pathname === '/events') {
201
- res.writeHead(200, {
202
- 'Content-Type': 'text/event-stream',
203
- Connection: 'keep-alive',
204
- 'Cache-Control': 'no-cache',
205
- });
206
- clients.add(res);
207
- req.on('close', () => clients.delete(res));
208
- return;
209
- }
210
- if (url.pathname === '/command' && req.method === 'POST') {
211
- const chunks = [];
212
- req.on('data', (chunk) => chunks.push(chunk));
213
- req.on('end', async () => {
214
- try {
215
- const payload = JSON.parse(Buffer.concat(chunks).toString('utf-8'));
216
- const t0 = Date.now();
217
- const action = String(payload?.action || '');
218
- const profileId = String(payload?.args?.profileId || payload?.args?.profile || payload?.args?.sessionId || '');
219
- appendCommandLog({
220
- action,
221
- profileId,
222
- payload: payload?.args ?? {},
223
- meta: {
224
- source: 'browser-service',
225
- cwd: process.cwd(),
226
- pid: process.pid,
227
- ppid: process.ppid,
228
- sender: payload?.meta?.sender && typeof payload.meta.sender === 'object' ? payload.meta.sender : {},
229
- },
230
- });
231
- logEvent('browser.command.start', { action, profileId });
232
- const result = await handleCommand(payload, sessionManager, wsServer, { onSessionStart: markSessionStarted });
233
- logEvent('browser.command.done', { action, profileId, ok: result.ok, ms: Date.now() - t0 });
234
- res.writeHead(result.ok ? 200 : 500, { 'Content-Type': 'application/json' });
235
- res.end(JSON.stringify(result.body));
236
- }
237
- catch (err) {
238
- logEvent('browser.command.error', { error: err?.message || String(err) });
239
- res.writeHead(500, { 'Content-Type': 'application/json' });
240
- res.end(JSON.stringify({ error: err.message }));
241
- }
242
- });
243
- return;
244
- }
245
- res.writeHead(404);
246
- res.end();
247
- })().catch((err) => {
248
- logEvent('http.request.error', {
249
- method: req?.method,
250
- url: req?.url,
251
- error: { message: err?.message || String(err), stack: err?.stack },
252
- });
253
- try {
254
- if (!res.headersSent)
255
- res.writeHead(500, { 'Content-Type': 'application/json' });
256
- res.end(JSON.stringify({ ok: false, error: 'Internal Server Error' }));
257
- }
258
- catch {
259
- // ignore
260
- }
261
- });
262
- });
263
- server.listen(port, host, () => {
264
- console.log(`BrowserService listening on http://${host}:${port}`);
265
- });
266
- if (enableWs) {
267
- wsServer = new BrowserWsServer({ host: wsHost, port: wsPort, sessionManager });
268
- try {
269
- await wsServer.start();
270
- }
271
- catch (err) {
272
- console.warn('[browser-service] failed to start WebSocket server:', err.message);
273
- }
274
- }
275
- const stopWsServer = async () => {
276
- if (!wsServer)
277
- return;
278
- await wsServer.stop().catch(() => { });
279
- };
280
- const shutdown = async () => {
281
- heartbeat.stop();
282
- server.close();
283
- clients.forEach((client) => client.end());
284
- autoLoops.forEach((timer) => clearInterval(timer));
285
- await stopWsServer();
286
- await sessionManager.shutdown();
287
- };
288
- process.on('SIGINT', shutdown);
289
- process.on('SIGTERM', shutdown);
290
- process.on(SESSION_CLOSED_EVENT, () => {
291
- if (!managerIsIdle(sessionManager))
292
- return;
293
- markAllSessionsClosed();
294
- if (autoExit || hasActiveSession) {
295
- shutdown().finally(() => process.exit(0));
296
- }
297
- });
298
- }
299
- function managerIsIdle(manager) {
300
- return manager.listSessions().length === 0;
301
- }
302
- async function handleCommand(payload, manager, wsServer, options = {}) {
303
- const action = payload.action;
304
- const args = payload.args ?? payload;
305
- switch (action) {
306
- case 'start': {
307
- const startViewport = resolveStartViewport(args);
308
- const opts = {
309
- profileId: args.profileId || 'default',
310
- sessionName: args.profileId || 'default',
311
- headless: !!args.headless,
312
- initialUrl: args.url,
313
- engine: args.engine || 'camoufox',
314
- fingerprintPlatform: args.fingerprintPlatform || null,
315
- ...(startViewport ? { viewport: startViewport } : {}),
316
- ...(args.ownerPid ? { ownerPid: args.ownerPid } : {}),
317
- };
318
- if (Number.isFinite(args.maxTabs) && args.maxTabs >= 1) {
319
- opts.maxTabs = Math.floor(args.maxTabs);
320
- }
321
- const res = await manager.createSession(opts);
322
- const session = manager.getSession(opts.profileId);
323
- if (!session) {
324
- throw new Error(`session for profile ${opts.profileId} not started`);
325
- }
326
- let recording = null;
327
- if (args.record === true || args.recording === true) {
328
- recording = await session.startRecording({
329
- name: args.recordName || args.recordingName,
330
- outputPath: args.recordOutput || args.recordingOutput || args.recordOutputPath,
331
- overlay: typeof args.recordOverlay === 'boolean' ? args.recordOverlay : undefined,
332
- });
333
- }
334
- options.onSessionStart?.();
335
- broadcast('browser:started', { profileId: opts.profileId, sessionId: res.sessionId });
336
- return {
337
- ok: true,
338
- body: {
339
- ok: true,
340
- sessionId: res.sessionId,
341
- profileId: opts.profileId,
342
- ...(recording ? { recording } : {}),
343
- },
344
- };
345
- }
346
- case 'goto': {
347
- const profileId = args.profileId || 'default';
348
- const session = manager.getSession(profileId);
349
- if (!session)
350
- throw new Error(`session for profile ${profileId} not started`);
351
- await session.goto(args.url);
352
- broadcast('page:navigated', { profileId, url: args.url });
353
- return { ok: true, body: { ok: true } };
354
- }
355
- case 'getCookies': {
356
- const profileId = args.profileId || 'default';
357
- const session = manager.getSession(profileId);
358
- if (!session)
359
- throw new Error(`session for profile ${profileId} not started`);
360
- const cookies = await session.getCookies();
361
- return { ok: true, body: { ok: true, cookies } };
362
- }
363
- case 'saveCookies': {
364
- const profileId = args.profileId || 'default';
365
- const session = manager.getSession(profileId);
366
- if (!session)
367
- throw new Error(`session for profile ${profileId} not started`);
368
- if (!args.path)
369
- throw new Error('path required');
370
- const result = await session.saveCookiesToFile(args.path);
371
- return { ok: true, body: { ok: true, ...result } };
372
- }
373
- case 'saveCookiesIfStable': {
374
- const profileId = args.profileId || 'default';
375
- const session = manager.getSession(profileId);
376
- if (!session)
377
- throw new Error(`session for profile ${profileId} not started`);
378
- if (!args.path)
379
- throw new Error('path required');
380
- const result = await session.saveCookiesIfStable(args.path, { minDelayMs: args.minDelayMs });
381
- return { ok: true, body: { ok: true, saved: !!result, ...result } };
382
- }
383
- case 'loadCookies': {
384
- const profileId = args.profileId || 'default';
385
- const session = manager.getSession(profileId);
386
- if (!session)
387
- throw new Error(`session for profile ${profileId} not started`);
388
- if (!args.path)
389
- throw new Error('path required');
390
- const result = await session.injectCookiesFromFile(args.path);
391
- return { ok: true, body: { ok: true, ...result } };
392
- }
393
- case 'getStatus': {
394
- return { ok: true, body: { ok: true, sessions: manager.listSessions() } };
395
- }
396
- case 'record:start': {
397
- const profileId = args.profileId || 'default';
398
- const session = manager.getSession(profileId);
399
- if (!session)
400
- throw new Error(`session for profile ${profileId} not started`);
401
- const recording = await session.startRecording({
402
- name: args.name || args.recordName,
403
- outputPath: args.outputPath || args.output || args.recordOutput,
404
- overlay: typeof args.overlay === 'boolean' ? args.overlay : undefined,
405
- });
406
- return { ok: true, body: { ok: true, profileId, recording } };
407
- }
408
- case 'record:stop': {
409
- const profileId = args.profileId || 'default';
410
- const session = manager.getSession(profileId);
411
- if (!session)
412
- throw new Error(`session for profile ${profileId} not started`);
413
- const recording = await session.stopRecording({ reason: String(args.reason || 'manual') });
414
- return { ok: true, body: { ok: true, profileId, recording } };
415
- }
416
- case 'record:status': {
417
- const profileId = args.profileId || 'default';
418
- const session = manager.getSession(profileId);
419
- if (!session)
420
- throw new Error(`session for profile ${profileId} not started`);
421
- const recording = session.getRecordingStatus();
422
- return { ok: true, body: { ok: true, profileId, recording } };
423
- }
424
- case 'system:display': {
425
- const metrics = getDisplayMetrics();
426
- return { ok: true, body: { ok: true, metrics: metrics || null } };
427
- }
428
- case 'window:move': {
429
- const profileId = args.profileId || 'default';
430
- const session = manager.getSession(profileId);
431
- if (!session)
432
- throw new Error(`session for profile ${profileId} not started`);
433
- const { x, y } = args;
434
- await session.evaluate(`window.moveTo(${x}, ${y})`);
435
- return { ok: true, body: { ok: true } };
436
- }
437
- case 'window:resize': {
438
- const profileId = args.profileId || 'default';
439
- const session = manager.getSession(profileId);
440
- if (!session)
441
- throw new Error(`session for profile ${profileId} not started`);
442
- const { width, height } = args;
443
- await session.evaluate(`window.resizeTo(${width}, ${height})`);
444
- return { ok: true, body: { ok: true } };
445
- }
446
- case 'stop': {
447
- const profileId = args.profileId || 'default';
448
- const deleted = await manager.deleteSession(profileId);
449
- return { ok: true, body: { ok: deleted } };
450
- }
451
- case 'service:shutdown': {
452
- console.log('[BrowserService] Received shutdown command, gracefully terminating...');
453
- const response = { ok: true, body: { message: 'Browser service shutting down' } };
454
- setImmediate(async () => {
455
- try {
456
- if (wsServer) {
457
- await wsServer.stop().catch(() => { });
458
- }
459
- await manager.shutdown();
460
- console.log('[BrowserService] Shutdown complete');
461
- process.exit(0);
462
- }
463
- catch (err) {
464
- console.error('[BrowserService] Error during shutdown:', err);
465
- process.exit(1);
466
- }
467
- });
468
- return response;
469
- }
470
- case 'screenshot': {
471
- const profileId = args.profileId || 'default';
472
- const session = manager.getSession(profileId);
473
- if (!session)
474
- throw new Error(`session for profile ${profileId} not started`);
475
- const buffer = await session.screenshot(!!args.fullPage);
476
- return { ok: true, body: { success: true, data: buffer.toString('base64') } };
477
- }
478
- case 'evaluate': {
479
- const profileId = args.profileId || 'default';
480
- const session = manager.getSession(profileId);
481
- if (!session)
482
- throw new Error(`session for profile ${profileId} not started`);
483
- const script = args.script;
484
- if (!script || typeof script !== 'string')
485
- throw new Error('script (string) is required');
486
- const result = await session.evaluate(script);
487
- return { ok: true, body: { ok: true, result } };
488
- }
489
- case 'page:list': {
490
- const profileId = args.profileId || 'default';
491
- const session = manager.getSession(profileId);
492
- if (!session)
493
- throw new Error(`session for profile ${profileId} not started`);
494
- const pages = session.listPages();
495
- const activeIndex = pages.find((p) => p.active)?.index ?? 0;
496
- return { ok: true, body: { ok: true, pages, activeIndex } };
497
- }
498
- case 'newTab':
499
- case 'page:new':
500
- case 'newPage': {
501
- const profileId = args.profileId || 'default';
502
- const session = manager.getSession(profileId);
503
- if (!session)
504
- throw new Error(`session for profile ${profileId} not started`);
505
- const url = args.url ? String(args.url) : undefined;
506
- const strictShortcut = args.strictShortcut === true;
507
- const result = await session.newPage(url, { strictShortcut });
508
- broadcast('page:created', { profileId, index: result.index, url: result.url });
509
- return { ok: true, body: { ok: true, ...result } };
510
- }
511
- case 'page:switch':
512
- case 'switchControl': {
513
- const profileId = args.profileId || 'default';
514
- const session = manager.getSession(profileId);
515
- if (!session)
516
- throw new Error(`session for profile ${profileId} not started`);
517
- const index = Number(args.index);
518
- const result = await session.switchPage(index);
519
- broadcast('page:switched', { profileId, index: result.index, url: result.url });
520
- return { ok: true, body: { ok: true, ...result } };
521
- }
522
- case 'page:close': {
523
- const profileId = args.profileId || 'default';
524
- const session = manager.getSession(profileId);
525
- if (!session)
526
- throw new Error(`session for profile ${profileId} not started`);
527
- const hasIndex = typeof args.index !== 'undefined' && args.index !== null;
528
- const index = hasIndex ? Number(args.index) : undefined;
529
- const result = await session.closePage(index);
530
- broadcast('page:closed', { profileId, closedIndex: result.closedIndex, activeIndex: result.activeIndex });
531
- return { ok: true, body: { ok: true, ...result } };
532
- }
533
- case 'page:back': {
534
- const profileId = args.profileId || 'default';
535
- const session = manager.getSession(profileId);
536
- if (!session)
537
- throw new Error(`session for profile ${profileId} not started`);
538
- const result = await session.goBack();
539
- broadcast('page:navigated', { profileId, url: result.url, via: 'page:back' });
540
- return { ok: true, body: { ok: true, ...result } };
541
- }
542
- case 'page:setViewport': {
543
- const profileId = args.profileId || 'default';
544
- const session = manager.getSession(profileId);
545
- if (!session)
546
- throw new Error(`session for profile ${profileId} not started`);
547
- const width = Number(args.width);
548
- const height = Number(args.height);
549
- const size = await session.setViewportSize({ width, height });
550
- broadcast('page:viewport', { profileId, ...size });
551
- return { ok: true, body: { ok: true, ...size } };
552
- }
553
- case 'autoCookies:start': {
554
- const profileId = args.profileId || 'default';
555
- const interval = Math.max(1000, Number(args.intervalMs) || 2500);
556
- const existing = autoLoops.get(profileId);
557
- if (existing)
558
- clearInterval(existing);
559
- const timer = setInterval(async () => {
560
- const session = manager.getSession(profileId);
561
- if (!session)
562
- return;
563
- try {
564
- await session.saveCookiesForActivePage();
565
- }
566
- catch {
567
- // ignore
568
- }
569
- }, interval);
570
- autoLoops.set(profileId, timer);
571
- return { ok: true, body: { ok: true } };
572
- }
573
- case 'autoCookies:stop': {
574
- const profileId = args.profileId || 'default';
575
- const timer = autoLoops.get(profileId);
576
- if (timer)
577
- clearInterval(timer);
578
- autoLoops.delete(profileId);
579
- return { ok: true, body: { ok: true } };
580
- }
581
- case 'autoCookies:status': {
582
- const profileId = args.profileId || 'default';
583
- return { ok: true, body: { ok: !!autoLoops.get(profileId) } };
584
- }
585
- case 'mouse:click': {
586
- const profileId = args.profileId || 'default';
587
- const session = manager.getSession(profileId);
588
- if (!session)
589
- throw new Error(`session for profile ${profileId} not started`);
590
- const { x, y, button, clicks, delay, nudgeBefore } = args;
591
- await session.mouseClick({ x: Number(x), y: Number(y), button, clicks, delay, nudgeBefore: nudgeBefore === true });
592
- return { ok: true, body: { ok: true } };
593
- }
594
- case 'mouse:move': {
595
- throw new Error('mouse:move disabled');
596
- }
597
- case 'mouse:wheel': {
598
- const profileId = args.profileId || 'default';
599
- const session = manager.getSession(profileId);
600
- if (!session)
601
- throw new Error(`session for profile ${profileId} not started`);
602
- const { deltaY, deltaX, anchorX, anchorY } = args;
603
- await session.mouseWheel({
604
- deltaY: Number(deltaY) || 0,
605
- deltaX: Number(deltaX) || 0,
606
- ...(Number.isFinite(Number(anchorX)) && Number.isFinite(Number(anchorY))
607
- ? { anchorX: Number(anchorX), anchorY: Number(anchorY) }
608
- : {}),
609
- });
610
- return { ok: true, body: { ok: true } };
611
- }
612
- case 'keyboard:type': {
613
- const profileId = args.profileId || 'default';
614
- const session = manager.getSession(profileId);
615
- if (!session)
616
- throw new Error(`session for profile ${profileId} not started`);
617
- const { text, delay, submit } = args;
618
- await session.keyboardType({
619
- text: String(text ?? ''),
620
- delay: typeof delay === 'number' ? delay : undefined,
621
- submit: !!submit,
622
- });
623
- return { ok: true, body: { ok: true } };
624
- }
625
- case 'keyboard:press': {
626
- const profileId = args.profileId || 'default';
627
- const session = manager.getSession(profileId);
628
- if (!session)
629
- throw new Error(`session for profile ${profileId} not started`);
630
- const { key, delay } = args;
631
- await session.keyboardPress({
632
- key: String(key ?? 'Enter'),
633
- delay: typeof delay === 'number' ? delay : undefined,
634
- });
635
- return { ok: true, body: { ok: true } };
636
- }
637
- default:
638
- throw new Error(`Unknown action: ${action}`);
639
- }
640
- }
641
- function broadcast(event, data) {
642
- const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
643
- clients.forEach((client) => {
644
- try {
645
- client.write(payload);
646
- }
647
- catch {
648
- clients.delete(client);
649
- }
650
- });
651
- }
652
- export function parseBrowserServiceCliArgs(argv = process.argv) {
653
- const hostArg = argv.indexOf('--host');
654
- const portArg = argv.indexOf('--port');
655
- const wsPortArg = argv.indexOf('--ws-port');
656
- const wsHostArg = argv.indexOf('--ws-host');
657
- const busUrlArg = argv.indexOf('--bus-url');
658
- const disableWs = argv.includes('--no-ws');
659
- return {
660
- host: hostArg >= 0 ? argv[hostArg + 1] : '127.0.0.1',
661
- port: portArg >= 0 ? Number(argv[portArg + 1]) : 7704,
662
- wsPort: wsPortArg >= 0 ? Number(argv[wsPortArg + 1]) : 8765,
663
- wsHost: wsHostArg >= 0 ? argv[wsHostArg + 1] : '127.0.0.1',
664
- busUrl: busUrlArg >= 0 ? argv[busUrlArg + 1] : undefined,
665
- enableWs: !disableWs,
666
- };
667
- }
668
- export async function runBrowserServiceCli(argv = process.argv) {
669
- await startBrowserService(parseBrowserServiceCliArgs(argv));
670
- }
671
- if (fileURLToPath(import.meta.url) === process.argv[1]) {
672
- void runBrowserServiceCli(process.argv);
673
- }
674
- //# sourceMappingURL=index.js.map
1
+ import http from 'http';
2
+ import { fileURLToPath } from 'node:url';
3
+ import os from 'node:os';
4
+ import { spawnSync } from 'node:child_process';
5
+ import { SessionManager, SESSION_CLOSED_EVENT, } from './internal/SessionManager.js';
6
+ import { BrowserWsServer } from './internal/ws-server.js';
7
+ import { logDebug } from './internal/logging.js';
8
+ import { installServiceProcessLogger } from './internal/service-process-logger.js';
9
+ import { startHeartbeatWriter } from './internal/heartbeat.js';
10
+ import { appendCommandLog } from '../../utils/command-log.mjs';
11
+ const clients = new Set();
12
+ const autoLoops = new Map();
13
+ function readNumber(value) {
14
+ if (!value)
15
+ return null;
16
+ const parsed = Number(value);
17
+ if (!Number.isFinite(parsed) || parsed <= 0)
18
+ return null;
19
+ return parsed;
20
+ }
21
+ function readPositiveNumber(value) {
22
+ const parsed = Number(value);
23
+ if (!Number.isFinite(parsed) || parsed <= 0)
24
+ return null;
25
+ return parsed;
26
+ }
27
+ function getDisplayMetrics() {
28
+ const envWidth = readNumber(process.env.CAMO_SCREEN_WIDTH || process.env.CAMO_SCREEN_WIDTH);
29
+ const envHeight = readNumber(process.env.CAMO_SCREEN_HEIGHT || process.env.CAMO_SCREEN_HEIGHT);
30
+ if (envWidth && envHeight) {
31
+ return { width: envWidth, height: envHeight, source: 'env' };
32
+ }
33
+ if (os.platform() === 'darwin') {
34
+ try {
35
+ const sp = spawnSync('system_profiler', ['SPDisplaysDataType', '-json'], { encoding: 'utf8' });
36
+ const spJson = sp.status === 0 && sp.stdout ? JSON.parse(sp.stdout) : null;
37
+ let width = null;
38
+ let height = null;
39
+ const displays = spJson?.SPDisplaysDataType;
40
+ if (Array.isArray(displays) && displays.length > 0) {
41
+ const first = displays[0];
42
+ const gpus = first?._items;
43
+ const maybe = Array.isArray(gpus) && gpus.length > 0 ? gpus[0] : first;
44
+ const resStr = maybe?.spdisplays_ndrvs?.[0]?._spdisplays_resolution || maybe?._spdisplays_resolution;
45
+ if (typeof resStr === 'string') {
46
+ const m = resStr.match(/(\d+)\s*x\s*(\d+)/i);
47
+ if (m) {
48
+ width = readNumber(m[1]);
49
+ height = readNumber(m[2]);
50
+ }
51
+ }
52
+ }
53
+ const osascript = spawnSync('osascript', [
54
+ '-l',
55
+ 'JavaScript',
56
+ '-e',
57
+ `ObjC.import('AppKit');
58
+ const s = $.NSScreen.mainScreen;
59
+ const f = s.frame;
60
+ const v = s.visibleFrame;
61
+ JSON.stringify({
62
+ width: Number(f.size.width),
63
+ height: Number(f.size.height),
64
+ workWidth: Number(v.size.width),
65
+ workHeight: Number(v.size.height)
66
+ });`,
67
+ ], { encoding: 'utf8' });
68
+ const vf = osascript.status === 0 && osascript.stdout ? JSON.parse(osascript.stdout.trim()) : null;
69
+ const finalW = readNumber(vf?.width) || width;
70
+ const finalH = readNumber(vf?.height) || height;
71
+ const workWidth = readNumber(vf?.workWidth);
72
+ const workHeight = readNumber(vf?.workHeight);
73
+ if (!finalW || !finalH)
74
+ return null;
75
+ return {
76
+ width: finalW,
77
+ height: finalH,
78
+ ...(workWidth ? { workWidth } : {}),
79
+ ...(workHeight ? { workHeight } : {}),
80
+ source: 'darwin',
81
+ };
82
+ }
83
+ catch {
84
+ return null;
85
+ }
86
+ }
87
+ if (os.platform() !== 'win32')
88
+ return null;
89
+ try {
90
+ const script = [
91
+ 'Add-Type -AssemblyName System.Windows.Forms;',
92
+ '$screen=[System.Windows.Forms.Screen]::PrimaryScreen;',
93
+ '$b=$screen.Bounds;',
94
+ '$w=$screen.WorkingArea;',
95
+ '$video=Get-CimInstance Win32_VideoController | Select-Object -First 1;',
96
+ '$nw=$null;$nh=$null;',
97
+ 'if ($video) { $nw=$video.CurrentHorizontalResolution; $nh=$video.CurrentVerticalResolution }',
98
+ '$o=[pscustomobject]@{width=$b.Width;height=$b.Height;workWidth=$w.Width;workHeight=$w.Height;nativeWidth=$nw;nativeHeight=$nh};',
99
+ '$o | ConvertTo-Json -Compress',
100
+ ].join(' ');
101
+ const res = spawnSync('powershell', ['-NoProfile', '-Command', script], {
102
+ encoding: 'utf8',
103
+ windowsHide: true,
104
+ });
105
+ if (res.status !== 0 || !res.stdout)
106
+ return null;
107
+ const payload = JSON.parse(res.stdout.trim());
108
+ const nativeWidth = readNumber(payload?.nativeWidth);
109
+ const nativeHeight = readNumber(payload?.nativeHeight);
110
+ const width = readNumber(payload?.width) || nativeWidth || null;
111
+ const height = readNumber(payload?.height) || nativeHeight || null;
112
+ const workWidth = readNumber(payload?.workWidth);
113
+ const workHeight = readNumber(payload?.workHeight);
114
+ if (!width || !height)
115
+ return null;
116
+ return {
117
+ width,
118
+ height,
119
+ ...(workWidth ? { workWidth } : {}),
120
+ ...(workHeight ? { workHeight } : {}),
121
+ ...(nativeWidth ? { nativeWidth } : {}),
122
+ ...(nativeHeight ? { nativeHeight } : {}),
123
+ source: 'win32',
124
+ };
125
+ }
126
+ catch {
127
+ return null;
128
+ }
129
+ }
130
+ function resolveStartViewport(args) {
131
+ const explicitWidth = readPositiveNumber(args?.width ?? args?.viewportWidth ?? args?.viewport?.width);
132
+ const explicitHeight = readPositiveNumber(args?.height ?? args?.viewportHeight ?? args?.viewport?.height);
133
+ if (explicitWidth && explicitHeight) {
134
+ return {
135
+ width: Math.floor(explicitWidth),
136
+ height: Math.floor(explicitHeight),
137
+ };
138
+ }
139
+ if (Boolean(args?.headless))
140
+ return null;
141
+ const display = getDisplayMetrics();
142
+ if (!display)
143
+ return null;
144
+ const reserveRaw = Number(process.env.CAMO_WINDOW_VERTICAL_RESERVE ?? process.env.CAMO_WINDOW_VERTICAL_RESERVE ?? 0);
145
+ const reserve = Number.isFinite(reserveRaw) ? Math.max(0, Math.min(240, Math.floor(reserveRaw))) : 0;
146
+ const baseWidth = readPositiveNumber(display.workWidth) || readPositiveNumber(display.width);
147
+ const baseHeight = readPositiveNumber(display.workHeight) || readPositiveNumber(display.height);
148
+ if (!baseWidth || !baseHeight)
149
+ return null;
150
+ return {
151
+ width: Math.max(960, Math.floor(baseWidth)),
152
+ height: Math.max(700, Math.floor(baseHeight - reserve)),
153
+ };
154
+ }
155
+ export async function startBrowserService(opts = {}) {
156
+ const { logEvent } = installServiceProcessLogger({ serviceName: 'browser-service' });
157
+ const host = opts.host || process.env.CAMO_BROWSER_HTTP_HOST || '127.0.0.1';
158
+ const port = Number(opts.port || process.env.CAMO_BROWSER_HTTP_PORT || 7704);
159
+ const sessionManager = new SessionManager();
160
+ const enableWs = opts.enableWs ?? process.env.CAMO_BROWSER_DISABLE_WS !== '1';
161
+ const wsHost = opts.wsHost || process.env.CAMO_WS_HOST || '127.0.0.1';
162
+ const wsPort = Number(opts.wsPort || process.env.CAMO_WS_PORT || 8765);
163
+ const autoExit = process.env.CAMO_BROWSER_AUTO_EXIT === '1';
164
+ const heartbeat = startHeartbeatWriter({ initialStatus: 'idle' });
165
+ let heartbeatStatus = 'idle';
166
+ let hasActiveSession = false;
167
+ const setHeartbeatStatus = (next) => {
168
+ if (heartbeatStatus === next)
169
+ return;
170
+ heartbeatStatus = next;
171
+ heartbeat.setStatus(next);
172
+ };
173
+ const markSessionStarted = () => {
174
+ hasActiveSession = true;
175
+ setHeartbeatStatus('running');
176
+ };
177
+ const markAllSessionsClosed = () => {
178
+ if (!hasActiveSession)
179
+ return;
180
+ setHeartbeatStatus('stopped');
181
+ };
182
+ logDebug('browser-service', 'start', { host, port, wsHost, wsPort, enableWs, autoExit });
183
+ let wsServer = null;
184
+ const server = http.createServer((req, res) => {
185
+ void (async () => {
186
+ const url = new URL(req.url || '/', `http://${req.headers.host}`);
187
+ res.setHeader('Access-Control-Allow-Origin', '*');
188
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
189
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
190
+ if (req.method === 'OPTIONS') {
191
+ res.writeHead(200);
192
+ res.end();
193
+ return;
194
+ }
195
+ if (url.pathname === '/health') {
196
+ res.writeHead(200, { 'Content-Type': 'application/json' });
197
+ res.end(JSON.stringify({ ok: true }));
198
+ return;
199
+ }
200
+ if (url.pathname === '/events') {
201
+ res.writeHead(200, {
202
+ 'Content-Type': 'text/event-stream',
203
+ Connection: 'keep-alive',
204
+ 'Cache-Control': 'no-cache',
205
+ });
206
+ clients.add(res);
207
+ req.on('close', () => clients.delete(res));
208
+ return;
209
+ }
210
+ if (url.pathname === '/command' && req.method === 'POST') {
211
+ const chunks = [];
212
+ req.on('data', (chunk) => chunks.push(chunk));
213
+ req.on('end', async () => {
214
+ try {
215
+ const payload = JSON.parse(Buffer.concat(chunks).toString('utf-8'));
216
+ const t0 = Date.now();
217
+ const action = String(payload?.action || '');
218
+ const profileId = String(payload?.args?.profileId || payload?.args?.profile || payload?.args?.sessionId || '');
219
+ appendCommandLog({
220
+ action,
221
+ profileId,
222
+ payload: payload?.args ?? {},
223
+ meta: {
224
+ source: 'browser-service',
225
+ cwd: process.cwd(),
226
+ pid: process.pid,
227
+ ppid: process.ppid,
228
+ sender: payload?.meta?.sender && typeof payload.meta.sender === 'object' ? payload.meta.sender : {},
229
+ },
230
+ });
231
+ logEvent('browser.command.start', { action, profileId });
232
+ const result = await handleCommand(payload, sessionManager, wsServer, { onSessionStart: markSessionStarted });
233
+ logEvent('browser.command.done', { action, profileId, ok: result.ok, ms: Date.now() - t0 });
234
+ res.writeHead(result.ok ? 200 : 500, { 'Content-Type': 'application/json' });
235
+ res.end(JSON.stringify(result.body));
236
+ }
237
+ catch (err) {
238
+ logEvent('browser.command.error', { error: err?.message || String(err) });
239
+ res.writeHead(500, { 'Content-Type': 'application/json' });
240
+ res.end(JSON.stringify({ error: err.message }));
241
+ }
242
+ });
243
+ return;
244
+ }
245
+ res.writeHead(404);
246
+ res.end();
247
+ })().catch((err) => {
248
+ logEvent('http.request.error', {
249
+ method: req?.method,
250
+ url: req?.url,
251
+ error: { message: err?.message || String(err), stack: err?.stack },
252
+ });
253
+ try {
254
+ if (!res.headersSent)
255
+ res.writeHead(500, { 'Content-Type': 'application/json' });
256
+ res.end(JSON.stringify({ ok: false, error: 'Internal Server Error' }));
257
+ }
258
+ catch {
259
+ // ignore
260
+ }
261
+ });
262
+ });
263
+ server.listen(port, host, () => {
264
+ console.log(`BrowserService listening on http://${host}:${port}`);
265
+ });
266
+ if (enableWs) {
267
+ wsServer = new BrowserWsServer({ host: wsHost, port: wsPort, sessionManager });
268
+ try {
269
+ await wsServer.start();
270
+ }
271
+ catch (err) {
272
+ console.warn('[browser-service] failed to start WebSocket server:', err.message);
273
+ }
274
+ }
275
+ const stopWsServer = async () => {
276
+ if (!wsServer)
277
+ return;
278
+ await wsServer.stop().catch(() => { });
279
+ };
280
+ const shutdown = async () => {
281
+ heartbeat.stop();
282
+ server.close();
283
+ clients.forEach((client) => client.end());
284
+ autoLoops.forEach((timer) => clearInterval(timer));
285
+ await stopWsServer();
286
+ await sessionManager.shutdown();
287
+ };
288
+ process.on('SIGINT', shutdown);
289
+ process.on('SIGTERM', shutdown);
290
+ process.on(SESSION_CLOSED_EVENT, () => {
291
+ if (!managerIsIdle(sessionManager))
292
+ return;
293
+ markAllSessionsClosed();
294
+ if (autoExit || hasActiveSession) {
295
+ shutdown().finally(() => process.exit(0));
296
+ }
297
+ });
298
+ }
299
+ function managerIsIdle(manager) {
300
+ return manager.listSessions().length === 0;
301
+ }
302
+ async function handleCommand(payload, manager, wsServer, options = {}) {
303
+ const action = payload.action;
304
+ const args = payload.args ?? payload;
305
+ switch (action) {
306
+ case 'start': {
307
+ const startViewport = resolveStartViewport(args);
308
+ const opts = {
309
+ profileId: args.profileId || 'default',
310
+ sessionName: args.profileId || 'default',
311
+ headless: !!args.headless,
312
+ initialUrl: args.url,
313
+ engine: args.engine || 'camoufox',
314
+ fingerprintPlatform: args.fingerprintPlatform || null,
315
+ ...(startViewport ? { viewport: startViewport } : {}),
316
+ ...(args.ownerPid ? { ownerPid: args.ownerPid } : {}),
317
+ };
318
+ const res = await manager.createSession(opts);
319
+ const session = manager.getSession(opts.profileId);
320
+ if (!session) {
321
+ throw new Error(`session for profile ${opts.profileId} not started`);
322
+ }
323
+ let recording = null;
324
+ if (args.record === true || args.recording === true) {
325
+ recording = await session.startRecording({
326
+ name: args.recordName || args.recordingName,
327
+ outputPath: args.recordOutput || args.recordingOutput || args.recordOutputPath,
328
+ overlay: typeof args.recordOverlay === 'boolean' ? args.recordOverlay : undefined,
329
+ });
330
+ }
331
+ options.onSessionStart?.();
332
+ broadcast('browser:started', { profileId: opts.profileId, sessionId: res.sessionId });
333
+ return {
334
+ ok: true,
335
+ body: {
336
+ ok: true,
337
+ sessionId: res.sessionId,
338
+ profileId: opts.profileId,
339
+ ...(recording ? { recording } : {}),
340
+ },
341
+ };
342
+ }
343
+ case 'goto': {
344
+ const profileId = args.profileId || 'default';
345
+ const session = manager.getSession(profileId);
346
+ if (!session)
347
+ throw new Error(`session for profile ${profileId} not started`);
348
+ await session.goto(args.url);
349
+ broadcast('page:navigated', { profileId, url: args.url });
350
+ return { ok: true, body: { ok: true } };
351
+ }
352
+ case 'getCookies': {
353
+ const profileId = args.profileId || 'default';
354
+ const session = manager.getSession(profileId);
355
+ if (!session)
356
+ throw new Error(`session for profile ${profileId} not started`);
357
+ const cookies = await session.getCookies();
358
+ return { ok: true, body: { ok: true, cookies } };
359
+ }
360
+ case 'saveCookies': {
361
+ const profileId = args.profileId || 'default';
362
+ const session = manager.getSession(profileId);
363
+ if (!session)
364
+ throw new Error(`session for profile ${profileId} not started`);
365
+ if (!args.path)
366
+ throw new Error('path required');
367
+ const result = await session.saveCookiesToFile(args.path);
368
+ return { ok: true, body: { ok: true, ...result } };
369
+ }
370
+ case 'saveCookiesIfStable': {
371
+ const profileId = args.profileId || 'default';
372
+ const session = manager.getSession(profileId);
373
+ if (!session)
374
+ throw new Error(`session for profile ${profileId} not started`);
375
+ if (!args.path)
376
+ throw new Error('path required');
377
+ const result = await session.saveCookiesIfStable(args.path, { minDelayMs: args.minDelayMs });
378
+ return { ok: true, body: { ok: true, saved: !!result, ...result } };
379
+ }
380
+ case 'loadCookies': {
381
+ const profileId = args.profileId || 'default';
382
+ const session = manager.getSession(profileId);
383
+ if (!session)
384
+ throw new Error(`session for profile ${profileId} not started`);
385
+ if (!args.path)
386
+ throw new Error('path required');
387
+ const result = await session.injectCookiesFromFile(args.path);
388
+ return { ok: true, body: { ok: true, ...result } };
389
+ }
390
+ case 'getStatus': {
391
+ return { ok: true, body: { ok: true, sessions: manager.listSessions() } };
392
+ }
393
+ case 'record:start': {
394
+ const profileId = args.profileId || 'default';
395
+ const session = manager.getSession(profileId);
396
+ if (!session)
397
+ throw new Error(`session for profile ${profileId} not started`);
398
+ const recording = await session.startRecording({
399
+ name: args.name || args.recordName,
400
+ outputPath: args.outputPath || args.output || args.recordOutput,
401
+ overlay: typeof args.overlay === 'boolean' ? args.overlay : undefined,
402
+ });
403
+ return { ok: true, body: { ok: true, profileId, recording } };
404
+ }
405
+ case 'record:stop': {
406
+ const profileId = args.profileId || 'default';
407
+ const session = manager.getSession(profileId);
408
+ if (!session)
409
+ throw new Error(`session for profile ${profileId} not started`);
410
+ const recording = await session.stopRecording({ reason: String(args.reason || 'manual') });
411
+ return { ok: true, body: { ok: true, profileId, recording } };
412
+ }
413
+ case 'record:status': {
414
+ const profileId = args.profileId || 'default';
415
+ const session = manager.getSession(profileId);
416
+ if (!session)
417
+ throw new Error(`session for profile ${profileId} not started`);
418
+ const recording = session.getRecordingStatus();
419
+ return { ok: true, body: { ok: true, profileId, recording } };
420
+ }
421
+ case 'system:display': {
422
+ const metrics = getDisplayMetrics();
423
+ return { ok: true, body: { ok: true, metrics: metrics || null } };
424
+ }
425
+ case 'window:move': {
426
+ const profileId = args.profileId || 'default';
427
+ const session = manager.getSession(profileId);
428
+ if (!session)
429
+ throw new Error(`session for profile ${profileId} not started`);
430
+ const { x, y } = args;
431
+ await session.evaluate(`window.moveTo(${x}, ${y})`);
432
+ return { ok: true, body: { ok: true } };
433
+ }
434
+ case 'window:resize': {
435
+ const profileId = args.profileId || 'default';
436
+ const session = manager.getSession(profileId);
437
+ if (!session)
438
+ throw new Error(`session for profile ${profileId} not started`);
439
+ const { width, height } = args;
440
+ await session.evaluate(`window.resizeTo(${width}, ${height})`);
441
+ return { ok: true, body: { ok: true } };
442
+ }
443
+ case 'stop': {
444
+ const profileId = args.profileId || 'default';
445
+ const deleted = await manager.deleteSession(profileId);
446
+ return { ok: true, body: { ok: deleted } };
447
+ }
448
+ case 'service:shutdown': {
449
+ console.log('[BrowserService] Received shutdown command, gracefully terminating...');
450
+ const response = { ok: true, body: { message: 'Browser service shutting down' } };
451
+ setImmediate(async () => {
452
+ try {
453
+ if (wsServer) {
454
+ await wsServer.stop().catch(() => { });
455
+ }
456
+ await manager.shutdown();
457
+ console.log('[BrowserService] Shutdown complete');
458
+ process.exit(0);
459
+ }
460
+ catch (err) {
461
+ console.error('[BrowserService] Error during shutdown:', err);
462
+ process.exit(1);
463
+ }
464
+ });
465
+ return response;
466
+ }
467
+ case 'screenshot': {
468
+ const profileId = args.profileId || 'default';
469
+ const session = manager.getSession(profileId);
470
+ if (!session)
471
+ throw new Error(`session for profile ${profileId} not started`);
472
+ const buffer = await session.screenshot(!!args.fullPage);
473
+ return { ok: true, body: { success: true, data: buffer.toString('base64') } };
474
+ }
475
+ case 'evaluate': {
476
+ const profileId = args.profileId || 'default';
477
+ const session = manager.getSession(profileId);
478
+ if (!session)
479
+ throw new Error(`session for profile ${profileId} not started`);
480
+ const script = args.script;
481
+ if (!script || typeof script !== 'string')
482
+ throw new Error('script (string) is required');
483
+ const result = await session.evaluate(script);
484
+ return { ok: true, body: { ok: true, result } };
485
+ }
486
+ case 'page:list': {
487
+ const profileId = args.profileId || 'default';
488
+ const session = manager.getSession(profileId);
489
+ if (!session)
490
+ throw new Error(`session for profile ${profileId} not started`);
491
+ const pages = session.listPages();
492
+ const activeIndex = pages.find((p) => p.active)?.index ?? 0;
493
+ return { ok: true, body: { ok: true, pages, activeIndex } };
494
+ }
495
+ case 'page:new':
496
+ case 'newTab':
497
+ case 'newPage': {
498
+ const profileId = args.profileId || 'default';
499
+ const session = manager.getSession(profileId);
500
+ if (!session)
501
+ throw new Error(`session for profile ${profileId} not started`);
502
+ const url = args.url ? String(args.url) : undefined;
503
+ const strictShortcut = args.strictShortcut === true;
504
+ const result = await session.newPage(url, { strictShortcut });
505
+ broadcast('page:created', { profileId, index: result.index, url: result.url });
506
+ return { ok: true, body: { ok: true, ...result } };
507
+ }
508
+ case 'page:switch':
509
+ case 'switchControl': {
510
+ const profileId = args.profileId || 'default';
511
+ const session = manager.getSession(profileId);
512
+ if (!session)
513
+ throw new Error(`session for profile ${profileId} not started`);
514
+ const index = Number(args.index);
515
+ const result = await session.switchPage(index);
516
+ broadcast('page:switched', { profileId, index: result.index, url: result.url });
517
+ return { ok: true, body: { ok: true, ...result } };
518
+ }
519
+ case 'page:close': {
520
+ const profileId = args.profileId || 'default';
521
+ const session = manager.getSession(profileId);
522
+ if (!session)
523
+ throw new Error(`session for profile ${profileId} not started`);
524
+ const hasIndex = typeof args.index !== 'undefined' && args.index !== null;
525
+ const index = hasIndex ? Number(args.index) : undefined;
526
+ const result = await session.closePage(index);
527
+ broadcast('page:closed', { profileId, closedIndex: result.closedIndex, activeIndex: result.activeIndex });
528
+ return { ok: true, body: { ok: true, ...result } };
529
+ }
530
+ case 'page:back': {
531
+ const profileId = args.profileId || 'default';
532
+ const session = manager.getSession(profileId);
533
+ if (!session)
534
+ throw new Error(`session for profile ${profileId} not started`);
535
+ const result = await session.goBack();
536
+ broadcast('page:navigated', { profileId, url: result.url, via: 'page:back' });
537
+ return { ok: true, body: { ok: true, ...result } };
538
+ }
539
+ case 'page:setViewport': {
540
+ const profileId = args.profileId || 'default';
541
+ const session = manager.getSession(profileId);
542
+ if (!session)
543
+ throw new Error(`session for profile ${profileId} not started`);
544
+ const width = Number(args.width);
545
+ const height = Number(args.height);
546
+ const size = await session.setViewportSize({ width, height });
547
+ broadcast('page:viewport', { profileId, ...size });
548
+ return { ok: true, body: { ok: true, ...size } };
549
+ }
550
+ case 'autoCookies:start': {
551
+ const profileId = args.profileId || 'default';
552
+ const interval = Math.max(1000, Number(args.intervalMs) || 2500);
553
+ const existing = autoLoops.get(profileId);
554
+ if (existing)
555
+ clearInterval(existing);
556
+ const timer = setInterval(async () => {
557
+ const session = manager.getSession(profileId);
558
+ if (!session)
559
+ return;
560
+ try {
561
+ await session.saveCookiesForActivePage();
562
+ }
563
+ catch {
564
+ // ignore
565
+ }
566
+ }, interval);
567
+ autoLoops.set(profileId, timer);
568
+ return { ok: true, body: { ok: true } };
569
+ }
570
+ case 'autoCookies:stop': {
571
+ const profileId = args.profileId || 'default';
572
+ const timer = autoLoops.get(profileId);
573
+ if (timer)
574
+ clearInterval(timer);
575
+ autoLoops.delete(profileId);
576
+ return { ok: true, body: { ok: true } };
577
+ }
578
+ case 'autoCookies:status': {
579
+ const profileId = args.profileId || 'default';
580
+ return { ok: true, body: { ok: !!autoLoops.get(profileId) } };
581
+ }
582
+ case 'mouse:click': {
583
+ const profileId = args.profileId || 'default';
584
+ const session = manager.getSession(profileId);
585
+ if (!session)
586
+ throw new Error(`session for profile ${profileId} not started`);
587
+ const { x, y, button, clicks, delay, nudgeBefore } = args;
588
+ await session.mouseClick({ x: Number(x), y: Number(y), button, clicks, delay, nudgeBefore: nudgeBefore === true });
589
+ return { ok: true, body: { ok: true } };
590
+ }
591
+ case 'mouse:move': {
592
+ throw new Error('mouse:move disabled');
593
+ }
594
+ case 'mouse:wheel': {
595
+ const profileId = args.profileId || 'default';
596
+ const session = manager.getSession(profileId);
597
+ if (!session)
598
+ throw new Error(`session for profile ${profileId} not started`);
599
+ const { deltaY, deltaX, anchorX, anchorY } = args;
600
+ await session.mouseWheel({
601
+ deltaY: Number(deltaY) || 0,
602
+ deltaX: Number(deltaX) || 0,
603
+ ...(Number.isFinite(Number(anchorX)) && Number.isFinite(Number(anchorY))
604
+ ? { anchorX: Number(anchorX), anchorY: Number(anchorY) }
605
+ : {}),
606
+ });
607
+ return { ok: true, body: { ok: true } };
608
+ }
609
+ case 'keyboard:type': {
610
+ const profileId = args.profileId || 'default';
611
+ const session = manager.getSession(profileId);
612
+ if (!session)
613
+ throw new Error(`session for profile ${profileId} not started`);
614
+ const { text, delay, submit } = args;
615
+ await session.keyboardType({
616
+ text: String(text ?? ''),
617
+ delay: typeof delay === 'number' ? delay : undefined,
618
+ submit: !!submit,
619
+ });
620
+ return { ok: true, body: { ok: true } };
621
+ }
622
+ case 'keyboard:press': {
623
+ const profileId = args.profileId || 'default';
624
+ const session = manager.getSession(profileId);
625
+ if (!session)
626
+ throw new Error(`session for profile ${profileId} not started`);
627
+ const { key, delay } = args;
628
+ await session.keyboardPress({
629
+ key: String(key ?? 'Enter'),
630
+ delay: typeof delay === 'number' ? delay : undefined,
631
+ });
632
+ return { ok: true, body: { ok: true } };
633
+ }
634
+ default:
635
+ throw new Error(`Unknown action: ${action}`);
636
+ }
637
+ }
638
+ function broadcast(event, data) {
639
+ const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
640
+ clients.forEach((client) => {
641
+ try {
642
+ client.write(payload);
643
+ }
644
+ catch {
645
+ clients.delete(client);
646
+ }
647
+ });
648
+ }
649
+ export function parseBrowserServiceCliArgs(argv = process.argv) {
650
+ const hostArg = argv.indexOf('--host');
651
+ const portArg = argv.indexOf('--port');
652
+ const wsPortArg = argv.indexOf('--ws-port');
653
+ const wsHostArg = argv.indexOf('--ws-host');
654
+ const busUrlArg = argv.indexOf('--bus-url');
655
+ const disableWs = argv.includes('--no-ws');
656
+ return {
657
+ host: hostArg >= 0 ? argv[hostArg + 1] : '127.0.0.1',
658
+ port: portArg >= 0 ? Number(argv[portArg + 1]) : 7704,
659
+ wsPort: wsPortArg >= 0 ? Number(argv[wsPortArg + 1]) : 8765,
660
+ wsHost: wsHostArg >= 0 ? argv[wsHostArg + 1] : '127.0.0.1',
661
+ busUrl: busUrlArg >= 0 ? argv[busUrlArg + 1] : undefined,
662
+ enableWs: !disableWs,
663
+ };
664
+ }
665
+ export async function runBrowserServiceCli(argv = process.argv) {
666
+ await startBrowserService(parseBrowserServiceCliArgs(argv));
667
+ }
668
+ if (fileURLToPath(import.meta.url) === process.argv[1]) {
669
+ void runBrowserServiceCli(process.argv);
670
+ }
671
+ //# sourceMappingURL=index.js.map