const express = require('express'); const fs = require('fs'); const path = require('path'); const router = express.Router(); const PLUGINS_DIR = path.join(__dirname, '..', 'plugins'); // Ensure plugins directory exists if (!fs.existsSync(PLUGINS_DIR)) { fs.mkdirSync(PLUGINS_DIR, { recursive: true }); } // List all available plugins router.get('/', (req, res) => { try { if (!fs.existsSync(PLUGINS_DIR)) { return res.json([]); } const plugins = []; const dirs = fs.readdirSync(PLUGINS_DIR); for (const dir of dirs) { const pluginPath = path.join(PLUGINS_DIR, dir); const manifestPath = path.join(pluginPath, 'plugin.json'); if (fs.existsSync(manifestPath)) { try { const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8')); plugins.push({ id: dir, ...manifest }); } catch (e) { console.warn(`Invalid plugin manifest: ${dir}`); } } } res.json(plugins); } catch (err) { console.error('Plugin list error:', err); res.status(500).json({ error: 'Failed to list plugins' }); } }); // Serve plugin code as JavaScript module router.get('/:id/code', (req, res) => { try { const pluginDir = path.join(PLUGINS_DIR, req.params.id); const codePath = path.join(pluginDir, 'plugin.js'); if (!fs.existsSync(codePath)) { return res.status(404).json({ error: 'Plugin code not found' }); } res.setHeader('Content-Type', 'application/javascript'); res.sendFile(codePath); } catch (err) { console.error('Plugin code error:', err); res.status(500).json({ error: 'Failed to load plugin code' }); } }); module.exports = router;