@d0nj/dsh-browser 0.0.0-stage → 0.1.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.
@@ -0,0 +1,108 @@
1
+ import type { ChildProcess } from 'node:child_process';
2
+ /** Where to look for a browser binary. */
3
+ export interface ExecutableSearch {
4
+ readonly platform: NodeJS.Platform;
5
+ readonly env: Readonly<Record<string, string | undefined>>;
6
+ readonly home: string;
7
+ readonly exists: (path: string) => Promise<boolean>;
8
+ }
9
+ /** The DevTools endpoint Chrome published for a profile directory. */
10
+ export interface DevToolsEndpoint {
11
+ readonly port: number;
12
+ readonly path: string;
13
+ readonly wsUrl: string;
14
+ }
15
+ /** One running or reused browser. */
16
+ export interface LaunchedBrowser {
17
+ readonly wsUrl: string;
18
+ readonly port: number;
19
+ /** The process this plugin started; undefined when the browser was reused or attached. */
20
+ readonly child: ChildProcess | undefined;
21
+ readonly owned: boolean;
22
+ }
23
+ /** Options for starting a browser. */
24
+ export interface LaunchRequest {
25
+ readonly executable: string;
26
+ readonly userDataDir: string;
27
+ readonly headless: boolean;
28
+ readonly windowSize: {
29
+ readonly width: number;
30
+ readonly height: number;
31
+ };
32
+ readonly extraArgs?: readonly string[];
33
+ readonly startupTimeoutMs?: number;
34
+ readonly signal?: AbortSignal;
35
+ }
36
+ /**
37
+ * Candidate executable paths for a platform, in preference order.
38
+ * @param platform - `process.platform`.
39
+ * @param env - environment variables to read install roots from.
40
+ * @param home - the user's home directory.
41
+ * @returns absolute paths to probe.
42
+ */
43
+ export declare function executableCandidates(platform: NodeJS.Platform, env: Readonly<Record<string, string | undefined>>, home: string): string[];
44
+ /**
45
+ * Pick the first installed browser.
46
+ * @param search - platform, environment, home, and an existence probe.
47
+ * @returns the executable path, or undefined when none of the candidates exist.
48
+ */
49
+ export declare function findExecutable(search: ExecutableSearch): Promise<string | undefined>;
50
+ /**
51
+ * Describe what the search looked at, for an actionable error message.
52
+ * @param search - platform, environment, and home.
53
+ * @returns the candidate list as a readable line.
54
+ */
55
+ export declare function describeSearch(search: Omit<ExecutableSearch, 'exists'>): string;
56
+ /**
57
+ * Read the endpoint Chrome records in its profile directory.
58
+ * @param userDataDir - the profile directory passed as `--user-data-dir`.
59
+ * @returns the published endpoint, or undefined when it is absent or incomplete.
60
+ */
61
+ export declare function readActivePort(userDataDir: string): Promise<DevToolsEndpoint | undefined>;
62
+ /**
63
+ * Ask a DevTools HTTP endpoint for its browser WebSocket URL.
64
+ * @param origin - `http://host:port`.
65
+ * @param timeoutMs - probe budget.
66
+ * @returns the browser WebSocket URL, or undefined when nothing answers.
67
+ */
68
+ export declare function probeVersion(origin: string, timeoutMs?: number): Promise<string | undefined>;
69
+ /**
70
+ * Resolve a configured CDP address into a browser WebSocket URL.
71
+ *
72
+ * Accepts a `ws://` URL, or an HTTP origin such as `http://127.0.0.1:9222`
73
+ * whose `/json/version` names the browser endpoint.
74
+ * @param address - configured `cdpUrl`.
75
+ * @param timeoutMs - probe budget.
76
+ * @returns the browser WebSocket URL.
77
+ */
78
+ export declare function resolveCdpAddress(address: string, timeoutMs?: number): Promise<string>;
79
+ /**
80
+ * Attach to a browser already using a profile directory.
81
+ * @param userDataDir - the profile directory.
82
+ * @returns the live endpoint, or undefined when no browser owns that directory.
83
+ */
84
+ export declare function reuseBrowser(userDataDir: string): Promise<LaunchedBrowser | undefined>;
85
+ /**
86
+ * Start a browser and wait for its DevTools endpoint.
87
+ * @param request - executable, profile, window, and extra flags.
88
+ * @returns the running browser.
89
+ */
90
+ export declare function launchChrome(request: LaunchRequest): Promise<LaunchedBrowser>;
91
+ /**
92
+ * Stop a browser this plugin started.
93
+ * @param child - the process returned by {@link launchChrome}.
94
+ */
95
+ export declare function stopBrowser(child: ChildProcess | undefined): Promise<void>;
96
+ /**
97
+ * Explain why a browser that started anyway never published an endpoint.
98
+ *
99
+ * Edge ships with `RemoteDebuggingAllowed=false` on many machines and exits with
100
+ * a message about remote debugging being disallowed; without naming that case
101
+ * the operator sees a generic timeout and retries the same browser.
102
+ * @param executable - the binary that was started.
103
+ * @param userDataDir - the profile directory it was given.
104
+ * @param stderr - whatever the process wrote before exiting.
105
+ * @returns the message for the caller.
106
+ */
107
+ export declare function describeLaunchFailure(executable: string, userDataDir: string, stderr: string): string;
108
+ //# sourceMappingURL=launch.d.ts.map
package/dist/launch.js ADDED
@@ -0,0 +1,260 @@
1
+ /**
2
+ * Finding, starting, and attaching to a Chromium-family browser.
3
+ *
4
+ * Chrome publishes its DevTools endpoint through a `DevToolsActivePort` file in
5
+ * the profile directory; reading it is the only way to discover a port chosen by
6
+ * the browser (`--remote-debugging-port=0`), and it is also what makes reuse
7
+ * across plugin restarts possible without hunting for PIDs.
8
+ *
9
+ * @module @d0nj/dsh-browser/launch
10
+ */
11
+ import { spawn } from 'node:child_process';
12
+ import { mkdir, readFile, rm } from 'node:fs/promises';
13
+ import { join, posix, win32 } from 'node:path';
14
+ /**
15
+ * Candidate executable paths for a platform, in preference order.
16
+ * @param platform - `process.platform`.
17
+ * @param env - environment variables to read install roots from.
18
+ * @param home - the user's home directory.
19
+ * @returns absolute paths to probe.
20
+ */
21
+ export function executableCandidates(platform, env, home) {
22
+ const explicit = env['CHROME_PATH'] ?? env['DSH_BROWSER_EXECUTABLE'];
23
+ const candidates = explicit === undefined || explicit === '' ? [] : [explicit];
24
+ if (platform === 'win32') {
25
+ for (const root of [env['ProgramFiles'], env['ProgramFiles(x86)'], env['LOCALAPPDATA']]) {
26
+ if (root === undefined || root === '')
27
+ continue;
28
+ candidates.push(win32.join(root, 'Google', 'Chrome', 'Application', 'chrome.exe'));
29
+ }
30
+ for (const root of [env['LOCALAPPDATA'], env['ProgramFiles']]) {
31
+ if (root === undefined || root === '')
32
+ continue;
33
+ candidates.push(win32.join(root, 'Chromium', 'Application', 'chrome.exe'));
34
+ }
35
+ const scoop = env['SCOOP'] ?? win32.join(home, 'scoop');
36
+ candidates.push(win32.join(scoop, 'apps', 'chromium', 'current', 'chrome.exe'), win32.join(scoop, 'apps', 'googlechrome', 'current', 'chrome.exe'), win32.join(scoop, 'apps', 'brave', 'current', 'brave.exe'), win32.join(scoop, 'shims', 'chromium.exe'), win32.join(scoop, 'shims', 'chrome.exe'));
37
+ const programData = env['ProgramData'];
38
+ if (programData !== undefined && programData !== '') {
39
+ candidates.push(win32.join(programData, 'chocolatey', 'bin', 'chrome.exe'), win32.join(programData, 'chocolatey', 'bin', 'chromium.exe'));
40
+ }
41
+ for (const root of [env['ProgramFiles'], env['LOCALAPPDATA']]) {
42
+ if (root === undefined || root === '')
43
+ continue;
44
+ candidates.push(win32.join(root, 'BraveSoftware', 'Brave-Browser', 'Application', 'brave.exe'));
45
+ }
46
+ // Edge often ships with remote debugging disabled by policy, so it is tried last.
47
+ for (const root of [env['ProgramFiles(x86)'], env['ProgramFiles'], env['LOCALAPPDATA']]) {
48
+ if (root === undefined || root === '')
49
+ continue;
50
+ candidates.push(win32.join(root, 'Microsoft', 'Edge', 'Application', 'msedge.exe'));
51
+ }
52
+ return candidates;
53
+ }
54
+ if (platform === 'darwin') {
55
+ for (const root of ['/Applications', posix.join(home, 'Applications')]) {
56
+ candidates.push(posix.join(root, 'Google Chrome.app', 'Contents', 'MacOS', 'Google Chrome'));
57
+ candidates.push(posix.join(root, 'Microsoft Edge.app', 'Contents', 'MacOS', 'Microsoft Edge'));
58
+ candidates.push(posix.join(root, 'Brave Browser.app', 'Contents', 'MacOS', 'Brave Browser'));
59
+ candidates.push(posix.join(root, 'Chromium.app', 'Contents', 'MacOS', 'Chromium'));
60
+ }
61
+ return candidates;
62
+ }
63
+ for (const name of ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser', 'microsoft-edge', 'brave-browser']) {
64
+ candidates.push(`/usr/bin/${name}`, `/usr/local/bin/${name}`, `/snap/bin/${name}`);
65
+ }
66
+ return candidates;
67
+ }
68
+ /**
69
+ * Pick the first installed browser.
70
+ * @param search - platform, environment, home, and an existence probe.
71
+ * @returns the executable path, or undefined when none of the candidates exist.
72
+ */
73
+ export async function findExecutable(search) {
74
+ for (const candidate of executableCandidates(search.platform, search.env, search.home)) {
75
+ if (await search.exists(candidate))
76
+ return candidate;
77
+ }
78
+ return undefined;
79
+ }
80
+ /**
81
+ * Describe what the search looked at, for an actionable error message.
82
+ * @param search - platform, environment, and home.
83
+ * @returns the candidate list as a readable line.
84
+ */
85
+ export function describeSearch(search) {
86
+ return executableCandidates(search.platform, search.env, search.home)
87
+ .map((candidate) => `\n - ${candidate}`)
88
+ .join('');
89
+ }
90
+ /**
91
+ * Read the endpoint Chrome records in its profile directory.
92
+ * @param userDataDir - the profile directory passed as `--user-data-dir`.
93
+ * @returns the published endpoint, or undefined when it is absent or incomplete.
94
+ */
95
+ export async function readActivePort(userDataDir) {
96
+ let raw;
97
+ try {
98
+ raw = await readFile(join(userDataDir, 'DevToolsActivePort'), 'utf8');
99
+ }
100
+ catch {
101
+ return undefined;
102
+ }
103
+ const [portLine, pathLine] = raw.split('\n');
104
+ const port = Number.parseInt(portLine?.trim() ?? '', 10);
105
+ const path = pathLine?.trim() ?? '';
106
+ if (!Number.isInteger(port) || port <= 0 || !path.startsWith('/'))
107
+ return undefined;
108
+ return { port, path, wsUrl: `ws://127.0.0.1:${port}${path}` };
109
+ }
110
+ /**
111
+ * Ask a DevTools HTTP endpoint for its browser WebSocket URL.
112
+ * @param origin - `http://host:port`.
113
+ * @param timeoutMs - probe budget.
114
+ * @returns the browser WebSocket URL, or undefined when nothing answers.
115
+ */
116
+ export async function probeVersion(origin, timeoutMs = 2_000) {
117
+ try {
118
+ const response = await fetch(`${origin.replace(/\/$/u, '')}/json/version`, { signal: AbortSignal.timeout(timeoutMs) });
119
+ if (!response.ok)
120
+ return undefined;
121
+ const info = (await response.json());
122
+ return info.webSocketDebuggerUrl;
123
+ }
124
+ catch {
125
+ return undefined;
126
+ }
127
+ }
128
+ /**
129
+ * Resolve a configured CDP address into a browser WebSocket URL.
130
+ *
131
+ * Accepts a `ws://` URL, or an HTTP origin such as `http://127.0.0.1:9222`
132
+ * whose `/json/version` names the browser endpoint.
133
+ * @param address - configured `cdpUrl`.
134
+ * @param timeoutMs - probe budget.
135
+ * @returns the browser WebSocket URL.
136
+ */
137
+ export async function resolveCdpAddress(address, timeoutMs = 5_000) {
138
+ const trimmed = address.trim();
139
+ if (trimmed.startsWith('ws://') || trimmed.startsWith('wss://'))
140
+ return trimmed;
141
+ const origin = trimmed.startsWith('http://') || trimmed.startsWith('https://') ? trimmed : `http://${trimmed}`;
142
+ const wsUrl = await probeVersion(origin, timeoutMs);
143
+ if (wsUrl === undefined) {
144
+ throw new Error(`cannot reach a DevTools endpoint at ${origin}: start the browser with --remote-debugging-port=<port>, or clear cdpUrl to let the plugin launch its own`);
145
+ }
146
+ return wsUrl;
147
+ }
148
+ /**
149
+ * Attach to a browser already using a profile directory.
150
+ * @param userDataDir - the profile directory.
151
+ * @returns the live endpoint, or undefined when no browser owns that directory.
152
+ */
153
+ export async function reuseBrowser(userDataDir) {
154
+ const endpoint = await readActivePort(userDataDir);
155
+ if (endpoint === undefined)
156
+ return undefined;
157
+ const wsUrl = await probeVersion(`http://127.0.0.1:${endpoint.port}`);
158
+ if (wsUrl === undefined)
159
+ return undefined;
160
+ return { wsUrl, port: endpoint.port, child: undefined, owned: false };
161
+ }
162
+ /**
163
+ * Start a browser and wait for its DevTools endpoint.
164
+ * @param request - executable, profile, window, and extra flags.
165
+ * @returns the running browser.
166
+ */
167
+ export async function launchChrome(request) {
168
+ const timeoutMs = request.startupTimeoutMs ?? 20_000;
169
+ await mkdir(request.userDataDir, { recursive: true });
170
+ await rm(join(request.userDataDir, 'DevToolsActivePort'), { force: true });
171
+ const args = [
172
+ '--remote-debugging-port=0',
173
+ `--user-data-dir=${request.userDataDir}`,
174
+ '--no-first-run',
175
+ '--no-default-browser-check',
176
+ '--disable-blink-features=AutomationControlled',
177
+ '--disable-features=Translate,MediaRouter,OptimizationHints',
178
+ '--disable-sync',
179
+ '--window-size=' + `${request.windowSize.width},${request.windowSize.height}`,
180
+ '--window-position=48,48',
181
+ ...(request.headless ? ['--headless=new'] : []),
182
+ ...(request.extraArgs ?? []),
183
+ 'about:blank',
184
+ ];
185
+ const child = spawn(request.executable, args, { stdio: ['ignore', 'ignore', 'pipe'], windowsHide: true });
186
+ let stderr = '';
187
+ child.stderr?.on('data', (chunk) => {
188
+ stderr = (stderr + chunk.toString('utf8')).slice(-2_000);
189
+ });
190
+ let exited;
191
+ child.on('exit', (code, signal) => {
192
+ exited = { code, signal };
193
+ });
194
+ child.on('error', (error) => {
195
+ exited = { code: null, signal: null };
196
+ stderr = `${stderr}\n${error.message}`;
197
+ });
198
+ const deadline = Date.now() + timeoutMs;
199
+ try {
200
+ while (Date.now() < deadline) {
201
+ if (request.signal?.aborted === true)
202
+ throw new Error('browser launch aborted');
203
+ if (exited !== undefined)
204
+ throw new Error(describeLaunchFailure(request.executable, request.userDataDir, stderr));
205
+ const endpoint = await readActivePort(request.userDataDir);
206
+ if (endpoint !== undefined && (await probeVersion(`http://127.0.0.1:${endpoint.port}`, 1_000)) !== undefined) {
207
+ return { wsUrl: endpoint.wsUrl, port: endpoint.port, child, owned: true };
208
+ }
209
+ await new Promise((resolve) => setTimeout(resolve, 100));
210
+ }
211
+ throw new Error(`Chrome did not open a DevTools endpoint within ${timeoutMs}ms.${stderr === '' ? '' : `\n${stderr.trim()}`}\nRun "${request.executable}" manually with the same --user-data-dir to see why.`);
212
+ }
213
+ catch (error) {
214
+ await stopBrowser(child);
215
+ throw error;
216
+ }
217
+ }
218
+ /**
219
+ * Stop a browser this plugin started.
220
+ * @param child - the process returned by {@link launchChrome}.
221
+ */
222
+ export async function stopBrowser(child) {
223
+ if (child === undefined || child.pid === undefined)
224
+ return;
225
+ if (child.exitCode !== null || child.signalCode !== null)
226
+ return;
227
+ const exited = new Promise((resolve) => {
228
+ child.once('exit', () => resolve());
229
+ setTimeout(resolve, 2_000).unref();
230
+ });
231
+ child.kill();
232
+ await exited;
233
+ if (child.exitCode !== null || child.signalCode !== null)
234
+ return;
235
+ if (process.platform === 'win32') {
236
+ const killer = spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });
237
+ await new Promise((resolve) => killer.once('exit', () => resolve()));
238
+ return;
239
+ }
240
+ child.kill('SIGKILL');
241
+ }
242
+ /**
243
+ * Explain why a browser that started anyway never published an endpoint.
244
+ *
245
+ * Edge ships with `RemoteDebuggingAllowed=false` on many machines and exits with
246
+ * a message about remote debugging being disallowed; without naming that case
247
+ * the operator sees a generic timeout and retries the same browser.
248
+ * @param executable - the binary that was started.
249
+ * @param userDataDir - the profile directory it was given.
250
+ * @param stderr - whatever the process wrote before exiting.
251
+ * @returns the message for the caller.
252
+ */
253
+ export function describeLaunchFailure(executable, userDataDir, stderr) {
254
+ const detail = stderr.trim() === '' ? '' : `\n${stderr.trim()}`;
255
+ if (/remote debugging is disallowed|devtools remote debugging is disallowed/iu.test(stderr)) {
256
+ return `"${executable}" refuses remote debugging on this machine, so the agent cannot drive it.${detail}\nInstall Chrome, Chromium, or Brave and let the plugin detect it, point executablePath at one of them, or set cdpUrl to a browser started with --remote-debugging-port.`;
257
+ }
258
+ return `"${executable}" exited before its DevTools endpoint came up.${detail}\nThe profile directory ${userDataDir} may be in use by another browser instance; close it or change the profile name.`;
259
+ }
260
+ //# sourceMappingURL=launch.js.map
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Projection of Chrome's accessibility tree into the numbered outline the model
3
+ * reads.
4
+ *
5
+ * The raw tree is tens of thousands of nodes for a real page and most of it is
6
+ * structure the model cannot act on. This module keeps what a reader can see or
7
+ * operate, assigns a stable `e12`-style reference to every actionable node, and
8
+ * stops at a character budget.
9
+ *
10
+ * @module @d0nj/dsh-browser/snapshot
11
+ */
12
+ /** A CDP `Accessibility.AXValue`. */
13
+ export interface AxValue {
14
+ readonly value?: unknown;
15
+ }
16
+ /** A CDP `Accessibility.AXProperty`. */
17
+ export interface AxProperty {
18
+ readonly name: string;
19
+ readonly value?: AxValue;
20
+ }
21
+ /** One node of `Accessibility.getFullAXTree`. */
22
+ export interface AxNode {
23
+ readonly nodeId: string;
24
+ readonly parentId?: string;
25
+ readonly ignored?: boolean;
26
+ readonly role?: AxValue;
27
+ readonly name?: AxValue;
28
+ readonly description?: AxValue;
29
+ readonly value?: AxValue;
30
+ readonly properties?: readonly AxProperty[];
31
+ readonly childIds?: readonly string[];
32
+ readonly backendDOMNodeId?: number;
33
+ }
34
+ /** Rendering limits. */
35
+ export interface SnapshotOptions {
36
+ /** Character budget for the rendered outline. */
37
+ readonly maxChars?: number;
38
+ /** Line budget for the rendered outline. */
39
+ readonly maxNodes?: number;
40
+ /** Render only the subtree under this backend node. */
41
+ readonly rootBackendNodeId?: number;
42
+ }
43
+ /** Rendered outline plus the reference table it assigns. */
44
+ export interface SnapshotResult {
45
+ readonly text: string;
46
+ /** `e12` → backend node id, valid until the next snapshot of this tab. */
47
+ readonly refs: ReadonlyMap<string, number>;
48
+ readonly lines: number;
49
+ readonly truncated: boolean;
50
+ }
51
+ /** Roles a user can operate with a pointer or keyboard. */
52
+ export declare const INTERACTIVE_ROLES: ReadonlySet<string>;
53
+ /**
54
+ * Collapse whitespace and cap length.
55
+ * @param input - raw accessibility text.
56
+ * @returns one line of display text.
57
+ */
58
+ export declare function normalizeText(input: string): string;
59
+ /**
60
+ * Render a full accessibility tree as a numbered outline.
61
+ * @param nodes - every node returned by `Accessibility.getFullAXTree`.
62
+ * @param options - character and line budgets.
63
+ * @returns the outline text and its reference table.
64
+ */
65
+ export declare function renderAccessibilityTree(nodes: readonly AxNode[], options?: SnapshotOptions): SnapshotResult;
66
+ //# sourceMappingURL=snapshot.d.ts.map
@@ -0,0 +1,220 @@
1
+ /** Roles a user can operate with a pointer or keyboard. */
2
+ export const INTERACTIVE_ROLES = new Set([
3
+ 'button',
4
+ 'checkbox',
5
+ 'combobox',
6
+ 'gridcell',
7
+ 'link',
8
+ 'listbox',
9
+ 'menuitem',
10
+ 'menuitemcheckbox',
11
+ 'menuitemradio',
12
+ 'option',
13
+ 'radio',
14
+ 'searchbox',
15
+ 'slider',
16
+ 'spinbutton',
17
+ 'switch',
18
+ 'tab',
19
+ 'textbox',
20
+ 'treeitem',
21
+ ]);
22
+ /** Roles worth a line even when they carry no accessible name. */
23
+ const STRUCTURAL_ROLES = new Set([
24
+ 'alert',
25
+ 'alertdialog',
26
+ 'banner',
27
+ 'cell',
28
+ 'columnheader',
29
+ 'complementary',
30
+ 'contentinfo',
31
+ 'dialog',
32
+ 'form',
33
+ 'grid',
34
+ 'heading',
35
+ 'img',
36
+ 'image',
37
+ 'iframe',
38
+ 'list',
39
+ 'listitem',
40
+ 'main',
41
+ 'menu',
42
+ 'menubar',
43
+ 'navigation',
44
+ 'row',
45
+ 'rowheader',
46
+ 'search',
47
+ 'status',
48
+ 'table',
49
+ 'tablist',
50
+ 'tabpanel',
51
+ 'toolbar',
52
+ 'tree',
53
+ 'treegrid',
54
+ ]);
55
+ /** Node roles rendered as plain quoted text. */
56
+ const TEXT_ROLES = new Set(['StaticText']);
57
+ /**
58
+ * Roles rendered transparently: their children take their place. The document
59
+ * root only repeats the page title the envelope already carries, and the others
60
+ * are Chrome's canvas-role normalization of plain markup.
61
+ */
62
+ const TRANSPARENT_ROLES = new Set([
63
+ 'Document',
64
+ 'InlineTextBox',
65
+ 'LineBreak',
66
+ 'RootWebArea',
67
+ 'WebArea',
68
+ 'none',
69
+ 'presentation',
70
+ ]);
71
+ const DEFAULT_MAX_CHARS = 12_000;
72
+ const DEFAULT_MAX_NODES = 1_500;
73
+ const MAX_NAME_CHARS = 160;
74
+ const MAX_URL_CHARS = 120;
75
+ /**
76
+ * Collapse whitespace and cap length.
77
+ * @param input - raw accessibility text.
78
+ * @returns one line of display text.
79
+ */
80
+ export function normalizeText(input) {
81
+ const collapsed = input.replace(/\s+/gu, ' ').trim();
82
+ return collapsed.length > MAX_NAME_CHARS ? `${collapsed.slice(0, MAX_NAME_CHARS - 1)}…` : collapsed;
83
+ }
84
+ function asString(value) {
85
+ return typeof value === 'string' ? value : typeof value === 'number' ? String(value) : '';
86
+ }
87
+ function stringValue(value) {
88
+ return asString(value?.value);
89
+ }
90
+ function propertyMap(properties) {
91
+ const map = new Map();
92
+ for (const property of properties ?? [])
93
+ map.set(property.name, property.value?.value);
94
+ return map;
95
+ }
96
+ function describeAttributes(role, node, properties) {
97
+ const attributes = [];
98
+ const level = properties.get('level');
99
+ if (typeof level === 'number')
100
+ attributes.push(`level=${level}`);
101
+ for (const flag of ['disabled', 'required', 'readonly', 'focused', 'selected']) {
102
+ if (properties.get(flag) === true)
103
+ attributes.push(flag);
104
+ }
105
+ const checked = properties.get('checked');
106
+ if (checked === true)
107
+ attributes.push('checked');
108
+ else if (checked === 'mixed')
109
+ attributes.push('checked=mixed');
110
+ const pressed = properties.get('pressed');
111
+ if (pressed === true)
112
+ attributes.push('pressed');
113
+ else if (pressed === 'mixed')
114
+ attributes.push('pressed=mixed');
115
+ const expanded = properties.get('expanded');
116
+ if (expanded === true)
117
+ attributes.push('expanded');
118
+ else if (expanded === false)
119
+ attributes.push('collapsed');
120
+ const invalid = properties.get('invalid');
121
+ if (typeof invalid === 'string' && invalid !== 'false')
122
+ attributes.push('invalid');
123
+ if (properties.get('modal') === true)
124
+ attributes.push('modal');
125
+ const url = properties.get('url');
126
+ if (role === 'link' && typeof url === 'string' && url !== '') {
127
+ attributes.push(`url=${url.length > MAX_URL_CHARS ? `${url.slice(0, MAX_URL_CHARS - 1)}…` : url}`);
128
+ }
129
+ const value = stringValue(node.value) || asString(properties.get('valuetext'));
130
+ if (value !== '' && (role === 'textbox' || role === 'searchbox' || role === 'combobox' || role === 'slider' || role === 'spinbutton' || role === 'progressbar')) {
131
+ attributes.push(`value="${normalizeText(value)}"`);
132
+ }
133
+ return attributes;
134
+ }
135
+ /**
136
+ * Render a full accessibility tree as a numbered outline.
137
+ * @param nodes - every node returned by `Accessibility.getFullAXTree`.
138
+ * @param options - character and line budgets.
139
+ * @returns the outline text and its reference table.
140
+ */
141
+ export function renderAccessibilityTree(nodes, options = {}) {
142
+ const maxChars = options.maxChars ?? DEFAULT_MAX_CHARS;
143
+ const maxNodes = options.maxNodes ?? DEFAULT_MAX_NODES;
144
+ const byId = new Map();
145
+ for (const node of nodes)
146
+ byId.set(node.nodeId, node);
147
+ const root = (options.rootBackendNodeId === undefined
148
+ ? undefined
149
+ : nodes.find((node) => node.backendDOMNodeId === options.rootBackendNodeId))
150
+ ?? nodes.find((node) => node.parentId === undefined)
151
+ ?? nodes[0];
152
+ const refs = new Map();
153
+ const lines = [];
154
+ let chars = 0;
155
+ let truncated = false;
156
+ if (root === undefined)
157
+ return { text: '(no accessible content)', refs, lines: 0, truncated: false };
158
+ const visited = new Set();
159
+ const stack = [{ node: root, depth: 0, parentName: '' }];
160
+ let lastText = '';
161
+ const pushChildren = (children, depth, parentName) => {
162
+ for (let index = children.length - 1; index >= 0; index--) {
163
+ stack.push({ node: children[index], depth, parentName });
164
+ }
165
+ };
166
+ while (stack.length > 0) {
167
+ if (lines.length >= maxNodes || chars >= maxChars) {
168
+ truncated = true;
169
+ break;
170
+ }
171
+ const frame = stack.pop();
172
+ const node = frame.node;
173
+ if (visited.has(node.nodeId))
174
+ continue;
175
+ visited.add(node.nodeId);
176
+ const role = stringValue(node.role);
177
+ const name = normalizeText(stringValue(node.name));
178
+ const children = (node.childIds ?? []).map((id) => byId.get(id)).filter((child) => child !== undefined);
179
+ if (TEXT_ROLES.has(role)) {
180
+ if (name !== '' && name !== frame.parentName && name !== lastText) {
181
+ lastText = name;
182
+ const line = `${' '.repeat(frame.depth)}- ${JSON.stringify(name)}`;
183
+ lines.push(line);
184
+ chars += line.length + 1;
185
+ }
186
+ pushChildren(children, frame.depth, name);
187
+ continue;
188
+ }
189
+ if (node.ignored === true || TRANSPARENT_ROLES.has(role)) {
190
+ pushChildren(children, frame.depth, frame.parentName);
191
+ continue;
192
+ }
193
+ const interactive = INTERACTIVE_ROLES.has(role);
194
+ const emit = name !== '' || interactive || STRUCTURAL_ROLES.has(role);
195
+ if (!emit) {
196
+ pushChildren(children, frame.depth, frame.parentName);
197
+ continue;
198
+ }
199
+ const attributes = describeAttributes(role, node, propertyMap(node.properties));
200
+ if (interactive && node.backendDOMNodeId !== undefined) {
201
+ const ref = `e${refs.size + 1}`;
202
+ refs.set(ref, node.backendDOMNodeId);
203
+ attributes.unshift(`ref=${ref}`);
204
+ }
205
+ const label = role === '' ? 'group' : role;
206
+ const line = `${' '.repeat(frame.depth)}- ${label}${name === '' ? '' : ` ${JSON.stringify(name)}`}${attributes.map((attribute) => ` [${attribute}]`).join('')}`;
207
+ lines.push(line);
208
+ chars += line.length + 1;
209
+ pushChildren(children, frame.depth + 1, name);
210
+ }
211
+ if (truncated)
212
+ lines.push(`… outline truncated at ${lines.length} lines; scope it with selector, or raise maxChars`);
213
+ return {
214
+ text: lines.length === 0 ? '(no accessible content)' : lines.join('\n'),
215
+ refs,
216
+ lines: lines.length,
217
+ truncated,
218
+ };
219
+ }
220
+ //# sourceMappingURL=snapshot.js.map