-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1190 lines (1032 loc) · 40.8 KB
/
main.js
File metadata and controls
1190 lines (1032 loc) · 40.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { app, BrowserWindow, ipcMain, dialog, protocol } = require('electron');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
// Try to load TypeScript, but don't fail if it's not available
let ts;
try {
ts = require('typescript');
} catch (err) {
console.warn('TypeScript module not available:', err.message);
ts = null;
}
const isDev = process.env.NODE_ENV === 'development' || process.env.NODE_ENV !== 'production' && process.defaultApp;
let mainWindow;
// Register custom protocol schemes before app is ready
protocol.registerSchemesAsPrivileged([
{ scheme: 'app', privileges: { secure: true, standard: true, supportFetchAPI: true, corsEnabled: true } }
]);
const sanitizeRelativeDirectory = (relativeDir) => {
if (typeof relativeDir !== 'string') {
return 'chats';
}
const normalized = relativeDir
.trim()
.replace(/^(?:\.\/)+/, '')
.replace(/^\/+/, '')
.replace(/^\\+/, '')
.replace(/\\/g, '/');
const segments = normalized
.split('/')
.map((segment) => segment.trim())
.filter((segment) => segment.length > 0 && segment !== '.' && segment !== '..');
return segments.length > 0 ? segments.join('/') : 'chats';
};
const sanitizeFileName = (fileName) => {
const fallback = 'chat.md';
if (!fileName || typeof fileName !== 'string') {
return fallback;
}
const trimmed = fileName.trim();
if (!trimmed) {
return fallback;
}
const normalized = trimmed.replace(/[\\/]/g, '');
const hasMarkdownExtension = normalized.toLowerCase().endsWith('.md');
const baseName = hasMarkdownExtension ? normalized.slice(0, -3) : normalized;
const sanitizedBase = baseName
.replace(/[^a-z0-9\-_.\s]/gi, '')
.replace(/\s+/g, '-');
const finalBase = sanitizedBase || 'chat';
return `${finalBase}.md`;
};
function createWindow() {
const preloadPath = path.join(__dirname, 'preload.js');
console.log('[MAIN] Preload script path:', preloadPath);
console.log('[MAIN] Preload script exists:', fs.existsSync(preloadPath));
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
minWidth: 800,
minHeight: 600,
title: 'Code Editor',
show: false, // Don't show until ready-to-show
webPreferences: {
nodeIntegration: false, // Disable for security
contextIsolation: true, // Enable for security
enableRemoteModule: false, // Disable for security
preload: preloadPath, // Use preload script
webSecurity: true, // Enable web security
allowRunningInsecureContent: false,
experimentalFeatures: false,
// Allow HTTPS requests to external APIs
webgl: false,
plugins: false,
// Enable fetch API for OpenRouter
nodeIntegrationInWorker: false,
nodeIntegrationInSubFrames: false
}
});
// Show window when ready to prevent visual flash
mainWindow.once('ready-to-show', () => {
mainWindow.show();
// Focus the window to ensure it's interactive
mainWindow.focus();
// Only open devtools in development mode and when explicitly requested
if (isDev && process.argv.includes('--dev-tools')) {
mainWindow.webContents.openDevTools();
}
});
// Set Content Security Policy for better security
const cspPolicy = isDev
? "default-src 'self' 'unsafe-inline' data: blob: ws: wss: http://localhost:* http://127.0.0.1:* https://va.vercel-scripts.com https://openrouter.ai https://*.openrouter.ai; script-src 'self' 'unsafe-inline' 'unsafe-eval' http://localhost:* http://127.0.0.1:* https://va.vercel-scripts.com; style-src 'self' 'unsafe-inline' http://localhost:* http://127.0.0.1:*; img-src 'self' data: blob: http://localhost:* http://127.0.0.1:*; font-src 'self' data: http://localhost:* http://127.0.0.1:*; connect-src 'self' ws: wss: http://localhost:* http://127.0.0.1:* https://vercel.live https://*.vercel.app https://va.vercel-scripts.com https://openrouter.ai https://*.openrouter.ai;"
: "default-src 'self' 'unsafe-inline' data: blob: file: app: https://openrouter.ai https://*.openrouter.ai; script-src 'self' 'unsafe-inline' 'unsafe-eval' file: app: https://va.vercel-scripts.com; style-src 'self' 'unsafe-inline' data: file: app:; img-src 'self' data: blob: file: app:; font-src 'self' data: file: app:; connect-src 'self' file: app: https://vercel.live https://*.vercel.app https://va.vercel-scripts.com https://openrouter.ai https://*.openrouter.ai;";
mainWindow.webContents.session.webRequest.onHeadersReceived((details, callback) => {
callback({
responseHeaders: {
...details.responseHeaders,
'Content-Security-Policy': [cspPolicy]
}
});
});
// Also set CSP via session
mainWindow.webContents.session.webRequest.onBeforeRequest((details, callback) => {
callback({});
});
// Protocol registration is handled in app.whenReady() to avoid conflicts
if (isDev) {
const devPort = process.env.PORT || '45623';
const devUrl = process.env.DEV_SERVER_URL || `http://localhost:${devPort}`;
mainWindow.loadURL(devUrl);
} else {
// En producción, la URL se establecerá después de que el servidor Next.js esté listo
console.log('[MAIN] Waiting for Next.js server to be ready...');
}
// Prevent new window creation
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
return { action: 'deny' };
});
}
app.whenReady().then(() => {
// Disable CSP warnings in development
if (isDev) {
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true';
}
// En producción, iniciar servidor Next.js antes de crear la ventana
if (!isDev) {
try {
const next = require('next');
const { parse } = require('url');
const nextApp = next({ dev: false, dir: __dirname });
const handle = nextApp.getRequestHandler();
nextApp.prepare().then(() => {
const { createServer } = require('http');
const server = createServer((req, res) => {
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
});
server.listen(3000, (err) => {
if (err) {
console.error('[MAIN] Error starting Next.js server:', err);
// Crear ventana con mensaje de error
createWindow();
if (mainWindow) {
mainWindow.loadURL(`data:text/html,<html><body><h1>Error: No se pudo cargar la aplicación</h1><p>Error al iniciar el servidor: ${err.message}</p></body></html>`);
}
return;
}
console.log('[MAIN] Next.js server ready on http://localhost:3000');
// Ahora crear la ventana y cargar la URL
createWindow();
if (mainWindow) {
mainWindow.loadURL('http://localhost:3000');
}
});
}).catch((err) => {
console.error('[MAIN] Error preparing Next.js app:', err);
// Crear ventana con mensaje de error
createWindow();
if (mainWindow) {
mainWindow.loadURL(`data:text/html,<html><body><h1>Error: No se pudo cargar la aplicación</h1><p>Error al preparar la aplicación: ${err.message}</p></body></html>`);
}
});
} catch (err) {
console.error('[MAIN] Next.js not available, cannot start server:', err.message);
// Show error to user
createWindow();
if (mainWindow) {
mainWindow.loadURL(`data:text/html,<html><body><h1>Error: Next.js not available</h1><p>The application requires Next.js to run in production mode. Please rebuild the application with all dependencies included.</p><p>Error: ${err.message}</p></body></html>`);
}
}
} else {
// En desarrollo, crear la ventana directamente
createWindow();
}
// Register custom protocol to handle static files correctly (moved here from before)
if (!isDev) {
// Register a custom protocol for serving static files
protocol.registerFileProtocol('app', (request, callback) => {
const url = request.url.substr(6); // Remove 'app://' prefix
const filePath = path.join(__dirname, 'out', url);
console.log('[PROTOCOL] app:// request for:', url, 'resolved to:', filePath);
callback({ path: filePath });
});
// Intercept file protocol for better static file handling
protocol.interceptFileProtocol('file', (request, callback) => {
let url = request.url.substr(7); // Remove 'file://' prefix
let finalPath;
console.log('[PROTOCOL] Intercepting file:// request for:', url);
// Handle relative paths starting with _next
if (url.startsWith('_next/') || url.includes('/_next/')) {
const relativePath = url.startsWith('_next/') ? url : url.substring(url.indexOf('_next/'));
finalPath = path.join(__dirname, 'out', relativePath);
console.log('[PROTOCOL] _next path detected, resolving to:', finalPath);
} else if (url.includes('static/css/') || url.includes('static/js/') || url.includes('static/chunks/')) {
// Manejar archivos CSS y JavaScript directamente
const staticPath = url.includes('/out/') ? url : path.join(__dirname, 'out', url);
finalPath = staticPath;
console.log('[PROTOCOL] Static asset detected, resolving to:', finalPath);
} else if (url.includes('out/index.html') || url === path.join(__dirname, 'out/index.html')) {
// Si es la página principal, asegurarse de que la ruta es correcta
finalPath = path.join(__dirname, 'out/index.html');
console.log('[PROTOCOL] Index file detected, resolving to:', finalPath);
} else {
finalPath = url;
console.log('[PROTOCOL] Other file detected, using original path:', finalPath);
}
// Verificar que el archivo existe
if (fs.existsSync(finalPath)) {
console.log('[PROTOCOL] File exists:', finalPath);
} else {
console.log('[PROTOCOL] WARNING: File does not exist:', finalPath);
}
callback({ path: finalPath });
});
}
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// IPC handlers for secure communication
ipcMain.handle('dialog:openFile', async () => {
const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
properties: ['openFile'],
filters: [
{ name: 'Text Files', extensions: ['txt', 'md', 'js', 'ts', 'jsx', 'tsx', 'css', 'html', 'json'] },
{ name: 'All Files', extensions: ['*'] }
]
});
if (canceled) {
return null;
} else {
try {
const content = fs.readFileSync(filePaths[0], 'utf-8');
return { path: filePaths[0], content };
} catch (error) {
console.error('Error reading file:', error);
return null;
}
}
});
ipcMain.handle('dialog:saveFile', async (event, content) => {
const { canceled, filePath } = await dialog.showSaveDialog(mainWindow, {
filters: [
{ name: 'Text Files', extensions: ['txt', 'md', 'js', 'ts', 'jsx', 'tsx', 'css', 'html', 'json'] },
{ name: 'All Files', extensions: ['*'] }
]
});
if (canceled) {
return false;
} else {
try {
fs.writeFileSync(filePath, content, 'utf-8');
return true;
} catch (error) {
console.error('Error saving file:', error);
return false;
}
}
});
// Auto save file to specified path without dialog
ipcMain.handle('fs:saveFile', async (event, filePath, content) => {
try {
// Ensure directory exists
const dir = path.dirname(filePath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(filePath, content, 'utf-8');
console.log('[MAIN] File saved automatically:', filePath);
return { success: true, filePath: filePath };
} catch (error) {
console.error('[MAIN] Error saving file:', error);
return { success: false, error: error.message };
}
});
ipcMain.handle('app:getVersion', () => {
return app.getVersion();
});
ipcMain.handle('window:minimize', () => {
mainWindow.minimize();
});
ipcMain.handle('window:maximize', () => {
if (mainWindow.isMaximized()) {
mainWindow.unmaximize();
} else {
mainWindow.maximize();
}
});
ipcMain.handle('window:close', () => {
mainWindow.close();
});
ipcMain.handle('dialog:openDirectory', async () => {
console.log('[DEBUG] dialog:openDirectory called');
const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
properties: ['openDirectory']
});
if (canceled) {
console.log('[DEBUG] Directory selection canceled');
return null;
} else {
try {
const directoryPath = filePaths[0];
console.log('[DEBUG] Selected directory:', directoryPath);
const directoryStructure = await readDirectoryStructure(directoryPath);
console.log('[DEBUG] Directory structure read, items count:', directoryStructure.length);
console.log('[DEBUG] First few items:', directoryStructure.slice(0, 3));
const result = { path: directoryPath, structure: directoryStructure };
console.log('[DEBUG] Returning result to frontend:', { path: result.path, structureLength: result.structure.length });
console.log('🚀 [BACKEND] ===== SENDING DATA TO FRONTEND =====');
console.log('📦 [BACKEND] Result structure sample:', JSON.stringify(result.structure.slice(0, 2), null, 2));
return result;
} catch (error) {
console.error('[ERROR] Error reading directory structure:', error);
return null;
}
}
});
// Test handler for debugging
ipcMain.handle('test:ping', async () => {
console.log('[DEBUG] Test ping received');
return { success: true, message: 'Pong from main process', timestamp: Date.now() };
});
// Handler para verificar si un archivo existe
ipcMain.handle('fs:fileExists', async (event, filePath) => {
try {
await fs.promises.access(filePath, fs.constants.F_OK);
return { success: true, exists: true };
} catch (error) {
return { success: true, exists: false };
}
});
ipcMain.handle('fs:readFile', async (event, filePath) => {
try {
const content = await fs.promises.readFile(filePath, 'utf-8');
return { success: true, content };
} catch (error) {
console.error('Error reading file:', filePath, error);
return { success: false, error: error.message };
}
});
// Handler para carga lazy de subdirectorios
ipcMain.handle('fs:loadSubdirectory', async (event, dirPath, rootPath) => {
try {
console.log('[DEBUG] Loading subdirectory:', dirPath);
const structure = await readDirectoryStructure(dirPath, {
maxDepth: 1,
currentDepth: 0,
rootPath: rootPath,
lazyLoad: false, // Cambiar a false para cargar archivos inmediatamente
includeFileStats: false
});
return { success: true, structure };
} catch (error) {
console.error('Error loading subdirectory:', dirPath, error);
return { success: false, error: error.message };
}
});
// Handler para refrescar la estructura de directorios
ipcMain.handle('fs:readDirectoryStructure', async (event, dirPath) => {
try {
console.log('[DEBUG] Refreshing directory structure for:', dirPath);
const structure = await readDirectoryStructure(dirPath);
console.log('[DEBUG] Refreshed structure loaded, items count:', structure.length);
return { success: true, structure };
} catch (error) {
console.error('Error refreshing directory structure:', dirPath, error);
return { success: false, error: error.message };
}
});
// Handler para obtener estadísticas de archivos
ipcMain.handle('fs:getFileStats', async (event, filePath) => {
try {
const stats = await fs.promises.stat(filePath);
return {
success: true,
stats: {
size: stats.size,
modified: stats.mtime,
created: stats.birthtime,
isDirectory: stats.isDirectory(),
isFile: stats.isFile()
}
};
} catch (error) {
console.error('Error getting file stats:', filePath, error);
return { success: false, error: error.message };
}
});
// Handler para búsqueda de archivos
ipcMain.handle('fs:searchFiles', async (event, searchPath, query, options = {}) => {
try {
const { maxResults = 100, includeContent = false, fileTypes = [] } = options;
console.log('[DEBUG] Searching files in:', searchPath, 'query:', query);
const results = [];
await searchFilesRecursive(searchPath, query, results, maxResults, includeContent, fileTypes);
return { success: true, results };
} catch (error) {
console.error('Error searching files:', error);
return { success: false, error: error.message };
}
});
// Función auxiliar para búsqueda recursiva
async function searchFilesRecursive(dirPath, query, results, maxResults, includeContent, fileTypes, depth = 0) {
if (results.length >= maxResults || depth > 10) return;
try {
const entries = await fs.promises.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
if (results.length >= maxResults) break;
if (shouldIgnoreEntry(entry.name, entry.isDirectory())) continue;
const fullPath = path.join(dirPath, entry.name);
if (entry.isFile()) {
const matchesName = entry.name.toLowerCase().includes(query.toLowerCase());
const matchesType = fileTypes.length === 0 || fileTypes.includes(path.extname(entry.name).toLowerCase());
if (matchesName && matchesType) {
const result = {
name: entry.name,
path: fullPath,
type: 'file',
extension: path.extname(entry.name)
};
if (includeContent) {
try {
const content = await fs.promises.readFile(fullPath, 'utf-8');
if (content.toLowerCase().includes(query.toLowerCase())) {
result.content = content;
result.matchType = 'content';
}
} catch (error) {
// Ignore files that can't be read as text
}
}
results.push(result);
}
} else if (entry.isDirectory()) {
await searchFilesRecursive(fullPath, query, results, maxResults, includeContent, fileTypes, depth + 1);
}
}
} catch (error) {
console.warn('Error reading directory during search:', dirPath, error);
}
}
// Function to recursively read directory structure
// Cache para directorios ya leídos
const directoryCache = new Map();
const CACHE_EXPIRY = 30000; // 30 segundos
// Filtros optimizados para archivos y directorios a ignorar
const IGNORED_DIRS = new Set([
'node_modules', 'dist', 'build', '.next', '.git', '.svn', '.hg',
'coverage', '.nyc_output', '.cache', 'tmp', 'temp', '.tmp',
'vendor', 'target', 'bin', 'obj', '.gradle', '.idea', '.vscode'
]);
const IGNORED_FILES = new Set([
'.DS_Store', 'Thumbs.db', '.gitignore', '.gitkeep',
'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'
]);
async function readDirectoryStructure(dirPath, options = {}) {
const {
maxDepth = Infinity, // Eliminamos la limitación de profundidad
currentDepth = 0,
rootPath = null,
lazyLoad = false, // Deshabilitamos lazy loading para cargar todo
includeFileStats = false,
maxFiles = 10000 // Aumentamos el límite de archivos
} = options;
if (currentDepth >= maxDepth) return [];
// Set root path on first call
const actualRootPath = rootPath || dirPath;
if (rootPath === null) {
console.log('[DEBUG] readDirectoryStructure starting with root:', actualRootPath);
}
// Check cache first
const cacheKey = `${dirPath}:${currentDepth}:${maxDepth}`;
const cached = directoryCache.get(cacheKey);
if (cached && Date.now() - cached.timestamp < CACHE_EXPIRY) {
console.log('[DEBUG] Using cached result for:', dirPath);
return cached.data;
}
try {
const entries = await fs.promises.readdir(dirPath, { withFileTypes: true });
console.log('[DEBUG] Reading directory:', dirPath, 'found', entries.length, 'entries');
const structure = [];
let fileCount = 0;
// Procesar directorios primero para mejor UX
const directories = entries.filter(entry => entry.isDirectory() && !shouldIgnoreEntry(entry.name, true));
const files = entries.filter(entry => entry.isFile() && !shouldIgnoreEntry(entry.name, false));
// Procesar directorios
for (const entry of directories) {
const fullPath = path.join(dirPath, entry.name);
const relativePath = path.relative(actualRootPath, fullPath);
let children = [];
let hasChildren = false;
// Siempre cargar hijos recursivamente para todos los niveles
try {
children = await readDirectoryStructure(fullPath, {
...options,
currentDepth: currentDepth + 1,
rootPath: actualRootPath
});
hasChildren = children.length > 0;
} catch (error) {
console.warn('[WARN] Could not read subdirectory:', fullPath, error);
children = [];
hasChildren = false;
}
structure.push({
name: entry.name,
type: 'directory',
path: relativePath,
fullPath: fullPath,
children: children,
hasChildren: hasChildren,
isExpanded: true, // Auto-expandir todos los niveles
isLoaded: true // Marcar todos como cargados
});
}
// Procesar archivos con límite
for (const entry of files) {
if (fileCount >= maxFiles) {
console.log('[DEBUG] File limit reached, stopping at:', maxFiles);
break;
}
const fullPath = path.join(dirPath, entry.name);
const relativePath = path.relative(actualRootPath, fullPath);
const fileInfo = {
name: entry.name,
type: 'file',
path: relativePath,
fullPath: fullPath
};
let stats = null;
try {
stats = await fs.promises.stat(fullPath);
} catch (error) {
console.warn('[WARN] Could not get stats for file:', fullPath, error.message);
}
if (stats) {
// Incluir estadísticas del archivo si se solicita
if (includeFileStats) {
fileInfo.size = stats.size;
fileInfo.modified = stats.mtime;
fileInfo.extension = path.extname(entry.name).toLowerCase();
}
const contextMetadata = await generateFileContextMetadata(fullPath, relativePath, entry.name, stats);
if (contextMetadata) {
fileInfo.context = contextMetadata;
}
}
structure.push(fileInfo);
fileCount++;
}
// Sort optimizado: directorios primero, luego archivos, ambos alfabéticamente
const sortedStructure = structure.sort((a, b) => {
if (a.type !== b.type) {
return a.type === 'directory' ? -1 : 1;
}
return a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' });
});
// Cache del resultado
directoryCache.set(cacheKey, {
data: sortedStructure,
timestamp: Date.now()
});
return sortedStructure;
} catch (error) {
console.error('Error reading directory:', dirPath, error);
return [];
}
}
function shouldIgnoreEntry(name, isDirectory) {
if (name.startsWith('.') && name !== '.env') return true;
if (isDirectory) return IGNORED_DIRS.has(name);
return IGNORED_FILES.has(name);
}
const TEXT_FILE_EXTENSIONS = new Set([
'.txt', '.md', '.markdown', '.json', '.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.c', '.h', '.cpp', '.hpp', '.java', '.py', '.rb',
'.go', '.rs', '.swift', '.php', '.cs', '.kt', '.kts', '.scala', '.sql', '.yml', '.yaml', '.toml', '.ini', '.cfg', '.conf', '.css',
'.scss', '.sass', '.less', '.html', '.htm', '.xml', '.svg', '.env', '.gitignore'
]);
const CONTEXT_PREVIEW_BYTES = 16 * 1024; // 16KB preview for summaries
const CONTEXT_HASH_SAMPLE_BYTES = 64 * 1024; // Sample up to 64KB for hashing
const SUMMARY_MAX_LINES = 12;
const SUMMARY_MAX_LENGTH = 600;
async function generateFileContextMetadata(fullPath, relativePath, displayName, stats) {
try {
const extension = path.extname(fullPath).toLowerCase();
const metadata = {
path: relativePath,
name: displayName,
extension,
size: stats.size,
modified: stats.mtimeMs
};
const isTextFile = isLikelyTextFile(extension, stats.size);
const signature = await computeFileSignature(fullPath, stats);
if (signature) {
metadata.hash = signature;
}
if (!isTextFile || stats.size === 0) {
return metadata;
}
const snippet = await readFileSnippet(fullPath, Math.min(CONTEXT_PREVIEW_BYTES, stats.size));
if (snippet) {
metadata.preview = snippet;
metadata.summary = createSummaryFromContent(snippet);
metadata.lineCount = snippet.split(/\r?\n/).length;
}
return metadata;
} catch (error) {
console.warn('[WARN] Could not generate context metadata for file:', fullPath, error.message);
return null;
}
}
function isLikelyTextFile(extension, fileSize) {
if (TEXT_FILE_EXTENSIONS.has(extension)) {
return true;
}
// Assume small files are text by default
return fileSize <= 8 * 1024;
}
async function readFileSnippet(fullPath, length) {
try {
const fileHandle = await fs.promises.open(fullPath, 'r');
const buffer = Buffer.alloc(length);
const { bytesRead } = await fileHandle.read(buffer, 0, length, 0);
await fileHandle.close();
return buffer.slice(0, bytesRead).toString('utf-8');
} catch (error) {
console.warn('[WARN] Could not read snippet for file:', fullPath, error.message);
return '';
}
}
async function computeFileSignature(fullPath, stats) {
try {
if (stats.size === 0) {
return 'empty';
}
const hash = crypto.createHash('sha1');
const sampleEnd = Math.min(stats.size - 1, CONTEXT_HASH_SAMPLE_BYTES - 1);
await new Promise((resolve, reject) => {
const stream = fs.createReadStream(fullPath, { start: 0, end: sampleEnd });
stream.on('data', (chunk) => hash.update(chunk));
stream.on('end', resolve);
stream.on('error', reject);
});
return `${hash.digest('hex')}:${stats.size}:${stats.mtimeMs}`;
} catch (error) {
console.warn('[WARN] Could not hash file for context metadata:', fullPath, error.message);
return `size:${stats.size}|mtime:${stats.mtimeMs}`;
}
}
function createSummaryFromContent(content) {
if (!content) {
return '';
}
const normalized = content.replace(/\r\n/g, '\n').trim();
const lines = normalized.split('\n').slice(0, SUMMARY_MAX_LINES);
const joined = lines.join('\n');
if (joined.length <= SUMMARY_MAX_LENGTH) {
return joined;
}
return `${joined.slice(0, SUMMARY_MAX_LENGTH)}…`;
}
// Handler para crear archivos
ipcMain.handle('fs:createFile', async (event, filePath, content = '') => {
try {
console.log('[DEBUG] Creating file:', filePath);
// Verificar si el archivo ya existe
try {
await fs.promises.access(filePath, fs.constants.F_OK);
return { success: false, error: 'El archivo ya existe' };
} catch (error) {
// El archivo no existe, podemos crearlo
}
// Crear el directorio padre si no existe
const dirPath = path.dirname(filePath);
await fs.promises.mkdir(dirPath, { recursive: true });
// Crear el archivo
await fs.promises.writeFile(filePath, content, 'utf-8');
console.log('[DEBUG] File created successfully:', filePath);
return { success: true, filePath };
} catch (error) {
console.error('Error creating file:', filePath, error);
return { success: false, error: error.message };
}
});
// Handler para crear directorios
ipcMain.handle('fs:createDirectory', async (event, dirPath) => {
try {
console.log('[DEBUG] Creating directory:', dirPath);
// Verificar si el directorio ya existe
try {
const stats = await fs.promises.stat(dirPath);
if (stats.isDirectory()) {
return { success: false, error: 'El directorio ya existe' };
}
} catch (error) {
// El directorio no existe, podemos crearlo
}
// Crear el directorio
await fs.promises.mkdir(dirPath, { recursive: true });
console.log('[DEBUG] Directory created successfully:', dirPath);
return { success: true, dirPath };
} catch (error) {
console.error('Error creating directory:', dirPath, error);
return { success: false, error: error.message };
}
});
// Handler para mover archivos y directorios
ipcMain.handle('fs:moveFileOrDirectory', async (event, sourcePath, destPath) => {
try {
console.log('[DEBUG] Moving from:', sourcePath, 'to:', destPath);
// Verificar que el archivo/directorio origen existe
try {
await fs.promises.access(sourcePath, fs.constants.F_OK);
} catch (error) {
return { success: false, error: 'El archivo o directorio origen no existe' };
}
// Verificar que el destino no existe
try {
await fs.promises.access(destPath, fs.constants.F_OK);
return { success: false, error: 'Ya existe un archivo o directorio con ese nombre en el destino' };
} catch (error) {
// El destino no existe, podemos mover
}
// Crear el directorio padre del destino si no existe
const destDir = path.dirname(destPath);
await fs.promises.mkdir(destDir, { recursive: true });
// Mover el archivo o directorio
await fs.promises.rename(sourcePath, destPath);
console.log('[DEBUG] File/directory moved successfully from:', sourcePath, 'to:', destPath);
return { success: true, sourcePath, destPath };
} catch (error) {
console.error('Error moving file/directory:', sourcePath, 'to:', destPath, error);
return { success: false, error: error.message };
}
});
// Handler para crear carpeta de chats
ipcMain.handle('fs:createChatsFolder', async (event, workspacePath, relativeDir = 'chats') => {
try {
const safeRelativeDir = sanitizeRelativeDirectory(relativeDir);
const chatsPath = path.join(workspacePath, safeRelativeDir);
console.log('[DEBUG] Creating chats folder at:', chatsPath);
// Verificar si la carpeta ya existe
try {
await fs.promises.access(chatsPath, fs.constants.F_OK);
console.log('[DEBUG] Chats folder already exists');
return { success: true, path: chatsPath, created: false, relativePath: safeRelativeDir };
} catch (error) {
// La carpeta no existe, crearla
await fs.promises.mkdir(chatsPath, { recursive: true });
console.log('[DEBUG] Chats folder created successfully');
return { success: true, path: chatsPath, created: true, relativePath: safeRelativeDir };
}
} catch (error) {
console.error('Error creating chats folder:', error);
return { success: false, error: error.message };
}
});
// Handler para guardar conversación en archivo MD
ipcMain.handle('fs:saveChatToFile', async (event, workspacePath, relativeDir = 'chats', fileName, content) => {
try {
const safeRelativeDir = sanitizeRelativeDirectory(relativeDir);
const chatsPath = path.join(workspacePath, safeRelativeDir);
// Asegurar que la carpeta chats existe
try {
await fs.promises.access(chatsPath, fs.constants.F_OK);
} catch (error) {
await fs.promises.mkdir(chatsPath, { recursive: true });
}
const fullFileName = sanitizeFileName(fileName);
const filePath = path.join(chatsPath, fullFileName);
console.log('[DEBUG] Saving chat to:', filePath);
// Guardar el archivo
await fs.promises.writeFile(filePath, content, 'utf-8');
return {
success: true,
filePath: filePath,
fileName: fullFileName,
relativePath: path.join(safeRelativeDir, fullFileName)
};
} catch (error) {
console.error('Error saving chat file:', error);
return { success: false, error: error.message };
}
});
// Handler para listar archivos de chat existentes
ipcMain.handle('fs:listChatFiles', async (event, workspacePath, relativeDir = 'chats') => {
try {
const safeRelativeDir = sanitizeRelativeDirectory(relativeDir);
const chatsPath = path.join(workspacePath, safeRelativeDir);
// Verificar si la carpeta existe
try {
await fs.promises.access(chatsPath, fs.constants.F_OK);
} catch (error) {
return { success: true, files: [] };
}
const files = await fs.promises.readdir(chatsPath);
const chatFiles = files
.filter(file => file.endsWith('.md'))
.map(file => ({
name: file,
path: path.join(chatsPath, file),
relativePath: path.join(safeRelativeDir, file)
}))
.sort((a, b) => b.name.localeCompare(a.name)); // Ordenar por fecha (más reciente primero)
return { success: true, files: chatFiles };
} catch (error) {
console.error('Error listing chat files:', error);
return { success: false, error: error.message };
}
});
// Handler para leer contenido de un archivo de chat
ipcMain.handle('fs:readChatFile', async (event, filePath) => {
try {
const content = await fs.promises.readFile(filePath, 'utf-8');
return { success: true, content };
} catch (error) {
console.error('Error reading chat file:', filePath, error);
return { success: false, error: error.message };
}
});
// TypeScript Language Service setup
// Un mapa para mantener el contenido de los archivos que el usuario edita
const tsFiles = new Map();
let languageService = null;
let languageServiceHost = null;
// Only setup TypeScript language service if TypeScript is available
if (ts) {
languageServiceHost = {
getScriptFileNames: () => Array.from(tsFiles.keys()),
getScriptVersion: (fileName) => tsFiles.get(fileName)?.version.toString() || '0',
getScriptSnapshot: (fileName) => {
const file = tsFiles.get(fileName);
if (!file) return undefined;
return ts.ScriptSnapshot.fromString(file.text);
},
getCurrentDirectory: () => process.cwd(),
getCompilationSettings: () => ts.getDefaultCompilerOptions(), // O tu tsconfig.json
getDefaultLibFileName: (options) => ts.getDefaultLibFilePath(options),
};
languageService = ts.createLanguageService(languageServiceHost, ts.createDocumentRegistry());
console.log('[MAIN] TypeScript language service initialized successfully');
} else {
console.warn('[MAIN] TypeScript language service not available - TypeScript features will be disabled');
}
// Función para actualizar el contenido del archivo desde la UI
function updateTsFile(fileName, newText) {
const version = (tsFiles.get(fileName)?.version || 0) + 1;
tsFiles.set(fileName, { text: newText, version });
}
// IPC handler para actualizar archivos TypeScript
ipcMain.handle('ts:updateFile', async (event, fileName, content) => {