repoview 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/CONTRIBUTING.md +4 -3
  3. package/DEVELOPMENT.md +70 -16
  4. package/README.md +36 -5
  5. package/dist/api.js +58 -0
  6. package/dist/api.js.map +1 -0
  7. package/dist/cli.js +224 -0
  8. package/dist/cli.js.map +1 -0
  9. package/dist/csv.js +64 -0
  10. package/dist/csv.js.map +1 -0
  11. package/dist/format.js +25 -0
  12. package/dist/format.js.map +1 -0
  13. package/dist/git.js +67 -0
  14. package/dist/git.js.map +1 -0
  15. package/dist/gitignore.js +34 -0
  16. package/dist/gitignore.js.map +1 -0
  17. package/dist/linkcheck.js +310 -0
  18. package/dist/linkcheck.js.map +1 -0
  19. package/dist/markdown.js +493 -0
  20. package/dist/markdown.js.map +1 -0
  21. package/dist/net.js +10 -0
  22. package/dist/net.js.map +1 -0
  23. package/dist/paths.js +59 -0
  24. package/dist/paths.js.map +1 -0
  25. package/dist/reload.js +36 -0
  26. package/dist/reload.js.map +1 -0
  27. package/dist/repo-context.js +73 -0
  28. package/dist/repo-context.js.map +1 -0
  29. package/dist/repo-router.js +801 -0
  30. package/dist/repo-router.js.map +1 -0
  31. package/dist/review-cli.js +228 -0
  32. package/dist/review-cli.js.map +1 -0
  33. package/dist/server.js +116 -0
  34. package/dist/server.js.map +1 -0
  35. package/dist/session.js +86 -0
  36. package/dist/session.js.map +1 -0
  37. package/dist/types.js +2 -0
  38. package/dist/types.js.map +1 -0
  39. package/dist/views.js +633 -0
  40. package/dist/views.js.map +1 -0
  41. package/package.json +20 -9
  42. package/public/app.css +82 -0
  43. package/public/app.js +4 -2
  44. package/public/review.js +9 -6
  45. package/public/session.js +61 -0
  46. package/src/cli.js +0 -91
  47. package/src/gitignore.js +0 -34
  48. package/src/linkcheck.js +0 -312
  49. package/src/markdown.js +0 -518
  50. package/src/review-cli.js +0 -245
  51. package/src/server.js +0 -1126
  52. package/src/views.js +0 -657
