Repository navigation
Expand file tree
/
Copy pathcodeview
More file actions
executable file
·920 lines (823 loc) · 29.9 KB
/
Copy pathcodeview
File metadata and controls
executable file
·920 lines (823 loc) · 29.9 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
#!/usr/bin/env node
/**
* CodeView launcher — tiny HTTP server that serves the app and the report.
*
* Usage:
* codeview # start viewer for the current project
* codeview --project <path> # view a specific project's report
* codeview --report <path> # point directly at a report JSON file
* codeview --port <n> # start on a specific port
* codeview --demo # serve the bundled sample-report.json
*
* codeview list # list all running instances
* codeview stop # stop the instance for this project
* codeview stop --all # stop every running instance
* codeview open # open browser for an already-running instance
*
* Report resolution order:
* 1. --report <path> explicit file
* 2. --demo bundled sample
* 3. --project <path>/.codeview/report.json
* 4. $CODEVIEW_REPORT env var
* 5. $CODEVIEW_PROJECT/.codeview/report.json
* 6. ./.codeview/report.json (cwd fallback)
* 7. ~/.codeview/config.json user config with { "defaultProject": "..." }
* 8. Refuse to start with a helpful error (NO silent demo fallback)
*
* State file: ~/.codeview/running.json — tracks PID, port, project, started-at
* Config file: ~/.codeview/config.json (optional) — defaultProject
* Per-project ports are assigned automatically starting at 4100 and scanning
* upward if busy.
*/
const http = require('node:http')
const fs = require('node:fs')
const path = require('node:path')
const os = require('node:os')
const { execSync } = require('node:child_process')
// ============================================================
// Config
// ============================================================
const STATE_DIR = path.join(os.homedir(), '.codeview')
const STATE_FILE = path.join(STATE_DIR, 'running.json')
const CONFIG_FILE = path.join(STATE_DIR, 'config.json')
const DEFAULT_PORT_START = 4100
const DEFAULT_PORT_END = 4199
/** Max time to wait for server.close() before forcing process exit on SIGINT/SIGTERM */
const SHUTDOWN_TIMEOUT_MS = 2000
/** Delay after SIGTERMing a target instance before we verify and force-prune its state entry */
const STOP_SETTLE_DELAY_MS = 500
// Resolve app assets relative to this script
const SCRIPT_DIR = __dirname
const APP_DIR = path.resolve(SCRIPT_DIR, '..', 'app')
const INDEX_HTML = path.join(APP_DIR, 'index.html')
const SAMPLE_REPORT = path.join(APP_DIR, 'sample-report.json')
// ============================================================
// Args parsing
// ============================================================
const args = process.argv.slice(2)
const command = args[0] && !args[0].startsWith('-') ? args[0] : 'start'
const getArg = (name, fallback) => {
const i = args.indexOf(name)
return i >= 0 && args[i + 1] ? args[i + 1] : fallback
}
const hasFlag = (name) => args.includes(name)
// ============================================================
// User config
// ============================================================
function readConfig() {
try {
const raw = fs.readFileSync(CONFIG_FILE, 'utf-8')
return JSON.parse(raw)
} catch {
return {}
}
}
function writeConfig(config) {
fs.mkdirSync(STATE_DIR, { recursive: true })
const tmpFile = CONFIG_FILE + '.tmp.' + process.pid
fs.writeFileSync(tmpFile, JSON.stringify(config, null, 2))
fs.renameSync(tmpFile, CONFIG_FILE)
}
function expandHome(p) {
if (!p) return p
if (p.startsWith('~/')) return path.join(os.homedir(), p.slice(2))
if (p === '~') return os.homedir()
return p
}
// ============================================================
// Report resolution
// ============================================================
/**
* Resolve which report to serve, in priority order.
* Returns { reportPath, projectRoot, source } or null if nothing found.
* `source` explains where the path came from for the user.
*/
function resolveReport(options) {
const { explicitReport, explicitProject, demo } = options
// 1. Explicit --report <path>
if (explicitReport) {
const p = path.resolve(expandHome(explicitReport))
if (!fs.existsSync(p)) {
return { error: `Report file not found: ${p}` }
}
return {
reportPath: p,
projectRoot: path.dirname(path.dirname(p)), // .codeview/report.json → parent of .codeview
source: '--report flag',
}
}
// 2. --demo
if (demo) {
return {
reportPath: SAMPLE_REPORT,
projectRoot: path.dirname(SAMPLE_REPORT),
source: '--demo flag',
}
}
// 3. --project <path>
if (explicitProject) {
const root = path.resolve(expandHome(explicitProject))
const rpt = path.join(root, '.codeview', 'report.json')
if (!fs.existsSync(rpt)) {
return { error: `No report at ${rpt}\nRun /codeview in Claude Code from that project first.` }
}
return { reportPath: rpt, projectRoot: root, source: '--project flag' }
}
// 4. CODEVIEW_REPORT env var
if (process.env.CODEVIEW_REPORT) {
const p = path.resolve(expandHome(process.env.CODEVIEW_REPORT))
if (fs.existsSync(p)) {
return { reportPath: p, projectRoot: path.dirname(path.dirname(p)), source: 'CODEVIEW_REPORT env var' }
}
}
// 5. CODEVIEW_PROJECT env var
if (process.env.CODEVIEW_PROJECT) {
const root = path.resolve(expandHome(process.env.CODEVIEW_PROJECT))
const rpt = path.join(root, '.codeview', 'report.json')
if (fs.existsSync(rpt)) {
return { reportPath: rpt, projectRoot: root, source: 'CODEVIEW_PROJECT env var' }
}
}
// 6. ./.codeview/report.json (cwd)
const cwdRoot = process.cwd()
const cwdReport = path.join(cwdRoot, '.codeview', 'report.json')
if (fs.existsSync(cwdReport)) {
return { reportPath: cwdReport, projectRoot: cwdRoot, source: 'current directory' }
}
// 7. ~/.codeview/config.json → defaultProject
const cfg = readConfig()
if (cfg.defaultProject) {
const root = path.resolve(expandHome(cfg.defaultProject))
const rpt = path.join(root, '.codeview', 'report.json')
if (fs.existsSync(rpt)) {
return { reportPath: rpt, projectRoot: root, source: `config.json defaultProject: ${cfg.defaultProject}` }
}
}
// 8. Nothing found — refuse to start
return {
error: [
'No CodeView report found.',
'',
`Checked: ${cwdReport}`,
cfg.defaultProject ? `Also tried default project: ${cfg.defaultProject}` : null,
'',
'To generate a report:',
' 1. cd into a project directory',
' 2. In Claude Code, run: /codeview',
' 3. Then run `codeview` again from that directory',
'',
'Or point directly at one:',
' codeview --project /path/to/project',
' codeview --report /path/to/report.json',
' codeview --demo # view the bundled sample',
'',
'Or set a default project by adding to ~/.codeview/config.json:',
' { "defaultProject": "/path/to/project" }',
].filter(Boolean).join('\n'),
}
}
// ============================================================
// State management
// ============================================================
function readState() {
try {
const raw = fs.readFileSync(STATE_FILE, 'utf-8')
const parsed = JSON.parse(raw)
return Array.isArray(parsed.instances) ? parsed : { instances: [] }
} catch {
return { instances: [] }
}
}
function writeState(state) {
try {
fs.mkdirSync(STATE_DIR, { recursive: true })
// Atomic write: write to a temp file in the same directory, then rename.
// On POSIX this is atomic — readers never see a partial JSON file even
// if multiple codeview processes update state concurrently.
const tmpFile = STATE_FILE + '.tmp.' + process.pid
fs.writeFileSync(tmpFile, JSON.stringify(state, null, 2))
fs.renameSync(tmpFile, STATE_FILE)
} catch (err) {
console.error('Warning: failed to write state file:', err.message)
}
}
function isPidAlive(pid) {
if (!pid) return false
try {
// Signal 0 — just checks existence
process.kill(pid, 0)
return true
} catch {
return false
}
}
function pruneDeadInstances(state) {
const alive = state.instances.filter((i) => isPidAlive(i.pid))
if (alive.length !== state.instances.length) {
state.instances = alive
writeState(state)
}
return state
}
function findInstanceForProject(projectRoot) {
const state = pruneDeadInstances(readState())
return state.instances.find((i) => i.projectRoot === projectRoot)
}
function registerInstance(entry) {
const state = pruneDeadInstances(readState())
state.instances.push(entry)
writeState(state)
}
function removeInstance(pid) {
const state = readState()
state.instances = state.instances.filter((i) => i.pid !== pid)
writeState(state)
}
// ============================================================
// Port selection
// ============================================================
function isPortFree(port) {
return new Promise((resolve) => {
const tester = http.createServer()
tester.once('error', () => resolve(false))
tester.once('listening', () => {
tester.close(() => resolve(true))
})
tester.listen(port, '127.0.0.1')
})
}
async function findFreePort(preferred) {
if (preferred) {
if (await isPortFree(preferred)) return preferred
throw new Error(`Port ${preferred} is in use.`)
}
// Also check the state file — skip ports already claimed by our own instances
const state = pruneDeadInstances(readState())
const claimed = new Set(state.instances.map((i) => i.port))
for (let p = DEFAULT_PORT_START; p <= DEFAULT_PORT_END; p++) {
if (claimed.has(p)) continue
if (await isPortFree(p)) return p
}
throw new Error(`No free ports in range ${DEFAULT_PORT_START}-${DEFAULT_PORT_END}.`)
}
// ============================================================
// HTTP server
// ============================================================
function safeRead(filePath) {
try {
return fs.readFileSync(filePath)
} catch {
return null
}
}
/**
* Server state — mutable, can be changed at runtime via the API.
* This is what makes the onboarding screen work: the server can start
* with no report, then the UI selects one and POSTs it here.
*/
class ServerState {
constructor(initial) {
this.reportPath = initial?.reportPath ?? null
this.projectRoot = initial?.projectRoot ?? null
this.source = initial?.source ?? null
this.isDemo = initial?.isDemo ?? false
}
hasReport() {
return this.reportPath !== null
}
toJSON() {
return {
hasReport: this.hasReport(),
reportPath: this.reportPath,
projectRoot: this.projectRoot,
source: this.source,
isDemo: this.isDemo,
}
}
/** Try to activate a project directory. Returns { ok: true } or { ok: false, error }. */
selectProject(projectRoot) {
const root = path.resolve(expandHome(projectRoot))
const rpt = path.join(root, '.codeview', 'report.json')
if (!fs.existsSync(rpt)) {
return { ok: false, error: `No report at ${rpt}. Run /codeview in Claude Code from that project first.` }
}
this.reportPath = rpt
this.projectRoot = root
this.source = 'ui'
this.isDemo = false
// Remember in config as the most recent project
rememberRecentProject(root)
return { ok: true, state: this.toJSON() }
}
/** Point at a specific report file directly. */
selectReport(reportPath) {
const p = path.resolve(expandHome(reportPath))
if (!fs.existsSync(p)) {
return { ok: false, error: `Report not found: ${p}` }
}
this.reportPath = p
this.projectRoot = path.dirname(path.dirname(p))
this.source = 'ui'
this.isDemo = false
return { ok: true, state: this.toJSON() }
}
/** Switch to the bundled demo report. */
selectDemo() {
this.reportPath = SAMPLE_REPORT
this.projectRoot = path.dirname(SAMPLE_REPORT)
this.source = 'demo'
this.isDemo = true
return { ok: true, state: this.toJSON() }
}
/** Clear the active project — the UI shows onboarding after this. */
clearProject() {
this.reportPath = null
this.projectRoot = null
this.source = null
this.isDemo = false
return { ok: true, state: this.toJSON() }
}
}
// Hard cap on JSON request bodies. All our real API calls are small
// (project path, report path, etc.) — anything larger is abuse.
const MAX_BODY_BYTES = 1024 * 1024 // 1 MB
function readBody(req) {
return new Promise((resolve, reject) => {
const chunks = []
let received = 0
let aborted = false
req.on('data', (chunk) => {
if (aborted) return
received += chunk.length
if (received > MAX_BODY_BYTES) {
aborted = true
const err = new Error(`Request body too large (> ${MAX_BODY_BYTES} bytes)`)
err.statusCode = 413
// Drain and abort the request so we don't keep buffering
req.destroy(err)
reject(err)
return
}
chunks.push(chunk)
})
req.on('end', () => {
if (aborted) return
const raw = Buffer.concat(chunks).toString('utf-8')
if (!raw) return resolve({})
try {
resolve(JSON.parse(raw))
} catch (err) {
reject(new Error('Invalid JSON body: ' + err.message))
}
})
req.on('error', (err) => {
if (!aborted) reject(err)
})
})
}
function sendJson(res, statusCode, data) {
res.writeHead(statusCode, {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-cache',
})
res.end(JSON.stringify(data))
}
/**
* Check that an API request originates from our own localhost page.
* Two-level defense:
* • For state-mutating methods (POST/PUT/DELETE/PATCH): REQUIRE a valid
* Origin header. Non-browser clients and old-form POSTs that omit
* Origin are rejected — even from localhost — because they could be
* CSRF attempts from a malicious process.
* • For GET (needed so the browser can load the HTML shell via top-level
* navigation): accept no-Origin (browsers don't always send it on
* top-level nav), but if Origin is present it must match localhost.
*
* Any non-loopback Origin is always rejected.
*/
function isOriginAllowed(req, serverPort) {
const origin = req.headers.origin
const method = (req.method || 'GET').toUpperCase()
const isStateMutating = method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS'
if (!origin) {
// No Origin header — only acceptable on safe methods (GET/HEAD/OPTIONS)
return !isStateMutating
}
try {
const url = new URL(origin)
const isLoopback = url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname === '[::1]'
const portMatches = !url.port || Number(url.port) === Number(serverPort)
return isLoopback && portMatches
} catch {
return false
}
}
function createServer(state, serverPort) {
return http.createServer(async (req, res) => {
const url = (req.url || '/').split('?')[0]
const method = req.method || 'GET'
// Origin check for all /api/* endpoints (CSRF defense)
if (url.startsWith('/api/') && !isOriginAllowed(req, serverPort)) {
return sendJson(res, 403, { error: 'Origin not allowed' })
}
try {
return await handleRequest(state, serverPort, req, res, url, method)
} catch (err) {
// Malformed request body, oversized body, etc. — return a clean
// error status code instead of crashing the process.
const statusCode = err && err.statusCode ? err.statusCode : 400
return sendJson(res, statusCode, { error: err.message || String(err) })
}
})
}
async function handleRequest(state, serverPort, req, res, url, method) {
// ─── API: state ────────────────────────────────────────
if (url === '/api/state' && method === 'GET') {
return sendJson(res, 200, state.toJSON())
}
// ─── API: recent projects ─────────────────────────────
if (url === '/api/recent-projects' && method === 'GET') {
const cfg = readConfig()
const recent = (cfg.recentProjects || []).filter((p) => {
const rpt = path.join(p, '.codeview', 'report.json')
return fs.existsSync(rpt)
})
return sendJson(res, 200, { projects: recent })
}
// ─── API: browse filesystem (server-side directory picker) ───
if (url === '/api/browse' && method === 'GET') {
const params = new URL(req.url, 'http://x').searchParams
const requestedPath = params.get('path')
const showHidden = params.get('hidden') === '1'
const homeDir = os.homedir()
let dir
try {
dir = requestedPath ? path.resolve(expandHome(requestedPath)) : homeDir
// Sandbox: limit browsing to the user's home directory subtree.
// Without this, any webpage that bypasses the Origin check could
// enumerate the entire filesystem.
if (dir !== homeDir && !dir.startsWith(homeDir + path.sep)) {
return sendJson(res, 403, {
error: `Directory browsing is restricted to ${homeDir} and its subdirectories.`,
})
}
const stat = fs.statSync(dir)
if (!stat.isDirectory()) {
return sendJson(res, 400, { error: `Not a directory: ${dir}` })
}
} catch (err) {
return sendJson(res, 400, { error: `Cannot access: ${err.message}` })
}
try {
const entries = fs.readdirSync(dir, { withFileTypes: true })
.filter((e) => e.isDirectory() || e.isSymbolicLink())
.filter((e) => showHidden || !e.name.startsWith('.'))
.map((e) => {
const fullPath = path.join(dir, e.name)
let hasReport = false
let isDir = e.isDirectory()
try {
// Resolve symlinks
if (e.isSymbolicLink()) {
isDir = fs.statSync(fullPath).isDirectory()
}
if (isDir) {
hasReport = fs.existsSync(path.join(fullPath, '.codeview', 'report.json'))
}
} catch {
// Permission denied or broken symlink — treat as non-dir
isDir = false
}
return { name: e.name, path: fullPath, isDirectory: isDir, hasReport }
})
.filter((e) => e.isDirectory)
.sort((a, b) => {
if (a.hasReport !== b.hasReport) return a.hasReport ? -1 : 1
return a.name.localeCompare(b.name, undefined, { sensitivity: 'base' })
})
// Parent link: null at the home boundary so users can't navigate above
const parentCandidate = path.dirname(dir)
const parent = dir === homeDir || parentCandidate === dir
? null
: parentCandidate
const currentHasReport = fs.existsSync(path.join(dir, '.codeview', 'report.json'))
return sendJson(res, 200, {
path: dir,
parent,
hasReport: currentHasReport,
home: os.homedir(),
entries,
})
} catch (err) {
return sendJson(res, 500, { error: `Read error: ${err.message}` })
}
}
// ─── API: select project ──────────────────────────────
if (url === '/api/select-project' && method === 'POST') {
const body = await readBody(req)
if (!body.projectRoot) {
return sendJson(res, 400, { ok: false, error: 'projectRoot is required' })
}
const result = state.selectProject(body.projectRoot)
return sendJson(res, result.ok ? 200 : 400, result)
}
// ─── API: select report file directly ─────────────────
if (url === '/api/select-report' && method === 'POST') {
const body = await readBody(req)
if (!body.reportPath) {
return sendJson(res, 400, { ok: false, error: 'reportPath is required' })
}
const result = state.selectReport(body.reportPath)
return sendJson(res, result.ok ? 200 : 400, result)
}
// ─── API: switch to demo ──────────────────────────────
if (url === '/api/select-demo' && method === 'POST') {
const result = state.selectDemo()
return sendJson(res, 200, result)
}
// ─── API: clear project (force onboarding) ────────────
if (url === '/api/clear-project' && method === 'POST') {
const result = state.clearProject()
return sendJson(res, 200, result)
}
// ─── Report JSON ───────────────────────────────────────
if (url === '/report.json') {
if (!state.hasReport()) {
return sendJson(res, 404, {
error: 'No project selected. Use the onboarding screen to pick one.',
hasReport: false,
})
}
const content = safeRead(state.reportPath)
if (!content) {
return sendJson(res, 404, {
error: `Report file vanished: ${state.reportPath}`,
hasReport: false,
})
}
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-cache',
})
res.end(content)
return
}
// ─── Static HTML (SPA) ─────────────────────────────────
const html = safeRead(INDEX_HTML)
if (!html) {
res.writeHead(500)
res.end('CodeView app not found at ' + INDEX_HTML)
return
}
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'no-cache',
'X-Content-Type-Options': 'nosniff',
})
res.end(html)
}
/** Keep a rolling list of recent projects in config.json */
function rememberRecentProject(projectRoot) {
const cfg = readConfig()
const recent = cfg.recentProjects || []
const filtered = recent.filter((p) => p !== projectRoot)
filtered.unshift(projectRoot)
cfg.recentProjects = filtered.slice(0, 10) // keep last 10
try {
writeConfig(cfg)
} catch (err) {
// Non-fatal — recent history is advisory — but still surface the failure
console.error('Warning: failed to update recent-projects history:', err.message)
}
}
function openInBrowser(url) {
try {
const cmd = process.platform === 'darwin'
? `open "${url}"`
: process.platform === 'win32'
? `start "" "${url}"`
: `xdg-open "${url}"`
execSync(cmd, { stdio: 'ignore' })
} catch {
// silent — user can click manually
}
}
// ============================================================
// Commands
// ============================================================
async function cmdStart() {
const cwd = process.cwd()
const preferredPort = args.includes('--port') ? parseInt(getArg('--port'), 10) : null
const explicitProject = getArg('--project')
const explicitReport = getArg('--report')
const demo = hasFlag('--demo')
// Resolve the initial report (if any). Unlike before, we DO NOT exit on failure —
// the server starts with no active report and the onboarding screen handles it.
const resolution = resolveReport({ explicitReport, explicitProject, demo })
// Detect an existing instance for this project (if we resolved to a real project).
// Reuse it so we don't spawn duplicates.
const reuseKey = resolution.projectRoot && !resolution.error ? resolution.projectRoot : cwd
const existing = findInstanceForProject(reuseKey)
if (existing && !preferredPort) {
const url = `http://localhost:${existing.port}`
console.log('')
console.log(` CodeView already running for this project at ${url}`)
console.log(` PID: ${existing.pid} · started: ${new Date(existing.startedAt).toLocaleString()}`)
console.log('')
console.log(` Opening browser. To stop: codeview stop`)
console.log('')
openInBrowser(url)
return
}
let port
try {
port = await findFreePort(preferredPort)
} catch (err) {
console.error('Error:', err.message)
process.exit(1)
}
// Build the initial state
const state = new ServerState(
resolution.error
? null
: {
reportPath: resolution.reportPath,
projectRoot: resolution.projectRoot,
source: resolution.source,
isDemo: Boolean(demo),
},
)
// Remember real projects (not demo, not errors)
if (state.hasReport() && !state.isDemo && state.projectRoot) {
rememberRecentProject(state.projectRoot)
}
const server = createServer(state, port)
// Bind to loopback only — never expose the dashboard on the network.
// Even with the Origin check and browse sandbox, defence in depth: if a
// process on the machine can talk to localhost, that's expected; LAN
// access is not. The listen() hostname argument controls which interface
// we accept connections on.
server.listen(port, '127.0.0.1', () => {
const url = `http://localhost:${port}`
registerInstance({
projectRoot: state.projectRoot || cwd,
port,
pid: process.pid,
demo: Boolean(demo),
startedAt: new Date().toISOString(),
})
console.log('')
console.log(` CodeView running at ${url}`)
if (state.hasReport()) {
console.log(` Project: ${state.projectRoot}`)
console.log(` Report: ${state.reportPath}${state.isDemo ? ' (demo)' : ''}`)
console.log(` Source: ${state.source}`)
} else {
console.log(` No report loaded — use the onboarding screen in the browser to pick one`)
}
console.log('')
console.log(` PID: ${process.pid}`)
console.log(` Stop: codeview stop (or Ctrl+C)`)
console.log('')
openInBrowser(url)
})
const shutdown = (signal) => {
console.log(`\n ${signal} received — shutting down CodeView`)
removeInstance(process.pid)
server.close(() => process.exit(0))
setTimeout(() => process.exit(0), SHUTDOWN_TIMEOUT_MS).unref()
}
process.on('SIGINT', () => shutdown('SIGINT'))
process.on('SIGTERM', () => shutdown('SIGTERM'))
process.on('exit', () => removeInstance(process.pid))
}
function cmdList() {
const state = pruneDeadInstances(readState())
if (state.instances.length === 0) {
console.log('No CodeView instances running.')
return
}
console.log('')
console.log(' Running CodeView instances:')
console.log('')
for (const inst of state.instances) {
const uptime = Date.now() - new Date(inst.startedAt).getTime()
const uptimeStr = formatDuration(uptime)
console.log(` [${inst.pid}] port ${inst.port} ${inst.projectRoot}`)
console.log(` http://localhost:${inst.port} · uptime ${uptimeStr}${inst.demo ? ' · demo' : ''}`)
}
console.log('')
}
function cmdStop() {
const all = hasFlag('--all')
const state = pruneDeadInstances(readState())
if (state.instances.length === 0) {
console.log('No CodeView instances running.')
return
}
let targets = []
if (all) {
targets = state.instances
} else {
const projectRoot = process.cwd()
const match = state.instances.find((i) => i.projectRoot === projectRoot)
if (!match) {
console.log(`No CodeView instance running for ${projectRoot}`)
console.log('Use "codeview list" to see all running instances, or "codeview stop --all" to stop everything.')
return
}
targets = [match]
}
for (const inst of targets) {
try {
process.kill(inst.pid, 'SIGTERM')
console.log(` Stopped [${inst.pid}] port ${inst.port} — ${inst.projectRoot}`)
} catch (err) {
console.log(` Warning: couldn't stop PID ${inst.pid}: ${err.message}`)
}
}
// Give the processes a moment to clean up their own state entries
setTimeout(() => {
const fresh = pruneDeadInstances(readState())
// For any targets that didn't clean up themselves, force-remove
for (const inst of targets) {
if (fresh.instances.some((i) => i.pid === inst.pid)) {
removeInstance(inst.pid)
}
}
}, STOP_SETTLE_DELAY_MS)
}
function cmdOpen() {
const projectRoot = process.cwd()
const inst = findInstanceForProject(projectRoot)
if (!inst) {
console.log(`No CodeView instance running for ${projectRoot}`)
console.log('Start one with: codeview')
return
}
const url = `http://localhost:${inst.port}`
console.log(`Opening ${url}`)
openInBrowser(url)
}
function cmdHelp() {
console.log(`
CodeView — code health dashboard
Usage:
codeview Start viewer for the current project
codeview --port <n> Use a specific port
codeview --demo Show the bundled sample report
codeview list List all running instances
codeview stop Stop the instance for the current project
codeview stop --all Stop every running instance
codeview open Open the browser to an already-running instance
codeview help Show this help
Ports are auto-assigned in the range ${DEFAULT_PORT_START}-${DEFAULT_PORT_END}.
State is tracked at ${STATE_FILE}
`)
}
// ============================================================
// Utility
// ============================================================
function formatDuration(ms) {
const s = Math.floor(ms / 1000)
if (s < 60) return `${s}s`
const m = Math.floor(s / 60)
if (m < 60) return `${m}m${s % 60}s`
const h = Math.floor(m / 60)
return `${h}h${m % 60}m`
}
// ============================================================
// Dispatch
// ============================================================
async function main() {
switch (command) {
case 'start':
await cmdStart()
break
case 'list':
case 'ls':
case 'ps':
cmdList()
break
case 'stop':
case 'kill':
cmdStop()
break
case 'open':
cmdOpen()
break
case 'help':
case '--help':
case '-h':
cmdHelp()
break
default:
console.error(`Unknown command: ${command}`)
cmdHelp()
process.exit(1)
}
}
main().catch((err) => {
console.error('Error:', err.message)
process.exit(1)
})