dynamic-interaction
Version:
Dynamic interaction 动态交互mcp,用于cursor、windsurf、trae 等 AI 智能编辑器 Agent 运行时交互使用
89 lines (88 loc) • 3.28 kB
JavaScript
;
/**
* HTTP 服务器管理
* 负责HTTP服务器的创建和配置
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.httpServer = exports.HttpServer = void 0;
const express_1 = __importDefault(require("express"));
const http_1 = __importDefault(require("http"));
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const config_1 = require("../../config");
const logger_1 = require("../../logger");
class HttpServer {
static instance;
app;
server;
constructor() {
this.app = (0, express_1.default)();
this.server = http_1.default.createServer(this.app);
this.configureMiddleware();
}
static getInstance() {
if (!HttpServer.instance) {
HttpServer.instance = new HttpServer();
}
return HttpServer.instance;
}
configureMiddleware() {
// 提供静态文件服务
const staticPath = path_1.default.join(__dirname, '..', '..', 'public');
this.app.use(express_1.default.static(staticPath));
// 默认语言注入中间件
this.app.use((req, res, next) => {
if (req.path === '/' || req.path === '/index.html') {
const filePath = path_1.default.join(staticPath, 'index.html');
let html = fs_1.default.readFileSync(filePath, 'utf-8');
html = html.replace('<html>', `<html lang="${process.env.DEFAULT_LANGUAGE || 'zh'}">`);
html = html.replace('</head>', `<script>window.__DEFAULT_LANG__ = "${process.env.DEFAULT_LANGUAGE || 'zh'}";</script></head>`);
res.setHeader('Content-Type', 'text/html');
res.end(html);
return;
}
next();
});
logger_1.logger.info(`静态文件服务路径: ${staticPath}`);
// /config 路由,提供运行时配置
this.app.get('/config', (_req, res) => {
res.json({ defaultLanguage: process.env.DEFAULT_LANGUAGE || 'zh' });
});
}
getApp() {
return this.app;
}
getServer() {
return this.server;
}
async start(port = config_1.PORT) {
return new Promise((resolve, reject) => {
this.server.listen(port, () => {
logger_1.logger.info(`HTTP服务器已启动,监听地址: http://localhost:${port}`);
resolve();
});
this.server.on('error', (error) => {
logger_1.logger.error('HTTP服务器启动失败:', error);
reject(error);
});
});
}
async stop() {
return new Promise((resolve, reject) => {
this.server.close((err) => {
if (err) {
logger_1.logger.error('关闭HTTP服务器时出错:', err);
reject(err);
return;
}
logger_1.logger.info('HTTP服务器已成功关闭');
resolve();
});
});
}
}
exports.HttpServer = HttpServer;
exports.httpServer = HttpServer.getInstance();