@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.
Files changed (74) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/LICENSE.md +110 -0
  3. package/README.md +149 -0
  4. package/dist/classifier.d.ts +70 -0
  5. package/dist/classifier.d.ts.map +1 -0
  6. package/dist/classifier.js +147 -0
  7. package/dist/classifier.js.map +1 -0
  8. package/dist/detect.d.ts +126 -0
  9. package/dist/detect.d.ts.map +1 -0
  10. package/dist/detect.js +282 -0
  11. package/dist/detect.js.map +1 -0
  12. package/dist/errors.d.ts +64 -0
  13. package/dist/errors.d.ts.map +1 -0
  14. package/dist/errors.js +99 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/host.d.ts +167 -0
  17. package/dist/host.d.ts.map +1 -0
  18. package/dist/host.js +1024 -0
  19. package/dist/host.js.map +1 -0
  20. package/dist/index.d.ts +17 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +10 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/page-scripts.d.ts +51 -0
  25. package/dist/page-scripts.d.ts.map +1 -0
  26. package/dist/page-scripts.js +123 -0
  27. package/dist/page-scripts.js.map +1 -0
  28. package/dist/policy.d.ts +61 -0
  29. package/dist/policy.d.ts.map +1 -0
  30. package/dist/policy.js +150 -0
  31. package/dist/policy.js.map +1 -0
  32. package/dist/profiles.d.ts +107 -0
  33. package/dist/profiles.d.ts.map +1 -0
  34. package/dist/profiles.js +312 -0
  35. package/dist/profiles.js.map +1 -0
  36. package/dist/relay.d.ts +27 -0
  37. package/dist/relay.d.ts.map +1 -0
  38. package/dist/relay.js +69 -0
  39. package/dist/relay.js.map +1 -0
  40. package/dist/snapshot.d.ts +101 -0
  41. package/dist/snapshot.d.ts.map +1 -0
  42. package/dist/snapshot.js +265 -0
  43. package/dist/snapshot.js.map +1 -0
  44. package/dist/windows-bridge-script.d.ts +29 -0
  45. package/dist/windows-bridge-script.d.ts.map +1 -0
  46. package/dist/windows-bridge-script.js +161 -0
  47. package/dist/windows-bridge-script.js.map +1 -0
  48. package/dist/windows-bridge.d.ts +120 -0
  49. package/dist/windows-bridge.d.ts.map +1 -0
  50. package/dist/windows-bridge.js +267 -0
  51. package/dist/windows-bridge.js.map +1 -0
  52. package/dist/windows-engine.d.ts +55 -0
  53. package/dist/windows-engine.d.ts.map +1 -0
  54. package/dist/windows-engine.js +154 -0
  55. package/dist/windows-engine.js.map +1 -0
  56. package/dist/wsl.d.ts +52 -0
  57. package/dist/wsl.d.ts.map +1 -0
  58. package/dist/wsl.js +134 -0
  59. package/dist/wsl.js.map +1 -0
  60. package/package.json +74 -0
  61. package/src/classifier.ts +191 -0
  62. package/src/detect.ts +432 -0
  63. package/src/errors.ts +121 -0
  64. package/src/host.ts +1217 -0
  65. package/src/index.ts +79 -0
  66. package/src/page-scripts.ts +154 -0
  67. package/src/policy.ts +190 -0
  68. package/src/profiles.ts +373 -0
  69. package/src/relay.ts +101 -0
  70. package/src/snapshot.ts +317 -0
  71. package/src/windows-bridge-script.ts +160 -0
  72. package/src/windows-bridge.ts +358 -0
  73. package/src/windows-engine.ts +208 -0
  74. package/src/wsl.ts +155 -0
