@nodetool-ai/browser 0.8.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 (43) hide show
  1. package/README.md +60 -0
  2. package/dist/.nodetool-build-stamp +1 -0
  3. package/dist/actions.d.ts +64 -0
  4. package/dist/actions.d.ts.map +1 -0
  5. package/dist/actions.js +468 -0
  6. package/dist/actions.js.map +1 -0
  7. package/dist/capture.d.ts +17 -0
  8. package/dist/capture.d.ts.map +1 -0
  9. package/dist/capture.js +95 -0
  10. package/dist/capture.js.map +1 -0
  11. package/dist/cdp-page.d.ts +125 -0
  12. package/dist/cdp-page.d.ts.map +1 -0
  13. package/dist/cdp-page.js +458 -0
  14. package/dist/cdp-page.js.map +1 -0
  15. package/dist/extension/channel.d.ts +28 -0
  16. package/dist/extension/channel.d.ts.map +1 -0
  17. package/dist/extension/channel.js +30 -0
  18. package/dist/extension/channel.js.map +1 -0
  19. package/dist/extension/client.d.ts +129 -0
  20. package/dist/extension/client.d.ts.map +1 -0
  21. package/dist/extension/client.js +352 -0
  22. package/dist/extension/client.js.map +1 -0
  23. package/dist/extension/page.d.ts +38 -0
  24. package/dist/extension/page.d.ts.map +1 -0
  25. package/dist/extension/page.js +50 -0
  26. package/dist/extension/page.js.map +1 -0
  27. package/dist/extension/protocol.d.ts +162 -0
  28. package/dist/extension/protocol.d.ts.map +1 -0
  29. package/dist/extension/protocol.js +45 -0
  30. package/dist/extension/protocol.js.map +1 -0
  31. package/dist/index.d.ts +30 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +30 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/schemas.d.ts +698 -0
  36. package/dist/schemas.d.ts.map +1 -0
  37. package/dist/schemas.js +262 -0
  38. package/dist/schemas.js.map +1 -0
  39. package/dist/upload.d.ts +24 -0
  40. package/dist/upload.d.ts.map +1 -0
  41. package/dist/upload.js +144 -0
  42. package/dist/upload.js.map +1 -0
  43. package/package.json +66 -0
