@howaboua/pi-browser 0.0.11 → 0.0.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/README.md +8 -0
- package/dist/extension.d.ts +3 -0
- package/dist/extension.js +29 -0
- package/dist/index.d.ts +1 -2
- package/dist/index.js +1 -101
- package/dist/remote-worker.js +132 -111
- package/dist/src/browser/config.d.ts +2 -0
- package/dist/src/browser/config.js +38 -5
- package/dist/src/browser/voice-start.d.ts +16 -0
- package/dist/src/browser/voice-start.js +110 -0
- package/dist/src/browser-registration.d.ts +6 -0
- package/dist/src/browser-registration.js +103 -0
- package/dist/src/browser-tool-definition.d.ts +12 -0
- package/dist/src/browser-tool-definition.js +63 -0
- package/dist/src/browser-tool.d.ts +1 -4
- package/dist/src/browser-tool.js +2 -62
- package/dist/src/cdp/session.d.ts +3 -8
- package/dist/src/cdp/session.js +1 -104
- package/dist/src/cdp/snapshot-tree.d.ts +8 -0
- package/dist/src/cdp/snapshot-tree.js +238 -0
- package/dist/src/cdp/snapshot.js +2 -234
- package/dist/src/cdp/tab-bridge.d.ts +25 -0
- package/dist/src/cdp/tab-bridge.js +107 -0
- package/extension.ts +35 -0
- package/index.ts +1 -128
- package/package.json +9 -4
- package/src/browser/config.ts +48 -7
- package/src/browser/voice-start.ts +154 -0
- package/src/browser-registration.ts +138 -0
- package/src/browser-tool-definition.ts +81 -0
- package/src/browser-tool.ts +3 -69
- package/src/cdp/session.ts +3 -145
- package/src/cdp/snapshot-tree.ts +291 -0
- package/src/cdp/snapshot.ts +5 -282
- package/src/cdp/tab-bridge.ts +149 -0
- package/tsconfig.json +1 -1
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { sleep } from "../cdp/discovery.js";
|
|
2
|
+
import { asRecord, errorMessage } from "../cdp/types.js";
|
|
3
|
+
import { assertHttpUrl } from "../cdp/url.js";
|
|
4
|
+
import { BrowserRuntime } from "./runtime.js";
|
|
5
|
+
// Read the bundled frontends' acknowledged audio state, not socket connectivity
|
|
6
|
+
// or the fact that a click was dispatched. No permissions or trust are changed.
|
|
7
|
+
const CONVERSATION_STATE = String.raw `(() => {
|
|
8
|
+
const button = document.querySelector('#voice');
|
|
9
|
+
const status = document.querySelector('#audio-state')?.textContent?.trim() || '';
|
|
10
|
+
const detail = document.querySelector('#audio-detail')?.textContent?.trim() || '';
|
|
11
|
+
const listening = button?.dataset.mode === 'conversation' && button?.getAttribute('aria-pressed') === 'true' && status === 'Listening';
|
|
12
|
+
const failed = ['Could not start', 'Voice disconnected', 'Could not reconnect', 'Moved to another device', 'Transferred session ended', 'Microphone muted'].includes(status);
|
|
13
|
+
return {state: listening ? 'listening' : failed ? 'error' : button && !button.disabled && button.getAttribute('aria-busy') !== 'true' && button.getAttribute('aria-pressed') !== 'true' && button.dataset.mode === 'conversation' ? 'ready' : 'waiting', status, detail};
|
|
14
|
+
})()`;
|
|
15
|
+
const GROK_STATE = String.raw `(() => {
|
|
16
|
+
const button = document.querySelector('#start');
|
|
17
|
+
const status = document.querySelector('#status')?.textContent?.trim() || '';
|
|
18
|
+
const detail = document.querySelector('#error')?.textContent?.trim() || '';
|
|
19
|
+
const mode = document.querySelector('#mode')?.value;
|
|
20
|
+
const muted = document.querySelector('#mute')?.getAttribute('aria-pressed') === 'true';
|
|
21
|
+
const listening = !muted && mode === 'voice' && /^listening(?: ·|$)/.test(status) && status.includes(' · browser microphone connected');
|
|
22
|
+
return {state: detail || muted ? 'error' : listening ? 'listening' : button && !button.disabled && mode === 'voice' ? 'ready' : 'waiting', status, detail: muted ? 'Microphone is muted. Unmute it in the voice page.' : detail};
|
|
23
|
+
})()`;
|
|
24
|
+
function pageState(result) {
|
|
25
|
+
if (typeof result["value"] !== "string")
|
|
26
|
+
throw new Error("Voice page did not return its audio status");
|
|
27
|
+
const value = asRecord(JSON.parse(result["value"]), "Voice page status");
|
|
28
|
+
const state = value["state"];
|
|
29
|
+
if ((state !== "listening" &&
|
|
30
|
+
state !== "ready" &&
|
|
31
|
+
state !== "waiting" &&
|
|
32
|
+
state !== "error") ||
|
|
33
|
+
typeof value["status"] !== "string" ||
|
|
34
|
+
typeof value["detail"] !== "string")
|
|
35
|
+
throw new Error("Voice page returned an invalid audio status");
|
|
36
|
+
return { state, status: value["status"], detail: value["detail"] };
|
|
37
|
+
}
|
|
38
|
+
/** Start once in a new tab; disconnect automation without closing the tab. */
|
|
39
|
+
export async function startBrowserVoice(options) {
|
|
40
|
+
const timeoutMs = options.timeoutMs ?? 30_000;
|
|
41
|
+
if (!Number.isInteger(timeoutMs) ||
|
|
42
|
+
timeoutMs <= 0 ||
|
|
43
|
+
timeoutMs > 2_147_483_647)
|
|
44
|
+
throw new Error("Voice browser timeout must fit a positive signed 32-bit millisecond timer");
|
|
45
|
+
assertHttpUrl(options.url);
|
|
46
|
+
if (!["codex", "gippity", "grok"].includes(options.provider))
|
|
47
|
+
throw new Error("Unsupported voice page provider");
|
|
48
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
49
|
+
const signal = options.signal
|
|
50
|
+
? AbortSignal.any([options.signal, timeout])
|
|
51
|
+
: timeout;
|
|
52
|
+
let runtime;
|
|
53
|
+
let refId;
|
|
54
|
+
let observed = { state: "waiting", status: "", detail: "" };
|
|
55
|
+
let clicked = false;
|
|
56
|
+
const result = (state, detail = observed.detail) => ({
|
|
57
|
+
state,
|
|
58
|
+
url: options.url,
|
|
59
|
+
...(refId ? { refId } : {}),
|
|
60
|
+
status: observed.status,
|
|
61
|
+
detail,
|
|
62
|
+
});
|
|
63
|
+
try {
|
|
64
|
+
const browser = new BrowserRuntime();
|
|
65
|
+
runtime = browser;
|
|
66
|
+
const execute = (operation) => browser.execute({
|
|
67
|
+
operations: [operation],
|
|
68
|
+
...(options.host ? { host: options.host } : {}),
|
|
69
|
+
}, { signal });
|
|
70
|
+
const opened = await execute({ action: "open", url: options.url });
|
|
71
|
+
if (opened["owned"] !== true || typeof opened["ref_id"] !== "string")
|
|
72
|
+
throw new Error("Browser did not confirm ownership of the new voice tab");
|
|
73
|
+
refId = opened["ref_id"];
|
|
74
|
+
await execute({
|
|
75
|
+
action: "wait",
|
|
76
|
+
ref_id: refId,
|
|
77
|
+
selector: options.provider === "grok" ? "#start" : "#voice",
|
|
78
|
+
timeout_ms: timeoutMs,
|
|
79
|
+
});
|
|
80
|
+
while (true) {
|
|
81
|
+
signal.throwIfAborted();
|
|
82
|
+
observed = pageState(await execute({
|
|
83
|
+
action: "evaluate",
|
|
84
|
+
ref_id: refId,
|
|
85
|
+
expression: options.provider === "grok" ? GROK_STATE : CONVERSATION_STATE,
|
|
86
|
+
}));
|
|
87
|
+
if (observed.state === "listening")
|
|
88
|
+
return result("listening");
|
|
89
|
+
if (observed.state === "error")
|
|
90
|
+
return result("error");
|
|
91
|
+
if (!clicked && observed.state === "ready") {
|
|
92
|
+
// Never retry a possibly dispatched start: it may toggle an active call.
|
|
93
|
+
clicked = true;
|
|
94
|
+
await execute({
|
|
95
|
+
action: "click",
|
|
96
|
+
ref_id: refId,
|
|
97
|
+
selector: options.provider === "grok" ? "#start" : "#voice",
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
await sleep(200, signal);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
return result(timeout.aborted && !options.signal?.aborted ? "timeout" : "error", `${errorMessage(error)}${observed.detail ? ` · ${observed.detail}` : ""}`);
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
// Disconnect automation only; the page owns the continuing microphone.
|
|
108
|
+
await runtime?.close();
|
|
109
|
+
}
|
|
110
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { BrowserRoutes, loadBrowserRoutes } from "./browser/routes.js";
|
|
2
|
+
import { BrowserRuntime } from "./browser/runtime.js";
|
|
3
|
+
import { registerBrowserCommand } from "./browser/settings.js";
|
|
4
|
+
import { createBrowserTool, prepareBrowserInput, } from "./browser-tool-definition.js";
|
|
5
|
+
const CODE_MODE_PACKAGE = "@howaboua/pi-codex-conversion";
|
|
6
|
+
const CODE_MODE_MODULE = `${CODE_MODE_PACKAGE}/code-mode`;
|
|
7
|
+
export default async function browserExtension(pi, sdk) {
|
|
8
|
+
let configError;
|
|
9
|
+
let routes;
|
|
10
|
+
try {
|
|
11
|
+
routes = loadBrowserRoutes();
|
|
12
|
+
}
|
|
13
|
+
catch (error) {
|
|
14
|
+
routes = new BrowserRoutes();
|
|
15
|
+
configError = error instanceof Error ? error.message : String(error);
|
|
16
|
+
}
|
|
17
|
+
const runtime = new BrowserRuntime(routes);
|
|
18
|
+
let gpt = false;
|
|
19
|
+
const tool = createBrowserTool(sdk, runtime, () => gpt);
|
|
20
|
+
registerBrowserCommand(pi);
|
|
21
|
+
pi.registerTool(tool);
|
|
22
|
+
try {
|
|
23
|
+
const { registerGptPromptMode } = await import("@howaboua/pi-codex-conversion/prompt-mode");
|
|
24
|
+
registerGptPromptMode(pi, (active) => {
|
|
25
|
+
gpt = active;
|
|
26
|
+
return [tool];
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (!(error instanceof Error) ||
|
|
31
|
+
!("code" in error) ||
|
|
32
|
+
![
|
|
33
|
+
"ERR_MODULE_NOT_FOUND",
|
|
34
|
+
"MODULE_NOT_FOUND",
|
|
35
|
+
"ERR_PACKAGE_PATH_NOT_EXPORTED",
|
|
36
|
+
].includes(String(error.code)) ||
|
|
37
|
+
!error.message.includes(CODE_MODE_PACKAGE))
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
const registration = await registerBrowserInCodeMode(pi, tool, sdk);
|
|
41
|
+
pi.on("session_shutdown", async () => {
|
|
42
|
+
registration?.unregister();
|
|
43
|
+
await runtime.close();
|
|
44
|
+
});
|
|
45
|
+
if (configError) {
|
|
46
|
+
pi.on("session_start", (_event, ctx) => {
|
|
47
|
+
ctx.ui.notify(`${configError}. Run /browser to repair it.`, "warning");
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
async function registerBrowserInCodeMode(pi, tool, sdk) {
|
|
52
|
+
try {
|
|
53
|
+
const { adaptToolForCodeMode, registerCodeModeExtensionTools } = await import("@howaboua/pi-codex-conversion/code-mode");
|
|
54
|
+
return registerCodeModeExtensionTools(pi, () => [
|
|
55
|
+
adaptToolForCodeMode({
|
|
56
|
+
...tool,
|
|
57
|
+
parameters: sdk.Type.Object({}, { additionalProperties: true }),
|
|
58
|
+
}, {
|
|
59
|
+
prepareInput: prepareBrowserInput,
|
|
60
|
+
discovery: "help",
|
|
61
|
+
resultValue: (result) => result.details,
|
|
62
|
+
}),
|
|
63
|
+
]);
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
if (isMissingCodeModeExtension(error))
|
|
67
|
+
return undefined;
|
|
68
|
+
if (isOutdatedCodeModeExtension(error)) {
|
|
69
|
+
throw new Error("Update " +
|
|
70
|
+
CODE_MODE_PACKAGE +
|
|
71
|
+
" to 3.0.24 or newer to use Pi Browser with it", { cause: error });
|
|
72
|
+
}
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function isMissingCodeModeExtension(error) {
|
|
77
|
+
if (!error ||
|
|
78
|
+
typeof error !== "object" ||
|
|
79
|
+
!("code" in error) ||
|
|
80
|
+
!("message" in error) ||
|
|
81
|
+
typeof error.message !== "string") {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
if (error.code !== "ERR_MODULE_NOT_FOUND" &&
|
|
85
|
+
error.code !== "MODULE_NOT_FOUND") {
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
const missing = error.message.match(/Cannot find (?:package|module) ['"]([^'"]+)['"]/)?.[1];
|
|
89
|
+
return missing === CODE_MODE_PACKAGE || missing === CODE_MODE_MODULE;
|
|
90
|
+
}
|
|
91
|
+
function isOutdatedCodeModeExtension(error) {
|
|
92
|
+
if (!error ||
|
|
93
|
+
typeof error !== "object" ||
|
|
94
|
+
!("code" in error) ||
|
|
95
|
+
!("message" in error) ||
|
|
96
|
+
typeof error.message !== "string")
|
|
97
|
+
return false;
|
|
98
|
+
return ((error.code === "ERR_PACKAGE_PATH_NOT_EXPORTED" ||
|
|
99
|
+
error.code === "ERR_UNSUPPORTED_DIR_IMPORT") &&
|
|
100
|
+
(error.message.includes(CODE_MODE_MODULE) ||
|
|
101
|
+
(error.message.includes("Package subpath './code-mode'") &&
|
|
102
|
+
error.message.includes(CODE_MODE_PACKAGE))));
|
|
103
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { defineTool as definePiTool } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { Type as SchemaType } from "typebox";
|
|
3
|
+
import type { BrowserRuntime } from "./browser/runtime.js";
|
|
4
|
+
export declare function prepareBrowserInput(input: unknown): {
|
|
5
|
+
command: string;
|
|
6
|
+
};
|
|
7
|
+
export declare function createBrowserTool({ defineTool, Type, }: {
|
|
8
|
+
defineTool: typeof definePiTool;
|
|
9
|
+
Type: typeof SchemaType;
|
|
10
|
+
}, runtime: BrowserRuntime, isGpt?: () => boolean): import("@earendil-works/pi-coding-agent").ToolDefinition<SchemaType.TObject<{
|
|
11
|
+
command: SchemaType.TOptional<SchemaType.TString>;
|
|
12
|
+
}>, unknown, any> & import("@earendil-works/pi-coding-agent").ToolDefinition<any, any, any>;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { browserHelp } from "./browser/help.js";
|
|
2
|
+
import { isRecordValue } from "./browser/parse-operation.js";
|
|
3
|
+
import { parseBrowserRequest } from "./browser/request.js";
|
|
4
|
+
export function prepareBrowserInput(input) {
|
|
5
|
+
if (input === undefined)
|
|
6
|
+
return { command: "help" };
|
|
7
|
+
if (typeof input === "string")
|
|
8
|
+
return { command: input };
|
|
9
|
+
if (!isRecordValue(input)) {
|
|
10
|
+
throw new Error("browser input must be a command envelope or JSON request");
|
|
11
|
+
}
|
|
12
|
+
if (Object.hasOwn(input, "command")) {
|
|
13
|
+
if (typeof input["command"] !== "string") {
|
|
14
|
+
throw new Error('browser command must be "help" or a JSON request string');
|
|
15
|
+
}
|
|
16
|
+
return { ...input, command: input["command"] };
|
|
17
|
+
}
|
|
18
|
+
// Resume old object calls without changing their stored history representation.
|
|
19
|
+
parseBrowserRequest(input);
|
|
20
|
+
return { command: JSON.stringify(input) };
|
|
21
|
+
}
|
|
22
|
+
export function createBrowserTool({ defineTool, Type, }, runtime, isGpt = () => false) {
|
|
23
|
+
return defineTool({
|
|
24
|
+
name: "browser",
|
|
25
|
+
label: "Browser",
|
|
26
|
+
description: "Control logged-in browser",
|
|
27
|
+
parameters: Type.Object({
|
|
28
|
+
command: Type.Optional(Type.String({ description: "help or JSON request" })),
|
|
29
|
+
}, { additionalProperties: false }),
|
|
30
|
+
prepareArguments: prepareBrowserInput,
|
|
31
|
+
async execute(_toolCallId, input, signal, onUpdate, ctx) {
|
|
32
|
+
const request = parseBrowserRequest(input.command);
|
|
33
|
+
let result = await runtime.execute(request, {
|
|
34
|
+
ownerId: ctx.sessionManager.getSessionId(),
|
|
35
|
+
signal: signal ?? new AbortController().signal,
|
|
36
|
+
onOperation(operation, index, total) {
|
|
37
|
+
onUpdate?.({
|
|
38
|
+
content: [
|
|
39
|
+
{
|
|
40
|
+
type: "text",
|
|
41
|
+
text: total === 1
|
|
42
|
+
? `Browser ${operation.action}`
|
|
43
|
+
: `Browser ${operation.action} ${index + 1}/${total}`,
|
|
44
|
+
},
|
|
45
|
+
],
|
|
46
|
+
details: {
|
|
47
|
+
action: operation.action,
|
|
48
|
+
index: index + 1,
|
|
49
|
+
total,
|
|
50
|
+
status: "running",
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
if (isGpt() && "help" in request)
|
|
56
|
+
result = browserHelp(runtime.hosts, true);
|
|
57
|
+
return {
|
|
58
|
+
content: [{ type: "text", text: JSON.stringify(result) }],
|
|
59
|
+
details: result,
|
|
60
|
+
};
|
|
61
|
+
},
|
|
62
|
+
});
|
|
63
|
+
}
|
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
import { Type } from "typebox";
|
|
2
|
-
import { BrowserRuntime } from "./browser/runtime.js";
|
|
3
|
-
export declare function prepareBrowserInput(input: unknown): {
|
|
4
|
-
command: string;
|
|
5
|
-
};
|
|
2
|
+
import type { BrowserRuntime } from "./browser/runtime.js";
|
|
6
3
|
export declare function createBrowserTool(runtime: BrowserRuntime, isGpt?: () => boolean): import("@earendil-works/pi-coding-agent").ToolDefinition<Type.TObject<{
|
|
7
4
|
command: Type.TOptional<Type.TString>;
|
|
8
5
|
}>, unknown, any> & import("@earendil-works/pi-coding-agent").ToolDefinition<any, any, any>;
|
package/dist/src/browser-tool.js
CHANGED
|
@@ -1,66 +1,6 @@
|
|
|
1
1
|
import { defineTool } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { Type } from "typebox";
|
|
3
|
-
import {
|
|
4
|
-
import { isRecordValue } from "./browser/parse-operation.js";
|
|
5
|
-
import { parseBrowserRequest } from "./browser/request.js";
|
|
6
|
-
import { BrowserRuntime } from "./browser/runtime.js";
|
|
7
|
-
export function prepareBrowserInput(input) {
|
|
8
|
-
if (input === undefined)
|
|
9
|
-
return { command: "help" };
|
|
10
|
-
if (typeof input === "string")
|
|
11
|
-
return { command: input };
|
|
12
|
-
if (!isRecordValue(input)) {
|
|
13
|
-
throw new Error("browser input must be a command envelope or JSON request");
|
|
14
|
-
}
|
|
15
|
-
if (Object.hasOwn(input, "command")) {
|
|
16
|
-
if (typeof input["command"] !== "string") {
|
|
17
|
-
throw new Error('browser command must be "help" or a JSON request string');
|
|
18
|
-
}
|
|
19
|
-
return { ...input, command: input["command"] };
|
|
20
|
-
}
|
|
21
|
-
// Resume old object calls without changing their stored history representation.
|
|
22
|
-
parseBrowserRequest(input);
|
|
23
|
-
return { command: JSON.stringify(input) };
|
|
24
|
-
}
|
|
3
|
+
import { createBrowserTool as createTool } from "./browser-tool-definition.js";
|
|
25
4
|
export function createBrowserTool(runtime, isGpt = () => false) {
|
|
26
|
-
return
|
|
27
|
-
name: "browser",
|
|
28
|
-
label: "Browser",
|
|
29
|
-
description: "Control logged-in browser",
|
|
30
|
-
parameters: Type.Object({
|
|
31
|
-
command: Type.Optional(Type.String({ description: "help or JSON request" })),
|
|
32
|
-
}, { additionalProperties: false }),
|
|
33
|
-
prepareArguments: prepareBrowserInput,
|
|
34
|
-
async execute(_toolCallId, input, signal, onUpdate, ctx) {
|
|
35
|
-
const request = parseBrowserRequest(input.command);
|
|
36
|
-
let result = await runtime.execute(request, {
|
|
37
|
-
ownerId: ctx.sessionManager.getSessionId(),
|
|
38
|
-
signal: signal ?? new AbortController().signal,
|
|
39
|
-
onOperation(operation, index, total) {
|
|
40
|
-
onUpdate?.({
|
|
41
|
-
content: [
|
|
42
|
-
{
|
|
43
|
-
type: "text",
|
|
44
|
-
text: total === 1
|
|
45
|
-
? `Browser ${operation.action}`
|
|
46
|
-
: `Browser ${operation.action} ${index + 1}/${total}`,
|
|
47
|
-
},
|
|
48
|
-
],
|
|
49
|
-
details: {
|
|
50
|
-
action: operation.action,
|
|
51
|
-
index: index + 1,
|
|
52
|
-
total,
|
|
53
|
-
status: "running",
|
|
54
|
-
},
|
|
55
|
-
});
|
|
56
|
-
},
|
|
57
|
-
});
|
|
58
|
-
if (isGpt() && "help" in request)
|
|
59
|
-
result = browserHelp(runtime.hosts, true);
|
|
60
|
-
return {
|
|
61
|
-
content: [{ type: "text", text: JSON.stringify(result) }],
|
|
62
|
-
details: result,
|
|
63
|
-
};
|
|
64
|
-
},
|
|
65
|
-
});
|
|
5
|
+
return createTool({ defineTool, Type }, runtime, isGpt);
|
|
66
6
|
}
|
|
@@ -1,11 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import type {
|
|
3
|
-
export
|
|
4
|
-
cdp: CdpClient;
|
|
5
|
-
sessionId: string;
|
|
6
|
-
elementRefs: ElementRefs;
|
|
7
|
-
refId: string;
|
|
8
|
-
}
|
|
1
|
+
import { type ActiveTab } from "./tab-bridge.js";
|
|
2
|
+
import type { PageInfo } from "./types.js";
|
|
3
|
+
export type { ActiveTab } from "./tab-bridge.js";
|
|
9
4
|
export declare class BrowserCdpSession {
|
|
10
5
|
private closing;
|
|
11
6
|
private root;
|
package/dist/src/cdp/session.js
CHANGED
|
@@ -1,111 +1,8 @@
|
|
|
1
1
|
import { CdpClient } from "./client.js";
|
|
2
2
|
import { getDisplayPrefixLength, getWebSocketUrl, resolvePrefix, } from "./discovery.js";
|
|
3
3
|
import { waitForTurn } from "./serial.js";
|
|
4
|
+
import { TabBridge } from "./tab-bridge.js";
|
|
4
5
|
import { BrowserTabs } from "./tabs.js";
|
|
5
|
-
import { asRecord } from "./types.js";
|
|
6
|
-
const TAB_IDLE_MS = 20 * 60 * 1_000;
|
|
7
|
-
class TabBridge {
|
|
8
|
-
elementRefs = new Map();
|
|
9
|
-
targetId;
|
|
10
|
-
cdp;
|
|
11
|
-
sessionId;
|
|
12
|
-
tail = Promise.resolve();
|
|
13
|
-
idleTimer;
|
|
14
|
-
closed = false;
|
|
15
|
-
backgroundRendering = false;
|
|
16
|
-
onClose;
|
|
17
|
-
constructor(targetId, cdp, sessionId, onClose) {
|
|
18
|
-
this.targetId = targetId;
|
|
19
|
-
this.cdp = cdp;
|
|
20
|
-
this.sessionId = sessionId;
|
|
21
|
-
this.onClose = onClose;
|
|
22
|
-
this.resetIdle();
|
|
23
|
-
cdp.onEvent("Target.targetDestroyed", (value) => {
|
|
24
|
-
const event = asRecord(value, "target destroyed event");
|
|
25
|
-
if (event["targetId"] === targetId)
|
|
26
|
-
this.close(false);
|
|
27
|
-
});
|
|
28
|
-
cdp.onEvent("Target.detachedFromTarget", (value) => {
|
|
29
|
-
const event = asRecord(value, "target detached event");
|
|
30
|
-
if (event["sessionId"] === sessionId)
|
|
31
|
-
this.close(false);
|
|
32
|
-
});
|
|
33
|
-
cdp.onClose(() => this.close(false));
|
|
34
|
-
}
|
|
35
|
-
static async connect(targetId, onClose, signal) {
|
|
36
|
-
const cdp = new CdpClient();
|
|
37
|
-
try {
|
|
38
|
-
await cdp.connect(await getWebSocketUrl(), signal);
|
|
39
|
-
const response = asRecord(await cdp.send("Target.attachToTarget", { targetId, flatten: true }, undefined, signal), "Target.attachToTarget response");
|
|
40
|
-
if (typeof response["sessionId"] !== "string") {
|
|
41
|
-
throw new Error("Chrome did not return a tab session");
|
|
42
|
-
}
|
|
43
|
-
return new TabBridge(targetId, cdp, response["sessionId"], onClose);
|
|
44
|
-
}
|
|
45
|
-
catch (error) {
|
|
46
|
-
cdp.close();
|
|
47
|
-
throw error;
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
async run(refId, signal, action) {
|
|
51
|
-
if (this.closed)
|
|
52
|
-
throw new Error("Tab bridge is closed");
|
|
53
|
-
let release;
|
|
54
|
-
const turn = new Promise((resolveValue) => {
|
|
55
|
-
release = resolveValue;
|
|
56
|
-
});
|
|
57
|
-
const previous = this.tail;
|
|
58
|
-
this.tail = previous.then(() => turn, () => turn);
|
|
59
|
-
try {
|
|
60
|
-
await waitForTurn(previous, signal);
|
|
61
|
-
if (this.closed)
|
|
62
|
-
throw new Error("Tab bridge is closed");
|
|
63
|
-
this.resetIdle();
|
|
64
|
-
return await action({
|
|
65
|
-
cdp: this.cdp,
|
|
66
|
-
sessionId: this.sessionId,
|
|
67
|
-
elementRefs: this.elementRefs,
|
|
68
|
-
refId,
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
finally {
|
|
72
|
-
release();
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
async setBackgroundRendering(enabled, signal) {
|
|
76
|
-
if (this.backgroundRendering === enabled)
|
|
77
|
-
return;
|
|
78
|
-
// An interrupted command may already have applied. Keep the state unknown
|
|
79
|
-
// until Chrome acknowledges it, so the next action reestablishes it.
|
|
80
|
-
this.backgroundRendering = undefined;
|
|
81
|
-
await this.cdp.send("Emulation.setFocusEmulationEnabled", { enabled }, this.sessionId, signal);
|
|
82
|
-
this.backgroundRendering = enabled;
|
|
83
|
-
}
|
|
84
|
-
close(detach = true) {
|
|
85
|
-
if (this.closed)
|
|
86
|
-
return;
|
|
87
|
-
this.closed = true;
|
|
88
|
-
if (this.idleTimer)
|
|
89
|
-
clearTimeout(this.idleTimer);
|
|
90
|
-
this.elementRefs.clear();
|
|
91
|
-
if (detach) {
|
|
92
|
-
void this.cdp
|
|
93
|
-
.send("Target.detachFromTarget", { sessionId: this.sessionId }, undefined, undefined)
|
|
94
|
-
.catch(() => undefined)
|
|
95
|
-
.finally(() => this.cdp.close());
|
|
96
|
-
}
|
|
97
|
-
else {
|
|
98
|
-
this.cdp.close();
|
|
99
|
-
}
|
|
100
|
-
this.onClose();
|
|
101
|
-
}
|
|
102
|
-
resetIdle() {
|
|
103
|
-
if (this.idleTimer)
|
|
104
|
-
clearTimeout(this.idleTimer);
|
|
105
|
-
this.idleTimer = setTimeout(() => this.close(), TAB_IDLE_MS);
|
|
106
|
-
this.idleTimer.unref?.();
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
6
|
export class BrowserCdpSession {
|
|
110
7
|
closing;
|
|
111
8
|
root;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { SnapshotElement, SnapshotLine } from "./snapshot-contract.js";
|
|
2
|
+
import type { ElementRefs } from "./types.js";
|
|
3
|
+
export declare function renderSnapshotTree(rawNodes: unknown[], elementRefs: ElementRefs): {
|
|
4
|
+
lines: (SnapshotLine & {
|
|
5
|
+
kind: string;
|
|
6
|
+
})[];
|
|
7
|
+
elements: SnapshotElement[];
|
|
8
|
+
};
|