readingroom 0.4.0 → 0.5.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/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,