@hera-al/browser-server 1.0.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.
Files changed (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +212 -0
  3. package/dist/config.d.ts +44 -0
  4. package/dist/config.js +74 -0
  5. package/dist/core/cdp.d.ts +124 -0
  6. package/dist/core/cdp.helpers.d.ts +14 -0
  7. package/dist/core/cdp.helpers.js +148 -0
  8. package/dist/core/cdp.js +309 -0
  9. package/dist/core/chrome.d.ts +21 -0
  10. package/dist/core/chrome.executables.d.ts +10 -0
  11. package/dist/core/chrome.executables.js +559 -0
  12. package/dist/core/chrome.js +257 -0
  13. package/dist/core/chrome.profile-decoration.d.ts +11 -0
  14. package/dist/core/chrome.profile-decoration.js +148 -0
  15. package/dist/core/constants.d.ts +9 -0
  16. package/dist/core/constants.js +9 -0
  17. package/dist/core/profiles.d.ts +31 -0
  18. package/dist/core/profiles.js +99 -0
  19. package/dist/core/target-id.d.ts +12 -0
  20. package/dist/core/target-id.js +21 -0
  21. package/dist/data-dir.d.ts +2 -0
  22. package/dist/data-dir.js +6 -0
  23. package/dist/logger.d.ts +16 -0
  24. package/dist/logger.js +125 -0
  25. package/dist/playwright/pw-role-snapshot.d.ts +32 -0
  26. package/dist/playwright/pw-role-snapshot.js +337 -0
  27. package/dist/playwright/pw-session.d.ts +119 -0
  28. package/dist/playwright/pw-session.js +530 -0
  29. package/dist/playwright/pw-tools-core.activity.d.ts +22 -0
  30. package/dist/playwright/pw-tools-core.activity.js +47 -0
  31. package/dist/playwright/pw-tools-core.d.ts +9 -0
  32. package/dist/playwright/pw-tools-core.downloads.d.ts +35 -0
  33. package/dist/playwright/pw-tools-core.downloads.js +186 -0
  34. package/dist/playwright/pw-tools-core.interactions.d.ts +104 -0
  35. package/dist/playwright/pw-tools-core.interactions.js +404 -0
  36. package/dist/playwright/pw-tools-core.js +9 -0
  37. package/dist/playwright/pw-tools-core.responses.d.ts +14 -0
  38. package/dist/playwright/pw-tools-core.responses.js +91 -0
  39. package/dist/playwright/pw-tools-core.shared.d.ts +7 -0
  40. package/dist/playwright/pw-tools-core.shared.js +50 -0
  41. package/dist/playwright/pw-tools-core.snapshot.d.ts +65 -0
  42. package/dist/playwright/pw-tools-core.snapshot.js +144 -0
  43. package/dist/playwright/pw-tools-core.state.d.ts +47 -0
  44. package/dist/playwright/pw-tools-core.state.js +154 -0
  45. package/dist/playwright/pw-tools-core.storage.d.ts +48 -0
  46. package/dist/playwright/pw-tools-core.storage.js +76 -0
  47. package/dist/playwright/pw-tools-core.trace.d.ts +13 -0
  48. package/dist/playwright/pw-tools-core.trace.js +26 -0
  49. package/dist/server/browser-context.d.ts +29 -0
  50. package/dist/server/browser-context.js +137 -0
  51. package/dist/server/browser-server.d.ts +7 -0
  52. package/dist/server/browser-server.js +49 -0
  53. package/dist/server/routes/act.d.ts +4 -0
  54. package/dist/server/routes/act.js +176 -0
  55. package/dist/server/routes/basic.d.ts +4 -0
  56. package/dist/server/routes/basic.js +36 -0
  57. package/dist/server/routes/index.d.ts +4 -0
  58. package/dist/server/routes/index.js +16 -0
  59. package/dist/server/routes/snapshot.d.ts +4 -0
  60. package/dist/server/routes/snapshot.js +143 -0
  61. package/dist/server/routes/storage.d.ts +4 -0
  62. package/dist/server/routes/storage.js +117 -0
  63. package/dist/server/routes/tabs.d.ts +4 -0
  64. package/dist/server/routes/tabs.js +51 -0
  65. package/dist/server/standalone.d.ts +9 -0
  66. package/dist/server/standalone.js +42 -0
  67. package/dist/utils.d.ts +18 -0
  68. package/dist/utils.js +58 -0
  69. package/package.json +66 -0
@@ -0,0 +1,309 @@
1
+ import { appendCdpPath, fetchJson, isLoopbackHost, withCdpSocket } from "./cdp.helpers.js";
2
+ export { appendCdpPath, fetchJson, fetchOk, getHeadersWithAuth } from "./cdp.helpers.js";
3
+ export function normalizeCdpWsUrl(wsUrl, cdpUrl) {
4
+ const ws = new URL(wsUrl);
5
+ const cdp = new URL(cdpUrl);
6
+ if (isLoopbackHost(ws.hostname) && !isLoopbackHost(cdp.hostname)) {
7
+ ws.hostname = cdp.hostname;
8
+ const cdpPort = cdp.port || (cdp.protocol === "https:" ? "443" : "80");
9
+ if (cdpPort) {
10
+ ws.port = cdpPort;
11
+ }
12
+ ws.protocol = cdp.protocol === "https:" ? "wss:" : "ws:";
13
+ }
14
+ if (cdp.protocol === "https:" && ws.protocol === "ws:") {
15
+ ws.protocol = "wss:";
16
+ }
17
+ if (!ws.username && !ws.password && (cdp.username || cdp.password)) {
18
+ ws.username = cdp.username;
19
+ ws.password = cdp.password;
20
+ }
21
+ for (const [key, value] of cdp.searchParams.entries()) {
22
+ if (!ws.searchParams.has(key)) {
23
+ ws.searchParams.append(key, value);
24
+ }
25
+ }
26
+ return ws.toString();
27
+ }
28
+ export async function captureScreenshotPng(opts) {
29
+ return await captureScreenshot({
30
+ wsUrl: opts.wsUrl,
31
+ fullPage: opts.fullPage,
32
+ format: "png",
33
+ });
34
+ }
35
+ export async function captureScreenshot(opts) {
36
+ return await withCdpSocket(opts.wsUrl, async (send) => {
37
+ await send("Page.enable");
38
+ let clip;
39
+ if (opts.fullPage) {
40
+ const metrics = (await send("Page.getLayoutMetrics"));
41
+ const size = metrics?.cssContentSize ?? metrics?.contentSize;
42
+ const width = Number(size?.width ?? 0);
43
+ const height = Number(size?.height ?? 0);
44
+ if (width > 0 && height > 0) {
45
+ clip = { x: 0, y: 0, width, height, scale: 1 };
46
+ }
47
+ }
48
+ const format = opts.format ?? "png";
49
+ const quality = format === "jpeg" ? Math.max(0, Math.min(100, Math.round(opts.quality ?? 85))) : undefined;
50
+ const result = (await send("Page.captureScreenshot", {
51
+ format,
52
+ ...(quality !== undefined ? { quality } : {}),
53
+ fromSurface: true,
54
+ captureBeyondViewport: true,
55
+ ...(clip ? { clip } : {}),
56
+ }));
57
+ const base64 = result?.data;
58
+ if (!base64) {
59
+ throw new Error("Screenshot failed: missing data");
60
+ }
61
+ return Buffer.from(base64, "base64");
62
+ });
63
+ }
64
+ export async function createTargetViaCdp(opts) {
65
+ const version = await fetchJson(appendCdpPath(opts.cdpUrl, "/json/version"), 1500);
66
+ const wsUrlRaw = String(version?.webSocketDebuggerUrl ?? "").trim();
67
+ const wsUrl = wsUrlRaw ? normalizeCdpWsUrl(wsUrlRaw, opts.cdpUrl) : "";
68
+ if (!wsUrl) {
69
+ throw new Error("CDP /json/version missing webSocketDebuggerUrl");
70
+ }
71
+ return await withCdpSocket(wsUrl, async (send) => {
72
+ const created = (await send("Target.createTarget", { url: opts.url }));
73
+ const targetId = String(created?.targetId ?? "").trim();
74
+ if (!targetId) {
75
+ throw new Error("CDP Target.createTarget returned no targetId");
76
+ }
77
+ return { targetId };
78
+ });
79
+ }
80
+ export async function evaluateJavaScript(opts) {
81
+ return await withCdpSocket(opts.wsUrl, async (send) => {
82
+ await send("Runtime.enable").catch(() => { });
83
+ const evaluated = (await send("Runtime.evaluate", {
84
+ expression: opts.expression,
85
+ awaitPromise: Boolean(opts.awaitPromise),
86
+ returnByValue: opts.returnByValue ?? true,
87
+ userGesture: true,
88
+ includeCommandLineAPI: true,
89
+ }));
90
+ const result = evaluated?.result;
91
+ if (!result) {
92
+ throw new Error("CDP Runtime.evaluate returned no result");
93
+ }
94
+ return { result, exceptionDetails: evaluated.exceptionDetails };
95
+ });
96
+ }
97
+ function axValue(v) {
98
+ if (!v || typeof v !== "object") {
99
+ return "";
100
+ }
101
+ const value = v.value;
102
+ if (typeof value === "string") {
103
+ return value;
104
+ }
105
+ if (typeof value === "number" || typeof value === "boolean") {
106
+ return String(value);
107
+ }
108
+ return "";
109
+ }
110
+ export function formatAriaSnapshot(nodes, limit) {
111
+ const byId = new Map();
112
+ for (const n of nodes) {
113
+ if (n.nodeId) {
114
+ byId.set(n.nodeId, n);
115
+ }
116
+ }
117
+ // Heuristic: pick a root-ish node (one that is not referenced as a child), else first.
118
+ const referenced = new Set();
119
+ for (const n of nodes) {
120
+ for (const c of n.childIds ?? []) {
121
+ referenced.add(c);
122
+ }
123
+ }
124
+ const root = nodes.find((n) => n.nodeId && !referenced.has(n.nodeId)) ?? nodes[0];
125
+ if (!root?.nodeId) {
126
+ return [];
127
+ }
128
+ const out = [];
129
+ const stack = [{ id: root.nodeId, depth: 0 }];
130
+ while (stack.length && out.length < limit) {
131
+ const popped = stack.pop();
132
+ if (!popped) {
133
+ break;
134
+ }
135
+ const { id, depth } = popped;
136
+ const n = byId.get(id);
137
+ if (!n) {
138
+ continue;
139
+ }
140
+ const role = axValue(n.role);
141
+ const name = axValue(n.name);
142
+ const value = axValue(n.value);
143
+ const description = axValue(n.description);
144
+ const ref = `ax${out.length + 1}`;
145
+ out.push({
146
+ ref,
147
+ role: role || "unknown",
148
+ name: name || "",
149
+ ...(value ? { value } : {}),
150
+ ...(description ? { description } : {}),
151
+ ...(typeof n.backendDOMNodeId === "number" ? { backendDOMNodeId: n.backendDOMNodeId } : {}),
152
+ depth,
153
+ });
154
+ const children = (n.childIds ?? []).filter((c) => byId.has(c));
155
+ for (let i = children.length - 1; i >= 0; i--) {
156
+ const child = children[i];
157
+ if (child) {
158
+ stack.push({ id: child, depth: depth + 1 });
159
+ }
160
+ }
161
+ }
162
+ return out;
163
+ }
164
+ export async function snapshotAria(opts) {
165
+ const limit = Math.max(1, Math.min(2000, Math.floor(opts.limit ?? 500)));
166
+ return await withCdpSocket(opts.wsUrl, async (send) => {
167
+ await send("Accessibility.enable").catch(() => { });
168
+ const res = (await send("Accessibility.getFullAXTree"));
169
+ const nodes = Array.isArray(res?.nodes) ? res.nodes : [];
170
+ return { nodes: formatAriaSnapshot(nodes, limit) };
171
+ });
172
+ }
173
+ export async function snapshotDom(opts) {
174
+ const limit = Math.max(1, Math.min(5000, Math.floor(opts.limit ?? 800)));
175
+ const maxTextChars = Math.max(0, Math.min(5000, Math.floor(opts.maxTextChars ?? 220)));
176
+ const expression = `(() => {
177
+ const maxNodes = ${JSON.stringify(limit)};
178
+ const maxText = ${JSON.stringify(maxTextChars)};
179
+ const nodes = [];
180
+ const root = document.documentElement;
181
+ if (!root) return { nodes };
182
+ const stack = [{ el: root, depth: 0, parentRef: null }];
183
+ while (stack.length && nodes.length < maxNodes) {
184
+ const cur = stack.pop();
185
+ const el = cur.el;
186
+ if (!el || el.nodeType !== 1) continue;
187
+ const ref = "n" + String(nodes.length + 1);
188
+ const tag = (el.tagName || "").toLowerCase();
189
+ const id = el.id ? String(el.id) : undefined;
190
+ const className = el.className ? String(el.className).slice(0, 300) : undefined;
191
+ const role = el.getAttribute && el.getAttribute("role") ? String(el.getAttribute("role")) : undefined;
192
+ const name = el.getAttribute && el.getAttribute("aria-label") ? String(el.getAttribute("aria-label")) : undefined;
193
+ let text = "";
194
+ try { text = String(el.innerText || "").trim(); } catch {}
195
+ if (maxText && text.length > maxText) text = text.slice(0, maxText) + "…";
196
+ const href = (el.href !== undefined && el.href !== null) ? String(el.href) : undefined;
197
+ const type = (el.type !== undefined && el.type !== null) ? String(el.type) : undefined;
198
+ const value = (el.value !== undefined && el.value !== null) ? String(el.value).slice(0, 500) : undefined;
199
+ nodes.push({
200
+ ref,
201
+ parentRef: cur.parentRef,
202
+ depth: cur.depth,
203
+ tag,
204
+ ...(id ? { id } : {}),
205
+ ...(className ? { className } : {}),
206
+ ...(role ? { role } : {}),
207
+ ...(name ? { name } : {}),
208
+ ...(text ? { text } : {}),
209
+ ...(href ? { href } : {}),
210
+ ...(type ? { type } : {}),
211
+ ...(value ? { value } : {}),
212
+ });
213
+ const children = el.children ? Array.from(el.children) : [];
214
+ for (let i = children.length - 1; i >= 0; i--) {
215
+ stack.push({ el: children[i], depth: cur.depth + 1, parentRef: ref });
216
+ }
217
+ }
218
+ return { nodes };
219
+ })()`;
220
+ const evaluated = await evaluateJavaScript({
221
+ wsUrl: opts.wsUrl,
222
+ expression,
223
+ awaitPromise: true,
224
+ returnByValue: true,
225
+ });
226
+ const value = evaluated.result?.value;
227
+ if (!value || typeof value !== "object") {
228
+ return { nodes: [] };
229
+ }
230
+ const nodes = value.nodes;
231
+ return { nodes: Array.isArray(nodes) ? nodes : [] };
232
+ }
233
+ export async function getDomText(opts) {
234
+ const maxChars = Math.max(0, Math.min(5_000_000, Math.floor(opts.maxChars ?? 200_000)));
235
+ const selectorExpr = opts.selector ? JSON.stringify(opts.selector) : "null";
236
+ const expression = `(() => {
237
+ const fmt = ${JSON.stringify(opts.format)};
238
+ const max = ${JSON.stringify(maxChars)};
239
+ const sel = ${selectorExpr};
240
+ const pick = sel ? document.querySelector(sel) : null;
241
+ let out = "";
242
+ if (fmt === "text") {
243
+ const el = pick || document.body || document.documentElement;
244
+ try { out = String(el && el.innerText ? el.innerText : ""); } catch { out = ""; }
245
+ } else {
246
+ const el = pick || document.documentElement;
247
+ try { out = String(el && el.outerHTML ? el.outerHTML : ""); } catch { out = ""; }
248
+ }
249
+ if (max && out.length > max) out = out.slice(0, max) + "\\n<!-- …truncated… -->";
250
+ return out;
251
+ })()`;
252
+ const evaluated = await evaluateJavaScript({
253
+ wsUrl: opts.wsUrl,
254
+ expression,
255
+ awaitPromise: true,
256
+ returnByValue: true,
257
+ });
258
+ const textValue = (evaluated.result?.value ?? "");
259
+ const text = typeof textValue === "string"
260
+ ? textValue
261
+ : typeof textValue === "number" || typeof textValue === "boolean"
262
+ ? String(textValue)
263
+ : "";
264
+ return { text };
265
+ }
266
+ export async function querySelector(opts) {
267
+ const limit = Math.max(1, Math.min(200, Math.floor(opts.limit ?? 20)));
268
+ const maxText = Math.max(0, Math.min(5000, Math.floor(opts.maxTextChars ?? 500)));
269
+ const maxHtml = Math.max(0, Math.min(20000, Math.floor(opts.maxHtmlChars ?? 1500)));
270
+ const expression = `(() => {
271
+ const sel = ${JSON.stringify(opts.selector)};
272
+ const lim = ${JSON.stringify(limit)};
273
+ const maxText = ${JSON.stringify(maxText)};
274
+ const maxHtml = ${JSON.stringify(maxHtml)};
275
+ const els = Array.from(document.querySelectorAll(sel)).slice(0, lim);
276
+ return els.map((el, i) => {
277
+ const tag = (el.tagName || "").toLowerCase();
278
+ const id = el.id ? String(el.id) : undefined;
279
+ const className = el.className ? String(el.className).slice(0, 300) : undefined;
280
+ let text = "";
281
+ try { text = String(el.innerText || "").trim(); } catch {}
282
+ if (maxText && text.length > maxText) text = text.slice(0, maxText) + "…";
283
+ const value = (el.value !== undefined && el.value !== null) ? String(el.value).slice(0, 500) : undefined;
284
+ const href = (el.href !== undefined && el.href !== null) ? String(el.href) : undefined;
285
+ let outerHTML = "";
286
+ try { outerHTML = String(el.outerHTML || ""); } catch {}
287
+ if (maxHtml && outerHTML.length > maxHtml) outerHTML = outerHTML.slice(0, maxHtml) + "…";
288
+ return {
289
+ index: i + 1,
290
+ tag,
291
+ ...(id ? { id } : {}),
292
+ ...(className ? { className } : {}),
293
+ ...(text ? { text } : {}),
294
+ ...(value ? { value } : {}),
295
+ ...(href ? { href } : {}),
296
+ ...(outerHTML ? { outerHTML } : {}),
297
+ };
298
+ });
299
+ })()`;
300
+ const evaluated = await evaluateJavaScript({
301
+ wsUrl: opts.wsUrl,
302
+ expression,
303
+ awaitPromise: true,
304
+ returnByValue: true,
305
+ });
306
+ const matches = evaluated.result?.value;
307
+ return { matches: Array.isArray(matches) ? matches : [] };
308
+ }
309
+ //# sourceMappingURL=cdp.js.map
@@ -0,0 +1,21 @@
1
+ import { type ChildProcessWithoutNullStreams } from "node:child_process";
2
+ import type { ResolvedBrowserConfig, ResolvedBrowserProfile } from "../config.js";
3
+ import { type BrowserExecutable } from "./chrome.executables.js";
4
+ export type { BrowserExecutable } from "./chrome.executables.js";
5
+ export { findChromeExecutableLinux, findChromeExecutableMac, findChromeExecutableWindows, resolveBrowserExecutableForPlatform, } from "./chrome.executables.js";
6
+ export { decorateOpenClawProfile, ensureProfileCleanExit, isProfileDecorated, } from "./chrome.profile-decoration.js";
7
+ export type RunningChrome = {
8
+ pid: number;
9
+ exe: BrowserExecutable;
10
+ userDataDir: string;
11
+ cdpPort: number;
12
+ startedAt: number;
13
+ proc: ChildProcessWithoutNullStreams;
14
+ };
15
+ export declare function resolveUserDataDir(profileName?: string): string;
16
+ export declare function isChromeReachable(cdpUrl: string, timeoutMs?: number): Promise<boolean>;
17
+ export declare function getChromeWebSocketUrl(cdpUrl: string, timeoutMs?: number): Promise<string | null>;
18
+ export declare function isChromeCdpReady(cdpUrl: string, timeoutMs?: number, handshakeTimeoutMs?: number): Promise<boolean>;
19
+ export declare function launchChrome(resolved: ResolvedBrowserConfig, profile: ResolvedBrowserProfile): Promise<RunningChrome>;
20
+ export declare function stopChrome(running: RunningChrome, timeoutMs?: number): Promise<void>;
21
+ //# sourceMappingURL=chrome.d.ts.map
@@ -0,0 +1,10 @@
1
+ import type { ResolvedBrowserConfig } from "../config.js";
2
+ export type BrowserExecutable = {
3
+ kind: "brave" | "canary" | "chromium" | "chrome" | "custom" | "edge";
4
+ path: string;
5
+ };
6
+ export declare function findChromeExecutableMac(): BrowserExecutable | null;
7
+ export declare function findChromeExecutableLinux(): BrowserExecutable | null;
8
+ export declare function findChromeExecutableWindows(): BrowserExecutable | null;
9
+ export declare function resolveBrowserExecutableForPlatform(resolved: ResolvedBrowserConfig, platform: NodeJS.Platform): BrowserExecutable | null;
10
+ //# sourceMappingURL=chrome.executables.d.ts.map