usecomputer 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +33 -13
  3. package/bin.sh +49 -0
  4. package/build.zig +12 -0
  5. package/dist/darwin-arm64/usecomputer +0 -0
  6. package/dist/darwin-arm64/usecomputer.node +0 -0
  7. package/dist/darwin-x64/usecomputer +0 -0
  8. package/dist/darwin-x64/usecomputer.node +0 -0
  9. package/dist/index.d.ts +0 -2
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +1 -3
  12. package/dist/linux-x64/usecomputer +0 -0
  13. package/dist/linux-x64/usecomputer.node +0 -0
  14. package/package.json +7 -14
  15. package/src/index.ts +1 -3
  16. package/zig/src/kitty-graphics.zig +151 -0
  17. package/zig/src/lib.zig +121 -0
  18. package/zig/src/main.zig +667 -47
  19. package/zig/src/table.zig +170 -0
  20. package/bin.js +0 -4
  21. package/dist/cli-parsing.test.d.ts +0 -2
  22. package/dist/cli-parsing.test.d.ts.map +0 -1
  23. package/dist/cli-parsing.test.js +0 -53
  24. package/dist/cli.d.ts +0 -6
  25. package/dist/cli.d.ts.map +0 -1
  26. package/dist/cli.js +0 -536
  27. package/dist/command-parsers.d.ts +0 -6
  28. package/dist/command-parsers.d.ts.map +0 -1
  29. package/dist/command-parsers.js +0 -54
  30. package/dist/command-parsers.test.d.ts +0 -2
  31. package/dist/command-parsers.test.d.ts.map +0 -1
  32. package/dist/command-parsers.test.js +0 -44
  33. package/dist/debug-point-image.d.ts +0 -8
  34. package/dist/debug-point-image.d.ts.map +0 -1
  35. package/dist/debug-point-image.js +0 -43
  36. package/dist/debug-point-image.test.d.ts +0 -2
  37. package/dist/debug-point-image.test.d.ts.map +0 -1
  38. package/dist/debug-point-image.test.js +0 -44
  39. package/dist/terminal-table.d.ts +0 -10
  40. package/dist/terminal-table.d.ts.map +0 -1
  41. package/dist/terminal-table.js +0 -55
  42. package/dist/terminal-table.test.d.ts +0 -2
  43. package/dist/terminal-table.test.d.ts.map +0 -1
  44. package/dist/terminal-table.test.js +0 -41
  45. package/src/cli-parsing.test.ts +0 -61
  46. package/src/cli.ts +0 -648
  47. package/src/command-parsers.test.ts +0 -50
  48. package/src/command-parsers.ts +0 -60
  49. package/src/debug-point-image.test.ts +0 -50
  50. package/src/debug-point-image.ts +0 -69
  51. package/src/terminal-table.test.ts +0 -44
  52. package/src/terminal-table.ts +0 -88
