readingroom 0.2.0 → 0.3.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.
package/dist/index.html CHANGED
@@ -22,8 +22,8 @@
22
22
  } catch (e) {}
23
23
  })();
24
24
  </script>
25
- <script type="module" crossorigin src="/assets/index-87varIK4.js"></script>
26
- <link rel="stylesheet" crossorigin href="/assets/index-jgmgco4r.css">
25
+ <script type="module" crossorigin src="/assets/index-BWX1yNrT.js"></script>
26
+ <link rel="stylesheet" crossorigin href="/assets/index-BFXOIu5r.css">
27
27
  </head>
28
28
  <body>
29
29
  <div id="root"></div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "readingroom",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Zero-config doc browser for your codebase.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/git.js ADDED
@@ -0,0 +1,216 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { realpathSync } from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ /**
6
+ * Git integration for the inspector (file info + history).
7
+ *
8
+ * Everything shells out to the `git` CLI via execFile — argv only, never a
9
+ * shell — so paths and refs are never interpreted as options or commands.
10
+ * Callers degrade gracefully when git is missing or the served folder is not
11
+ * a repository: repo detection returns null and endpoints report git:false.
12
+ */
13
+
14
+ const GIT_TIMEOUT_MS = 5000;
15
+ const MAX_BUFFER = 10 * 1024 * 1024; // biggest blob we will hand out
16
+ const HISTORY_LIMIT = 500;
17
+ const FIELD = '\x1f';
18
+ const RECORD = '\x1e';
19
+ const PRETTY = `%H${FIELD}%h${FIELD}%an${FIELD}%ae${FIELD}%aI${FIELD}%s${RECORD}`;
20
+
21
+ export class VersionNotFound extends Error {
22
+ constructor() {
23
+ super('version not found');
24
+ }
25
+ }
26
+
27
+ function runGit(cwd, args, opts = {}) {
28
+ return new Promise((resolve, reject) => {
29
+ execFile(
30
+ 'git',
31
+ args,
32
+ { cwd, timeout: GIT_TIMEOUT_MS, maxBuffer: MAX_BUFFER, windowsHide: true, ...opts },
33
+ (err, stdout, stderr) => {
34
+ if (err) {
35
+ err.gitStderr = String(stderr ?? '');
36
+ reject(err);
37
+ } else {
38
+ resolve(stdout);
39
+ }
40
+ },
41
+ );
42
+ });
43
+ }
44
+
45
+ // Positive detections are cached for the life of the process; misses re-probe
46
+ // (one cheap exec) so `git init` mid-session starts working without a restart.
47
+ const repoCache = new Map();
48
+
49
+ /** Detect the repository containing rootAbs: { repoRoot, subDir } | null. */
50
+ export async function findRepo(rootAbs) {
51
+ if (repoCache.has(rootAbs)) return repoCache.get(rootAbs);
52
+ let repo = null;
53
+ try {
54
+ // --show-toplevel reports the real path, so compare against the real
55
+ // served root or symlinked roots (macOS /var -> /private/var) never match.
56
+ const realRoot = realpathSync(rootAbs);
57
+ const top = path.resolve(String(await runGit(realRoot, ['rev-parse', '--show-toplevel'])).trim());
58
+ if (top === realRoot || realRoot.startsWith(top + path.sep)) {
59
+ repo = { repoRoot: top, subDir: path.relative(top, realRoot).split(path.sep).join('/') };
60
+ }
61
+ } catch {
62
+ /* git missing, not a repository, or blocked (e.g. dubious ownership) */
63
+ }
64
+ if (repo) repoCache.set(rootAbs, repo);
65
+ return repo;
66
+ }
67
+
68
+ /** The served root may sit below the repo root; git wants repo-relative paths. */
69
+ function repoRelative(repo, rel) {
70
+ const p = String(rel).replace(/\\/g, '/');
71
+ return repo.subDir ? `${repo.subDir}/${p}` : p;
72
+ }
73
+
74
+ /** `git log --name-status` quotes exotic paths C-style; undo the common cases. */
75
+ function unquotePath(p) {
76
+ if (p.length >= 2 && p.startsWith('"') && p.endsWith('"')) {
77
+ try {
78
+ return JSON.parse(p);
79
+ } catch {
80
+ return p.slice(1, -1);
81
+ }
82
+ }
83
+ return p;
84
+ }
85
+
86
+ function parseCommits(out) {
87
+ const commits = [];
88
+ let current = null;
89
+ for (const line of String(out).split(/\r?\n/)) {
90
+ if (line.includes(RECORD)) {
91
+ const fields = line.slice(0, line.indexOf(RECORD)).split(FIELD);
92
+ current = {
93
+ sha: fields[0] || '',
94
+ abbrev: fields[1] || '',
95
+ author: fields[2] || '',
96
+ email: fields[3] || '',
97
+ date: fields[4] || '',
98
+ subject: fields.slice(5).join(FIELD),
99
+ status: null,
100
+ moves: [],
101
+ };
102
+ if (current.sha) commits.push(current);
103
+ } else if (current && line.includes('\t')) {
104
+ const cols = line.split('\t');
105
+ current.status = current.status || cols[0].replace(/\d+$/, ''); // R100 -> R
106
+ current.moves.push(cols.slice(1).map(unquotePath));
107
+ }
108
+ }
109
+ return commits;
110
+ }
111
+
112
+ /**
113
+ * `--follow` reports every commit against the file's current name. Annotate
114
+ * each commit with the path the file had at that point (newest -> oldest walk
115
+ * flips the path at each rename) so snapshots resolve across renames.
116
+ */
117
+ function withPathAtCommit(commits, startPath) {
118
+ let pathNow = startPath;
119
+ return commits.map((commit) => {
120
+ const entry = {
121
+ sha: commit.sha,
122
+ abbrev: commit.abbrev,
123
+ author: commit.author,
124
+ email: commit.email,
125
+ date: commit.date,
126
+ subject: commit.subject,
127
+ status: commit.status || 'M',
128
+ path: pathNow,
129
+ };
130
+ const move = commit.moves.find((m) => m.length === 2 && m[1] === pathNow);
131
+ if (move) pathNow = move[0];
132
+ return entry;
133
+ });
134
+ }
135
+
136
+ function isUnborn(err) {
137
+ return /does not have any commits yet/i.test(err.gitStderr || '');
138
+ }
139
+
140
+ /** { git, branch } for the repo containing rootAbs (branch null if unknown). */
141
+ export async function repoStatus(rootAbs) {
142
+ const repo = await findRepo(rootAbs);
143
+ if (!repo) return { git: false, branch: null };
144
+ try {
145
+ const branch = String(await runGit(repo.repoRoot, ['rev-parse', '--abbrev-ref', 'HEAD'])).trim();
146
+ return { git: true, branch: branch && branch !== 'HEAD' ? branch : null };
147
+ } catch {
148
+ return { git: true, branch: null }; // unborn branch or detached HEAD
149
+ }
150
+ }
151
+
152
+ /** Latest commit that touched rel (served-root relative), or null. */
153
+ export async function lastCommitFor(rootAbs, rel) {
154
+ const repo = await findRepo(rootAbs);
155
+ if (!repo) return null;
156
+ try {
157
+ const out = await runGit(repo.repoRoot, ['log', '-n', '1', `--format=${PRETTY}`, '--', repoRelative(repo, rel)]);
158
+ const commit = parseCommits(out)[0];
159
+ return commit ? { sha: commit.sha, abbrev: commit.abbrev, author: commit.author, email: commit.email, date: commit.date, subject: commit.subject } : null;
160
+ } catch {
161
+ return null; // untracked, unborn repo, or a git hiccup — info degrades quietly
162
+ }
163
+ }
164
+
165
+ /** Commit timeline for rel: { repo, commits, truncated } | null when not a repo. */
166
+ export async function fileHistory(rootAbs, rel) {
167
+ const repo = await findRepo(rootAbs);
168
+ if (!repo) return null;
169
+ let out;
170
+ try {
171
+ out = await runGit(repo.repoRoot, [
172
+ 'log', '--follow', '--name-status', `--format=${PRETTY}`,
173
+ '-n', String(HISTORY_LIMIT), '--', repoRelative(repo, rel),
174
+ ]);
175
+ } catch (err) {
176
+ if (isUnborn(err)) return { repo, commits: [], truncated: false };
177
+ throw err;
178
+ }
179
+ const commits = withPathAtCommit(parseCommits(out), repoRelative(repo, rel));
180
+ return { repo, commits, truncated: commits.length >= HISTORY_LIMIT };
181
+ }
182
+
183
+ /**
184
+ * Blob for rel at ref (a commit sha). Rename-aware via the history walk;
185
+ * commits that deleted the file resolve to the parent (last live version).
186
+ * Returns { repo, buffer, entry } | null (not a repo); throws VersionNotFound.
187
+ */
188
+ export async function fileVersion(rootAbs, rel, ref) {
189
+ const repo = await findRepo(rootAbs);
190
+ if (!repo) return null;
191
+ const repoRel = repoRelative(repo, rel);
192
+
193
+ let entry = null;
194
+ try {
195
+ const history = await fileHistory(rootAbs, rel);
196
+ entry = history?.commits.find((c) => c.sha === ref || c.sha.startsWith(ref)) || null;
197
+ } catch {
198
+ /* fall through to the direct lookup below */
199
+ }
200
+
201
+ const attempts = [];
202
+ if (entry) {
203
+ attempts.push([entry.status === 'D' ? `${entry.sha}^` : entry.sha, entry.path]);
204
+ }
205
+ attempts.push([ref, repoRel]); // refs outside the walked history, or walk failures
206
+
207
+ for (const [showRef, showPath] of attempts) {
208
+ try {
209
+ const out = await runGit(repo.repoRoot, ['show', `${showRef}:${showPath}`], { encoding: 'buffer' });
210
+ return { repo, buffer: out == null ? Buffer.alloc(0) : Buffer.from(out), entry };
211
+ } catch {
212
+ /* try the next candidate */
213
+ }
214
+ }
215
+ throw new VersionNotFound();
216
+ }
package/src/server.js CHANGED
@@ -3,6 +3,7 @@ import { createReadStream, existsSync, readFileSync, statSync, watch } from 'nod
3
3
  import path from 'node:path';
