@namzu/computer-use 1.4.2 → 2.0.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 +65 -0
  2. package/README.md +96 -5
  3. package/dist/SubprocessComputerUseHost.d.ts +45 -5
  4. package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
  5. package/dist/SubprocessComputerUseHost.js +94 -8
  6. package/dist/SubprocessComputerUseHost.js.map +1 -1
  7. package/dist/adapters/cua-driver/adapter.d.ts +100 -0
  8. package/dist/adapters/cua-driver/adapter.d.ts.map +1 -0
  9. package/dist/adapters/cua-driver/adapter.js +459 -0
  10. package/dist/adapters/cua-driver/adapter.js.map +1 -0
  11. package/dist/adapters/cua-driver/client.d.ts +108 -0
  12. package/dist/adapters/cua-driver/client.d.ts.map +1 -0
  13. package/dist/adapters/cua-driver/client.js +316 -0
  14. package/dist/adapters/cua-driver/client.js.map +1 -0
  15. package/dist/adapters/cua-driver/keys.d.ts +24 -0
  16. package/dist/adapters/cua-driver/keys.d.ts.map +1 -0
  17. package/dist/adapters/cua-driver/keys.js +106 -0
  18. package/dist/adapters/cua-driver/keys.js.map +1 -0
  19. package/dist/adapters/cua-driver/provision.d.ts +80 -0
  20. package/dist/adapters/cua-driver/provision.d.ts.map +1 -0
  21. package/dist/adapters/cua-driver/provision.js +147 -0
  22. package/dist/adapters/cua-driver/provision.js.map +1 -0
  23. package/dist/adapters/cua-driver/ui-tree.d.ts +42 -0
  24. package/dist/adapters/cua-driver/ui-tree.d.ts.map +1 -0
  25. package/dist/adapters/cua-driver/ui-tree.js +187 -0
  26. package/dist/adapters/cua-driver/ui-tree.js.map +1 -0
  27. package/dist/adapters/cua-driver/zip.d.ts +6 -0
  28. package/dist/adapters/cua-driver/zip.d.ts.map +1 -0
  29. package/dist/adapters/cua-driver/zip.js +86 -0
  30. package/dist/adapters/cua-driver/zip.js.map +1 -0
  31. package/dist/adapters/darwin.d.ts +23 -0
  32. package/dist/adapters/darwin.d.ts.map +1 -1
  33. package/dist/adapters/darwin.js +96 -31
  34. package/dist/adapters/darwin.js.map +1 -1
  35. package/dist/adapters/linux-wayland.d.ts.map +1 -1
  36. package/dist/adapters/linux-wayland.js +12 -0
  37. package/dist/adapters/linux-wayland.js.map +1 -1
  38. package/dist/adapters/linux-x11.d.ts.map +1 -1
  39. package/dist/adapters/linux-x11.js +12 -0
  40. package/dist/adapters/linux-x11.js.map +1 -1
  41. package/dist/adapters/types.d.ts +23 -5
  42. package/dist/adapters/types.d.ts.map +1 -1
  43. package/dist/adapters/types.js.map +1 -1
  44. package/dist/adapters/win32-powershell.d.ts +41 -0
  45. package/dist/adapters/win32-powershell.d.ts.map +1 -0
  46. package/dist/adapters/win32-powershell.js +407 -0
  47. package/dist/adapters/win32-powershell.js.map +1 -0
  48. package/dist/adapters/win32.d.ts +39 -11
  49. package/dist/adapters/win32.d.ts.map +1 -1
  50. package/dist/adapters/win32.js +72 -311
  51. package/dist/adapters/win32.js.map +1 -1
  52. package/dist/adapters/wsl.d.ts +46 -0
  53. package/dist/adapters/wsl.d.ts.map +1 -0
  54. package/dist/adapters/wsl.js +130 -0
  55. package/dist/adapters/wsl.js.map +1 -0
  56. package/dist/index.d.ts +2 -1
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js.map +1 -1
  59. package/package.json +3 -3
  60. package/src/SubprocessComputerUseHost.ts +115 -8
  61. package/src/adapters/cua-driver/adapter.ts +571 -0
  62. package/src/adapters/cua-driver/client.ts +451 -0
  63. package/src/adapters/cua-driver/keys.ts +111 -0
  64. package/src/adapters/cua-driver/provision.ts +208 -0
  65. package/src/adapters/cua-driver/ui-tree.ts +234 -0
  66. package/src/adapters/cua-driver/zip.ts +90 -0
  67. package/src/adapters/darwin.ts +124 -38
  68. package/src/adapters/linux-wayland.ts +13 -0
  69. package/src/adapters/linux-x11.ts +13 -0
  70. package/src/adapters/types.ts +29 -4
  71. package/src/adapters/win32-powershell.ts +482 -0
  72. package/src/adapters/win32.ts +112 -356
  73. package/src/adapters/wsl.ts +150 -0
  74. package/src/index.ts +5 -1
