UNPKG

irys-complete-toolkit

Version:

Complete Irys SDK toolkit supporting all chains, tokens, and features

379 lines (378 loc) 11.8 kB
"use strict"; /** * Irys CLI Wrapper * Programmatic interface for Irys CLI operations */ Object.defineProperty(exports, "__esModule", { value: true }); exports.IrysCLI = void 0; const child_process_1 = require("child_process"); const types_1 = require("../types"); class IrysCLI { constructor(cliPath = 'irys', options = {}) { this.cliPath = cliPath; this.defaultOptions = { stdio: ['pipe', 'pipe', 'pipe'], ...options, }; } /** * Execute CLI command */ async executeCommand(args, options = {}) { return new Promise((resolve) => { const child = (0, child_process_1.spawn)(this.cliPath, args, { ...this.defaultOptions, ...options, }); let stdout = ''; let stderr = ''; if (child.stdout) { child.stdout.on('data', (data) => { stdout += data.toString(); }); } if (child.stderr) { child.stderr.on('data', (data) => { stderr += data.toString(); }); } child.on('close', (code) => { resolve({ success: code === 0, stdout: stdout.trim(), stderr: stderr.trim(), exitCode: code, }); }); child.on('error', (error) => { resolve({ success: false, stdout: '', stderr: error.message, exitCode: null, }); }); }); } /** * Check if CLI is available */ async isAvailable() { try { const result = await this.executeCommand(['--version']); return result.success; } catch (error) { return false; } } /** * Get CLI version */ async getVersion() { const result = await this.executeCommand(['--version']); if (!result.success) { throw new types_1.IrysError(`Failed to get CLI version: ${result.stderr}`); } return result.stdout; } /** * Upload a file using CLI */ async uploadFile(filePath, options) { this.validateToken(options.token); const args = ['upload', filePath]; // Add network option if (options.network) { args.push('-n', options.network); } // Add token option args.push('-t', options.token); // Add private key args.push('-w', options.privateKey); // Add provider URL if specified if (options.providerUrl) { args.push('--provider-url', options.providerUrl); } // Add tags if specified if (options.tags) { args.push('--tags'); Object.entries(options.tags).forEach(([key, value]) => { args.push(key, value); }); } const result = await this.executeCommand(args); if (!result.success) { throw new types_1.IrysError(`Upload failed: ${result.stderr || result.stdout}`); } // Parse the output to extract transaction ID const transactionId = this.extractTransactionId(result.stdout); const url = `https://gateway.irys.xyz/${transactionId}`; return { transactionId, url, receipt: this.parseReceipt(result.stdout), }; } /** * Upload a directory using CLI */ async uploadDirectory(directoryPath, options) { this.validateToken(options.token); const args = ['upload-dir', directoryPath]; // Add network option if (options.network) { args.push('-n', options.network); } // Add token option args.push('-t', options.token); // Add private key args.push('-w', options.privateKey); // Add provider URL if specified if (options.providerUrl) { args.push('--provider-url', options.providerUrl); } // Add tags if specified if (options.tags) { args.push('--tags'); Object.entries(options.tags).forEach(([key, value]) => { args.push(key, value); }); } const result = await this.executeCommand(args); if (!result.success) { throw new types_1.IrysError(`Directory upload failed: ${result.stderr || result.stdout}`); } // Parse the output to extract manifest ID const manifestId = this.extractTransactionId(result.stdout); const url = `https://gateway.irys.xyz/${manifestId}`; return { manifestId, url, receipt: this.parseReceipt(result.stdout), }; } /** * Get account balance using CLI */ async getBalance(options) { this.validateToken(options.token); const args = ['balance', options.address]; // Add network option if (options.network) { args.push('-n', options.network); } // Add token option args.push('-t', options.token); // Add provider URL if specified if (options.providerUrl) { args.push('--provider-url', options.providerUrl); } const result = await this.executeCommand(args); if (!result.success) { throw new types_1.IrysError(`Balance check failed: ${result.stderr || result.stdout}`); } // Parse balance from output return this.extractBalance(result.stdout); } /** * Fund account using CLI */ async fund(amount, options) { this.validateToken(options.token); const args = ['fund', amount]; // Add network option if (options.network) { args.push('-n', options.network); } // Add token option args.push('-t', options.token); // Add private key args.push('-w', options.privateKey); // Add provider URL if specified if (options.providerUrl) { args.push('--provider-url', options.providerUrl); } const result = await this.executeCommand(args); if (!result.success) { throw new types_1.IrysError(`Funding failed: ${result.stderr || result.stdout}`); } return { transactionId: this.extractTransactionId(result.stdout), amount, token: options.token, }; } /** * Get upload price using CLI */ async getPrice(bytes, options) { this.validateToken(options.token); const args = ['price', bytes.toString()]; // Add network option if (options.network) { args.push('-n', options.network); } // Add token option args.push('-t', options.token); // Add provider URL if specified if (options.providerUrl) { args.push('--provider-url', options.providerUrl); } const result = await this.executeCommand(args); if (!result.success) { throw new types_1.IrysError(`Price check failed: ${result.stderr || result.stdout}`); } return this.extractPrice(result.stdout); } /** * Withdraw funds using CLI */ async withdraw(amount, options) { this.validateToken(options.token); const args = ['withdraw', amount]; // Add network option if (options.network) { args.push('-n', options.network); } // Add token option args.push('-t', options.token); // Add private key args.push('-w', options.privateKey); // Add provider URL if specified if (options.providerUrl) { args.push('--provider-url', options.providerUrl); } const result = await this.executeCommand(args); if (!result.success) { throw new types_1.IrysError(`Withdrawal failed: ${result.stderr || result.stdout}`); } return { transactionId: this.extractTransactionId(result.stdout), amount, token: options.token, }; } /** * Get CLI status/info */ async getStatus() { const result = await this.executeCommand(['status']); if (!result.success) { throw new types_1.IrysError(`Status check failed: ${result.stderr}`); } try { return JSON.parse(result.stdout); } catch (error) { return { output: result.stdout }; } } /** * Validate token support */ validateToken(token) { if (!types_1.SUPPORTED_TOKENS[token]) { throw new types_1.IrysError(`Unsupported token: ${token}. Supported tokens: ${Object.keys(types_1.SUPPORTED_TOKENS).join(', ')}`); } } /** * Extract transaction ID from CLI output */ extractTransactionId(output) { // Look for various patterns that might contain transaction IDs const patterns = [ /Transaction ID:\s*([A-Za-z0-9_-]+)/, /ID:\s*([A-Za-z0-9_-]+)/, /https:\/\/gateway\.irys\.xyz\/([A-Za-z0-9_-]+)/, /([A-Za-z0-9_-]{43,})/, ]; for (const pattern of patterns) { const match = output.match(pattern); if (match && match[1]) { return match[1]; } } throw new types_1.IrysError(`Could not extract transaction ID from output: ${output}`); } /** * Extract balance from CLI output */ extractBalance(output) { const patterns = [ /Balance:\s*([0-9.]+)/, /([0-9.]+)\s*[A-Z]+/, /([0-9.]+)/, ]; for (const pattern of patterns) { const match = output.match(pattern); if (match && match[1]) { return match[1]; } } throw new types_1.IrysError(`Could not extract balance from output: ${output}`); } /** * Extract price from CLI output */ extractPrice(output) { const patterns = [ /Price:\s*([0-9.]+)/, /([0-9.]+)\s*[A-Z]+/, /([0-9.]+)/, ]; for (const pattern of patterns) { const match = output.match(pattern); if (match && match[1]) { return match[1]; } } throw new types_1.IrysError(`Could not extract price from output: ${output}`); } /** * Parse receipt from CLI output */ parseReceipt(output) { try { // Try to find JSON in the output const jsonMatch = output.match(/\{.*\}/s); if (jsonMatch) { return JSON.parse(jsonMatch[0]); } } catch (error) { // Ignore JSON parsing errors } // Return basic receipt info return { id: this.extractTransactionId(output), timestamp: Date.now(), output, }; } /** * Set CLI path */ setCLIPath(path) { this.cliPath = path; } /** * Get current CLI path */ getCLIPath() { return this.cliPath; } /** * Set default spawn options */ setDefaultOptions(options) { this.defaultOptions = { ...this.defaultOptions, ...options }; } /** * Get supported tokens for CLI */ static getSupportedTokens() { return Object.keys(types_1.SUPPORTED_TOKENS); } } exports.IrysCLI = IrysCLI;