// ApiTraceDebugger.js const fs = require('fs'); const path = require('path'); const { app } = require('electron'); // เก็บ reference ของฟังก์ชันดั้งเดิมไว้ก่อนที่จะ patch เพื่อป้องกัน circular dependency const originalFs = { readFileSync: fs.readFileSync, writeFileSync: fs.writeFileSync, existsSync: fs.existsSync, mkdirSync: fs.mkdirSync, readdirSync: fs.readdirSync, unlinkSync: fs.unlinkSync, statSync: fs.statSync, createWriteStream: fs.createWriteStream }; const originalPath = { join: path.join, resolve: path.resolve, dirname: path.dirname, extname: path.extname, basename: path.basename, relative: path.relative }; /** * [ปรับปรุงใหม่] ระบบดีบั๊กสำหรับติดตามและบันทึก API Call ลงไฟล์แบบ Real-time * @class ApiTraceDebugger */ class ApiTraceDebugger { constructor() { this.isActive = false; this.logStream = null; // Stream สำหรับเขียนไฟล์ this.logFilePath = null; // Path ของไฟล์ Log ปัจจุบัน this.originalFunctions = new Map(); this.pluginsPath = this._getPluginsPath(); } /** * [ปรับปรุงใหม่] เริ่มการทำงาน, สร้างไฟล์ และเปิด Stream */ start() { if (this.isActive) { return; } try { // ตรวจสอบว่า app พร้อมใช้งาน if (!app || !app.getPath) { console.warn('[API TRACE] App ยังไม่พร้อม ข้าม API Trace initialization'); return; } // สร้างโฟลเดอร์สำหรับเก็บ Log ถ้ายังไม่มี const logDir = originalPath.join(app.getPath('userData'), 'logs', 'api-traces'); if (!originalFs.existsSync(logDir)) { originalFs.mkdirSync(logDir, { recursive: true }); } // สร้างชื่อไฟล์ Log ที่ไม่ซ้ำกัน const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); this.logFilePath = originalPath.join(logDir, `trace-${timestamp}.log`); // สร้าง Write Stream ไปยังไฟล์ Log this.logStream = originalFs.createWriteStream(this.logFilePath, { flags: 'a' }); this.isActive = true; this._writeHeader(); // เขียนข้อมูลเริ่มต้นลงไฟล์ console.log(`[API TRACE] REAL-TIME MODE: เริ่มบันทึก Log ไปที่ไฟล์: ${this.logFilePath}`); // เริ่มทำการ Patch ฟังก์ชันเป้าหมาย this._patchAllFunctions(); } catch (error) { console.error('[API TRACE] ไม่สามารถเริ่มระบบ Real-time logger ได้:', error); this.isActive = false; } } /** * [ปรับปรุงใหม่] หยุดการทำงานและปิด Stream */ stop() { if (!this.isActive) { return; } this.isActive = false; console.log('[API TRACE] หยุดการทำงานและกำลังคืนค่าฟังก์ชันดั้งเดิม...'); // คืนค่าฟังก์ชันดั้งเดิม this._unpatchAllFunctions(); // ปิด Stream และไฟล์ Log if (this.logStream) { this.logStream.end('\n--- LOGGING STOPPED ---\n'); this.logStream = null; console.log('[API TRACE] ปิดไฟล์ Log เรียบร้อยแล้ว'); } } /** * [เพิ่มใหม่] ฟังก์ชันสำหรับหา Path ของโฟลเดอร์ plugins * @private */ _getPluginsPath() { try { // ตรวจสอบว่า app พร้อมใช้งานหรือไม่ก่อน if (!app || !app.getPath) { console.warn('[API TRACE] App ยังไม่พร้อม ข้าม plugins path detection'); return null; } if (app.isPackaged) { // โหมด Production: โฟลเดอร์ plugins จะอยู่ข้างไฟล์ .exe // ใช้ originalPath เพื่อป้องกัน circular dependency return originalPath.join(originalPath.dirname(app.getPath('exe')), 'plugins'); } else { // โหมด Development: อยู่ใน AppData // ใช้ originalPath เพื่อป้องกัน circular dependency return originalPath.join(app.getPath('userData'), 'plugins'); } } catch (e) { console.warn('[API TRACE] ไม่สามารถหา Path ของโฟลเดอร์ plugins ได้:', e.message); return null; } } /** * [แก้ไข] เพิ่มการกรองโฟลเดอร์ plugins เข้าไป * ฟังก์ชันค้นหาไฟล์และบรรทัดที่เรียกใช้ (Call Site) * @private */ _getCallSite() { const originalPrepareStackTrace = Error.prepareStackTrace; try { Error.prepareStackTrace = (_, stack) => stack; const err = new Error(); const stack = err.stack; Error.prepareStackTrace = originalPrepareStackTrace; for (let i = 2; i < stack.length; i++) { const frame = stack[i]; const fileName = frame.getFileName(); if (fileName) { const isNodeModule = fileName.includes('node_modules'); const isInternal = fileName.startsWith('node:internal'); const isSelf = fileName.endsWith('ApiTraceDebugger.js'); // [แก้ไข] ตรวจสอบว่าเป็นไฟล์ในโฟลเดอร์ plugins หรือไม่ และใช้ originalPath const isPlugin = this.pluginsPath ? fileName.startsWith(this.pluginsPath) : false; if (!isNodeModule && !isInternal && !isSelf && !isPlugin) { // ใช้ originalPath เพื่อป้องกัน circular dependency const relativePath = originalPath.relative(process.cwd(), fileName); return `${relativePath}:${frame.getLineNumber()}`; } } } } catch (e) { Error.prepareStackTrace = originalPrepareStackTrace; } return 'unknown'; } /** * [ปรับปรุงใหม่] ฟังก์ชันภายในสำหรับบันทึก Log โดยจะเขียนลงไฟล์ทันที */ _logTrace(moduleName, functionName, args, result, error, callSite) { // ถ้า stream ไม่พร้อมทำงาน ให้ข้ามไป if (!this.logStream) { return; } const logType = error ? '[API-ERR ]' : '[API-CALL]'; const timestamp = new Date().toISOString(); // จัดรูปแบบ Arguments และ ผลลัพธ์ const formatArg = (arg) => { if (typeof arg === 'string') { if (arg.length > 150) return `'${arg.substring(0, 147)}...'`; return `'${arg}'`; } if (typeof arg === 'object' && arg !== null) return JSON.stringify(arg); return String(arg); }; const argsString = args.map(formatArg).join(', '); let outcomeString = ''; if (error) { outcomeString = `=> ERROR: ${error.message}`; } else { let resultStr = JSON.stringify(result); if (resultStr && resultStr.length > 200) { resultStr = resultStr.substring(0, 197) + '...'; } outcomeString = `=> RESULT: ${resultStr}`; } // สร้าง Log 1 บรรทัดและเขียนลง Stream const line = `${timestamp} ${logType} ${moduleName}.${functionName}(${argsString}) ${outcomeString} (from ${callSite})\n`; this.logStream.write(line); } /** * ฟังก์ชันภายในสำหรับทำการ Patch (แทนที่) ฟังก์ชันเป้าหมาย * @private */ _patchFunction(module, moduleName, functionName) { const originalFunction = module[functionName]; if (typeof originalFunction !== 'function' || this.originalFunctions.has(`${moduleName}.${functionName}`)) { return; } this.originalFunctions.set(`${moduleName}.${functionName}`, originalFunction); const self = this; const patchFunction = function (...args) { const callSite = self._getCallSite(); // [แก้ไข] เพิ่มการกรอง `plugins` เข้าไปในเงื่อนไข และใช้ originalPath const isNodeModule = callSite.includes('node_modules'); const isPlugin = self.pluginsPath ? callSite.startsWith(originalPath.relative(process.cwd(), self.pluginsPath)) : false; // ถ้ามาจาก node_modules หรือ plugins ให้ข้ามการบันทึก Log if (isNodeModule || isPlugin) { return originalFunction.apply(this, args); } let result, error = null; try { result = originalFunction.apply(this, args); } catch (e) { error = e; } self._logTrace(moduleName, functionName, args, result, error, callSite); if (error) { throw error; } return result; }; module[functionName] = patchFunction; } // ฟังก์ชันสำหรับวนลูป Patch (แยกออกมาเพื่อความสะอาด) _patchAllFunctions() { const modulesToTrace = { fs: ['readFileSync', 'writeFileSync', 'existsSync', 'mkdirSync', 'readdirSync', 'unlinkSync', 'statSync'], path: ['join', 'resolve', 'dirname', 'extname', 'basename'] }; for (const moduleName in modulesToTrace) { const functions = modulesToTrace[moduleName]; const module = require(moduleName); for (const functionName of functions) { this._patchFunction(module, moduleName, functionName); } } } // ฟังก์ชันสำหรับวนลูป Unpatch _unpatchAllFunctions() { for (const [key, originalFunction] of this.originalFunctions.entries()) { const [module, functionName] = key.split('.'); require(module)[functionName] = originalFunction; } this.originalFunctions.clear(); } // เขียน Header ลงไฟล์ Log _writeHeader() { if (!this.logStream) return; const header = ` =========================================== Chahuadev API Trace Log (Real-time) =========================================== Start Time : ${new Date().toISOString()} Platform : ${process.platform} Version : ${app.getVersion ? app.getVersion() : 'Unknown'} Log File : ${this.logFilePath} ------------------------------------------- `; this.logStream.write(header); } } module.exports = new ApiTraceDebugger();