@@ -0,0 +1,95 @@
1
+ /**
2
+ * In-page media capture for browser tools.
3
+ *
4
+ * Reads a `blob:`/`<video>`/`<audio>`/`<img>` source from the page, fetches it
5
+ * to an ArrayBuffer inside the page context, and returns base64 bytes plus the
6
+ * resolved MIME type. This is the universally-available rung of the capture
7
+ * ladder (it uses only `CdpPage.evaluate`).
8
+ */
9
+ /**
10
+ * Resolve the source URL for an indexed element (a media element previously
11
+ * tagged with `data-nt-idx` by browser_view), preferring `currentSrc` so the
12
+ * actually-loaded resolution variant is captured.
13
+ */
14
+ async function resolveElementSource(page, index, mediaType) {
15
+ return page.evaluate((idx, _kind) => {
16
+ const el = document.querySelector(`[data-nt-idx="${idx}"]`);
17
+ if (!el)
18
+ return null;
19
+ const media = el;
20
+ const src = media.currentSrc || media.src || el.getAttribute("src");
21
+ if (src)
22
+ return src;
23
+ // Fall back to a nested media/source element (e.g. <video><source>).
24
+ const nested = el.querySelector("video, audio, img, source");
25
+ if (!nested)
26
+ return null;
27
+ return (nested.currentSrc ||
28
+ nested.src ||
29
+ nested.getAttribute("src"));
30
+ }, index, mediaType ?? null);
31
+ }
32
+ /** Default MIME when the source declares none, biased by the caller's hint. */
33
+ function fallbackMime(mediaType) {
34
+ if (mediaType === "video")
35
+ return "video/mp4";
36
+ if (mediaType === "audio")
37
+ return "audio/mpeg";
38
+ if (mediaType === "image")
39
+ return "image/png";
40
+ return "application/octet-stream";
41
+ }
42
+ /**
43
+ * Fetch a URL inside the page to an ArrayBuffer and return base64 + MIME.
44
+ * Runs in the page so `blob:` URLs and same-origin credentials resolve.
45
+ */
46
+ async function fetchToBase64(page, url) {
47
+ return page.evaluate(async (target) => {
48
+ const res = await fetch(target, { credentials: "include" });
49
+ if (!res.ok) {
50
+ throw new Error(`fetch ${target} failed: HTTP ${res.status}`);
51
+ }
52
+ const buf = await res.arrayBuffer();
53
+ const view = new Uint8Array(buf);
54
+ // Base64-encode in chunks so a large buffer never overflows the call stack
55
+ // via String.fromCharCode(...spread).
56
+ let binary = "";
57
+ const CHUNK = 0x8000;
58
+ for (let i = 0; i < view.length; i += CHUNK) {
59
+ binary += String.fromCharCode(...view.subarray(i, i + CHUNK));
60
+ }
61
+ return {
62
+ base64: btoa(binary),
63
+ mime: res.headers.get("content-type")?.split(";")[0]?.trim() || "",
64
+ sourceUrl: target
65
+ };
66
+ }, url);
67
+ }
68
+ /**
69
+ * Capture media via the in-page `fetch()` rung.
70
+ *
71
+ * @throws if no source URL can be resolved or the fetch fails.
72
+ */
73
+ export async function captureMediaInPage(page, input) {
74
+ let url = input.url ?? input.resource_url ?? null;
75
+ if (input.index !== undefined) {
76
+ url = await resolveElementSource(page, input.index, input.media_type);
77
+ if (!url) {
78
+ throw new Error(`No media source found on element index ${input.index}`);
79
+ }
80
+ }
81
+ if (!url) {
82
+ throw new Error("No media URL to capture");
83
+ }
84
+ const result = await fetchToBase64(page, url);
85
+ if (!result || !result.base64) {
86
+ throw new Error(`Failed to capture media from ${url}`);
87
+ }
88
+ return {
89
+ media_b64: result.base64,
90
+ mime_type: result.mime || fallbackMime(input.media_type),
91
+ source_url: result.sourceUrl,
92
+ via: "in_page_fetch"
93
+ };
94
+ }
95
+ //# sourceMappingURL=capture.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"capture.js","sourceRoot":"","sources":["../src/capture.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAeH;;;;GAIG;AACH,KAAK,UAAU,oBAAoB,CACjC,IAAa,EACb,KAAa,EACb,SAAiD;IAEjD,OAAO,IAAI,CAAC,QAAQ,CAClB,CAAC,GAAW,EAAE,KAAoB,EAAE,EAAE;QACpC,MAAM,EAAE,GAAG,QAAQ,CAAC,aAAa,CAC/B,iBAAiB,GAAG,IAAI,CACzB,CAAC;QACF,IAAI,CAAC,EAAE;YAAE,OAAO,IAAI,CAAC;QACrB,MAAM,KAAK,GAAG,EAAyC,CAAC;QACxD,MAAM,GAAG,GAAG,KAAK,CAAC,UAAU,IAAI,KAAK,CAAC,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E,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,gCAAgC,GAAG,EAAE,CAAC,CAAC;IACzD,CAAC;IACD,OAAO;QACL,SAAS,EAAE,MAAM,CAAC,MAAM;QACxB,SAAS,EAAE,MAAM,CAAC,IAAI,IAAI,YAAY,CAAC,KAAK,CAAC,UAAU,CAAC;QACxD,UAAU,EAAE,MAAM,CAAC,SAAS;QAC5B,GAAG,EAAE,eAAe;KACrB,CAAC;AACJ,CAAC"}
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Minimal Page-like wrapper around the Chrome DevTools Protocol.
3
+ *
4
+ * Replaces the small subset of the Playwright API used by lib-browser nodes.
5
+ * Backed by `chrome-launcher` (to start Chrome) and `chrome-remote-interface`
6
+ * (to speak CDP). Designed to be lazy-loaded so installing Chrome is only
7
+ * required when a browser node actually runs.
8
+ */
9
+ import type { LaunchedChrome } from "chrome-launcher";
10
+ type CDPClient = any;
11
+ export interface LaunchOptions {
12
+ /** Existing CDP endpoint port. If set, a Chrome instance is not launched. */
13
+ port?: number;
14
+ extraFlags?: string[];
15
+ viewport?: {
16
+ width: number;
17
+ height: number;
18
+ };
19
+ }
20
+ export type WaitUntil = "load" | "domcontentloaded" | "networkidle";
21
+ interface ConsoleHandler {
22
+ (msg: {
23
+ type: string;
24
+ text: string;
25
+ }): void;
26
+ }
27
+ /** A function shipped into the page context and called through CDP. */
28
+ type PageFunction = (...args: never[]) => unknown;
29
+ export declare class CdpPage {
30
+ private client;
31
+ private currentUrl;
32
+ private currentTitle;
33
+ private viewport;
34
+ private consoleHandlers;
35
+ private lastNavStatus;
36
+ constructor(client: CDPClient, viewport: {
37
+ width: number;
38
+ height: number;
39
+ });
40
+ static create(client: CDPClient, viewport: {
41
+ width: number;
42
+ height: number;
43
+ }): Promise<CdpPage>;
44
+ url(): string;
45
+ viewportSize(): {
46
+ width: number;
47
+ height: number;
48
+ };
49
+ on(event: "console", handler: ConsoleHandler): void;
50
+ title(): Promise<string>;
51
+ /**
52
+ * Wait for a one-shot CDP page event. chrome-remote-interface's domain
53
+ * namespace methods (`client.Page.loadEventFired(fn)`) subscribe and
54
+ * return an unsubscribe function — there is no `.once()` like Playwright.
55
+ * This helper subscribes, resolves on the first emission, and unsubscribes.
56
+ */
57
+ private waitForLoadEvent;
58
+ goto(url: string, opts?: {
59
+ waitUntil?: WaitUntil;
60
+ timeout?: number;
61
+ }): Promise<{
62
+ status: number | null;
63
+ }>;
64
+ reload(opts?: {
65
+ waitUntil?: WaitUntil;
66
+ timeout?: number;
67
+ }): Promise<void>;
68
+ goBack(opts?: {
69
+ timeout?: number;
70
+ waitUntil?: WaitUntil;
71
+ }): Promise<void>;
72
+ goForward(opts?: {
73
+ timeout?: number;
74
+ waitUntil?: WaitUntil;
75
+ }): Promise<void>;
76
+ private historyNav;
77
+ content(): Promise<string>;
78
+ /**
79
+ * Run a function in the page context with arguments marshalled out-of-band
80
+ * via CDP's `Runtime.callFunctionOn`. Argument values are passed in the
81
+ * `arguments` array (serialised by the protocol) and never concatenated into
82
+ * source, so untrusted strings cannot escape into executable code.
83
+ */
84
+ private callFn;
85
+ evaluate<T = unknown>(fnOrExpr: string | PageFunction, ...args: unknown[]): Promise<T>;
86
+ waitForSelector(selector: string, opts?: {
87
+ timeout?: number;
88
+ }): Promise<{
89
+ exists: true;
90
+ }>;
91
+ click(selector: string): Promise<void>;
92
+ fill(selector: string, text: string): Promise<void>;
93
+ press(selector: string, key: string): Promise<void>;
94
+ selectOption(selector: string, value: string): Promise<string[]>;
95
+ /**
96
+ * Native file-input injection: resolve the `<input type="file">` matched by
97
+ * `selector` to a CDP nodeId and hand Chrome real filesystem paths via
98
+ * `DOM.setFileInputFiles`. The paths must exist on the machine running this
99
+ * Chrome instance (host process for local Chrome, container for the sandbox);
100
+ * when no such path is reachable — e.g. the extension transport driving the
101
+ * user's own machine from the server — callers fall back to an in-page
102
+ * DataTransfer injection instead.
103
+ */
104
+ setFileInputFiles(selector: string, files: string[]): Promise<void>;
105
+ screenshot(opts?: {
106
+ fullPage?: boolean;
107
+ }): Promise<Buffer>;
108
+ screenshotOfElement(selector: string): Promise<Buffer>;
109
+ readonly mouse: {
110
+ move: (x: number, y: number) => Promise<void>;
111
+ click: (x: number, y: number) => Promise<void>;
112
+ };
113
+ readonly keyboard: {
114
+ type: (text: string) => Promise<void>;
115
+ press: (key: string) => Promise<void>;
116
+ };
117
+ }
118
+ export declare function launchBrowser(opts?: LaunchOptions): Promise<{
119
+ client: CDPClient;
120
+ chrome: LaunchedChrome | null;
121
+ close: () => Promise<void>;
122
+ }>;
123
+ export declare function withPage<T>(opts: LaunchOptions, fn: (page: CdpPage) => Promise<T>): Promise<T>;
124
+ export {};
125
+ //# sourceMappingURL=cdp-page.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cdp-page.d.ts","sourceRoot":"","sources":["../src/cdp-page.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAEtD,KAAK,SAAS,GAAG,GAAG,CAAC;AAcrB,MAAM,WAAW,aAAa;IAC5B,6EAA6E;IAC7E,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,QAAQ,CAAC,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;CAC9C;AAED,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,kBAAkB,GAAG,aAAa,CAAC;AAEpE,UAAU,cAAc;IACtB,CAAC,GAAG,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;CAC7C;AAED,uEAAuE;AACvE,KAAK,YAAY,GAAG,CAAC,GAAG,IAAI,EAAE,KAAK,EAAE,KAAK,OAAO,CAAC;AAclD,qBAAa,OAAO;IAON,OAAO,CAAC,MAAM;IAN1B,OAA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iB3D;IAED,QAAQ,CAAC,KAAK;QACZ,IAAI,MAAY,MAAM,KAAK,MAAM,KAAG,OAAO,CAAC,IAAI,CAAC;QAGjD,KAAK,MAAY,MAAM,KAAK,MAAM,KAAG,OAAO,CAAC,IAAI,CAAC;MAgBlD;IAEF,QAAQ,CAAC,QAAQ;QACf,IAAI,SAAe,MAAM,KAAG,OAAO,CAAC,IAAI,CAAC;QAKzC,KAAK,QAAc,MAAM,KAAG,OAAO,CAAC,IAAI,CAAC;MAgBzC;CACH;AAuED,wBAAsB,aAAa,CAAC,IAAI,GAAE,aAAkB,GAAG,OAAO,CAAC;IACrE,MAAM,EAAE,SAAS,CAAC;IAClB,MAAM,EAAE,cAAc,GAAG,IAAI,CAAC;IAC9B,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5B,CAAC,CA+CD;AAED,wBAAsB,QAAQ,CAAC,CAAC,EAC9B,IAAI,EAAE,aAAa,EACnB,EAAE,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,OAAO,CAAC,CAAC,CAAC,GAChC,OAAO,CAAC,CAAC,CAAC,CAQZ"}
@@ -0,0 +1,458 @@
1
+ /**
2
+ * Minimal Page-like wrapper around the Chrome DevTools Protocol.
3
+ *
4
+ * Replaces the small subset of the Playwright API used by lib-browser nodes.
5
+ * Backed by `chrome-launcher` (to start Chrome) and `chrome-remote-interface`
6
+ * (to speak CDP). Designed to be lazy-loaded so installing Chrome is only
7
+ * required when a browser node actually runs.
8
+ */
9
+ const DEFAULT_FLAGS = [
10
+ "--headless=new",
11
+ "--disable-gpu",
12
+ "--no-sandbox",
13
+ "--disable-setuid-sandbox",
14
+ "--disable-dev-shm-usage",
15
+ "--disable-software-rasterizer",
16
+ "--hide-scrollbars",
17
+ "--mute-audio",
18
+ "--window-size=1280,900"
19
+ ];
20
+ export class CdpPage {
21
+ client;
22
+ currentUrl = "about:blank";
23
+ currentTitle = "";
24
+ viewport;
25
+ consoleHandlers = [];
26
+ lastNavStatus = null;
27
+ constructor(client, viewport) {
28
+ this.client = client;
29
+ this.viewport = viewport;
30
+ }
31
+ static async create(client, viewport) {
32
+ const { Page, Runtime, Network, DOM, Console } = client;
33
+ await Promise.all([
34
+ Page.enable(),
35
+ Runtime.enable(),
36
+ Network.enable(),
37
+ DOM.enable(),
38
+ Console.enable?.()
39
+ ]);
40
+ const page = new CdpPage(client, viewport);
41
+ Runtime.consoleAPICalled((evt) => {
42
+ const text = (evt.args ?? [])
43
+ .map((a) => (a.value !== undefined ? String(a.value) : (a.description ?? "")))
44
+ .join(" ");
45
+ const type = evt.type ?? "log";
46
+ for (const h of page.consoleHandlers)
47
+ h({ type, text });
48
+ });
49
+ Network.responseReceived((evt) => {
50
+ if (evt.type === "Document") {
51
+ page.lastNavStatus = evt.response?.status ?? null;
52
+ }
53
+ });
54
+ return page;
55
+ }
56
+ url() {
57
+ return this.currentUrl;
58
+ }
59
+ viewportSize() {
60
+ return this.viewport;
61
+ }
62
+ on(event, handler) {
63
+ if (event === "console")
64
+ this.consoleHandlers.push(handler);
65
+ }
66
+ async title() {
67
+ const r = await this.client.Runtime.evaluate({
68
+ expression: "document.title",
69
+ returnByValue: true
70
+ });
71
+ return r.result?.value ?? this.currentTitle;
72
+ }
73
+ /**
74
+ * Wait for a one-shot CDP page event. chrome-remote-interface's domain
75
+ * namespace methods (`client.Page.loadEventFired(fn)`) subscribe and
76
+ * return an unsubscribe function — there is no `.once()` like Playwright.
77
+ * This helper subscribes, resolves on the first emission, and unsubscribes.
78
+ */
79
+ waitForLoadEvent(waitUntil, timeout, label) {
80
+ if (waitUntil === "networkidle") {
81
+ return waitForNetworkIdle(this.client, timeout);
82
+ }
83
+ const eventName = waitUntil === "domcontentloaded" ? "domContentEventFired" : "loadEventFired";
84
+ return new Promise((resolve, reject) => {
85
+ let off = null;
86
+ const t = setTimeout(() => {
87
+ off?.();
88
+ reject(new Error(`Timed out after ${timeout}ms ${label}`));
89
+ }, timeout);
90
+ off = this.client.Page[eventName](() => {
91
+ clearTimeout(t);
92
+ off?.();
93
+ resolve();
94
+ });
95
+ });
96
+ }
97
+ async goto(url, opts = {}) {
98
+ const waitUntil = opts.waitUntil ?? "load";
99
+ const timeout = opts.timeout ?? 30000;
100
+ this.lastNavStatus = null;
101
+ const loadPromise = this.waitForLoadEvent(waitUntil, timeout, `loading ${url}`);
102
+ await this.client.Page.navigate({ url });
103
+ await loadPromise;
104
+ this.currentUrl = url;
105
+ return { status: this.lastNavStatus };
106
+ }
107
+ async reload(opts = {}) {
108
+ const waitUntil = opts.waitUntil ?? "load";
109
+ const timeout = opts.timeout ?? 30000;
110
+ const loadPromise = this.waitForLoadEvent(waitUntil, timeout, "reloading");
111
+ await this.client.Page.reload({});
112
+ await loadPromise;
113
+ }
114
+ async goBack(opts = {}) {
115
+ await this.historyNav(-1, opts);
116
+ }
117
+ async goForward(opts = {}) {
118
+ await this.historyNav(1, opts);
119
+ }
120
+ async historyNav(delta, opts) {
121
+ const history = await this.client.Page.getNavigationHistory();
122
+ const idx = history.currentIndex + delta;
123
+ const entry = history.entries[idx];
124
+ if (!entry)
125
+ return;
126
+ await this.goto(entry.url, opts);
127
+ }
128
+ async content() {
129
+ const r = await this.client.Runtime.evaluate({
130
+ expression: "document.documentElement.outerHTML",
131
+ returnByValue: true
132
+ });
133
+ return r.result?.value ?? "";
134
+ }
135
+ /**
136
+ * Run a function in the page context with arguments marshalled out-of-band
137
+ * via CDP's `Runtime.callFunctionOn`. Argument values are passed in the
138
+ * `arguments` array (serialised by the protocol) and never concatenated into
139
+ * source, so untrusted strings cannot escape into executable code.
140
+ */
141
+ async callFn(fn, ...args) {
142
+ const Runtime = this.client.Runtime;
143
+ const globalRef = await Runtime.evaluate({ expression: "globalThis" });
144
+ const objectId = globalRef.result?.objectId;
145
+ if (!objectId) {
146
+ throw new Error("Failed to obtain global object reference");
147
+ }
148
+ try {
149
+ const r = await Runtime.callFunctionOn({
150
+ objectId,
151
+ functionDeclaration: fn.toString(),
152
+ arguments: args.map((value) => ({ value })),
153
+ returnByValue: true,
154
+ awaitPromise: true,
155
+ userGesture: true
156
+ });
157
+ if (r.exceptionDetails) {
158
+ throw new Error(r.exceptionDetails.exception?.description ??
159
+ r.exceptionDetails.text ??
160
+ "evaluation failed");
161
+ }
162
+ return r.result?.value;
163
+ }
164
+ finally {
165
+ try {
166
+ await Runtime.releaseObject({ objectId });
167
+ }
168
+ catch {
169
+ // ignore
170
+ }
171
+ }
172
+ }
173
+ async evaluate(fnOrExpr, ...args) {
174
+ if (typeof fnOrExpr === "function") {
175
+ return this.callFn(fnOrExpr, ...args);
176
+ }
177
+ const r = await this.client.Runtime.evaluate({
178
+ expression: `(async () => { return (${fnOrExpr}); })()`,
179
+ returnByValue: true,
180
+ awaitPromise: true,
181
+ userGesture: true
182
+ });
183
+ if (r.exceptionDetails) {
184
+ throw new Error(r.exceptionDetails.exception?.description ??
185
+ r.exceptionDetails.text ??
186
+ "evaluation failed");
187
+ }
188
+ return r.result?.value;
189
+ }
190
+ async waitForSelector(selector, opts = {}) {
191
+ const timeout = opts.timeout ?? 30000;
192
+ const start = Date.now();
193
+ while (Date.now() - start < timeout) {
194
+ const found = await this.callFn((sel) => !!document.querySelector(sel), selector);
195
+ if (found)
196
+ return { exists: true };
197
+ await new Promise((r) => setTimeout(r, 100));
198
+ }
199
+ throw new Error(`Timed out waiting for selector: ${selector}`);
200
+ }
201
+ async click(selector) {
202
+ const ok = await this.callFn((sel) => {
203
+ const el = document.querySelector(sel);
204
+ if (!el)
205
+ return false;
206
+ el.scrollIntoView({ block: "center" });
207
+ el.click();
208
+ return true;
209
+ }, selector);
210
+ if (!ok)
211
+ throw new Error(`Element not found: ${selector}`);
212
+ }
213
+ async fill(selector, text) {
214
+ const ok = await this.callFn((sel, val) => {
215
+ const el = document.querySelector(sel);
216
+ if (!el)
217
+ return false;
218
+ el.focus();
219
+ el.value = val;
220
+ el.dispatchEvent(new Event("input", { bubbles: true }));
221
+ el.dispatchEvent(new Event("change", { bubbles: true }));
222
+ return true;
223
+ }, selector, text);
224
+ if (!ok)
225
+ throw new Error(`Element not found: ${selector}`);
226
+ }
227
+ async press(selector, key) {
228
+ await this.click(selector);
229
+ await this.keyboard.press(key);
230
+ }
231
+ async selectOption(selector, value) {
232
+ const out = await this.callFn((sel, val) => {
233
+ const el = document.querySelector(sel);
234
+ if (!el)
235
+ return null;
236
+ el.value = val;
237
+ el.dispatchEvent(new Event("change", { bubbles: true }));
238
+ return [el.value];
239
+ }, selector, value);
240
+ if (!out)
241
+ throw new Error(`Element not found: ${selector}`);
242
+ return out;
243
+ }
244
+ /**
245
+ * Native file-input injection: resolve the `<input type="file">` matched by
246
+ * `selector` to a CDP nodeId and hand Chrome real filesystem paths via
247
+ * `DOM.setFileInputFiles`. The paths must exist on the machine running this
248
+ * Chrome instance (host process for local Chrome, container for the sandbox);
249
+ * when no such path is reachable — e.g. the extension transport driving the
250
+ * user's own machine from the server — callers fall back to an in-page
251
+ * DataTransfer injection instead.
252
+ */
253
+ async setFileInputFiles(selector, files) {
254
+ const { root } = await this.client.DOM.getDocument({ depth: 0 });
255
+ const { nodeId } = await this.client.DOM.querySelector({
256
+ nodeId: root.nodeId,
257
+ selector
258
+ });
259
+ if (!nodeId)
260
+ throw new Error(`Element not found: ${selector}`);
261
+ await this.client.DOM.setFileInputFiles({ files, nodeId });
262
+ }
263
+ async screenshot(opts = {}) {
264
+ const { data } = await this.client.Page.captureScreenshot({
265
+ format: "png",
266
+ captureBeyondViewport: opts.fullPage ?? false
267
+ });
268
+ return Buffer.from(data, "base64");
269
+ }
270
+ async screenshotOfElement(selector) {
271
+ const rect = await this.callFn((sel) => {
272
+ const el = document.querySelector(sel);
273
+ if (!el)
274
+ return null;
275
+ el.scrollIntoView({ block: "center" });
276
+ const r = el.getBoundingClientRect();
277
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
278
+ }, selector);
279
+ if (!rect)
280
+ throw new Error(`Element not found: ${selector}`);
281
+ const { data } = await this.client.Page.captureScreenshot({
282
+ format: "png",
283
+ clip: { x: rect.x, y: rect.y, width: rect.width, height: rect.height, scale: 1 }
284
+ });
285
+ return Buffer.from(data, "base64");
286
+ }
287
+ mouse = {
288
+ move: async (x, y) => {
289
+ await this.client.Input.dispatchMouseEvent({ type: "mouseMoved", x, y });
290
+ },
291
+ click: async (x, y) => {
292
+ await this.client.Input.dispatchMouseEvent({
293
+ type: "mousePressed",
294
+ x,
295
+ y,
296
+ button: "left",
297
+ clickCount: 1
298
+ });
299
+ await this.client.Input.dispatchMouseEvent({
300
+ type: "mouseReleased",
301
+ x,
302
+ y,
303
+ button: "left",
304
+ clickCount: 1
305
+ });
306
+ }
307
+ };
308
+ keyboard = {
309
+ type: async (text) => {
310
+ for (const ch of text) {
311
+ await this.client.Input.dispatchKeyEvent({ type: "char", text: ch });
312
+ }
313
+ },
314
+ press: async (key) => {
315
+ const code = mapKey(key);
316
+ await this.client.Input.dispatchKeyEvent({
317
+ type: "keyDown",
318
+ key: code.key,
319
+ code: code.code,
320
+ windowsVirtualKeyCode: code.vk,
321
+ text: code.text
322
+ });
323
+ await this.client.Input.dispatchKeyEvent({
324
+ type: "keyUp",
325
+ key: code.key,
326
+ code: code.code,
327
+ windowsVirtualKeyCode: code.vk
328
+ });
329
+ }
330
+ };
331
+ }
332
+ async function waitForNetworkIdle(client, timeout) {
333
+ return new Promise((resolve, reject) => {
334
+ let inflight = 0;
335
+ let idleTimer = null;
336
+ const onLoad = () => {
337
+ if (inflight === 0)
338
+ armIdle();
339
+ };
340
+ const onReq = () => {
341
+ inflight++;
342
+ if (idleTimer) {
343
+ clearTimeout(idleTimer);
344
+ idleTimer = null;
345
+ }
346
+ };
347
+ const onDone = () => {
348
+ inflight = Math.max(0, inflight - 1);
349
+ if (inflight === 0)
350
+ armIdle();
351
+ };
352
+ // Subscribe first so the unsubscribers exist before any timer can fire.
353
+ const offLoad = client.Page.loadEventFired(onLoad);
354
+ const offReq = client.Network.requestWillBeSent(onReq);
355
+ const offFinished = client.Network.loadingFinished(onDone);
356
+ const offFailed = client.Network.loadingFailed(onDone);
357
+ const cleanup = () => {
358
+ clearTimeout(overall);
359
+ if (idleTimer)
360
+ clearTimeout(idleTimer);
361
+ offLoad?.();
362
+ offReq?.();
363
+ offFinished?.();
364
+ offFailed?.();
365
+ };
366
+ const armIdle = () => {
367
+ if (idleTimer)
368
+ clearTimeout(idleTimer);
369
+ idleTimer = setTimeout(() => {
370
+ cleanup();
371
+ resolve();
372
+ }, 500);
373
+ };
374
+ const overall = setTimeout(() => {
375
+ cleanup();
376
+ reject(new Error(`Timed out after ${timeout}ms waiting for network idle`));
377
+ }, timeout);
378
+ armIdle();
379
+ });
380
+ }
381
+ function mapKey(key) {
382
+ const map = {
383
+ Enter: { key: "Enter", code: "Enter", vk: 13, text: "\r" },
384
+ Tab: { key: "Tab", code: "Tab", vk: 9 },
385
+ Escape: { key: "Escape", code: "Escape", vk: 27 },
386
+ Backspace: { key: "Backspace", code: "Backspace", vk: 8 },
387
+ ArrowLeft: { key: "ArrowLeft", code: "ArrowLeft", vk: 37 },
388
+ ArrowUp: { key: "ArrowUp", code: "ArrowUp", vk: 38 },
389
+ ArrowRight: { key: "ArrowRight", code: "ArrowRight", vk: 39 },
390
+ ArrowDown: { key: "ArrowDown", code: "ArrowDown", vk: 40 },
391
+ Space: { key: " ", code: "Space", vk: 32, text: " " }
392
+ };
393
+ if (map[key])
394
+ return map[key];
395
+ if (key.length === 1) {
396
+ return { key, code: `Key${key.toUpperCase()}`, vk: key.toUpperCase().charCodeAt(0), text: key };
397
+ }
398
+ return { key, code: key, vk: 0 };
399
+ }
400
+ export async function launchBrowser(opts = {}) {
401
+ const viewport = opts.viewport ?? { width: 1280, height: 900 };
402
+ let chrome = null;
403
+ let port = opts.port;
404
+ if (!port) {
405
+ const { launch } = await import("chrome-launcher");
406
+ const flags = [...DEFAULT_FLAGS];
407
+ if (opts.extraFlags)
408
+ flags.push(...opts.extraFlags);
409
+ chrome = await launch({
410
+ chromeFlags: flags,
411
+ ignoreDefaultFlags: false,
412
+ // Honor CHROME_PATH when set (sandbox container points at
413
+ // /usr/bin/chromium); otherwise fall back to chrome-launcher's own
414
+ // platform-aware discovery for local dev.
415
+ chromePath: process.env.CHROME_PATH || undefined
416
+ });
417
+ port = chrome.port;
418
+ }
419
+ const CDPMod = (await import("chrome-remote-interface")).default;
420
+ const client = await CDPMod({ port });
421
+ await client.Emulation.setDeviceMetricsOverride({
422
+ width: viewport.width,
423
+ height: viewport.height,
424
+ deviceScaleFactor: 1,
425
+ mobile: false
426
+ });
427
+ return {
428
+ client,
429
+ chrome,
430
+ close: async () => {
431
+ try {
432
+ await client.close();
433
+ }
434
+ catch {
435
+ // ignore
436
+ }
437
+ if (chrome) {
438
+ try {
439
+ await chrome.kill();
440
+ }
441
+ catch {
442
+ // ignore
443
+ }
444
+ }
445
+ }
446
+ };
447
+ }
448
+ export async function withPage(opts, fn) {
449
+ const session = await launchBrowser(opts);
450
+ try {
451
+ const page = await CdpPage.create(session.client, opts.viewport ?? { width: 1280, height: 900 });
452
+ return await fn(page);
453
+ }
454
+ finally {
455
+ await session.close();
456
+ }
457
+ }
458
+ //# sourceMappingURL=cdp-page.js.map