/** * Main Application Entry Point * * This is the main entry point for the CLI application. * It integrates all the deobfuscated components and provides * the primary interface for the shell command processing system. */ const { ShellParser } = require("./core/shell-parser"); const { HttpClient } = require("./network/http-client"); const { performanceMonitor } = require("./instrumentation/performance-monitor"); const { moduleLoader } = require("./module-system/module-loader"); const { getGlobalObject } = require("./platform/global-object"); const { detectRuntime } = require("./platform/environment-detection"); const { TimingUtils } = require("./platform/compatibility"); const { generateUuid4 } = require("./utils/uuid"); const pathUtils = require("./utils/path-utils"); const stringUtils = require("./utils/string-utils"); /** * Main CLI Application class */ class CLIApplication { constructor(options = {}) { this.options = { debug: options.debug || false, timeout: options.timeout || 30000, maxConcurrency: options.maxConcurrency || 10, ...options, }; this.shellParser = new ShellParser(); this.httpClient = new HttpClient(); this.timingUtils = new TimingUtils(); this.activeCommands = new Map(); this.commandHistory = []; this.environment = detectRuntime(); this.init(); } /** * Initialize the application */ init() { this.setupGlobalErrorHandlers(); this.setupPerformanceMonitoring(); this.logStartupInfo(); } /** * Setup global error handlers */ setupGlobalErrorHandlers() { const global = getGlobalObject(); if (typeof global.addEventListener === "function") { global.addEventListener("error", (event) => { this.handleError(event.error, "global-error"); }); global.addEventListener("unhandledrejection", (event) => { this.handleError(event.reason, "unhandled-rejection"); }); } } /** * Setup performance monitoring */ setupPerformanceMonitoring() { if (this.options.debug) { performanceMonitor.startTiming("application-lifecycle"); } } /** * Log startup information */ logStartupInfo() { if (this.options.debug) { console.log("CLI Application Starting..."); console.log("Runtime:", this.environment.name, this.environment.version); console.log("Platform:", this.environment.platform); console.log("Features:", this.environment.features); } } /** * Execute a shell command * @param {string} command - Command to execute * @param {Object} context - Execution context * @returns {Promise} Execution result */ async executeCommand(command, context = {}) { const commandId = generateUuid4(); const timerId = performanceMonitor.startTiming(`command-${commandId}`); try { // Parse the command const parsed = this.shellParser.parseShellCommand(command, context.env); // Validate command if (!parsed.command) { throw new Error("Invalid command: empty or malformed"); } // Track active command this.activeCommands.set(commandId, { command: parsed.command, args: parsed.args, startTime: Date.now(), timerId, }); // Execute based on command type let result; if (this.isBuiltinCommand(parsed.command)) { result = await this.executeBuiltinCommand(parsed, context); } else { result = await this.executeExternalCommand(parsed, context); } // Add to history this.addToHistory(command, result); return result; } catch (error) { this.handleError(error, "command-execution", { command, commandId }); throw error; } finally { // Cleanup this.activeCommands.delete(commandId); performanceMonitor.endTiming(timerId); } } /** * Check if command is a builtin * @param {string} command - Command name * @returns {boolean} True if builtin */ isBuiltinCommand(command) { const builtins = [ "cd", "pwd", "echo", "export", "set", "unset", "alias", "unalias", "history", "jobs", "help", "version", "exit", "quit", ]; return builtins.includes(command); } /** * Execute builtin command * @param {Object} parsed - Parsed command * @param {Object} context - Execution context * @returns {Promise} Result */ async executeBuiltinCommand(parsed, context) { const { command, args } = parsed; switch (command) { case "echo": return this.executeEcho(args); case "pwd": return this.executePwd(); case "cd": return this.executeCd(args[0]); case "export": return this.executeExport(args, context); case "set": return this.executeSet(args, context); case "history": return this.executeHistory(args); case "help": return this.executeHelp(args); case "version": return this.executeVersion(); case "exit": case "quit": return this.executeExit(args); default: throw new Error(`Unknown builtin command: ${command}`); } } /** * Execute external command * @param {Object} parsed - Parsed command * @param {Object} context - Execution context * @returns {Promise} Result */ async executeExternalCommand(parsed, context) { // In a real implementation, this would spawn a child process // For this deobfuscated version, we'll simulate command execution const { command, args } = parsed; // Simulate some common commands if (command === "ls" || command === "dir") { return this.simulateListDirectory(args); } else if (command === "cat" || command === "type") { return this.simulateReadFile(args); } else if (command === "curl" || command === "wget") { return this.simulateHttpRequest(args); } // Default simulation return { exitCode: 0, stdout: `Simulated execution of: ${command} ${args.join(" ")}`, stderr: "", duration: Math.random() * 1000 + 100, }; } /** * Execute echo command * @param {Array} args - Command arguments * @returns {Object} Result */ executeEcho(args) { const output = args.join(" "); return { exitCode: 0, stdout: output, stderr: "", }; } /** * Execute pwd command * @returns {Object} Result */ executePwd() { const cwd = process.cwd ? process.cwd() : "/"; return { exitCode: 0, stdout: cwd, stderr: "", }; } /** * Execute cd command * @param {string} path - Target path * @returns {Object} Result */ executeCd(path) { if (!path) path = "~"; try { const resolvedPath = pathUtils.resolve(path); // In a real implementation, this would change the working directory return { exitCode: 0, stdout: "", stderr: "", cwd: resolvedPath, }; } catch (error) { return { exitCode: 1, stdout: "", stderr: `cd: ${error.message}`, }; } } /** * Execute export command * @param {Array} args - Command arguments * @param {Object} context - Execution context * @returns {Object} Result */ executeExport(args, context) { if (args.length === 0) { // Show all exported variables const vars = Object.entries(context.env || {}) .map(([key, value]) => `${key}=${value}`) .join("\n"); return { exitCode: 0, stdout: vars, stderr: "", }; } // Set environment variables for (const arg of args) { const [key, value] = arg.split("=", 2); if (key && value !== undefined) { context.env = context.env || {}; context.env[key] = value; } } return { exitCode: 0, stdout: "", stderr: "", }; } /** * Execute set command * @param {Array} args - Command arguments * @param {Object} context - Execution context * @returns {Object} Result */ executeSet(args, context) { // Similar to export but for shell variables return this.executeExport(args, context); } /** * Execute history command * @param {Array} args - Command arguments * @returns {Object} Result */ executeHistory(args) { const count = args[0] ? parseInt(args[0], 10) : this.commandHistory.length; const history = this.commandHistory .slice(-count) .map((entry, index) => `${index + 1} ${entry.command}`) .join("\n"); return { exitCode: 0, stdout: history, stderr: "", }; } /** * Execute help command * @param {Array} args - Command arguments * @returns {Object} Result */ executeHelp(args) { const helpText = ` CLI Application Help Builtin Commands: cd [path] Change directory pwd Print working directory echo [args] Print arguments export [var] Set environment variable set [var] Set shell variable history [n] Show command history help [cmd] Show help information version Show version information exit/quit Exit the application External Commands: Commands are executed in the system shell when not builtin. Examples: cd /home/user echo "Hello World" export PATH=/usr/bin:$PATH ls -la curl https://example.com `.trim(); return { exitCode: 0, stdout: helpText, stderr: "", }; } /** * Execute version command * @returns {Object} Result */ executeVersion() { const version = `CLI Application v1.0.0 Runtime: ${this.environment.name} ${this.environment.version} Platform: ${this.environment.platform} Node.js: ${process.version || "N/A"}`; return { exitCode: 0, stdout: version, stderr: "", }; } /** * Execute exit command * @param {Array} args - Command arguments * @returns {Object} Result */ executeExit(args) { const exitCode = args[0] ? parseInt(args[0], 10) : 0; // Cleanup this.cleanup(); return { exitCode, stdout: "Goodbye!", stderr: "", shouldExit: true, }; } /** * Simulate directory listing * @param {Array} args - Command arguments * @returns {Object} Result */ simulateListDirectory(args) { const files = [ "file1.txt", "file2.js", "directory1/", "README.md", ".hidden", ]; return { exitCode: 0, stdout: files.join("\n"), stderr: "", }; } /** * Simulate file reading * @param {Array} args - Command arguments * @returns {Object} Result */ simulateReadFile(args) { if (args.length === 0) { return { exitCode: 1, stdout: "", stderr: "cat: missing file operand", }; } const filename = args[0]; return { exitCode: 0, stdout: `Contents of ${filename}:\nThis is simulated file content.`, stderr: "", }; } /** * Simulate HTTP request * @param {Array} args - Command arguments * @returns {Promise} Result */ async simulateHttpRequest(args) { if (args.length === 0) { return { exitCode: 1, stdout: "", stderr: "curl: missing URL", }; } const url = args[0]; try { const response = await this.httpClient.get(url); return { exitCode: 0, stdout: JSON.stringify(response.data, null, 2), stderr: "", }; } catch (error) { return { exitCode: 1, stdout: "", stderr: `curl: ${error.message}`, }; } } /** * Add command to history * @param {string} command - Command string * @param {Object} result - Execution result */ addToHistory(command, result) { this.commandHistory.push({ command, timestamp: Date.now(), exitCode: result.exitCode, duration: result.duration, }); // Keep history limited if (this.commandHistory.length > 1000) { this.commandHistory = this.commandHistory.slice(-500); } } /** * Handle errors * @param {Error} error - Error object * @param {string} context - Error context * @param {Object} metadata - Additional metadata */ handleError(error, context, metadata = {}) { const errorInfo = { message: error.message, stack: error.stack, context, timestamp: Date.now(), ...metadata, }; if (this.options.debug) { console.error("CLI Error:", errorInfo); } // In a real implementation, this might send to a logging service } /** * Get application statistics * @returns {Object} Statistics */ getStats() { return { commandsExecuted: this.commandHistory.length, activeCommands: this.activeCommands.size, uptime: Date.now() - (this.startTime || Date.now()), environment: this.environment, memoryUsage: this.getMemoryUsage(), }; } /** * Get memory usage * @returns {Object} Memory usage info */ getMemoryUsage() { if (typeof process !== "undefined" && process.memoryUsage) { return process.memoryUsage(); } if (typeof performance !== "undefined" && performance.memory) { return { rss: performance.memory.usedJSHeapSize, heapTotal: performance.memory.totalJSHeapSize, heapUsed: performance.memory.usedJSHeapSize, external: 0, }; } return null; } /** * Cleanup resources */ cleanup() { if (this.options.debug) { const duration = performanceMonitor.endTiming("application-lifecycle"); console.log(`Application ran for ${duration}ms`); } // Clear active commands this.activeCommands.clear(); // Cleanup performance monitoring performanceMonitor.clearAllMeasurements(); } } /** * Create and run CLI application * @param {Object} options - Application options * @returns {CLIApplication} Application instance */ function createCLI(options = {}) { return new CLIApplication(options); } /** * Main entry point when run directly */ function main() { const app = createCLI({ debug: true }); // Example usage if ( typeof process !== "undefined" && process.argv && process.argv.length > 2 ) { const command = process.argv.slice(2).join(" "); app .executeCommand(command) .then((result) => { console.log(result.stdout); if (result.stderr) console.error(result.stderr); if (result.shouldExit) process.exit(result.exitCode); }) .catch((error) => { console.error("Command failed:", error.message); process.exit(1); }); } else { console.log( "CLI Application initialized. Use createCLI() to create an instance.", ); } } module.exports = { CLIApplication, createCLI, main, }; // Run main if this is the entry point if (typeof require !== "undefined" && require.main === module) { main(); }