@howaboua/pi-browser 0.0.11 → 0.0.12

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.
@@ -2,198 +2,14 @@ import { evaluate } from "./evaluate.js";
2
2
  import {
3
3
  positiveInteger,
4
4
  SNAPSHOT_LIMITS,
5
- type SnapshotElement,
6
- type SnapshotLine,
7
5
  type SnapshotOptions,
8
6
  type SnapshotResult,
9
7
  snapshotResponseLength,
10
8
  } from "./snapshot-contract.js";
9
+ import { renderSnapshotTree } from "./snapshot-tree.js";
11
10
  import type { CdpConnection, ElementRefs } from "./types.js";
12
11
  import { asRecord } from "./types.js";
13
12
 
14
- interface AxValue {
15
- value?: unknown;
16
- }
17
-
18
- interface AxProperty {
19
- name: string;
20
- value?: AxValue | undefined;
21
- }
22
-
23
- interface AxNode {
24
- nodeId: string;
25
- parentId?: string | undefined;
26
- childIds?: string[] | undefined;
27
- backendDOMNodeId?: number | undefined;
28
- ignored?: boolean | undefined;
29
- role?: AxValue | undefined;
30
- name?: AxValue | undefined;
31
- value?: AxValue | undefined;
32
- properties?: AxProperty[] | undefined;
33
- }
34
-
35
- const INTERACTIVE_ROLES = new Set([
36
- "button",
37
- "checkbox",
38
- "combobox",
39
- "link",
40
- "listbox",
41
- "menuitem",
42
- "option",
43
- "menuitemcheckbox",
44
- "menuitemradio",
45
- "radio",
46
- "searchbox",
47
- "slider",
48
- "spinbutton",
49
- "switch",
50
- "tab",
51
- "textbox",
52
- "treeitem",
53
- ]);
54
- const NEXT_ELEMENT_IDS = new WeakMap<ElementRefs, number>();
55
-
56
- function axProperty(value: unknown): AxProperty {
57
- const record = asRecord(value, "accessibility property");
58
- if (typeof record["name"] !== "string") {
59
- throw new Error("Accessibility property has no name");
60
- }
61
- return {
62
- name: record["name"],
63
- ...(record["value"] ? { value: asRecord(record["value"]) } : {}),
64
- };
65
- }
66
-
67
- function axNode(value: unknown): AxNode {
68
- const record = asRecord(value, "accessibility node");
69
- if (typeof record["nodeId"] !== "string") {
70
- throw new Error("Accessibility node has no nodeId");
71
- }
72
- return {
73
- nodeId: record["nodeId"],
74
- ...(typeof record["parentId"] === "string"
75
- ? { parentId: record["parentId"] }
76
- : {}),
77
- ...(Array.isArray(record["childIds"])
78
- ? {
79
- childIds: record["childIds"].filter(
80
- (id): id is string => typeof id === "string",
81
- ),
82
- }
83
- : {}),
84
- ...(typeof record["backendDOMNodeId"] === "number"
85
- ? { backendDOMNodeId: record["backendDOMNodeId"] }
86
- : {}),
87
- ...(typeof record["ignored"] === "boolean"
88
- ? { ignored: record["ignored"] }
89
- : {}),
90
- ...(record["role"] ? { role: asRecord(record["role"]) } : {}),
91
- ...(record["name"] ? { name: asRecord(record["name"]) } : {}),
92
- ...(record["value"] ? { value: asRecord(record["value"]) } : {}),
93
- ...(Array.isArray(record["properties"])
94
- ? { properties: record["properties"].map(axProperty) }
95
- : {}),
96
- };
97
- }
98
-
99
- function shouldShow(node: AxNode): boolean {
100
- const role = String(node.role?.value ?? "");
101
- const name = node.name?.value ?? "";
102
- const value = node.value?.value;
103
- if (role === "InlineTextBox") return false;
104
- if (INTERACTIVE_ROLES.has(role)) return true;
105
- return (
106
- role !== "none" &&
107
- role !== "generic" &&
108
- !(name === "" && (value === "" || value == null))
109
- );
110
- }
111
-
112
- function orderedChildren(
113
- node: AxNode,
114
- nodesById: Map<string, AxNode>,
115
- childrenByParent: Map<string, AxNode[]>,
116
- ): AxNode[] {
117
- const children: AxNode[] = [];
118
- const seen = new Set<string>();
119
- for (const childId of node.childIds ?? []) {
120
- const child = nodesById.get(childId);
121
- if (child && !seen.has(child.nodeId)) {
122
- seen.add(child.nodeId);
123
- children.push(child);
124
- }
125
- }
126
- for (const child of childrenByParent.get(node.nodeId) ?? []) {
127
- if (!seen.has(child.nodeId)) {
128
- seen.add(child.nodeId);
129
- children.push(child);
130
- }
131
- }
132
- return children;
133
- }
134
-
135
- function normalizeText(value: unknown): string {
136
- return String(value ?? "")
137
- .replace(/\s+/g, " ")
138
- .trim();
139
- }
140
-
141
- function splitText(value: unknown, max = 700): string[] {
142
- const text = normalizeText(value);
143
- if (!text) return [];
144
- const parts: string[] = [];
145
- for (let start = 0; start < text.length; start += max) {
146
- parts.push(text.slice(start, start + max));
147
- }
148
- return parts;
149
- }
150
-
151
- function interactiveState(
152
- node: AxNode,
153
- ): Pick<SnapshotElement, "checked" | "selected" | "expanded" | "disabled"> {
154
- const values = new Map(
155
- (node.properties ?? []).map((property) => [
156
- property.name,
157
- property.value?.value,
158
- ]),
159
- );
160
- const checkedValue = values.get("checked");
161
- const checked =
162
- checkedValue === "true"
163
- ? true
164
- : checkedValue === "false"
165
- ? false
166
- : typeof checkedValue === "boolean" || checkedValue === "mixed"
167
- ? checkedValue
168
- : undefined;
169
- const selected = values.get("selected");
170
- const expanded = values.get("expanded");
171
- const disabled = values.get("disabled");
172
- return {
173
- ...(checked === undefined ? {} : { checked }),
174
- ...(typeof selected === "boolean" ? { selected } : {}),
175
- ...(typeof expanded === "boolean" ? { expanded } : {}),
176
- ...(typeof disabled === "boolean" ? { disabled } : {}),
177
- };
178
- }
179
-
180
- function interactiveText(
181
- role: string,
182
- name: string,
183
- value: unknown,
184
- state: ReturnType<typeof interactiveState>,
185
- ): string {
186
- const states = [
187
- state.checked === undefined ? undefined : `checked=${state.checked}`,
188
- state.selected === undefined ? undefined : `selected=${state.selected}`,
189
- state.expanded === undefined ? undefined : `expanded=${state.expanded}`,
190
- state.disabled === undefined ? undefined : `disabled=${state.disabled}`,
191
- ].filter((entry): entry is string => entry !== undefined);
192
- return `${role}${name ? ` ${name}` : ""}${
193
- value === "" || value == null ? "" : ` = ${JSON.stringify(value)}`
194
- }${states.length > 0 ? ` [${states.join(", ")}]` : ""}`;
195
- }
196
-
197
13
  export async function snapshotData(
198
14
  cdp: CdpConnection,
199
15
  sessionId: string,
@@ -214,103 +30,10 @@ export async function snapshotData(
214
30
  if (!Array.isArray(response["nodes"])) {
215
31
  throw new Error("Accessibility response has no nodes");
216
32
  }
217
- const nodes = response["nodes"].map(axNode);
218
- const nodesById = new Map(nodes.map((node) => [node.nodeId, node]));
219
- const childrenByParent = new Map<string, AxNode[]>();
220
- for (const node of nodes) {
221
- if (!node.parentId) continue;
222
- const children = childrenByParent.get(node.parentId) ?? [];
223
- children.push(node);
224
- childrenByParent.set(node.parentId, children);
225
- }
226
-
227
- elementRefs.clear();
228
- type InternalLine = SnapshotLine & { kind: string };
229
- const lines: InternalLine[] = [];
230
- const elements: SnapshotElement[] = [];
231
- const visited = new Set<string>();
232
- const nextElementId = () => {
233
- const id = NEXT_ELEMENT_IDS.get(elementRefs) ?? 1;
234
- if (!Number.isSafeInteger(id)) {
235
- throw new Error("Element id limit reached; restart the tab bridge");
236
- }
237
- NEXT_ELEMENT_IDS.set(elementRefs, id + 1);
238
- return id;
239
- };
240
- const addLine = (text: string, element?: SnapshotElement, kind = "text") => {
241
- for (const part of splitText(text)) {
242
- lines.push({
243
- line: lines.length + 1,
244
- text: part,
245
- kind,
246
- ...(element ? { element_id: element.id } : {}),
247
- });
248
- }
249
- };
250
- const addStaticText = (text: string) => {
251
- const normalized = normalizeText(text);
252
- if (!normalized) return;
253
- const previous = lines.at(-1);
254
- if (
255
- previous?.kind === "text" &&
256
- previous.text.length + normalized.length + 1 <= 700
257
- ) {
258
- previous.text += ` ${normalized}`;
259
- return;
260
- }
261
- addLine(normalized);
262
- };
263
- const visit = (node: AxNode | undefined, parentName = ""): void => {
264
- if (!node || visited.has(node.nodeId)) return;
265
- visited.add(node.nodeId);
266
- const role = String(node.role?.value ?? "");
267
- const name = normalizeText(node.name?.value ?? "");
268
- const value = node.value?.value;
269
- let renderedName = parentName;
270
- if (!node.ignored && shouldShow(node)) {
271
- if (INTERACTIVE_ROLES.has(role)) {
272
- const state = interactiveState(node);
273
- const text = interactiveText(role, name, value, state);
274
- if (!node.backendDOMNodeId) {
275
- addLine(text, undefined, "interactive");
276
- renderedName = name;
277
- } else {
278
- const href =
279
- role === "link"
280
- ? node.properties?.find((property) => property.name === "url")
281
- ?.value?.value
282
- : undefined;
283
- const element: SnapshotElement = {
284
- id: nextElementId(),
285
- role,
286
- ...(name ? { name } : {}),
287
- ...(typeof href === "string" && href ? { href } : {}),
288
- ...(value === "" || value == null ? {} : { value }),
289
- ...state,
290
- };
291
- elementRefs.set(element.id, node.backendDOMNodeId);
292
- elements.push(element);
293
- addLine(`[${element.id}] ${text}`, element, "interactive");
294
- renderedName = name;
295
- }
296
- } else if (role === "StaticText") {
297
- if (name && name !== parentName) addStaticText(name);
298
- } else if (role === "heading" || role === "image") {
299
- if (name) addLine(`${role}: ${name}`, undefined, role);
300
- renderedName = name || parentName;
301
- }
302
- }
303
- for (const child of orderedChildren(node, nodesById, childrenByParent)) {
304
- visit(child, renderedName);
305
- }
306
- };
307
-
308
- for (const root of nodes.filter(
309
- (node) => !node.parentId || !nodesById.has(node.parentId),
310
- )) {
311
- visit(root);
312
- }
313
- for (const node of nodes) visit(node);
33
+ const { lines, elements } = renderSnapshotTree(
34
+ response["nodes"],
35
+ elementRefs,
36
+ );
314
37
 
315
38
  const metadata = asRecord(
316
39
  await evaluate(
@@ -0,0 +1,149 @@
1
+ import { CdpClient } from "./client.js";
2
+ import { getWebSocketUrl } from "./discovery.js";
3
+ import { waitForTurn } from "./serial.js";
4
+ import type { ElementRefs } from "./types.js";
5
+ import { asRecord } from "./types.js";
6
+
7
+ const TAB_IDLE_MS = 20 * 60 * 1_000;
8
+
9
+ export interface ActiveTab {
10
+ cdp: CdpClient;
11
+ sessionId: string;
12
+ elementRefs: ElementRefs;
13
+ refId: string;
14
+ }
15
+
16
+ export class TabBridge {
17
+ readonly elementRefs: ElementRefs = new Map();
18
+ readonly targetId: string;
19
+ readonly cdp: CdpClient;
20
+ readonly sessionId: string;
21
+ private tail = Promise.resolve();
22
+ private idleTimer: ReturnType<typeof setTimeout> | undefined;
23
+ private closed = false;
24
+ private backgroundRendering: boolean | undefined = false;
25
+ private readonly onClose: () => void;
26
+
27
+ private constructor(
28
+ targetId: string,
29
+ cdp: CdpClient,
30
+ sessionId: string,
31
+ onClose: () => void,
32
+ ) {
33
+ this.targetId = targetId;
34
+ this.cdp = cdp;
35
+ this.sessionId = sessionId;
36
+ this.onClose = onClose;
37
+ this.resetIdle();
38
+ cdp.onEvent("Target.targetDestroyed", (value) => {
39
+ const event = asRecord(value, "target destroyed event");
40
+ if (event["targetId"] === targetId) this.close(false);
41
+ });
42
+ cdp.onEvent("Target.detachedFromTarget", (value) => {
43
+ const event = asRecord(value, "target detached event");
44
+ if (event["sessionId"] === sessionId) this.close(false);
45
+ });
46
+ cdp.onClose(() => this.close(false));
47
+ }
48
+
49
+ static async connect(
50
+ targetId: string,
51
+ onClose: () => void,
52
+ signal?: AbortSignal,
53
+ ): Promise<TabBridge> {
54
+ const cdp = new CdpClient();
55
+ try {
56
+ await cdp.connect(await getWebSocketUrl(), signal);
57
+ const response = asRecord(
58
+ await cdp.send(
59
+ "Target.attachToTarget",
60
+ { targetId, flatten: true },
61
+ undefined,
62
+ signal,
63
+ ),
64
+ "Target.attachToTarget response",
65
+ );
66
+ if (typeof response["sessionId"] !== "string") {
67
+ throw new Error("Chrome did not return a tab session");
68
+ }
69
+ return new TabBridge(targetId, cdp, response["sessionId"], onClose);
70
+ } catch (error) {
71
+ cdp.close();
72
+ throw error;
73
+ }
74
+ }
75
+
76
+ async run<T>(
77
+ refId: string,
78
+ signal: AbortSignal | undefined,
79
+ action: (tab: ActiveTab) => Promise<T>,
80
+ ): Promise<T> {
81
+ if (this.closed) throw new Error("Tab bridge is closed");
82
+ let release!: () => void;
83
+ const turn = new Promise<void>((resolveValue) => {
84
+ release = resolveValue;
85
+ });
86
+ const previous = this.tail;
87
+ this.tail = previous.then(
88
+ () => turn,
89
+ () => turn,
90
+ );
91
+ try {
92
+ await waitForTurn(previous, signal);
93
+ if (this.closed) throw new Error("Tab bridge is closed");
94
+ this.resetIdle();
95
+ return await action({
96
+ cdp: this.cdp,
97
+ sessionId: this.sessionId,
98
+ elementRefs: this.elementRefs,
99
+ refId,
100
+ });
101
+ } finally {
102
+ release();
103
+ }
104
+ }
105
+
106
+ async setBackgroundRendering(
107
+ enabled: boolean,
108
+ signal?: AbortSignal,
109
+ ): Promise<void> {
110
+ if (this.backgroundRendering === enabled) return;
111
+ // An interrupted command may already have applied. Keep the state unknown
112
+ // until Chrome acknowledges it, so the next action reestablishes it.
113
+ this.backgroundRendering = undefined;
114
+ await this.cdp.send(
115
+ "Emulation.setFocusEmulationEnabled",
116
+ { enabled },
117
+ this.sessionId,
118
+ signal,
119
+ );
120
+ this.backgroundRendering = enabled;
121
+ }
122
+
123
+ close(detach = true): void {
124
+ if (this.closed) return;
125
+ this.closed = true;
126
+ if (this.idleTimer) clearTimeout(this.idleTimer);
127
+ this.elementRefs.clear();
128
+ if (detach) {
129
+ void this.cdp
130
+ .send(
131
+ "Target.detachFromTarget",
132
+ { sessionId: this.sessionId },
133
+ undefined,
134
+ undefined,
135
+ )
136
+ .catch(() => undefined)
137
+ .finally(() => this.cdp.close());
138
+ } else {
139
+ this.cdp.close();
140
+ }
141
+ this.onClose();
142
+ }
143
+
144
+ private resetIdle(): void {
145
+ if (this.idleTimer) clearTimeout(this.idleTimer);
146
+ this.idleTimer = setTimeout(() => this.close(), TAB_IDLE_MS);
147
+ this.idleTimer.unref?.();
148
+ }
149
+ }
package/tsconfig.json CHANGED
@@ -3,5 +3,5 @@
3
3
  "compilerOptions": {
4
4
  "lib": ["ESNext", "DOM"]
5
5
  },
6
- "include": ["index.ts", "remote-worker.ts", "src/**/*.ts"]
6
+ "include": ["index.ts", "extension.ts", "remote-worker.ts", "src/**/*.ts"]
7
7
  }