4
4
  import { scanTree, fileKind, DEFAULT_IGNORED_DIRS } from './scanner.js';
5
5
  import { openExternal } from './openBrowser.js';
6
+ import { repoStatus, lastCommitFor, fileHistory, fileVersion, VersionNotFound } from './git.js';
6
7
 
7
8
  const MIME = {
8
9
  '.md': 'text/markdown; charset=utf-8',
@@ -220,6 +221,140 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
220
221
  return;
221
222
  }
222
223
 
224
+ if (pathname === '/api/repo') {
225
+ sendJson(res, 200, await repoStatus(rootAbs));
226
+ return;
227
+ }
228
+
229
+ if (pathname === '/api/meta') {
230
+ const rel = url.searchParams.get('p');
231
+ const abs = safeResolve(rel);
232
+ if (!abs) {
233
+ sendJson(res, 403, { error: 'path outside root' });
234
+ return;
235
+ }
236
+ let st;
237
+ try {
238
+ st = statSync(abs);
239
+ } catch {
240
+ sendJson(res, 404, { error: 'not found' });
241
+ return;
242
+ }
243
+ if (!st.isFile()) {
244
+ sendJson(res, 400, { error: 'not a file' });
245
+ return;
246
+ }
247
+ const cleanRel = rel.replace(/\\/g, '/');
248
+ const name = path.basename(abs);
249
+ const kind = fileKind(name);
250
+ let words = null;
251
+ let chars = null;
252
+ if (kind === 'md' || kind === 'txt') {
253
+ try {
254
+ const content = readFileSync(abs, 'utf8');
255
+ words = (content.match(/\S+/g) || []).length;
256
+ chars = content.length;
257
+ } catch {
258
+ /* unreadable right now — reading stats stay null */
259
+ }
260
+ }
261
+ const lastCommit = await lastCommitFor(rootAbs, cleanRel);
262
+ sendJson(res, 200, {
263
+ path: cleanRel,
264
+ name,
265
+ ext: path.extname(abs).toLowerCase(),
266
+ kind,
267
+ size: st.size,
268
+ mtime: st.mtimeMs,
269
+ words,
270
+ chars,
271
+ lastCommit,
272
+ });
273
+ return;
274
+ }
275
+
276
+ if (pathname === '/api/history') {
277
+ const rel = url.searchParams.get('p');
278
+ const abs = safeResolve(rel);
279
+ if (!abs) {
280
+ sendJson(res, 403, { error: 'path outside root' });
281
+ return;
282
+ }
283
+ let history;
284
+ try {
285
+ history = await fileHistory(rootAbs, rel.replace(/\\/g, '/'));
286
+ } catch {
287
+ sendJson(res, 500, { error: 'git failed' });
288
+ return;
289
+ }
290
+ if (!history) {
291
+ sendJson(res, 200, { git: false, commits: [], truncated: false });
292
+ return;
293
+ }
294
+ sendJson(res, 200, { git: true, commits: history.commits, truncated: history.truncated });
295
+ return;
296
+ }
297
+
298
+ if (pathname === '/api/version') {
299
+ const rel = url.searchParams.get('p');
300
+ const abs = safeResolve(rel);
301
+ if (!abs) {
302
+ sendJson(res, 403, { error: 'path outside root' });
303
+ return;
304
+ }
305
+ const ref = url.searchParams.get('ref');
306
+ if (!ref || !/^[0-9a-f]{7,40}$/i.test(ref)) {
307
+ sendJson(res, 400, { error: 'bad ref' });
308
+ return;
309
+ }
310
+ let version;
311
+ try {
312
+ version = await fileVersion(rootAbs, rel.replace(/\\/g, '/'), ref);
313
+ } catch (err) {
314
+ if (err instanceof VersionNotFound) {
315
+ sendJson(res, 404, { error: 'version not found' });
316
+ } else {
317
+ sendJson(res, 500, { error: 'git failed' });
318
+ }
319
+ return;
320
+ }
321
+ if (!version) {
322
+ sendJson(res, 404, { error: 'not a git repository' });
323
+ return;
324
+ }
325
+ const name = path.basename(abs);
326
+ const kind = fileKind(name);
327
+ if (url.searchParams.get('raw') === '1') {
328
+ const type = mimeType(abs);
329
+ res.writeHead(200, {
330
+ 'Content-Type': type,
331
+ 'Content-Length': version.buffer.length,
332
+ 'Cache-Control': 'no-store',
333
+ 'X-Content-Type-Options': 'nosniff',
334
+ ...(type === 'application/pdf' ? {} : { 'Content-Security-Policy': 'sandbox' }),
335
+ });
336
+ res.end(version.buffer);
337
+ return;
338
+ }
339
+ const isText = kind === 'md' || kind === 'txt';
340
+ const entry = version.entry;
341
+ sendJson(res, 200, {
342
+ path: rel.replace(/\\/g, '/'),
343
+ name,
344
+ ext: path.extname(abs).toLowerCase(),
345
+ kind,
346
+ size: version.buffer.length,
347
+ binary: !isText,
348
+ content: isText ? version.buffer.toString('utf8') : null,
349
+ ref: entry ? entry.sha : ref,
350
+ author: entry ? entry.author : null,
351
+ date: entry ? entry.date : null,
352
+ subject: entry ? entry.subject : null,
353
+ deleted: entry ? entry.status === 'D' : false,
354
+ });
355
+ return;
356
+ }
357
+
223
358
  if (pathname === '/api/raw') {
224
359
  const abs = safeResolve(url.searchParams.get('p'));
225
360
  if (!abs) {