### Start Screen Recording Example Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/screen-recording.md Example usage of the startRecordingScreen method with specific recording parameters. ```typescript // Using W3C WebDriver method const video = await driver.startRecordingScreen({ deviceId: 0, timeLimit: 120, fps: 30 }); ``` -------------------------------- ### Install project dependencies Source: https://github.com/appium/appium-mac2-driver/blob/master/docs/contributing.md Run this command after cloning the repository to install necessary dependencies. ```bash npm install ``` -------------------------------- ### Run in development mode Source: https://github.com/appium/appium-mac2-driver/blob/master/docs/contributing.md Starts the project in development mode. ```bash npm run dev ``` -------------------------------- ### startRecordingScreen() Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/screen-recording.md Starts a screen recording session with optional configuration parameters. ```APIDOC ## startRecordingScreen() ### Description Starts a screen recording session on the target device. ### Method SDK Method ### Parameters - **options** (object) - Optional - Recording options including deviceId, timeLimit, videoFilter, fps, preset, captureCursor, captureClicks, and forceRestart. ### Returns - **Promise** - The path to the recorded video file. ### Example ```typescript const video = await driver.startRecordingScreen({ deviceId: 0, timeLimit: 120, fps: 30 }); ``` ``` -------------------------------- ### macosKeys Usage Examples Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/gestures.md Examples demonstrating how to send simple keys, special keys, and keys with modifiers. ```typescript // Send simple keys await driver.macosKeys(['a', 'b', 'c']); // Send special keys await driver.macosKeys(['Return', 'Tab']); // Send keys with modifiers await driver.macosKeys([ {key: 'a', modifierFlags: 0x100000}, // Cmd+A {key: 'c', modifierFlags: 0x100000} // Cmd+C ]); // Send to specific element await driver.macosKeys(['a', 'b', 'c'], 'element-uuid-123'); // Send mixed keys and key options await driver.macosKeys([ 'a', {key: 'b', modifierFlags: 0x200000}, // Shift+B 'c' ]); ``` -------------------------------- ### Install FFmpeg for Screen Recording Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/errors.md Install FFmpeg via Homebrew and verify the installation to resolve 'ffmpeg binary not found' errors. ```bash # macOS brew install ffmpeg # Verify installation which ffmpeg ffmpeg -version ``` -------------------------------- ### Develop documentation Source: https://github.com/appium/appium-mac2-driver/blob/master/docs/contributing.md Commands to install documentation dependencies and serve the documentation locally. ```bash npm run install-docs-deps # install the dependencies (Python packages) npm run dev:docs # serve the docs locally and watch for changes ``` -------------------------------- ### macosSetValue Usage Examples Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/gestures.md Examples demonstrating how to set text, arrays, and use modifier keys. ```typescript // Set text field value await driver.macosSetValue('element-uuid-123', 'Hello World'); // Set value with array await driver.macosSetValue('element-uuid-123', ['H', 'e', 'l', 'l', 'o']); // Set text with modifier keys await driver.macosSetValue('element-uuid-123', undefined, 'test', 0x100000); ``` -------------------------------- ### macos: startRecordingScreen Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/endpoints.md Starts an FFmpeg-based screen recording session. ```APIDOC ## execute('macos: startRecordingScreen', params) ### Description Start FFmpeg-based screen recording. ### Parameters #### Required Parameters - **deviceId** (string|number) - Required - The device ID to record. #### Optional Parameters - **timeLimit** (string|number) - Optional - Recording time limit in seconds. Default is 600. - **videoFilter** (string) - Optional - Video filter settings. - **fps** (string|number) - Optional - Frames per second. Default is 15. - **preset** (string) - Optional - Encoding preset. Default is 'veryfast'. - **captureCursor** (boolean) - Optional - Whether to capture the cursor. Default is false. - **captureClicks** (boolean) - Optional - Whether to capture clicks. Default is false. - **forceRestart** (boolean) - Optional - Whether to force restart the recording. Default is false. ``` -------------------------------- ### Verify Appium server installation Source: https://github.com/appium/appium-mac2-driver/blob/master/docs/getting-started/index.md Launch the Appium server and confirm the Mac2 driver is loaded in the logs. ```bash appium ``` ```text [Appium] Mac2Driver has been successfully loaded in 0.789s ``` -------------------------------- ### Install Appium Mac2 Driver Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/README.md Use npm to install the driver package in your project. ```bash npm install appium-mac2-driver ``` -------------------------------- ### Install Mac2 driver Source: https://github.com/appium/appium-mac2-driver/blob/master/docs/getting-started/index.md Install the latest or a specific version of the Mac2 driver using the Appium extension CLI. ```bash appium driver install mac2 ``` ```bash appium driver install mac2@2.2.0 ``` -------------------------------- ### Launch macOS Applications Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/app-management.md Examples of launching applications using bundle IDs, paths, command-line arguments, and environment variables. ```typescript // Launch by bundle ID await driver.macosLaunchApp('com.apple.TextEdit'); // Launch with arguments await driver.macosLaunchApp('com.example.MyApp', undefined, ['--debug', '--port=8080']); // Launch with environment variables await driver.macosLaunchApp( 'com.example.MyApp', undefined, [], {'MY_VAR': 'value', 'DEBUG': '1'} ); // Launch by path await driver.macosLaunchApp( undefined, '/Applications/TextEdit.app' ); ``` -------------------------------- ### Capturing and Saving Screenshots Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/other-commands.md Examples demonstrating how to capture screenshots for all displays or a specific display, and how to save them to the filesystem. ```typescript // Screenshot all displays const screenshots = await driver.macosScreenshots(); Object.entries(screenshots).forEach(([displayId, info]) => { console.log(`Display ${info.id}${info.isMain ? ' (main)' : ''}`); // Save screenshot const imageBuffer = Buffer.from(info.payload, 'base64'); // Save or upload imageBuffer }); // Screenshot specific display const screenshots = await driver.macosScreenshots(0); const mainDisplay = screenshots['0']; const imageData = Buffer.from(mainDisplay.payload, 'base64'); // Save screenshot to file import fs from 'fs'; const screenshots = await driver.macosScreenshots(); Object.entries(screenshots).forEach(([id, info]) => { fs.writeFileSync(`screenshot-${id}.png`, Buffer.from(info.payload, 'base64')); }); ``` -------------------------------- ### Create WebDriver Session Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/mac2-driver.md Example of creating a session with W3C capabilities. ```typescript const caps = { alwaysMatch: { platformName: 'Mac', 'appium:automationName': 'Mac2', 'appium:bundleId': 'com.apple.TextEdit', }, }; const [sessionId, finalCaps] = await driver.createSession(caps); console.log(`Session created: ${sessionId}`); ``` -------------------------------- ### macos: startNativeScreenRecording Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/endpoints.md Starts a native XCTest-based screen recording. ```APIDOC ## execute('macos: startNativeScreenRecording', params) ### Description Start native XCTest screen recording. ### Parameters #### Required Parameters - **displayId** (number) - Required - The display ID to record. #### Optional Parameters - **fps** (number) - Optional - Frames per second. - **codec** (string) - Optional - Video codec. ``` -------------------------------- ### Instantiate Mac2Driver Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/configuration.md Example of direct driver instantiation with custom system port and host configuration. ```typescript import {Mac2Driver} from 'appium-mac2-driver'; const driver = new Mac2Driver({ appium: { systemPort: 10100, systemHost: '127.0.0.1' } }); ``` -------------------------------- ### Initialize Mac2 Session Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/configuration.md Examples for creating a new Mac2 driver session using WebdriverIO. ```javascript const {remote} = require('webdriverio'); const caps = { platformName: 'Mac', 'appium:automationName': 'Mac2', 'appium:bundleId': 'com.apple.TextEdit', 'appium:systemPort': 10100, 'appium:serverStartupTimeout': 180000, 'appium:arguments': ['--debug'], 'appium:environment': { 'MY_ENV_VAR': 'value', 'DEBUG': '1' }, 'appium:appLocale': { 'language': 'en', 'country': 'US' } }; const driver = await remote({ path: '/wd/hub', port: 4723, capabilities: {alwaysMatch: caps} }); ``` ```typescript import {remote, RemoteOptions} from 'webdriverio'; const capabilities = { platformName: 'Mac', 'appium:automationName': 'Mac2', 'appium:bundleId': 'com.apple.TextEdit', 'appium:noReset': false, 'appium:showServerLogs': true, 'appium:prerun': { command: 'tell application "Finder" to activate' } } as const; const opts: RemoteOptions = { path: '/wd/hub', port: 4723, capabilities: {alwaysMatch: capabilities} }; const driver = await remote(opts); ``` -------------------------------- ### Start Screen Recording Endpoint Source: https://github.com/appium/appium-mac2-driver/blob/master/docs/reference/endpoints.md Initiates a screen recording session via a POST request. ```http POST /session/:sessionId/appium/start_recording_screen ``` -------------------------------- ### List Displays and Start Recording Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/screen-recording.md Retrieves a list of available displays and demonstrates how to identify the main display to initiate a recording session. ```typescript const displays = await driver.macosListDisplays(); console.log(`Found ${displays.length} displays:`); displays.forEach(display => { console.log(`Display ${display.id}${display.isMain ? ' (main)' : ''}`); }); // Record main display const mainDisplay = displays.find(d => d.isMain); if (mainDisplay) { await driver.macosStartRecordingScreen(mainDisplay.id); } ``` -------------------------------- ### macosStartRecordingScreen() Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/screen-recording.md Starts a screen recording session on the specified device using FFmpeg. Returns the path to the resulting video file. ```APIDOC ## macosStartRecordingScreen() ### Description Starts recording the screen using FFmpeg. This method allows for customization of recording parameters such as duration, frame rate, and visual capture settings. ### Method async macosStartRecordingScreen(deviceId, timeLimit, videoFilter, fps, preset, captureCursor, captureClicks, forceRestart) ### Parameters - **deviceId** (string | number) - Required - Display device ID (e.g., "0" or 0 for main display) - **timeLimit** (string | number) - Optional - Max recording duration in seconds (Default: 600) - **videoFilter** (string) - Optional - FFmpeg video filter string - **fps** (string | number) - Optional - Frames per second for recording (Default: 15) - **preset** (Preset) - Optional - FFmpeg preset (ultrafast to veryslow) (Default: 'veryfast') - **captureCursor** (boolean) - Optional - Include mouse cursor in recording (Default: false) - **captureClicks** (boolean) - Optional - Highlight mouse clicks (Default: false) - **forceRestart** (boolean) - Optional - Restart if already recording (Default: false) ### Returns - **Promise** - The path to the recorded video file. ### Example ```typescript const videoPath = await driver.macosStartRecordingScreen(0, 120, undefined, 30, 'fast', true, true); ``` ``` -------------------------------- ### POST /session/:sessionId/appium/start_recording_screen Source: https://github.com/appium/appium-mac2-driver/blob/master/docs/reference/endpoints.md Starts a screen recording session on the target macOS device. ```APIDOC ## POST /session/:sessionId/appium/start_recording_screen ### Description Starts a screen recording. A wrapper for the macos: startRecordingScreen execute method. ### Method POST ### Endpoint /session/:sessionId/appium/start_recording_screen ### Parameters #### Request Body - **options** (Record) - Optional - Map of screen recording options. ### Response #### Success Response (200) - **null** ``` -------------------------------- ### createSession(w3cCaps1, w3cCaps2?, w3cCaps3?, driverData?) Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/mac2-driver.md Initializes a new WebDriver session, starts the WebDriverAgentMac server, and prepares the driver for automation. ```APIDOC ## Method: createSession ### Description Creates a new WebDriver session with the provided capabilities. Initializes the WebDriverAgentMac server and prepares the driver for automation. ### Parameters - **w3cCaps1** (W3CMac2DriverCaps) - Required - Primary W3C capabilities - **w3cCaps2** (W3CMac2DriverCaps) - Optional - Secondary capabilities (Microsoft standard) - **w3cCaps3** (W3CMac2DriverCaps) - Optional - Tertiary capabilities (fallback) - **driverData** (DriverData[]) - Optional - Additional driver-specific data ### Returns - **Promise<[sessionId: string, caps: Mac2DriverCaps]>** - Session ID and final capabilities ``` -------------------------------- ### Usage Examples for StringRecord Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/types.md Demonstrates initializing StringRecord objects for environment variables, HTTP headers, and generic options. ```typescript // Environment variables const env: StringRecord = { 'PATH': '/usr/local/bin', 'DEBUG': '1' }; // HTTP headers const headers: StringRecord = { 'Authorization': 'Bearer token', 'Content-Type': 'application/json' }; // Generic options const opts: StringRecord = { key1: 'value1', key2: 123, key3: true }; ``` -------------------------------- ### macosStartNativeScreenRecording() Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/screen-recording.md Starts a native XCTest screen recording session on the specified display. ```APIDOC ## macosStartNativeScreenRecording(displayId, codec, fps, forceRestart) ### Description Starts a native XCTest screen recording. This method provides higher quality output compared to FFmpeg-based recording. ### Parameters - **displayId** (number) - Optional - Display ID to record. - **codec** (string) - Optional - Video codec (e.g., 'h264'). - **fps** (number) - Optional - Frames per second. - **forceRestart** (boolean) - Optional - Restart if already recording (default: false). ### Returns - **Promise** - Returns a recording UUID for tracking. ### Example ```typescript const recordingId = await driver.macosStartNativeScreenRecording(0, 'h264', 30); ``` ``` -------------------------------- ### Start Screen Recording Options Structure Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/screen-recording.md The configuration object structure for customizing screen recording parameters. ```typescript { deviceId?: string | number; timeLimit?: string | number; videoFilter?: string; fps?: string | number; preset?: Preset; captureCursor?: boolean; captureClicks?: boolean; forceRestart?: boolean; } ``` -------------------------------- ### Screen Recording Usage Examples Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/screen-recording.md Demonstrates various ways to invoke screen recording, including basic usage, custom settings, video filtering, and force-restarting. ```typescript // Basic screen recording const videoPath = await driver.macosStartRecordingScreen(0); // Record main display with custom settings const videoPath = await driver.macosStartRecordingScreen( 0, // main display 120, // 2-minute max undefined, // no video filter 30, // 30 FPS 'fast', // fast encoding true, // include cursor true // highlight clicks ); // Recording with video filter (e.g., scale video) const videoPath = await driver.macosStartRecordingScreen( 0, 180, 'scale=1280:-1' // scale width to 1280 ); // Restart recording if already running const videoPath = await driver.macosStartRecordingScreen( 0, undefined, undefined, undefined, undefined, undefined, undefined, true // force restart ); ``` -------------------------------- ### Start Screen Recording Method Definition Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/screen-recording.md The method signature for initiating a screen recording session. ```typescript async startRecordingScreen(options?: any): Promise ``` -------------------------------- ### Activate macOS Applications Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/app-management.md Examples of activating running applications using either a bundle ID or a file path. ```typescript // Activate by bundle ID await driver.macosActivateApp('com.apple.TextEdit'); // Activate by path await driver.macosActivateApp(undefined, '/Applications/TextEdit.app'); ``` -------------------------------- ### macosLaunchApp() Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/app-management.md Starts an application using its bundle identifier or path, or activates it if it is already running. Supports passing command line arguments and environment variables. ```APIDOC ## macosLaunchApp(bundleId, path, args, environment) ### Description Start an app with given bundle identifier or activate it if already running. ### Signature `async macosLaunchApp(bundleId?: string, path?: string, args?: string[], environment?: StringRecord): Promise` ### Parameters - **bundleId** (string) - Optional - Bundle identifier of the app to launch/activate. Either bundleId or path must be provided. - **path** (string) - Optional - Full path to the app bundle. Either bundleId or path must be provided. - **args** (string[]) - Optional - Command line arguments for app launch. - **environment** (StringRecord) - Optional - Environment variables to set. ### Returns - **Promise** - Result from WDA server. ### Example ```typescript await driver.macosLaunchApp('com.apple.TextEdit'); await driver.macosLaunchApp('com.example.MyApp', undefined, ['--debug', '--port=8080']); ``` ``` -------------------------------- ### Stop Screen Recording Example Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/screen-recording.md Example usage of the stopRecordingScreen method with a remote upload path. ```typescript // Using W3C WebDriver method const video = await driver.stopRecordingScreen({ remotePath: 'http://example.com/upload' }); ``` -------------------------------- ### macosClick() Usage Examples Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/gestures.md Demonstrates clicking by element ID, absolute coordinates, or with modifier keys. ```typescript // Click on element await driver.macosClick('element-uuid-123'); // Click at absolute coordinates await driver.macosClick(undefined, 100, 200); // Click with modifier keys (Cmd key = 0x100000) await driver.macosClick('element-uuid-123', undefined, undefined, 0x100000); ``` -------------------------------- ### Get Application Source Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/endpoints.md Retrieves the application source code in either XML or description format. ```javascript const xmlSource = await driver.execute('macos: source', { format: 'xml' }); const descSource = await driver.execute('macos: source', { format: 'description' }); ``` -------------------------------- ### macosDoubleClick() Usage Examples Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/gestures.md Demonstrates double-clicking by element ID or specific coordinates. ```typescript // Double-click element await driver.macosDoubleClick('element-uuid-123'); // Double-click at coordinates await driver.macosDoubleClick(undefined, 150, 250); ``` -------------------------------- ### Define Valid and Invalid Prerun Capabilities Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/errors.md Examples of correct and incorrect structures for the prerun capability. ```json // Correct structure { 'appium:prerun': { script: 'tell application "Finder" to activate' } } // Or { 'appium:prerun': { command: 'tell application "TextEdit" to activate' } } // Not valid: { 'appium:prerun': { script: 123 // Must be string } } ``` -------------------------------- ### Define session capabilities Source: https://github.com/appium/appium-mac2-driver/blob/master/docs/getting-started/index.md Minimum required capabilities to start a macOS session and attach to the Finder application. ```json // This will start a macOS session and attach to the Finder application { ... "platformName": "mac", "appium:automationName": "mac2", ... } ``` -------------------------------- ### Execute Key Commands with Modifiers Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/types.md Example usage of KeyOptions to perform key sequences with modifier flags. ```typescript const keyWithModifiers: KeyOptions = { key: 'a', modifierFlags: 0x100000 // Cmd+A }; const keys: (KeyOptions | string)[] = [ 'a', {key: 'b', modifierFlags: 0x20000}, // Shift+B {key: 's', modifierFlags: 0x100000} // Cmd+S ]; await driver.macosKeys(keys); ``` -------------------------------- ### Screen Recording Workflow in TypeScript Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/screen-recording.md Demonstrates the full lifecycle of a screen recording session, including starting, interacting with the system, and stopping the recording with optional remote upload. ```typescript // Set up test const driver = new Mac2Driver(); // Create session await driver.createSession({ alwaysMatch: { platformName: 'Mac', 'appium:automationName': 'Mac2', 'appium:bundleId': 'com.apple.TextEdit' } }); // Start recording with custom options await driver.macosStartRecordingScreen(0, 300, undefined, 30, 'veryfast', true); // Run test actions await driver.macosClick(/* ... */); // Get available displays (optional) const displays = await driver.macosListDisplays(); // Stop and retrieve video const base64Video = await driver.macosStopRecordingScreen(); // Or upload directly const uploadResult = await driver.macosStopRecordingScreen( 'http://ci.example.com/artifacts', 'ci_user', 'ci_pass' ); // Clean up await driver.deleteSession(); ``` -------------------------------- ### Start FFmpeg Screen Recording Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/endpoints.md Initiates screen recording using FFmpeg with configurable parameters like time limit and frame rate. ```javascript await driver.execute('macos: startRecordingScreen', { deviceId: 0, timeLimit: 120, fps: 30 }); ``` -------------------------------- ### Proxy Command Usage Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/mac2-driver.md Example of executing a POST request to the WDA server to check application state. ```typescript const response = await driver.proxyCommand('/wda/apps/state', 'POST', { bundleId: 'com.apple.TextEdit' }); ``` -------------------------------- ### macosSwipe() Usage Examples Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/gestures.md Demonstrates swiping within an element, swiping with velocity, and swiping with high velocity. ```typescript // Swipe within element await driver.macosSwipe('up', 'element-uuid-123'); // Swipe with velocity await driver.macosSwipe('down', undefined, 300, 400, 1000); // Swipe left with high velocity await driver.macosSwipe('left', 'element-uuid-123', undefined, undefined, 5000); ``` -------------------------------- ### Manage screen recording Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/README.md Starts a screen recording session, performs actions, and saves the resulting video buffer to a file. ```typescript // Start recording await driver.execute('macos: startRecordingScreen', { deviceId: 0, timeLimit: 120, fps: 30 }); // Run test await driver.macosClick('element-id'); // Stop and download const video = await driver.execute('macos: stopRecordingScreen'); const buffer = Buffer.from(video, 'base64'); fs.writeFileSync('recording.mp4', buffer); ``` -------------------------------- ### Start native screen recording Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/screen-recording.md Initiates a native XCTest screen recording session. Returns a UUID used to track the recording. ```typescript async macosStartNativeScreenRecording( displayId?: number, codec?: string, fps?: number, forceRestart?: boolean ): Promise ``` ```typescript // Start native recording const recordingId = await driver.macosStartNativeScreenRecording(0); // With specific codec const recordingId = await driver.macosStartNativeScreenRecording(0, 'h264', 30); ``` -------------------------------- ### Manage FFmpeg Screen Recording Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/screen-recording.md Demonstrates the lifecycle of the ScreenRecorder class, including initialization, starting, stopping, and retrieving the output video path. ```typescript const recorder = new ScreenRecorder('/tmp/video.mp4', logger, { deviceId: 0, fps: 30, preset: 'fast' }); await recorder.start(); // ... test ... await recorder.stop(); const videoPath = await recorder.getVideoPath(); ``` -------------------------------- ### Verifying Application State for DeepLinks Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/errors.md Verify application installation status or provide a bundle ID when deep linking fails. ```typescript // Verify app is installed const state = await driver.macosQueryAppState('com.example.MyApp'); if (state === 0) { console.error('App not installed'); } // Or use bundle ID await driver.macosDeepLink('myapp://data', 'com.example.MyApp'); ``` -------------------------------- ### macosExecAppleScript Usage Examples Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/other-commands.md Various ways to invoke AppleScript, including single commands, full scripts, language overrides, timeouts, and setting the working directory. ```typescript // Execute a command const output = await driver.macosExecAppleScript( undefined, undefined, 'tell application "Finder" to activate' ); // Execute a full script const script = ` tell application "System Events" keystroke "a" using command down keystroke "c" using command down end tell `; const output = await driver.macosExecAppleScript(script); // Execute with language override const output = await driver.macosExecAppleScript( 'tell application "System Events" to keystroke return', 'en' ); // Execute with timeout const output = await driver.macosExecAppleScript( script, undefined, undefined, undefined, 30 // 30 second timeout ); // Set working directory const output = await driver.macosExecAppleScript( script, undefined, undefined, '/tmp' ); ``` -------------------------------- ### Get System Clipboard Content Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/other-commands.md Defines the signature for retrieving clipboard content and provides examples for reading different content types. ```typescript async macosGetClipboard( contentType?: string ): Promise ``` ```typescript // Get plain text const textBase64 = await driver.macosGetClipboard(); const text = Buffer.from(textBase64, 'base64').toString('utf-8'); console.log(text); // Get URL const urlBase64 = await driver.macosGetClipboard('url'); const url = Buffer.from(urlBase64, 'base64').toString('utf-8'); // Get image const imageBase64 = await driver.macosGetClipboard('image'); // Check if clipboard has content const clipboardContent = await driver.macosGetClipboard(); if (clipboardContent) { console.log('Clipboard has content'); } else { console.log('Clipboard is empty'); } ``` -------------------------------- ### StartRecordingScreenOptions Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/types.md User-facing options for initiating a screen recording session. ```APIDOC ## StartRecordingScreenOptions ### Description User-facing options for starting screen recording. ### Parameters - **deviceId** (string | number) - Optional - Display to record - **timeLimit** (string | number) - Optional - Max duration (seconds) (Default: 600) - **videoFilter** (string) - Optional - FFmpeg filter string - **fps** (string | number) - Optional - Frames per second (Default: 15) - **preset** (Preset) - Optional - Compression preset (Default: 'veryfast') - **captureCursor** (boolean) - Optional - Include cursor (Default: false) - **captureClicks** (boolean) - Optional - Highlight clicks (Default: false) - **forceRestart** (boolean) - Optional - Restart if recording (Default: false) ``` -------------------------------- ### Build the project Source: https://github.com/appium/appium-mac2-driver/blob/master/docs/contributing.md Compiles the project source code. ```bash npm run build ``` -------------------------------- ### Get Window Rectangle Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/mac2-driver.md Retrieve the window dimensions and position. ```typescript const rect = await driver.getWindowRect(); console.log(`Window size: ${rect.width}x${rect.height}`); ``` -------------------------------- ### Get Server Status Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/mac2-driver.md Retrieve the current status of the WebDriverAgentMac server. ```typescript const status = await driver.getStatus(); ``` -------------------------------- ### Define StartRecordingScreenOptions interface Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/types.md User-facing options for initiating a screen recording session. ```typescript interface StartRecordingScreenOptions { deviceId?: string | number; timeLimit?: string | number; videoFilter?: string; fps?: string | number; preset?: Preset; captureCursor?: boolean; captureClicks?: boolean; forceRestart?: boolean; } ``` -------------------------------- ### Process Screenshot Data Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/types.md Example of retrieving and processing screenshot information from the driver. ```typescript const screenshots: ScreenshotsInfo = await driver.macosScreenshots(); Object.entries(screenshots).forEach(([displayId, info]) => { console.log(`Display ${info.id} (main: ${info.isMain})`); const imageBuffer = Buffer.from(info.payload, 'base64'); }); ``` -------------------------------- ### Get Driver Status Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/README.md Retrieve the current status of the Appium driver instance. ```typescript const status = await driver.getStatus(); console.log(status); ``` -------------------------------- ### Get Proxy Avoid List Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/mac2-driver.md Retrieves the list of routes that bypass the WDA proxy. ```typescript override getProxyAvoidList(sessionId: string): RouteMatcher[] ``` -------------------------------- ### Launch Application Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/endpoints.md Launches or activates an application using either a bundle identifier or a file path. ```javascript await driver.execute('macos: launchApp', { bundleId: 'com.apple.TextEdit' }); await driver.execute('macos: launchApp', { path: '/Applications/TextEdit.app', arguments: ['--debug'], environment: {'DEBUG': '1'} }); ``` -------------------------------- ### Configure Server Settings Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/configuration.md Customize the WebDriverAgentMac server host, port, and startup timeout settings. ```json { "appium:systemHost": "192.168.1.100", "appium:systemPort": 10100, "appium:serverStartupTimeout": 180000 } ``` -------------------------------- ### Performing Accessibility Audits Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/other-commands.md Examples of running full or targeted accessibility audits and processing the results. ```typescript // Audit all aspects const issues = await driver.macosPerformAccessibilityAudit(); console.log(`Found ${issues.length} accessibility issues`); issues.forEach(issue => { console.log(`${issue.auditType}: ${issue.compactDescription}`); }); // Audit specific aspects const contrastIssues = await driver.macosPerformAccessibilityAudit([ 'XCUIAccessibilityAuditTypeContrast' ]); // Assert no critical issues in tests const criticalIssues = issues.filter( issue => issue.auditType === 'XCUIAccessibilityAuditTypeContrast' ); console.assert(criticalIssues.length === 0, 'Critical accessibility issues found'); ``` -------------------------------- ### Initialize and Use Mac2 Driver Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/README.md Demonstrates creating a session with WebDriverIO, interacting with elements, and cleaning up the session. ```typescript import {Mac2Driver} from 'appium-mac2-driver'; import {remote} from 'webdriverio'; // Create a session const driver = await remote({ path: '/wd/hub', port: 4723, capabilities: { alwaysMatch: { platformName: 'Mac', 'appium:automationName': 'Mac2', 'appium:bundleId': 'com.apple.TextEdit' } } }); // Use the driver await driver.macosClick('element-id'); const text = await driver.$('.some-class').getText(); // Clean up await driver.deleteSession(); ``` -------------------------------- ### Manage Application Lifecycle in TypeScript Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/app-management.md Demonstrates the full lifecycle of an application including launching, state verification, activation, and termination. ```typescript // Complete app lifecycle management const bundleId = 'com.example.MyApp'; // Launch the app await driver.macosLaunchApp(bundleId, undefined, ['--debug']); // Verify it's running let state = await driver.macosQueryAppState(bundleId); if (state !== 3) { // Activate if not in foreground await driver.macosActivateApp(bundleId); } // Do testing... // Clean up const wasRunning = await driver.macosTerminateApp(bundleId); console.log(`App was running: ${wasRunning}`); ``` -------------------------------- ### Mac2Driver(opts?: InitialOpts) Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/mac2-driver.md Creates a new instance of the Mac2Driver class with optional initialization parameters. ```APIDOC ## Constructor: Mac2Driver(opts?: InitialOpts) ### Description Creates a new Mac2Driver instance with optional initialization options. ### Parameters - **opts** (InitialOpts) - Optional - Initial driver options from Appium framework ### Returns - **Mac2Driver** instance ``` -------------------------------- ### macosScroll() Usage Examples Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/gestures.md Demonstrates scrolling within an element, at specific screen coordinates, and horizontal scrolling. ```typescript // Scroll within element await driver.macosScroll(0, -100, 'element-uuid-123'); // Scroll at screen coordinates await driver.macosScroll(50, -200, undefined, 400, 300); // Horizontal scroll await driver.macosScroll(100, 0, 'element-uuid-123'); ``` -------------------------------- ### Initialize and execute basic test flow Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/README.md Connects to the Appium server and performs basic interactions like clicking elements, taking screenshots, and executing AppleScript. ```typescript // Connect to local Appium server const driver = await remote({ path: '/wd/hub', port: 4723, capabilities: { alwaysMatch: { platformName: 'Mac', 'appium:automationName': 'Mac2', 'appium:bundleId': 'com.apple.TextEdit' } } }); try { // Interact with app const button = await driver.$('accessibility id:submitBtn'); await button.click(); // Take screenshot const screenshot = await driver.takeScreenshot(); // Run AppleScript const result = await driver.execute('macos: appleScript', { command: 'tell application "System Events" to keystroke return' }); } finally { await driver.deleteSession(); } ``` -------------------------------- ### Catch WDA Initialization Errors Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/errors.md Demonstrates how to catch and handle errors when the WDA server is not initialized. ```typescript try { await driver.getStatus(); } catch (err: any) { if (err.message === 'WDA server is not initialized') { console.error('Session not properly initialized'); } } ``` -------------------------------- ### Get Native Screen Recording Info Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/endpoints.md Retrieves metadata about the current native screen recording session. ```javascript const info = await driver.execute('macos: getNativeScreenRecordingInfo'); ``` -------------------------------- ### Activate Application Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/endpoints.md Brings an existing application to the foreground. ```javascript await driver.execute('macos: activateApp', { bundleId: 'com.apple.TextEdit' }); ``` -------------------------------- ### getSettings Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/configuration.md Retrieves the current runtime settings from the driver. ```APIDOC ## getSettings ### Description Returns the current configuration settings currently in use by the driver. ### Method async getSettings() ### Response - **settings** (object) - The current configuration object. ``` -------------------------------- ### Get Clipboard Content Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/endpoints.md Retrieves the current clipboard content. Supports 'plaintext', 'image', and 'url' content types. ```javascript const text = await driver.execute('macos: getClipboard', { contentType: 'plaintext' }); ``` -------------------------------- ### Open Xcode Helper directory Source: https://github.com/appium/appium-mac2-driver/blob/master/docs/getting-started/index.md Open the Finder directory containing the Xcode Helper app to configure accessibility permissions. ```bash open /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Xcode/Agents/ ``` -------------------------------- ### List Displays Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/endpoints.md Returns a list of all available displays connected to the system. ```javascript const displays = await driver.execute('macos: listDisplays'); ``` -------------------------------- ### Set System Clipboard Content Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/other-commands.md Defines the signature for setting clipboard content and provides examples for plaintext, URL, and image types. ```typescript async macosSetClipboard( content: string, contentType?: string ): Promise ``` ```typescript // Set plain text await driver.macosSetClipboard( Buffer.from('Hello World').toString('base64'), 'plaintext' ); // Set URL const url = 'https://example.com'; await driver.macosSetClipboard( Buffer.from(url).toString('base64'), 'url' ); // Set image (base64-encoded PNG) const imageBase64 = 'iVBORw0KGgoAAAANSUhEUgAA...'; await driver.macosSetClipboard(imageBase64, 'image'); ``` -------------------------------- ### Retrieve application source with macosSource Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/other-commands.md Fetches the application source in either XML or description format. XML is the default format. ```typescript // Get XML source (default) const xmlSource = await driver.macosSource(); console.log(xmlSource); // Get description format const descSource = await driver.macosSource('description'); console.log(descSource); // Parse XML const parser = new DOMParser(); const doc = parser.parseFromString(xmlSource, 'text/xml'); ``` -------------------------------- ### Project Structure Overview Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/README.md Visual representation of the repository file layout. ```text appium-mac2-driver/ ├── lib/ │ ├── driver.ts # Main Mac2Driver class │ ├── index.ts # Entry point │ ├── constraints.ts # Capability constraints │ ├── types.ts # Type definitions │ ├── utils.ts # Utility functions │ ├── logger.ts # Logging setup │ ├── method-map.ts # HTTP route mappings │ ├── execute-method-map.ts # Execute script mappings │ ├── wda-mac.ts # WebDriverAgentMac integration │ ├── commands/ │ │ ├── app-management.ts # Launch, activate, terminate apps │ │ ├── applescript.ts # AppleScript execution │ │ ├── audit.ts # Accessibility auditing │ │ ├── clipboard.ts # Clipboard operations │ │ ├── execute.ts # Execute script handling │ │ ├── find.ts # Element finding │ │ ├── gestures.ts # Click, drag, swipe, keyboard │ │ ├── navigation.ts # DeepLink navigation │ │ ├── record-screen.ts # FFmpeg screen recording │ │ ├── native-record-screen.ts # XCTest native recording │ │ ├── screenshots.ts # Screenshot capture │ │ ├── source.ts # App source retrieval │ │ ├── helpers.ts # Shared helpers │ │ └── bidi/ # BiDi protocol support │ └── doctor/ # Health checks ├── WebDriverAgentMac/ # Native XCTest agent ├── package.json └── README.md ``` -------------------------------- ### appium:mac2.nativeVideoRecordingChunkAdded Source: https://github.com/appium/appium-mac2-driver/blob/master/docs/reference/bidi.md An event emitted when a new native video recording chunk is available. It is triggered after starting native screen recording. ```APIDOC ## Event: appium:mac2.nativeVideoRecordingChunkAdded ### Description Indicates that a new native video recording chunk is available for consumption. This event is emitted continuously after `macos: startNativeScreenRecording` is invoked until recording is stopped. ### Parameters - **uuid** (text) - The UUID of the video being broadcast. - **payload** (text) - Base64-encoded chunk of the corresponding video file. ``` -------------------------------- ### Enable all insecure features via CLI Source: https://github.com/appium/appium-mac2-driver/blob/master/docs/reference/insecure-features.md Use the --relaxed-security flag to enable all insecure features at once. ```bash appium --relaxed-security ``` -------------------------------- ### Handle Invalid Display Device IDs Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/errors.md Retrieve available displays to ensure a valid device ID is used when starting a screen recording. ```typescript // Get available displays first const displays = await driver.macosListDisplays(); console.log(displays); // [{id: 0, isMain: true}, ...] // Use valid display ID await driver.macosStartRecordingScreen(displays[0].id); ``` -------------------------------- ### Configure Application Targeting Capabilities Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/configuration.md Use these capabilities to specify the target application via bundle identifier or file path. ```json { "platformName": "Mac", "appium:automationName": "Mac2", "appium:bundleId": "com.apple.TextEdit" } ``` -------------------------------- ### macos: launchApp Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/endpoints.md Launch or activate an application using its bundle identifier or path. ```APIDOC ## macos: launchApp ### Description Launch or activate an application. ### Method execute('macos: launchApp', params) ### Parameters - **bundleId** (string) - Optional - Bundle identifier (e.g., 'com.apple.TextEdit') - **path** (string) - Optional - Full path to app bundle - **arguments** (string[]) - Optional - Command-line arguments - **environment** (object) - Optional - Environment variables *Note: Either bundleId or path is required.* ``` -------------------------------- ### Stop Screen Recording Examples Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/screen-recording.md Various ways to stop a screen recording, including base64 retrieval, remote uploads, and multipart form submissions. ```typescript // Stop recording and return base64 const base64Video = await driver.macosStopRecordingScreen(); console.log(`Video size: ${base64Video.length} bytes`); // Stop and upload to remote server const result = await driver.macosStopRecordingScreen( 'http://example.com/upload/video.mp4', 'user', 'password' ); // Upload with custom headers const result = await driver.macosStopRecordingScreen( 'http://example.com/upload', undefined, undefined, 'POST', {'Authorization': 'Bearer token123'} ); // Upload with form fields (multipart) const result = await driver.macosStopRecordingScreen( 'http://example.com/upload', undefined, undefined, 'POST', undefined, 'video', {'userId': '123', 'testId': 'test-456'} ); // Complete workflow await driver.macosStartRecordingScreen(0, 60); // ... run test ... const video = await driver.macosStopRecordingScreen(); // Save or upload video ``` -------------------------------- ### Manage Concurrent Recording Sessions Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/errors.md Stop an active recording before starting a new one, or use the force restart option to override existing sessions. ```typescript // Stop current recording await driver.macosStopRecordingScreen(); // Then start new one await driver.macosStartRecordingScreen(0); // Or force restart await driver.macosStartRecordingScreen(0, undefined, undefined, undefined, undefined, undefined, undefined, true); ``` -------------------------------- ### macosStartRecordingScreen Method Signature Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/screen-recording.md Defines the parameters for initiating a screen recording session. ```typescript async macosStartRecordingScreen( deviceId: string | number, timeLimit?: string | number, videoFilter?: string, fps?: string | number, preset?: Preset, captureCursor?: boolean, captureClicks?: boolean, forceRestart?: boolean ): Promise ``` -------------------------------- ### macosSource() Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/other-commands.md Retrieves the application source in either XML or description format. ```APIDOC ## macosSource() ### Description Get the page/app source in XML or description format. ### Parameters - **format** (string) - Optional - Source format (xml or description). Defaults to 'xml'. ### Returns - **Promise** - Application source in requested format. ### Example ```typescript // Get XML source (default) const xmlSource = await driver.macosSource(); // Get description format const descSource = await driver.macosSource('description'); ``` ``` -------------------------------- ### Initialize Mac2Driver Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/mac2-driver.md Create a new instance of the Mac2Driver. ```typescript import {Mac2Driver} from 'appium-mac2-driver'; const driver = new Mac2Driver(); ``` -------------------------------- ### macosLaunchApp Method Definition Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/app-management.md Defines the signature for launching or activating a macOS application. ```typescript async macosLaunchApp( bundleId?: string, path?: string, args?: string[], environment?: StringRecord ): Promise ``` -------------------------------- ### Drag & Drop Gesture W3C Action Source: https://github.com/appium/appium-mac2-driver/blob/master/docs/guides/w3c-action-recipes.md Moves the pointer to a start position, holds the button, and moves to an end position. The duration of the second pointerMove determines drag velocity. ```json [ {"type": "pointerMove", "duration": 10, "x": 100, "y": 100}, {"type": "pointerDown", "button": 0}, {"type": "pause", "duration": 600}, {"type": "pointerMove", "duration": 10, "x": 200, "y": 200}, {"type": "pointerUp", "button": 0} ] ``` -------------------------------- ### Configure Initial Deeplink Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/configuration.md Specify a URL to open upon application launch, supported in Xcode 14.3 and later. ```json { "appium:initialDeeplinkUrl": "myapp://data/123" } ``` -------------------------------- ### macos: activateApp Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/endpoints.md Activate an existing application. ```APIDOC ## macos: activateApp ### Description Activate an application. ### Method execute('macos: activateApp', params) ### Parameters - **bundleId** (string) - Optional - Bundle identifier - **path** (string) - Optional - Full path to app bundle *Note: Either bundleId or path is required.* ``` -------------------------------- ### macosDeepLink() Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/other-commands.md Opens a URL using the default application or a specified application bundle ID. ```APIDOC ## macosDeepLink(url, bundleId) ### Description Opens a URL with the default or specified application. Requires Xcode 14.3+. ### Parameters - **url** (string) - Required - URL to open - **bundleId** (string) - Optional - Bundle ID of app to open URL with ### Returns - **Promise** - Result from WDA ### Example ```typescript await driver.macosDeepLink('https://example.com'); await driver.macosDeepLink('myapp://data/123', 'com.example.MyApp'); ``` ``` -------------------------------- ### onSettingsUpdate(key, value) Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/api-reference/mac2-driver.md Updates a specific driver setting and propagates the change to the underlying WebDriverAgentMac instance. ```APIDOC ## onSettingsUpdate(key, value) ### Description Handles changes to driver settings and propagates them to WebDriverAgentMac. ### Method async onSettingsUpdate(key: string, value: unknown): Promise ### Parameters - **key** (string) - Required - Setting key name - **value** (unknown) - Required - New setting value ### Example ```typescript await driver.onSettingsUpdate('mjpegServerFramerate', 30); ``` ``` -------------------------------- ### Configure Server Startup Timeout Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/errors.md Increases the default server startup timeout to accommodate slower initialization processes. ```typescript const caps = { 'appium:serverStartupTimeout': 180000 // 3 minutes }; ``` -------------------------------- ### Retrieve Application Source Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/README.md Execute a command to fetch the current application source in XML format. ```typescript const source = await driver.execute('macos: source', {format: 'xml'}); console.log(source); ``` -------------------------------- ### Manage application lifecycle Source: https://github.com/appium/appium-mac2-driver/blob/master/_autodocs/README.md Provides commands to launch, query, activate, and terminate macOS applications. ```typescript // Launch await driver.macosLaunchApp('com.example.App', undefined, ['--debug']); // Query state const state = await driver.macosQueryAppState('com.example.App'); // Activate await driver.macosActivateApp('com.example.App'); // Terminate const wasRunning = await driver.macosTerminateApp('com.example.App'); ```