@@ -0,0 +1,317 @@
1
+ import type { BrowserRefDescription } from '@namzu/sdk'
2
+ import type { Locator, Page } from 'playwright-core'
3
+ import { isCredentialField } from './classifier.js'
4
+ import { type InvisibleBoxes, type Rect, fieldFacts, invisibleBoxes } from './page-scripts.js'
5
+
6
+ /**
7
+ * The accessibility snapshot, and the one place that knows how Playwright
8
+ * produces refs and resolves them.
9
+ *
10
+ * Two Playwright surfaces are used, and they are not equally stable:
11
+ *
12
+ * - `page.ariaSnapshotJSON({ mode: 'ai', boxes: true })` is public API in the
13
+ * pinned version: the accessibility tree with a `ref` on every element
14
+ * that can be targeted, stable across snapshots for an element that stays.
15
+ * - `page.locator('aria-ref=eN')` resolves a ref. That selector engine is
16
+ * NOT documented; it is what Playwright's own agent tooling uses. It is
17
+ * why `playwright-core` is pinned exactly, and the contract test in
18
+ * `__tests__/e2e` fails if an upgrade changes it. The fallback, should it
19
+ * go, is CDP `Accessibility.getFullAXTree` with `DOM.resolveNode` on each
20
+ * node's `backendDOMNodeId` — behind this module's same three functions.
21
+ *
22
+ * Observed in 1.63.0 and relied on here: a snapshot of a single element
23
+ * REPLACES the page's ref table (refs outside it stop resolving), so a
24
+ * region is always cut out of a whole-page snapshot on this side; and a
25
+ * snapshot hangs while a JavaScript dialog is open, so the host never takes
26
+ * one then.
27
+ */
28
+
29
+ /** The `playwright-core` version this module was verified against. */
30
+ export const PLAYWRIGHT_CORE_VERSION = '1.63.0'
31
+
32
+ /** One node of `ariaSnapshotJSON({ mode: 'ai' })`. Fields beyond these are ignored. */
33
+ export interface AriaNode {
34
+ readonly role: string
35
+ readonly name?: string
36
+ readonly ref?: string
37
+ readonly box?: Rect
38
+ readonly text?: string
39
+ readonly url?: string
40
+ readonly placeholder?: string
41
+ readonly ariaHidden?: boolean
42
+ readonly checked?: boolean | 'mixed'
43
+ readonly disabled?: boolean
44
+ readonly expanded?: boolean
45
+ readonly invalid?: boolean | string
46
+ readonly level?: number
47
+ readonly pressed?: boolean | 'mixed'
48
+ readonly selected?: boolean
49
+ readonly children?: readonly (string | AriaNode)[]
50
+ }
51
+
52
+ /** What a rendered snapshot knows: its lines, and every ref it showed. */
53
+ export interface RenderedSnapshot {
54
+ readonly text: string
55
+ readonly refs: ReadonlyMap<string, BrowserRefDescription>
56
+ }
57
+
58
+ const NO_HIDDEN: InvisibleBoxes = { scrollX: 0, scrollY: 0, boxes: [] }
59
+
60
+ /** Most boxes the page is asked for when looking for invisible text. */
61
+ const INVISIBLE_BOX_LIMIT = 5000
62
+
63
+ function sameBox(a: Rect, b: Rect): boolean {
64
+ return (
65
+ Math.abs(a.x - b.x) < 0.5 &&
66
+ Math.abs(a.y - b.y) < 0.5 &&
67
+ Math.abs(a.width - b.width) < 0.5 &&
68
+ Math.abs(a.height - b.height) < 0.5
69
+ )
70
+ }
71
+
72
+ /**
73
+ * Can nobody see this node? Too small to hold text (the 1px "visually
74
+ * hidden" pattern included), outside the document, or drawn invisibly. Only
75
+ * the main frame's boxes are comparable with the page's; inside a frame only
76
+ * the size counts.
77
+ */
78
+ function unseen(node: AriaNode, hidden: InvisibleBoxes, inFrame: boolean): boolean {
79
+ const box = node.box
80
+ if (!box) return false
81
+ if (box.width <= 1 || box.height <= 1) return true
82
+ if (inFrame) return false
83
+ if (box.x + box.width + hidden.scrollX <= 0 || box.y + box.height + hidden.scrollY <= 0)
84
+ return true
85
+ return hidden.boxes.some((b) => sameBox(b, box))
86
+ }
87
+
88
+ function flat(value: string): string {
89
+ return value.replace(/\s+/g, ' ').trim()
90
+ }
91
+
92
+ function quote(value: string): string {
93
+ return JSON.stringify(flat(value))
94
+ }
95
+
96
+ const FLAGS = [
97
+ 'checked',
98
+ 'disabled',
99
+ 'expanded',
100
+ 'invalid',
101
+ 'level',
102
+ 'pressed',
103
+ 'selected',
104
+ ] as const
105
+
106
+ function flags(node: AriaNode): string {
107
+ let out = ''
108
+ for (const flag of FLAGS) {
109
+ const value = node[flag]
110
+ if (value === undefined || value === false) continue
111
+ out += value === true ? ` [${flag}]` : ` [${flag}=${flat(String(value))}]`
112
+ }
113
+ return out
114
+ }
115
+
116
+ /** What a credential field's value is shown as. */
117
+ export const REDACTED = '[value hidden: password or one-time code]'
118
+
119
+ /**
120
+ * Render nodes as the snapshot text the model reads, one element per line:
121
+ *
122
+ * ```text
123
+ * - link "Pricing" [ref=e7]:
124
+ * - /url: /pricing
125
+ * - textbox "Email" [ref=e9]
126
+ * ```
127
+ *
128
+ * Dropped: `aria-hidden` subtrees, and the own text of nodes nobody can see
129
+ * (their visible children are kept, one level up). With `rootRef`, only that
130
+ * element's subtree; `undefined` when the ref is not in the tree.
131
+ */
132
+ export function renderAriaTree(
133
+ nodes: readonly (string | AriaNode)[],
134
+ hidden: InvisibleBoxes = NO_HIDDEN,
135
+ rootRef?: string,
136
+ redact: ReadonlySet<string> = new Set(),
137
+ ): RenderedSnapshot | undefined {
138
+ const lines: string[] = []
139
+ const refs = new Map<string, BrowserRefDescription>()
140
+
141
+ const emit = (item: string | AriaNode, depth: number, inFrame: boolean): void => {
142
+ const indent = ' '.repeat(depth)
143
+ if (typeof item === 'string') {
144
+ const text = flat(item)
145
+ if (text) lines.push(`${indent}- text: ${text}`)
146
+ return
147
+ }
148
+ if (item.ariaHidden) return
149
+ const childFrame = inFrame || item.role === 'iframe'
150
+ if (unseen(item, hidden, inFrame)) {
151
+ for (const child of item.children ?? []) {
152
+ if (typeof child !== 'string') emit(child, depth, childFrame)
153
+ }
154
+ return
155
+ }
156
+ let line = `${indent}- ${item.role}`
157
+ if (item.name) line += ` ${quote(item.name)}`
158
+ line += flags(item)
159
+ if (item.ref) {
160
+ line += ` [ref=${item.ref}]`
161
+ refs.set(item.ref, {
162
+ role: item.role,
163
+ ...(item.name ? { name: flat(item.name) } : {}),
164
+ })
165
+ }
166
+ const text =
167
+ item.text === undefined || item.text === ''
168
+ ? ''
169
+ : item.ref !== undefined && redact.has(item.ref)
170
+ ? REDACTED
171
+ : flat(item.text)
172
+ const hasChildren =
173
+ (item.children?.length ?? 0) > 0 || item.url !== undefined || item.placeholder !== undefined
174
+ if (text) line += `: ${text}`
175
+ else if (hasChildren) line += ':'
176
+ lines.push(line)
177
+ const inner = `${indent} `
178
+ if (item.url !== undefined) lines.push(`${inner}- /url: ${flat(item.url)}`)
179
+ if (item.placeholder !== undefined)
180
+ lines.push(`${inner}- /placeholder: ${quote(item.placeholder)}`)
181
+ for (const child of item.children ?? []) emit(child, depth + 1, childFrame)
182
+ }
183
+
184
+ if (rootRef === undefined) {
185
+ for (const node of nodes) emit(node, 0, false)
186
+ return { text: lines.join('\n'), refs }
187
+ }
188
+ const found = findRef(nodes, rootRef, false)
189
+ if (!found) return undefined
190
+ emit(found.node, 0, found.inFrame)
191
+ return { text: lines.join('\n'), refs }
192
+ }
193
+
194
+ function findRef(
195
+ nodes: readonly (string | AriaNode)[],
196
+ ref: string,
197
+ inFrame: boolean,
198
+ ): { node: AriaNode; inFrame: boolean } | undefined {
199
+ for (const node of nodes) {
200
+ if (typeof node === 'string' || node.ariaHidden) continue
201
+ if (node.ref === ref) return { node, inFrame }
202
+ const hit = findRef(node.children ?? [], ref, inFrame || node.role === 'iframe')
203
+ if (hit) return hit
204
+ }
205
+ return undefined
206
+ }
207
+
208
+ /**
209
+ * Take a whole-page snapshot. `ariaSnapshotJSON` returns one root node or a
210
+ * list; either way the result is a list.
211
+ */
212
+ export async function captureAriaTree(
213
+ page: Page,
214
+ timeoutMs: number,
215
+ ): Promise<{ nodes: (string | AriaNode)[]; hidden: InvisibleBoxes; redact: Set<string> }> {
216
+ const [tree, hidden] = await Promise.all([
217
+ page.ariaSnapshotJSON({ mode: 'ai', boxes: true, timeout: timeoutMs }),
218
+ page.evaluate(invisibleBoxes, INVISIBLE_BOX_LIMIT).catch(() => NO_HIDDEN),
219
+ ])
220
+ const nodes = (Array.isArray(tree) ? tree : [tree]) as unknown as (string | AriaNode)[]
221
+ return { nodes, hidden, redact: await credentialRefs(page, nodes) }
222
+ }
223
+
224
+ const TEXT_ROLES = new Set(['textbox', 'searchbox', 'spinbutton', 'combobox'])
225
+
226
+ /**
227
+ * Refs of text fields that hold a value AND are a password or one-time-code
228
+ * field. The accessibility tree carries an input's value as its text, a
229
+ * password's included — an autofilled profile would hand the model the
230
+ * password. Each candidate is asked about individually through its ref, which
231
+ * reaches into frames as the boxes cannot. A field that cannot be asked is
232
+ * hidden too.
233
+ */
234
+ async function credentialRefs(
235
+ page: Page,
236
+ nodes: readonly (string | AriaNode)[],
237
+ ): Promise<Set<string>> {
238
+ const candidates: string[] = []
239
+ const walk = (items: readonly (string | AriaNode)[]): void => {
240
+ for (const item of items) {
241
+ if (typeof item === 'string') continue
242
+ if (item.ref && item.text && TEXT_ROLES.has(item.role)) candidates.push(item.ref)
243
+ walk(item.children ?? [])
244
+ }
245
+ }
246
+ walk(nodes)
247
+ const redact = new Set<string>()
248
+ await Promise.all(
249
+ candidates.map(async (ref) => {
250
+ try {
251
+ const facts = await locateRef(page, ref).evaluate(fieldFacts, undefined, { timeout: 2000 })
252
+ if (isCredentialField(facts)) redact.add(ref)
253
+ } catch {
254
+ redact.add(ref)
255
+ }
256
+ }),
257
+ )
258
+ return redact
259
+ }
260
+
261
+ /** The element a ref names, in whichever frame it lives. */
262
+ export function locateRef(page: Page, ref: string): Locator {
263
+ return page.locator(`aria-ref=${ref}`)
264
+ }
265
+
266
+ // ---------------------------------------------------------------------------
267
+ // Pagination
268
+ // ---------------------------------------------------------------------------
269
+
270
+ /** Longest snapshot text kept for paging, in characters. Past it: cut, with a note. */
271
+ export const SNAPSHOT_TOTAL_MAX_CHARS = 400_000
272
+
273
+ export interface SnapshotPage {
274
+ readonly text: string
275
+ readonly nextCursor?: string
276
+ }
277
+
278
+ /**
279
+ * Pages of one snapshot, cut at line boundaries. A cursor names the snapshot
280
+ * and the offset, so a cursor from an older snapshot is refused rather than
281
+ * silently reading the new page from the middle.
282
+ */
283
+ export class SnapshotPager {
284
+ private id = 0
285
+ private text = ''
286
+
287
+ constructor(private readonly pageChars: number) {}
288
+
289
+ /** Start a new snapshot and return its first page. */
290
+ start(text: string): SnapshotPage {
291
+ this.id += 1
292
+ this.text =
293
+ text.length > SNAPSHOT_TOTAL_MAX_CHARS
294
+ ? `${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.]`
295
+ : text
296
+ return this.pageAt(0)
297
+ }
298
+
299
+ /** The page a cursor names, or `undefined` when the cursor is not from the latest snapshot. */
300
+ resume(cursor: string): SnapshotPage | undefined {
301
+ const match = /^s(\d+):(\d+)$/.exec(cursor)
302
+ if (!match || Number(match[1]) !== this.id) return undefined
303
+ const offset = Number(match[2])
304
+ if (offset <= 0 || offset >= this.text.length) return undefined
305
+ return this.pageAt(offset)
306
+ }
307
+
308
+ private pageAt(offset: number): SnapshotPage {
309
+ const rest = this.text.slice(offset)
310
+ if (rest.length <= this.pageChars) return { text: rest }
311
+ const window = rest.slice(0, this.pageChars)
312
+ const lastBreak = window.lastIndexOf('\n')
313
+ const cut = lastBreak > 0 ? lastBreak : this.pageChars
314
+ const next = offset + cut + (lastBreak > 0 ? 1 : 0)
315
+ return { text: rest.slice(0, cut), nextCursor: `s${this.id}:${next}` }
316
+ }
317
+ }
@@ -0,0 +1,160 @@
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
+ `