readingroom 0.4.0 → 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.
package/src/scanner.js CHANGED
@@ -1,12 +1,21 @@
1
- import { readdirSync, readFileSync, statSync } from 'node:fs';
1
+ import { closeSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
 
4
- export const TEXT_EXTENSIONS = ['.md', '.txt'];
5
- export const IMAGE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp', '.gif', '.avif', '.svg'];
4
+ export const MARKDOWN_EXTENSIONS = ['.md', '.markdown'];
5
+ export const TEXT_EXTENSIONS = ['.txt', '.text', '.log'];
6
+ export const JSON_EXTENSIONS = ['.json', '.jsonc'];
7
+ export const CODE_EXTENSIONS = [
8
+ '.c', '.cc', '.cpp', '.cs', '.css', '.go', '.h', '.hpp', '.html', '.htm',
9
+ '.java', '.js', '.jsx', '.mjs', '.cjs', '.kt', '.kts', '.lua', '.php',
10
+ '.py', '.rb', '.rs', '.sh', '.sql', '.swift', '.ts', '.tsx', '.vue',
11
+ '.xml', '.xhtml', '.yaml', '.yml', '.toml', '.ini', '.conf', '.env',
12
+ ];
13
+ export const IMAGE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp', '.gif', '.avif', '.svg', '.ico'];
6
14
  export const PDF_EXTENSIONS = ['.pdf'];
7
15
 
8
16
  const KIND_BY_EXT = new Map([
9
- ...TEXT_EXTENSIONS.map((ext) => [ext, ext === '.txt' ? 'txt' : 'md']),
17
+ ...MARKDOWN_EXTENSIONS.map((ext) => [ext, 'md']),
18
+ ...TEXT_EXTENSIONS.map((ext) => [ext, 'txt']),
10
19
  ...IMAGE_EXTENSIONS.map((ext) => [ext, 'img']),
11
20
  ...PDF_EXTENSIONS.map((ext) => [ext, 'pdf']),
12
21
  ]);
@@ -38,10 +47,67 @@ export const DEFAULT_IGNORED_DIRS = new Set([
38
47
 
39
48
  const MAX_DEPTH = 40;
40
49
 
50
+ const CATEGORY_BY_EXT = new Map([
51
+ ...MARKDOWN_EXTENSIONS.map((ext) => [ext, 'markdown']),
52
+ ...TEXT_EXTENSIONS.map((ext) => [ext, 'text']),
53
+ ...JSON_EXTENSIONS.map((ext) => [ext, 'json']),
54
+ ...CODE_EXTENSIONS.map((ext) => [ext, 'code']),
55
+ ...IMAGE_EXTENSIONS.map((ext) => [ext, 'images']),
56
+ ...PDF_EXTENSIONS.map((ext) => [ext, 'pdfs']),
57
+ ]);
58
+
59
+ const CATEGORY_BY_NAME = new Map([
60
+ ['dockerfile', 'code'],
61
+ ['makefile', 'code'],
62
+ ['justfile', 'code'],
63
+ ]);
64
+
65
+ function isLikelyText(buffer) {
66
+ if (!buffer || buffer.length === 0) return true;
67
+ if (buffer.includes(0)) return false;
68
+ try {
69
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(buffer);
70
+ let printable = 0;
71
+ for (const char of text) {
72
+ const code = char.codePointAt(0);
73
+ if (code === 9 || code === 10 || code === 13 || (code >= 32 && code !== 127)) printable++;
74
+ }
75
+ return printable / Math.max(text.length, 1) >= 0.85;
76
+ } catch {
77
+ return false;
78
+ }
79
+ }
80
+
81
+ function readSample(abs) {
82
+ let fd;
83
+ try {
84
+ fd = openSync(abs, 'r');
85
+ const buffer = Buffer.allocUnsafe(4096);
86
+ const bytes = readSync(fd, buffer, 0, buffer.length, 0);
87
+ return buffer.subarray(0, bytes);
88
+ } catch {
89
+ return null;
90
+ } finally {
91
+ if (fd !== undefined) closeSync(fd);
92
+ }
93
+ }
94
+
41
95
  export function fileKind(name) {
42
96
  return KIND_BY_EXT.get(path.extname(name).toLowerCase()) ?? null;
43
97
  }
44
98
 
99
+ export function fileCategory(name, sample = null) {
100
+ const ext = path.extname(name).toLowerCase();
101
+ return CATEGORY_BY_EXT.get(ext) || CATEGORY_BY_NAME.get(name.toLowerCase()) || (isLikelyText(sample) ? 'text' : 'other');
102
+ }
103
+
104
+ export function filePreview(name, category = fileCategory(name)) {
105
+ if (category === 'markdown' || category === 'text' || category === 'json' || category === 'code') return 'text';
106
+ if (category === 'images') return 'image';
107
+ if (category === 'pdfs') return 'pdf';
108
+ return 'download';
109
+ }
110
+
45
111
  function escapeRe(ch) {
46
112
  return ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');
47
113
  }
@@ -125,11 +191,11 @@ function countFiles(nodes) {
125
191
  }
126
192
 
127
193
  /**
128
- * Scan a directory tree and return only the documentation files:
129
- * { type, name, path, count?, size?, mtime?, children? }
130
- * `path` is a repo-relative POSIX path ('' for the root).
194
+ * Scan a directory tree. By default this returns only the documentation files
195
+ * readingroom can preview; includeAll also keeps every non-ignored file for
196
+ * inventory-style views such as the home dashboard.
131
197
  */
132
- export function scanTree(rootDir) {
198
+ function scan(rootDir, includeAll) {
133
199
  const rootAbs = path.resolve(rootDir);
134
200
  const rootName = path.basename(rootAbs) || rootAbs;
135
201
  const stack = [];
@@ -168,16 +234,28 @@ export function scanTree(rootDir) {
168
234
  dirNodes.push({ type: 'dir', name: entry.name, path: rel, count: countFiles(children), children });
169
235
  }
170
236
  } else if (entry.isFile()) {
237
+ const abs = path.join(dirAbs, entry.name);
171
238
  const kind = fileKind(entry.name);
172
- if (!kind) continue;
239
+ if (!includeAll && !kind) continue;
173
240
  if (isIgnored(rel, false, stack)) continue;
174
241
  let st;
175
242
  try {
176
- st = statSync(path.join(dirAbs, entry.name));
243
+ st = statSync(abs);
177
244
  } catch {
178
245
  continue;
179
246
  }
180
- fileNodes.push({ type: 'file', name: entry.name, path: rel, kind, size: st.size, mtime: st.mtimeMs });
247
+ const sample = includeAll && !kind ? readSample(abs) : null;
248
+ const category = fileCategory(entry.name, sample);
249
+ fileNodes.push({
250
+ type: 'file',
251
+ name: entry.name,
252
+ path: rel,
253
+ kind: kind || 'other',
254
+ category,
255
+ preview: filePreview(entry.name, category),
256
+ size: st.size,
257
+ mtime: st.mtimeMs,
258
+ });
181
259
  }
182
260
  }
183
261
 
@@ -193,3 +271,11 @@ export function scanTree(rootDir) {
193
271
  const children = walk(rootAbs, '', 0);
194
272
  return { type: 'dir', name: rootName, path: '', count: countFiles(children), children };
195
273
  }
274
+
275
+ export function scanTree(rootDir) {
276
+ return scan(rootDir, false);
277
+ }
278
+
279
+ export function scanAllTree(rootDir) {
280
+ return scan(rootDir, true);
281
+ }
package/src/server.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import http from 'node:http';
2
2
  import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
3
- import { createReadStream, existsSync, readFileSync, statSync, watch } from 'node:fs';
3
+ import { closeSync, createReadStream, existsSync, openSync, readFileSync, readSync, statSync, watch } from 'node:fs';
4
4
  import { networkInterfaces } from 'node:os';
5
5
  import path from 'node:path';
6
- import { scanTree, fileKind, DEFAULT_IGNORED_DIRS } from './scanner.js';
6
+ import { scanAllTree, fileCategory, fileKind, filePreview, DEFAULT_IGNORED_DIRS } from './scanner.js';
7
7
  import { openExternal } from './openBrowser.js';
8
8
  import { repoStatus, lastCommitFor, fileHistory, fileVersion, VersionNotFound } from './git.js';
9
+ import { buildDashboard } from './dashboard.js';
9
10
  import { startQuickTunnel } from './tunnel.js';
10
11
 
11
12
  const MIME = {
@@ -91,6 +92,34 @@ const NOT_BUILT_PAGE = `<!doctype html>
91
92
  </body></html>`;
92
93
 
93
94
  const PAIR_COOKIE = 'rr_pair';
95
+ const MAX_TEXT_PREVIEW_BYTES = 2 * 1024 * 1024;
96
+ const MAX_CODE_PREVIEW_BYTES = 512 * 1024;
97
+
98
+ function readTextPreview(abs, maxBytes = MAX_TEXT_PREVIEW_BYTES) {
99
+ let fd;
100
+ try {
101
+ fd = openSync(abs, 'r');
102
+ const buffer = Buffer.allocUnsafe(maxBytes);
103
+ const bytes = readSync(fd, buffer, 0, maxBytes, 0);
104
+ return { content: buffer.subarray(0, bytes).toString('utf8'), truncated: bytes < statSync(abs).size };
105
+ } finally {
106
+ if (fd !== undefined) closeSync(fd);
107
+ }
108
+ }
109
+
110
+ function readFileSample(abs, maxBytes = 4096) {
111
+ let fd;
112
+ try {
113
+ fd = openSync(abs, 'r');
114
+ const buffer = Buffer.allocUnsafe(maxBytes);
115
+ const bytes = readSync(fd, buffer, 0, maxBytes, 0);
116
+ return buffer.subarray(0, bytes);
117
+ } catch {
118
+ return null;
119
+ } finally {
120
+ if (fd !== undefined) closeSync(fd);
121
+ }
122
+ }
94
123
 
95
124
  // Served to unauthenticated visitors on the mobile listener. Deliberately
96
125
  // does not echo the token — only the paired desktop and QR URL know it.
@@ -177,8 +206,11 @@ export async function startServer({
177
206
  }
178
207
  return false;
179
208
  };
180
- let cachedTree = scanTree(rootAbs);
209
+ let cachedTree = scanAllTree(rootAbs);
210
+ let cachedInventory = cachedTree;
181
211
  let lastTreeJson = JSON.stringify(cachedTree);
212
+ let lastInventoryJson = JSON.stringify(cachedInventory);
213
+ let dashboardCache = { inventoryJson: null, promise: null };
182
214
  const sseClients = new Set();
183
215
 
184
216
  // Only serve files that resolve inside the scanned root.
@@ -194,16 +226,40 @@ export async function startServer({
194
226
  for (const res of sseClients) res.write(payload);
195
227
  }
196
228
 
229
+ function dashboardData() {
230
+ if (dashboardCache.inventoryJson === lastInventoryJson && dashboardCache.promise) {
231
+ return dashboardCache.promise;
232
+ }
233
+ dashboardCache = {
234
+ inventoryJson: lastInventoryJson,
235
+ promise: buildDashboard(cachedInventory, rootAbs),
236
+ };
237
+ return dashboardCache.promise;
238
+ }
239
+
197
240
  let rescanTimer = null;
198
241
  function scheduleRescan() {
199
242
  clearTimeout(rescanTimer);
200
243
  rescanTimer = setTimeout(() => {
201
244
  try {
202
- const next = scanTree(rootAbs);
203
- const json = JSON.stringify(next);
204
- if (json !== lastTreeJson) {
205
- cachedTree = next;
206
- lastTreeJson = json;
245
+ const next = scanAllTree(rootAbs);
246
+ const nextInventory = next;
247
+ const treeJson = JSON.stringify(next);
248
+ const inventoryJson = JSON.stringify(nextInventory);
249
+ const treeChanged = treeJson !== lastTreeJson;
250
+ const inventoryChanged = inventoryJson !== lastInventoryJson;
251
+ if (treeChanged || inventoryChanged) {
252
+ if (treeChanged) {
253
+ cachedTree = next;
254
+ lastTreeJson = treeJson;
255
+ }
256
+ if (inventoryChanged) {
257
+ cachedInventory = nextInventory;
258
+ lastInventoryJson = inventoryJson;
259
+ }
260
+ dashboardCache = { inventoryJson: null, promise: null };
261
+ // An inventory-only change still needs to wake the dashboard, while
262
+ // keeping the sidebar tree payload stable for its subscribers.
207
263
  broadcastTree();
208
264
  }
209
265
  } catch {
@@ -273,6 +329,11 @@ export async function startServer({
273
329
  return;
274
330
  }
275
331
 
332
+ if (pathname === '/api/dashboard') {
333
+ sendJson(res, 200, await dashboardData());
334
+ return;
335
+ }
336
+
276
337
  if (pathname === '/api/file') {
277
338
  const rel = url.searchParams.get('p');
278
339
  const abs = safeResolve(rel);
@@ -280,11 +341,6 @@ export async function startServer({
280
341
  sendJson(res, 403, { error: 'path outside root' });
281
342
  return;
282
343
  }
283
- const kind = fileKind(path.basename(abs));
284
- if (kind !== 'md' && kind !== 'txt') {
285
- sendJson(res, 400, { error: 'only .md and .txt files can be opened as text' });
286
- return;
287
- }
288
344
  let st;
289
345
  try {
290
346
  st = statSync(abs);
@@ -296,14 +352,40 @@ export async function startServer({
296
352
  sendJson(res, 400, { error: 'not a file' });
297
353
  return;
298
354
  }
299
- const content = readFileSync(abs, 'utf8');
355
+ const name = path.basename(abs);
356
+ const kind = fileKind(name);
357
+ const category = fileCategory(name, readFileSample(abs));
358
+ const preview = filePreview(name, category);
359
+ if (preview !== 'text') {
360
+ sendJson(res, 200, {
361
+ path: rel.replace(/\\/g, '/'),
362
+ name,
363
+ ext: path.extname(abs).toLowerCase(),
364
+ size: st.size,
365
+ mtime: st.mtimeMs,
366
+ kind: kind || 'other',
367
+ category,
368
+ preview,
369
+ previewable: false,
370
+ content: null,
371
+ });
372
+ return;
373
+ }
374
+ const previewLimit = category === 'code' || category === 'json' ? MAX_CODE_PREVIEW_BYTES : MAX_TEXT_PREVIEW_BYTES;
375
+ const { content, truncated } = readTextPreview(abs, previewLimit);
300
376
  sendJson(res, 200, {
301
377
  path: rel.replace(/\\/g, '/'),
302
- name: path.basename(abs),
378
+ name,
303
379
  ext: path.extname(abs).toLowerCase(),
304
380
  size: st.size,
305
381
  mtime: st.mtimeMs,
306
- kind,
382
+ kind: kind || 'other',
383
+ category,
384
+ preview,
385
+ previewable: true,
386
+ truncated,
387
+ previewBytes: Buffer.byteLength(content),
388
+ previewLimit,
307
389
  content,
308
390
  });
309
391
  return;
@@ -335,11 +417,12 @@ export async function startServer({
335
417
  const cleanRel = rel.replace(/\\/g, '/');
336
418
  const name = path.basename(abs);
337
419
  const kind = fileKind(name);
420
+ const category = fileCategory(name, readFileSample(abs));
338
421
  let words = null;
339
422
  let chars = null;
340
- if (kind === 'md' || kind === 'txt') {
423
+ if (filePreview(name, category) === 'text' && st.size <= MAX_TEXT_PREVIEW_BYTES) {
341
424
  try {
342
- const content = readFileSync(abs, 'utf8');
425
+ const content = readTextPreview(abs).content;
343
426
  words = (content.match(/\S+/g) || []).length;
344
427
  chars = content.length;
345
428
  } catch {
@@ -352,6 +435,9 @@ export async function startServer({
352
435
  name,
353
436
  ext: path.extname(abs).toLowerCase(),
354
437
  kind,
438
+ category,
439
+ preview: filePreview(name, category),
440
+ previewable: filePreview(name, category) === 'text' && st.size <= MAX_TEXT_PREVIEW_BYTES,
355
441
  size: st.size,
356
442
  mtime: st.mtimeMs,
357
443
  words,
@@ -412,6 +498,8 @@ export async function startServer({
412
498
  }
413
499
  const name = path.basename(abs);
414
500
  const kind = fileKind(name);
501
+ const category = fileCategory(name, version.buffer.subarray(0, 4096));
502
+ const preview = filePreview(name, category);
415
503
  if (url.searchParams.get('raw') === '1') {
416
504
  const type = mimeType(abs);
417
505
  res.writeHead(200, {
@@ -430,16 +518,21 @@ export async function startServer({
430
518
  res.end(version.buffer);
431
519
  return;
432
520
  }
433
- const isText = kind === 'md' || kind === 'txt';
521
+ const isText = preview === 'text';
434
522
  const entry = version.entry;
523
+ const contentLimit = category === 'code' || category === 'json' ? MAX_CODE_PREVIEW_BYTES : MAX_TEXT_PREVIEW_BYTES;
524
+ const contentBuffer = isText ? version.buffer.subarray(0, contentLimit) : null;
435
525
  sendJson(res, 200, {
436
526
  path: rel.replace(/\\/g, '/'),
437
527
  name,
438
528
  ext: path.extname(abs).toLowerCase(),
439
529
  kind,
530
+ category,
531
+ preview,
440
532
  size: version.buffer.length,
441
533
  binary: !isText,
442
- content: isText ? version.buffer.toString('utf8') : null,
534
+ content: contentBuffer ? contentBuffer.toString('utf8') : null,
535
+ truncated: Boolean(contentBuffer && contentBuffer.length < version.buffer.length),
443
536
  ref: entry ? entry.sha : ref,
444
537
  author: entry ? entry.author : null,
445
538
  date: entry ? entry.date : null,