| |
|
|
| const fs = require('fs'); |
| const path = require('path'); |
| const { app } = require('electron'); |
|
|
| |
| 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 |
| }; |
|
|
| |
| |
| |
| |
| class ApiTraceDebugger { |
| constructor() { |
| this.isActive = false; |
| this.logStream = null; |
| this.logFilePath = null; |
| this.originalFunctions = new Map(); |
| this.pluginsPath = this._getPluginsPath(); |
| } |
|
|
| |
| |
| |
| start() { |
| if (this.isActive) { return; } |
|
|
| try { |
| |
| if (!app || !app.getPath) { |
| console.warn('[API TRACE] App ยังไม่พร้อม ข้าม API Trace initialization'); |
| return; |
| } |
|
|
| |
| const logDir = originalPath.join(app.getPath('userData'), 'logs', 'api-traces'); |
| if (!originalFs.existsSync(logDir)) { |
| originalFs.mkdirSync(logDir, { recursive: true }); |
| } |
|
|
| |
| const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); |
| this.logFilePath = originalPath.join(logDir, `trace-${timestamp}.log`); |
|
|
| |
| this.logStream = originalFs.createWriteStream(this.logFilePath, { flags: 'a' }); |
|
|
| this.isActive = true; |
| this._writeHeader(); |
| console.log(`[API TRACE] REAL-TIME MODE: เริ่มบันทึก Log ไปที่ไฟล์: ${this.logFilePath}`); |
|
|
| |
| this._patchAllFunctions(); |
|
|
| } catch (error) { |
| console.error('[API TRACE] ไม่สามารถเริ่มระบบ Real-time logger ได้:', error); |
| this.isActive = false; |
| } |
| } |
|
|
| |
| |
| |
| stop() { |
| if (!this.isActive) { return; } |
| this.isActive = false; |
| console.log('[API TRACE] หยุดการทำงานและกำลังคืนค่าฟังก์ชันดั้งเดิม...'); |
|
|
| |
| this._unpatchAllFunctions(); |
|
|
| |
| if (this.logStream) { |
| this.logStream.end('\n--- LOGGING STOPPED ---\n'); |
| this.logStream = null; |
| console.log('[API TRACE] ปิดไฟล์ Log เรียบร้อยแล้ว'); |
| } |
| } |
|
|
| |
| |
| |
| |
| _getPluginsPath() { |
| try { |
| |
| if (!app || !app.getPath) { |
| console.warn('[API TRACE] App ยังไม่พร้อม ข้าม plugins path detection'); |
| return null; |
| } |
|
|
| if (app.isPackaged) { |
| |
| |
| return originalPath.join(originalPath.dirname(app.getPath('exe')), 'plugins'); |
| } else { |
| |
| |
| return originalPath.join(app.getPath('userData'), 'plugins'); |
| } |
| } catch (e) { |
| console.warn('[API TRACE] ไม่สามารถหา Path ของโฟลเดอร์ plugins ได้:', e.message); |
| return null; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| _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'); |
| |
| const isPlugin = this.pluginsPath ? fileName.startsWith(this.pluginsPath) : false; |
|
|
| if (!isNodeModule && !isInternal && !isSelf && !isPlugin) { |
| |
| const relativePath = originalPath.relative(process.cwd(), fileName); |
| return `${relativePath}:${frame.getLineNumber()}`; |
| } |
| } |
| } |
| } catch (e) { |
| Error.prepareStackTrace = originalPrepareStackTrace; |
| } |
| return 'unknown'; |
| } |
|
|
| |
| |
| |
| _logTrace(moduleName, functionName, args, result, error, callSite) { |
| |
| if (!this.logStream) { return; } |
|
|
| const logType = error ? '[API-ERR ]' : '[API-CALL]'; |
| const timestamp = new Date().toISOString(); |
|
|
| |
| 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}`; |
| } |
|
|
| |
| const line = `${timestamp} ${logType} ${moduleName}.${functionName}(${argsString}) ${outcomeString} (from ${callSite})\n`; |
| this.logStream.write(line); |
| } |
|
|
| |
| |
| |
| |
| _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(); |
|
|
| |
| const isNodeModule = callSite.includes('node_modules'); |
| const isPlugin = self.pluginsPath ? callSite.startsWith(originalPath.relative(process.cwd(), self.pluginsPath)) : false; |
|
|
| |
| 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; |
| } |
|
|
| |
| _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); |
| } |
| } |
| } |
|
|
| |
| _unpatchAllFunctions() { |
| for (const [key, originalFunction] of this.originalFunctions.entries()) { |
| const [module, functionName] = key.split('.'); |
| require(module)[functionName] = originalFunction; |
| } |
| this.originalFunctions.clear(); |
| } |
|
|
| |
| _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(); |