Execution API
The core execution API provides the fundamental interface for executing commands across all environments with a consistent, powerful syntax.
Overview
The Execution API (packages/core/src/core/execution-engine.ts
) provides:
- Template literal syntax for natural command execution
- Method chaining for composable operations
- Environment switching between adapters
- Configuration merging with defaults
- Event emission for monitoring
- Result handling with type safety
Core API
Template Literal Execution
import { $ } from '@xec-sh/core';
// Basic execution
const result = await $`ls -la`;
console.log(result.stdout);
// With variables
const file = 'document.txt';
await $`cat ${file}`;
// Multi-line commands
await $`
cd /app
npm install
npm run build
`;
ExecutionEngine Class
import { ExecutionEngine } from '@xec-sh/core';
// Create custom instance
const engine = new ExecutionEngine({
shell: '/bin/zsh',
cwd: '/home/user',
env: {
NODE_ENV: 'production'
}
});
// Use instance
await engine`command`;
Adapter Selection
// Local execution (default)
await $`local-command`;
await $.local`explicit-local`;
// SSH execution
await $.ssh({ host: 'server', username: 'user' })`remote-command`;
// Docker execution
await $.docker({ container: 'app' })`container-command`;
// Kubernetes execution
await $.k8s({ pod: 'worker', namespace: 'default' })`pod-command`;
Command Building
String Interpolation
// Safe interpolation
const userInput = "'; rm -rf /";
await $`echo ${userInput}`; // Automatically escaped
// Array expansion
const files = ['file1.txt', 'file2.txt', 'file3.txt'];
await $`cat ${files}`; // Expands to: cat file1.txt file2.txt file3.txt
// Object interpolation
const options = { verbose: true, recursive: true };
await $`rsync ${options} source/ dest/`; // Converts to flags
Command Options
// Configure execution options
const result = await $`command`.options({
timeout: 5000,
maxBuffer: 10 * 1024 * 1024, // 10MB
encoding: 'utf8',
shell: '/bin/bash',
env: { CUSTOM_VAR: 'value' }
});
Environment Configuration
Working Directory
// Change working directory
await $`pwd`.cwd('/tmp'); // Outputs: /tmp
// Chain with cd()
const project = $.cd('/project');
await project`npm install`;
await project`npm test`;
// Temporary directory change
await $.within('/tmp', async () => {
await $`create-temp-files`;
}); // Returns to original directory
Environment Variables
// Set environment variables
await $`node script.js`.env({
NODE_ENV: 'production',
API_KEY: 'secret'
});
// Merge with existing
const production = $.env({ NODE_ENV: 'production' });
await production`npm start`;
// Clear environment
await $`printenv`.env({}, { replace: true }); // Empty environment
Shell Configuration
// Use specific shell
await $`echo $0`.shell('/bin/zsh');
// Disable shell (direct execution)
await $`ls`.shell(false);
// Custom shell with options
await $`complex-script`.shell({
path: '/bin/bash',
args: ['-e', '-o', 'pipefail']
});