package/src/server.js DELETED
@@ -1,1126 +0,0 @@
1
- import fs from "node:fs/promises";
2
- import http from "node:http";
3
- import { createRequire } from "node:module";
4
- import path from "node:path";
5
- import { spawn } from "node:child_process";
6
- import { fileURLToPath } from "node:url";
7
- import express from "express";
8
- import chokidar from "chokidar";
9
- import mime from "mime-types";
10
-
11
- import { createMarkdownRenderer } from "./markdown.js";
12
- import { loadGitIgnoreMatcher } from "./gitignore.js";
13
- import { createRepoLinkScanner } from "./linkcheck.js";
14
- import diff2html from "diff2html";
15
- import {
16
- escapeHtml,
17
- renderBrokenLinksPage,
18
- renderDiffPage,
19
- renderErrorPage,
20
- renderFilePage,
21
- renderReviewListPage,
22
- renderReviewThreadPage,
23
- renderTreePage,
24
- } from "./views.js";
25
-
26
- function toPosixPath(p) {
27
- return p.split(path.sep).join("/");
28
- }
29
-
30
- function encodePathForUrl(posixPath) {
31
- return posixPath
32
- .split("/")
33
- .map((segment) => encodeURIComponent(segment))
34
- .join("/");
35
- }
36
-
37
- function isWithinRoot(rootReal, candidateReal) {
38
- if (candidateReal === rootReal) return true;
39
- const rootWithSep = rootReal.endsWith(path.sep) ? rootReal : rootReal + path.sep;
40
- return candidateReal.startsWith(rootWithSep);
41
- }
42
-
43
- function parseCsv(text, delimiter = ",") {
44
- const rows = [];
45
- let current = [];
46
- let cell = "";
47
- let inQuotes = false;
48
-
49
- for (let i = 0; i < text.length; i++) {
50
- const ch = text[i];
51
- if (inQuotes) {
52
- if (ch === '"' && text[i + 1] === '"') {
53
- cell += '"';
54
- i++;
55
- } else if (ch === '"') {
56
- inQuotes = false;
57
- } else {
58
- cell += ch;
59
- }
60
- } else {
61
- if (ch === '"') {
62
- inQuotes = true;
63
- } else if (ch === delimiter) {
64
- current.push(cell);
65
- cell = "";
66
- } else if (ch === "\n" || (ch === "\r" && text[i + 1] === "\n")) {
67
- if (ch === "\r") i++;
68
- current.push(cell);
69
- rows.push(current);
70
- current = [];
71
- cell = "";
72
- } else if (ch === "\r") {
73
- current.push(cell);
74
- rows.push(current);
75
- current = [];
76
- cell = "";
77
- } else {
78
- cell += ch;
79
- }
80
- }
81
- }
82
- if (cell || current.length) {
83
- current.push(cell);
84
- rows.push(current);
85
- }
86
- return rows;
87
- }
88
-
89
- function renderCsvTable(rows, escFn) {
90
- if (!rows.length) return "<p>Empty file</p>";
91
- const header = rows[0];
92
- const body = rows.slice(1);
93
- const ths = header.map((h) => `<th>${escFn(h)}</th>`).join("");
94
- const trs = body
95
- .map((row) => `<tr>${row.map((c) => `<td>${escFn(c)}</td>`).join("")}</tr>`)
96
- .join("\n");
97
- return `<div class="csv-table-wrap"><table class="csv-table"><thead><tr>${ths}</tr></thead><tbody>${trs}</tbody></table></div>`;
98
- }
99
-
100
- function execGit(repoRootReal, args, maxBytes = 1024 * 1024) {
101
- return new Promise((resolve) => {
102
- const child = spawn("git", args, { cwd: repoRootReal });
103
- let out = "";
104
- let size = 0;
105
- let killed = false;
106
- child.stdout.on("data", (chunk) => {
107
- size += chunk.length;
108
- if (size > maxBytes) {
109
- if (!killed) { killed = true; child.kill(); }
110
- return;
111
- }
112
- out += String(chunk);
113
- });
114
- child.on("close", (code) => {
115
- if (killed) return resolve({ output: out, tooLarge: true, code });
116
- resolve({ output: code === 0 ? out.trim() : null, tooLarge: false, code });
117
- });
118
- child.on("error", () => resolve({ output: null, tooLarge: false, code: -1 }));
119
- });
120
- }
121
-
122
- function validateGitRef(ref) {
123
- if (!ref || typeof ref !== "string") return false;
124
- return /^[a-zA-Z0-9_.\/\-~^]+$/.test(ref);
125
- }
126
-
127
- async function getGitBranches(repoRootReal) {
128
- const { output } = await execGit(repoRootReal, ["branch", "--format=%(refname:short)"]);
129
- if (!output) return [];
130
- return output.split("\n").filter(Boolean);
131
- }
132
-
133
- async function getGitTags(repoRootReal) {
134
- const { output } = await execGit(repoRootReal, ["tag", "-l"]);
135
- if (!output) return [];
136
- return output.split("\n").filter(Boolean);
137
- }
138
-
139
- async function getGitDiffRaw(repoRootReal, base) {
140
- const maxBytes = 512 * 1024;
141
- const { output, tooLarge } = await execGit(repoRootReal, ["diff", base], maxBytes);
142
- return { raw: output || "", tooLarge };
143
- }
144
-
145
- async function getGitInfo(repoRootReal) {
146
- const gitDir = path.join(repoRootReal, ".git");
147
- try {
148
- await fs.stat(gitDir);
149
- } catch {
150
- return { branch: null, commit: null };
151
- }
152
-
153
- const [branchResult, commitResult] = await Promise.all([
154
- execGit(repoRootReal, ["rev-parse", "--abbrev-ref", "HEAD"]),
155
- execGit(repoRootReal, ["rev-parse", "HEAD"]),
156
- ]);
157
- const branch = branchResult.output;
158
- const commit = commitResult.output;
159
- return { branch: branch && branch !== "HEAD" ? branch : branch, commit };
160
- }
161
-
162
- async function safeRealpath(rootReal, requestPath) {
163
- const stripped = String(requestPath || "").replace(/^\/+/, "");
164
- const resolved = path.resolve(rootReal, stripped);
165
- if (!isWithinRoot(rootReal, resolved)) {
166
- const err = new Error("Path escapes repo root");
167
- err.statusCode = 400;
168
- throw err;
169
- }
170
-
171
- let real;
172
- try {
173
- real = await fs.realpath(resolved);
174
- } catch (e) {
175
- e.statusCode = 404;
176
- throw e;
177
- }
178
- if (!isWithinRoot(rootReal, real)) {
179
- const err = new Error("Path resolves outside repo root");
180
- err.statusCode = 400;
181
- throw err;
182
- }
183
- return { stripped, resolved: real };
184
- }
185
-
186
- async function statSafe(p, { followSymlinks = true } = {}) {
187
- try {
188
- const stat = followSymlinks ? await fs.stat(p) : await fs.lstat(p);
189
- return {
190
- isFile: stat.isFile(),
191
- isDir: stat.isDirectory(),
192
- size: stat.size,
193
- mtimeMs: stat.mtimeMs,
194
- };
195
- } catch (e) {
196
- if (e.code === "EACCES" || e.code === "EPERM") {
197
- return null;
198
- }
199
- throw e;
200
- }
201
- }
202
-
203
- function formatBytes(bytes) {
204
- if (!Number.isFinite(bytes)) return "";
205
- if (bytes < 1024) return `${bytes} B`;
206
- const units = ["KB", "MB", "GB", "TB"];
207
- let value = bytes / 1024;
208
- let unit = 0;
209
- while (value >= 1024 && unit < units.length - 1) {
210
- value /= 1024;
211
- unit++;
212
- }
213
- return `${value.toFixed(value < 10 ? 1 : 0)} ${units[unit]}`;
214
- }
215
-
216
- function formatDate(ms) {
217
- const d = new Date(ms);
218
- return d.toLocaleString(undefined, {
219
- year: "numeric",
220
- month: "short",
221
- day: "2-digit",
222
- hour: "2-digit",
223
- minute: "2-digit",
224
- });
225
- }
226
-
227
- function createReloadHub() {
228
- const clients = new Set();
229
- let revision = 0;
230
- return {
231
- add(res) {
232
- clients.add(res);
233
- res.on("close", () => clients.delete(res));
234
- },
235
- broadcastReload() {
236
- revision++;
237
- const payload = `event: reload\ndata: ${Date.now()}\n\n`;
238
- for (const res of clients) res.write(payload);
239
- },
240
- getRevision() {
241
- return revision;
242
- },
243
- broadcastPing() {
244
- const payload = `event: ping\ndata: ${Date.now()}\n\n`;
245
- for (const res of clients) res.write(payload);
246
- },
247
- };
248
- }
249
-
250
- export async function startServer({ repoRoot, host, port, watch }) {
251
- const __filename = fileURLToPath(import.meta.url);
252
- const __dirname = path.dirname(__filename);
253
- const packageRoot = path.resolve(__dirname, "..");
254
- const require = createRequire(import.meta.url);
255
-
256
- const resolvePackageDir = (name) => {
257
- const pkgJson = require.resolve(`${name}/package.json`);
258
- return path.dirname(pkgJson);
259
- };
260
-
261
- const repoRootReal = await fs.realpath(repoRoot);
262
- const repoName = path.basename(repoRootReal);
263
- const gitInfo = await getGitInfo(repoRootReal);
264
- const reloadHub = createReloadHub();
265
- const md = createMarkdownRenderer();
266
- let ignoreMatcher = await loadGitIgnoreMatcher(repoRootReal);
267
- const isIgnored = (relPosix, opts) => ignoreMatcher.ignores(relPosix, opts);
268
- const linkScanner = createRepoLinkScanner({ repoRootReal, markdownRenderer: md, isIgnored });
269
-
270
- const app = express();
271
- app.disable("x-powered-by");
272
-
273
- const publicDir = path.join(packageRoot, "public");
274
- app.use("/static", express.static(publicDir, { fallthrough: true }));
275
- app.use(
276
- "/static/vendor/github-markdown-css",
277
- express.static(resolvePackageDir("github-markdown-css"), {
278
- fallthrough: false,
279
- }),
280
- );
281
- app.use(
282
- "/static/vendor/highlight.js",
283
- express.static(resolvePackageDir("highlight.js"), {
284
- fallthrough: false,
285
- }),
286
- );
287
- app.use(
288
- "/static/vendor/katex",
289
- express.static(path.join(resolvePackageDir("katex"), "dist"), {
290
- fallthrough: false,
291
- }),
292
- );
293
- app.use(
294
- "/static/vendor/mermaid",
295
- express.static(path.join(resolvePackageDir("mermaid"), "dist"), {
296
- fallthrough: false,
297
- }),
298
- );
299
- app.use(
300
- "/static/vendor/diff2html",
301
- express.static(path.join(resolvePackageDir("diff2html"), "bundles", "css"), {
302
- fallthrough: false,
303
- }),
304
- );
305
-
306
- app.use((req, res, next) => {
307
- if (!req.path.startsWith("/static/")) res.setHeader("Cache-Control", "no-store");
308
- next();
309
- });
310
-
311
- app.get("/", (req, res) => res.redirect("/tree/"));
312
-
313
- void linkScanner.triggerScan();
314
-
315
- app.get("/rev", (req, res) => {
316
- res.setHeader("Content-Type", "application/json; charset=utf-8");
317
- res.status(200).send({ revision: reloadHub.getRevision() });
318
- });
319
-
320
- app.get("/broken-links.json", (req, res) => {
321
- res.setHeader("Content-Type", "application/json; charset=utf-8");
322
- res.status(200).send(linkScanner.getState());
323
- });
324
-
325
- app.get("/broken-links", (req, res) => {
326
- const showIgnored = req.query.ignored === "1";
327
- const query = new URLSearchParams();
328
- if (req.query.watch === "0") query.set("watch", "0");
329
- if (showIgnored) query.set("ignored", "1");
330
- const querySuffix = query.toString() ? `?${query.toString()}` : "";
331
- const toggleIgnoredSuffix = (() => {
332
- const q = new URLSearchParams(query);
333
- if (showIgnored) q.delete("ignored");
334
- else q.set("ignored", "1");
335
- return q.toString() ? `?${q.toString()}` : "";
336
- })();
337
- const toggleIgnoredHref = `/broken-links${toggleIgnoredSuffix}`;
338
- const state = linkScanner.getState();
339
- res.status(200).send(
340
- renderBrokenLinksPage({
341
- title: `${repoName} · Broken links`,
342
- repoName,
343
- gitInfo,
344
- relPathPosix: "",
345
- scanState: state,
346
- querySuffix,
347
- toggleIgnoredHref,
348
- showIgnored,
349
- }),
350
- );
351
- });
352
-
353
- app.get("/events", (req, res) => {
354
- res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
355
- res.setHeader("Cache-Control", "no-cache, no-transform");
356
- res.setHeader("Connection", "keep-alive");
357
- res.flushHeaders?.();
358
- res.write("event: hello\ndata: ok\n\n");
359
- reloadHub.add(res);
360
-
361
- const interval = setInterval(() => {
362
- try {
363
- res.write(":\n\n");
364
- reloadHub.broadcastPing();
365
- } catch {
366
- // ignore
367
- }
368
- }, 15000);
369
- res.on("close", () => clearInterval(interval));
370
- });
371
-
372
- app.get("/diff", async (req, res) => {
373
- try {
374
- const base = req.query.base || "HEAD";
375
- if (!validateGitRef(base)) {
376
- const err = new Error("Invalid base ref");
377
- err.statusCode = 400;
378
- throw err;
379
- }
380
-
381
- if (!gitInfo.commit) {
382
- const err = new Error("Not a git repository");
383
- err.statusCode = 400;
384
- throw err;
385
- }
386
-
387
- const query = new URLSearchParams();
388
- if (req.query.watch === "0") query.set("watch", "0");
389
- if (req.query.ignored === "1") query.set("ignored", "1");
390
- if (base !== "HEAD") query.set("base", base);
391
- if (req.query.show_all === "1") query.set("show_all", "1");
392
- const querySuffix = query.toString() ? `?${query.toString()}` : "";
393
-
394
- const [branches, tags, diffResult] = await Promise.all([
395
- getGitBranches(repoRootReal),
396
- getGitTags(repoRootReal),
397
- getGitDiffRaw(repoRootReal, base),
398
- ]);
399
-
400
- const MAX_DIFF_FILES = 30;
401
- let diffHtml = "";
402
- let fileCount = 0;
403
- const showAll = req.query.show_all === "1";
404
- if (!diffResult.tooLarge && diffResult.raw) {
405
- const parsed = diff2html.parse(diffResult.raw);
406
- fileCount = parsed.length;
407
- const toRender = (!showAll && parsed.length > MAX_DIFF_FILES)
408
- ? parsed.slice(0, MAX_DIFF_FILES)
409
- : parsed;
410
- diffHtml = diff2html.html(toRender, {
411
- outputFormat: "line-by-line",
412
- drawFileList: true,
413
- });
414
- }
415
-
416
- res.status(200).send(
417
- renderDiffPage({
418
- title: `${repoName} · Diff`,
419
- repoName,
420
- gitInfo,
421
- relPathPosix: "",
422
- querySuffix,
423
- base,
424
- branches,
425
- tags,
426
- diffHtml,
427
- tooLarge: diffResult.tooLarge,
428
- empty: !diffResult.raw,
429
- fileCount,
430
- showAll,
431
- }),
432
- );
433
- } catch (e) {
434
- res
435
- .status(e.statusCode || 500)
436
- .send(renderErrorPage({ title: "Error", message: e.message }));
437
- }
438
- });
439
-
440
- app.get(["/tree/*", "/tree"], async (req, res) => {
441
- try {
442
- const showIgnored = req.query.ignored === "1";
443
- const query = new URLSearchParams();
444
- if (req.query.watch === "0") query.set("watch", "0");
445
- if (showIgnored) query.set("ignored", "1");
446
- const querySuffix = query.toString() ? `?${query.toString()}` : "";
447
- const toggleIgnoredSuffix = (() => {
448
- const q = new URLSearchParams(query);
449
- if (showIgnored) q.delete("ignored");
450
- else q.set("ignored", "1");
451
- return q.toString() ? `?${q.toString()}` : "";
452
- })();
453
-
454
- const p = req.params[0] ?? "";
455
- const { stripped, resolved } = await safeRealpath(repoRootReal, p);
456
- const toggleIgnoredHref = `/tree/${encodePathForUrl(
457
- toPosixPath(stripped),
458
- )}${toggleIgnoredSuffix}`;
459
- const st = await statSafe(resolved);
460
- if (st === null) {
461
- const err = new Error("Permission denied");
462
- err.statusCode = 403;
463
- throw err;
464
- }
465
- if (st.isFile)
466
- return res.redirect(
467
- `/blob/${encodePathForUrl(toPosixPath(stripped))}${querySuffix}`,
468
- );
469
-
470
- let entries;
471
- try {
472
- entries = await fs.readdir(resolved, { withFileTypes: true });
473
- } catch (e) {
474
- if (e.code === "EACCES" || e.code === "EPERM") {
475
- const err = new Error("Permission denied");
476
- err.statusCode = 403;
477
- throw err;
478
- }
479
- throw e;
480
- }
481
- const readmeEntry = entries.find(
482
- (e) =>
483
- e.isFile() &&
484
- /^readme(?:\.(?:md|markdown|mdown|mkd|mkdn))?$/i.test(e.name),
485
- );
486
- const rows = (
487
- await Promise.all(
488
- entries
489
- .filter((e) => {
490
- if (e.name === ".git") return false;
491
- if (showIgnored) return true;
492
- const relPosix = toPosixPath(path.posix.join(toPosixPath(stripped), e.name));
493
- return !ignoreMatcher.ignores(relPosix, { isDir: e.isDirectory() });
494
- })
495
- .map(async (e) => {
496
- const relPosix = toPosixPath(path.posix.join(toPosixPath(stripped), e.name));
497
- const full = path.join(resolved, e.name);
498
- const info = await statSafe(full, { followSymlinks: false });
499
- if (info === null) return null;
500
- const isDir = e.isDirectory();
501
- const href = isDir
502
- ? `/tree/${encodePathForUrl(relPosix)}${querySuffix}`
503
- : `/blob/${encodePathForUrl(relPosix)}${querySuffix}`;
504
- return {
505
- name: e.name,
506
- isDir,
507
- href,
508
- size: isDir ? "" : formatBytes(info.size),
509
- mtime: formatDate(info.mtimeMs),
510
- mtimeMs: info.mtimeMs,
511
- };
512
- }),
513
- )
514
- ).filter((row) => row !== null);
515
-
516
- rows.sort((a, b) => {
517
- if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
518
- return a.name.localeCompare(b.name);
519
- });
520
-
521
- let readmeHtml = "";
522
- if (readmeEntry) {
523
- try {
524
- const readmeRel = toPosixPath(path.posix.join(toPosixPath(stripped), readmeEntry.name));
525
- if (!showIgnored && ignoreMatcher.ignores(readmeRel, { isDir: false }))
526
- throw new Error("ignored");
527
- const { resolved: readmePath } = await safeRealpath(repoRootReal, readmeRel);
528
- const readmeStat = await statSafe(readmePath);
529
- if (readmeStat.size <= 2 * 1024 * 1024) {
530
- const buf = await fs.readFile(readmePath);
531
- readmeHtml = md.render(buf.toString("utf8"), {
532
- baseDirPosix: toPosixPath(stripped),
533
- });
534
- }
535
- } catch {
536
- readmeHtml = "";
537
- }
538
- }
539
-
540
- res.status(200).send(
541
- renderTreePage({
542
- title: `${repoName}${stripped ? `/${stripped}` : ""}`,
543
- repoName,
544
- gitInfo,
545
- brokenLinks: linkScanner.getState(),
546
- relPathPosix: toPosixPath(stripped),
547
- querySuffix,
548
- toggleIgnoredHref,
549
- showIgnored,
550
- rows,
551
- readmeHtml,
552
- }),
553
- );
554
- } catch (e) {
555
- res
556
- .status(e.statusCode || 500)
557
- .send(renderErrorPage({ title: "Error", message: e.message }));
558
- }
559
- });
560
-
561
- app.get(["/blob/*", "/blob"], async (req, res) => {
562
- try {
563
- const showIgnored = req.query.ignored === "1";
564
- const query = new URLSearchParams();
565
- if (req.query.watch === "0") query.set("watch", "0");
566
- if (showIgnored) query.set("ignored", "1");
567
- const querySuffix = query.toString() ? `?${query.toString()}` : "";
568
- const toggleIgnoredSuffix = (() => {
569
- const q = new URLSearchParams(query);
570
- if (showIgnored) q.delete("ignored");
571
- else q.set("ignored", "1");
572
- return q.toString() ? `?${q.toString()}` : "";
573
- })();
574
-
575
- const p = req.params[0] ?? "";
576
- const { stripped, resolved } = await safeRealpath(repoRootReal, p);
577
- const toggleIgnoredHref = `/blob/${encodePathForUrl(
578
- toPosixPath(stripped),
579
- )}${toggleIgnoredSuffix}`;
580
- const st = await statSafe(resolved);
581
- if (st === null) {
582
- const err = new Error("Permission denied");
583
- err.statusCode = 403;
584
- throw err;
585
- }
586
- if (st.isDir)
587
- return res.redirect(
588
- `/tree/${encodePathForUrl(toPosixPath(stripped))}${querySuffix}`,
589
- );
590
-
591
- const fileName = path.basename(resolved);
592
- const ext = path.extname(fileName).toLowerCase();
593
- const isMarkdown = [".md", ".markdown", ".mdown", ".mkd", ".mkdn"].includes(ext);
594
- const isPdf = ext === ".pdf";
595
- const isImage = [".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".ico", ".bmp"].includes(ext);
596
- const isCsv = [".csv", ".tsv"].includes(ext);
597
- const maxBytes = 2 * 1024 * 1024;
598
- const rawSrc = `/raw/${encodePathForUrl(toPosixPath(stripped))}`;
599
-
600
- if (isPdf) {
601
- res.status(200).send(
602
- renderFilePage({
603
- title: `${repoName}/${stripped}`,
604
- repoName,
605
- gitInfo,
606
- brokenLinks: linkScanner.getState(),
607
- relPathPosix: toPosixPath(stripped),
608
- querySuffix,
609
- toggleIgnoredHref,
610
- showIgnored,
611
- fileName,
612
- isMarkdown: false,
613
- mediaType: "pdf",
614
- renderedHtml: `<iframe class="pdf-frame" src="${rawSrc}"></iframe>`,
615
- }),
616
- );
617
- return;
618
- }
619
-
620
- if (isImage) {
621
- res.status(200).send(
622
- renderFilePage({
623
- title: `${repoName}/${stripped}`,
624
- repoName,
625
- gitInfo,
626
- brokenLinks: linkScanner.getState(),
627
- relPathPosix: toPosixPath(stripped),
628
- querySuffix,
629
- toggleIgnoredHref,
630
- showIgnored,
631
- fileName,
632
- isMarkdown: false,
633
- mediaType: "image",
634
- renderedHtml: `<img class="image-preview" src="${rawSrc}" alt="${escapeHtml(fileName)}" />`,
635
- }),
636
- );
637
- return;
638
- }
639
-
640
- if (st.size > maxBytes) {
641
- res.status(200).send(
642
- renderFilePage({
643
- title: `${repoName}/${stripped}`,
644
- repoName,
645
- gitInfo,
646
- brokenLinks: linkScanner.getState(),
647
- relPathPosix: toPosixPath(stripped),
648
- querySuffix,
649
- toggleIgnoredHref,
650
- showIgnored,
651
- fileName,
652
- isMarkdown: false,
653
- renderedHtml: `<div class="note">File is too large to render (${formatBytes(
654
- st.size,
655
- )}). Use <a href="/raw/${encodePathForUrl(
656
- toPosixPath(stripped),
657
- )}${querySuffix}">Raw</a>.</div>`,
658
- }),
659
- );
660
- return;
661
- }
662
-
663
- const raw = await fs.readFile(resolved);
664
- const text = raw.toString("utf8");
665
-
666
- let renderedHtml;
667
- let mediaType;
668
- if (isCsv) {
669
- const delimiter = ext === ".tsv" ? "\t" : ",";
670
- const rows = parseCsv(text, delimiter);
671
- renderedHtml = renderCsvTable(rows, escapeHtml);
672
- mediaType = "csv";
673
- } else if (isMarkdown) {
674
- const baseDir = toPosixPath(path.posix.dirname(toPosixPath(stripped)));
675
- renderedHtml = md.render(text, { baseDirPosix: baseDir === "." ? "" : baseDir });
676
- } else {
677
- renderedHtml = md.renderCodeBlock(text, {
678
- languageHint: ext ? ext.slice(1) : "",
679
- });
680
- }
681
-
682
- res.status(200).send(
683
- renderFilePage({
684
- title: `${repoName}/${stripped}`,
685
- repoName,
686
- gitInfo,
687
- brokenLinks: linkScanner.getState(),
688
- relPathPosix: toPosixPath(stripped),
689
- querySuffix,
690
- toggleIgnoredHref,
691
- showIgnored,
692
- fileName,
693
- isMarkdown,
694
- mediaType,
695
- renderedHtml,
696
- }),
697
- );
698
- } catch (e) {
699
- res
700
- .status(e.statusCode || 500)
701
- .send(renderErrorPage({ title: "Error", message: e.message }));
702
- }
703
- });
704
-
705
- // --- Review routes ---
706
- const reviewDir = path.join(repoRootReal, ".repoview", "reviews");
707
- const THREAD_ID_RE = /^[a-zA-Z0-9_-]+$/;
708
-
709
- function validateThreadId(id) {
710
- return id && typeof id === "string" && THREAD_ID_RE.test(id);
711
- }
712
-
713
- app.get("/review/", async (req, res) => {
714
- try {
715
- let entries = [];
716
- try {
717
- entries = await fs.readdir(reviewDir, { withFileTypes: true });
718
- } catch {
719
- // no review dir yet
720
- }
721
-
722
- const threads = [];
723
- for (const entry of entries) {
724
- if (!entry.isDirectory()) continue;
725
- const threadFile = path.join(reviewDir, entry.name, "thread.json");
726
- try {
727
- const thread = JSON.parse(await fs.readFile(threadFile, "utf8"));
728
- let messageCount = 0;
729
- let lastMessageId = null;
730
- try {
731
- const msgs = (await fs.readdir(path.join(reviewDir, entry.name, "messages")))
732
- .filter((f) => f.endsWith(".json"))
733
- .sort();
734
- messageCount = msgs.length;
735
- lastMessageId = msgs.length ? msgs[msgs.length - 1].replace(".json", "") : null;
736
- } catch {
737
- // no messages
738
- }
739
- const unreadCount = thread.readUntil && lastMessageId
740
- ? Math.max(0, parseInt(lastMessageId, 10) - parseInt(thread.readUntil, 10))
741
- : thread.readUntil ? 0 : messageCount;
742
- threads.push({ ...thread, messageCount, lastMessageId, unreadCount });
743
- } catch {
744
- // skip
745
- }
746
- }
747
-
748
- threads.sort((a, b) => new Date(b.lastActivityAt) - new Date(a.lastActivityAt));
749
-
750
- res.status(200).send(
751
- renderReviewListPage({
752
- title: `${repoName} · Reviews`,
753
- repoName,
754
- gitInfo,
755
- threads,
756
- }),
757
- );
758
- } catch (e) {
759
- res.status(500).send(renderErrorPage({ title: "Error", message: e.message }));
760
- }
761
- });
762
-
763
- app.get("/review/:threadId", async (req, res) => {
764
- try {
765
- const { threadId } = req.params;
766
- if (!validateThreadId(threadId)) {
767
- return res.status(400).send(renderErrorPage({ title: "Error", message: "Invalid thread ID" }));
768
- }
769
-
770
- const threadDir = path.join(reviewDir, threadId);
771
- const threadFile = path.join(threadDir, "thread.json");
772
-
773
- let thread;
774
- try {
775
- thread = JSON.parse(await fs.readFile(threadFile, "utf8"));
776
- } catch {
777
- return res.status(404).send(renderErrorPage({ title: "Error", message: "Thread not found" }));
778
- }
779
-
780
- const messagesDir = path.join(threadDir, "messages");
781
- let messageFiles = [];
782
- try {
783
- messageFiles = (await fs.readdir(messagesDir)).filter((f) => f.endsWith(".json")).sort();
784
- } catch {
785
- // no messages
786
- }
787
-
788
- const messages = [];
789
- for (const f of messageFiles) {
790
- messages.push(JSON.parse(await fs.readFile(path.join(messagesDir, f), "utf8")));
791
- }
792
-
793
- let comments = [];
794
- try {
795
- const commentsData = JSON.parse(await fs.readFile(path.join(threadDir, "comments.json"), "utf8"));
796
- comments = commentsData.comments || [];
797
- } catch {
798
- // no comments
799
- }
800
-
801
- // Render agent messages as markdown, user messages as plain text
802
- const renderedMessages = messages.map((msg) => {
803
- if (msg.role === "agent" && msg.format === "markdown") {
804
- return md.render(msg.body, { baseDirPosix: "", emitLineMap: true });
805
- }
806
- return msg.body;
807
- });
808
-
809
- // Mark as read
810
- if (messageFiles.length) {
811
- const lastMsgId = messageFiles[messageFiles.length - 1].replace(".json", "");
812
- thread.readUntil = lastMsgId;
813
- await fs.writeFile(threadFile, JSON.stringify(thread, null, 2) + "\n");
814
- }
815
-
816
- res.status(200).send(
817
- renderReviewThreadPage({
818
- title: `${repoName} · ${thread.title}`,
819
- repoName,
820
- gitInfo,
821
- thread,
822
- messages,
823
- comments,
824
- renderedMessages,
825
- }),
826
- );
827
- } catch (e) {
828
- res.status(500).send(renderErrorPage({ title: "Error", message: e.message }));
829
- }
830
- });
831
-
832
- app.post("/review/:threadId/messages", express.json(), async (req, res) => {
833
- try {
834
- const { threadId } = req.params;
835
- if (!validateThreadId(threadId)) {
836
- return res.status(400).json({ error: "Invalid thread ID" });
837
- }
838
-
839
- const threadDir = path.join(reviewDir, threadId);
840
- const threadFile = path.join(threadDir, "thread.json");
841
- const messagesDir = path.join(threadDir, "messages");
842
-
843
- let thread;
844
- try {
845
- thread = JSON.parse(await fs.readFile(threadFile, "utf8"));
846
- } catch {
847
- return res.status(404).json({ error: "Thread not found" });
848
- }
849
-
850
- const { body } = req.body;
851
- if (!body || !body.trim()) {
852
- return res.status(400).json({ error: "Message body is required" });
853
- }
854
-
855
- let entries = [];
856
- try {
857
- entries = (await fs.readdir(messagesDir)).filter((f) => f.endsWith(".json"));
858
- } catch {
859
- await fs.mkdir(messagesDir, { recursive: true });
860
- }
861
-
862
- const existingIds = entries.map((e) => e.replace(".json", ""));
863
- let max = 0;
864
- for (const id of existingIds) {
865
- const n = parseInt(id, 10);
866
- if (n > max) max = n;
867
- }
868
- const nextId = String(max + 1).padStart(3, "0");
869
- const now = new Date().toISOString();
870
-
871
- const message = {
872
- id: nextId,
873
- role: "user",
874
- format: "text",
875
- body: body.trim(),
876
- createdAt: now,
877
- };
878
-
879
- await fs.writeFile(path.join(messagesDir, `${nextId}.json`), JSON.stringify(message, null, 2) + "\n");
880
- thread.lastActivityAt = now;
881
- await fs.writeFile(threadFile, JSON.stringify(thread, null, 2) + "\n");
882
-
883
- res.status(201).json(message);
884
- } catch (e) {
885
- res.status(500).json({ error: e.message });
886
- }
887
- });
888
-
889
- app.post("/review/:threadId/comments", express.json(), async (req, res) => {
890
- try {
891
- const { threadId } = req.params;
892
- if (!validateThreadId(threadId)) {
893
- return res.status(400).json({ error: "Invalid thread ID" });
894
- }
895
-
896
- const threadDir = path.join(reviewDir, threadId);
897
- const commentsFile = path.join(threadDir, "comments.json");
898
-
899
- const { messageId, anchorLine, anchorEndLine, anchorText, body } = req.body;
900
- if (!body || !body.trim()) {
901
- return res.status(400).json({ error: "Comment body is required" });
902
- }
903
-
904
- let commentsData = { comments: [] };
905
- try {
906
- commentsData = JSON.parse(await fs.readFile(commentsFile, "utf8"));
907
- } catch {
908
- // fresh comments
909
- }
910
-
911
- const id = `c_${Date.now()}_${Math.random().toString(36).slice(2, 5)}`;
912
- const comment = {
913
- id,
914
- messageId: messageId || null,
915
- anchorLine: anchorLine || null,
916
- anchorEndLine: anchorEndLine || null,
917
- anchorText: anchorText || null,
918
- body: body.trim(),
919
- createdAt: new Date().toISOString(),
920
- resolved: false,
921
- };
922
-
923
- commentsData.comments.push(comment);
924
- await fs.writeFile(commentsFile, JSON.stringify(commentsData, null, 2) + "\n");
925
-
926
- res.status(201).json(comment);
927
- } catch (e) {
928
- res.status(500).json({ error: e.message });
929
- }
930
- });
931
-
932
- app.patch("/review/:threadId/comments/:commentId", express.json(), async (req, res) => {
933
- try {
934
- const { threadId, commentId } = req.params;
935
- if (!validateThreadId(threadId)) {
936
- return res.status(400).json({ error: "Invalid thread ID" });
937
- }
938
-
939
- const commentsFile = path.join(reviewDir, threadId, "comments.json");
940
-
941
- let commentsData;
942
- try {
943
- commentsData = JSON.parse(await fs.readFile(commentsFile, "utf8"));
944
- } catch {
945
- return res.status(404).json({ error: "Comments not found" });
946
- }
947
-
948
- const comment = commentsData.comments.find((c) => c.id === commentId);
949
- if (!comment) {
950
- return res.status(404).json({ error: "Comment not found" });
951
- }
952
-
953
- if (req.body.resolved !== undefined) comment.resolved = req.body.resolved;
954
- if (req.body.body !== undefined) comment.body = req.body.body;
955
-
956
- await fs.writeFile(commentsFile, JSON.stringify(commentsData, null, 2) + "\n");
957
- res.status(200).json(comment);
958
- } catch (e) {
959
- res.status(500).json({ error: e.message });
960
- }
961
- });
962
-
963
- app.delete("/review/:threadId/comments/:commentId", async (req, res) => {
964
- try {
965
- const { threadId, commentId } = req.params;
966
- if (!validateThreadId(threadId)) {
967
- return res.status(400).json({ error: "Invalid thread ID" });
968
- }
969
-
970
- const commentsFile = path.join(reviewDir, threadId, "comments.json");
971
-
972
- let commentsData;
973
- try {
974
- commentsData = JSON.parse(await fs.readFile(commentsFile, "utf8"));
975
- } catch {
976
- return res.status(404).json({ error: "Comments not found" });
977
- }
978
-
979
- const idx = commentsData.comments.findIndex((c) => c.id === commentId);
980
- if (idx === -1) {
981
- return res.status(404).json({ error: "Comment not found" });
982
- }
983
-
984
- commentsData.comments.splice(idx, 1);
985
- await fs.writeFile(commentsFile, JSON.stringify(commentsData, null, 2) + "\n");
986
- res.status(200).json({ ok: true });
987
- } catch (e) {
988
- res.status(500).json({ error: e.message });
989
- }
990
- });
991
-
992
- app.post("/review/:threadId/mark-read", express.json(), async (req, res) => {
993
- try {
994
- const { threadId } = req.params;
995
- if (!validateThreadId(threadId)) {
996
- return res.status(400).json({ error: "Invalid thread ID" });
997
- }
998
-
999
- const threadFile = path.join(reviewDir, threadId, "thread.json");
1000
- let thread;
1001
- try {
1002
- thread = JSON.parse(await fs.readFile(threadFile, "utf8"));
1003
- } catch {
1004
- return res.status(404).json({ error: "Thread not found" });
1005
- }
1006
-
1007
- const { readUntil } = req.body;
1008
- if (readUntil) thread.readUntil = readUntil;
1009
- await fs.writeFile(threadFile, JSON.stringify(thread, null, 2) + "\n");
1010
- res.status(200).json({ ok: true });
1011
- } catch (e) {
1012
- res.status(500).json({ error: e.message });
1013
- }
1014
- });
1015
-
1016
- // --- Code context API for inline code popups ---
1017
- app.get("/api/code-context", async (req, res) => {
1018
- try {
1019
- const filePath = req.query.file;
1020
- if (!filePath || typeof filePath !== "string") {
1021
- return res.status(400).json({ error: "file parameter required" });
1022
- }
1023
- const line = parseInt(req.query.line, 10) || 1;
1024
- const endLine = parseInt(req.query.endLine, 10) || line;
1025
- const context = Math.min(parseInt(req.query.context, 10) || 20, 200);
1026
-
1027
- const { resolved, stripped } = await safeRealpath(repoRootReal, filePath);
1028
- const st = await statSafe(resolved);
1029
- if (!st || !st.isFile) {
1030
- return res.status(404).json({ error: "File not found" });
1031
- }
1032
- if (st.size > 2 * 1024 * 1024) {
1033
- return res.status(400).json({ error: "File too large" });
1034
- }
1035
-
1036
- const raw = await fs.readFile(resolved, "utf8");
1037
- const allLines = raw.split("\n");
1038
-
1039
- const startLine = Math.max(1, Math.min(line, endLine) - context);
1040
- const stopLine = Math.min(allLines.length, Math.max(line, endLine) + context);
1041
- const snippet = allLines.slice(startLine - 1, stopLine);
1042
-
1043
- const ext = path.extname(stripped).slice(1);
1044
-
1045
- // Get diff for this file (against HEAD)
1046
- let diff = null;
1047
- const diffResult = await execGit(repoRootReal, ["diff", "HEAD", "--", stripped], 256 * 1024);
1048
- if (diffResult.output) {
1049
- diff = diffResult.output;
1050
- }
1051
-
1052
- res.json({
1053
- file: toPosixPath(stripped),
1054
- startLine,
1055
- stopLine,
1056
- highlightStart: Math.min(line, endLine),
1057
- highlightEnd: Math.max(line, endLine),
1058
- lines: snippet,
1059
- language: ext,
1060
- totalLines: allLines.length,
1061
- diff,
1062
- });
1063
- } catch (e) {
1064
- res.status(e.statusCode || 500).json({ error: e.message });
1065
- }
1066
- });
1067
-
1068
- app.get(["/raw/*", "/raw"], async (req, res) => {
1069
- try {
1070
- const p = req.params[0] ?? "";
1071
- const { resolved } = await safeRealpath(repoRootReal, p);
1072
- const st = await statSafe(resolved);
1073
- if (st === null) {
1074
- const err = new Error("Permission denied");
1075
- err.statusCode = 403;
1076
- throw err;
1077
- }
1078
- if (!st.isFile) {
1079
- const err = new Error("Not a file");
1080
- err.statusCode = 400;
1081
- throw err;
1082
- }
1083
-
1084
- const contentType = mime.contentType(path.extname(resolved)) || "application/octet-stream";
1085
- res.setHeader("Content-Type", contentType);
1086
- res.sendFile(resolved);
1087
- } catch (e) {
1088
- res
1089
- .status(e.statusCode || 500)
1090
- .send(renderErrorPage({ title: "Error", message: e.message }));
1091
- }
1092
- });
1093
-
1094
- const server = http.createServer(app);
1095
- await new Promise((resolve) => server.listen(port, host, resolve));
1096
-
1097
- if (watch) {
1098
- const watcher = chokidar.watch(repoRootReal, {
1099
- ignored: [
1100
- /(^|[/\\])\.git([/\\]|$)/,
1101
- /(^|[/\\])node_modules([/\\]|$)/,
1102
- /(^|[/\\])\.repoview([/\\]|$)/,
1103
- ],
1104
- ignoreInitial: true,
1105
- ignorePermissionErrors: true,
1106
- });
1107
- watcher.on("error", () => {
1108
- // Silently ignore watch errors (e.g., permission denied)
1109
- });
1110
- let pending = null;
1111
- watcher.on("all", () => {
1112
- if (pending) return;
1113
- pending = setTimeout(() => {
1114
- pending = null;
1115
- reloadHub.broadcastReload();
1116
- void loadGitIgnoreMatcher(repoRootReal).then((m) => (ignoreMatcher = m));
1117
- void linkScanner.triggerScan();
1118
- }, 100);
1119
- });
1120
- }
1121
-
1122
- // eslint-disable-next-line no-console
1123
- console.log(`repoview: ${repoRootReal}`);
1124
- // eslint-disable-next-line no-console
1125
- console.log(`listening: http://${host}:${port}`);
1126
- }