#!/usr/bin/env node /** * Chahuadev Framework - CLI Interface * Chahua Development Thailand * CEO: Saharath C. * * Purpose: Command Line Interface สำหรับ automation และ integration */ const { program } = require('commander'); const path = require('path'); const fs = require('fs'); // Import core modules (same as app.js) const ValidationGateway = require('./validation_gateway'); const ContextManager = require('./modules/context-manager'); const ErrorHandler = require('./modules/error-handler'); const Executor = require('./modules/executor'); const SystemDetector = require('./modules/system-detector'); const PluginManager = require('./modules/plugin-manager'); class ChahuadevCLI { constructor() { this.validationGateway = new ValidationGateway(); this.contextManager = new ContextManager(); this.errorHandler = new ErrorHandler(); this.executor = new Executor(); this.systemDetector = new SystemDetector(); this.pluginManager = new PluginManager(); console.log(' Chahuadev CLI initialized'); } async initialize() { try { // Load plugins await this.pluginManager.loadPlugins(); console.log(' CLI ready with all modules loaded'); } catch (error) { console.error(' CLI initialization failed:', error.message); process.exit(1); } } async executeCommand(command, options = {}) { const context = this.contextManager.create('cli-execution', { command, options, timestamp: new Date().toISOString(), cwd: process.cwd() }); try { // Validate request const validation = await this.validationGateway.validateRequest({ command, ...options }); if (!validation.success) { throw new Error(`Security validation failed: ${validation.error}`); } // Execute through executor const result = await this.executor.execute({ command, project: options.project || process.cwd(), strategy: options.strategy }, context); return result; } catch (error) { this.errorHandler.handle(error, context.id); throw error; } } async scanProject(projectPath) { try { const fullPath = path.resolve(projectPath); if (!fs.existsSync(fullPath)) { throw new Error(`Project path does not exist: ${fullPath}`); } const detection = await this.systemDetector.detectProject(fullPath); console.log('\n Project Scan Results:'); console.log('========================'); console.log('Project Path:', fullPath); console.log('Detected Type:', detection.type); console.log('Confidence:', `${(detection.confidence * 100).toFixed(1)}%`); console.log('Strategy:', detection.strategy); if (detection.details) { console.log('\n Details:'); Object.entries(detection.details).forEach(([key, value]) => { console.log(` ${key}: ${value}`); }); } return detection; } catch (error) { console.error(' Project scan failed:', error.message); throw error; } } async listPlugins() { try { const plugins = this.pluginManager.getAvailablePlugins(); console.log('\n Available Plugins:'); console.log('===================='); if (plugins.length === 0) { console.log('No plugins loaded'); return; } plugins.forEach(plugin => { console.log(` ${plugin.name}`); console.log(` File: ${plugin.filename}`); console.log(` Status: ${plugin.status}`); console.log(` Loaded: ${plugin.loadedAt.toISOString()}`); if (plugin.metadata.description) { console.log(` Description: ${plugin.metadata.description}`); } console.log(''); }); return plugins; } catch (error) { console.error(' Failed to list plugins:', error.message); throw error; } } async executePlugin(pluginName, data) { try { const result = await this.pluginManager.executePlugin(pluginName, data); if (result.success) { console.log(` Plugin ${pluginName} executed successfully`); console.log('Result:', JSON.stringify(result.result, null, 2)); } else { console.error(` Plugin ${pluginName} failed: ${result.error}`); } return result; } catch (error) { console.error(' Plugin execution failed:', error.message); throw error; } } async getStatus() { const status = { framework: 'Chahuadev Framework', version: '1.0.0', interface: 'CLI', timestamp: new Date().toISOString(), modules: { validationGateway: !!this.validationGateway, contextManager: !!this.contextManager, errorHandler: !!this.errorHandler, executor: !!this.executor, systemDetector: !!this.systemDetector, pluginManager: !!this.pluginManager }, plugins: this.pluginManager.getPluginStats() }; console.log('\n System Status:'); console.log('================'); console.log(JSON.stringify(status, null, 2)); return status; } } // CLI Commands Setup async function setupCommands() { const cli = new ChahuadevCLI(); await cli.initialize(); program .name('chahuadev') .description('Chahuadev Framework CLI') .version('1.0.0'); // Execute command program .command('execute ') .description('Execute a command through the framework') .option('-p, --project ', 'Project path', process.cwd()) .option('-s, --strategy ', 'Force specific strategy') .action(async (command, options) => { try { console.log(` Executing: ${command}`); const result = await cli.executeCommand(command, options); console.log(' Execution completed'); console.log(JSON.stringify(result, null, 2)); } catch (error) { console.error(' Execution failed:', error.message); process.exit(1); } }); // Scan project program .command('scan ') .description('Scan project and detect type') .action(async (projectPath) => { try { await cli.scanProject(projectPath); } catch (error) { console.error(' Scan failed:', error.message); process.exit(1); } }); // Plugin management program .command('plugins') .description('List available plugins') .action(async () => { try { await cli.listPlugins(); } catch (error) { console.error(' Failed to list plugins:', error.message); process.exit(1); } }); program .command('plugin ') .description('Execute a plugin') .option('-d, --data ', 'JSON data to pass to plugin', '{}') .action(async (name, options) => { try { const data = JSON.parse(options.data); await cli.executePlugin(name, data); } catch (error) { console.error(' Plugin execution failed:', error.message); process.exit(1); } }); // Status program .command('status') .description('Show system status') .action(async () => { try { await cli.getStatus(); } catch (error) { console.error(' Failed to get status:', error.message); process.exit(1); } }); // Help command program .command('help') .description('Show help information') .action(() => { console.log('\n Chahuadev Framework CLI'); console.log('==========================='); console.log('Usage examples:'); console.log(''); console.log(' chahuadev execute "npm test" # Execute npm test'); console.log(' chahuadev execute "node app.js" -p ./src # Execute in specific project'); console.log(' chahuadev scan ./my-project # Scan project type'); console.log(' chahuadev plugins # List available plugins'); console.log(' chahuadev plugin zip-compressor # Execute plugin'); console.log(' chahuadev status # Show system status'); console.log(''); program.help(); }); return { cli, program }; } // Main execution if (require.main === module) { setupCommands().then(({ program }) => { // Parse command line arguments program.parse(); }).catch(error => { console.error(' CLI setup failed:', error.message); process.exit(1); }); } module.exports = { ChahuadevCLI, setupCommands };