Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
804 lines (730 loc) · 24.3 KB
/
Copy pathmain.js
File metadata and controls
804 lines (730 loc) · 24.3 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
import pc from 'picocolors';
import path from 'path';
import { spawnSync } from 'child_process';
import { intro, outro, select, text, confirm, isCancel, log } from '@clack/prompts';
import {
loadProjects, addProject, removeProject, updateSettings, getSettings,
getConfigPath, readConfigText, onConfigSaved, getRootDir,
ensureConfigFile, setBeforeConfigMutate,
} from './lib/config.js';
import processManager from './lib/process-manager.js';
import logStore from './lib/log-store.js';
import { pullLatest, checkCliForUpdates, ensureRepo, prepareProject, syncRemoteUrl } from './lib/git-ops.js';
import { createHotReload, parseConfigText } from './lib/hot-reload.js';
import { createStatusWriter } from './lib/status-file.js';
import Dashboard from './lib/ui.js';
import { pickSuccess, pickFarewell, pickError, pickCrash } from './lib/flair.js';
import { terminalTheme } from './lib/theme.js';
const accent = terminalTheme.accent;
const accentBg = terminalTheme.accentBg;
const muted = terminalTheme.muted;
const dim = terminalTheme.dim;
const APP_NAME = 'PROZESSOR';
const APP_VERSION = '1.0.0';
const BRAILLE_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
const MENU_CANCEL = '__MENU_CANCEL__';
const MENU_EXIT = '__MENU_EXIT__';
const MENU_LOGO_LINES = [
' █▀█ █▀█ █▀█ ▀▀█ █▀▀ █▀▀ █▀▀ █▀█ █▀█',
' █▀▀ █▀▄ █ █ ▄▀ █▀▀ ▀▀█ ▀▀█ █ █ █▀▄',
' ▀ ▀ ▀ ▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀ ▀ ▀',
];
const MENU_LOGO_GRADIENT = [
[168, 85, 247],
[192, 132, 252],
[211, 170, 255],
];
const originalWrite = process.stdout.write.bind(process.stdout);
process.stdout.write = function patchedWrite(data, ...args) {
if (typeof data === 'string') {
if (terminalTheme.colorLevel === 'truecolor') {
data = data.replaceAll('\x1b[36m', '\x1b[38;2;192;132;252m');
} else if (terminalTheme.colorLevel === 'basic') {
data = data.replaceAll('\x1b[36m', '\x1b[35m');
}
}
return originalWrite(data, ...args);
};
function animatedSpinner() {
let interval = null;
let msg = '';
let frameIdx = 0;
return {
start(msg) {
this.stop();
process.stdout.write('\x1b[?25l');
this.message(msg);
interval = setInterval(() => {
const frame = BRAILLE_FRAMES[frameIdx++ % BRAILLE_FRAMES.length];
process.stdout.write(`\r\x1b[2K ${accent(frame)} ${msg}`);
}, 85);
},
stop(finalMessage = '') {
if (interval) {
clearInterval(interval);
interval = null;
}
process.stdout.write('\r\x1b[2K\x1b[?25h');
if (finalMessage) process.stdout.write(` ${finalMessage}\n`);
},
message(next) {
msg = next.replace(/\.+\s*$/, '');
frameIdx = 0;
const frame = BRAILLE_FRAMES[frameIdx % BRAILLE_FRAMES.length];
process.stdout.write(`\r\x1b[2K ${accent(frame)} ${msg}`);
},
};
}
let dashboard = null;
let pollTimer = null;
let hotReload = null;
let statusWriter = null;
let menuOpening = false;
let menuCancelIntent = 'dashboard';
let originalStdinEmit = null;
let lastKeyTime = 0;
let lastKeyName = '';
function beginMenuKeyTracking() {
menuCancelIntent = 'dashboard';
if (!process.stdin || originalStdinEmit) return;
originalStdinEmit = process.stdin.emit.bind(process.stdin);
process.stdin.emit = function (event, ...args) {
if (event === 'keypress' && args[1]) {
const key = args[1];
if (key.ctrl && key.name === 'c') menuCancelIntent = 'exit';
else if (key.name === 'escape') menuCancelIntent = 'dashboard';
else if (key.name === 'up' || key.name === 'down') {
const now = Date.now();
if (now - lastKeyTime < 50 && lastKeyName === key.name) {
return false;
}
lastKeyTime = now;
lastKeyName = key.name;
}
} else if (event === 'data' && args[0]) {
const chunk = args[0];
if (chunk.length > 0) {
const first = typeof chunk === 'string' ? chunk.charCodeAt(0) : chunk[0];
if (first === 3) menuCancelIntent = 'exit';
else if (first === 27) menuCancelIntent = 'dashboard';
}
}
return originalStdinEmit(event, ...args);
};
}
function endMenuKeyTracking() {
if (process.stdin && originalStdinEmit) {
process.stdin.emit = originalStdinEmit;
}
lastKeyTime = 0;
lastKeyName = '';
originalStdinEmit = null;
menuCancelIntent = 'dashboard';
}
function handleCancel(value) {
if (isCancel(value)) {
if (menuOpening && menuCancelIntent === 'exit') {
return MENU_EXIT;
}
return MENU_CANCEL;
}
return value;
}
function isCancelled(value) {
return value === MENU_CANCEL;
}
function isMenuExit(value) {
return value === MENU_EXIT;
}
function getCancelReturn(value) {
if (isCancelled(value) || isMenuExit(value)) return value;
return null;
}
function formatUptime(ms) {
if (!ms) return pc.dim('--');
const secs = Math.floor(ms / 1000);
if (secs < 60) return `${secs}s`;
const mins = Math.floor(secs / 60);
if (mins < 60) return `${mins}m ${secs % 60}s`;
const hrs = Math.floor(mins / 60);
return `${hrs}h ${mins % 60}m`;
}
function startPollTimer(seconds) {
// the value can come from a hand-edited file, so never poll git faster than 5s
const n = Number(seconds);
const secs = Number.isFinite(n) ? Math.max(5, n) : 20;
if (pollTimer) clearInterval(pollTimer);
pollTimer = setInterval(pollForUpdates, secs * 1000);
}
// git updates run in each project's reload lane, so an update and a config
// reload for the same project never overlap; at most one queued per project
const pullPending = new Set();
function pollForUpdates() {
for (const proj of hotReload.getConfig().projects) {
if (proj.enabled === false || pullPending.has(proj.name)) continue;
pullPending.add(proj.name);
hotReload.runExclusive(proj.name, async () => {
try {
// re-read: a reload may have changed or removed it while queued
const fresh = hotReload.getConfig().projects.find((p) => p.name === proj.name);
if (fresh && fresh.enabled !== false) await pullLatest(fresh, processManager);
} finally {
pullPending.delete(proj.name);
}
});
}
}
// runs after every hot reload (and after menu saves, with no project actions)
function handleConfigApplied(next, plan) {
if (plan.settings.pollInterval && pollTimer) startPollTimer(next.settings.pollInterval);
if (plan.settings.logBufferSize) {
const size = parseInt(next.settings.logBufferSize, 10);
if (Number.isInteger(size) && size >= 50) logStore.setBufferSize(size);
}
if (dashboard) dashboard.updateProjects(next.projects);
if (statusWriter) statusWriter.schedule();
}
// stop watchers and get logs + status on disk before exiting
async function flushPersistence() {
if (hotReload) hotReload.stop();
if (statusWriter) {
statusWriter.flush();
statusWriter.stop();
}
await logStore.flushFiles();
}
async function showLogo() {
console.clear();
console.log('');
for (let i = 0; i < MENU_LOGO_LINES.length; i++) {
const line = MENU_LOGO_LINES[i];
if (terminalTheme.colorLevel === 'truecolor') {
const [r, g, b] = MENU_LOGO_GRADIENT[i % MENU_LOGO_GRADIENT.length];
console.log(`\x1b[38;2;${r};${g};${b}m${line}\x1b[39m`);
} else {
console.log(accent(line));
}
}
console.log('');
intro(accentBg(` made by @buildwithsid v${APP_VERSION} `));
}
async function mainMenu() {
const data = loadProjects();
const projects = data.projects;
const running = projects.filter((p) => processManager.getStatus(p.name) === 'running').length;
const statusSummary = `${running}/${projects.length} running`;
const choice = handleCancel(
await select({
message: accent(`Control Panel ${dim(`(${statusSummary})`)}`),
options: [
{ value: 'start', label: `Start Project`, hint: 'wakey wakey project' },
{ value: 'stop', label: `Stop Project`, hint: 'put a project to sleep' },
{ value: 'add', label: `Add Project`, hint: 'add a new project' },
{ value: 'remove', label: `Remove Project`, hint: 'remove a project' },
{ value: 'settings', label: `Settings`, hint: 'tune the engine' },
{ value: 'dashboard', label: `Back to Dashboard`, hint: 'return to live view' },
],
})
);
if (isMenuExit(choice)) return MENU_EXIT;
if (isCancelled(choice) || choice === 'dashboard') return MENU_CANCEL;
switch (choice) {
case 'start': {
const result = await startFlow();
if (isMenuExit(result)) return MENU_EXIT;
if (isCancelled(result)) return;
return mainMenu();
}
case 'stop': {
const result = await stopFlow();
if (isMenuExit(result)) return MENU_EXIT;
if (isCancelled(result)) return;
return mainMenu();
}
case 'add': {
const result = await addProjectFlow();
if (isMenuExit(result)) return MENU_EXIT;
if (isCancelled(result)) return;
return mainMenu();
}
case 'remove': {
const result = await removeFlow();
if (isMenuExit(result)) return MENU_EXIT;
if (isCancelled(result)) return;
return mainMenu();
}
case 'settings': {
const result = await settingsMenu();
if (isMenuExit(result)) return MENU_EXIT;
if (isCancelled(result)) return;
return mainMenu();
}
}
}
async function startFlow() {
const { projects } = loadProjects();
const stopped = projects.filter((p) => processManager.getStatus(p.name) !== 'running');
if (stopped.length === 0) {
log.info(`All projects already running. ${dim(pickSuccess())}`);
return;
}
const name = handleCancel(
await select({
message: 'Start which project?',
options: stopped.map((p) => ({ value: p.name, label: p.name, hint: processManager.getStatus(p.name) })),
})
);
{
const cancelValue = getCancelReturn(name);
if (cancelValue) return cancelValue;
}
const proj = projects.find((p) => p.name === name);
const s = animatedSpinner();
s.start(`Waking up ${name}`);
await processManager.startProject(proj);
await new Promise((r) => setTimeout(r, 1500));
const status = processManager.getStatus(name);
if (status === 'running') {
s.stop(`✅ ${name} is alive! ${dim(pickSuccess())}`);
} else {
s.stop(`❌ ${name} — ${status} ${dim(pickError())}`);
}
}
async function stopFlow() {
const { projects } = loadProjects();
const running = projects.filter((p) => processManager.getStatus(p.name) === 'running');
if (running.length === 0) {
log.info('No running projects to stop.');
return;
}
const name = handleCancel(
await select({
message: 'Stop which project?',
options: running.map((p) => ({
value: p.name,
label: p.name,
hint: `PID ${processManager.getPid(p.name)} · ${formatUptime(processManager.getUptime(p.name))}`,
})),
})
);
{
const cancelValue = getCancelReturn(name);
if (cancelValue) return cancelValue;
}
const s = animatedSpinner();
s.start(`Putting ${name} to sleep`);
await processManager.stopProject(name);
s.stop(`✅ ${name} stopped. ${dim(pickSuccess())}`);
}
async function addProjectFlow() {
const name = handleCancel(
await text({
message: 'Project name:',
placeholder: 'my-project',
validate(v) { if (!v.trim()) return 'Name is required.'; },
})
);
{
const cancelValue = getCancelReturn(name);
if (cancelValue) return cancelValue;
}
const repoUrl = handleCancel(
await text({
message: 'Git repo URL:',
placeholder: 'git@github.com:user/repo.git',
validate(v) { if (!v.trim()) return 'Repo URL is required.'; },
})
);
{
const cancelValue = getCancelReturn(repoUrl);
if (cancelValue) return cancelValue;
}
const branch = handleCancel(
await text({
message: 'Branch:',
placeholder: 'main',
initialValue: 'main',
})
);
{
const cancelValue = getCancelReturn(branch);
if (cancelValue) return cancelValue;
}
const subdir = handleCancel(
await text({
message: 'Subdirectory (where server lives):',
placeholder: 'backend',
initialValue: 'backend',
})
);
{
const cancelValue = getCancelReturn(subdir);
if (cancelValue) return cancelValue;
}
const entrypoint = handleCancel(
await text({
message: 'Entry file:',
placeholder: 'server.js',
initialValue: 'server.js',
})
);
{
const cancelValue = getCancelReturn(entrypoint);
if (cancelValue) return cancelValue;
}
const envSrc = handleCancel(
await text({
message: 'Env file path (relative to envs/, leave empty for none):',
placeholder: '.env.myproject',
})
);
{
const cancelValue = getCancelReturn(envSrc);
if (cancelValue) return cancelValue;
}
try {
addProject({
name: name.trim(),
repoUrl: repoUrl.trim(),
branch: (branch && branch.trim()) || 'main',
envSrc: (envSrc && envSrc.trim()) || '',
subdir: (subdir && subdir.trim()) || 'backend',
entrypoint: (entrypoint && entrypoint.trim()) || 'server.js',
});
log.success(`Added "${name.trim()}" to the roster. ${dim(pickSuccess())}`);
const startNow = handleCancel(
await confirm({ message: 'Clone and start now?', initialValue: true })
);
{
const cancelValue = getCancelReturn(startNow);
if (cancelValue) return cancelValue;
}
if (startNow) {
const data = loadProjects();
const proj = data.projects.find((p) => p.name === name.trim());
if (proj) {
const s = animatedSpinner();
s.start('Cloning repository');
const { ensureRepo, prepareProject } = await import('./lib/git-ops.js');
await ensureRepo(proj);
s.stop(`✅ Cloned.`);
s.start('Installing dependencies');
await prepareProject(proj);
s.stop(`✅ Dependencies installed.`);
await processManager.startProject(proj);
log.success(`${name.trim()} is live! ${dim(pickSuccess())}`);
if (dashboard) dashboard.updateProjects(data.projects);
}
}
} catch (err) {
log.error(`${err.message} ${dim(pickError())}`);
}
}
async function removeFlow() {
const { projects } = loadProjects();
if (projects.length === 0) {
log.info('No projects to remove.');
return;
}
const name = handleCancel(
await select({
message: 'Remove which project?',
options: projects.map((p) => ({
value: p.name,
label: p.name,
hint: processManager.getStatus(p.name),
})),
})
);
{
const cancelValue = getCancelReturn(name);
if (cancelValue) return cancelValue;
}
const sure = handleCancel(
await confirm({ message: pc.red(`Remove "${name}"? This won't delete the repo folder.`), initialValue: false })
);
{
const cancelValue = getCancelReturn(sure);
if (cancelValue) return cancelValue;
}
if (!sure) return;
// whatever its state (running, crashed, cooldown, starting), stop it and drop
// its runtime state so no retry brings it back
await processManager.forgetProject(name);
removeProject(name);
log.success(`Removed "${name}" from config.`);
if (dashboard) {
const data = loadProjects();
dashboard.updateProjects(data.projects);
}
}
async function settingsMenu() {
const settings = getSettings();
const choice = handleCancel(
await select({
message: accent('Settings'),
options: [
{ value: 'crashes', label: 'Max Crash Retries', hint: `${settings.maxCrashRetries} before cooldown` },
{ value: 'cooldown', label: 'Crash Cooldown', hint: `${settings.crashCooldownMins}m pause` },
{ value: 'poll', label: 'Git Poll Interval', hint: `every ${settings.pollInterval}s` },
{ value: 'buffer', label: 'Log Buffer Size', hint: `${settings.logBufferSize} lines/project` },
{ value: 'autoUpdate', label: 'Auto Update CLI', hint: settings.autoUpdateCli !== false ? 'Enabled' : 'Disabled' },
{ value: 'back', label: 'Back' },
],
})
);
if (isMenuExit(choice)) return MENU_EXIT;
if (isCancelled(choice)) return MENU_CANCEL;
if (choice === 'back') return;
switch (choice) {
case 'crashes': {
const v = handleCancel(
await text({
message: `Max crashes before cooldown (currently ${settings.maxCrashRetries}):`,
placeholder: String(settings.maxCrashRetries),
validate(v) {
if (v && v.trim()) {
const n = parseInt(v);
if (isNaN(n) || n < 1) return 'Minimum 1.';
}
},
})
);
{
const cancelValue = getCancelReturn(v);
if (cancelValue) return cancelValue;
}
if (!isCancelled(v) && v && v.trim()) {
updateSettings({ maxCrashRetries: parseInt(v) });
log.success(`Max crash retries → ${parseInt(v)}. ${dim(pickSuccess())}`);
}
break;
}
case 'cooldown': {
const v = handleCancel(
await text({
message: `Cooldown duration in minutes (currently ${settings.crashCooldownMins}):`,
placeholder: String(settings.crashCooldownMins),
validate(v) {
if (v && v.trim()) {
const n = parseFloat(v);
if (isNaN(n) || n < 0.5) return 'Minimum 0.5 minutes.';
}
},
})
);
{
const cancelValue = getCancelReturn(v);
if (cancelValue) return cancelValue;
}
if (!isCancelled(v) && v && v.trim()) {
updateSettings({ crashCooldownMins: parseFloat(v) });
log.success(`Crash cooldown → ${parseFloat(v)}m. ${dim(pickSuccess())}`);
}
break;
}
case 'poll': {
const v = handleCancel(
await text({
message: `Poll interval in seconds (currently ${settings.pollInterval}):`,
placeholder: String(settings.pollInterval),
validate(v) {
if (v && v.trim()) {
const n = parseInt(v);
if (isNaN(n) || n < 5) return 'Minimum 5 seconds.';
}
},
})
);
{
const cancelValue = getCancelReturn(v);
if (cancelValue) return cancelValue;
}
if (!isCancelled(v) && v && v.trim()) {
const newInterval = parseInt(v);
updateSettings({ pollInterval: newInterval });
startPollTimer(newInterval);
log.success(`Poll interval → ${newInterval}s. ${dim(pickSuccess())}`);
}
break;
}
case 'buffer': {
const v = handleCancel(
await text({
message: `Log buffer size per project (currently ${settings.logBufferSize}):`,
placeholder: String(settings.logBufferSize),
validate(v) {
if (v && v.trim()) {
const n = parseInt(v);
if (isNaN(n) || n < 50) return 'Minimum 50 lines.';
}
},
})
);
{
const cancelValue = getCancelReturn(v);
if (cancelValue) return cancelValue;
}
if (!isCancelled(v) && v && v.trim()) {
const newSize = parseInt(v);
updateSettings({ logBufferSize: newSize });
logStore.setBufferSize(newSize);
log.success(`Log buffer → ${newSize} lines/project. ${dim(pickSuccess())}`);
}
break;
}
case 'autoUpdate': {
const v = handleCancel(
await confirm({ message: 'Enable Auto Update for CLI?', initialValue: settings.autoUpdateCli !== false })
);
{
const cancelValue = getCancelReturn(v);
if (cancelValue) return cancelValue;
}
updateSettings({ autoUpdateCli: v });
log.success(`Auto Update CLI → ${v ? 'Enabled' : 'Disabled'}. ${dim(pickSuccess())}`);
break;
}
}
return settingsMenu();
}
async function shutdownAndExit() {
if (dashboard) dashboard.destroy();
console.clear();
console.log(accent(pc.bold(`\n ${APP_NAME} — shutting down\n`)));
const s2 = animatedSpinner();
s2.start('Stopping all processes');
if (pollTimer) clearInterval(pollTimer);
if (hotReload) hotReload.stop();
await processManager.shutdownAll();
await flushPersistence();
s2.stop(`✅ All processes stopped.`);
outro(accent(pickFarewell()));
process.exit(0);
}
async function main() {
ensureConfigFile();
let data = loadProjects();
const settings = getSettings();
logStore.setBufferSize(settings.logBufferSize);
logStore.enablePersistence(process.env.PROZESSOR_LOGS_DIR || path.join(getRootDir(), 'logs'));
// baseline for hot reload: the exact text we started from
let initialText = null;
try {
initialText = readConfigText();
const parsed = parseConfigText(initialText);
if (parsed.ok) data = parsed.config;
else initialText = null;
} catch {
initialText = null;
}
hotReload = createHotReload({
file: getConfigPath(),
initialConfig: data,
initialText,
processManager,
ensureRepo,
prepareProject,
syncRemoteUrl,
log: (name, msg, stream = 'stdout') => logStore.push(name, msg, stream),
onApplied: handleConfigApplied,
});
onConfigSaved((text) => hotReload.absorb(text));
setBeforeConfigMutate(() => hotReload.check());
statusWriter = createStatusWriter({
processManager,
getProjects: () => hotReload.getConfig().projects,
});
statusWriter.start();
dashboard = new Dashboard(data.projects);
function launchDashboard() {
const freshData = hotReload.getConfig();
dashboard.projects = freshData.projects;
dashboard._lastLogSignature = '';
dashboard._lastStatusContent = '';
dashboard._lastCommandContent = '';
dashboard._pendingLogsRefresh = true;
dashboard.init();
dashboard.onMenuRequested = async () => {
if (menuOpening) return;
menuOpening = true;
try {
dashboard.pause();
beginMenuKeyTracking();
await showLogo();
const menuResult = await mainMenu();
if (menuResult === MENU_EXIT) {
await shutdownAndExit();
return;
}
console.clear();
launchDashboard();
} catch (err) {
// e.g. projects.json is mid-edit and unparsable: never take services down for it
logStore.push('PROZESSOR', `⚠ Menu closed: ${err.message}`, 'stderr');
console.clear();
launchDashboard();
} finally {
endMenuKeyTracking();
menuOpening = false;
}
};
dashboard.onQuitRequested = async () => {
await shutdownAndExit();
};
}
launchDashboard();
// CLI auto-update check (runs in background, status shown in TUI)
if (settings.autoUpdateCli !== false) {
logStore.push('PROZESSOR', '🔍 Checking for CLI updates...', 'stdout');
try {
const updated = await checkCliForUpdates(settings);
if (updated) {
logStore.push('PROZESSOR', '✅ CLI updated! Restarting...', 'stdout');
await new Promise(r => setTimeout(r, 1200));
if (dashboard) dashboard.destroy();
spawnSync(process.argv[0], process.argv.slice(1), { stdio: 'inherit' });
process.exit(0);
} else {
logStore.push('PROZESSOR', '✅ CLI is up to date.', 'stdout');
}
} catch {
logStore.push('PROZESSOR', '⚠ Could not check for CLI updates.', 'stderr');
}
}
await processManager.initializeAll(data.projects);
// watch only after the initial start, so reload actions never race it;
// start() immediately applies anything edited in the meantime
hotReload.start();
startPollTimer(hotReload.getConfig().settings.pollInterval);
}
let sigintCount = 0;
process.on('SIGINT', async () => {
sigintCount++;
if (sigintCount >= 2) {
// force-quit: no time to await, synchronously reap every process tree
processManager.killAllSync();
process.exit(1);
}
if (dashboard) dashboard.destroy();
console.log(accent(`\n Shutting down... ${dim('(press Ctrl+C again to force)')}`));
if (pollTimer) clearInterval(pollTimer);
if (hotReload) hotReload.stop();
await processManager.shutdownAll();
await flushPersistence();
console.log(accent(` ${pickFarewell()}`));
process.exit(0);
});
process.on('uncaughtException', async (err) => {
if (dashboard) dashboard.destroy();
console.error(pc.red(`\n Fatal error: ${err.message} ${dim(pickCrash())}`));
console.error(err.stack);
try {
await processManager.shutdownAll();
} catch {}
try { await flushPersistence(); } catch {}
// final safety net so no service is left holding a port on a crash
processManager.killAllSync();
process.exit(1);
});
main();