@howaboua/pi-browser 0.0.2 → 0.0.4

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 (59) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +4 -0
  3. package/dist/index.js +5 -5
  4. package/dist/remote-worker.js +985 -139
  5. package/dist/src/browser/bounds.d.ts +1 -1
  6. package/dist/src/browser/bounds.js +6 -3
  7. package/dist/src/browser/help.js +17 -6
  8. package/dist/src/browser/operation-executor.js +15 -1
  9. package/dist/src/browser/operation.d.ts +25 -2
  10. package/dist/src/browser/operation.js +5 -0
  11. package/dist/src/browser/parse-operation.js +61 -2
  12. package/dist/src/browser/remote.d.ts +1 -1
  13. package/dist/src/browser/remote.js +2 -2
  14. package/dist/src/browser/runtime.d.ts +8 -3
  15. package/dist/src/browser/runtime.js +91 -25
  16. package/dist/src/browser/worker-server.js +12 -6
  17. package/dist/src/browser-parameters.d.ts +10 -0
  18. package/dist/src/browser-parameters.js +32 -0
  19. package/dist/src/browser-tool.d.ts +10 -0
  20. package/dist/src/browser-tool.js +3 -12
  21. package/dist/src/cdp/actions/click.d.ts +2 -0
  22. package/dist/src/cdp/actions/click.js +1 -1
  23. package/dist/src/cdp/actions/fill.d.ts +8 -0
  24. package/dist/src/cdp/actions/fill.js +175 -0
  25. package/dist/src/cdp/actions/key.d.ts +20 -0
  26. package/dist/src/cdp/actions/key.js +166 -0
  27. package/dist/src/cdp/actions/wait.d.ts +9 -0
  28. package/dist/src/cdp/actions/wait.js +95 -0
  29. package/dist/src/cdp/pages.d.ts +2 -1
  30. package/dist/src/cdp/pages.js +8 -4
  31. package/dist/src/cdp/session.d.ts +7 -1
  32. package/dist/src/cdp/session.js +79 -27
  33. package/dist/src/cdp/snapshot-contract.d.ts +4 -0
  34. package/dist/src/cdp/snapshot.js +67 -11
  35. package/dist/src/cdp/tabs.d.ts +32 -0
  36. package/dist/src/cdp/tabs.js +226 -0
  37. package/dist/src/cdp/types.d.ts +2 -0
  38. package/index.ts +5 -11
  39. package/package.json +5 -5
  40. package/src/browser/bounds.ts +7 -2
  41. package/src/browser/help.ts +18 -6
  42. package/src/browser/operation-executor.ts +34 -0
  43. package/src/browser/operation.ts +19 -1
  44. package/src/browser/parse-operation.ts +63 -2
  45. package/src/browser/remote.ts +2 -1
  46. package/src/browser/runtime.ts +115 -26
  47. package/src/browser/worker-server.ts +24 -7
  48. package/src/browser-parameters.ts +34 -0
  49. package/src/browser-tool.ts +3 -13
  50. package/src/cdp/actions/click.ts +1 -1
  51. package/src/cdp/actions/fill.ts +246 -0
  52. package/src/cdp/actions/key.ts +202 -0
  53. package/src/cdp/actions/wait.ts +117 -0
  54. package/src/cdp/pages.ts +9 -6
  55. package/src/cdp/session.ts +98 -46
  56. package/src/cdp/snapshot-contract.ts +4 -0
  57. package/src/cdp/snapshot.ts +86 -17
  58. package/src/cdp/tabs.ts +292 -0
  59. package/src/cdp/types.ts +2 -0
@@ -4,11 +4,10 @@ import {
4
4
  getWebSocketUrl,
5
5
  resolvePrefix,
6
6
  } from "./discovery.js";
7
- import { getPages, waitForOpenedTarget } from "./pages.js";
8
7
  import { waitForTurn } from "./serial.js";
8
+ import { BrowserTabs } from "./tabs.js";
9
9
  import type { ElementRefs, PageInfo } from "./types.js";
10
10
  import { asRecord } from "./types.js";
11
- import { assertHttpUrl } from "./url.js";
12
11
 
