-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshipyard.js
More file actions
945 lines (823 loc) · 33.6 KB
/
shipyard.js
File metadata and controls
945 lines (823 loc) · 33.6 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
#!/usr/bin/env node
'use strict';
const http = require('node:http');
const { spawn, execSync, exec: execCb } = require('node:child_process');
const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
const { promisify } = require('node:util');
const exec = promisify(execCb);
// ---------------------------------------------------------------------------
// Paths
// ---------------------------------------------------------------------------
const PREVU_DIR = path.join(os.homedir(), '.shipyard');
const CONFIG_PATH = path.join(PREVU_DIR, 'config.json');
const STATE_PATH = path.join(PREVU_DIR, 'state.json');
const WORKSPACES_DIR = path.join(PREVU_DIR, 'workspaces');
const LOGS_DIR = path.join(PREVU_DIR, 'logs');
const MAX_LOG_SIZE = 10 * 1024 * 1024; // 10 MB
// ---------------------------------------------------------------------------
// CLI args
// ---------------------------------------------------------------------------
let PORT = 8090;
for (let i = 2; i < process.argv.length; i++) {
if (process.argv[i] === '--port' && process.argv[i + 1]) {
PORT = parseInt(process.argv[i + 1], 10) || 8090;
i++;
}
}
const HOSTNAME = os.hostname();
// ---------------------------------------------------------------------------
// Ensure dirs
// ---------------------------------------------------------------------------
for (const d of [PREVU_DIR, WORKSPACES_DIR, LOGS_DIR]) {
fs.mkdirSync(d, { recursive: true });
}
// ---------------------------------------------------------------------------
// Config & State helpers
// ---------------------------------------------------------------------------
function loadConfig() {
try { return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')); }
catch { return { repos: {} }; }
}
function saveConfig(cfg) {
fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2));
}
function loadState() {
try { return JSON.parse(fs.readFileSync(STATE_PATH, 'utf8')); }
catch { return { previews: {} }; }
}
function saveState(state) {
fs.writeFileSync(STATE_PATH, JSON.stringify(state, null, 2));
}
let config = loadConfig();
let state = loadState();
// Track child processes for cleanup
const childProcesses = new Map(); // key -> ChildProcess
// ---------------------------------------------------------------------------
// Logging
// ---------------------------------------------------------------------------
function log(msg) {
const ts = new Date().toISOString();
console.log(`[${ts}] ${msg}`);
}
function getLogPath(repoName, label) {
return path.join(LOGS_DIR, `${repoName}-${label}.log`);
}
function rotateLog(logPath) {
try {
const stat = fs.statSync(logPath);
if (stat.size > MAX_LOG_SIZE) {
fs.writeFileSync(logPath, `--- log truncated at ${new Date().toISOString()} ---\n`);
}
} catch { /* file doesn't exist yet */ }
}
// ---------------------------------------------------------------------------
// Process management
// ---------------------------------------------------------------------------
function isRunning(pid) {
if (!pid) return false;
try { process.kill(pid, 0); return true; }
catch { return false; }
}
function killProcess(key) {
const child = childProcesses.get(key);
if (child) {
try { process.kill(-child.pid, 'SIGTERM'); } catch {}
try { child.kill('SIGTERM'); } catch {}
childProcesses.delete(key);
}
// Also try PID from state
const preview = state.previews[key];
if (preview && preview.pid && isRunning(preview.pid)) {
try { process.kill(-preview.pid, 'SIGTERM'); } catch {}
try { process.kill(preview.pid, 'SIGTERM'); } catch {}
}
}
function previewKey(repoName, label) {
return `${repoName}:${label}`;
}
// ---------------------------------------------------------------------------
// Shell helpers
// ---------------------------------------------------------------------------
async function sh(cmd, cwd) {
try {
const { stdout } = await exec(cmd, { cwd, timeout: 120000, maxBuffer: 10 * 1024 * 1024 });
return stdout.trim();
} catch (e) {
log(`Command failed: ${cmd} — ${e.message}`);
throw e;
}
}
// ---------------------------------------------------------------------------
// Workspace management
// ---------------------------------------------------------------------------
function workspacePath(repoName, label) {
return path.join(WORKSPACES_DIR, repoName, label);
}
async function setupWorkspace(repo, repoName, branch, label) {
const ws = workspacePath(repoName, label);
const gitDir = path.join(ws, '.git');
if (!fs.existsSync(gitDir)) {
fs.mkdirSync(path.dirname(ws), { recursive: true });
log(`Cloning ${repoName}/${branch} → ${ws}`);
await sh(`git clone --single-branch --branch ${branch} "${repo.localPath}" "${ws}"`);
} else {
log(`Updating ${repoName}/${branch}`);
await sh(`git fetch origin ${branch}`, ws);
await sh(`git reset --hard origin/${branch}`, ws);
}
// Get current SHA
const sha = await sh('git rev-parse HEAD', ws);
// Install deps
if (repo.installCommand) {
log(`Installing deps for ${repoName}/${label}`);
await sh(repo.installCommand, ws);
}
return sha;
}
// ---------------------------------------------------------------------------
// Dev server management
// ---------------------------------------------------------------------------
function startDevServer(repo, repoName, label, port) {
const ws = workspacePath(repoName, label);
const key = previewKey(repoName, label);
killProcess(key);
const cmd = repo.devCommand.replace(/\{\{port\}\}/g, String(port));
const logPath = getLogPath(repoName, label);
rotateLog(logPath);
const logFd = fs.openSync(logPath, 'a');
log(`Starting dev server: ${cmd} (port ${port})`);
const child = spawn('sh', ['-c', cmd], {
cwd: ws,
stdio: ['ignore', logFd, logFd],
detached: true,
env: { ...process.env, PORT: String(port), NODE_ENV: 'development' },
});
fs.closeSync(logFd);
child.on('error', (err) => log(`Process error ${key}: ${err.message}`));
child.on('exit', (code) => {
log(`Process exited ${key} with code ${code}`);
childProcesses.delete(key);
if (state.previews[key]) {
state.previews[key].status = 'down';
saveState(state);
}
});
child.unref();
childProcesses.set(key, child);
// Update state
state.previews[key] = {
...state.previews[key],
pid: child.pid,
port,
status: 'starting',
startedAt: new Date().toISOString(),
};
saveState(state);
// Mark running after a delay
setTimeout(() => {
if (state.previews[key] && isRunning(child.pid)) {
state.previews[key].status = 'running';
saveState(state);
}
}, 5000);
}
// ---------------------------------------------------------------------------
// Full preview setup (workspace + server)
// ---------------------------------------------------------------------------
async function setupPreview(repo, repoName, branch, label, port) {
const key = previewKey(repoName, label);
state.previews[key] = {
...state.previews[key],
repoName,
label,
branch,
port,
status: 'starting',
};
saveState(state);
try {
const sha = await setupWorkspace(repo, repoName, branch, label);
state.previews[key].sha = sha;
state.previews[key].updatedAt = new Date().toISOString();
saveState(state);
startDevServer(repo, repoName, label, port);
} catch (e) {
log(`Failed to setup preview ${key}: ${e.message}`);
state.previews[key].status = 'down';
state.previews[key].error = e.message;
saveState(state);
}
}
// ---------------------------------------------------------------------------
// Polling
// ---------------------------------------------------------------------------
async function pollRepo(repoName) {
const repo = config.repos[repoName];
if (!repo) return;
log(`Polling ${repoName}...`);
// Fetch in source repo
try {
await sh('git fetch --all --prune', repo.localPath);
} catch (e) {
log(`git fetch failed for ${repoName}: ${e.message}`);
return;
}
// Check default branch
const defaultBranch = repo.defaultBranch || 'main';
const defaultLabel = defaultBranch;
const defaultKey = previewKey(repoName, defaultLabel);
const defaultPort = repo.basePort;
try {
const remoteSha = await sh(`git rev-parse origin/${defaultBranch}`, repo.localPath);
const currentSha = state.previews[defaultKey]?.sha;
const running = state.previews[defaultKey]?.pid && isRunning(state.previews[defaultKey].pid);
if (remoteSha !== currentSha || !running) {
log(`${repoName}/${defaultBranch}: SHA changed or not running, updating...`);
await setupPreview(repo, repoName, defaultBranch, defaultLabel, defaultPort);
}
} catch (e) {
log(`Default branch check failed for ${repoName}: ${e.message}`);
}
// Check PRs
if (repo.githubRemote) {
try {
const prJson = await sh(
`gh pr list --repo "${repo.githubRemote}" --json number,headRefName,headRefOid,title,url --state open`,
repo.localPath
);
const prs = JSON.parse(prJson || '[]');
const prNumbers = new Set(prs.map(pr => pr.number));
// Setup new/updated PRs
for (const pr of prs) {
const label = `pr-${pr.number}`;
const key = previewKey(repoName, label);
const port = repo.basePort + pr.number;
const currentSha = state.previews[key]?.sha;
const running = state.previews[key]?.pid && isRunning(state.previews[key].pid);
if (pr.headRefOid !== currentSha || !running) {
log(`${repoName}/PR#${pr.number}: updating...`);
state.previews[key] = {
...state.previews[key],
prNumber: pr.number,
prTitle: pr.title,
prUrl: pr.url,
branch: pr.headRefName,
};
await setupPreview(repo, repoName, pr.headRefName, label, port);
}
}
// Cleanup closed PRs
for (const [key, preview] of Object.entries(state.previews)) {
if (preview.repoName !== repoName) continue;
if (!preview.prNumber) continue;
if (!prNumbers.has(preview.prNumber)) {
log(`Cleaning up closed PR#${preview.prNumber} for ${repoName}`);
killProcess(key);
const ws = workspacePath(repoName, `pr-${preview.prNumber}`);
try { fs.rmSync(ws, { recursive: true, force: true }); } catch {}
delete state.previews[key];
saveState(state);
}
}
} catch (e) {
log(`PR check failed for ${repoName}: ${e.message}`);
}
}
}
async function pollAll() {
for (const repoName of Object.keys(config.repos)) {
await pollRepo(repoName);
}
}
// Polling intervals per repo
const pollTimers = new Map();
function startPolling(repoName) {
stopPolling(repoName);
const repo = config.repos[repoName];
if (!repo) return;
const interval = (repo.pollInterval || 300) * 1000;
pollTimers.set(repoName, setInterval(() => pollRepo(repoName), interval));
}
function stopPolling(repoName) {
const timer = pollTimers.get(repoName);
if (timer) { clearInterval(timer); pollTimers.delete(repoName); }
}
// ---------------------------------------------------------------------------
// Cleanup helpers for repo deletion
// ---------------------------------------------------------------------------
async function cleanupRepo(repoName) {
// Kill all processes for this repo
for (const [key, preview] of Object.entries(state.previews)) {
if (preview.repoName === repoName) {
killProcess(key);
delete state.previews[key];
}
}
saveState(state);
// Remove workspaces
const wsDir = path.join(WORKSPACES_DIR, repoName);
try { fs.rmSync(wsDir, { recursive: true, force: true }); } catch {}
// Remove logs
try {
for (const f of fs.readdirSync(LOGS_DIR)) {
if (f.startsWith(repoName + '-')) {
fs.unlinkSync(path.join(LOGS_DIR, f));
}
}
} catch {}
stopPolling(repoName);
}
// ---------------------------------------------------------------------------
// HTTP helpers
// ---------------------------------------------------------------------------
function jsonResponse(res, status, data) {
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
}
function readBody(req) {
return new Promise((resolve, reject) => {
let body = '';
req.on('data', chunk => { body += chunk; if (body.length > 1e6) reject(new Error('Too large')); });
req.on('end', () => {
try { resolve(JSON.parse(body)); }
catch { reject(new Error('Invalid JSON')); }
});
});
}
// ---------------------------------------------------------------------------
// Dashboard HTML
// ---------------------------------------------------------------------------
function dashboardHTML() {
const statusData = getStatusData();
const statusJson = JSON.stringify(statusData).replace(/</g, '\\u003c').replace(/>/g, '\\u003e');
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>shipyard</title>
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
body{background:#0d1117;color:#c9d1d9;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif;line-height:1.5}
a{color:#58a6ff;text-decoration:none}a:hover{text-decoration:underline}
.header{display:flex;align-items:center;justify-content:space-between;padding:16px 24px;border-bottom:1px solid #21262d;background:#161b22}
.logo{font-size:24px;font-weight:700;color:#f0f6fc;letter-spacing:-0.5px}
.logo span{color:#58a6ff}
.btn{display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:6px;border:1px solid #30363d;background:#21262d;color:#c9d1d9;font-size:14px;cursor:pointer;transition:all .15s ease}
.btn:hover{background:#30363d;border-color:#8b949e}
.btn-primary{background:#238636;border-color:#238636;color:#fff}
.btn-primary:hover{background:#2ea043}
.btn-danger{background:#da3633;border-color:#da3633;color:#fff}
.btn-danger:hover{background:#e5534b}
.btn-sm{padding:4px 10px;font-size:12px}
.container{max-width:1100px;margin:0 auto;padding:24px}
.empty{text-align:center;padding:80px 24px;color:#8b949e}
.empty h2{font-size:20px;margin-bottom:8px;color:#c9d1d9}
.repo-card{background:#161b22;border:1px solid #21262d;border-radius:8px;margin-bottom:16px;overflow:hidden}
.repo-header{display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid #21262d;background:#161b2299}
.repo-name{font-size:16px;font-weight:600;color:#f0f6fc}
.preview-table{width:100%;border-collapse:collapse}
.preview-table th{text-align:left;padding:8px 16px;font-size:12px;font-weight:600;color:#8b949e;text-transform:uppercase;letter-spacing:0.5px;border-bottom:1px solid #21262d}
.preview-table td{padding:10px 16px;border-bottom:1px solid #21262d;font-size:14px;vertical-align:middle}
.preview-table tr:last-child td{border-bottom:none}
.badge{display:inline-block;padding:2px 8px;border-radius:12px;font-size:12px;font-weight:600;line-height:1.5}
.badge-green{background:#23863633;color:#3fb950;border:1px solid #23863666}
.badge-blue{background:#58a6ff22;color:#58a6ff;border:1px solid #58a6ff44}
.status-dot{display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:6px}
.status-running .status-dot{background:#3fb950}
.status-down .status-dot{background:#da3633}
.status-starting .status-dot{background:#d29922}
.status-cell{display:flex;align-items:center}
.sha{font-family:'SFMono-Regular',Consolas,monospace;font-size:12px;color:#8b949e}
.time{font-size:12px;color:#8b949e}
/* Modal */
.overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:100;justify-content:center;align-items:center}
.overlay.active{display:flex}
.modal{background:#161b22;border:1px solid #30363d;border-radius:12px;width:100%;max-width:520px;max-height:90vh;overflow-y:auto;box-shadow:0 8px 32px rgba(0,0,0,.4)}
.modal-header{display:flex;align-items:center;justify-content:space-between;padding:16px 20px;border-bottom:1px solid #21262d}
.modal-header h2{font-size:18px;color:#f0f6fc}
.modal-close{background:none;border:none;color:#8b949e;font-size:20px;cursor:pointer;padding:4px 8px}
.modal-close:hover{color:#c9d1d9}
.modal-body{padding:20px}
.form-group{margin-bottom:16px}
.form-group label{display:block;font-size:13px;font-weight:600;color:#c9d1d9;margin-bottom:4px}
.form-group label .req{color:#da3633}
.form-group input,.form-group select{width:100%;padding:8px 12px;border-radius:6px;border:1px solid #30363d;background:#0d1117;color:#c9d1d9;font-size:14px;outline:none}
.form-group input:focus{border-color:#58a6ff;box-shadow:0 0 0 3px #58a6ff33}
.form-group .hint{font-size:11px;color:#8b949e;margin-top:2px}
.form-group .error{font-size:11px;color:#da3633;margin-top:2px;display:none}
.modal-footer{display:flex;gap:8px;justify-content:flex-end;padding:16px 20px;border-top:1px solid #21262d}
.refresh-bar{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;font-size:12px;color:#8b949e}
</style>
</head>
<body>
<div class="header">
<div class="logo"><span>⚡</span> shipyard</div>
<div style="display:flex;gap:8px">
<button class="btn btn-sm" onclick="triggerPoll()">🔄 Poll Now</button>
<button class="btn btn-primary" onclick="openAddModal()">+ Add Repo</button>
</div>
</div>
<div class="container">
<div class="refresh-bar">
<span id="lastUpdate"></span>
<span>Auto-refreshes every 30s</span>
</div>
<div id="content"></div>
</div>
<!-- Add/Edit Modal -->
<div class="overlay" id="modalOverlay" onclick="if(event.target===this)closeModal()">
<div class="modal">
<div class="modal-header">
<h2 id="modalTitle">Add Repo</h2>
<button class="modal-close" onclick="closeModal()">×</button>
</div>
<div class="modal-body">
<form id="repoForm" onsubmit="return handleSubmit(event)">
<input type="hidden" id="editMode" value="">
<input type="hidden" id="editOrigName" value="">
<div class="form-group">
<label>Name <span class="req">*</span></label>
<input id="f_name" required placeholder="my-project">
</div>
<div class="form-group">
<label>Local Path <span class="req">*</span></label>
<input id="f_localPath" required placeholder="/home/user/my-project">
</div>
<div class="form-group">
<label>GitHub Remote (owner/repo) <span class="req">*</span></label>
<input id="f_githubRemote" required placeholder="owner/repo">
</div>
<div class="form-group">
<label>Dev Command <span class="req">*</span></label>
<input id="f_devCommand" required placeholder="npx vite --port {{port}} --host">
<div class="hint">Use {{port}} as port placeholder</div>
</div>
<div class="form-group">
<label>Install Command <span class="req">*</span></label>
<input id="f_installCommand" required placeholder="npm install">
</div>
<div class="form-group">
<label>Base Port <span class="req">*</span></label>
<input id="f_basePort" type="number" required placeholder="3000" min="1024" max="65535">
</div>
<div class="form-group">
<label>Default Branch</label>
<input id="f_defaultBranch" placeholder="main" value="main">
</div>
<div class="form-group">
<label>Poll Interval (seconds)</label>
<input id="f_pollInterval" type="number" placeholder="300" value="300" min="10">
</div>
</form>
</div>
<div class="modal-footer" id="modalFooter">
<button class="btn" onclick="closeModal()">Cancel</button>
<button class="btn btn-primary" onclick="document.getElementById('repoForm').requestSubmit()">Save</button>
</div>
</div>
</div>
<script>
let data = ${statusJson};
function render() {
const el = document.getElementById('content');
document.getElementById('lastUpdate').textContent = 'Updated: ' + new Date().toLocaleTimeString();
const repos = Object.entries(data.repos || {});
if (!repos.length) {
el.innerHTML = '<div class="empty"><h2>No repos configured</h2><p>Click "Add Repo" to get started</p></div>';
return;
}
let html = '';
for (const [name, repo] of repos) {
const previews = Object.entries(data.previews || {}).filter(([k,v]) => v.repoName === name);
const defaultPreviews = previews.filter(([k,v]) => !v.prNumber);
const prPreviews = previews.filter(([k,v]) => v.prNumber).sort((a,b) => a[1].prNumber - b[1].prNumber);
html += '<div class="repo-card">';
html += '<div class="repo-header"><span class="repo-name">' + esc(name) + '</span>';
html += '<div><button class="btn btn-sm" onclick="restartRepo(\\''+esc(name)+'\\')">🔄 Restart</button> ';
html += '<button class="btn btn-sm" onclick="openEditModal(\\''+esc(name)+'\\')">⚙️ Settings</button></div></div>';
html += '<table class="preview-table"><thead><tr><th>Branch</th><th>Status</th><th>Port</th><th>Preview</th><th>SHA</th><th>Updated</th></tr></thead><tbody>';
for (const [key, p] of [...defaultPreviews, ...prPreviews]) {
const statusClass = 'status-' + (p.status || 'down');
const statusLabel = p.status ? p.status.charAt(0).toUpperCase() + p.status.slice(1) : 'Down';
const badge = p.prNumber
? '<span class="badge badge-blue">PR #' + p.prNumber + '</span> ' + esc(p.branch || '')
: '<span class="badge badge-green">' + esc(p.branch || repo.defaultBranch || 'main') + '</span>';
const link = p.port ? 'http://${HOSTNAME}:' + p.port + '/' : '';
const sha = p.sha ? p.sha.substring(0, 7) : '-';
const time = p.updatedAt ? new Date(p.updatedAt).toLocaleString() : '-';
const title = p.prTitle ? ' title="' + esc(p.prTitle) + '"' : '';
html += '<tr' + title + '>';
html += '<td>' + badge + '</td>';
html += '<td><div class="status-cell ' + statusClass + '"><span class="status-dot"></span>' + statusLabel + '</div></td>';
html += '<td>' + (p.port || '-') + '</td>';
html += '<td>' + (link ? '<a href="' + link + '" target="_blank">Open ↗</a>' : '-') + '</td>';
html += '<td><span class="sha">' + sha + '</span></td>';
html += '<td><span class="time">' + time + '</span></td>';
html += '</tr>';
}
if (!previews.length) {
html += '<tr><td colspan="6" style="text-align:center;color:#8b949e;padding:20px">No previews running</td></tr>';
}
html += '</tbody></table></div>';
}
el.innerHTML = html;
}
function esc(s) { return String(s||'').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,'''); }
async function refresh() {
try {
const r = await fetch('/api/status');
data = await r.json();
render();
} catch(e) { console.error('Refresh failed', e); }
}
function openAddModal() {
document.getElementById('modalTitle').textContent = 'Add Repo';
document.getElementById('editMode').value = '';
document.getElementById('editOrigName').value = '';
document.getElementById('repoForm').reset();
document.getElementById('f_defaultBranch').value = 'main';
document.getElementById('f_pollInterval').value = '300';
// Remove delete button if present
const del = document.getElementById('deleteBtn');
if (del) del.remove();
document.getElementById('modalOverlay').classList.add('active');
}
function openEditModal(name) {
const repo = data.repos[name];
if (!repo) return;
document.getElementById('modalTitle').textContent = 'Edit Repo';
document.getElementById('editMode').value = 'edit';
document.getElementById('editOrigName').value = name;
document.getElementById('f_name').value = name;
document.getElementById('f_localPath').value = repo.localPath || '';
document.getElementById('f_githubRemote').value = repo.githubRemote || '';
document.getElementById('f_devCommand').value = repo.devCommand || '';
document.getElementById('f_installCommand').value = repo.installCommand || '';
document.getElementById('f_basePort').value = repo.basePort || '';
document.getElementById('f_defaultBranch').value = repo.defaultBranch || 'main';
document.getElementById('f_pollInterval').value = repo.pollInterval || 300;
// Add delete button
const footer = document.getElementById('modalFooter');
if (!document.getElementById('deleteBtn')) {
const btn = document.createElement('button');
btn.id = 'deleteBtn';
btn.className = 'btn btn-danger';
btn.textContent = '🗑 Delete Repo';
btn.style.marginRight = 'auto';
btn.onclick = () => deleteRepo(name);
footer.prepend(btn);
}
document.getElementById('modalOverlay').classList.add('active');
}
function closeModal() {
document.getElementById('modalOverlay').classList.remove('active');
const del = document.getElementById('deleteBtn');
if (del) del.remove();
}
async function handleSubmit(e) {
e.preventDefault();
const body = {
name: document.getElementById('f_name').value.trim(),
localPath: document.getElementById('f_localPath').value.trim(),
githubRemote: document.getElementById('f_githubRemote').value.trim(),
devCommand: document.getElementById('f_devCommand').value.trim(),
installCommand: document.getElementById('f_installCommand').value.trim(),
basePort: parseInt(document.getElementById('f_basePort').value),
defaultBranch: document.getElementById('f_defaultBranch').value.trim() || 'main',
pollInterval: parseInt(document.getElementById('f_pollInterval').value) || 300,
};
const editMode = document.getElementById('editMode').value;
const origName = document.getElementById('editOrigName').value;
try {
let r;
if (editMode === 'edit') {
r = await fetch('/api/repos/' + encodeURIComponent(origName), {
method: 'PUT', headers: {'Content-Type':'application/json'}, body: JSON.stringify(body)
});
} else {
r = await fetch('/api/repos', {
method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify(body)
});
}
const result = await r.json();
if (!r.ok) { alert(result.error || 'Failed'); return false; }
closeModal();
await refresh();
} catch(e) { alert('Error: ' + e.message); }
return false;
}
async function deleteRepo(name) {
if (!confirm('Delete repo "' + name + '" and all its previews?')) return;
try {
await fetch('/api/repos/' + encodeURIComponent(name), { method: 'DELETE' });
closeModal();
await refresh();
} catch(e) { alert('Error: ' + e.message); }
}
async function restartRepo(name) {
try {
await fetch('/api/repos/' + encodeURIComponent(name) + '/restart', { method: 'POST' });
setTimeout(refresh, 2000);
} catch(e) { alert('Error: ' + e.message); }
}
async function triggerPoll() {
try {
await fetch('/api/poll', { method: 'POST' });
setTimeout(refresh, 3000);
} catch(e) { alert('Error: ' + e.message); }
}
render();
setInterval(refresh, 30000);
</script>
</body>
</html>`;
}
// ---------------------------------------------------------------------------
// Status data
// ---------------------------------------------------------------------------
function getStatusData() {
// Check liveness of all previews
for (const [key, preview] of Object.entries(state.previews)) {
if (preview.pid && !isRunning(preview.pid)) {
if (preview.status === 'running' || preview.status === 'starting') {
preview.status = 'down';
}
}
}
return { repos: config.repos || {}, previews: state.previews || {} };
}
// ---------------------------------------------------------------------------
// HTTP Server
// ---------------------------------------------------------------------------
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
const method = req.method;
const pathname = url.pathname;
try {
// Dashboard
if (method === 'GET' && pathname === '/') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(dashboardHTML());
return;
}
// API: Status
if (method === 'GET' && pathname === '/api/status') {
jsonResponse(res, 200, getStatusData());
return;
}
// API: Add repo
if (method === 'POST' && pathname === '/api/repos') {
const body = await readBody(req);
const { name, localPath, githubRemote, devCommand, installCommand, basePort, defaultBranch, pollInterval } = body;
if (!name || !localPath || !githubRemote || !devCommand || !installCommand || !basePort) {
jsonResponse(res, 400, { error: 'Missing required fields' });
return;
}
if (config.repos[name]) {
jsonResponse(res, 409, { error: 'Repo already exists' });
return;
}
config.repos[name] = { localPath, githubRemote, devCommand, installCommand, basePort, defaultBranch: defaultBranch || 'main', pollInterval: pollInterval || 300 };
saveConfig(config);
// Start default branch preview
const repo = config.repos[name];
setupPreview(repo, name, repo.defaultBranch, repo.defaultBranch, repo.basePort).catch(e => log(`Setup failed: ${e.message}`));
startPolling(name);
jsonResponse(res, 201, { ok: true });
return;
}
// API: Update repo
const putMatch = pathname.match(/^\/api\/repos\/([^/]+)$/);
if (method === 'PUT' && putMatch) {
const repoName = decodeURIComponent(putMatch[1]);
if (!config.repos[repoName]) {
jsonResponse(res, 404, { error: 'Repo not found' });
return;
}
const body = await readBody(req);
const { name, localPath, githubRemote, devCommand, installCommand, basePort, defaultBranch, pollInterval } = body;
if (!name || !localPath || !githubRemote || !devCommand || !installCommand || !basePort) {
jsonResponse(res, 400, { error: 'Missing required fields' });
return;
}
// If name changed, rename
if (name !== repoName) {
await cleanupRepo(repoName);
delete config.repos[repoName];
}
config.repos[name] = { localPath, githubRemote, devCommand, installCommand, basePort, defaultBranch: defaultBranch || 'main', pollInterval: pollInterval || 300 };
saveConfig(config);
// Restart
const repo = config.repos[name];
setupPreview(repo, name, repo.defaultBranch, repo.defaultBranch, repo.basePort).catch(e => log(`Setup failed: ${e.message}`));
startPolling(name);
jsonResponse(res, 200, { ok: true });
return;
}
// API: Delete repo
const delMatch = pathname.match(/^\/api\/repos\/([^/]+)$/);
if (method === 'DELETE' && delMatch) {
const repoName = decodeURIComponent(delMatch[1]);
if (!config.repos[repoName]) {
jsonResponse(res, 404, { error: 'Repo not found' });
return;
}
await cleanupRepo(repoName);
delete config.repos[repoName];
saveConfig(config);
jsonResponse(res, 200, { ok: true });
return;
}
// API: Restart repo
const restartMatch = pathname.match(/^\/api\/repos\/([^/]+)\/restart$/);
if (method === 'POST' && restartMatch) {
const repoName = decodeURIComponent(restartMatch[1]);
const repo = config.repos[repoName];
if (!repo) {
jsonResponse(res, 404, { error: 'Repo not found' });
return;
}
// Kill all and re-poll
for (const [key, preview] of Object.entries(state.previews)) {
if (preview.repoName === repoName) {
killProcess(key);
delete state.previews[key];
}
}
saveState(state);
pollRepo(repoName).catch(e => log(`Restart poll failed: ${e.message}`));
jsonResponse(res, 200, { ok: true });
return;
}
// API: Trigger poll
if (method === 'POST' && pathname === '/api/poll') {
pollAll().catch(e => log(`Poll failed: ${e.message}`));
jsonResponse(res, 200, { ok: true });
return;
}
// 404
jsonResponse(res, 404, { error: 'Not found' });
} catch (e) {
log(`HTTP error: ${e.message}`);
jsonResponse(res, 500, { error: 'Internal server error' });
}
});
// ---------------------------------------------------------------------------
// Startup
// ---------------------------------------------------------------------------
async function startup() {
log(`shipyard starting on port ${PORT}...`);
// Check liveness of existing previews, restart dead ones
for (const [key, preview] of Object.entries(state.previews)) {
if (preview.pid && !isRunning(preview.pid)) {
preview.status = 'down';
}
}
saveState(state);
server.listen(PORT, () => {
log(`Dashboard: http://${HOSTNAME}:${PORT}/`);
});
// Initial poll for all repos
await pollAll();
// Start polling timers
for (const repoName of Object.keys(config.repos)) {
startPolling(repoName);
}
}
// ---------------------------------------------------------------------------
// Graceful shutdown
// ---------------------------------------------------------------------------
function shutdown(signal) {
log(`Received ${signal}, shutting down...`);
// Stop polling
for (const timer of pollTimers.values()) clearInterval(timer);
pollTimers.clear();
// Kill all child processes
for (const [key] of childProcesses) {
killProcess(key);
}
// Also kill any PIDs from state
for (const [key, preview] of Object.entries(state.previews)) {
if (preview.pid && isRunning(preview.pid)) {
try { process.kill(-preview.pid, 'SIGTERM'); } catch {}
try { process.kill(preview.pid, 'SIGTERM'); } catch {}
}
preview.status = 'down';
}
saveState(state);
server.close(() => {
log('Server closed');
process.exit(0);
});
// Force exit after 5s
setTimeout(() => process.exit(1), 5000);
}
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
startup().catch(e => {
log(`Startup failed: ${e.message}`);
process.exit(1);
});