chahuadev commited on
Commit
857cdcf
·
1 Parent(s): 0c3905c

Update README

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +7 -60
  2. .gitignore +84 -0
  3. .wslconfig +11 -0
  4. ApiTraceDebugger.js +284 -0
  5. LICENSE.md +54 -0
  6. README.md +263 -3
  7. app.html +0 -0
  8. auth-dialog.js +171 -0
  9. backend/utils/inspector-worker.js +169 -0
  10. backend/utils/project-inspector-ipc.js +247 -0
  11. backend/utils/project-inspector.js +1813 -0
  12. build-desktop.bat +220 -0
  13. build-linux-wsl.sh +90 -0
  14. build_assets/plugins/.gitkeep +2 -0
  15. checksums.json +13 -0
  16. checksums.sig +1 -0
  17. config/default.json +102 -0
  18. config/obfuscator.config.js +143 -0
  19. config/production.json +102 -0
  20. debug-manager.js +501 -0
  21. debugger.html +884 -0
  22. debugger.js +659 -0
  23. generate-checksums.js +73 -0
  24. generate-manifests.js +124 -0
  25. junk-map-layout.json +242 -0
  26. main.js +2464 -0
  27. modules/button-generator.js +621 -0
  28. modules/cache-manager.js +350 -0
  29. modules/callback-hub.js +202 -0
  30. modules/callback-logger.js +147 -0
  31. modules/cli.js +301 -0
  32. modules/context-manager.js +368 -0
  33. modules/error-handler.js +380 -0
  34. modules/executor.js +242 -0
  35. modules/health-monitor.js +207 -0
  36. modules/key-system.js +167 -0
  37. modules/plugin-manager.js +96 -0
  38. modules/retry-controller.js +131 -0
  39. modules/rollback-manager.js +274 -0
  40. modules/security-logger.js +346 -0
  41. modules/svg-icons.js +253 -0
  42. modules/system-detector.js +1157 -0
  43. modules/tamper-detector.js +387 -0
  44. npm-runner.bat +144 -0
  45. package.json +261 -0
  46. packages/@chahuadev/framework/LICENSE.md +54 -0
  47. packages/@chahuadev/framework/README.md +143 -0
  48. packages/@chahuadev/framework/index.js +26 -0
  49. packages/@chahuadev/framework/install.js +73 -0
  50. packages/@chahuadev/framework/package.json +16 -0
.gitattributes CHANGED
@@ -1,60 +1,7 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.avro filter=lfs diff=lfs merge=lfs -text
4
- *.bin filter=lfs diff=lfs merge=lfs -text
5
- *.bz2 filter=lfs diff=lfs merge=lfs -text
6
- *.ckpt filter=lfs diff=lfs merge=lfs -text
7
- *.ftz filter=lfs diff=lfs merge=lfs -text
8
- *.gz filter=lfs diff=lfs merge=lfs -text
9
- *.h5 filter=lfs diff=lfs merge=lfs -text
10
- *.joblib filter=lfs diff=lfs merge=lfs -text
11
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
12
- *.lz4 filter=lfs diff=lfs merge=lfs -text
13
- *.mds filter=lfs diff=lfs merge=lfs -text
14
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
15
- *.model filter=lfs diff=lfs merge=lfs -text
16
- *.msgpack filter=lfs diff=lfs merge=lfs -text
17
- *.npy filter=lfs diff=lfs merge=lfs -text
18
- *.npz filter=lfs diff=lfs merge=lfs -text
19
- *.onnx filter=lfs diff=lfs merge=lfs -text
20
- *.ot filter=lfs diff=lfs merge=lfs -text
21
- *.parquet filter=lfs diff=lfs merge=lfs -text
22
- *.pb filter=lfs diff=lfs merge=lfs -text
23
- *.pickle filter=lfs diff=lfs merge=lfs -text
24
- *.pkl filter=lfs diff=lfs merge=lfs -text
25
- *.pt filter=lfs diff=lfs merge=lfs -text
26
- *.pth filter=lfs diff=lfs merge=lfs -text
27
- *.rar filter=lfs diff=lfs merge=lfs -text
28
- *.safetensors filter=lfs diff=lfs merge=lfs -text
29
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
30
- *.tar.* filter=lfs diff=lfs merge=lfs -text
31
- *.tar filter=lfs diff=lfs merge=lfs -text
32
- *.tflite filter=lfs diff=lfs merge=lfs -text
33
- *.tgz filter=lfs diff=lfs merge=lfs -text
34
- *.wasm filter=lfs diff=lfs merge=lfs -text
35
- *.xz filter=lfs diff=lfs merge=lfs -text
36
- *.zip filter=lfs diff=lfs merge=lfs -text
37
- *.zst filter=lfs diff=lfs merge=lfs -text
38
- *tfevents* filter=lfs diff=lfs merge=lfs -text
39
- # Audio files - uncompressed
40
- *.pcm filter=lfs diff=lfs merge=lfs -text
41
- *.sam filter=lfs diff=lfs merge=lfs -text
42
- *.raw filter=lfs diff=lfs merge=lfs -text
43
- # Audio files - compressed
44
- *.aac filter=lfs diff=lfs merge=lfs -text
45
- *.flac filter=lfs diff=lfs merge=lfs -text
46
- *.mp3 filter=lfs diff=lfs merge=lfs -text
47
- *.ogg filter=lfs diff=lfs merge=lfs -text
48
- *.wav filter=lfs diff=lfs merge=lfs -text
49
- # Image files - uncompressed
50
- *.bmp filter=lfs diff=lfs merge=lfs -text
51
- *.gif filter=lfs diff=lfs merge=lfs -text
52
- *.png filter=lfs diff=lfs merge=lfs -text
53
- *.tiff filter=lfs diff=lfs merge=lfs -text
54
- # Image files - compressed
55
- *.jpg filter=lfs diff=lfs merge=lfs -text
56
- *.jpeg filter=lfs diff=lfs merge=lfs -text
57
- *.webp filter=lfs diff=lfs merge=lfs -text
58
- # Video files - compressed
59
- *.mp4 filter=lfs diff=lfs merge=lfs -text
60
- *.webm filter=lfs diff=lfs merge=lfs -text
 
1
+ chahuadev-junk-sweeper1.png filter=lfs diff=lfs merge=lfs -text
2
+ chahuadev-junk-sweeper.png filter=lfs diff=lfs merge=lfs -text
3
+ icons/icon.png filter=lfs diff=lfs merge=lfs -text
4
+ icons/logo.ico filter=lfs diff=lfs merge=lfs -text
5
+ icons/logo.png filter=lfs diff=lfs merge=lfs -text
6
+ icons/icon.ico filter=lfs diff=lfs merge=lfs -text
7
+ icons/app-icon.png filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dependencies
2
+ node_modules/
3
+ npm-debug.log*
4
+ yarn-debug.log*
5
+ yarn-error.log*
6
+ package-lock.json
7
+ yarn.lock
8
+
9
+ # Runtime
10
+ *.log
11
+ logs/
12
+ pids/
13
+ *.pid
14
+ *.seed
15
+ *.pid.lock
16
+
17
+ # Coverage and testing
18
+ coverage/
19
+ .nyc_output/
20
+ .jest/
21
+
22
+ # Environment
23
+ .env
24
+ .env.local
25
+ .env.development.local
26
+ .env.test.local
27
+ .env.production.local
28
+
29
+ # Editor files
30
+ .vscode/
31
+ .idea/
32
+ *.swp
33
+ *.swo
34
+ *~
35
+
36
+ # OS generated files
37
+ .DS_Store
38
+ .DS_Store?
39
+ ._*
40
+ .Spotlight-V100
41
+ .Trashes
42
+ ehthumbs.db
43
+ Thumbs.db
44
+
45
+ # Backup directories (created by this tool)
46
+ emoji-backup-*/
47
+ backup-*/
48
+
49
+ # Temporary test files
50
+ test/temp/
51
+ test/fixtures/temp/
52
+ test
53
+
54
+ # Distribution
55
+ dist/
56
+ build/
57
+
58
+ # NPM
59
+ .npm
60
+ .npmrc
61
+
62
+ # Ignore binary images
63
+ icons/
64
+
65
+ # Layout files (auto-generated per project)
66
+ layouts/*.json
67
+
68
+ # Python runtime — downloaded at build time, never committed
69
+ # Run: npm run download-python-win (Windows only, ~12 MB)
70
+ runtimes/
71
+
72
+ # Python compiled cache
73
+ __pycache__/
74
+ *.pyc
75
+ *.pyo
76
+
77
+ # .NET build artifacts
78
+ engines/cs_scanner/bin/
79
+ engines/cs_scanner/obj/
80
+ *.pyd
81
+ logo.ico
82
+ logo.png
83
+
84
+ icon.png
.wslconfig ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [interop]
2
+ appendWindowsPath = true
3
+
4
+ [automount]
5
+ enabled = true
6
+ root = /mnt
7
+ options = "metadata,umask=0022,fmask=0011"
8
+ mountFsTab = true
9
+
10
+ [filesystem]
11
+ umask = 0022
ApiTraceDebugger.js ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ApiTraceDebugger.js
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { app } = require('electron');
6
+
7
+ // เก็บ reference ของฟังก์ชันดั้งเดิมไว้ก่อนที่จะ patch เพื่อป้องกัน circular dependency
8
+ const originalFs = {
9
+ readFileSync: fs.readFileSync,
10
+ writeFileSync: fs.writeFileSync,
11
+ existsSync: fs.existsSync,
12
+ mkdirSync: fs.mkdirSync,
13
+ readdirSync: fs.readdirSync,
14
+ unlinkSync: fs.unlinkSync,
15
+ statSync: fs.statSync,
16
+ createWriteStream: fs.createWriteStream
17
+ };
18
+
19
+ const originalPath = {
20
+ join: path.join,
21
+ resolve: path.resolve,
22
+ dirname: path.dirname,
23
+ extname: path.extname,
24
+ basename: path.basename,
25
+ relative: path.relative
26
+ };
27
+
28
+ /**
29
+ * [ปรับปรุงใหม่] ระบบดีบั๊กสำหรับติดตามและบันทึก API Call ลงไฟล์แบบ Real-time
30
+ * @class ApiTraceDebugger
31
+ */
32
+ class ApiTraceDebugger {
33
+ constructor() {
34
+ this.isActive = false;
35
+ this.logStream = null; // Stream สำหรับเขียนไฟล์
36
+ this.logFilePath = null; // Path ของไฟล์ Log ปัจจุบัน
37
+ this.originalFunctions = new Map();
38
+ this.pluginsPath = this._getPluginsPath();
39
+ }
40
+
41
+ /**
42
+ * [ปรับปรุงใหม่] เริ่มการทำงาน, สร้างไฟล์ และเปิด Stream
43
+ */
44
+ start() {
45
+ if (this.isActive) { return; }
46
+
47
+ try {
48
+ // ตรวจสอบว่า app พร้อมใช้งาน
49
+ if (!app || !app.getPath) {
50
+ console.warn('[API TRACE] App ยังไม่พร้อม ข้าม API Trace initialization');
51
+ return;
52
+ }
53
+
54
+ // สร้างโฟลเดอร์สำหรับเก็บ Log ถ้ายังไม่มี
55
+ const logDir = originalPath.join(app.getPath('userData'), 'logs', 'api-traces');
56
+ if (!originalFs.existsSync(logDir)) {
57
+ originalFs.mkdirSync(logDir, { recursive: true });
58
+ }
59
+
60
+ // สร้างชื่อไฟล์ Log ที่ไม่ซ้ำกัน
61
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
62
+ this.logFilePath = originalPath.join(logDir, `trace-${timestamp}.log`);
63
+
64
+ // สร้าง Write Stream ไปยังไฟล์ Log
65
+ this.logStream = originalFs.createWriteStream(this.logFilePath, { flags: 'a' });
66
+
67
+ this.isActive = true;
68
+ this._writeHeader(); // เขียนข้อมูลเริ่มต้นลงไฟล์
69
+ console.log(`[API TRACE] REAL-TIME MODE: เริ่มบันทึก Log ไปที่ไฟล์: ${this.logFilePath}`);
70
+
71
+ // เริ่มทำการ Patch ฟังก์ชันเป้าหมาย
72
+ this._patchAllFunctions();
73
+
74
+ } catch (error) {
75
+ console.error('[API TRACE] ไม่สามารถเริ่มระบบ Real-time logger ได้:', error);
76
+ this.isActive = false;
77
+ }
78
+ }
79
+
80
+ /**
81
+ * [ปรับปรุงใหม่] หยุดการทำงานและปิด Stream
82
+ */
83
+ stop() {
84
+ if (!this.isActive) { return; }
85
+ this.isActive = false;
86
+ console.log('[API TRACE] หยุดการทำงานและกำลังคืนค่าฟังก์ชันดั้งเดิม...');
87
+
88
+ // คืนค่าฟังก์ชันดั้งเดิม
89
+ this._unpatchAllFunctions();
90
+
91
+ // ปิด Stream และไฟล์ Log
92
+ if (this.logStream) {
93
+ this.logStream.end('\n--- LOGGING STOPPED ---\n');
94
+ this.logStream = null;
95
+ console.log('[API TRACE] ปิดไฟล์ Log เรียบร้อยแล้ว');
96
+ }
97
+ }
98
+
99
+ /**
100
+ * [เพิ่มใหม่] ฟังก์ชันสำหรับหา Path ของโฟลเดอร์ plugins
101
+ * @private
102
+ */
103
+ _getPluginsPath() {
104
+ try {
105
+ // ตรวจสอบว่า app พร้อมใช้งานหรือไม่ก่อน
106
+ if (!app || !app.getPath) {
107
+ console.warn('[API TRACE] App ยังไม่พร้อม ข้าม plugins path detection');
108
+ return null;
109
+ }
110
+
111
+ if (app.isPackaged) {
112
+ // โหมด Production: โฟลเดอร์ plugins จะอยู่ข้างไฟล์ .exe
113
+ // ใช้ originalPath เพื่อป้องกัน circular dependency
114
+ return originalPath.join(originalPath.dirname(app.getPath('exe')), 'plugins');
115
+ } else {
116
+ // โหมด Development: อยู่ใน AppData
117
+ // ใช้ originalPath เพื่อป้องกัน circular dependency
118
+ return originalPath.join(app.getPath('userData'), 'plugins');
119
+ }
120
+ } catch (e) {
121
+ console.warn('[API TRACE] ไม่สามารถหา Path ของโฟลเดอร์ plugins ได้:', e.message);
122
+ return null;
123
+ }
124
+ }
125
+
126
+ /**
127
+ * [แก้ไข] เพิ่มการกรองโฟลเดอร์ plugins เข้าไป
128
+ * ฟังก์ชันค้นหาไฟล์และบรรทัดที่เรียกใช้ (Call Site)
129
+ * @private
130
+ */
131
+ _getCallSite() {
132
+ const originalPrepareStackTrace = Error.prepareStackTrace;
133
+ try {
134
+ Error.prepareStackTrace = (_, stack) => stack;
135
+ const err = new Error();
136
+ const stack = err.stack;
137
+ Error.prepareStackTrace = originalPrepareStackTrace;
138
+
139
+ for (let i = 2; i < stack.length; i++) {
140
+ const frame = stack[i];
141
+ const fileName = frame.getFileName();
142
+
143
+ if (fileName) {
144
+ const isNodeModule = fileName.includes('node_modules');
145
+ const isInternal = fileName.startsWith('node:internal');
146
+ const isSelf = fileName.endsWith('ApiTraceDebugger.js');
147
+ // [แก้ไข] ตรวจสอบว่าเป็นไฟล์ในโฟลเดอร์ plugins หรือไม่ และใช้ originalPath
148
+ const isPlugin = this.pluginsPath ? fileName.startsWith(this.pluginsPath) : false;
149
+
150
+ if (!isNodeModule && !isInternal && !isSelf && !isPlugin) {
151
+ // ใช้ originalPath เพื่อป้องกัน circular dependency
152
+ const relativePath = originalPath.relative(process.cwd(), fileName);
153
+ return `${relativePath}:${frame.getLineNumber()}`;
154
+ }
155
+ }
156
+ }
157
+ } catch (e) {
158
+ Error.prepareStackTrace = originalPrepareStackTrace;
159
+ }
160
+ return 'unknown';
161
+ }
162
+
163
+ /**
164
+ * [ปรับปรุงใหม่] ฟังก์ชันภายในสำหรับบันทึก Log โดยจะเขียนลงไฟล์ทันที
165
+ */
166
+ _logTrace(moduleName, functionName, args, result, error, callSite) {
167
+ // ถ้า stream ไม่พร้อมทำงาน ให้ข้ามไป
168
+ if (!this.logStream) { return; }
169
+
170
+ const logType = error ? '[API-ERR ]' : '[API-CALL]';
171
+ const timestamp = new Date().toISOString();
172
+
173
+ // จัดรูปแบบ Arguments และ ผลลัพธ์
174
+ const formatArg = (arg) => {
175
+ if (typeof arg === 'string') {
176
+ if (arg.length > 150) return `'${arg.substring(0, 147)}...'`;
177
+ return `'${arg}'`;
178
+ }
179
+ if (typeof arg === 'object' && arg !== null) return JSON.stringify(arg);
180
+ return String(arg);
181
+ };
182
+ const argsString = args.map(formatArg).join(', ');
183
+
184
+ let outcomeString = '';
185
+ if (error) {
186
+ outcomeString = `=> ERROR: ${error.message}`;
187
+ } else {
188
+ let resultStr = JSON.stringify(result);
189
+ if (resultStr && resultStr.length > 200) {
190
+ resultStr = resultStr.substring(0, 197) + '...';
191
+ }
192
+ outcomeString = `=> RESULT: ${resultStr}`;
193
+ }
194
+
195
+ // สร้าง Log 1 บรรทัดและเขียนลง Stream
196
+ const line = `${timestamp} ${logType} ${moduleName}.${functionName}(${argsString}) ${outcomeString} (from ${callSite})\n`;
197
+ this.logStream.write(line);
198
+ }
199
+
200
+ /**
201
+ * ฟังก์ชันภายในสำหรับทำการ Patch (แทนที่) ฟังก์ชันเป้าหมาย
202
+ * @private
203
+ */
204
+ _patchFunction(module, moduleName, functionName) {
205
+ const originalFunction = module[functionName];
206
+
207
+ if (typeof originalFunction !== 'function' || this.originalFunctions.has(`${moduleName}.${functionName}`)) {
208
+ return;
209
+ }
210
+
211
+ this.originalFunctions.set(`${moduleName}.${functionName}`, originalFunction);
212
+
213
+ const self = this;
214
+ const patchFunction = function (...args) {
215
+ const callSite = self._getCallSite();
216
+
217
+ // [แก้ไข] เพิ่มการกรอง `plugins` เข้าไปในเงื่อนไข และใช้ originalPath
218
+ const isNodeModule = callSite.includes('node_modules');
219
+ const isPlugin = self.pluginsPath ? callSite.startsWith(originalPath.relative(process.cwd(), self.pluginsPath)) : false;
220
+
221
+ // ถ้ามาจาก node_modules ��รือ plugins ให้ข้ามการบันทึก Log
222
+ if (isNodeModule || isPlugin) {
223
+ return originalFunction.apply(this, args);
224
+ }
225
+
226
+ let result, error = null;
227
+ try {
228
+ result = originalFunction.apply(this, args);
229
+ } catch (e) {
230
+ error = e;
231
+ }
232
+
233
+ self._logTrace(moduleName, functionName, args, result, error, callSite);
234
+
235
+ if (error) { throw error; }
236
+ return result;
237
+ };
238
+
239
+ module[functionName] = patchFunction;
240
+ }
241
+
242
+ // ฟังก์ชันสำหรับวนลูป Patch (แยกออกมาเพื่อความสะอาด)
243
+ _patchAllFunctions() {
244
+ const modulesToTrace = {
245
+ fs: ['readFileSync', 'writeFileSync', 'existsSync', 'mkdirSync', 'readdirSync', 'unlinkSync', 'statSync'],
246
+ path: ['join', 'resolve', 'dirname', 'extname', 'basename']
247
+ };
248
+ for (const moduleName in modulesToTrace) {
249
+ const functions = modulesToTrace[moduleName];
250
+ const module = require(moduleName);
251
+ for (const functionName of functions) {
252
+ this._patchFunction(module, moduleName, functionName);
253
+ }
254
+ }
255
+ }
256
+
257
+ // ฟังก์ชันสำหรับวนลูป Unpatch
258
+ _unpatchAllFunctions() {
259
+ for (const [key, originalFunction] of this.originalFunctions.entries()) {
260
+ const [module, functionName] = key.split('.');
261
+ require(module)[functionName] = originalFunction;
262
+ }
263
+ this.originalFunctions.clear();
264
+ }
265
+
266
+ // เขียน Header ลงไฟล์ Log
267
+ _writeHeader() {
268
+ if (!this.logStream) return;
269
+ const header = `
270
+ ===========================================
271
+ Chahuadev API Trace Log (Real-time)
272
+ ===========================================
273
+ Start Time : ${new Date().toISOString()}
274
+ Platform : ${process.platform}
275
+ Version : ${app.getVersion ? app.getVersion() : 'Unknown'}
276
+ Log File : ${this.logFilePath}
277
+ -------------------------------------------
278
+
279
+ `;
280
+ this.logStream.write(header);
281
+ }
282
+ }
283
+
284
+ module.exports = new ApiTraceDebugger();
LICENSE.md ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CHAHUADEV NON-COMMERCIAL & ACCEPTABLE USE LICENSE
2
+
3
+ Copyright (c) 2026 Chahuadev. All rights reserved.
4
+
5
+ This software and its source code are provided for educational, personal, and open-source community use. By downloading, accessing, or using this software, you agree to the following conditions:
6
+
7
+ ---
8
+
9
+ ## 1. FREE DISTRIBUTION ONLY (การแจกจ่ายต้องฟรีเท่านั้น)
10
+
11
+ You are permitted to download, copy, modify, and distribute the software and its source code, provided that such distribution is **strictly free of charge**.
12
+
13
+ ---
14
+
15
+ ## 2. NO COMMERCIAL USE (ห้ามใช้หรือดัดแปลงเพื่อการค้า)
16
+
17
+ You may **NOT** use, modify, distribute, or incorporate this software (or any of its parts) for any commercial purposes. This includes, but is not limited to:
18
+
19
+ - Selling the software or derived versions.
20
+ - Locking the software behind a paywall or subscription.
21
+ - Using the software to provide commercial services.
22
+ - Placing advertisements within the software.
23
+
24
+ ---
25
+
26
+ ## 3. ACCEPTABLE USE / NO MALICIOUS USE (ห้ามใช้ในทางที่ผิด)
27
+
28
+ This software must not be used for any illegal, malicious, or harmful activities. You are strictly prohibited from using this codebase to:
29
+
30
+ - Create malware, ransomware, or any destructive software.
31
+ - Bypass security systems, steal data, or perform unauthorized access.
32
+ - Violate any local, national, or international laws.
33
+
34
+ If the software is found to be used in violation of these terms, your license to use it is immediately and permanently terminated without notice.
35
+
36
+ ---
37
+
38
+ ## 4. ATTRIBUTION (ต้องแสดงแหล่งที่มา)
39
+
40
+ Any permitted distribution or modification must clearly credit the original author:
41
+
42
+ > Original work by **Chahuadev** — https://chahuadev.com
43
+
44
+ You may not remove, obscure, or alter any copyright notices or attribution present in the source code or documentation.
45
+
46
+ ---
47
+
48
+ ## 5. DISCLAIMER OF LIABILITY (ข้อสงวนสิทธิ์ความรับผิดชอบ)
49
+
50
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
51
+
52
+ ---
53
+
54
+ For questions regarding licensing, contact: **Chahuadev** via https://chahuadev.com
README.md CHANGED
@@ -1,3 +1,263 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Chahuadev Framework - Plugin Management System
2
+
3
+ > Electron-based Desktop Application for Managing and Executing NPM Projects
4
+
5
+ ---
6
+
7
+ ## Documentation
8
+
9
+ All documentation files have been organized in the `docs/` folder:
10
+
11
+ ### Core Documentation
12
+ - **[docs/README.md](docs/README.md)** - Original project README
13
+ - **[docs/IMPLEMENTATION_COMPLETE.txt](docs/IMPLEMENTATION_COMPLETE.txt)** - Project implementation status
14
+ - **[docs/EMOJI_REMOVAL_COMPLETE.md](docs/EMOJI_REMOVAL_COMPLETE.md)** - Emoji removal system documentation
15
+
16
+ ### Authentication & Security
17
+ - **[docs/OFFLINE_AUTH_GUIDE.md](docs/OFFLINE_AUTH_GUIDE.md)** - Offline authentication system guide
18
+ - **[docs/OFFLINE_AUTH_CHANGES.md](docs/OFFLINE_AUTH_CHANGES.md)** - Offline authentication changes and implementation
19
+ - **[docs/AUTH_SECURITY_GUIDE.md](docs/AUTH_SECURITY_GUIDE.md)** - Authentication security in ValidationGateway
20
+ - **[docs/AUTH_SECURITY_IMPLEMENTATION.txt](docs/AUTH_SECURITY_IMPLEMENTATION.txt)** - Auth security implementation details
21
+ - **[docs/SWITCH_TO_OAUTH_GUIDE.md](docs/SWITCH_TO_OAUTH_GUIDE.md)** - How to switch back to OAuth
22
+
23
+ ---
24
+
25
+ ## 🐧 Running the AppImage on Linux / WSL2 (Ubuntu)
26
+
27
+ First install the required system libraries (one-time setup):
28
+
29
+ ```bash
30
+ sudo apt-get update && sudo apt-get install -y \
31
+ libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 \
32
+ libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 \
33
+ libxrandr2 libgbm1 libasound2
34
+ ```
35
+
36
+ Then run the AppImage:
37
+
38
+ ```bash
39
+ chmod +x "Chahuadev-Framework.AppImage"
40
+ DISPLAY=:0 WAYLAND_DISPLAY=wayland-0 \
41
+ ./"Chahuadev-Framework.AppImage" \
42
+ --appimage-extract-and-run --no-sandbox --disable-gpu
43
+ ```
44
+
45
+ > **WSL2 tip:** Copy the AppImage to the WSL native filesystem first for best performance:
46
+ > ```bash
47
+ > # Path after: npm install -g @chahuadev/framework
48
+ > # (no sudo)
49
+ > cp ~/.npm-global/lib/node_modules/@chahuadev/framework/bin/Chahuadev-Framework.AppImage /tmp/ChahuadevFramework.AppImage
50
+ > # (with sudo)
51
+ > # cp /usr/lib/node_modules/@chahuadev/framework/bin/Chahuadev-Framework.AppImage /tmp/ChahuadevFramework.AppImage
52
+ > chmod +x /tmp/ChahuadevFramework.AppImage
53
+ > DISPLAY=:0 WAYLAND_DISPLAY=wayland-0 /tmp/ChahuadevFramework.AppImage \
54
+ > --appimage-extract-and-run --no-sandbox --disable-gpu
55
+ > ```
56
+
57
+ ---
58
+
59
+ ## Quick Start
60
+
61
+ ```bash
62
+ # Install dependencies
63
+ npm install
64
+
65
+ # Start development server
66
+ npm start
67
+
68
+ # Start with dev mode
69
+ npm run dev
70
+
71
+ # Generate builds
72
+ npm run build # All platforms
73
+ npm run build-win # Windows only
74
+ npm run build-msi # MSI installer
75
+ npm run build-exe # Portable executable
76
+ npm run build-nsis # NSIS installer
77
+ ```
78
+
79
+ ---
80
+
81
+ ## Key Features
82
+
83
+ **Offline Authentication** - No internet connection required
84
+ **SVG Icon System** - 40+ SVG icons for UI/logging
85
+ **Fort-Knox Security** - Anti-debugging, tamper detection, runtime integrity checks
86
+ **Gateway Pattern** - Centralized command processing and validation
87
+ **Multi-User Support** - Admin, Developer, User roles with permission levels
88
+ **Plugin Management** - Load and execute NPM projects as plugins
89
+
90
+ ---
91
+
92
+ ## Project Structure
93
+
94
+ ```
95
+ chahuadev-framework/
96
+ ├── docs/ # Documentation (moved here)
97
+ │ ├── README.md
98
+ │ ├── IMPLEMENTATION_COMPLETE.txt
99
+ │ ├── OFFLINE_AUTH_GUIDE.md
100
+ │ ├── AUTH_SECURITY_GUIDE.md
101
+ │ └── ...
102
+ ├── src/
103
+ ├── backend/ # Backend utilities
104
+ ├── modules/ # Core modules
105
+ │ ├── svg-icons.js # SVG icon system (40+ icons)
106
+ │ ├── tamper-detector.js
107
+ │ └── ...
108
+ ├── scripts/ # Build and utility scripts
109
+ ├── main.js # Electron main process
110
+ ├── preload.js # Preload script for IPC
111
+ ├── index.html # Main UI
112
+ ├── validation_gateway.js # Command gateway with auth
113
+ └── package.json
114
+ ```
115
+
116
+ ---
117
+
118
+ ## Authentication System
119
+
120
+ ### Demo Users (Offline Mode)
121
+ ```
122
+ Username: admin | Password: demo123 | Role: Administrator | Permissions: read, write, admin
123
+ Username: developer | Password: demo123 | Role: Developer | Permissions: read, write
124
+ Username: user | Password: demo123 | Role: User | Permissions: read
125
+ ```
126
+
127
+ ### Token Storage
128
+ - Location: `~/.chahuadev/auth.json`
129
+ - Expiration: 24 hours
130
+
131
+ ### Permission Levels
132
+ - `read` - View data, list plugins
133
+ - `write` - Run commands, execute npm
134
+ - `admin` - System configuration, auth checks
135
+
136
+ ---
137
+
138
+ ## Security Features
139
+
140
+ ### Fort-Knox Level Security
141
+ - Anti-debugging protection
142
+ - Tamper detection system
143
+ - Runtime integrity checks
144
+ - DevTools protection
145
+ - Supply chain security verification
146
+
147
+ ### Authentication Security
148
+ - Account lockout (5 attempts, 5-minute timeout)
149
+ - Token expiration checking
150
+ - Permission-based access control
151
+ - Command-level authentication checks
152
+
153
+ ### Command Security
154
+ - IPC command sanitization
155
+ - Dangerous pattern detection
156
+ - Whitelist-based execution
157
+ - Plugin signature verification
158
+
159
+ ---
160
+
161
+ ## Logging System
162
+
163
+ ### Text-based Logging Tags
164
+ Instead of emoji, the system now uses text-based tags:
165
+
166
+ ```
167
+ [SUCCESS] - Operation successful
168
+ [ERROR] - Error occurred
169
+ [FAILED] - Operation failed
170
+ [DENIED] - Access denied
171
+ [LOCKED] - Account/resource locked
172
+ [UNLOCKED] - Account/resource unlocked
173
+ [EXPIRED] - Token expired
174
+ [AUTH] - Authentication operation
175
+ [PERMISSION] - Permission check
176
+ [GATEWAY] - Gateway operation
177
+ [ADMIN] - Administrator action
178
+ [DEV] - Developer action
179
+ [USER] - User action
180
+ ```
181
+
182
+ ---
183
+
184
+ ## SVG Icons System
185
+
186
+ 40+ SVG icons available in `modules/svg-icons.js`:
187
+
188
+ ### Security & Auth Icons
189
+ - lock, unlock, shield, checkCircle, alertCircle, xCircle
190
+ - userCheck, userX, user, users
191
+
192
+ ### System Icons
193
+ - zap, settings, loader, refresh, eye, eyeOff
194
+ - check, x, alertTriangle, info, bell, clock
195
+
196
+ ### Usage
197
+ ```javascript
198
+ const SVGIcons = require('./modules/svg-icons.js');
199
+
200
+ // Get SVG string
201
+ const svg = SVGIcons.getSVG('lock', 'icon-small');
202
+
203
+ // Create DOM element
204
+ const elem = SVGIcons.createSVGElement('user', 'user-icon');
205
+ ```
206
+
207
+ ---
208
+
209
+ ## Development Commands
210
+
211
+ ```bash
212
+ # Start development
213
+ npm start # Normal start
214
+ npm run dev # Development mode
215
+ npm run dev-mode # Development mode with flags
216
+
217
+ # Security
218
+ npm run generate-checksums # Generate file checksums
219
+ npm run security:check # Run security checks
220
+ npm run security:audit # Audit dependencies
221
+ npm run security:report # Generate security report
222
+
223
+ # Building
224
+ npm run build # Build all platforms
225
+ npm run build-win # Windows build
226
+ npm run build-msi # MSI installer
227
+ npm run build-exe # Portable executable
228
+ npm run build-nsis # NSIS installer
229
+
230
+ # Testing
231
+ npm test # Run tests
232
+ npm run test:logo # Test logo system
233
+ ```
234
+
235
+ ---
236
+
237
+ ## For More Information
238
+
239
+ - See **[docs/](docs/)** folder for detailed documentation
240
+ - Check specific guides for authentication, security, and emoji removal
241
+ - Review `AUTH_SECURITY_GUIDE.md` for authentication implementation details
242
+
243
+ ---
244
+
245
+ ## License
246
+
247
+ Non-Commercial & Acceptable Use — See [LICENSE.md](LICENSE.md)
248
+
249
+ ---
250
+
251
+ ## Contributing
252
+
253
+ For contributing guidelines, see the main documentation files in `docs/` folder
254
+
255
+ ---
256
+
257
+ **Status**: Production Ready
258
+ **Version**: 1.0.0
259
+ **Last Updated**: February 17, 2026
260
+
261
+ ---
262
+
263
+ *Chahuadev Framework - Making Project Management Simple & Secure*
app.html ADDED
The diff for this file is too large to render. See raw diff
 
auth-dialog.js ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Auth Dialog System - ระบบกล่องแจ้งเตือนล็อกอิน
3
+ * สำหรับแจ้งเตือนเมื่อผู้ใช้ยังไม่ได้ล็อกอิน
4
+ */
5
+
6
+ class AuthDialog {
7
+ constructor() {
8
+ this.createStyles();
9
+ }
10
+
11
+ createStyles() {
12
+ const styles = `
13
+ .auth-dialog-overlay {
14
+ position: fixed;
15
+ top: 0;
16
+ left: 0;
17
+ width: 100%;
18
+ height: 100%;
19
+ background: rgba(0, 0, 0, 0.8);
20
+ backdrop-filter: blur(5px);
21
+ display: flex;
22
+ align-items: center;
23
+ justify-content: center;
24
+ z-index: 15000;
25
+ animation: auth-dialog-fade-in 0.3s ease-out;
26
+ }
27
+
28
+ .auth-dialog-box {
29
+ background: linear-gradient(135deg, #1a1a1a 0%, #0a0a0a 100%);
30
+ border: 2px solid #333;
31
+ border-radius: 12px;
32
+ padding: 30px;
33
+ max-width: 400px;
34
+ width: 90%;
35
+ box-shadow:
36
+ 0 20px 40px rgba(0, 0, 0, 0.5),
37
+ 0 0 0 1px rgba(255, 255, 255, 0.1),
38
+ inset 0 1px 0 rgba(255, 255, 255, 0.1);
39
+ animation: auth-dialog-slide-up 0.3s ease-out;
40
+ text-align: center;
41
+ }
42
+
43
+ .auth-dialog-header {
44
+ color: #e0e0e0;
45
+ font-size: 18px;
46
+ font-weight: 600;
47
+ margin-bottom: 8px;
48
+ padding-bottom: 15px;
49
+ border-bottom: 1px solid #333;
50
+ }
51
+
52
+ .auth-dialog-message {
53
+ color: #b0b0b0;
54
+ font-size: 16px;
55
+ line-height: 1.5;
56
+ margin-bottom: 25px;
57
+ margin-top: 15px;
58
+ }
59
+
60
+ .auth-dialog-button {
61
+ background: linear-gradient(135deg, #0ea5e9, #0284c7);
62
+ border: none;
63
+ color: white;
64
+ padding: 12px 24px;
65
+ border-radius: 8px;
66
+ font-size: 14px;
67
+ font-weight: 600;
68
+ cursor: pointer;
69
+ transition: all 0.3s ease;
70
+ box-shadow: 0 4px 15px rgba(14, 165, 233, 0.3);
71
+ min-width: 100px;
72
+ }
73
+
74
+ .auth-dialog-button:hover {
75
+ background: linear-gradient(135deg, #0284c7, #0369a1);
76
+ transform: translateY(-2px);
77
+ box-shadow: 0 6px 20px rgba(14, 165, 233, 0.4);
78
+ }
79
+
80
+ .auth-dialog-button:active {
81
+ transform: translateY(0);
82
+ }
83
+
84
+ @keyframes auth-dialog-fade-in {
85
+ from {
86
+ opacity: 0;
87
+ }
88
+ to {
89
+ opacity: 1;
90
+ }
91
+ }
92
+
93
+ @keyframes auth-dialog-slide-up {
94
+ from {
95
+ opacity: 0;
96
+ transform: translateY(30px) scale(0.9);
97
+ }
98
+ to {
99
+ opacity: 1;
100
+ transform: translateY(0) scale(1);
101
+ }
102
+ }
103
+ `;
104
+
105
+ // เพิ่ม CSS styles
106
+ if (!document.getElementById('auth-dialog-styles')) {
107
+ const styleElement = document.createElement('style');
108
+ styleElement.id = 'auth-dialog-styles';
109
+ styleElement.textContent = styles;
110
+ document.head.appendChild(styleElement);
111
+ }
112
+ }
113
+
114
+ show(options = {}) {
115
+ const {
116
+ title = 'ข้อความจาก chahuadev.com',
117
+ message = 'กรุณาล็อกอินก่อนใช้งาน',
118
+ buttonText = 'ตกลง'
119
+ } = options;
120
+
121
+ // ลบ dialog เก่าถ้ามี
122
+ this.hide();
123
+
124
+ // สร้าง dialog overlay
125
+ const overlay = document.createElement('div');
126
+ overlay.className = 'auth-dialog-overlay';
127
+ overlay.id = 'auth-dialog-overlay';
128
+
129
+ // สร้าง dialog box
130
+ const dialog = document.createElement('div');
131
+ dialog.className = 'auth-dialog-box';
132
+
133
+ dialog.innerHTML = `
134
+ <div class="auth-dialog-header">${title}</div>
135
+ <div class="auth-dialog-message">${message}</div>
136
+ <button class="auth-dialog-button" onclick="authDialog.hide()">${buttonText}</button>
137
+ `;
138
+
139
+ overlay.appendChild(dialog);
140
+ document.body.appendChild(overlay);
141
+
142
+ // ปิด dialog เมื่อคลิกข้างนอก
143
+ overlay.addEventListener('click', (e) => {
144
+ if (e.target === overlay) {
145
+ this.hide();
146
+ }
147
+ });
148
+
149
+ // ปิด dialog ด้วย ESC key
150
+ const escapeHandler = (e) => {
151
+ if (e.key === 'Escape') {
152
+ this.hide();
153
+ document.removeEventListener('keydown', escapeHandler);
154
+ }
155
+ };
156
+ document.addEventListener('keydown', escapeHandler);
157
+ }
158
+
159
+ hide() {
160
+ const overlay = document.getElementById('auth-dialog-overlay');
161
+ if (overlay) {
162
+ overlay.style.animation = 'auth-dialog-fade-in 0.2s ease-out reverse';
163
+ setTimeout(() => {
164
+ overlay.remove();
165
+ }, 200);
166
+ }
167
+ }
168
+ }
169
+
170
+ // สร้าง instance ของ AuthDialog
171
+ window.authDialog = new AuthDialog();
backend/utils/inspector-worker.js ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const { parentPort } = require('worker_threads');
2
+ const path = require('path');
3
+
4
+ // ProjectInspector class will be imported in the message handler
5
+
6
+ /**
7
+ * Inspector Worker - Project Analysis Worker Thread
8
+ *
9
+ * Worker Thread สำหรับการวิเคราะห์โปรเจกต์แบบไม่ blocking UI
10
+ * ทำงานแยกต่างหากจาก Main Process เพื่อป้องกันการค้างของ UI
11
+ *
12
+ * การทำงาน:
13
+ * 1. รับ path จาก Main Process ผ่าน message
14
+ * 2. ใช้ ProjectInspector instance ที่ถูก export มา
15
+ * 3. เริ่มการวิเคราะห์แบบ asynchronous
16
+ * 4. ส่งผลลัพธ์กลับไปให้ Main Process
17
+ * 5. จัดการ error ทุกกรณี
18
+ */
19
+
20
+ console.log(' [Inspector Worker] Worker thread started');
21
+
22
+ // เมื่อได้รับคำสั่งจาก Main Process
23
+ parentPort.on('message', async (data) => {
24
+ const { projectPath, scanTarget = 'โปรเจกต์' } = data;
25
+
26
+ try {
27
+ console.log(` [Inspector Worker] Received job to analyze ${scanTarget}: ${projectPath}`);
28
+
29
+ // ส่งสถานะเริ่มต้นกลับไป
30
+ parentPort.postMessage({
31
+ type: 'progress',
32
+ message: `เริ่มการวิเคราะห์ ${scanTarget}...`,
33
+ progress: 0
34
+ });
35
+
36
+ // สร้าง ProjectInspector instance พร้อม status callback
37
+ const statusUpdateCallback = (message) => {
38
+ // ส่งสถานะอัปเดตไปยัง Main Process ทันที
39
+ parentPort.postMessage({
40
+ type: 'status-update',
41
+ data: message
42
+ });
43
+ };
44
+
45
+ // --- เพิ่มการตรวจสอบ Error ตรงนี้ ---
46
+ let ProjectInspector;
47
+ try {
48
+ // ลอง require ไฟล์ ProjectInspector
49
+ ProjectInspector = require('./project-inspector');
50
+ } catch (e) {
51
+ throw new Error(`Failed to require ProjectInspector: ${e.message}`);
52
+ }
53
+
54
+ if (typeof ProjectInspector !== 'function') {
55
+ throw new Error('ProjectInspector that was required is not a constructor. Check module.exports.');
56
+ }
57
+
58
+ // สร้าง ProjectInspector instance โดยส่ง callback เข้าไป
59
+ const inspector = new ProjectInspector(statusUpdateCallback);
60
+
61
+ console.log(` [Inspector Worker] Created ProjectInspector with status callback`);
62
+
63
+ // ส่งสถานะการเตรียมตัว
64
+ parentPort.postMessage({
65
+ type: 'progress',
66
+ message: 'กำลังเตรียมเครื่องมือวิเคราะห์...',
67
+ progress: 10
68
+ });
69
+
70
+ // เริ่มการวิเคราะห์ (ต่อไปนี้เป็นงานหนัก)
71
+ const startTime = Date.now();
72
+ console.log(` [Inspector Worker] Starting intensive analysis of: ${projectPath}`);
73
+
74
+ // ส่งสถานะเริ่มสแกน
75
+ parentPort.postMessage({
76
+ type: 'progress',
77
+ message: 'กำลังสแกนไฟล์ทั้งหมด...',
78
+ progress: 25
79
+ });
80
+
81
+ // ทำการวิเคราะห์หลัก (จุดที่ใช้เวลานาน)
82
+ const analysisResult = await inspector.analyzeProject(projectPath);
83
+
84
+ const endTime = Date.now();
85
+ const duration = (endTime - startTime) / 1000;
86
+
87
+ console.log(` [Inspector Worker] Analysis completed in ${duration}s`);
88
+ console.log(` [Inspector Worker] Found ${analysisResult.totalFiles} files, ${analysisResult.totalIssues} issues`);
89
+
90
+ // ส่งสถานะเสร็จสิ้น
91
+ parentPort.postMessage({
92
+ type: 'progress',
93
+ message: 'การวิเคราะห์เสร็จสมบูรณ์!',
94
+ progress: 100
95
+ });
96
+
97
+ // ส่งผลลัพธ์สุดท้ายกลับไปให้ Main Process
98
+ parentPort.postMessage({
99
+ type: 'analysis-result',
100
+ success: true,
101
+ analysis: analysisResult,
102
+ scanTarget,
103
+ duration,
104
+ timestamp: new Date().toISOString()
105
+ });
106
+
107
+ // Force cleanup and graceful exit after successful completion
108
+ console.log(' [Inspector Worker] Results sent, scheduling graceful exit...');
109
+ setTimeout(() => {
110
+ console.log(' [Inspector Worker] Analysis complete, terminating gracefully');
111
+ process.exit(0);
112
+ }, 100);
113
+
114
+ } catch (error) {
115
+ console.error(` [Inspector Worker] Analysis failed:`, error);
116
+
117
+ // ส่ง Error ที่ชัดเจนกลับไป
118
+ parentPort.postMessage({
119
+ type: 'analysis-result',
120
+ success: false,
121
+ error: {
122
+ message: error.message,
123
+ stack: error.stack,
124
+ name: error.name,
125
+ timestamp: new Date().toISOString()
126
+ }
127
+ });
128
+
129
+ // Force cleanup and exit after error
130
+ setTimeout(() => {
131
+ console.log(' [Inspector Worker] Error handled, terminating gracefully');
132
+ process.exit(0);
133
+ }, 50);
134
+ }
135
+ });
136
+
137
+ // จัดการ error ที่ไม่คาดคิด
138
+ process.on('unhandledRejection', (reason, promise) => {
139
+ console.error(' [Inspector Worker] Unhandled Rejection at:', promise, 'reason:', reason);
140
+ parentPort.postMessage({
141
+ type: 'error',
142
+ error: {
143
+ message: `Unhandled rejection: ${reason}`,
144
+ stack: reason?.stack || 'No stack trace available',
145
+ name: 'UnhandledRejection',
146
+ timestamp: new Date().toISOString()
147
+ }
148
+ });
149
+ });
150
+
151
+ process.on('uncaughtException', (error) => {
152
+ console.error(' [Inspector Worker] Uncaught Exception:', error);
153
+ parentPort.postMessage({
154
+ type: 'error',
155
+ error: {
156
+ message: error.message,
157
+ stack: error.stack,
158
+ name: error.name,
159
+ timestamp: new Date().toISOString()
160
+ }
161
+ });
162
+ // Don't exit immediately to allow for graceful cleanup
163
+ setTimeout(() => {
164
+ console.log(' [Inspector Worker] Graceful shutdown after uncaught exception');
165
+ process.exit(0);
166
+ }, 100);
167
+ });
168
+
169
+ console.log(' [Inspector Worker] Listening for messages from Main Process...');
backend/utils/project-inspector-ipc.js ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const { ipcMain, app } = require('electron');
2
+ const { Worker } = require('worker_threads');
3
+ const path = require('path');
4
+ const fs = require('fs');
5
+ // Note: projectInspector is now handled by Worker Thread
6
+
7
+ // Track if handlers are already registered
8
+ let handlersRegistered = false;
9
+
10
+ /**
11
+ * IPC Handlers สำหรับ Project Inspector
12
+ * @param {Object} logger - Logger object
13
+ * @param {Object} debugManager - Debug manager instance
14
+ * @param {Object} cmdLogger - CMD logger for real-time display
15
+ */
16
+ function setupProjectInspectorIPC(logger, debugManager, cmdLogger) {
17
+ // ป้องกันการลงทะเบียนซ้ำ
18
+ if (handlersRegistered) {
19
+ console.log(' Project Inspector IPC handlers already registered, skipping...');
20
+ return;
21
+ }
22
+
23
+ try {
24
+ // Project Inspector IPC Handlers (ใช้ Worker Threads เพื่อป้องกัน UI ค้าง)
25
+ ipcMain.handle('project:analyze', async (event, projectPath) => {
26
+ return new Promise((resolve, reject) => {
27
+ try {
28
+ let pathToScan;
29
+ let scanTarget;
30
+
31
+ // ถ้าไม่ได้ระบุ path มา, ให้สแกนโฟลเดอร์ plugins เป็น default
32
+ if (!projectPath) {
33
+ console.log('No path provided, defaulting to plugins directory.');
34
+ scanTarget = 'ปลั๊กอินทั้งหมด';
35
+
36
+ // หา Path ของโฟลเดอร์ plugins ที่ถูกต้อง
37
+ if (app.isPackaged) {
38
+ pathToScan = path.join(path.dirname(app.getPath('exe')), 'plugins');
39
+ } else {
40
+ pathToScan = path.join(app.getPath('userData'), 'plugins');
41
+ }
42
+ } else {
43
+ pathToScan = projectPath;
44
+ scanTarget = 'โปรเจกต์เฉพาะ';
45
+ }
46
+
47
+ console.log(`[IPC] Starting project analysis for ${scanTarget}: ${pathToScan}`);
48
+
49
+ // ตรวจสอบว่าโฟลเดอร์มีอยู่จริง
50
+ if (!fs.existsSync(pathToScan)) {
51
+ fs.mkdirSync(pathToScan, { recursive: true });
52
+ console.log(`Created missing directory: ${pathToScan}`);
53
+ }
54
+
55
+ logger.info('Starting project analysis with Worker Thread', { pathToScan, scanTarget });
56
+
57
+ // ส่งข้อความเริ่มต้นไปยัง CMD
58
+ if (cmdLogger) {
59
+ cmdLogger.info(`[Inspector] Starting project analysis...`);
60
+ cmdLogger.info(`[Inspector] Scan target: ${scanTarget}`);
61
+ cmdLogger.info(`[Inspector] Path to scan: ${pathToScan}`);
62
+ }
63
+
64
+ // สร้าง Worker Thread สำหรับการวิเคราะห์
65
+ const worker = new Worker(path.join(__dirname, 'inspector-worker.js'));
66
+
67
+ console.log(`[IPC] Created Worker Thread for analysis`);
68
+ if (cmdLogger) {
69
+ cmdLogger.debug(`[Inspector] Worker Thread created successfully`);
70
+ }
71
+
72
+ // รอรับผลลัพธ์และสถานะจาก Worker
73
+ worker.on('message', (result) => {
74
+ if (result.type === 'progress') {
75
+ // ส่ง progress update ไปให้ Frontend (ถ้าต้องการ)
76
+ const progressMessage = `Progress: ${result.message} (${result.progress}%)`;
77
+ console.log(`[IPC] ${progressMessage}`);
78
+ // ส่ง progress ไปยัง CMD แบบ real-time
79
+ if (cmdLogger) {
80
+ cmdLogger.info(`[Inspector] ${progressMessage}`);
81
+ }
82
+ // event.sender.send('project:analysis-progress', result);
83
+
84
+ } else if (result.type === 'status-update') {
85
+ // ส่งสถานะ real-time ไปให้ UI และ CMD ทันที
86
+ console.log(`[IPC] Status: ${result.data}`);
87
+
88
+ // ส่งไปยัง CMD แบบ real-time
89
+ if (cmdLogger) {
90
+ cmdLogger.info(`[Inspector] ${result.data}`);
91
+ }
92
+
93
+ try {
94
+ // ส่งสถานะไปยัง debug window หรือ main window
95
+ event.sender.send('inspector:status-update', result.data);
96
+
97
+ // ส่งสถานะไปยัง debug manager ถ้ามี (สำหรับ Real-time Terminal Display)
98
+ if (debugManager) {
99
+ // ตรวจสอบว่า debug window เปิดอยู่หรือไม่
100
+ if (debugManager.isDebugWindowOpen && debugManager.isDebugWindowOpen()) {
101
+ // ส่งข้อความไปยัง terminal ใน debug window
102
+ debugManager.sendTerminalMessage && debugManager.sendTerminalMessage(result.data, 'info');
103
+ console.log(`[IPC] Status sent to debug terminal: ${result.data}`);
104
+ } else {
105
+ console.log(`[IPC] Debug window is closed, skipping terminal message`);
106
+ }
107
+ } else {
108
+ console.log(`[IPC] Debug manager not available`);
109
+ }
110
+ } catch (error) {
111
+ console.warn('[IPC] Failed to send status update to renderer:', error.message);
112
+ }
113
+
114
+ } else if (result.type === 'analysis-result') {
115
+ // จัดการผลลัพธ์สุดท้าย
116
+ if (result.success) {
117
+ logger.info('Project analysis completed successfully', {
118
+ totalFiles: result.analysis.totalFiles,
119
+ totalIssues: result.analysis.totalIssues,
120
+ scanTarget: result.scanTarget,
121
+ duration: result.duration
122
+ });
123
+
124
+ const successMessage = `Worker completed successfully in ${result.duration}s - Files: ${result.analysis.totalFiles}, Issues: ${result.analysis.totalIssues}`;
125
+ console.log(`[IPC] ${successMessage}`);
126
+
127
+ // ส่งผลลัพธ์สุดท้ายไปยัง CMD
128
+ if (cmdLogger) {
129
+ cmdLogger.info(`[Inspector] ${successMessage}`);
130
+ cmdLogger.info(`[Inspector] Analysis completed for: ${result.scanTarget}`);
131
+ }
132
+
133
+ resolve({
134
+ success: true,
135
+ analysis: result.analysis,
136
+ scanTarget: result.scanTarget,
137
+ duration: result.duration
138
+ });
139
+ // Let worker terminate gracefully on its own
140
+
141
+ } else {
142
+ // จัดการ error case
143
+ logger.error('Project analysis failed in Worker', result.error);
144
+ const errorMessage = `Worker failed: ${result.error.message || result.error}`;
145
+ console.error(`[IPC] ${errorMessage}`);
146
+
147
+ // ส่ง error ไปยัง CMD
148
+ if (cmdLogger) {
149
+ cmdLogger.error(`[Inspector] ${errorMessage}`);
150
+ }
151
+
152
+ resolve({ success: false, error: result.error.message });
153
+ // Let worker terminate gracefully on its own
154
+ }
155
+ }
156
+ });
157
+
158
+ // รอรับ Error ที่ไม่คาดคิดจาก Worker
159
+ worker.on('error', (err) => {
160
+ logger.error('Worker encountered unrecoverable error', err);
161
+ const errorMessage = `Worker unrecoverable error: ${err.message}`;
162
+ console.error(`[IPC] ${errorMessage}`);
163
+
164
+ // ส่ง error ไปยัง CMD
165
+ if (cmdLogger) {
166
+ cmdLogger.error(`[Inspector] ${errorMessage}`);
167
+ }
168
+
169
+ resolve({ success: false, error: err.message });
170
+ worker.terminate();
171
+ });
172
+
173
+ // ตรวจสอบการปิด Worker
174
+ worker.on('exit', (code) => {
175
+ if (code !== 0) {
176
+ const exitMessage = `Worker stopped with exit code ${code}`;
177
+ console.error(`[IPC] ${exitMessage}`);
178
+
179
+ // ส่ง exit message ไปยัง CMD
180
+ if (cmdLogger) {
181
+ cmdLogger.warn(`[Inspector] ${exitMessage}`);
182
+ }
183
+ }
184
+ });
185
+
186
+ // สั่งให้ Worker เริ่มทำงานโดยส่ง data เข้าไป
187
+ worker.postMessage({
188
+ projectPath: pathToScan,
189
+ scanTarget
190
+ });
191
+
192
+ // ส่งข้อความที่เริ่มงานไปยัง CMD
193
+ if (cmdLogger) {
194
+ cmdLogger.info(`[Inspector] Sending analysis request to Worker Thread...`);
195
+ }
196
+
197
+ } catch (error) {
198
+ logger.error('Failed to create Worker for project analysis', error);
199
+ const errorMessage = `Failed to create Worker: ${error.message}`;
200
+
201
+ // ส่ง error ไปยัง CMD
202
+ if (cmdLogger) {
203
+ cmdLogger.error(`[Inspector] ${errorMessage}`);
204
+ }
205
+
206
+ resolve({ success: false, error: error.message });
207
+ }
208
+ });
209
+ });
210
+
211
+ ipcMain.handle('project:get-stats', async (event, analysis) => {
212
+ try {
213
+ // สำหรับ get-stats เราสามารถคำนวณใน Main Process ได้ เพราะไม่ใช่งานหนัก
214
+ const ProjectInspector = require('./project-inspector');
215
+ const tempInspector = new ProjectInspector();
216
+ const stats = tempInspector.getAnalysisStats(analysis);
217
+ return { success: true, stats };
218
+ } catch (error) {
219
+ logger.error('Failed to get project stats', error);
220
+ return { success: false, error: error.message };
221
+ }
222
+ });
223
+
224
+ ipcMain.handle('project:set-rules', async (event, rules) => {
225
+ try {
226
+ // สำหรับ set-rules เราจัดเก็บใน memory หรือ file เพื่อให้ Worker ใช้ได้
227
+ // ตอนนี้จะ implement แบบง่ายๆ ก่อน
228
+ console.log('[IPC] Analysis rules updated:', rules);
229
+ // TODO: Implement rules storage for Worker Threads
230
+ return { success: true, message: 'Rules will be applied to next analysis' };
231
+ } catch (error) {
232
+ logger.error('Failed to set analysis rules', error);
233
+ return { success: false, error: error.message };
234
+ }
235
+ });
236
+
237
+ // ทำเครื่องหมายว่าลงทะเบียนแล้ว
238
+ handlersRegistered = true;
239
+ console.log(' Project Inspector IPC handlers registered');
240
+
241
+ } catch (error) {
242
+ console.error(' Failed to register Project Inspector IPC handlers:', error);
243
+ throw error;
244
+ }
245
+ }
246
+
247
+ module.exports = setupProjectInspectorIPC;
backend/utils/project-inspector.js ADDED
@@ -0,0 +1,1813 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ // ตรวจสอบและใช้ Dependencies ที่จำเป็นสำหรับการวิเคราะห์ขั้นสูง
5
+ let acorn, cheerio;
6
+ let dependencyWarning = null;
7
+ try {
8
+ acorn = require('acorn');
9
+ cheerio = require('cheerio');
10
+ console.log(' Advanced analysis packages loaded successfully');
11
+ } catch (error) {
12
+ console.warn(' Some analysis packages not found. Advanced checking will be disabled.');
13
+ dependencyWarning = 'Advanced analysis (HTML/JS/IPC) is disabled because required packages (acorn, cheerio) are missing.';
14
+ acorn = null;
15
+ cheerio = null;
16
+ }
17
+
18
+ /**
19
+ * Project Inspector V.2 - Full-Stack Application Integrity Analysis System
20
+ *
21
+ * ระบบวิเคราะห์ความสมบูรณ์ของแอปพลิเคชันแบบ Full-Stack
22
+ * ตรวจสอบ "ไวยากรณ์ของสถาปัตยกรรม" ตั้งแต่ Frontend ไปจนถึง Backend
23
+ *
24
+ * ความสามารถใหม่:
25
+ * 1. HTML-JS Link Analysis - ตรวจสอบการเชื่อมต่อระหว่าง HTML กับ JavaScript
26
+ * 2. IPC Communication Analysis - ตรวจสอบการสื่อสาร Renderer Main Process
27
+ * 3. Visual Regression Detection - ตรวจสอบ Layout และ UI Integrity
28
+ * 4. Architecture Grammar Validation - ตรวจสอบไวยากรณ์ของสถาปัตยกรรม
29
+ *
30
+ * พร้อมระบบคัดกรองไฟล์ของระบบแบบ Professional
31
+ *
32
+ * การปรับแต่งสำหรับการดีบัก:
33
+ * - index.html ได้รับการปลดล็อกจาก exclusion rules เพื่อให้สามารถตรวจเจอปัญหาได้
34
+ * - ระบบจะสแกนและวิเคราะห์ index.html อย่างละเอียดเหมือนไฟล์อื่นๆ
35
+ *
36
+ * การปรับปรุงครั้งใหญ่:
37
+ * - ปรับปรุงกฎการคัดกรองให้ฉลาดขึ้น (Smart Exclusion Rules)
38
+ * - เพิ่มการรองรับไฟล์สมัยใหม่ (Modern File Extensions)
39
+ * - ปรับปรุงการจัดการ Dependencies
40
+ */
41
+ class ProjectInspector {
42
+ // แก้ไข constructor ให้รับ status callback
43
+ constructor(statusUpdateCallback = () => {}) {
44
+ this.statusUpdate = statusUpdateCallback;
45
+ this.fileContentCache = new Map();
46
+ this.dependencyWarning = dependencyWarning; // เก็บ warning message
47
+
48
+ // อัปเกรดกฎการวิเคราะห์ให้ครอบคลุม Full-Stack
49
+ this.analysisRules = {
50
+ // การวิเคราะห์พื้นฐาน
51
+ checkSyntax: acorn !== null,
52
+ checkMissingFiles: true,
53
+ checkUnusedFiles: false,
54
+ checkMissingDependencies: true,
55
+ checkCircularDependencies: true,
56
+ checkDuplicateExports: true,
57
+ checkImportExportMismatch: acorn !== null,
58
+
59
+ // การวิเคราะห์ขั้นสูง (ใหม่)
60
+ checkHtmlJsLinks: cheerio !== null && acorn !== null, // วิเคราะห์ HTML-JS connections
61
+ checkIpcIntegrity: acorn !== null, // วิเคราะห์ IPC communication
62
+ checkVisualRegression: true, // เตรียมพร้อมสำหรับ Visual Testing
63
+ checkArchitectureGrammar: true // วิเคราะห์ไวยากรณ์สถาปัตยกรรม
64
+ };
65
+
66
+ // ข้อมูลสำหรับการวิเคราะห์ขั้นสูง
67
+ this.htmlElements = new Map(); // เก็บ HTML elements และ IDs
68
+ this.jsHandlers = new Map(); // เก็บ JavaScript event handlers
69
+ this.ipcChannels = new Map(); // เก็บ IPC channels
70
+ this.cssClasses = new Set(); // เก็บ CSS classes
71
+
72
+ // [ปรับปรุงครั้งใหญ่] กฎการคัดกรองที่ฉลาดขึ้น - แก้ปัญหาการสแกนไม่ครอบคลุม
73
+ this.isExcluded = (filePath, projectRootPath) => {
74
+ // กฎข้อที่ 0: เด็ดขาดที่สุด - ห้ามทุกอย่างที่อยู่ใน node_modules
75
+ // กฎนี้จะทำงานก่อนเสมอและมีประสิทธิภาพสูงสุด
76
+ if (filePath.includes(path.sep + 'node_modules' + path.sep)) {
77
+ return true;
78
+ }
79
+
80
+ const relativePath = path.relative(projectRootPath, filePath);
81
+ const baseName = path.basename(filePath).toLowerCase();
82
+
83
+ // --- กฎข้อที่ 1: โฟลเดอร์ระดับรูทที่ต้องข้ามเสมอ (Root-level exclusions only) ---
84
+ // ตรวจสอบกับ relativePath เพื่อให้แน่ใจว่าเป็นโฟลเดอร์ที่อยู่ระดับบนสุดจริงๆ
85
+ const rootLevelExclusions = ['dist', 'build', '.git', 'test-results'];
86
+ if (rootLevelExclusions.some(dir => relativePath.startsWith(dir + path.sep) || relativePath === dir)) {
87
+ return true;
88
+ }
89
+
90
+ // --- กฎข้อที่ 2: โฟลเดอร์ระบบ Chahuadev Framework (เฉพาะของ Framework เท่านั้น) ---
91
+ const frameworkSystemDirs = new Set(['vendor', 'resources', 'bridge', 'logs', 'temp_extract']);
92
+ const pathParts = relativePath.split(path.sep);
93
+ if (pathParts.some(part => frameworkSystemDirs.has(part))) {
94
+ return true;
95
+ }
96
+
97
+ // --- กฎข้อที่ 3: ชื่อไฟล์ระบบที่ต้องข้ามเสมอ ---
98
+ const definitiveFileExclusions = new Set([
99
+ 'splash.html', 'loading.html', 'debugger.html',
100
+ 'main.js', 'preload.js', 'validation_gateway.js', 'debug-manager.js',
101
+ 'project-inspector.js', 'project-inspector-ipc.js',
102
+ 'generate-checksums.js', 'generate-keys.js', 'generate-manifests.js'
103
+ ]);
104
+ if (definitiveFileExclusions.has(baseName)) return true;
105
+
106
+ // --- กฎข้อที่ 4: รูปแบบชื่อไฟล์ที่ต้องข้าม ---
107
+ if (baseName.endsWith('.min.js') || baseName.endsWith('.bundle.js')) {
108
+ return true;
109
+ }
110
+
111
+ // --- กฎข้อที่ 5: ไฟล์ประเภทที่ไม่ควรสแกน (Binary files) ---
112
+ const binaryExtensions = ['.exe', '.dll', '.so', '.dylib', '.asar'];
113
+ if (binaryExtensions.some(ext => baseName.endsWith(ext))) {
114
+ return true;
115
+ }
116
+
117
+ // ถ้าไม่เข้าเงื่อนไขใดๆ เลย แสดงว่าไฟล์นี้ควรถูกสแกน
118
+ return false;
119
+ };
120
+
121
+ // Multi-Language Project Type Detection Rules
122
+ this.projectTypeRules = {
123
+ 'node': {
124
+ identifierFiles: ['package.json'],
125
+ extensions: ['.js', '.mjs', '.ts', '.jsx', '.json'],
126
+ checks: ['syntax', 'dependencies', 'imports']
127
+ },
128
+ 'python': {
129
+ identifierFiles: ['requirements.txt', 'setup.py', 'pyproject.toml'],
130
+ extensions: ['.py'],
131
+ checks: ['syntax', 'imports']
132
+ },
133
+ 'php': {
134
+ identifierFiles: ['composer.json', 'composer.lock'],
135
+ extensions: ['.php'],
136
+ checks: ['syntax', 'dependencies']
137
+ },
138
+ 'static_html': {
139
+ identifierFiles: ['index.html', 'main.html'],
140
+ extensions: ['.html', '.css', '.js', '.scss', '.less'],
141
+ checks: ['links', 'assets']
142
+ }
143
+ };
144
+ }
145
+
146
+
147
+
148
+ /**
149
+ * ฟังก์ชัน detectProjectType ที่ใช้ isExcluded เป็นด่านแรก
150
+ * @param {string} projectPath - เส้นทางของโปรเจกต์
151
+ * @returns {object} - { type: string, identifierFile: string | null }
152
+ */
153
+ detectProjectType(projectPath) {
154
+ console.log(` Detecting project type for: ${projectPath}`);
155
+
156
+ // ตรวจสอบไฟล์ identifier สำหรับแต่ละประเภท
157
+ for (const [type, rules] of Object.entries(this.projectTypeRules)) {
158
+ for (const identifierFile of rules.identifierFiles) {
159
+ const filePath = path.join(projectPath, identifierFile);
160
+
161
+ // ตรวจสอบก่อนว่าไฟล์ identifier ถูกสั่งให้ข้ามหรือไม่
162
+ if (this.isExcluded(filePath, projectPath)) {
163
+ console.log(` Skipping ${identifierFile} for ${type} detection (excluded by system rules)`);
164
+ continue;
165
+ }
166
+
167
+ if (fs.existsSync(filePath)) {
168
+ console.log(` Detected ${type} project (found ${identifierFile})`);
169
+ return { type, identifierFile };
170
+ }
171
+ }
172
+ }
173
+
174
+ // Fallback: ตรวจสอบจากนามสกุลไฟล์ที่มีอยู่
175
+ try {
176
+ const files = fs.readdirSync(projectPath);
177
+
178
+ // ตรวจหา .py files
179
+ if (files.some(file => file.endsWith('.py'))) {
180
+ console.log(' Detected python project (found .py files)');
181
+ return { type: 'python', identifierFile: null };
182
+ }
183
+
184
+ // ตรวจหา .php files
185
+ if (files.some(file => file.endsWith('.php'))) {
186
+ console.log(' Detected php project (found .php files)');
187
+ return { type: 'php', identifierFile: null };
188
+ }
189
+
190
+ // ตรวจหา HTML files (ต้องไม่ถูก exclude)
191
+ const htmlFiles = files.filter(file => {
192
+ const filePath = path.join(projectPath, file);
193
+ return file.endsWith('.html') && !this.isExcluded(filePath, projectPath);
194
+ });
195
+
196
+ if (htmlFiles.length > 0) {
197
+ console.log(' Detected static_html project (found .html files)');
198
+ return { type: 'static_html', identifierFile: null };
199
+ }
200
+
201
+ // ตรวจหา .js files (default Node.js)
202
+ if (files.some(file => file.endsWith('.js'))) {
203
+ console.log(' Detected node project (found .js files)');
204
+ return { type: 'node', identifierFile: null };
205
+ }
206
+
207
+ } catch (error) {
208
+ console.warn(` Error reading directory ${projectPath}:`, error.message);
209
+ }
210
+
211
+ console.log(' Unknown project type');
212
+ return { type: 'unknown', identifierFile: null };
213
+ }
214
+
215
+ /**
216
+ * อ่านเนื้อหาไฟล์พร้อม Cache (สำหรับ Metadata Flag Detection)
217
+ */
218
+ readFileContent(filePath) {
219
+ if (this.fileContentCache.has(filePath)) {
220
+ return this.fileContentCache.get(filePath);
221
+ }
222
+ const content = fs.readFileSync(filePath, 'utf-8');
223
+ this.fileContentCache.set(filePath, content);
224
+ return content;
225
+ }
226
+
227
+ /**
228
+ * อัปเดตฟังก์ชัน walkDirectory ให้ส่งสถานะ Real-time
229
+ */
230
+ walkDirectory(dir, projectPath, filelist = []) {
231
+ if (!projectPath) projectPath = dir; // กำหนด root path ครั้งแรก
232
+
233
+ // ส่งสถานะว่ากำลังจะสแกนโฟลเดอร์นี้
234
+ this.statusUpdate(` Scanning directory: ${path.relative(projectPath, dir) || '.'}`);
235
+
236
+ try {
237
+ const items = fs.readdirSync(dir, { withFileTypes: true });
238
+
239
+ for (const item of items) {
240
+ const fullPath = path.join(dir, item.name);
241
+
242
+ // ตรวจสอบกับกฎคัดกรองก่อนทำอะไรทั้งสิ้น!
243
+ if (this.isExcluded(fullPath, projectPath)) {
244
+ // ส่งสถานะว่ากำลังข้ามไฟล์/โฟลเดอร์นี้
245
+ this.statusUpdate(` Skipping: ${item.name}`);
246
+ continue; // ข้ามทันที - ไม่เข้าไปใน node_modules, .asar, หรือไฟล์ระบบ
247
+ }
248
+
249
+ if (item.isDirectory()) {
250
+ // ข้าม hidden folders เพิ่มเติม
251
+ if (!item.name.startsWith('.')) {
252
+ this.walkDirectory(fullPath, projectPath, filelist);
253
+ }
254
+ } else if (this.isPluginFile(item.name)) {
255
+ // ส่งสถานะว่าพบไฟล์ที่จะนำไปวิเคราะห์
256
+ this.statusUpdate(` Found file: ${item.name}`);
257
+ filelist.push(fullPath);
258
+ }
259
+ }
260
+ } catch (error) {
261
+ console.warn(`Cannot read directory ${dir}:`, error.message);
262
+ }
263
+ return filelist;
264
+ }
265
+
266
+ /**
267
+ * [ปรับปรุงครั้งใหญ่] ตรวจสอบไฟล์ปลั๊กอินด้วยการรองรับไฟล์สมัยใหม่
268
+ * เปลี่ยนจาก Whitelist เป็น Comprehensive Coverage
269
+ */
270
+ isPluginFile(filename) {
271
+ // รายการนามสกุลไฟล์ที่ครอบคลุมการพัฒนาสมัยใหม่
272
+ const pluginExtensions = [
273
+ // JavaScript & Frameworks
274
+ '.js', '.mjs', '.ts', '.jsx', '.tsx',
275
+ // Web Frontend
276
+ '.html', '.htm', '.css', '.scss', '.sass', '.less', '.vue',
277
+ // Backend Languages
278
+ '.py', '.php', '.rb', '.go', '.rs', '.java',
279
+ // Config & Data
280
+ '.json', '.yaml', '.yml', '.xml', '.toml', '.ini',
281
+ // Documentation & Text
282
+ '.txt', '.md', '.markdown', '.rst',
283
+ // Template Engines
284
+ '.ejs', '.pug', '.handlebars', '.hbs',
285
+ // Other useful formats
286
+ '.sql', '.graphql', '.env'
287
+ ];
288
+
289
+ const systemFiles = ['package.json', 'requirements.txt', 'composer.json', 'Cargo.toml', 'go.mod'];
290
+
291
+ // อนุญาตไฟล์การกำหนดค่าที่สำคัญ
292
+ if (systemFiles.includes(filename)) return true;
293
+
294
+ // อนุญาตไฟล์ที่มีนามสกุลที่เกี่ยวข้องกับปลั๊กอิน
295
+ return pluginExtensions.some(ext => filename.endsWith(ext));
296
+ }
297
+
298
+ /**
299
+ * ฟังก์ชันหลักในการเริ่มวิเคราะห์โปรเจกต์ (เวอร์ชันปรับปรุงขั้นสุดท้าย)
300
+ */
301
+ async analyzeProject(projectPath = process.cwd()) {
302
+ const analysis = {
303
+ timestamp: new Date().toISOString(),
304
+ projectPath,
305
+ totalFiles: 0,
306
+ totalIssues: 0,
307
+ issues: [],
308
+ dependencies: new Map(),
309
+ fileGraph: new Map(),
310
+ unusedFiles: [],
311
+ circularDeps: [],
312
+ stats: {
313
+ syntaxErrors: 0,
314
+ missingFiles: 0,
315
+ unusedFiles: 0,
316
+ missingDependencies: 0,
317
+ circularDependencies: 0,
318
+ duplicateExports: 0,
319
+ importExportMismatch: 0,
320
+ typeSpecificIssues: 0
321
+ }
322
+ };
323
+
324
+ try {
325
+ console.log(' Starting Project Inspector analysis...');
326
+
327
+ // ส่งสถานะเริ่มต้นการวิเคราะห์
328
+ this.statusUpdate(' Starting Project Inspector analysis...');
329
+
330
+ // Multi-Language Project Type Detection
331
+ this.statusUpdate(' Detecting project type...');
332
+ const detectionResult = this.detectProjectType(projectPath);
333
+ const projectType = detectionResult.type;
334
+ analysis.projectType = projectType;
335
+
336
+ this.statusUpdate(` Project type detected: ${projectType}`);
337
+
338
+ // --- การตรวจสอบ System File Exclusion ที่เด็ดขาดขึ้น ---
339
+ if (detectionResult.identifierFile) {
340
+ const identifierFilePath = path.join(projectPath, detectionResult.identifierFile);
341
+ if (this.isExcluded(identifierFilePath, projectPath)) {
342
+ console.log(` Skipping type-specific analysis for '${projectType}' because its identifier file '${detectionResult.identifierFile}' is excluded by System File Exclusion rules.`);
343
+ analysis.typeAnalysis = {
344
+ projectType,
345
+ typeSpecificIssues: [],
346
+ recommendations: ['ข้ามการวิเคราะห์เฉพาะประเภทเพราะไฟล์หลักอยู่ใน System File Exclusion rules']
347
+ };
348
+ } else {
349
+ // Type-specific Analysis (จะทำงานก็ต่อเมื่อไม่ถูกข้าม)
350
+ const typeAnalysis = this.analyzeByProjectType(projectPath, projectType);
351
+ analysis.typeAnalysis = typeAnalysis;
352
+
353
+ // เพิ่ม type-specific issues เข้าไปใน main issues
354
+ analysis.issues.push(...typeAnalysis.typeSpecificIssues);
355
+ analysis.totalIssues += typeAnalysis.typeSpecificIssues.length;
356
+ analysis.stats.typeSpecificIssues = typeAnalysis.typeSpecificIssues.length;
357
+
358
+ console.log(` Project type detected: ${projectType}`);
359
+ if (typeAnalysis.recommendations.length > 0) {
360
+ console.log(` Recommendations: ${typeAnalysis.recommendations.length} items`);
361
+ }
362
+ }
363
+ } else {
364
+ // กรณีไม่มี identifierFile ให้ทำ type analysis ปกติ
365
+ const typeAnalysis = this.analyzeByProjectType(projectPath, projectType);
366
+ analysis.typeAnalysis = typeAnalysis;
367
+
368
+ analysis.issues.push(...typeAnalysis.typeSpecificIssues);
369
+ analysis.totalIssues += typeAnalysis.typeSpecificIssues.length;
370
+ analysis.stats.typeSpecificIssues = typeAnalysis.typeSpecificIssues.length;
371
+
372
+ console.log(` Project type detected: ${projectType}`);
373
+ if (typeAnalysis.recommendations.length > 0) {
374
+ console.log(` Recommendations: ${typeAnalysis.recommendations.length} items`);
375
+ }
376
+ }
377
+
378
+ // 1. รวบรวมไฟล์ทั้งหมด (walkDirectory จะคัดกรองเบื้องต้นแล้ว)
379
+ this.statusUpdate(' Collecting files to analyze...');
380
+ const filesToAnalyze = this.walkDirectory(projectPath, projectPath);
381
+ const finalFileList = [];
382
+
383
+ // --- เพิ่มการคัดกรองชั้นที่สองโดยการอ่านเนื้อหาไฟล์ (Metadata Flag) ---
384
+ this.statusUpdate(' Performing secondary file filtering...');
385
+ for (const filePath of filesToAnalyze) {
386
+ try {
387
+ const content = this.readFileContent(filePath);
388
+ // ถ้าเจอ "ป้ายกำกับ" ของไฟล์ระบบ ให้ข้ามไป
389
+ if (content.includes('CHAHUADEV_SYSTEM_FILE')) {
390
+ console.log(` Skipping file with system flag: ${path.basename(filePath)}`);
391
+ continue;
392
+ }
393
+ finalFileList.push(filePath);
394
+ } catch (e) {
395
+ // ถ้าอ่านไฟล์ไม่ได้ ก็ข้ามไป
396
+ continue;
397
+ }
398
+ }
399
+
400
+ analysis.totalFiles = finalFileList.length;
401
+ this.statusUpdate(` Found ${analysis.totalFiles} files to analyze`);
402
+
403
+ // เพิ่มการแจ้งเตือนเกี่ยวกับ Dependencies ที่ขาดหายไป
404
+ if (this.dependencyWarning) {
405
+ analysis.issues.push({
406
+ type: 'ConfigurationWarning',
407
+ severity: 'warning',
408
+ file: 'Project Inspector',
409
+ message: this.dependencyWarning,
410
+ suggestion: 'Run "npm install acorn cheerio" in your project directory to enable advanced analysis features.',
411
+ line: 1,
412
+ column: 1
413
+ });
414
+ analysis.totalIssues += 1;
415
+ console.log(` ${this.dependencyWarning}`);
416
+ }
417
+
418
+ if (analysis.totalFiles === 0) {
419
+ console.log(' No plugin files found in project');
420
+ // สำหรับโปรเจกต์ที่ไม่ใช่ Node.js/JavaScript ให้ส่งผล type analysis กลับ
421
+ if (projectType !== 'node' && projectType !== 'unknown') {
422
+ console.log(` Analysis completed for ${projectType} project (no plugin files needed)`);
423
+ return analysis;
424
+ }
425
+ return analysis;
426
+ }
427
+
428
+ const allProjectFiles = new Set();
429
+ finalFileList.forEach(file => {
430
+ const relativePath = path.relative(projectPath, file);
431
+ allProjectFiles.add(relativePath);
432
+ });
433
+
434
+ // 2. วิเคราะห์แต่ละไฟล์
435
+ this.statusUpdate(' Starting file analysis...');
436
+ for (const filePath of finalFileList) {
437
+ try {
438
+ const code = fs.readFileSync(filePath, 'utf-8');
439
+ const relativePath = path.relative(projectPath, filePath);
440
+
441
+ // ส่งสถานะว่ากำลังวิเคราะห์ไฟล์นี้
442
+ this.statusUpdate(` Analyzing: ${relativePath}`);
443
+
444
+ // 2.1 ตรวจสอบ Syntax
445
+ if (this.analysisRules.checkSyntax && acorn) {
446
+ const syntaxIssues = this.checkSyntax(code, relativePath, projectPath);
447
+ analysis.issues.push(...syntaxIssues);
448
+ analysis.stats.syntaxErrors += syntaxIssues.length;
449
+ }
450
+
451
+ // 2.2 วิเคราะห์ Dependencies
452
+ if (this.analysisRules.checkMissingFiles) {
453
+ const depIssues = this.analyzeDependencies(code, filePath, projectPath, analysis);
454
+ analysis.issues.push(...depIssues);
455
+ analysis.stats.missingFiles += depIssues.length;
456
+ }
457
+
458
+ // 2.3 ตรวจสอบ Duplicate Exports
459
+ if (this.analysisRules.checkDuplicateExports && acorn) {
460
+ const exportIssues = this.checkDuplicateExports(code, relativePath, projectPath);
461
+ analysis.issues.push(...exportIssues);
462
+ analysis.stats.duplicateExports += exportIssues.length;
463
+ }
464
+
465
+ // 2.4 ตรวจสอบ Import/Export Mismatch
466
+ if (this.analysisRules.checkImportExportMismatch && acorn) {
467
+ const mismatchIssues = this.checkImportExportMismatch(code, filePath, projectPath);
468
+ analysis.issues.push(...mismatchIssues);
469
+ analysis.stats.importExportMismatch += mismatchIssues.length;
470
+ }
471
+
472
+ } catch (error) {
473
+ // ไม่สามารถวิเคราะห์ไฟล์นี้ได้
474
+ analysis.issues.push({
475
+ type: 'AnalysisError',
476
+ severity: 'warning',
477
+ file: path.relative(projectPath, filePath),
478
+ message: `ไม่สามารถวิเคราะห์ไฟล์ได้: ${error.message}`,
479
+ line: 1,
480
+ column: 1
481
+ });
482
+ }
483
+ }
484
+
485
+ // 3. หาไฟล์ที่ไม่ได้ใช้งาน
486
+ if (this.analysisRules.checkUnusedFiles) {
487
+ const unusedIssues = this.findUnusedFiles(analysis.dependencies, allProjectFiles, projectPath);
488
+ analysis.issues.push(...unusedIssues);
489
+ analysis.stats.unusedFiles += unusedIssues.length;
490
+ }
491
+
492
+ // 4. ตรวจสอบ Circular Dependencies
493
+ if (this.analysisRules.checkCircularDependencies) {
494
+ const circularIssues = this.findCircularDependencies(analysis.fileGraph, projectPath);
495
+ analysis.issues.push(...circularIssues);
496
+ analysis.stats.circularDependencies += circularIssues.length;
497
+ }
498
+
499
+ // 5. ตรวจสอบ Missing Dependencies ใน package.json
500
+ if (this.analysisRules.checkMissingDependencies) {
501
+ const missingDepIssues = this.checkMissingDependencies(analysis.dependencies, projectPath);
502
+ analysis.issues.push(...missingDepIssues);
503
+ analysis.stats.missingDependencies += missingDepIssues.length;
504
+ }
505
+
506
+ // ========== ADVANCED ANALYSIS (NEW) ==========
507
+
508
+ // 6. วิเคราะห์การเชื่อมต่อ HTML-JavaScript
509
+ if (this.analysisRules.checkHtmlJsLinks) {
510
+ const htmlFiles = finalFileList.filter(f => f.endsWith('.html'));
511
+ const jsFiles = finalFileList.filter(f => f.endsWith('.js') && !f.includes('.min.js'));
512
+
513
+ if (htmlFiles.length > 0 && jsFiles.length > 0) {
514
+ this.statusUpdate(' [Advanced] Running HTML-JavaScript link analysis...');
515
+ console.log(' [Advanced] Running HTML-JavaScript link analysis...');
516
+ const htmlJsIssues = this.analyzeHtmlJsLinks(htmlFiles, jsFiles, projectPath);
517
+ analysis.issues.push(...htmlJsIssues);
518
+ analysis.stats.htmlJsLinkIssues = htmlJsIssues.length;
519
+ }
520
+ }
521
+
522
+ // 7. วิเคราะห์การสื่อสาร IPC
523
+ if (this.analysisRules.checkIpcIntegrity) {
524
+ const rendererFiles = finalFileList.filter(f =>
525
+ (f.endsWith('.js') && !f.includes('main.js')) || f.includes('preload.js') || f.includes('renderer')
526
+ );
527
+ const mainFiles = finalFileList.filter(f =>
528
+ f.includes('main.js') || f.includes('debug-manager.js')
529
+ );
530
+
531
+ this.statusUpdate(' [Advanced] Running IPC communication analysis...');
532
+
533
+ if (rendererFiles.length > 0 && mainFiles.length > 0) {
534
+ console.log(' [Advanced] Running IPC communication analysis...');
535
+ const ipcIssues = this.analyzeIpcIntegrity(rendererFiles, mainFiles, projectPath);
536
+ analysis.issues.push(...ipcIssues);
537
+ analysis.stats.ipcIntegrityIssues = ipcIssues.length;
538
+ }
539
+ }
540
+
541
+ // 8. ตรวจสอบไวยากรณ์ของสถาปัตยกรรม
542
+ if (this.analysisRules.checkArchitectureGrammar) {
543
+ this.statusUpdate(' [Advanced] Running architecture grammar validation...');
544
+ console.log(' [Advanced] Running architecture grammar validation...');
545
+ const architectureIssues = this.validateArchitectureGrammar(projectPath, finalFileList);
546
+ analysis.issues.push(...architectureIssues);
547
+ analysis.stats.architectureGrammarIssues = architectureIssues.length;
548
+ }
549
+
550
+ analysis.totalIssues = analysis.issues.length;
551
+
552
+ // ล้าง cache หลังจากวิเคราะห์เสร็จ
553
+ this.fileContentCache.clear();
554
+
555
+ this.statusUpdate(` Analysis completed: ${analysis.totalIssues} issues found in ${analysis.totalFiles} files`);
556
+ console.log(` Project Inspector completed: ${analysis.totalIssues} issues found in ${analysis.totalFiles} files`);
557
+ return analysis;
558
+
559
+ } catch (error) {
560
+ console.error(' Project Inspector failed:', error);
561
+ throw error;
562
+ }
563
+ }
564
+
565
+ /**
566
+ * วิเคราะห์ปลั๊กอินตามประเภท
567
+ * @param {string} projectPath - เส้นทางของโปรเจกต์
568
+ * @param {string} projectType - ประเภทของโปรเจกต์
569
+ * @returns {Object} - ผลการวิเคราะห์เฉพาะประเภท
570
+ */
571
+ analyzeByProjectType(projectPath, projectType) {
572
+ const typeAnalysis = {
573
+ projectType,
574
+ typeSpecificIssues: [],
575
+ recommendations: []
576
+ };
577
+
578
+ try {
579
+ switch (projectType) {
580
+ case 'node':
581
+ return this.analyzeNodeProject(projectPath, typeAnalysis);
582
+ case 'python':
583
+ return this.analyzePythonProject(projectPath, typeAnalysis);
584
+ case 'php':
585
+ return this.analyzePhpProject(projectPath, typeAnalysis);
586
+ case 'static_html':
587
+ return this.analyzeHtmlProject(projectPath, typeAnalysis);
588
+ default:
589
+ typeAnalysis.recommendations.push('ไม่สามารถระบุประเภทโปรเจกต์ได้ - แนะนำให้เพิ่มไฟล์ manifest');
590
+ return typeAnalysis;
591
+ }
592
+ } catch (error) {
593
+ console.error(` Error analyzing ${projectType} project:`, error);
594
+ typeAnalysis.typeSpecificIssues.push({
595
+ type: 'analysis_error',
596
+ severity: 'high',
597
+ message: `ไม่สามารถวิเคราะห์โปรเจกต์ประเภท ${projectType} ได้: ${error.message}`
598
+ });
599
+ return typeAnalysis;
600
+ }
601
+ }
602
+
603
+ /**
604
+ * วิเคราะห์โปรเจกต์ Node.js
605
+ */
606
+ analyzeNodeProject(projectPath, typeAnalysis) {
607
+ const packageJsonPath = path.join(projectPath, 'package.json');
608
+
609
+ if (fs.existsSync(packageJsonPath)) {
610
+ try {
611
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
612
+
613
+ // ตรวจสอบ main entry point
614
+ if (!packageJson.main && !packageJson.scripts?.start) {
615
+ typeAnalysis.typeSpecificIssues.push({
616
+ type: 'missing_entry_point',
617
+ severity: 'medium',
618
+ message: 'ไม่พบ main entry point หรือ start script ใน package.json'
619
+ });
620
+ typeAnalysis.recommendations.push('เพิ่ม "main": "index.js" หรือ "scripts": {"start": "node index.js"} ใน package.json');
621
+ }
622
+
623
+ // ตรวจสอบ dependencies
624
+ if (!packageJson.dependencies && !packageJson.devDependencies) {
625
+ typeAnalysis.recommendations.push('โปรเจกต์ไม่มี dependencies - ตรวจสอบว่าต้องการ package เพิ่มเติมหรือไม่');
626
+ }
627
+
628
+ } catch (error) {
629
+ typeAnalysis.typeSpecificIssues.push({
630
+ type: 'invalid_package_json',
631
+ severity: 'high',
632
+ message: 'ไฟล์ package.json ไม่ถูกต้อง: ' + error.message
633
+ });
634
+ }
635
+ }
636
+
637
+ return typeAnalysis;
638
+ }
639
+
640
+ /**
641
+ * วิเคราะห์โปรเจกต์ Python
642
+ */
643
+ analyzePythonProject(projectPath, typeAnalysis) {
644
+ const requirementsPath = path.join(projectPath, 'requirements.txt');
645
+
646
+ // ตรวจสอบ requirements.txt
647
+ if (fs.existsSync(requirementsPath)) {
648
+ try {
649
+ const requirements = fs.readFileSync(requirementsPath, 'utf8');
650
+ if (requirements.trim().length === 0) {
651
+ typeAnalysis.recommendations.push('ไฟล์ requirements.txt ว่างเปล่า - พิจารณาเพิ่ม dependencies ที่จำเป็น');
652
+ }
653
+ } catch (error) {
654
+ typeAnalysis.typeSpecificIssues.push({
655
+ type: 'invalid_requirements',
656
+ severity: 'medium',
657
+ message: 'ไม่สามารถอ่านไฟล์ requirements.txt ได้: ' + error.message
658
+ });
659
+ }
660
+ } else {
661
+ typeAnalysis.recommendations.push('แนะนำให้สร้างไฟล์ requirements.txt สำหรับจัดการ Python dependencies');
662
+ }
663
+
664
+ // ตรวจหาไฟล์ main
665
+ const mainFiles = ['main.py', 'app.py', '__main__.py'];
666
+ const hasMainFile = mainFiles.some(file => fs.existsSync(path.join(projectPath, file)));
667
+
668
+ if (!hasMainFile) {
669
+ typeAnalysis.recommendations.push('แนะนำให้มีไฟล์ main entry point เช่น main.py หรือ app.py');
670
+ }
671
+
672
+ return typeAnalysis;
673
+ }
674
+
675
+ /**
676
+ * วิเคราะห์โปรเจกต์ PHP
677
+ */
678
+ analyzePhpProject(projectPath, typeAnalysis) {
679
+ const composerJsonPath = path.join(projectPath, 'composer.json');
680
+
681
+ if (fs.existsSync(composerJsonPath)) {
682
+ try {
683
+ const composerJson = JSON.parse(fs.readFileSync(composerJsonPath, 'utf8'));
684
+
685
+ // ตรวจสอบ autoload
686
+ if (!composerJson.autoload) {
687
+ typeAnalysis.recommendations.push('แนะนำให้เพิ่ม autoload configuration ใน composer.json');
688
+ }
689
+
690
+ } catch (error) {
691
+ typeAnalysis.typeSpecificIssues.push({
692
+ type: 'invalid_composer_json',
693
+ severity: 'high',
694
+ message: 'ไฟล์ composer.json ไม่ถูกต้อง: ' + error.message
695
+ });
696
+ }
697
+ } else {
698
+ typeAnalysis.recommendations.push('แนะนำให้สร้างไฟล์ composer.json สำหรับจัดการ PHP dependencies');
699
+ }
700
+
701
+ // ตรวจหาไฟล์ main
702
+ const mainFiles = ['index.php', 'main.php', 'app.php'];
703
+ const hasMainFile = mainFiles.some(file => fs.existsSync(path.join(projectPath, file)));
704
+
705
+ if (!hasMainFile) {
706
+ typeAnalysis.recommendations.push('แนะนำให้มีไฟล์ entry point เช่น index.php');
707
+ }
708
+
709
+ return typeAnalysis;
710
+ }
711
+
712
+ /**
713
+ * วิเคราะห์โปรเจกต์ HTML
714
+ */
715
+ analyzeHtmlProject(projectPath, typeAnalysis) {
716
+ const indexHtmlPath = path.join(projectPath, 'index.html');
717
+
718
+ if (fs.existsSync(indexHtmlPath)) {
719
+ try {
720
+ const htmlContent = fs.readFileSync(indexHtmlPath, 'utf8');
721
+
722
+ // ตรวจสอบ external resources
723
+ const cssLinks = (htmlContent.match(/<link[^>]*\.css/g) || []).length;
724
+ const jsScripts = (htmlContent.match(/<script[^>]*\.js/g) || []).length;
725
+
726
+ if (cssLinks === 0) {
727
+ typeAnalysis.recommendations.push('ไม่พบไฟล์ CSS - พิจารณาเพิ่ม styling');
728
+ }
729
+
730
+ if (jsScripts === 0) {
731
+ typeAnalysis.recommendations.push('ไม่พบไฟล์ JavaScript - ตรวจสอบว่าเป็น static site หรือต้องการ interactivity');
732
+ }
733
+
734
+ // ตรวจสอบโครงสร้าง HTML พื้นฐาน
735
+ if (!htmlContent.includes('<title>')) {
736
+ typeAnalysis.typeSpecificIssues.push({
737
+ type: 'missing_title',
738
+ severity: 'low',
739
+ message: 'ไม่พบ <title> tag ใน HTML'
740
+ });
741
+ }
742
+
743
+ } catch (error) {
744
+ typeAnalysis.typeSpecificIssues.push({
745
+ type: 'invalid_html',
746
+ severity: 'medium',
747
+ message: 'ไม่สามารถอ่านไฟล์ index.html ได้: ' + error.message
748
+ });
749
+ }
750
+ } else {
751
+ typeAnalysis.typeSpecificIssues.push({
752
+ type: 'missing_index_html',
753
+ severity: 'high',
754
+ message: 'ไม่พบไฟล์ index.html'
755
+ });
756
+ }
757
+
758
+ return typeAnalysis;
759
+ }
760
+
761
+ /**
762
+ * ดึง code snippet รอบๆ บรรทัดที่มีปัญหา
763
+ */
764
+ extractCodeSnippet(filePath, problemLine, contextLines = 2) {
765
+ try {
766
+ // ตรวจสอบ cache ก่อน
767
+ let content;
768
+ if (this.fileContentCache.has(filePath)) {
769
+ content = this.fileContentCache.get(filePath);
770
+ } else {
771
+ content = fs.readFileSync(filePath, 'utf8');
772
+ this.fileContentCache.set(filePath, content);
773
+ }
774
+
775
+ const lines = content.split('\n');
776
+ const startLine = Math.max(0, problemLine - contextLines - 1);
777
+ const endLine = Math.min(lines.length, problemLine + contextLines);
778
+
779
+ const snippetLines = [];
780
+ for (let i = startLine; i < endLine; i++) {
781
+ const lineNumber = i + 1;
782
+ const isErrorLine = lineNumber === problemLine;
783
+ const prefix = isErrorLine ? '>' : ' ';
784
+ const lineNumStr = lineNumber.toString().padStart(3, ' ');
785
+ snippetLines.push(`${prefix} ${lineNumStr} | ${lines[i] || ''}`);
786
+ }
787
+
788
+ return {
789
+ snippet: snippetLines.join('\n'),
790
+ problemLine: lines[problemLine - 1] || '',
791
+ totalLines: lines.length
792
+ };
793
+ } catch (error) {
794
+ return {
795
+ snippet: 'ไม่สามารถอ่านไฟล์ได้',
796
+ problemLine: '',
797
+ totalLines: 0
798
+ };
799
+ }
800
+ }
801
+
802
+ /**
803
+ * สร้าง issue object พร้อม code snippet
804
+ */
805
+ createIssue(type, severity, filePath, line, column, message, suggestion, projectPath) {
806
+ const relativePath = typeof filePath === 'string' && path.isAbsolute(filePath)
807
+ ? path.relative(projectPath || process.cwd(), filePath)
808
+ : filePath;
809
+
810
+ const absolutePath = path.isAbsolute(filePath)
811
+ ? filePath
812
+ : path.resolve(projectPath || process.cwd(), filePath);
813
+
814
+ const codeInfo = this.extractCodeSnippet(absolutePath, line);
815
+
816
+ return {
817
+ type,
818
+ severity,
819
+ file: relativePath,
820
+ line,
821
+ column,
822
+ message,
823
+ suggestion,
824
+ codeSnippet: codeInfo.snippet,
825
+ problemLine: codeInfo.problemLine,
826
+ totalLines: codeInfo.totalLines
827
+ };
828
+ }
829
+
830
+ /**
831
+ * อัปเดต checkSyntax ให้ตรวจเฉพาะไฟล์ JS ที่ไม่ถูกบีบอัด (Professional Version)
832
+ */
833
+ checkSyntax(code, relativePath, projectPath) {
834
+ // ทำงานเฉพาะกับไฟล์ .js และ .mjs เท่านั้น
835
+ if (!relativePath.endsWith('.js') && !relativePath.endsWith('.mjs')) {
836
+ return [];
837
+ }
838
+
839
+ // ข้ามไฟล์ที่ถูกบีบอัดหรือ minified (เพราะมักจะให้ผลลวง)
840
+ const filename = path.basename(relativePath).toLowerCase();
841
+ if (filename.includes('.min.') || filename.includes('.bundle.') || filename.includes('.compiled.')) {
842
+ return [];
843
+ }
844
+
845
+ const issues = [];
846
+
847
+ // ถ้าไม่มี acorn ให้ return array ว่าง
848
+ if (!acorn) {
849
+ return issues;
850
+ }
851
+
852
+ try {
853
+ acorn.parse(code, {
854
+ sourceType: 'module',
855
+ locations: true,
856
+ ecmaVersion: 'latest',
857
+ allowReturnOutsideFunction: true
858
+ });
859
+ } catch (error) {
860
+ if (error instanceof SyntaxError) {
861
+ const issue = this.createIssue(
862
+ 'SyntaxError',
863
+ 'error',
864
+ relativePath,
865
+ error.loc ? error.loc.line : 1,
866
+ error.loc ? error.loc.column : 1,
867
+ `ไวยากรณ์ผิดพลาด: ${error.message}`,
868
+ this.getSyntaxErrorSuggestion(error.message),
869
+ projectPath
870
+ );
871
+ issues.push(issue);
872
+ }
873
+ }
874
+
875
+ return issues;
876
+ }
877
+
878
+ /**
879
+ * วิเคราะห์ Dependencies ของไฟล์
880
+ */
881
+ analyzeDependencies(code, currentFilePath, projectPath, analysis) {
882
+ const issues = [];
883
+
884
+ try {
885
+ const ast = acorn.parse(code, {
886
+ sourceType: 'module',
887
+ locations: true,
888
+ ecmaVersion: 'latest',
889
+ allowReturnOutsideFunction: true
890
+ });
891
+
892
+ const relativePath = path.relative(projectPath, currentFilePath);
893
+ analysis.fileGraph.set(relativePath, []);
894
+
895
+ this.walkAST(ast, (node) => {
896
+ let depPath = null;
897
+ let line = 1;
898
+ let column = 1;
899
+
900
+ // Import statements
901
+ if (node.type === 'ImportDeclaration' && node.source) {
902
+ depPath = node.source.value;
903
+ line = node.source.loc.start.line;
904
+ column = node.source.loc.start.column;
905
+ }
906
+ // Require calls
907
+ else if (node.type === 'CallExpression' &&
908
+ node.callee.name === 'require' &&
909
+ node.arguments.length > 0 &&
910
+ node.arguments[0].type === 'Literal') {
911
+ depPath = node.arguments[0].value;
912
+ line = node.arguments[0].loc.start.line;
913
+ column = node.arguments[0].loc.start.column;
914
+ }
915
+
916
+ if (depPath && typeof depPath === 'string') {
917
+ // เก็บ dependency ไว้ใน graph
918
+ analysis.fileGraph.get(relativePath).push(depPath);
919
+
920
+ // ตรวจสอบเฉพาะ relative imports
921
+ if (depPath.startsWith('./') || depPath.startsWith('../')) {
922
+ const absoluteDepPath = path.resolve(path.dirname(currentFilePath), depPath);
923
+ const relativeDepPath = path.relative(projectPath, absoluteDepPath);
924
+
925
+ analysis.dependencies.set(relativeDepPath, true);
926
+ analysis.dependencies.set(relativeDepPath + '.js', true);
927
+
928
+ // ตรวจสอบว่าไฟล์มีอยู่จริงหรือไม่
929
+ if (!fs.existsSync(absoluteDepPath) &&
930
+ !fs.existsSync(absoluteDepPath + '.js')) {
931
+ const issue = this.createIssue(
932
+ 'MissingFile',
933
+ 'error',
934
+ currentFilePath,
935
+ line,
936
+ column,
937
+ `ไม่พบไฟล์ที่ต้องการ: '${depPath}'`,
938
+ this.getMissingFileSuggestion(depPath, currentFilePath),
939
+ projectPath
940
+ );
941
+ issues.push(issue);
942
+ }
943
+ }
944
+ // ตรวจสอบ npm packages
945
+ else if (!depPath.startsWith('/') && !depPath.includes('node_modules')) {
946
+ analysis.dependencies.set(depPath, true);
947
+ }
948
+ }
949
+ });
950
+
951
+ } catch (error) {
952
+ // ไม่สามารถ parse ได้ แสดงว่ามี syntax error อยู่แล้ว
953
+ }
954
+
955
+ return issues;
956
+ }
957
+
958
+ /**
959
+ * ตรวจสอบ Duplicate Exports
960
+ */
961
+ checkDuplicateExports(code, relativePath, projectPath) {
962
+ const issues = [];
963
+ const exports = new Map();
964
+
965
+ try {
966
+ const ast = acorn.parse(code, {
967
+ sourceType: 'module',
968
+ locations: true,
969
+ ecmaVersion: 'latest',
970
+ allowReturnOutsideFunction: true
971
+ });
972
+
973
+ this.walkAST(ast, (node) => {
974
+ if (node.type === 'ExportNamedDeclaration' && node.declaration) {
975
+ const exportName = node.declaration.id ? node.declaration.id.name : 'anonymous';
976
+
977
+ if (exports.has(exportName)) {
978
+ const issue = this.createIssue(
979
+ 'DuplicateExport',
980
+ 'error',
981
+ relativePath,
982
+ node.loc.start.line,
983
+ node.loc.start.column,
984
+ `Export ซ้ำ: '${exportName}' ถูก export แล้วที่บรรทัด ${exports.get(exportName)}`,
985
+ `ลบ export ที่ซ้ำหรือเปลี่ยนชื่อ export`,
986
+ projectPath
987
+ );
988
+ issues.push(issue);
989
+ } else {
990
+ exports.set(exportName, node.loc.start.line);
991
+ }
992
+ }
993
+ });
994
+
995
+ } catch (error) {
996
+ // ไม่สามารถ parse ได้
997
+ }
998
+
999
+ return issues;
1000
+ }
1001
+
1002
+ /**
1003
+ * ตรวจสอบ Import/Export Mismatch
1004
+ * หาเจอ Runtime Error ที่เกิดจากการ import สิ่งที่ไม่ได้ export จากไฟล์ปลายทาง
1005
+ */
1006
+ checkImportExportMismatch(code, currentFilePath, projectPath) {
1007
+ const issues = [];
1008
+
1009
+ try {
1010
+ const ast = acorn.parse(code, {
1011
+ sourceType: 'module',
1012
+ locations: true,
1013
+ ecmaVersion: 'latest',
1014
+ allowReturnOutsideFunction: true
1015
+ });
1016
+
1017
+ // เก็บรายการ imports ที่ต้องตรวจสอบ
1018
+ const importsToCheck = [];
1019
+
1020
+ this.walkAST(ast, (node) => {
1021
+ // ตรวจสอบ Named Imports เช่น import { NodePalette } from './node-palette.js'
1022
+ if (node.type === 'ImportDeclaration' && node.source) {
1023
+ const modulePath = node.source.value;
1024
+
1025
+ // เช็คเฉพาะ relative imports
1026
+ if (modulePath.startsWith('./') || modulePath.startsWith('../')) {
1027
+ const importedNames = [];
1028
+
1029
+ // รวบรวมชื่อที่ import เข้ามา
1030
+ if (node.specifiers) {
1031
+ node.specifiers.forEach(spec => {
1032
+ if (spec.type === 'ImportSpecifier') {
1033
+ // Named import: import { NodePalette }
1034
+ importedNames.push({
1035
+ name: spec.imported.name,
1036
+ localName: spec.local.name,
1037
+ line: spec.loc.start.line,
1038
+ column: spec.loc.start.column
1039
+ });
1040
+ } else if (spec.type === 'ImportDefaultSpecifier') {
1041
+ // Default import: import NodePalette
1042
+ importedNames.push({
1043
+ name: 'default',
1044
+ localName: spec.local.name,
1045
+ line: spec.loc.start.line,
1046
+ column: spec.loc.start.column
1047
+ });
1048
+ }
1049
+ });
1050
+ }
1051
+
1052
+ if (importedNames.length > 0) {
1053
+ importsToCheck.push({
1054
+ modulePath,
1055
+ importedNames,
1056
+ line: node.loc.start.line,
1057
+ column: node.loc.start.column
1058
+ });
1059
+ }
1060
+ }
1061
+ }
1062
+ });
1063
+
1064
+ // ตรวจสอบแต่ละ import
1065
+ for (const importData of importsToCheck) {
1066
+ const absoluteModulePath = path.resolve(path.dirname(currentFilePath), importData.modulePath);
1067
+ const modulePathWithJs = absoluteModulePath.endsWith('.js') ? absoluteModulePath : absoluteModulePath + '.js';
1068
+
1069
+ // ตรวจสอบว่าไฟล์มีอยู่จริง
1070
+ let targetFilePath = null;
1071
+ if (fs.existsSync(absoluteModulePath)) {
1072
+ targetFilePath = absoluteModulePath;
1073
+ } else if (fs.existsSync(modulePathWithJs)) {
1074
+ targetFilePath = modulePathWithJs;
1075
+ }
1076
+
1077
+ if (targetFilePath) {
1078
+ // อ่านไฟล์ปลายทางและหา exports
1079
+ try {
1080
+ let targetCode;
1081
+ if (this.fileContentCache.has(targetFilePath)) {
1082
+ targetCode = this.fileContentCache.get(targetFilePath);
1083
+ } else {
1084
+ targetCode = fs.readFileSync(targetFilePath, 'utf8');
1085
+ this.fileContentCache.set(targetFilePath, targetCode);
1086
+ }
1087
+
1088
+ const availableExports = this.extractExportsFromCode(targetCode);
1089
+
1090
+ // ตรวจสอบแต่ละ imported name
1091
+ for (const imported of importData.importedNames) {
1092
+ if (!availableExports.has(imported.name)) {
1093
+ const issue = this.createIssue(
1094
+ 'MissingExport',
1095
+ 'error',
1096
+ currentFilePath,
1097
+ importData.line,
1098
+ importData.column,
1099
+ `ไฟล์ '${importData.modulePath}' ไม่ได้ export '${imported.name}' ออกมา`,
1100
+ `ตรวจสอบการ export ในไฟล์ ${importData.modulePath} หรือเปลี่ยนชื่อที่ import ให้ถูกต้อง`,
1101
+ projectPath
1102
+ );
1103
+ issues.push(issue);
1104
+ }
1105
+ }
1106
+ } catch (error) {
1107
+ // ไม่สามารถอ่านไฟล์ปลายทางได้
1108
+ }
1109
+ }
1110
+ }
1111
+
1112
+ } catch (error) {
1113
+ // ไม่สามารถ parse ได้
1114
+ }
1115
+
1116
+ return issues;
1117
+ }
1118
+
1119
+ /**
1120
+ * สกัด exports ทั้งหมดจากโค้ด
1121
+ */
1122
+ extractExportsFromCode(code) {
1123
+ const exports = new Set();
1124
+
1125
+ try {
1126
+ const ast = acorn.parse(code, {
1127
+ sourceType: 'module',
1128
+ locations: true,
1129
+ ecmaVersion: 'latest',
1130
+ allowReturnOutsideFunction: true
1131
+ });
1132
+
1133
+ this.walkAST(ast, (node) => {
1134
+ // Export declarations
1135
+ if (node.type === 'ExportNamedDeclaration') {
1136
+ if (node.declaration) {
1137
+ // export function name() {} หรือ export class Name {}
1138
+ if (node.declaration.id) {
1139
+ exports.add(node.declaration.id.name);
1140
+ }
1141
+ // export const a = 1, b = 2;
1142
+ else if (node.declaration.declarations) {
1143
+ node.declaration.declarations.forEach(decl => {
1144
+ if (decl.id && decl.id.name) {
1145
+ exports.add(decl.id.name);
1146
+ }
1147
+ });
1148
+ }
1149
+ }
1150
+ // export { a, b };
1151
+ else if (node.specifiers) {
1152
+ node.specifiers.forEach(spec => {
1153
+ if (spec.exported) {
1154
+ exports.add(spec.exported.name);
1155
+ }
1156
+ });
1157
+ }
1158
+ }
1159
+ // Default exports
1160
+ else if (node.type === 'ExportDefaultDeclaration') {
1161
+ exports.add('default');
1162
+ }
1163
+ // module.exports pattern (CommonJS)
1164
+ else if (node.type === 'AssignmentExpression' &&
1165
+ node.left.type === 'MemberExpression' &&
1166
+ node.left.object.name === 'module' &&
1167
+ node.left.property.name === 'exports') {
1168
+ exports.add('default');
1169
+ }
1170
+ });
1171
+
1172
+ } catch (error) {
1173
+ // ไม่สามารถ parse ได้
1174
+ }
1175
+
1176
+ return exports;
1177
+ }
1178
+
1179
+ /**
1180
+ * หาไฟล์ที่ไม่ได้ใช้งาน
1181
+ */
1182
+ findUnusedFiles(dependencies, allProjectFiles, projectPath) {
1183
+ const issues = [];
1184
+ const usedFiles = new Set();
1185
+
1186
+ // เก็บรายชื่อไฟล์ที่ถูกใช้งาน
1187
+ dependencies.forEach((_, depPath) => {
1188
+ usedFiles.add(depPath);
1189
+ });
1190
+
1191
+ // หาไฟล์ที่ไม่ได้ใช้งาน
1192
+ allProjectFiles.forEach(file => {
1193
+ if (!usedFiles.has(file) &&
1194
+ !file.includes('main.js') &&
1195
+ !file.includes('index.js') &&
1196
+ !file.includes('preload.js')) {
1197
+ const issue = this.createIssue(
1198
+ 'UnusedFile',
1199
+ 'warning',
1200
+ file,
1201
+ 1,
1202
+ 1,
1203
+ 'ไฟล์นี้ไม่ได้ถูกใช้งานโดยไฟล์อื่นๆ',
1204
+ 'ลบไฟล์ที่ไม่ได้ใช้งาน หรือเพิ่ม import ในไฟล์อื่น',
1205
+ projectPath
1206
+ );
1207
+ issues.push(issue);
1208
+ }
1209
+ });
1210
+
1211
+ return issues;
1212
+ }
1213
+
1214
+ /**
1215
+ * หา Circular Dependencies
1216
+ */
1217
+ findCircularDependencies(fileGraph, projectPath) {
1218
+ const issues = [];
1219
+ const visited = new Set();
1220
+ const recursionStack = new Set();
1221
+
1222
+ const dfs = (file, path = []) => {
1223
+ if (recursionStack.has(file)) {
1224
+ const cycle = [...path, file];
1225
+ const cycleStart = cycle.indexOf(file);
1226
+ const circularPath = cycle.slice(cycleStart);
1227
+
1228
+ const issue = this.createIssue(
1229
+ 'CircularDependency',
1230
+ 'warning',
1231
+ file,
1232
+ 1,
1233
+ 1,
1234
+ `พบการอ้างอิงแบบวงกลม: ${circularPath.join(' -> ')}`,
1235
+ 'ปรับโครงสร้างไฟล์เพื่อหลีกเลี่ยง circular dependency',
1236
+ projectPath
1237
+ );
1238
+ issues.push(issue);
1239
+ return;
1240
+ }
1241
+
1242
+ if (visited.has(file)) return;
1243
+
1244
+ visited.add(file);
1245
+ recursionStack.add(file);
1246
+
1247
+ const dependencies = fileGraph.get(file) || [];
1248
+ for (const dep of dependencies) {
1249
+ if (dep.startsWith('./') || dep.startsWith('../')) {
1250
+ dfs(dep, [...path, file]);
1251
+ }
1252
+ }
1253
+
1254
+ recursionStack.delete(file);
1255
+ };
1256
+
1257
+ for (const file of fileGraph.keys()) {
1258
+ if (!visited.has(file)) {
1259
+ dfs(file);
1260
+ }
1261
+ }
1262
+
1263
+ return issues;
1264
+ }
1265
+
1266
+ /**
1267
+ * ตรวจสอบ Missing Dependencies ใน package.json
1268
+ */
1269
+ checkMissingDependencies(dependencies, projectPath) {
1270
+ // สร้าง Set ของโมดูลพื้นฐานของ Node.js
1271
+ const nodeBuiltins = new Set([
1272
+ 'fs', 'path', 'os', 'crypto', 'events', 'child_process', 'util',
1273
+ 'stream', 'https', 'http', 'url', 'querystring', 'zlib',
1274
+ 'worker_threads', 'cluster', 'net', 'tls', 'dns', 'dgram',
1275
+ 'readline', 'repl', 'vm', 'module', 'assert', 'buffer',
1276
+ 'console', 'process', 'timers', 'string_decoder', 'punycode'
1277
+ ]);
1278
+
1279
+ const issues = [];
1280
+
1281
+ try {
1282
+ const packageJsonPath = path.join(projectPath, 'package.json');
1283
+ if (!fs.existsSync(packageJsonPath)) {
1284
+ return issues;
1285
+ }
1286
+
1287
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
1288
+ const installedDeps = new Set([
1289
+ ...Object.keys(packageJson.dependencies || {}),
1290
+ ...Object.keys(packageJson.devDependencies || {})
1291
+ ]);
1292
+
1293
+ dependencies.forEach((_, depPath) => {
1294
+ // ตรวจสอบเงื่อนไขใหม่ที่ฉลาดขึ้น
1295
+ if (!depPath.startsWith('./') &&
1296
+ !depPath.startsWith('../') &&
1297
+ !path.isAbsolute(depPath) && // ไม่ใช่ path เต็ม
1298
+ !nodeBuiltins.has(depPath) && // ไม่ใช่โมดูลของ Node.js
1299
+ !depPath.includes('.js') &&
1300
+ !installedDeps.has(depPath)) {
1301
+
1302
+ issues.push({
1303
+ type: 'MissingDependency',
1304
+ severity: 'error',
1305
+ file: 'package.json',
1306
+ line: 1,
1307
+ column: 1,
1308
+ message: `ไม่พบ dependency '${depPath}' ใน package.json`,
1309
+ suggestion: `รัน: npm install ${depPath}`
1310
+ });
1311
+ }
1312
+ });
1313
+
1314
+ } catch (error) {
1315
+ // ไม่สามารถอ่าน package.json ได้
1316
+ }
1317
+
1318
+ return issues;
1319
+ }
1320
+
1321
+ /**
1322
+ * เดินทาง AST
1323
+ */
1324
+ walkAST(node, callback) {
1325
+ if (!node || typeof node !== 'object') return;
1326
+
1327
+ callback(node);
1328
+
1329
+ for (const key in node) {
1330
+ if (node.hasOwnProperty(key)) {
1331
+ const child = node[key];
1332
+ if (Array.isArray(child)) {
1333
+ child.forEach(item => this.walkAST(item, callback));
1334
+ } else if (child && typeof child === 'object') {
1335
+ this.walkAST(child, callback);
1336
+ }
1337
+ }
1338
+ }
1339
+ }
1340
+
1341
+ /**
1342
+ * แนะนำแก้ไข Syntax Error
1343
+ */
1344
+ getSyntaxErrorSuggestion(errorMessage) {
1345
+ if (errorMessage.includes('Unexpected token')) {
1346
+ return 'ตรวจสอบเครื่องหมายวรรคตอน เช่น { } ( ) [ ] หรือ ;';
1347
+ }
1348
+ if (errorMessage.includes('Unexpected string')) {
1349
+ return 'ตรวจสอบ quote marks (" หรือ \') ให้ถูกต้อง';
1350
+ }
1351
+ if (errorMessage.includes('Unexpected identifier')) {
1352
+ return 'ตรวจสอบชื่อตัวแปรหรือฟังก์ชัน';
1353
+ }
1354
+ return 'ตรวจสอบไวยากรณ์ JavaScript';
1355
+ }
1356
+
1357
+ /**
1358
+ * แนะนำแก้ไข Missing File
1359
+ */
1360
+ getMissingFileSuggestion(depPath, currentFilePath) {
1361
+ const dir = path.dirname(currentFilePath);
1362
+ const suggestedPath = path.resolve(dir, depPath);
1363
+
1364
+ return `ตรวจสอบว่าไฟล์อยู่ที่ ${suggestedPath} หรือปรับ path ให้ถูกต้อง`;
1365
+ }
1366
+
1367
+ /**
1368
+ * ตั้งค่ากฎการวิเคราะห์
1369
+ */
1370
+ setAnalysisRules(rules) {
1371
+ this.analysisRules = { ...this.analysisRules, ...rules };
1372
+ }
1373
+
1374
+ /**
1375
+ * ได้รับสถิติการวิเคราะห์
1376
+ */
1377
+ getAnalysisStats(analysis) {
1378
+ return {
1379
+ totalFiles: analysis.totalFiles,
1380
+ totalIssues: analysis.totalIssues,
1381
+ severityBreakdown: {
1382
+ error: analysis.issues.filter(i => i.severity === 'error').length,
1383
+ warning: analysis.issues.filter(i => i.severity === 'warning').length,
1384
+ info: analysis.issues.filter(i => i.severity === 'info').length
1385
+ },
1386
+ typeBreakdown: analysis.stats
1387
+ };
1388
+ }
1389
+
1390
+ // ========== ADVANCED ANALYSIS METHODS (NEW) ==========
1391
+
1392
+ /**
1393
+ * HTML-JS Link Analyzer - วิเคราะห์การเชื่อมต่อระหว่าง HTML กับ JavaScript
1394
+ * ตรวจสอบ getElementById, onclick handlers, และ DOM element integrity
1395
+ */
1396
+ analyzeHtmlJsLinks(htmlFiles, jsFiles, projectPath) {
1397
+ if (!cheerio || !acorn) {
1398
+ console.warn(' HTML-JS analysis requires cheerio and acorn packages');
1399
+ return [];
1400
+ }
1401
+
1402
+ const issues = [];
1403
+ console.log(' [HTML-JS] Starting HTML-JavaScript link analysis...');
1404
+
1405
+ // Step 1: Parse HTML files to extract IDs and onclick handlers
1406
+ const htmlData = this.parseHtmlFiles(htmlFiles, projectPath);
1407
+
1408
+ // Step 2: Parse JS files to extract getElementById calls and function declarations
1409
+ const jsData = this.parseJsFiles(jsFiles, projectPath);
1410
+
1411
+ // Step 3: Cross-reference and find mismatches
1412
+
1413
+ // Check for missing element IDs
1414
+ jsData.getElementByIdCalls.forEach(call => {
1415
+ if (!htmlData.elementIds.has(call.id)) {
1416
+ issues.push(this.createIssue(
1417
+ 'MissingElementID',
1418
+ 'error',
1419
+ call.file,
1420
+ call.line,
1421
+ call.column,
1422
+ `getElementById('${call.id}') เรียกใช้ ID ที่ไม่มีอยู่ใน HTML`,
1423
+ `เพิ่ม element ที่มี id="${call.id}" ใน HTML หรือตรวจสอบ ID ให้ถูกต้อง`,
1424
+ projectPath
1425
+ ));
1426
+ }
1427
+ });
1428
+
1429
+ // Check for missing onclick handlers
1430
+ htmlData.onclickHandlers.forEach(handler => {
1431
+ if (!jsData.functionDeclarations.has(handler.functionName)) {
1432
+ issues.push(this.createIssue(
1433
+ 'MissingFunctionHandler',
1434
+ 'error',
1435
+ handler.file,
1436
+ handler.line,
1437
+ 1,
1438
+ `onclick="${handler.functionName}()" เรียกใช้ฟังก์ชันที่ไม่มีอยู่`,
1439
+ `สร้างฟังก์ชัน ${handler.functionName}() ใน JavaScript หรือตรวจสอบชื่อฟังก์ชัน`,
1440
+ projectPath
1441
+ ));
1442
+ }
1443
+ });
1444
+
1445
+ // Check for unused element IDs
1446
+ htmlData.elementIds.forEach((elementInfo, id) => {
1447
+ const isUsed = jsData.getElementByIdCalls.some(call => call.id === id);
1448
+ if (!isUsed && id !== 'app' && id !== 'root') { // ข้าม common framework IDs
1449
+ issues.push(this.createIssue(
1450
+ 'UnusedElementID',
1451
+ 'info',
1452
+ elementInfo.file,
1453
+ elementInfo.line,
1454
+ 1,
1455
+ `Element ID "${id}" ไม่ได้ถูกใช้งานใน JavaScript`,
1456
+ `ลบ ID ที่ไม่จำเป็น หรือเพิ่มโค้ด JavaScript ที่ใช้งาน ID นี้`,
1457
+ projectPath
1458
+ ));
1459
+ }
1460
+ });
1461
+
1462
+ console.log(` [HTML-JS] Analysis complete. Found ${issues.length} issues.`);
1463
+ return issues;
1464
+ }
1465
+
1466
+ /**
1467
+ * IPC Communication Analyzer - วิเคราะห์การสื่อสาร IPC ระหว่าง Renderer Main
1468
+ * ตรวจสอบ ipcRenderer.invoke กับ ipcMain.handle channel integrity
1469
+ */
1470
+ analyzeIpcIntegrity(rendererFiles, mainFiles, projectPath) {
1471
+ if (!acorn) {
1472
+ console.warn(' IPC analysis requires acorn package');
1473
+ return [];
1474
+ }
1475
+
1476
+ const issues = [];
1477
+ console.log(' [IPC] Starting IPC communication analysis...');
1478
+
1479
+ // Step 1: Parse renderer files for ipcRenderer.invoke calls
1480
+ const rendererChannels = this.parseRendererIpcCalls(rendererFiles, projectPath);
1481
+
1482
+ // Step 2: Parse main files for ipcMain.handle definitions
1483
+ const mainHandlers = this.parseMainIpcHandlers(mainFiles, projectPath);
1484
+
1485
+ // Step 3: Cross-reference channels
1486
+
1487
+ // Check for missing IPC handlers
1488
+ rendererChannels.forEach(channel => {
1489
+ if (!mainHandlers.has(channel.name)) {
1490
+ issues.push(this.createIssue(
1491
+ 'MissingIpcHandler',
1492
+ 'error',
1493
+ channel.file,
1494
+ channel.line,
1495
+ channel.column,
1496
+ `ipcRenderer.invoke('${channel.name}') ไม่มี handler ใน Main Process`,
1497
+ `เพิ่ม ipcMain.handle('${channel.name}', ...) ใน main.js`,
1498
+ projectPath
1499
+ ));
1500
+ }
1501
+ });
1502
+
1503
+ // Check for unused IPC handlers
1504
+ mainHandlers.forEach((handlerInfo, channelName) => {
1505
+ const isUsed = rendererChannels.some(channel => channel.name === channelName);
1506
+ if (!isUsed) {
1507
+ issues.push(this.createIssue(
1508
+ 'UnusedIpcHandler',
1509
+ 'warning',
1510
+ handlerInfo.file,
1511
+ handlerInfo.line,
1512
+ 1,
1513
+ `ipcMain.handle('${channelName}') ไม่ได้ถูกเรียกใช้จาก Renderer`,
1514
+ `ลบ handler ที่ไม่ใช้ หรือเพิ่มการเรียกใช้จาก frontend`,
1515
+ projectPath
1516
+ ));
1517
+ }
1518
+ });
1519
+
1520
+ console.log(` [IPC] Analysis complete. Found ${issues.length} issues.`);
1521
+ return issues;
1522
+ }
1523
+
1524
+ /**
1525
+ * Architecture Grammar Validator - ตรวจสอบไวยากรณ์ของสถาปัตยกรรม
1526
+ * ตรวจสอบรูปแบบการจัดวางไฟล์และการตั้งชื่อตามมาตรฐาน
1527
+ */
1528
+ validateArchitectureGrammar(projectPath, fileList) {
1529
+ const issues = [];
1530
+ console.log(' [Architecture] Starting architecture grammar validation...');
1531
+
1532
+ // Rule 1: HTML files should be in root or have corresponding JS files
1533
+ const htmlFiles = fileList.filter(f => f.endsWith('.html'));
1534
+ const jsFiles = fileList.filter(f => f.endsWith('.js'));
1535
+
1536
+ htmlFiles.forEach(htmlFile => {
1537
+ const baseName = path.basename(htmlFile, '.html');
1538
+ const expectedJsFile = jsFiles.find(jsFile =>
1539
+ path.basename(jsFile, '.js') === baseName ||
1540
+ path.basename(jsFile, '.js') === baseName + '.script'
1541
+ );
1542
+
1543
+ if (!expectedJsFile && baseName !== 'splash' && baseName !== 'loading') {
1544
+ const relativePath = path.relative(projectPath, htmlFile);
1545
+ issues.push(this.createIssue(
1546
+ 'MissingCompanionJS',
1547
+ 'warning',
1548
+ relativePath,
1549
+ 1,
1550
+ 1,
1551
+ `HTML file "${baseName}.html" ไม่มีไฟล์ JavaScript คู่`,
1552
+ `สร้างไฟล์ ${baseName}.js สำหรับจัดการ logic ของหน้านี้`,
1553
+ projectPath
1554
+ ));
1555
+ }
1556
+ });
1557
+
1558
+ // Rule 2: Check for proper electron app structure
1559
+ const hasMainJs = fileList.some(f => path.basename(f) === 'main.js');
1560
+ const hasPreloadJs = fileList.some(f => path.basename(f) === 'preload.js');
1561
+ const hasIndexHtml = fileList.some(f => path.basename(f) === 'index.html');
1562
+
1563
+ if (hasMainJs && !hasPreloadJs) {
1564
+ issues.push(this.createIssue(
1565
+ 'MissingPreloadScript',
1566
+ 'warning',
1567
+ 'project structure',
1568
+ 1,
1569
+ 1,
1570
+ 'Electron app ควรมี preload.js สำหรับ security',
1571
+ 'สร้างไฟล์ preload.js เพื่อปรับปรุงความปลอดภัย',
1572
+ projectPath
1573
+ ));
1574
+ }
1575
+
1576
+ if (hasMainJs && !hasIndexHtml) {
1577
+ issues.push(this.createIssue(
1578
+ 'MissingIndexHtml',
1579
+ 'error',
1580
+ 'project structure',
1581
+ 1,
1582
+ 1,
1583
+ 'Electron app ต้องมี index.html เป็นหน้าหลัก',
1584
+ 'สร้างไฟล์ index.html เป็น entry point ของแอป',
1585
+ projectPath
1586
+ ));
1587
+ }
1588
+
1589
+ console.log(` [Architecture] Grammar validation complete. Found ${issues.length} issues.`);
1590
+ return issues;
1591
+ }
1592
+
1593
+ // ========== HELPER METHODS FOR ADVANCED ANALYSIS ==========
1594
+
1595
+ /**
1596
+ * Parse HTML files to extract element IDs and onclick handlers
1597
+ */
1598
+ /**
1599
+ * Parse HTML files to extract element IDs and onclick handlers
1600
+ * เวอร์ชันแก้ไข: เพิ่มการค้นหาหมายเลขบรรทัดจริง
1601
+ */
1602
+ parseHtmlFiles(htmlFiles, projectPath) {
1603
+ const elementIds = new Map();
1604
+ const onclickHandlers = [];
1605
+
1606
+ htmlFiles.forEach(filePath => {
1607
+ try {
1608
+ // 1. อ่านเนื้อหาไฟล์ทั้งหมดเก็บไว้
1609
+ const content = fs.readFileSync(filePath, 'utf-8');
1610
+ const lines = content.split('\n'); // แบ่งเนื้อหาเป็นบรรทัด
1611
+
1612
+ const $ = cheerio.load(content);
1613
+ const relativePath = path.relative(projectPath, filePath);
1614
+
1615
+ // 2. ค้นหา Elements ที่มี ID
1616
+ $('[id]').each((i, elem) => {
1617
+ const id = $(elem).attr('id');
1618
+ if (id) {
1619
+ // 3. ค้นหาหมายเลขบรรทัดของ ID ที่เจอ
1620
+ let lineNumber = 1; // ค่าเริ่มต้น
1621
+ for (let j = 0; j < lines.length; j++) {
1622
+ // ค้นหาบรรทัดที่มี id="your-id" หรือ id='your-id'
1623
+ if (lines[j].includes(`id="${id}"`) || lines[j].includes(`id='${id}'`)) {
1624
+ lineNumber = j + 1; // +1 เพราะ index ของ array เริ่มที่ 0
1625
+ break; // เจอแล้ว หยุดค้นหา
1626
+ }
1627
+ }
1628
+
1629
+ elementIds.set(id, {
1630
+ file: relativePath,
1631
+ line: lineNumber, // ใช้หมายเลขบรรทัดที่หาเจอ
1632
+ tag: elem.tagName
1633
+ });
1634
+ }
1635
+ });
1636
+
1637
+ // ส่วนของ onclick ยังคงทำงานเหมือนเดิม
1638
+ $('[onclick]').each((i, elem) => {
1639
+ const onclick = $(elem).attr('onclick');
1640
+ if (onclick) {
1641
+ const functionMatch = onclick.match(/(\w+)\s*\(/);
1642
+ if (functionMatch) {
1643
+ onclickHandlers.push({
1644
+ functionName: functionMatch[1],
1645
+ file: relativePath,
1646
+ line: 1, // onclick ยังใช้ line 1 ไปก่อนได้
1647
+ element: elem.tagName
1648
+ });
1649
+ }
1650
+ }
1651
+ });
1652
+
1653
+ } catch (error) {
1654
+ console.warn(` Could not parse HTML file: ${filePath}`);
1655
+ }
1656
+ });
1657
+
1658
+ return { elementIds, onclickHandlers };
1659
+ }
1660
+
1661
+ /**
1662
+ * Parse JS files to extract getElementById calls and function declarations
1663
+ */
1664
+ parseJsFiles(jsFiles, projectPath) {
1665
+ const getElementByIdCalls = [];
1666
+ const functionDeclarations = new Set();
1667
+
1668
+ jsFiles.forEach(filePath => {
1669
+ try {
1670
+ const content = fs.readFileSync(filePath, 'utf-8');
1671
+ const relativePath = path.relative(projectPath, filePath);
1672
+
1673
+ // Skip minified files
1674
+ if (filePath.includes('.min.js')) return;
1675
+
1676
+ const ast = acorn.parse(content, {
1677
+ sourceType: 'module',
1678
+ locations: true,
1679
+ ecmaVersion: 'latest',
1680
+ allowReturnOutsideFunction: true
1681
+ });
1682
+
1683
+ this.walkAST(ast, (node) => {
1684
+ // Find getElementById calls
1685
+ if (node.type === 'CallExpression' &&
1686
+ node.callee &&
1687
+ node.callee.type === 'MemberExpression' &&
1688
+ node.callee.property &&
1689
+ node.callee.property.name === 'getElementById' &&
1690
+ node.arguments.length > 0 &&
1691
+ node.arguments[0].type === 'Literal') {
1692
+
1693
+ getElementByIdCalls.push({
1694
+ id: node.arguments[0].value,
1695
+ file: relativePath,
1696
+ line: node.loc ? node.loc.start.line : 1,
1697
+ column: node.loc ? node.loc.start.column : 1
1698
+ });
1699
+ }
1700
+
1701
+ // Find function declarations
1702
+ if (node.type === 'FunctionDeclaration' && node.id) {
1703
+ functionDeclarations.add(node.id.name);
1704
+ }
1705
+
1706
+ // Find function expressions assigned to variables
1707
+ if (node.type === 'VariableDeclarator' &&
1708
+ node.id && node.id.type === 'Identifier' &&
1709
+ node.init && (node.init.type === 'FunctionExpression' || node.init.type === 'ArrowFunctionExpression')) {
1710
+ functionDeclarations.add(node.id.name);
1711
+ }
1712
+ });
1713
+
1714
+ } catch (error) {
1715
+ console.warn(` Could not parse JS file: ${filePath}`);
1716
+ }
1717
+ });
1718
+
1719
+ return { getElementByIdCalls, functionDeclarations };
1720
+ }
1721
+
1722
+ /**
1723
+ * Parse renderer files for ipcRenderer.invoke calls
1724
+ */
1725
+ parseRendererIpcCalls(rendererFiles, projectPath) {
1726
+ const channels = [];
1727
+
1728
+ rendererFiles.forEach(filePath => {
1729
+ try {
1730
+ const content = fs.readFileSync(filePath, 'utf-8');
1731
+ const relativePath = path.relative(projectPath, filePath);
1732
+
1733
+ if (filePath.includes('.min.js')) return;
1734
+
1735
+ const ast = acorn.parse(content, {
1736
+ sourceType: 'module',
1737
+ locations: true,
1738
+ ecmaVersion: 'latest',
1739
+ allowReturnOutsideFunction: true
1740
+ });
1741
+
1742
+ this.walkAST(ast, (node) => {
1743
+ // Find ipcRenderer.invoke calls
1744
+ if (node.type === 'CallExpression' &&
1745
+ node.callee &&
1746
+ node.callee.type === 'MemberExpression' &&
1747
+ node.callee.property &&
1748
+ node.callee.property.name === 'invoke' &&
1749
+ node.arguments.length > 0 &&
1750
+ node.arguments[0].type === 'Literal') {
1751
+
1752
+ channels.push({
1753
+ name: node.arguments[0].value,
1754
+ file: relativePath,
1755
+ line: node.loc ? node.loc.start.line : 1,
1756
+ column: node.loc ? node.loc.start.column : 1
1757
+ });
1758
+ }
1759
+ });
1760
+
1761
+ } catch (error) {
1762
+ console.warn(` Could not parse renderer file: ${filePath}`);
1763
+ }
1764
+ });
1765
+
1766
+ return channels;
1767
+ }
1768
+
1769
+ /**
1770
+ * Parse main files for ipcMain.handle definitions
1771
+ */
1772
+ parseMainIpcHandlers(mainFiles, projectPath) {
1773
+ const handlers = new Map();
1774
+
1775
+ mainFiles.forEach(filePath => {
1776
+ try {
1777
+ const content = fs.readFileSync(filePath, 'utf-8');
1778
+ const relativePath = path.relative(projectPath, filePath);
1779
+
1780
+ const ast = acorn.parse(content, {
1781
+ sourceType: 'module',
1782
+ locations: true,
1783
+ ecmaVersion: 'latest',
1784
+ allowReturnOutsideFunction: true
1785
+ });
1786
+
1787
+ this.walkAST(ast, (node) => {
1788
+ // Find ipcMain.handle calls
1789
+ if (node.type === 'CallExpression' &&
1790
+ node.callee &&
1791
+ node.callee.type === 'MemberExpression' &&
1792
+ node.callee.property &&
1793
+ node.callee.property.name === 'handle' &&
1794
+ node.arguments.length > 0 &&
1795
+ node.arguments[0].type === 'Literal') {
1796
+
1797
+ handlers.set(node.arguments[0].value, {
1798
+ file: relativePath,
1799
+ line: node.loc ? node.loc.start.line : 1
1800
+ });
1801
+ }
1802
+ });
1803
+
1804
+ } catch (error) {
1805
+ console.warn(` Could not parse main file: ${filePath}`);
1806
+ }
1807
+ });
1808
+
1809
+ return handlers;
1810
+ }
1811
+ }
1812
+
1813
+ module.exports = ProjectInspector;
build-desktop.bat ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ chcp 65001 > nul
3
+ title Chahuadev Framework -- Desktop Builder
4
+
5
+ setlocal enabledelayedexpansion
6
+ set "PROJECT_DIR=%~dp0"
7
+ cd /d "%PROJECT_DIR%"
8
+
9
+ echo.
10
+ echo ================================================================
11
+ echo Chahuadev Framework -- Desktop Builder v1.0.0
12
+ echo ================================================================
13
+ echo.
14
+ echo Project : %PROJECT_DIR%
15
+ echo.
16
+
17
+ :menu
18
+ echo Build options:
19
+ echo.
20
+ echo [1] Windows NSIS + Portable (build-win)
21
+ echo [2] Windows NSIS Installer only
22
+ echo [3] Windows Portable only
23
+ echo [4] Windows MSI Installer only
24
+ echo [5] Linux AppImage via WSL
25
+ echo [6] Build exe + AppImage
26
+ echo [7] Clean Delete dist folder
27
+ echo [8] Status View build output
28
+ echo [9] Exit
29
+ echo.
30
+ set /p "choice= > "
31
+
32
+ if "%choice%"=="1" goto build_win
33
+ if "%choice%"=="2" goto build_nsis
34
+ if "%choice%"=="3" goto build_portable
35
+ if "%choice%"=="4" goto build_msi
36
+ if "%choice%"=="5" goto build_linux
37
+ if "%choice%"=="6" goto build_all
38
+ if "%choice%"=="7" goto clean_dist
39
+ if "%choice%"=="8" goto show_status
40
+ if "%choice%"=="9" goto done
41
+
42
+ echo.
43
+ echo [ERROR] Invalid choice. Try again.
44
+ timeout /t 1 >nul
45
+ goto menu
46
+
47
+ REM ----------------------------------------------------------------
48
+ :build_win
49
+ echo.
50
+ echo [BUILD] Windows -- NSIS + Portable...
51
+ echo.
52
+ call npm run build-win
53
+ if %errorlevel% neq 0 (
54
+ echo.
55
+ echo [FAILED] Windows build failed.
56
+ pause
57
+ goto menu
58
+ )
59
+ echo.
60
+ echo [OK] Windows build complete.
61
+ goto show_results
62
+
63
+ REM ----------------------------------------------------------------
64
+ :build_nsis
65
+ echo.
66
+ echo [BUILD] Windows -- NSIS Installer...
67
+ echo.
68
+ call npm run build-nsis
69
+ if %errorlevel% neq 0 (
70
+ echo.
71
+ echo [FAILED] NSIS build failed.
72
+ pause
73
+ goto menu
74
+ )
75
+ echo.
76
+ echo [OK] NSIS build complete.
77
+ goto show_results
78
+
79
+ REM ----------------------------------------------------------------
80
+ :build_portable
81
+ echo.
82
+ echo [BUILD] Windows -- Portable...
83
+ echo.
84
+ call npm run build-exe
85
+ if %errorlevel% neq 0 (
86
+ echo.
87
+ echo [FAILED] Portable build failed.
88
+ pause
89
+ goto menu
90
+ )
91
+ echo.
92
+ echo [OK] Portable build complete.
93
+ goto show_results
94
+
95
+ REM ----------------------------------------------------------------
96
+ :build_msi
97
+ echo.
98
+ echo [BUILD] Windows -- MSI Installer...
99
+ echo.
100
+ call npm run build-msi
101
+ if %errorlevel% neq 0 (
102
+ echo.
103
+ echo [FAILED] MSI build failed.
104
+ pause
105
+ goto menu
106
+ )
107
+ echo.
108
+ echo [OK] MSI build complete.
109
+ goto show_results
110
+
111
+ REM ----------------------------------------------------------------
112
+ :build_linux
113
+ echo.
114
+ echo [BUILD] Linux -- AppImage via WSL...
115
+ echo.
116
+ call npm run build:linux:wsl
117
+ if %errorlevel% neq 0 (
118
+ echo.
119
+ echo [FAILED] Linux build failed.
120
+ echo Make sure WSL and Node.js are installed inside WSL.
121
+ pause
122
+ goto menu
123
+ )
124
+ echo.
125
+ echo [OK] Linux build complete.
126
+ goto show_results
127
+
128
+ REM ----------------------------------------------------------------
129
+ :build_all
130
+ echo.
131
+ echo [!] Make sure Chahuadev Framework app is fully closed before building.
132
+ echo (app.asar will be locked if the app is running)
133
+ echo.
134
+ set /p "confirm= Continue? (y/n): "
135
+ if /i not "%confirm%"=="y" goto menu
136
+ echo.
137
+ echo [BUILD] exe + AppImage...
138
+ echo.
139
+ echo [1/2] Windows Portable (.exe)...
140
+ call npm run build-exe
141
+ if %errorlevel% neq 0 (
142
+ echo [FAILED] exe build failed.
143
+ pause
144
+ goto menu
145
+ )
146
+ echo [OK] exe done.
147
+ echo.
148
+ echo [2/2] Linux AppImage via WSL...
149
+ call npm run build:linux:wsl
150
+ if %errorlevel% neq 0 (
151
+ echo [FAILED] AppImage build failed.
152
+ echo Make sure WSL and Node.js are installed inside WSL.
153
+ pause
154
+ goto menu
155
+ )
156
+ echo [OK] AppImage done.
157
+ echo.
158
+ echo [OK] exe + AppImage builds complete.
159
+ goto show_results
160
+
161
+ REM ----------------------------------------------------------------
162
+ :clean_dist
163
+ echo.
164
+ if exist "dist" (
165
+ echo [INFO] Deleting dist\...
166
+ rmdir /s /q "dist"
167
+ echo [OK] Done.
168
+ ) else (
169
+ echo [INFO] No dist folder found.
170
+ )
171
+ echo.
172
+ pause
173
+ goto menu
174
+
175
+ REM ----------------------------------------------------------------
176
+ :show_status
177
+ echo.
178
+ echo [STATUS] Files in dist\:
179
+ echo.
180
+ if exist "dist" (
181
+ for %%f in ("dist\*.exe" "dist\*.msi" "dist\*.AppImage") do echo %%~nxf
182
+ for /d %%d in ("dist\*") do (
183
+ for %%f in ("%%d\*.exe" "%%d\*.msi" "%%d\*.AppImage") do echo %%~nxf
184
+ )
185
+ ) else (
186
+ echo [INFO] No dist folder. Run a build first.
187
+ )
188
+ echo.
189
+ pause
190
+ goto menu
191
+
192
+ REM ----------------------------------------------------------------
193
+ :show_results
194
+ echo.
195
+ echo ================================================================
196
+ echo Build Results
197
+ echo ================================================================
198
+ echo.
199
+ if exist "dist" (
200
+ for %%f in ("dist\*.exe" "dist\*.msi" "dist\*.AppImage") do echo %%~nxf
201
+ for /d %%d in ("dist\*") do (
202
+ for %%f in ("%%d\*.exe" "%%d\*.msi" "%%d\*.AppImage") do echo %%~nxf
203
+ )
204
+ echo.
205
+ set /p "open_dist= Open dist folder? (y/n): "
206
+ if /i "!open_dist!"=="y" start "" "%PROJECT_DIR%dist"
207
+ ) else (
208
+ echo [INFO] No dist folder found.
209
+ )
210
+ echo.
211
+ pause
212
+ goto menu
213
+
214
+ REM ----------------------------------------------------------------
215
+ :done
216
+ echo.
217
+ echo Goodbye.
218
+ echo.
219
+ endlocal
220
+ exit /b 0
build-linux-wsl.sh ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Build Chahuadev Framework on WSL using native Linux filesystem
3
+
4
+ BUILD_DIR="/tmp/chahuadev-build-$$"
5
+ WINDOWS_PROJECT="/mnt/d/Chahuadev/chahuadev-framework-en"
6
+ OUTPUT_DIR="$WINDOWS_PROJECT/dist"
7
+
8
+ echo "========================================================"
9
+ echo "Chahuadev Framework - Linux Build on WSL (Native FS)"
10
+ echo "========================================================"
11
+ echo ""
12
+
13
+ # Step 1: Create temp build directory
14
+ echo "[1/5] Setting up build environment..."
15
+ mkdir -p "$BUILD_DIR"
16
+ echo " Build directory: $BUILD_DIR"
17
+
18
+ # Step 2: Copy source code to WSL filesystem
19
+ echo ""
20
+ echo "[2/5] Copying project files (this may take a moment)..."
21
+ cp -r "$WINDOWS_PROJECT" "$BUILD_DIR/project"
22
+ if [ $? -ne 0 ]; then
23
+ echo "ERROR: Failed to copy project files"
24
+ rm -rf "$BUILD_DIR"
25
+ exit 1
26
+ fi
27
+ echo " OK - Project copied"
28
+
29
+ # Step 3: Navigate and install dependencies
30
+ echo ""
31
+ echo "[3/5] Installing dependencies..."
32
+ cd "$BUILD_DIR/project"
33
+ npm install 2>&1 | tail -5
34
+ if [ $? -ne 0 ]; then
35
+ echo "ERROR: npm install failed"
36
+ rm -rf "$BUILD_DIR"
37
+ exit 1
38
+ fi
39
+ echo " OK - Dependencies installed"
40
+
41
+ # Step 4: Build
42
+ echo ""
43
+ echo "[4/5] Building Linux distribution (x64)..."
44
+ export NODE_ENV=production
45
+
46
+ npm run generate-checksums
47
+ if [ $? -ne 0 ]; then
48
+ echo "ERROR: generate-checksums failed"
49
+ rm -rf "$BUILD_DIR"
50
+ exit 1
51
+ fi
52
+
53
+ echo ""
54
+ echo "Running electron-builder..."
55
+ npx electron-builder --linux --x64
56
+ BUILD_STATUS=$?
57
+
58
+ # Step 5: Copy output back
59
+ echo ""
60
+ echo "[5/5] Copying build output back to Windows..."
61
+ if [ $BUILD_STATUS -eq 0 ]; then
62
+ # Remove old dist if exists
63
+ rm -rf "$OUTPUT_DIR"
64
+
65
+ # Copy new dist
66
+ cp -r "$BUILD_DIR/project/dist" "$WINDOWS_PROJECT/"
67
+ if [ $? -eq 0 ]; then
68
+ echo " OK - Build output copied"
69
+
70
+ echo ""
71
+ echo "========================================================"
72
+ echo "SUCCESS - Build completed!"
73
+ echo "========================================================"
74
+ echo ""
75
+ echo "Output files:"
76
+ ls -lh "$OUTPUT_DIR"/*.AppImage 2>/dev/null
77
+
78
+ # Cleanup
79
+ rm -rf "$BUILD_DIR"
80
+ exit 0
81
+ else
82
+ echo "ERROR: Failed to copy output"
83
+ fi
84
+ else
85
+ echo "ERROR: Build failed"
86
+ fi
87
+
88
+ # Cleanup on error
89
+ rm -rf "$BUILD_DIR"
90
+ exit 1
build_assets/plugins/.gitkeep ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # This file ensures the plugins directory is tracked by Git
2
+ # The plugins folder will be empty in the build output, ready for user plugins
checksums.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "main.js": "222c0424abcddf6f3e8d3b1baa622f5471a567aac1a8486401cd1800766f53ca",
3
+ "preload.js": "20791ca2e1ccb960af534537300c4c355edcf338391e36ff02e03510dc1664c6",
4
+ "validation_gateway.js": "87d0675b666489c193031d2ea61f265e55cdcdd937932eecbf532ad9e6f0a716",
5
+ "generate-manifests.js": "050cfeadf9aa259b51660cecbceee816f7ce2a6a4f1730454d30ab78aaf7c1f4",
6
+ "modules/error-handler.js": "c6aa70f8ecfe5da280caf5f36ca9f8eedceb90e3ca096e6f110011f5aeee285e",
7
+ "modules/security-logger.js": "04508a07a771d115da42701b70448a2cf005c85a301f83391837ed489142bf28",
8
+ "modules/system-detector.js": "f7e9eb6a608d3a597df013375fd2760db97f790eba460e66f0dc7db138874ef4",
9
+ "modules/button-generator.js": "863923b7922ac7eec544efedb12d33e2e9908fa80531a06b2e12f639d7aa5fbc",
10
+ "modules/plugin-manager.js": "fc0940715218f76b0058327cd8ffe5800a94fee3fc42159ed7dffd99589baffc",
11
+ "modules/executor.js": "3b839dc67b048ecd94c53f2edf92acdf9612cecd697ef410ec27b290c43dd32f",
12
+ "modules/context-manager.js": "179c28cf401d67355d07175fee1a5fa80711c737a11438199f03e9f98bd0d828"
13
+ }
checksums.sig ADDED
@@ -0,0 +1 @@
 
 
1
+ 6bbd8be4b09efae19de6ed991ff91b8cf6fc45d693487bfa289c496048c30b433a7ce1c7898078df3174cd941a4598db56c605ca381106a4708f4870049629122d4409bfe4a3cba879b308ff8a88b5aebac9a450b9365e8d6a5ad919b7a79a2a3abe258d5aa9c663f9e8abf87ce5d51101d3354319b8b41326a7549e90b63552d183522f49c494adf6208235bca08f093ccb27efe180678dc808e1c33ade6e731c6bae59af272c0ab15f955e73a723ee057b892414dd31d1fd31d33d368683b448c0f8235275ef043fba4b925c4e0fe1b52e2b123599429647987bbe024d47d1274be177007cefd6a78da62074d24c807cdef5e36e1e2b3b542b5421ab1b2d68
config/default.json ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_comment": " Chahua Development Thailand - Default Configuration",
3
+ "_author": " CEO: Saharath C.",
4
+ "server": {
5
+ "port": 3000,
6
+ "host": "localhost",
7
+ "cors": {
8
+ "enabled": true,
9
+ "allowedOrigins": [
10
+ "*"
11
+ ],
12
+ "allowedMethods": [
13
+ "GET",
14
+ "POST",
15
+ "PUT",
16
+ "DELETE",
17
+ "OPTIONS"
18
+ ],
19
+ "allowedHeaders": [
20
+ "Content-Type",
21
+ "Authorization",
22
+ "X-Requested-With"
23
+ ]
24
+ }
25
+ },
26
+ "security": {
27
+ "jwt": {
28
+ "secret": "default-secret-change-in-production",
29
+ "expiresIn": "24h",
30
+ "algorithm": "HS256"
31
+ },
32
+ "rateLimit": {
33
+ "windowMs": 900000,
34
+ "maxRequests": 100,
35
+ "skipSuccessfulRequests": false
36
+ },
37
+ "validation": {
38
+ "enabled": true,
39
+ "strictMode": true
40
+ }
41
+ },
42
+ "logging": {
43
+ "level": "info",
44
+ "path": "./chahuadev-framework/logs",
45
+ "maxSize": 10485760,
46
+ "maxFiles": 5,
47
+ "enableConsole": true,
48
+ "enableFile": true
49
+ },
50
+ "cache": {
51
+ "maxSize": 100,
52
+ "defaultTTL": 300000,
53
+ "cleanupInterval": 60000,
54
+ "enablePersistence": false,
55
+ "persistPath": "./chahuadev-framework/logs/cache"
56
+ },
57
+ "retry": {
58
+ "maxAttempts": 3,
59
+ "baseDelay": 1000,
60
+ "maxDelay": 30000,
61
+ "backoffMultiplier": 2,
62
+ "jitter": true
63
+ },
64
+ "rollback": {
65
+ "maxSnapshots": 10,
66
+ "snapshotPath": "./chahuadev-framework/logs/snapshots",
67
+ "autoCleanup": true
68
+ },
69
+ "security_logger": {
70
+ "alertThreshold": 10,
71
+ "enableRealTimeAlerts": true,
72
+ "logPath": "./chahuadev-framework/logs/security",
73
+ "maxLogSize": 10485760,
74
+ "maxLogFiles": 5
75
+ },
76
+ "health": {
77
+ "checkInterval": 30000,
78
+ "thresholds": {
79
+ "cpu": 80,
80
+ "memory": 85,
81
+ "disk": 90
82
+ },
83
+ "enableAutoRecovery": true,
84
+ "alertCooldown": 300000
85
+ },
86
+ "plugins": {
87
+ "hotReload": true,
88
+ "maxExecutionTime": 30000,
89
+ "loadOnStartup": true,
90
+ "enableLogging": true
91
+ },
92
+ "api": {
93
+ "timeout": 10000,
94
+ "maxRetries": 3,
95
+ "enableCaching": true
96
+ },
97
+ "test": {
98
+ "timeout": 5000,
99
+ "parallel": true,
100
+ "coverage": true
101
+ }
102
+ }
config/obfuscator.config.js ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * JavaScript Obfuscator Configuration - Fort-Knox Level
3
+ *
4
+ * การป้องกันระดับสูงสุดสำหรับโค้ด JavaScript
5
+ * ป้องกันการทำ Reverse Engineering และการอ่านโค้ดโดยไม่ได้รับอนุญาต
6
+ *
7
+ * คำเตือน: การตั้งค่าแบบนี้จะทำให้โค้ดช้าลงเล็กน้อย (5-15%)
8
+ * แต่จะเพิ่มความปลอดภัยขึ้นอย่างมาก (90%+ harder to reverse engineer)
9
+ */
10
+
11
+ module.exports = {
12
+ // ===== CORE OBFUSCATION SETTINGS =====
13
+
14
+ // ทำให้ตัวแปรและฟังก์ชันชื่อใหม่ที่อ่านไม่ออก
15
+ identifierNamesGenerator: 'mangled-shuffled', // เปลี่ยนจาก hexadecimal
16
+
17
+ // เข้ารหัสสตริงทั้งหมด (ลดความเข้มงวด)
18
+ stringArray: true,
19
+ stringArrayIndexShift: true,
20
+ stringArrayRotate: true,
21
+ stringArrayShuffle: true,
22
+ stringArrayWrappersCount: 2, // ลดจาก 5
23
+ stringArrayWrappersChainedCalls: true,
24
+ stringArrayWrappersParametersMaxCount: 3, // ลดจาก 5
25
+ stringArrayWrappersType: 'function',
26
+ stringArrayThreshold: 0.8, // ลดจาก 1 (100%)
27
+
28
+ // ===== ANTI-DEBUGGING FEATURES =====
29
+
30
+ // ป้องกันการใช้ Debug Console
31
+ debugProtection: true,
32
+ debugProtectionInterval: 2000, // ตรวจสอบทุก 2 วินาที
33
+
34
+ // ป้องกันการใช้ DevTools
35
+ disableConsoleOutput: true,
36
+
37
+ // ตรวจจับการใช้เครื่องมือ debugging
38
+ selfDefending: true,
39
+
40
+ // ===== CODE FLOW PROTECTION =====
41
+
42
+ // ทำให้โครงสร้างโค้ดซับซ้อน (ลดความเข้มงวด)
43
+ controlFlowFlattening: true,
44
+ controlFlowFlatteningThreshold: 0.5, // ลดจาก 1
45
+
46
+ // สร้าง Dead Code (โค้ดปลอม) เพื่อหลอกลวง (ลดความเข้มงวด)
47
+ deadCodeInjection: true,
48
+ deadCodeInjectionThreshold: 0.2, // ลดจาก 0.5
49
+
50
+ // ===== ADVANCED PROTECTION =====
51
+
52
+ // แบ่ง string ออกเป็นชิ้นเล็กๆ
53
+ splitStrings: true,
54
+ splitStringsChunkLength: 5,
55
+
56
+ // ป้องกันการ beautify โค้ด
57
+ compact: true,
58
+
59
+ // ลบ comments และ whitespace ทั้งหมด
60
+ numbersToExpressions: true,
61
+
62
+ // เปลี่ยนตัวเลขเป็น expression
63
+ simplify: true,
64
+
65
+ // ===== SPECIFIC FOR ELECTRON APPS =====
66
+
67
+ // เป้าหมาย: Node.js environment
68
+ target: 'node',
69
+
70
+ // ไม่ obfuscate require() calls เพื่อไม่ให้แอป Electron พัง
71
+ reservedNames: [
72
+ 'require',
73
+ 'module',
74
+ 'exports',
75
+ '__dirname',
76
+ '__filename',
77
+ 'process',
78
+ 'global',
79
+ 'Buffer',
80
+ // Electron APIs ที่ต้องการ
81
+ 'ipcMain',
82
+ 'ipcRenderer',
83
+ 'BrowserWindow',
84
+ 'app',
85
+ 'dialog',
86
+ 'shell',
87
+ 'contextBridge',
88
+ // เพิ่มชื่อฟังก์ชันสำคัญของเราเองที่ไม่ควรโดน obfuscate
89
+ 'electronAPI',
90
+ 'validationGateway'
91
+ ],
92
+
93
+ // ไม่ obfuscate properties เหล่านี้
94
+ reservedStrings: [
95
+ 'electron',
96
+ 'node_modules',
97
+ 'package.json',
98
+ 'main.js',
99
+ 'preload.js',
100
+ 'renderer.js'
101
+ ],
102
+
103
+ // ===== PERFORMANCE TUNING =====
104
+
105
+ // ปรับให้เร็วขึ้นนิดหน่อย (แลกกับความปลอดภัยเล็กน้อย)
106
+ unicodeEscapeSequence: false, // ปิดเพื่อประสิทธิภาพ
107
+
108
+ // ===== FILES TO EXCLUDE =====
109
+
110
+ // ไม่ obfuscate ไฟล์พิเศษเหล่านี้ (จะตั้งค่าใน script)
111
+ excludes: [
112
+ // ไฟล์ที่ไม่ควร obfuscate
113
+ '**/node_modules/**',
114
+ '**/test/**',
115
+ '**/tests/**',
116
+ '**/spec/**',
117
+ '**/*.test.js',
118
+ '**/*.spec.js',
119
+ '**/vendor/**'
120
+ ]
121
+ };
122
+
123
+ /**
124
+ * คำอธิบายระดับการป้องกัน:
125
+ *
126
+ * BASIC (เหมาะสำหรับ prototype):
127
+ * - stringArray: false
128
+ * - controlFlowFlattening: false
129
+ * - debugProtection: false
130
+ *
131
+ * MEDIUM (เหมาะสำหรับ production ทั่วไป):
132
+ * - stringArray: true, threshold: 0.5
133
+ * - controlFlowFlattening: true, threshold: 0.3
134
+ * - debugProtection: true
135
+ *
136
+ * MAXIMUM (สำหรับแอปที่มีมูลค่าสูง - config นี้):
137
+ * - ทุกอย่างเปิดเต็มที่
138
+ * - Anti-debugging เปิด
139
+ * - Dead code injection
140
+ *
141
+ * Note: ยิ่งการป้องกันสูง โค้ดจะยิ่งช้าและใหญ่ขึ้น
142
+ * แต่จะยากต่อการ reverse engineer มากขึ้นตามไปด้วย
143
+ */
config/production.json ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_comment": " Chahua Development Thailand - Production Configuration",
3
+ "_author": " CEO: Saharath C.",
4
+ "_warning": " PRODUCTION ENVIRONMENT - Use secure values!",
5
+ "server": {
6
+ "port": 8080,
7
+ "host": "0.0.0.0",
8
+ "cors": {
9
+ "enabled": true,
10
+ "allowedOrigins": [
11
+ "https://yourdomain.com",
12
+ "https://api.yourdomain.com"
13
+ ],
14
+ "allowedMethods": [
15
+ "GET",
16
+ "POST",
17
+ "PUT",
18
+ "DELETE"
19
+ ],
20
+ "allowedHeaders": [
21
+ "Content-Type",
22
+ "Authorization"
23
+ ]
24
+ }
25
+ },
26
+ "security": {
27
+ "jwt": {
28
+ "secret": "CHANGE_THIS_TO_SECURE_SECRET_IN_PRODUCTION",
29
+ "expiresIn": "1h",
30
+ "algorithm": "HS256"
31
+ },
32
+ "rateLimit": {
33
+ "windowMs": 900000,
34
+ "maxRequests": 50,
35
+ "skipSuccessfulRequests": true
36
+ },
37
+ "validation": {
38
+ "enabled": true,
39
+ "strictMode": true
40
+ }
41
+ },
42
+ "logging": {
43
+ "level": "warn",
44
+ "path": "/var/log/chahuadev",
45
+ "maxSize": 52428800,
46
+ "maxFiles": 10,
47
+ "enableConsole": false,
48
+ "enableFile": true
49
+ },
50
+ "cache": {
51
+ "maxSize": 1000,
52
+ "defaultTTL": 600000,
53
+ "cleanupInterval": 300000,
54
+ "enablePersistence": true,
55
+ "persistPath": "/var/cache/chahuadev"
56
+ },
57
+ "retry": {
58
+ "maxAttempts": 5,
59
+ "baseDelay": 2000,
60
+ "maxDelay": 60000,
61
+ "backoffMultiplier": 2.5,
62
+ "jitter": true
63
+ },
64
+ "rollback": {
65
+ "maxSnapshots": 50,
66
+ "snapshotPath": "/var/backups/chahuadev/snapshots",
67
+ "autoCleanup": true
68
+ },
69
+ "security_logger": {
70
+ "alertThreshold": 5,
71
+ "enableRealTimeAlerts": true,
72
+ "logPath": "/var/log/chahuadev/security",
73
+ "maxLogSize": 52428800,
74
+ "maxLogFiles": 20
75
+ },
76
+ "health": {
77
+ "checkInterval": 15000,
78
+ "thresholds": {
79
+ "cpu": 75,
80
+ "memory": 80,
81
+ "disk": 85
82
+ },
83
+ "enableAutoRecovery": true,
84
+ "alertCooldown": 600000
85
+ },
86
+ "plugins": {
87
+ "hotReload": false,
88
+ "maxExecutionTime": 10000,
89
+ "loadOnStartup": true,
90
+ "enableLogging": false
91
+ },
92
+ "api": {
93
+ "timeout": 5000,
94
+ "maxRetries": 5,
95
+ "enableCaching": true
96
+ },
97
+ "test": {
98
+ "timeout": 10000,
99
+ "parallel": false,
100
+ "coverage": false
101
+ }
102
+ }
debug-manager.js ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const { BrowserWindow, ipcMain } = require('electron');
2
+ const path = require('path');
3
+
4
+ // --- Command Firewall: Whitelist ของคำสั่งที่ปลอดภัย ---
5
+ const ALLOWED_COMMANDS = new Set([
6
+ // คำสั่งภายในระบบ
7
+ 'help', 'clear', 'workflows', 'cache', 'logs', 'status', 'info', 'test', 'e2e', 'report',
8
+ // คำสั่งภายนอกที่ปลอดภัย
9
+ 'node', 'npm', 'git', 'ping', 'tracert', 'ipconfig', 'ifconfig', 'whoami', 'date', 'time',
10
+ // คำสั่งสำหรับการพัฒนา
11
+ 'npx', 'playwright', 'jest', 'mocha', 'yarn', 'pnpm',
12
+ // คำสั่งระบบพื้นฐาน
13
+ 'echo', 'pwd', 'ls', 'dir', 'hostname', 'uname'
14
+ ]);
15
+
16
+ // --- Blacklist ของคำสั่งอันตราย ---
17
+ const DANGEROUS_COMMANDS = new Set([
18
+ 'rm', 'rmdir', 'del', 'deltree', 'format', 'fdisk', 'mkfs', 'dd',
19
+ 'shutdown', 'reboot', 'halt', 'poweroff', 'init', 'killall', 'pkill',
20
+ 'chmod', 'chown', 'su', 'sudo', 'passwd', 'useradd', 'userdel',
21
+ 'wget', 'curl', 'nc', 'netcat', 'telnet', 'ftp', 'sftp',
22
+ 'eval', 'exec', 'system', 'shell', 'bash', 'sh', 'cmd', 'powershell',
23
+ 'python', 'php', 'perl', 'ruby', 'java', 'javac'
24
+ ]);
25
+
26
+ /**
27
+ * Debug Manager - จัดการหน้าต่าง Hybrid Diagnostic Dashboard
28
+ */
29
+ class DebugManager {
30
+ constructor() {
31
+ this.debugWindow = null;
32
+ this.mainWindow = null; // เพิ่ม property สำหรับ main window
33
+ this.logs = [];
34
+ this.commandHistory = [];
35
+ this.maxLogs = 1000;
36
+ this.maxCommandHistory = 100;
37
+
38
+ this.setupIpcHandlers();
39
+ }
40
+
41
+ /**
42
+ * ตั้งค่า main window reference
43
+ */
44
+ setMainWindow(window) {
45
+ this.mainWindow = window;
46
+ console.log(' Main Window connected to Debug Manager');
47
+ }
48
+
49
+ createDebugWindow() {
50
+ if (this.debugWindow && !this.debugWindow.isDestroyed()) {
51
+ this.debugWindow.focus();
52
+ return;
53
+ }
54
+
55
+ this.debugWindow = new BrowserWindow({
56
+ width: 1600,
57
+ height: 1000,
58
+ minWidth: 1200,
59
+ minHeight: 800,
60
+ webPreferences: {
61
+ nodeIntegration: false,
62
+ contextIsolation: true,
63
+ preload: path.join(__dirname, 'preload.js')
64
+ },
65
+ title: 'Chahuadev Hybrid Diagnostic Dashboard',
66
+ icon: path.join(__dirname, 'src/assets/icons/icon.png'),
67
+ show: false,
68
+ backgroundColor: '#1a1a1a'
69
+ });
70
+
71
+ this.debugWindow.loadFile('debugger.html');
72
+
73
+ this.debugWindow.once('ready-to-show', () => {
74
+ this.debugWindow.show();
75
+ this.sendWelcomeMessage();
76
+ });
77
+
78
+ this.debugWindow.on('closed', () => {
79
+ this.debugWindow = null;
80
+ });
81
+
82
+ console.log(' Hybrid Debug Window สร้างแล้ว');
83
+ }
84
+
85
+ sendWelcomeMessage() {
86
+ if (this.debugWindow && !this.debugWindow.isDestroyed()) {
87
+ this.debugWindow.webContents.send('terminal:welcome', {
88
+ message: 'Hybrid Diagnostic Dashboard ready!',
89
+ timestamp: new Date().toISOString()
90
+ });
91
+ }
92
+ }
93
+
94
+ setupIpcHandlers() {
95
+ // ดึง logs ย้อนหลัง
96
+ ipcMain.handle('diagnostics:get-logs', async (event, options = {}) => {
97
+ const limit = options.limit || 100;
98
+ return this.logs.slice(0, limit);
99
+ });
100
+
101
+ // ดึงข้อมูล health
102
+ ipcMain.handle('diagnostics:get-health', async () => {
103
+ try {
104
+ // Simplified health data without health-monitor dependency
105
+ return {
106
+ cpu: 0, // Placeholder - health monitoring removed
107
+ memory: process.memoryUsage().rss,
108
+ connections: 0, // Placeholder
109
+ uptime: process.uptime()
110
+ };
111
+ } catch (error) {
112
+ console.error('Error getting health metrics:', error);
113
+ return {
114
+ cpu: 0,
115
+ memory: 0,
116
+ connections: 0,
117
+ uptime: process.uptime()
118
+ };
119
+ }
120
+ });
121
+
122
+ // ดึงข้อมูล running workflows - Disabled (workflow engine removed)
123
+ ipcMain.handle('diagnostics:get-workflows', async () => {
124
+ try {
125
+ console.log(' Workflow engine has been removed from system');
126
+ return [];
127
+ } catch (error) {
128
+ console.error('Error getting workflows:', error);
129
+ return [];
130
+ }
131
+ });
132
+
133
+ // Command history
134
+ ipcMain.handle('diagnostics:get-command-history', async () => {
135
+ return this.commandHistory.slice(0, 50); // Return last 50 commands
136
+ });
137
+
138
+ // Clear command history
139
+ ipcMain.handle('diagnostics:clear-command-history', async () => {
140
+ this.commandHistory = [];
141
+ return true;
142
+ });
143
+
144
+ // E2E Testing
145
+ ipcMain.handle('diagnostics:run-e2e-tests', async () => {
146
+ return this.runE2eTests();
147
+ });
148
+
149
+ // Open Test Report
150
+ ipcMain.handle('diagnostics:open-test-report', async () => {
151
+ return this.openTestReport();
152
+ });
153
+
154
+ // Terminal-specific handlers
155
+ ipcMain.handle('terminal:execute-command', async (event, command) => {
156
+ return this.executeTerminalCommand(command);
157
+ });
158
+
159
+ ipcMain.handle('terminal:get-system-info', async () => {
160
+ return {
161
+ platform: process.platform,
162
+ arch: process.arch,
163
+ nodeVersion: process.version,
164
+ pid: process.pid,
165
+ uptime: process.uptime(),
166
+ memory: process.memoryUsage(),
167
+ cwd: process.cwd()
168
+ };
169
+ });
170
+ }
171
+
172
+ async executeTerminalCommand(command) {
173
+ const commandEntry = {
174
+ command,
175
+ timestamp: new Date().toISOString(),
176
+ id: Date.now()
177
+ };
178
+
179
+ this.commandHistory.unshift(commandEntry);
180
+ if (this.commandHistory.length > this.maxCommandHistory) {
181
+ this.commandHistory = this.commandHistory.slice(0, this.maxCommandHistory);
182
+ }
183
+
184
+ // --- Security Check: Command Firewall ---
185
+ const sanitizedCommand = command.trim();
186
+ const commandBase = sanitizedCommand.split(' ')[0].toLowerCase();
187
+
188
+ // ตรวจสอบ Blacklist ก่อน (เพื่อความปลอดภัยสูงสุด)
189
+ if (DANGEROUS_COMMANDS.has(commandBase)) {
190
+ const errorMessage = ` SECURITY ALERT: Command '${commandBase}' is explicitly blocked for security reasons!`;
191
+ console.warn(`[Security] Blocked dangerous command: ${command}`);
192
+ this.sendTerminalMessage(errorMessage, 'error');
193
+ this.sendCommandResult(command, null, errorMessage);
194
+ return { success: false, error: errorMessage, blocked: true };
195
+ }
196
+
197
+ // ตรวจสอบ Whitelist
198
+ if (!ALLOWED_COMMANDS.has(commandBase)) {
199
+ const errorMessage = ` Command '${commandBase}' is not whitelisted. Only approved commands are allowed.`;
200
+ console.warn(`[Security] Blocked non-whitelisted command: ${command}`);
201
+ this.sendTerminalMessage(errorMessage, 'error');
202
+ this.sendCommandResult(command, null, errorMessage);
203
+ return { success: false, error: errorMessage, blocked: true };
204
+ }
205
+
206
+ // คำสั่งผ่านการตรวจสอบแล้ว
207
+ console.log(`[Security] Command approved: ${command}`);
208
+
209
+ // Broadcast command to debug window
210
+ if (this.debugWindow && !this.debugWindow.isDestroyed()) {
211
+ this.debugWindow.webContents.send('terminal:command-executed', commandEntry);
212
+ }
213
+
214
+ // จัดการคำสั่งภายในระบบ
215
+ if (commandBase === 'help') {
216
+ return this.handleHelpCommand();
217
+ // Clear command removed - prevents clearing of real-time logs
218
+ } else if (commandBase === 'status') {
219
+ return this.handleStatusCommand();
220
+ } else if (commandBase === 'e2e') {
221
+ return this.runE2eTests();
222
+ } else if (commandBase === 'report') {
223
+ return this.openTestReport();
224
+ } else {
225
+ // สำหรับคำสั่งภายนอก ให้จำลองการทำงาน (ไม่รันจริง)
226
+ return this.handleExternalCommand(sanitizedCommand);
227
+ }
228
+ }
229
+
230
+ // --- Security Command Handlers ---
231
+
232
+ handleHelpCommand() {
233
+ const helpText = `
234
+ Secure Terminal Commands:
235
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
236
+
237
+ System Commands:
238
+ help - Show this help message
239
+ clear - Clear terminal screen
240
+ status - Show system status
241
+ info - Show system information
242
+
243
+ Testing Commands:
244
+ e2e - Run E2E tests
245
+ report - Open test report
246
+
247
+ Diagnostic Commands:
248
+ logs - Show system logs
249
+ workflows - Show running workflows
250
+ cache - Show cache information
251
+
252
+ Security Notice:
253
+ Only whitelisted commands are allowed
254
+ Dangerous commands are blocked for security
255
+ All commands are logged for audit
256
+
257
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━���━━━━━━━━━━━━━━━━
258
+ `;
259
+
260
+ this.sendTerminalMessage(helpText, 'info');
261
+ return { success: true, output: helpText };
262
+ }
263
+
264
+ handleClearCommand() {
265
+ if (this.debugWindow && !this.debugWindow.isDestroyed()) {
266
+ this.debugWindow.webContents.send('terminal:clear');
267
+ }
268
+ return { success: true, output: 'Terminal cleared' };
269
+ }
270
+
271
+ handleStatusCommand() {
272
+ const stats = this.getStats();
273
+ const statusText = `
274
+ System Status:
275
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
276
+ Logs: ${stats.totalLogs}
277
+ Commands: ${stats.totalCommands}
278
+ Debug Window: ${stats.isWindowOpen ? 'Open' : 'Closed'}
279
+ Uptime: ${Math.floor(stats.uptime)}s
280
+ Memory: ${Math.round(stats.memoryUsage.rss / 1024 / 1024)} MB
281
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
282
+ `;
283
+
284
+ this.sendTerminalMessage(statusText, 'info');
285
+ return { success: true, output: statusText };
286
+ }
287
+
288
+ handleExternalCommand(command) {
289
+ // จำลองการทำงานของคำสั่งภายนอกโดยไม่รันจริง
290
+ const simulatedOutput = `
291
+ Security Mode: External command simulation
292
+ Command: ${command}
293
+ Status: Approved but not executed for security reasons
294
+ Note: This is a simulated response to prevent potential security risks
295
+ `;
296
+
297
+ this.sendTerminalMessage(simulatedOutput, 'info');
298
+ this.sendCommandResult(command, simulatedOutput);
299
+ return { success: true, output: simulatedOutput, simulated: true };
300
+ }
301
+
302
+ // เพิ่ม log ใหม่
303
+ addLog(logData) {
304
+ const processedLog = {
305
+ id: Date.now() + Math.random(),
306
+ timestamp: logData.timestamp || new Date().toISOString(),
307
+ level: logData.level || 'info',
308
+ source: logData.source || 'System',
309
+ message: logData.message || '',
310
+ error: logData.error || null,
311
+ stack: logData.stack || null,
312
+ context: logData.context || {},
313
+ filePath: logData.filePath || null,
314
+ lineNumber: logData.lineNumber || null,
315
+ functionName: logData.functionName || null,
316
+ codeSnippet: logData.codeSnippet || null
317
+ };
318
+
319
+ this.logs.unshift(processedLog);
320
+
321
+ // จำกัดจำนวน logs
322
+ if (this.logs.length > this.maxLogs) {
323
+ this.logs = this.logs.slice(0, this.maxLogs);
324
+ }
325
+
326
+ // ส่งไปยัง debug window ถ้าเปิดอยู่
327
+ if (this.debugWindow && !this.debugWindow.isDestroyed()) {
328
+ this.debugWindow.webContents.send('diagnostic:new-log', processedLog);
329
+ this.debugWindow.webContents.send('terminal:new-log', processedLog);
330
+ }
331
+ }
332
+
333
+ // ส่งข้อมูล health update
334
+ sendHealthUpdate(healthData) {
335
+ if (this.debugWindow && !this.debugWindow.isDestroyed()) {
336
+ this.debugWindow.webContents.send('diagnostic:health-update', healthData);
337
+ }
338
+ }
339
+
340
+ // ส่งข้อมูล workflows update
341
+ sendWorkflowsUpdate(workflowsData) {
342
+ if (this.debugWindow && !this.debugWindow.isDestroyed()) {
343
+ this.debugWindow.webContents.send('diagnostic:workflows-update', workflowsData);
344
+ }
345
+ }
346
+
347
+ // ส่งข้อความไปยัง terminal
348
+ sendTerminalMessage(message, type = 'info') {
349
+ console.log(`[DebugManager] Sending terminal message: ${message} (type: ${type})`);
350
+ if (this.debugWindow && !this.debugWindow.isDestroyed()) {
351
+ this.debugWindow.webContents.send('terminal:message', {
352
+ message,
353
+ type,
354
+ timestamp: new Date().toISOString()
355
+ });
356
+ console.log(`[DebugManager] Terminal message sent successfully`);
357
+ } else {
358
+ console.log(`[DebugManager] Debug window is not available or destroyed`);
359
+ }
360
+ }
361
+
362
+ // ส่งผลลัพธ์คำสั่งไปยัง terminal
363
+ sendCommandResult(command, result, error = null) {
364
+ if (this.debugWindow && !this.debugWindow.isDestroyed()) {
365
+ this.debugWindow.webContents.send('terminal:command-result', {
366
+ command,
367
+ result,
368
+ error,
369
+ timestamp: new Date().toISOString()
370
+ });
371
+ }
372
+ }
373
+
374
+ // ปิด debug window
375
+ closeDebugWindow() {
376
+ if (this.debugWindow && !this.debugWindow.isDestroyed()) {
377
+ this.debugWindow.close();
378
+ }
379
+ }
380
+
381
+ // ตรวจสอบว่�� debug window เปิดอยู่หรือไม่
382
+ isDebugWindowOpen() {
383
+ return this.debugWindow && !this.debugWindow.isDestroyed();
384
+ }
385
+
386
+ // รับข้อมูลสถิติ
387
+ getStats() {
388
+ return {
389
+ totalLogs: this.logs.length,
390
+ totalCommands: this.commandHistory.length,
391
+ isWindowOpen: this.isDebugWindowOpen(),
392
+ uptime: process.uptime(),
393
+ memoryUsage: process.memoryUsage()
394
+ };
395
+ }
396
+
397
+ // เคลียร์ข้อมูลทั้งหมด
398
+ clearAllData() {
399
+ this.logs = [];
400
+ this.commandHistory = [];
401
+
402
+ if (this.debugWindow && !this.debugWindow.isDestroyed()) {
403
+ this.debugWindow.webContents.send('terminal:clear-all');
404
+ }
405
+ }
406
+
407
+ // Export logs
408
+ exportLogs(filepath) {
409
+ const fs = require('fs');
410
+ const exportData = {
411
+ timestamp: new Date().toISOString(),
412
+ logs: this.logs,
413
+ commandHistory: this.commandHistory,
414
+ stats: this.getStats()
415
+ };
416
+
417
+ fs.writeFileSync(filepath, JSON.stringify(exportData, null, 2));
418
+ return true;
419
+ }
420
+
421
+ // E2E Testing ระบบ - เวอร์ชันแก้ไข: แก้ปัญหา CLI ไม่รันคำสั่ง
422
+ async runE2eTests() {
423
+ const { spawn } = require('child_process');
424
+ const path = require('path');
425
+
426
+ this.sendTerminalMessage(' Launching E2E tests in a new CLI window...', 'info');
427
+
428
+ try {
429
+ const projectRoot = process.cwd();
430
+ const testCommand = `cd /d "${projectRoot}" && npx playwright test && echo. && echo. && echo ================================= && echo. && echo E2E Tests Finished. && echo. && echo ================================= && pause || echo. && echo. && echo ================================= && echo. && echo E2E Tests Failed. && echo. && echo ================================= && pause`;
431
+
432
+ const terminalProcess = spawn('cmd.exe', ['/k', testCommand], {
433
+ detached: true,
434
+ stdio: 'ignore'
435
+ // shell: true <-- เอาบรรทัดนี้ออก
436
+ });
437
+
438
+ terminalProcess.unref();
439
+
440
+ const successMessage = ' E2E tests started in a new CLI window.';
441
+ this.sendTerminalMessage(successMessage, 'success');
442
+
443
+ return {
444
+ success: true,
445
+ message: successMessage
446
+ };
447
+
448
+ } catch (error) {
449
+ const errorMessage = ` Failed to launch E2E test window: ${error.message}`;
450
+ this.sendTerminalMessage(errorMessage, 'error');
451
+
452
+ return {
453
+ success: false,
454
+ error: error.message
455
+ };
456
+ }
457
+ }
458
+
459
+ // เปิดรายงานผลการทดสอบ HTML
460
+ async openTestReport() {
461
+ const { shell } = require('electron');
462
+ const path = require('path');
463
+ const fs = require('fs');
464
+
465
+ try {
466
+ const testResultsPath = path.join(process.cwd(), 'test-results');
467
+ const indexPath = path.join(testResultsPath, 'index.html');
468
+
469
+ this.sendTerminalMessage('Checking for test report...', 'info');
470
+
471
+ // ตรวจสอบว่ามีไฟล์รายงานหรือไม่
472
+ if (!fs.existsSync(indexPath)) {
473
+ return {
474
+ success: false,
475
+ error: 'ไม่พบรายงานผลการทดสอบ - โปรดรันการทดสอบ E2E ก่อน'
476
+ };
477
+ }
478
+
479
+ // เปิดไฟล์รายงานด้วย default browser
480
+ await shell.openPath(indexPath);
481
+
482
+ this.sendTerminalMessage('HTML Test Report opened successfully', 'success');
483
+
484
+ return {
485
+ success: true,
486
+ message: 'เปิดรายงานผลการทดสอบใน Browser แล้ว',
487
+ reportPath: indexPath
488
+ };
489
+ } catch (error) {
490
+ const errorMessage = `Failed to open test report: ${error.message}`;
491
+ this.sendTerminalMessage(errorMessage, 'error');
492
+
493
+ return {
494
+ success: false,
495
+ error: error.message
496
+ };
497
+ }
498
+ }
499
+ }
500
+
501
+ module.exports = DebugManager;
debugger.html ADDED
@@ -0,0 +1,884 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="th">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>แดชบอร์ดวินิจฉัยระบบ Chahua Development</title>
7
+ <style>
8
+ /* --- CSS Variables for Clean Theme (Based on chahua_license) --- */
9
+ :root {
10
+ --bg-color: #f8f9fa;
11
+ --surface-color: #ffffff;
12
+ --primary-text-color: #212529;
13
+ --secondary-text-color: #6c757d;
14
+ --accent-color: #0056b3;
15
+ --accent-hover-color: #004085;
16
+ --border-color: #dee2e6;
17
+ --shadow-color: rgba(0, 0, 0, 0.1);
18
+ --success-color: #28a745;
19
+ --warning-color: #ffc107;
20
+ --danger-color: #dc3545;
21
+ --info-color: #17a2b8;
22
+ --terminal-bg: #2d3748;
23
+ --terminal-border: #4a5568;
24
+ --font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
25
+ --border-radius: 12px;
26
+ --shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
27
+ --transition: all 0.3s ease;
28
+ }
29
+
30
+ * {
31
+ margin: 0;
32
+ padding: 0;
33
+ box-sizing: border-box;
34
+ }
35
+
36
+ body {
37
+ font-family: var(--font-family);
38
+ background: var(--bg-color);
39
+ color: var(--primary-text-color);
40
+ line-height: 1.6;
41
+ overflow: hidden;
42
+ height: 100vh;
43
+ width: 100vw;
44
+ }
45
+
46
+ /* Main Container Layout */
47
+ .dashboard-container {
48
+ display: flex;
49
+ height: 100vh;
50
+ gap: 20px;
51
+ padding: 20px;
52
+ position: relative;
53
+ }
54
+
55
+ /* Left Panel - Terminal Section */
56
+ .terminal-panel {
57
+ background: var(--terminal-bg);
58
+ border-radius: var(--border-radius);
59
+ color: #ffffff;
60
+ font-family: 'Courier New', monospace;
61
+ box-shadow: var(--shadow);
62
+ display: flex;
63
+ flex-direction: column;
64
+ overflow: hidden;
65
+ border: 1px solid var(--border-color);
66
+ flex: 0 0 auto;
67
+ position: relative;
68
+ min-width: 400px;
69
+ max-width: 75%;
70
+ width: calc(60% - 10px);
71
+ }
72
+
73
+ .terminal-header {
74
+ background: rgba(0, 86, 179, 0.1);
75
+ padding: 15px 20px;
76
+ border-bottom: 1px solid var(--border-color);
77
+ display: flex;
78
+ align-items: center;
79
+ justify-content: space-between;
80
+ }
81
+
82
+ .terminal-title {
83
+ color: var(--accent-color);
84
+ font-size: 1.1rem;
85
+ margin: 0;
86
+ font-weight: 600;
87
+ display: flex;
88
+ align-items: center;
89
+ gap: 10px;
90
+ }
91
+
92
+ .terminal-controls {
93
+ display: flex;
94
+ gap: 8px;
95
+ }
96
+
97
+ .terminal-btn {
98
+ background: var(--surface-color);
99
+ color: var(--accent-color);
100
+ border: 1px solid var(--border-color);
101
+ padding: 6px 12px;
102
+ border-radius: var(--border-radius);
103
+ cursor: pointer;
104
+ font-size: 0.8rem;
105
+ font-weight: 500;
106
+ transition: var(--transition);
107
+ white-space: nowrap;
108
+ }
109
+
110
+ .terminal-btn:hover {
111
+ background: var(--accent-color);
112
+ color: white;
113
+ border-color: var(--accent-color);
114
+ transform: translateY(-2px);
115
+ box-shadow: 0 4px 8px rgba(0, 86, 179, 0.2);
116
+ }
117
+
118
+ .terminal-btn:disabled {
119
+ background: var(--bg-color);
120
+ color: var(--secondary-text-color);
121
+ cursor: not-allowed;
122
+ border-color: var(--border-color);
123
+ transform: none;
124
+ box-shadow: none;
125
+ }
126
+
127
+ .terminal-btn.export-btn {
128
+ background: var(--success-color);
129
+ border-color: var(--success-color);
130
+ color: white;
131
+ }
132
+
133
+ .terminal-btn.export-btn:hover:not(:disabled) {
134
+ background: #1e7e34;
135
+ border-color: #1e7e34;
136
+ }
137
+
138
+ #terminal-container {
139
+ flex: 1;
140
+ padding: 20px;
141
+ background: var(--terminal-bg);
142
+ overflow: hidden;
143
+ font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
144
+ font-size: 0.9rem;
145
+ line-height: 1.4;
146
+ }
147
+
148
+ /* Resize Handle */
149
+ .resize-handle {
150
+ position: absolute;
151
+ top: 0;
152
+ right: -10px;
153
+ width: 20px;
154
+ height: 100%;
155
+ cursor: col-resize;
156
+ background: transparent;
157
+ z-index: 10;
158
+ user-select: none;
159
+ display: flex;
160
+ align-items: center;
161
+ justify-content: center;
162
+ }
163
+
164
+ .resize-handle::before {
165
+ content: '';
166
+ width: 4px;
167
+ height: 40px;
168
+ background: var(--border-color);
169
+ border-radius: 2px;
170
+ transition: var(--transition);
171
+ }
172
+
173
+ .resize-handle:hover::before {
174
+ background: var(--accent-color);
175
+ opacity: 0.7;
176
+ }
177
+
178
+ .resize-handle.resizing::before {
179
+ background: var(--accent-color);
180
+ opacity: 1;
181
+ box-shadow: 0 0 10px rgba(0, 86, 179, 0.5);
182
+ }
183
+
184
+ .dashboard-container.resizing {
185
+ user-select: none;
186
+ }
187
+
188
+ .dashboard-container.resizing * {
189
+ pointer-events: none;
190
+ }
191
+
192
+ .dashboard-container.resizing .resize-handle {
193
+ pointer-events: auto;
194
+ }
195
+
196
+ /* Right Panel - Analysis Panel */
197
+ .analysis-panel {
198
+ background: var(--surface-color);
199
+ border-radius: var(--border-radius);
200
+ box-shadow: var(--shadow);
201
+ overflow: hidden;
202
+ border: 1px solid var(--border-color);
203
+ flex: 1;
204
+ min-width: 300px;
205
+ display: flex;
206
+ flex-direction: column;
207
+ }
208
+
209
+ .analysis-header {
210
+ background: var(--surface-color);
211
+ padding: 20px;
212
+ border-bottom: 1px solid var(--border-color);
213
+ }
214
+
215
+ .analysis-title {
216
+ color: var(--accent-color);
217
+ font-size: 1.3rem;
218
+ font-weight: 600;
219
+ margin: 0;
220
+ text-align: center;
221
+ }
222
+
223
+ .analysis-content {
224
+ flex: 1;
225
+ overflow-y: auto;
226
+ padding: 20px;
227
+ }
228
+
229
+ /* Inspector Panel */
230
+ .inspector-panel {
231
+ background: var(--surface-color);
232
+ border-radius: var(--border-radius);
233
+ border: 1px solid var(--border-color);
234
+ overflow: hidden;
235
+ }
236
+
237
+ .inspector-header {
238
+ display: flex;
239
+ justify-content: space-between;
240
+ align-items: center;
241
+ flex-wrap: wrap;
242
+ gap: 10px;
243
+ padding: 15px 20px;
244
+ background: rgba(0, 86, 179, 0.05);
245
+ border-bottom: 1px solid var(--border-color);
246
+ }
247
+
248
+ .inspector-title {
249
+ color: var(--accent-color);
250
+ font-size: 1.1rem;
251
+ font-weight: 600;
252
+ display: flex;
253
+ align-items: center;
254
+ gap: 8px;
255
+ }
256
+
257
+ .inspector-controls {
258
+ display: flex;
259
+ gap: 8px;
260
+ flex-wrap: wrap;
261
+ }
262
+
263
+ .inspector-content {
264
+ padding: 20px;
265
+ display: flex;
266
+ flex-direction: column;
267
+ gap: 15px;
268
+ }
269
+
270
+ /* Inspector Stats */
271
+ .inspector-stats {
272
+ background: rgba(0, 86, 179, 0.05);
273
+ border-radius: var(--border-radius);
274
+ padding: 15px;
275
+ border: 1px solid var(--border-color);
276
+ }
277
+
278
+ .stats-row {
279
+ display: flex;
280
+ justify-content: space-around;
281
+ gap: 10px;
282
+ margin-bottom: 10px;
283
+ }
284
+
285
+ .stat-item {
286
+ text-align: center;
287
+ }
288
+
289
+ .stat-label {
290
+ color: var(--secondary-text-color);
291
+ font-size: 0.85rem;
292
+ margin-bottom: 5px;
293
+ }
294
+
295
+ .stat-value {
296
+ color: var(--primary-text-color);
297
+ font-size: 1.5rem;
298
+ font-weight: bold;
299
+ }
300
+
301
+ .stat-error {
302
+ color: var(--danger-color);
303
+ }
304
+
305
+ .stat-warning {
306
+ color: var(--warning-color);
307
+ }
308
+
309
+ /* Inspector Filters */
310
+ .inspector-filters {
311
+ background: var(--surface-color);
312
+ border-radius: var(--border-radius);
313
+ padding: 15px;
314
+ border: 1px solid var(--border-color);
315
+ }
316
+
317
+ .filter-group {
318
+ margin-bottom: 10px;
319
+ display: flex;
320
+ align-items: center;
321
+ gap: 10px;
322
+ }
323
+
324
+ .filter-group label {
325
+ color: var(--secondary-text-color);
326
+ font-size: 0.9rem;
327
+ font-weight: 500;
328
+ min-width: 120px;
329
+ }
330
+
331
+ .filter-group select {
332
+ flex: 1;
333
+ padding: 8px 12px;
334
+ border: 1px solid var(--border-color);
335
+ border-radius: var(--border-radius);
336
+ background: var(--surface-color);
337
+ color: var(--primary-text-color);
338
+ font-size: 0.9rem;
339
+ transition: var(--transition);
340
+ }
341
+
342
+ .filter-group select:focus {
343
+ outline: none;
344
+ border-color: var(--accent-color);
345
+ box-shadow: 0 0 0 2px rgba(0, 86, 179, 0.2);
346
+ }
347
+
348
+ /* Inspector Results */
349
+ .inspector-results {
350
+ background: var(--surface-color);
351
+ border-radius: var(--border-radius);
352
+ padding: 20px;
353
+ border: 1px solid var(--border-color);
354
+ min-height: 200px;
355
+ }
356
+
357
+ .no-selection {
358
+ text-align: center;
359
+ color: var(--secondary-text-color);
360
+ padding: 30px;
361
+ }
362
+
363
+ .no-selection i {
364
+ font-size: 3rem;
365
+ margin-bottom: 20px;
366
+ color: var(--border-color);
367
+ }
368
+
369
+ .no-selection h3 {
370
+ color: var(--primary-text-color);
371
+ margin-bottom: 10px;
372
+ font-size: 1.2rem;
373
+ }
374
+
375
+ /* Code Snippet */
376
+ .code-snippet {
377
+ background: var(--terminal-bg) !important;
378
+ color: #c9d1d9;
379
+ font-family: 'Consolas', 'Courier New', monospace;
380
+ white-space: pre;
381
+ overflow-x: auto;
382
+ border: 1px solid var(--border-color);
383
+ border-radius: var(--border-radius);
384
+ padding: 15px;
385
+ margin: 10px 0;
386
+ font-size: 0.85rem;
387
+ line-height: 1.4;
388
+ }
389
+
390
+ /* Detail Section */
391
+ .detail-section {
392
+ margin-bottom: 20px;
393
+ }
394
+
395
+ .detail-label {
396
+ color: var(--accent-color);
397
+ font-weight: 600;
398
+ margin-bottom: 8px;
399
+ font-size: 0.9rem;
400
+ }
401
+
402
+ .detail-value {
403
+ background: rgba(0, 86, 179, 0.05);
404
+ padding: 12px;
405
+ border-radius: var(--border-radius);
406
+ font-family: 'Courier New', monospace;
407
+ white-space: pre-wrap;
408
+ word-break: break-word;
409
+ border: 1px solid var(--border-color);
410
+ font-size: 0.85rem;
411
+ }
412
+
413
+ /* Scrollbar */
414
+ ::-webkit-scrollbar {
415
+ width: 8px;
416
+ }
417
+
418
+ ::-webkit-scrollbar-track {
419
+ background: var(--bg-color);
420
+ }
421
+
422
+ ::-webkit-scrollbar-thumb {
423
+ background: var(--border-color);
424
+ border-radius: 4px;
425
+ }
426
+
427
+ ::-webkit-scrollbar-thumb:hover {
428
+ background: var(--secondary-text-color);
429
+ }
430
+
431
+ /* CSS สำหรับ Log Viewer ใหม่ */
432
+ .log-viewer-container {
433
+ flex: 1;
434
+ background: #0d1117; /* สีดำสนิท */
435
+ color: #c9d1d9; /* สีเทาอ่อน */
436
+ font-family: 'Consolas', 'Courier New', monospace;
437
+ font-size: 13px;
438
+ padding: 15px;
439
+ overflow-y: auto; /* ทำให้เลื่อนได้เมื่อ Log ยาว */
440
+ white-space: pre-wrap; /* ทำให้ขึ้นบรรทัดใหม่เมื่อยาวเกิน */
441
+ word-break: break-all;
442
+ margin: 0;
443
+ border: none;
444
+ outline: none;
445
+ }
446
+
447
+ /* สไตล์สำหรับแต่ละบรรทัดของ Log */
448
+ .log-line {
449
+ display: block;
450
+ margin: 0;
451
+ padding: 1px 0;
452
+ }
453
+
454
+ /* สีสำหรับ Log แต่ละประเภท */
455
+ .log-line.log-error { color: #f85149; font-weight: bold; }
456
+ .log-line.log-warning { color: #f2cc60; }
457
+ .log-line.log-success { color: #7ee787; }
458
+ .log-line.log-info { color: #8b949e; } /* สีเทาสำหรับข้อมูลทั่วไป */
459
+ .log-line.log-debug { color: #58a6ff; } /* สีฟ้าสำหรับ debug */
460
+ .log-line.log-command { color: #bc8cff; font-style: italic; }
461
+
462
+ /* Responsive adjustments */
463
+ @media (max-width: 768px) {
464
+ .dashboard-container {
465
+ flex-direction: column;
466
+ }
467
+
468
+ .terminal-panel {
469
+ width: 100%;
470
+ max-width: none;
471
+ height: 50%;
472
+ }
473
+
474
+ .inspector-controls {
475
+ justify-content: center;
476
+ }
477
+ }
478
+
479
+ /* Hide dev buttons unless in dev mode */
480
+ body:not(.dev-mode) .dev-only {
481
+ display: none !important;
482
+ }
483
+ </style>
484
+ </head>
485
+ <body>
486
+ <div class="dashboard-container">
487
+ <!-- Left Panel - Terminal Section -->
488
+ <div class="terminal-panel">
489
+ <div class="terminal-header">
490
+ <div class="terminal-title">
491
+ <i class="fas fa-terminal"></i>
492
+ เทอร์มินัลแบบโต้ตอบ
493
+ </div>
494
+
495
+ </div>
496
+ <pre id="log-viewer" class="log-viewer-container"></pre>
497
+ <!-- Resize Handle -->
498
+ <div class="resize-handle" id="resizeHandle"></div>
499
+ </div>
500
+
501
+ <!-- Right Panel - Inspector Panel -->
502
+ <div class="analysis-panel">
503
+ <div class="analysis-header">
504
+ <div class="analysis-title">
505
+ <i class="fas fa-search"></i> เครื่องมือตรวจสอบโปรเจค
506
+ </div>
507
+ </div>
508
+ <div class="analysis-content">
509
+ <div class="inspector-panel">
510
+ <div class="inspector-header">
511
+ <div class="inspector-title">
512
+ <i class="fas fa-bug"></i>
513
+ ตรวจสอบและวิเคราะห์
514
+ </div>
515
+ <div class="inspector-controls">
516
+ <button class="terminal-btn dev-only" id="scanSelfBtn">
517
+ <i class="fas fa-user-secret"></i> สแกนตัวเอง (Dev)
518
+ </button>
519
+ <button class="terminal-btn" id="scanPluginsBtn">
520
+ <i class="fas fa-puzzle-piece"></i> สแกนปลั๊กอิน
521
+ </button>
522
+ <button class="terminal-btn dev-only" id="runE2eTestsBtn" style="color: var(--success-color) !important; border-color: var(--success-color) !important;">
523
+ <i class="fas fa-vial"></i> เริ่มการทดสอบ E2E (Dev)
524
+ </button>
525
+ <button class="terminal-btn dev-only" id="openTestReportBtn" style="color: var(--warning-color) !important; border-color: var(--warning-color) !important;">
526
+ <i class="fas fa-chart-line"></i> เปิดรายงานผลการทดสอบ (Dev)
527
+ </button>
528
+ <button class="terminal-btn export-btn" id="exportIssuesBtn" disabled style="display: none;">
529
+ <i class="fas fa-download"></i> ส่งออก JSON
530
+ </button>
531
+ </div>
532
+ </div>
533
+
534
+ <div class="inspector-content">
535
+ <div class="inspector-stats" id="inspectorStats" style="display: none;">
536
+ <div class="stats-row">
537
+ <div class="stat-item">
538
+ <div class="stat-label">ไฟล์ทั้งหมด</div>
539
+ <div class="stat-value" id="totalFiles">0</div>
540
+ </div>
541
+ <div class="stat-item">
542
+ <div class="stat-label">ปัญหาทั้งหมด</div>
543
+ <div class="stat-value" id="totalIssues">0</div>
544
+ </div>
545
+ <div class="stat-item">
546
+ <div class="stat-label">ข้อผิดพลาด</div>
547
+ <div class="stat-value stat-error" id="totalErrors">0</div>
548
+ </div>
549
+ <div class="stat-item">
550
+ <div class="stat-label">คำเตือน</div>
551
+ <div class="stat-value stat-warning" id="totalWarnings">0</div>
552
+ </div>
553
+ </div>
554
+ </div>
555
+
556
+ <div class="inspector-filters" id="inspectorFilters" style="display: none;">
557
+ <div class="filter-group">
558
+ <label>กรองตามประเภท:</label>
559
+ <select id="typeFilter">
560
+ <option value="all">ทุกประเภท</option>
561
+ <option value="SyntaxError">ข้อผิดพลาดไวยากรณ์</option>
562
+ <option value="MissingFile">ไฟล์หายไป</option>
563
+ <option value="UnusedFile">ไฟล์ไม่ได้ใช้</option>
564
+ <option value="MissingDependency">การพึ่งพาหายไป</option>
565
+ <option value="CircularDependency">การพึ่งพาแบบวนรอบ</option>
566
+ <option value="DuplicateExport">การส่งออกซ้ำ</option>
567
+ <option value="MissingExport">การนำเข้า/ส่งออกไม่ตรงกัน</option>
568
+ </select>
569
+ </div>
570
+ <div class="filter-group">
571
+ <label>กรองตามความรุนแรง:</label>
572
+ <select id="severityFilter">
573
+ <option value="all">ทุกระดับ</option>
574
+ <option value="error">ข้อผิดพลาด</option>
575
+ <option value="warning">คำเตือน</option>
576
+ <option value="info">ข้อมูล</option>
577
+ </select>
578
+ </div>
579
+ </div>
580
+
581
+ <div class="inspector-results" id="inspectorResults">
582
+ <div class="no-selection">
583
+ <i class="fas fa-search"></i>
584
+ <h3>เครื่องมือตรวจสอบโปรเจค</h3>
585
+ <p>เครื่องมือวิเคราะห์โค้ดเพื่อหาปัญหาต่างๆ ก่อนการรัน</p>
586
+ <div style="margin-top: 20px; text-align: left;">
587
+ <h4 style="color: var(--accent-color); margin-bottom: 10px;">ความสามารถ:</h4>
588
+ <ul style="color: var(--secondary-text-color); line-height: 1.6;">
589
+ <li>ตรวจสอบไวยากรณ์ (ข้อผิดพลาดไวยากรณ์)</li>
590
+ <li>หาไฟล์ที่ไม่มีอยู่จริง (ไฟล์หายไป)</li>
591
+ <li>หาไฟล์ที่ไม่ได้ใช้งาน (ไฟล์ไม่ได้ใช้)</li>
592
+ <li>ตรวจสอบการพึ่งพาที่ขาดหาย</li>
593
+ <li>หาการพึ่งพาแบบวนรอบ</li>
594
+ <li>หาการส่งออกซ้ำ</li>
595
+ <li>หาการนำเข้า/ส่งออกไม่ตรงกัน (ข้อผิดพลาดรันไทม์)</li>
596
+ </ul>
597
+ </div>
598
+ <div style="margin-top: 20px;">
599
+ <p style="color: var(--warning-color);">คลิก "สแกนปลั๊กอิน" เพื่อเริ่มวิเคราะห์</p>
600
+ </div>
601
+ </div>
602
+ </div>
603
+ </div>
604
+ </div>
605
+ </div>
606
+ </div>
607
+ </div>
608
+
609
+ <script src="debugger.js"></script>
610
+
611
+ <script>
612
+ // =================================
613
+ // PRODUCTION SECURITY SYSTEM
614
+ // =================================
615
+
616
+ // ตรวจสอบโหมดการทำงาน
617
+ const isDevelopmentMode = () => {
618
+ // ตรวจสอบจาก URL parameters
619
+ const urlParams = new URLSearchParams(window.location.search);
620
+ const devParam = urlParams.get('dev');
621
+
622
+ // ตรวจสอบจาก localStorage
623
+ const devStorage = localStorage.getItem('chahua_dev_mode');
624
+
625
+ // ตรวจสอบจาก environment variables (ถ้ามี)
626
+ const isLocalhost = window.location.hostname === 'localhost' ||
627
+ window.location.hostname === '127.0.0.1' ||
628
+ window.location.hostname === '';
629
+
630
+ return devParam === 'true' || devStorage === 'true' || isLocalhost;
631
+ };
632
+
633
+ // ระบบป้องกัน Console และ Developer Tools
634
+ const initProductionSecurity = () => {
635
+ if (isDevelopmentMode()) {
636
+ // เปิดใช้งาน dev mode
637
+ document.body.classList.add('dev-mode');
638
+ console.log('%c Developer Mode Enabled', 'color: #28a745; font-weight: bold; font-size: 14px;');
639
+ return;
640
+ }
641
+
642
+ // ปิดใช้งาน console ทั้งหมด
643
+ const noop = () => {};
644
+ const consoleMethods = [
645
+ 'log', 'debug', 'info', 'warn', 'error', 'assert', 'dir', 'dirxml',
646
+ 'group', 'groupEnd', 'time', 'timeEnd', 'count', 'trace', 'profile', 'profileEnd'
647
+ ];
648
+
649
+ consoleMethods.forEach(method => {
650
+ console[method] = noop;
651
+ });
652
+
653
+ // ป้องกันการเปิด Developer Tools
654
+ let devtools = {open: false, orientation: null};
655
+ const threshold = 160;
656
+
657
+ setInterval(() => {
658
+ if (window.outerHeight - window.innerHeight > threshold ||
659
+ window.outerWidth - window.innerWidth > threshold) {
660
+ if (!devtools.open) {
661
+ devtools.open = true;
662
+ // Redirect หรือ แสดงข้อความเตือน
663
+ document.body.innerHTML = `
664
+ <div style="
665
+ position: fixed; top: 0; left: 0; right: 0; bottom: 0;
666
+ background: #f8f9fa; display: flex; align-items: center; justify-content: center;
667
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
668
+ ">
669
+ <div style="text-align: center; color: #212529;">
670
+ <h2 style="color: #dc3545; margin-bottom: 20px;"> การเข้าถึงถูกจำกัด</h2>
671
+ <p>กรุณาปิด Developer Tools เพื่อดำเนินการต่อ</p>
672
+ <p style="color: #6c757d; font-size: 0.9rem;">Developer Tools detected. Please close to continue.</p>
673
+ </div>
674
+ </div>
675
+ `;
676
+ }
677
+ } else {
678
+ devtools.open = false;
679
+ }
680
+ }, 500);
681
+
682
+ // ปิดใช้งานคำสั่งลัดของ Developer Tools
683
+ document.addEventListener('keydown', (e) => {
684
+ // ปิด F12
685
+ if (e.key === 'F12') {
686
+ e.preventDefault();
687
+ return false;
688
+ }
689
+
690
+ // ปิด Ctrl+Shift+I, Ctrl+Shift+J, Ctrl+Shift+C
691
+ if (e.ctrlKey && e.shiftKey && (e.key === 'I' || e.key === 'J' || e.key === 'C')) {
692
+ e.preventDefault();
693
+ return false;
694
+ }
695
+
696
+ // ปิด Ctrl+U (View Source)
697
+ if (e.ctrlKey && e.key === 'U') {
698
+ e.preventDefault();
699
+ return false;
700
+ }
701
+
702
+ // ปิด Ctrl+S (Save Page)
703
+ if (e.ctrlKey && e.key === 'S') {
704
+ e.preventDefault();
705
+ return false;
706
+ }
707
+ });
708
+
709
+ // ป้องกัน Right Click Context Menu
710
+ document.addEventListener('contextmenu', (e) => {
711
+ e.preventDefault();
712
+ return false;
713
+ });
714
+
715
+ // ป้องกัน Text Selection
716
+ document.addEventListener('selectstart', (e) => {
717
+ e.preventDefault();
718
+ return false;
719
+ });
720
+
721
+ // ป้องกัน Drag and Drop
722
+ document.addEventListener('dragstart', (e) => {
723
+ e.preventDefault();
724
+ return false;
725
+ });
726
+ };
727
+
728
+ // =================================
729
+ // RESIZE HANDLE FUNCTIONALITY
730
+ // =================================
731
+
732
+ // Resize Handle Functionality
733
+ class ResizeController {
734
+ constructor() {
735
+ this.container = document.querySelector('.dashboard-container');
736
+ this.terminalPanel = document.querySelector('.terminal-panel');
737
+ this.resizeHandle = document.getElementById('resizeHandle');
738
+ this.isResizing = false;
739
+ this.resizeTimeout = null;
740
+
741
+ if (this.resizeHandle) {
742
+ this.init();
743
+ }
744
+ }
745
+
746
+ init() {
747
+ // เพิ่ม throttled resize method
748
+ this.boundThrottledResize = this.throttle(this.resizeTerminal.bind(this), 100);
749
+
750
+ // Bound methods for proper event handling
751
+ this.boundHandleResize = this.handleResize.bind(this);
752
+ this.boundStopResize = this.stopResize.bind(this);
753
+ this.boundKeydownHandler = this.handleKeydown.bind(this);
754
+ this.emergencyCleanup = this.stopResize.bind(this);
755
+
756
+ // Mouse events
757
+ this.resizeHandle.addEventListener('mousedown', this.startResize.bind(this));
758
+
759
+ // Log เฉพาะใน dev mode
760
+ if (isDevelopmentMode()) {
761
+ console.log(" Resize controller initialized for debugger");
762
+ }
763
+ }
764
+
765
+ startResize(e) {
766
+ e.preventDefault();
767
+ this.isResizing = true;
768
+
769
+ // Add visual feedback
770
+ this.container.classList.add('resizing');
771
+ this.resizeHandle.classList.add('resizing');
772
+
773
+ // Add event listeners
774
+ document.addEventListener('mousemove', this.boundHandleResize);
775
+ document.addEventListener('mouseup', this.boundStopResize);
776
+
777
+ // Emergency cleanup listeners
778
+ document.addEventListener('mouseleave', this.emergencyCleanup);
779
+ window.addEventListener('blur', this.emergencyCleanup);
780
+ document.addEventListener('keydown', this.boundKeydownHandler);
781
+
782
+ // Log เฉพาะใน dev mode
783
+ if (isDevelopmentMode()) {
784
+ console.log(" Resize started");
785
+ }
786
+ }
787
+
788
+ handleResize(e) {
789
+ if (!this.isResizing) return;
790
+
791
+ e.preventDefault();
792
+
793
+ const containerRect = this.container.getBoundingClientRect();
794
+ const newWidth = e.clientX - containerRect.left;
795
+ const containerWidth = containerRect.width;
796
+ const minWidth = 300;
797
+ const maxWidth = containerWidth * 0.8;
798
+
799
+ if (newWidth >= minWidth && newWidth <= maxWidth) {
800
+ this.terminalPanel.style.width = `${newWidth}px`;
801
+ this.terminalPanel.style.flex = 'none';
802
+ }
803
+ }
804
+
805
+ handleKeydown(e) {
806
+ if (e.key === 'Escape' && this.isResizing) {
807
+ this.stopResize();
808
+ }
809
+ }
810
+
811
+ stopResize() {
812
+ if (!this.isResizing) return;
813
+
814
+ this.isResizing = false;
815
+
816
+ // Remove visual feedback
817
+ this.container.classList.remove('resizing');
818
+ this.resizeHandle.classList.remove('resizing');
819
+
820
+ // Remove event listeners
821
+ document.removeEventListener('mousemove', this.boundHandleResize);
822
+ document.removeEventListener('mouseup', this.boundStopResize);
823
+
824
+ // Remove emergency cleanup listeners
825
+ document.removeEventListener('mouseleave', this.emergencyCleanup);
826
+ window.removeEventListener('blur', this.emergencyCleanup);
827
+ document.removeEventListener('keydown', this.boundKeydownHandler);
828
+
829
+ // Clear timeout
830
+ if (this.resizeTimeout) {
831
+ clearTimeout(this.resizeTimeout);
832
+ this.resizeTimeout = null;
833
+ }
834
+
835
+ // Log เฉพาะใน dev mode
836
+ if (isDevelopmentMode()) {
837
+ console.log(" Resize stopped and listeners cleaned up");
838
+ }
839
+ }
840
+
841
+ // เพิ่มฟังก์ชัน throttle เข้าไปใน Class
842
+ throttle(func, limit) {
843
+ let inThrottle;
844
+ return function() {
845
+ const args = arguments;
846
+ const context = this;
847
+ if (!inThrottle) {
848
+ func.apply(context, args);
849
+ inThrottle = true;
850
+ setTimeout(() => inThrottle = false, limit);
851
+ }
852
+ }
853
+ }
854
+
855
+ // เพิ่มฟังก์ชัน resizeTerminal สำหรับการอ้างอิงใน boundThrottledResize
856
+ resizeTerminal() {
857
+ // ถ้ามี diagnostic dashboard ให้เรียกใช้ resizeTerminal ของมัน
858
+ if (window.diagnosticDashboard && window.diagnosticDashboard.resizeTerminal) {
859
+ window.diagnosticDashboard.resizeTerminal();
860
+ }
861
+ }
862
+ }
863
+
864
+ // =================================
865
+ // INITIALIZATION
866
+ // =================================
867
+
868
+ // Initialize security system first
869
+ initProductionSecurity();
870
+
871
+ // Initialize resize controller when DOM is loaded
872
+ document.addEventListener('DOMContentLoaded', () => {
873
+ window.resizeController = new ResizeController();
874
+ });
875
+
876
+ // Cleanup on page unload
877
+ window.addEventListener('beforeunload', () => {
878
+ if (window.resizeController) {
879
+ window.resizeController.stopResize();
880
+ }
881
+ });
882
+ </script>
883
+ </body>
884
+ </html>
debugger.js ADDED
@@ -0,0 +1,659 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Chahuadev Hybrid Diagnostic Dashboard - Terminal + GUI
3
+ */
4
+
5
+ class DiagnosticDashboard {
6
+ constructor() {
7
+ this.selectedLog = null;
8
+ this.currentTab = 'details';
9
+ this.maxLogs = 1000;
10
+
11
+ this.init();
12
+ }
13
+
14
+ async init() {
15
+ console.log(' เริ่มต้น Hybrid Diagnostic Dashboard...');
16
+
17
+ // ตั้งค่า global reference สำหรับการเรียกใช้จาก HTML
18
+ window.diagnosticDashboard = this;
19
+
20
+ // ตรวจสอบ DEV MODE
21
+ try {
22
+ // เรียก API จาก Backend เพื่อตรวจสอบโหมดการทำงาน
23
+ const runMode = await window.electronAPI.getRunMode();
24
+ if (runMode && runMode.isDevMode) {
25
+ console.log(' Running in Developer Mode');
26
+ document.body.classList.add('dev-mode');
27
+ } else {
28
+ console.log(' Running in User Mode');
29
+ document.body.classList.remove('dev-mode');
30
+ }
31
+ } catch (error) {
32
+ console.warn(' ไม่สามารถตรวจสอบโหมดการทำงานได้', error);
33
+ }
34
+
35
+ this.setupTerminal();
36
+ this.setupEventListeners();
37
+ this.startRealTimeUpdates();
38
+
39
+ console.log(' Hybrid Diagnostic Dashboard พร้อมใช้งาน');
40
+ }
41
+
42
+ // [เวอร์ชันใหม่] ตั้งค่า Log Viewer ของเราเอง
43
+ setupTerminal() {
44
+ // เราจะเรียกใช้ฟังก์ชันนี้ใน init() เหมือนเดิม
45
+ // แต่ตอนนี้มันแค่เตรียมพร้อม ไม่ได้สร้าง Terminal ที่ซับซ้อน
46
+ this.logViewer = document.getElementById('log-viewer');
47
+
48
+ if (this.logViewer) {
49
+ this.logViewer.innerHTML = ''; // ล้าง Log เก่าตอนเริ่มต้น
50
+ this.writeLog({
51
+ message: '===== Chahuadev Diagnostic Log (Raw HTML) =====',
52
+ type: 'debug'
53
+ });
54
+ this.writeLog({
55
+ message: 'Real-time logs will appear here...',
56
+ type: 'info'
57
+ });
58
+ } else {
59
+ console.error('Log viewer container not found!');
60
+ }
61
+ }
62
+
63
+ // ไม่ต้องมี resizeTerminal() อีกต่อไป เพราะ CSS จัดการให้แล้ว!
64
+
65
+ /**
66
+ * Throttle function เพื่อจำกัดการเรียกฟังก์ชัน
67
+ */
68
+ throttle(func, limit) {
69
+ let inThrottle;
70
+ return function() {
71
+ const args = arguments;
72
+ const context = this;
73
+ if (!inThrottle) {
74
+ func.apply(context, args);
75
+ inThrottle = true;
76
+ setTimeout(() => inThrottle = false, limit);
77
+ }
78
+ }
79
+ }
80
+
81
+ setupEventListeners() {
82
+ // Tab buttons
83
+ document.querySelectorAll('.tab-btn').forEach(btn => {
84
+ btn.addEventListener('click', (e) => {
85
+ this.setActiveTab(e.target.dataset.tab);
86
+ });
87
+ });
88
+
89
+ // Project Inspector buttons
90
+ document.getElementById('scanSelfBtn')?.addEventListener('click', async () => {
91
+ await this.handleProjectScan('self');
92
+ });
93
+
94
+ document.getElementById('scanPluginsBtn')?.addEventListener('click', async () => {
95
+ await this.handleProjectScan('plugins');
96
+ });
97
+
98
+ document.getElementById('exportIssuesBtn')?.addEventListener('click', async () => {
99
+ await this.handleExportIssues();
100
+ });
101
+
102
+ // E2E Testing button
103
+ document.getElementById('runE2eTestsBtn')?.addEventListener('click', async () => {
104
+ this.writeln('\x1b[1;36m กำลังเริ่มการทดสอบ E2E ทั้งระบบ...\x1b[0m');
105
+ try {
106
+ const result = await window.electronAPI.diagnostics.runE2eTests();
107
+ if (result.success) {
108
+ this.writeln('\x1b[1;32m การทดสอบ E2E เสร็จสิ้น\x1b[0m');
109
+ if (result.message) {
110
+ this.writeln(`\x1b[1;37m${result.message}\x1b[0m`);
111
+ }
112
+ } else {
113
+ this.writeln(`\x1b[1;31m การทดสอบ E2E ล้มเหลว: ${result.error}\x1b[0m`);
114
+ }
115
+ } catch (error) {
116
+ this.writeln(`\x1b[1;31m ไม่สามารถเริ่มการทดสอบได้: ${error.message}\x1b[0m`);
117
+ }
118
+ });
119
+
120
+ // Open Test Report button
121
+ document.getElementById('openTestReportBtn')?.addEventListener('click', async () => {
122
+ this.writeln('\x1b[1;33m กำลังเปิดรายงานผลการทดสอบ...\x1b[0m');
123
+ try {
124
+ const result = await window.electronAPI.diagnostics.openTestReport();
125
+ if (result.success) {
126
+ this.writeln('\x1b[1;32m เปิดรายงานผลการทดสอบแล้ว\x1b[0m');
127
+ if (result.message) {
128
+ this.writeln(`\x1b[1;37m${result.message}\x1b[0m`);
129
+ }
130
+ } else {
131
+ this.writeln(`\x1b[1;31m ไม่สามารถเปิดรายงานได้: ${result.error}\x1b[0m`);
132
+ }
133
+ } catch (error) {
134
+ this.writeln(`\x1b[1;31m เกิดข้อผิดพลาด: ${error.message}\x1b[0m`);
135
+ }
136
+ });
137
+ }
138
+
139
+ /**
140
+ * จัดการการสแกนโปรเจกต์
141
+ * @param {'self' | 'plugins'} target - เป้าหมายที่จะสแกน
142
+ */
143
+ async handleProjectScan(target) {
144
+ try {
145
+ let projectPath = null; // เริ่มต้นเป็น null
146
+ let targetName = '';
147
+
148
+ // ปรับปรุงตรรกะการเลือก Path
149
+ if (target === 'self') {
150
+ targetName = 'โปรเจกต์หลัก (Framework)';
151
+ // ขอ Path ของโปรแกรมปัจจุบันจาก Backend
152
+ projectPath = await window.electronAPI.system.getCwd();
153
+ } else if (target === 'plugins') {
154
+ targetName = 'ปลั๊กอินทั้งหมด';
155
+ // ไม่ต้องส่ง Path! เพื่อให้ main process ใช้ default path ของ plugins
156
+ projectPath = undefined; // ให้ Backend เลือก plugins directory เอง
157
+ } else {
158
+ this.writeln(`\x1b[1;31m ข้อผิดพลาด: ไม่รู้จักเป้าหมายการสแกน '${target}'\x1b[0m`);
159
+ return;
160
+ }
161
+
162
+ this.writeln(`\x1b[1;33m กำลังเริ่มวิเคราะห์: ${targetName}...\x1b[0m`);
163
+ if (projectPath) {
164
+ this.writeln(`\x1b[1;36m Path: ${projectPath}\x1b[0m`);
165
+ } else {
166
+ this.writeln(`\x1b[1;36m ใช้ Path เริ่มต้นของปลั๊กอิน\x1b[0m`);
167
+ }
168
+
169
+ // ปิดการใช้งานปุ่มขณะสแกน
170
+ const scanSelfBtn = document.getElementById('scanSelfBtn');
171
+ const scanPluginsBtn = document.getElementById('scanPluginsBtn');
172
+ const exportBtn = document.getElementById('exportIssuesBtn');
173
+
174
+ if (scanSelfBtn) scanSelfBtn.disabled = true;
175
+ if (scanPluginsBtn) scanPluginsBtn.disabled = true;
176
+
177
+ // ซ่อนปุ่ม export ขณะสแกน
178
+ if (exportBtn) {
179
+ exportBtn.style.display = 'none';
180
+ exportBtn.disabled = true;
181
+ }
182
+
183
+ if (window.electronAPI && window.electronAPI.project) {
184
+ // เรียก API โดยส่ง path ที่อาจจะเป็น undefined สำหรับ plugins
185
+ const result = await window.electronAPI.project.analyze(projectPath);
186
+
187
+ if (result.success) {
188
+ const scanInfo = result.scanTarget ? ` (${result.scanTarget})` : '';
189
+ this.writeln(`\x1b[1;32m วิเคราะห์สำเร็จ${scanInfo}: พบ ${result.analysis.totalIssues} ปัญหาใน ${result.analysis.totalFiles} ไฟล์\x1b[0m`);
190
+
191
+ // แสดงรายละเอียดเพิ่มเติม
192
+ if (result.analysis.totalFiles === 0) {
193
+ this.writeln(`\x1b[1;33m ไม่พบไฟล์ในโฟลเดอร์นี้ หรือไฟล์ทั้งหมดถูกคัดกรองออกโดย exclusion rules\x1b[0m`);
194
+ }
195
+
196
+ // แสดงผลลัพธ์ใน Inspector tab
197
+ this.displayAnalysisResults(result.analysis);
198
+
199
+ } else {
200
+ this.writeln(`\x1b[1;31m วิเคราะห์ล้มเหลว: ${result.error}\x1b[0m`);
201
+
202
+ // แสดงปุ่ม export แม้ว่าจะล้มเหลว เผื่อมีข้อมูลบางส่วน
203
+ if (exportBtn) {
204
+ exportBtn.style.display = 'inline-block';
205
+ exportBtn.disabled = false;
206
+ }
207
+ }
208
+ } else {
209
+ this.writeln('\x1b[1;31m ข้อผิดพลาด: ไม่พบ Project Inspector API\x1b[0m');
210
+ }
211
+
212
+ } catch (error) {
213
+ this.writeln(`\x1b[1;31m ข้อผิดพลาดในการสแกน: ${error.message}\x1b[0m`);
214
+ } finally {
215
+ // คืนสถานะปุ่ม
216
+ const scanSelfBtn = document.getElementById('scanSelfBtn');
217
+ const scanPluginsBtn = document.getElementById('scanPluginsBtn');
218
+ if (scanSelfBtn) scanSelfBtn.disabled = false;
219
+ if (scanPluginsBtn) scanPluginsBtn.disabled = false;
220
+ }
221
+ }
222
+
223
+ /**
224
+ * แสดงผลลัพธ์การวิเคราะห์
225
+ */
226
+ displayAnalysisResults(analysis) {
227
+ // อัปเดตสถิติ
228
+ document.getElementById('totalFiles').textContent = analysis.totalFiles || 0;
229
+ document.getElementById('totalIssues').textContent = analysis.totalIssues || 0;
230
+ document.getElementById('totalErrors').textContent = analysis.stats?.syntaxErrors || 0;
231
+ document.getElementById('totalWarnings').textContent =
232
+ (analysis.stats?.missingFiles || 0) +
233
+ (analysis.stats?.unusedFiles || 0) +
234
+ (analysis.stats?.circularDependencies || 0);
235
+
236
+ // แสดงส่วนสถิติและฟิลเตอร์
237
+ document.getElementById('inspectorStats').style.display = 'block';
238
+ document.getElementById('inspectorFilters').style.display = 'block';
239
+
240
+ // แสดงรายการปัญหา
241
+ this.displayIssuesList(analysis.issues || []);
242
+
243
+ // เก็บข้อมูลสำหรับการ export
244
+ this.currentAnalysis = analysis;
245
+
246
+ // แสดงปุ่ม Export JSON หลังจากมีผลลัพธ์ (ไม่ว่าจะพบปัญหาหรือไม่)
247
+ const exportBtn = document.getElementById('exportIssuesBtn');
248
+ if (exportBtn) {
249
+ exportBtn.style.display = 'inline-block';
250
+ exportBtn.disabled = false;
251
+
252
+ // แจ้งเตือนเมื่อพบปัญหา
253
+ if (analysis.issues && analysis.issues.length > 0) {
254
+ this.writeln('\x1b[1;36m คลิกปุ่ม "ส่งออก JSON" เพื่อบันทึกผลการวิเคราะห์\x1b[0m');
255
+ } else {
256
+ this.writeln('\x1b[1;36m ผลการวิเคราะห์พร้อมส่งออก (ไม่พบปัญหา)\x1b[0m');
257
+ }
258
+ }
259
+
260
+ // แสดง notification แทนการเปลี่ยนแท็บอัตโนมัติ
261
+ this.writeln('\x1b[1;33m ผลการวิเคราะห์พร้อมแล้ว! ไปดูในแท็บ "Inspector" ด้านบน\x1b[0m');
262
+ }
263
+
264
+ /**
265
+ * แสดงรายการปัญหา
266
+ */
267
+ displayIssuesList(issues) {
268
+ const resultsContainer = document.getElementById('inspectorResults');
269
+
270
+ if (!issues || issues.length === 0) {
271
+ resultsContainer.innerHTML = `
272
+ <div class="no-selection">
273
+ <i class="fas fa-check-circle" style="color: #10b981;"></i>
274
+ <h3>ไม่พบปัญหา</h3>
275
+ <p>โปรเจกต์ของคุณไม่มีปัญหาที่ตรวจพบ</p>
276
+ </div>
277
+ `;
278
+ return;
279
+ }
280
+
281
+ let html = '<div class="issues-list">';
282
+
283
+ issues.forEach((issue, index) => {
284
+ const severityClass = issue.severity === 'error' ? 'stat-error' : 'stat-warning';
285
+ const severityIcon = issue.severity === 'error' ? 'fas fa-times-circle' : 'fas fa-exclamation-triangle';
286
+ const severityText = issue.severity === 'error' ? 'ข้อผิดพลาด' : 'คำเตือน';
287
+ const codeSnippetId = `code-snippet-${index}`;
288
+
289
+ html += `
290
+ <div class="issue-item" style="background: #2a2a2a; border-radius: 6px; padding: 12px; margin-bottom: 10px; border-left: 3px solid ${issue.severity === 'error' ? '#ef4444' : '#f59e0b'};">
291
+ <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 8px;">
292
+ <div>
293
+ <span class="${severityClass}" style="font-weight: bold;">
294
+ <i class="${severityIcon}"></i> ${issue.type}
295
+ </span>
296
+ <span style="color: #9ca3af; margin-left: 10px; font-size: 12px;">
297
+ ${issue.file}:${issue.line}:${issue.column}
298
+ </span>
299
+ </div>
300
+ <span style="background: #1a1a1a; color: #9ca3af; padding: 2px 6px; border-radius: 3px; font-size: 11px;">
301
+ ${severityText.toUpperCase()}
302
+ </span>
303
+ </div>
304
+
305
+ <div style="color: #e0e0e0; margin-bottom: 12px;">${issue.message}</div>
306
+
307
+ ${issue.codeSnippet ? `
308
+ <div class="code-snippet-container" style="margin-bottom: 12px;">
309
+ <div style="display: flex; align-items: center; justify-content: space-between; background: #1a1a1a; padding: 6px 10px; border-radius: 4px 4px 0 0; border-bottom: 1px solid #3a3a3a;">
310
+ <span style="color: #9ca3af; font-size: 12px; font-weight: 500;">
311
+ <i class="fas fa-code" style="margin-right: 5px;"></i>
312
+ บริบทของโค้ด
313
+ </span>
314
+ <button class="copy-code-btn" onclick="window.diagnosticDashboard.copyCodeSnippet('${codeSnippetId}')"
315
+ style="background: none; border: none; color: #9ca3af; cursor: pointer; font-size: 12px; padding: 2px 5px; border-radius: 2px;">
316
+ <i class="fas fa-copy"></i> คัดลอก
317
+ </button>
318
+ </div>
319
+ <pre id="${codeSnippetId}" class="code-snippet" style="background: #0d1117; color: #c9d1d9; margin: 0; padding: 12px; border-radius: 0 0 4px 4px; overflow-x: auto; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 13px; line-height: 1.4;"><code class="language-javascript">${this.escapeHtml(issue.codeSnippet)}</code></pre>
320
+ </div>
321
+ ` : ''}
322
+
323
+ ${issue.suggestion ? `<div style="color: #4fc3f7; font-size: 13px; font-style: italic;"> ${issue.suggestion}</div>` : ''}
324
+ </div>
325
+ `;
326
+ });
327
+
328
+ html += '</div>';
329
+ resultsContainer.innerHTML = html;
330
+
331
+ // เพิ่ม syntax highlighting
332
+ this.applySyntaxHighlighting();
333
+
334
+ // เพิ่ม filter functionality
335
+ this.setupIssueFilters(issues);
336
+ }
337
+
338
+ /**
339
+ * หลีกเลี่ยงการแสดง HTML tags ในโค้ด
340
+ */
341
+ escapeHtml(text) {
342
+ const div = document.createElement('div');
343
+ div.textContent = text;
344
+ return div.innerHTML;
345
+ }
346
+
347
+ /**
348
+ * ใช้ syntax highlighting กับ code snippets
349
+ */
350
+ applySyntaxHighlighting() {
351
+ const codeBlocks = document.querySelectorAll('.code-snippet code');
352
+ codeBlocks.forEach(block => {
353
+ this.highlightJavaScript(block);
354
+ });
355
+ }
356
+
357
+ /**
358
+ * Syntax highlighting สำหรับ JavaScript
359
+ */
360
+ highlightJavaScript(codeElement) {
361
+ let code = codeElement.textContent;
362
+
363
+ // Keywords
364
+ code = code.replace(/\b(const|let|var|function|class|if|else|for|while|return|import|export|from|require|try|catch|throw|async|await|new|this|super|extends|static|null|undefined|true|false)\b/g,
365
+ '<span style="color: #ff7b72;">$1</span>');
366
+
367
+ // Strings
368
+ code = code.replace(/(["'`])((?:\\.|(?!\1)[^\\])*?)\1/g,
369
+ '<span style="color: #a5d6ff;">$1$2$1</span>');
370
+
371
+ // Numbers
372
+ code = code.replace(/\b(\d+(?:\.\d+)?)\b/g,
373
+ '<span style="color: #79c0ff;">$1</span>');
374
+
375
+ // Comments
376
+ code = code.replace(/\/\/(.*$)/gm,
377
+ '<span style="color: #8b949e; font-style: italic;">//$1</span>');
378
+ code = code.replace(/\/\*([\s\S]*?)\*\//g,
379
+ '<span style="color: #8b949e; font-style: italic;">/*$1*/</span>');
380
+
381
+ // Function calls
382
+ code = code.replace(/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/g,
383
+ '<span style="color: #d2a8ff;">$1</span>(');
384
+
385
+ // Problem line highlight (line starting with >)
386
+ code = code.replace(/^(>\s*\d+\s*\|)(.*$)/gm,
387
+ '<span style="background: rgba(248, 81, 73, 0.1); display: block; margin: 0 -12px; padding: 0 12px;"><span style="color: #f85149; font-weight: bold;">$1</span>$2</span>');
388
+
389
+ codeElement.innerHTML = code;
390
+ }
391
+
392
+ /**
393
+ * คัดลอกโค้ดไปยังคลิปบอร์ด
394
+ */
395
+ copyCodeSnippet(snippetId) {
396
+ const element = document.getElementById(snippetId);
397
+ if (element) {
398
+ const text = element.textContent;
399
+ navigator.clipboard.writeText(text).then(() => {
400
+ // แสดงการแจ้งเตือนสั้นๆ
401
+ const copyBtn = element.parentElement.querySelector('.copy-code-btn');
402
+ const originalText = copyBtn.innerHTML;
403
+ copyBtn.innerHTML = '<i class="fas fa-check"></i> คัดลอกแล้ว!';
404
+ copyBtn.style.color = '#10b981';
405
+
406
+ setTimeout(() => {
407
+ copyBtn.innerHTML = originalText;
408
+ copyBtn.style.color = '#9ca3af';
409
+ }, 2000);
410
+ }).catch(err => {
411
+ console.error('ไม่สามารถคัดลอกได้: ', err);
412
+ });
413
+ }
414
+ }
415
+
416
+ /**
417
+ * ตั้งค่าระบบกรองปัญหา
418
+ */
419
+ setupIssueFilters(issues) {
420
+ const typeFilter = document.getElementById('typeFilter');
421
+ const severityFilter = document.getElementById('severityFilter');
422
+
423
+ if (typeFilter) {
424
+ typeFilter.addEventListener('change', () => {
425
+ this.filterIssues(issues);
426
+ });
427
+ }
428
+
429
+ if (severityFilter) {
430
+ severityFilter.addEventListener('change', () => {
431
+ this.filterIssues(issues);
432
+ });
433
+ }
434
+ }
435
+
436
+ /**
437
+ * กรองปัญหาตามเงื่อนไข
438
+ */
439
+ filterIssues(allIssues) {
440
+ const typeFilter = document.getElementById('typeFilter')?.value || 'all';
441
+ const severityFilter = document.getElementById('severityFilter')?.value || 'all';
442
+
443
+ let filteredIssues = allIssues;
444
+
445
+ if (typeFilter !== 'all') {
446
+ filteredIssues = filteredIssues.filter(issue => issue.type === typeFilter);
447
+ }
448
+
449
+ if (severityFilter !== 'all') {
450
+ filteredIssues = filteredIssues.filter(issue => issue.severity === severityFilter);
451
+ }
452
+
453
+ this.displayIssuesList(filteredIssues);
454
+ }
455
+
456
+ /**
457
+ * จัดการการ export ปัญหา
458
+ */
459
+ async handleExportIssues() {
460
+ if (!this.currentAnalysis) {
461
+ this.writeln('\x1b[1;33m ไม่มีข้อมูลการวิเคราะห์สำหรับส่งออก\x1b[0m');
462
+ return;
463
+ }
464
+
465
+ try {
466
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
467
+ const filename = `การวิเคราะห์โปรเจกต์-${timestamp}.json`;
468
+
469
+ // ใช้ Electron dialog API เพื่อให้ผู้ใช้เลือกที่บันทึก
470
+ if (window.electronAPI && window.electronAPI.dialog) {
471
+ const result = await window.electronAPI.dialog.showSaveDialog({
472
+ defaultPath: filename,
473
+ filters: [
474
+ { name: 'ไฟล์ JSON', extensions: ['json'] },
475
+ { name: 'ไฟล์ทั้งหมด', extensions: ['*'] }
476
+ ]
477
+ });
478
+
479
+ if (!result.canceled && result.filePath) {
480
+ await window.electronAPI.file.write(result.filePath, JSON.stringify(this.currentAnalysis, null, 2));
481
+ this.writeln(`\x1b[1;32m ส่งออกการวิเคราะห์เรียบร้อย: ${result.filePath}\x1b[0m`);
482
+ } else {
483
+ this.writeln('\x1b[1;33m ยกเลิกการส่งออก\x1b[0m');
484
+ }
485
+ } else {
486
+ // Fallback: สร้างลิงก์ดาวน์โหลด
487
+ const dataStr = JSON.stringify(this.currentAnalysis, null, 2);
488
+ const dataBlob = new Blob([dataStr], {type:'application/json'});
489
+ const url = URL.createObjectURL(dataBlob);
490
+ const link = document.createElement('a');
491
+ link.href = url;
492
+ link.download = filename;
493
+ link.click();
494
+ URL.revokeObjectURL(url);
495
+
496
+ this.writeln(`\x1b[1;32m เริ่มดาวน์โหลดไฟล์: ${filename}\x1b[0m`);
497
+ }
498
+ } catch (error) {
499
+ this.writeln(`\x1b[1;31m ข้อผิดพลาดในการส่งออก: ${error.message}\x1b[0m`);
500
+ }
501
+ }
502
+
503
+ setActiveTab(tab) {
504
+ this.currentTab = tab;
505
+
506
+ // อัปเดต tab buttons
507
+ document.querySelectorAll('.tab-btn').forEach(btn => {
508
+ btn.classList.toggle('active', btn.dataset.tab === tab);
509
+ });
510
+
511
+ // อัปเดต tab content
512
+ document.querySelectorAll('.tab-content').forEach(content => {
513
+ content.classList.toggle('active', content.id === tab + 'Tab');
514
+ });
515
+
516
+ // โหลดข้อมูลเฉพาะ tab
517
+ if (tab === 'workflows') {
518
+ this.requestWorkflowsUpdate();
519
+ }
520
+ }
521
+
522
+ // [เวอร์ชันใหม่] ฟังก์ชันสำหรับเขียน Log ที่เราควบคุมได้ 100%
523
+ writeLog(logData) {
524
+ if (!this.logViewer) return;
525
+
526
+ const timestamp = logData.timestamp ? new Date(logData.timestamp) : new Date();
527
+ const time = timestamp.toLocaleTimeString('th-TH', { hour12: false });
528
+
529
+ // สร้าง Element ใหม่สำหรับแต่ละบรรทัด Log
530
+ const logLine = document.createElement('span');
531
+ logLine.className = `log-line log-${logData.type || 'info'}`;
532
+
533
+ // สร้างข้อความ Log
534
+ logLine.textContent = `[${time}] ${logData.message}\n`;
535
+
536
+ // เพิ่มบรรทัดใหม่ลงใน Log Viewer
537
+ this.logViewer.appendChild(logLine);
538
+
539
+ // เลื่อนหน้าจอไปที่บรรทัดล่าสุดเสมอ
540
+ this.logViewer.scrollTop = this.logViewer.scrollHeight;
541
+ }
542
+
543
+ // Helper function เพื่อความง่ายในการแทนที่ terminal.writeln()
544
+ writeln(message, type = 'info') {
545
+ // ลบ ANSI color codes ออกจากข้อความ
546
+ const cleanMessage = message.replace(/\x1b\[[0-9;]*m/g, '');
547
+
548
+ // แปลงสีจาก ANSI codes เป็นประเภท Log
549
+ let messageType = type;
550
+ if (message.includes('\x1b[1;32m')) messageType = 'success'; // เขียว
551
+ else if (message.includes('\x1b[1;31m')) messageType = 'error'; // แดง
552
+ else if (message.includes('\x1b[1;33m')) messageType = 'warning'; // เหลือง
553
+ else if (message.includes('\x1b[1;36m')) messageType = 'debug'; // ฟ้า
554
+
555
+ this.writeLog({
556
+ message: cleanMessage,
557
+ type: messageType,
558
+ timestamp: new Date().toISOString()
559
+ });
560
+ }
561
+
562
+ // [เวอร์ชันใหม่] อัปเดต Event Listener ให้เรียกใช้ฟังก์ชันใหม่
563
+ startRealTimeUpdates() {
564
+ if (window.electronAPI && window.electronAPI.onTerminalMessage) {
565
+
566
+ window.electronAPI.onTerminalMessage((logData) => {
567
+ // logData คือ { message, type, timestamp } ที่ส่งมาจาก Backend
568
+ // เรียกใช้ฟังก์ชันเขียน Log ใหม่ของเราโดยตรง
569
+ this.writeLog(logData);
570
+ });
571
+
572
+ console.log(' Raw HTML Log listener enabled.');
573
+ } else {
574
+ console.error(' Could not set up real-time log listener.');
575
+ }
576
+ }
577
+
578
+ updateRunningWorkflows(workflowsData) {
579
+ const container = document.getElementById('runningWorkflows');
580
+ if (!container) return;
581
+
582
+ if (!workflowsData || workflowsData.length === 0) {
583
+ container.innerHTML = `
584
+ <div class="no-selection">
585
+ <i class="fas fa-pause-circle"></i>
586
+ <h3>ไม่มีเวิร์กโฟลว์ที่กำลังทำงาน</h3>
587
+ <p>ใช้คำสั่ง <code>workflows</code> ในเทอร์มินัลเพื่อดูข้อมูลล่าสุด</p>
588
+ </div>
589
+ `;
590
+ return;
591
+ }
592
+
593
+ container.innerHTML = '';
594
+ workflowsData.forEach(workflow => {
595
+ const workflowElement = this.createWorkflowElement(workflow);
596
+ container.appendChild(workflowElement);
597
+ });
598
+ }
599
+
600
+ createWorkflowElement(workflow) {
601
+ const div = document.createElement('div');
602
+ div.className = 'workflow-item';
603
+
604
+ const statusClass = `status-${workflow.status}`;
605
+ const progress = workflow.completedNodes || 0;
606
+ const total = workflow.totalNodes || 0;
607
+ const percentage = total > 0 ? Math.round((progress / total) * 100) : 0;
608
+
609
+ div.innerHTML = `
610
+ <div class="workflow-header">
611
+ <span class="workflow-name">${workflow.name}</span>
612
+ <span class="workflow-status ${statusClass}">${workflow.status}</span>
613
+ </div>
614
+ <div class="workflow-progress">
615
+ <span>${progress}/${total} nodes</span>
616
+ <span>${percentage}% complete</span>
617
+ </div>
618
+ `;
619
+
620
+ return div;
621
+ }
622
+
623
+ updateWorkflowsTab(workflowsData) {
624
+ this.updateRunningWorkflows(workflowsData);
625
+ }
626
+
627
+ formatUptime(seconds) {
628
+ const hours = Math.floor(seconds / 3600);
629
+ const minutes = Math.floor((seconds % 3600) / 60);
630
+ const secs = Math.floor(seconds % 60);
631
+
632
+ if (hours > 0) {
633
+ return `${hours}h ${minutes}m ${secs}s`;
634
+ } else if (minutes > 0) {
635
+ return `${minutes}m ${secs}s`;
636
+ } else {
637
+ return `${secs}s`;
638
+ }
639
+ }
640
+
641
+ async requestWorkflowsUpdate() {
642
+ try {
643
+ if (window.electronAPI && window.electronAPI.diagnostics) {
644
+ const workflows = await window.electronAPI.diagnostics.getWorkflows();
645
+ this.updateRunningWorkflows(workflows);
646
+ }
647
+ } catch (error) {
648
+ console.error('ไม่สามารถดึงข้อมูล workflows ได้:', error);
649
+ }
650
+ }
651
+ }
652
+
653
+ // เริ่มต้น Dashboard เมื่อ DOM พร้อม
654
+ document.addEventListener('DOMContentLoaded', () => {
655
+ window.diagnosticDashboard = new DiagnosticDashboard();
656
+ });
657
+
658
+ // Export สำหรับใช้ใน console
659
+ window.DiagnosticDashboard = DiagnosticDashboard;
generate-checksums.js ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const crypto = require('crypto');
4
+
5
+ // รายชื่อไฟล์ที่สำคัญที่เราไม่ต้องการให้ใครแก้ไข
6
+ const criticalFiles = [
7
+ 'main.js',
8
+ 'preload.js',
9
+ 'validation_gateway.js',
10
+ 'generate-manifests.js',
11
+ 'modules/error-handler.js',
12
+ 'modules/security-logger.js',
13
+ 'modules/system-detector.js',
14
+ 'modules/button-generator.js',
15
+ 'modules/plugin-manager.js',
16
+ 'modules/executor.js',
17
+ 'modules/context-manager.js'
18
+ ];
19
+
20
+ const checksums = {};
21
+
22
+ console.log(' Generating checksums for critical files...');
23
+
24
+ criticalFiles.forEach(filePath => {
25
+ try {
26
+ const fullPath = path.join(__dirname, filePath);
27
+ if (fs.existsSync(fullPath)) {
28
+ const fileContent = fs.readFileSync(fullPath);
29
+ const hash = crypto.createHash('sha256').update(fileContent).digest('hex');
30
+ checksums[filePath] = hash;
31
+ console.log(` ${filePath} -> ${hash.substring(0, 20)}...`);
32
+ } else {
33
+ console.error(` ERROR: File not found at ${fullPath}`);
34
+ }
35
+ } catch (error) {
36
+ console.error(` ERROR: Could not process file ${filePath}: ${error.message}`);
37
+ }
38
+ });
39
+
40
+ // เขียนผลลัพธ์ลงในไฟล์ checksums.json
41
+ const checksumsJson = JSON.stringify(checksums, null, 2);
42
+ fs.writeFileSync(path.join(__dirname, 'checksums.json'), checksumsJson);
43
+
44
+ console.log('\n Checksums generated and saved to checksums.json');
45
+
46
+ // ส่วนที่เพิ่มเข้ามา: สร้าง Signature
47
+ try {
48
+ const privateKeyPath = path.join(__dirname, 'private_key.pem');
49
+
50
+ if (!fs.existsSync(privateKeyPath)) {
51
+ console.error('\n FATAL ERROR: private_key.pem not found!');
52
+ console.error(' Please run "node generate-keys.js" first to generate key pair.');
53
+ console.error(' Or ensure private_key.pem is in the project root directory.');
54
+ process.exit(1);
55
+ }
56
+
57
+ const privateKey = fs.readFileSync(privateKeyPath, 'utf8');
58
+ const signer = crypto.createSign('sha256');
59
+ signer.update(checksumsJson);
60
+ signer.end();
61
+
62
+ const signature = signer.sign(privateKey, 'hex');
63
+ fs.writeFileSync(path.join(__dirname, 'checksums.sig'), signature);
64
+
65
+ console.log(' Checksums successfully signed -> checksums.sig');
66
+ console.log(' Signature:', signature.substring(0, 40) + '...');
67
+
68
+ } catch (error) {
69
+ console.error('\n FATAL ERROR: Could not sign checksums:', error.message);
70
+ console.error(' Please ensure private_key.pem is valid and accessible.');
71
+ console.error(' You may need to regenerate keys by running "node generate-keys.js"');
72
+ process.exit(1);
73
+ }
generate-manifests.js ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // generate-manifests.js (v2 - Final)
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const SystemDetector = require('./modules/system-detector.js');
5
+
6
+ // รับ pluginsDir เป็นพารามิเตอร์
7
+ async function generateManifests(pluginsDir) {
8
+ console.log(' Starting Intelligent Manifest Generator...');
9
+ console.log(` Scanning target directory: ${pluginsDir}`); // Log path ที่ได้รับมา
10
+ const systemDetector = new SystemDetector();
11
+
12
+ if (!fs.existsSync(pluginsDir)) {
13
+ console.error(' Plugins directory not found.');
14
+ return;
15
+ }
16
+
17
+ const items = fs.readdirSync(pluginsDir, { withFileTypes: true });
18
+ let generated = 0, skipped = 0;
19
+
20
+ for (const item of items) {
21
+ if (!item.isDirectory() || item.name.startsWith('.')) continue;
22
+
23
+ const projectPath = path.join(pluginsDir, item.name);
24
+ const manifestPath = path.join(projectPath, 'chahua.json');
25
+
26
+ if (fs.existsSync(manifestPath)) {
27
+ console.log(`- Skipping ${item.name}: Manifest already exists.`);
28
+ skipped++;
29
+ continue;
30
+ }
31
+
32
+ console.log(`+ Analyzing ${item.name}...`);
33
+ try {
34
+ const detectionResult = await systemDetector.detect(projectPath);
35
+ const { type, confidence } = detectionResult;
36
+
37
+ const manifestData = {
38
+ name: item.name.replace(/_/g, ' ').replace(/[.-]/g, ' '),
39
+ description: `Auto-generated manifest for ${type} project.`,
40
+ type: type,
41
+ icon: getIconForType(type),
42
+ buttons: generateButtonsForType(type, projectPath, item.name),
43
+ publisher: 'Chahua Development Thailand' // เพิ่มบรรทัดนี้
44
+ };
45
+
46
+ fs.writeFileSync(manifestPath, JSON.stringify(manifestData, null, 2));
47
+ console.log(` -> Successfully generated chahua.json for [${type}] project: ${item.name}`);
48
+ generated++;
49
+ } catch (error) {
50
+ console.error(` -> Failed to analyze ${item.name}: ${error.message}`);
51
+ }
52
+ }
53
+ console.log(`\n Manifest generation complete! (${generated} generated, ${skipped} skipped)`);
54
+ }
55
+
56
+ function getIconForType(projectType) {
57
+ const icons = {
58
+ 'node': '', 'python': '', 'batch_project': '',
59
+ 'executable_project': '', 'standalone_js': '', 'html': ''
60
+ };
61
+ return icons[projectType] || '';
62
+ }
63
+
64
+ function generateButtonsForType(projectType, projectPath, folderName) {
65
+ const buttons = [];
66
+ const rootFiles = fs.readdirSync(projectPath).map(f => f.toLowerCase());
67
+
68
+ switch (projectType) {
69
+ case 'node':
70
+ const pkgPath = path.join(projectPath, 'package.json');
71
+ try {
72
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
73
+ buttons.push({ id: 'install', name: 'Install', command: 'npm install', icon: '' });
74
+ if (pkg.scripts?.start) buttons.push({ id: 'start', name: 'Start', command: 'npm start', icon: '' });
75
+ // ลบปุ่ม Dev ออก: if (pkg.scripts?.dev) buttons.push({ id: 'dev', name: 'Dev', command: 'npm run dev', icon: '' });
76
+ } catch { console.warn(`Could not parse package.json for ${folderName}`); }
77
+ break;
78
+
79
+ case 'batch_project':
80
+ const batFile = rootFiles.find(f => f === `${folderName.toLowerCase()}.bat`) || rootFiles.find(f => f.endsWith('.bat'));
81
+ if (batFile) {
82
+ buttons.push({ id: 'run-batch', name: 'Run Script', command: 'run-batch', icon: '' });
83
+ buttons.push({ id: 'edit-batch', name: 'Edit Script', command: 'edit-batch', icon: '' });
84
+ }
85
+ break;
86
+
87
+ case 'executable_project':
88
+ const exeFile = rootFiles.find(f => f === `${folderName.toLowerCase()}.exe`) || rootFiles.find(f => f.endsWith('.exe'));
89
+ if (exeFile) {
90
+ buttons.push({ id: 'launch-exe', name: 'Launch App', command: 'launch-exe', icon: '' });
91
+ buttons.push({ id: 'run-as-admin', name: 'Run as Admin', command: 'run-as-admin', icon: '' });
92
+ }
93
+ break;
94
+
95
+ case 'python':
96
+ if (rootFiles.includes('requirements.txt')) {
97
+ buttons.push({ id: 'pip-install', name: 'Install', command: 'pip install -r requirements.txt', icon: '' });
98
+ }
99
+ const pyFile = ['app.py', 'main.py'].find(f => rootFiles.includes(f)) || rootFiles.find(f => f.endsWith('.py'));
100
+ if (pyFile) {
101
+ buttons.push({ id: 'run-python', name: 'Run', command: `python ${pyFile}`, icon: '' });
102
+ }
103
+ break;
104
+
105
+ case 'standalone_js':
106
+ const jsFile = rootFiles.find(f => f.endsWith('.js'));
107
+ if (jsFile) {
108
+ buttons.push({ id: 'run-js', name: 'Run Script', command: `node ${jsFile}`, icon: '' });
109
+ }
110
+ break;
111
+ }
112
+
113
+ buttons.push({ id: 'open-folder', name: 'Open Folder', command: 'open_explorer', icon: '' });
114
+ return buttons;
115
+ }
116
+
117
+ // Export the function for use in other modules (e.g., main.js)
118
+ module.exports = { generateManifests };
119
+
120
+ if (require.main === module) {
121
+ // เมื่อรันโดยตรง ให้ใช้ path แบบเดิม (สำหรับ development)
122
+ const pluginsDir = path.join(__dirname, 'plugins');
123
+ generateManifests(pluginsDir).catch(console.error);
124
+ }
junk-map-layout.json ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "ApiTraceDebugger.js": {
3
+ "x": 0,
4
+ "y": 0
5
+ },
6
+ "auth-dialog.js": {
7
+ "x": 280,
8
+ "y": 0
9
+ },
10
+ "backend/utils/inspector-worker.js": {
11
+ "x": 560,
12
+ "y": 0
13
+ },
14
+ "backend/utils/project-inspector.js": {
15
+ "x": 840,
16
+ "y": 0
17
+ },
18
+ "backend/utils/project-inspector-ipc.js": {
19
+ "x": 1120,
20
+ "y": 0
21
+ },
22
+ "checksums.json": {
23
+ "x": 1400,
24
+ "y": 0
25
+ },
26
+ "config/default.json": {
27
+ "x": 1680,
28
+ "y": 0
29
+ },
30
+ "config/obfuscator.config.js": {
31
+ "x": 1960,
32
+ "y": 0
33
+ },
34
+ "config/production.json": {
35
+ "x": 2240,
36
+ "y": 0
37
+ },
38
+ "debug-manager.js": {
39
+ "x": 2520,
40
+ "y": 0
41
+ },
42
+ "debugger.html": {
43
+ "x": 0,
44
+ "y": 130
45
+ },
46
+ "debugger.js": {
47
+ "x": 280,
48
+ "y": 130
49
+ },
50
+ "generate-checksums.js": {
51
+ "x": 560,
52
+ "y": 130
53
+ },
54
+ "generate-manifests.js": {
55
+ "x": 840,
56
+ "y": 130
57
+ },
58
+ "modules/system-detector.js": {
59
+ "x": 1120,
60
+ "y": 130
61
+ },
62
+ "index.html": {
63
+ "x": 1400,
64
+ "y": 130
65
+ },
66
+ "main.js": {
67
+ "x": 1680,
68
+ "y": 130
69
+ },
70
+ "validation_gateway.js": {
71
+ "x": 1960,
72
+ "y": 130
73
+ },
74
+ "modules/tamper-detector.js": {
75
+ "x": 2240,
76
+ "y": 130
77
+ },
78
+ "utils/project-inspector.js": {
79
+ "x": 2520,
80
+ "y": 130
81
+ },
82
+ "strategies/NodeStrategy.js": {
83
+ "x": 0,
84
+ "y": 260
85
+ },
86
+ "modules/button-generator.js": {
87
+ "x": 280,
88
+ "y": 260
89
+ },
90
+ "modules/cache-manager.js": {
91
+ "x": 560,
92
+ "y": 260
93
+ },
94
+ "modules/callback-hub.js": {
95
+ "x": 840,
96
+ "y": 260
97
+ },
98
+ "modules/callback-logger.js": {
99
+ "x": 1120,
100
+ "y": 260
101
+ },
102
+ "modules/cli.js": {
103
+ "x": 1400,
104
+ "y": 260
105
+ },
106
+ "modules/validation_gateway.js": {
107
+ "x": 1680,
108
+ "y": 260
109
+ },
110
+ "modules/modules/context-manager.js": {
111
+ "x": 1960,
112
+ "y": 260
113
+ },
114
+ "modules/modules/error-handler.js": {
115
+ "x": 2240,
116
+ "y": 260
117
+ },
118
+ "modules/modules/executor.js": {
119
+ "x": 2520,
120
+ "y": 260
121
+ },
122
+ "modules/modules/system-detector.js": {
123
+ "x": 0,
124
+ "y": 390
125
+ },
126
+ "modules/modules/plugin-manager.js": {
127
+ "x": 280,
128
+ "y": 390
129
+ },
130
+ "modules/context-manager.js": {
131
+ "x": 560,
132
+ "y": 390
133
+ },
134
+ "modules/error-handler.js": {
135
+ "x": 840,
136
+ "y": 390
137
+ },
138
+ "modules/executor.js": {
139
+ "x": 1120,
140
+ "y": 390
141
+ },
142
+ "modules/health-monitor.js": {
143
+ "x": 1400,
144
+ "y": 390
145
+ },
146
+ "modules/key-system.js": {
147
+ "x": 1680,
148
+ "y": 390
149
+ },
150
+ "modules/plugin-manager.js": {
151
+ "x": 1960,
152
+ "y": 390
153
+ },
154
+ "modules/retry-controller.js": {
155
+ "x": 2240,
156
+ "y": 390
157
+ },
158
+ "modules/rollback-manager.js": {
159
+ "x": 2520,
160
+ "y": 390
161
+ },
162
+ "modules/security-logger.js": {
163
+ "x": 0,
164
+ "y": 520
165
+ },
166
+ "modules/svg-icons.js": {
167
+ "x": 280,
168
+ "y": 520
169
+ },
170
+ "strategies/PythonStrategy.js": {
171
+ "x": 560,
172
+ "y": 520
173
+ },
174
+ "strategies/JavaStrategy.js": {
175
+ "x": 840,
176
+ "y": 520
177
+ },
178
+ "strategies/ApiStrategy.js": {
179
+ "x": 1120,
180
+ "y": 520
181
+ },
182
+ "package-lock.json": {
183
+ "x": 1400,
184
+ "y": 520
185
+ },
186
+ "package.json": {
187
+ "x": 1680,
188
+ "y": 520
189
+ },
190
+ "packages/@chahuadev/framework/index.js": {
191
+ "x": 1960,
192
+ "y": 520
193
+ },
194
+ "packages/@chahuadev/framework/install.js": {
195
+ "x": 2240,
196
+ "y": 520
197
+ },
198
+ "packages/@chahuadev/framework/package-lock.json": {
199
+ "x": 2520,
200
+ "y": 520
201
+ },
202
+ "packages/@chahuadev/framework/package.json": {
203
+ "x": 0,
204
+ "y": 650
205
+ },
206
+ "playwright.config.js": {
207
+ "x": 280,
208
+ "y": 650
209
+ },
210
+ "preload-webview.js": {
211
+ "x": 560,
212
+ "y": 650
213
+ },
214
+ "preload.js": {
215
+ "x": 840,
216
+ "y": 650
217
+ },
218
+ "scripts/copy-user-guides.js": {
219
+ "x": 1120,
220
+ "y": 650
221
+ },
222
+ "scripts/main.js": {
223
+ "x": 1400,
224
+ "y": 650
225
+ },
226
+ "scripts/project-manager.js": {
227
+ "x": 1680,
228
+ "y": 650
229
+ },
230
+ "scripts/secure-build.js": {
231
+ "x": 1960,
232
+ "y": 650
233
+ },
234
+ "scripts/setup-npm-token.js": {
235
+ "x": 2240,
236
+ "y": 650
237
+ },
238
+ "splash.html": {
239
+ "x": 2520,
240
+ "y": 650
241
+ }
242
+ }
main.js ADDED
@@ -0,0 +1,2464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ const { app, BrowserWindow, ipcMain, dialog, Menu, shell } = require('electron'); // เพิ่ม Menu และ shell
3
+ const path = require('path');
4
+ const fs = require('fs');
5
+ const os = require('os'); // เพิ่ม os
6
+ const crypto = require('crypto'); // เพิ่ม crypto
7
+ const https = require('https'); // เพิ่มสำหรับ OAuth Device Flow
8
+ const { spawn, exec } = require('child_process'); // เพิ่มสำหรับ manifest generator และ terminal
9
+
10
+ // Ignore dev flags in packaged builds so distributed binaries cannot be forced into dev mode.
11
+ if (app.isPackaged) {
12
+ process.argv = process.argv.filter(arg => arg !== '--dev-mode' && arg !== '--dev');
13
+ }
14
+
15
+ // ======================================================================
16
+ // ขั้นตอนที่ 1: เตรียมระบบติดตาม API (ไม่เริ่มทันที)
17
+ // ======================================================================
18
+
19
+ // ตรวจสอบ Dev Mode ให้เร็วที่สุด
20
+ const isDevMode = !app.isPackaged || process.argv.includes('--dev-mode');
21
+ console.log(` Developer Mode: ${isDevMode ? 'ENABLED' : 'DISABLED'} (${!app.isPackaged ? 'Development' : process.argv.includes('--dev-mode') ? '--dev-mode flag' : 'Production'})`);
22
+
23
+ // [COMMENTED] โหลด ApiTraceDebugger แต่ยังไม่เริ่มทำงาน (จะเริ่มใน app.whenReady())
24
+ // [REASON] ออฟไลน์ Auth System ใช้อยู่แล้ว - คอมเมนท์ไว้ เผื่อต้องใช้ในอนาคต
25
+ // const ApiTraceDebugger = require('./ApiTraceDebugger');
26
+ // console.log('[API TRACE] ระบบติดตาม API พร้อมใช้งาน (จะเริ่มหลัง app.whenReady())');
27
+
28
+ // Stub ApiTraceDebugger เพื่อป้องกัน error
29
+ const ApiTraceDebugger = {
30
+ start: () => console.log('[API TRACE] (Disabled - using Offline Auth)'),
31
+ stop: () => console.log('[API TRACE] (Disabled)')
32
+ };
33
+
34
+ // ======================================================================
35
+ // ขั้นตอนที่ 2: โหลดโมดูลอื่นๆ ของแอปพลิเคชันตามปกติ
36
+ // ======================================================================
37
+ // โมดูลเหล่านี้จะถูกโหลดก่อน แต่ยังไม่ได้ใช้งาน API มากนัก
38
+
39
+ // Direct Integration - ไม่ต้อง spawn app.js แล้ว!
40
+ const ValidationGateway = require('./validation_gateway');
41
+ // ========== FORT-KNOX LEVEL SECURITY SYSTEM ==========
42
+
43
+ // เพิ่ม Tamper Detector
44
+ const TamperDetector = require('./modules/tamper-detector');
45
+
46
+ /**
47
+ * OFFLINE DEMO AUTHENTICATION CLIENT (ปิด OAuth Device Flow ชั่วคราว)
48
+ * สำหรับการทดสอบและการพัฒนาโดยไม่ต้องเชื่อมต่อ chahuadev.com
49
+ */
50
+ class OfflineAuthClient {
51
+ constructor() {
52
+ this.storagePath = path.join(os.homedir(), '.chahuadev', 'auth.json');
53
+ this.demoUsers = {
54
+ 'admin': {
55
+ username: 'admin',
56
+ password: 'demo123',
57
+ userId: 'usr_admin_001',
58
+ email: 'admin@chahuadev.local',
59
+ role: 'Administrator',
60
+ avatar: '[ADMIN]',
61
+ permissions: ['read', 'write', 'admin']
62
+ },
63
+ 'developer': {
64
+ username: 'developer',
65
+ password: 'demo123',
66
+ userId: 'usr_dev_001',
67
+ email: 'dev@chahuadev.local',
68
+ role: 'Developer',
69
+ avatar: '[DEV]',
70
+ permissions: ['read', 'write']
71
+ },
72
+ 'user': {
73
+ username: 'user',
74
+ password: 'demo123',
75
+ userId: 'usr_user_001',
76
+ email: 'user@chahuadev.local',
77
+ role: 'User',
78
+ avatar: '[USER]',
79
+ permissions: ['read']
80
+ }
81
+ };
82
+
83
+ this.ensureStorageDirectory();
84
+ console.log('[OFFLINE AUTH] [SUCCESS] OFFLINE AUTH MODE (เดโมสำหรับการพัฒนา) - ไม่ต้องเชื่อมต่อ chahuadev.com');
85
+ }
86
+
87
+ /**
88
+ * สร้าง directory สำหรับเก็บข้อมูล authentication
89
+ */
90
+ ensureStorageDirectory() {
91
+ const dir = path.dirname(this.storagePath);
92
+ if (!fs.existsSync(dir)) {
93
+ fs.mkdirSync(dir, { recursive: true });
94
+ }
95
+ }
96
+
97
+ /**
98
+ * OFFLINE: เริ่มต้นการล็อคอินแบบออฟไลน์ (จำลองแบบ Device Flow)
99
+ */
100
+ async startDeviceFlow() {
101
+ console.log(' [OFFLINE AUTH] Device Flow simulation started');
102
+
103
+ // จำลองการสร้าง device code
104
+ const deviceCode = 'OFFLINE-' + crypto.randomBytes(16).toString('hex').toUpperCase();
105
+ const userCode = 'DEMO-' + Math.random().toString(36).substring(2, 8).toUpperCase();
106
+
107
+ const mockResponse = {
108
+ success: true,
109
+ deviceCode: deviceCode,
110
+ userCode: userCode,
111
+ expiresIn: 600,
112
+ interval: 5,
113
+ message: ' กรุณาป้อน User Code: ' + userCode,
114
+ instruction: 'ใช้ชื่อผู้ใช้: admin/developer/user พร้อม password: demo123'
115
+ };
116
+
117
+ console.log(' [OFFLINE AUTH] Mock Device Code:', deviceCode);
118
+ console.log(' [OFFLINE AUTH] Mock User Code:', userCode);
119
+
120
+ return mockResponse;
121
+ }
122
+
123
+ /**
124
+ * OFFLINE: การยืนยันการล็อคอินแบบออฟไลน์
125
+ */
126
+ async authenticateOffline(username, password) {
127
+ console.log(` [OFFLINE AUTH] Attempting login: ${username}`);
128
+
129
+ // ตรวจสอบ username และ password
130
+ const user = this.demoUsers[username];
131
+ if (!user || user.password !== password) {
132
+ console.error(' [OFFLINE AUTH] Invalid credentials');
133
+ return {
134
+ success: false,
135
+ error: 'ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง'
136
+ };
137
+ }
138
+
139
+ // สร้าง mock tokens
140
+ const mockTokens = {
141
+ accessToken: 'mock_access_' + crypto.randomBytes(32).toString('hex'),
142
+ refreshToken: 'mock_refresh_' + crypto.randomBytes(32).toString('hex'),
143
+ expiresIn: 86400, // 24 hours
144
+ user: {
145
+ username: user.username,
146
+ userId: user.userId,
147
+ email: user.email,
148
+ role: user.role,
149
+ avatar: user.avatar,
150
+ permissions: user.permissions
151
+ },
152
+ authenticated: true,
153
+ authenticatedAt: new Date().toISOString()
154
+ };
155
+
156
+ // บันทึก tokens
157
+ await this.saveTokens(mockTokens);
158
+
159
+ console.log(' [OFFLINE AUTH] Login successful:', user.username);
160
+ return {
161
+ success: true,
162
+ status: 'approved',
163
+ data: mockTokens
164
+ };
165
+ }
166
+
167
+ /**
168
+ * OFFLINE: จำลอง polling device status
169
+ */
170
+ async pollDeviceStatus(deviceCode) {
171
+ console.log(' [OFFLINE AUTH] Polling device status (offline mode)');
172
+
173
+ // ในโหมดออฟไลน์ เราจะรีเทิร์นสถานะรอการยืนยัน
174
+ return {
175
+ success: true,
176
+ status: 'pending',
177
+ message: 'รอการใส่ชื่อผู้ใช้และรหัสผ่าน'
178
+ };
179
+ }
180
+
181
+ /**
182
+ * บันทึก tokens ลงไฟล์
183
+ */
184
+ async saveTokens(tokens) {
185
+ try {
186
+ const authData = {
187
+ accessToken: tokens.accessToken,
188
+ refreshToken: tokens.refreshToken,
189
+ expiresAt: Date.now() + (tokens.expiresIn * 1000),
190
+ user: tokens.user,
191
+ savedAt: new Date().toISOString(),
192
+ authMode: 'offline-demo'
193
+ };
194
+
195
+ fs.writeFileSync(this.storagePath, JSON.stringify(authData, null, 2), 'utf8');
196
+ console.log(' [OFFLINE AUTH] Tokens saved:', this.storagePath);
197
+ return { success: true };
198
+ } catch (error) {
199
+ console.error(' [OFFLINE AUTH] Failed to save tokens:', error);
200
+ return { success: false, error: error.message };
201
+ }
202
+ }
203
+
204
+ /**
205
+ * โหลด tokens จากไฟล์
206
+ */
207
+ async loadTokens() {
208
+ try {
209
+ if (!fs.existsSync(this.storagePath)) {
210
+ return { success: false, error: 'No saved tokens found' };
211
+ }
212
+
213
+ const authData = JSON.parse(fs.readFileSync(this.storagePath, 'utf8'));
214
+
215
+ // ตรวจสอบว่า token หมดอายุหรือไม่
216
+ if (authData.expiresAt && Date.now() > authData.expiresAt) {
217
+ console.log(' [OFFLINE AUTH] Token expired');
218
+ return { success: false, error: 'Token expired' };
219
+ }
220
+
221
+ console.log(' [OFFLINE AUTH] Tokens loaded:', authData.user.username);
222
+ return { success: true, data: authData };
223
+ } catch (error) {
224
+ console.error(' [OFFLINE AUTH] Failed to load tokens:', error);
225
+ return { success: false, error: error.message };
226
+ }
227
+ }
228
+
229
+ /**
230
+ * ลบ tokens (logout)
231
+ */
232
+ async removeTokens() {
233
+ try {
234
+ if (fs.existsSync(this.storagePath)) {
235
+ fs.unlinkSync(this.storagePath);
236
+ }
237
+ console.log(' [OFFLINE AUTH] Logged out successfully');
238
+ return { success: true };
239
+ } catch (error) {
240
+ console.error(' [OFFLINE AUTH] Failed to remove tokens:', error);
241
+ return { success: false, error: error.message };
242
+ }
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Anti-Debugging Protection System
248
+ * ป้องกันการใช้เครื่องมือดีบักและ reverse engineering
249
+ */
250
+ class AntiDebuggingSystem {
251
+ constructor() {
252
+ this.checkInterval = null;
253
+ // ปรับปรุงการตรวจสอบ developer mode ให้ครอบคลุมมากขึ้น
254
+ this.isDevMode = this.detectDeveloperMode();
255
+ this.suspiciousActivityCount = 0;
256
+ this.maxSuspiciousActivity = 3;
257
+
258
+ // เริ่มต้นระบบตรวจจับการแก้ไข
259
+ this.tamperDetector = new TamperDetector();
260
+
261
+ console.log(this.isDevMode ? ' Anti-Debugging: Development mode detected' : ' Anti-Debugging: Production mode active');
262
+ }
263
+
264
+ /**
265
+ * ระบบตรวจสอบ Developer Mode ที่ครอบคลุม
266
+ * ตรวจสอบจากหลายแหล่งเพื่อความแม่นยำ
267
+ */
268
+ detectDeveloperMode() {
269
+ const indicators = {
270
+ // 1. Process arguments
271
+ hasDevArgs: process.argv.includes('--dev-mode') || process.argv.includes('--dev'),
272
+
273
+ // 2. Application packaging status
274
+ isUnpackaged: !app.isPackaged,
275
+
276
+ // 3. Environment variables
277
+ hasDevEnv: process.env.NODE_ENV === 'development' || process.env.CHAHUA_DEV === 'true',
278
+
279
+ // 4. Development port detection
280
+ hasDevPort: process.env.PORT && (process.env.PORT === '3000' || process.env.PORT === '8080'),
281
+
282
+ // 5. Debug mode flags
283
+ hasDebugFlag: process.execArgv.some(arg => arg.includes('--inspect') || arg.includes('--debug')),
284
+
285
+ // 6. Development dependencies
286
+ hasDevDeps: false // จะตรวจสอบเพิ่มเติมใน package.json ถ้าจำเป็น
287
+ };
288
+
289
+ // Log detection results for debugging
290
+ console.log(' Developer Mode Detection Results:', indicators);
291
+
292
+ // Return true if any indicator suggests development mode
293
+ return Object.values(indicators).some(Boolean);
294
+ }
295
+
296
+ /**
297
+ * เริ่มระบบป้องกันการดีบัก
298
+ */
299
+ start(mainWindow) {
300
+ if (this.isDevMode) {
301
+ console.log(' Anti-Debugging: Disabled in development mode');
302
+ return;
303
+ }
304
+
305
+ console.log(' Starting Anti-Debugging protection...');
306
+ this.mainWindow = mainWindow;
307
+
308
+ // เริ่มระบบตรวจจับการแก้ไขไฟล์
309
+ this.tamperDetector.startMonitoring();
310
+
311
+ // ตรวจสอบทุกๆ 2 วินาที
312
+ this.checkInterval = setInterval(() => {
313
+ this.performSecurityChecks();
314
+ }, 2000);
315
+
316
+ // ตรวจสอบ DevTools events
317
+ if (mainWindow && mainWindow.webContents) {
318
+ mainWindow.webContents.on('devtools-opened', () => {
319
+ this.handleSuspiciousActivity('DevTools opened');
320
+ });
321
+
322
+ mainWindow.webContents.on('devtools-focused', () => {
323
+ this.handleSuspiciousActivity('DevTools focused');
324
+ });
325
+ }
326
+ }
327
+
328
+ /**
329
+ * ทำการตรวจสอบความปลอดภัย
330
+ */
331
+ performSecurityChecks() {
332
+ try {
333
+ // ตรวจสอบ DevTools
334
+ if (this.mainWindow && this.mainWindow.webContents && this.mainWindow.webContents.isDevToolsOpened()) {
335
+ this.handleSuspiciousActivity('DevTools detected as open');
336
+ return;
337
+ }
338
+
339
+ // ตรวจสอบ debugging tools ใน process list (Windows)
340
+ if (process.platform === 'win32') {
341
+ this.checkForDebuggingProcesses();
342
+ }
343
+
344
+ // ตรวจสอบ performance timing anomalies (อาจมี debugger ทำให้ช้า)
345
+ this.checkPerformanceAnomalies();
346
+
347
+ } catch (error) {
348
+ console.warn(' Anti-Debugging check error:', error.message);
349
+ }
350
+ }
351
+
352
+ /**
353
+ * ตรวจสอบ process ที่น่าสงสัย
354
+ */
355
+ checkForDebuggingProcesses() {
356
+ const suspiciousProcesses = [
357
+ 'cheatengine', 'x64dbg', 'x32dbg', 'ollydbg', 'windbg',
358
+ 'processhacker', 'pestudio', 'ida64', 'ida32', 'ghidra'
359
+ ];
360
+
361
+ // ใช้ tasklist command เพื่อดู running processes
362
+ exec('tasklist', (error, stdout) => {
363
+ if (error) return;
364
+
365
+ const runningProcesses = stdout.toLowerCase();
366
+ for (const suspiciousProcess of suspiciousProcesses) {
367
+ if (runningProcesses.includes(suspiciousProcess)) {
368
+ this.handleSuspiciousActivity(`Debugging tool detected: ${suspiciousProcess}`);
369
+ return;
370
+ }
371
+ }
372
+ });
373
+ }
374
+
375
+ /**
376
+ * ตรวจสอบ performance anomalies
377
+ */
378
+ checkPerformanceAnomalies() {
379
+ const start = Date.now();
380
+
381
+ // สร้าง simple computation
382
+ let sum = 0;
383
+ for (let i = 0; i < 10000; i++) {
384
+ sum += Math.random();
385
+ }
386
+
387
+ const duration = Date.now() - start;
388
+
389
+ // ถ้าใช้เวลานานกว่าปกติมาก อาจมี debugger
390
+ if (duration > 100) { // ปกติควรใช้เวลาไม่เกิน 10-20ms
391
+ this.handleSuspiciousActivity(`Performance anomaly detected: ${duration}ms`);
392
+ }
393
+ }
394
+
395
+ /**
396
+ * จัดการเมื่อพบกิจกรรมน่าสงสัย
397
+ */
398
+ handleSuspiciousActivity(reason) {
399
+ this.suspiciousActivityCount++;
400
+ console.warn(` Security Alert [${this.suspiciousActivityCount}/${this.maxSuspiciousActivity}]: ${reason}`);
401
+
402
+ if (this.suspiciousActivityCount >= this.maxSuspiciousActivity) {
403
+ console.error(' Security breach detected! Shutting down application...');
404
+
405
+ // แสดง warning dialog ก่อนปิด
406
+ if (this.mainWindow) {
407
+ dialog.showErrorBox(
408
+ 'Security Alert',
409
+ 'Security violation detected. Application will now close for protection.'
410
+ );
411
+ }
412
+
413
+ // ปิดแอปทันที
414
+ process.exit(1);
415
+ }
416
+ }
417
+
418
+ /**
419
+ * หยุดระบบป้องกัน
420
+ */
421
+ stop() {
422
+ if (this.checkInterval) {
423
+ clearInterval(this.checkInterval);
424
+ this.checkInterval = null;
425
+ console.log(' Anti-Debugging protection stopped');
426
+ }
427
+
428
+ // หยุดระบบตรวจจับการแก้ไข
429
+ if (this.tamperDetector) {
430
+ this.tamperDetector.stopMonitoring();
431
+ }
432
+ }
433
+ }
434
+
435
+ /**
436
+ * IPC Command Sanitization System
437
+ * ป้องกันการโจมตีแบบ Command Injection ผ่าน IPC
438
+ */
439
+ class IPCSecuritySystem {
440
+ constructor() {
441
+ // รายการคำสั่งที่อนุญาตให้รันผ่าน child_process
442
+ this.allowedCommands = new Set([
443
+ 'node', 'npm', 'git', 'where', 'which', 'echo', 'dir', 'ls',
444
+ 'cd', 'pwd', 'whoami', 'hostname', 'ipconfig', 'ping',
445
+ 'powershell', // สำหรับ Run as Admin
446
+ 'explorer' // สำหรับ Open Folder
447
+ ]);
448
+
449
+ // Pattern ที่อันตราย
450
+ this.dangerousPatterns = [
451
+ /rm\s+-rf/i, // ลบไฟล์
452
+ /del\s+\/[sq]/i, // Windows delete
453
+ /format\s+[cd]:/i, // Format drive
454
+ /shutdown/i, // Shutdown
455
+ /reboot/i, // Reboot
456
+ />\s*nul/i, // Redirect อันตราย
457
+ /`[^`]*`/, // Command substitution
458
+ /\$\([^)]*\)/, // Command substitution
459
+ /eval\s*\(/i, // Eval
460
+ /exec\s*\(/i // Exec
461
+ ];
462
+
463
+ console.log(' IPC Security System initialized');
464
+ }
465
+
466
+ /**
467
+ * ตรวจสอบและทำความสะอาดคำสั่ง
468
+ */
469
+ sanitizeCommand(command, options = {}) {
470
+ if (!command || typeof command !== 'string') {
471
+ throw new Error('Invalid command: Command must be a non-empty string');
472
+ }
473
+
474
+ const trimmedCommand = command.trim();
475
+
476
+ // เพิ่ม: ยกเว้นสำหรับ powershell ที่มี -Command และ Start-Process (ปลอดภัยสำหรับ Run as Admin)
477
+ if (trimmedCommand.startsWith('powershell -Command "Start-Process')) {
478
+ console.log(' Allowed safe powershell command for admin mode');
479
+ return {
480
+ original: command,
481
+ sanitized: trimmedCommand,
482
+ baseCommand: 'powershell',
483
+ isAllowed: true
484
+ };
485
+ }
486
+
487
+ // ตรวจสอบ dangerous patterns
488
+ for (const pattern of this.dangerousPatterns) {
489
+ if (pattern.test(trimmedCommand)) {
490
+ throw new Error(`Dangerous command pattern detected: ${pattern.source}`);
491
+ }
492
+ }
493
+
494
+ // แยกคำสั่งหลักออกมา
495
+ const commandParts = trimmedCommand.split(/\s+/);
496
+ const baseCommand = commandParts[0].toLowerCase();
497
+
498
+ // ตรวจสอบว่าคำสั่งหลักอยู่ใน whitelist หรือไม่
499
+ if (!this.allowedCommands.has(baseCommand)) {
500
+ throw new Error(`Command not allowed: ${baseCommand}`);
501
+ }
502
+
503
+ // ตรวจสอบ path traversal
504
+ if (trimmedCommand.includes('../') || trimmedCommand.includes('..\\')) {
505
+ throw new Error('Path traversal detected in command');
506
+ }
507
+
508
+ // จำกัดความยาวคำสั่ง
509
+ if (trimmedCommand.length > 500) {
510
+ throw new Error('Command too long (max 500 characters)');
511
+ }
512
+
513
+ console.log(` Command sanitized: ${baseCommand}`);
514
+ return {
515
+ original: command,
516
+ sanitized: trimmedCommand,
517
+ baseCommand: baseCommand,
518
+ isAllowed: true
519
+ };
520
+ }
521
+
522
+ /**
523
+ * เพิ่มคำสั่งที่อนุญาต
524
+ */
525
+ addAllowedCommand(command) {
526
+ this.allowedCommands.add(command.toLowerCase());
527
+ console.log(` Added allowed command: ${command}`);
528
+ }
529
+
530
+ /**
531
+ * ลบคำสั่งที่อนุญาต
532
+ */
533
+ removeAllowedCommand(command) {
534
+ this.allowedCommands.delete(command.toLowerCase());
535
+ console.log(` Removed allowed command: ${command}`);
536
+ }
537
+
538
+ /**
539
+ * ดูรายการคำสั่งที่อนุญาต
540
+ */
541
+ getAllowedCommands() {
542
+ return Array.from(this.allowedCommands);
543
+ }
544
+ }
545
+
546
+ // สร้าง instance ของระบบป้องกัน
547
+ const antiDebugging = new AntiDebuggingSystem();
548
+ const ipcSecurity = new IPCSecuritySystem();
549
+
550
+ // Import generate-manifests function for production builds
551
+ const { generateManifests } = require('./generate-manifests.js');
552
+
553
+ // ฟังก์ชันตรวจสอบ Digital Signature และ Integrity
554
+ function checkAppIntegrity() {
555
+ console.log(' Verifying application integrity & signature...');
556
+
557
+ // ข้าม checksum verification ในโหมด development
558
+ if (!app.isPackaged || process.argv.includes('--dev-mode')) {
559
+ console.log(' Development mode detected - skipping checksum verification');
560
+ return true;
561
+ }
562
+
563
+ try {
564
+ // --- 1. อ่านไฟล์ทั้งหมดที่จำเป็น ---
565
+ // Security files are now stored inside ASAR for better protection
566
+ let checksumsPath, signaturePath, publicKeyPath;
567
+
568
+ if (app.isPackaged) {
569
+ // Production: อ่านจากใน ASAR (ปลอดภัย)
570
+ checksumsPath = path.join(__dirname, 'checksums.json');
571
+ signaturePath = path.join(__dirname, 'checksums.sig');
572
+ publicKeyPath = path.join(__dirname, 'public_key.pem');
573
+ console.log(' Production mode: Reading security files from ASAR');
574
+ } else {
575
+ // Development: อ่านจาก project root
576
+ checksumsPath = path.join(__dirname, 'checksums.json');
577
+ signaturePath = path.join(__dirname, 'checksums.sig');
578
+ publicKeyPath = path.join(__dirname, 'public_key.pem');
579
+ console.log(' Development mode: Reading security files from project root');
580
+ }
581
+
582
+ // ตรวจสอบว่าไฟล์ security มีอยู่หรือไม่
583
+ if (!fs.existsSync(checksumsPath) || !fs.existsSync(signaturePath) || !fs.existsSync(publicKeyPath)) {
584
+ console.log(' Security files not found - skipping integrity check (Development mode?)');
585
+ return true; // ในโหมดพัฒนาหรือไม่มีไฟล์ security ให้ผ่าน
586
+ }
587
+
588
+ const storedChecksumsJson = fs.readFileSync(checksumsPath, 'utf8');
589
+ const signature = fs.readFileSync(signaturePath, 'utf8');
590
+ const publicKey = fs.readFileSync(publicKeyPath, 'utf8');
591
+
592
+ // --- 2. ตรวจสอบลายเซ็นก่อน (Verify Signature) ---
593
+ const verifier = crypto.createVerify('sha256');
594
+ verifier.update(storedChecksumsJson);
595
+ verifier.end();
596
+
597
+ if (!verifier.verify(publicKey, signature, 'hex')) {
598
+ // ถ้าลายเซ็นไม่ถูกต้อง แสดงว่า checksums.json ถูกแก้ไข!
599
+ dialog.showErrorBox('Security Alert', 'Checksum file signature is invalid. The application has been tampered with.');
600
+ return false;
601
+ }
602
+ console.log(' Signature verification passed.');
603
+
604
+ // --- 3. ถ้าลายเซ็นถูกต้อง ค่อยตรวจสอบ Integrity ของไฟล์ ---
605
+ const storedChecksums = JSON.parse(storedChecksumsJson);
606
+
607
+ for (const filePath in storedChecksums) {
608
+ const fullPath = path.join(__dirname, filePath);
609
+ if (!fs.existsSync(fullPath)) {
610
+ console.log(` Security file missing: ${filePath} - skipping check`);
611
+ continue; // ข้ามไฟล์ที่ไม่มี แทนที่จะ error
612
+ }
613
+
614
+ const fileContent = fs.readFileSync(fullPath);
615
+ const currentHash = crypto.createHash('sha256').update(fileContent).digest('hex');
616
+
617
+ if (currentHash !== storedChecksums[filePath]) {
618
+ // ถ้า Hash ไม่ตรงกัน แสดงว่าไฟล์ถูกแก้ไข!
619
+ dialog.showErrorBox('Security Alert', `File tampering detected: ${filePath}. The program will now exit.`);
620
+ return false;
621
+ }
622
+ }
623
+
624
+ console.log(' All file integrity checks passed.');
625
+ return true;
626
+
627
+ } catch (error) {
628
+ console.error(' Security check error:', error.message);
629
+ // ในกรณีที่เกิดข้อผิดพลาดในการตรวจสอบ ให้ผ่านในโหมดพัฒนา
630
+ if (!app.isPackaged) {
631
+ console.log(' Development mode: Skipping security check due to error');
632
+ return true;
633
+ }
634
+ dialog.showErrorBox('Fatal Error', `A critical error occurred during security check: ${error.message}`);
635
+ return false;
636
+ }
637
+ }
638
+
639
+ const isPackaged = app.isPackaged;
640
+
641
+ // เก็บ isDev ไว้เพื่อ backward compatibility
642
+ const isDev = isDevMode;
643
+
644
+ // Build Dashboard - เฉพาะโหมดพัฒนา (Removed - Use builder.html separately)
645
+
646
+ // ฟังก์ชันสำหรับหาตำแหน่ง node.exe และ npm-cli.js ที่ถูกต้อง (เวอร์ชันอัปเดต)
647
+ function getBundledNpmPaths() {
648
+ if (isPackaged) {
649
+ // เมื่อ Pack แอปแล้ว: ชี้ไปที่ไฟล์ที่เราฝังไว้ใน resources
650
+ const nodeDir = path.join(process.resourcesPath, 'node');
651
+ return {
652
+ nodePath: path.join(nodeDir, 'node.exe'),
653
+ npmCliPath: path.join(nodeDir, 'node_modules', 'npm', 'bin', 'npm-cli.js')
654
+ };
655
+ } else {
656
+ // ตอนพัฒนา: ใช้ npm ของเครื่องตามปกติ
657
+ return {
658
+ nodePath: 'node', // ใช้ node ของระบบ
659
+ npmCliPath: 'npm' // ใช้ npm ของระบบ (วิธีนี้จะเปลี่ยนไปเล็กน้อย)
660
+ };
661
+ }
662
+ }
663
+
664
+ let mainWindow;
665
+ // [CLEANED] Removed authentication window variables and functions
666
+ let splashWindow; // เพิ่มตัวแปรสำหรับ splash window
667
+ let debugWindow; // เพิ่มตัวแปรสำหรับ debug window
668
+
669
+ // --- CMD Logger สำหรับแสดงผล Log ใน CMD Window ---
670
+ const cmdLogger = {
671
+ info: (message, ...args) => {
672
+ // แสดงผลข้อความเป็นสีเขียวใน CMD
673
+ console.log('\x1b[32m%s\x1b[0m', `[INFO] ${message}`, ...args);
674
+ },
675
+ warn: (message, ...args) => {
676
+ // แสดงผลข้อความเป็นสีเหลือง
677
+ console.warn('\x1b[33m%s\x1b[0m', `[WARN] ${message}`, ...args);
678
+ },
679
+ error: (message, ...args) => {
680
+ // แสดงผลข้อความเป็นสีแดง
681
+ console.error('\x1b[31m%s\x1b[0m', `[ERROR] ${message}`, ...args);
682
+ },
683
+ debug: (message, ...args) => {
684
+ // แสดงผลเฉพาะใน Dev Mode
685
+ const isDevMode = process.argv.includes('--dev-mode') || process.argv.includes('--dev') || !app.isPackaged;
686
+ if (isDevMode) {
687
+ console.log('\x1b[36m%s\x1b[0m', `[DEBUG] ${message}`, ...args);
688
+ }
689
+ }
690
+ };
691
+
692
+ // Initialize Core Components - Simplified for ValidationGateway-centric architecture
693
+ const validationGateway = new ValidationGateway();
694
+
695
+ // ASAR-Safe Path Helper Functions
696
+ function getAppBasePath() {
697
+ if (app.isPackaged) {
698
+ // Production: ใช้ path ข้างนอก app.asar
699
+ return path.dirname(app.getPath('exe'));
700
+ } else {
701
+ // Development: ใช้ __dirname ปกติ
702
+ return __dirname;
703
+ }
704
+ }
705
+
706
+ function getUnpackedPath(relativePath) {
707
+ if (app.isPackaged) {
708
+ // Production: ไฟล์ที่ unpack อยู่ใน app.asar.unpacked
709
+ const appPath = app.getAppPath();
710
+ return path.join(path.dirname(appPath), 'app.asar.unpacked', relativePath);
711
+ } else {
712
+ // Development: ใช้ path ปกติ
713
+ return path.join(__dirname, relativePath);
714
+ }
715
+ }
716
+
717
+ function getResourcePath(relativePath) {
718
+ if (app.isPackaged) {
719
+ // Production: resources อยู่ใน app.asar (สำหรับไฟล์ที่ไม่ต้อง unpack)
720
+ return path.join(app.getAppPath(), relativePath);
721
+ } else {
722
+ // Development: ใช้ path ปกติ
723
+ return path.join(__dirname, relativePath);
724
+ }
725
+ }
726
+
727
+ // Create splash screen window first
728
+ function createSplashWindow() {
729
+ // เส้นทางไฟล์ที่ถูกต้องสำหรับ icon.png (extraFiles)
730
+ const iconPath = isPackaged ?
731
+ path.join(getAppBasePath(), 'icon.png') :
732
+ getResourcePath('icon.png');
733
+
734
+ // เส้นทางไฟล์ที่ถูกต้องสำหรับ splash.html (extraFiles)
735
+ const splashPath = isPackaged ?
736
+ path.join(getAppBasePath(), 'splash.html') :
737
+ path.join(__dirname, 'splash.html');
738
+
739
+ splashWindow = new BrowserWindow({
740
+ width: 600,
741
+ height: 500,
742
+ frame: false,
743
+ alwaysOnTop: true,
744
+ transparent: false,
745
+ resizable: false,
746
+ center: true,
747
+ webPreferences: {
748
+ nodeIntegration: false,
749
+ contextIsolation: true
750
+ },
751
+ icon: iconPath
752
+ });
753
+
754
+ splashWindow.loadFile(splashPath);
755
+
756
+ splashWindow.show();
757
+
758
+ console.log(' Splash screen created and shown');
759
+ console.log(` Icon path: ${iconPath}`);
760
+ console.log(` Splash path: ${splashPath}`);
761
+
762
+ // Close splash and create main window after loading completes
763
+ setTimeout(() => {
764
+ createMainWindow();
765
+ if (splashWindow && !splashWindow.isDestroyed()) {
766
+ splashWindow.close();
767
+ splashWindow = null;
768
+ console.log(' Splash closed, main window created');
769
+ }
770
+ }, 4000); // Slightly longer to match progress animation
771
+
772
+ return splashWindow;
773
+ }
774
+
775
+ function createMainWindow() {
776
+ // เส้นทางไฟล์ที่ถูกต้องสำหรับ icon.png (extraFiles)
777
+ const iconPath = isPackaged ?
778
+ path.join(getAppBasePath(), 'icon.png') :
779
+ getResourcePath('icon.png');
780
+
781
+ mainWindow = new BrowserWindow({
782
+ width: 1400,
783
+ height: 900,
784
+ minWidth: 800,
785
+ minHeight: 600,
786
+ title: 'Chahuadev Framework - Plugin Management System',
787
+ icon: iconPath,
788
+ autoHideMenuBar: true,
789
+ webPreferences: {
790
+ nodeIntegration: false,
791
+ contextIsolation: true,
792
+ enableRemoteModule: false,
793
+ preload: getResourcePath('preload.js'),
794
+ webSecurity: true,
795
+ sandbox: true,
796
+ webviewTag: true // เพิ่มบรรทัดนี้เพื่อเปิดใช้งาน <webview>
797
+ },
798
+ show: false
799
+ });
800
+
801
+ // Load the framework interface
802
+ mainWindow.loadFile('app.html');
803
+
804
+ console.log(` Main window icon path: ${iconPath}`);
805
+
806
+ // Show when ready
807
+ mainWindow.once('ready-to-show', () => {
808
+ mainWindow.show();
809
+ console.log(' Chahuadev Framework Desktop App ready!');
810
+
811
+
812
+ // เริ่มระบบป้องกันการดีบัก (Fort-Knox Level Security)
813
+ antiDebugging.start(mainWindow);
814
+ });
815
+
816
+ // Handle window closed
817
+ mainWindow.on('closed', () => {
818
+ mainWindow = null;
819
+ // หยุดระบบป้องกัน
820
+ antiDebugging.stop();
821
+ // Cleanup all plugins
822
+ cleanupAllPlugins();
823
+ });
824
+
825
+ // Development tools
826
+ if (process.env.NODE_ENV === 'development') {
827
+ mainWindow.webContents.openDevTools();
828
+ }
829
+ }
830
+
831
+ // Build Dashboard Functions - เฉพาะโหมดพัฒนา (Removed - Use builder.html separately)
832
+
833
+ // Create Developer Menu - เฉพาะโหมดพัฒนา
834
+ function createDeveloperMenu() {
835
+ if (!isDevMode) return; // เฉพาะโหมดพัฒนาเท่านั้น
836
+
837
+ const mainMenu = Menu.buildFromTemplate([
838
+ {
839
+ label: 'เครื่องมือนักพัฒนา',
840
+ submenu: [
841
+ { role: 'toggleDevTools', label: 'เปิด/ปิด DevTools' },
842
+ { role: 'reload', label: 'โหลดใหม่' },
843
+ { role: 'forceReload', label: 'บังคับโหลดใหม่' },
844
+ { type: 'separator' }
845
+ ]
846
+ },
847
+ {
848
+ label: 'มุมมอง',
849
+ submenu: [
850
+ { role: 'resetZoom', label: 'รีเซ็ตการซูม' },
851
+ { role: 'zoomIn', label: 'ซูมเข้า' },
852
+ { role: 'zoomOut', label: 'ซูมออก' },
853
+ { type: 'separator' },
854
+ { role: 'togglefullscreen', label: 'เปิด/ปิดเต็มจอ' }
855
+ ]
856
+ }
857
+ ]);
858
+
859
+ Menu.setApplicationMenu(mainMenu);
860
+ console.log(' Developer menu created');
861
+ }
862
+
863
+ // Cleanup All Plugins - Now handled by ValidationGateway
864
+ async function cleanupAllPlugins() {
865
+ console.log(' Cleaning up all plugins...');
866
+ try {
867
+ // ValidationGateway will handle plugin cleanup
868
+ console.log(' Plugin cleanup delegated to ValidationGateway');
869
+ } catch (error) {
870
+ console.error(' Plugin cleanup failed:', error.message);
871
+ }
872
+ }
873
+
874
+ // ระบบ��รวจสอบ Runtime Integrity เป็นระยะๆ
875
+ let runtimeIntegrityInterval = null;
876
+ let integrityCheckCount = 0;
877
+ const MAX_INTEGRITY_CHECKS = 10; // จำกัดจำนวนครั้งเพื่อไม่ให้กินทรัพยากรมากเกินไป
878
+
879
+ function startRuntimeIntegrityChecks() {
880
+ // ข้ามในโหมดพัฒนา
881
+ if (!app.isPackaged || process.argv.includes('--dev-mode')) {
882
+ console.log(' Development mode: Skipping runtime integrity checks');
883
+ return;
884
+ }
885
+
886
+ console.log(' Starting periodic runtime integrity checks...');
887
+
888
+ runtimeIntegrityInterval = setInterval(() => {
889
+ integrityCheckCount++;
890
+
891
+ if (integrityCheckCount > MAX_INTEGRITY_CHECKS) {
892
+ console.log(' Runtime integrity check limit reached, stopping periodic checks');
893
+ stopRuntimeIntegrityChecks();
894
+ return;
895
+ }
896
+
897
+ console.log(` Runtime integrity check #${integrityCheckCount}...`);
898
+
899
+ try {
900
+ // ตรวจสอบไฟล์สำคัญ
901
+ const criticalFiles = [
902
+ 'main.js',
903
+ 'preload.js',
904
+ 'package.json'
905
+ ];
906
+
907
+ const storedChecksumsPath = path.join(__dirname, 'checksums.json');
908
+ if (!fs.existsSync(storedChecksumsPath)) {
909
+ console.log(' Checksums file not found for runtime check');
910
+ return;
911
+ }
912
+
913
+ const storedChecksums = JSON.parse(fs.readFileSync(storedChecksumsPath, 'utf8'));
914
+
915
+ for (const fileName of criticalFiles) {
916
+ if (!storedChecksums[fileName]) continue;
917
+
918
+ const filePath = path.join(__dirname, fileName);
919
+ if (!fs.existsSync(filePath)) continue;
920
+
921
+ const fileContent = fs.readFileSync(filePath);
922
+ const currentHash = crypto.createHash('sha256').update(fileContent).digest('hex');
923
+
924
+ if (currentHash !== storedChecksums[fileName]) {
925
+ console.error(` RUNTIME TAMPERING DETECTED: ${fileName}`);
926
+ handleRuntimeTampering(fileName);
927
+ return;
928
+ }
929
+ }
930
+
931
+ console.log(` Runtime integrity check #${integrityCheckCount} passed`);
932
+
933
+ } catch (error) {
934
+ console.warn(` Runtime integrity check #${integrityCheckCount} failed:`, error.message);
935
+ }
936
+
937
+ }, 30000); // ตรวจสอบทุก 30 วินาที
938
+ }
939
+
940
+ function stopRuntimeIntegrityChecks() {
941
+ if (runtimeIntegrityInterval) {
942
+ clearInterval(runtimeIntegrityInterval);
943
+ runtimeIntegrityInterval = null;
944
+ console.log(' Runtime integrity checks stopped');
945
+ }
946
+ }
947
+
948
+ function handleRuntimeTampering(fileName) {
949
+ console.error(` CRITICAL SECURITY ALERT: Runtime tampering detected in ${fileName}`);
950
+
951
+ // แสดงแจ้งเตือนและปิดโปรแกรม
952
+ dialog.showErrorBox(
953
+ 'Security Alert',
954
+ `Runtime tampering detected in ${fileName}. The application will now exit for security reasons.`
955
+ );
956
+
957
+ // ล็อกเหตุการณ์
958
+ const logEntry = {
959
+ timestamp: new Date().toISOString(),
960
+ event: 'RUNTIME_TAMPERING_DETECTED',
961
+ file: fileName,
962
+ checkNumber: integrityCheckCount
963
+ };
964
+
965
+ try {
966
+ const securityLogPath = path.join(app.getPath('userData'), 'security-events.log');
967
+ fs.appendFileSync(securityLogPath, JSON.stringify(logEntry) + '\n');
968
+ } catch (error) {
969
+ console.error('Failed to log security event:', error);
970
+ }
971
+
972
+ // ปิดโปรแกรมทันที
973
+ app.quit();
974
+ }
975
+
976
+ // เพิ่มฟังก์ชันตรวจสอบการเปลี่ยนแปลงในหน่วยความจำ (Memory Protection)
977
+ function enableMemoryProtection() {
978
+ // ข้ามในโหมดพัฒนา
979
+ if (!app.isPackaged || process.argv.includes('--dev-mode')) {
980
+ return;
981
+ }
982
+
983
+ console.log(' Enabling memory protection...');
984
+
985
+ // ตรวจสอบการเปลี่ยนแปลง critical functions
986
+ const originalFunctions = {
987
+ require: typeof global.require === 'function' ? global.require.toString() : '',
988
+ eval: typeof global.eval === 'function' ? global.eval.toString() : '',
989
+ Function: typeof global.Function === 'function' ? global.Function.toString() : ''
990
+ };
991
+
992
+ setInterval(() => {
993
+ try {
994
+ // ตรวจสอบว่า critical functions ถูกแก้ไขหรือไม่
995
+ const currentRequire = typeof global.require === 'function' ? global.require.toString() : '';
996
+ const currentEval = typeof global.eval === 'function' ? global.eval.toString() : '';
997
+ const currentFunction = typeof global.Function === 'function' ? global.Function.toString() : '';
998
+
999
+ if (originalFunctions.require && currentRequire !== originalFunctions.require ||
1000
+ originalFunctions.eval && currentEval !== originalFunctions.eval ||
1001
+ originalFunctions.Function && currentFunction !== originalFunctions.Function) {
1002
+
1003
+ console.error(' MEMORY TAMPERING DETECTED: Critical functions modified');
1004
+ handleRuntimeTampering('critical-functions');
1005
+ }
1006
+ } catch (error) {
1007
+ console.warn('Memory protection check failed:', error.message);
1008
+ }
1009
+ }, 60000); // ตรวจสอบทุก 1 นาที
1010
+ }
1011
+
1012
+ // Supply Chain Security - ตรวจสอบ Dependencies
1013
+ async function checkSupplyChainSecurity() {
1014
+ // ข้ามในโหมดพัฒนา
1015
+ if (!app.isPackaged || process.argv.includes('--dev-mode')) {
1016
+ console.log(' Development mode: Skipping supply chain security check');
1017
+ return true;
1018
+ }
1019
+
1020
+ console.log(' Checking supply chain security...');
1021
+
1022
+ try {
1023
+ const packageJsonPath = path.join(__dirname, 'package.json');
1024
+ const packageLockPath = path.join(__dirname, 'package-lock.json');
1025
+
1026
+ if (!fs.existsSync(packageJsonPath) || !fs.existsSync(packageLockPath)) {
1027
+ console.log(' Package files not found for supply chain check');
1028
+ return true;
1029
+ }
1030
+
1031
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
1032
+ const packageLock = JSON.parse(fs.readFileSync(packageLockPath, 'utf8'));
1033
+
1034
+ // ตรวจสอบ Critical Dependencies
1035
+ const criticalDependencies = [
1036
+ 'electron', 'express',
1037
+ 'crypto', 'fs-extra', 'archiver'
1038
+ ];
1039
+
1040
+ for (const dep of criticalDependencies) {
1041
+ if (packageJson.dependencies[dep]) {
1042
+ const installedVersion = packageLock.packages[`node_modules/${dep}`]?.version;
1043
+ if (!installedVersion) {
1044
+ console.warn(` Critical dependency ${dep} not found in package-lock.json`);
1045
+ continue;
1046
+ }
1047
+
1048
+ // ตรวจสอบ known vulnerabilities (simplified check)
1049
+ if (await checkKnownVulnerabilities(dep, installedVersion)) {
1050
+ console.error(` Known vulnerability detected in ${dep}@${installedVersion}`);
1051
+ return false;
1052
+ }
1053
+ }
1054
+ }
1055
+
1056
+ // ตรวจสอบ Package Integrity
1057
+ const lockFileHash = crypto.createHash('sha256')
1058
+ .update(fs.readFileSync(packageLockPath))
1059
+ .digest('hex');
1060
+
1061
+ const expectedLockHashPath = path.join(__dirname, 'package-lock.hash');
1062
+ if (fs.existsSync(expectedLockHashPath)) {
1063
+ const expectedHash = fs.readFileSync(expectedLockHashPath, 'utf8').trim();
1064
+ if (lockFileHash !== expectedHash) {
1065
+ console.error(' Package-lock.json integrity check failed');
1066
+ return false;
1067
+ }
1068
+ } else {
1069
+ // สร้าง hash file สำหรับครั้งแรก
1070
+ fs.writeFileSync(expectedLockHashPath, lockFileHash);
1071
+ console.log(' Created package-lock.hash for future integrity checks');
1072
+ }
1073
+
1074
+ console.log(' Supply chain security check passed');
1075
+ return true;
1076
+
1077
+ } catch (error) {
1078
+ console.error(' Supply chain security check failed:', error.message);
1079
+ return false;
1080
+ }
1081
+ }
1082
+
1083
+ // ตรวจสอบ known vulnerabilities (simplified implementation)
1084
+ async function checkKnownVulnerabilities(packageName, version) {
1085
+ // รายการ packages ที่มี known issues (อัปเดตตามความเป็นจริง)
1086
+ const knownVulnerablePackages = {
1087
+ 'electron': {
1088
+ '<28.0.0': 'CVE-2023-xxxxx'
1089
+ },
1090
+ 'express': {
1091
+ '<4.18.0': 'CVE-2022-xxxxx'
1092
+ }
1093
+ // เพิ่มรายการตามความจำเป็น
1094
+ };
1095
+
1096
+ const vulnInfo = knownVulnerablePackages[packageName];
1097
+ if (!vulnInfo) return false;
1098
+
1099
+ // ตรวจสอบเวอร์ชันที่มีปัญหา (simplified version comparison)
1100
+ for (const [vulnerableVersion, cve] of Object.entries(vulnInfo)) {
1101
+ if (vulnerableVersion.startsWith('<')) {
1102
+ const targetVersion = vulnerableVersion.slice(1);
1103
+ if (compareVersions(version, targetVersion) < 0) {
1104
+ console.error(` ${packageName}@${version} has ${cve}`);
1105
+ return true;
1106
+ }
1107
+ }
1108
+ }
1109
+
1110
+ return false;
1111
+ }
1112
+
1113
+ // เปรียบเทียบเวอร์ชัน (simplified)
1114
+ function compareVersions(version1, version2) {
1115
+ const v1parts = version1.split('.').map(Number);
1116
+ const v2parts = version2.split('.').map(Number);
1117
+
1118
+ for (let i = 0; i < Math.max(v1parts.length, v2parts.length); i++) {
1119
+ const v1part = v1parts[i] || 0;
1120
+ const v2part = v2parts[i] || 0;
1121
+
1122
+ if (v1part < v2part) return -1;
1123
+ if (v1part > v2part) return 1;
1124
+ }
1125
+
1126
+ return 0;
1127
+ }
1128
+
1129
+ // App event handlers
1130
+ app.whenReady().then(async () => {
1131
+ console.log(' Electron app ready, performing security checks...');
1132
+
1133
+ // ขั้นตอนที่ 1: ตรวจสอบ Digital Signature และ Integrity ก่อน
1134
+ const integrityOk = checkAppIntegrity();
1135
+ if (!integrityOk) {
1136
+ console.log(' App integrity check failed. Shutting down.');
1137
+ app.quit();
1138
+ return;
1139
+ }
1140
+
1141
+ // ขั้นตอนที่ 2: ตรวจสอบ Supply Chain Security
1142
+ const supplyChainOk = await checkSupplyChainSecurity();
1143
+ if (!supplyChainOk) {
1144
+ console.log(' Supply chain security check failed. Shutting down.');
1145
+ dialog.showErrorBox('Security Alert', 'Supply chain security check failed. Please contact support.');
1146
+ app.quit();
1147
+ return;
1148
+ }
1149
+
1150
+ // เริ่มระบบตรวจสอบ Runtime Integrity
1151
+ startRuntimeIntegrityChecks();
1152
+
1153
+ // เปิดใช้งาน Memory Protection
1154
+ enableMemoryProtection();
1155
+
1156
+ // เพิ่ม: เริ่มการทำงานของระบบดีบั๊กเฉพาะใน Dev Mode (ปิดชั่วคราว)
1157
+ if (isDevMode && false) { // ปิดชั่วคราวเพื่อแก้ปัญหาการค้าง
1158
+ try {
1159
+ ApiTraceDebugger.start();
1160
+ console.log('[API TRACE] ระบบติดตาม API เริ่มทำงานแล้ว (Real-time Logging)');
1161
+ } catch (error) {
1162
+ console.error('[API TRACE] ไม่สามารถเริ่มระบบติดตาม API ได้:', error.message);
1163
+ }
1164
+ } else if (isDevMode) {
1165
+ console.log('[API TRACE] ระบบติดตาม API ถูกปิดชั่วคราว (กำลังแก้ไขปัญหา)');
1166
+ }
1167
+
1168
+ // ขั้นตอนที่ 3: Initialize Plugins via Gateway
1169
+ try {
1170
+ await validationGateway.initializePlugins();
1171
+ console.log(' Plugins initialized via Gateway');
1172
+ } catch (error) {
1173
+ console.warn(' Plugin initialization skipped:', error.message);
1174
+ }
1175
+
1176
+ // Auto-scan projects on startup
1177
+ try {
1178
+ await handleScanProjects();
1179
+ console.log(' Auto project scan completed');
1180
+ } catch (error) {
1181
+ console.warn(' Auto project scan failed:', error.message);
1182
+ }
1183
+
1184
+ // Create UI
1185
+ createSplashWindow();
1186
+
1187
+ // แก้ไขตรงนี้: เรียกใช้ createDeveloperMenu() เฉพาะใน Dev Mode
1188
+ if (isDevMode) {
1189
+ createDeveloperMenu();
1190
+ } else {
1191
+ // ในโหมดผู้ใช้ ให้ตั้งค่าเมนูเป็น null เพื่อลบเมนูทั้งหมด
1192
+ Menu.setApplicationMenu(null);
1193
+ }
1194
+
1195
+ app.on('activate', () => {
1196
+ if (BrowserWindow.getAllWindows().length === 0) {
1197
+ createSplashWindow();
1198
+ }
1199
+ });
1200
+ });
1201
+
1202
+ app.on('window-all-closed', () => {
1203
+ if (process.platform !== 'darwin') {
1204
+ app.quit();
1205
+ }
1206
+ });
1207
+
1208
+ app.on('before-quit', async () => {
1209
+ console.log(' App shutting down...');
1210
+ if (isDevMode) {
1211
+ ApiTraceDebugger.stop();
1212
+ }
1213
+ await cleanupAllPlugins();
1214
+ stopRuntimeIntegrityChecks();
1215
+ });
1216
+
1217
+ // IPC handlers for desktop app functionality
1218
+ ipcMain.handle('get-app-version', () => {
1219
+ return app.getVersion();
1220
+ });
1221
+
1222
+ // ========== OFFLINE DEMO AUTH IPC HANDLERS ==========
1223
+
1224
+ // สร้าง OfflineAuthClient instance (แทนที่ DeviceAuthClient)
1225
+ let offlineAuthClient = null;
1226
+
1227
+ /**
1228
+ * Initialize Offline Auth Client
1229
+ */
1230
+ function getOfflineAuthClient() {
1231
+ if (!offlineAuthClient) {
1232
+ offlineAuthClient = new OfflineAuthClient();
1233
+ }
1234
+ return offlineAuthClient;
1235
+ }
1236
+
1237
+ /**
1238
+ * IPC Handler: เริ่มต้น Offline Auth (Dashboard)
1239
+ */
1240
+ ipcMain.handle('auth:start-device-flow', async () => {
1241
+ try {
1242
+ console.log(' [OFFLINE AUTH] Initializing demo auth screen...');
1243
+ const client = getOfflineAuthClient();
1244
+ const result = await client.startDeviceFlow();
1245
+
1246
+ return {
1247
+ success: true,
1248
+ data: result
1249
+ };
1250
+ } catch (error) {
1251
+ console.error(' [OFFLINE AUTH] Failed to initialize:', error);
1252
+ return {
1253
+ success: false,
1254
+ error: error.message
1255
+ };
1256
+ }
1257
+ });
1258
+
1259
+ /**
1260
+ * IPC Handler: Offline Authentication (ล็อคอินแบบออฟไลน์)
1261
+ */
1262
+ ipcMain.handle('auth:offline-login', async (event, { username, password }) => {
1263
+ try {
1264
+ if (!username || !password) {
1265
+ throw new Error('ชื่อผู้ใช้และรหัสผ่านจำเป็น');
1266
+ }
1267
+
1268
+ const client = getOfflineAuthClient();
1269
+ const result = await client.authenticateOffline(username, password);
1270
+
1271
+ if (result.success && result.data) {
1272
+ console.log(' [OFFLINE AUTH] User authenticated successfully');
1273
+
1274
+ // Inject tokens to webview
1275
+ try {
1276
+ await injectTokensToWebview(result.data);
1277
+ console.log(' [OFFLINE AUTH] Tokens injected to webviews');
1278
+ } catch (injectError) {
1279
+ console.warn(' [OFFLINE AUTH] Token injection failed:', injectError.message);
1280
+ }
1281
+ }
1282
+
1283
+ return result;
1284
+ } catch (error) {
1285
+ console.error(' [OFFLINE AUTH] Login failed:', error);
1286
+ return {
1287
+ success: false,
1288
+ error: error.message
1289
+ };
1290
+ }
1291
+ });
1292
+
1293
+ /**
1294
+ * IPC Handler: Polling Device Status (รอ user approve) - Offline Mode
1295
+ */
1296
+ ipcMain.handle('auth:poll-device', async (event, deviceCode) => {
1297
+ try {
1298
+ if (!deviceCode) {
1299
+ throw new Error('Device code is required');
1300
+ }
1301
+
1302
+ const client = getOfflineAuthClient();
1303
+ const result = await client.pollDeviceStatus(deviceCode);
1304
+
1305
+ return {
1306
+ success: true,
1307
+ data: result
1308
+ };
1309
+ } catch (error) {
1310
+ console.error(' [OFFLINE AUTH] Failed to poll device status:', error);
1311
+ return {
1312
+ success: false,
1313
+ error: error.message
1314
+ };
1315
+ }
1316
+ });
1317
+
1318
+ /**
1319
+ * IPC Handler: ดึงข้อมูล User ปัจจุบัน
1320
+ */
1321
+ ipcMain.handle('auth:get-current-user', async () => {
1322
+ try {
1323
+ const client = getOfflineAuthClient();
1324
+ const tokenData = await client.loadTokens();
1325
+
1326
+ if (tokenData.success) {
1327
+ return {
1328
+ success: true,
1329
+ data: tokenData.data.user,
1330
+ authenticated: true
1331
+ };
1332
+ } else {
1333
+ return {
1334
+ success: true,
1335
+ data: null,
1336
+ authenticated: false,
1337
+ error: tokenData.error
1338
+ };
1339
+ }
1340
+ } catch (error) {
1341
+ console.error(' [OFFLINE AUTH] Failed to get current user:', error);
1342
+ return {
1343
+ success: false,
1344
+ error: error.message,
1345
+ authenticated: false
1346
+ };
1347
+ }
1348
+ });
1349
+
1350
+ /**
1351
+ * IPC Handler: Logout (ลบ tokens)
1352
+ */
1353
+ ipcMain.handle('auth:logout', async () => {
1354
+ try {
1355
+ console.log(' [OFFLINE AUTH] Logging out...');
1356
+ const client = getOfflineAuthClient();
1357
+ await client.removeTokens();
1358
+
1359
+ return {
1360
+ success: true,
1361
+ message: 'Logged out successfully'
1362
+ };
1363
+ } catch (error) {
1364
+ console.error(' [OFFLINE AUTH] Failed to logout:', error);
1365
+ return {
1366
+ success: false,
1367
+ error: error.message
1368
+ };
1369
+ }
1370
+ });
1371
+
1372
+ /**
1373
+ * IPC Handler: ตรวจสอบสถานะ Authentication
1374
+ */
1375
+ ipcMain.handle('auth:check-status', async () => {
1376
+ try {
1377
+ const client = getOfflineAuthClient();
1378
+ const tokenData = await client.loadTokens();
1379
+
1380
+ return {
1381
+ success: true,
1382
+ authenticated: tokenData.success,
1383
+ user: tokenData.success ? tokenData.data.user : null,
1384
+ tokenExists: tokenData.success,
1385
+ error: tokenData.success ? null : tokenData.error
1386
+ };
1387
+ } catch (error) {
1388
+ console.error(' [OFFLINE AUTH] Failed to check auth status:', error);
1389
+ return {
1390
+ success: false,
1391
+ authenticated: false,
1392
+ error: error.message
1393
+ };
1394
+ }
1395
+ });
1396
+
1397
+ /**
1398
+ * Inject authentication tokens to webview
1399
+ * @param {Object} tokens - Token data to inject
1400
+ */
1401
+ async function injectTokensToWebview(tokens) {
1402
+ console.log(' [Webview] Injecting tokens to active webviews');
1403
+
1404
+ try {
1405
+ if (!mainWindow || !mainWindow.webContents) {
1406
+ throw new Error('Main window not available');
1407
+ }
1408
+
1409
+ // Send tokens to all webviews through the main window
1410
+ mainWindow.webContents.send('auth:inject-to-webviews', tokens);
1411
+
1412
+ console.log(' [Webview] Tokens sent to webviews');
1413
+ return { success: true };
1414
+ } catch (error) {
1415
+ console.error(' [Webview] Token injection failed:', error);
1416
+ throw error;
1417
+ }
1418
+ }
1419
+
1420
+ // [CLEANED] Removed old authentication IPC handlers - replaced with new Device Flow handlers above
1421
+
1422
+ ipcMain.handle('webview:inject-tokens', async (event, { webviewId, tokens }) => {
1423
+ console.log(`[WEBVIEW] Injecting tokens to webview ${webviewId}...`);
1424
+ try {
1425
+ await injectTokensToWebview(tokens);
1426
+ return { success: true };
1427
+ } catch (error) {
1428
+ return { success: false, error: error.message };
1429
+ }
1430
+ });
1431
+
1432
+ // Handle webview request for auth tokens
1433
+ ipcMain.handle('webview:request-auth-tokens', async (event) => {
1434
+ console.log(' [Webview] Webview requesting auth tokens');
1435
+ try {
1436
+ const client = getDeviceAuthClient();
1437
+ const tokenData = await client.loadTokens();
1438
+
1439
+ if (tokenData.success) {
1440
+ // Send tokens back to the requesting webview
1441
+ event.sender.send('auth:inject-tokens', tokenData.data);
1442
+ console.log(' [Webview] Tokens sent to requesting webview');
1443
+ return { success: true };
1444
+ } else {
1445
+ console.log(' [Webview] No valid tokens found');
1446
+ return { success: false, error: 'No authentication tokens found' };
1447
+ }
1448
+ } catch (error) {
1449
+ console.error(' [Webview] Failed to retrieve tokens:', error);
1450
+ return { success: false, error: error.message };
1451
+ }
1452
+ });
1453
+
1454
+ ipcMain.handle('show-message-box', async (event, options) => {
1455
+ const { dialog } = require('electron');
1456
+ return await dialog.showMessageBox(mainWindow, options);
1457
+ });
1458
+
1459
+ ipcMain.handle('open-external', async (event, url) => {
1460
+ if (!url || typeof url !== 'string') {
1461
+ console.warn('Invalid URL provided to open-external:', url);
1462
+ return false;
1463
+ }
1464
+
1465
+ try {
1466
+ console.log('Opening external URL:', url);
1467
+ await shell.openExternal(url);
1468
+ return true;
1469
+ } catch (error) {
1470
+ console.error('Failed to open external URL:', error);
1471
+ return false;
1472
+ }
1473
+ });
1474
+
1475
+ const API_BASE_URL = 'https://chahuadev.com';
1476
+
1477
+ // [เพิ่มใหม่] IPC Handler สำหรับส่ง Path ของ preload-webview.js
1478
+ ipcMain.handle('get-preload-webview-path', () => {
1479
+ try {
1480
+ const preloadPath = path.join(__dirname, 'preload-webview.js');
1481
+ console.log(`[IPC] Providing webview preload path: ${preloadPath}`);
1482
+ return preloadPath;
1483
+ } catch (error) {
1484
+ console.error(' Error getting webview preload path:', error);
1485
+ return null;
1486
+ }
1487
+ });
1488
+
1489
+ ipcMain.handle('get-preload-path', () => {
1490
+ try {
1491
+ const preloadPath = path.join(__dirname, 'preload-webview.js');
1492
+ console.log(`[IPC] Providing preload path: ${preloadPath}`);
1493
+ return preloadPath;
1494
+ } catch (error) {
1495
+ console.error(' Error getting preload path:', error);
1496
+ return null;
1497
+ }
1498
+ });
1499
+
1500
+ ipcMain.handle('get-system-info', async () => {
1501
+ const os = require('os');
1502
+ return {
1503
+ platform: os.platform(),
1504
+ arch: os.arch(),
1505
+ release: os.release(),
1506
+ hostname: os.hostname(),
1507
+ userInfo: os.userInfo(),
1508
+ cpus: os.cpus().length,
1509
+ totalMemory: os.totalmem(),
1510
+ freeMemory: os.freemem()
1511
+ };
1512
+ });
1513
+
1514
+ // --- WebView Action Handler ---
1515
+ ipcMain.handle('handle-webview-action', async (event, message) => {
1516
+ console.log(`[Main] Received action from WebView: ${message.action}`);
1517
+
1518
+ if (message.action === 'install-plugin') {
1519
+ const pluginData = message.payload;
1520
+ console.log(`[Main] Starting Framework installation for:`, pluginData);
1521
+
1522
+ try {
1523
+ const pluginId = pluginData.id || pluginData.pluginId || pluginData.name;
1524
+ console.log(`[Main] Installing Framework with NPM for plugin: ${pluginId}`);
1525
+
1526
+ // ติดตั้ง Framework ผ่าน NPM
1527
+ const { execSync } = require('child_process');
1528
+
1529
+ console.log(`[Framework Install] Running: npm install -g @chahuadev/framework`);
1530
+
1531
+ // รัน npm install command
1532
+ const result = execSync('npm install -g @chahuadev/framework', {
1533
+ encoding: 'utf8',
1534
+ stdio: 'pipe'
1535
+ });
1536
+
1537
+ console.log(` [Framework Install] NPM Output:`, result);
1538
+ console.log(` [Framework Install] Framework installed successfully`);
1539
+
1540
+ // แจ้งให้ UI ทราบผลลัพธ์
1541
+ if (mainWindow && mainWindow.webContents) {
1542
+ mainWindow.webContents.send('show-notification', ` ติดตั้ง Chahua Framework สำเร็จ`);
1543
+ mainWindow.webContents.send('refresh-plugins');
1544
+ }
1545
+
1546
+ return { success: true, installMethod: 'npm' };
1547
+
1548
+ } catch (error) {
1549
+ console.error('[Main] Framework installation error:', error);
1550
+
1551
+ // แจ้งข้อผิดพลาดให้ UI
1552
+ if (mainWindow && mainWindow.webContents) {
1553
+ mainWindow.webContents.send('show-notification', ` เกิดข้อผิดพลาดในการติดตั้ง Framework: ${error.message}`);
1554
+ }
1555
+
1556
+ return { success: false, error: error.message };
1557
+ }
1558
+ }
1559
+
1560
+ return { success: false, error: 'Unknown action' };
1561
+ });
1562
+
1563
+ // SECURE NPM COMMAND EXECUTION - ผ่าน ValidationGateway
1564
+ ipcMain.handle('execute-npm-command', async (event, command) => {
1565
+ try {
1566
+ console.log(`[Main] NPM Command Request: ${command}`);
1567
+
1568
+ // ส่งคำขอไปยัง ValidationGateway เพื่อตรวจสอบความปลอดภัย
1569
+ const result = await validationGateway.processCommand({
1570
+ action: 'execute-npm-command',
1571
+ command: command,
1572
+ userAgent: 'Electron-App',
1573
+ timestamp: new Date().toISOString()
1574
+ });
1575
+
1576
+ // แจ้งผลลัพธ์ให้ UI
1577
+ if (mainWindow && mainWindow.webContents) {
1578
+ if (result.success) {
1579
+ // ดึงชื่อแอปจากคำสั่งเพื่อแสดงใน notification
1580
+ const appMatch = command.match(/@chahuadev\/([\w-]+)/);
1581
+ const appName = appMatch ? appMatch[1] : 'Chahua App';
1582
+ const actionMatch = command.match(/^npm\s+(install|update|uninstall)/);
1583
+ const action = actionMatch ? actionMatch[1] : 'process';
1584
+
1585
+ let message = ' ดำเนินการสำเร็จ';
1586
+ if (action === 'install') message = ` ติดตั้ง ${appName} สำเร็จ`;
1587
+ else if (action === 'update') message = ` อัปเดต ${appName} สำเร็จ`;
1588
+ else if (action === 'uninstall') message = ` ถอนการติดตั้ง ${appName} สำเร็จ`;
1589
+
1590
+ mainWindow.webContents.send('show-notification', message);
1591
+ } else {
1592
+ mainWindow.webContents.send('show-notification', ` เกิดข้อผิดพลาด: ${result.error}`);
1593
+ }
1594
+ }
1595
+
1596
+ return result;
1597
+
1598
+ } catch (error) {
1599
+ console.error(`[Main] NPM Command Handler Failed:`, error.message);
1600
+
1601
+ // แจ้งข้อผิดพลาดให้ UI
1602
+ if (mainWindow && mainWindow.webContents) {
1603
+ mainWindow.webContents.send('show-notification', ` เกิดข้อผิดพลาดภายใน: ${error.message}`);
1604
+ }
1605
+
1606
+ return {
1607
+ success: false,
1608
+ error: error.message,
1609
+ command: command,
1610
+ securityLevel: 'SYSTEM_ERROR'
1611
+ };
1612
+ }
1613
+ });
1614
+
1615
+ // IPC Handler: Run Manifest Generator (Production-Safe)
1616
+ ipcMain.handle('run-manifest-generator', async () => {
1617
+ try {
1618
+ console.log(' [IPC] Running manifest generator function directly...');
1619
+
1620
+ // 1. คำนวณ Path ของโฟลเดอร์ plugins ที่ถูกต้อง - FIX: ใช้ app.isPackaged
1621
+ let pluginsDir;
1622
+ if (app.isPackaged) {
1623
+ pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins');
1624
+ } else {
1625
+ pluginsDir = path.join(app.getPath('userData'), 'plugins');
1626
+ }
1627
+
1628
+ // ตรวจสอบและสร้างโฟลเดอร์หากยังไม่มี
1629
+ if (!fs.existsSync(pluginsDir)) {
1630
+ fs.mkdirSync(pluginsDir, { recursive: true });
1631
+ }
1632
+
1633
+ console.log(` [IPC] Using plugins directory: ${pluginsDir}`);
1634
+
1635
+ // 2. ส่ง Path ที่ถูกต้องเข้าไปในฟังก์ชัน
1636
+ await generateManifests(pluginsDir);
1637
+
1638
+ // 3. สั่งให้ ValidationGateway โหลดปลั๊กอินใหม่!
1639
+ try {
1640
+ await validationGateway.initializePlugins(); // สั่งให้ Gateway โหลดปลั๊กอินใหม่!
1641
+ console.log(' Plugins reloaded via Gateway');
1642
+ } catch (error) {
1643
+ console.warn(' Plugin reload skipped:', error.message);
1644
+ }
1645
+
1646
+ console.log(' Manifest generation and plugin reload completed.');
1647
+ return {
1648
+ success: true,
1649
+ output: `Manifest generation completed successfully in:\n${pluginsDir}`,
1650
+ message: 'Manifests generated successfully and plugin list reloaded.'
1651
+ };
1652
+
1653
+ } catch (error) {
1654
+ console.error(` Manifest generator failed during direct call: ${error.message}`);
1655
+ return { success: false, error: error.message };
1656
+ }
1657
+ });
1658
+
1659
+ // IPC Handler: System Check for In-App Diagnostics
1660
+ ipcMain.handle('run-system-check', async () => {
1661
+ try {
1662
+ console.log(' [IPC] Running system check and auto-repair...');
1663
+
1664
+ // คำนวณ Path ของโฟลเดอร์ plugins
1665
+ let pluginsDir;
1666
+ if (app.isPackaged) {
1667
+ pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins');
1668
+ } else {
1669
+ pluginsDir = path.join(app.getPath('userData'), 'plugins');
1670
+ }
1671
+
1672
+ // ใช้ Project Inspector เพื่อวิเคราะห์ปลั๊กอิน
1673
+ const projectInspector = require('./utils/project-inspector');
1674
+ const analysis = await projectInspector.analyzeProject(pluginsDir);
1675
+
1676
+ let repairResults = [];
1677
+
1678
+ // การซ่อมแซมอัตโนมัติ
1679
+ if (analysis.totalIssues > 0) {
1680
+ console.log(` Found ${analysis.totalIssues} issues, attempting auto-repair...`);
1681
+
1682
+ // ลองซ่อมแซมด้วยการสร้าง manifest ใหม่
1683
+ try {
1684
+ await generateManifests(pluginsDir);
1685
+ repairResults.push('Generated missing manifest files');
1686
+ } catch (error) {
1687
+ console.warn(' Auto-repair failed:', error.message);
1688
+ }
1689
+
1690
+ // ลองรีโหลดปลั๊กอิน
1691
+ try {
1692
+ await validationGateway.initializePlugins();
1693
+ repairResults.push('Reloaded plugin registry');
1694
+ } catch (error) {
1695
+ console.warn(' Plugin reload failed:', error.message);
1696
+ }
1697
+ }
1698
+
1699
+ const message = analysis.totalIssues === 0
1700
+ ? 'ไม่พบปัญหาในระบบ ทุกอย่างทำงานปกติ'
1701
+ : `พบปัญหา ${analysis.totalIssues} รายการ - ระบบได้ทำการซ่อมแซมแล้ว`;
1702
+
1703
+ console.log(' System check completed successfully');
1704
+ return {
1705
+ success: true,
1706
+ message: message,
1707
+ fixed: repairResults.length > 0,
1708
+ repairActions: repairResults,
1709
+ analysis: analysis
1710
+ };
1711
+
1712
+ } catch (error) {
1713
+ console.error(` System check failed: ${error.message}`);
1714
+ return { success: false, error: error.message };
1715
+ }
1716
+ });
1717
+
1718
+ // IPC Handler: Parameterized System Check
1719
+ ipcMain.handle('run-parameterized-system-check', async (event, params) => {
1720
+ try {
1721
+ console.log(' [IPC] Running parameterized system check...', params);
1722
+
1723
+ const { scope, plugins } = params;
1724
+
1725
+ // คำนวณ Path ของโฟลเดอร์ plugins
1726
+ let pluginsDir;
1727
+ if (app.isPackaged) {
1728
+ pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins');
1729
+ } else {
1730
+ pluginsDir = path.join(app.getPath('userData'), 'plugins');
1731
+ }
1732
+
1733
+ let analysisResult;
1734
+ let repairResults = [];
1735
+ let recommendations = [];
1736
+
1737
+ switch (scope) {
1738
+ case 'all':
1739
+ // วิเคราะห์ทั้งระบบ (เหมือนเดิม)
1740
+ const projectInspector = require('./utils/project-inspector');
1741
+ analysisResult = await projectInspector.analyzeProject(pluginsDir);
1742
+
1743
+ if (analysisResult.totalIssues > 0) {
1744
+ // ซ่อมแซมอัตโนมัติ
1745
+ try {
1746
+ await generateManifests(pluginsDir);
1747
+ repairResults.push('Generated missing manifest files');
1748
+ } catch (error) {
1749
+ console.warn(' Auto-repair failed:', error.message);
1750
+ }
1751
+ }
1752
+ break;
1753
+
1754
+ case 'plugins':
1755
+ // วิเคราะห์เฉพาะปลั๊กอิน
1756
+ const projectInspector2 = require('./utils/project-inspector');
1757
+ analysisResult = await projectInspector2.analyzeProject(pluginsDir);
1758
+
1759
+ // เน้นที่ข้อมูล type analysis
1760
+ if (analysisResult.typeAnalysis) {
1761
+ recommendations.push(...analysisResult.typeAnalysis.recommendations);
1762
+ }
1763
+ break;
1764
+
1765
+ case 'core':
1766
+ // วิเคราะห์เฉพาะระบบหลัก
1767
+ analysisResult = {
1768
+ totalIssues: 0,
1769
+ message: 'ตรวจสอบระบบหลักเสร็จสิ้น - ไม่พบปัญหา'
1770
+ };
1771
+ break;
1772
+
1773
+ case 'dependencies':
1774
+ // วิเคราะห์ dependencies
1775
+ analysisResult = await analyzeDependencies(pluginsDir);
1776
+ break;
1777
+
1778
+ case 'specific':
1779
+ // วิเคราะห์ปลั๊กอินที่เลือก
1780
+ if (plugins && plugins.length > 0) {
1781
+ analysisResult = await analyzeSpecificPlugins(plugins);
1782
+ } else {
1783
+ return {
1784
+ success: false,
1785
+ error: 'กรุณาเลือกปลั๊กอินที่ต้องการตรวจสอบ'
1786
+ };
1787
+ }
1788
+ break;
1789
+
1790
+ default:
1791
+ return {
1792
+ success: false,
1793
+ error: 'ประเภทการวินิจฉัยไม่ถูกต้อง'
1794
+ };
1795
+ }
1796
+
1797
+ const message = analysisResult.totalIssues === 0
1798
+ ? `ไม่พบปัญหาใน${getScopeText(scope)}`
1799
+ : `พบปัญหา ${analysisResult.totalIssues} รายการใน${getScopeText(scope)}`;
1800
+
1801
+ console.log(' Parameterized system check completed successfully');
1802
+ return {
1803
+ success: true,
1804
+ message: message,
1805
+ fixed: repairResults.length > 0,
1806
+ repairActions: repairResults,
1807
+ recommendations: recommendations,
1808
+ analysis: analysisResult,
1809
+ scope: scope
1810
+ };
1811
+
1812
+ } catch (error) {
1813
+ console.error(` Parameterized system check failed: ${error.message}`);
1814
+ return { success: false, error: error.message };
1815
+ }
1816
+ });
1817
+
1818
+ // Helper functions for parameterized diagnostics
1819
+ function getScopeText(scope) {
1820
+ const texts = {
1821
+ 'all': 'ทั้งระบบ',
1822
+ 'plugins': 'ปลั๊กอิน',
1823
+ 'core': 'ระบบหลัก',
1824
+ 'dependencies': 'Dependencies',
1825
+ 'specific': 'ปลั๊กอินที่เลือก'
1826
+ };
1827
+ return texts[scope] || 'ส่วนที่ระบุ';
1828
+ }
1829
+
1830
+ async function analyzeDependencies(pluginsDir) {
1831
+ // ตรวจสอบ dependencies ของปลั๊กอินต่างๆ
1832
+ const issues = [];
1833
+
1834
+ try {
1835
+ const plugins = fs.readdirSync(pluginsDir);
1836
+ for (const plugin of plugins) {
1837
+ const pluginPath = path.join(pluginsDir, plugin);
1838
+ const stat = fs.statSync(pluginPath);
1839
+
1840
+ if (stat.isDirectory()) {
1841
+ // ตรวจสอบ package.json
1842
+ const packageJsonPath = path.join(pluginPath, 'package.json');
1843
+ if (fs.existsSync(packageJsonPath)) {
1844
+ try {
1845
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
1846
+ if (!packageJson.dependencies && !packageJson.devDependencies) {
1847
+ issues.push(`ปลั๊กอิน ${plugin} ไม่มี dependencies`);
1848
+ }
1849
+ } catch (error) {
1850
+ issues.push(`ปลั๊กอิน ${plugin} มี package.json ที่ไม่ถูกต้อง`);
1851
+ }
1852
+ }
1853
+ }
1854
+ }
1855
+ } catch (error) {
1856
+ issues.push(`ไม่สามารถตรวจสอบ dependencies ได้: ${error.message}`);
1857
+ }
1858
+
1859
+ return {
1860
+ totalIssues: issues.length,
1861
+ issues: issues,
1862
+ message: issues.length === 0 ? 'Dependencies ทั้งหมดปกติ' : `พบปัญหา dependencies ${issues.length} รายการ`
1863
+ };
1864
+ }
1865
+
1866
+ async function analyzeSpecificPlugins(pluginPaths) {
1867
+ const projectInspector = require('./utils/project-inspector');
1868
+ let totalIssues = 0;
1869
+ const results = [];
1870
+
1871
+ for (const pluginPath of pluginPaths) {
1872
+ try {
1873
+ const analysis = await projectInspector.analyzeProject(pluginPath);
1874
+ totalIssues += analysis.totalIssues;
1875
+ results.push({
1876
+ path: pluginPath,
1877
+ analysis: analysis
1878
+ });
1879
+ } catch (error) {
1880
+ totalIssues++;
1881
+ results.push({
1882
+ path: pluginPath,
1883
+ error: error.message
1884
+ });
1885
+ }
1886
+ }
1887
+
1888
+ return {
1889
+ totalIssues: totalIssues,
1890
+ results: results,
1891
+ message: `ตรวจสอบปลั๊กอิน ${pluginPaths.length} รายการเสร็จสิ้น`
1892
+ };
1893
+ }
1894
+
1895
+ // Removed duplicate 'get-available-plugins' handler - using ValidationGateway version instead
1896
+
1897
+ // IPC Handler: Open Plugins Folder (NEW - สำหรับเปิดโฟลเดอร์ plugins) - FIX: ใช้ app.isPackaged
1898
+ ipcMain.handle('open-plugins-folder', () => {
1899
+ // FIX: ใช้ app.isPackaged เพื่อจัดการ plugins directory path
1900
+ let pluginsDir;
1901
+ if (app.isPackaged) {
1902
+ pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins');
1903
+ } else {
1904
+ pluginsDir = path.join(app.getPath('userData'), 'plugins');
1905
+ }
1906
+
1907
+ // สร้างโฟลเดอร์ถ้ายังไม่มี
1908
+ if (!fs.existsSync(pluginsDir)) {
1909
+ try {
1910
+ fs.mkdirSync(pluginsDir, { recursive: true });
1911
+ console.log(` Created plugins directory at: ${pluginsDir}`);
1912
+ } catch (error) {
1913
+ console.error(` Failed to create plugins directory:`, error);
1914
+ return { success: false, error: error.message };
1915
+ }
1916
+ }
1917
+
1918
+ // เปิดโฟลเดอร์ใน File Explorer
1919
+ shell.openPath(pluginsDir);
1920
+ console.log(` Opened plugins folder: ${pluginsDir}`);
1921
+
1922
+ return { success: true, path: pluginsDir };
1923
+ });
1924
+
1925
+ // IPC Handler: Get All Available Plugins (via ValidationGateway)
1926
+ ipcMain.handle('get-available-plugins', async () => {
1927
+ try {
1928
+ // ValidationGateway's PluginManager will handle this
1929
+ const result = await validationGateway.processCommand({ action: 'list-plugins' });
1930
+ console.log(` Returning available plugins via Gateway`);
1931
+ return result;
1932
+ } catch (error) {
1933
+ console.error(' Failed to get plugins:', error.message);
1934
+ return {
1935
+ success: false,
1936
+ error: error.message
1937
+ };
1938
+ }
1939
+ });
1940
+
1941
+ // Plugin-specific IPC handlers removed - all commands now go through execute-command -> ValidationGateway
1942
+
1943
+ // Plugin command handling functions removed - now handled by ValidationGateway
1944
+
1945
+ // IPC Handler: Run NPM Project Commands (for HTML plugins)
1946
+ ipcMain.handle('run-npm-project', async (event, payload) => {
1947
+ console.log(' [IPC] NPM Project command received:', payload);
1948
+
1949
+ try {
1950
+ // Check if this comes from an HTML plugin window
1951
+ const senderWebContentsId = event.sender.id;
1952
+ const htmlPluginInfo = global.htmlPluginWindows?.get(senderWebContentsId);
1953
+
1954
+ if (!htmlPluginInfo || !htmlPluginInfo.isProjectManager) {
1955
+ throw new Error('This command can only be executed from HTML project management plugins');
1956
+ }
1957
+
1958
+ console.log(` [IPC] Running command from ${htmlPluginInfo.pluginName}`);
1959
+
1960
+ // Security validation
1961
+ const context = {
1962
+ pipelineId: 'html_plugin_' + Date.now(),
1963
+ type: 'html_plugin_request',
1964
+ request: payload,
1965
+ htmlPlugin: htmlPluginInfo.pluginName
1966
+ };
1967
+
1968
+ const securityResult = await validationGateway.validate(payload, context);
1969
+
1970
+ if (!securityResult.valid) {
1971
+ console.log(' [IPC] Security validation failed for HTML plugin:', securityResult.message);
1972
+ return {
1973
+ success: false,
1974
+ error: securityResult.message || 'Security validation failed'
1975
+ };
1976
+ }
1977
+
1978
+ // Execute based on action type
1979
+ switch (payload.action) {
1980
+ case 'scan-projects':
1981
+ return await handleScanProjects();
1982
+
1983
+ case 'scan-project':
1984
+ return await handleScanProject(payload.project, payload.path);
1985
+
1986
+ default:
1987
+ // Regular command execution
1988
+ const NodeStrategy = require('./strategies/NodeStrategy');
1989
+ const nodeStrategy = new NodeStrategy();
1990
+
1991
+ let projectPath = payload.path || payload.cwd;
1992
+ if (!projectPath) {
1993
+ projectPath = path.join(__dirname, 'plugins', 'Chahuadev_Studio_V.10.0.0');
1994
+ }
1995
+
1996
+ const commandContext = {
1997
+ command: payload.command || payload.action,
1998
+ projectPath: projectPath,
1999
+ options: {
2000
+ timeout: 60000,
2001
+ env: {}
2002
+ }
2003
+ };
2004
+
2005
+ const result = await nodeStrategy.execute(commandContext);
2006
+
2007
+ return {
2008
+ success: result.success,
2009
+ data: result.success ? {
2010
+ success: true,
2011
+ output: result.output,
2012
+ message: `Command executed successfully`,
2013
+ command: commandContext.command,
2014
+ exitCode: result.exitCode,
2015
+ duration: result.duration
2016
+ } : null,
2017
+ error: result.success ? null : result.error,
2018
+ timestamp: new Date().toISOString(),
2019
+ source: 'html_plugin_npm'
2020
+ };
2021
+ }
2022
+
2023
+ } catch (error) {
2024
+ console.error(' [IPC] HTML Plugin NPM command error:', error.message);
2025
+
2026
+ return {
2027
+ success: false,
2028
+ error: error.message,
2029
+ timestamp: new Date().toISOString()
2030
+ };
2031
+ }
2032
+ });
2033
+
2034
+ // Project analysis functions removed - now handled by ValidationGateway's SystemDetector
2035
+
2036
+ // Handler: Scan Projects (NEW!)
2037
+ async function handleScanProjects() {
2038
+ console.log(' [Scan] Starting project scan...');
2039
+
2040
+ try {
2041
+ // ใช้ SystemDetector ในการสแกน
2042
+ const SystemDetector = require('./modules/system-detector');
2043
+ const systemDetector = new SystemDetector();
2044
+
2045
+ // เรียกใช้ scanProjects ที่ SystemDetector
2046
+ const result = await systemDetector.scanProjects();
2047
+
2048
+ console.log(` [Scan] Scan complete: ${result.count} projects found`);
2049
+
2050
+ return {
2051
+ success: true,
2052
+ data: result,
2053
+ timestamp: new Date().toISOString()
2054
+ };
2055
+
2056
+ } catch (error) {
2057
+ console.error(' [Scan] Error during project scan:', error.message);
2058
+ return {
2059
+ success: false,
2060
+ error: error.message,
2061
+ timestamp: new Date().toISOString()
2062
+ };
2063
+ }
2064
+ }
2065
+
2066
+ // Handler: Scan Single Project (NEW!)
2067
+ async function handleScanProject(projectName, projectPath) {
2068
+ console.log(` [Scan] Scanning single project: ${projectName} at ${projectPath}`);
2069
+
2070
+ try {
2071
+ // ใช้ SystemDetector ในการสแกน
2072
+ const SystemDetector = require('./modules/system-detector');
2073
+ const systemDetector = new SystemDetector();
2074
+
2075
+ // เรียกใช้ detect สำหรับโปรเจกต์เดียว
2076
+ const result = await systemDetector.detect(projectPath);
2077
+
2078
+ console.log(` [Scan] Single project scan complete: ${result.type} (${result.confidence}%)`);
2079
+
2080
+ return {
2081
+ success: true,
2082
+ data: result,
2083
+ timestamp: new Date().toISOString()
2084
+ };
2085
+
2086
+ } catch (error) {
2087
+ console.error(' [Scan] Error during single project scan:', error.message);
2088
+ return {
2089
+ success: false,
2090
+ error: error.message,
2091
+ timestamp: new Date().toISOString()
2092
+ };
2093
+ }
2094
+ }
2095
+
2096
+ // IPC Handler: Execute Quick Commands (NEW!) - with Fort-Knox Security
2097
+ ipcMain.handle('execute-quick-command', async (event, command) => {
2098
+ console.log(' [IPC] Quick command received:', command);
2099
+
2100
+ try {
2101
+ // SECURITY: ตรวจสอบและทำความสะอาดคำสั่งก่อนรัน
2102
+ let sanitizedResult;
2103
+ try {
2104
+ sanitizedResult = ipcSecurity.sanitizeCommand(command);
2105
+ } catch (securityError) {
2106
+ console.error(' [Security] Command blocked:', securityError.message);
2107
+ return {
2108
+ success: false,
2109
+ error: `Security violation: ${securityError.message}`,
2110
+ securityAlert: true
2111
+ };
2112
+ }
2113
+
2114
+ // Parse --cwd= parameter if present
2115
+ let workingDir = null;
2116
+ let cleanCommand = sanitizedResult.sanitized;
2117
+
2118
+ if (cleanCommand.includes('--cwd=')) {
2119
+ const cwdMatch = cleanCommand.match(/--cwd=([^\s]+)/);
2120
+ if (cwdMatch) {
2121
+ workingDir = cwdMatch[1];
2122
+ cleanCommand = cleanCommand.replace(/--cwd=[^\s]+\s*/, '').trim();
2123
+ console.log(` [IPC] Working directory: ${workingDir}`);
2124
+
2125
+ // ตรวจสอบ working directory path
2126
+ if (workingDir.includes('../') || workingDir.includes('..\\')) {
2127
+ throw new Error('Path traversal detected in working directory');
2128
+ }
2129
+ }
2130
+ }
2131
+
2132
+ // Execute using NodeStrategy
2133
+ const NodeStrategy = require('./strategies/NodeStrategy');
2134
+ const nodeStrategy = new NodeStrategy();
2135
+
2136
+ const commandContext = {
2137
+ command: cleanCommand,
2138
+ projectPath: workingDir || getUnpackedPath('plugins/Chahuadev_Studio_V.10.0.0'),
2139
+ options: { timeout: 60000, env: {} }
2140
+ };
2141
+
2142
+ const result = await nodeStrategy.execute(commandContext);
2143
+
2144
+ return {
2145
+ success: result.success,
2146
+ data: result.success ? {
2147
+ output: result.output,
2148
+ message: `Quick command executed: ${cleanCommand}`,
2149
+ exitCode: result.exitCode,
2150
+ securityInfo: `Command sanitized and executed safely (${sanitizedResult.baseCommand})`
2151
+ } : null,
2152
+ error: result.success ? null : result.error
2153
+ };
2154
+
2155
+ } catch (error) {
2156
+ console.error(' [IPC] Quick command error:', error.message);
2157
+ return { success: false, error: error.message };
2158
+ }
2159
+ });
2160
+
2161
+ // IPC Handler: Execute Plugin Commands (NEW - to bridge UI buttons)
2162
+ ipcMain.handle('execute-plugin-command', async (event, pluginName, command, data) => {
2163
+ console.log(` [IPC] Received command: [${command}] on [${pluginName}]`);
2164
+ if (!validationGateway) {
2165
+ return { success: false, error: 'Validation Gateway not initialized' };
2166
+ }
2167
+
2168
+ try {
2169
+ // หา Path ของโปรเจกต์ (ปลั๊กอิน) ก่อน
2170
+ const projectPath = await validationGateway.getPluginPath(pluginName);
2171
+
2172
+ // สร้าง request object ที่สมบูรณ์เพื่อส่งให้ Gateway
2173
+ const request = {
2174
+ action: command, // action คือคำสั่งที่ได้จากปุ่มโดยตรง เช่น 'launch-exe'
2175
+ pluginName: pluginName,
2176
+ projectPath: projectPath, // ส่ง Path ที่ถูกต้องไปด้วย
2177
+ data: data || {}
2178
+ };
2179
+
2180
+ console.log(`Forwarding to Gateway processCommand:`, request);
2181
+
2182
+ // ส่งให้ processCommand ใน Gateway จัดการ ซึ่งมี switch-case รองรับทุก action
2183
+ const result = await validationGateway.processCommand(request);
2184
+
2185
+ return result;
2186
+
2187
+ } catch (error) {
2188
+ console.error(` [IPC] Error processing command "${command}" for "${pluginName}":`, error);
2189
+ return { success: false, error: error.message };
2190
+ }
2191
+ });
2192
+
2193
+ // MAIN IPC HANDLER: Execute Commands via ValidationGateway
2194
+ ipcMain.handle('execute-command', async (event, payload) => {
2195
+ console.log(' [IPC] Received command, forwarding to Validation Gateway:', payload);
2196
+ try {
2197
+ // ส่งต่อไปให้ Gateway จัดการทั้งหมด
2198
+ return await validationGateway.processCommand(payload);
2199
+ } catch (error) {
2200
+ console.error(' [IPC] Error forwarding to ValidationGateway:', error.message);
2201
+ return {
2202
+ success: false,
2203
+ error: error.message,
2204
+ timestamp: new Date().toISOString()
2205
+ };
2206
+ }
2207
+ });
2208
+
2209
+ // IPC Handler: Get Run Mode (Development vs Production)
2210
+ ipcMain.handle('get-run-mode', () => {
2211
+ console.log(` [IPC] Checking run mode - isDevMode: ${isDevMode}`);
2212
+ return { isDevMode: isDevMode };
2213
+ });
2214
+
2215
+ // IPC Handler: Build App Process (NEW!)
2216
+ ipcMain.handle('start-build', async (event) => {
2217
+ console.log(' [IPC] Starting build process...');
2218
+
2219
+ // ใช้ child_process เพื่อรันคำสั่ง electron-builder
2220
+ const { exec } = require('child_process');
2221
+
2222
+ // คำสั่ง build สำหรับ Windows
2223
+ const command = 'npx electron-builder --win --x64';
2224
+
2225
+ // ได้ project root จากฟังก์ชันที่มีอยู่แล้ว
2226
+ const projectRoot = getAppBasePath();
2227
+
2228
+ console.log(` Starting build with command: ${command}`);
2229
+ console.log(` Project root: ${projectRoot}`);
2230
+
2231
+ try {
2232
+ // รันคำสั่ง build
2233
+ const buildProcess = exec(command, { cwd: projectRoot });
2234
+
2235
+ // ส่ง Log กลับไปที่ UI แบบ Real-time
2236
+ buildProcess.stdout.on('data', (data) => {
2237
+ console.log(` [STDOUT] ${data}`);
2238
+ // ส่ง Log กลับไปที่หน้าต่างหลักผ่านช่องทาง 'build-log'
2239
+ if (mainWindow && !mainWindow.isDestroyed()) {
2240
+ mainWindow.webContents.send('build-log', data.toString());
2241
+ }
2242
+ });
2243
+
2244
+ // ส่ง Error Log กลับไป
2245
+ buildProcess.stderr.on('data', (data) => {
2246
+ console.log(` [STDERR] ${data}`);
2247
+ if (mainWindow && !mainWindow.isDestroyed()) {
2248
+ // ส่ง Error Log กลับไปในรูปแบบที่แตกต่าง
2249
+ mainWindow.webContents.send('build-log', `[ERROR] ${data.toString()}`);
2250
+ }
2251
+ });
2252
+
2253
+ // เมื่อกระบวนการ Build สิ้นสุดลง
2254
+ buildProcess.on('close', (code) => {
2255
+ const message = code === 0
2256
+ ? ' กระบวนการ Build เสร็จสมบูรณ์!'
2257
+ : ` กระบวนการ Build ล้มเหลว (Exit Code: ${code})`;
2258
+
2259
+ console.log(` Build process finished with code: ${code}`);
2260
+
2261
+ if (mainWindow && !mainWindow.isDestroyed()) {
2262
+ mainWindow.webContents.send('build-log', `\n ${message}`);
2263
+
2264
+ if (code === 0) {
2265
+ // ส่งข้อมูลเพิ่มเติมเมื่อ Build สำเร็จ
2266
+ mainWindow.webContents.send('build-log', ' ไฟล์ Build สำเร็จแล้ว สามารถดูได้ในโฟลเดอร์ dist/');
2267
+ mainWindow.webContents.send('build-log', ' ไฟล์ที่สร้าง: *.exe, *.msi, *.zip');
2268
+ mainWindow.webContents.send('build-log', ' สามารถนำไปติดตั้งบนเครื่องอื่นได้แล้ว!');
2269
+ }
2270
+ }
2271
+ });
2272
+
2273
+ // เมื่อมี error ในการ start process
2274
+ buildProcess.on('error', (error) => {
2275
+ console.error(` Build process error:`, error);
2276
+ if (mainWindow && !mainWindow.isDestroyed()) {
2277
+ mainWindow.webContents.send('build-log', `[ERROR] ไม่สามารถเริ่ม Build ได้: ${error.message}`);
2278
+ }
2279
+ });
2280
+
2281
+ return { success: true };
2282
+
2283
+ } catch (error) {
2284
+ console.error(` Build command failed to start:`, error);
2285
+ return { success: false, error: error.message };
2286
+ }
2287
+ });
2288
+
2289
+ // System Information API Handlers - สำหรับ debugger.js
2290
+ ipcMain.handle('system:get-info', async () => {
2291
+ try {
2292
+ const info = {
2293
+ platform: os.platform(),
2294
+ arch: os.arch(),
2295
+ version: os.version(),
2296
+ uptime: os.uptime(),
2297
+ totalmem: os.totalmem(),
2298
+ freemem: os.freemem(),
2299
+ cpus: os.cpus().length,
2300
+ networkInterfaces: Object.keys(os.networkInterfaces()).length
2301
+ };
2302
+ return info;
2303
+ } catch (error) {
2304
+ console.error(' [System] Get info error:', error);
2305
+ throw error;
2306
+ }
2307
+ });
2308
+
2309
+ ipcMain.handle('system:get-cwd', async () => {
2310
+ try {
2311
+ return process.cwd();
2312
+ } catch (error) {
2313
+ console.error(' [System] Get CWD error:', error);
2314
+ throw error;
2315
+ }
2316
+ });
2317
+
2318
+ ipcMain.handle('system:get-version', async () => {
2319
+ try {
2320
+ return app.getVersion();
2321
+ } catch (error) {
2322
+ console.error(' [System] Get version error:', error);
2323
+ throw error;
2324
+ }
2325
+ });
2326
+
2327
+ ipcMain.handle('system:get-memory-usage', async () => {
2328
+ try {
2329
+ return process.memoryUsage();
2330
+ } catch (error) {
2331
+ console.error(' [System] Get memory usage error:', error);
2332
+ throw error;
2333
+ }
2334
+ });
2335
+
2336
+ ipcMain.handle('system:get-cpu-usage', async () => {
2337
+ try {
2338
+ return os.cpus();
2339
+ } catch (error) {
2340
+ console.error(' [System] Get CPU usage error:', error);
2341
+ throw error;
2342
+ }
2343
+ });
2344
+
2345
+ ipcMain.handle('system:get-platform', async () => {
2346
+ try {
2347
+ return {
2348
+ platform: process.platform,
2349
+ arch: process.arch,
2350
+ version: process.version
2351
+ };
2352
+ } catch (error) {
2353
+ console.error(' [System] Get platform error:', error);
2354
+ throw error;
2355
+ }
2356
+ });
2357
+
2358
+ ipcMain.handle('system:get-plugins-path', async () => {
2359
+ try {
2360
+ let pluginsDir;
2361
+ if (app.isPackaged) {
2362
+ // โหมดใช้งานจริง: อยู่ข้างไฟล์ .exe
2363
+ pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins');
2364
+ } else {
2365
+ // โหมดพัฒนา: อยู่ใน AppData
2366
+ pluginsDir = path.join(app.getPath('userData'), 'plugins');
2367
+ }
2368
+ return pluginsDir;
2369
+ } catch (error) {
2370
+ console.error(' [System] Get plugins path error:', error);
2371
+ throw error;
2372
+ }
2373
+ });
2374
+
2375
+ // ========== FORT-KNOX SECURITY IPC HANDLERS ==========
2376
+ ipcMain.handle('process-command', async (event, request) => {
2377
+ try {
2378
+ console.log(' [Main] Processing command:', request.command || request.action);
2379
+ const result = await validationGateway.processCommand(request);
2380
+ return result;
2381
+ } catch (error) {
2382
+ console.error(' [Main] Process command error:', error);
2383
+ return { success: false, error: error.message };
2384
+ }
2385
+ });
2386
+
2387
+ // ========== FORT-KNOX SECURITY IPC HANDLERS ==========
2388
+
2389
+ // IPC Handler: ตรวจสอบโหมด Developer Mode
2390
+ ipcMain.handle('security:get-dev-mode', async () => {
2391
+ try {
2392
+ return {
2393
+ success: true,
2394
+ data: {
2395
+ isDevMode: antiDebugging.isDevMode,
2396
+ detectionMethod: antiDebugging.detectDeveloperMode ? 'enhanced' : 'legacy',
2397
+ timestamp: Date.now()
2398
+ }
2399
+ };
2400
+ } catch (error) {
2401
+ console.error(' Error getting dev mode status:', error);
2402
+ return {
2403
+ success: false,
2404
+ error: error.message,
2405
+ data: { isDevMode: false } // Default to production mode on error
2406
+ };
2407
+ }
2408
+ });
2409
+
2410
+ // IPC Handler: ตรวจสอบสถานะความปลอดภัย
2411
+ ipcMain.handle('security:get-status', async () => {
2412
+ try {
2413
+ return {
2414
+ success: true,
2415
+ data: {
2416
+ antiDebugging: {
2417
+ enabled: !antiDebugging.isDevMode,
2418
+ mode: antiDebugging.isDevMode ? 'development' : 'production',
2419
+ suspiciousActivityCount: antiDebugging.suspiciousActivityCount,
2420
+ maxSuspiciousActivity: antiDebugging.maxSuspiciousActivity
2421
+ },
2422
+ ipcSecurity: {
2423
+ enabled: true,
2424
+ allowedCommands: ipcSecurity.getAllowedCommands(),
2425
+ commandCount: ipcSecurity.getAllowedCommands().length
2426
+ },
2427
+ buildMode: app.isPackaged ? 'production' : 'development',
2428
+ version: app.getVersion(),
2429
+ securityLevel: 'Fort-Knox'
2430
+ }
2431
+ };
2432
+ } catch (error) {
2433
+ return { success: false, error: error.message };
2434
+ }
2435
+ });
2436
+
2437
+ // IPC Handler: ทดสอบการทำงานของระบบความปลอดภัย
2438
+ ipcMain.handle('security:test-command-sanitization', async (event, testCommand) => {
2439
+ try {
2440
+ const result = ipcSecurity.sanitizeCommand(testCommand);
2441
+ return {
2442
+ success: true,
2443
+ data: {
2444
+ original: result.original,
2445
+ sanitized: result.sanitized,
2446
+ baseCommand: result.baseCommand,
2447
+ isAllowed: result.isAllowed,
2448
+ testResult: 'Command passed security validation'
2449
+ }
2450
+ };
2451
+ } catch (error) {
2452
+ return {
2453
+ success: false,
2454
+ error: error.message,
2455
+ data: {
2456
+ original: testCommand,
2457
+ testResult: 'Command blocked by security system',
2458
+ reason: error.message
2459
+ }
2460
+ };
2461
+ }
2462
+ });
2463
+
2464
+ module.exports = { mainWindow };
modules/button-generator.js ADDED
@@ -0,0 +1,621 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Button Generator - Smart Button Creation System
3
+ * Chahua Development Thailand
4
+ * CEO: Saharath C.
5
+ *
6
+ * Purpose: สร้างปุ่มแบบอัจฉริยะตามการทำงานของโปรเจค
7
+ */
8
+
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+
12
+ class ButtonGenerator {
13
+ constructor(language = 'en') {
14
+ this.buttonRegistry = new Map();
15
+ this.language = language; // ภาษาปัจจุบัน: 'en' หรือ 'th'
16
+ this.templateLibrary = this.initializeTemplateLibrary();
17
+ this.actionHandlers = new Map();
18
+ this.translations = this.initializeTranslations();
19
+
20
+ console.log(` Button Generator initialized (Language: ${language})`);
21
+ }
22
+
23
+ // ระบบแปลหลายภาษา
24
+ initializeTranslations() {
25
+ return {
26
+ 'en': {
27
+ // Node.js
28
+ 'npm-install': 'Install',
29
+ 'npm-start': 'Start',
30
+ 'npm-test': 'Test',
31
+ 'npm-build': 'Build',
32
+ 'npm-lint': 'Lint',
33
+ 'npm-dev': 'Dev',
34
+ 'npm-serve': 'Serve',
35
+ // Python
36
+ 'pip-install': 'Install',
37
+ 'python-run': 'Run Main',
38
+ 'python-test': 'Test',
39
+ 'python-format': 'Format',
40
+ // Executable
41
+ 'launch-exe': 'Launch App',
42
+ 'run-as-admin': 'Run as Admin',
43
+ // Batch
44
+ 'run-batch': 'Run Script',
45
+ 'edit-batch': 'Edit Script',
46
+ // Utility
47
+ 'open-terminal': 'Terminal',
48
+ 'file-explorer': 'Open Folder',
49
+ 'refresh': 'Refresh',
50
+ 'settings': 'Settings',
51
+ // Web
52
+ 'npm-watch': 'Watch',
53
+ 'deploy': 'Deploy',
54
+ // Categories
55
+ 'Node.js Basic': 'Node.js Basic',
56
+ 'Node.js Advanced': 'Node.js Advanced',
57
+ 'Python Basic': 'Python Basic',
58
+ 'Python Advanced': 'Python Advanced',
59
+ 'Application': 'Application',
60
+ 'Batch Scripts': 'Batch Scripts',
61
+ 'Utility': 'Utility',
62
+ 'Web Development': 'Web Development'
63
+ },
64
+ 'th': {
65
+ // Node.js
66
+ 'npm-install': 'ติดตั้ง',
67
+ 'npm-start': 'เริ่มต้น',
68
+ 'npm-test': 'ทดสอบ',
69
+ 'npm-build': 'สร้าง',
70
+ 'npm-lint': 'ตรวจสอบ',
71
+ 'npm-dev': 'พัฒนา',
72
+ 'npm-serve': 'เรียกใช้',
73
+ // Python
74
+ 'pip-install': 'ติดตั้ง',
75
+ 'python-run': 'รันหลัก',
76
+ 'python-test': 'ทดสอบ',
77
+ 'python-format': 'จัดรูป',
78
+ // Executable
79
+ 'launch-exe': 'เปิดแอป',
80
+ 'run-as-admin': 'รันเป็นผู้ดูแลระบบ',
81
+ // Batch
82
+ 'run-batch': 'รันสคริปต์',
83
+ 'edit-batch': 'แก้ไขสคริปต์',
84
+ // Utility
85
+ 'open-terminal': 'เทอร์มินัล',
86
+ 'file-explorer': 'เปิดโฟลเดอร์',
87
+ 'refresh': 'รีเฟรช',
88
+ 'settings': 'ตั้งค่า',
89
+ // Web
90
+ 'npm-watch': 'เฝ้าดู',
91
+ 'deploy': 'ปรับใช้',
92
+ // Categories
93
+ 'Node.js Basic': 'Node.js พื้นฐาน',
94
+ 'Node.js Advanced': 'Node.js ขั้นสูง',
95
+ 'Python Basic': 'Python พื้นฐาน',
96
+ 'Python Advanced': 'Python ขั้นสูง',
97
+ 'Application': 'แอปพลิเคชัน',
98
+ 'Batch Scripts': 'สคริปต์ Batch',
99
+ 'Utility': 'เครื่องมือ',
100
+ 'Web Development': 'พัฒนา Web'
101
+ }
102
+ };
103
+ }
104
+
105
+ // ฟังก์ชันแปลข้อความ
106
+ translate(key) {
107
+ const trans = this.translations[this.language] || this.translations['en'];
108
+ return trans[key] || key;
109
+ }
110
+
111
+ // ตั้งภาษา
112
+ setLanguage(language) {
113
+ if (this.translations[language]) {
114
+ this.language = language;
115
+ console.log(` Button language changed to: ${language}`);
116
+ } else {
117
+ console.warn(` Unsupported language: ${language}, using English`);
118
+ this.language = 'en';
119
+ }
120
+ }
121
+
122
+ // ไลบรารีเทมเพลตปุ่มสำหรับโปรเจคต่างๆ
123
+ initializeTemplateLibrary() {
124
+ return {
125
+ // Node.js Project Templates
126
+ 'node-basic': {
127
+ category: 'Node.js Basic',
128
+ buttons: [
129
+ { id: 'npm-install', nameKey: 'npm-install', command: 'npm-install', icon: '' },
130
+ { id: 'npm-start', nameKey: 'npm-start', command: 'npm-start', icon: '' }
131
+ ]
132
+ },
133
+ 'node-advanced': {
134
+ category: 'Node.js Advanced',
135
+ buttons: [
136
+ { id: 'npm-test', nameKey: 'npm-test', command: 'npm-test', icon: '' },
137
+ { id: 'npm-build', nameKey: 'npm-build', command: 'npm-build', icon: '' },
138
+ { id: 'npm-lint', nameKey: 'npm-lint', command: 'npm-lint', icon: '' }
139
+ ]
140
+ },
141
+
142
+ // Python Project Templates
143
+ 'python-basic': {
144
+ category: 'Python Basic',
145
+ buttons: [
146
+ { id: 'pip-install', nameKey: 'pip-install', command: 'pip-install', icon: '' },
147
+ { id: 'python-run', nameKey: 'python-run', command: 'python-run', icon: '' }
148
+ ]
149
+ },
150
+
151
+ // เพิ่ม Template ใหม่สำหรับ EXE
152
+ 'executable-runner': {
153
+ category: 'Application',
154
+ buttons: [
155
+ { id: 'launch-exe', nameKey: 'launch-exe', command: 'launch-exe', icon: '' },
156
+ { id: 'run-as-admin', nameKey: 'run-as-admin', command: 'run-as-admin', icon: '' }
157
+ ]
158
+ },
159
+
160
+ // เพิ่ม Template ใหม่สำหรับ BAT
161
+ 'batch-runner': {
162
+ category: 'Batch Scripts',
163
+ buttons: [
164
+ { id: 'run-batch', nameKey: 'run-batch', command: 'run-batch', icon: '' },
165
+ { id: 'edit-batch', nameKey: 'edit-batch', command: 'edit-batch', icon: '' }
166
+ ]
167
+ },
168
+
169
+ // Utility Templates (ปุ่มพื้นฐาน)
170
+ 'utility': {
171
+ category: 'Utility',
172
+ buttons: [
173
+ { id: 'open-terminal', nameKey: 'open-terminal', command: 'open_terminal', icon: '' },
174
+ { id: 'file-explorer', nameKey: 'file-explorer', command: 'open_explorer', icon: '' }
175
+ ]
176
+ }
177
+ };
178
+ }
179
+
180
+ // สร้างปุ่มตามข้อมูลโปรเจค
181
+ generateProjectButtons(projectInfo, features) {
182
+ const { name, type, path: projectPath, previewImage } = projectInfo; // เพิ่ม previewImage
183
+ let buttons = [];
184
+ console.log(` Generating buttons for project: ${name} (Type: ${type})`);
185
+
186
+ // เพิ่ม fallback สำหรับ unknown type
187
+ let projectType = type;
188
+ if (projectType === 'unknown') {
189
+ projectType = 'executable_project'; // fallback เป็น executable_project
190
+ console.log(` -> [Fallback] Using executable_project type instead of unknown`);
191
+ projectInfo.type = projectType; // อัปเดต type ใน object
192
+ }
193
+
194
+ // --- อัปเกรดตรรกะการตัดสินใจเป็นแบบ 3 ทาง ---
195
+
196
+ if (features.hasBatchRunner) {
197
+ // 1. ทางพิเศษสำหรับ .bat
198
+ console.log(` -> Using Batch Runner strategy`);
199
+ const batchTemplate = this.templateLibrary['batch-runner'];
200
+ if (batchTemplate) {
201
+ const batchButtons = this.customizeButtons(batchTemplate.buttons, projectInfo, features);
202
+ buttons.push(...this.customizeBatchButtons(batchButtons, projectInfo));
203
+ }
204
+
205
+ } else if (projectType === 'executable_project') {
206
+ // 2. ทางพิเศษสำหรับ .exe
207
+ console.log(` -> Using Executable Runner strategy`);
208
+ const exeTemplate = this.templateLibrary['executable-runner'];
209
+ if (exeTemplate) {
210
+ const exeButtons = this.customizeButtons(exeTemplate.buttons, projectInfo, features);
211
+ buttons.push(...this.customizeExecutableButtons(exeButtons, projectInfo));
212
+ }
213
+
214
+ } else {
215
+ // 3. ทางปกติสำหรับ npm และอื่นๆ
216
+ console.log(` -> Using standard template strategy`);
217
+ const templates = this.selectTemplates(projectType, features);
218
+ for (const template of templates) {
219
+ const templateButtons = this.templateLibrary[template];
220
+ if (templateButtons) {
221
+ buttons.push(...this.customizeButtons(templateButtons.buttons, projectInfo, features));
222
+ }
223
+ }
224
+ }
225
+ // --- จบส่วนตรรกะ ---
226
+
227
+ // เพิ่มปุ่มพิเศษตามฟีเจอร��� (เฉพาะโปรเจคธรรมดา)
228
+ if (!features.hasBatchRunner && projectType !== 'executable_project') {
229
+ buttons.push(...this.generateConditionalButtons(features, projectInfo));
230
+ }
231
+
232
+ // เพิ่มปุ่มยูทิลิตี้พื้นฐาน
233
+ buttons.push(...this.generateUtilityButtons(projectInfo));
234
+
235
+ // เพิ่มข้อมูลภาพตัวอย่างในปุ่มทุกปุ่ม
236
+ buttons = buttons.map(button => ({
237
+ ...button,
238
+ previewImage: previewImage, // เพิ่มภาพตัวอย่าง
239
+ projectPreview: previewImage // เก็บ reference เพิ่มเติม
240
+ }));
241
+
242
+ // ลงทะเบียนปุ่ม
243
+ this.buttonRegistry.set(name, {
244
+ projectInfo,
245
+ buttons,
246
+ previewImage, // เก็บ previewImage ใน registry
247
+ generated: new Date().toISOString()
248
+ });
249
+
250
+ console.log(` Generated ${buttons.length} buttons for ${name} with preview: ${previewImage || 'none'}`);
251
+ return buttons;
252
+ }
253
+
254
+ // เลือกเทมเพลตตามประเภทและฟีเจอร์
255
+ selectTemplates(projectType, features) {
256
+ const templates = [];
257
+
258
+ switch (projectType) {
259
+ case 'node':
260
+ templates.push('node-basic');
261
+ if (features.hasLinter || features.hasTests || features.hasTypeScript) {
262
+ templates.push('node-advanced');
263
+ }
264
+ break;
265
+
266
+ case 'python':
267
+ templates.push('python-basic');
268
+ if (features.hasFlask || features.hasDjango || features.hasJupyter) {
269
+ templates.push('python-web');
270
+ }
271
+ break;
272
+
273
+ case 'html':
274
+ templates.push('web-basic');
275
+ break;
276
+
277
+ case 'studio':
278
+ templates.push('studio');
279
+ break;
280
+
281
+ // เพิ่มการรองรับ executable และ batch projects
282
+ case 'executable_project':
283
+ templates.push('executable-runner');
284
+ break;
285
+
286
+ case 'batch_project':
287
+ templates.push('batch-runner');
288
+ break;
289
+
290
+ default:
291
+ templates.push('utility');
292
+ break;
293
+ }
294
+
295
+ return templates;
296
+ }
297
+
298
+ // ปรับแต่งปุ่มตามโปรเจค
299
+ customizeButtons(templateButtons, projectInfo, features) {
300
+ return templateButtons.map(btn => ({
301
+ ...btn,
302
+ name: this.translate(btn.nameKey), // แปลชื่อปุ่ม
303
+ projectName: projectInfo.name,
304
+ projectPath: projectInfo.path,
305
+ projectType: projectInfo.type,
306
+ enabled: this.checkButtonCompatibility(btn, features),
307
+ tooltip: `${this.translate(btn.nameKey)} for ${projectInfo.name}`,
308
+ lastUsed: null
309
+ }));
310
+ }
311
+
312
+ // สร้างปุ่มแบบมีเงื่อนไข
313
+ generateConditionalButtons(features, projectInfo) {
314
+ const conditionalButtons = [];
315
+
316
+ // Electron specific buttons - ลบปุ่ม Dev ออก
317
+ // if (features.hasElectron) {
318
+ // conditionalButtons.push({
319
+ // id: 'electron-dev',
320
+ // name: 'Electron Dev',
321
+ // command: 'electron-dev',
322
+ // icon: '',
323
+ // color: '#9F7AEA',
324
+ // category: 'electron',
325
+ // projectName: projectInfo.name,
326
+ // projectPath: projectInfo.path,
327
+ // enabled: true
328
+ // });
329
+ // }
330
+
331
+ // TypeScript specific buttons
332
+ if (features.hasTypeScript) {
333
+ conditionalButtons.push({
334
+ id: 'tsc-check',
335
+ nameKey: 'npm-build', // ใช้ key ที่เป็น static
336
+ name: this.translate(features.hasTypeScript ? 'npm-build' : 'npm-lint'),
337
+ // FIX: เปลี่ยน command จาก 'npx tsc --noEmit' เป็น 'tsc-check'
338
+ command: 'tsc-check',
339
+ icon: '',
340
+ color: '#3182CE',
341
+ category: 'typescript',
342
+ projectName: projectInfo.name,
343
+ projectPath: projectInfo.path,
344
+ enabled: true
345
+ });
346
+ }
347
+
348
+ return conditionalButtons;
349
+ }
350
+
351
+ // สร้างปุ่มยูทิลิตี้
352
+ generateUtilityButtons(projectInfo) {
353
+ const utilityTemplate = this.templateLibrary['utility'];
354
+ return this.customizeButtons(utilityTemplate.buttons, projectInfo, {});
355
+ }
356
+
357
+ // ตรวจสอบความเข้ากันได้ของปุ่ม
358
+ checkButtonCompatibility(button, features) {
359
+ // ตรวจสอบเงื่อนไขเฉพาะ
360
+ if (button.requires) {
361
+ return button.requires.every(req => features[req]);
362
+ }
363
+
364
+ // ปุ่มพื้นฐานใช้ได้เสมอ
365
+ return true;
366
+ }
367
+
368
+ // ปรับแต่งปุ่มสำหรับ Batch Scripts (เวอร์ชันแก้ไข)
369
+ customizeBatchButtons(batchButtons, projectInfo) {
370
+ const fs = require('fs');
371
+ const path = require('path');
372
+
373
+ const { path: projectPath, name } = projectInfo;
374
+ const customizedButtons = [];
375
+
376
+ try {
377
+ const files = fs.readdirSync(projectPath);
378
+ const batchFiles = files.filter(file =>
379
+ file.endsWith('.bat') || file.endsWith('.cmd')
380
+ );
381
+
382
+ console.log(` -> Found ${batchFiles.length} batch files: ${batchFiles.join(', ')}`);
383
+
384
+ // ถ้าไม่เจอไฟล์ batch เลย ก็ไม่ต้องสร้างปุ่ม
385
+ if (batchFiles.length === 0) return [];
386
+
387
+ // ใช้ไฟล์ .bat แรกที่เจอ หรือหาตัวที่ชื่อตรงกับโฟลเดอร์
388
+ const targetBatch = batchFiles.find(file =>
389
+ file.toLowerCase().includes(name.toLowerCase())
390
+ ) || batchFiles[0];
391
+
392
+ for (const button of batchButtons) {
393
+ const customButton = { ...button };
394
+
395
+ // **จุดแก้ไข:** ให้ command เป็น action name ไม่ใช่ชื่อไฟล์
396
+ if (button.id === 'run-batch') {
397
+ customButton.command = 'run-batch'; // <--- แก้ไขตรงนี้
398
+ customButton.name = `Run ${path.parse(targetBatch).name}`;
399
+ customButton.tooltip = `Execute ${targetBatch}`;
400
+ } else if (button.id === 'edit-batch') {
401
+ customButton.command = 'edit-batch'; // <--- แก้ไขตรงนี้
402
+ customButton.name = `Edit ${path.parse(targetBatch).name}`;
403
+ customButton.tooltip = `Edit ${targetBatch} in Notepad`;
404
+ }
405
+
406
+ if (customButton.command) {
407
+ customizedButtons.push(customButton);
408
+ }
409
+ }
410
+
411
+ console.log(` -> Customized ${customizedButtons.length} batch buttons`);
412
+ return customizedButtons;
413
+
414
+ } catch (error) {
415
+ console.log(` -> Error customizing batch buttons: ${error.message}`);
416
+ return [];
417
+ }
418
+ }
419
+
420
+ // ปรับแต่งปุ่มสำหรับ Executable Files (เวอร์ชันแก้ไข)
421
+ customizeExecutableButtons(exeButtons, projectInfo) {
422
+ const fs = require('fs');
423
+ const path = require('path');
424
+
425
+ const { path: projectPath, name } = projectInfo;
426
+ const customizedButtons = [];
427
+
428
+ try {
429
+ const files = fs.readdirSync(projectPath);
430
+ const exeFiles = files.filter(file => file.endsWith('.exe'));
431
+
432
+ console.log(` -> Found ${exeFiles.length} executable files: ${exeFiles.join(', ')}`);
433
+
434
+ // ถ้าไม่เจอไฟล์ .exe เลย ก็ไม่ต้องสร้างปุ่ม
435
+ if (exeFiles.length === 0) return [];
436
+
437
+ // ใช้ไฟล์ .exe แรกที่เจอ หรือหาตัวที่ชื่อตรงกับโฟลเดอร์
438
+ const targetExe = exeFiles.find(file =>
439
+ file.toLowerCase().includes(name.toLowerCase())
440
+ ) || exeFiles[0];
441
+
442
+ for (const button of exeButtons) {
443
+ const customButton = { ...button };
444
+
445
+ // **จุดแก้ไข:** ให้ command เป็น action name ที่ Gateway รู้จัก
446
+ if (button.id === 'launch-exe') {
447
+ customButton.command = 'launch-exe'; // <--- แก้ไขตรงนี้
448
+ customButton.name = `Launch ${path.parse(targetExe).name}`;
449
+ customButton.tooltip = `Execute ${targetExe}`;
450
+ } else if (button.id === 'run-as-admin') {
451
+ customButton.command = 'run-as-admin'; // <--- แก้ไขตรงนี้
452
+ customButton.name = `Admin ${path.parse(targetExe).name}`;
453
+ customButton.tooltip = `Run ${targetExe} as Administrator`;
454
+ }
455
+
456
+ if (customButton.command) {
457
+ customizedButtons.push(customButton);
458
+ }
459
+ }
460
+
461
+ console.log(` -> Customized ${customizedButtons.length} executable buttons`);
462
+ return customizedButtons;
463
+
464
+ } catch (error) {
465
+ console.log(` -> Error customizing executable buttons: ${error.message}`);
466
+ return [];
467
+ }
468
+ }
469
+
470
+ // สร้าง HTML สำหรับปุ่ม
471
+ generateButtonHTML(button) {
472
+ const hotkey = button.hotkey ? `title="${button.tooltip || button.name} (${button.hotkey})"` : `title="${button.tooltip || button.name}"`;
473
+
474
+ // เพิ่ม preview image ถ้ามี
475
+ const previewImageHTML = button.previewImage ?
476
+ `<div class="button-preview" style="background-image: url('${button.previewImage}'); background-size: cover; background-position: center; width: 40px; height: 30px; border-radius: 4px; margin-right: 8px;"></div>` : '';
477
+
478
+ return `
479
+ <button
480
+ class="project-button"
481
+ data-button-id="${button.id}"
482
+ data-project="${button.projectName}"
483
+ data-command="${button.command}"
484
+ style="background-color: ${button.color || '#718096'}; margin: 4px; padding: 8px 12px; border: none; border-radius: 6px; color: white; cursor: pointer; font-size: 14px; display: inline-flex; align-items: center; gap: 6px;"
485
+ ${hotkey}
486
+ ${!button.enabled ? 'disabled' : ''}
487
+ >
488
+ ${previewImageHTML}
489
+ <span>${button.icon || ''}</span>
490
+ <span>${button.name}</span>
491
+ </button>
492
+ `;
493
+ }
494
+
495
+ // สร้างภาพตัวอย่างแบบ SVG สำหรับปุ่ม
496
+ generateButtonPreviewSVG(projectType, projectName) {
497
+ const previewConfigs = {
498
+ 'executable_project': {
499
+ color: '#4A5568',
500
+ icon: '',
501
+ label: 'EXE'
502
+ },
503
+ 'batch_project': {
504
+ color: '#38A169',
505
+ icon: '',
506
+ label: 'BAT'
507
+ },
508
+ 'node': {
509
+ color: '#68D391',
510
+ icon: '',
511
+ label: 'NODE'
512
+ },
513
+ 'python': {
514
+ color: '#4FD1C7',
515
+ icon: '',
516
+ label: 'PY'
517
+ },
518
+ 'html': {
519
+ color: '#90CDF4',
520
+ icon: '',
521
+ label: 'WEB'
522
+ },
523
+ 'default': {
524
+ color: '#718096',
525
+ icon: '',
526
+ label: 'PLUGIN'
527
+ }
528
+ };
529
+
530
+ const config = previewConfigs[projectType] || previewConfigs['default'];
531
+
532
+ const svgContent = `
533
+ <svg width="100" height="80" xmlns="http://www.w3.org/2000/svg">
534
+ <rect width="100" height="80" fill="${config.color}" rx="4"/>
535
+ <text x="50" y="35" font-family="Arial" font-size="20" fill="white" text-anchor="middle">${config.icon}</text>
536
+ <text x="50" y="55" font-family="Arial" font-size="10" fill="#E2E8F0" text-anchor="middle">${config.label}</text>
537
+ <text x="50" y="70" font-family="Arial" font-size="8" fill="#CBD5E0" text-anchor="middle">${projectName.substring(0, 12)}</text>
538
+ </svg>
539
+ `;
540
+
541
+ return `data:image/svg+xml;base64,${Buffer.from(svgContent).toString('base64')}`;
542
+ }
543
+
544
+ // สร้างภาพตัวอย่างสำหรับปุ่มเก่าที่ยังไม่มี
545
+ generateMissingPreviews() {
546
+ const updated = [];
547
+
548
+ for (const [projectName, projectData] of this.buttonRegistry.entries()) {
549
+ if (!projectData.previewImage) {
550
+ const { projectInfo } = projectData;
551
+ const previewImage = this.generateButtonPreviewSVG(projectInfo.type, projectInfo.name);
552
+
553
+ // อัปเดตข้อมูลใน registry
554
+ projectData.previewImage = previewImage;
555
+ projectData.projectInfo.previewImage = previewImage;
556
+
557
+ // อัปเดตปุ่มทั้งหมด
558
+ projectData.buttons = projectData.buttons.map(button => ({
559
+ ...button,
560
+ previewImage: previewImage,
561
+ projectPreview: previewImage
562
+ }));
563
+
564
+ updated.push(projectName);
565
+ console.log(` Generated missing preview for: ${projectName}`);
566
+ }
567
+ }
568
+
569
+ if (updated.length > 0) {
570
+ console.log(` Updated ${updated.length} projects with missing previews`);
571
+ }
572
+
573
+ return updated;
574
+ }
575
+
576
+ // สร้าง HTML การ์ดโปรเจคแบบเต็ม (รวมภาพตัวอย่าง)
577
+ generateProjectCardHTML(projectData) {
578
+ const { projectInfo, buttons, previewImage } = projectData;
579
+
580
+ const cardPreviewImage = previewImage || this.generateButtonPreviewSVG(projectInfo.type, projectInfo.name);
581
+
582
+ const buttonsHTML = buttons.map(button => this.generateButtonHTML(button)).join('');
583
+
584
+ return `
585
+ <div class="project-card" data-project="${projectInfo.name}">
586
+ <div class="project-header">
587
+ <div class="project-preview">
588
+ <img src="${cardPreviewImage}" alt="Preview for ${projectInfo.name}" class="preview-image">
589
+ </div>
590
+ <div class="project-info">
591
+ <h3 class="project-title">${projectInfo.name}</h3>
592
+ <p class="project-type">${projectInfo.type}</p>
593
+ <p class="project-path">${projectInfo.path}</p>
594
+ </div>
595
+ </div>
596
+ <div class="project-buttons">
597
+ ${buttonsHTML}
598
+ </div>
599
+ </div>
600
+ `;
601
+ }
602
+
603
+ // ดึงข้อมูลปุ่มทั้งหมด
604
+ getAllButtons() {
605
+ return Array.from(this.buttonRegistry.values());
606
+ }
607
+
608
+ // ดึงปุ่มสำหรับโปรเจคเฉพาะ
609
+ getProjectButtons(projectName) {
610
+ const projectData = this.buttonRegistry.get(projectName);
611
+ return projectData ? projectData.buttons : [];
612
+ }
613
+
614
+ // รีเซ็ตระบบปุ่ม
615
+ reset() {
616
+ this.buttonRegistry.clear();
617
+ console.log(' Button registry reset');
618
+ }
619
+ }
620
+
621
+ module.exports = ButtonGenerator;
modules/cache-manager.js ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Cache Manager - ระบบจัดการ Cache
3
+ * Chahua Development Thailand
4
+ * CEO: Saharath C.
5
+ *
6
+ * Purpose: จัดการการ cache ข้อมูลเพื่อประสิทธิภาพ
7
+ */
8
+
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+
12
+ class CacheManager {
13
+ constructor(options = {}) {
14
+ this.config = {
15
+ defaultTTL: options.defaultTTL || 300, // 5 minutes
16
+ maxSize: options.maxSize || 1000, // Max 1000 items
17
+ persistPath: options.persistPath || './logs/cache',
18
+ enablePersistence: options.enablePersistence || false,
19
+ cleanupInterval: options.cleanupInterval || 60000, // 1 minute
20
+ compressionEnabled: options.compressionEnabled || false
21
+ };
22
+
23
+ this.cache = new Map();
24
+ this.accessTimes = new Map();
25
+ this.stats = {
26
+ hits: 0,
27
+ misses: 0,
28
+ sets: 0,
29
+ deletes: 0,
30
+ cleanups: 0
31
+ };
32
+
33
+ this.setupCleanupTimer();
34
+
35
+ if (this.config.enablePersistence) {
36
+ this.loadFromDisk();
37
+ }
38
+
39
+ console.log('Cache Manager initialized');
40
+ }
41
+
42
+ async set(key, value, options = {}) {
43
+ try {
44
+ const ttl = options.ttl || this.config.defaultTTL;
45
+ const expiry = Date.now() + (ttl * 1000);
46
+
47
+ const cacheItem = {
48
+ key,
49
+ value,
50
+ expiry,
51
+ size: this.calculateSize(value),
52
+ created: Date.now(),
53
+ accessed: Date.now(),
54
+ hits: 0
55
+ };
56
+
57
+ // Check if we need to make space
58
+ if (this.cache.size >= this.config.maxSize) {
59
+ this.evictLRU();
60
+ }
61
+
62
+ this.cache.set(key, cacheItem);
63
+ this.accessTimes.set(key, Date.now());
64
+ this.stats.sets++;
65
+
66
+ if (this.config.enablePersistence) {
67
+ await this.persistToDisk();
68
+ }
69
+
70
+ console.log(`Cache SET: ${key} (TTL: ${ttl}s)`);
71
+ return true;
72
+
73
+ } catch (error) {
74
+ console.error('Cache set error:', error.message);
75
+ return false;
76
+ }
77
+ }
78
+
79
+ async get(key) {
80
+ try {
81
+ const item = this.cache.get(key);
82
+
83
+ if (!item) {
84
+ this.stats.misses++;
85
+ console.log(`Cache MISS: ${key}`);
86
+ return null;
87
+ }
88
+
89
+ // Check if expired
90
+ if (Date.now() > item.expiry) {
91
+ this.cache.delete(key);
92
+ this.accessTimes.delete(key);
93
+ this.stats.misses++;
94
+ console.log(`Cache EXPIRED: ${key}`);
95
+ return null;
96
+ }
97
+
98
+ // Update access info
99
+ item.accessed = Date.now();
100
+ item.hits++;
101
+ this.accessTimes.set(key, Date.now());
102
+ this.stats.hits++;
103
+
104
+ console.log(`Cache HIT: ${key}`);
105
+ return item.value;
106
+
107
+ } catch (error) {
108
+ console.error('Cache get error:', error.message);
109
+ this.stats.misses++;
110
+ return null;
111
+ }
112
+ }
113
+
114
+ async delete(key) {
115
+ try {
116
+ const deleted = this.cache.delete(key);
117
+ this.accessTimes.delete(key);
118
+
119
+ if (deleted) {
120
+ this.stats.deletes++;
121
+ console.log(`Cache DELETE: ${key}`);
122
+
123
+ if (this.config.enablePersistence) {
124
+ await this.persistToDisk();
125
+ }
126
+ }
127
+
128
+ return deleted;
129
+
130
+ } catch (error) {
131
+ console.error('Cache delete error:', error.message);
132
+ return false;
133
+ }
134
+ }
135
+
136
+ async clear() {
137
+ try {
138
+ const size = this.cache.size;
139
+ this.cache.clear();
140
+ this.accessTimes.clear();
141
+
142
+ if (this.config.enablePersistence) {
143
+ await this.persistToDisk();
144
+ }
145
+
146
+ console.log(`Cache CLEARED: ${size} items removed`);
147
+ return true;
148
+
149
+ } catch (error) {
150
+ console.error('Cache clear error:', error.message);
151
+ return false;
152
+ }
153
+ }
154
+
155
+ has(key) {
156
+ const item = this.cache.get(key);
157
+ if (!item) return false;
158
+
159
+ // Check if expired
160
+ if (Date.now() > item.expiry) {
161
+ this.cache.delete(key);
162
+ this.accessTimes.delete(key);
163
+ return false;
164
+ }
165
+
166
+ return true;
167
+ }
168
+
169
+ keys() {
170
+ const validKeys = [];
171
+ const now = Date.now();
172
+
173
+ for (const [key, item] of this.cache.entries()) {
174
+ if (now <= item.expiry) {
175
+ validKeys.push(key);
176
+ }
177
+ }
178
+
179
+ return validKeys;
180
+ }
181
+
182
+ size() {
183
+ this.cleanup(); // Clean expired items first
184
+ return this.cache.size;
185
+ }
186
+
187
+ evictLRU() {
188
+ // Find least recently used item
189
+ let oldestKey = null;
190
+ let oldestTime = Date.now();
191
+
192
+ for (const [key, time] of this.accessTimes.entries()) {
193
+ if (time < oldestTime) {
194
+ oldestTime = time;
195
+ oldestKey = key;
196
+ }
197
+ }
198
+
199
+ if (oldestKey) {
200
+ this.cache.delete(oldestKey);
201
+ this.accessTimes.delete(oldestKey);
202
+ console.log(`Cache LRU EVICTED: ${oldestKey}`);
203
+ }
204
+ }
205
+
206
+ cleanup() {
207
+ const now = Date.now();
208
+ let cleanedCount = 0;
209
+
210
+ for (const [key, item] of this.cache.entries()) {
211
+ if (now > item.expiry) {
212
+ this.cache.delete(key);
213
+ this.accessTimes.delete(key);
214
+ cleanedCount++;
215
+ }
216
+ }
217
+
218
+ if (cleanedCount > 0) {
219
+ this.stats.cleanups++;
220
+ console.log(`Cache CLEANUP: ${cleanedCount} expired items removed`);
221
+ }
222
+
223
+ return cleanedCount;
224
+ }
225
+
226
+ setupCleanupTimer() {
227
+ this.cleanupTimer = setInterval(() => {
228
+ this.cleanup();
229
+ }, this.config.cleanupInterval);
230
+ }
231
+
232
+ stopCleanupTimer() {
233
+ if (this.cleanupTimer) {
234
+ clearInterval(this.cleanupTimer);
235
+ this.cleanupTimer = null;
236
+ }
237
+ }
238
+
239
+ calculateSize(value) {
240
+ try {
241
+ return JSON.stringify(value).length;
242
+ } catch (error) {
243
+ return 0;
244
+ }
245
+ }
246
+
247
+ async persistToDisk() {
248
+ try {
249
+ const cacheDir = path.dirname(this.config.persistPath);
250
+ if (!fs.existsSync(cacheDir)) {
251
+ fs.mkdirSync(cacheDir, { recursive: true });
252
+ }
253
+
254
+ const cacheData = {
255
+ timestamp: Date.now(),
256
+ cache: Array.from(this.cache.entries()),
257
+ accessTimes: Array.from(this.accessTimes.entries()),
258
+ stats: this.stats
259
+ };
260
+
261
+ fs.writeFileSync(this.config.persistPath, JSON.stringify(cacheData));
262
+
263
+ } catch (error) {
264
+ console.error('Cache persist error:', error.message);
265
+ }
266
+ }
267
+
268
+ loadFromDisk() {
269
+ try {
270
+ if (!fs.existsSync(this.config.persistPath)) {
271
+ return;
272
+ }
273
+
274
+ const data = JSON.parse(fs.readFileSync(this.config.persistPath, 'utf8'));
275
+
276
+ // Restore cache
277
+ this.cache = new Map(data.cache || []);
278
+ this.accessTimes = new Map(data.accessTimes || []);
279
+ this.stats = { ...this.stats, ...data.stats };
280
+
281
+ // Clean expired items
282
+ this.cleanup();
283
+
284
+ console.log('Cache loaded from disk');
285
+
286
+ } catch (error) {
287
+ console.error('Cache load error:', error.message);
288
+ }
289
+ }
290
+
291
+ getStats() {
292
+ const totalRequests = this.stats.hits + this.stats.misses;
293
+ const hitRate = totalRequests > 0 ? Math.round((this.stats.hits / totalRequests) * 100) : 0;
294
+
295
+ return {
296
+ size: this.cache.size,
297
+ hitRate: `${hitRate}%`,
298
+ totalHits: this.stats.hits,
299
+ totalMisses: this.stats.misses,
300
+ totalSets: this.stats.sets,
301
+ totalDeletes: this.stats.deletes,
302
+ totalCleanups: this.stats.cleanups,
303
+ totalRequests
304
+ };
305
+ }
306
+
307
+ getDetailedStats() {
308
+ const stats = this.getStats();
309
+ const items = [];
310
+
311
+ for (const [key, item] of this.cache.entries()) {
312
+ items.push({
313
+ key,
314
+ size: item.size,
315
+ hits: item.hits,
316
+ created: new Date(item.created).toISOString(),
317
+ accessed: new Date(item.accessed).toISOString(),
318
+ expiresIn: Math.max(0, Math.round((item.expiry - Date.now()) / 1000))
319
+ });
320
+ }
321
+
322
+ // Sort by most accessed
323
+ items.sort((a, b) => b.hits - a.hits);
324
+
325
+ return {
326
+ ...stats,
327
+ items: items.slice(0, 10) // Top 10 most accessed
328
+ };
329
+ }
330
+
331
+ exportCache() {
332
+ const exportData = {
333
+ exportTime: new Date().toISOString(),
334
+ config: this.config,
335
+ stats: this.getStats(),
336
+ items: Array.from(this.cache.entries()).map(([key, item]) => ({
337
+ key,
338
+ value: item.value,
339
+ created: new Date(item.created).toISOString(),
340
+ accessed: new Date(item.accessed).toISOString(),
341
+ hits: item.hits,
342
+ size: item.size
343
+ }))
344
+ };
345
+
346
+ return exportData;
347
+ }
348
+ }
349
+
350
+ module.exports = CacheManager;
modules/callback-hub.js ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Chahua Development Thailand
3
+ * บริษัทชาหัวประเทศไทย
4
+ * CEO: Saharath C.
5
+ * www.chahuadev.com
6
+ * chahuadev@gmail.com
7
+ *
8
+ * /**
9
+ * HUB - Central Event Hub (Pub/Sub System) V.11.0.0
10
+ *
11
+ * ศูนย์กลางการสื่อสารระหว่างโมดูลทั้งหมดในแอปพลิเคชัน
12
+ * ทำงานในรูปแบบ Publish/Subscribe เพื่อลดการพึ่งพากัน (Decoupling)
13
+ *
14
+ * Features:
15
+ * on(event, fn): ลงทะเบียนเพื่อ "ฟัง" เหตุการณ์
16
+ * emit(event, data): "ส่ง" เหตุการณ์ออกไปให้ผู้ฟังทั้งหมด
17
+ * once(event, fn): ลงทะเบียนฟังเหตุการณ์แค่ครั้งเดียวแล้วลบออก
18
+ * off(event, fn): ยกเลิกการฟังเหตุการณ์
19
+ * emitAsync(event, data): emit แบบรอให้ callback ที่เป็น async ทำงานจนเสร็จ
20
+ * Wildcard Listener ('*'): ดักฟังทุกเหตุการณ์ที่เกิดขึ้นใน Hub
21
+ *
22
+ * by Chahuadev Studio V.11.0.0 Enterprise Architecture
23
+ */
24
+
25
+ class CallbackHub {
26
+ constructor() {
27
+ this.handlers = {};
28
+ this.debug_mode = process.env.HUB_DEBUG === 'true' || false;
29
+
30
+ console.log(' Event Hub initialized - Pub/Sub System V.11.0.0');
31
+ }
32
+
33
+ /**
34
+ * ลงทะเบียนฟังก์ชัน (callback) เพื่อรอฟังเหตุการณ์ (event)
35
+ * @param {string} eventName - ชื่อเหตุการณ์ที่ต้องการฟัง (เช่น 'license.loaded' หรือ '*' เพื่อฟังทุกอย่าง)
36
+ * @param {Function} callback - ฟังก์ชันที่จะถูกเรียกใช้เมื่อมีเหตุการณ์เกิดขึ้น
37
+ */
38
+ on(eventName, callback) {
39
+ if (!this.handlers[eventName]) {
40
+ this.handlers[eventName] = [];
41
+ }
42
+ this.handlers[eventName].push(callback);
43
+
44
+ if (this.debug_mode) {
45
+ console.log(` Hub: Listener registered for "${eventName}" (${this.handlers[eventName].length} total)`);
46
+ }
47
+ }
48
+
49
+ /**
50
+ * ลงทะเบียนฟังก์ชันเพื่อรอฟังเหตุการณ์แค่ "ครั้งเดียว"
51
+ * หลังจากทำงานเสร็จ callback จะถูกลบออกไปโดยอัตโนมัติ
52
+ * @param {string} eventName - ชื่อเหตุการณ์
53
+ * @param {Function} callback - ฟังก์ชันที่จะถูกเรียกใช้
54
+ */
55
+ once(eventName, callback) {
56
+ const onceWrapper = (data) => {
57
+ callback(data);
58
+ this.off(eventName, onceWrapper);
59
+ if (this.debug_mode) {
60
+ console.log(` Hub: Once listener for "${eventName}" executed and removed`);
61
+ }
62
+ };
63
+ this.on(eventName, onceWrapper);
64
+ }
65
+
66
+ /**
67
+ * ยกเลิกการลงทะเบียน callback
68
+ * @param {string} eventName - ชื่อเหตุการณ์
69
+ * @param {Function} callback - ฟังก์ชันที่ต้องการยกเลิก
70
+ */
71
+ off(eventName, callback) {
72
+ if (this.handlers[eventName]) {
73
+ const initialLength = this.handlers[eventName].length;
74
+ this.handlers[eventName] = this.handlers[eventName].filter(cb => cb !== callback);
75
+
76
+ if (this.debug_mode && this.handlers[eventName].length < initialLength) {
77
+ console.log(` Hub: Listener removed from "${eventName}" (${this.handlers[eventName].length} remaining)`);
78
+ }
79
+ }
80
+ }
81
+
82
+ /**
83
+ * ส่งสัญญาณ (emit) เหตุการณ์ออกไป
84
+ * จะเรียก callback ทุกตัวที่ลงทะเบียนไว้กับ event นี้แบบ non-blocking
85
+ * @param {string} eventName - ชื่อเหตุการณ์
86
+ * @param {*} [data] - ข้อมูลที่ต้องการส่งไปกับเหตุการณ์
87
+ */
88
+ emit(eventName, data) {
89
+ let listenersNotified = 0;
90
+
91
+ // ส่งให้ผู้ฟังที่เจาะจง event นี้
92
+ if (this.handlers[eventName]) {
93
+ this.handlers[eventName].forEach(fn => {
94
+ try {
95
+ fn(data);
96
+ listenersNotified++;
97
+ } catch (err) {
98
+ console.error(` Hub: Callback error on "${eventName}":`, err);
99
+ }
100
+ });
101
+ }
102
+
103
+ // ส่งให้ผู้ฟังแบบ Wildcard ('*') ด้วย
104
+ if (this.handlers['*']) {
105
+ this.handlers['*'].forEach(fn => {
106
+ try {
107
+ fn({ event: eventName, data: data });
108
+ listenersNotified++;
109
+ } catch (err) {
110
+ console.error(` Hub: Wildcard callback error on "${eventName}":`, err);
111
+ }
112
+ });
113
+ }
114
+
115
+ if (this.debug_mode) {
116
+ console.log(` Hub: Event "${eventName}" emitted to ${listenersNotified} listener(s)`);
117
+ }
118
+ }
119
+
120
+ /**
121
+ * ส่งสัญญาณ (emit) เหตุการณ์และรอให้ callback ที่เป็น async ทำงานจนเสร็จ
122
+ * @param {string} eventName - ชื่อเหตุการณ์
123
+ * @param {*} [data] - ข้อมูลที่ต้องการส่งไปกับเหตุการณ์
124
+ * @returns {Promise<void>}
125
+ */
126
+ async emitAsync(eventName, data) {
127
+ const promises = [];
128
+
129
+ // ผู้ฟังที่เจาะจง event
130
+ if (this.handlers[eventName]) {
131
+ this.handlers[eventName].forEach(fn => {
132
+ promises.push(Promise.resolve().then(() => fn(data)).catch(err => {
133
+ console.error(` Hub: Async callback error on "${eventName}":`, err);
134
+ }));
135
+ });
136
+ }
137
+
138
+ // ผู้ฟังแบบ Wildcard ('*')
139
+ if (this.handlers['*']) {
140
+ this.handlers['*'].forEach(fn => {
141
+ promises.push(Promise.resolve().then(() => fn({ event: eventName, data: data })).catch(err => {
142
+ console.error(` Hub: Async wildcard callback error on "${eventName}":`, err);
143
+ }));
144
+ });
145
+ }
146
+
147
+ if (this.debug_mode) {
148
+ console.log(` Hub: Async event "${eventName}" emitted to ${promises.length} listener(s)`);
149
+ }
150
+
151
+ await Promise.all(promises);
152
+ }
153
+
154
+ /**
155
+ * แสดงรายชื่อ event ทั้งหมดที่มีการลงทะเบียนไว้
156
+ */
157
+ debug() {
158
+ console.log(' Hub: Registered Event Handlers:');
159
+ for (const eventName in this.handlers) {
160
+ console.log(` - ${eventName} (${this.handlers[eventName].length} listener(s))`);
161
+ }
162
+
163
+ const totalEvents = Object.keys(this.handlers).length;
164
+ const totalListeners = Object.values(this.handlers).reduce((sum, handlers) => sum + handlers.length, 0);
165
+ console.log(` Hub: Total ${totalEvents} events, ${totalListeners} listeners`);
166
+ }
167
+
168
+ /**
169
+ * เปิด/ปิด debug mode
170
+ * @param {boolean} enabled - เปิดหรือปิด debug mode
171
+ */
172
+ setDebugMode(enabled) {
173
+ this.debug_mode = enabled;
174
+ console.log(` Hub: Debug mode ${enabled ? 'ENABLED' : 'DISABLED'}`);
175
+ }
176
+
177
+ /**
178
+ * ลบ listeners ทั้งหมดของ event หนึ่งๆ
179
+ * @param {string} eventName - ชื่อเหตุการณ์ที่ต้องการลบ listeners
180
+ */
181
+ removeAllListeners(eventName) {
182
+ if (this.handlers[eventName]) {
183
+ const count = this.handlers[eventName].length;
184
+ delete this.handlers[eventName];
185
+ if (this.debug_mode) {
186
+ console.log(` Hub: Removed all ${count} listeners for "${eventName}"`);
187
+ }
188
+ }
189
+ }
190
+
191
+ /**
192
+ * ลบ listeners ทั้งหมด
193
+ */
194
+ removeAll() {
195
+ const eventCount = Object.keys(this.handlers).length;
196
+ this.handlers = {};
197
+ console.log(` Hub: Removed all listeners (${eventCount} events cleared)`);
198
+ }
199
+ }
200
+
201
+ // สร้างและ Export เป็น Singleton Instance เพื่อให้ทุกไฟล์ได้ใช้ตัวเดียวกัน
202
+ module.exports = new CallbackHub();
modules/callback-logger.js ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Chahua Development Thailand
3
+ บริษัทชาหัวประเทศไทย
4
+ CEO: Saharath C.
5
+ www.chahuadev.com
6
+ chahuadev@gmail.com
7
+
8
+ /**
9
+ * Centralized Callback Logger V.11.0.0
10
+ *
11
+ * ระบบจัดการ Log และ Event กลางแบบ Non-Blocking
12
+ *
13
+ * Features:
14
+ * Log Levels (info, warn, error, debug)
15
+ * Console Output with Colors (เพื่อง่ายต่อการอ่าน)
16
+ * File Logging (บันทึก Log ลงไฟล์ logs/system.log)
17
+ * Non-Blocking (ไม่รบกวนการทำงานหลักของแอปพลิเคชัน)
18
+ * Singleton Pattern (ทุกโมดูลใช้ instance เดียวกัน)
19
+ * Timestamp & Standardized Formatting
20
+ *
21
+ * by Chahuadev Studio V.11.0.0 Enterprise Architecture
22
+ */
23
+
24
+ const fs = require('fs');
25
+ const path = require('path');
26
+ const util = require('util');
27
+
28
+ class CallbackLogger {
29
+ constructor() {
30
+ this.logDirectory = path.join(__dirname, '../logs');
31
+ this.logFilePath = path.join(this.logDirectory, 'system.log');
32
+ this.inMemoryLogs = [];
33
+ this.maxMemoryLogs = 200; // เก็บ Log ในหน่วยความจำสูงสุด 200 รายการ
34
+
35
+ this.ensureLogDirectory();
36
+
37
+ // สร้าง Stream สำหรับเขียนไฟล์แบบ Append (เขียนต่อท้าย)
38
+ this.logStream = fs.createWriteStream(this.logFilePath, { flags: 'a' });
39
+
40
+ // สีสำหรับ Console Log
41
+ this.colors = {
42
+ info: '\x1b[36m', // Cyan
43
+ warn: '\x1b[33m', // Yellow
44
+ error: '\x1b[31m', // Red
45
+ debug: '\x1b[35m', // Magenta
46
+ reset: '\x1b[0m' // Reset color
47
+ };
48
+
49
+ this.info('logger.init', { message: 'CallbackLogger has started successfully.' });
50
+ }
51
+
52
+ /**
53
+ * ตรวจสอบว่าโฟลเดอร์ logs มีอยู่จริงหรือไม่ ถ้าไม่มีให้สร้างใหม่
54
+ */
55
+ ensureLogDirectory() {
56
+ if (!fs.existsSync(this.logDirectory)) {
57
+ try {
58
+ fs.mkdirSync(this.logDirectory, { recursive: true });
59
+ console.log(`[Logger] Created log directory at: ${this.logDirectory}`);
60
+ } catch (error) {
61
+ console.error(`[Logger] Failed to create log directory:`, error);
62
+ }
63
+ }
64
+ }
65
+
66
+ /**
67
+ * ฟังก์ชันหลักในการ Log (เป็น private)
68
+ * @param {'info' | 'warn' | 'error' | 'debug'} level ระดับของ Log
69
+ * @param {string} eventName ชื่อของ Event
70
+ * @param {object | string} data ข้อมูลที่ต้องการ Log
71
+ */
72
+ _log(level, eventName, data) {
73
+ const timestamp = new Date().toISOString();
74
+ const icons = { info: '', warn: '', error: '', debug: '' };
75
+ const icon = icons[level] || '';
76
+
77
+ // จัดรูปแบบข้อมูลให้สวยงาม
78
+ const formattedData = typeof data === 'object' ? util.inspect(data, { depth: null, colors: false }) : data;
79
+ const formattedDataColor = typeof data === 'object' ? util.inspect(data, { depth: null, colors: true }) : data;
80
+
81
+ // สร้างข้อความ Log
82
+ const logMessageForFile = `[${timestamp}] [${level.toUpperCase()}] [${eventName}] ${formattedData}`;
83
+ const logMessageForConsole = `${this.colors[level]}[${timestamp}] ${icon} [${level.toUpperCase()}] [${eventName}]${this.colors.reset} ${formattedDataColor}`;
84
+
85
+ // 1. แสดงผลใน Console
86
+ console.log(logMessageForConsole);
87
+
88
+ // 2. เขียนลงไฟล์
89
+ this.logStream.write(logMessageForFile + '\n', (err) => {
90
+ if (err) console.error('[Logger] Failed to write to log file:', err);
91
+ });
92
+
93
+ // 3. เก็บในหน่วยความจำ (สำหรับเรียกดูย้อนหลัง)
94
+ this.inMemoryLogs.push(logMessageForFile);
95
+ if (this.inMemoryLogs.length > this.maxMemoryLogs) {
96
+ this.inMemoryLogs.shift(); // ลบอันเก่าสุดออก
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Log ข้อมูลทั่วไป
102
+ * @param {string} eventName ชื่อ Event (เช่น 'i18n.loaded')
103
+ * @param {object|string} data ข้อมูล
104
+ */
105
+ info(eventName, data) {
106
+ this._log('info', eventName, data);
107
+ }
108
+
109
+ /**
110
+ * Log คำเตือน
111
+ * @param {string} eventName ชื่อ Event (เช่น 'license.expiring')
112
+ * @param {object|string} data ข้อมูล
113
+ */
114
+ warn(eventName, data) {
115
+ this._log('warn', eventName, data);
116
+ }
117
+
118
+ /**
119
+ * Log ข้อผิดพลาด
120
+ * @param {string} eventName ชื่อ Event (เช่น 'database.connection.failed')
121
+ * @param {object|string} data ข้อมูล
122
+ */
123
+ error(eventName, data) {
124
+ this._log('error', eventName, data);
125
+ }
126
+
127
+ /**
128
+ * Log ข้อมูลสำหรับการดีบัก
129
+ * @param {string} eventName ชื่อ Event (เช่น 'user.data.raw')
130
+ * @param {object|string} data ข้อมูล
131
+ */
132
+ debug(eventName, data) {
133
+ this._log('debug', eventName, data);
134
+ }
135
+
136
+ /**
137
+ * ดึง Log ล่าสุดจากหน่วยความจำ
138
+ * @param {number} limit จำนวนที่ต้องการ
139
+ * @returns {string[]}
140
+ */
141
+ getRecentLogs(limit = 20) {
142
+ return this.inMemoryLogs.slice(-limit);
143
+ }
144
+ }
145
+
146
+ // สร้างและ Export เป็น Singleton Instance เพื่อให้ทุกไฟล์ได้ใช้ตัวเดียวกัน
147
+ module.exports = new CallbackLogger();
modules/cli.js ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Chahuadev Framework - CLI Interface
5
+ * Chahua Development Thailand
6
+ * CEO: Saharath C.
7
+ *
8
+ * Purpose: Command Line Interface สำหรับ automation และ integration
9
+ */
10
+
11
+ const { program } = require('commander');
12
+ const path = require('path');
13
+ const fs = require('fs');
14
+
15
+ // Import core modules (same as app.js)
16
+ const ValidationGateway = require('./validation_gateway');
17
+ const ContextManager = require('./modules/context-manager');
18
+ const ErrorHandler = require('./modules/error-handler');
19
+ const Executor = require('./modules/executor');
20
+ const SystemDetector = require('./modules/system-detector');
21
+ const PluginManager = require('./modules/plugin-manager');
22
+
23
+ class ChahuadevCLI {
24
+ constructor() {
25
+ this.validationGateway = new ValidationGateway();
26
+ this.contextManager = new ContextManager();
27
+ this.errorHandler = new ErrorHandler();
28
+ this.executor = new Executor();
29
+ this.systemDetector = new SystemDetector();
30
+ this.pluginManager = new PluginManager();
31
+
32
+ console.log(' Chahuadev CLI initialized');
33
+ }
34
+
35
+ async initialize() {
36
+ try {
37
+ // Load plugins
38
+ await this.pluginManager.loadPlugins();
39
+ console.log(' CLI ready with all modules loaded');
40
+ } catch (error) {
41
+ console.error(' CLI initialization failed:', error.message);
42
+ process.exit(1);
43
+ }
44
+ }
45
+
46
+ async executeCommand(command, options = {}) {
47
+ const context = this.contextManager.create('cli-execution', {
48
+ command,
49
+ options,
50
+ timestamp: new Date().toISOString(),
51
+ cwd: process.cwd()
52
+ });
53
+
54
+ try {
55
+ // Validate request
56
+ const validation = await this.validationGateway.validateRequest({
57
+ command,
58
+ ...options
59
+ });
60
+
61
+ if (!validation.success) {
62
+ throw new Error(`Security validation failed: ${validation.error}`);
63
+ }
64
+
65
+ // Execute through executor
66
+ const result = await this.executor.execute({
67
+ command,
68
+ project: options.project || process.cwd(),
69
+ strategy: options.strategy
70
+ }, context);
71
+
72
+ return result;
73
+
74
+ } catch (error) {
75
+ this.errorHandler.handle(error, context.id);
76
+ throw error;
77
+ }
78
+ }
79
+
80
+ async scanProject(projectPath) {
81
+ try {
82
+ const fullPath = path.resolve(projectPath);
83
+
84
+ if (!fs.existsSync(fullPath)) {
85
+ throw new Error(`Project path does not exist: ${fullPath}`);
86
+ }
87
+
88
+ const detection = await this.systemDetector.detectProject(fullPath);
89
+
90
+ console.log('\n Project Scan Results:');
91
+ console.log('========================');
92
+ console.log('Project Path:', fullPath);
93
+ console.log('Detected Type:', detection.type);
94
+ console.log('Confidence:', `${(detection.confidence * 100).toFixed(1)}%`);
95
+ console.log('Strategy:', detection.strategy);
96
+
97
+ if (detection.details) {
98
+ console.log('\n Details:');
99
+ Object.entries(detection.details).forEach(([key, value]) => {
100
+ console.log(` ${key}: ${value}`);
101
+ });
102
+ }
103
+
104
+ return detection;
105
+
106
+ } catch (error) {
107
+ console.error(' Project scan failed:', error.message);
108
+ throw error;
109
+ }
110
+ }
111
+
112
+ async listPlugins() {
113
+ try {
114
+ const plugins = this.pluginManager.getAvailablePlugins();
115
+
116
+ console.log('\n Available Plugins:');
117
+ console.log('====================');
118
+
119
+ if (plugins.length === 0) {
120
+ console.log('No plugins loaded');
121
+ return;
122
+ }
123
+
124
+ plugins.forEach(plugin => {
125
+ console.log(` ${plugin.name}`);
126
+ console.log(` File: ${plugin.filename}`);
127
+ console.log(` Status: ${plugin.status}`);
128
+ console.log(` Loaded: ${plugin.loadedAt.toISOString()}`);
129
+ if (plugin.metadata.description) {
130
+ console.log(` Description: ${plugin.metadata.description}`);
131
+ }
132
+ console.log('');
133
+ });
134
+
135
+ return plugins;
136
+
137
+ } catch (error) {
138
+ console.error(' Failed to list plugins:', error.message);
139
+ throw error;
140
+ }
141
+ }
142
+
143
+ async executePlugin(pluginName, data) {
144
+ try {
145
+ const result = await this.pluginManager.executePlugin(pluginName, data);
146
+
147
+ if (result.success) {
148
+ console.log(` Plugin ${pluginName} executed successfully`);
149
+ console.log('Result:', JSON.stringify(result.result, null, 2));
150
+ } else {
151
+ console.error(` Plugin ${pluginName} failed: ${result.error}`);
152
+ }
153
+
154
+ return result;
155
+
156
+ } catch (error) {
157
+ console.error(' Plugin execution failed:', error.message);
158
+ throw error;
159
+ }
160
+ }
161
+
162
+ async getStatus() {
163
+ const status = {
164
+ framework: 'Chahuadev Framework',
165
+ version: '1.0.0',
166
+ interface: 'CLI',
167
+ timestamp: new Date().toISOString(),
168
+ modules: {
169
+ validationGateway: !!this.validationGateway,
170
+ contextManager: !!this.contextManager,
171
+ errorHandler: !!this.errorHandler,
172
+ executor: !!this.executor,
173
+ systemDetector: !!this.systemDetector,
174
+ pluginManager: !!this.pluginManager
175
+ },
176
+ plugins: this.pluginManager.getPluginStats()
177
+ };
178
+
179
+ console.log('\n System Status:');
180
+ console.log('================');
181
+ console.log(JSON.stringify(status, null, 2));
182
+
183
+ return status;
184
+ }
185
+ }
186
+
187
+ // CLI Commands Setup
188
+ async function setupCommands() {
189
+ const cli = new ChahuadevCLI();
190
+ await cli.initialize();
191
+
192
+ program
193
+ .name('chahuadev')
194
+ .description('Chahuadev Framework CLI')
195
+ .version('1.0.0');
196
+
197
+ // Execute command
198
+ program
199
+ .command('execute <command>')
200
+ .description('Execute a command through the framework')
201
+ .option('-p, --project <path>', 'Project path', process.cwd())
202
+ .option('-s, --strategy <strategy>', 'Force specific strategy')
203
+ .action(async (command, options) => {
204
+ try {
205
+ console.log(` Executing: ${command}`);
206
+ const result = await cli.executeCommand(command, options);
207
+ console.log(' Execution completed');
208
+ console.log(JSON.stringify(result, null, 2));
209
+ } catch (error) {
210
+ console.error(' Execution failed:', error.message);
211
+ process.exit(1);
212
+ }
213
+ });
214
+
215
+ // Scan project
216
+ program
217
+ .command('scan <path>')
218
+ .description('Scan project and detect type')
219
+ .action(async (projectPath) => {
220
+ try {
221
+ await cli.scanProject(projectPath);
222
+ } catch (error) {
223
+ console.error(' Scan failed:', error.message);
224
+ process.exit(1);
225
+ }
226
+ });
227
+
228
+ // Plugin management
229
+ program
230
+ .command('plugins')
231
+ .description('List available plugins')
232
+ .action(async () => {
233
+ try {
234
+ await cli.listPlugins();
235
+ } catch (error) {
236
+ console.error(' Failed to list plugins:', error.message);
237
+ process.exit(1);
238
+ }
239
+ });
240
+
241
+ program
242
+ .command('plugin <name>')
243
+ .description('Execute a plugin')
244
+ .option('-d, --data <data>', 'JSON data to pass to plugin', '{}')
245
+ .action(async (name, options) => {
246
+ try {
247
+ const data = JSON.parse(options.data);
248
+ await cli.executePlugin(name, data);
249
+ } catch (error) {
250
+ console.error(' Plugin execution failed:', error.message);
251
+ process.exit(1);
252
+ }
253
+ });
254
+
255
+ // Status
256
+ program
257
+ .command('status')
258
+ .description('Show system status')
259
+ .action(async () => {
260
+ try {
261
+ await cli.getStatus();
262
+ } catch (error) {
263
+ console.error(' Failed to get status:', error.message);
264
+ process.exit(1);
265
+ }
266
+ });
267
+
268
+ // Help command
269
+ program
270
+ .command('help')
271
+ .description('Show help information')
272
+ .action(() => {
273
+ console.log('\n Chahuadev Framework CLI');
274
+ console.log('===========================');
275
+ console.log('Usage examples:');
276
+ console.log('');
277
+ console.log(' chahuadev execute "npm test" # Execute npm test');
278
+ console.log(' chahuadev execute "node app.js" -p ./src # Execute in specific project');
279
+ console.log(' chahuadev scan ./my-project # Scan project type');
280
+ console.log(' chahuadev plugins # List available plugins');
281
+ console.log(' chahuadev plugin zip-compressor # Execute plugin');
282
+ console.log(' chahuadev status # Show system status');
283
+ console.log('');
284
+ program.help();
285
+ });
286
+
287
+ return { cli, program };
288
+ }
289
+
290
+ // Main execution
291
+ if (require.main === module) {
292
+ setupCommands().then(({ program }) => {
293
+ // Parse command line arguments
294
+ program.parse();
295
+ }).catch(error => {
296
+ console.error(' CLI setup failed:', error.message);
297
+ process.exit(1);
298
+ });
299
+ }
300
+
301
+ module.exports = { ChahuadevCLI, setupCommands };
modules/context-manager.js ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Chahuadev Framework - Context Manager Module
3
+ * Pipeline Context Object Management & Data Flow Tracking
4
+ *
5
+ * Chahua Development Thailand
6
+ * CEO: Saharath C.
7
+ * www.chahuadev.com
8
+ */
9
+
10
+ const crypto = require('crypto');
11
+
12
+ class ContextManager {
13
+ constructor() {
14
+ this.contexts = new Map(); // Store active contexts
15
+ console.log(' Context Manager initialized');
16
+ }
17
+
18
+ /**
19
+ * Create new pipeline context
20
+ * @param {string} pipelineType - Type of pipeline (e.g., 'execution', 'api', 'validation')
21
+ * @param {Object} initialData - Initial request data
22
+ * @returns {Object} Pipeline context object
23
+ */
24
+ create(pipelineType = 'execution', initialData = {}) {
25
+ const pipelineId = this.generatePipelineId();
26
+ const timestamp = new Date().toISOString();
27
+
28
+ const context = {
29
+ // Pipeline identification
30
+ pipelineId: pipelineId,
31
+ pipelineType: pipelineType,
32
+ timestamp: timestamp,
33
+
34
+ // Request information
35
+ request: {
36
+ command: initialData.command || '',
37
+ originalData: initialData || {},
38
+ parameters: this.parseParameters(initialData),
39
+ source: initialData.source || 'unknown'
40
+ },
41
+
42
+ // System information (will be populated by system-detector)
43
+ systemInfo: {
44
+ detectedType: null,
45
+ projectPath: null,
46
+ strategy: null,
47
+ dependencies: [],
48
+ environment: process.env.NODE_ENV || 'development'
49
+ },
50
+
51
+ // Security context
52
+ security: {
53
+ keyHash: null,
54
+ permissionLevel: 'basic',
55
+ userSession: null,
56
+ securityChecks: [],
57
+ validatedAt: null
58
+ },
59
+
60
+ // Execution tracking
61
+ execution: {
62
+ strategy: null,
63
+ startTime: null,
64
+ endTime: null,
65
+ status: 'pending', // 'pending', 'running', 'completed', 'failed'
66
+ exitCode: null,
67
+ output: null
68
+ },
69
+
70
+ // Step tracking
71
+ steps: [],
72
+
73
+ // Performance metrics
74
+ performance: {
75
+ totalTime: null,
76
+ memoryUsage: process.memoryUsage(),
77
+ cacheHit: false,
78
+ stepTimings: {}
79
+ },
80
+
81
+ // Error tracking
82
+ error: null,
83
+
84
+ // Metadata
85
+ metadata: {
86
+ createdAt: timestamp,
87
+ updatedAt: timestamp,
88
+ version: '1.0.0',
89
+ framework: 'chahuadev'
90
+ }
91
+ };
92
+
93
+ // Store context for tracking
94
+ this.contexts.set(pipelineId, context);
95
+ console.log(` Context created: ${pipelineId} (${pipelineType})`);
96
+
97
+ return context;
98
+ }
99
+
100
+ /**
101
+ * Add step result to context
102
+ * @param {Object} context - Pipeline context
103
+ * @param {string} stepName - Name of the step
104
+ * @param {string} status - Step status ('started', 'completed', 'failed')
105
+ * @param {*} result - Step result data
106
+ * @returns {Object} Updated context
107
+ */
108
+ addStep(context, stepName, status, result = null) {
109
+ if (!context || !context.pipelineId) {
110
+ throw new Error('Invalid context provided');
111
+ }
112
+
113
+ const step = {
114
+ stepName: stepName,
115
+ timestamp: new Date().toISOString(),
116
+ status: status,
117
+ result: result,
118
+ duration: null
119
+ };
120
+
121
+ // Calculate duration if completing a step
122
+ if (status === 'completed' || status === 'failed') {
123
+ const startStep = context.steps.find(s =>
124
+ s.stepName === stepName && s.status === 'started'
125
+ );
126
+ if (startStep) {
127
+ step.duration = Date.now() - new Date(startStep.timestamp).getTime();
128
+ context.performance.stepTimings[stepName] = step.duration;
129
+ }
130
+ }
131
+
132
+ context.steps.push(step);
133
+ context.metadata.updatedAt = new Date().toISOString();
134
+
135
+ console.log(` Step added: ${stepName} (${status}) to ${context.pipelineId}`);
136
+ return context;
137
+ }
138
+
139
+ /**
140
+ * Update context security information
141
+ * @param {Object} context - Pipeline context
142
+ * @param {Object} securityData - Security validation data
143
+ * @returns {Object} Updated context
144
+ */
145
+ updateSecurity(context, securityData) {
146
+ if (!context || !context.pipelineId) {
147
+ throw new Error('Invalid context provided');
148
+ }
149
+
150
+ context.security = {
151
+ ...context.security,
152
+ ...securityData,
153
+ validatedAt: new Date().toISOString()
154
+ };
155
+
156
+ context.metadata.updatedAt = new Date().toISOString();
157
+ console.log(` Security updated for: ${context.pipelineId}`);
158
+
159
+ return context;
160
+ }
161
+
162
+ /**
163
+ * Update system information
164
+ * @param {Object} context - Pipeline context
165
+ * @param {Object} systemData - System detection data
166
+ * @returns {Object} Updated context
167
+ */
168
+ updateSystemInfo(context, systemData) {
169
+ if (!context || !context.pipelineId) {
170
+ throw new Error('Invalid context provided');
171
+ }
172
+
173
+ context.systemInfo = {
174
+ ...context.systemInfo,
175
+ ...systemData
176
+ };
177
+
178
+ context.metadata.updatedAt = new Date().toISOString();
179
+ console.log(` System info updated for: ${context.pipelineId}`);
180
+
181
+ return context;
182
+ }
183
+
184
+ /**
185
+ * Update execution status
186
+ * @param {Object} context - Pipeline context
187
+ * @param {string} status - Execution status
188
+ * @param {*} output - Execution output
189
+ * @param {number} exitCode - Exit code
190
+ * @returns {Object} Updated context
191
+ */
192
+ updateExecution(context, status, output = null, exitCode = null) {
193
+ if (!context || !context.pipelineId) {
194
+ throw new Error('Invalid context provided');
195
+ }
196
+
197
+ // Set start time when execution begins
198
+ if (status === 'running' && !context.execution.startTime) {
199
+ context.execution.startTime = new Date().toISOString();
200
+ }
201
+
202
+ // Set end time when execution completes or fails
203
+ if ((status === 'completed' || status === 'failed') && !context.execution.endTime) {
204
+ context.execution.endTime = new Date().toISOString();
205
+
206
+ // Calculate total time
207
+ if (context.execution.startTime) {
208
+ const startTime = new Date(context.execution.startTime).getTime();
209
+ const endTime = new Date(context.execution.endTime).getTime();
210
+ context.performance.totalTime = endTime - startTime;
211
+ }
212
+ }
213
+
214
+ context.execution.status = status;
215
+ if (output !== null) context.execution.output = output;
216
+ if (exitCode !== null) context.execution.exitCode = exitCode;
217
+
218
+ context.metadata.updatedAt = new Date().toISOString();
219
+ console.log(` Execution updated: ${status} for ${context.pipelineId}`);
220
+
221
+ return context;
222
+ }
223
+
224
+ /**
225
+ * Set error in context
226
+ * @param {Object} context - Pipeline context
227
+ * @param {Error|string} error - Error object or message
228
+ * @returns {Object} Updated context
229
+ */
230
+ setError(context, error) {
231
+ if (!context || !context.pipelineId) {
232
+ throw new Error('Invalid context provided');
233
+ }
234
+
235
+ const errorInfo = {
236
+ message: error.message || error,
237
+ stack: error.stack || null,
238
+ timestamp: new Date().toISOString(),
239
+ step: context.steps.length > 0 ? context.steps[context.steps.length - 1].stepName : 'unknown'
240
+ };
241
+
242
+ context.error = errorInfo;
243
+ context.execution.status = 'failed';
244
+ context.metadata.updatedAt = new Date().toISOString();
245
+
246
+ console.error(` Error set for ${context.pipelineId}:`, errorInfo.message);
247
+ return context;
248
+ }
249
+
250
+ /**
251
+ * Get context by pipeline ID
252
+ * @param {string} pipelineId - Pipeline ID
253
+ * @returns {Object|null} Context object or null if not found
254
+ */
255
+ get(pipelineId) {
256
+ return this.contexts.get(pipelineId) || null;
257
+ }
258
+
259
+ /**
260
+ * Remove context (cleanup)
261
+ * @param {string} pipelineId - Pipeline ID
262
+ * @returns {boolean} True if removed
263
+ */
264
+ remove(pipelineId) {
265
+ const removed = this.contexts.delete(pipelineId);
266
+ if (removed) {
267
+ console.log(` Context removed: ${pipelineId}`);
268
+ }
269
+ return removed;
270
+ }
271
+
272
+ /**
273
+ * Clear context by execution ID (alias for remove)
274
+ * @param {string} executionId - Execution ID
275
+ * @returns {boolean} True if removed
276
+ */
277
+ clearContext(executionId) {
278
+ return this.remove(executionId);
279
+ }
280
+
281
+ /**
282
+ * Create context object (for BaseStrategy compatibility)
283
+ * @param {Object} data - Context data
284
+ * @returns {Object} Context object
285
+ */
286
+ createContext(data) {
287
+ return data; // Return as-is since BaseStrategy creates its own context
288
+ }
289
+
290
+ /**
291
+ * Generate unique pipeline ID
292
+ * @private
293
+ * @returns {string} Pipeline ID
294
+ */
295
+ generatePipelineId() {
296
+ const timestamp = Date.now();
297
+ const random = crypto.randomBytes(4).toString('hex');
298
+ return `pipe_${timestamp}_${random}`;
299
+ }
300
+
301
+ /**
302
+ * Parse parameters from initial data
303
+ * @private
304
+ * @param {Object} data - Initial data
305
+ * @returns {Object} Parsed parameters
306
+ */
307
+ parseParameters(data) {
308
+ if (!data || typeof data !== 'object') {
309
+ return {};
310
+ }
311
+
312
+ // Extract common parameters
313
+ return {
314
+ timeout: data.timeout || 30000,
315
+ retry: data.retry || false,
316
+ maxRetries: data.maxRetries || 3,
317
+ silent: data.silent || false,
318
+ workingDir: data.workingDir || process.cwd()
319
+ };
320
+ }
321
+
322
+ /**
323
+ * Get all active contexts (for monitoring)
324
+ * @returns {Array} Array of context objects
325
+ */
326
+ getAll() {
327
+ return Array.from(this.contexts.values());
328
+ }
329
+
330
+ /**
331
+ * Clean up old contexts (older than specified minutes)
332
+ * @param {number} maxAgeMinutes - Maximum age in minutes
333
+ * @returns {number} Number of cleaned contexts
334
+ */
335
+ cleanup(maxAgeMinutes = 60) {
336
+ const cutoffTime = Date.now() - (maxAgeMinutes * 60 * 1000);
337
+ let cleaned = 0;
338
+
339
+ for (const [pipelineId, context] of this.contexts.entries()) {
340
+ const contextTime = new Date(context.metadata.createdAt).getTime();
341
+ if (contextTime < cutoffTime) {
342
+ this.contexts.delete(pipelineId);
343
+ cleaned++;
344
+ }
345
+ }
346
+
347
+ if (cleaned > 0) {
348
+ console.log(` Cleaned up ${cleaned} old contexts`);
349
+ }
350
+
351
+ return cleaned;
352
+ }
353
+
354
+ /**
355
+ * Get context manager status
356
+ * @returns {Object} Status information
357
+ */
358
+ getStatus() {
359
+ return {
360
+ activeContexts: this.contexts.size,
361
+ memoryUsage: process.memoryUsage(),
362
+ ready: true
363
+ };
364
+ }
365
+ }
366
+
367
+ // Export class (not singleton)
368
+ module.exports = ContextManager;
modules/error-handler.js ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Chahuadev Framework - Error Handler Module
3
+ * Error Detection, Logging & Debugging Support
4
+ *
5
+ * Chahua Development Thailand
6
+ * CEO: Saharath C.
7
+ * www.chahuadev.com
8
+ */
9
+
10
+ const fs = require('fs');
11
+ const path = require('path');
12
+
13
+ class ErrorHandler {
14
+ constructor() {
15
+ this.errorTypes = {
16
+ VALIDATION: 'validation',
17
+ SECURITY: 'security',
18
+ EXECUTION: 'execution',
19
+ SYSTEM: 'system',
20
+ NETWORK: 'network',
21
+ BRIDGE: 'bridge',
22
+ CONTEXT: 'context'
23
+ };
24
+
25
+ this.logFile = path.join(process.cwd(), 'logs', 'errors.log');
26
+ this.debugMode = process.env.DEBUG === 'true' || process.env.NODE_ENV === 'development';
27
+
28
+ this.ensureLogDirectory();
29
+ console.log(' Error Handler initialized');
30
+ }
31
+
32
+ /**
33
+ * Handle and log error
34
+ * @param {Error|string} error - Error object or message
35
+ * @param {string} type - Error type
36
+ * @param {Object} context - Pipeline context
37
+ * @param {Object} metadata - Additional metadata
38
+ * @returns {Object} Processed error info
39
+ */
40
+ handle(error, type = this.errorTypes.SYSTEM, context = null, metadata = {}) {
41
+ const errorInfo = this.processError(error, type, context, metadata);
42
+
43
+ // Log error
44
+ this.log(errorInfo);
45
+
46
+ // Console output based on debug mode
47
+ if (this.debugMode) {
48
+ this.debugOutput(errorInfo);
49
+ } else {
50
+ console.error(` ${errorInfo.type}: ${errorInfo.message}`);
51
+ }
52
+
53
+ return errorInfo;
54
+ }
55
+
56
+ /**
57
+ * Process error into standardized format
58
+ * @private
59
+ * @param {Error|string} error - Error object or message
60
+ * @param {string} type - Error type
61
+ * @param {Object} context - Pipeline context
62
+ * @param {Object} metadata - Additional metadata
63
+ * @returns {Object} Processed error info
64
+ */
65
+ processError(error, type, context, metadata) {
66
+ const timestamp = new Date().toISOString();
67
+ const errorId = this.generateErrorId();
68
+
69
+ let errorInfo = {
70
+ id: errorId,
71
+ timestamp: timestamp,
72
+ type: type,
73
+ message: '',
74
+ stack: null,
75
+ code: null,
76
+ details: {},
77
+ context: null,
78
+ metadata: metadata || {}
79
+ };
80
+
81
+ // Extract error information
82
+ if (error instanceof Error) {
83
+ errorInfo.message = error.message;
84
+ errorInfo.stack = error.stack;
85
+ errorInfo.code = error.code || null;
86
+
87
+ // Extract additional error properties
88
+ if (error.errno) errorInfo.details.errno = error.errno;
89
+ if (error.syscall) errorInfo.details.syscall = error.syscall;
90
+ if (error.path) errorInfo.details.path = error.path;
91
+ } else {
92
+ errorInfo.message = String(error);
93
+ }
94
+
95
+ // Add context information
96
+ if (context) {
97
+ errorInfo.context = {
98
+ pipelineId: context.pipelineId,
99
+ pipelineType: context.pipelineType,
100
+ currentStep: context.steps.length > 0 ?
101
+ context.steps[context.steps.length - 1].stepName : 'unknown',
102
+ executionStatus: context.execution.status,
103
+ systemType: context.systemInfo.detectedType
104
+ };
105
+ }
106
+
107
+ // Add environment information
108
+ errorInfo.environment = {
109
+ nodeVersion: process.version,
110
+ platform: process.platform,
111
+ arch: process.arch,
112
+ memory: process.memoryUsage(),
113
+ uptime: process.uptime()
114
+ };
115
+
116
+ return errorInfo;
117
+ }
118
+
119
+ /**
120
+ * Log error to file
121
+ * @private
122
+ * @param {Object} errorInfo - Processed error information
123
+ */
124
+ log(errorInfo) {
125
+ try {
126
+ const logEntry = JSON.stringify(errorInfo) + '\n';
127
+ fs.appendFileSync(this.logFile, logEntry, 'utf8');
128
+ } catch (logError) {
129
+ console.error('Failed to write error log:', logError.message);
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Debug output to console
135
+ * @private
136
+ * @param {Object} errorInfo - Processed error information
137
+ */
138
+ debugOutput(errorInfo) {
139
+ console.error('\n=== CHAHUADEV ERROR DEBUG ===');
140
+ console.error(` Error ID: ${errorInfo.id}`);
141
+ console.error(` Timestamp: ${errorInfo.timestamp}`);
142
+ console.error(` Type: ${errorInfo.type}`);
143
+ console.error(` Message: ${errorInfo.message}`);
144
+
145
+ if (errorInfo.context) {
146
+ console.error(` Pipeline: ${errorInfo.context.pipelineId}`);
147
+ console.error(` Step: ${errorInfo.context.currentStep}`);
148
+ }
149
+
150
+ if (errorInfo.stack && this.debugMode) {
151
+ console.error(` Stack Trace:\n${errorInfo.stack}`);
152
+ }
153
+
154
+ if (Object.keys(errorInfo.details).length > 0) {
155
+ console.error(' Details:', errorInfo.details);
156
+ }
157
+
158
+ console.error('========================\n');
159
+ }
160
+
161
+ /**
162
+ * Create validation error
163
+ * @param {string} message - Error message
164
+ * @param {Object} context - Pipeline context
165
+ * @param {Object} validationData - Validation specific data
166
+ * @returns {Object} Error info
167
+ */
168
+ validation(message, context = null, validationData = {}) {
169
+ return this.handle(
170
+ new Error(message),
171
+ this.errorTypes.VALIDATION,
172
+ context,
173
+ { validationData }
174
+ );
175
+ }
176
+
177
+ /**
178
+ * Create security error
179
+ * @param {string} message - Error message
180
+ * @param {Object} context - Pipeline context
181
+ * @param {Object} securityData - Security specific data
182
+ * @returns {Object} Error info
183
+ */
184
+ security(message, context = null, securityData = {}) {
185
+ return this.handle(
186
+ new Error(message),
187
+ this.errorTypes.SECURITY,
188
+ context,
189
+ { securityData }
190
+ );
191
+ }
192
+
193
+ /**
194
+ * Create execution error
195
+ * @param {string} message - Error message
196
+ * @param {Object} context - Pipeline context
197
+ * @param {Object} executionData - Execution specific data
198
+ * @returns {Object} Error info
199
+ */
200
+ execution(message, context = null, executionData = {}) {
201
+ return this.handle(
202
+ new Error(message),
203
+ this.errorTypes.EXECUTION,
204
+ context,
205
+ { executionData }
206
+ );
207
+ }
208
+
209
+ /**
210
+ * Create bridge communication error
211
+ * @param {string} message - Error message
212
+ * @param {Object} context - Pipeline context
213
+ * @param {Object} bridgeData - Bridge specific data
214
+ * @returns {Object} Error info
215
+ */
216
+ bridge(message, context = null, bridgeData = {}) {
217
+ return this.handle(
218
+ new Error(message),
219
+ this.errorTypes.BRIDGE,
220
+ context,
221
+ { bridgeData }
222
+ );
223
+ }
224
+
225
+ /**
226
+ * Create context error
227
+ * @param {string} message - Error message
228
+ * @param {Object} context - Pipeline context
229
+ * @param {Object} contextData - Context specific data
230
+ * @returns {Object} Error info
231
+ */
232
+ context(message, context = null, contextData = {}) {
233
+ return this.handle(
234
+ new Error(message),
235
+ this.errorTypes.CONTEXT,
236
+ context,
237
+ { contextData }
238
+ );
239
+ }
240
+
241
+ /**
242
+ * Wrap function with error handling
243
+ * @param {Function} fn - Function to wrap
244
+ * @param {string} errorType - Error type for this function
245
+ * @param {Object} context - Pipeline context
246
+ * @returns {Function} Wrapped function
247
+ */
248
+ wrap(fn, errorType = this.errorTypes.SYSTEM, context = null) {
249
+ return async (...args) => {
250
+ try {
251
+ return await fn(...args);
252
+ } catch (error) {
253
+ this.handle(error, errorType, context, {
254
+ functionName: fn.name,
255
+ arguments: args.length
256
+ });
257
+ throw error; // Re-throw for upstream handling
258
+ }
259
+ };
260
+ }
261
+
262
+ /**
263
+ * Get recent errors
264
+ * @param {number} limit - Number of recent errors to get
265
+ * @param {string} type - Filter by error type
266
+ * @returns {Array} Array of error objects
267
+ */
268
+ getRecentErrors(limit = 10, type = null) {
269
+ try {
270
+ if (!fs.existsSync(this.logFile)) {
271
+ return [];
272
+ }
273
+
274
+ const logContent = fs.readFileSync(this.logFile, 'utf8');
275
+ const lines = logContent.trim().split('\n').filter(line => line);
276
+
277
+ let errors = lines.map(line => {
278
+ try {
279
+ return JSON.parse(line);
280
+ } catch (e) {
281
+ return null;
282
+ }
283
+ }).filter(error => error !== null);
284
+
285
+ // Filter by type if specified
286
+ if (type) {
287
+ errors = errors.filter(error => error.type === type);
288
+ }
289
+
290
+ // Sort by timestamp (newest first) and limit
291
+ return errors
292
+ .sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
293
+ .slice(0, limit);
294
+
295
+ } catch (error) {
296
+ console.error('Failed to read error log:', error.message);
297
+ return [];
298
+ }
299
+ }
300
+
301
+ /**
302
+ * Clear error logs
303
+ * @returns {boolean} Success status
304
+ */
305
+ clearLogs() {
306
+ try {
307
+ if (fs.existsSync(this.logFile)) {
308
+ fs.writeFileSync(this.logFile, '', 'utf8');
309
+ console.log(' Error logs cleared');
310
+ return true;
311
+ }
312
+ return true;
313
+ } catch (error) {
314
+ console.error('Failed to clear error logs:', error.message);
315
+ return false;
316
+ }
317
+ }
318
+
319
+ /**
320
+ * Generate unique error ID
321
+ * @private
322
+ * @returns {string} Error ID
323
+ */
324
+ generateErrorId() {
325
+ const timestamp = Date.now();
326
+ const random = Math.random().toString(36).substring(2, 8);
327
+ return `err_${timestamp}_${random}`;
328
+ }
329
+
330
+ /**
331
+ * Ensure log directory exists
332
+ * @private
333
+ */
334
+ ensureLogDirectory() {
335
+ const logDir = path.dirname(this.logFile);
336
+ if (!fs.existsSync(logDir)) {
337
+ try {
338
+ fs.mkdirSync(logDir, { recursive: true });
339
+ } catch (error) {
340
+ console.warn('Could not create log directory:', error.message);
341
+ }
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Get error handler status
347
+ * @returns {Object} Status information
348
+ */
349
+ getStatus() {
350
+ return {
351
+ errorTypes: Object.values(this.errorTypes),
352
+ logFile: this.logFile,
353
+ debugMode: this.debugMode,
354
+ logExists: fs.existsSync(this.logFile),
355
+ ready: true
356
+ };
357
+ }
358
+
359
+ /**
360
+ * Set debug mode
361
+ * @param {boolean} enabled - Enable debug mode
362
+ */
363
+ setDebugMode(enabled) {
364
+ this.debugMode = enabled;
365
+ console.log(` Debug mode: ${enabled ? 'enabled' : 'disabled'}`);
366
+ }
367
+
368
+ /**
369
+ * Log error with type and metadata (for BaseStrategy compatibility)
370
+ * @param {string} type - Error type
371
+ * @param {Error|string} error - Error object or message
372
+ * @param {Object} metadata - Additional metadata
373
+ */
374
+ logError(type, error, metadata = {}) {
375
+ this.handle(error, type, null, metadata);
376
+ }
377
+ }
378
+
379
+ // Export class (not singleton)
380
+ module.exports = ErrorHandler;
modules/executor.js ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * executor.js - Execution Strategy Manager (Level 5)
3
+ * สำหรับ Chahuadev Framework
4
+ *
5
+ * ใช้: system-detector.js (Level 4), validation_gateway.js (Level 4)
6
+ * จัดการ: Strategy selection, execution flow, error handling
7
+ */
8
+
9
+ const SystemDetector = require('./system-detector');
10
+ const ErrorHandler = require('./error-handler');
11
+ const ContextManager = require('./context-manager');
12
+
13
+ class Executor {
14
+ constructor() {
15
+ this.systemDetector = new SystemDetector();
16
+ this.errorHandler = new ErrorHandler();
17
+ this.contextManager = new ContextManager();
18
+
19
+ this.executionHistory = [];
20
+ this.maxHistorySize = 100;
21
+
22
+ console.log(' Executor initialized - ready for strategy execution');
23
+ }
24
+
25
+ /**
26
+ * Main execution method
27
+ */
28
+ async execute(request) {
29
+ const executionId = this.generateExecutionId();
30
+ const startTime = Date.now();
31
+
32
+ try {
33
+ console.log(` Starting execution [${executionId}]`);
34
+
35
+ // Phase 1: Use request as-is (validation done by ValidationGateway)
36
+ const validationResult = {
37
+ success: true,
38
+ sessionId: 'exec_' + Date.now(),
39
+ userId: request.userId || 'system',
40
+ permissions: request.permissions || 'admin',
41
+ level: 'admin'
42
+ };
43
+
44
+ // Phase 2: Context Preparation
45
+ const executionContext = this.prepareExecutionContext(request, executionId, validationResult);
46
+
47
+ // Phase 3: System Detection
48
+ const detectionResult = await this.systemDetector.detect(
49
+ executionContext.projectPath,
50
+ executionContext
51
+ );
52
+
53
+ // Phase 4: Strategy Execution
54
+ const executionResult = await this.executeWithStrategy(
55
+ detectionResult.strategy,
56
+ executionContext
57
+ );
58
+
59
+ // Phase 5: Result Processing
60
+ const finalResult = this.processExecutionResult(
61
+ executionResult,
62
+ detectionResult,
63
+ executionContext,
64
+ startTime
65
+ );
66
+
67
+ this.recordExecution(finalResult);
68
+ console.log(` Execution completed [${executionId}] in ${finalResult.totalDuration}ms`);
69
+
70
+ return finalResult;
71
+
72
+ } catch (error) {
73
+ console.log(` Execution failed [${executionId}]: ${error.message}`);
74
+ const errorResult = this.handleExecutionError(error, request, executionId, startTime);
75
+ this.recordExecution(errorResult);
76
+ return errorResult;
77
+ }
78
+ }
79
+
80
+ /**
81
+ * เตรียม execution context
82
+ */
83
+ prepareExecutionContext(request, executionId, validationResult) {
84
+ // จัดการ command และ args
85
+ let fullCommand;
86
+ if (request.args && Array.isArray(request.args) && request.args.length > 0) {
87
+ // ถ้ามี args แยกมา ให้รวมกับ command
88
+ fullCommand = `${request.command} ${request.args.join(' ')}`;
89
+ } else {
90
+ // ถ้าไม่มี args ใช้ command ตรงๆ
91
+ fullCommand = request.command;
92
+ }
93
+
94
+ const context = this.contextManager.createContext({
95
+ executionId: executionId,
96
+ command: fullCommand,
97
+ originalCommand: request.command, // เก็บ command เดิมไว้
98
+ args: request.args || [], // เก็บ args แยกไว้
99
+ projectPath: request.projectPath || process.cwd(),
100
+ options: request.options || {},
101
+ sessionId: validationResult.sessionId,
102
+ userId: validationResult.userId,
103
+ permissions: validationResult.permissions,
104
+ timestamp: Date.now(),
105
+ platform: process.platform,
106
+ nodeVersion: process.version,
107
+ isSecure: validationResult.success,
108
+ validationLevel: validationResult.level
109
+ });
110
+
111
+ console.log(` Execution context prepared: ${context.executionId}`);
112
+ return context;
113
+ }
114
+
115
+ /**
116
+ * รัน command ด้วย strategy
117
+ */
118
+ async executeWithStrategy(strategy, executionContext) {
119
+ console.log(` Executing with strategy: ${strategy.name}`);
120
+
121
+ const strategyStatus = await strategy.getStatus();
122
+ if (strategyStatus.status !== 'READY') {
123
+ throw new Error(`Strategy not ready: ${strategy.name}`);
124
+ }
125
+
126
+ const result = await strategy.execute(executionContext);
127
+ console.log(` Strategy execution completed: ${strategy.name}`);
128
+
129
+ return result;
130
+ }
131
+
132
+ /**
133
+ * ประมวลผลผลลัพธ์
134
+ */
135
+ processExecutionResult(executionResult, detectionResult, executionContext, startTime) {
136
+ return {
137
+ success: executionResult.success,
138
+ executionId: executionContext.executionId,
139
+ command: executionContext.command,
140
+ projectPath: executionContext.projectPath,
141
+ strategy: detectionResult.type,
142
+ confidence: detectionResult.confidence,
143
+ output: executionResult.output,
144
+ exitCode: executionResult.exitCode,
145
+ error: executionResult.error,
146
+ totalDuration: Date.now() - startTime,
147
+ strategyDuration: executionResult.duration,
148
+ sessionId: executionContext.sessionId,
149
+ userId: executionContext.userId,
150
+ timestamp: startTime,
151
+ platform: executionContext.platform
152
+ };
153
+ }
154
+
155
+ /**
156
+ * จัดการ error
157
+ */
158
+ handleExecutionError(error, request, executionId, startTime) {
159
+ this.errorHandler.logError('EXECUTION_FAILED', error, {
160
+ executionId: executionId,
161
+ request: request
162
+ });
163
+
164
+ return {
165
+ success: false,
166
+ executionId: executionId,
167
+ error: error.message,
168
+ command: request.command,
169
+ projectPath: request.projectPath,
170
+ totalDuration: Date.now() - startTime,
171
+ timestamp: startTime,
172
+ errorType: error.constructor.name
173
+ };
174
+ }
175
+
176
+ /**
177
+ * บันทึก execution history
178
+ */
179
+ recordExecution(result) {
180
+ this.executionHistory.unshift(result);
181
+ if (this.executionHistory.length > this.maxHistorySize) {
182
+ this.executionHistory = this.executionHistory.slice(0, this.maxHistorySize);
183
+ }
184
+ console.log(` Execution recorded: ${result.executionId}`);
185
+ }
186
+
187
+ /**
188
+ * รัน command แบบง่าย
189
+ */
190
+ async run(command, projectPath = process.cwd(), options = {}) {
191
+ return this.execute({
192
+ command: command,
193
+ projectPath: projectPath,
194
+ options: options
195
+ });
196
+ }
197
+
198
+ /**
199
+ * รายงานสถานะ
200
+ */
201
+ async getStatus() {
202
+ const systemStatus = await this.systemDetector.getStatus();
203
+
204
+ return {
205
+ executor: 'ExecutionManager',
206
+ status: 'READY',
207
+ components: {
208
+ systemDetector: systemStatus
209
+ },
210
+ executionHistory: {
211
+ total: this.executionHistory.length,
212
+ successful: this.executionHistory.filter(r => r.success).length,
213
+ failed: this.executionHistory.filter(r => !r.success).length
214
+ },
215
+ timestamp: Date.now()
216
+ };
217
+ }
218
+
219
+ /**
220
+ * สร้าง execution ID
221
+ */
222
+ generateExecutionId() {
223
+ return `exec_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
224
+ }
225
+
226
+ /**
227
+ * ดู execution history
228
+ */
229
+ getHistory(limit = 10) {
230
+ return this.executionHistory.slice(0, limit);
231
+ }
232
+
233
+ /**
234
+ * ล้าง history
235
+ */
236
+ clearHistory() {
237
+ this.executionHistory = [];
238
+ console.log(' Execution history cleared');
239
+ }
240
+ }
241
+
242
+ module.exports = Executor;
modules/health-monitor.js ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Health Monitor - ระบบตรวจสอบสุขภาพ
3
+ * Chahua Development Thailand
4
+ * CEO: Saharath C.
5
+ *
6
+ * Purpose: ตรวจสอบสุขภาพของระบบและ components
7
+ */
8
+
9
+ const os = require('os');
10
+ const fs = require('fs').promises;
11
+
12
+ class HealthMonitor {
13
+ constructor(options = {}) {
14
+ this.config = {
15
+ checkInterval: options.checkInterval || 30000, // 30 seconds
16
+ thresholds: {
17
+ cpu: options.cpuThreshold || 80,
18
+ memory: options.memoryThreshold || 80,
19
+ disk: options.diskThreshold || 90
20
+ }
21
+ };
22
+
23
+ this.healthStatus = {
24
+ system: 'healthy',
25
+ components: {},
26
+ lastCheck: null,
27
+ uptime: process.uptime()
28
+ };
29
+
30
+ this.isMonitoring = false;
31
+ console.log(' Health Monitor initialized');
32
+ }
33
+
34
+ async startMonitoring() {
35
+ if (this.isMonitoring) {
36
+ console.log(' Health monitoring already running');
37
+ return;
38
+ }
39
+
40
+ this.isMonitoring = true;
41
+ console.log(' Starting health monitoring...');
42
+
43
+ // Initial health check
44
+ await this.performHealthCheck();
45
+
46
+ // Start periodic monitoring
47
+ this.monitoringInterval = setInterval(async () => {
48
+ await this.performHealthCheck();
49
+ }, this.config.checkInterval);
50
+ }
51
+
52
+ stopMonitoring() {
53
+ if (this.monitoringInterval) {
54
+ clearInterval(this.monitoringInterval);
55
+ this.monitoringInterval = null;
56
+ }
57
+ this.isMonitoring = false;
58
+ console.log(' Health monitoring stopped');
59
+ }
60
+
61
+ async performHealthCheck() {
62
+ const checkStart = Date.now();
63
+
64
+ try {
65
+ const systemHealth = await this.checkSystemHealth();
66
+ const componentsHealth = await this.checkComponentsHealth();
67
+
68
+ this.healthStatus = {
69
+ system: this.determineOverallHealth(systemHealth, componentsHealth),
70
+ systemMetrics: systemHealth,
71
+ components: componentsHealth,
72
+ lastCheck: new Date().toISOString(),
73
+ uptime: process.uptime(),
74
+ checkDuration: Date.now() - checkStart
75
+ };
76
+
77
+ if (this.healthStatus.system !== 'healthy') {
78
+ console.warn(` System health: ${this.healthStatus.system}`);
79
+ }
80
+
81
+ } catch (error) {
82
+ console.error(' Health check failed:', error.message);
83
+ this.healthStatus.system = 'critical';
84
+ this.healthStatus.error = error.message;
85
+ }
86
+ }
87
+
88
+ async checkSystemHealth() {
89
+ const cpuUsage = await this.getCPUUsage();
90
+ const memoryUsage = this.getMemoryUsage();
91
+ const diskUsage = await this.getDiskUsage();
92
+
93
+ return {
94
+ cpu: {
95
+ usage: cpuUsage,
96
+ status: cpuUsage > this.config.thresholds.cpu ? 'warning' : 'healthy'
97
+ },
98
+ memory: {
99
+ usage: memoryUsage,
100
+ status: memoryUsage > this.config.thresholds.memory ? 'warning' : 'healthy'
101
+ },
102
+ disk: {
103
+ usage: diskUsage,
104
+ status: diskUsage > this.config.thresholds.disk ? 'warning' : 'healthy'
105
+ }
106
+ };
107
+ }
108
+
109
+ async checkComponentsHealth() {
110
+ const components = {};
111
+
112
+ // Check if key modules are responding
113
+ try {
114
+ components.fileSystem = await this.checkFileSystemAccess();
115
+ components.network = await this.checkNetworkConnectivity();
116
+ components.nodeVersion = this.checkNodeVersion();
117
+ } catch (error) {
118
+ console.error('Component health check error:', error.message);
119
+ }
120
+
121
+ return components;
122
+ }
123
+
124
+ async getCPUUsage() {
125
+ return new Promise((resolve) => {
126
+ const startUsage = process.cpuUsage();
127
+ setTimeout(() => {
128
+ const endUsage = process.cpuUsage(startUsage);
129
+ const totalUsage = (endUsage.user + endUsage.system) / 1000; // Convert to ms
130
+ const usage = Math.round((totalUsage / 100) * 100) / 100; // Percentage estimation
131
+ resolve(Math.min(usage, 100));
132
+ }, 100);
133
+ });
134
+ }
135
+
136
+ getMemoryUsage() {
137
+ const used = process.memoryUsage();
138
+ const total = os.totalmem();
139
+ return Math.round((used.rss / total) * 100);
140
+ }
141
+
142
+ async getDiskUsage() {
143
+ try {
144
+ const stats = await fs.stat(process.cwd());
145
+ // Simple disk usage estimation (this is platform-dependent)
146
+ return 50; // Return a safe default
147
+ } catch (error) {
148
+ return 0;
149
+ }
150
+ }
151
+
152
+ async checkFileSystemAccess() {
153
+ try {
154
+ await fs.access(process.cwd(), fs.constants.R_OK | fs.constants.W_OK);
155
+ return { status: 'healthy', message: 'File system accessible' };
156
+ } catch (error) {
157
+ return { status: 'critical', message: 'File system access failed' };
158
+ }
159
+ }
160
+
161
+ async checkNetworkConnectivity() {
162
+ // Simple network check
163
+ return { status: 'healthy', message: 'Network connectivity assumed OK' };
164
+ }
165
+
166
+ checkNodeVersion() {
167
+ const version = process.version;
168
+ const majorVersion = parseInt(version.split('.')[0].substring(1));
169
+
170
+ return {
171
+ version: version,
172
+ status: majorVersion >= 16 ? 'healthy' : 'warning',
173
+ message: majorVersion >= 16 ? 'Node.js version OK' : 'Node.js version may be outdated'
174
+ };
175
+ }
176
+
177
+ determineOverallHealth(systemHealth, componentsHealth) {
178
+ // Check for critical issues
179
+ if (Object.values(componentsHealth).some(c => c.status === 'critical')) {
180
+ return 'critical';
181
+ }
182
+
183
+ if (Object.values(systemHealth).some(s => s.status === 'warning')) {
184
+ return 'warning';
185
+ }
186
+
187
+ if (Object.values(componentsHealth).some(c => c.status === 'warning')) {
188
+ return 'warning';
189
+ }
190
+
191
+ return 'healthy';
192
+ }
193
+
194
+ getHealthStatus() {
195
+ return this.healthStatus;
196
+ }
197
+
198
+ getSimpleStatus() {
199
+ return {
200
+ status: this.healthStatus.system,
201
+ uptime: this.healthStatus.uptime,
202
+ lastCheck: this.healthStatus.lastCheck
203
+ };
204
+ }
205
+ }
206
+
207
+ module.exports = HealthMonitor;
modules/key-system.js ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Chahuadev Framework - Key System Module (Testing Only)
3
+ * JWT Key Management + Security System
4
+ *
5
+ * DEPRECATED: This module is used for testing purposes only.
6
+ * For license validation, use: ./chahua-license-system
7
+ *
8
+ * Chahua Development Thailand
9
+ * CEO: Saharath C.
10
+ * www.chahuadev.com
11
+ *
12
+ * @deprecated Use Chahua License System for production license validation
13
+ * @usecase Testing and JWT token generation for test scenarios
14
+ */
15
+
16
+ const crypto = require('crypto');
17
+ const jwt = require('jsonwebtoken');
18
+
19
+ class KeySystem {
20
+ constructor() {
21
+ // JWT Secret from environment variable (required for security)
22
+ this.jwtSecret = process.env.JWT_SECRET || 'chahuadev-framework-super-secret-key-for-development-2025-v1.0.0-thailand';
23
+ this.algorithm = 'HS256';
24
+ this.defaultExpiry = '1h';
25
+
26
+ console.log(' Key System initialized');
27
+
28
+ if (!process.env.JWT_SECRET) {
29
+ console.warn(' Warning: Using fallback JWT secret. Set JWT_SECRET environment variable for production!');
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Generate JWT token for authentication
35
+ * @param {Object} payload - Data to encode in token
36
+ * @param {string} expiresIn - Token expiry time
37
+ * @returns {string} JWT token
38
+ */
39
+ generateToken(payload = {}, expiresIn = this.defaultExpiry) {
40
+ try {
41
+ const tokenPayload = {
42
+ ...payload,
43
+ iat: Math.floor(Date.now() / 1000),
44
+ iss: 'chahuadev-framework'
45
+ };
46
+
47
+ const token = jwt.sign(tokenPayload, this.jwtSecret, {
48
+ algorithm: this.algorithm,
49
+ expiresIn: expiresIn
50
+ });
51
+
52
+ console.log(' JWT token generated successfully');
53
+ return token;
54
+
55
+ } catch (error) {
56
+ console.error(' JWT generation failed:', error.message);
57
+ throw new Error('Failed to generate JWT token');
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Verify and decode JWT token
63
+ * @param {string} token - JWT token to verify
64
+ * @returns {Object} Decoded payload
65
+ */
66
+ verifyToken(token) {
67
+ try {
68
+ if (!token) {
69
+ throw new Error('Token is required');
70
+ }
71
+
72
+ const decoded = jwt.verify(token, this.jwtSecret, {
73
+ algorithms: [this.algorithm]
74
+ });
75
+
76
+ console.log(' JWT token verified successfully');
77
+ return decoded;
78
+
79
+ } catch (error) {
80
+ console.error(' JWT verification failed:', error.message);
81
+ throw new Error(`Invalid token: ${error.message}`);
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Generate API key for bridge communication
87
+ * @returns {string} API key
88
+ */
89
+ generateApiKey() {
90
+ const apiKey = crypto.randomBytes(32).toString('hex');
91
+ console.log(' API key generated');
92
+ return apiKey;
93
+ }
94
+
95
+ /**
96
+ * Hash sensitive data
97
+ * @param {string} data - Data to hash
98
+ * @returns {string} Hashed data
99
+ */
100
+ hashData(data) {
101
+ if (!data) {
102
+ throw new Error('Data is required for hashing');
103
+ }
104
+
105
+ const hash = crypto.createHash('sha256')
106
+ .update(data)
107
+ .digest('hex');
108
+
109
+ return hash;
110
+ }
111
+
112
+ /**
113
+ * Generate secure random string
114
+ * @param {number} length - Length of random string
115
+ * @returns {string} Random string
116
+ */
117
+ generateSecureRandom(length = 16) {
118
+ return crypto.randomBytes(Math.ceil(length / 2))
119
+ .toString('hex')
120
+ .slice(0, length);
121
+ }
122
+
123
+
124
+
125
+ /**
126
+ * Check if token is expired (without throwing error)
127
+ * @param {string} token - JWT token to check
128
+ * @returns {boolean} True if expired
129
+ */
130
+ isTokenExpired(token) {
131
+ try {
132
+ this.verifyToken(token);
133
+ return false;
134
+ } catch (error) {
135
+ return error.message.includes('expired');
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Extract payload without verification (for debugging)
141
+ * @param {string} token - JWT token
142
+ * @returns {Object} Decoded payload (without verification)
143
+ */
144
+ decodeTokenUnsafe(token) {
145
+ try {
146
+ return jwt.decode(token);
147
+ } catch (error) {
148
+ return null;
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Get key system status
154
+ * @returns {Object} Status information
155
+ */
156
+ getStatus() {
157
+ return {
158
+ algorithm: this.algorithm,
159
+ hasJwtSecret: !!process.env.JWT_SECRET,
160
+ defaultExpiry: this.defaultExpiry,
161
+ ready: true
162
+ };
163
+ }
164
+ }
165
+
166
+ // Export class (not singleton)
167
+ module.exports = KeySystem;
modules/plugin-manager.js ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Plugin Manager (V4 - Correct Pathing)
3
+ * Chahua Development Thailand
4
+ * Purpose: โหลดและจัดการ plugins ผ่าน chahua.json manifest เท่านั้น
5
+ * แก้ไข: กำหนด Path ของ plugins ให้ถูกต้องทั้งในโหมด Dev และ Production
6
+ */
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const os = require('os');
10
+
11
+ class PluginManager {
12
+ constructor() {
13
+ this.projectFeatures = new Map();
14
+
15
+ // --- ส่วน Path Detection ที่แก้ไขใหม่ให้ถูกต้อง 100% ---
16
+ const { app } = require('electron');
17
+
18
+ if (app.isPackaged) {
19
+ // Production Mode: ใช้โฟลเดอร์ 'plugins' ที่อยู่ข้างไฟล์ .exe
20
+ this.pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins');
21
+ } else {
22
+ // Development Mode: ใช้โฟลเดอร์ 'plugins' ใน AppData
23
+ this.pluginsDir = path.join(app.getPath('userData'), 'plugins');
24
+ }
25
+
26
+ // สร้างโฟลเดอร์ plugins ให้ผู้ใช้เลย ถ้ายังไม่มี
27
+ if (!fs.existsSync(this.pluginsDir)) {
28
+ try {
29
+ fs.mkdirSync(this.pluginsDir, { recursive: true });
30
+ console.log(` Created user plugins directory at: ${this.pluginsDir}`);
31
+ } catch (error) {
32
+ console.error(` Failed to create user plugins directory:`, error);
33
+ }
34
+ }
35
+
36
+ console.log(' Plugin Manager initialized. User plugins path is now:', this.pluginsDir);
37
+ }
38
+
39
+ /**
40
+ * ฟังก์ชันหลัก: สแกนหาและอ่าน chahua.json จาก Path ที่ถูกต้อง
41
+ */
42
+ async loadPlugins() {
43
+ console.log(`[PluginManager] Scanning for manifests in '${this.pluginsDir}'...`);
44
+ this.projectFeatures.clear();
45
+
46
+ if (!fs.existsSync(this.pluginsDir)) {
47
+ console.warn(`[PluginManager] Plugins directory not found, skipping scan.`);
48
+ return;
49
+ }
50
+
51
+ try {
52
+ const items = fs.readdirSync(this.pluginsDir, { withFileTypes: true });
53
+
54
+ for (const item of items) {
55
+ if (!item.isDirectory()) continue;
56
+
57
+ const projectPath = path.join(this.pluginsDir, item.name);
58
+ const manifestPath = path.join(projectPath, 'chahua.json');
59
+
60
+ if (fs.existsSync(manifestPath)) {
61
+ try {
62
+ const manifestContent = fs.readFileSync(manifestPath, 'utf8');
63
+ const manifestData = JSON.parse(manifestContent);
64
+
65
+ this.projectFeatures.set(item.name, {
66
+ name: item.name,
67
+ displayName: manifestData.name || item.name,
68
+ path: projectPath,
69
+ description: manifestData.description || 'No description.',
70
+ type: manifestData.type || 'unknown',
71
+ icon: manifestData.icon || '',
72
+ buttons: manifestData.buttons || []
73
+ });
74
+ console.log(` -> Registered plugin: ${manifestData.name || item.name}`);
75
+ } catch (e) {
76
+ console.error(` -> Error parsing manifest for ${item.name}: ${e.message}`);
77
+ }
78
+ }
79
+ }
80
+ } catch (error) {
81
+ console.error(`[PluginManager] Error during manifest scan: ${error.message}`);
82
+ }
83
+ }
84
+
85
+ getProjectFeatures() {
86
+ return Array.from(this.projectFeatures.values());
87
+ }
88
+
89
+ getPluginStats() {
90
+ return {
91
+ projects: this.getProjectFeatures()
92
+ };
93
+ }
94
+ }
95
+
96
+ module.exports = PluginManager;
modules/retry-controller.js ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Retry Controller - ระบบควบคุมการทำซ้ำ
3
+ * Chahua Development Thailand
4
+ * CEO: Saharath C.
5
+ *
6
+ * Purpose: จัดการการ retry operations ที่ล้มเหลว
7
+ */
8
+
9
+ class RetryController {
10
+ constructor(options = {}) {
11
+ this.config = {
12
+ maxRetries: options.maxRetries || 3,
13
+ baseDelay: options.baseDelay || 1000, // 1 second
14
+ maxDelay: options.maxDelay || 30000, // 30 seconds
15
+ backoffMultiplier: options.backoffMultiplier || 2,
16
+ jitter: options.jitter || true
17
+ };
18
+
19
+ this.retryHistory = new Map();
20
+ console.log(' Retry Controller initialized');
21
+ }
22
+
23
+ async executeWithRetry(operation, context = {}, customConfig = {}) {
24
+ const config = { ...this.config, ...customConfig };
25
+ const operationId = context.id || this.generateOperationId();
26
+
27
+ console.log(` Starting operation with retry: ${operationId}`);
28
+
29
+ let lastError;
30
+ let attempt = 0;
31
+
32
+ while (attempt <= config.maxRetries) {
33
+ try {
34
+ console.log(` Attempt ${attempt + 1}/${config.maxRetries + 1}`);
35
+
36
+ const result = await operation(context, attempt);
37
+
38
+ if (attempt > 0) {
39
+ console.log(` Operation succeeded on attempt ${attempt + 1}`);
40
+ }
41
+
42
+ this.logSuccess(operationId, attempt);
43
+ return result;
44
+
45
+ } catch (error) {
46
+ lastError = error;
47
+ attempt++;
48
+
49
+ console.log(` Attempt ${attempt} failed: ${error.message}`);
50
+
51
+ if (attempt <= config.maxRetries) {
52
+ const delay = this.calculateDelay(attempt, config);
53
+ console.log(` Retrying in ${delay}ms...`);
54
+
55
+ await this.sleep(delay);
56
+ } else {
57
+ console.log(` All retry attempts exhausted for ${operationId}`);
58
+ }
59
+ }
60
+ }
61
+
62
+ this.logFailure(operationId, config.maxRetries + 1, lastError);
63
+ throw new Error(`Operation failed after ${config.maxRetries + 1} attempts: ${lastError.message}`);
64
+ }
65
+
66
+ calculateDelay(attempt, config) {
67
+ let delay = config.baseDelay * Math.pow(config.backoffMultiplier, attempt - 1);
68
+
69
+ // Cap at max delay
70
+ delay = Math.min(delay, config.maxDelay);
71
+
72
+ // Add jitter to prevent thundering herd
73
+ if (config.jitter) {
74
+ delay = delay * (0.5 + Math.random() * 0.5);
75
+ }
76
+
77
+ return Math.round(delay);
78
+ }
79
+
80
+ async sleep(ms) {
81
+ return new Promise(resolve => setTimeout(resolve, ms));
82
+ }
83
+
84
+ generateOperationId() {
85
+ return `op_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
86
+ }
87
+
88
+ logSuccess(operationId, attempts) {
89
+ this.retryHistory.set(operationId, {
90
+ operationId,
91
+ success: true,
92
+ attempts: attempts + 1,
93
+ timestamp: new Date().toISOString()
94
+ });
95
+ }
96
+
97
+ logFailure(operationId, attempts, error) {
98
+ this.retryHistory.set(operationId, {
99
+ operationId,
100
+ success: false,
101
+ attempts,
102
+ error: error.message,
103
+ timestamp: new Date().toISOString()
104
+ });
105
+ }
106
+
107
+ getRetryStats() {
108
+ const history = Array.from(this.retryHistory.values());
109
+ const successful = history.filter(h => h.success).length;
110
+ const failed = history.length - successful;
111
+
112
+ const avgAttempts = history.length > 0
113
+ ? Math.round(history.reduce((sum, h) => sum + h.attempts, 0) / history.length)
114
+ : 0;
115
+
116
+ return {
117
+ totalOperations: history.length,
118
+ successful,
119
+ failed,
120
+ successRate: history.length > 0 ? Math.round((successful / history.length) * 100) : 0,
121
+ averageAttempts: avgAttempts
122
+ };
123
+ }
124
+
125
+ clearHistory() {
126
+ this.retryHistory.clear();
127
+ console.log(' Retry history cleared');
128
+ }
129
+ }
130
+
131
+ module.exports = RetryController;
modules/rollback-manager.js ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Rollback Manager - ระบบจัดการ Rollback
3
+ * Chahua Development Thailand
4
+ * CEO: Saharath C.
5
+ *
6
+ * Purpose: จัดการการ rollback เมื่อเกิดข้อผิดพลาด
7
+ */
8
+
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+
12
+ class RollbackManager {
13
+ constructor(options = {}) {
14
+ this.config = {
15
+ snapshotPath: options.snapshotPath || './logs/snapshots',
16
+ maxSnapshots: options.maxSnapshots || 10,
17
+ enableCompression: options.enableCompression || false,
18
+ retentionDays: options.retentionDays || 7
19
+ };
20
+
21
+ this.activeTransactions = new Map();
22
+ this.rollbackHistory = [];
23
+
24
+ this.ensureSnapshotDirectory();
25
+ console.log('Rollback Manager initialized');
26
+ }
27
+
28
+ ensureSnapshotDirectory() {
29
+ try {
30
+ if (!fs.existsSync(this.config.snapshotPath)) {
31
+ fs.mkdirSync(this.config.snapshotPath, { recursive: true });
32
+ }
33
+ } catch (error) {
34
+ console.warn('Warning: Could not create snapshot directory:', error.message);
35
+ }
36
+ }
37
+
38
+ async createSnapshot(transactionId, data, metadata = {}) {
39
+ try {
40
+ const snapshot = {
41
+ id: transactionId,
42
+ timestamp: new Date().toISOString(),
43
+ data: JSON.parse(JSON.stringify(data)), // Deep clone
44
+ metadata: {
45
+ source: metadata.source || 'unknown',
46
+ description: metadata.description || 'Auto snapshot',
47
+ version: metadata.version || '1.0.0',
48
+ ...metadata
49
+ },
50
+ size: this.calculateDataSize(data)
51
+ };
52
+
53
+ // Store in memory
54
+ this.activeTransactions.set(transactionId, snapshot);
55
+
56
+ // Save to disk
57
+ await this.saveSnapshotToDisk(snapshot);
58
+
59
+ console.log(`Snapshot created: ${transactionId}`);
60
+ return transactionId;
61
+
62
+ } catch (error) {
63
+ console.error('Error creating snapshot:', error.message);
64
+ return null;
65
+ }
66
+ }
67
+
68
+ async rollback(transactionId) {
69
+ try {
70
+ console.log(`Starting rollback for transaction: ${transactionId}`);
71
+
72
+ let snapshot = this.activeTransactions.get(transactionId);
73
+
74
+ // If not in memory, try loading from disk
75
+ if (!snapshot) {
76
+ snapshot = await this.loadSnapshotFromDisk(transactionId);
77
+ }
78
+
79
+ if (!snapshot) {
80
+ throw new Error(`Snapshot not found for transaction: ${transactionId}`);
81
+ }
82
+
83
+ // Perform rollback
84
+ const rollbackResult = await this.performRollback(snapshot);
85
+
86
+ // Log rollback
87
+ this.logRollback(transactionId, rollbackResult);
88
+
89
+ // Cleanup
90
+ await this.cleanupSnapshot(transactionId);
91
+
92
+ console.log(`Rollback completed: ${transactionId}`);
93
+ return {
94
+ success: true,
95
+ transactionId,
96
+ timestamp: new Date().toISOString(),
97
+ dataRestored: rollbackResult.itemsRestored || 0
98
+ };
99
+
100
+ } catch (error) {
101
+ console.error(`Rollback failed for ${transactionId}:`, error.message);
102
+ return {
103
+ success: false,
104
+ transactionId,
105
+ error: error.message,
106
+ timestamp: new Date().toISOString()
107
+ };
108
+ }
109
+ }
110
+
111
+ async performRollback(snapshot) {
112
+ // This is a generic rollback implementation
113
+ // In a real system, this would restore actual system state
114
+
115
+ console.log(`Restoring data from snapshot: ${snapshot.id}`);
116
+ console.log(`Snapshot created: ${snapshot.timestamp}`);
117
+ console.log(`Data size: ${snapshot.size} bytes`);
118
+
119
+ // Simulate data restoration
120
+ let itemsRestored = 0;
121
+
122
+ if (snapshot.data && typeof snapshot.data === 'object') {
123
+ itemsRestored = Object.keys(snapshot.data).length;
124
+ }
125
+
126
+ return {
127
+ itemsRestored,
128
+ snapshotId: snapshot.id,
129
+ originalTimestamp: snapshot.timestamp
130
+ };
131
+ }
132
+
133
+ async saveSnapshotToDisk(snapshot) {
134
+ try {
135
+ const filename = `snapshot_${snapshot.id}_${Date.now()}.json`;
136
+ const filepath = path.join(this.config.snapshotPath, filename);
137
+
138
+ const snapshotData = {
139
+ ...snapshot,
140
+ filename,
141
+ savedAt: new Date().toISOString()
142
+ };
143
+
144
+ fs.writeFileSync(filepath, JSON.stringify(snapshotData, null, 2));
145
+
146
+ // Update snapshot with file path
147
+ snapshot.filepath = filepath;
148
+ snapshot.filename = filename;
149
+
150
+ } catch (error) {
151
+ console.error('Error saving snapshot to disk:', error.message);
152
+ }
153
+ }
154
+
155
+ async loadSnapshotFromDisk(transactionId) {
156
+ try {
157
+ const files = fs.readdirSync(this.config.snapshotPath);
158
+ const snapshotFile = files.find(file => file.includes(`snapshot_${transactionId}_`));
159
+
160
+ if (!snapshotFile) {
161
+ return null;
162
+ }
163
+
164
+ const filepath = path.join(this.config.snapshotPath, snapshotFile);
165
+ const snapshotData = JSON.parse(fs.readFileSync(filepath, 'utf8'));
166
+
167
+ console.log(`Snapshot loaded from disk: ${transactionId}`);
168
+ return snapshotData;
169
+
170
+ } catch (error) {
171
+ console.error('Error loading snapshot from disk:', error.message);
172
+ return null;
173
+ }
174
+ }
175
+
176
+ async cleanupSnapshot(transactionId) {
177
+ try {
178
+ // Remove from memory
179
+ this.activeTransactions.delete(transactionId);
180
+
181
+ // Remove from disk (optional - you might want to keep for audit)
182
+ const files = fs.readdirSync(this.config.snapshotPath);
183
+ const snapshotFile = files.find(file => file.includes(`snapshot_${transactionId}_`));
184
+
185
+ if (snapshotFile) {
186
+ const filepath = path.join(this.config.snapshotPath, snapshotFile);
187
+ fs.unlinkSync(filepath);
188
+ console.log(`Snapshot file cleaned up: ${snapshotFile}`);
189
+ }
190
+
191
+ } catch (error) {
192
+ console.error('Error cleaning up snapshot:', error.message);
193
+ }
194
+ }
195
+
196
+ logRollback(transactionId, result) {
197
+ const rollbackEntry = {
198
+ transactionId,
199
+ timestamp: new Date().toISOString(),
200
+ success: result.itemsRestored !== undefined,
201
+ itemsRestored: result.itemsRestored || 0,
202
+ details: result
203
+ };
204
+
205
+ this.rollbackHistory.push(rollbackEntry);
206
+
207
+ // Keep only recent entries
208
+ if (this.rollbackHistory.length > 100) {
209
+ this.rollbackHistory.shift();
210
+ }
211
+ }
212
+
213
+ calculateDataSize(data) {
214
+ try {
215
+ return JSON.stringify(data).length;
216
+ } catch (error) {
217
+ return 0;
218
+ }
219
+ }
220
+
221
+ getActiveTransactions() {
222
+ return Array.from(this.activeTransactions.keys());
223
+ }
224
+
225
+ getRollbackHistory() {
226
+ return this.rollbackHistory.slice(-20); // Last 20 entries
227
+ }
228
+
229
+ getStats() {
230
+ const totalRollbacks = this.rollbackHistory.length;
231
+ const successfulRollbacks = this.rollbackHistory.filter(r => r.success).length;
232
+
233
+ return {
234
+ activeTransactions: this.activeTransactions.size,
235
+ totalRollbacks,
236
+ successfulRollbacks,
237
+ failedRollbacks: totalRollbacks - successfulRollbacks,
238
+ successRate: totalRollbacks > 0 ? Math.round((successfulRollbacks / totalRollbacks) * 100) : 0
239
+ };
240
+ }
241
+
242
+ async cleanupOldSnapshots() {
243
+ try {
244
+ const files = fs.readdirSync(this.config.snapshotPath);
245
+ const cutoffDate = new Date(Date.now() - (this.config.retentionDays * 24 * 60 * 60 * 1000));
246
+
247
+ let cleanedCount = 0;
248
+
249
+ for (const file of files) {
250
+ if (file.startsWith('snapshot_')) {
251
+ const filepath = path.join(this.config.snapshotPath, file);
252
+ const stats = fs.statSync(filepath);
253
+
254
+ if (stats.mtime < cutoffDate) {
255
+ fs.unlinkSync(filepath);
256
+ cleanedCount++;
257
+ }
258
+ }
259
+ }
260
+
261
+ if (cleanedCount > 0) {
262
+ console.log(`Cleaned up ${cleanedCount} old snapshot files`);
263
+ }
264
+
265
+ return cleanedCount;
266
+
267
+ } catch (error) {
268
+ console.error('Error cleaning up old snapshots:', error.message);
269
+ return 0;
270
+ }
271
+ }
272
+ }
273
+
274
+ module.exports = RollbackManager;
modules/security-logger.js ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Security Logger - ระบบบันทึกเหตุการณ์ความปลอดภัย
3
+ * Chahua Development Thailand
4
+ * CEO: Saharath C.
5
+ *
6
+ * Purpose: บันทึกและตรวจสอบเหตุการณ์ด้านความปลอดภัย
7
+ */
8
+
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+
12
+ class SecurityLogger {
13
+ constructor(options = {}) {
14
+ this.config = {
15
+ logPath: options.logPath || './logs/security',
16
+ maxLogSize: options.maxLogSize || 10 * 1024 * 1024, // 10MB
17
+ maxLogFiles: options.maxLogFiles || 5,
18
+ alertThreshold: options.alertThreshold || 10, // Alert after 10 events
19
+ enableRealTimeAlerts: options.enableRealTimeAlerts || true,
20
+ sensitiveFields: options.sensitiveFields || ['password', 'token', 'secret', 'key']
21
+ };
22
+
23
+ this.securityEvents = [];
24
+ this.alertCount = 0;
25
+ this.blockedIPs = new Set();
26
+ this.suspiciousActivities = new Map();
27
+
28
+ this.ensureLogDirectory();
29
+ console.log('Security Logger initialized');
30
+ }
31
+
32
+ ensureLogDirectory() {
33
+ try {
34
+ if (!fs.existsSync(this.config.logPath)) {
35
+ fs.mkdirSync(this.config.logPath, { recursive: true });
36
+ }
37
+ } catch (error) {
38
+ console.warn('Warning: Could not create security log directory:', error.message);
39
+ }
40
+ }
41
+
42
+ async logSecurityEvent(eventData) {
43
+ const timestamp = new Date().toISOString();
44
+ const eventId = this.generateEventId();
45
+
46
+ const securityEvent = {
47
+ id: eventId,
48
+ timestamp,
49
+ type: eventData.type || 'UNKNOWN',
50
+ severity: eventData.severity || 'medium',
51
+ details: this.sanitizeDetails(eventData),
52
+ ip: eventData.ip || 'unknown',
53
+ userAgent: eventData.userAgent || 'unknown',
54
+ source: eventData.source || 'system'
55
+ };
56
+
57
+ // Add to memory
58
+ this.securityEvents.push(securityEvent);
59
+
60
+ // Maintain max events in memory
61
+ if (this.securityEvents.length > 1000) {
62
+ this.securityEvents.shift();
63
+ }
64
+
65
+ // Write to file
66
+ this.writeToLogFile(securityEvent);
67
+
68
+ // Check for alerts
69
+ this.checkForAlerts(securityEvent);
70
+
71
+ // Update suspicious activity tracking
72
+ this.updateSuspiciousActivity(securityEvent);
73
+
74
+ console.log(`Security Event [${securityEvent.severity.toUpperCase()}]: ${securityEvent.type} - ${eventId}`);
75
+
76
+ return eventId;
77
+ }
78
+
79
+ logAuthFailure(ip, username, details = {}) {
80
+ return this.logSecurityEvent({
81
+ type: 'AUTH_FAILURE',
82
+ ip,
83
+ username,
84
+ severity: 'high',
85
+ ...details
86
+ });
87
+ }
88
+
89
+ logAuthSuccess(ip, username, details = {}) {
90
+ return this.logSecurityEvent({
91
+ type: 'AUTH_SUCCESS',
92
+ ip,
93
+ username,
94
+ severity: 'low',
95
+ ...details
96
+ });
97
+ }
98
+
99
+ logSuspiciousAccess(ip, endpoint, details = {}) {
100
+ return this.logSecurityEvent({
101
+ type: 'SUSPICIOUS_ACCESS',
102
+ ip,
103
+ endpoint,
104
+ severity: 'high',
105
+ ...details
106
+ });
107
+ }
108
+
109
+ logRateLimitExceeded(ip, endpoint, details = {}) {
110
+ return this.logSecurityEvent({
111
+ type: 'RATE_LIMIT_EXCEEDED',
112
+ ip,
113
+ endpoint,
114
+ severity: 'medium',
115
+ ...details
116
+ });
117
+ }
118
+
119
+ logDataBreach(source, details = {}) {
120
+ return this.logSecurityEvent({
121
+ type: 'DATA_BREACH',
122
+ source,
123
+ severity: 'critical',
124
+ ...details
125
+ });
126
+ }
127
+
128
+ logUnauthorizedAccess(ip, resource, details = {}) {
129
+ return this.logSecurityEvent({
130
+ type: 'UNAUTHORIZED_ACCESS',
131
+ ip,
132
+ resource,
133
+ severity: 'high',
134
+ ...details
135
+ });
136
+ }
137
+
138
+ logSystemAnomaly(anomalyType, details = {}) {
139
+ return this.logSecurityEvent({
140
+ type: 'SYSTEM_ANOMALY',
141
+ anomalyType,
142
+ severity: 'medium',
143
+ ...details
144
+ });
145
+ }
146
+
147
+ sanitizeDetails(details) {
148
+ const sanitized = { ...details };
149
+
150
+ // Remove sensitive fields
151
+ for (const field of this.config.sensitiveFields) {
152
+ if (sanitized[field]) {
153
+ sanitized[field] = '***REDACTED***';
154
+ }
155
+ }
156
+
157
+ return sanitized;
158
+ }
159
+
160
+ writeToLogFile(event) {
161
+ try {
162
+ const logFileName = `security-${new Date().toISOString().split('T')[0]}.log`;
163
+ const logFilePath = path.join(this.config.logPath, logFileName);
164
+
165
+ const logEntry = JSON.stringify(event) + '\n';
166
+
167
+ // Check file size and rotate if needed
168
+ if (fs.existsSync(logFilePath)) {
169
+ const stats = fs.statSync(logFilePath);
170
+ if (stats.size > this.config.maxLogSize) {
171
+ this.rotateLogFile(logFilePath);
172
+ }
173
+ }
174
+
175
+ fs.appendFileSync(logFilePath, logEntry);
176
+
177
+ } catch (error) {
178
+ console.error('Error writing security log:', error.message);
179
+ }
180
+ }
181
+
182
+ rotateLogFile(logFilePath) {
183
+ try {
184
+ const logDir = path.dirname(logFilePath);
185
+ const baseName = path.basename(logFilePath, '.log');
186
+
187
+ // Rotate existing files
188
+ for (let i = this.config.maxLogFiles - 1; i > 0; i--) {
189
+ const oldFile = path.join(logDir, `${baseName}.${i}.log`);
190
+ const newFile = path.join(logDir, `${baseName}.${i + 1}.log`);
191
+
192
+ if (fs.existsSync(oldFile)) {
193
+ if (i === this.config.maxLogFiles - 1) {
194
+ fs.unlinkSync(oldFile); // Delete oldest
195
+ } else {
196
+ fs.renameSync(oldFile, newFile);
197
+ }
198
+ }
199
+ }
200
+
201
+ // Move current file to .1
202
+ const rotatedFile = path.join(logDir, `${baseName}.1.log`);
203
+ fs.renameSync(logFilePath, rotatedFile);
204
+
205
+ console.log(`Security log rotated: ${logFilePath}`);
206
+
207
+ } catch (error) {
208
+ console.error('Error rotating security log:', error.message);
209
+ }
210
+ }
211
+
212
+ checkForAlerts(event) {
213
+ if (!this.config.enableRealTimeAlerts) return;
214
+
215
+ // Count events from same IP in last hour
216
+ const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
217
+ const recentEvents = this.securityEvents.filter(e =>
218
+ e.ip === event.ip &&
219
+ new Date(e.timestamp) > oneHourAgo
220
+ );
221
+
222
+ if (recentEvents.length >= this.config.alertThreshold) {
223
+ this.triggerAlert(event.ip, recentEvents);
224
+ }
225
+
226
+ // Immediate alert for critical events
227
+ if (event.severity === 'critical') {
228
+ this.triggerCriticalAlert(event);
229
+ }
230
+ }
231
+
232
+ triggerAlert(ip, events) {
233
+ this.alertCount++;
234
+ console.warn(`SECURITY ALERT: Multiple events from IP ${ip} (${events.length} events)`);
235
+
236
+ // Block IP after multiple alerts
237
+ if (events.length >= this.config.alertThreshold * 2) {
238
+ this.blockedIPs.add(ip);
239
+ console.warn(`IP ${ip} has been blocked due to suspicious activity`);
240
+ }
241
+
242
+ // In a real system, you might send email/SMS alerts here
243
+ }
244
+
245
+ triggerCriticalAlert(event) {
246
+ console.error(`CRITICAL SECURITY ALERT: ${event.type} - ${event.id}`);
247
+ // In a real system, you might trigger immediate notifications
248
+ }
249
+
250
+ updateSuspiciousActivity(event) {
251
+ const key = `${event.ip}_${event.type}`;
252
+ const count = this.suspiciousActivities.get(key) || 0;
253
+ this.suspiciousActivities.set(key, count + 1);
254
+ }
255
+
256
+ isIPBlocked(ip) {
257
+ return this.blockedIPs.has(ip);
258
+ }
259
+
260
+ unblockIP(ip) {
261
+ if (this.blockedIPs.delete(ip)) {
262
+ console.log(`IP ${ip} has been unblocked`);
263
+ return true;
264
+ }
265
+ return false;
266
+ }
267
+
268
+ getSecurityReport(timeRange = '24h') {
269
+ const hours = timeRange === '24h' ? 24 : parseInt(timeRange);
270
+ const startTime = new Date(Date.now() - hours * 60 * 60 * 1000);
271
+
272
+ const relevantEvents = this.securityEvents.filter(e =>
273
+ new Date(e.timestamp) > startTime
274
+ );
275
+
276
+ const report = {
277
+ timeRange: `${hours} hours`,
278
+ totalEvents: relevantEvents.length,
279
+ eventTypes: {},
280
+ severityBreakdown: {},
281
+ topIPs: {},
282
+ blockedIPs: Array.from(this.blockedIPs),
283
+ alertsTriggered: this.alertCount
284
+ };
285
+
286
+ // Analyze events
287
+ relevantEvents.forEach(event => {
288
+ // Event types
289
+ report.eventTypes[event.type] = (report.eventTypes[event.type] || 0) + 1;
290
+
291
+ // Severity breakdown
292
+ report.severityBreakdown[event.severity] = (report.severityBreakdown[event.severity] || 0) + 1;
293
+
294
+ // Top IPs
295
+ report.topIPs[event.ip] = (report.topIPs[event.ip] || 0) + 1;
296
+ });
297
+
298
+ // Sort top IPs
299
+ report.topIPs = Object.entries(report.topIPs)
300
+ .sort(([,a], [,b]) => b - a)
301
+ .slice(0, 10)
302
+ .reduce((obj, [ip, count]) => {
303
+ obj[ip] = count;
304
+ return obj;
305
+ }, {});
306
+
307
+ return report;
308
+ }
309
+
310
+ exportSecurityLogs(startDate, endDate) {
311
+ try {
312
+ const events = this.securityEvents.filter(e => {
313
+ const eventDate = new Date(e.timestamp);
314
+ return eventDate >= startDate && eventDate <= endDate;
315
+ });
316
+
317
+ const exportData = {
318
+ exportDate: new Date().toISOString(),
319
+ dateRange: { start: startDate, end: endDate },
320
+ totalEvents: events.length,
321
+ events: events
322
+ };
323
+
324
+ return exportData;
325
+
326
+ } catch (error) {
327
+ console.error('Error exporting security logs:', error.message);
328
+ return null;
329
+ }
330
+ }
331
+
332
+ generateEventId() {
333
+ return `sec_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
334
+ }
335
+
336
+ getStats() {
337
+ return {
338
+ totalEvents: this.securityEvents.length,
339
+ alertsTriggered: this.alertCount,
340
+ blockedIPs: this.blockedIPs.size,
341
+ suspiciousActivities: this.suspiciousActivities.size
342
+ };
343
+ }
344
+ }
345
+
346
+ module.exports = SecurityLogger;
modules/svg-icons.js ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * ╔════════════════════════════════════════════════════════════════════════════════════╗
3
+ * ║ SVG ICON SYSTEM ║
4
+ * ║ ระบบไอคอน SVG ปลอดภัย ║
5
+ * ║ [ใช้งาน] ใช้แทนอิโมจิทั้งหมดในระบบ Chahuadev Framework ║
6
+ * ╚════════════════════════════════════════════════════════════════════════════════════╝
7
+ */
8
+
9
+ class SVGIcons {
10
+ /**
11
+ * สร้างไอคอน SVG สำหรับใช้ในระบบ
12
+ */
13
+ static icons = {
14
+ // Security & Auth Icons
15
+ lock: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
16
+ <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
17
+ <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
18
+ <circle cx="12" cy="20" r="1"></circle>
19
+ </svg>`,
20
+
21
+ unlock: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
22
+ <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
23
+ <path d="M7 11V7a5 5 0 0 1 9.2 1"></path>
24
+ <circle cx="12" cy="20" r="1"></circle>
25
+ </svg>`,
26
+
27
+ shield: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
28
+ <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path>
29
+ </svg>`,
30
+
31
+ checkCircle: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
32
+ <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
33
+ <polyline points="22 4 12 14.01 9 11.01"></polyline>
34
+ </svg>`,
35
+
36
+ alertCircle: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
37
+ <circle cx="12" cy="12" r="10"></circle>
38
+ <line x1="12" y1="8" x2="12" y2="12"></line>
39
+ <line x1="12" y1="16" x2="12.01" y2="16"></line>
40
+ </svg>`,
41
+
42
+ xCircle: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
43
+ <circle cx="12" cy="12" r="10"></circle>
44
+ <line x1="15" y1="9" x2="9" y2="15"></line>
45
+ <line x1="9" y1="9" x2="15" y2="15"></line>
46
+ </svg>`,
47
+
48
+ // User & Auth Icons
49
+ user: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
50
+ <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
51
+ <circle cx="12" cy="7" r="4"></circle>
52
+ </svg>`,
53
+
54
+ users: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
55
+ <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
56
+ <circle cx="9" cy="7" r="4"></circle>
57
+ <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
58
+ <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
59
+ </svg>`,
60
+
61
+ userCheck: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
62
+ <path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
63
+ <circle cx="8.5" cy="7" r="4"></circle>
64
+ <polyline points="21 15 16 20 13 17"></polyline>
65
+ </svg>`,
66
+
67
+ userX: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
68
+ <path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
69
+ <circle cx="8.5" cy="7" r="4"></circle>
70
+ <line x1="18" y1="8" x2="23" y2="13"></line>
71
+ <line x1="23" y1="8" x2="18" y2="13"></line>
72
+ </svg>`,
73
+
74
+ // System Icons
75
+ zap: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
76
+ <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"></polygon>
77
+ </svg>`,
78
+
79
+ settings: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
80
+ <circle cx="12" cy="12" r="3"></circle>
81
+ <path d="M12 1v6m0 6v6M4.22 4.22l4.24 4.24m3.08 3.08l4.24 4.24M1 12h6m6 0h6m-16.78 7.78l4.24-4.24m3.08-3.08l4.24-4.24"></path>
82
+ </svg>`,
83
+
84
+ loader: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
85
+ <line x1="12" y1="2" x2="12" y2="6"></line>
86
+ <line x1="12" y1="18" x2="12" y2="22"></line>
87
+ <line x1="4.22" y1="4.22" x2="7.34" y2="7.34"></line>
88
+ <line x1="16.66" y1="16.66" x2="19.78" y2="19.78"></line>
89
+ <line x1="2" y1="12" x2="6" y2="12"></line>
90
+ <line x1="18" y1="12" x2="22" y2="12"></line>
91
+ <line x1="4.22" y1="19.78" x2="7.34" y2="16.66"></line>
92
+ <line x1="16.66" y1="7.34" x2="19.78" y2="4.22"></line>
93
+ </svg>`,
94
+
95
+ // Status Icons
96
+ check: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
97
+ <polyline points="20 6 9 17 4 12"></polyline>
98
+ </svg>`,
99
+
100
+ x: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
101
+ <line x1="18" y1="6" x2="6" y2="18"></line>
102
+ <line x1="6" y1="6" x2="18" y2="18"></line>
103
+ </svg>`,
104
+
105
+ alertTriangle: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
106
+ <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3.05h16.94a2 2 0 0 0 1.71-3.05l-8.47-14.14a2 2 0 0 0-3.42 0z"></path>
107
+ <line x1="12" y1="9" x2="12" y2="13"></line>
108
+ <line x1="12" y1="17" x2="12.01" y2="17"></line>
109
+ </svg>`,
110
+
111
+ info: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
112
+ <circle cx="12" cy="12" r="10"></circle>
113
+ <line x1="12" y1="16" x2="12" y2="12"></line>
114
+ <line x1="12" y1="8" x2="12.01" y2="8"></line>
115
+ </svg>`,
116
+
117
+ // App Icons
118
+ plugin: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
119
+ <circle cx="12" cy="12" r="1"></circle>
120
+ <path d="M12 1v6m0 6v6"></path>
121
+ <path d="M4.22 4.22l4.24 4.24m3.08 3.08l4.24 4.24"></path>
122
+ <path d="M1 12h6m6 0h6"></path>
123
+ <path d="M4.22 19.78l4.24-4.24m3.08-3.08l4.24-4.24"></path>
124
+ </svg>`,
125
+
126
+ package: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
127
+ <line x1="16.5" y1="9.4" x2="7.5" y2="4.21"></line>
128
+ <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path>
129
+ <polyline points="3.27 6.96 12 12.01 20.73 6.96"></polyline>
130
+ <line x1="12" y1="22.08" x2="12" y2="12"></line>
131
+ </svg>`,
132
+
133
+ database: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
134
+ <ellipse cx="12" cy="5" rx="9" ry="3"></ellipse>
135
+ <path d="M3 5v14a9 3 0 0 0 18 0V5"></path>
136
+ <ellipse cx="12" cy="19" rx="9" ry="3"></ellipse>
137
+ </svg>`,
138
+
139
+ // Action Icons
140
+ download: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
141
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
142
+ <polyline points="7 10 12 15 17 10"></polyline>
143
+ <line x1="12" y1="15" x2="12" y2="3"></line>
144
+ </svg>`,
145
+
146
+ upload: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
147
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
148
+ <polyline points="17 8 12 3 7 8"></polyline>
149
+ <line x1="12" y1="3" x2="12" y2="15"></line>
150
+ </svg>`,
151
+
152
+ refresh: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
153
+ <polyline points="23 4 23 10 17 10"></polyline>
154
+ <polyline points="1 20 1 14 7 14"></polyline>
155
+ <path d="M3.51 9a9 9 0 0 1 14.85-3.36M20.49 15a9 9 0 0 1-14.85 3.36"></path>
156
+ </svg>`,
157
+
158
+ trash: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
159
+ <polyline points="3 6 5 6 21 6"></polyline>
160
+ <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
161
+ <line x1="10" y1="11" x2="10" y2="17"></line>
162
+ <line x1="14" y1="11" x2="14" y2="17"></line>
163
+ </svg>`,
164
+
165
+ edit: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
166
+ <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
167
+ <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
168
+ </svg>`,
169
+
170
+ // System Status
171
+ server: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
172
+ <rect x="2" y="2" width="20" height="8" rx="2" ry="2"></rect>
173
+ <rect x="2" y="14" width="20" height="8" rx="2" ry="2"></rect>
174
+ <line x1="6" y1="6" x2="6.01" y2="6"></line>
175
+ <line x1="6" y1="18" x2="6.01" y2="18"></line>
176
+ </svg>`,
177
+
178
+ gitBranch: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
179
+ <line x1="6" y1="3" x2="6" y2="15"></line>
180
+ <circle cx="18" cy="6" r="3"></circle>
181
+ <circle cx="6" cy="18" r="3"></circle>
182
+ <path d="M18 9a9 9 0 0 1-9 9"></path>
183
+ </svg>`,
184
+
185
+ terminal: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
186
+ <polyline points="4 17 10 11 4 5"></polyline>
187
+ <line x1="12" y1="19" x2="20" y2="19"></line>
188
+ </svg>`,
189
+
190
+ // Misc Icons
191
+ eye: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
192
+ <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
193
+ <circle cx="12" cy="12" r="3"></circle>
194
+ </svg>`,
195
+
196
+ eyeOff: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
197
+ <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path>
198
+ <line x1="1" y1="1" x2="23" y2="23"></line>
199
+ </svg>`,
200
+
201
+ search: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
202
+ <circle cx="11" cy="11" r="8"></circle>
203
+ <path d="m21 21-4.35-4.35"></path>
204
+ </svg>`,
205
+
206
+ bell: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
207
+ <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path>
208
+ <path d="M13.73 21a2 2 0 0 1-3.46 0"></path>
209
+ </svg>`,
210
+
211
+ clock: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
212
+ <circle cx="12" cy="12" r="10"></circle>
213
+ <polyline points="12 6 12 12 16 14"></polyline>
214
+ </svg>`,
215
+ };
216
+
217
+ /**
218
+ * ดึง SVG icon แบบสตริง
219
+ * @param {string} name - ชื่อ icon
220
+ * @param {string} className - CSS class ที่ต้องเพิ่ม (optional)
221
+ * @returns {string} HTML SVG element
222
+ */
223
+ static getSVG(name, className = '') {
224
+ if (!this.icons[name]) {
225
+ console.warn(`Icon not found: ${name}`);
226
+ return '';
227
+ }
228
+
229
+ const svgString = this.icons[name];
230
+ if (className) {
231
+ return svgString.replace('<svg', `<svg class="${className}"`);
232
+ }
233
+ return svgString;
234
+ }
235
+
236
+ /**
237
+ * สร้าง HTML element จาก SVG
238
+ * @param {string} name - ชื่อ icon
239
+ * @param {string} className - CSS class
240
+ * @returns {HTMLElement} SVG element
241
+ */
242
+ static createSVGElement(name, className = '') {
243
+ const svg = this.getSVG(name, className);
244
+ const div = document.createElement('div');
245
+ div.innerHTML = svg;
246
+ return div.firstChild;
247
+ }
248
+ }
249
+
250
+ // ส่งออก
251
+ if (typeof module !== 'undefined' && module.exports) {
252
+ module.exports = SVGIcons;
253
+ }
modules/system-detector.js ADDED
@@ -0,0 +1,1157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * system-detector.js - Auto System Detection (Level 4)
3
+ * สำหรับ Chahuadev Framework
4
+ *
5
+ * ใช้: BaseStrategy และ concrete strategies จาก Level 3
6
+ * ตรวจสอบ: Project type, runtime environment, available tools
7
+ */
8
+
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+ const { exec } = require('child_process');
12
+
13
+ // Import strategies จาก Level 3
14
+ const NodeStrategy = require('../strategies/NodeStrategy');
15
+ const PythonStrategy = require('../strategies/PythonStrategy');
16
+ const JavaStrategy = require('../strategies/JavaStrategy');
17
+ const ApiStrategy = require('../strategies/ApiStrategy');
18
+ const ButtonGenerator = require('./button-generator');
19
+
20
+ class SystemDetector {
21
+ constructor() {
22
+ // สร้าง strategy instances
23
+ this.strategies = {
24
+ node: new NodeStrategy(),
25
+ python: new PythonStrategy(),
26
+ java: new JavaStrategy(),
27
+ api: new ApiStrategy(),
28
+ // เพิ่ม strategies สำหรับ executable และ batch projects
29
+ // ใช้ NodeStrategy เพราะสามารถรันคำสั่งทั่วไปได้
30
+ executable_project: new NodeStrategy(),
31
+ batch_project: new NodeStrategy()
32
+ };
33
+
34
+ this.detectionRules = this.initializeDetectionRules();
35
+
36
+ // เพิ่มระบบสร้างปุ่มอัจฉริยะ
37
+ this.buttonGenerator = new ButtonGenerator();
38
+ this.projectsWithButtons = new Map();
39
+
40
+ console.log(' SystemDetector initialized with Smart Button System');
41
+ }
42
+
43
+ /**
44
+ * กำหนด detection rules สำหรับแต่ละ project type
45
+ */
46
+ initializeDetectionRules() {
47
+ return {
48
+ node: {
49
+ files: ['package.json', 'node_modules/', 'yarn.lock', 'package-lock.json'],
50
+ extensions: ['.js', '.ts', '.json'],
51
+ commands: ['node', 'npm', 'yarn'],
52
+ priority: 10
53
+ },
54
+ python: {
55
+ files: ['requirements.txt', 'setup.py', 'pyproject.toml', 'Pipfile', 'main.py', 'app.py'],
56
+ extensions: ['.py', '.pyx', '.ipynb'],
57
+ commands: ['python', 'python3', 'pip', 'pip3'],
58
+ priority: 9
59
+ },
60
+ java: {
61
+ files: ['pom.xml', 'build.gradle', 'gradlew', 'build.xml'],
62
+ extensions: ['.java', '.class', '.jar'],
63
+ commands: ['java', 'javac', 'mvn', 'gradle'],
64
+ priority: 8
65
+ },
66
+ // เพิ่มประเภทใหม่สำหรับโปรเจกต์ .exe
67
+ executable_project: {
68
+ files: [], // ไม่ต้องหาไฟล์ชื่อเฉพาะ
69
+ extensions: ['.exe'], // แค่มองหานามสกุล .exe ก็พอ
70
+ commands: [],
71
+ priority: 12 // ให้ความสำคัญสูงสุด เพราะชัดเจนที่สุด
72
+ },
73
+ // เพิ่มประเภทใหม่สำหรับโปรเจกต์ .bat
74
+ batch_project: {
75
+ files: [], // ไม่ต้องหาไฟล์ชื่อเฉพาะ
76
+ extensions: ['.bat', '.cmd'], // หานามสกุล .bat และ .cmd
77
+ commands: [],
78
+ priority: 11 // ให้ความสำคัญรองจาก .exe
79
+ },
80
+ api: {
81
+ // API strategy ไม่ต้องมี files เพราะใช้ URL
82
+ files: [],
83
+ extensions: [],
84
+ commands: [],
85
+ priority: 5,
86
+ special: 'url-based' // ตรวจสอบจาก URL pattern
87
+ }
88
+ };
89
+ }
90
+
91
+ /**
92
+ * SystemDetector V2: Checklist-based Detection
93
+ * ตรวจสอบ project type ตามลำดับความสำคัญอย่างชัดเจน
94
+ */
95
+ async detect(projectPath = process.cwd(), context = {}) {
96
+ console.log(`[SystemDetector V2] Using Checklist-based detection for: ${path.basename(projectPath)}`);
97
+ try {
98
+ // ถ้า context มี URL ให้ใช้ API strategy
99
+ if (context.command && this.isUrl(context.command)) {
100
+ console.log(' URL detected, using API strategy');
101
+ return {
102
+ type: 'api',
103
+ strategy: this.strategies.api,
104
+ confidence: 100,
105
+ reason: 'URL detected in command'
106
+ };
107
+ }
108
+
109
+ // ถ้า context ระบุ type มาแล้ว
110
+ if (context.forceType && this.strategies[context.forceType]) {
111
+ console.log(` Forced type detected: ${context.forceType}`);
112
+ return {
113
+ type: context.forceType,
114
+ strategy: this.strategies[context.forceType],
115
+ confidence: 100,
116
+ reason: 'Force type specified in context'
117
+ };
118
+ }
119
+
120
+ if (!fs.existsSync(projectPath)) {
121
+ throw new Error(`Project path not found: ${projectPath}`);
122
+ }
123
+
124
+ const files = fs.readdirSync(projectPath).map(f => f.toLowerCase());
125
+ let detectedType = 'unknown';
126
+
127
+ // --- ระบบ Checklist ตามลำดับความสำคัญ ---
128
+
129
+ // Priority 1: Batch Project (ชัดเจนที่สุด)
130
+ if (files.some(f => f.endsWith('.bat') || f.endsWith('.cmd'))) {
131
+ detectedType = 'batch_project';
132
+ console.log(` -> Priority 1: Found .bat/.cmd file. Type set to [${detectedType}]`);
133
+
134
+ // Priority 2: Executable Project
135
+ } else if (files.some(f => f.endsWith('.exe'))) {
136
+ detectedType = 'executable_project';
137
+ console.log(` -> Priority 2: Found .exe file. Type set to [${detectedType}]`);
138
+
139
+ // Priority 3: Node.js Project
140
+ } else if (files.includes('package.json')) {
141
+ detectedType = 'node';
142
+ console.log(` -> Priority 3: Found package.json. Type set to [${detectedType}]`);
143
+
144
+ // Priority 4: Python Project
145
+ } else if (files.includes('requirements.txt') || files.includes('main.py') || files.includes('app.py')) {
146
+ detectedType = 'python';
147
+ console.log(` -> Priority 4: Found Python indicators. Type set to [${detectedType}]`);
148
+
149
+ // Priority 5: Java Project
150
+ } else if (files.includes('pom.xml') || files.includes('build.gradle')) {
151
+ detectedType = 'java';
152
+ console.log(` -> Priority 5: Found Java indicators. Type set to [${detectedType}]`);
153
+
154
+ // Priority 6: Basic HTML Project
155
+ } else if (files.some(f => f.endsWith('.html'))) {
156
+ detectedType = 'html';
157
+ console.log(` -> Priority 6: Found .html file. Type set to [${detectedType}]`);
158
+ }
159
+
160
+ // --- จบระบบ Checklist ---
161
+
162
+ if (detectedType === 'unknown') {
163
+ console.log(` -> No specific project type detected. Marked as 'unknown'.`);
164
+
165
+ // เพิ่ม fallback สำหรับ production mode
166
+ const { app } = require('electron');
167
+ if (app.isPackaged) {
168
+ detectedType = 'executable_project';
169
+ console.log(` -> [Fallback] Set to executable_project for production mode`);
170
+ }
171
+ }
172
+
173
+ // สร้างปุ่มสำหรับโปรเจคที่ตรวจพบ
174
+ if (detectedType !== 'unknown') {
175
+ const detectionResult = {
176
+ type: detectedType,
177
+ confidence: 100
178
+ };
179
+ await this.generateProjectButtons(projectPath, detectionResult);
180
+ }
181
+
182
+ return {
183
+ type: detectedType,
184
+ confidence: detectedType !== 'unknown' ? 100 : 0, // ถ้าเจอคือมั่นใจ 100%
185
+ reason: `Checklist-based detection: Priority rule for [${detectedType}] triggered.`,
186
+ strategy: this.strategies[detectedType] || this.strategies.node // Fallback to node strategy
187
+ };
188
+
189
+ } catch (error) {
190
+ console.error(` Detection failed for ${projectPath}: ${error.message}`);
191
+ return {
192
+ type: 'unknown',
193
+ confidence: 0,
194
+ error: error.message,
195
+ strategy: this.strategies.node
196
+ };
197
+ }
198
+ }
199
+
200
+ /**
201
+ * รัน detection tests สำหรับทุก strategy
202
+ */
203
+ async runDetectionTests(projectPath) {
204
+ const results = {};
205
+
206
+ for (const [strategyName, rules] of Object.entries(this.detectionRules)) {
207
+ if (rules.special === 'url-based') {
208
+ // Skip API strategy สำหรับ file-based detection
209
+ continue;
210
+ }
211
+
212
+ console.log(` Testing ${strategyName} detection...`);
213
+
214
+ const score = await this.calculateDetectionScore(projectPath, rules, strategyName);
215
+
216
+ results[strategyName] = {
217
+ type: strategyName,
218
+ strategy: this.strategies[strategyName],
219
+ score: score,
220
+ confidence: Math.min(score * 10, 100), // แปลง score เป็น percentage
221
+ rules: rules
222
+ };
223
+
224
+ console.log(` ${strategyName} detection score: ${score}/10 (${results[strategyName].confidence}%)`);
225
+ }
226
+
227
+ return results;
228
+ }
229
+
230
+ /**
231
+ * คำนวณ detection score สำหรับ strategy
232
+ */
233
+ async calculateDetectionScore(projectPath, rules, strategyName) {
234
+ let score = 0;
235
+ const maxScore = 10;
236
+
237
+ // ตรวจสอบ files (40% ของคะแนน)
238
+ const fileScore = this.checkFiles(projectPath, rules.files);
239
+ score += fileScore * 0.4;
240
+
241
+ // ตรวจสอบ extensions (30% ของคะแนน)
242
+ const extensionScore = this.checkExtensions(projectPath, rules.extensions);
243
+ score += extensionScore * 0.3;
244
+
245
+ // ตรวจสอบ commands (30% ของคะแนน)
246
+ const commandScore = await this.checkCommands(rules.commands);
247
+ score += commandScore * 0.3;
248
+
249
+ return Math.round(score * 10) / 10; // ปัดเศษ 1 ตำแหน่ง
250
+ }
251
+
252
+ /**
253
+ * ตรวจสอบ files ที่บ่งบอกประเภท project
254
+ */
255
+ checkFiles(projectPath, requiredFiles) {
256
+ if (!requiredFiles.length) return 0;
257
+
258
+ let foundCount = 0;
259
+
260
+ for (const file of requiredFiles) {
261
+ const filePath = path.join(projectPath, file);
262
+ if (fs.existsSync(filePath)) {
263
+ foundCount++;
264
+ console.log(` Found indicator file: ${file}`);
265
+ }
266
+ }
267
+
268
+ return foundCount / requiredFiles.length * 10;
269
+ }
270
+
271
+ /**
272
+ * ตรวจสอบ file extensions
273
+ */
274
+ checkExtensions(projectPath, extensions) {
275
+ if (!extensions.length) return 0;
276
+
277
+ const files = this.getFilesRecursive(projectPath, 2); // ค้นหา 2 levels
278
+ let foundCount = 0;
279
+
280
+ for (const ext of extensions) {
281
+ const hasExtension = files.some(file => file.endsWith(ext));
282
+ if (hasExtension) {
283
+ foundCount++;
284
+ console.log(` Found files with extension: ${ext}`);
285
+ }
286
+ }
287
+
288
+ return foundCount / extensions.length * 10;
289
+ }
290
+
291
+ /**
292
+ * ตรวจสอบ commands ว่ามีอยู่ในระบบหรือไม่
293
+ */
294
+ async checkCommands(commands) {
295
+ if (!commands.length) return 0;
296
+
297
+ let availableCount = 0;
298
+
299
+ for (const command of commands) {
300
+ const isAvailable = await this.isCommandAvailable(command);
301
+ if (isAvailable) {
302
+ availableCount++;
303
+ console.log(` Command available: ${command}`);
304
+ }
305
+ }
306
+
307
+ return availableCount / commands.length * 10;
308
+ }
309
+
310
+ /**
311
+ * ตรวจสอบว่า command มีอยู่ในระบบหรือไม่
312
+ */
313
+ async isCommandAvailable(command) {
314
+ return new Promise((resolve) => {
315
+ const testCommand = process.platform === 'win32' ? `where ${command}` : `which ${command}`;
316
+
317
+ exec(testCommand, (error, stdout, stderr) => {
318
+ resolve(!error && stdout.trim().length > 0);
319
+ });
320
+ });
321
+ }
322
+
323
+ /**
324
+ * เลือก strategy ที่ดีที่สุด
325
+ */
326
+ selectBestStrategy(detectionResults) {
327
+ const strategies = Object.values(detectionResults);
328
+
329
+ // เรียงลำดับตาม confidence และ priority
330
+ strategies.sort((a, b) => {
331
+ if (a.confidence !== b.confidence) {
332
+ return b.confidence - a.confidence; // เรียงจากมากไปน้อย
333
+ }
334
+ return b.rules.priority - a.rules.priority; // เรียงตาม priority
335
+ });
336
+
337
+ const bestStrategy = strategies[0];
338
+
339
+ return {
340
+ type: bestStrategy.type,
341
+ strategy: bestStrategy.strategy,
342
+ confidence: bestStrategy.confidence,
343
+ reason: `Best match based on detection tests`,
344
+ allResults: detectionResults
345
+ };
346
+ }
347
+
348
+ /**
349
+ * ตรวจสอบว่าเป็น URL หรือไม่
350
+ */
351
+ isUrl(str) {
352
+ try {
353
+ new URL(str);
354
+ return str.startsWith('http://') || str.startsWith('https://');
355
+ } catch {
356
+ return false;
357
+ }
358
+ }
359
+
360
+ /**
361
+ * ค้นหาไฟล์แบบ recursive
362
+ */
363
+ getFilesRecursive(dirPath, maxDepth = 2) {
364
+ const files = [];
365
+
366
+ const scanDir = (currentPath, depth) => {
367
+ if (depth > maxDepth) return;
368
+
369
+ try {
370
+ const items = fs.readdirSync(currentPath);
371
+
372
+ for (const item of items) {
373
+ const fullPath = path.join(currentPath, item);
374
+ const stat = fs.lstatSync(fullPath);
375
+
376
+ if (stat.isFile()) {
377
+ files.push(fullPath);
378
+ } else if (stat.isDirectory() && !item.startsWith('.') && item !== 'node_modules') {
379
+ scanDir(fullPath, depth + 1);
380
+ }
381
+ }
382
+ } catch (error) {
383
+ // Ignore permission errors
384
+ }
385
+ };
386
+
387
+ scanDir(dirPath, 0);
388
+ return files;
389
+ }
390
+
391
+ // สร้างปุ่มตามข้อมูลโปรเจค (เวอร์ชันสแกนรูปอัตโนมัติ)
392
+ async generateProjectButtons(projectPath, detectionResult) {
393
+ try {
394
+ console.log(` Generating buttons for project at: ${projectPath}`);
395
+
396
+ // วิเคราะห์ฟีเจอร์ของโปรเจค
397
+ const features = await this.analyzeProjectFeatures(projectPath, detectionResult);
398
+
399
+ // สร้างภาพตัวอย่างปลั๊กอิน
400
+ const previewImage = await this.generatePluginPreview(projectPath, detectionResult);
401
+
402
+ // --- จุดแก้ไข: ตรวจสอบและดึง strategy ให้ถูกต้อง ---
403
+ const strategy = this.strategies[detectionResult.type];
404
+ if (!strategy) {
405
+ console.warn(` No strategy found for project type "${detectionResult.type}". Skipping button generation.`);
406
+ // ลองใช้ fallback strategy ถ้ามี
407
+ const fallbackStrategy = this.strategies.node;
408
+ if (!fallbackStrategy) return [];
409
+ }
410
+ // --- จบส่วนแก้ไข ---
411
+
412
+ // สร้างข้อมูลโปรเจค
413
+ const projectInfo = {
414
+ name: path.basename(projectPath),
415
+ path: projectPath,
416
+ type: detectionResult.type,
417
+ confidence: detectionResult.confidence,
418
+ strategy: strategy ? strategy.constructor.name : 'Unknown', // ป้องกัน error
419
+ previewImage: previewImage // เพิ่มภาพตัวอย่าง
420
+ };
421
+
422
+ // สร้างปุ่ม
423
+ const buttons = this.buttonGenerator.generateProjectButtons(projectInfo, features);
424
+
425
+ // เก็บข้อมูลโปรเจคและปุ่ม
426
+ this.projectsWithButtons.set(projectPath, {
427
+ projectInfo,
428
+ buttons,
429
+ generated: new Date().toISOString()
430
+ });
431
+
432
+ console.log(` Generated ${buttons.length} buttons for ${projectInfo.name}`);
433
+ return buttons;
434
+
435
+ } catch (error) {
436
+ console.warn(` Failed to generate buttons for ${projectPath}:`, error.message);
437
+ return [];
438
+ }
439
+ }
440
+
441
+ // สร้างภาพตัวอย่างปลั๊กอิน
442
+ async generatePluginPreview(projectPath, detectionResult) {
443
+ try {
444
+ console.log(` Generating preview for plugin: ${path.basename(projectPath)}`);
445
+
446
+ const previewsDir = this.getPreviewsDirectory();
447
+ const pluginName = path.basename(projectPath);
448
+ const previewFileName = `${pluginName}_preview.png`;
449
+ const previewPath = path.join(previewsDir, previewFileName);
450
+
451
+ // ตรวจสอบว่ามีภาพตัวอย่างอยู่แล้วหรือไม่
452
+ if (fs.existsSync(previewPath)) {
453
+ console.log(` Preview already exists: ${previewFileName}`);
454
+ return `file://${previewPath.replace(/\\/g, '/')}`;
455
+ }
456
+
457
+ // สร้างภาพตัวอย่างตามประเภทปลั๊กอิน
458
+ const success = await this.createPreviewImage(projectPath, detectionResult, previewPath);
459
+
460
+ if (success) {
461
+ console.log(` Preview created: ${previewFileName}`);
462
+ return `file://${previewPath.replace(/\\/g, '/')}`;
463
+ } else {
464
+ console.warn(` Failed to create preview for ${pluginName}`);
465
+ return this.getDefaultPreviewImage(detectionResult.type);
466
+ }
467
+
468
+ } catch (error) {
469
+ console.error(` Error generating preview: ${error.message}`);
470
+ return this.getDefaultPreviewImage(detectionResult.type);
471
+ }
472
+ }
473
+
474
+ // ดึง directory สำหรับเก็บภาพตัวอย่าง
475
+ getPreviewsDirectory() {
476
+ const { app } = require('electron');
477
+ let previewsDir;
478
+
479
+ if (app.isPackaged) {
480
+ previewsDir = path.join(path.dirname(app.getPath('exe')), 'previews');
481
+ } else {
482
+ previewsDir = path.join(process.cwd(), 'previews');
483
+ }
484
+
485
+ // สร้างโฟลเดอร์ถ้ายังไม่มี
486
+ if (!fs.existsSync(previewsDir)) {
487
+ fs.mkdirSync(previewsDir, { recursive: true });
488
+ console.log(` Created previews directory: ${previewsDir}`);
489
+ }
490
+
491
+ return previewsDir;
492
+ }
493
+
494
+ // สร้างภาพตัวอย่างตามประเภทปลั๊กอิน
495
+ async createPreviewImage(projectPath, detectionResult, outputPath) {
496
+ try {
497
+ const { type } = detectionResult;
498
+
499
+ switch (type) {
500
+ case 'executable_project':
501
+ return await this.createExecutablePreview(projectPath, outputPath);
502
+ case 'batch_project':
503
+ return await this.createBatchPreview(projectPath, outputPath);
504
+ case 'node':
505
+ return await this.createNodePreview(projectPath, outputPath);
506
+ case 'python':
507
+ return await this.createPythonPreview(projectPath, outputPath);
508
+ case 'html':
509
+ return await this.createWebPreview(projectPath, outputPath);
510
+ default:
511
+ return await this.createGenericPreview(projectPath, outputPath, type);
512
+ }
513
+ } catch (error) {
514
+ console.error(` Error creating preview image: ${error.message}`);
515
+ return false;
516
+ }
517
+ }
518
+
519
+ // สร้างภาพตัวอย่างสำหรับ Executable
520
+ async createExecutablePreview(projectPath, outputPath) {
521
+ try {
522
+ const canvas = this.createCanvas(400, 300);
523
+ const ctx = canvas.getContext('2d');
524
+
525
+ // Background gradient
526
+ const gradient = ctx.createLinearGradient(0, 0, 400, 300);
527
+ gradient.addColorStop(0, '#4A5568');
528
+ gradient.addColorStop(1, '#2D3748');
529
+ ctx.fillStyle = gradient;
530
+ ctx.fillRect(0, 0, 400, 300);
531
+
532
+ // Icon
533
+ ctx.font = 'bold 60px Arial';
534
+ ctx.fillStyle = '#E2E8F0';
535
+ ctx.textAlign = 'center';
536
+ ctx.fillText('', 200, 120);
537
+
538
+ // Title
539
+ ctx.font = 'bold 24px Arial';
540
+ ctx.fillStyle = '#F7FAFC';
541
+ const pluginName = path.basename(projectPath);
542
+ ctx.fillText(pluginName, 200, 180);
543
+
544
+ // Subtitle
545
+ ctx.font = '16px Arial';
546
+ ctx.fillStyle = '#CBD5E0';
547
+ ctx.fillText('Executable Application', 200, 210);
548
+
549
+ // Type badge
550
+ ctx.fillStyle = '#4FD1C7';
551
+ ctx.fillRect(150, 230, 100, 25);
552
+ ctx.fillStyle = '#1A202C';
553
+ ctx.font = '12px Arial';
554
+ ctx.fillText('EXE', 200, 247);
555
+
556
+ return await this.saveCanvas(canvas, outputPath);
557
+ } catch (error) {
558
+ console.error(` Error creating executable preview: ${error.message}`);
559
+ return false;
560
+ }
561
+ }
562
+
563
+ // สร้างภาพตัวอย่างสำหรับ Batch
564
+ async createBatchPreview(projectPath, outputPath) {
565
+ try {
566
+ const canvas = this.createCanvas(400, 300);
567
+ const ctx = canvas.getContext('2d');
568
+
569
+ // Background
570
+ const gradient = ctx.createLinearGradient(0, 0, 400, 300);
571
+ gradient.addColorStop(0, '#38A169');
572
+ gradient.addColorStop(1, '#2F855A');
573
+ ctx.fillStyle = gradient;
574
+ ctx.fillRect(0, 0, 400, 300);
575
+
576
+ // Icon
577
+ ctx.font = 'bold 60px Arial';
578
+ ctx.fillStyle = '#F0FFF4';
579
+ ctx.textAlign = 'center';
580
+ ctx.fillText('', 200, 120);
581
+
582
+ // Title
583
+ ctx.font = 'bold 24px Arial';
584
+ ctx.fillStyle = '#F7FAFC';
585
+ const pluginName = path.basename(projectPath);
586
+ ctx.fillText(pluginName, 200, 180);
587
+
588
+ // Subtitle
589
+ ctx.font = '16px Arial';
590
+ ctx.fillStyle = '#C6F6D5';
591
+ ctx.fillText('Batch Script', 200, 210);
592
+
593
+ // Type badge
594
+ ctx.fillStyle = '#68D391';
595
+ ctx.fillRect(150, 230, 100, 25);
596
+ ctx.fillStyle = '#1A202C';
597
+ ctx.font = '12px Arial';
598
+ ctx.fillText('BAT', 200, 247);
599
+
600
+ return await this.saveCanvas(canvas, outputPath);
601
+ } catch (error) {
602
+ console.error(` Error creating batch preview: ${error.message}`);
603
+ return false;
604
+ }
605
+ }
606
+
607
+ // สร้างภาพตัวอย่างสำหรับ Node.js
608
+ async createNodePreview(projectPath, outputPath) {
609
+ try {
610
+ const canvas = this.createCanvas(400, 300);
611
+ const ctx = canvas.getContext('2d');
612
+
613
+ // Background
614
+ const gradient = ctx.createLinearGradient(0, 0, 400, 300);
615
+ gradient.addColorStop(0, '#68D391');
616
+ gradient.addColorStop(1, '#48BB78');
617
+ ctx.fillStyle = gradient;
618
+ ctx.fillRect(0, 0, 400, 300);
619
+
620
+ // Icon
621
+ ctx.font = 'bold 60px Arial';
622
+ ctx.fillStyle = '#F0FFF4';
623
+ ctx.textAlign = 'center';
624
+ ctx.fillText('', 200, 120);
625
+
626
+ // Title
627
+ ctx.font = 'bold 24px Arial';
628
+ ctx.fillStyle = '#F7FAFC';
629
+ const pluginName = path.basename(projectPath);
630
+ ctx.fillText(pluginName, 200, 180);
631
+
632
+ // Subtitle
633
+ ctx.font = '16px Arial';
634
+ ctx.fillStyle = '#C6F6D5';
635
+ ctx.fillText('Node.js Project', 200, 210);
636
+
637
+ // Type badge
638
+ ctx.fillStyle = '#9AE6B4';
639
+ ctx.fillRect(150, 230, 100, 25);
640
+ ctx.fillStyle = '#1A202C';
641
+ ctx.font = '12px Arial';
642
+ ctx.fillText('NODE', 200, 247);
643
+
644
+ return await this.saveCanvas(canvas, outputPath);
645
+ } catch (error) {
646
+ console.error(` Error creating node preview: ${error.message}`);
647
+ return false;
648
+ }
649
+ }
650
+
651
+ // สร้างภาพตัวอย่างสำหรับ Python
652
+ async createPythonPreview(projectPath, outputPath) {
653
+ try {
654
+ const canvas = this.createCanvas(400, 300);
655
+ const ctx = canvas.getContext('2d');
656
+
657
+ // Background
658
+ const gradient = ctx.createLinearGradient(0, 0, 400, 300);
659
+ gradient.addColorStop(0, '#4FD1C7');
660
+ gradient.addColorStop(1, '#38B2AC');
661
+ ctx.fillStyle = gradient;
662
+ ctx.fillRect(0, 0, 400, 300);
663
+
664
+ // Icon
665
+ ctx.font = 'bold 60px Arial';
666
+ ctx.fillStyle = '#E6FFFA';
667
+ ctx.textAlign = 'center';
668
+ ctx.fillText('', 200, 120);
669
+
670
+ // Title
671
+ ctx.font = 'bold 24px Arial';
672
+ ctx.fillStyle = '#F7FAFC';
673
+ const pluginName = path.basename(projectPath);
674
+ ctx.fillText(pluginName, 200, 180);
675
+
676
+ // Subtitle
677
+ ctx.font = '16px Arial';
678
+ ctx.fillStyle = '#B2F5EA';
679
+ ctx.fillText('Python Project', 200, 210);
680
+
681
+ // Type badge
682
+ ctx.fillStyle = '#81E6D9';
683
+ ctx.fillRect(150, 230, 100, 25);
684
+ ctx.fillStyle = '#1A202C';
685
+ ctx.font = '12px Arial';
686
+ ctx.fillText('PY', 200, 247);
687
+
688
+ return await this.saveCanvas(canvas, outputPath);
689
+ } catch (error) {
690
+ console.error(` Error creating python preview: ${error.message}`);
691
+ return false;
692
+ }
693
+ }
694
+
695
+ // สร้างภาพตัวอย่างสำหรับ Web/HTML
696
+ async createWebPreview(projectPath, outputPath) {
697
+ try {
698
+ const canvas = this.createCanvas(400, 300);
699
+ const ctx = canvas.getContext('2d');
700
+
701
+ // Background
702
+ const gradient = ctx.createLinearGradient(0, 0, 400, 300);
703
+ gradient.addColorStop(0, '#90CDF4');
704
+ gradient.addColorStop(1, '#63B3ED');
705
+ ctx.fillStyle = gradient;
706
+ ctx.fillRect(0, 0, 400, 300);
707
+
708
+ // Icon
709
+ ctx.font = 'bold 60px Arial';
710
+ ctx.fillStyle = '#EBF8FF';
711
+ ctx.textAlign = 'center';
712
+ ctx.fillText('', 200, 120);
713
+
714
+ // Title
715
+ ctx.font = 'bold 24px Arial';
716
+ ctx.fillStyle = '#F7FAFC';
717
+ const pluginName = path.basename(projectPath);
718
+ ctx.fillText(pluginName, 200, 180);
719
+
720
+ // Subtitle
721
+ ctx.font = '16px Arial';
722
+ ctx.fillStyle = '#BEE3F8';
723
+ ctx.fillText('Web Application', 200, 210);
724
+
725
+ // Type badge
726
+ ctx.fillStyle = '#A3BFFA';
727
+ ctx.fillRect(150, 230, 100, 25);
728
+ ctx.fillStyle = '#1A202C';
729
+ ctx.font = '12px Arial';
730
+ ctx.fillText('WEB', 200, 247);
731
+
732
+ return await this.saveCanvas(canvas, outputPath);
733
+ } catch (error) {
734
+ console.error(` Error creating web preview: ${error.message}`);
735
+ return false;
736
+ }
737
+ }
738
+
739
+ // สร้างภาพตัวอย่างทั่วไป
740
+ async createGenericPreview(projectPath, outputPath, type) {
741
+ try {
742
+ const canvas = this.createCanvas(400, 300);
743
+ const ctx = canvas.getContext('2d');
744
+
745
+ // Background
746
+ const gradient = ctx.createLinearGradient(0, 0, 400, 300);
747
+ gradient.addColorStop(0, '#A0AEC0');
748
+ gradient.addColorStop(1, '#718096');
749
+ ctx.fillStyle = gradient;
750
+ ctx.fillRect(0, 0, 400, 300);
751
+
752
+ // Icon
753
+ ctx.font = 'bold 60px Arial';
754
+ ctx.fillStyle = '#F7FAFC';
755
+ ctx.textAlign = 'center';
756
+ ctx.fillText('', 200, 120);
757
+
758
+ // Title
759
+ ctx.font = 'bold 24px Arial';
760
+ ctx.fillStyle = '#F7FAFC';
761
+ const pluginName = path.basename(projectPath);
762
+ ctx.fillText(pluginName, 200, 180);
763
+
764
+ // Subtitle
765
+ ctx.font = '16px Arial';
766
+ ctx.fillStyle = '#E2E8F0';
767
+ ctx.fillText(`${type.toUpperCase()} Plugin`, 200, 210);
768
+
769
+ // Type badge
770
+ ctx.fillStyle = '#CBD5E0';
771
+ ctx.fillRect(150, 230, 100, 25);
772
+ ctx.fillStyle = '#1A202C';
773
+ ctx.font = '12px Arial';
774
+ ctx.fillText(type.substring(0, 8).toUpperCase(), 200, 247);
775
+
776
+ return await this.saveCanvas(canvas, outputPath);
777
+ } catch (error) {
778
+ console.error(` Error creating generic preview: ${error.message}`);
779
+ return false;
780
+ }
781
+ }
782
+
783
+ // สร้าง Canvas (ใช้ node-canvas หรือ fallback)
784
+ createCanvas(width, height) {
785
+ try {
786
+ // ลองใช้ node-canvas ก่อน
787
+ const { createCanvas } = require('canvas');
788
+ return createCanvas(width, height);
789
+ } catch (error) {
790
+ // Fallback: สร้าง mock canvas สำหรับ testing
791
+ console.warn(' node-canvas not available, using fallback');
792
+ return this.createMockCanvas(width, height);
793
+ }
794
+ }
795
+
796
+ // Mock Canvas สำหรับ fallback
797
+ createMockCanvas(width, height) {
798
+ return {
799
+ width,
800
+ height,
801
+ getContext: () => ({
802
+ fillStyle: '',
803
+ font: '',
804
+ textAlign: '',
805
+ fillRect: () => {},
806
+ fillText: () => {},
807
+ createLinearGradient: () => ({
808
+ addColorStop: () => {}
809
+ })
810
+ }),
811
+ toBuffer: () => Buffer.from('')
812
+ };
813
+ }
814
+
815
+ // บันทึก Canvas เป็นไฟล์
816
+ async saveCanvas(canvas, outputPath) {
817
+ try {
818
+ const buffer = canvas.toBuffer('image/png');
819
+ fs.writeFileSync(outputPath, buffer);
820
+ return true;
821
+ } catch (error) {
822
+ console.error(` Error saving canvas: ${error.message}`);
823
+ // สร้างไฟล์ placeholder
824
+ return this.createPlaceholderImage(outputPath);
825
+ }
826
+ }
827
+
828
+ // สร้างไฟล์ placeholder
829
+ createPlaceholderImage(outputPath) {
830
+ try {
831
+ // สร้างไฟล์ SVG placeholder
832
+ const svgContent = `
833
+ <svg width="400" height="300" xmlns="http://www.w3.org/2000/svg">
834
+ <rect width="400" height="300" fill="#718096"/>
835
+ <text x="200" y="150" font-family="Arial" font-size="20" fill="white" text-anchor="middle"> Plugin Preview</text>
836
+ <text x="200" y="180" font-family="Arial" font-size="14" fill="#E2E8F0" text-anchor="middle">Preview Generation Failed</text>
837
+ </svg>
838
+ `;
839
+
840
+ // เปลี่ยนนามสกุลเป็น .svg
841
+ const svgPath = outputPath.replace('.png', '.svg');
842
+ fs.writeFileSync(svgPath, svgContent);
843
+ console.log(` Created SVG placeholder: ${path.basename(svgPath)}`);
844
+ return true;
845
+ } catch (error) {
846
+ console.error(` Error creating placeholder: ${error.message}`);
847
+ return false;
848
+ }
849
+ }
850
+
851
+ // ดึงภาพตัวอย่างเริ่มต้นตามประเภท
852
+ getDefaultPreviewImage(type) {
853
+ const defaultImages = {
854
+ 'executable_project': 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjQwMCIgaGVpZ2h0PSIzMDAiIGZpbGw9IiM0QTU1NjgiLz4KPHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHg9IjE4MCIgeT0iODAiPgo8dGV4dCB4PSIyMCIgeT0iMzAiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIzMCIgZmlsbD0iI0UyRThGMCI+8J+agDwvdGV4dD4KPC9zdmc+Cjx0ZXh0IHg9IjIwMCIgeT0iMTgwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5FeGVjdXRhYmxlPC90ZXh0Pgo8L3N2Zz4=',
855
+ 'batch_project': 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjQwMCIgaGVpZ2h0PSIzMDAiIGZpbGw9IiMzOEExNjkiLz4KPHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHg9IjE4MCIgeT0iODAiPgo8dGV4dCB4PSIyMCIgeT0iMzAiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIzMCIgZmlsbD0iI0YwRkZGNCI+8J+mhzwvdGV4dD4KPC9zdmc+Cjx0ZXh0IHg9IjIwMCIgeT0iMTgwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5CYXRjaCBTY3JpcHQ8L3RleHQ+Cjwvc3ZnPg==',
856
+ 'node': 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjQwMCIgaGVpZ2h0PSIzMDAiIGZpbGw9IiM2OEQzOTEiLz4KPHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHg9IjE4MCIgeT0iODAiPgo8dGV4dCB4PSIyMCIgeT0iMzAiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIzMCIgZmlsbD0iI0YwRkZGNCI+8J+UpzwvdGV4dD4KPC9zdmc+Cjx0ZXh0IHg9IjIwMCIgeT0iMTgwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5Ob2RlLmpzPC90ZXh0Pgo8L3N2Zz4=',
857
+ 'python': 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjQwMCIgaGVpZ2h0PSIzMDAiIGZpbGw9IiM0RkQxQzciLz4KPHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHg9IjE4MCIgeT0iODAiPgo8dGV4dCB4PSIyMCIgeT0iMzAiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIzMCIgZmlsbD0iI0U2RkZGQSI+8J+QjTwvdGV4dD4KPC9zdmc+Cjx0ZXh0IHg9IjIwMCIgeT0iMTgwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5QeXRob248L3RleHQ+Cjwvc3ZnPg==',
858
+ 'html': 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjQwMCIgaGVpZ2h0PSIzMDAiIGZpbGw9IiM5MENERjQiLz4KPHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHg9IjE4MCIgeT0iODAiPgo8dGV4dCB4PSIyMCIgeT0iMzAiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIzMCIgZmlsbD0iI0VCRjhGRiI+8J+MkDwvdGV4dD4KPC9zdmc+Cjx0ZXh0IHg9IjIwMCIgeT0iMTgwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5XZWIgQXBwPC90ZXh0Pgo8L3N2Zz4=',
859
+ 'default': 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjQwMCIgaGVpZ2h0PSIzMDAiIGZpbGw9IiM3MTgwOTYiLz4KPHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHg9IjE4MCIgeT0iODAiPgo8dGV4dCB4PSIyMCIgeT0iMzAiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIzMCIgZmlsbD0iI0Y3RkFGQyI+8J+UjDwvdGV4dD4KPC9zdmc+Cjx0ZXh0IHg9IjIwMCIgeT0iMTgwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5QbHVnaW48L3RleHQ+Cjwvc3ZnPg=='
860
+ };
861
+
862
+ return defaultImages[type] || defaultImages['default'];
863
+ }
864
+
865
+ // วิเคราะห์ฟีเจอร์เพิ่มเติมของโปรเจค
866
+ async analyzeProjectFeatures(projectPath, detectionResult) {
867
+ const features = {
868
+ hasPackageJson: false,
869
+ hasNodeModules: false,
870
+ hasRequirementsTxt: false,
871
+ hasMainPy: false,
872
+ hasAppPy: false,
873
+ hasIndexHtml: false,
874
+ hasElectron: false,
875
+ hasTypeScript: false,
876
+ hasLinter: false,
877
+ hasTests: false,
878
+ hasFlask: false,
879
+ hasDjango: false,
880
+ hasJupyter: false,
881
+ hasCSS: false,
882
+ hasJS: false,
883
+ hasDocker: false,
884
+ projectType: detectionResult.type
885
+ };
886
+
887
+ try {
888
+ const files = fs.readdirSync(projectPath);
889
+
890
+ // ตรวจสอบไฟล์พื้นฐาน
891
+ features.hasPackageJson = files.includes('package.json');
892
+ features.hasNodeModules = files.includes('node_modules');
893
+ features.hasRequirementsTxt = files.includes('requirements.txt');
894
+ features.hasMainPy = files.includes('main.py');
895
+ features.hasAppPy = files.includes('app.py');
896
+ features.hasIndexHtml = files.includes('index.html');
897
+ features.hasDocker = files.includes('Dockerfile') || files.includes('docker-compose.yml');
898
+
899
+ // วิเคราะห์ package.json สำหรับ Node.js
900
+ if (features.hasPackageJson) {
901
+ const packagePath = path.join(projectPath, 'package.json');
902
+ try {
903
+ const packageData = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
904
+ const allDeps = { ...packageData.dependencies, ...packageData.devDependencies };
905
+
906
+ features.hasElectron = 'electron' in allDeps;
907
+ features.hasTypeScript = 'typescript' in allDeps || files.some(f => f.endsWith('.ts'));
908
+ features.hasLinter = 'eslint' in allDeps || 'tslint' in allDeps;
909
+ features.hasTests = 'jest' in allDeps || 'mocha' in allDeps || 'jasmine' in allDeps;
910
+ } catch (error) {
911
+ console.warn('Could not parse package.json:', error.message);
912
+ }
913
+ }
914
+
915
+ // วิเคราะห์ requirements.txt สำหรับ Python
916
+ if (features.hasRequirementsTxt) {
917
+ const requirementsPath = path.join(projectPath, 'requirements.txt');
918
+ try {
919
+ const requirements = fs.readFileSync(requirementsPath, 'utf8');
920
+ features.hasFlask = requirements.includes('Flask');
921
+ features.hasDjango = requirements.includes('Django');
922
+ features.hasJupyter = requirements.includes('jupyter') || requirements.includes('notebook');
923
+ } catch (error) {
924
+ console.warn('Could not parse requirements.txt:', error.message);
925
+ }
926
+ }
927
+
928
+ // ตรวจสอบไฟล์เว็บ
929
+ const webFiles = files.filter(f => f.endsWith('.css') || f.endsWith('.js') || f.endsWith('.html'));
930
+ features.hasCSS = webFiles.some(f => f.endsWith('.css'));
931
+ features.hasJS = webFiles.some(f => f.endsWith('.js'));
932
+
933
+ } catch (error) {
934
+ console.warn(` Error analyzing features for ${projectPath}:`, error.message);
935
+ }
936
+
937
+ return features;
938
+ }
939
+
940
+ // ดึงข้อมูลโปรเจคที่มีปุ่ม
941
+ getProjectsWithButtons() {
942
+ return Array.from(this.projectsWithButtons.values());
943
+ }
944
+
945
+ // ดึงปุ่มสำหรับโปรเจคเฉพาะ
946
+ getProjectButtons(projectPath) {
947
+ const projectData = this.projectsWithButtons.get(projectPath);
948
+ return projectData ? projectData.buttons : [];
949
+ }
950
+
951
+ // สร้าง UI Interface สำหรับการแสดงผล
952
+ generateProjectsUI() {
953
+ const projects = this.getProjectsWithButtons();
954
+ const uiInterface = {
955
+ sections: [],
956
+ totalProjects: projects.length,
957
+ totalButtons: 0,
958
+ lastUpdated: new Date().toISOString()
959
+ };
960
+
961
+ for (const projectData of projects) {
962
+ const { projectInfo, buttons, features } = projectData;
963
+
964
+ const section = {
965
+ projectName: projectInfo.name,
966
+ projectType: projectInfo.type,
967
+ projectPath: projectInfo.path,
968
+ confidence: projectInfo.confidence,
969
+ buttons: buttons,
970
+ features: features,
971
+ buttonCount: buttons.length
972
+ };
973
+
974
+ uiInterface.sections.push(section);
975
+ uiInterface.totalButtons += buttons.length;
976
+ }
977
+
978
+ return uiInterface;
979
+ }
980
+
981
+ // --- ฟังก์ชันใหม่: สแกนหาโปรเจกต์ทั้งหมดอย่างครอบคลุม ---
982
+ /**
983
+ * สแกนหาโปรเจกต์ทั้งหมดจากตำแหน่งที่กำหนดไว้
984
+ */
985
+ async scanProjects() {
986
+ console.log('[SystemDetector] ===========================================');
987
+ console.log('[SystemDetector] Starting a full project scan...');
988
+ this.projectsWithButtons.clear(); // ล้างข้อมูลเก่าก่อนเริ่มสแกน
989
+
990
+ const { app } = require('electron');
991
+ const isPackaged = app.isPackaged;
992
+
993
+ // --- ส่วนที่แก้ไข ---
994
+ let pluginsPath;
995
+ if (isPackaged) {
996
+ // Production: มองหาโฟลเดอร์ plugins ข้างๆ ไฟล์ .exe
997
+ pluginsPath = path.join(path.dirname(app.getPath('exe')), 'plugins');
998
+ } else {
999
+ // Development: มองหาใน UserData (หรือตามที่คุณตั้งค่าไว้)
1000
+ // เราจะใช้ basePath สำหรับโฟลเดอร์อื่น แต่จะระบุ pluginsPath แยกต่างหาก
1001
+ const basePath = app.getAppPath();
1002
+ pluginsPath = path.join(basePath, 'plugins'); // หรือ path.join(app.getPath('userData'), 'plugins') หากต้องการ
1003
+ }
1004
+
1005
+ const scanLocations = [
1006
+ pluginsPath // สแกนที่ตำแหน่งของ plugins ที่ถูกต้องเพียงที่เดียว
1007
+ ];
1008
+
1009
+ for (const location of scanLocations) {
1010
+ console.log(`[SystemDetector] Scanning location: ${location}`);
1011
+ if (fs.existsSync(location)) {
1012
+ await this.scanDirectoryRecursive(location, 0, 3); // สแกนลึกสูงสุด 3 ระดับ
1013
+ } else {
1014
+ console.warn(`[SystemDetector] -> Location not found, skipping.`);
1015
+ }
1016
+ }
1017
+
1018
+ console.log(`[SystemDetector] Scan complete. Found ${this.projectsWithButtons.size} actionable projects.`);
1019
+ console.log('[SystemDetector] ===========================================');
1020
+
1021
+ const uiData = this.generateProjectsUI();
1022
+ return {
1023
+ success: true,
1024
+ projects: uiData.sections,
1025
+ count: uiData.totalProjects
1026
+ };
1027
+ }
1028
+
1029
+ /**
1030
+ * สแกนโฟลเดอร์ย่อยๆ ข้���งใน (Recursive)
1031
+ */
1032
+ async scanDirectoryRecursive(dirPath, currentDepth = 0, maxDepth = 3) {
1033
+ // หยุดสแกนถ้าลึกเกินที่กำหนด
1034
+ if (currentDepth > maxDepth) {
1035
+ return;
1036
+ }
1037
+
1038
+ try {
1039
+ const items = fs.readdirSync(dirPath, { withFileTypes: true });
1040
+
1041
+ for (const item of items) {
1042
+ const fullPath = path.join(dirPath, item.name);
1043
+
1044
+ // ข้ามโฟลเดอร์ที่ไม่ควรสแกน
1045
+ if (item.name === 'node_modules' ||
1046
+ item.name.startsWith('.') ||
1047
+ item.name === 'vendor' ||
1048
+ item.name === 'logs' ||
1049
+ item.name === 'cache') {
1050
+ continue;
1051
+ }
1052
+
1053
+ if (item.isDirectory()) {
1054
+ // ตรวจสอบว่าโฟลเดอร์นี้เป็นโปรเจกต์หรือไม่
1055
+ const detectionResult = await this.detect(fullPath);
1056
+ if (detectionResult.confidence > 30) { // ถ้ามั่นใจเกิน 30% ว่าเป็นโปรเจกต์
1057
+ console.log(`[SystemDetector] -> Project detected: ${item.name} (Type: ${detectionResult.type}, Confidence: ${detectionResult.confidence}%)`);
1058
+ await this.generateProjectButtons(fullPath, detectionResult);
1059
+ } else {
1060
+ // ถ้าไม่ใช่โปรเจกต์ ให้ลองสแกนหาข้างในต่อ
1061
+ await this.scanDirectoryRecursive(fullPath, currentDepth + 1, maxDepth);
1062
+ }
1063
+ }
1064
+ }
1065
+ } catch (error) {
1066
+ console.warn(`[SystemDetector] Error scanning directory ${dirPath}:`, error.message);
1067
+ }
1068
+ }
1069
+
1070
+ // รีเฟรชการสแกนและสร้างปุ่ม (เก็บไว้เพื่อ backward compatibility)
1071
+ async refreshProjectScans() {
1072
+ console.log(' Refreshing project scans and button generation...');
1073
+
1074
+ this.projectsWithButtons.clear();
1075
+ this.buttonGenerator.reset();
1076
+
1077
+ const { app } = require('electron');
1078
+ const isPackaged = app.isPackaged;
1079
+
1080
+ // --- ส่วนที่แก้ไข ---
1081
+ let pluginsPath;
1082
+ if (isPackaged) {
1083
+ // Production: มองหาโฟลเดอร์ plugins ข้างๆ ไฟล์ .exe
1084
+ pluginsPath = path.join(path.dirname(app.getPath('exe')), 'plugins');
1085
+ } else {
1086
+ // Development: มองหาใน Root ของโปรเจกต์
1087
+ const basePath = app.getAppPath();
1088
+ pluginsPath = path.join(basePath, 'plugins');
1089
+ }
1090
+
1091
+ // สแกนโปรเจคใหม่ใน directories ต่างๆ
1092
+ const projectDirs = [
1093
+ pluginsPath,
1094
+ path.join(pluginsPath, 'Chahuadev_Studio_V.10.0.0'),
1095
+ path.join(pluginsPath, 'Chahuadev_Engine_ระบบต้นแบบ')
1096
+ ];
1097
+
1098
+ for (const dir of projectDirs) {
1099
+ if (fs.existsSync(dir)) {
1100
+ await this.scanProjectDirectory(dir);
1101
+ }
1102
+ }
1103
+
1104
+ console.log(` Refresh complete! Found ${this.projectsWithButtons.size} projects with buttons`);
1105
+ return this.generateProjectsUI();
1106
+ }
1107
+
1108
+ // สแกนโฟลเดอร์โปรเจค
1109
+ async scanProjectDirectory(dirPath) {
1110
+ try {
1111
+ if (fs.statSync(dirPath).isFile()) {
1112
+ return;
1113
+ }
1114
+
1115
+ const items = fs.readdirSync(dirPath, { withFileTypes: true });
1116
+
1117
+ for (const item of items) {
1118
+ if (item.isDirectory()) {
1119
+ const fullPath = path.join(dirPath, item.name);
1120
+
1121
+ // ตรวจสอบว่าเป็นโปรเจคหรือไม่
1122
+ const detectionResult = await this.detect(fullPath);
1123
+
1124
+ if (detectionResult.confidence > 30) {
1125
+ await this.generateProjectButtons(fullPath, detectionResult);
1126
+ }
1127
+ }
1128
+ }
1129
+ } catch (error) {
1130
+ console.warn(` Error scanning directory ${dirPath}:`, error.message);
1131
+ }
1132
+ }
1133
+
1134
+ /**
1135
+ * รายงานสถานะ detector
1136
+ */
1137
+ async getStatus() {
1138
+ const strategiesStatus = {};
1139
+
1140
+ for (const [name, strategy] of Object.entries(this.strategies)) {
1141
+ strategiesStatus[name] = await strategy.getStatus();
1142
+ }
1143
+
1144
+ return {
1145
+ detector: 'SystemDetector',
1146
+ status: 'READY',
1147
+ supportedStrategies: Object.keys(this.strategies),
1148
+ detectionRules: this.detectionRules,
1149
+ projectsWithButtons: this.projectsWithButtons.size,
1150
+ totalButtons: this.buttonGenerator.getAllButtons().length,
1151
+ strategies: strategiesStatus,
1152
+ timestamp: Date.now()
1153
+ };
1154
+ }
1155
+ }
1156
+
1157
+ module.exports = SystemDetector;
modules/tamper-detector.js ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Tamper Detection System - Anti-Modification Protection
3
+ * ระบบตรวจจับการแก้ไขไฟล์และป้องกันการดัดแปลง
4
+ *
5
+ * Features:
6
+ * - Real-time file integrity monitoring
7
+ * - Script injection detection
8
+ * - Checksum validation
9
+ * - Warning notifications (Thai/English)
10
+ */
11
+
12
+ const fs = require('fs');
13
+ const path = require('path');
14
+ const crypto = require('crypto');
15
+ const { dialog, app } = require('electron');
16
+
17
+ // ตรวจสอบว่า chokidar มีหรือไม่ (สำหรับ dev mode)
18
+ let chokidar = null;
19
+ try {
20
+ chokidar = require('chokidar');
21
+ } catch (error) {
22
+ console.log(' chokidar not available - file watching disabled');
23
+ }
24
+
25
+ class TamperDetector {
26
+ constructor() {
27
+ this.isMonitoring = false;
28
+ this.originalChecksums = {};
29
+
30
+ // ตรวจสอบว่าเป็น development หรือ production
31
+ this.isPackaged = app ? app.isPackaged : false;
32
+ this.appPath = this.getAppBasePath();
33
+
34
+ console.log(` TamperDetector mode: ${this.isPackaged ? 'PRODUCTION' : 'DEVELOPMENT'}`);
35
+ console.log(` App path: ${this.appPath}`);
36
+
37
+ // กำหนดไฟล์ที่ต้องตรวจสอบตาม environment
38
+ if (this.isPackaged) {
39
+ // Production: ตรวจไฟล์ asar และไฟล์สำคัญ
40
+ this.criticalFiles = [
41
+ 'resources/app.asar', // ไฟล์หลักที่บีบแล้ว
42
+ 'checksums.json',
43
+ 'checksums.sig',
44
+ 'public_key.pem'
45
+ ];
46
+ } else {
47
+ // Development: ตรวจ source files
48
+ this.criticalFiles = [
49
+ 'main.js',
50
+ 'preload.js',
51
+ 'validation_gateway.js',
52
+ 'modules/executor.js',
53
+ 'modules/system-detector.js',
54
+ 'modules/plugin-manager.js'
55
+ ];
56
+ }
57
+
58
+ this.warningMessages = {
59
+ thai: {
60
+ title: ' ตรวจพบการแก้ไขไฟล์',
61
+ fileModified: 'พบการแก้ไขไฟล์ระบบ:',
62
+ scriptInjection: 'ตรวจพบการแทรกสคิปต์ต้องสงสัย:',
63
+ checksumMismatch: 'Checksum ไม่ตรงกัน - ไฟล์อาจถูกดัดแปลง:',
64
+ securityThreat: 'การกระทำนี้อาจเป็นภัยต่อความปลอดภัย\nโปรแกรมจะหยุดทำงานเพื่อป้องกันความเสียหาย',
65
+ actions: 'การดำเนินการ:\n กรุณาตรวจสอบไฟล์\n คืนค่าไฟล์จาก backup\n ติดต่อฝ่ายสนับสนุน',
66
+ buttons: ['ออกจากโปรแกรม', 'ข้ามการตรวจสอบ (ไม่แนะนำ)']
67
+ },
68
+ english: {
69
+ title: ' File Modification Detected',
70
+ fileModified: 'System file modification detected:',
71
+ scriptInjection: 'Suspicious script injection detected:',
72
+ checksumMismatch: 'Checksum mismatch - file may be tampered:',
73
+ securityThreat: 'This action may pose a security risk.\nApplication will terminate to prevent damage.',
74
+ actions: 'Recommended actions:\n Verify file integrity\n Restore from backup\n Contact support team',
75
+ buttons: ['Exit Application', 'Skip Check (Not Recommended)']
76
+ }
77
+ };
78
+
79
+ console.log(' Tamper Detection System initialized');
80
+ }
81
+
82
+ /**
83
+ * ได้ path ฐานของแอปพลิเคชัน
84
+ */
85
+ getAppBasePath() {
86
+ if (!app) {
87
+ // หากไม่มี app object ให้ใช้ __dirname (สำหรับ testing)
88
+ return path.join(__dirname, '..');
89
+ }
90
+
91
+ if (this.isPackaged) {
92
+ // Production: ไฟล์อยู่ใน .exe directory
93
+ // path ควรจะเป็น: C:\Program Files\AppName\ หรือ .\dist\win-unpacked\
94
+ const execPath = process.execPath; // path ของ .exe
95
+ const appDir = path.dirname(execPath); // directory ที่มี .exe
96
+
97
+ console.log(` Production app directory: ${appDir}`);
98
+ return appDir;
99
+ } else {
100
+ // Development: ใช้ __dirname
101
+ return path.join(__dirname, '..');
102
+ }
103
+ }
104
+
105
+ /**
106
+ * เริ่มต้นระบบตรวจจับการแก้ไข
107
+ */
108
+ async startMonitoring() {
109
+ if (this.isMonitoring) {
110
+ console.log(' Tamper detection already running');
111
+ return;
112
+ }
113
+
114
+ try {
115
+ // โหลด checksums ที่ถูกต้อง
116
+ await this.loadOriginalChecksums();
117
+
118
+ // ตรวจสอบไฟล์ครั้งแรก
119
+ await this.performInitialCheck();
120
+
121
+ // เริ่มต้น file watcher
122
+ this.startFileWatcher();
123
+
124
+ this.isMonitoring = true;
125
+ console.log(' Tamper detection monitoring started');
126
+
127
+ } catch (error) {
128
+ console.error(' Failed to start tamper detection:', error);
129
+ }
130
+ }
131
+
132
+ /**
133
+ * โหลด checksums ที่ถูกต้อง
134
+ */
135
+ async loadOriginalChecksums() {
136
+ try {
137
+ const checksumsPath = path.join(this.appPath, 'checksums.json');
138
+
139
+ if (fs.existsSync(checksumsPath)) {
140
+ const data = fs.readFileSync(checksumsPath, 'utf8');
141
+ this.originalChecksums = JSON.parse(data);
142
+ console.log(' Loaded checksums for', Object.keys(this.originalChecksums).length, 'files');
143
+ } else {
144
+ console.warn(' checksums.json not found - generating new checksums');
145
+ await this.generateCurrentChecksums();
146
+ }
147
+ } catch (error) {
148
+ console.error(' Error loading checksums:', error);
149
+ throw error;
150
+ }
151
+ }
152
+
153
+ /**
154
+ * สร้าง checksums ปัจจุบัน
155
+ */
156
+ async generateCurrentChecksums() {
157
+ for (const file of this.criticalFiles) {
158
+ const filePath = path.join(this.appPath, file);
159
+ if (fs.existsSync(filePath)) {
160
+ const checksum = await this.calculateFileChecksum(filePath);
161
+ this.originalChecksums[file] = checksum;
162
+ }
163
+ }
164
+ }
165
+
166
+ /**
167
+ * คำนวณ checksum ของไฟล์
168
+ */
169
+ async calculateFileChecksum(filePath) {
170
+ return new Promise((resolve, reject) => {
171
+ const hash = crypto.createHash('sha256');
172
+ const stream = fs.createReadStream(filePath);
173
+
174
+ stream.on('data', (data) => hash.update(data));
175
+ stream.on('end', () => resolve(hash.digest('hex')));
176
+ stream.on('error', reject);
177
+ });
178
+ }
179
+
180
+ /**
181
+ * ตรวจสอบไฟล์ครั้งแรก
182
+ */
183
+ async performInitialCheck() {
184
+ console.log(' Performing initial integrity check...');
185
+
186
+ for (const file of this.criticalFiles) {
187
+ await this.checkFileIntegrity(file);
188
+ }
189
+
190
+ console.log(' Initial integrity check completed');
191
+ }
192
+
193
+ /**
194
+ * ตรวจสอบความถูกต้องของไฟล์
195
+ */
196
+ async checkFileIntegrity(fileName) {
197
+ try {
198
+ const filePath = path.join(this.appPath, fileName);
199
+
200
+ if (!fs.existsSync(filePath)) {
201
+ this.showTamperWarning('thai', 'fileModified', fileName + ' (ไฟล์หายไป/File missing)');
202
+ return false;
203
+ }
204
+
205
+ const currentChecksum = await this.calculateFileChecksum(filePath);
206
+ const originalChecksum = this.originalChecksums[fileName];
207
+
208
+ if (originalChecksum && currentChecksum !== originalChecksum) {
209
+ console.log(` Checksum mismatch for ${fileName}`);
210
+ console.log(` Original: ${originalChecksum}`);
211
+ console.log(` Current: ${currentChecksum}`);
212
+
213
+ this.showTamperWarning('thai', 'checksumMismatch', fileName);
214
+ return false;
215
+ }
216
+
217
+ // ตรวจสอบการแทรกสคิปต์
218
+ if (await this.detectScriptInjection(filePath)) {
219
+ this.showTamperWarning('thai', 'scriptInjection', fileName);
220
+ return false;
221
+ }
222
+
223
+ return true;
224
+
225
+ } catch (error) {
226
+ console.error(` Error checking ${fileName}:`, error);
227
+ return false;
228
+ }
229
+ }
230
+
231
+ /**
232
+ * ตรวจจับการแทรกสคิปต์ต้องสงสัย
233
+ */
234
+ async detectScriptInjection(filePath) {
235
+ try {
236
+ const content = fs.readFileSync(filePath, 'utf8');
237
+
238
+ // รายการ patterns ต้องสงสัย
239
+ const suspiciousPatterns = [
240
+ /eval\s*\(/gi, // eval() calls
241
+ /Function\s*\(/gi, // Function constructor
242
+ /document\.write/gi, // document.write
243
+ /innerHTML\s*=/gi, // innerHTML assignments
244
+ /outerHTML\s*=/gi, // outerHTML assignments
245
+ /script\s*>/gi, // script tags
246
+ /javascript\s*:/gi, // javascript: protocol
247
+ /on\w+\s*=/gi, // event handlers (onclick, etc.)
248
+ /setTimeout\s*\(/gi, // setTimeout with strings
249
+ /setInterval\s*\(/gi, // setInterval with strings
250
+ /\.appendChild/gi, // DOM manipulation
251
+ /\.createElement\s*\(\s*['"]script/gi, // Creating script elements
252
+ /base64/gi, // base64 encoded content
253
+ /atob\s*\(/gi, // base64 decode
254
+ /btoa\s*\(/gi, // base64 encode
255
+ /unescape\s*\(/gi, // unescape
256
+ /decodeURI/gi, // URI decoding
257
+ /\\x[0-9a-f]{2}/gi, // hex encoded strings
258
+ /\\u[0-9a-f]{4}/gi, // unicode encoded strings
259
+ ];
260
+
261
+ for (const pattern of suspiciousPatterns) {
262
+ if (pattern.test(content)) {
263
+ console.log(` Suspicious pattern detected in ${path.basename(filePath)}: ${pattern}`);
264
+ return true;
265
+ }
266
+ }
267
+
268
+ return false;
269
+
270
+ } catch (error) {
271
+ console.error(' Error detecting script injection:', error);
272
+ return false;
273
+ }
274
+ }
275
+
276
+ /**
277
+ * เริ่มต้น file watcher
278
+ */
279
+ startFileWatcher() {
280
+ if (this.isPackaged) {
281
+ console.log(' File watcher disabled in production - monitoring asar integrity instead');
282
+ return;
283
+ }
284
+
285
+ if (!chokidar) {
286
+ console.log(' File watcher disabled - chokidar not available');
287
+ return;
288
+ }
289
+
290
+ const watchPaths = this.criticalFiles.map(file =>
291
+ path.join(this.appPath, file)
292
+ );
293
+
294
+ this.watcher = chokidar.watch(watchPaths, {
295
+ ignored: /(^|[\/\\])\../, // ignore dotfiles
296
+ persistent: true,
297
+ ignoreInitial: true
298
+ });
299
+
300
+ this.watcher
301
+ .on('change', (filePath) => {
302
+ const fileName = path.relative(this.appPath, filePath);
303
+ console.log(` File changed: ${fileName}`);
304
+ setTimeout(() => this.checkFileIntegrity(fileName), 1000); // รอ 1 วินาที
305
+ })
306
+ .on('unlink', (filePath) => {
307
+ const fileName = path.relative(this.appPath, filePath);
308
+ console.log(` File deleted: ${fileName}`);
309
+ this.showTamperWarning('thai', 'fileModified', fileName + ' (ถูกลบ/Deleted)');
310
+ });
311
+
312
+ console.log(' File watcher started for', this.criticalFiles.length, 'critical files');
313
+ }
314
+
315
+ /**
316
+ * แสดงข้อความเตือนการดัดแปลง
317
+ */
318
+ showTamperWarning(language, type, fileName) {
319
+ const msg = this.warningMessages[language];
320
+
321
+ const message = `${msg[type]} ${fileName}\n\n${msg.securityThreat}\n\n${msg.actions}`;
322
+
323
+ // แสดงทั้งภาษาไทยและอังกฤษ
324
+ const englishMsg = this.warningMessages.english;
325
+ const fullMessage = `${message}\n\n--- English ---\n${englishMsg[type]} ${fileName}\n\n${englishMsg.securityThreat}\n\n${englishMsg.actions}`;
326
+
327
+ dialog.showMessageBox({
328
+ type: 'warning',
329
+ title: `${msg.title} / ${englishMsg.title}`,
330
+ message: fullMessage,
331
+ buttons: [...msg.buttons, ...englishMsg.buttons],
332
+ defaultId: 0,
333
+ cancelId: 1
334
+ }).then((result) => {
335
+ if (result.response === 0 || result.response === 2) { // ออกจากโปรแกรม
336
+ console.log(' Application terminated due to security threat');
337
+ process.exit(1);
338
+ } else {
339
+ console.log(' User chose to skip security check - WARNING!');
340
+ }
341
+ });
342
+ }
343
+
344
+ /**
345
+ * หยุดการตรวจสอบ
346
+ */
347
+ stopMonitoring() {
348
+ if (this.watcher && chokidar) {
349
+ this.watcher.close();
350
+ }
351
+ this.isMonitoring = false;
352
+ console.log(' Tamper detection monitoring stopped');
353
+ }
354
+
355
+ /**
356
+ * ตรวจสอบแบบ manual
357
+ */
358
+ async manualCheck() {
359
+ console.log(' Manual integrity check requested...');
360
+
361
+ let allFilesOk = true;
362
+
363
+ for (const file of this.criticalFiles) {
364
+ const isOk = await this.checkFileIntegrity(file);
365
+ if (!isOk) {
366
+ allFilesOk = false;
367
+ }
368
+ }
369
+
370
+ if (allFilesOk) {
371
+ console.log(' All files passed integrity check');
372
+
373
+ dialog.showMessageBox({
374
+ type: 'info',
375
+ title: ' ตรวจสอบเสร็จสิ้��� / Check Complete',
376
+ message: 'ไฟล์ทั้งหมดผ่านการตรวจสอบความถูกต้อง\n\nAll files passed integrity verification.',
377
+ buttons: ['ตกลง / OK']
378
+ });
379
+ } else {
380
+ console.log(' Some files failed integrity check');
381
+ }
382
+
383
+ return allFilesOk;
384
+ }
385
+ }
386
+
387
+ module.exports = TamperDetector;
npm-runner.bat ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ chcp 65001 > nul
3
+ color 0A
4
+ title Chahuadev Framework Desktop Builder
5
+
6
+ echo.
7
+
8
+ :MENU
9
+ cls
10
+ echo ╔════════════════════════════════════════════════════════════════════════════════╗
11
+ echo ║ 🚀 Chahuadev Framework Desktop Builder ║
12
+ echo ║ Version 1.0.0 ║
13
+ echo ╚════════════════════════════════════════════════════════════════════════════════╝
14
+ echo.
15
+ echo.
16
+ echo --- Common Tasks ---
17
+ echo [1] npm install (ติดตั้ง Dependencies)
18
+ echo [2] npm start (รันโปรเจกต์)
19
+ echo [3] npm run dev (รันในโหมดพัฒนา)
20
+ echo [4] npm test (รันเทส)
21
+ echo.
22
+ echo --- Build & Package ---
23
+ echo [7] npm run build (Build โปรเจกต์)
24
+ echo [8] npm run pack (Pack เป็น Unpacked Folder)
25
+ echo [9] npm run dist (สร้างไฟล์ติดตั้ง)
26
+ echo.
27
+ echo --- Utilities ---
28
+ echo [5] Open Folder (เปิดโฟลเดอร์นี้ใน Explorer)
29
+ echo [6] Open VS Code (เปิดโฟลเดอร์นี้ใน VS Code)
30
+ echo.
31
+ echo [0] Exit (ออกจากสคริปต์)
32
+ echo.
33
+ echo ===================================================
34
+ echo.
35
+
36
+ :: รับ Input จากผู้ใช้
37
+ set /p "CHOICE=Please select an option and press Enter: "
38
+
39
+ :: ตรวจสอบตัวเลือก
40
+ if "%CHOICE%"=="1" goto INSTALL
41
+ if "%CHOICE%"=="2" goto START
42
+ if "%CHOICE%"=="3" goto DEV
43
+ if "%CHOICE%"=="4" goto TEST
44
+ if "%CHOICE%"=="5" goto OPEN_FOLDER
45
+ if "%CHOICE%"=="6" goto OPEN_CODE
46
+ if "%CHOICE%"=="7" goto BUILD
47
+ if "%CHOICE%"=="8" goto PACK
48
+ if "%CHOICE%"=="9" goto DIST
49
+ if "%CHOICE%"=="0" goto EXIT
50
+
51
+ :: ถ้าพิมพ์ผิด
52
+ echo Invalid choice. Please try again.
53
+ pause
54
+ goto MENU
55
+
56
+
57
+ :: =================================
58
+ :: ## Action Sections ##
59
+ :: =================================
60
+
61
+ :INSTALL
62
+ cls
63
+ echo ########## Running npm install ##########
64
+ echo.
65
+ call npm install
66
+ echo.
67
+ echo ########## 'npm install' finished. ##########
68
+ pause
69
+ goto MENU
70
+
71
+ :START
72
+ cls
73
+ echo ########## Running npm start ##########
74
+ echo.
75
+ call npm start
76
+ echo.
77
+ echo ########## 'npm start' finished or was terminated. ##########
78
+ pause
79
+ goto MENU
80
+
81
+ :DEV
82
+ cls
83
+ echo ########## Running npm run dev ##########
84
+ echo.
85
+ call npm run dev
86
+ echo.
87
+ echo ########## 'npm run dev' finished or was terminated. ##########
88
+ pause
89
+ goto MENU
90
+
91
+ :TEST
92
+ cls
93
+ echo ########## Running npm test ##########
94
+ echo.
95
+ call npm test
96
+ echo.
97
+ echo ########## 'npm test' finished. ##########
98
+ pause
99
+ goto MENU
100
+
101
+ :BUILD
102
+ cls
103
+ echo ########## Running npm run build ##########
104
+ echo.
105
+ call npm run build
106
+ echo.
107
+ echo ########## 'npm run build' finished. ##########
108
+ pause
109
+ goto MENU
110
+
111
+ :PACK
112
+ cls
113
+ echo ########## Running npm run pack ##########
114
+ echo.
115
+ call npm run pack
116
+ echo.
117
+ echo ########## 'npm run pack' finished. ##########
118
+ pause
119
+ goto MENU
120
+
121
+ :DIST
122
+ cls
123
+ echo ########## Running npm run dist ##########
124
+ echo.
125
+ call npm run dist
126
+ echo.
127
+ echo ########## 'npm run dist' finished. ##########
128
+ pause
129
+ goto MENU
130
+
131
+ :OPEN_FOLDER
132
+ cls
133
+ echo ########## Opening current folder... ##########
134
+ explorer .
135
+ goto MENU
136
+
137
+ :OPEN_CODE
138
+ cls
139
+ echo ########## Opening in VS Code... ##########
140
+ code .
141
+ goto MENU
142
+
143
+ :EXIT
144
+ exit /b
package.json ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "chahuadev-framework",
3
+ "version": "6.0.0",
4
+ "description": "Chahuadev Framework - NPM Project Manager Desktop App",
5
+ "main": "main.js",
6
+ "scripts": {
7
+ "prestart": "node -e \"const fs=require('fs'); if(!fs.existsSync('private_key.pem')||!fs.existsSync('public_key.pem')){console.warn('⚠️ Warning: Security keys not found. Build integrity protection may be disabled.');} else {console.log('🔐 Security keys found - integrity protection active');}\"",
8
+ "start": "electron .",
9
+ "dev": "electron . --dev",
10
+ "dev-mode": "electron . --dev-mode",
11
+ "generate-checksums": "node generate-checksums.js",
12
+ "build": "cross-env NODE_ENV=production npm run docs:copy && npm run generate-checksums && electron-builder",
13
+ "pack": "cross-env NODE_ENV=production npm run docs:copy && npm run generate-checksums && electron-builder --dir",
14
+ "dist": "cross-env NODE_ENV=production electron-builder --publish=always",
15
+ "build-win": "cross-env NODE_ENV=production npm run docs:copy && npm run generate-checksums && electron-builder --win",
16
+ "build-msi": "cross-env NODE_ENV=production npm run docs:copy && npm run generate-checksums && electron-builder --win msi --x64",
17
+ "build-exe": "cross-env NODE_ENV=production npm run generate-checksums && electron-builder --win portable --x64",
18
+ "build-nsis": "cross-env NODE_ENV=production npm run docs:copy && npm run generate-checksums && electron-builder --win nsis --x64",
19
+ "build:secure": "cross-env NODE_ENV=production electron-builder --win --publish=never",
20
+ "build:secure-msi": "cross-env NODE_ENV=production node scripts/secure-build.js && electron-builder --win msi --x64",
21
+ "build:fort-knox": "echo ' Starting Fort-Knox Level Build...' && cross-env NODE_ENV=production node scripts/secure-build.js",
22
+ "docs:copy": "node scripts/copy-user-guides.js",
23
+ "docs:status": "node scripts/copy-user-guides.js --status",
24
+ "docs:help": "node scripts/copy-user-guides.js --help",
25
+ "build:win": "cross-env NODE_ENV=production electron-builder --win",
26
+ "build:msi": "cross-env NODE_ENV=production electron-builder --win --publish=never",
27
+ "pack:msi": "cross-env NODE_ENV=production electron-builder --win --dir",
28
+ "dist:msi": "cross-env NODE_ENV=production electron-builder --win msi --publish=always",
29
+ "build:dev": "cross-env CSC_IDENTITY_AUTO_DISCOVERY=false npm run build",
30
+ "build:prod": "cross-env NODE_ENV=production npm run security:check && npm run generate-checksums && electron-builder",
31
+ "build:unsigned": "cross-env CSC_IDENTITY_AUTO_DISCOVERY=false electron-builder --win",
32
+ "build:signed": "cross-env NODE_ENV=production electron-builder --win",
33
+ "prepare:signing": "echo 'Preparing Code Signing...' && echo 'Set CSC_LINK and CSC_KEY_PASSWORD environment variables' && echo 'Example: export CSC_LINK=path/to/certificate.p12' && echo 'Example: export CSC_KEY_PASSWORD=your_certificate_password'",
34
+ "ui": "electron .",
35
+ "projects": "cmd /c \"cd chahuadev-framework && npm run project:list && pause\"",
36
+ "install-sample": "cmd /c \"cd chahuadev-framework && npm run install:sample\"",
37
+ "start-sample": "cmd /c \"cd chahuadev-framework && npm run start:sample\"",
38
+ "start-studio": "cmd /c \"cd chahuadev-framework && npm run project:start Chahuadev_Studio_V.10.0.0\"",
39
+ "install-studio": "cmd /c \"cd chahuadev-framework && npm run project:install Chahuadev_Studio_V.10.0.0\"",
40
+ "validation": "node validation_gateway.js",
41
+ "test": "node test/test-runner.js",
42
+ "postinstall": "electron-builder install-app-deps",
43
+ "test:packed": "echo \"ทดสอบแอปที่ Pack แล้วในโหมดพัฒนา:\" && echo \"./dist/win-unpacked/\\\"Chahuadev Framework.exe\\\" --dev-mode\"",
44
+ "studio:dev": "cd plugins/Chahuadev_Studio_V.10.0.0 && npm run dev",
45
+ "studio:build": "cd plugins/Chahuadev_Studio_V.10.0.0 && npm run build",
46
+ "studio:install": "cd plugins/Chahuadev_Studio_V.10.0.0 && npm install",
47
+ "plugins:generate": "node generate-manifests.js",
48
+ "framework:status": "node -e \"console.log('Chahuadev Framework Status: Ready')\"",
49
+ "quick": "electron . && echo 'Quick Launch Complete'",
50
+ "test:splash": "echo \" Testing Splash Screen System...\" && electron . --dev-mode",
51
+ "test:logo": "echo \" Logo System Test:\" && echo \" 1. Checking icon.png...\" && (ls icon.png > nul 2>&1 && echo \" [SUCCESS] icon.png found\" || echo \" [ERROR] icon.png missing\") && echo \" 2. Checking splash.html...\" && (ls splash.html > nul 2>&1 && echo \" [SUCCESS] splash.html found\" || echo \" [ERROR] splash.html missing\") && echo \" 3. Testing app...\" && electron . --dev-mode",
52
+ "security:audit": "npm audit --audit-level=moderate",
53
+ "security:audit-fix": "npm audit fix --force",
54
+ "security:check": "npm run security:audit && npm run security:outdated && npm run security:licenses",
55
+ "security:outdated": "npm outdated --depth=0",
56
+ "security:licenses": "echo \" Checking package licenses...\" && npx license-checker --summary",
57
+ "security:update": "npx npm-check-updates -u && npm install && npm run security:audit",
58
+ "security:report": "echo \" Generating Security Report...\" && npm audit --json > security-audit.json && npm outdated --json > outdated-packages.json && echo \"[SUCCESS] Security reports generated\"",
59
+ "security:daily": "echo \" Daily Security Check...\" && npm run security:check && echo \"[SUCCESS] Daily security check completed\"",
60
+ "dist:exe": "electron-builder --win portable --publish=always",
61
+ "dist:dev": "electron-builder --publish=never",
62
+ "build:simple": "electron-builder",
63
+ "npm:prepare": "node scripts/prepare-npm-package.js",
64
+ "npm:build": "npm run build:win && npm run npm:prepare",
65
+ "npm:publish": "cd npm-package && npm publish",
66
+ "npm:publish-test": "cd npm-package && npm publish --dry-run",
67
+ "build:windows": "cross-env NODE_ENV=production npm run docs:copy && npm run generate-checksums && electron-builder --win --x64 --ia32",
68
+ "build:linux": "cross-env NODE_ENV=production npm run docs:copy && npm run generate-checksums && electron-builder --linux --x64",
69
+ "build:linux:native": "cross-env NODE_ENV=production electron-builder --linux --x64",
70
+ "build:linux:wsl": "wsl bash build-linux-wsl.sh",
71
+ "build:all": "cross-env NODE_ENV=production npm run docs:copy && npm run generate-checksums && electron-builder --win --x64 --ia32 --linux --x64",
72
+ "build:all:smart": "node scripts/build-all-platforms.js"
73
+ },
74
+ "keywords": [
75
+ "chahuadev",
76
+ "framework",
77
+ "npm",
78
+ "electron",
79
+ "desktop"
80
+ ],
81
+ "author": "Chahua Development Thailand",
82
+ "license": "SEE LICENSE IN LICENSE.md",
83
+ "dependencies": {
84
+ "acorn": "^8.15.0",
85
+ "adm-zip": "^0.5.16",
86
+ "archiver": "^4.0.2",
87
+ "axios": "^1.11.0",
88
+ "canvas": "^3.1.2",
89
+ "cheerio": "^1.1.0",
90
+ "child_process": "*",
91
+ "commander": "^11.0.0",
92
+ "cors": "^2.8.5",
93
+ "crypto": "^1.0.1",
94
+ "cytoscape-svg": "^0.4.0",
95
+ "exceljs": "^4.1.1",
96
+ "express": "^4.21.2",
97
+ "fs-extra": "^11.0.0",
98
+ "glob": "^11.0.3",
99
+ "html2canvas": "^1.4.1",
100
+ "jsonwebtoken": "^9.0.2",
101
+ "mammoth": "^1.9.1",
102
+ "mime-types": "^2.1.35",
103
+ "monaco-editor": "^0.45.0",
104
+ "os": "*",
105
+ "path": "*",
106
+ "pdf-parse": "^1.1.1",
107
+ "rimraf": "^6.1.3",
108
+ "util": "*",
109
+ "uuid": "^11.1.0",
110
+ "ws": "^8.18.3",
111
+ "yauzl": "^3.2.0"
112
+ },
113
+ "devDependencies": {
114
+ "audit-ci": "^7.1.0",
115
+ "concurrently": "^8.2.0",
116
+ "cross-env": "^7.0.3",
117
+ "electron": "^38.0.0",
118
+ "electron-builder": "^26.8.1",
119
+ "electron-updater": "^6.6.2",
120
+ "javascript-obfuscator": "^0.14.3",
121
+ "license-checker": "^25.0.1",
122
+ "nodemon": "^3.0.1",
123
+ "npm-check-updates": "^17.0.6",
124
+ "retire": "^5.0.0",
125
+ "webpack-obfuscator": "^0.6.0"
126
+ },
127
+ "build": {
128
+ "asar": true,
129
+ "appId": "com.chahuadev.framework",
130
+ "productName": "Chahuadev Framework",
131
+ "artifactName": "${productName}-${version}.${ext}",
132
+ "directories": {
133
+ "output": "dist/${productName}-${version}",
134
+ "buildResources": "build"
135
+ },
136
+ "extraFiles": [
137
+ {
138
+ "from": "icon.png",
139
+ "to": "."
140
+ },
141
+ {
142
+ "from": "logo.png",
143
+ "to": "."
144
+ },
145
+ {
146
+ "from": "logo.ico",
147
+ "to": "."
148
+ },
149
+ {
150
+ "from": "splash.html",
151
+ "to": "."
152
+ },
153
+ {
154
+ "from": "build_assets/plugins",
155
+ "to": "plugins"
156
+ }
157
+ ],
158
+ "extraResources": [
159
+ {
160
+ "from": "vendor/node-v20.15.1-win-x64/",
161
+ "to": "node"
162
+ }
163
+ ],
164
+ "files": [
165
+ "main.js",
166
+ "app.html",
167
+ "splash.html",
168
+ "preload.js",
169
+ "package.json",
170
+ "icon.png",
171
+ "web/**/*",
172
+ "modules/**/*",
173
+ "strategies/**/*",
174
+ "backend/**/*",
175
+ "tools/**/*",
176
+ "video/**/*",
177
+ "!plugins/**/*",
178
+ "projects/**/*",
179
+ "vendor/**/*",
180
+ "config/**/*",
181
+ "validation_gateway.js",
182
+ "cli.js",
183
+ "generate-manifests.js",
184
+ "checksums.json",
185
+ "checksums.sig",
186
+ "public_key.pem",
187
+ "!private_key.pem",
188
+ "!node_modules/.cache/**/*",
189
+ "!dist/**/*",
190
+ "!projects/*/node_modules/**/*",
191
+ "!projects/*/dist/**/*",
192
+ "!builder.html",
193
+ "!generated_*/**/*",
194
+ "!**/logs/**/*",
195
+ "!test/**/*",
196
+ "!docs/**/*",
197
+ "!*.log"
198
+ ],
199
+ "win": {
200
+ "target": [
201
+ {
202
+ "target": "nsis",
203
+ "arch": [
204
+ "x64",
205
+ "ia32"
206
+
207
+ ]
208
+ },
209
+ {
210
+ "target": "msi",
211
+ "arch": [
212
+ "x64",
213
+ "ia32"
214
+ ]
215
+ },
216
+ {
217
+ "target": "portable",
218
+ "arch": [
219
+ "x64",
220
+ "ia32"
221
+ ]
222
+ },
223
+ {
224
+ "target": "dir",
225
+ "arch": [
226
+ "x64",
227
+ "ia32"
228
+ ]
229
+ }
230
+ ],
231
+ "icon": "icon.png",
232
+ "requestedExecutionLevel": "asInvoker",
233
+ "signAndEditExecutable": false,
234
+ "verifyUpdateCodeSignature": false,
235
+ "artifactName": "${productName}-${version}-${os}-${arch}.${ext}"
236
+ },
237
+ "mac": {
238
+ "target": "dmg",
239
+ "icon": "icon.png"
240
+ },
241
+ "linux": {
242
+ "target": "AppImage",
243
+ "icon": "icon.png"
244
+ },
245
+ "nsis": {
246
+ "oneClick": false,
247
+ "allowToChangeInstallationDirectory": true,
248
+ "createDesktopShortcut": true,
249
+ "createStartMenuShortcut": true,
250
+ "shortcutName": "Chahuadev Framework"
251
+ },
252
+ "msi": {
253
+ "oneClick": false,
254
+ "warningsAsErrors": false,
255
+ "additionalWixArgs": [
256
+ "-cultures:th-TH"
257
+ ]
258
+ },
259
+ "generateUpdatesFilesForAllChannels": true
260
+ }
261
+ }
packages/@chahuadev/framework/LICENSE.md ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CHAHUADEV NON-COMMERCIAL & ACCEPTABLE USE LICENSE
2
+
3
+ Copyright (c) 2026 Chahuadev. All rights reserved.
4
+
5
+ This software and its source code are provided for educational, personal, and open-source community use. By downloading, accessing, or using this software, you agree to the following conditions:
6
+
7
+ ---
8
+
9
+ ## 1. FREE DISTRIBUTION ONLY (การแจกจ่ายต้องฟรีเท่านั้น)
10
+
11
+ You are permitted to download, copy, modify, and distribute the software and its source code, provided that such distribution is **strictly free of charge**.
12
+
13
+ ---
14
+
15
+ ## 2. NO COMMERCIAL USE (ห้ามใช้หรือดัดแปลงเพื่อการค้า)
16
+
17
+ You may **NOT** use, modify, distribute, or incorporate this software (or any of its parts) for any commercial purposes. This includes, but is not limited to:
18
+
19
+ - Selling the software or derived versions.
20
+ - Locking the software behind a paywall or subscription.
21
+ - Using the software to provide commercial services.
22
+ - Placing advertisements within the software.
23
+
24
+ ---
25
+
26
+ ## 3. ACCEPTABLE USE / NO MALICIOUS USE (ห้ามใช้ในทางที่ผิด)
27
+
28
+ This software must not be used for any illegal, malicious, or harmful activities. You are strictly prohibited from using this codebase to:
29
+
30
+ - Create malware, ransomware, or any destructive software.
31
+ - Bypass security systems, steal data, or perform unauthorized access.
32
+ - Violate any local, national, or international laws.
33
+
34
+ If the software is found to be used in violation of these terms, your license to use it is immediately and permanently terminated without notice.
35
+
36
+ ---
37
+
38
+ ## 4. ATTRIBUTION (ต้องแสดงแหล่งที่มา)
39
+
40
+ Any permitted distribution or modification must clearly credit the original author:
41
+
42
+ > Original work by **Chahuadev** — https://chahuadev.com
43
+
44
+ You may not remove, obscure, or alter any copyright notices or attribution present in the source code or documentation.
45
+
46
+ ---
47
+
48
+ ## 5. DISCLAIMER OF LIABILITY (ข้อสงวนสิทธิ์ความรับผิดชอบ)
49
+
50
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
51
+
52
+ ---
53
+
54
+ For questions regarding licensing, contact: **Chahuadev** via https://chahuadev.com
packages/@chahuadev/framework/README.md ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @chahuadev/framework
2
+
3
+ The official core executable framework for Chahuadev.
4
+
5
+ <div align="center">
6
+
7
+ <p align="center">
8
+ <img src="https://huggingface.co/datasets/chahuadev/chahuadev-emoji-cleaner-tool/blob/main/chahuadev-framework.png" width="600" alt="Chahuadev Framework">
9
+ </p>
10
+
11
+ <p align="center">
12
+ <a href="https://www.npmjs.com/package/@chahuadev/framework"><img src="https://img.shields.io/npm/v/@chahuadev/framework?style=for-the-badge&color=blue" alt="NPM Version"></a>
13
+ <a href="https://www.npmjs.com/package/@chahuadev/framework"><img src="https://img.shields.io/npm/dt/@chahuadev/framework?style=for-the-badge&color=success" alt="NPM Downloads"></a>
14
+ <a href="https://huggingface.co/datasets/chahuadev/chahuadev-framework-binaries"><img src="https://img.shields.io/badge/Hugging%20Face-Dataset-FFD21E?style=for-the-badge" alt="Hugging Face Dataset"></a>
15
+ </p>
16
+
17
+ > ⏳ **Development Journey:** This framework is the proud result of **1 full year of dedicated development**. What began as a simple concept evolved into a highly advanced, secure, and robust architecture. Every line of code was meticulously crafted to ensure maximum stability and a premium experience for developers.
18
+
19
+ </div>
20
+
21
+ ---
22
+
23
+ ## � Running on Linux / WSL2 (Ubuntu)
24
+
25
+ First install the required system libraries (one-time setup):
26
+
27
+ ```bash
28
+ sudo apt-get update && sudo apt-get install -y \
29
+ libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 \
30
+ libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 \
31
+ libxrandr2 libgbm1 libasound2
32
+ ```
33
+
34
+ Then run the AppImage:
35
+
36
+ ```bash
37
+ chmod +x "Chahuadev-Framework.AppImage"
38
+ DISPLAY=:0 WAYLAND_DISPLAY=wayland-0 \
39
+ ./"Chahuadev-Framework.AppImage" \
40
+ --appimage-extract-and-run --no-sandbox --disable-gpu
41
+ ```
42
+
43
+ > **WSL2 tip:** Copy to WSL native filesystem first:
44
+ > ```bash
45
+ > # Path after: npm install -g @chahuadev/framework
46
+ > # (no sudo)
47
+ > cp ~/.npm-global/lib/node_modules/@chahuadev/framework/bin/Chahuadev-Framework.AppImage /tmp/ChahuadevFramework.AppImage
48
+ > # (with sudo)
49
+ > # cp /usr/lib/node_modules/@chahuadev/framework/bin/Chahuadev-Framework.AppImage /tmp/ChahuadevFramework.AppImage
50
+ > chmod +x /tmp/ChahuadevFramework.AppImage
51
+ > DISPLAY=:0 WAYLAND_DISPLAY=wayland-0 /tmp/ChahuadevFramework.AppImage \
52
+ > --appimage-extract-and-run --no-sandbox --disable-gpu
53
+ > ```
54
+
55
+ ---
56
+
57
+ ## �🛡️ CRITICAL SECURITY WARNING - FORTRESS PROTECTION
58
+
59
+ ### Maximum Security Architecture
60
+ - **Intelligent OS Routing**: Automatically detects and securely isolates platform-specific binaries.
61
+ - **Strict Execution Boundaries**: Prevents unauthorized cross-platform executions and corrupted loads.
62
+ - **Anti-Hack Protection System**: Built-in safeguards against malicious executable swapping.
63
+ - **Dependency Isolation**: Operates securely via standalone binaries without bloating your system.
64
+
65
+ ---
66
+
67
+ ## ⚙️ Installation & Usage
68
+
69
+ > **Multi-Platform Support:** This framework runs seamlessly on **Windows (x64, ia32)** and **Linux (x64)**.
70
+ > Our system automatically detects your operating system and securely downloads the required binary behind the scenes.
71
+
72
+ ### Global Install (Recommended for CLI)
73
+ If you want to use the framework from your terminal anywhere on your system:
74
+
75
+ ```bash
76
+ npm install -g @chahuadev/framework --foreground-scripts --force
77
+
78
+ ```
79
+ ---
80
+
81
+
82
+ ### When you install:**
83
+ 1. npm detects your OS and architecture
84
+ 2. Installs only the required platform-specific package
85
+ 3. index.js routes to the correct executable
86
+
87
+ This ensures:
88
+ - Minimal disk space usage (only your OS binary)
89
+ - No cross-platform conflicts
90
+ - Automatic binary selection
91
+
92
+ ---
93
+
94
+ ## Platform Support
95
+
96
+ | Platform | Architecture | Status | Format |
97
+ |----------|-------------|--------|--------|
98
+ | Windows | 64-bit (x64) | Supported | EXE |
99
+ | Windows | 32-bit (ia32) | Supported | EXE |
100
+ | Linux | 64-bit (x64) | Supported | AppImage |
101
+ | macOS | Intel (x64) | Coming Soon | DMG/App |
102
+ | macOS | Apple Silicon (arm64) | Coming Soon | DMG/App |
103
+
104
+ ---
105
+
106
+ ## Package Structure
107
+
108
+
109
+ @chahuadev/
110
+ ├── framework/
111
+ │ └── index.js
112
+ │ └── install.js
113
+ │ └── package.json
114
+ │ └── README.md
115
+
116
+ ---
117
+
118
+ ## Troubleshooting
119
+
120
+ ### "Command not found: chahuadev-framework"
121
+ Make sure you installed globally:
122
+ ```bash
123
+ npm install -g @chahuadev/framework --foreground-scripts --force
124
+ ```
125
+
126
+ ### "Module not found"
127
+ If using locally, ensure it's installed:
128
+ ```bash
129
+ npm install -g @chahuadev/framework --foreground-scripts --force
130
+ ```
131
+
132
+ ### "Unsupported platform"
133
+ Your OS/architecture combination is not yet supported. Check the Platform Support table above.
134
+
135
+ ---
136
+
137
+ ## License
138
+ Non-Commercial & Acceptable Use — See [LICENSE.md](LICENSE.md)
139
+
140
+ ---
141
+
142
+
143
+
packages/@chahuadev/framework/index.js ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ const path = require('path');
4
+ const { spawnSync } = require('child_process');
5
+ const fs = require('fs');
6
+ const os = require('os');
7
+
8
+ const platform = os.platform();
9
+ let exeName = '';
10
+
11
+ if (platform === 'win32') {
12
+ exeName = 'Chahuadev-Framework.exe';
13
+ } else {
14
+ console.error(`Chahuadev Framework does not support ${platform} yet.`);
15
+ process.exit(1);
16
+ }
17
+
18
+ const exePath = path.join(__dirname, 'bin', exeName);
19
+ if (!fs.existsSync(exePath)) {
20
+ console.error(`Executable not found: ${exePath}`);
21
+ console.error('Try running "npm install" again to download the binary.');
22
+ process.exit(1);
23
+ }
24
+
25
+ const result = spawnSync(exePath, process.argv.slice(2), { stdio: 'inherit' });
26
+ process.exit(result.status ?? 0);
packages/@chahuadev/framework/install.js ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const https = require('https');
5
+ const os = require('os');
6
+
7
+ const platform = os.platform();
8
+ const arch = os.arch();
9
+
10
+ const R2_BASE = 'https://pub-419d22521da042dfb27d1f404b3eb8a6.r2.dev';
11
+
12
+
13
+ let downloadUrl = '';
14
+ let fileName = '';
15
+
16
+ if (platform === 'win32') {
17
+ downloadUrl = `${R2_BASE}/Chahuadev-Framework.exe`;
18
+ fileName = 'Chahuadev Framework.exe';
19
+ } else if (platform === 'linux') {
20
+ downloadUrl = `${R2_BASE}/Chahuadev-Framework.AppImage`;
21
+ fileName = 'Chahuadev Framework.AppImage';
22
+ } else {
23
+ console.warn(`Chahuadev Framework does not support ${platform} ${arch} yet.`);
24
+ process.exit(0);
25
+ }
26
+
27
+ const binDir = path.join(__dirname, 'bin');
28
+ if (!fs.existsSync(binDir)) fs.mkdirSync(binDir, { recursive: true });
29
+
30
+ const filePath = path.join(binDir, fileName);
31
+ console.log(`Downloading Chahuadev Framework for ${platform} (${arch})...`);
32
+ console.log('Please wait, this may take a few minutes.\n');
33
+
34
+ function downloadFile(url, dest) {
35
+ https.get(url, (response) => {
36
+ if (response.statusCode === 301 || response.statusCode === 302) {
37
+ return downloadFile(response.headers.location, dest);
38
+ }
39
+ if (response.statusCode !== 200) {
40
+ console.error(`Download failed: HTTP ${response.statusCode}`);
41
+ process.exit(1);
42
+ }
43
+ const totalBytes = parseInt(response.headers['content-length'], 10);
44
+ let downloadedBytes = 0;
45
+ const file = fs.createWriteStream(dest);
46
+ response.on('data', (chunk) => {
47
+ downloadedBytes += chunk.length;
48
+ if (!isNaN(totalBytes)) {
49
+ const percent = ((downloadedBytes / totalBytes) * 100).toFixed(1);
50
+ const dlMB = (downloadedBytes / (1024 * 1024)).toFixed(1);
51
+ const totalMB = (totalBytes / (1024 * 1024)).toFixed(1);
52
+ const filled = Math.round(30 * downloadedBytes / totalBytes);
53
+ const bar = '#'.repeat(filled) + '-'.repeat(30 - filled);
54
+ process.stdout.write(`\r[${bar}] ${percent}% (${dlMB} MB / ${totalMB} MB)`);
55
+ } else {
56
+ process.stdout.write(`\rDownloading... ${(downloadedBytes / (1024 * 1024)).toFixed(1)} MB`);
57
+ }
58
+ });
59
+ response.pipe(file);
60
+ file.on('finish', () => {
61
+ file.close();
62
+ console.log('\n\nDownload completed.');
63
+ console.log(`Saved to: ${dest}\n`);
64
+ if (platform !== 'win32') fs.chmodSync(dest, 0o755);
65
+ });
66
+ }).on('error', (err) => {
67
+ fs.unlink(dest, () => {});
68
+ console.error('\nDownload failed:', err.message);
69
+ process.exit(1);
70
+ });
71
+ }
72
+
73
+ downloadFile(downloadUrl, filePath);
packages/@chahuadev/framework/package.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@chahuadev/framework",
3
+ "version": "6.0.1",
4
+ "description": "Chahuadev Framework",
5
+ "main": "index.js",
6
+ "bin": {
7
+ "chahuadev-framework": "index.js"
8
+ },
9
+ "scripts": {
10
+ "postinstall": "node install.js"
11
+ },
12
+ "license": "SEE LICENSE IN LICENSE.md",
13
+ "publishConfig": {
14
+ "access": "public"
15
+ }
16
+ }