-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
1476 lines (1260 loc) · 42.7 KB
/
server.js
File metadata and controls
1476 lines (1260 loc) · 42.7 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
/**
* Backend API Server
* Gère l'exécution des analyses Figma et stream les logs en temps réel
*/
import express from 'express'
import { spawn } from 'child_process'
import { createServer as createViteServer } from 'vite'
import { createServer as createHttpServer } from 'http'
import path from 'path'
import { fileURLToPath } from 'url'
import fs from 'fs'
import { getExportsPath, getResponsiveScreensPath } from './scripts/utils/electron-paths.js'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
// Detect Electron environment
const isElectron = process.env.ELECTRON_MODE === 'true'
const isProduction = process.env.NODE_ENV === 'production'
const HOST = isElectron ? '127.0.0.1' : '0.0.0.0'
/**
* Get the correct base path for file operations
* In Electron production mode, files are in process.cwd() (app.asar.unpacked/..)
* In other modes, files are in __dirname
*/
function getBasePath() {
return (isElectron && isProduction) ? process.cwd() : __dirname
}
// Debug: Log paths in Electron mode
if (isElectron) {
console.log(`🔍 Electron Mode - Path Debug:`)
console.log(` __dirname: ${__dirname}`)
console.log(` process.cwd(): ${process.cwd()}`)
console.log(` Base path: ${getBasePath()}`)
console.log(` Export path: ${getExportsPath()}`)
}
// Initialize figma-usage.json from template if needed
const usageFile = path.join(getBasePath(), 'data', 'figma-usage.json')
const templateFile = path.join(getBasePath(), 'data', 'figma-usage.default.json')
if (!fs.existsSync(usageFile) && fs.existsSync(templateFile)) {
fs.copyFileSync(templateFile, usageFile)
console.log('✅ Created figma-usage.json from template')
}
const app = express()
const PORT = process.env.PORT || 5173
// Middleware
app.use(express.json())
// Store active analysis jobs
const activeJobs = new Map()
/**
* Strip ANSI color codes from text
* Removes escape sequences like [1m, [32m, [0m, etc.
*/
function stripAnsi(text) {
// eslint-disable-next-line no-control-regex
return text.replace(/\x1b\[[0-9;]*m/g, '')
}
/**
* POST /api/analyze
* Lance une analyse Figma
*/
app.post('/api/analyze', async (req, res) => {
const { figmaUrl } = req.body
if (!figmaUrl) {
return res.status(400).json({ error: 'URL Figma requise' })
}
// Validate Figma URL format
if (!figmaUrl.includes('figma.com')) {
return res.status(400).json({ error: 'URL Figma invalide' })
}
// Generate unique job ID
const jobId = `job-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
// Create job metadata
const job = {
id: jobId,
url: figmaUrl,
status: 'running',
startTime: Date.now(),
logs: [],
clients: [],
exportId: null // Will be extracted from logs
}
activeJobs.set(jobId, job)
// Start the analysis process
const cliPath = path.join(getBasePath(), 'scripts', 'figma-cli.js')
const child = spawn('node', [cliPath, figmaUrl, '--clean'], {
cwd: getBasePath(),
env: {
...process.env,
FORCE_COLOR: '1' // Keep ANSI colors for react-lazylog
}
})
job.process = child
// Capture stdout
child.stdout.on('data', (data) => {
const log = data.toString()
const cleanLog = stripAnsi(log)
job.logs.push(cleanLog)
// Extract exportId from logs (format: "EXPORT_ID: node-XXX-XXX")
const exportIdMatch = cleanLog.match(/EXPORT_ID:\s*(node-[^\s\n]+)/)
if (exportIdMatch) {
job.exportId = exportIdMatch[1].trim()
console.log('✓ Export ID extracted:', job.exportId) // Debug log
}
// Broadcast to all connected clients
job.clients.forEach(client => {
client.write(`data: ${JSON.stringify({ type: 'log', message: cleanLog })}\n\n`)
})
})
// Capture stderr
child.stderr.on('data', (data) => {
const log = data.toString()
const cleanLog = stripAnsi(log)
job.logs.push(cleanLog)
// Broadcast to all connected clients
job.clients.forEach(client => {
client.write(`data: ${JSON.stringify({ type: 'log', message: cleanLog })}\n\n`)
})
})
// Handle process exit
child.on('close', (code) => {
job.status = code === 0 ? 'completed' : 'failed'
job.endTime = Date.now()
job.exitCode = code
const finalMessage = code === 0
? '\n✓ Analyse terminée avec succès\n'
: `\n✗ Analyse échouée (code: ${code})\n`
job.logs.push(finalMessage)
// Broadcast completion to all clients
job.clients.forEach(client => {
client.write(`data: ${JSON.stringify({ type: 'done', message: finalMessage, success: code === 0, exportId: job.exportId })}\n\n`)
})
// Don't close connections, let clients handle it
})
// Handle process errors
child.on('error', (error) => {
job.status = 'failed'
job.error = error.message
job.endTime = Date.now()
const errorMessage = `\n✗ Erreur: ${error.message}\n`
job.logs.push(errorMessage)
// Broadcast error to all clients
job.clients.forEach(client => {
client.write(`data: ${JSON.stringify({ type: 'error', message: errorMessage })}\n\n`)
})
})
res.json({
jobId,
status: 'started',
message: 'Analyse lancée avec succès'
})
})
/**
* GET /api/analyze/logs/:jobId
* Stream les logs d'une analyse via Server-Sent Events (SSE)
*/
app.get('/api/analyze/logs/:jobId', (req, res) => {
const { jobId } = req.params
const job = activeJobs.get(jobId)
if (!job) {
return res.status(404).json({ error: 'Job non trouvé' })
}
// Configure SSE
res.setHeader('Content-Type', 'text/event-stream')
res.setHeader('Cache-Control', 'no-cache')
res.setHeader('Connection', 'keep-alive')
res.flushHeaders()
// Send existing logs
job.logs.forEach(log => {
res.write(`data: ${JSON.stringify({ type: 'log', message: log })}\n\n`)
})
// Add client to broadcast list
job.clients.push(res)
// Send initial status if job already completed
if (job.status === 'completed') {
res.write(`data: ${JSON.stringify({ type: 'done', success: true, testId: job.testId })}\n\n`)
} else if (job.status === 'failed') {
res.write(`data: ${JSON.stringify({ type: 'done', success: false })}\n\n`)
}
// Handle client disconnect
req.on('close', () => {
const index = job.clients.indexOf(res)
if (index !== -1) {
job.clients.splice(index, 1)
}
// Clean up job if no clients and completed
if (job.clients.length === 0 && (job.status === 'completed' || job.status === 'failed')) {
setTimeout(() => {
activeJobs.delete(jobId)
}, 60000) // Keep for 1 minute after last client disconnects
}
})
})
/**
* GET /api/analyze/status/:jobId
* Récupère le statut d'une analyse
*/
app.get('/api/analyze/status/:jobId', (req, res) => {
const { jobId } = req.params
const job = activeJobs.get(jobId)
if (!job) {
return res.status(404).json({ error: 'Job non trouvé' })
}
res.json({
jobId: job.id,
status: job.status,
url: job.url,
startTime: job.startTime,
endTime: job.endTime,
exitCode: job.exitCode,
logsCount: job.logs.length
})
})
/**
* DELETE /api/export_figma/:exportId
* Supprime un export et son dossier
*/
app.delete('/api/export_figma/:exportId', async (req, res) => {
const { exportId } = req.params
if (!exportId || !exportId.startsWith('node-')) {
return res.status(400).json({ error: 'Export ID invalide' })
}
try {
const { rm } = await import('fs/promises')
const exportPath = path.join(getExportsPath(), exportId)
// Supprimer le dossier et tout son contenu
await rm(exportPath, { recursive: true, force: true })
res.json({
success: true,
message: 'Export supprimé avec succès',
exportId
})
} catch (error) {
console.error('Erreur lors de la suppression:', error)
res.status(500).json({
error: 'Erreur lors de la suppression de l\'export',
message: error.message
})
}
})
/**
* GET /api/mcp/health
* Vérifie la connexion au serveur MCP
*/
app.get('/api/mcp/health', async (req, res) => {
// TEMPORARY FIX: In Electron mode, always return success
// The real MCP connection will be tested when actually making analysis calls
if (isElectron) {
return res.json({
status: 'connected',
message: 'MCP server check skipped in Electron mode',
mode: 'electron'
})
}
// Docker mode: test actual connection
try {
const defaultHost = 'host.docker.internal'
const mcpHost = process.env.MCP_HOST || defaultHost
const mcpPort = process.env.MCP_SERVER_PORT || 3845
const mcpUrl = `http://${mcpHost}:${mcpPort}/mcp`
const response = await fetch(mcpUrl, {
method: 'GET',
signal: AbortSignal.timeout(2000)
})
res.json({
status: 'connected',
message: 'MCP server is reachable',
mcpHost,
mcpPort
})
} catch (error) {
res.status(503).json({ status: 'error', message: error.message })
}
})
/**
* GET /api/usage
* Récupère les statistiques d'utilisation de l'API Figma
*/
app.get('/api/usage', (req, res) => {
try {
const usageFilePath = path.join(getBasePath(), 'data', 'figma-usage.json')
// Load settings for dailyTokenLimit
let dailyLimit = 1200000; // Default fallback
try {
const settingsPath = path.join(getBasePath(), 'cli', 'config', 'settings.json')
if (fs.existsSync(settingsPath)) {
const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'))
dailyLimit = settings.apiLimits?.dailyTokenLimit || 1200000
}
} catch (err) {
console.warn('Failed to load dailyTokenLimit from settings, using default:', err.message)
}
// Si le fichier n'existe pas, retourner des stats vides
if (!fs.existsSync(usageFilePath)) {
return res.json({
today: {
date: new Date().toISOString().split('T')[0],
calls: {},
totalCalls: 0,
analyses: 0,
credits: {
min: 0,
typical: 0,
max: 0,
dailyLimit: dailyLimit,
percentUsed: 0
}
},
historical: [],
status: {
emoji: '✅',
text: 'SAFE - No usage yet',
level: 'safe'
}
})
}
// Lire le fichier d'usage
const usageData = JSON.parse(fs.readFileSync(usageFilePath, 'utf8'))
const today = new Date().toISOString().split('T')[0]
const todayData = usageData.daily[today] || { calls: {}, totalCalls: 0, analyses: 0, tokens: {}, totalTokens: 0 }
// Use actual tokens from measurements
const totalTokens = todayData.totalTokens || 0
const percentUsed = (totalTokens / dailyLimit) * 100
// Load thresholds from settings
let thresholds = { warning: 50, critical: 75, danger: 90 }; // Defaults
try {
const settingsPath = path.join(getBasePath(), 'cli', 'config', 'settings.json')
if (fs.existsSync(settingsPath)) {
const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'))
if (settings.apiLimits?.thresholds) {
thresholds = settings.apiLimits.thresholds
}
}
} catch (err) {
console.warn('Failed to load thresholds from settings:', err.message)
}
// Déterminer le statut
let status
if (percentUsed < 10) {
status = { emoji: '✅', text: 'SAFE - Plenty of quota remaining', level: 'safe' }
} else if (percentUsed < thresholds.warning) {
status = { emoji: '🟢', text: 'GOOD - Moderate usage', level: 'good' }
} else if (percentUsed < thresholds.critical) {
status = { emoji: '🟡', text: 'WARNING - High usage', level: 'warning' }
} else if (percentUsed < thresholds.danger) {
status = { emoji: '🟠', text: 'CRITICAL - Near limit', level: 'critical' }
} else {
status = { emoji: '🔴', text: 'DANGER - Likely exceeded limit', level: 'danger' }
}
// Historique 7 derniers jours
const historical = []
for (let i = 6; i >= 0; i--) {
const date = new Date()
date.setDate(date.getDate() - i)
const dateStr = date.toISOString().split('T')[0]
const dayData = usageData.daily[dateStr]
if (dayData) {
historical.push({
date: dateStr,
totalCalls: dayData.totalCalls,
analyses: dayData.analyses,
creditsEstimate: dayData.totalTokens || 0,
calls: dayData.calls || {},
tokens: dayData.tokens || {}
})
} else {
historical.push({
date: dateStr,
totalCalls: 0,
analyses: 0,
creditsEstimate: 0,
calls: {},
tokens: {}
})
}
}
res.json({
today: {
date: today,
calls: todayData.calls,
totalCalls: todayData.totalCalls,
analyses: todayData.analyses,
tokens: todayData.tokens || {},
credits: {
min: totalTokens,
typical: totalTokens,
max: totalTokens,
dailyLimit: dailyLimit,
percentUsed,
isActual: true
}
},
historical,
status
})
} catch (error) {
console.error('Error reading usage data:', error)
res.status(500).json({ error: 'Failed to read usage data' })
}
})
/**
* GET /api/export_figma/:exportId/data
* Récupère les données complètes d'un export (metadata.json, metadata.xml, analysis.md)
*/
app.get('/api/export_figma/:exportId/data', async (req, res) => {
const { exportId } = req.params
if (!exportId || !exportId.startsWith('node-')) {
return res.status(400).json({ error: 'Export ID invalide' })
}
try {
const exportPath = path.join(getExportsPath(), exportId)
// Vérifier que le dossier existe
if (!fs.existsSync(exportPath)) {
return res.status(404).json({ error: 'Export non trouvé' })
}
const data = {}
// Lire metadata.json
const metadataPath = path.join(exportPath, 'metadata.json')
if (fs.existsSync(metadataPath)) {
data.metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf8'))
}
// Lire metadata.xml
const xmlPath = path.join(exportPath, 'metadata.xml')
if (fs.existsSync(xmlPath)) {
const xmlContent = fs.readFileSync(xmlPath, 'utf8')
data.metadataXml = xmlContent
// Extraire layerName depuis XML
const frameMatch = xmlContent.match(/<frame[^>]+name="([^"]+)"/)
if (frameMatch && data.metadata) {
data.metadata.layerName = frameMatch[1]
}
}
// Lire analysis.md
const analysisPath = path.join(exportPath, 'analysis.md')
if (fs.existsSync(analysisPath)) {
data.analysis = fs.readFileSync(analysisPath, 'utf8')
}
res.json(data)
} catch (error) {
console.error('Error loading export data:', error)
res.status(500).json({ error: 'Failed to load export data' })
}
})
/**
* GET /api/export_figma
* Récupère la liste de tous les exports avec leurs métadonnées
*/
app.get('/api/export_figma', async (req, res) => {
try {
const exportsDir = getExportsPath()
// Vérifier que le dossier existe
if (!fs.existsSync(exportsDir)) {
return res.json([])
}
// Lire tous les dossiers d'exports
const exportFolders = fs.readdirSync(exportsDir)
.filter(name => name.startsWith('node-'))
// Charger les métadonnées pour chaque export
const exports = exportFolders.map(exportId => {
try {
const exportPath = path.join(exportsDir, exportId)
const metadataPath = path.join(exportPath, 'metadata.json')
const xmlPath = path.join(exportPath, 'metadata.xml')
// Lire metadata.json
let metadata = {}
if (fs.existsSync(metadataPath)) {
metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf8'))
}
// Lire layerName depuis metadata.xml
let layerName = null
if (fs.existsSync(xmlPath)) {
const xmlContent = fs.readFileSync(xmlPath, 'utf8')
const frameMatch = xmlContent.match(/<frame[^>]+name="([^"]+)"/)
layerName = frameMatch ? frameMatch[1] : null
}
return {
...metadata,
exportId,
layerName
}
} catch (error) {
console.error(`Error loading export ${exportId}:`, error)
return null
}
}).filter(exportFigma => exportFigma !== null)
res.json(exports)
} catch (error) {
console.error('Error reading exports:', error)
res.status(500).json({ error: 'Failed to read exports' })
}
})
/**
* GET /api/responsive-merges
* Récupère la liste de tous les tests responsive avec leurs métadonnées
*/
app.get('/api/responsive-merges', async (req, res) => {
try {
const responsiveDir = getResponsiveScreensPath()
// Vérifier que le dossier existe
if (!fs.existsSync(responsiveDir)) {
return res.json([])
}
// Lire tous les dossiers de tests responsive
const testFolders = fs.readdirSync(responsiveDir)
.filter(name => name.startsWith('responsive-merger-'))
// Charger les métadonnées pour chaque test
const tests = testFolders.map(mergeId => {
try {
const testPath = path.join(responsiveDir, mergeId)
const metadataPath = path.join(testPath, 'responsive-metadata.json')
// Lire responsive-metadata.json
if (fs.existsSync(metadataPath)) {
const metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf8'))
return metadata
}
return null
} catch (error) {
console.error(`Error loading responsive test ${mergeId}:`, error)
return null
}
}).filter(test => test !== null)
// Trier par timestamp décroissant (plus récent en premier)
tests.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
res.json(tests)
} catch (error) {
console.error('Error reading responsive tests:', error)
res.status(500).json({ error: 'Failed to read responsive tests' })
}
})
/**
* POST /api/responsive-merges
* Lance un nouveau merge responsive
*/
app.post('/api/responsive-merges', async (req, res) => {
const { desktop, tablet, mobile } = req.body
// Validation
if (!desktop || !tablet || !mobile) {
return res.status(400).json({ error: 'Desktop, tablet et mobile requis' })
}
if (!desktop.size || !desktop.exportId || !tablet.size || !tablet.exportId || !mobile.size || !mobile.exportId) {
return res.status(400).json({ error: 'Chaque breakpoint doit avoir size et exportId' })
}
// Valider que les exports existent
const exportsDir = getExportsPath()
const desktopPath = path.join(exportsDir, desktop.exportId)
const tabletPath = path.join(exportsDir, tablet.exportId)
const mobilePath = path.join(exportsDir, mobile.exportId)
if (!fs.existsSync(desktopPath) || !fs.existsSync(tabletPath) || !fs.existsSync(mobilePath)) {
return res.status(400).json({ error: 'Un ou plusieurs exports n\'existent pas' })
}
// Generate unique job ID
const jobId = `merge-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
const mergeId = `responsive-merger-${Date.now()}`
// Create job metadata
const job = {
id: jobId,
mergeId,
breakpoints: { desktop, tablet, mobile },
status: 'running',
startTime: Date.now(),
logs: [],
clients: []
}
activeJobs.set(jobId, job)
// Helper function to run component-splitter synchronously
const runComponentSplitter = (testPath, breakpointName) => {
return new Promise((resolve, reject) => {
const splitterPath = path.join(getBasePath(), 'scripts', 'post-processing', 'component-splitter.js')
const splitProcess = spawn('node', [splitterPath, testPath], {
cwd: getBasePath(),
env: process.env
})
let output = ''
let errorOutput = ''
splitProcess.stdout.on('data', (data) => {
const log = data.toString()
output += log
const cleanLog = stripAnsi(log)
job.logs.push(cleanLog)
// Broadcast to all connected clients
job.clients.forEach(client => {
client.write(`data: ${JSON.stringify({ type: 'log', message: cleanLog })}\n\n`)
})
})
splitProcess.stderr.on('data', (data) => {
const log = data.toString()
errorOutput += log
const cleanLog = stripAnsi(log)
job.logs.push(cleanLog)
// Broadcast to all connected clients
job.clients.forEach(client => {
client.write(`data: ${JSON.stringify({ type: 'log', message: cleanLog })}\n\n`)
})
})
splitProcess.on('close', (code) => {
if (code === 0) {
resolve({ success: true, output })
} else {
reject(new Error(`${breakpointName} split failed (code: ${code})\n${errorOutput}`))
}
})
splitProcess.on('error', (error) => {
reject(new Error(`${breakpointName} split error: ${error.message}`))
})
})
}
// Run component-splitter on all 3 tests sequentially, then start merge
;(async () => {
try {
// Split Desktop
job.logs.push('\n🔪 Splitting Desktop components...\n')
job.clients.forEach(client => {
client.write(`data: ${JSON.stringify({ type: 'log', message: '\n🔪 Splitting Desktop components...\n' })}\n\n`)
})
await runComponentSplitter(desktopPath, 'Desktop')
// Split Tablet
job.logs.push('\n🔪 Splitting Tablet components...\n')
job.clients.forEach(client => {
client.write(`data: ${JSON.stringify({ type: 'log', message: '\n🔪 Splitting Tablet components...\n' })}\n\n`)
})
await runComponentSplitter(tabletPath, 'Tablet')
// Split Mobile
job.logs.push('\n🔪 Splitting Mobile components...\n')
job.clients.forEach(client => {
client.write(`data: ${JSON.stringify({ type: 'log', message: '\n🔪 Splitting Mobile components...\n' })}\n\n`)
})
await runComponentSplitter(mobilePath, 'Mobile')
// All splits successful, now start the merge
job.logs.push('\n🚀 Starting responsive merge...\n')
job.clients.forEach(client => {
client.write(`data: ${JSON.stringify({ type: 'log', message: '\n🚀 Starting responsive merge...\n' })}\n\n`)
})
const mergerPath = path.join(getBasePath(), 'scripts', 'responsive-merger.js')
const child = spawn('node', [
mergerPath,
'--desktop', desktop.size, desktop.exportId,
'--tablet', tablet.size, tablet.exportId,
'--mobile', mobile.size, mobile.exportId
], {
cwd: getBasePath(),
env: {
...process.env,
FORCE_COLOR: '1'
}
})
job.process = child
// Capture stdout
child.stdout.on('data', (data) => {
const log = data.toString()
const cleanLog = stripAnsi(log)
job.logs.push(cleanLog)
// Broadcast to all connected clients
job.clients.forEach(client => {
client.write(`data: ${JSON.stringify({ type: 'log', message: cleanLog })}\n\n`)
})
})
// Capture stderr
child.stderr.on('data', (data) => {
const log = data.toString()
const cleanLog = stripAnsi(log)
job.logs.push(cleanLog)
// Broadcast to all connected clients
job.clients.forEach(client => {
client.write(`data: ${JSON.stringify({ type: 'log', message: cleanLog })}\n\n`)
})
})
// Handle process exit
child.on('close', (code) => {
job.status = code === 0 ? 'completed' : 'failed'
job.endTime = Date.now()
job.exitCode = code
const finalMessage = code === 0
? '\n✓ Merge responsive terminé avec succès\n'
: `\n✗ Merge responsive échoué (code: ${code})\n`
job.logs.push(finalMessage)
// Broadcast completion to all clients
job.clients.forEach(client => {
client.write(`data: ${JSON.stringify({ type: 'done', message: finalMessage, success: code === 0, mergeId })}\n\n`)
})
})
// Handle process errors
child.on('error', (error) => {
job.status = 'failed'
job.error = error.message
job.endTime = Date.now()
const errorMessage = `\n✗ Erreur: ${error.message}\n`
job.logs.push(errorMessage)
// Broadcast error to all clients
job.clients.forEach(client => {
client.write(`data: ${JSON.stringify({ type: 'error', message: errorMessage })}\n\n`)
})
})
} catch (error) {
// Handle component splitting errors
job.status = 'failed'
job.error = error.message
job.endTime = Date.now()
const errorMessage = `\n✗ Erreur lors du split des composants: ${error.message}\n`
job.logs.push(errorMessage)
// Broadcast error to all clients
job.clients.forEach(client => {
client.write(`data: ${JSON.stringify({ type: 'error', message: errorMessage })}\n\n`)
client.write(`data: ${JSON.stringify({ type: 'done', success: false })}\n\n`)
})
}
})()
res.json({
jobId,
mergeId,
status: 'started',
message: 'Merge responsive lancé avec succès'
})
})
/**
* GET /api/responsive-merges/logs/:jobId
* Stream les logs d'un merge responsive via Server-Sent Events (SSE)
*/
app.get('/api/responsive-merges/logs/:jobId', (req, res) => {
const { jobId } = req.params
const job = activeJobs.get(jobId)
if (!job) {
return res.status(404).json({ error: 'Job non trouvé' })
}
// Configure SSE
res.setHeader('Content-Type', 'text/event-stream')
res.setHeader('Cache-Control', 'no-cache')
res.setHeader('Connection', 'keep-alive')
res.flushHeaders()
// Send existing logs
job.logs.forEach(log => {
res.write(`data: ${JSON.stringify({ type: 'log', message: log })}\n\n`)
})
// Add client to broadcast list
job.clients.push(res)
// Send initial status if job already completed
if (job.status === 'completed') {
res.write(`data: ${JSON.stringify({ type: 'done', success: true, mergeId: job.mergeId })}\n\n`)
} else if (job.status === 'failed') {
res.write(`data: ${JSON.stringify({ type: 'done', success: false })}\n\n`)
}
// Handle client disconnect
req.on('close', () => {
const index = job.clients.indexOf(res)
if (index !== -1) {
job.clients.splice(index, 1)
}
// Clean up job if no clients and completed
if (job.clients.length === 0 && (job.status === 'completed' || job.status === 'failed')) {
setTimeout(() => {
activeJobs.delete(jobId)
}, 60000)
}
})
})
/**
* DELETE /api/responsive-merges/:mergeId
* Supprime un test responsive et son dossier
*/
app.delete('/api/responsive-merges/:mergeId', async (req, res) => {
const { mergeId } = req.params
if (!mergeId || !mergeId.startsWith('responsive-merger-')) {
return res.status(400).json({ error: 'Merge ID invalide' })
}
try {
const { rm } = await import('fs/promises')
const testPath = path.join(getResponsiveScreensPath(), mergeId)
// Supprimer le dossier et tout son contenu
await rm(testPath, { recursive: true, force: true })
res.json({
success: true,
message: 'Test responsive supprimé avec succès',
mergeId
})
} catch (error) {
console.error('Erreur lors de la suppression:', error)
res.status(500).json({
error: 'Erreur lors de la suppression du test responsive',
message: error.message
})
}
})
/**
* GET /api/responsive-merges/:mergeId/puck-config
* Retourne la configuration Puck (liste des composants disponibles)
*/
app.get('/api/responsive-merges/:mergeId/puck-config', async (req, res) => {
const { mergeId } = req.params
if (!mergeId || !mergeId.startsWith('responsive-merger-')) {
return res.status(400).json({ error: 'Merge ID invalide' })
}
try {
const metadataPath = path.join(
getBasePath(),
'src/generated/responsive-screens',
mergeId,
'responsive-metadata.json'
)
if (!fs.existsSync(metadataPath)) {
return res.status(404).json({ error: 'Test responsive introuvable' })
}
const metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf8'))
res.json({
componentNames: metadata.components || [],
breakpoints: metadata.breakpoints,
mergeId: metadata.mergeId
})
} catch (error) {
console.error('Erreur lors du chargement de la config Puck:', error)
res.status(500).json({
error: 'Erreur lors du chargement de la configuration',
message: error.message
})
}
})
/**
* GET /api/responsive-merges/:mergeId/puck-data
* Retourne le layout Puck sauvegardé (ou null si pas encore sauvegardé)
*/
app.get('/api/responsive-merges/:mergeId/puck-data', async (req, res) => {
const { mergeId } = req.params
if (!mergeId || !mergeId.startsWith('responsive-merger-')) {
return res.status(400).json({ error: 'Merge ID invalide' })
}
try {
const dataPath = path.join(
getBasePath(),
'src/generated/responsive-screens',
mergeId,
'puck/puck-data.json'
)
if (!fs.existsSync(dataPath)) {
// Pas encore de données sauvegardées, retourner null
return res.json(null)
}
const data = JSON.parse(fs.readFileSync(dataPath, 'utf8'))
res.json(data)
} catch (error) {
console.error('Erreur lors du chargement des données Puck:', error)
res.status(500).json({
error: 'Erreur lors du chargement des données',
message: error.message
})
}
})
/**
* POST /api/responsive-merges/:mergeId/puck-save
* Sauvegarde le layout Puck
*/
app.post('/api/responsive-merges/:mergeId/puck-save', async (req, res) => {
const { mergeId } = req.params