universal-screenshot-mcp 1.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.
@@ -0,0 +1,78 @@
1
+ import { z } from 'zod';
2
+ import { existsSync } from 'fs';
3
+ import { defaultOutDir, ensureDefaultDirectory } from '../config/runtime.js';
4
+ import { ALLOWED_OUTPUT_DIRS } from '../config/index.js';
5
+ import { validateOutputPath } from '../validators/path.js';
6
+ import { ok, err, timestamp, ensureDir } from '../utils/helpers.js';
7
+ import { getScreenshotProvider } from '../utils/screenshot-provider.js';
8
+ // No semaphore — system screenshot tools are lightweight (< 100ms, < 10MB)
9
+ export function registerTakeSystemScreenshot(server) {
10
+ server.registerTool('take_system_screenshot', {
11
+ description: 'Capture desktop, window, or region screenshot. Cross-platform: macOS (screencapture), Linux (maim/scrot/gnome-screenshot/etc.), Windows (PowerShell+.NET). Saves to ~/Desktop/Screenshots by default. For window mode, provide windowName (app name like "Safari") or windowId.',
12
+ inputSchema: {
13
+ mode: z
14
+ .enum(['fullscreen', 'window', 'region'])
15
+ .describe('fullscreen=entire screen, window=specific app (requires windowName or windowId), region=coordinates'),
16
+ windowId: z.number().int().min(0).optional().describe('Window ID (for window mode)'),
17
+ windowName: z
18
+ .string()
19
+ .optional()
20
+ .describe('App name like "Safari", "Firefox" (for window mode)'),
21
+ region: z
22
+ .object({
23
+ x: z.number().int().min(0),
24
+ y: z.number().int().min(0),
25
+ width: z.number().int().min(1).max(7680),
26
+ height: z.number().int().min(1).max(4320),
27
+ })
28
+ .optional()
29
+ .describe('Region {x,y,width,height}'),
30
+ display: z.number().min(1).optional().describe('Display number'),
31
+ includeCursor: z.boolean().optional().describe('Include cursor'),
32
+ format: z.enum(['png', 'jpg']).optional().describe('Image format (png or jpg)'),
33
+ delay: z.number().min(0).max(10).optional().describe('Delay seconds'),
34
+ outputPath: z
35
+ .string()
36
+ .optional()
37
+ .describe('Absolute path, or relative to home dir'),
38
+ },
39
+ }, async ({ mode, windowId, windowName, region, display, includeCursor, format, delay, outputPath: custom, }) => {
40
+ ensureDefaultDirectory();
41
+ try {
42
+ // Get the platform-appropriate screenshot provider
43
+ const provider = await getScreenshotProvider();
44
+ const ext = format || 'png';
45
+ // Security: Validate output path (path traversal prevention)
46
+ const pathValidation = await validateOutputPath(custom, `system-screenshot-${timestamp()}.${ext}`, { allowedOutputDirs: ALLOWED_OUTPUT_DIRS, defaultOutDir });
47
+ if (!pathValidation.valid) {
48
+ return err(`Output path validation failed: ${pathValidation.error}`);
49
+ }
50
+ const dest = pathValidation.path;
51
+ ensureDir(dest);
52
+ const captureOpts = {
53
+ outputPath: dest,
54
+ format: format,
55
+ includeCursor,
56
+ delay,
57
+ display,
58
+ };
59
+ if (mode === 'fullscreen') {
60
+ await provider.captureFullscreen(captureOpts);
61
+ }
62
+ else if (mode === 'window') {
63
+ await provider.captureWindow({ ...captureOpts, windowId, windowName });
64
+ }
65
+ else if (mode === 'region') {
66
+ if (!region)
67
+ return err('Region mode requires region coordinates');
68
+ await provider.captureRegion({ ...captureOpts, ...region });
69
+ }
70
+ if (!existsSync(dest))
71
+ return err('Screenshot failed — file not created');
72
+ return ok(`System screenshot saved: ${dest}`);
73
+ }
74
+ catch (e) {
75
+ return err(`System screenshot error: ${e instanceof Error ? e.message : e}`);
76
+ }
77
+ });
78
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,22 @@
1
+ // ============================================================================
2
+ // Shared helper functions
3
+ // ============================================================================
4
+ import { dirname } from 'path';
5
+ import { existsSync, mkdirSync } from 'fs';
6
+ /** Return a successful MCP tool response. */
7
+ export const ok = (text) => ({
8
+ content: [{ type: 'text', text }],
9
+ });
10
+ /** Return an error MCP tool response. */
11
+ export const err = (text) => ({
12
+ content: [{ type: 'text', text }],
13
+ isError: true,
14
+ });
15
+ /** Generate an ISO-8601 timestamp safe for filenames (colons/dots replaced with dashes). */
16
+ export const timestamp = () => new Date().toISOString().replace(/[:.]/g, '-');
17
+ /** Ensure the parent directory of a file path exists, creating it recursively if needed. */
18
+ export const ensureDir = (p) => {
19
+ const d = dirname(p);
20
+ if (!existsSync(d))
21
+ mkdirSync(d, { recursive: true });
22
+ };
@@ -0,0 +1,172 @@
1
+ // ============================================================================
2
+ // Linux screenshot provider — fallback chain of native tools
3
+ // ============================================================================
4
+ import { execFileAsync, commandExists, sleep } from './screenshot-provider.js';
5
+ /**
6
+ * Linux screenshot provider with automatic tool detection.
7
+ * Probes for available tools in priority order and uses the first one found.
8
+ */
9
+ export class LinuxProvider {
10
+ platform = 'Linux';
11
+ _backend = null;
12
+ _detected = false;
13
+ async isAvailable() {
14
+ await this.detectBackend();
15
+ return this._backend !== null;
16
+ }
17
+ async captureFullscreen(opts) {
18
+ const backend = await this.getBackend();
19
+ if (opts.delay && opts.delay > 0)
20
+ await sleep(opts.delay);
21
+ switch (backend) {
22
+ case 'gnome-screenshot':
23
+ await execFileAsync('gnome-screenshot', ['-f', opts.outputPath]);
24
+ break;
25
+ case 'spectacle':
26
+ await execFileAsync('spectacle', ['-b', '-n', '-f', '-o', opts.outputPath]);
27
+ break;
28
+ case 'scrot':
29
+ await execFileAsync('scrot', [opts.outputPath]);
30
+ break;
31
+ case 'maim':
32
+ await execFileAsync('maim', [opts.outputPath]);
33
+ break;
34
+ case 'grim':
35
+ await execFileAsync('grim', [opts.outputPath]);
36
+ break;
37
+ case 'import':
38
+ await execFileAsync('import', ['-window', 'root', opts.outputPath]);
39
+ break;
40
+ }
41
+ }
42
+ async captureWindow(opts) {
43
+ const backend = await this.getBackend();
44
+ if (opts.delay && opts.delay > 0)
45
+ await sleep(opts.delay);
46
+ // Try to resolve window ID from name using xdotool (X11 only)
47
+ let xWindowId;
48
+ if (opts.windowName && !opts.windowId) {
49
+ xWindowId = await this.findXWindowId(opts.windowName);
50
+ }
51
+ else if (opts.windowId) {
52
+ xWindowId = String(opts.windowId);
53
+ }
54
+ switch (backend) {
55
+ case 'gnome-screenshot':
56
+ // gnome-screenshot -w captures the focused window
57
+ // If we have a window ID, try to focus it first via xdotool
58
+ if (xWindowId)
59
+ await this.focusWindow(xWindowId);
60
+ await execFileAsync('gnome-screenshot', ['-w', '-f', opts.outputPath]);
61
+ break;
62
+ case 'spectacle':
63
+ if (xWindowId)
64
+ await this.focusWindow(xWindowId);
65
+ await execFileAsync('spectacle', ['-b', '-n', '-a', '-o', opts.outputPath]);
66
+ break;
67
+ case 'scrot':
68
+ if (xWindowId)
69
+ await this.focusWindow(xWindowId);
70
+ await execFileAsync('scrot', ['-u', opts.outputPath]);
71
+ break;
72
+ case 'maim':
73
+ if (xWindowId) {
74
+ await execFileAsync('maim', ['-i', xWindowId, opts.outputPath]);
75
+ }
76
+ else {
77
+ // Fallback: capture focused window
78
+ throw new Error('maim requires a window ID or xdotool for window-by-name capture');
79
+ }
80
+ break;
81
+ case 'grim':
82
+ throw new Error('Window capture is not supported on Wayland with grim. Use fullscreen or region mode.');
83
+ case 'import':
84
+ if (xWindowId) {
85
+ await execFileAsync('import', ['-window', xWindowId, opts.outputPath]);
86
+ }
87
+ else {
88
+ throw new Error('import requires a window ID for window capture');
89
+ }
90
+ break;
91
+ }
92
+ }
93
+ async captureRegion(opts) {
94
+ const backend = await this.getBackend();
95
+ if (opts.delay && opts.delay > 0)
96
+ await sleep(opts.delay);
97
+ const geometry = `${opts.width}x${opts.height}+${opts.x}+${opts.y}`;
98
+ switch (backend) {
99
+ case 'gnome-screenshot':
100
+ // gnome-screenshot doesn't support arbitrary region coordinates
101
+ // Fall back to using maim/import if available, otherwise error
102
+ throw new Error('gnome-screenshot does not support region capture with coordinates. ' +
103
+ 'Install maim or scrot for region support.');
104
+ case 'spectacle':
105
+ // spectacle --region requires interactive selection
106
+ throw new Error('spectacle does not support non-interactive region capture. ' +
107
+ 'Install maim or scrot for region support.');
108
+ case 'scrot':
109
+ // scrot -a x,y,w,h
110
+ await execFileAsync('scrot', ['-a', `${opts.x},${opts.y},${opts.width},${opts.height}`, opts.outputPath]);
111
+ break;
112
+ case 'maim':
113
+ await execFileAsync('maim', ['-g', geometry, opts.outputPath]);
114
+ break;
115
+ case 'grim':
116
+ await execFileAsync('grim', ['-g', `${opts.x},${opts.y} ${opts.width}x${opts.height}`, opts.outputPath]);
117
+ break;
118
+ case 'import':
119
+ await execFileAsync('import', ['-crop', geometry, '-window', 'root', opts.outputPath]);
120
+ break;
121
+ }
122
+ }
123
+ // ── Private helpers ────────────────────────────────────────────────────
124
+ async detectBackend() {
125
+ if (this._detected)
126
+ return;
127
+ this._detected = true;
128
+ // Priority order: most feature-complete first
129
+ const candidates = [
130
+ 'maim', 'scrot', 'gnome-screenshot', 'spectacle', 'grim', 'import',
131
+ ];
132
+ for (const cmd of candidates) {
133
+ if (await commandExists(cmd)) {
134
+ this._backend = cmd;
135
+ return;
136
+ }
137
+ }
138
+ }
139
+ async getBackend() {
140
+ await this.detectBackend();
141
+ if (!this._backend) {
142
+ throw new Error('No screenshot tool found. Install one of: maim, scrot, gnome-screenshot, spectacle, grim, or ImageMagick (import).');
143
+ }
144
+ return this._backend;
145
+ }
146
+ /**
147
+ * Find an X11 window ID by application name using xdotool.
148
+ */
149
+ async findXWindowId(name) {
150
+ try {
151
+ const { stdout } = await execFileAsync('xdotool', ['search', '--name', name]);
152
+ const ids = stdout.trim().split('\n').filter(Boolean);
153
+ return ids[0]; // Return first match
154
+ }
155
+ catch {
156
+ return undefined;
157
+ }
158
+ }
159
+ /**
160
+ * Focus a window by X11 window ID using xdotool.
161
+ */
162
+ async focusWindow(windowId) {
163
+ try {
164
+ await execFileAsync('xdotool', ['windowactivate', '--sync', windowId]);
165
+ // Brief pause to let the window manager bring it to front
166
+ await sleep(0.3);
167
+ }
168
+ catch {
169
+ // Non-fatal — window may still be capturable
170
+ }
171
+ }
172
+ }
@@ -0,0 +1,50 @@
1
+ // ============================================================================
2
+ // macOS screenshot provider — wraps native `screencapture` CLI
3
+ // ============================================================================
4
+ import { execFileAsync, commandExists } from './screenshot-provider.js';
5
+ import { getWindowId } from './macos.js';
6
+ export class MacOSProvider {
7
+ platform = 'macOS';
8
+ async isAvailable() {
9
+ return commandExists('screencapture');
10
+ }
11
+ async captureFullscreen(opts) {
12
+ const args = this.buildBaseArgs(opts);
13
+ args.push(opts.outputPath);
14
+ await execFileAsync('screencapture', args);
15
+ }
16
+ async captureWindow(opts) {
17
+ let wid = opts.windowId;
18
+ if (!wid && opts.windowName) {
19
+ wid = (await getWindowId(opts.windowName)) ?? undefined;
20
+ }
21
+ if (!wid) {
22
+ throw new Error(opts.windowName
23
+ ? `Window not found: ${opts.windowName}`
24
+ : 'Window mode requires windowId or windowName');
25
+ }
26
+ const args = this.buildBaseArgs(opts);
27
+ args.push('-l', String(wid));
28
+ args.push(opts.outputPath);
29
+ await execFileAsync('screencapture', args);
30
+ }
31
+ async captureRegion(opts) {
32
+ const args = this.buildBaseArgs(opts);
33
+ args.push('-R', `${opts.x},${opts.y},${opts.width},${opts.height}`);
34
+ args.push(opts.outputPath);
35
+ await execFileAsync('screencapture', args);
36
+ }
37
+ // ── Private helpers ────────────────────────────────────────────────────
38
+ buildBaseArgs(opts) {
39
+ const args = ['-x']; // no sound
40
+ if (opts.includeCursor)
41
+ args.push('-C');
42
+ if (opts.format)
43
+ args.push('-t', opts.format);
44
+ if (opts.delay && opts.delay > 0)
45
+ args.push('-T', String(opts.delay));
46
+ if (opts.display)
47
+ args.push('-D', String(opts.display));
48
+ return args;
49
+ }
50
+ }
@@ -0,0 +1,38 @@
1
+ // ============================================================================
2
+ // macOS window utilities
3
+ // ============================================================================
4
+ import { execFile } from 'child_process';
5
+ import { promisify } from 'util';
6
+ import { SAFE_APP_NAME_PATTERN } from '../config/index.js';
7
+ const execFileAsync = promisify(execFile);
8
+ /** Default executor backed by Node's child_process.execFile. */
9
+ const defaultExecutor = {
10
+ execFile: (command, args) => execFileAsync(command, args),
11
+ };
12
+ /**
13
+ * Look up a macOS window ID by application name via CoreGraphics.
14
+ *
15
+ * @param appName - The display name of the application (e.g. "Safari").
16
+ * @param executor - Optional command executor for testing / DI.
17
+ * @returns The window ID if found, or null.
18
+ */
19
+ export async function getWindowId(appName, executor = defaultExecutor) {
20
+ // NFC-normalize the app name so composed/decomposed Unicode compares equal
21
+ const normalized = appName.normalize('NFC');
22
+ // Security: Reject app names with potentially dangerous characters
23
+ if (!SAFE_APP_NAME_PATTERN.test(normalized)) {
24
+ console.error(`Security: Rejected unsafe app name: ${normalized}`);
25
+ return null;
26
+ }
27
+ try {
28
+ // Build Swift code to find window ID by app name
29
+ const swift = `import CoreGraphics;if let l=CGWindowListCopyWindowInfo(.optionOnScreenOnly,0)as?[[String:Any]]{for w in l{if let n=w[kCGWindowOwnerName as String]as?String,let i=w[kCGWindowNumber as String]as?Int,n.lowercased()=="${normalized.toLowerCase()}"{print(i);exit(0)}}};print(-1)`;
30
+ // Security: Use execFile to avoid shell interpretation (SEC-003)
31
+ const { stdout } = await executor.execFile('swift', ['-e', swift]);
32
+ const id = parseInt(stdout.trim(), 10);
33
+ return id > 0 ? id : null;
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ }
@@ -0,0 +1,67 @@
1
+ // ============================================================================
2
+ // Cross-platform screenshot provider interface + factory
3
+ // ============================================================================
4
+ import { execFile } from 'child_process';
5
+ import { promisify } from 'util';
6
+ export const execFileAsync = promisify(execFile);
7
+ // ── Factory ────────────────────────────────────────────────────────────────
8
+ let _cachedProvider = null;
9
+ /**
10
+ * Return the appropriate ScreenshotProvider for the current OS.
11
+ * The provider is cached after first call.
12
+ */
13
+ export async function getScreenshotProvider() {
14
+ if (_cachedProvider)
15
+ return _cachedProvider;
16
+ let provider;
17
+ switch (process.platform) {
18
+ case 'darwin': {
19
+ const { MacOSProvider } = await import('./macos-provider.js');
20
+ provider = new MacOSProvider();
21
+ break;
22
+ }
23
+ case 'linux': {
24
+ const { LinuxProvider } = await import('./linux-provider.js');
25
+ provider = new LinuxProvider();
26
+ break;
27
+ }
28
+ case 'win32': {
29
+ const { WindowsProvider } = await import('./windows-provider.js');
30
+ provider = new WindowsProvider();
31
+ break;
32
+ }
33
+ default:
34
+ throw new Error(`Unsupported platform: ${process.platform}`);
35
+ }
36
+ const available = await provider.isAvailable();
37
+ if (!available) {
38
+ throw new Error(`No screenshot tools found for ${provider.platform}. ` +
39
+ `See README for required system dependencies.`);
40
+ }
41
+ _cachedProvider = provider;
42
+ return provider;
43
+ }
44
+ /** Reset the cached provider (for testing) */
45
+ export function resetProviderCache() {
46
+ _cachedProvider = null;
47
+ }
48
+ // ── Helpers shared across providers ────────────────────────────────────────
49
+ /**
50
+ * Check if a command exists on the system PATH.
51
+ */
52
+ export async function commandExists(cmd) {
53
+ try {
54
+ const whichCmd = process.platform === 'win32' ? 'where' : 'which';
55
+ await execFileAsync(whichCmd, [cmd]);
56
+ return true;
57
+ }
58
+ catch {
59
+ return false;
60
+ }
61
+ }
62
+ /**
63
+ * Sleep for a given number of seconds (for delay support).
64
+ */
65
+ export function sleep(seconds) {
66
+ return new Promise(resolve => setTimeout(resolve, seconds * 1000));
67
+ }
@@ -0,0 +1,63 @@
1
+ // ============================================================================
2
+ // Semaphore — async concurrency limiter
3
+ // ============================================================================
4
+ /**
5
+ * Simple async semaphore for limiting concurrent access to a resource.
6
+ * Uses a promise-based queue to manage waiting callers.
7
+ */
8
+ export class Semaphore {
9
+ permits;
10
+ waiting = [];
11
+ constructor(permits) {
12
+ this.permits = permits;
13
+ }
14
+ /**
15
+ * Acquire a permit. Resolves immediately if permits available,
16
+ * otherwise waits until a permit is released.
17
+ */
18
+ async acquire() {
19
+ if (this.permits > 0) {
20
+ this.permits--;
21
+ return;
22
+ }
23
+ // No permits available - queue the caller
24
+ // Permit will be handed off directly by release() (no increment/decrement)
25
+ await new Promise(resolve => this.waiting.push(resolve));
26
+ }
27
+ /**
28
+ * Try to acquire a permit without waiting.
29
+ * Returns true if acquired, false if no permits available.
30
+ */
31
+ tryAcquire() {
32
+ if (this.permits > 0) {
33
+ this.permits--;
34
+ return true;
35
+ }
36
+ return false;
37
+ }
38
+ /**
39
+ * Release a permit, allowing the next waiting caller to proceed.
40
+ */
41
+ release() {
42
+ const next = this.waiting.shift();
43
+ if (next) {
44
+ // Hand off permit directly to waiter (don't increment, avoiding race condition)
45
+ next();
46
+ }
47
+ else {
48
+ this.permits++;
49
+ }
50
+ }
51
+ /**
52
+ * Get current available permits (for logging/debugging).
53
+ */
54
+ get available() {
55
+ return this.permits;
56
+ }
57
+ /**
58
+ * Get number of waiting callers (for logging/debugging).
59
+ */
60
+ get waitingCount() {
61
+ return this.waiting.length;
62
+ }
63
+ }
@@ -0,0 +1,130 @@
1
+ // ============================================================================
2
+ // Windows screenshot provider — PowerShell + .NET System.Drawing
3
+ // ============================================================================
4
+ import { execFileAsync, commandExists, sleep } from './screenshot-provider.js';
5
+ /**
6
+ * Windows screenshot provider using PowerShell with .NET System.Drawing.
7
+ * Zero external dependencies — PowerShell and .NET are built into all modern Windows.
8
+ */
9
+ export class WindowsProvider {
10
+ platform = 'Windows';
11
+ async isAvailable() {
12
+ return commandExists('powershell');
13
+ }
14
+ async captureFullscreen(opts) {
15
+ if (opts.delay && opts.delay > 0)
16
+ await sleep(opts.delay);
17
+ const format = this.dotNetFormat(opts.format);
18
+ const displayIndex = (opts.display ?? 1) - 1; // Convert 1-based to 0-based
19
+ const script = `
20
+ Add-Type -AssemblyName System.Windows.Forms
21
+ Add-Type -AssemblyName System.Drawing
22
+ $screens = [System.Windows.Forms.Screen]::AllScreens
23
+ $screen = if (${displayIndex} -lt $screens.Length) { $screens[${displayIndex}] } else { [System.Windows.Forms.Screen]::PrimaryScreen }
24
+ $bounds = $screen.Bounds
25
+ $bitmap = New-Object System.Drawing.Bitmap($bounds.Width, $bounds.Height)
26
+ $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
27
+ ${opts.includeCursor ? '$cursorPos = [System.Windows.Forms.Cursor]::Position\n' : ''}
28
+ $graphics.CopyFromScreen($bounds.Location, [System.Drawing.Point]::Empty, $bounds.Size)
29
+ ${opts.includeCursor ? this.cursorDrawScript() : ''}
30
+ $bitmap.Save('${this.escapePath(opts.outputPath)}', [System.Drawing.Imaging.ImageFormat]::${format})
31
+ $graphics.Dispose()
32
+ $bitmap.Dispose()
33
+ `.trim();
34
+ await this.runPowerShell(script);
35
+ }
36
+ async captureWindow(opts) {
37
+ if (opts.delay && opts.delay > 0)
38
+ await sleep(opts.delay);
39
+ if (!opts.windowName && !opts.windowId) {
40
+ throw new Error('Window mode requires windowName or windowId');
41
+ }
42
+ const format = this.dotNetFormat(opts.format);
43
+ // Use windowName to find the process, or windowId as HWND
44
+ const findWindowScript = opts.windowName
45
+ ? `
46
+ $proc = Get-Process | Where-Object { $_.MainWindowTitle -like '*${this.escapeString(opts.windowName)}*' -and $_.MainWindowHandle -ne 0 } | Select-Object -First 1
47
+ if (-not $proc) { throw "Window not found: ${this.escapeString(opts.windowName)}" }
48
+ $hwnd = $proc.MainWindowHandle
49
+ `
50
+ : `$hwnd = [IntPtr]::new(${opts.windowId})`;
51
+ const script = `
52
+ Add-Type -AssemblyName System.Drawing
53
+ Add-Type @"
54
+ using System;
55
+ using System.Runtime.InteropServices;
56
+ public class Win32 {
57
+ [DllImport("user32.dll")]
58
+ public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
59
+ [DllImport("user32.dll")]
60
+ public static extern bool SetForegroundWindow(IntPtr hWnd);
61
+ [StructLayout(LayoutKind.Sequential)]
62
+ public struct RECT {
63
+ public int Left, Top, Right, Bottom;
64
+ }
65
+ }
66
+ "@
67
+ ${findWindowScript}
68
+ [Win32]::SetForegroundWindow($hwnd) | Out-Null
69
+ Start-Sleep -Milliseconds 300
70
+ $rect = New-Object Win32+RECT
71
+ [Win32]::GetWindowRect($hwnd, [ref]$rect) | Out-Null
72
+ $width = $rect.Right - $rect.Left
73
+ $height = $rect.Bottom - $rect.Top
74
+ if ($width -le 0 -or $height -le 0) { throw "Invalid window dimensions" }
75
+ $bitmap = New-Object System.Drawing.Bitmap($width, $height)
76
+ $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
77
+ $graphics.CopyFromScreen($rect.Left, $rect.Top, 0, 0, (New-Object System.Drawing.Size($width, $height)))
78
+ $bitmap.Save('${this.escapePath(opts.outputPath)}', [System.Drawing.Imaging.ImageFormat]::${format})
79
+ $graphics.Dispose()
80
+ $bitmap.Dispose()
81
+ `.trim();
82
+ await this.runPowerShell(script);
83
+ }
84
+ async captureRegion(opts) {
85
+ if (opts.delay && opts.delay > 0)
86
+ await sleep(opts.delay);
87
+ const format = this.dotNetFormat(opts.format);
88
+ const script = `
89
+ Add-Type -AssemblyName System.Drawing
90
+ $bitmap = New-Object System.Drawing.Bitmap(${opts.width}, ${opts.height})
91
+ $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
92
+ $graphics.CopyFromScreen(${opts.x}, ${opts.y}, 0, 0, (New-Object System.Drawing.Size(${opts.width}, ${opts.height})))
93
+ $bitmap.Save('${this.escapePath(opts.outputPath)}', [System.Drawing.Imaging.ImageFormat]::${format})
94
+ $graphics.Dispose()
95
+ $bitmap.Dispose()
96
+ `.trim();
97
+ await this.runPowerShell(script);
98
+ }
99
+ // ── Private helpers ────────────────────────────────────────────────────
100
+ async runPowerShell(script) {
101
+ await execFileAsync('powershell', [
102
+ '-ExecutionPolicy', 'Bypass',
103
+ '-NoProfile',
104
+ '-NonInteractive',
105
+ '-Command', script,
106
+ ]);
107
+ }
108
+ dotNetFormat(format) {
109
+ switch (format) {
110
+ case 'jpg': return 'Jpeg';
111
+ default: return 'Png';
112
+ }
113
+ }
114
+ escapePath(p) {
115
+ // Escape single quotes for PowerShell string literals
116
+ return p.replace(/'/g, "''");
117
+ }
118
+ escapeString(s) {
119
+ // Escape characters that could break PowerShell string interpolation
120
+ return s.replace(/'/g, "''").replace(/[`$"]/g, '');
121
+ }
122
+ cursorDrawScript() {
123
+ return `
124
+ try {
125
+ $cursorBounds = New-Object System.Drawing.Rectangle($cursorPos.X - $bounds.X, $cursorPos.Y - $bounds.Y, 32, 32)
126
+ [System.Windows.Forms.Cursors]::Default.Draw($graphics, $cursorBounds)
127
+ } catch {}
128
+ `;
129
+ }
130
+ }