@namzu/browser 0.1.0
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 +32 -0
- package/LICENSE.md +110 -0
- package/README.md +149 -0
- package/dist/classifier.d.ts +70 -0
- package/dist/classifier.d.ts.map +1 -0
- package/dist/classifier.js +147 -0
- package/dist/classifier.js.map +1 -0
- package/dist/detect.d.ts +126 -0
- package/dist/detect.d.ts.map +1 -0
- package/dist/detect.js +282 -0
- package/dist/detect.js.map +1 -0
- package/dist/errors.d.ts +64 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +99 -0
- package/dist/errors.js.map +1 -0
- package/dist/host.d.ts +167 -0
- package/dist/host.d.ts.map +1 -0
- package/dist/host.js +1024 -0
- package/dist/host.js.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/page-scripts.d.ts +51 -0
- package/dist/page-scripts.d.ts.map +1 -0
- package/dist/page-scripts.js +123 -0
- package/dist/page-scripts.js.map +1 -0
- package/dist/policy.d.ts +61 -0
- package/dist/policy.d.ts.map +1 -0
- package/dist/policy.js +150 -0
- package/dist/policy.js.map +1 -0
- package/dist/profiles.d.ts +107 -0
- package/dist/profiles.d.ts.map +1 -0
- package/dist/profiles.js +312 -0
- package/dist/profiles.js.map +1 -0
- package/dist/relay.d.ts +27 -0
- package/dist/relay.d.ts.map +1 -0
- package/dist/relay.js +69 -0
- package/dist/relay.js.map +1 -0
- package/dist/snapshot.d.ts +101 -0
- package/dist/snapshot.d.ts.map +1 -0
- package/dist/snapshot.js +265 -0
- package/dist/snapshot.js.map +1 -0
- package/dist/windows-bridge-script.d.ts +29 -0
- package/dist/windows-bridge-script.d.ts.map +1 -0
- package/dist/windows-bridge-script.js +161 -0
- package/dist/windows-bridge-script.js.map +1 -0
- package/dist/windows-bridge.d.ts +120 -0
- package/dist/windows-bridge.d.ts.map +1 -0
- package/dist/windows-bridge.js +267 -0
- package/dist/windows-bridge.js.map +1 -0
- package/dist/windows-engine.d.ts +55 -0
- package/dist/windows-engine.d.ts.map +1 -0
- package/dist/windows-engine.js +154 -0
- package/dist/windows-engine.js.map +1 -0
- package/dist/wsl.d.ts +52 -0
- package/dist/wsl.d.ts.map +1 -0
- package/dist/wsl.js +134 -0
- package/dist/wsl.js.map +1 -0
- package/package.json +74 -0
- package/src/classifier.ts +191 -0
- package/src/detect.ts +432 -0
- package/src/errors.ts +121 -0
- package/src/host.ts +1217 -0
- package/src/index.ts +79 -0
- package/src/page-scripts.ts +154 -0
- package/src/policy.ts +190 -0
- package/src/profiles.ts +373 -0
- package/src/relay.ts +101 -0
- package/src/snapshot.ts +317 -0
- package/src/windows-bridge-script.ts +160 -0
- package/src/windows-bridge.ts +358 -0
- package/src/windows-engine.ts +208 -0
- package/src/wsl.ts +155 -0
package/dist/snapshot.js
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import { isCredentialField } from './classifier.js';
|
|
2
|
+
import { fieldFacts, invisibleBoxes } from './page-scripts.js';
|
|
3
|
+
/**
|
|
4
|
+
* The accessibility snapshot, and the one place that knows how Playwright
|
|
5
|
+
* produces refs and resolves them.
|
|
6
|
+
*
|
|
7
|
+
* Two Playwright surfaces are used, and they are not equally stable:
|
|
8
|
+
*
|
|
9
|
+
* - `page.ariaSnapshotJSON({ mode: 'ai', boxes: true })` is public API in the
|
|
10
|
+
* pinned version: the accessibility tree with a `ref` on every element
|
|
11
|
+
* that can be targeted, stable across snapshots for an element that stays.
|
|
12
|
+
* - `page.locator('aria-ref=eN')` resolves a ref. That selector engine is
|
|
13
|
+
* NOT documented; it is what Playwright's own agent tooling uses. It is
|
|
14
|
+
* why `playwright-core` is pinned exactly, and the contract test in
|
|
15
|
+
* `__tests__/e2e` fails if an upgrade changes it. The fallback, should it
|
|
16
|
+
* go, is CDP `Accessibility.getFullAXTree` with `DOM.resolveNode` on each
|
|
17
|
+
* node's `backendDOMNodeId` — behind this module's same three functions.
|
|
18
|
+
*
|
|
19
|
+
* Observed in 1.63.0 and relied on here: a snapshot of a single element
|
|
20
|
+
* REPLACES the page's ref table (refs outside it stop resolving), so a
|
|
21
|
+
* region is always cut out of a whole-page snapshot on this side; and a
|
|
22
|
+
* snapshot hangs while a JavaScript dialog is open, so the host never takes
|
|
23
|
+
* one then.
|
|
24
|
+
*/
|
|
25
|
+
/** The `playwright-core` version this module was verified against. */
|
|
26
|
+
export const PLAYWRIGHT_CORE_VERSION = '1.63.0';
|
|
27
|
+
const NO_HIDDEN = { scrollX: 0, scrollY: 0, boxes: [] };
|
|
28
|
+
/** Most boxes the page is asked for when looking for invisible text. */
|
|
29
|
+
const INVISIBLE_BOX_LIMIT = 5000;
|
|
30
|
+
function sameBox(a, b) {
|
|
31
|
+
return (Math.abs(a.x - b.x) < 0.5 &&
|
|
32
|
+
Math.abs(a.y - b.y) < 0.5 &&
|
|
33
|
+
Math.abs(a.width - b.width) < 0.5 &&
|
|
34
|
+
Math.abs(a.height - b.height) < 0.5);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Can nobody see this node? Too small to hold text (the 1px "visually
|
|
38
|
+
* hidden" pattern included), outside the document, or drawn invisibly. Only
|
|
39
|
+
* the main frame's boxes are comparable with the page's; inside a frame only
|
|
40
|
+
* the size counts.
|
|
41
|
+
*/
|
|
42
|
+
function unseen(node, hidden, inFrame) {
|
|
43
|
+
const box = node.box;
|
|
44
|
+
if (!box)
|
|
45
|
+
return false;
|
|
46
|
+
if (box.width <= 1 || box.height <= 1)
|
|
47
|
+
return true;
|
|
48
|
+
if (inFrame)
|
|
49
|
+
return false;
|
|
50
|
+
if (box.x + box.width + hidden.scrollX <= 0 || box.y + box.height + hidden.scrollY <= 0)
|
|
51
|
+
return true;
|
|
52
|
+
return hidden.boxes.some((b) => sameBox(b, box));
|
|
53
|
+
}
|
|
54
|
+
function flat(value) {
|
|
55
|
+
return value.replace(/\s+/g, ' ').trim();
|
|
56
|
+
}
|
|
57
|
+
function quote(value) {
|
|
58
|
+
return JSON.stringify(flat(value));
|
|
59
|
+
}
|
|
60
|
+
const FLAGS = [
|
|
61
|
+
'checked',
|
|
62
|
+
'disabled',
|
|
63
|
+
'expanded',
|
|
64
|
+
'invalid',
|
|
65
|
+
'level',
|
|
66
|
+
'pressed',
|
|
67
|
+
'selected',
|
|
68
|
+
];
|
|
69
|
+
function flags(node) {
|
|
70
|
+
let out = '';
|
|
71
|
+
for (const flag of FLAGS) {
|
|
72
|
+
const value = node[flag];
|
|
73
|
+
if (value === undefined || value === false)
|
|
74
|
+
continue;
|
|
75
|
+
out += value === true ? ` [${flag}]` : ` [${flag}=${flat(String(value))}]`;
|
|
76
|
+
}
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
/** What a credential field's value is shown as. */
|
|
80
|
+
export const REDACTED = '[value hidden: password or one-time code]';
|
|
81
|
+
/**
|
|
82
|
+
* Render nodes as the snapshot text the model reads, one element per line:
|
|
83
|
+
*
|
|
84
|
+
* ```text
|
|
85
|
+
* - link "Pricing" [ref=e7]:
|
|
86
|
+
* - /url: /pricing
|
|
87
|
+
* - textbox "Email" [ref=e9]
|
|
88
|
+
* ```
|
|
89
|
+
*
|
|
90
|
+
* Dropped: `aria-hidden` subtrees, and the own text of nodes nobody can see
|
|
91
|
+
* (their visible children are kept, one level up). With `rootRef`, only that
|
|
92
|
+
* element's subtree; `undefined` when the ref is not in the tree.
|
|
93
|
+
*/
|
|
94
|
+
export function renderAriaTree(nodes, hidden = NO_HIDDEN, rootRef, redact = new Set()) {
|
|
95
|
+
const lines = [];
|
|
96
|
+
const refs = new Map();
|
|
97
|
+
const emit = (item, depth, inFrame) => {
|
|
98
|
+
const indent = ' '.repeat(depth);
|
|
99
|
+
if (typeof item === 'string') {
|
|
100
|
+
const text = flat(item);
|
|
101
|
+
if (text)
|
|
102
|
+
lines.push(`${indent}- text: ${text}`);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (item.ariaHidden)
|
|
106
|
+
return;
|
|
107
|
+
const childFrame = inFrame || item.role === 'iframe';
|
|
108
|
+
if (unseen(item, hidden, inFrame)) {
|
|
109
|
+
for (const child of item.children ?? []) {
|
|
110
|
+
if (typeof child !== 'string')
|
|
111
|
+
emit(child, depth, childFrame);
|
|
112
|
+
}
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
let line = `${indent}- ${item.role}`;
|
|
116
|
+
if (item.name)
|
|
117
|
+
line += ` ${quote(item.name)}`;
|
|
118
|
+
line += flags(item);
|
|
119
|
+
if (item.ref) {
|
|
120
|
+
line += ` [ref=${item.ref}]`;
|
|
121
|
+
refs.set(item.ref, {
|
|
122
|
+
role: item.role,
|
|
123
|
+
...(item.name ? { name: flat(item.name) } : {}),
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
const text = item.text === undefined || item.text === ''
|
|
127
|
+
? ''
|
|
128
|
+
: item.ref !== undefined && redact.has(item.ref)
|
|
129
|
+
? REDACTED
|
|
130
|
+
: flat(item.text);
|
|
131
|
+
const hasChildren = (item.children?.length ?? 0) > 0 || item.url !== undefined || item.placeholder !== undefined;
|
|
132
|
+
if (text)
|
|
133
|
+
line += `: ${text}`;
|
|
134
|
+
else if (hasChildren)
|
|
135
|
+
line += ':';
|
|
136
|
+
lines.push(line);
|
|
137
|
+
const inner = `${indent} `;
|
|
138
|
+
if (item.url !== undefined)
|
|
139
|
+
lines.push(`${inner}- /url: ${flat(item.url)}`);
|
|
140
|
+
if (item.placeholder !== undefined)
|
|
141
|
+
lines.push(`${inner}- /placeholder: ${quote(item.placeholder)}`);
|
|
142
|
+
for (const child of item.children ?? [])
|
|
143
|
+
emit(child, depth + 1, childFrame);
|
|
144
|
+
};
|
|
145
|
+
if (rootRef === undefined) {
|
|
146
|
+
for (const node of nodes)
|
|
147
|
+
emit(node, 0, false);
|
|
148
|
+
return { text: lines.join('\n'), refs };
|
|
149
|
+
}
|
|
150
|
+
const found = findRef(nodes, rootRef, false);
|
|
151
|
+
if (!found)
|
|
152
|
+
return undefined;
|
|
153
|
+
emit(found.node, 0, found.inFrame);
|
|
154
|
+
return { text: lines.join('\n'), refs };
|
|
155
|
+
}
|
|
156
|
+
function findRef(nodes, ref, inFrame) {
|
|
157
|
+
for (const node of nodes) {
|
|
158
|
+
if (typeof node === 'string' || node.ariaHidden)
|
|
159
|
+
continue;
|
|
160
|
+
if (node.ref === ref)
|
|
161
|
+
return { node, inFrame };
|
|
162
|
+
const hit = findRef(node.children ?? [], ref, inFrame || node.role === 'iframe');
|
|
163
|
+
if (hit)
|
|
164
|
+
return hit;
|
|
165
|
+
}
|
|
166
|
+
return undefined;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Take a whole-page snapshot. `ariaSnapshotJSON` returns one root node or a
|
|
170
|
+
* list; either way the result is a list.
|
|
171
|
+
*/
|
|
172
|
+
export async function captureAriaTree(page, timeoutMs) {
|
|
173
|
+
const [tree, hidden] = await Promise.all([
|
|
174
|
+
page.ariaSnapshotJSON({ mode: 'ai', boxes: true, timeout: timeoutMs }),
|
|
175
|
+
page.evaluate(invisibleBoxes, INVISIBLE_BOX_LIMIT).catch(() => NO_HIDDEN),
|
|
176
|
+
]);
|
|
177
|
+
const nodes = (Array.isArray(tree) ? tree : [tree]);
|
|
178
|
+
return { nodes, hidden, redact: await credentialRefs(page, nodes) };
|
|
179
|
+
}
|
|
180
|
+
const TEXT_ROLES = new Set(['textbox', 'searchbox', 'spinbutton', 'combobox']);
|
|
181
|
+
/**
|
|
182
|
+
* Refs of text fields that hold a value AND are a password or one-time-code
|
|
183
|
+
* field. The accessibility tree carries an input's value as its text, a
|
|
184
|
+
* password's included — an autofilled profile would hand the model the
|
|
185
|
+
* password. Each candidate is asked about individually through its ref, which
|
|
186
|
+
* reaches into frames as the boxes cannot. A field that cannot be asked is
|
|
187
|
+
* hidden too.
|
|
188
|
+
*/
|
|
189
|
+
async function credentialRefs(page, nodes) {
|
|
190
|
+
const candidates = [];
|
|
191
|
+
const walk = (items) => {
|
|
192
|
+
for (const item of items) {
|
|
193
|
+
if (typeof item === 'string')
|
|
194
|
+
continue;
|
|
195
|
+
if (item.ref && item.text && TEXT_ROLES.has(item.role))
|
|
196
|
+
candidates.push(item.ref);
|
|
197
|
+
walk(item.children ?? []);
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
walk(nodes);
|
|
201
|
+
const redact = new Set();
|
|
202
|
+
await Promise.all(candidates.map(async (ref) => {
|
|
203
|
+
try {
|
|
204
|
+
const facts = await locateRef(page, ref).evaluate(fieldFacts, undefined, { timeout: 2000 });
|
|
205
|
+
if (isCredentialField(facts))
|
|
206
|
+
redact.add(ref);
|
|
207
|
+
}
|
|
208
|
+
catch {
|
|
209
|
+
redact.add(ref);
|
|
210
|
+
}
|
|
211
|
+
}));
|
|
212
|
+
return redact;
|
|
213
|
+
}
|
|
214
|
+
/** The element a ref names, in whichever frame it lives. */
|
|
215
|
+
export function locateRef(page, ref) {
|
|
216
|
+
return page.locator(`aria-ref=${ref}`);
|
|
217
|
+
}
|
|
218
|
+
// ---------------------------------------------------------------------------
|
|
219
|
+
// Pagination
|
|
220
|
+
// ---------------------------------------------------------------------------
|
|
221
|
+
/** Longest snapshot text kept for paging, in characters. Past it: cut, with a note. */
|
|
222
|
+
export const SNAPSHOT_TOTAL_MAX_CHARS = 400_000;
|
|
223
|
+
/**
|
|
224
|
+
* Pages of one snapshot, cut at line boundaries. A cursor names the snapshot
|
|
225
|
+
* and the offset, so a cursor from an older snapshot is refused rather than
|
|
226
|
+
* silently reading the new page from the middle.
|
|
227
|
+
*/
|
|
228
|
+
export class SnapshotPager {
|
|
229
|
+
pageChars;
|
|
230
|
+
id = 0;
|
|
231
|
+
text = '';
|
|
232
|
+
constructor(pageChars) {
|
|
233
|
+
this.pageChars = pageChars;
|
|
234
|
+
}
|
|
235
|
+
/** Start a new snapshot and return its first page. */
|
|
236
|
+
start(text) {
|
|
237
|
+
this.id += 1;
|
|
238
|
+
this.text =
|
|
239
|
+
text.length > SNAPSHOT_TOTAL_MAX_CHARS
|
|
240
|
+
? `${text.slice(0, SNAPSHOT_TOTAL_MAX_CHARS)}\n[The page's snapshot was cut at ${SNAPSHOT_TOTAL_MAX_CHARS} characters. Take a snapshot of one region with ref to read the rest.]`
|
|
241
|
+
: text;
|
|
242
|
+
return this.pageAt(0);
|
|
243
|
+
}
|
|
244
|
+
/** The page a cursor names, or `undefined` when the cursor is not from the latest snapshot. */
|
|
245
|
+
resume(cursor) {
|
|
246
|
+
const match = /^s(\d+):(\d+)$/.exec(cursor);
|
|
247
|
+
if (!match || Number(match[1]) !== this.id)
|
|
248
|
+
return undefined;
|
|
249
|
+
const offset = Number(match[2]);
|
|
250
|
+
if (offset <= 0 || offset >= this.text.length)
|
|
251
|
+
return undefined;
|
|
252
|
+
return this.pageAt(offset);
|
|
253
|
+
}
|
|
254
|
+
pageAt(offset) {
|
|
255
|
+
const rest = this.text.slice(offset);
|
|
256
|
+
if (rest.length <= this.pageChars)
|
|
257
|
+
return { text: rest };
|
|
258
|
+
const window = rest.slice(0, this.pageChars);
|
|
259
|
+
const lastBreak = window.lastIndexOf('\n');
|
|
260
|
+
const cut = lastBreak > 0 ? lastBreak : this.pageChars;
|
|
261
|
+
const next = offset + cut + (lastBreak > 0 ? 1 : 0);
|
|
262
|
+
return { text: rest.slice(0, cut), nextCursor: `s${this.id}:${next}` };
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
//# sourceMappingURL=snapshot.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"snapshot.js","sourceRoot":"","sources":["../src/snapshot.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAA;AACnD,OAAO,EAAkC,UAAU,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAA;AAE9F;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,sEAAs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Windows PowerShell
|
|
3
|
+
* 5.1 (every Windows 10 and 11 has it) through WSL interop. It needs nothing
|
|
4
|
+
* installed on Windows beyond the browser.
|
|
5
|
+
*
|
|
6
|
+
* It reads its parameters from `__NAMZU_BRIDGE_PARAMS__` (base64 JSON, so no
|
|
7
|
+
* quoting reaches PowerShell's parser), then:
|
|
8
|
+
*
|
|
9
|
+
* 1. attaches to a browser already running on the profile, if the profile's
|
|
10
|
+
* `DevToolsActivePort` names a port that answers;
|
|
11
|
+
* 2. otherwise deletes a stale `DevToolsActivePort`, starts the browser with
|
|
12
|
+
* `--user-data-dir=<profile> --remote-debugging-port=0` (the browser picks a
|
|
13
|
+
* free port on `127.0.0.1` and writes it to that file), and polls the file;
|
|
14
|
+
* 3. announces itself with one `@namzu {"type":"ready",…}` line;
|
|
15
|
+
* 4. relays CDP: every stdin line starting `{` is one message sent to the
|
|
16
|
+
* browser; every message from the browser, assembled from however many
|
|
17
|
+
* WebSocket frames it came in, is one stdout line. CDP's JSON never holds
|
|
18
|
+
* a raw newline, so a line is a message;
|
|
19
|
+
* 5. exits when stdin closes or the browser goes away. If it started the
|
|
20
|
+
* browser and was told to close on exit (and no `@namzu keep` line has
|
|
21
|
+
* arrived since), it closes the browser first: `Browser.close` over CDP,
|
|
22
|
+
* then, after ten seconds, the process it started, by id. Nothing else is
|
|
23
|
+
* ever stopped.
|
|
24
|
+
*
|
|
25
|
+
* Every line it writes is either a CDP message (`{…}`) or a control line
|
|
26
|
+
* (`@namzu {…}`). PowerShell's own errors go to stderr.
|
|
27
|
+
*/
|
|
28
|
+
export declare const WINDOWS_BRIDGE_SCRIPT: string;
|
|
29
|
+
//# sourceMappingURL=windows-bridge-script.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"windows-bridge-script.d.ts","sourceRoot":"","sources":["../src/windows-bridge-script.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,eAAO,MAAM,qBAAqB,QAoIjC,CAAA"}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The PowerShell half of the `windows-cdp` engine, run by Windows PowerShell
|
|
3
|
+
* 5.1 (every Windows 10 and 11 has it) through WSL interop. It needs nothing
|
|
4
|
+
* installed on Windows beyond the browser.
|
|
5
|
+
*
|
|
6
|
+
* It reads its parameters from `__NAMZU_BRIDGE_PARAMS__` (base64 JSON, so no
|
|
7
|
+
* quoting reaches PowerShell's parser), then:
|
|
8
|
+
*
|
|
9
|
+
* 1. attaches to a browser already running on the profile, if the profile's
|
|
10
|
+
* `DevToolsActivePort` names a port that answers;
|
|
11
|
+
* 2. otherwise deletes a stale `DevToolsActivePort`, starts the browser with
|
|
12
|
+
* `--user-data-dir=<profile> --remote-debugging-port=0` (the browser picks a
|
|
13
|
+
* free port on `127.0.0.1` and writes it to that file), and polls the file;
|
|
14
|
+
* 3. announces itself with one `@namzu {"type":"ready",…}` line;
|
|
15
|
+
* 4. relays CDP: every stdin line starting `{` is one message sent to the
|
|
16
|
+
* browser; every message from the browser, assembled from however many
|
|
17
|
+
* WebSocket frames it came in, is one stdout line. CDP's JSON never holds
|
|
18
|
+
* a raw newline, so a line is a message;
|
|
19
|
+
* 5. exits when stdin closes or the browser goes away. If it started the
|
|
20
|
+
* browser and was told to close on exit (and no `@namzu keep` line has
|
|
21
|
+
* arrived since), it closes the browser first: `Browser.close` over CDP,
|
|
22
|
+
* then, after ten seconds, the process it started, by id. Nothing else is
|
|
23
|
+
* ever stopped.
|
|
24
|
+
*
|
|
25
|
+
* Every line it writes is either a CDP message (`{…}`) or a control line
|
|
26
|
+
* (`@namzu {…}`). PowerShell's own errors go to stderr.
|
|
27
|
+
*/
|
|
28
|
+
export const WINDOWS_BRIDGE_SCRIPT = String.raw `$ErrorActionPreference = 'Stop'
|
|
29
|
+
$ProgressPreference = 'SilentlyContinue'
|
|
30
|
+
$utf8 = New-Object System.Text.UTF8Encoding $false
|
|
31
|
+
$P = $utf8.GetString([Convert]::FromBase64String('__NAMZU_BRIDGE_PARAMS__')) | ConvertFrom-Json
|
|
32
|
+
$out = New-Object System.IO.BufferedStream ([Console]::OpenStandardOutput()), 1048576
|
|
33
|
+
$in = New-Object System.IO.StreamReader ([Console]::OpenStandardInput(65536)), $utf8, $false, 1048576
|
|
34
|
+
$newline = [byte[]](10)
|
|
35
|
+
function Emit([byte[]]$bytes, [int]$count) { $out.Write($bytes, 0, $count); $out.Write($newline, 0, 1); $out.Flush() }
|
|
36
|
+
function Say($obj) { $b = $utf8.GetBytes('@namzu ' + ($obj | ConvertTo-Json -Compress)); Emit $b $b.Length }
|
|
37
|
+
function Fail([string]$code, [string]$message) { Say @{ type = 'error'; code = $code; message = $message }; exit 1 }
|
|
38
|
+
|
|
39
|
+
$dir = [string]$P.userDataDir
|
|
40
|
+
if (-not $dir) {
|
|
41
|
+
if (-not $env:LOCALAPPDATA) { Fail 'no-localappdata' 'LOCALAPPDATA is not set on the Windows side.' }
|
|
42
|
+
$dir = Join-Path $env:LOCALAPPDATA ('namzu\browser\profiles\' + [string]$P.profile)
|
|
43
|
+
}
|
|
44
|
+
$portFile = Join-Path $dir 'DevToolsActivePort'
|
|
45
|
+
|
|
46
|
+
function Read-Endpoint {
|
|
47
|
+
if (-not (Test-Path -LiteralPath $portFile)) { return $null }
|
|
48
|
+
try { $lines = [System.IO.File]::ReadAllLines($portFile) } catch { return $null }
|
|
49
|
+
if ($lines.Count -lt 2) { return $null }
|
|
50
|
+
$port = 0
|
|
51
|
+
if (-not [int]::TryParse($lines[0].Trim(), [ref]$port) -or $port -le 0 -or $port -gt 65535) { return $null }
|
|
52
|
+
$path = $lines[1].Trim()
|
|
53
|
+
if ($path -notmatch '^/devtools/browser/[A-Za-z0-9-]+$') { return $null }
|
|
54
|
+
return @{ port = $port; path = $path }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function Open-Socket($ep, [int]$ms) {
|
|
58
|
+
$s = New-Object System.Net.WebSockets.ClientWebSocket
|
|
59
|
+
$cts = New-Object System.Threading.CancellationTokenSource $ms
|
|
60
|
+
try {
|
|
61
|
+
$s.ConnectAsync([Uri]('ws://127.0.0.1:' + $ep.port + $ep.path), $cts.Token).Wait()
|
|
62
|
+
return $s
|
|
63
|
+
} catch {
|
|
64
|
+
$s.Dispose()
|
|
65
|
+
return $null
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
$ws = $null
|
|
70
|
+
$proc = $null
|
|
71
|
+
$ep = Read-Endpoint
|
|
72
|
+
if ($ep) { $ws = Open-Socket $ep 2000 }
|
|
73
|
+
if (-not $ws) {
|
|
74
|
+
if ($P.attachOnly) { Fail 'not-running' ('No browser with remote debugging is running on ' + $dir + '.') }
|
|
75
|
+
if (Test-Path -LiteralPath $portFile) { Remove-Item -LiteralPath $portFile -Force -ErrorAction SilentlyContinue }
|
|
76
|
+
New-Item -ItemType Directory -Force -Path $dir | Out-Null
|
|
77
|
+
$argv = @('"--user-data-dir=' + $dir + '"', '--remote-debugging-port=0', '--no-first-run', '--no-default-browser-check')
|
|
78
|
+
if ($P.headless) { $argv += '--headless=new'; $argv += '--window-size=1280,800' }
|
|
79
|
+
$argv += 'about:blank'
|
|
80
|
+
try { $proc = Start-Process -FilePath ([string]$P.executable) -ArgumentList $argv -PassThru }
|
|
81
|
+
catch { Fail 'launch-failed' ('Could not start ' + $P.executable + ': ' + $_.Exception.Message) }
|
|
82
|
+
$null = $proc.Handle
|
|
83
|
+
$deadline = [DateTime]::UtcNow.AddMilliseconds([int]$P.launchTimeoutMs)
|
|
84
|
+
while (-not $ws) {
|
|
85
|
+
$ep = Read-Endpoint
|
|
86
|
+
if ($ep) { $ws = Open-Socket $ep 2000 }
|
|
87
|
+
if ($ws) { break }
|
|
88
|
+
if ($proc.HasExited) {
|
|
89
|
+
Fail 'browser-exited' ('The browser exited (code ' + $proc.ExitCode + ') before it opened a debugging port. The profile is probably open in a window started without remote debugging; close that window and try again.')
|
|
90
|
+
}
|
|
91
|
+
if ([DateTime]::UtcNow -gt $deadline) {
|
|
92
|
+
try { Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue } catch { }
|
|
93
|
+
Fail 'launch-timeout' ('The browser did not open a debugging port within ' + $P.launchTimeoutMs + ' ms.')
|
|
94
|
+
}
|
|
95
|
+
Start-Sleep -Milliseconds 50
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
$launched = $null -ne $proc
|
|
100
|
+
$procId = 0
|
|
101
|
+
if ($launched) { $procId = $proc.Id }
|
|
102
|
+
Say @{ type = 'ready'; userDataDir = $dir; port = $ep.port; path = $ep.path; launched = $launched; pid = $procId; localAppData = [string]$env:LOCALAPPDATA }
|
|
103
|
+
|
|
104
|
+
$closeOnExit = [bool]$P.closeOnExit
|
|
105
|
+
$none = [System.Threading.CancellationToken]::None
|
|
106
|
+
$buf = New-Object byte[] 1048576
|
|
107
|
+
$seg = New-Object 'System.ArraySegment[byte]' -ArgumentList (,$buf)
|
|
108
|
+
$msg = New-Object System.IO.MemoryStream
|
|
109
|
+
$text = [System.Net.WebSockets.WebSocketMessageType]::Text
|
|
110
|
+
$readTask = $in.ReadLineAsync()
|
|
111
|
+
$recvTask = $ws.ReceiveAsync($seg, $none)
|
|
112
|
+
$why = 'stdin'
|
|
113
|
+
try {
|
|
114
|
+
while ($true) {
|
|
115
|
+
[void][System.Threading.Tasks.Task]::WaitAny([System.Threading.Tasks.Task[]]@($readTask, $recvTask))
|
|
116
|
+
if ($recvTask.IsCompleted) {
|
|
117
|
+
if ($recvTask.IsFaulted -or $recvTask.IsCanceled) { $why = 'socket'; break }
|
|
118
|
+
$r = $recvTask.Result
|
|
119
|
+
if ($r.MessageType -eq [System.Net.WebSockets.WebSocketMessageType]::Close) { $why = 'browser'; break }
|
|
120
|
+
$msg.Write($buf, 0, $r.Count)
|
|
121
|
+
if ($r.EndOfMessage) {
|
|
122
|
+
Emit $msg.GetBuffer() ([int]$msg.Length)
|
|
123
|
+
$msg.SetLength(0)
|
|
124
|
+
}
|
|
125
|
+
$recvTask = $ws.ReceiveAsync($seg, $none)
|
|
126
|
+
}
|
|
127
|
+
if ($readTask.IsCompleted) {
|
|
128
|
+
if ($readTask.IsFaulted) { break }
|
|
129
|
+
$line = $readTask.Result
|
|
130
|
+
if ($null -eq $line) { break }
|
|
131
|
+
if ($line.StartsWith('{')) {
|
|
132
|
+
$bytes = $utf8.GetBytes($line)
|
|
133
|
+
$ws.SendAsync((New-Object 'System.ArraySegment[byte]' -ArgumentList (,$bytes)), $text, $true, $none).Wait()
|
|
134
|
+
} elseif ($line -eq '@namzu keep') {
|
|
135
|
+
$closeOnExit = $false
|
|
136
|
+
} elseif ($line -eq '@namzu close') {
|
|
137
|
+
$closeOnExit = $true
|
|
138
|
+
}
|
|
139
|
+
$readTask = $in.ReadLineAsync()
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
} catch {
|
|
143
|
+
$why = 'error: ' + $_.Exception.Message
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if ($launched -and $closeOnExit -and -not $proc.HasExited) {
|
|
147
|
+
try {
|
|
148
|
+
if ($ws.State -eq [System.Net.WebSockets.WebSocketState]::Open) {
|
|
149
|
+
$bye = $utf8.GetBytes('{"id":2147483000,"method":"Browser.close"}')
|
|
150
|
+
$ws.SendAsync((New-Object 'System.ArraySegment[byte]' -ArgumentList (,$bye)), $text, $true, $none).Wait(2000) | Out-Null
|
|
151
|
+
}
|
|
152
|
+
} catch { }
|
|
153
|
+
if (-not $proc.WaitForExit(10000)) {
|
|
154
|
+
try { Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue } catch { }
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
try { $ws.Abort() } catch { }
|
|
158
|
+
try { Say @{ type = 'exit'; reason = $why } } catch { }
|
|
159
|
+
exit 0
|
|
160
|
+
`;
|
|
161
|
+
//# sourceMappingURL=windows-bridge-script.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"windows-bridge-script.js","sourceRoot":"","sources":["../src/windows-bridge-script.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,MAAM,CAAC,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoI9C,CAAA"}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { type ChildProcessWithoutNullStreams } from 'node:child_process';
|
|
2
|
+
/**
|
|
3
|
+
* The WSL half of the PowerShell bridge: builds the command line, starts
|
|
4
|
+
* `powershell.exe` through interop, reads its `ready` line, and moves
|
|
5
|
+
* newline-framed CDP messages in and out of its standard streams.
|
|
6
|
+
*/
|
|
7
|
+
/** What the bridge script is told, as base64 JSON inside the script. */
|
|
8
|
+
export interface WindowsBridgeParams {
|
|
9
|
+
/** The browser, as Windows sees it. */
|
|
10
|
+
readonly executable: string;
|
|
11
|
+
/** The profile name; the user data directory defaults to `%LOCALAPPDATA%\namzu\browser\profiles\<profile>`. */
|
|
12
|
+
readonly profile: string;
|
|
13
|
+
/** A user data directory (Windows path) to use instead of the default. */
|
|
14
|
+
readonly userDataDir?: string;
|
|
15
|
+
readonly headless: boolean;
|
|
16
|
+
/** Close a browser this bridge started when its stdin closes. */
|
|
17
|
+
readonly closeOnExit: boolean;
|
|
18
|
+
/** How long to wait for `DevToolsActivePort` after starting the browser. */
|
|
19
|
+
readonly launchTimeoutMs: number;
|
|
20
|
+
/** Only attach to a running browser; never start one. */
|
|
21
|
+
readonly attachOnly?: boolean;
|
|
22
|
+
}
|
|
23
|
+
/** The bridge's `ready` line. */
|
|
24
|
+
export interface WindowsBridgeReady {
|
|
25
|
+
readonly type: 'ready';
|
|
26
|
+
/** The profile's user data directory, as Windows sees it. */
|
|
27
|
+
readonly userDataDir: string;
|
|
28
|
+
/** The browser's debugging port on Windows' `127.0.0.1`. */
|
|
29
|
+
readonly port: number;
|
|
30
|
+
/** `/devtools/browser/<id>`. */
|
|
31
|
+
readonly path: string;
|
|
32
|
+
/** Whether this bridge started the browser (else it attached to a running one). */
|
|
33
|
+
readonly launched: boolean;
|
|
34
|
+
/** The started browser's Windows process id; 0 when attached. */
|
|
35
|
+
readonly pid: number;
|
|
36
|
+
readonly localAppData: string;
|
|
37
|
+
}
|
|
38
|
+
/** A refusal from the bridge script, before `ready`. */
|
|
39
|
+
export declare class WindowsBridgeError extends Error {
|
|
40
|
+
readonly code: string;
|
|
41
|
+
readonly name = "WindowsBridgeError";
|
|
42
|
+
constructor(code: string, message: string);
|
|
43
|
+
}
|
|
44
|
+
/** PowerShell's `-EncodedCommand` form: the script as UTF-16LE, base64. */
|
|
45
|
+
export declare function encodePowerShellCommand(script: string): string;
|
|
46
|
+
/** The bridge script with `params` embedded. */
|
|
47
|
+
export declare function bridgeScript(params: WindowsBridgeParams): string;
|
|
48
|
+
/** `powershell.exe`'s arguments for the bridge. */
|
|
49
|
+
export declare function bridgeArguments(params: WindowsBridgeParams): string[];
|
|
50
|
+
/**
|
|
51
|
+
* Chrome's `DevToolsActivePort` file: the port on the first line, the browser
|
|
52
|
+
* target's path on the second. `undefined` for anything else.
|
|
53
|
+
*/
|
|
54
|
+
export declare function parseDevToolsActivePort(text: string | undefined): {
|
|
55
|
+
port: number;
|
|
56
|
+
path: string;
|
|
57
|
+
} | undefined;
|
|
58
|
+
/**
|
|
59
|
+
* Cuts a byte stream into lines at `\n` (a trailing `\r` is dropped).
|
|
60
|
+
* Chunks are kept as they arrive and joined once per line, and only the new
|
|
61
|
+
* chunk is scanned, so a multi-megabyte line costs one copy.
|
|
62
|
+
*/
|
|
63
|
+
export declare class LineSplitter {
|
|
64
|
+
private readonly onLine;
|
|
65
|
+
private pending;
|
|
66
|
+
private pendingBytes;
|
|
67
|
+
constructor(onLine: (line: Buffer) => void);
|
|
68
|
+
push(chunk: Buffer): void;
|
|
69
|
+
/** Bytes held for a line not yet ended. */
|
|
70
|
+
get buffered(): number;
|
|
71
|
+
}
|
|
72
|
+
export interface StartWindowsBridgeOptions {
|
|
73
|
+
/** `powershell.exe`, as WSL sees it. */
|
|
74
|
+
readonly powershell: string;
|
|
75
|
+
readonly params: WindowsBridgeParams;
|
|
76
|
+
/** The environment for `powershell.exe`; must carry a working `WSL_INTEROP`. */
|
|
77
|
+
readonly env: NodeJS.ProcessEnv;
|
|
78
|
+
/** How long to wait for `ready`. Default: the launch timeout plus 15 s. */
|
|
79
|
+
readonly readyTimeoutMs?: number;
|
|
80
|
+
/** For tests: start something other than `powershell.exe`. */
|
|
81
|
+
readonly spawnProcess?: (command: string, args: readonly string[], env: NodeJS.ProcessEnv) => ChildProcessWithoutNullStreams;
|
|
82
|
+
}
|
|
83
|
+
/** A running bridge: one `powershell.exe`, one browser connection. */
|
|
84
|
+
export declare class WindowsCdpBridge {
|
|
85
|
+
private readonly child;
|
|
86
|
+
readonly ready: WindowsBridgeReady;
|
|
87
|
+
private readonly stderrTail;
|
|
88
|
+
private messageListener;
|
|
89
|
+
private readonly early;
|
|
90
|
+
private exitedFlag;
|
|
91
|
+
/** Resolves when the bridge process has exited. */
|
|
92
|
+
readonly exited: Promise<{
|
|
93
|
+
code: number | null;
|
|
94
|
+
signal: NodeJS.Signals | null;
|
|
95
|
+
}>;
|
|
96
|
+
private constructor();
|
|
97
|
+
/** The bridge's process id on the Linux side. */
|
|
98
|
+
get pid(): number | undefined;
|
|
99
|
+
get alive(): boolean;
|
|
100
|
+
static start(options: StartWindowsBridgeOptions): Promise<WindowsCdpBridge>;
|
|
101
|
+
private deliver;
|
|
102
|
+
/** Receive every CDP message from the browser, one per call, as UTF-8 JSON. */
|
|
103
|
+
onMessage(listener: (message: Buffer) => void): void;
|
|
104
|
+
/**
|
|
105
|
+
* Send one CDP message. A message with a raw newline (legal JSON
|
|
106
|
+
* whitespace, never produced by Playwright) is re-serialised so it stays
|
|
107
|
+
* one line.
|
|
108
|
+
*/
|
|
109
|
+
send(message: string | Buffer): boolean;
|
|
110
|
+
/** Leave a browser this bridge started running when it exits. */
|
|
111
|
+
keepBrowser(): void;
|
|
112
|
+
/**
|
|
113
|
+
* Close stdin and wait for the bridge to exit (it closes a browser it
|
|
114
|
+
* started unless told to keep it). Killed after `timeoutMs`.
|
|
115
|
+
*/
|
|
116
|
+
stop(timeoutMs?: number): Promise<void>;
|
|
117
|
+
/** The end of what `powershell.exe` wrote to stderr. */
|
|
118
|
+
get stderr(): string;
|
|
119
|
+
}
|
|
120
|
+
//# sourceMappingURL=windows-bridge.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"windows-bridge.d.ts","sourceRoot":"","sources":["../src/windows-bridge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,8BAA8B,EAAS,MAAM,oBAAoB,CAAA;AAG/E;;;;GAIG;AAEH,wEAAwE;AACxE,MAAM,WAAW,mBAAmB;IACnC,uCAAuC;IACvC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAC3B,+GAA+G;IAC/G,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,0EAA0E;IAC1E,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAA;IAC7B,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAA;IAC1B,iEAAiE;IACjE,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAA;IAC7B,4EAA4E;IAC5E,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAA;IAChC,yDAAyD;IACzD,QAAQ,CAAC,UAAU,CAAC,EAAE,OAAO,CAAA;CAC7B;AAED,iCAAiC;AACjC,MAAM,WAAW,kBAAkB;IAClC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAA;IACtB,6DAA6D;IAC7D,QAAQ,CAAC,WAAW,EA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