### Basic Command Execution Example Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/INDEX.md Demonstrates how to execute a basic command and collect its output. ```rust use tauri_plugin_shellx::Command; async fn run_command() -> Result<(), Box> { let output = Command::new("echo") .args(["Hello, Tauri!"]) .execute() .await?; println!("Stdout: {}", output.stdout); println!("Stderr: {}", output.stderr); Ok(()) } ``` -------------------------------- ### Complete Tauri Plugin Shellx Configuration Example Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/configuration.md A full JSON configuration example for tauri-plugin-shellx, demonstrating scope definitions for commands and URL opening. ```json { "build": { "devPath": "http://localhost:5173", "frontendDist": "../dist" }, "bundle": { "externalBin": [ "my-sidecar" ] }, "plugins": { "shell": { "scope": [ { "name": "echo-all", "cmd": "echo", "args": true }, { "name": "ls-pwd", "cmd": "ls", "args": ["-la"] }, { "name": "find-txt", "cmd": "find", "args": [ "$HOME", "-name", { "validator": ".*\\.txt$" } ] }, { "name": "my-sidecar", "cmd": "my-sidecar", "args": true, "sidecar": true } ], "open": "^https?://(www\\.)?example\\.com.*" } } } ``` -------------------------------- ### Execute Command with Binary Output Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/types.md Example demonstrating how to execute a command and receive its output as a Uint8Array. ```typescript import { Command } from 'tauri-plugin-shellx-api' // Binary output const binCmd = Command.create('ls', ['-la'], { encoding: 'raw' }) const binOut = await binCmd.execute() // binOut.stdout is Uint8Array ``` -------------------------------- ### Execute Command with String Output Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/types.md Example demonstrating how to execute a command and receive its output as a string. ```typescript import { Command } from 'tauri-plugin-shellx-api' // String output (default) const strCmd = Command.create('echo', 'hello') const strOut = await strCmd.execute() // strOut.stdout is string ``` -------------------------------- ### Scope Entry: Any Arguments Allowed Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/configuration.md Example of a scope entry allowing any arguments for the specified command. ```json { "name": "any-echo", "cmd": "echo", "args": true } ``` -------------------------------- ### Spawn Process with Custom Options Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/types.md Example of creating and executing a command with custom spawn options, including working directory, environment variables, and encoding. ```typescript import { Command } from 'tauri-plugin-shellx-api' const cmd = Command.create( 'npm', ['run', 'build'], { cwd: '/path/to/project', env: { NODE_ENV: 'production', PATH: process.env.PATH || '' }, encoding: 'utf-8' } ) const result = await cmd.execute() ``` -------------------------------- ### Execute Command and Log Output Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/types.md Example of executing a command and logging its exit code, stdout, and stderr. Includes a check for successful execution. ```typescript import { Command } from 'tauri-plugin-shellx-api' const output: ChildProcess = await Command.create('ls').execute() console.log(output.code) // 0 console.log(output.stdout) // directory listing as string console.log(output.stderr) // any error output // Check success if (output.code === 0) { console.log('Command succeeded') } ``` -------------------------------- ### Run Command with Custom Environment Variables Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/USAGE_EXAMPLES.md This example demonstrates how to execute a command with a custom set of environment variables. Ensure the 'env' object is correctly formatted. ```typescript import { Command } from 'tauri-plugin-shellx-api' async function runWithCustomEnv() { const result = await Command.create('env', [], { env: { CUSTOM_VAR: 'hello', PATH: process.env.PATH || '/usr/bin:/bin', HOME: '/home/user' } }).execute() console.log('Environment:', result.stdout) } ``` -------------------------------- ### Install Tauri Plugin Shellx Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/README.md Install the npm package and Rust crate for Tauri Plugin Shellx. Ensure npm package and Rust crate versions are the same to avoid compatibility issues. ```bash npm install tauri-plugin-shellx-api cargo add tauri-plugin-shellx ``` -------------------------------- ### Process Output Streams Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/types.md Example of spawning a command and attaching listeners to its stdout and stderr streams. This allows for capturing and logging both standard output and error messages as they are produced. ```typescript import { Command } from 'tauri-plugin-shellx-api' const cmd = Command.create('tail', ['-f', '/var/log/system.log']) const child = await cmd.spawn() cmd.stdout.on('data', (line: string) => { console.log('Log:', line) }) cmd.stderr.on('data', (line: string) => { console.error('Error:', line) }) ``` -------------------------------- ### Handle Process Termination Event Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/types.md Example of how to spawn a command and listen for its termination event. This snippet demonstrates accessing the exit code and signal from the TerminatedPayload. ```typescript import { Command } from 'tauri-plugin-shellx-api' const cmd = Command.create('sleep', ['10']) const child = await cmd.spawn() cmd.on('close', (data: TerminatedPayload) => { console.log(`Process exited with code: ${data.code}`) if (data.signal !== null) { console.log(`Terminated by signal: ${data.signal}`) } }) ``` -------------------------------- ### Scope Entry: Fixed Arguments Only Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/configuration.md Example of a scope entry that only allows a specific list of arguments for the command. ```json { "name": "ls-home", "cmd": "ls", "args": ["-la", "$HOME"] } ``` -------------------------------- ### Interactive Process with Stdin/Stdout Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/child.md Example of managing an interactive process, including setting up listeners for stdout and stderr, and sending commands via stdin. This pattern is useful for shell-like interactions. ```typescript import { Command } from 'tauri-plugin-shellx-api' const cmd = Command.create('python', ['-i']) const child = await cmd.spawn() // Register output listeners cmd.stdout.on('data', (line) => { console.log('Output:', line) }) cmd.stderr.on('data', (line) => { console.error('Error:', line) }) cmd.on('close', (data) => { console.log(`Process exited with code ${data.code}`) }) // Send commands to the process await child.write('print("hello")\n') await child.write('x = 5\n') await child.write('exit()\n') ``` -------------------------------- ### Locked Mode Configuration Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/index.md Example of configuring the 'shell' plugin in tauri.conf.json for locked mode, specifying allowed commands and their arguments. ```json { "plugins": { "shell": { "scope": [ { "name": "ls", "cmd": "ls", "args": ["-la"] } ] } } } ``` -------------------------------- ### Execute Bash and Python Scripts Sequentially Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/script-utilities.md Use `executeBashScript` and `executePythonScript` to run scripts one after another. Ensure necessary setup commands are included in the bash script. ```typescript import { executeBashScript, executePythonScript } from 'tauri-plugin-shellx-api' // Run setup const bashResult = await executeBashScript(` mkdir -p /tmp/workspace cd /tmp/workspace echo "Setup complete" `) console.log(bashResult.stdout) // "Setup complete\n" // Run Python analysis const pyResult = await executePythonScript(` import os print(f"Directory contents: {os.listdir('/tmp/workspace')}") `) console.log(pyResult.stdout) ``` -------------------------------- ### Execute Platform-Specific Scripts Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/index.md This example shows how to conditionally execute scripts based on the operating system using 'likelyOnWindows', 'executePowershellScript', and 'executeBashScript'. All necessary functions must be imported from 'tauri-plugin-shellx-api'. ```typescript import { likelyOnWindows, executePowershellScript, executeBashScript } from 'tauri-plugin-shellx-api' const isWindows = await likelyOnWindows() if (isWindows) { await executePowershellScript('Get-ChildItem') } else { await executeBashScript('ls -la') } ``` -------------------------------- ### Spawn a Child Process with Event Handling Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/command.md Use `spawn()` to start a command as a child process. It returns a handle for managing the process and allows real-time streaming of stdout/stderr via event emitters. This is useful for long-running processes or when interactive output is needed. ```typescript import { Command } from 'tauri-plugin-shellx-api' const cmd = Command.create('ffmpeg', [ '-i', '/input.mp4', '/output.mp4' ]) cmd.on('close', (data) => { console.log(`process finished with code ${data.code}`) }) cmd.on('error', (error) => console.error(`error: ${error}`)) cmd.stdout.on('data', (line) => console.log(`stdout: ${line}`)) cmd.stderr.on('data', (line) => console.log(`stderr: ${line}`)) const child = await cmd.spawn() console.log('pid:', child.pid) // Can kill the process later await child.kill() ``` -------------------------------- ### hasCommand(command: string) Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/utilities.md Checks if a specified command is available in the system's PATH. It uses appropriate system commands (`which` or `Get-Command`) based on the operating system. This is useful for verifying if necessary tools are installed and accessible. ```APIDOC ## Function: hasCommand(command: string) ### Description Determines if a command is available in the system PATH. Uses `which` on Unix-like systems and `Get-Command` on Windows. ### Parameters #### Path Parameters - **command** (`string`) - Required - The command name to check (e.g., 'python', 'git', 'docker') ### Return Type `Promise` - `true` if the command exists and is in PATH, `false` otherwise. ### Implementation - Calls `whereIsCommand()` internally - Returns `true` if the result is a non-empty string - Returns `false` if not found or command fails ### Example ```typescript import { hasCommand } from 'tauri-plugin-shellx-api' const hasPython = await hasCommand('python') const hasGit = await hasCommand('git') const hasDocker = await hasCommand('docker') if (!hasPython) { console.log('Python is not installed') } else { console.log('Python found') } // Check multiple commands const tools = ['git', 'gcc', 'make'] const available = await Promise.all( tools.map(t => hasCommand(t)) ) console.log('Available tools:', tools.filter((_, i) => available[i])) ``` ``` -------------------------------- ### Command Creation and Execution Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/README.md Demonstrates how to create a new command instance, spawn it, and execute it to completion. It also shows how to handle standard output and standard error streams. ```APIDOC ## Command Creation and Execution ### Description This section details how to create and execute commands using the `Command` class. You can spawn a command and wait for its completion, or stream its output. ### Static Methods #### `Command.create(program: string, args?: string[], options?: SpawnOptions): Command` Creates a new `Command` instance. #### `Command.sidecar(program: string, args?: string[], options?: SpawnOptions): Command` Creates a new `Command` instance for a sidecar. ### Instance Methods #### `spawn(): Promise` Spawns the command and returns a `Child` object for managing the process. #### `execute(): Promise>` Executes the command and returns a `ChildProcess` object containing the final output and exit status. ### Example Usage ```typescript import { Command } from 'tauri-plugin-shellx'; // Example using execute async function runCommand() { try { const command = Command.create('echo', ['hello world'], { encoding: 'utf-8' }); const output = await command.execute(); console.log('STDOUT:', output.stdout); console.log('STDERR:', output.stderr); console.log('Exit Code:', output.code); } catch (error) { console.error('Command execution failed:', error); } } runCommand(); // Example using spawn and event listeners async function streamCommand() { try { const command = Command.create('sleep', ['5']); const child = await command.spawn(); command.on('close', (payload) => { console.log(`Command closed with code: ${payload.code}, signal: ${payload.signal}`); }); command.stdout.on('data', (data) => { console.log('STDOUT:', data); }); command.stderr.on('data', (data) => { console.error('STDERR:', data); }); // To kill the process later: // await child.kill(); } catch (error) { console.error('Command spawning failed:', error); } } streamCommand(); ``` ``` -------------------------------- ### Basic Command Execution Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/index.md Demonstrates how to create and execute a simple shell command and retrieve its output. ```APIDOC ## Command Creation & Execution ### Description Create and run shell commands. ### Method `Command.create(command: string, args?: string[]): Command` ### Usage ```typescript import { Command } from 'tauri-plugin-shellx-api' const output = await Command.create('echo', ['Hello, World!']).execute() console.log(output.stdout) ``` ### Response #### Success Response - **stdout** (string) - The standard output of the command. - **stderr** (string) - The standard error of the command. - **code** (number) - The exit code of the command. ``` -------------------------------- ### Scope Entry: Validated Arguments with Regex Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/configuration.md Example of a scope entry using regex validators to control allowed arguments for a command. ```json { "name": "grep-files", "cmd": "grep", "args": [ { "validator": "[a-zA-Z0-9]+" }, { "validator": ".*\\.txt$" } ] } ``` -------------------------------- ### Executing a Bash Script Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/INDEX.md Demonstrates creating and executing a bash script. ```rust use tauri_plugin_shellx::script_utilities::{make_bash_script, execute_bash_script}; async fn run_bash_script() -> Result<(), Box> { let script_content = "echo \"Hello from Bash!\"; exit 0"; let script = make_bash_script(script_content)?; let output = execute_bash_script(&script).await?; println!("Bash script output: {}", output.stdout); Ok(()) } ``` -------------------------------- ### Type-Safe Command Creation Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/types.md Demonstrates how to create commands with type safety for string or binary output, and how to apply custom spawn options. ```typescript import { Command } from 'tauri-plugin-shellx-api' import type { SpawnOptions, ChildProcess } from 'tauri-plugin-shellx-api' // String output (default) const strCmd: Command = Command.create('echo', 'hello') const strResult: ChildProcess = await strCmd.execute() // Binary output const binCmd: Command = Command.create('ls', [], { encoding: 'raw' }) const binResult: ChildProcess = await binCmd.execute() // Custom options const opts: SpawnOptions = { cwd: '/tmp', env: { USER: 'test', HOME: '/home/test' } } const cmd = Command.create('pwd', [], opts) ``` -------------------------------- ### Executing a Node.js Script Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/INDEX.md Demonstrates creating and executing a Node.js script. ```rust use tauri_plugin_shellx::script_utilities::{make_node_script, execute_node_script}; async fn run_node_script() -> Result<(), Box> { let script_content = "console.log('Hello from Node.js!');"; let script = make_node_script(script_content)?; let output = execute_node_script(&script).await?; println!("Node.js script output: {}", output.stdout); Ok(()) } ``` -------------------------------- ### Executing a Python Script Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/INDEX.md Demonstrates creating and executing a Python script. ```rust use tauri_plugin_shellx::script_utilities::{make_python_script, execute_python_script}; async fn run_python_script() -> Result<(), Box> { let script_content = "print('Hello from Python!')"; let script = make_python_script(script_content)?; let output = execute_python_script(&script).await?; println!("Python script output: {}", output.stdout); Ok(()) } ``` -------------------------------- ### Rust Backend - Plugin Initialization Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/architecture.md Initializes the shellx plugin. The `init` function configures the permission mode (unlocked or restricted), registers command handlers for IPC communication, and sets up the child process store. ```rust pub fn init(unlocked: bool) -> Result, Error> // Configure permission mode // Register command handlers // Set up child process store ``` -------------------------------- ### Invalid Regex in Validator Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/configuration.md An example of an invalid regex pattern within a validator configuration. This will cause the plugin to fail initialization with a regex parse error. ```json { "args": [ { "validator": "[invalid(regex" } ] } ``` -------------------------------- ### fixPathEnv() Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/utilities.md Attempts to fix the PATH environment variable, which is useful when commands installed via package managers are not found by the Tauri app. The fix is platform-specific. ```APIDOC ## Function: fixPathEnv() ### Description Attempts to fix the PATH environment variable. This is useful when commands that are installed (e.g., ffmpeg) cannot be found despite being in the system PATH. The exact fix behavior is platform-specific. ### Return Type `Promise` - Resolves when the operation completes. ### Use Cases - After installing a command, PATH isn't immediately updated - Command works in terminal but not in Tauri app - Command located at non-standard paths ### Example ```typescript import { Command, fixPathEnv, hasCommand } from 'tauri-plugin-shellx-api' // Check if ffmpeg is available if (!(await hasCommand('ffmpeg'))) { // Try to fix PATH await fixPathEnv() // Verify if it's now available if (await hasCommand('ffmpeg')) { console.log('ffmpeg is now available') } } // Or just attempt the command directly try { const result = await Command.create('ffmpeg', ['-version']).execute() console.log(result.stdout) } catch (e) { console.log('ffmpeg not found, trying to fix PATH') await fixPathEnv() // Retry the command const result = await Command.create('ffmpeg', ['-version']).execute() console.log(result.stdout) } ``` ``` -------------------------------- ### Spawn and Manage a Shell Command Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/event-emitter.md This snippet demonstrates how to create a command, spawn it as a child process, and register event listeners for stdout, stderr, and the close event. It also shows how to check and remove listeners. ```typescript import { Command } from 'tauri-plugin-shellx-api' const cmd = Command.create('npm', ['run', 'build']) const child = await cmd.spawn() const onClose = (data) => { console.log('Build complete') } // Register listeners cmd.stdout.on('data', (line) => console.log('[OUT]', line)) cmd.stderr.on('data', (line) => console.error('[ERR]', line)) cmd.once('close', onClose) cmd.on('error', (err) => console.error('[ERROR]', err)) // Check listener count console.log(`Close listeners: ${cmd.listenerCount('close')}`) // Remove specific listener later cmd.off('close', onClose) ``` -------------------------------- ### Execute a Command and Get Result Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/README.md Execute a command and wait for its completion, then access its standard output and exit code. A zero exit code indicates success. ```typescript const result = await Command.create('ls', ['-la']).execute() console.log(result.stdout) console.log(result.code) // 0 = success ``` -------------------------------- ### Command.create() Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/command.md Creates a command to execute a specified program. The program must be configured in `tauri.conf.json`. It supports custom arguments and spawn options, including encoding for raw binary output. ```APIDOC ## Command.create() ### Description Creates a command to execute the given program. ### Method `static create(program: string, args?: string | string[], options?: SpawnOptions): Command` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters * **program** (string) - Required - The program to execute (must be configured in tauri.conf.json) * **args** (string | string[]) - Optional - Program arguments * **options** (SpawnOptions) - Optional - Spawn options; if `encoding: 'raw'` is set, returns `Command` ### Return Type `Command` or `Command` depending on encoding option. ### Request Example ```typescript import { Command } from 'tauri-plugin-shellx-api' // Execute echo command const cmd = Command.create('echo', ['Hello, World!']) const output = await cmd.execute() console.log(output.stdout) // 'Hello, World!' // Execute with raw binary output const binary = Command.create('ls', ['-la'], { encoding: 'raw' }) ``` ``` -------------------------------- ### Streaming Process Output Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/index.md Shows how to spawn a command and listen for its standard output in real-time, as well as handling process closure events. ```APIDOC ## Child Process Management & Event Handling ### Description Manage spawned processes and listen to process events like data streams and closure. ### Method `cmd.spawn(): Promise ` `cmd.stdout.on('data', (line) => { ... }) cmd.on('close', (data) => { ... }) ` ### Usage ```typescript import { Command } from 'tauri-plugin-shellx-api' const cmd = Command.create('ls', ['-la']) const child = await cmd.spawn() cmd.stdout.on('data', (line) => { console.log('Output:', line) }) cmd.on('close', (data) => { console.log('Process exited with code:', data.code) }) ``` ### Response #### Success Response (spawn) - **ChildProcess** - An object representing the spawned child process. #### Event Data (on 'data') - **line** (string) - A chunk of data from the standard output. #### Event Data (on 'close') - **code** (number) - The exit code of the process. ``` -------------------------------- ### Create a Command Instance Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/index.md Use Command.create() to instantiate a Command object for executing shell commands. This is the primary method for setting up a command before execution. ```typescript Command.create() ``` -------------------------------- ### Open Files and URLs with System Defaults or Specific Applications Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/USAGE_EXAMPLES.md Use the `open` function to launch files or URLs. You can specify a browser or protocol for opening. This is useful for integrating with the user's system to open external resources. ```typescript import { open } from 'tauri-plugin-shellx-api' async function openResources() { // Open with system default await open('https://github.com/huakunshen/tauri-plugin-shellx') // Open file with default program await open('/path/to/document.pdf') // Open with specific browser await open('https://example.com', 'firefox') // Send email await open('mailto:user@example.com') // Make phone call (if supported) await open('tel:+1234567890') } ``` -------------------------------- ### Check if Command Exists in PATH Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/utilities.md Determines if a command is available in the system PATH using 'which' on Unix-like systems and 'Get-Command' on Windows. Useful for checking if necessary tools are installed. ```typescript import { hasCommand } from 'tauri-plugin-shellx-api' const hasPython = await hasCommand('python') const hasGit = await hasCommand('git') const hasDocker = await hasCommand('docker') if (!hasPython) { console.log('Python is not installed') } else { console.log('Python found') } // Check multiple commands const tools = ['git', 'gcc', 'make'] const available = await Promise.all( tools.map(t => hasCommand(t)) ) console.log('Available tools:', tools.filter((_, i) => available[i])) ``` -------------------------------- ### open() Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/utilities.md Opens a path or URL with the system's default application, or a specific application if provided. The path is validated against a regex pattern defined in tauri.conf.json. ```APIDOC ## Function: open() ### Description Opens a path or URL with the system's default application, or a specific application if provided. ### Parameters #### Path Parameters - **path** (string) - Required - The path or URL to open - **openWith** (string) - Optional - The application to use for opening. Defaults to the system default. ### Valid openWith Values - `'open'` - Default opener (macOS) - `'start'` - Default opener (Windows) - `'xdg-open'` - Default opener (Linux) - `'gio'` - GNOME opener - `'gnome-open'` - GNOME opener (legacy) - `'kde-open'` - KDE opener - `'firefox'` - Firefox browser - `'google chrome'` or `'chrome'` - Google Chrome - `'chromium'` - Chromium browser - `'safari'` - Safari browser (macOS) - `'wslview'` - WSL opener ### Path Validation The path is validated against a regex pattern defined in `tauri.conf.json > plugins > shell > open`. ### Return Type `Promise` - Resolves when the file/URL is opened. ### Example ```typescript import { open } from 'tauri-plugin-shellx-api' // Open with system default await open('https://github.com/huakunshen/tauri-plugin-shellx') // Open a file with default program await open('/path/to/document.pdf') // Open with specific browser await open('https://example.com', 'firefox') // Open mailto link await open('mailto:contact@example.com') // Open URL with Chrome await open('https://example.com', 'google chrome') // Platform-specific opener if (process.platform === 'darwin') { await open('https://example.com', 'safari') } else if (process.platform === 'win32') { await open('https://example.com', 'chrome') } else { await open('https://example.com', 'firefox') } ``` ``` -------------------------------- ### Fix PATH Environment Variable Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/utilities.md Attempts to fix the PATH environment variable, which is useful when commands installed in non-standard locations are not found. This operation is platform-specific. Use this when commands work in the terminal but not within your Tauri app. ```typescript import { Command, fixPathEnv, hasCommand } from 'tauri-plugin-shellx-api' // Check if ffmpeg is available if (!(await hasCommand('ffmpeg'))) { // Try to fix PATH await fixPathEnv() // Verify if it's now available if (await hasCommand('ffmpeg')) { console.log('ffmpeg is now available') } } // Or just attempt the command directly try { const result = await Command.create('ffmpeg', ['-version']).execute() console.log(result.stdout) } catch (e) { console.log('ffmpeg not found, trying to fix PATH') await fixPathEnv() // Retry the command const result = await Command.create('ffmpeg', ['-version']).execute() console.log(result.stdout) } ``` -------------------------------- ### Handle Command Events Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/types.md Demonstrates spawning a command and setting up listeners for both 'close' and 'error' events. This allows for robust handling of command execution outcomes. ```typescript import { Command } from 'tauri-plugin-shellx-api' const cmd = Command.create('ls') const child = await cmd.spawn() cmd.on('close', (data) => console.log('Done:', data.code)) cmd.on('error', (err) => console.error('Error:', err)) ``` -------------------------------- ### Executing Scripts Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/index.md Demonstrates how to execute shell scripts directly using provided utility functions. ```APIDOC ## Script Execution ### Description Execute scripts in various languages. ### Method `executeBashScript(script: string): Promise` `executePowershellScript(script: string): Promise` ### Usage ```typescript import { executeBashScript } from 'tauri-plugin-shellx-api' const result = await executeBashScript(` echo "Hello from Bash" date `) console.log(result.stdout) ``` ### Response #### Success Response - **stdout** (string) - The standard output of the script. - **stderr** (string) - The standard error of the script. - **code** (number) - The exit code of the script. ``` -------------------------------- ### Configure Process Environment Variables Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/configuration.md Demonstrates how to clear, set specific, or inherit and add environment variables for spawned commands using the Command.create API. ```typescript import { Command } from 'tauri-plugin-shellx-api' // Clear all environment variables const cmd1 = Command.create('env', [], { env: {} // Empty record clears the environment }) // Set specific variables const cmd2 = Command.create('node', ['script.js'], { env: { NODE_ENV: 'production', API_KEY: 'secret-key', PATH: process.env.PATH || '' } }) // Inherit parent and add variables const parentEnv = process.env as Record const cmd3 = Command.create('python', ['script.py'], { env: { ...parentEnv, PYTHONDONTWRITEBYTECODE: '1' } }) ``` -------------------------------- ### Rust Backend - Process Management Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/architecture.md Manages child processes. The `Command` struct represents a shell command, with methods to `spawn`, `execute`, and check its `status`. `CommandChild` represents a running process with methods to `write` to stdin, `kill`, and get its `pid`. `CommandEvent` enum represents events emitted by child processes. ```rust struct Command { ... } impl Command { spawn() -> (Receiver, CommandChild) execute() -> Output status() -> ExitStatus } struct CommandChild { ... } impl CommandChild { write(buf: &[u8]) kill() pid() -> u32 } enum CommandEvent { Stdout(Vec), Stderr(Vec), Terminated(TerminatedPayload), Error(String), } ``` -------------------------------- ### Executing a Sidecar Command Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/INDEX.md Illustrates how to execute a command packaged as a sidecar. ```rust use tauri_plugin_shellx::Command; async fn run_sidecar() -> Result<(), Box> { let output = Command::sidecar("my-sidecar") .args(["--version"]) .execute() .await?; println!("Sidecar version: {}", output.stdout); Ok(()) } ``` -------------------------------- ### Create and Execute a Custom Command Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/architecture.md Wrap an existing command to execute it with custom arguments. This snippet demonstrates how to create a new Command instance and execute it. ```typescript async function customCommand( program: string, args: string[] ): Promise> { return Command.create(program, args).execute() } ``` -------------------------------- ### Build Project with Progress Callback Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/USAGE_EXAMPLES.md Spawns an 'npm run build' command and processes its output. It accepts an optional progress callback to handle build output lines. Rejects if the build fails. Ensure 'npm' is available. ```typescript import { Command } from 'tauri-plugin-shellx-api' async function buildProject(onProgress?: (line: string) => void) { const cmd = Command.create('npm', ['run', 'build']) const child = await cmd.spawn() let buildSuccess = false cmd.stdout.on('data', (line) => { console.log('[BUILD]', line) onProgress?.(line) }) cmd.stderr.on('data', (line) => { console.error('[BUILD ERROR]', line) }) return new Promise((resolve, reject) => { cmd.on('close', (data) => { if (data.code === 0) { resolve({ success: true, code: data.code }) } else { reject(new Error(`Build failed with code ${data.code}`)) } }) cmd.on('error', (err) => { reject(new Error(`Build error: ${err}`)) }) }) } // Usage with progress callback await buildProject((line) => { if (line.includes('Compiling')) { // Update UI with progress } }) ``` -------------------------------- ### Open Path or URL Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/index.md Use the open() utility function to open a specified path or URL using the system's default application or a configured one. This is useful for launching files or websites. ```typescript open() ``` -------------------------------- ### Streaming Command Output Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/INDEX.md Shows how to spawn a command and stream its stdout and stderr. ```rust use tauri_plugin_shellx::{Command, CommandEvent}; async fn stream_command() -> Result<(), Box> { let mut child = Command::new("ping") .args(["localhost"]) .spawn() .await?; while let Some(event) = child.next_event().await { match event { CommandEvent::Stdout(data) => println!("Stdout: {}", String::from_utf8_lossy(&data)), CommandEvent::Stderr(data) => println!("Stderr: {}", String::from_utf8_lossy(&data)), CommandEvent::Terminated(payload) => { println!("Process terminated: exit_code={:?}, signal={:?}", payload.exit_code, payload.signal); break; } _ => {} // Ignore other events like অপারেটিং_SYSTEM } } Ok(()) } ``` -------------------------------- ### makeBashScript() Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/script-utilities.md Creates a Bash script command. Equivalent to `Command.create('bash', ['-c', script])`. ```APIDOC ## Function: makeBashScript() ```typescript function makeBashScript(script: string): Command ``` ### Description Creates a Bash script command. Equivalent to `Command.create('bash', ['-c', script])`. ### Parameters #### Path Parameters - **script** (string) - Required - The Bash script code to execute ### Return Type `Command` - A Command instance ready to spawn or execute. ### Example ```typescript import { makeBashScript } from 'tauri-plugin-shellx-api' const cmd = makeBashScript(` echo "Hello from Bash" echo "Current directory: $(pwd)" `) const output = await cmd.execute() console.log(output.stdout) ``` ``` -------------------------------- ### Rust Backend - Configuration Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/architecture.md Defines the plugin's configuration structure, including allowlist settings for opening URLs. `Config` holds the overall configuration, and `ShellAllowlistOpen` specifies allowed URL patterns. ```rust struct Config { ... } enum ShellAllowlistOpen { ... } ``` -------------------------------- ### Opening URL with System App Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/INDEX.md Utility to open a URL using the system's default browser or handler. ```rust use tauri_plugin_shellx::utilities::open; async fn open_url() -> Result<(), Box> { open("https://tauri.app").await?; Ok(()) } ``` -------------------------------- ### Type-Safe Command Creation Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/index.md Demonstrates how to create a command with type-safe options and execute it. Ensure you import the necessary types from 'tauri-plugin-shellx-api'. ```typescript import type { Command, Child, SpawnOptions, ChildProcess, TerminatedPayload } from 'tauri-plugin-shellx-api' // Type-safe command creation const opts: SpawnOptions = { cwd: '/home/user', env: { HOME: '/home/user' }, encoding: 'utf-8' } const cmd: Command = Command.create('ls', ['-la'], opts) const result: ChildProcess = await cmd.execute() ``` -------------------------------- ### Create Command with Raw Binary Output Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/command.md When raw binary output is needed, specify `{ encoding: 'raw' }` in the options for `Command.create`. This returns a `Command`. ```typescript import { Command } from 'tauri-plugin-shellx-api' // Execute echo command const cmd = Command.create('echo', ['Hello, World!']) const output = await cmd.execute() console.log(output.stdout) // 'Hello, World!' // Execute with raw binary output const binary = Command.create('ls', ['-la'], { encoding: 'raw' }) ``` -------------------------------- ### Open URLs with System Default or Specific Browser Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/index.md Use the 'open' function to launch a URL. You can let the system choose the default browser or specify a particular browser. Import 'open' from 'tauri-plugin-shellx-api'. ```typescript import { open } from 'tauri-plugin-shellx-api' // Open with system default await open('https://example.com') // Open with specific browser await open('https://example.com', 'firefox') ``` -------------------------------- ### Execute a Simple Command Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/index.md Use this snippet to create and execute a basic shell command and capture its standard output. Ensure the 'tauri-plugin-shellx-api' is imported. ```typescript import { Command } from 'tauri-plugin-shellx-api' // Execute a simple command const output = await Command.create('echo', ['Hello, World!']).execute() console.log(output.stdout) // 'Hello, World!' ``` -------------------------------- ### executeBashScript() Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/script-utilities.md Creates and immediately executes a Bash script, returning the complete output including exit code, signal, stdout, and stderr. ```APIDOC ## executeBashScript() ### Description Creates and immediately executes a Bash script, returning the complete output. ### Method `async` ### Parameters #### Path Parameters - **script** (string) - Required - The Bash script code to execute ### Return Type `Promise>` - The exit code, signal, stdout, and stderr. ### Request Example ```typescript import { executeBashScript } from 'tauri-plugin-shellx-api' const result = await executeBashScript(` for i in {1..3}; do echo "Count: $i" done `) console.log(result.code) // 0 console.log(result.stdout) // "Count: 1\nCount: 2\nCount: 3\n" ``` ``` -------------------------------- ### Execute Shell Command with Tauri Plugin Shellx Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/README.md Use the `Command.create` and `execute` methods to run a shell command and retrieve its standard output. This is suitable for commands that complete quickly. ```typescript const cmd = Command.create('echo', ['echo', 'Hello, World!']) const out = await cmd.execute() const stdout = out.stdout // stdout === 'Hello, World!' ``` -------------------------------- ### Command Event Handling Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/index.md Shows how to spawn a command and listen for its events, including process close/error events and stdout/stderr data. Import Command from 'tauri-plugin-shellx-api'. ```typescript import { Command } from 'tauri-plugin-shellx-api' const cmd = Command.create('npm', ['run', 'build']) const child = await cmd.spawn() // Process events cmd.on('close', (data) => console.log('Closed:', data)) cmd.on('error', (err) => console.error('Error:', err)) // Output events cmd.stdout.on('data', (line) => console.log('Out:', line)) cmd.stderr.on('data', (line) => console.error('Err:', line)) ``` -------------------------------- ### Frontend API - Utilities Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/architecture.md Provides utility functions for interacting with the shell and operating system. `open` launches a file or URL with a specified application. `fixPathEnv` ensures the PATH environment variable is correctly configured. `killPid` terminates a process by its PID. `likelyOnWindows` checks if the current OS is Windows. `hasCommand` checks for the existence of a command. ```typescript open(path: string, app?: string): Promise fixPathEnv(): Promise killPid(pid: number): Promise likelyOnWindows(): Promise hasCommand(cmd: string): Promise ``` -------------------------------- ### spawn() Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/command.md Spawns a command as a child process, providing a handle to manage it and enabling real-time streaming of stdout/stderr through event emitters. This method is non-blocking. ```APIDOC ## spawn() ### Description Spawns the command as a child process and returns a handle to manage it. Allows real-time streaming of stdout/stderr through event emitters. ### Method ```typescript async spawn(): Promise ``` ### Return Type `Promise` - A promise that resolves to a Child process handle. ### Throws - On spawn failure or if the program is not allowed by the scope ### Example ```typescript import { Command } from 'tauri-plugin-shellx-api' const cmd = Command.create('ffmpeg', [ '-i', '/input.mp4', '/output.mp4' ]) cmd.on('close', (data) => { console.log(`process finished with code ${data.code}`) }) cmd.on('error', (error) => console.error(`error: ${error}`)) cmd.stdout.on('data', (line) => console.log(`stdout: ${line}`)) cmd.stderr.on('data', (line) => console.log(`stderr: ${line}`)) const child = await cmd.spawn() console.log('pid:', child.pid) // Can kill the process later await child.kill() ``` ``` -------------------------------- ### makeAppleScript() Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/script-utilities.md Creates an AppleScript command. Equivalent to `Command.create('osascript', ['-e', script])`. Macros only available on macOS. ```APIDOC ## Function: makeAppleScript() ```typescript function makeAppleScript(script: string): Command ``` ### Description Creates an AppleScript command. Equivalent to `Command.create('osascript', ['-e', script])`. Macros only available on macOS. ### Parameters #### Path Parameters - **script** (string) - Required - The AppleScript code to execute ### Return Type `Command` - A Command instance ready to spawn or execute. ### Example ```typescript import { makeAppleScript } from 'tauri-plugin-shellx-api' const cmd = makeAppleScript(` tell application "Finder" activate end tell `) const output = await cmd.execute() ``` ``` -------------------------------- ### Command Execution Flow Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/architecture.md Illustrates the sequence of operations when executing a command, from TypeScript initiation to Rust handling and result deserialization. ```typescript Command.create('ls', ['-la']).execute() ``` ```typescript invoke('plugin:shellx|execute', { program: 'ls', args: ['-la'], options: { cwd: '...', env: {...} } }) ``` ```rust // Rust Handler (commands.rs::execute) // - Check permission mode (unlocked vs locked) // - If locked: validate scope (scope.rs::prepare) // - Create std::process::Command // - Execute and collect output ``` ```json { code: 0, signal: null, stdout: "...", stderr: "" } ``` ```typescript // TypeScript // Deserialize into ChildProcess ``` -------------------------------- ### SpawnOptions Interface Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/types.md The SpawnOptions interface defines the configuration options for spawning a new process. It allows specifying the current working directory, environment variables, and the character encoding for standard output and error streams. ```APIDOC ## SpawnOptions ### Description Options for spawning a process, including working directory, environment variables, and character encoding. ### Properties | Property | Type | Required | Default | Description | |----------|------|----------|---------|-------------| | `cwd` | `string` | No | current directory | Working directory for the process | | `env` | `Record` | No | inherit parent | Environment variables; if set, the parent's env is not inherited | | `encoding` | `string` | No | system default | Character encoding for stdout/stderr ('utf-8', 'latin1', 'raw', etc.) | ### Example ```typescript import { Command } from 'tauri-plugin-shellx-api' const cmd = Command.create( 'npm', ['run', 'build'], { cwd: '/path/to/project', env: { NODE_ENV: 'production', PATH: process.env.PATH || '' }, encoding: 'utf-8' } ) const result = await cmd.execute() ``` ``` -------------------------------- ### executeAppleScript() Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/script-utilities.md Creates and immediately executes an AppleScript, returning the complete output. macOS only. ```APIDOC ## executeAppleScript() ### Description Creates and immediately executes an AppleScript, returning the complete output. macOS only. ### Method `async` ### Parameters #### Path Parameters - **script** (string) - Required - The AppleScript code to execute ### Return Type `Promise>` - The exit code, signal, stdout, and stderr. ### Request Example ```typescript import { executeAppleScript } from 'tauri-plugin-shellx-api' const result = await executeAppleScript(` tell application "System Events" return user name of current user end tell `) console.log(result.stdout) ``` ``` -------------------------------- ### Execute a Sidecar Command Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/configuration.md Shows how to execute a bundled sidecar binary with specified arguments using the Command.sidecar API. ```typescript import { Command } from 'tauri-plugin-shellx-api' const result = await Command.sidecar('my-tool', ['arg1', 'arg2']).execute() ``` -------------------------------- ### executeZshScript() Source: https://github.com/huakunshen/tauri-plugin-shellx/blob/main/_autodocs/api-reference/script-utilities.md Creates and immediately executes a Zsh script, returning the complete output. ```APIDOC ## executeZshScript() ### Description Creates and immediately executes a Zsh script, returning the complete output. ### Method `async` ### Parameters #### Path Parameters - **script** (string) - Required - The Zsh script code to execute ### Return Type `Promise>` - The exit code, signal, stdout, and stderr. ### Request Example ```typescript import { executeZshScript } from 'tauri-plugin-shellx-api' const result = await executeZshScript(` echo "Zsh version: $ZSH_VERSION" `) console.log(result.stdout) ``` ```