package/src/cli.ts DELETED
@@ -1,648 +0,0 @@
1
- // usecomputer CLI entrypoint and command wiring for desktop automation actions.
2
-
3
- import { goke } from 'goke'
4
- import pc from 'picocolors'
5
- import { z } from 'zod'
6
- import dedent from 'string-dedent'
7
- import { createRequire } from 'node:module'
8
- import fs from 'node:fs'
9
- import pathModule from 'node:path'
10
- import url from 'node:url'
11
- import { createBridge } from './bridge.js'
12
- import {
13
- getRegionFromCoordMap,
14
- mapPointFromCoordMap,
15
- mapPointToCoordMap,
16
- parseCoordMapOrThrow,
17
- } from './coord-map.js'
18
- import { parseDirection, parseModifiers, parsePoint, parseRegion } from './command-parsers.js'
19
- import { drawDebugPointOnImage } from './debug-point-image.js'
20
- import { renderAlignedTable } from './terminal-table.js'
21
- import type { DisplayInfo, MouseButton, Point, UseComputerBridge, WindowInfo } from './types.js'
22
-
23
- const require = createRequire(import.meta.url)
24
- const packageJson = require('../package.json') as { version: string }
25
-
26
- function printJson(value: unknown): void {
27
- process.stdout.write(`${JSON.stringify(value, null, 2)}\n`)
28
- }
29
-
30
- function printLine(value: string): void {
31
- process.stdout.write(`${value}\n`)
32
- }
33
-
34
- function readTextFromStdin(): string {
35
- return fs.readFileSync(0, 'utf8')
36
- }
37
-
38
- function parsePositiveInteger({
39
- value,
40
- option,
41
- }: {
42
- value?: number
43
- option: string
44
- }): number | undefined {
45
- if (typeof value !== 'number') {
46
- return undefined
47
- }
48
- if (!Number.isFinite(value) || value <= 0) {
49
- throw new Error(`Option ${option} must be a positive number`)
50
- }
51
- return Math.round(value)
52
- }
53
-
54
- function splitIntoChunks({
55
- text,
56
- chunkSize,
57
- }: {
58
- text: string
59
- chunkSize?: number
60
- }): string[] {
61
- if (!chunkSize || text.length <= chunkSize) {
62
- return [text]
63
- }
64
- const chunkCount = Math.ceil(text.length / chunkSize)
65
- return Array.from({ length: chunkCount }, (_, index) => {
66
- const start = index * chunkSize
67
- const end = start + chunkSize
68
- return text.slice(start, end)
69
- }).filter((chunk) => {
70
- return chunk.length > 0
71
- })
72
- }
73
-
74
- function sleep({
75
- ms,
76
- }: {
77
- ms: number
78
- }): Promise<void> {
79
- return new Promise((resolve) => {
80
- setTimeout(() => {
81
- resolve()
82
- }, ms)
83
- })
84
- }
85
-
86
- function parsePointOrThrow(input: string): Point {
87
- const parsed = parsePoint(input)
88
- if (parsed instanceof Error) {
89
- throw parsed
90
- }
91
- return parsed
92
- }
93
-
94
-
95
- function resolveOutputPath({ path }: { path?: string }): string | undefined {
96
- if (!path) {
97
- return undefined
98
- }
99
-
100
- return path.startsWith('/')
101
- ? path
102
- : `${process.cwd()}/${path}`
103
- }
104
-
105
- function ensureParentDirectory({ filePath }: { filePath?: string }): void {
106
- if (!filePath) {
107
- return
108
- }
109
-
110
- const parentDirectory = pathModule.dirname(filePath)
111
- fs.mkdirSync(parentDirectory, { recursive: true })
112
- }
113
-
114
- function resolvePointInput({
115
- x,
116
- y,
117
- target,
118
- command,
119
- }: {
120
- x?: number
121
- y?: number
122
- target?: string
123
- command: string
124
- }): Point {
125
- if (typeof x === 'number' || typeof y === 'number') {
126
- if (typeof x !== 'number' || typeof y !== 'number') {
127
- throw new Error(`Command \"${command}\" requires both -x and -y when using coordinate flags`)
128
- }
129
- return { x, y }
130
- }
131
- if (target) {
132
- return parsePointOrThrow(target)
133
- }
134
- throw new Error(`Command \"${command}\" requires coordinates. Use -x <n> -y <n>`)
135
- }
136
-
137
- function parseButton(input?: string): MouseButton {
138
- if (input === 'right' || input === 'middle') {
139
- return input
140
- }
141
- return 'left'
142
- }
143
-
144
- function printDesktopList({ displays }: { displays: DisplayInfo[] }) {
145
- const rows = displays.map((display) => {
146
- return {
147
- desktop: `#${display.index}`,
148
- primary: display.isPrimary ? pc.green('yes') : 'no',
149
- size: `${display.width}x${display.height}`,
150
- position: `${display.x},${display.y}`,
151
- id: String(display.id),
152
- scale: String(display.scale),
153
- name: display.name,
154
- }
155
- })
156
-
157
- const lines = renderAlignedTable({
158
- rows,
159
- columns: [
160
- { header: pc.bold('desktop'), value: (row) => { return row.desktop } },
161
- { header: pc.bold('primary'), value: (row) => { return row.primary } },
162
- { header: pc.bold('size'), value: (row) => { return row.size }, align: 'right' },
163
- { header: pc.bold('position'), value: (row) => { return row.position }, align: 'right' },
164
- { header: pc.bold('id'), value: (row) => { return row.id }, align: 'right' },
165
- { header: pc.bold('scale'), value: (row) => { return row.scale }, align: 'right' },
166
- { header: pc.bold('name'), value: (row) => { return row.name } },
167
- ],
168
- })
169
- lines.forEach((line) => {
170
- printLine(line)
171
- })
172
- }
173
-
174
- function mapWindowsByDesktopIndex({
175
- windows,
176
- }: {
177
- windows: WindowInfo[]
178
- }): Map<number, WindowInfo[]> {
179
- return windows.reduce((acc, window) => {
180
- const list = acc.get(window.desktopIndex) ?? []
181
- list.push(window)
182
- acc.set(window.desktopIndex, list)
183
- return acc
184
- }, new Map<number, WindowInfo[]>())
185
- }
186
-
187
- function printDesktopListWithWindows({
188
- displays,
189
- windows,
190
- }: {
191
- displays: DisplayInfo[]
192
- windows: WindowInfo[]
193
- }) {
194
- const windowsByDesktop = mapWindowsByDesktopIndex({ windows })
195
- printDesktopList({ displays })
196
-
197
- displays.forEach((display) => {
198
- printLine('')
199
- printLine(pc.bold(pc.cyan(`desktop #${display.index} windows`)))
200
-
201
- const desktopWindows = windowsByDesktop.get(display.index) ?? []
202
- if (desktopWindows.length === 0) {
203
- printLine(pc.dim('none'))
204
- return
205
- }
206
-
207
- const lines = renderAlignedTable({
208
- rows: desktopWindows,
209
- columns: [
210
- { header: pc.bold('id'), value: (row) => { return String(row.id) }, align: 'right' },
211
- { header: pc.bold('app'), value: (row) => { return row.ownerName } },
212
- { header: pc.bold('pid'), value: (row) => { return String(row.ownerPid) }, align: 'right' },
213
- { header: pc.bold('size'), value: (row) => { return `${row.width}x${row.height}` }, align: 'right' },
214
- { header: pc.bold('position'), value: (row) => { return `${row.x},${row.y}` }, align: 'right' },
215
- { header: pc.bold('title'), value: (row) => { return row.title } },
216
- ],
217
- })
218
- lines.forEach((line) => {
219
- printLine(line)
220
- })
221
- })
222
- }
223
-
224
- function printWindowList({ windows }: { windows: WindowInfo[] }) {
225
- const lines = renderAlignedTable({
226
- rows: windows,
227
- columns: [
228
- { header: pc.bold('id'), value: (row) => { return String(row.id) }, align: 'right' },
229
- { header: pc.bold('desktop'), value: (row) => { return `#${row.desktopIndex}` }, align: 'right' },
230
- { header: pc.bold('app'), value: (row) => { return row.ownerName } },
231
- { header: pc.bold('pid'), value: (row) => { return String(row.ownerPid) }, align: 'right' },
232
- { header: pc.bold('size'), value: (row) => { return `${row.width}x${row.height}` }, align: 'right' },
233
- { header: pc.bold('position'), value: (row) => { return `${row.x},${row.y}` }, align: 'right' },
234
- { header: pc.bold('title'), value: (row) => { return row.title } },
235
- ],
236
- })
237
- lines.forEach((line) => {
238
- printLine(line)
239
- })
240
- }
241
-
242
- export function createCli({ bridge = createBridge() }: { bridge?: UseComputerBridge } = {}) {
243
- const cli = goke('usecomputer')
244
-
245
- cli
246
- .command(
247
- 'screenshot [path]',
248
- dedent`
249
- Take a screenshot of the entire screen or a region.
250
-
251
- This command uses a native Zig backend over macOS APIs.
252
- `,
253
- )
254
- .option('-r, --region [region]', z.string().describe('Capture region as x,y,width,height'))
255
- .option(
256
- '--display [display]',
257
- z.number().describe('Display index for multi-monitor setups (0-based: first display is index 0)'),
258
- )
259
- .option('--window [window]', z.number().describe('Capture a specific window by window id'))
260
- .option('--annotate', 'Annotate screenshot with labels')
261
- .option('--json', 'Output as JSON')
262
- .action(async (path, options) => {
263
- const outputPath = resolveOutputPath({ path })
264
- ensureParentDirectory({ filePath: outputPath })
265
- const region = options.region ? parseRegion(options.region) : undefined
266
- if (region instanceof Error) {
267
- throw region
268
- }
269
- if (typeof options.window === 'number' && region) {
270
- throw new Error('Cannot use --window and --region together')
271
- }
272
- if (typeof options.window === 'number' && typeof options.display === 'number') {
273
- throw new Error('Cannot use --window and --display together')
274
- }
275
- const result = await bridge.screenshot({
276
- path: outputPath,
277
- region,
278
- display: options.display,
279
- window: options.window,
280
- annotate: options.annotate,
281
- })
282
- if (options.json) {
283
- printJson(result)
284
- return
285
- }
286
- printLine(result.path)
287
- printLine(result.hint)
288
- printLine(`desktop-index=${String(result.desktopIndex)}`)
289
- })
290
-
291
- cli
292
- .command(
293
- 'click [target]',
294
- dedent`
295
- Click at coordinates.
296
-
297
- When you are clicking from a screenshot, use the exact pixel coordinates
298
- of the target in that screenshot image and always pass the exact
299
- --coord-map value printed by usecomputer screenshot. The coord map
300
- scales screenshot-space pixels back into the real captured desktop or
301
- window rectangle before sending the native click.
302
- `,
303
- )
304
- .option('-x [x]', z.number().describe('X coordinate. When using --coord-map, this must be the exact pixel from the screenshot image'))
305
- .option('-y [y]', z.number().describe('Y coordinate. When using --coord-map, this must be the exact pixel from the screenshot image'))
306
- .option('--button [button]', z.enum(['left', 'right', 'middle']).default('left').describe('Mouse button'))
307
- .option('--count [count]', z.number().default(1).describe('Number of clicks'))
308
- .option('--modifiers [modifiers]', z.string().describe('Modifiers as ctrl,shift,alt,meta'))
309
- .option('--coord-map [coordMap]', z.string().describe('Map exact screenshot-space pixels back into the real captured desktop or window rectangle'))
310
- .example('# Click the exact pixel you saw in a screenshot')
311
- .example('usecomputer click -x 155 -y 446 --coord-map "0,0,1720,1440,1568,1313"')
312
- .action(async (target, options) => {
313
- const point = resolvePointInput({
314
- x: options.x,
315
- y: options.y,
316
- target,
317
- command: 'click',
318
- })
319
- const coordMap = parseCoordMapOrThrow(options.coordMap)
320
- await bridge.click({
321
- point: mapPointFromCoordMap({ point, coordMap }),
322
- button: options.button,
323
- count: options.count,
324
- modifiers: parseModifiers(options.modifiers),
325
- })
326
- })
327
-
328
- cli
329
- .command(
330
- 'debug-point [target]',
331
- dedent`
332
- Capture a screenshot and draw a red marker where a click would land.
333
-
334
- Pass the same --coord-map you plan to use for click. This validates
335
- screenshot-space coordinates before you send a real click. When
336
- --coord-map is present, debug-point captures that same region so the
337
- overlay matches the screenshot you are targeting.
338
- `,
339
- )
340
- .option('-x [x]', z.number().describe('X coordinate'))
341
- .option('-y [y]', z.number().describe('Y coordinate'))
342
- .option('--coord-map [coordMap]', z.string().describe('Map input coordinates from screenshot space'))
343
- .option('--output [path]', z.string().describe('Write the annotated screenshot to this path'))
344
- .option('--json', 'Output as JSON')
345
- .example('# Validate the same coordinates you plan to click')
346
- .example('usecomputer debug-point -x 210 -y 560 --coord-map "0,0,1720,1440,1568,1313"')
347
- .action(async (target, options) => {
348
- const point = resolvePointInput({
349
- x: options.x,
350
- y: options.y,
351
- target,
352
- command: 'debug-point',
353
- })
354
- const inputCoordMap = parseCoordMapOrThrow(options.coordMap)
355
- const desktopPoint = mapPointFromCoordMap({ point, coordMap: inputCoordMap })
356
- const outputPath = resolveOutputPath({ path: options.output ?? './tmp/debug-point.png' })
357
- ensureParentDirectory({ filePath: outputPath })
358
- const screenshotRegion = getRegionFromCoordMap({ coordMap: inputCoordMap })
359
-
360
- const screenshot = await bridge.screenshot({
361
- path: outputPath,
362
- region: screenshotRegion,
363
- })
364
- const screenshotCoordMap = parseCoordMapOrThrow(screenshot.coordMap)
365
- const screenshotPoint = mapPointToCoordMap({ point: desktopPoint, coordMap: screenshotCoordMap })
366
-
367
- await drawDebugPointOnImage({
368
- imagePath: screenshot.path,
369
- point: screenshotPoint,
370
- imageWidth: screenshot.imageWidth,
371
- imageHeight: screenshot.imageHeight,
372
- })
373
-
374
- if (options.json) {
375
- printJson({
376
- path: screenshot.path,
377
- inputPoint: point,
378
- desktopPoint,
379
- screenshotPoint,
380
- inputCoordMap: options.coordMap ?? null,
381
- screenshotCoordMap: screenshot.coordMap,
382
- hint: screenshot.hint,
383
- })
384
- return
385
- }
386
-
387
- printLine(screenshot.path)
388
- printLine(`input-point=${point.x},${point.y}`)
389
- printLine(`desktop-point=${desktopPoint.x},${desktopPoint.y}`)
390
- printLine(`screenshot-point=${screenshotPoint.x},${screenshotPoint.y}`)
391
- printLine(screenshot.hint)
392
- })
393
-
394
- cli
395
- .command(
396
- 'type [text]',
397
- dedent`
398
- Type text in the currently focused input.
399
-
400
- Supports direct text arguments or --stdin for long/multiline content.
401
- For very long text, use --chunk-size to split input into multiple native
402
- type calls so shells and apps are less likely to drop input.
403
- `,
404
- )
405
- .option('--stdin', 'Read text from stdin instead of [text] argument')
406
- .option('--delay [delay]', z.number().describe('Delay in milliseconds between typed characters'))
407
- .option('--chunk-size [size]', z.number().describe('Split text into fixed-size chunks before typing'))
408
- .option('--chunk-delay [delay]', z.number().describe('Delay in milliseconds between chunks'))
409
- .option('--max-length [length]', z.number().describe('Fail when input text exceeds this maximum length'))
410
- .example('# Type a short string')
411
- .example('usecomputer type "hello"')
412
- .example('# Type multiline text from a file')
413
- .example('cat ./notes.txt | usecomputer type --stdin --chunk-size 4000 --chunk-delay 15')
414
- .action(async (text, options) => {
415
- const fromStdin = Boolean(options.stdin)
416
- if (fromStdin && text) {
417
- throw new Error('Use either [text] or --stdin, not both')
418
- }
419
- if (!fromStdin && !text) {
420
- throw new Error('Command "type" requires [text] or --stdin')
421
- }
422
-
423
- const sourceText = fromStdin ? readTextFromStdin() : text ?? ''
424
- const chunkSize = parsePositiveInteger({
425
- value: options.chunkSize,
426
- option: '--chunk-size',
427
- })
428
- const maxLength = parsePositiveInteger({
429
- value: options.maxLength,
430
- option: '--max-length',
431
- })
432
- const chunkDelay = parsePositiveInteger({
433
- value: options.chunkDelay,
434
- option: '--chunk-delay',
435
- })
436
-
437
- if (typeof maxLength === 'number' && sourceText.length > maxLength) {
438
- throw new Error(`Input text length ${String(sourceText.length)} exceeds --max-length ${String(maxLength)}`)
439
- }
440
-
441
- const chunks = splitIntoChunks({
442
- text: sourceText,
443
- chunkSize,
444
- })
445
- await chunks.reduce(async (previousChunk, chunk, index) => {
446
- await previousChunk
447
- await bridge.typeText({
448
- text: chunk,
449
- delayMs: options.delay,
450
- })
451
- if (typeof chunkDelay === 'number' && index < chunks.length - 1) {
452
- await sleep({ ms: chunkDelay })
453
- }
454
- }, Promise.resolve())
455
- })
456
-
457
- cli
458
- .command(
459
- 'press <key>',
460
- dedent`
461
- Press a key or key combo in the focused app.
462
-
463
- Key combos use plus syntax such as cmd+s or ctrl+shift+p.
464
- Platform behavior: cmd maps to Command on macOS, Win/Super on
465
- Windows/Linux. For cross-platform app shortcuts, prefer ctrl+... .
466
- `,
467
- )
468
- .option('--count [count]', z.number().default(1).describe('How many times to press'))
469
- .option('--delay [delay]', z.number().describe('Delay between presses in milliseconds'))
470
- .example('# Save in the current app on macOS')
471
- .example('usecomputer press "cmd+s"')
472
- .example('# Portable save shortcut across most apps')
473
- .example('usecomputer press "ctrl+s"')
474
- .example('# Open command palette in many editors')
475
- .example('usecomputer press "cmd+shift+p"')
476
- .action(async (key, options) => {
477
- await bridge.press({ key, count: options.count, delayMs: options.delay })
478
- })
479
-
480
- cli
481
- .command('scroll <direction> [amount]', 'Scroll in a direction')
482
- .option('--at [at]', z.string().describe('Coordinates x,y where scroll happens'))
483
- .action(async (direction, amount, options) => {
484
- const parsedDirection = parseDirection(direction)
485
- if (parsedDirection instanceof Error) {
486
- throw parsedDirection
487
- }
488
- const at = options.at ? parsePointOrThrow(options.at) : undefined
489
- const scrollAmount = amount ? Number(amount) : 300
490
- if (!Number.isFinite(scrollAmount)) {
491
- throw new Error(`Invalid amount \"${amount}\"`)
492
- }
493
- await bridge.scroll({
494
- direction: parsedDirection,
495
- amount: scrollAmount,
496
- at,
497
- })
498
- })
499
-
500
- cli
501
- .command('drag <from> <to>', 'Drag from one coordinate to another')
502
- .option('--duration [duration]', z.number().describe('Duration in milliseconds'))
503
- .option('--button [button]', z.enum(['left', 'right', 'middle']).default('left').describe('Mouse button'))
504
- .option('--coord-map [coordMap]', z.string().describe('Map input coordinates from screenshot space'))
505
- .action(async (from, to, options) => {
506
- const coordMap = parseCoordMapOrThrow(options.coordMap)
507
- await bridge.drag({
508
- from: mapPointFromCoordMap({ point: parsePointOrThrow(from), coordMap }),
509
- to: mapPointFromCoordMap({ point: parsePointOrThrow(to), coordMap }),
510
- durationMs: options.duration,
511
- button: options.button,
512
- })
513
- })
514
-
515
- cli
516
- .command('hover [target]', 'Move mouse cursor to coordinates without clicking')
517
- .option('-x [x]', z.number().describe('X coordinate'))
518
- .option('-y [y]', z.number().describe('Y coordinate'))
519
- .option('--coord-map [coordMap]', z.string().describe('Map input coordinates from screenshot space'))
520
- .action(async (target, options) => {
521
- const point = resolvePointInput({
522
- x: options.x,
523
- y: options.y,
524
- target,
525
- command: 'hover',
526
- })
527
- const coordMap = parseCoordMapOrThrow(options.coordMap)
528
- await bridge.hover(mapPointFromCoordMap({ point, coordMap }))
529
- })
530
-
531
- cli
532
- .command('mouse move [x] [y]', 'Move mouse cursor to absolute coordinates (optional before click; click can target coordinates directly)')
533
- .option('-x [x]', z.number().describe('X coordinate'))
534
- .option('-y [y]', z.number().describe('Y coordinate'))
535
- .option('--coord-map [coordMap]', z.string().describe('Map input coordinates from screenshot space'))
536
- .action(async (x, y, options) => {
537
- const point = resolvePointInput({
538
- x: options.x,
539
- y: options.y,
540
- target: x && y ? `${x},${y}` : undefined,
541
- command: 'mouse move',
542
- })
543
- const coordMap = parseCoordMapOrThrow(options.coordMap)
544
- await bridge.mouseMove(mapPointFromCoordMap({ point, coordMap }))
545
- })
546
-
547
- cli
548
- .command('mouse down', 'Press and hold mouse button')
549
- .option('--button [button]', z.enum(['left', 'right', 'middle']).default('left').describe('Mouse button'))
550
- .action(async (options) => {
551
- await bridge.mouseDown({ button: parseButton(options.button) })
552
- })
553
-
554
- cli
555
- .command('mouse up', 'Release mouse button')
556
- .option('--button [button]', z.enum(['left', 'right', 'middle']).default('left').describe('Mouse button'))
557
- .action(async (options) => {
558
- await bridge.mouseUp({ button: parseButton(options.button) })
559
- })
560
-
561
- cli
562
- .command('mouse position', 'Print current mouse position as x,y')
563
- .option('--json', 'Output as JSON')
564
- .action(async (options) => {
565
- const position = await bridge.mousePosition()
566
- if (options.json) {
567
- printJson(position)
568
- return
569
- }
570
- printLine(`${position.x},${position.y}`)
571
- })
572
-
573
- cli
574
- .command('display list', 'List connected displays')
575
- .option('--json', 'Output as JSON')
576
- .action(async (options) => {
577
- const displays = await bridge.displayList()
578
- if (options.json) {
579
- printJson(displays)
580
- return
581
- }
582
- printDesktopList({ displays })
583
- })
584
-
585
- cli
586
- .command('desktop list', 'List desktops as display indexes and sizes (#0 is the primary display)')
587
- .option('--windows', 'Include available windows grouped by desktop index')
588
- .option('--json', 'Output as JSON')
589
- .action(async (options) => {
590
- const displays = await bridge.displayList()
591
- const windows = options.windows ? await bridge.windowList() : []
592
- if (options.json) {
593
- if (options.windows) {
594
- printJson({ displays, windows })
595
- return
596
- }
597
- printJson(displays)
598
- return
599
- }
600
- if (options.windows) {
601
- printDesktopListWithWindows({ displays, windows })
602
- return
603
- }
604
- printDesktopList({ displays })
605
- })
606
-
607
- cli
608
- .command('clipboard get', 'Print clipboard text')
609
- .action(async () => {
610
- const text = await bridge.clipboardGet()
611
- printLine(text)
612
- })
613
-
614
- cli
615
- .command('clipboard set <text>', 'Set clipboard text')
616
- .action(async (text) => {
617
- await bridge.clipboardSet({ text })
618
- })
619
-
620
- cli.command('window list').option('--json', 'Output as JSON').action(async (options) => {
621
- const windows = await bridge.windowList()
622
- if (options.json) {
623
- printJson(windows)
624
- return
625
- }
626
- printWindowList({ windows })
627
- })
628
- cli.help()
629
- cli.version(packageJson.version)
630
- return cli
631
- }
632
-
633
- export function runCli(): void {
634
- const cli = createCli()
635
- cli.parse()
636
- }
637
-
638
- const isDirectEntrypoint = (() => {
639
- const argvPath = process.argv[1]
640
- if (!argvPath) {
641
- return false
642
- }
643
- return import.meta.url === url.pathToFileURL(argvPath).href
644
- })()
645
-
646
- if (isDirectEntrypoint) {
647
- runCli()
648
- }
@@ -1,50 +0,0 @@
1
- // Tests for parsing coordinates, regions, directions, and keyboard modifiers.
2
-
3
- import { describe, expect, test } from 'vitest'
4
- import { parseDirection, parseModifiers, parsePoint, parseRegion } from './command-parsers.js'
5
-
6
- describe('command parsers', () => {
7
- test('parses x,y points', () => {
8
- const result = parsePoint('100,200')
9
- expect(result).toMatchInlineSnapshot(`
10
- {
11
- "x": 100,
12
- "y": 200,
13
- }
14
- `)
15
- })
16
-
17
- test('rejects invalid points', () => {
18
- const result = parsePoint('100')
19
- expect(result instanceof Error).toBe(true)
20
- expect(result instanceof Error ? result.message : '').toMatchInlineSnapshot(`"Invalid point "100". Expected x,y"`)
21
- })
22
-
23
- test('parses x,y,width,height regions', () => {
24
- const result = parseRegion('10,20,300,400')
25
- expect(result).toMatchInlineSnapshot(`
26
- {
27
- "height": 400,
28
- "width": 300,
29
- "x": 10,
30
- "y": 20,
31
- }
32
- `)
33
- })
34
-
35
- test('parses modifiers with normalization', () => {
36
- expect(parseModifiers(' CMD,shift, alt ')).toMatchInlineSnapshot(`
37
- [
38
- "cmd",
39
- "shift",
40
- "alt",
41
- ]
42
- `)
43
- })
44
-
45
- test('validates scroll direction', () => {
46
- expect(parseDirection('down')).toBe('down')
47
- const invalid = parseDirection('diagonal')
48
- expect(invalid instanceof Error).toBe(true)
49
- })
50
- })