@tuanjie/mcp_serial 0.0.0-stage → 2.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,191 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
4
+ import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
5
+ import { SerialConnectionManager } from "../services/serial-connection-manager.js";
6
+ import { CommandLineParser } from "../cli/command-line-parser.js";
7
+ import { Logger } from "../utils/logger.js";
8
+ import { registerAllTools } from "../tools/index.js";
9
+ import { SERVER_CONFIG } from "../config/server.js";
10
+ import http from "node:http";
11
+ /**
12
+ * 创建一个已注册工具的 MCP 服务实例。
13
+ * SDK 单实例只能挂一个 transport;HTTP 须一会话/一请求一实例。
14
+ */
15
+ function createToolServer() {
16
+ const server = new McpServer(SERVER_CONFIG);
17
+ registerAllTools(server);
18
+ return server;
19
+ }
20
+ /**
21
+ * MCP Server class
22
+ */
23
+ export class SerialMcpServer {
24
+ server;
25
+ serialManager;
26
+ constructor() {
27
+ this.server = createToolServer();
28
+ this.serialManager = SerialConnectionManager.getInstance();
29
+ }
30
+ async run() {
31
+ const parsedArgs = CommandLineParser.parseArgs();
32
+ this.serialManager.setConfig(parsedArgs.configs);
33
+ if (parsedArgs.preConnect) {
34
+ if (Object.keys(parsedArgs.configs).length === 0) {
35
+ Logger.log("Pre-connect skipped: no serial connections configured", "info");
36
+ }
37
+ else {
38
+ Logger.log("Pre-connecting to all configured serial ports...", "info");
39
+ try {
40
+ await this.serialManager.connectAll();
41
+ Logger.log("Successfully pre-connected to all serial ports", "info");
42
+ }
43
+ catch (error) {
44
+ Logger.log(`Warning: Some serial connections failed during pre-connect: ${error.message}`, "error");
45
+ }
46
+ }
47
+ }
48
+ const toolCount = Object.keys(this.server._registeredTools || {}).length;
49
+ Logger.log(`Tools registered successfully: ${toolCount} tools`, "info");
50
+ if (parsedArgs.serverOptions.transport === "http") {
51
+ await this.runHttpServer(parsedArgs.serverOptions);
52
+ }
53
+ else {
54
+ await this.runStdioServer();
55
+ }
56
+ }
57
+ async runStdioServer() {
58
+ const transport = new StdioServerTransport();
59
+ await this.server.connect(transport);
60
+ Logger.log("MCP server connection established (stdio)");
61
+ }
62
+ /**
63
+ * SSE + Streamable HTTP(与 mcp_telnet / mcp_ssh 对齐)
64
+ */
65
+ async runHttpServer(options) {
66
+ const sseSessions = new Map();
67
+ const httpServer = http.createServer(async (req, res) => {
68
+ const started = Date.now();
69
+ const remote = req.socket.remoteAddress || "?";
70
+ try {
71
+ if (!req.url?.startsWith("/mcp")) {
72
+ res.writeHead(404).end("Not Found");
73
+ return;
74
+ }
75
+ const url = new URL(req.url, `http://${req.headers.host}`);
76
+ const sessionId = req.headers["mcp-session-id"] ||
77
+ url.searchParams.get("sessionId") ||
78
+ "";
79
+ // SSE: GET /mcp
80
+ if (req.method === "GET" && req.headers.accept?.includes("text/event-stream")) {
81
+ const server = createToolServer();
82
+ const transport = new SSEServerTransport("/mcp", res);
83
+ sseSessions.set(transport.sessionId, { server, transport });
84
+ res.on("close", () => {
85
+ sseSessions.delete(transport.sessionId);
86
+ void server.close().catch(() => undefined);
87
+ });
88
+ await server.connect(transport);
89
+ Logger.log(`SSE session opened: ${transport.sessionId} from ${remote}`, "info");
90
+ return;
91
+ }
92
+ // SSE: POST
93
+ if (req.method === "POST" && sessionId && sseSessions.has(sessionId)) {
94
+ const session = sseSessions.get(sessionId);
95
+ const chunks = [];
96
+ req.on("data", (chunk) => chunks.push(chunk));
97
+ req.on("end", async () => {
98
+ try {
99
+ const body = JSON.parse(Buffer.concat(chunks).toString());
100
+ const method = body?.method || "?";
101
+ const toolName = body?.params?.name || "";
102
+ Logger.log(`SSE POST session=${sessionId} method=${method}${toolName ? ` tool=${toolName}` : ""}`, "info");
103
+ await session.transport.handlePostMessage(req, res, body);
104
+ Logger.log(`SSE done session=${sessionId} method=${method} ${Date.now() - started}ms`, "info");
105
+ }
106
+ catch (error) {
107
+ Logger.handleError(error, `SSE POST error`, false);
108
+ if (!res.headersSent) {
109
+ res.writeHead(400, { "Content-Type": "application/json" });
110
+ res.end(JSON.stringify({ error: "Invalid request body" }));
111
+ }
112
+ }
113
+ });
114
+ return;
115
+ }
116
+ // Streamable HTTP
117
+ if (req.method === "POST" || req.method === "DELETE") {
118
+ const server = createToolServer();
119
+ const transport = new StreamableHTTPServerTransport({
120
+ sessionIdGenerator: undefined,
121
+ enableJsonResponse: true,
122
+ });
123
+ let cleaned = false;
124
+ const cleanup = () => {
125
+ if (cleaned)
126
+ return;
127
+ cleaned = true;
128
+ void transport.close().catch(() => undefined);
129
+ void server.close().catch(() => undefined);
130
+ };
131
+ res.on("close", cleanup);
132
+ const chunks = [];
133
+ req.on("data", (chunk) => chunks.push(chunk));
134
+ req.on("end", async () => {
135
+ let method = "?";
136
+ try {
137
+ const body = chunks.length
138
+ ? JSON.parse(Buffer.concat(chunks).toString())
139
+ : undefined;
140
+ method =
141
+ body?.method ||
142
+ (Array.isArray(body)
143
+ ? body.map((m) => m.method).join(",")
144
+ : "?");
145
+ const toolName = body?.params?.name || "";
146
+ Logger.log(`HTTP ${req.method} from ${remote} method=${method}${toolName ? ` tool=${toolName}` : ""}`, "info");
147
+ await server.connect(transport);
148
+ await transport.handleRequest(req, res, body);
149
+ Logger.log(`HTTP done method=${method}${toolName ? ` tool=${toolName}` : ""} ${Date.now() - started}ms`, "info");
150
+ }
151
+ catch (error) {
152
+ Logger.handleError(error, `HTTP ${req.method} request error`, false);
153
+ if (!res.headersSent) {
154
+ if (error instanceof SyntaxError) {
155
+ res.writeHead(400, { "Content-Type": "application/json" });
156
+ res.end(JSON.stringify({ error: "Invalid request body" }));
157
+ }
158
+ else {
159
+ res.writeHead(500, { "Content-Type": "application/json" });
160
+ res.end(JSON.stringify({ error: "Internal server error" }));
161
+ }
162
+ }
163
+ cleanup();
164
+ }
165
+ });
166
+ req.on("error", (error) => {
167
+ Logger.handleError(error, `HTTP request stream error`, false);
168
+ });
169
+ return;
170
+ }
171
+ res.writeHead(405).end("Method Not Allowed");
172
+ }
173
+ catch (error) {
174
+ Logger.handleError(error, `HTTP server request handler error`, false);
175
+ if (!res.headersSent) {
176
+ res.writeHead(500, { "Content-Type": "application/json" });
177
+ res.end(JSON.stringify({ error: "Internal server error" }));
178
+ }
179
+ }
180
+ });
181
+ httpServer.listen(options.httpPort || 8800, options.httpHost || "0.0.0.0", () => {
182
+ Logger.log(`MCP server running on http://${options.httpHost || "0.0.0.0"}:${options.httpPort || 8800}/mcp (SSE + streamable-http, per-session server)`);
183
+ });
184
+ httpServer.on("error", (error) => {
185
+ Logger.log(`HTTP server error: ${error.message}`, "error");
186
+ });
187
+ httpServer.on("close", () => {
188
+ Logger.log("HTTP server closed", "info");
189
+ });
190
+ }
191
+ }
package/build/index.js ADDED
@@ -0,0 +1,52 @@
1
+ #!/usr/bin/env node
2
+ import { SerialMcpServer } from "./core/mcp-server.js";
3
+ import { Logger } from "./utils/logger.js";
4
+ import { SerialConnectionManager } from "./services/serial-connection-manager.js";
5
+ /**
6
+ * Main program entry
7
+ */
8
+ async function main() {
9
+ Logger.initialize("mcp_serial");
10
+ // Handle uncaught exceptions
11
+ process.on("uncaughtException", (error) => {
12
+ Logger.handleError(error, "【Uncaught Exception】", false);
13
+ // Don't exit on uncaught exception for HTTP mode, log and continue
14
+ });
15
+ // Handle unhandled promise rejections
16
+ process.on("unhandledRejection", (reason, promise) => {
17
+ const error = reason instanceof Error ? reason : new Error(String(reason));
18
+ Logger.handleError(error, "【Unhandled Promise Rejection】", false);
19
+ // Don't exit on unhandled rejection, log and continue
20
+ });
21
+ // Graceful shutdown handlers
22
+ const shutdown = async (signal) => {
23
+ Logger.log(`Received ${signal}, shutting down gracefully...`, "info");
24
+ try {
25
+ // Close all serial connections
26
+ const serialManager = SerialConnectionManager.getInstance();
27
+ await serialManager.closeAll();
28
+ Logger.log("All serial connections closed", "info");
29
+ }
30
+ catch (error) {
31
+ Logger.handleError(error, "Error during shutdown", false);
32
+ }
33
+ finally {
34
+ Logger.close();
35
+ process.exit(0);
36
+ }
37
+ };
38
+ process.on("SIGINT", () => shutdown("SIGINT"));
39
+ process.on("SIGTERM", () => shutdown("SIGTERM"));
40
+ try {
41
+ const serialMcpServer = new SerialMcpServer();
42
+ await serialMcpServer.run();
43
+ }
44
+ catch (error) {
45
+ // For initialization errors, exit the process
46
+ Logger.handleError(error, "【Serial MCP Server Error】", true);
47
+ }
48
+ }
49
+ main().catch((error) => {
50
+ // This should only happen if run() throws before server starts
51
+ Logger.handleError(error, "【Serial MCP Server Fatal Error】", true);
52
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,377 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { Logger } from "../utils/logger.js";
4
+ import { formatLogTimestamp, formatLogDate, parseLogTimestamp } from "../utils/time-format.js";
5
+ import { splitCompleteSerialLines } from "../utils/serial-line-split.js";
6
+ import { randomUUID } from "node:crypto";
7
+ /** 串口纯文本日志:YYYYMMDDHHmmssSSS >>>|<内容(发/收) */
8
+ const SERIAL_CONTENT_LINE_REGEX = /^(\d{17})\s(>>>|<<<)\s(.*)$/;
9
+ /** 旧版行式日志(兼容解析) */
10
+ const LEGACY_LINE_LOG_REGEX = /^\[([^\]]+)\]\s+(READ|WRITE|RECV|CONNECT|DISCONNECT)\s+(OK|FAIL)\s+(\S+)\s+\|\s(.*)$/;
11
+ /**
12
+ * History Service for managing serial port operation history
13
+ * - history.json:结构化操作审计
14
+ * - {port}_{YYYYMMDD}.log:纯文本串口内容,按天切分,发送 `<<<`、接收 `>>>`
15
+ */
16
+ /** 字符统计日志:每行最多 20 对 `<时间戳,字符数>`,字符数等宽右对齐 */
17
+ const CHAR_COUNT_PAIRS_PER_LINE = 20;
18
+ /** 字符数字段等宽位数(左侧补零) */
19
+ const CHAR_COUNT_FIELD_WIDTH = 6;
20
+ export class HistoryService {
21
+ static instance;
22
+ historyDir;
23
+ historyFile;
24
+ maxHistorySize = 1000;
25
+ history = [];
26
+ /** 字符统计待写入缓冲:portPath → ["<时间戳,字符数>", ...] */
27
+ charCountPendingPairs = new Map();
28
+ constructor() {
29
+ this.historyDir = path.join(process.cwd(), ".serial-history");
30
+ this.historyFile = path.join(this.historyDir, "history.json");
31
+ if (!fs.existsSync(this.historyDir)) {
32
+ fs.mkdirSync(this.historyDir, { mode: 0o700, recursive: true });
33
+ }
34
+ this.loadHistory();
35
+ }
36
+ static getInstance() {
37
+ if (!HistoryService.instance) {
38
+ HistoryService.instance = new HistoryService();
39
+ }
40
+ return HistoryService.instance;
41
+ }
42
+ /**
43
+ * 串口路径 → 安全文件名(如 /dev/ttyUSB0 → dev_ttyUSB0)
44
+ */
45
+ portPathToSafeName(portPath) {
46
+ return portPath.replace(/^\//, "").replace(/\//g, "_");
47
+ }
48
+ /**
49
+ * 串口路径 + 日期 → 日志文件路径(如 dev_ttyUSB0_20260709.log)
50
+ */
51
+ getPortLogPath(portPath, date = new Date()) {
52
+ const safeName = this.portPathToSafeName(portPath);
53
+ const dayStr = formatLogDate(date);
54
+ return path.join(this.historyDir, `${safeName}_${dayStr}.log`);
55
+ }
56
+ /**
57
+ * 串口路径 + 日期 → 字符统计文件路径(如 dev_ttyUSB0_20260709.chars.log)
58
+ * 命名规则与纯文本日志一致,扩展名为 .chars.log
59
+ */
60
+ getPortCharCountLogPath(portPath, date = new Date()) {
61
+ const safeName = this.portPathToSafeName(portPath);
62
+ const dayStr = formatLogDate(date);
63
+ return path.join(this.historyDir, `${safeName}_${dayStr}.chars.log`);
64
+ }
65
+ /**
66
+ * 格式化单条字符统计:`<YYYYMMDDHHmmssSSS, chars>`(字符数等宽)
67
+ */
68
+ formatCharCountPair(timeStr, charCount) {
69
+ const countStr = String(charCount).padStart(CHAR_COUNT_FIELD_WIDTH, "0");
70
+ return `<${timeStr},${countStr}>`;
71
+ }
72
+ /**
73
+ * 追加一条 3 秒窗口字符统计记录;满 20 对自动换行写入文件
74
+ */
75
+ appendCharCountEntry(portPath, timestamp, charCount) {
76
+ try {
77
+ const timeStr = formatLogTimestamp(new Date(timestamp));
78
+ const pair = this.formatCharCountPair(timeStr, charCount);
79
+ const pending = this.charCountPendingPairs.get(portPath) || [];
80
+ pending.push(pair);
81
+ this.charCountPendingPairs.set(portPath, pending);
82
+ if (pending.length >= CHAR_COUNT_PAIRS_PER_LINE) {
83
+ this.flushCharCountBuffer(portPath, timestamp);
84
+ }
85
+ }
86
+ catch (error) {
87
+ Logger.log(`Failed to append char count log: ${error.message}`, "error");
88
+ }
89
+ }
90
+ /**
91
+ * 将待写入的字符统计缓冲刷入文件(断开连接或换天时调用)
92
+ */
93
+ flushCharCountBuffer(portPath, timestamp = Date.now()) {
94
+ const pending = this.charCountPendingPairs.get(portPath);
95
+ if (!pending || pending.length === 0) {
96
+ return;
97
+ }
98
+ try {
99
+ const logFile = this.getPortCharCountLogPath(portPath, new Date(timestamp));
100
+ const line = pending.join(" ") + "\n";
101
+ fs.appendFileSync(logFile, line, "utf-8");
102
+ this.charCountPendingPairs.set(portPath, []);
103
+ }
104
+ catch (error) {
105
+ Logger.log(`Failed to flush char count log: ${error.message}`, "error");
106
+ }
107
+ }
108
+ /**
109
+ * 列出某串口的全部日志文件(含按天文件与旧版无日期文件)
110
+ */
111
+ listPortLogFiles(portPath) {
112
+ if (!fs.existsSync(this.historyDir)) {
113
+ return [];
114
+ }
115
+ const safeName = this.portPathToSafeName(portPath);
116
+ const datedPattern = new RegExp(`^${safeName}_\\d{8}\\.log$`);
117
+ const files = [];
118
+ for (const name of fs.readdirSync(this.historyDir)) {
119
+ if (name === `${safeName}.log` || datedPattern.test(name)) {
120
+ files.push(path.join(this.historyDir, name));
121
+ }
122
+ }
123
+ return files.sort();
124
+ }
125
+ inferPortFromLogFileName(fileName) {
126
+ if (fileName === "serial.log" || fileName === "history.json") {
127
+ return undefined;
128
+ }
129
+ const dated = fileName.match(/^(.+)_(\d{8})\.log$/);
130
+ if (dated) {
131
+ return `/${dated[1].replace(/_/g, "/")}`;
132
+ }
133
+ if (fileName.endsWith(".log")) {
134
+ return `/${fileName.slice(0, -4).replace(/_/g, "/")}`;
135
+ }
136
+ return undefined;
137
+ }
138
+ getHistoryDir() {
139
+ return this.historyDir;
140
+ }
141
+ loadHistory() {
142
+ try {
143
+ if (fs.existsSync(this.historyFile)) {
144
+ const data = fs.readFileSync(this.historyFile, "utf-8");
145
+ if (data.trim()) {
146
+ this.history = JSON.parse(data);
147
+ if (!Array.isArray(this.history)) {
148
+ this.history = [];
149
+ }
150
+ this.history = this.history.map((h) => ({
151
+ ...h,
152
+ time: h.time || formatLogTimestamp(new Date(h.timestamp)),
153
+ }));
154
+ }
155
+ else {
156
+ this.history = [];
157
+ }
158
+ }
159
+ else {
160
+ this.history = [];
161
+ }
162
+ }
163
+ catch (error) {
164
+ Logger.log(`Failed to load history: ${error.message}`, "error");
165
+ this.history = [];
166
+ }
167
+ }
168
+ saveHistory() {
169
+ try {
170
+ if (!fs.existsSync(this.historyDir)) {
171
+ fs.mkdirSync(this.historyDir, { mode: 0o700, recursive: true });
172
+ }
173
+ fs.writeFileSync(this.historyFile, JSON.stringify(this.history, null, 2), "utf-8");
174
+ }
175
+ catch (error) {
176
+ Logger.log(`Failed to save history: ${error.message}`, "error");
177
+ }
178
+ }
179
+ /**
180
+ * 追加串口纯文本内容(发送 <<<,接收 >>>)
181
+ * 多行输入会拆成多条,每条独立带时间戳
182
+ */
183
+ appendSerialContent(portPath, content, direction, timestamp = Date.now()) {
184
+ const parts = splitCompleteSerialLines(content);
185
+ if (parts.length === 0) {
186
+ return;
187
+ }
188
+ try {
189
+ const logFile = this.getPortLogPath(portPath, new Date(timestamp));
190
+ const timeStr = formatLogTimestamp(new Date(timestamp));
191
+ const arrow = direction === "tx" ? "<<<" : ">>>";
192
+ const lines = parts.map((part) => `${timeStr} ${arrow} ${part}`).join("\n") + "\n";
193
+ fs.appendFileSync(logFile, lines, "utf-8");
194
+ }
195
+ catch (error) {
196
+ Logger.log(`Failed to append serial content log: ${error.message}`, "error");
197
+ }
198
+ }
199
+ /**
200
+ * 解析单行串口纯文本日志
201
+ */
202
+ parseLogLine(line, portPath) {
203
+ const trimmed = line.trim();
204
+ if (!trimmed)
205
+ return null;
206
+ const serialMatch = trimmed.match(SERIAL_CONTENT_LINE_REGEX);
207
+ if (serialMatch) {
208
+ const [, timeStr, arrow, data] = serialMatch;
209
+ return {
210
+ timestamp: parseLogTimestamp(timeStr),
211
+ time: timeStr,
212
+ line: trimmed,
213
+ data,
214
+ direction: arrow === "<<<" ? "tx" : "rx",
215
+ portPath,
216
+ };
217
+ }
218
+ const legacyMatch = trimmed.match(LEGACY_LINE_LOG_REGEX);
219
+ if (legacyMatch) {
220
+ const [, timeStr, op, status, connectionName, data] = legacyMatch;
221
+ return {
222
+ timestamp: parseLogTimestamp(timeStr),
223
+ time: timeStr,
224
+ line: trimmed,
225
+ data: data.replace(/\\r/g, "\r").replace(/\\n/g, "\n"),
226
+ portPath,
227
+ operation: op.toLowerCase(),
228
+ success: status === "OK",
229
+ connectionName,
230
+ };
231
+ }
232
+ return null;
233
+ }
234
+ /**
235
+ * 读取指定串口(或全部 *.log)的纯文本日志
236
+ */
237
+ readAllLogLines(portPath) {
238
+ const logFiles = [];
239
+ if (portPath) {
240
+ for (const filePath of this.listPortLogFiles(portPath)) {
241
+ logFiles.push({ filePath, portPath });
242
+ }
243
+ }
244
+ else if (fs.existsSync(this.historyDir)) {
245
+ for (const name of fs.readdirSync(this.historyDir)) {
246
+ if (!name.endsWith(".log"))
247
+ continue;
248
+ const inferredPort = this.inferPortFromLogFileName(name);
249
+ if (!inferredPort)
250
+ continue;
251
+ logFiles.push({
252
+ filePath: path.join(this.historyDir, name),
253
+ portPath: inferredPort,
254
+ });
255
+ }
256
+ }
257
+ const lines = [];
258
+ for (const { filePath, portPath: inferred } of logFiles) {
259
+ if (!fs.existsSync(filePath))
260
+ continue;
261
+ const content = fs.readFileSync(filePath, "utf-8");
262
+ for (const rawLine of content.split("\n")) {
263
+ const parsed = this.parseLogLine(rawLine, inferred);
264
+ if (parsed)
265
+ lines.push(parsed);
266
+ }
267
+ }
268
+ return lines.sort((a, b) => a.timestamp - b.timestamp);
269
+ }
270
+ addHistory(connectionName, operation, data, success = true, error, duration, options) {
271
+ const timestamp = Date.now();
272
+ const record = {
273
+ id: randomUUID(),
274
+ timestamp,
275
+ time: formatLogTimestamp(new Date(timestamp)),
276
+ connectionName,
277
+ operation,
278
+ data: data ? (data.length > 1000 ? data.substring(0, 1000) + "..." : data) : undefined,
279
+ dataLength: data?.length,
280
+ success,
281
+ error,
282
+ duration,
283
+ options,
284
+ };
285
+ this.history.push(record);
286
+ if (this.history.length > this.maxHistorySize) {
287
+ this.history = this.history.slice(-this.maxHistorySize);
288
+ }
289
+ this.saveHistory();
290
+ return record.id;
291
+ }
292
+ getHistoryById(id) {
293
+ return this.history.find((h) => h.id === id);
294
+ }
295
+ listHistory(connectionName, operation, limit, offset) {
296
+ let filtered = this.history;
297
+ if (connectionName) {
298
+ filtered = filtered.filter((h) => h.connectionName === connectionName);
299
+ }
300
+ if (operation) {
301
+ filtered = filtered.filter((h) => h.operation === operation);
302
+ }
303
+ filtered = filtered.sort((a, b) => b.timestamp - a.timestamp);
304
+ if (offset !== undefined) {
305
+ filtered = filtered.slice(offset);
306
+ }
307
+ if (limit !== undefined) {
308
+ filtered = filtered.slice(0, limit);
309
+ }
310
+ return filtered;
311
+ }
312
+ /**
313
+ * 按时间段查询串口纯文本日志(闭区间)
314
+ */
315
+ listHistoryBetween(startTime, endTime, portPath) {
316
+ if (startTime > endTime) {
317
+ throw new Error("startTime must be less than or equal to endTime");
318
+ }
319
+ return this.readAllLogLines(portPath).filter((h) => h.timestamp >= startTime && h.timestamp <= endTime);
320
+ }
321
+ exportHistory(exportPath, options = {}) {
322
+ const { startTime, endTime, portPath, format = "json" } = options;
323
+ let records;
324
+ if (startTime !== undefined && endTime !== undefined) {
325
+ records = this.listHistoryBetween(startTime, endTime, portPath);
326
+ }
327
+ else {
328
+ records = this.readAllLogLines(portPath);
329
+ }
330
+ const dir = path.dirname(exportPath);
331
+ if (!fs.existsSync(dir)) {
332
+ fs.mkdirSync(dir, { recursive: true });
333
+ }
334
+ if (format === "text") {
335
+ const lines = records.map((h) => h.line);
336
+ fs.writeFileSync(exportPath, lines.join("\n") + (lines.length ? "\n" : ""), "utf-8");
337
+ }
338
+ else {
339
+ const payload = {
340
+ exportedAt: formatLogTimestamp(),
341
+ count: records.length,
342
+ lines: records.map((h) => h.line),
343
+ records,
344
+ };
345
+ fs.writeFileSync(exportPath, JSON.stringify(payload, null, 2), "utf-8");
346
+ }
347
+ return { path: exportPath, count: records.length, format };
348
+ }
349
+ getHistoryCount(connectionName, operation) {
350
+ let filtered = this.history;
351
+ if (connectionName) {
352
+ filtered = filtered.filter((h) => h.connectionName === connectionName);
353
+ }
354
+ if (operation) {
355
+ filtered = filtered.filter((h) => h.operation === operation);
356
+ }
357
+ return filtered.length;
358
+ }
359
+ clearHistory(connectionName, operation) {
360
+ const beforeCount = this.history.length;
361
+ if (connectionName || operation) {
362
+ this.history = this.history.filter((h) => {
363
+ if (connectionName && h.connectionName !== connectionName)
364
+ return true;
365
+ if (operation && h.operation !== operation)
366
+ return true;
367
+ return false;
368
+ });
369
+ }
370
+ else {
371
+ this.history = [];
372
+ }
373
+ const afterCount = this.history.length;
374
+ this.saveHistory();
375
+ return beforeCount - afterCount;
376
+ }
377
+ }