13
12
  const TAB_IDLE_MS = 20 * 60 * 1_000;
14
13
 
@@ -25,6 +24,11 @@ interface PendingConnection<T> {
25
24
  value?: T;
26
25
  }
27
26
 
27
+ interface BrowserConnection {
28
+ cdp: CdpClient;
29
+ tabs: BrowserTabs;
30
+ }
31
+
28
32
  class TabBridge {
29
33
  readonly elementRefs: ElementRefs = new Map();
30
34
  readonly targetId: string;
@@ -33,6 +37,7 @@ class TabBridge {
33
37
  private tail = Promise.resolve();
34
38
  private idleTimer: ReturnType<typeof setTimeout> | undefined;
35
39
  private closed = false;
40
+ private backgroundRendering: boolean | undefined = false;
36
41
  private readonly onClose: () => void;
37
42
 
38
43
  private constructor(
@@ -114,6 +119,23 @@ class TabBridge {
114
119
  }
115
120
  }
116
121
 
122
+ async setBackgroundRendering(
123
+ enabled: boolean,
124
+ signal?: AbortSignal,
125
+ ): Promise<void> {
126
+ if (this.backgroundRendering === enabled) return;
127
+ // An interrupted command may already have applied. Keep the state unknown
128
+ // until Chrome acknowledges it, so the next action reestablishes it.
129
+ this.backgroundRendering = undefined;
130
+ await this.cdp.send(
131
+ "Emulation.setFocusEmulationEnabled",
132
+ { enabled },
133
+ this.sessionId,
134
+ signal,
135
+ );
136
+ this.backgroundRendering = enabled;
137
+ }
138
+
117
139
  close(detach = true): void {
118
140
  if (this.closed) return;
119
141
  this.closed = true;
@@ -143,16 +165,24 @@ class TabBridge {
143
165
  }
144
166
 
145
167
  export class BrowserCdpSession {
146
- private root: CdpClient | undefined;
147
- private rootPending: PendingConnection<CdpClient> | undefined;
168
+ private closing: Promise<void> | undefined;
169
+ private root: BrowserConnection | undefined;
170
+ private rootPending: PendingConnection<BrowserConnection> | undefined;
171
+ private readonly ownerId: string;
172
+ private readonly ownershipDirectory: string;
148
173
  private readonly tabs = new Map<string, TabBridge>();
149
174
  private readonly tabPromises = new Map<
150
175
  string,
151
176
  PendingConnection<TabBridge>
152
177
  >();
153
178
 
179
+ constructor(ownerId: string, ownershipDirectory: string) {
180
+ this.ownerId = ownerId;
181
+ this.ownershipDirectory = ownershipDirectory;
182
+ }
183
+
154
184
  async pages(signal?: AbortSignal): Promise<PageInfo[]> {
155
- return getPages(await this.rootConnection(signal), signal);
185
+ return (await this.rootConnection(signal)).tabs.list(signal);
156
186
  }
157
187
 
158
188
  async open(
@@ -161,32 +191,25 @@ export class BrowserCdpSession {
161
191
  ): Promise<{
162
192
  refId: string;
163
193
  }> {
164
- assertHttpUrl(url);
194
+ return (await this.rootConnection(signal)).tabs.open(url, signal);
195
+ }
196
+
197
+ async show(refId: string, signal?: AbortSignal): Promise<string> {
198
+ return (await this.rootConnection(signal)).tabs.show(refId, signal);
199
+ }
200
+
201
+ async closeTab(refId: string, signal?: AbortSignal): Promise<string> {
165
202
  const root = await this.rootConnection(signal);
166
- const response = asRecord(
167
- await root.send("Target.createTarget", { url }, undefined, signal),
168
- "Target.createTarget response",
169
- );
170
- if (typeof response["targetId"] !== "string") {
171
- throw new Error("Chrome did not return a new tab target");
172
- }
173
- const page = await waitForOpenedTarget(
174
- root,
175
- response["targetId"],
176
- url,
177
- 5_000,
178
- signal,
179
- );
180
- const pages = await getPages(root, signal);
181
- if (!pages.some((candidate) => candidate.targetId === page.targetId)) {
182
- pages.push(page);
183
- }
184
- const prefixLength = getDisplayPrefixLength(
185
- pages.map((candidate) => candidate.targetId),
186
- );
187
- return {
188
- refId: page.targetId.slice(0, prefixLength),
189
- };
203
+ const resolved = await root.tabs.resolve(refId, signal);
204
+ const targetId = resolved.page.targetId;
205
+ this.stopPendingTab(targetId, "Tab is closing");
206
+ const bridge = this.tabs.get(targetId);
207
+ const close = () => root.tabs.close(targetId, signal);
208
+ const closed = bridge
209
+ ? await bridge.run(resolved.refId, signal, close)
210
+ : await close();
211
+ bridge?.close(false);
212
+ return closed.refId;
190
213
  }
191
214
 
192
215
  async withTab<T>(
@@ -237,7 +260,14 @@ export class BrowserCdpSession {
237
260
  const prefixLength = getDisplayPrefixLength(
238
261
  pages.map((page) => page.targetId),
239
262
  );
240
- return bridge.run(targetId.slice(0, prefixLength), signal, action);
263
+ const owned = pages.some(
264
+ (page) => page.targetId === targetId && page.owned === true,
265
+ );
266
+ const current = bridge;
267
+ return current.run(targetId.slice(0, prefixLength), signal, async (tab) => {
268
+ await current.setBackgroundRendering(owned, signal);
269
+ return action(tab);
270
+ });
241
271
  }
242
272
 
243
273
  async stop(refId?: string): Promise<void> {
@@ -260,7 +290,8 @@ export class BrowserCdpSession {
260
290
  this.tabs.delete(targetId);
261
291
  }
262
292
 
263
- close(): void {
293
+ close(): Promise<void> {
294
+ if (this.closing) return this.closing;
264
295
  for (const targetId of this.tabPromises.keys()) {
265
296
  this.stopPendingTab(targetId, "Browser session closed");
266
297
  }
@@ -268,18 +299,27 @@ export class BrowserCdpSession {
268
299
  this.tabs.clear();
269
300
  const rootPending = this.rootPending;
270
301
  this.rootPending = undefined;
271
- if (rootPending) {
272
- rootPending.controller.abort(new Error("Browser session closed"));
273
- void rootPending.promise.then(
274
- (client) => client.close(),
275
- () => undefined,
276
- );
277
- }
278
- this.root?.close();
302
+ rootPending?.controller.abort(new Error("Browser session closed"));
303
+ const root = this.root;
279
304
  this.root = undefined;
305
+ this.closing = (async () => {
306
+ const connected = await rootPending?.promise.catch(() => undefined);
307
+ for (const connection of new Set([root, connected])) {
308
+ if (!connection) continue;
309
+ try {
310
+ await connection.tabs.shutdown();
311
+ } finally {
312
+ connection.cdp.close();
313
+ }
314
+ }
315
+ })();
316
+ return this.closing;
280
317
  }
281
318
 
282
- private async rootConnection(signal?: AbortSignal): Promise<CdpClient> {
319
+ private async rootConnection(
320
+ signal?: AbortSignal,
321
+ ): Promise<BrowserConnection> {
322
+ if (this.closing) throw new Error("Browser session closed");
283
323
  if (this.root) return this.root;
284
324
  let pending = this.rootPending;
285
325
  if (!pending) {
@@ -332,14 +372,26 @@ export class BrowserCdpSession {
332
372
  );
333
373
  }
334
374
 
335
- private async connectRoot(signal: AbortSignal): Promise<CdpClient> {
375
+ private async connectRoot(signal: AbortSignal): Promise<BrowserConnection> {
336
376
  const client = new CdpClient();
337
- await client.connect(await getWebSocketUrl(), signal);
338
- this.root = client;
377
+ const url = await getWebSocketUrl();
378
+ try {
379
+ await client.connect(url, signal);
380
+ signal.throwIfAborted();
381
+ if (this.closing) throw new Error("Browser session closed");
382
+ } catch (error) {
383
+ client.close();
384
+ throw error;
385
+ }
386
+ const connection = {
387
+ cdp: client,
388
+ tabs: new BrowserTabs(client, this.ownerId, this.ownershipDirectory, url),
389
+ };
390
+ this.root = connection;
339
391
  client.onClose(() => {
340
- if (this.root !== client) return;
392
+ if (this.root !== connection) return;
341
393
  this.root = undefined;
342
394
  });
343
- return client;
395
+ return connection;
344
396
  }
345
397
  }
@@ -17,6 +17,10 @@ export interface SnapshotElement {
17
17
  role: string;
18
18
  name?: string | undefined;
19
19
  value?: unknown;
20
+ checked?: boolean | "mixed" | undefined;
21
+ selected?: boolean | undefined;
22
+ expanded?: boolean | undefined;
23
+ disabled?: boolean | undefined;
20
24
  }
21
25
 
22
26
  export interface SnapshotResult {
@@ -15,6 +15,11 @@ interface AxValue {
15
15
  value?: unknown;
16
16
  }
17
17
 
18
+ interface AxProperty {
19
+ name: string;
20
+ value?: AxValue | undefined;
21
+ }
22
+
18
23
  interface AxNode {
19
24
  nodeId: string;
20
25
  parentId?: string | undefined;
@@ -24,6 +29,7 @@ interface AxNode {
24
29
  role?: AxValue | undefined;
25
30
  name?: AxValue | undefined;
26
31
  value?: AxValue | undefined;
32
+ properties?: AxProperty[] | undefined;
27
33
  }
28
34
 
29
35
  const INTERACTIVE_ROLES = new Set([
@@ -47,6 +53,17 @@ const INTERACTIVE_ROLES = new Set([
47
53
  ]);
48
54
  const NEXT_ELEMENT_IDS = new WeakMap<ElementRefs, number>();
49
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
+
50
67
  function axNode(value: unknown): AxNode {
51
68
  const record = asRecord(value, "accessibility node");
52
69
  if (typeof record["nodeId"] !== "string") {
@@ -73,6 +90,9 @@ function axNode(value: unknown): AxNode {
73
90
  ...(record["role"] ? { role: asRecord(record["role"]) } : {}),
74
91
  ...(record["name"] ? { name: asRecord(record["name"]) } : {}),
75
92
  ...(record["value"] ? { value: asRecord(record["value"]) } : {}),
93
+ ...(Array.isArray(record["properties"])
94
+ ? { properties: record["properties"].map(axProperty) }
95
+ : {}),
76
96
  };
77
97
  }
78
98
 
@@ -81,6 +101,7 @@ function shouldShow(node: AxNode): boolean {
81
101
  const name = node.name?.value ?? "";
82
102
  const value = node.value?.value;
83
103
  if (role === "InlineTextBox") return false;
104
+ if (INTERACTIVE_ROLES.has(role)) return true;
84
105
  return (
85
106
  role !== "none" &&
86
107
  role !== "generic" &&
@@ -127,6 +148,52 @@ function splitText(value: unknown, max = 700): string[] {
127
148
  return parts;
128
149
  }
129
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
+
130
197
  export async function snapshotData(
131
198
  cdp: CdpConnection,
132
199
  sessionId: string,
@@ -201,23 +268,25 @@ export async function snapshotData(
201
268
  const value = node.value?.value;
202
269
  let renderedName = parentName;
203
270
  if (!node.ignored && shouldShow(node)) {
204
- if (INTERACTIVE_ROLES.has(role) && node.backendDOMNodeId) {
205
- const element: SnapshotElement = {
206
- id: nextElementId(),
207
- role,
208
- ...(name ? { name } : {}),
209
- ...(value === "" || value == null ? {} : { value }),
210
- };
211
- elementRefs.set(element.id, node.backendDOMNodeId);
212
- elements.push(element);
213
- addLine(
214
- `[${element.id}] ${role}${name ? ` ${name}` : ""}${
215
- value === "" || value == null ? "" : ` = ${JSON.stringify(value)}`
216
- }`,
217
- element,
218
- "interactive",
219
- );
220
- renderedName = name;
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 element: SnapshotElement = {
279
+ id: nextElementId(),
280
+ role,
281
+ ...(name ? { name } : {}),
282
+ ...(value === "" || value == null ? {} : { value }),
283
+ ...state,
284
+ };
285
+ elementRefs.set(element.id, node.backendDOMNodeId);
286
+ elements.push(element);
287
+ addLine(`[${element.id}] ${text}`, element, "interactive");
288
+ renderedName = name;
289
+ }
221
290
  } else if (role === "StaticText") {
222
291
  if (name && name !== parentName) addStaticText(name);
223
292
  } else if (role === "heading" || role === "image") {
@@ -0,0 +1,292 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstat, mkdir, readdir, rm, utimes, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { getDisplayPrefixLength, resolvePrefix } from "./discovery.js";
5
+ import {
6
+ getDisplayedPages,
7
+ getPageTargets,
8
+ waitForOpenedTarget,
9
+ } from "./pages.js";
10
+ import { waitForTurn } from "./serial.js";
11
+ import type { CdpConnection, PageInfo } from "./types.js";
12
+ import { asRecord, errorMessage } from "./types.js";
13
+ import { assertHttpUrl } from "./url.js";
14
+
15
+ const TARGET_ID = /^[A-Za-z0-9_-]{1,128}$/;
16
+ const SCOPE_ID = /^[a-f0-9]{64}$/;
17
+ // Listings refresh active scopes. One connection retires at most 32 month-old
18
+ // scopes, bounding cleanup while catching up faster than scopes are created.
19
+ const SCOPE_TTL_MS = 30 * 24 * 60 * 60 * 1_000;
20
+ const SCOPE_PRUNE_LIMIT = 32;
21
+
22
+ function missing(error: unknown): boolean {
23
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
24
+ }
25
+
26
+ async function pruneOwnershipScopes(
27
+ directory: string,
28
+ currentScope: string,
29
+ now = Date.now(),
30
+ ): Promise<void> {
31
+ let entries;
32
+ try {
33
+ entries = await readdir(directory, { withFileTypes: true });
34
+ } catch (error) {
35
+ if (missing(error)) return;
36
+ throw error;
37
+ }
38
+ const stale: { path: string; mtimeMs: number }[] = [];
39
+ for (const entry of entries) {
40
+ if (
41
+ entry.name === currentScope ||
42
+ !SCOPE_ID.test(entry.name) ||
43
+ !entry.isDirectory()
44
+ )
45
+ continue;
46
+ const path = join(directory, entry.name);
47
+ try {
48
+ const info = await lstat(path);
49
+ if (
50
+ info.isDirectory() &&
51
+ !info.isSymbolicLink() &&
52
+ now - info.mtimeMs > SCOPE_TTL_MS
53
+ ) {
54
+ stale.push({ path, mtimeMs: info.mtimeMs });
55
+ }
56
+ } catch (error) {
57
+ if (!missing(error)) throw error;
58
+ }
59
+ }
60
+ stale.sort((left, right) => left.mtimeMs - right.mtimeMs);
61
+ await Promise.all(
62
+ stale
63
+ .slice(0, SCOPE_PRUNE_LIMIT)
64
+ .map((scope) => rm(scope.path, { force: true, recursive: true })),
65
+ );
66
+ }
67
+
68
+ export class BrowserTabs {
69
+ private readonly cdp: CdpConnection;
70
+ private readonly directory: string;
71
+ private readonly ownershipDirectory: string;
72
+ private readonly scope: string;
73
+ private tail: Promise<void> = Promise.resolve();
74
+ private closed = false;
75
+ private prepared = false;
76
+
77
+ constructor(
78
+ cdp: CdpConnection,
79
+ ownerId: string,
80
+ directory: string,
81
+ browserUrl: string,
82
+ ) {
83
+ this.cdp = cdp;
84
+ this.ownershipDirectory = directory;
85
+ // Browser endpoint identity changes on restart, so restored tabs do not
86
+ // inherit an old automation session's ownership.
87
+ this.scope = createHash("sha256")
88
+ .update(`${browserUrl}\0${ownerId}`)
89
+ .digest("hex");
90
+ this.directory = join(directory, this.scope);
91
+ }
92
+
93
+ list(signal?: AbortSignal): Promise<PageInfo[]> {
94
+ return this.enqueue(() => this.listNow(signal), signal);
95
+ }
96
+
97
+ async shutdown(): Promise<void> {
98
+ this.closed = true;
99
+ await this.tail;
100
+ }
101
+
102
+ private enqueue<T>(
103
+ action: () => Promise<T>,
104
+ signal?: AbortSignal,
105
+ ): Promise<T> {
106
+ const pending = this.tail.then(async () => {
107
+ signal?.throwIfAborted();
108
+ if (this.closed) throw new Error("Browser session closed");
109
+ if (!this.prepared) {
110
+ await this.touchDirectory();
111
+ await pruneOwnershipScopes(this.ownershipDirectory, this.scope);
112
+ this.prepared = true;
113
+ }
114
+ return action();
115
+ });
116
+ this.tail = pending.then(
117
+ () => undefined,
118
+ () => undefined,
119
+ );
120
+ return waitForTurn(pending, signal);
121
+ }
122
+
123
+ private async listNow(signal?: AbortSignal): Promise<PageInfo[]> {
124
+ // Read ownership first so a concurrent creation is not pruned against an
125
+ // older browser target snapshot.
126
+ const owned = await this.readOwned();
127
+ const targets = await getPageTargets(this.cdp, signal);
128
+ const pages = getDisplayedPages(targets);
129
+ const known = new Set(owned);
130
+ // Resolve descendants before removing closed openers from the registry.
131
+ let changed = true;
132
+ while (changed) {
133
+ changed = false;
134
+ for (const page of pages) {
135
+ if (
136
+ !page.openerId ||
137
+ !known.has(page.openerId) ||
138
+ known.has(page.targetId)
139
+ )
140
+ continue;
141
+ await this.remember(page.targetId);
142
+ known.add(page.targetId);
143
+ changed = true;
144
+ }
145
+ }
146
+ const live = new Set(targets.map((page) => page.targetId));
147
+ await Promise.all(
148
+ owned.filter((id) => !live.has(id)).map((id) => this.forget(id)),
149
+ );
150
+ return pages.map((page) => ({ ...page, owned: known.has(page.targetId) }));
151
+ }
152
+
153
+ async resolve(
154
+ refId: string,
155
+ signal?: AbortSignal,
156
+ ): Promise<{ page: PageInfo; refId: string }> {
157
+ const pages = await this.list(signal);
158
+ const ids = pages.map((page) => page.targetId);
159
+ const targetId = resolvePrefix(refId, ids, "target", "Run tabs.");
160
+ const page = pages.find((candidate) => candidate.targetId === targetId);
161
+ if (!page) throw new Error("Tab disappeared; run tabs again");
162
+ return { page, refId: targetId.slice(0, getDisplayPrefixLength(ids)) };
163
+ }
164
+
165
+ async open(url: string, signal?: AbortSignal): Promise<{ refId: string }> {
166
+ assertHttpUrl(url);
167
+ const targetId = await this.enqueue(async () => {
168
+ // Once dispatched, preserve the reply and ownership write even if the
169
+ // caller aborts. Listings and shutdown wait for this critical section.
170
+ let response: Record<string, unknown>;
171
+ try {
172
+ response = asRecord(
173
+ await this.cdp.send("Target.createTarget", { url, background: true }),
174
+ "Target.createTarget response",
175
+ );
176
+ } catch (error) {
177
+ throw new Error(
178
+ `Chrome did not confirm tab creation; a shared tab may exist. Run tabs before retrying: ${errorMessage(error)}`,
179
+ );
180
+ }
181
+ if (typeof response["targetId"] !== "string")
182
+ throw new Error(
183
+ "Chrome did not return a new tab target; run tabs before retrying",
184
+ );
185
+ const created = response["targetId"];
186
+ try {
187
+ await this.remember(created);
188
+ } catch (error) {
189
+ throw new Error(
190
+ `Opened tab ${created} but could not save ownership; it remains shared: ${errorMessage(error)}`,
191
+ );
192
+ }
193
+ return created;
194
+ }, signal);
195
+ await waitForOpenedTarget(this.cdp, targetId, url, 5_000, signal);
196
+ const { refId } = await this.resolve(targetId, signal);
197
+ return { refId };
198
+ }
199
+
200
+ async show(refId: string, signal?: AbortSignal): Promise<string> {
201
+ const resolved = await this.resolve(refId, signal);
202
+ await this.cdp.send(
203
+ "Target.activateTarget",
204
+ { targetId: resolved.page.targetId },
205
+ undefined,
206
+ signal,
207
+ );
208
+ return resolved.refId;
209
+ }
210
+
211
+ async close(
212
+ refId: string,
213
+ signal?: AbortSignal,
214
+ ): Promise<{ targetId: string; refId: string }> {
215
+ const resolved = await this.resolve(refId, signal);
216
+ const targetId = resolved.page.targetId;
217
+ const response = asRecord(
218
+ await this.cdp.send(
219
+ "Target.closeTarget",
220
+ { targetId },
221
+ undefined,
222
+ signal,
223
+ ),
224
+ "Target.closeTarget response",
225
+ );
226
+ if (response["success"] !== true)
227
+ throw new Error("Chrome did not close the tab; run tabs to inspect it");
228
+ await this.forget(targetId);
229
+ return { targetId, refId: resolved.refId };
230
+ }
231
+
232
+ private targetPath(targetId: string): string {
233
+ if (!TARGET_ID.test(targetId))
234
+ throw new Error("Chrome returned an invalid target id");
235
+ return join(this.directory, targetId);
236
+ }
237
+
238
+ private async readOwned(): Promise<string[]> {
239
+ if (!(await this.touchDirectory())) return [];
240
+ try {
241
+ const files = await readdir(this.directory, { withFileTypes: true });
242
+ for (const file of files) {
243
+ if (!file.isFile() || !TARGET_ID.test(file.name))
244
+ throw new Error(
245
+ "Invalid browser ownership record; refusing to infer tab ownership",
246
+ );
247
+ }
248
+ return files.map((file) => file.name);
249
+ } catch (error) {
250
+ if (missing(error)) return [];
251
+ throw error;
252
+ }
253
+ }
254
+
255
+ private async touchDirectory(): Promise<boolean> {
256
+ try {
257
+ const info = await lstat(this.directory);
258
+ if (!info.isDirectory() || info.isSymbolicLink())
259
+ throw new Error("Invalid browser ownership directory");
260
+ const now = new Date();
261
+ await utimes(this.directory, now, now);
262
+ return true;
263
+ } catch (error) {
264
+ if (missing(error)) return false;
265
+ throw error;
266
+ }
267
+ }
268
+
269
+ private async remember(targetId: string): Promise<void> {
270
+ const path = this.targetPath(targetId);
271
+ await mkdir(this.directory, { recursive: true, mode: 0o700 });
272
+ const info = await lstat(this.directory);
273
+ if (!info.isDirectory() || info.isSymbolicLink())
274
+ throw new Error("Invalid browser ownership directory");
275
+ // One record per target avoids read/modify/write races between clients of
276
+ // the same Pi session and survives reloads or managed-worker upgrades.
277
+ try {
278
+ await writeFile(path, "", { flag: "wx", mode: 0o600 });
279
+ } catch (error) {
280
+ if (
281
+ !(error instanceof Error && "code" in error && error.code === "EEXIST")
282
+ )
283
+ throw error;
284
+ if (!(await lstat(path)).isFile())
285
+ throw new Error("Invalid browser ownership record");
286
+ }
287
+ }
288
+
289
+ private async forget(targetId: string): Promise<void> {
290
+ await rm(this.targetPath(targetId), { force: true });
291
+ }
292
+ }
package/src/cdp/types.ts CHANGED
@@ -25,6 +25,8 @@ export interface PageInfo {
25
25
  title: string;
26
26
  url: string;
27
27
  type?: string;
28
+ openerId?: string;
29
+ owned?: boolean;
28
30
  }
29
31
 
30
32
  export type ElementRefs = Map<number, number>;