/** * Transport - 传输层抽象基类 * * 定义传输层接口,所有传输实现(子进程、WebSocket等)都需要实现这个接口。 */ const { EventEmitter } = require('events'); /** * 传输层基类 * * Events: * - 'message': 收到结构化 JSON 消息 * - 'output': 收到非 JSON 文本输出 * - 'stderr': 收到标准错误输出 * - 'error': 发生错误 * - 'close': 连接关闭 */ class Transport extends EventEmitter { constructor() { super(); this.buffer = ''; } /** * 处理接收到的原始数据(NDJSON 缓冲分包) * 子类在收到数据时调用此方法,自动解析 JSON 行并发出对应事件。 * @param {string|Buffer} chunk - 原始数据块 * @protected */ _handleData(chunk) { this.buffer += chunk.toString(); // 按换行符分割 (支持 \r\n 和 \n) const lines = this.buffer.split(/\r?\n/); // 保留不完整的行 this.buffer = lines.pop() || ''; for (const line of lines) { if (!line.trim()) continue; // 处理 Bridge 转发的 stderr if (line.trim().startsWith('{')) { try { const msg = JSON.parse(line); if (msg._stderr !== undefined) { this.emit('stderr', msg._stderr); continue; } this.emit('message', msg); } catch (e) { this.emit('output', line); } } else { this.emit('output', line); } } } /** * 建立连接 * @param {string} command - 命令 * @param {string[]} args - 参数列表 * @param {object} options - 选项 * @returns {Promise} */ async connect(command, args, options = {}) { throw new Error('Transport.connect() must be implemented'); } /** * 发送消息 * @param {object} msg - 要发送的消息对象 */ send(msg) { throw new Error('Transport.send() must be implemented'); } /** * 关闭连接 */ close() { throw new Error('Transport.close() must be implemented'); } /** * 检查是否已连接 * @returns {boolean} */ get isConnected() { throw new Error('Transport.isConnected getter must be implemented'); } } module.exports = { Transport };