@@ -0,0 +1,208 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
3
+ import { homedir } from 'node:os'
4
+ import { join } from 'node:path'
5
+ import { extractZipEntry } from './zip.js'
6
+
7
+ /**
8
+ * The cua-driver build this package drives on Windows, pinned by version and
9
+ * by SHA-256 of both the release archive and the executable inside it.
10
+ *
11
+ * cua-driver (github.com/trycua/cua, MIT) publishes every build as a GitHub
12
+ * prerelease with a `checksums.txt`; the archive hashes below are the ones it
13
+ * lists for `cua-driver-rs-v0.28.2`, and the executable hashes were taken
14
+ * from those archives. Moving to another build means changing all four and
15
+ * re-running the Windows verification in `docs/sdk/computer-actions.md`.
16
+ */
17
+ export const CUA_DRIVER_RELEASE = {
18
+ version: '0.28.2',
19
+ tag: 'cua-driver-rs-v0.28.2',
20
+ baseUrl: 'https://github.com/trycua/cua/releases/download',
21
+ windows: {
22
+ x64: {
23
+ archive: 'cua-driver-rs-0.28.2-windows-x86_64-binary.zip',
24
+ archiveSize: 29_085_823,
25
+ archiveSha256: '1f4bfceeab64cb7f56be7aad774c3dc2d2910d1427e4be1d79939c706e8029ba',
26
+ exeSize: 30_922_064,
27
+ exeSha256: 'dbbd52d75759900155fbf3d5f0a13c759a12d06ef17338b88b3f2b8b9c1ef8dc',
28
+ },
29
+ arm64: {
30
+ archive: 'cua-driver-rs-0.28.2-windows-arm64-binary.zip',
31
+ archiveSize: 27_394_922,
32
+ archiveSha256: '578b88ff2dd56f06eb7e984d73aaf5e76f59c6fde9542c967d6a30d00213c680',
33
+ exeSize: 26_643_272,
34
+ exeSha256: '8f36d502e841485c59fd6734e2193841c61f234870f8b92c3d7d0c18123b28ba',
35
+ },
36
+ },
37
+ } as const
38
+
39
+ export type CuaDriverArch = keyof typeof CUA_DRIVER_RELEASE.windows
40
+
41
+ /** One pinned archive and the executable inside it. */
42
+ export interface CuaDriverAssetPin {
43
+ readonly archive: string
44
+ readonly archiveSize: number
45
+ readonly archiveSha256: string
46
+ readonly exeSize: number
47
+ readonly exeSha256: string
48
+ }
49
+
50
+ const EXE_NAME = 'cua-driver.exe'
51
+
52
+ export interface ResolveCuaDriverOptions {
53
+ /** An existing `cua-driver.exe` to use as it is: no download, no hash check. */
54
+ readonly path?: string
55
+ /** Where the pinned build is kept. Default `<NAMZU_HOME>/computer-use/cua-driver/<version>`. */
56
+ readonly cacheDir?: string
57
+ /** Download the pinned build when it is not cached. Default true. */
58
+ readonly download?: boolean
59
+ /** Default `process.arch`. Windows under WSL has the distro's architecture. */
60
+ readonly arch?: string
61
+ readonly env?: NodeJS.ProcessEnv
62
+ /** How long the archive download may take. Default 180 s. */
63
+ readonly downloadTimeoutMs?: number
64
+ /** For tests. */
65
+ readonly fetch?: typeof fetch
66
+ /** For tests: another pin than the architecture's. */
67
+ readonly asset?: CuaDriverAssetPin
68
+ }
69
+
70
+ export interface ResolvedCuaDriver {
71
+ readonly path: string
72
+ /** Where it came from: the caller, the cache, or a download just now. */
73
+ readonly source: 'configured' | 'cache' | 'download'
74
+ }
75
+
76
+ export class CuaDriverUnavailableError extends Error {
77
+ override readonly name = 'CuaDriverUnavailableError'
78
+ }
79
+
80
+ /** `<NAMZU_HOME>/computer-use/cua-driver/<version>`, `NAMZU_HOME` defaulting to `~/.namzu`. */
81
+ export function defaultCuaDriverCacheDir(env: NodeJS.ProcessEnv = process.env): string {
82
+ const home =
83
+ env.NAMZU_HOME && env.NAMZU_HOME.length > 0 ? env.NAMZU_HOME : join(homedir(), '.namzu')
84
+ return join(home, 'computer-use', 'cua-driver', CUA_DRIVER_RELEASE.version)
85
+ }
86
+
87
+ /** The pinned asset for an architecture, or undefined when cua-driver ships none. */
88
+ export function cuaDriverAsset(arch: string): CuaDriverAssetPin | undefined {
89
+ if (arch === 'x64' || arch === 'arm64') return CUA_DRIVER_RELEASE.windows[arch]
90
+ return undefined
91
+ }
92
+
93
+ export function cuaDriverDownloadUrl(archive: string): string {
94
+ return `${CUA_DRIVER_RELEASE.baseUrl}/${CUA_DRIVER_RELEASE.tag}/${archive}`
95
+ }
96
+
97
+ /** Executables already hashed by this process, keyed by path, with the size and mtime seen. */
98
+ const verified = new Map<string, string>()
99
+
100
+ /**
101
+ * The `cua-driver.exe` to run: the caller's, else the pinned build from the
102
+ * cache (hash-checked once per process), else — when allowed — the pinned
103
+ * archive downloaded, checked, and unpacked into the cache. Throws
104
+ * {@link CuaDriverUnavailableError} with the reason otherwise.
105
+ */
106
+ export async function resolveCuaDriver(
107
+ options: ResolveCuaDriverOptions = {},
108
+ ): Promise<ResolvedCuaDriver> {
109
+ if (options.path !== undefined) {
110
+ const found = await stat(options.path).catch(() => undefined)
111
+ if (!found?.isFile()) {
112
+ throw new CuaDriverUnavailableError(
113
+ `cua-driver was configured at ${options.path}, which is not a file.`,
114
+ )
115
+ }
116
+ return { path: options.path, source: 'configured' }
117
+ }
118
+
119
+ const arch = options.arch ?? process.arch
120
+ const asset = options.asset ?? cuaDriverAsset(arch)
121
+ if (!asset) {
122
+ throw new CuaDriverUnavailableError(
123
+ `cua-driver publishes no Windows build for the ${arch} architecture.`,
124
+ )
125
+ }
126
+ const dir = options.cacheDir ?? defaultCuaDriverCacheDir(options.env)
127
+ const exe = join(dir, EXE_NAME)
128
+
129
+ if (await isPinnedExecutable(exe, asset.exeSize, asset.exeSha256)) {
130
+ return { path: exe, source: 'cache' }
131
+ }
132
+ if (options.download === false) {
133
+ throw new CuaDriverUnavailableError(
134
+ `cua-driver ${CUA_DRIVER_RELEASE.version} is not in ${dir} and downloading it is turned off.`,
135
+ )
136
+ }
137
+
138
+ const url = cuaDriverDownloadUrl(asset.archive)
139
+ const archive = await download(url, options.fetch ?? fetch, options.downloadTimeoutMs ?? 180_000)
140
+ if (archive.length !== asset.archiveSize || sha256(archive) !== asset.archiveSha256) {
141
+ throw new CuaDriverUnavailableError(
142
+ `${url} did not match its pinned SHA-256 (${archive.length} bytes received); nothing was installed.`,
143
+ )
144
+ }
145
+ const content = extractZipEntry(archive, EXE_NAME)
146
+ if (!content || content.length !== asset.exeSize || sha256(content) !== asset.exeSha256) {
147
+ throw new CuaDriverUnavailableError(
148
+ `${asset.archive} passed its checksum but its ${EXE_NAME} did not match the pinned SHA-256; nothing was installed.`,
149
+ )
150
+ }
151
+ await mkdir(dir, { recursive: true, mode: 0o700 })
152
+ const temporary = join(dir, `${EXE_NAME}.${process.pid}.${Date.now()}.partial`)
153
+ try {
154
+ await writeFile(temporary, content, { mode: 0o755 })
155
+ // WSL starts a Windows program only when the Linux file is executable.
156
+ await chmod(temporary, 0o755)
157
+ await rename(temporary, exe)
158
+ } catch (error) {
159
+ await rm(temporary, { force: true }).catch(() => undefined)
160
+ throw new CuaDriverUnavailableError(
161
+ `cua-driver was downloaded and verified but could not be written to ${dir}: ${error instanceof Error ? error.message : String(error)}`,
162
+ )
163
+ }
164
+ const written = await stat(exe)
165
+ verified.set(exe, `${written.size}:${written.mtimeMs}`)
166
+ return { path: exe, source: 'download' }
167
+ }
168
+
169
+ async function isPinnedExecutable(path: string, size: number, digest: string): Promise<boolean> {
170
+ const found = await stat(path).catch(() => undefined)
171
+ if (!found?.isFile() || found.size !== size) return false
172
+ const identity = `${found.size}:${found.mtimeMs}`
173
+ if (verified.get(path) === identity) return true
174
+ const content = await readFile(path).catch(() => undefined)
175
+ if (!content || sha256(content) !== digest) return false
176
+ verified.set(path, identity)
177
+ return true
178
+ }
179
+
180
+ async function download(url: string, fetcher: typeof fetch, timeoutMs: number): Promise<Buffer> {
181
+ let response: Response
182
+ try {
183
+ response = await fetcher(url, { redirect: 'follow', signal: AbortSignal.timeout(timeoutMs) })
184
+ } catch (error) {
185
+ throw new CuaDriverUnavailableError(
186
+ `Could not download ${url}: ${error instanceof Error ? error.message : String(error)}`,
187
+ )
188
+ }
189
+ if (!response.ok) {
190
+ throw new CuaDriverUnavailableError(`Could not download ${url}: HTTP ${response.status}.`)
191
+ }
192
+ try {
193
+ return Buffer.from(await response.arrayBuffer())
194
+ } catch (error) {
195
+ throw new CuaDriverUnavailableError(
196
+ `The download of ${url} stopped: ${error instanceof Error ? error.message : String(error)}`,
197
+ )
198
+ }
199
+ }
200
+
201
+ function sha256(data: Buffer): string {
202
+ return createHash('sha256').update(data).digest('hex')
203
+ }
204
+
205
+ /** For tests: forget which executables were verified. */
206
+ export function _resetVerifiedCuaDriverCache(): void {
207
+ verified.clear()
208
+ }
@@ -0,0 +1,234 @@
1
+ import type { Rect, UiElement, UiElementAction } from '@namzu/sdk'
2
+
3
+ /**
4
+ * cua-driver's `get_window_state` → the host's `UiElement` tree.
5
+ *
6
+ * The driver answers with two views of one UI Automation walk:
7
+ * `structuredContent.elements`, one record per control it can act on (index,
8
+ * token, role, label, value, state, patterns, frame), and `tree_markdown`,
9
+ * every node of the walk as an indented list in which the actionable ones
10
+ * carry `[index]`. The markdown is the only place the rest of the tree
11
+ * lives — a calculator's "Expression is 125 × 8=", a status bar's
12
+ * "Ln 1, Col 1" — so the shape and the unindexed nodes come from it and
13
+ * everything about an indexed node comes from its record. Without markdown
14
+ * the records alone make the tree, nested by `parent_index`.
15
+ *
16
+ * Only a control with a pattern this host can drive gets a `ref` (its
17
+ * element token); the rest are in the tree for what they say.
18
+ */
19
+
20
+ export interface CuaUiElement {
21
+ readonly element_index?: unknown
22
+ readonly element_token?: unknown
23
+ readonly role?: unknown
24
+ readonly label?: unknown
25
+ readonly value?: unknown
26
+ readonly enabled?: unknown
27
+ readonly selected?: unknown
28
+ readonly actions?: unknown
29
+ readonly frame?: unknown
30
+ readonly parent_index?: unknown
31
+ }
32
+
33
+ /** What `uiAct` needs to know about a ref: the element's current value, for set_value's fallback. */
34
+ export interface UiRefFacts {
35
+ readonly value?: string
36
+ }
37
+
38
+ export interface ParsedUiTree {
39
+ readonly root: UiElement
40
+ /** Every ref in the tree, with what `uiAct` needs about it. */
41
+ readonly refs: ReadonlyMap<string, UiRefFacts>
42
+ readonly count: number
43
+ }
44
+
45
+ /** cua-driver's pattern names → the actions this host performs for them. */
46
+ const PATTERN_ACTIONS: Readonly<Record<string, readonly UiElementAction[]>> = {
47
+ invoke: ['invoke'],
48
+ set_value: ['set_value'],
49
+ expand: ['expand', 'collapse'],
50
+ collapse: ['expand', 'collapse'],
51
+ toggle: ['toggle'],
52
+ select: ['select'],
53
+ }
54
+
55
+ interface MutableElement {
56
+ ref: string
57
+ role: string
58
+ name: string
59
+ value?: string
60
+ automationId?: string
61
+ bounds?: Rect
62
+ states?: string[]
63
+ actions?: UiElementAction[]
64
+ children: MutableElement[]
65
+ }
66
+
67
+ function text(value: unknown): string | undefined {
68
+ return typeof value === 'string' ? value : undefined
69
+ }
70
+
71
+ function actionsOf(raw: unknown): UiElementAction[] {
72
+ if (!Array.isArray(raw)) return []
73
+ const out: UiElementAction[] = []
74
+ for (const name of raw) {
75
+ for (const action of PATTERN_ACTIONS[String(name)] ?? []) {
76
+ if (!out.includes(action)) out.push(action)
77
+ }
78
+ }
79
+ return out
80
+ }
81
+
82
+ function boundsOf(raw: unknown): Rect | undefined {
83
+ if (typeof raw !== 'object' || raw === null) return undefined
84
+ const frame = raw as { x?: unknown; y?: unknown; w?: unknown; h?: unknown }
85
+ const numbers = [frame.x, frame.y, frame.w, frame.h]
86
+ if (!numbers.every((n) => typeof n === 'number' && Number.isFinite(n))) return undefined
87
+ const [x, y, width, height] = numbers as number[]
88
+ if ((width as number) <= 0 || (height as number) <= 0) return undefined
89
+ return {
90
+ x: Math.round(x as number),
91
+ y: Math.round(y as number),
92
+ width: Math.round(width as number),
93
+ height: Math.round(height as number),
94
+ }
95
+ }
96
+
97
+ function fromRecord(record: CuaUiElement, automationId: string | undefined): MutableElement {
98
+ const actions = actionsOf(record.actions)
99
+ const token = text(record.element_token)
100
+ const states: string[] = []
101
+ if (record.enabled === false) states.push('disabled')
102
+ if (record.selected === true) states.push('selected')
103
+ const value = text(record.value)
104
+ const bounds = boundsOf(record.frame)
105
+ return {
106
+ // A control this host can do nothing with gets no ref.
107
+ ref: token && actions.length > 0 ? token : '',
108
+ role: text(record.role) ?? 'Element',
109
+ name: text(record.label) ?? '',
110
+ ...(value !== undefined ? { value } : {}),
111
+ ...(automationId !== undefined ? { automationId } : {}),
112
+ ...(bounds ? { bounds } : {}),
113
+ ...(states.length > 0 ? { states } : {}),
114
+ ...(actions.length > 0 && token ? { actions } : {}),
115
+ children: [],
116
+ }
117
+ }
118
+
119
+ /**
120
+ * An unindexed markdown row: `Role "Name"`, `Role`, or either with a
121
+ * trailing `[attributes]`. Returns undefined for a row it cannot read.
122
+ */
123
+ function fromMarkdownRow(rest: string): MutableElement | undefined {
124
+ const role = /^([A-Za-z][\w-]*)/.exec(rest)?.[1]
125
+ if (!role) return undefined
126
+ let tail = rest.slice(role.length)
127
+ let name = ''
128
+ if (tail.startsWith(' "')) {
129
+ const close = tail.endsWith('"') ? tail.length - 1 : tail.lastIndexOf('" [')
130
+ if (close > 1) {
131
+ name = tail.slice(2, close)
132
+ tail = tail.slice(close + 1)
133
+ }
134
+ }
135
+ const automationId = automationIdOf(tail)
136
+ return {
137
+ ref: '',
138
+ role,
139
+ name,
140
+ ...(automationId !== undefined ? { automationId } : {}),
141
+ children: [],
142
+ }
143
+ }
144
+
145
+ function automationIdOf(attributes: string): string | undefined {
146
+ return /\[(?:[^\]]*\s)?id=([A-Za-z0-9_.:-]+)/.exec(attributes)?.[1]
147
+ }
148
+
149
+ function freeze(element: MutableElement): UiElement {
150
+ const { children, ...rest } = element
151
+ return Object.freeze({
152
+ ...rest,
153
+ ...(children.length > 0 ? { children: Object.freeze(children.map(freeze)) } : {}),
154
+ }) as UiElement
155
+ }
156
+
157
+ function collectRefs(element: MutableElement, into: Map<string, UiRefFacts>): number {
158
+ let count = 1
159
+ if (element.ref)
160
+ into.set(element.ref, element.value !== undefined ? { value: element.value } : {})
161
+ for (const child of element.children) count += collectRefs(child, into)
162
+ return count
163
+ }
164
+
165
+ /** The whole tree of one `get_window_state` answer. */
166
+ export function toUiTree(state: Record<string, unknown>): ParsedUiTree {
167
+ const records = Array.isArray(state.elements) ? (state.elements as CuaUiElement[]) : []
168
+ const byIndex = new Map<number, CuaUiElement>()
169
+ for (const record of records) {
170
+ if (typeof record.element_index === 'number') byIndex.set(record.element_index, record)
171
+ }
172
+ const title = text(state.window_title) ?? ''
173
+ const markdown = text(state.tree_markdown)
174
+ const top: MutableElement[] = []
175
+ const used = new Set<number>()
176
+
177
+ if (markdown) {
178
+ // The open ancestors with their depths: a row's parent is the latest
179
+ // row above it that is less indented. The driver skips a level where
180
+ // it leaves a node out, so depth is compared, not counted.
181
+ const stack: { depth: number; node: MutableElement }[] = []
182
+ for (const line of markdown.split('\n')) {
183
+ const row = /^( *)- (.*)$/.exec(line)
184
+ if (!row) continue
185
+ const depth = Math.floor((row[1] ?? '').length / 2)
186
+ const rest = row[2] ?? ''
187
+ const indexed = /^\[(\d+)\] (.*)$/.exec(rest)
188
+ let node: MutableElement | undefined
189
+ if (indexed) {
190
+ const index = Number(indexed[1])
191
+ const record = byIndex.get(index)
192
+ if (record) {
193
+ used.add(index)
194
+ node = fromRecord(record, automationIdOf(indexed[2] ?? ''))
195
+ } else {
196
+ node = fromMarkdownRow(indexed[2] ?? '')
197
+ }
198
+ } else {
199
+ node = fromMarkdownRow(rest)
200
+ }
201
+ if (!node) continue
202
+ while (stack.length > 0 && (stack[stack.length - 1]?.depth ?? 0) >= depth) stack.pop()
203
+ const parent = stack[stack.length - 1]
204
+ if (parent) parent.node.children.push(node)
205
+ else top.push(node)
206
+ stack.push({ depth, node })
207
+ }
208
+ }
209
+
210
+ // Records the markdown did not place (or no markdown at all): nested by
211
+ // parent_index where that parent is known, else at the top.
212
+ const placed = new Map<number, MutableElement>()
213
+ for (const record of records) {
214
+ const index = record.element_index
215
+ if (typeof index !== 'number' || used.has(index)) continue
216
+ placed.set(index, fromRecord(record, undefined))
217
+ }
218
+ for (const record of records) {
219
+ const index = record.element_index
220
+ if (typeof index !== 'number') continue
221
+ const node = placed.get(index)
222
+ if (!node) continue
223
+ const parent =
224
+ typeof record.parent_index === 'number' ? placed.get(record.parent_index) : undefined
225
+ if (parent) parent.children.push(node)
226
+ else top.push(node)
227
+ }
228
+
229
+ const root: MutableElement =
230
+ top.length === 1 && top[0] ? top[0] : { ref: '', role: 'Window', name: title, children: top }
231
+ const refs = new Map<string, UiRefFacts>()
232
+ const count = collectRefs(root, refs)
233
+ return { root: freeze(root), refs, count }
234
+ }
@@ -0,0 +1,90 @@
1
+ import { inflateRawSync } from 'node:zlib'
2
+
3
+ /**
4
+ * Just enough of the ZIP format to take one file out of an archive whose
5
+ * SHA-256 has already been checked: the central directory, stored and
6
+ * deflated entries. ZIP64, encryption and multi-disk archives are refused,
7
+ * not guessed at — the pinned release archives use none of them.
8
+ */
9
+
10
+ const EOCD_SIGNATURE = 0x06054b50
11
+ const CENTRAL_SIGNATURE = 0x02014b50
12
+ const LOCAL_SIGNATURE = 0x04034b50
13
+ const EOCD_MIN_LENGTH = 22
14
+ const MAX_COMMENT_LENGTH = 0xffff
15
+ const ZIP64_MARKER = 0xffffffff
16
+
17
+ export class ZipFormatError extends Error {
18
+ override readonly name = 'ZipFormatError'
19
+ }
20
+
21
+ /** The bytes of the entry named `name` (exact, `/`-separated), or undefined when the archive has none. */
22
+ export function extractZipEntry(archive: Buffer, name: string): Buffer | undefined {
23
+ const eocd = findEndOfCentralDirectory(archive)
24
+ const entries = archive.readUInt16LE(eocd + 10)
25
+ const size = archive.readUInt32LE(eocd + 12)
26
+ const offset = archive.readUInt32LE(eocd + 16)
27
+ if (size === ZIP64_MARKER || offset === ZIP64_MARKER || entries === 0xffff) {
28
+ throw new ZipFormatError('ZIP64 archives are not supported.')
29
+ }
30
+ if (offset + size > archive.length)
31
+ throw new ZipFormatError('The central directory is truncated.')
32
+
33
+ let at = offset
34
+ for (let index = 0; index < entries; index++) {
35
+ if (at + 46 > archive.length || archive.readUInt32LE(at) !== CENTRAL_SIGNATURE) {
36
+ throw new ZipFormatError(`Central directory entry ${index} is malformed.`)
37
+ }
38
+ const flags = archive.readUInt16LE(at + 8)
39
+ const method = archive.readUInt16LE(at + 10)
40
+ const compressedSize = archive.readUInt32LE(at + 20)
41
+ const uncompressedSize = archive.readUInt32LE(at + 24)
42
+ const nameLength = archive.readUInt16LE(at + 28)
43
+ const extraLength = archive.readUInt16LE(at + 30)
44
+ const commentLength = archive.readUInt16LE(at + 32)
45
+ const localOffset = archive.readUInt32LE(at + 42)
46
+ const entryName = archive.subarray(at + 46, at + 46 + nameLength).toString('utf8')
47
+ at += 46 + nameLength + extraLength + commentLength
48
+ if (entryName !== name) continue
49
+
50
+ if ((flags & 0x1) !== 0) throw new ZipFormatError(`${name} is encrypted.`)
51
+ if (compressedSize === ZIP64_MARKER || uncompressedSize === ZIP64_MARKER) {
52
+ throw new ZipFormatError(`${name} is a ZIP64 entry, which is not supported.`)
53
+ }
54
+ if (
55
+ localOffset + 30 > archive.length ||
56
+ archive.readUInt32LE(localOffset) !== LOCAL_SIGNATURE
57
+ ) {
58
+ throw new ZipFormatError(`The local header of ${name} is malformed.`)
59
+ }
60
+ const dataStart =
61
+ localOffset +
62
+ 30 +
63
+ archive.readUInt16LE(localOffset + 26) +
64
+ archive.readUInt16LE(localOffset + 28)
65
+ const dataEnd = dataStart + compressedSize
66
+ if (dataEnd > archive.length) throw new ZipFormatError(`${name} is truncated.`)
67
+ const data = archive.subarray(dataStart, dataEnd)
68
+ let content: Buffer
69
+ if (method === 0) content = Buffer.from(data)
70
+ else if (method === 8) content = inflateRawSync(data)
71
+ else
72
+ throw new ZipFormatError(`${name} uses compression method ${method}, which is not supported.`)
73
+ if (content.length !== uncompressedSize) {
74
+ throw new ZipFormatError(
75
+ `${name} inflated to ${content.length} bytes; the directory says ${uncompressedSize}.`,
76
+ )
77
+ }
78
+ return content
79
+ }
80
+ return undefined
81
+ }
82
+
83
+ function findEndOfCentralDirectory(archive: Buffer): number {
84
+ if (archive.length < EOCD_MIN_LENGTH) throw new ZipFormatError('Not a ZIP archive: too short.')
85
+ const lowest = Math.max(0, archive.length - EOCD_MIN_LENGTH - MAX_COMMENT_LENGTH)
86
+ for (let at = archive.length - EOCD_MIN_LENGTH; at >= lowest; at--) {
87
+ if (archive.readUInt32LE(at) === EOCD_SIGNATURE) return at
88
+ }
89
+ throw new ZipFormatError('Not a ZIP archive: no end-of-central-directory record.')
90
+ }