### Create Detachable Sessions Source: https://context7.com/superfly/sprites-js/llms.txt Create detachable sessions using `createSession` that persist even after disconnection. The example shows how to start a session, send commands, disconnect, list active sessions, and re-attach to an existing one. ```typescript import { SpritesClient } from '@fly/sprites'; const client = new SpritesClient(process.env.SPRITES_TOKEN!); const sprite = client.sprite('my-sprite'); // Create a detachable session const session = sprite.createSession('bash', [], { tty: true, rows: 24, cols: 80, }); // Run some commands session.stdin.write('echo "Starting long process..." '); session.stdin.write('sleep 3600 '); // Disconnect (session keeps running) session.stdin.end(); // Later, list active sessions const sessions = await sprite.listSessions(); for (const s of sessions) { console.log(`Session ${s.id}: ${s.command} (active: ${s.isActive})`); console.log(` Created: ${s.created}`); console.log(` Last activity: ${s.lastActivity}`); console.log(` TTY: ${s.tty}`); } // Attach to an existing session const attached = sprite.attachSession(sessions[0].id, { tty: true, rows: 24, cols: 80, }); process.stdin.setRawMode(true); process.stdin.pipe(attached.stdin); attached.stdout.pipe(process.stdout); await attached.wait(); ``` -------------------------------- ### Services API: Managed Process Operations in TypeScript Source: https://context7.com/superfly/sprites-js/llms.txt Illustrates how to create and manage long-running services on a sprite using the SpritesClient. Covers service creation with dependencies and ports, streaming logs, listing, getting, stopping, starting, signaling, and deleting services. Log streaming events are processed to display output and status updates. ```typescript import { SpritesClient } from '@fly/sprites'; const client = new SpritesClient(process.env.SPRITES_TOKEN!); const sprite = client.sprite('my-sprite'); // Create a service (starts automatically) const logStream = await sprite.createService('web', { cmd: 'node', args: ['server.js'], needs: ['database'], // dependencies httpPort: 3000, // optional HTTP port for proxy routing }, '10s'); // optional: stream logs for 10 seconds // Process startup logs for await (const event of logStream) { switch (event.type) { case 'stdout': process.stdout.write(event.data || ''); break; case 'stderr': process.stderr.write(event.data || ''); break; case 'started': console.log('Service started'); break; case 'exit': console.log(`Service exited with code ${event.exitCode}`); break; case 'complete': console.log('Log files:', event.logFiles); break; } } // List all services const services = await sprite.listServices(); for (const svc of services) { console.log(`${svc.name}: ${svc.state?.status || 'unknown'}`); if (svc.state?.pid) { console.log(` PID: ${svc.state.pid}`); } } // Get a specific service const webService = await sprite.getService('web'); console.log(`Status: ${webService.state?.status}`); console.log(`Restart count: ${webService.state?.restartCount}`); // Stop a service const stopStream = await sprite.stopService('web', '10s'); // optional timeout await stopStream.processAll((event) => { if (event.type === 'stopped') { console.log('Service stopped'); } }); // Start a stopped service const startStream = await sprite.startService('web', '5s'); await startStream.processAll((event) => { console.log(`[${event.type}] ${event.data || ''}`); }); // Send signal to a service await sprite.signalService('web', 'HUP'); // reload config await sprite.signalService('web', 'TERM'); // graceful shutdown // Delete a service await sprite.deleteService('web'); ``` -------------------------------- ### Spawn Interactive TTY Sessions Source: https://context7.com/superfly/sprites-js/llms.txt Enable TTY mode for interactive terminal sessions using `spawn`. This allows for proper terminal emulation and resizing support. The example demonstrates connecting local stdin/stdout to the remote process and handling terminal resize events. ```typescript import { SpritesClient } from '@fly/sprites'; const client = new SpritesClient(process.env.SPRITES_TOKEN!); const sprite = client.sprite('my-sprite'); // Start an interactive bash session const cmd = sprite.spawn('bash', [], { tty: true, rows: 24, cols: 80, }); // Connect local terminal to remote process.stdin.setRawMode(true); process.stdin.pipe(cmd.stdin); cmd.stdout.pipe(process.stdout); // Handle terminal resize process.stdout.on('resize', () => { cmd.resize(process.stdout.columns, process.stdout.rows); }); // Clean up on exit cmd.on('exit', (code) => { process.stdin.setRawMode(false); console.log(`\nSession ended with code ${code}`); process.exit(code); }); ``` -------------------------------- ### Handle Port Notifications Source: https://context7.com/superfly/sprites-js/llms.txt Listen for port notifications when processes open network ports on the sprite using the `message` event. The example demonstrates how to react to `port_opened` and `port_closed` events, which can be used to set up local proxies or open browsers. ```typescript import { SpritesClient } from '@fly/sprites'; const client = new SpritesClient(process.env.SPRITES_TOKEN!); const sprite = client.sprite('my-sprite'); // Start a web server const cmd = sprite.spawn('python', ['-m', 'http.server', '8080']); // Listen for port events cmd.on('message', (msg) => { if (msg.type === 'port_opened') { console.log(`Port ${msg.port} opened by PID ${msg.pid} on ${msg.address}`); // Start local proxy, open browser, etc. } else if (msg.type === 'port_closed') { console.log(`Port ${msg.port} closed`); } }); cmd.stdout.on('data', (chunk) => process.stdout.write(chunk)); cmd.stderr.on('data', (chunk) => process.stderr.write(chunk)); await cmd.wait(); ``` -------------------------------- ### Manage Sprite Checkpoints with Sprites.js Source: https://context7.com/superfly/sprites-js/llms.txt This snippet illustrates how to create, list, get details of, and restore sprite checkpoints using Sprites.js. It shows handling checkpoint creation progress streams and processing messages. ```typescript import { SpritesClient } from '@fly/sprites'; const client = new SpritesClient(process.env.SPRITES_TOKEN!); const sprite = client.sprite('my-sprite'); // Create a checkpoint with streaming progress const checkpointStream = await sprite.createCheckpoint('Before deployment'); // Process checkpoint progress messages for await (const msg of checkpointStream) { if (msg.type === 'info') { console.log('Info:', msg.data); } else if (msg.type === 'stdout') { process.stdout.write(msg.data || ''); } else if (msg.type === 'stderr') { process.stderr.write(msg.data || ''); } else if (msg.type === 'error') { console.error('Error:', msg.error); } } // Or use processAll for simpler handling const stream2 = await sprite.createCheckpoint('Backup'); await stream2.processAll((msg) => { console.log(`[${msg.type}] ${msg.data || msg.error || ''}`); }); // List checkpoints const checkpoints = await sprite.listCheckpoints(); for (const cp of checkpoints) { console.log(`${cp.id}: ${cp.comment} (created: ${cp.createTime})`); } // Get checkpoint details const checkpoint = await sprite.getCheckpoint('v3'); console.log(`Checkpoint: ${checkpoint.id}`); console.log(`Comment: ${checkpoint.comment}`); console.log(`History: ${checkpoint.history?.join(', ')}`); // Restore from a checkpoint const restoreStream = await sprite.restoreCheckpoint('v3'); for await (const msg of restoreStream) { console.log(`[${msg.type}] ${msg.data || ''}`); } ``` -------------------------------- ### Initialize Sprites Client and Execute Commands Source: https://github.com/superfly/sprites-js/blob/main/README.md Demonstrates how to instantiate the SpritesClient and perform both event-based command spawning and promise-based execution. ```typescript import { SpritesClient } from '@fly/sprites'; const client = new SpritesClient(process.env.SPRITES_TOKEN!); const sprite = client.sprite('my-sprite'); // Event-based API const cmd = sprite.spawn('ls', ['-la']); cmd.stdout.on('data', (chunk) => { process.stdout.write(chunk); }); cmd.on('exit', (code) => { console.log(`Exited with code ${code}`); }); // Promise-based API const { stdout } = await sprite.exec('echo hello'); console.log(stdout); ``` -------------------------------- ### Initialize and Manage Sprites with SpritesClient Source: https://context7.com/superfly/sprites-js/llms.txt Demonstrates how to initialize the SpritesClient, create, list, and manage the lifecycle of remote sprite instances. It covers authentication, configuration, and administrative tasks like upgrading or deleting sprites. ```typescript import { SpritesClient } from '@fly/sprites'; const client = new SpritesClient(process.env.SPRITES_TOKEN!, { baseURL: 'https://api.sprites.dev', timeout: 30000, controlMode: false, }); const sprite = client.sprite('my-sprite'); const newSprite = await client.createSprite('my-new-sprite', { ramMB: 512, cpus: 1, region: 'ord', storageGB: 10, }); const existingSprite = await client.getSprite('my-sprite'); console.log(`Status: ${existingSprite.status}`); const { sprites } = await client.listSprites({ prefix: 'dev-', maxResults: 50 }); await client.deleteSprite('my-old-sprite'); await client.upgradeSprite('my-sprite'); await client.updateURLSettings('my-sprite', { auth: 'public' }); const token = await SpritesClient.createToken(flyMacaroon, 'my-org', 'optional-invite-code'); ``` -------------------------------- ### Configure Network Access Policies Source: https://context7.com/superfly/sprites-js/llms.txt Demonstrates how to retrieve and update network policies for a sprite. It shows how to define allow/deny rules, use wildcards, and implement restrictive default-deny configurations. ```typescript import { SpritesClient } from '@fly/sprites'; const client = new SpritesClient(process.env.SPRITES_TOKEN!); const sprite = client.sprite('my-sprite'); // Get current network policy const policy = await sprite.getNetworkPolicy(); console.log('Current rules:'); for (const rule of policy.rules) { if (rule.include) { console.log(` include: ${rule.include}`); } else { console.log(` ${rule.action}: ${rule.domain}`); } } // Update network policy await sprite.updateNetworkPolicy({ rules: [ { include: 'defaults' }, { domain: 'api.example.com', action: 'allow' }, { domain: 'dangerous.com', action: 'deny' }, { domain: '*.trusted.org', action: 'allow' }, ], }); // Restrictive policy - deny by default await sprite.updateNetworkPolicy({ rules: [ { domain: 'api.myservice.com', action: 'allow' }, { domain: 'registry.npmjs.org', action: 'allow' }, ], }); ``` -------------------------------- ### Execute Remote Commands with spawn Source: https://context7.com/superfly/sprites-js/llms.txt Shows how to use the spawn method to execute commands on a remote sprite. It demonstrates streaming stdout/stderr, handling process lifecycle events, piping streams, and writing to stdin. ```typescript import { SpritesClient } from '@fly/sprites'; const client = new SpritesClient(process.env.SPRITES_TOKEN!); const sprite = client.sprite('my-sprite'); const cmd = sprite.spawn('ls', ['-la', '/app']); cmd.stdout.on('data', (chunk: Buffer) => process.stdout.write(chunk)); cmd.on('exit', (code: number) => console.log(`Process exited with code ${code}`)); const cmd2 = sprite.spawn('cat', ['/etc/passwd']); cmd2.stdout.pipe(process.stdout); await cmd2.wait(); const cmd3 = sprite.spawn('cat'); cmd3.stdin.write('Hello from stdin!\n'); cmd3.stdin.end(); await cmd3.wait(); ``` -------------------------------- ### Execute Commands with Streaming and Capture Source: https://github.com/superfly/sprites-js/blob/main/README.md Shows how to pipe command output streams and capture output using the promise-based exec method. ```typescript const cmd = sprite.spawn('ls', ['-la']); cmd.stdout.pipe(process.stdout); cmd.stderr.pipe(process.stderr); await cmd.wait(); const { stdout, stderr } = await sprite.exec('ls -la'); console.log(stdout); ``` -------------------------------- ### Create Local TCP Proxies with Sprites.js Source: https://context7.com/superfly/sprites-js/llms.txt This snippet demonstrates how to create local TCP proxies that forward connections to specified ports on a sprite. It covers creating single and multiple port proxies, including optional remote host configuration. Error handling and closing proxies are also shown. ```typescript import { SpritesClient } from '@fly/sprites'; const client = new SpritesClient(process.env.SPRITES_TOKEN!); const sprite = client.sprite('my-sprite'); // Start a service on the sprite await sprite.exec('python -m http.server 8080 &'); // Create a single port proxy const proxy = await sprite.proxyPort( 3000, // local port 8080, // remote port 'localhost' // optional remote host ); console.log(`Proxy listening on ${proxy.localAddr()}`); // Now http://localhost:3000 forwards to the sprite's port 8080 // Create multiple port proxies const proxies = await sprite.proxyPorts([ { localPort: 3000, remotePort: 8080 }, { localPort: 5432, remotePort: 5432, remoteHost: 'localhost' }, { localPort: 6379, remotePort: 6379 }, ]); // Handle proxy errors proxy.on('error', (err) => { console.error('Proxy error:', err.message); }); // Close proxies when done proxy.close(); for (const p of proxies) { p.close(); } ``` -------------------------------- ### Execute Commands with exec/execFile - Promise-Based Source: https://context7.com/superfly/sprites-js/llms.txt Utilize `exec` and `execFile` for promise-based command execution. These methods capture stdout, stderr, and exit codes, returning them as strings or buffers. They support various options for controlling execution context, encoding, and buffer size. Error handling for non-zero exit codes is also demonstrated. ```typescript import { SpritesClient, ExecError } from '@fly/sprites'; const client = new SpritesClient(process.env.SPRITES_TOKEN!); const sprite = client.sprite('my-sprite'); // Execute a shell command (parsed by spaces) const { stdout, stderr, exitCode } = await sprite.exec('echo hello world'); console.log(stdout); // 'hello world\n' // Execute a file with separate arguments (safer for complex args) const result = await sprite.execFile('python', ['-c', 'print(2 + 2)']); console.log(result.stdout); // '4\n' // Execute with options const result2 = await sprite.execFile('node', ['script.js'], { cwd: '/app', // working directory env: { NODE_ENV: 'production' }, // environment variables encoding: 'utf8', // output encoding (default) maxBuffer: 10 * 1024 * 1024, // max output buffer (10MB default) }); // Get output as Buffer instead of string const result3 = await sprite.execFile('cat', ['/bin/ls'], { encoding: 'buffer' as any, }); console.log(result3.stdout instanceof Buffer); // true // Handle non-zero exit codes try { await sprite.exec('exit 1'); } catch (error) { if (error instanceof ExecError) { console.log('Exit code:', error.exitCode); // 1 console.log('Stdout:', error.stdout); console.log('Stderr:', error.stderr); } } ``` -------------------------------- ### Configure TTY Mode for Interactive Commands Source: https://github.com/superfly/sprites-js/blob/main/README.md Demonstrates how to enable TTY mode for a command, pipe standard input/output, and resize the terminal window. ```typescript const cmd = sprite.spawn('bash', [], { tty: true, rows: 24, cols: 80, }); process.stdin.pipe(cmd.stdin); cmd.stdout.pipe(process.stdout); cmd.resize(100, 30); ``` -------------------------------- ### Filesystem API: Remote File Operations in TypeScript Source: https://context7.com/superfly/sprites-js/llms.txt Demonstrates Node.js-like file operations on a sprite's filesystem using the SpritesClient. Supports reading, writing, directory manipulation, file statistics, renaming, copying, permission changes, removal, existence checks, appending, and JSON handling. Errors are caught using standard try-catch blocks. ```typescript import { SpritesClient, FilesystemError } from '@fly/sprites'; const client = new SpritesClient(process.env.SPRITES_TOKEN!); const sprite = client.sprite('my-sprite'); // Get filesystem interface with working directory const fs = sprite.filesystem('/app'); // Read files const content = await fs.readFile('config.json', 'utf8'); console.log(content); const binary = await fs.readFile('image.png'); // returns Buffer console.log(`Size: ${binary.length} bytes`); // Write files (creates parent directories automatically) await fs.writeFile('output.txt', 'Hello, world!'); await fs.writeFile('script.sh', '#!/bin/bash\necho "Hello"', { mode: 0o755 }); // Read directory contents const files = await fs.readdir('.'); console.log('Files:', files); // Read with file type information const entries = await fs.readdir('.', { withFileTypes: true }); for (const entry of entries) { const type = entry.isDirectory() ? 'DIR' : entry.isSymbolicLink() ? 'LINK' : 'FILE'; console.log(`[${type}] ${entry.name}`); } // Create directories await fs.mkdir('logs'); await fs.mkdir('deep/nested/path', { recursive: true }); // Get file statistics const stats = await fs.stat('config.json'); console.log(`Size: ${stats.size}`); console.log(`Modified: ${stats.mtime}`); console.log(`Is directory: ${stats.isDirectory()}`); // Rename files await fs.rename('old.txt', 'new.txt'); // Copy files await fs.copyFile('source.txt', 'destination.txt'); await fs.copyFile('src-dir', 'dst-dir', { recursive: true }); // Change permissions await fs.chmod('script.sh', 0o755); await fs.chmod('logs', 0o777, { recursive: true }); // Remove files/directories await fs.rm('temp.txt'); await fs.rm('old-logs', { recursive: true }); await fs.rm('maybe-exists.txt', { force: true }); // no error if missing // Check if file exists if (await fs.exists('config.json')) { console.log('Config exists'); } // Append to file await fs.appendFile('log.txt', 'New log entry\n'); // JSON helpers const config = await fs.readJSON<{ port: number }>('config.json'); console.log(`Port: ${config.port}`); await fs.writeJSON('settings.json', { theme: 'dark' }, { spaces: 2 }); // Handle filesystem errors try { await fs.readFile('nonexistent.txt', 'utf8'); } catch (error) { if ((error as any).code === 'ENOENT') { console.log('File not found'); } } ``` -------------------------------- ### Perform Sprite Lifecycle Management Source: https://github.com/superfly/sprites-js/blob/main/README.md Covers the creation, listing, and deletion of sprite instances. Configuration options like RAM and CPU allocation are defined during creation. ```typescript const sprite = await client.createSprite('my-sprite', { ramMB: 512, cpus: 1, region: 'ord', }); const sprites = await client.listAllSprites(); await sprite.delete(); ``` -------------------------------- ### Manage Detachable Sessions with Sprites Source: https://github.com/superfly/sprites-js/blob/main/README.md Demonstrates how to create, list, and attach to remote sessions using the sprite instance. These methods allow for persistent execution environments. ```typescript const session = sprite.createSession('bash'); await session.wait(); const sessions = await sprite.listSessions(); console.log(sessions); const attached = sprite.attachSession(sessions[0].id); ``` -------------------------------- ### Handle Port Notifications via Events Source: https://github.com/superfly/sprites-js/blob/main/README.md Shows how to listen for custom messages emitted by a command, such as port notifications from a running process. ```typescript const cmd = sprite.spawn('python', ['app.py']); cmd.on('message', (msg) => { if (msg.type === 'port_opened') { console.log(`Port ${msg.port} opened by PID ${msg.pid}`); } }); ``` -------------------------------- ### Sessions - Detachable Processes Source: https://context7.com/superfly/sprites-js/llms.txt Create and manage detachable sessions that persist after disconnection. Allows for creating, listing, and attaching to long-running processes. ```APIDOC ## Sessions - Detachable Processes ### Description Create detachable sessions that persist after disconnection, allowing you to reconnect later. ### Methods - `sprite.createSession(command, [args], [options])` - `sprite.listSessions()` - `sprite.attachSession(sessionId, [options])` ### Parameters #### `createSession` and `attachSession` Options - **tty** (boolean) - Enable TTY mode. - **rows** (number) - Number of rows. - **cols** (number) - Number of columns. ### Request Example ```typescript // Create a detachable session const session = sprite.createSession('bash', [], { tty: true, rows: 24, cols: 80, }); session.stdin.write('echo "Starting long process..."\n'); session.stdin.write('sleep 3600\n'); session.stdin.end(); // Disconnect // List active sessions const sessions = await sprite.listSessions(); console.log(sessions); // Attach to an existing session const attached = sprite.attachSession(sessions[0].id, { tty: true, rows: 24, cols: 80, }); process.stdin.setRawMode(true); process.stdin.pipe(attached.stdin); attached.stdout.pipe(process.stdout); await attached.wait(); ``` ### Response #### `createSession` / `attachSession` Returns an object with `stdin`, `stdout`, `stderr` streams, and `wait` method. #### `listSessions` Returns an array of session objects: - **id** (string) - Unique session ID. - **command** (string) - The command that was run. - **isActive** (boolean) - Whether the session is currently active. - **created** (string) - Timestamp of creation. - **lastActivity** (string) - Timestamp of last activity. - **tty** (boolean) - Whether TTY mode was enabled. ### Response Example (`listSessions`) ```json [ { "id": "sess_abc123", "command": "bash", "isActive": true, "created": "2023-10-27T10:00:00Z", "lastActivity": "2023-10-27T10:05:00Z", "tty": true } ] ``` ``` -------------------------------- ### POST /sprite/proxyPort Source: https://context7.com/superfly/sprites-js/llms.txt Establishes a local TCP proxy that forwards traffic to a specific port on a remote sprite. ```APIDOC ## POST /sprite/proxyPort ### Description Creates a local TCP proxy to forward connections from a local port to a remote port on the sprite. ### Method POST ### Endpoint /sprite/proxyPort ### Parameters #### Request Body - **localPort** (number) - Required - The local port to listen on. - **remotePort** (number) - Required - The target port on the sprite. - **remoteHost** (string) - Optional - The target host on the sprite (defaults to 'localhost'). ### Request Example { "localPort": 3000, "remotePort": 8080, "remoteHost": "localhost" } ### Response #### Success Response (200) - **localAddr** (string) - The address the proxy is listening on. #### Response Example { "localAddr": "127.0.0.1:3000" } ``` -------------------------------- ### Handle SDK Execution and API Errors Source: https://context7.com/superfly/sprites-js/llms.txt Provides patterns for catching and inspecting specific error types including ExecError for shell failures, APIError for rate limits, and filesystem errors for I/O issues. ```typescript import { SpritesClient, ExecError, APIError, FilesystemError } from '@fly/sprites'; const client = new SpritesClient(process.env.SPRITES_TOKEN!); // Handle command execution errors try { await client.sprite('my-sprite').exec('exit 42'); } catch (error) { if (error instanceof ExecError) { console.log(`Command failed with exit code: ${error.exitCode}`); } } // Handle API errors try { await client.createSprite('new-sprite'); } catch (error) { if (error instanceof APIError) { console.log(`API error: ${error.message}`); if (error.isRateLimitError()) { console.log(`Retry after ${error.getRetryAfterSeconds()} seconds`); } } } // Handle filesystem errors const fs = client.sprite('my-sprite').filesystem('/app'); try { await fs.readFile('missing.txt', 'utf8'); } catch (error) { const fsError = error as any; if (fsError.code === 'ENOENT') { console.log(`File not found: ${fsError.path}`); } } ``` -------------------------------- ### POST /sprite/checkpoint Source: https://context7.com/superfly/sprites-js/llms.txt Creates a new checkpoint to save the current state of a sprite or restores a previously saved state. ```APIDOC ## POST /sprite/checkpoint ### Description Creates a snapshot of the sprite's current state or restores it from a specific checkpoint ID. ### Method POST ### Endpoint /sprite/checkpoint ### Parameters #### Request Body - **comment** (string) - Required - A description for the checkpoint. - **action** (string) - Required - Either 'create' or 'restore'. - **checkpointId** (string) - Required (if restoring) - The ID of the checkpoint to restore. ### Request Example { "action": "create", "comment": "Before deployment" } ### Response #### Success Response (200) - **id** (string) - The unique identifier for the checkpoint. - **status** (string) - The current status of the operation. #### Response Example { "id": "v3", "status": "success" } ``` -------------------------------- ### exec/execFile - Promise-Based Command Execution Source: https://context7.com/superfly/sprites-js/llms.txt Execute shell commands or files with promise-based handling of stdout, stderr, and exit codes. Supports options for working directory, environment variables, encoding, and buffer size. ```APIDOC ## exec/execFile - Promise-Based Command Execution ### Description The `exec` and `execFile` methods provide promise-based command execution that captures output and returns it as strings or buffers. ### Method `sprite.exec(command, [options])` or `sprite.execFile(file, [args], [options])` ### Parameters #### Query Parameters - **command** (string) - Required - The shell command to execute. - **file** (string) - Required - The file to execute. - **args** (string[]) - Optional - Arguments to pass to the file. - **options** (object) - Optional - Configuration options: - **cwd** (string) - Working directory. - **env** (object) - Environment variables. - **encoding** (string) - Output encoding (e.g., 'utf8', 'buffer'). Defaults to 'utf8'. - **maxBuffer** (number) - Maximum output buffer size in bytes. Defaults to 10MB. ### Request Example ```typescript // Execute a shell command const { stdout, stderr, exitCode } = await sprite.exec('echo hello world'); // Execute a file with arguments const result = await sprite.execFile('python', ['-c', 'print(2 + 2)']); // Execute with options const result2 = await sprite.execFile('node', ['script.js'], { cwd: '/app', env: { NODE_ENV: 'production' }, encoding: 'utf8', maxBuffer: 10 * 1024 * 1024, }); // Get output as Buffer const result3 = await sprite.execFile('cat', ['/bin/ls'], { encoding: 'buffer' as any }); ``` ### Response #### Success Response (200) - **stdout** (string | Buffer) - The standard output of the command. - **stderr** (string | Buffer) - The standard error of the command. - **exitCode** (number) - The exit code of the command. #### Error Response (non-zero exit code) - **exitCode** (number) - The non-zero exit code. - **stdout** (string | Buffer) - The standard output. - **stderr** (string | Buffer) - The standard error. ### Response Example ```json { "stdout": "hello world\n", "stderr": "", "exitCode": 0 } ``` ### Error Handling Example ```typescript try { await sprite.exec('exit 1'); } catch (error) { if (error instanceof ExecError) { console.log('Exit code:', error.exitCode); // 1 console.log('Stdout:', error.stdout); console.log('Stderr:', error.stderr); } } ``` ``` -------------------------------- ### TTY Mode - Interactive Terminal Source: https://context7.com/superfly/sprites-js/llms.txt Enable TTY mode for interactive terminal sessions with proper terminal emulation and resizing support. Allows piping local input to the remote process and vice-versa. ```APIDOC ## TTY Mode - Interactive Terminal ### Description Enable TTY mode for interactive terminal sessions with proper terminal emulation and resizing support. ### Method `sprite.spawn(command, [args], [options])` ### Parameters #### Path Parameters - **command** (string) - Required - The command to spawn. - **args** (string[]) - Optional - Arguments for the command. - **options** (object) - Required - TTY configuration: - **tty** (boolean) - Must be `true` to enable TTY mode. - **rows** (number) - Number of rows for the terminal. - **cols** (number) - Number of columns for the terminal. ### Request Example ```typescript const cmd = sprite.spawn('bash', [], { tty: true, rows: 24, cols: 80, }); // Connect local terminal to remote process.stdin.setRawMode(true); process.stdin.pipe(cmd.stdin); cmd.stdout.pipe(process.stdout); // Handle terminal resize process.stdout.on('resize', () => { cmd.resize(process.stdout.columns, process.stdout.rows); }); // Clean up on exit cmd.on('exit', (code) => { process.stdin.setRawMode(false); console.log(`\nSession ended with code ${code}`); process.exit(code); }); ``` ### Response - The `spawn` method returns a `ChildProcess` like object with `stdin`, `stdout`, `stderr` streams, and `resize` and `wait` methods. ``` -------------------------------- ### Port Notifications - React to Network Events Source: https://context7.com/superfly/sprites-js/llms.txt Listen for port notifications when processes open network ports on the sprite. Allows reacting to newly opened or closed ports. ```APIDOC ## Port Notifications - React to Network Events ### Description Listen for port notifications when processes open network ports on the sprite. ### Method `cmd.on('message', (msg) => { ... })` where `cmd` is the result of `sprite.spawn()`. ### Event Listener - **message** (object) - Emitted when a message is received from the process. - **type** (string) - Type of message. Expected values: `'port_opened'` or `'port_closed'`. - **port** (number) - The port number. - **pid** (number) - The process ID that opened/closed the port. - **address** (string) - The address the port is bound to (for `port_opened`). ### Request Example ```typescript const cmd = sprite.spawn('python', ['-m', 'http.server', '8080']); cmd.on('message', (msg) => { if (msg.type === 'port_opened') { console.log(`Port ${msg.port} opened by PID ${msg.pid} on ${msg.address}`); } else if (msg.type === 'port_closed') { console.log(`Port ${msg.port} closed`); } }); ``` ### Response - The `message` event provides structured data about port events. ``` -------------------------------- ### Handle Execution Errors in Sprites Source: https://github.com/superfly/sprites-js/blob/main/README.md Shows how to catch and inspect ExecError instances when a sprite command fails. It provides access to exit codes, standard output, and standard error streams. ```typescript import { ExecError } from '@fly/sprites'; try { await sprite.exec('false'); } catch (error) { if (error instanceof ExecError) { console.log('Exit code:', error.exitCode); console.log('Stdout:', error.stdout); console.log('Stderr:', error.stderr); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.