-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
782 lines (716 loc) · 27.6 KB
/
Copy pathserver.js
File metadata and controls
782 lines (716 loc) · 27.6 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
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const os = require('os');
const path = require('path');
const http = require('http');
const { exec } = require('child_process');
const { WebSocketServer } = require('ws');
const chokidar = require('chokidar');
const matter = require('gray-matter');
const app = express();
const server = http.createServer(app);
const wss = new WebSocketServer({ server });
const PORT = 3001;
// --- Config ---
// Resolve config file path from (in priority order):
// 1. --config <path> CLI argument
// 2. NB_CONFIG environment variable
// 3. ./config.json next to server.js (local dev fallback)
function resolveConfigPath() {
const flagIdx = process.argv.indexOf('--config');
if (flagIdx !== -1 && process.argv[flagIdx + 1]) {
return path.resolve(process.argv[flagIdx + 1]);
}
if (process.env.NB_CONFIG) {
return path.resolve(process.env.NB_CONFIG);
}
return path.join(__dirname, 'config.json');
}
const CONFIG_FILE = resolveConfigPath();
if (!fs.existsSync(CONFIG_FILE)) {
console.error(`Error: config file not found: ${CONFIG_FILE}`);
console.error('Pass a config path via --config <path> or the NB_CONFIG env var.');
console.error('See config.example.json for the expected format.');
process.exit(1);
}
function expandHome(p) {
if (!p) return p;
if (p === '~') return os.homedir();
if (p.startsWith('~/') || p.startsWith('~\\')) return path.join(os.homedir(), p.slice(2));
return p;
}
function loadConfig() {
try {
return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
} catch {
return {
notesDir: './notes',
templatesDir: './templates',
templatePaths: {
'daily-note': 'Daily/{{date}}.md',
'meeting-note': 'Meetings/{{date}}-{{slug}}.md',
'blank': '{{title}}.md',
},
};
}
}
function saveConfig(cfg) {
fs.writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2));
}
// Remove a top-level YAML key (and its indented children) from a frontmatter
// block using line-by-line text manipulation — no YAML parse/stringify, so date
// strings, special values etc. are never coerced to JS types and back.
function stripFrontmatterKey(raw, key) {
if (!raw.startsWith('---\n') && !raw.startsWith('---\r\n')) return raw;
const closeIdx = raw.indexOf('\n---', 4);
if (closeIdx === -1) return raw;
const fmLines = raw.slice(4, closeIdx).split('\n');
const after = raw.slice(closeIdx); // keeps the '\n---\n' and body
const keyRe = new RegExp(`^${key}\\s*:`);
const filtered = [];
let skipping = false; // currently inside the block to remove
for (let i = 0; i < fmLines.length; i++) {
const line = fmLines[i];
if (!skipping) {
if (keyRe.test(line)) { skipping = true; continue; }
filtered.push(line);
continue;
}
// Inside the block: skip blank lines and any line that is indented
// (blank lines can appear inside YAML literal/folded block scalars)
if (line.trim() === '') continue;
if (/^[ \t]/.test(line)) continue;
// Non-empty, non-indented line — we've left the block
skipping = false;
filtered.push(line);
}
return '---\n' + filtered.join('\n') + after;
}
// Mutable — updated live when config is changed via the settings UI
let cfg = loadConfig();
// Env-var overrides allow the test runner to point at an isolated directory
let NOTES_DIR = process.env.NB_NOTES_DIR
? path.resolve(process.env.NB_NOTES_DIR)
: path.resolve(expandHome(cfg.notesDir));
let TEMPLATES_DIR = process.env.NB_TEMPLATES_DIR
? path.resolve(process.env.NB_TEMPLATES_DIR)
: path.resolve(expandHome(cfg.templatesDir));
function ensureDirs() {
if (!fs.existsSync(NOTES_DIR)) fs.mkdirSync(NOTES_DIR, { recursive: true });
if (!fs.existsSync(TEMPLATES_DIR)) fs.mkdirSync(TEMPLATES_DIR, { recursive: true });
}
ensureDirs();
app.use(cors());
app.use(express.json());
// Serve the built React client (production mode)
const CLIENT_DIST = path.join(__dirname, 'client', 'dist');
if (fs.existsSync(CLIENT_DIST)) {
app.use(express.static(CLIENT_DIST));
}
// --- WebSocket ---
wss.on('connection', (ws) => {
ws.send(JSON.stringify({ type: 'connected' }));
});
function broadcast(data) {
const msg = JSON.stringify(data);
wss.clients.forEach((client) => {
if (client.readyState === 1) client.send(msg);
});
}
// --- File watcher (re-created when notes dir changes) ---
let watcher = null;
function startWatcher(dir) {
if (watcher) {
watcher.close();
watcher = null;
}
if (!fs.existsSync(dir)) return;
watcher = chokidar.watch(dir, { ignoreInitial: true, persistent: true });
watcher.on('all', () => broadcast({ type: 'tree-change' }));
}
startWatcher(NOTES_DIR);
// --- Git auto-commit ---
// Commit each file save. Uses the git repo that contains NOTES_DIR.
function gitCommitFile(filePath) {
// Use NOTES_DIR as the -C dir; git walks up to find the repo root automatically.
const repoDir = NOTES_DIR;
const rel = path.relative(repoDir, filePath);
// Step 1: stage the file
exec(`git -C ${JSON.stringify(repoDir)} add ${JSON.stringify(filePath)}`, (addErr, _out, addStderr) => {
if (addErr) {
console.error('[git] add failed:', (addStderr || addErr.message).trim());
return;
}
// Step 2: check whether anything is actually staged before committing
exec(`git -C ${JSON.stringify(repoDir)} diff --cached --quiet`, (diffErr) => {
// exit 0 = nothing staged (file unchanged) — skip silently
if (!diffErr) return;
// exit 1 = staged changes exist — commit
const msg = `notes: update ${rel}`;
exec(`git -C ${JSON.stringify(repoDir)} commit -m ${JSON.stringify(msg)}`, (commitErr, _o, commitStderr) => {
if (commitErr) {
console.error('[git] commit failed:', (commitStderr || commitErr.message).trim());
return;
}
console.log('[git] committed:', rel);
});
});
});
}
// --- Path safety ---
function safePath(inputPath, baseDir) {
let resolved;
if (path.isAbsolute(inputPath)) {
resolved = path.resolve(inputPath);
} else {
resolved = path.resolve(baseDir, inputPath);
}
// Read current dirs each call so changes take effect immediately
const notesResolved = path.resolve(NOTES_DIR);
const templatesResolved = path.resolve(TEMPLATES_DIR);
if (!resolved.startsWith(notesResolved) && !resolved.startsWith(templatesResolved)) {
throw new Error('Path traversal detected');
}
return resolved;
}
// --- Build file tree ---
// skipPaths: Set of absolute paths to exclude (e.g. templatesDir)
// Only .md files are included; hidden entries (starting with '.') are always skipped.
function buildTree(dirPath, skipPaths) {
const name = path.basename(dirPath);
if (name.startsWith('.')) return null; // skip .git, .DS_Store, etc.
const stat = fs.statSync(dirPath);
if (stat.isDirectory()) {
if (skipPaths && skipPaths.has(dirPath)) return null;
let children = [];
try {
children = fs.readdirSync(dirPath)
.map((entry) => {
try { return buildTree(path.join(dirPath, entry), skipPaths); } catch { return null; }
})
.filter(Boolean)
.sort((a, b) => {
if (a.type !== b.type) return a.type === 'dir' ? -1 : 1;
return a.name.localeCompare(b.name);
});
} catch { children = []; }
return { name, path: dirPath, type: 'dir', children };
}
// Only show markdown and canvas files
if (!name.endsWith('.md') && !name.endsWith('.canvas')) return null;
return { name, path: dirPath, type: 'file' };
}
// --- API Routes ---
// GET /api/config
app.get('/api/config', (req, res) => {
try {
res.json({ ...loadConfig(), _resolved: { notesDir: NOTES_DIR, templatesDir: TEMPLATES_DIR } });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// PUT /api/config — saves config and applies directory changes live
app.put('/api/config', (req, res) => {
try {
const incoming = req.body;
// Preserve templatePaths and any other keys not sent by the UI
const current = loadConfig();
const merged = { ...current, ...incoming };
saveConfig(merged);
cfg = merged;
const newNotesDir = path.resolve(expandHome(cfg.notesDir));
const newTemplatesDir = path.resolve(expandHome(cfg.templatesDir));
const notesDirChanged = newNotesDir !== NOTES_DIR;
NOTES_DIR = newNotesDir;
TEMPLATES_DIR = newTemplatesDir;
ensureDirs();
if (notesDirChanged) {
startWatcher(NOTES_DIR);
broadcast({ type: 'tree-change' });
}
res.json({ success: true, notesDir: NOTES_DIR, templatesDir: TEMPLATES_DIR });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// GET /api/resolve?name=NoteName — find a note file by name (for wiki links)
app.get('/api/resolve', (req, res) => {
const { name } = req.query;
if (!name) return res.status(400).json({ error: 'name required' });
function search(dir) {
try {
for (const entry of fs.readdirSync(dir)) {
const full = path.join(dir, entry);
try {
const stat = fs.statSync(full);
if (stat.isDirectory()) {
const found = search(full);
if (found) return found;
} else if (
entry === name ||
entry === name + '.md' ||
entry.replace(/\.md$/, '') === name
) {
return full;
}
} catch { continue; }
}
} catch { }
return null;
}
const found = search(NOTES_DIR);
if (found) res.json({ path: found });
else res.status(404).json({ error: 'Note not found' });
});
// GET /api/tree
app.get('/api/tree', (req, res) => {
try {
const rootParam = req.query.root;
const rootDir = rootParam ? path.resolve(rootParam) : NOTES_DIR;
if (!fs.existsSync(rootDir)) fs.mkdirSync(rootDir, { recursive: true });
// Exclude the templates directory — it's shown separately in the sidebar
const skipPaths = new Set([path.resolve(TEMPLATES_DIR)]);
res.json(buildTree(rootDir, skipPaths));
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// GET /api/file
app.get('/api/file', (req, res) => {
try {
const filePath = safePath(req.query.path, NOTES_DIR);
if (!fs.existsSync(filePath)) return res.status(404).json({ error: 'File not found' });
res.type('text/plain').send(fs.readFileSync(filePath, 'utf-8'));
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// GET /api/export/html?path= — styled HTML for print-to-PDF
app.get('/api/export/html', async (req, res) => {
try {
const filePath = safePath(req.query.path, NOTES_DIR);
const raw = fs.readFileSync(filePath, 'utf-8');
const { marked } = await import('marked');
// Strip YAML frontmatter before converting
const md = raw.startsWith('---\n')
? raw.slice(raw.indexOf('\n---\n', 4) + 5).trimStart()
: raw;
const body = await marked.parse(md);
const title = path.basename(filePath, '.md');
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>${title}</title>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: Georgia, 'Times New Roman', serif;
font-size: 15px; line-height: 1.75; color: #1a1a1a;
max-width: 760px; margin: 48px auto; padding: 0 48px;
}
h1,h2,h3,h4,h5,h6 { margin: 1.4em 0 0.5em; font-weight: 700; line-height: 1.3; }
h1 { font-size: 2em; } h2 { font-size: 1.5em; } h3 { font-size: 1.2em; }
p { margin: 0.8em 0; }
a { color: #005cc5; }
code { background: #f3f3f3; padding: 2px 5px; border-radius: 3px; font-size: 0.9em; font-family: monospace; }
pre { background: #f3f3f3; padding: 16px; border-radius: 4px; overflow-x: auto; margin: 1em 0; }
pre code { background: none; padding: 0; }
blockquote { border-left: 4px solid #ccc; padding-left: 1em; color: #555; margin: 1em 0; }
ul, ol { padding-left: 1.5em; margin: 0.8em 0; }
li { margin: 0.3em 0; }
table { border-collapse: collapse; width: 100%; margin: 1em 0; }
th, td { border: 1px solid #ccc; padding: 6px 12px; text-align: left; }
th { background: #f3f3f3; font-weight: 600; }
hr { border: none; border-top: 1px solid #ccc; margin: 2em 0; }
img { max-width: 100%; }
@media print {
body { margin: 0; padding: 24px; }
@page { margin: 1.5cm; }
}
</style>
</head>
<body>
<h1>${title}</h1>
${body}
</body>
</html>`;
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.send(html);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// PUT /api/file
app.put('/api/file', (req, res) => {
try {
const { path: filePath, content } = req.body;
if (!filePath) return res.status(400).json({ error: 'path required' });
const safe = safePath(filePath, NOTES_DIR);
const dir = path.dirname(safe);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(safe, content ?? '', 'utf-8');
res.json({ success: true, path: safe });
if (req.query.nocommit !== '1') gitCommitFile(safe); // ← only change
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// POST /api/git/commit — explicit commit for a single file
app.post('/api/git/commit', (req, res) => {
try {
const { path: filePath } = req.body;
if (!filePath) return res.status(400).json({ error: 'path required' });
const safe = safePath(filePath, NOTES_DIR);
gitCommitFile(safe);
res.json({ success: true });
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// DELETE /api/file
app.delete('/api/file', (req, res) => {
try {
const filePath = safePath(req.query.path, NOTES_DIR);
if (!fs.existsSync(filePath)) return res.status(404).json({ error: 'File not found' });
const stat = fs.statSync(filePath);
if (stat.isDirectory()) fs.rmSync(filePath, { recursive: true });
else fs.unlinkSync(filePath);
res.json({ success: true });
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// POST /api/mkdir
app.post('/api/mkdir', (req, res) => {
try {
const { path: dirPath } = req.body;
if (!dirPath) return res.status(400).json({ error: 'path required' });
const safe = safePath(dirPath, NOTES_DIR);
fs.mkdirSync(safe, { recursive: true });
res.json({ success: true, path: safe });
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// POST /api/rename
app.post('/api/rename', (req, res) => {
try {
const { oldPath, newPath } = req.body;
if (!oldPath || !newPath) return res.status(400).json({ error: 'oldPath and newPath required' });
const safeOld = safePath(oldPath, NOTES_DIR);
const safeNew = safePath(newPath, NOTES_DIR);
if (!fs.existsSync(safeOld)) return res.status(404).json({ error: 'Source not found' });
const newDir = path.dirname(safeNew);
if (!fs.existsSync(newDir)) fs.mkdirSync(newDir, { recursive: true });
fs.renameSync(safeOld, safeNew);
res.json({ success: true });
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// GET /api/search
app.get('/api/search', (req, res) => {
try {
const { q } = req.query;
if (!q) return res.json([]);
const searchDir = NOTES_DIR;
const results = [];
const query = q.toLowerCase();
function searchDir_(dir) {
let entries;
try { entries = fs.readdirSync(dir); } catch { return; }
for (const entry of entries) {
const fullPath = path.join(dir, entry);
let stat;
try { stat = fs.statSync(fullPath); } catch { continue; }
if (stat.isDirectory()) {
searchDir_(fullPath);
} else if (entry.endsWith('.md')) {
const nameMatch = entry.toLowerCase().includes(query);
let snippet = '';
let contentMatch = false;
try {
const content = fs.readFileSync(fullPath, 'utf-8');
const lower = content.toLowerCase();
const idx = lower.indexOf(query);
if (idx !== -1) {
contentMatch = true;
const start = Math.max(0, idx - 60);
const end = Math.min(content.length, idx + query.length + 60);
snippet = (start > 0 ? '...' : '') + content.slice(start, end) + (end < content.length ? '...' : '');
}
} catch { /* skip */ }
if (nameMatch || contentMatch) results.push({ path: fullPath, name: entry, snippet });
}
}
}
searchDir_(searchDir);
res.json(results);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// GET /api/templates
app.get('/api/templates', (req, res) => {
try {
if (!fs.existsSync(TEMPLATES_DIR)) return res.json([]);
const files = fs.readdirSync(TEMPLATES_DIR).filter((f) => f.endsWith('.md'));
const templates = files.map((f) => {
const raw = fs.readFileSync(path.join(TEMPLATES_DIR, f), 'utf-8');
const parsed = matter(raw);
return {
name: f.replace(/\.md$/, ''),
filename: f,
path: path.join(TEMPLATES_DIR, f),
shortcuts: parsed.data._shortcuts || [],
tags: parsed.data.tags || [],
};
});
res.json(templates);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// POST /api/template
app.post('/api/template', (req, res) => {
try {
const { templateName, outputPath, vars } = req.body;
if (!templateName || !outputPath) {
return res.status(400).json({ error: 'templateName and outputPath required' });
}
const templateFile = path.join(TEMPLATES_DIR, templateName.endsWith('.md') ? templateName : `${templateName}.md`);
if (!fs.existsSync(templateFile)) return res.status(404).json({ error: 'Template not found' });
const rawTemplate = fs.readFileSync(templateFile, 'utf-8');
// Build replacements first
const now = new Date();
const pad = (n) => String(n).padStart(2, '0');
const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
const time = `${pad(now.getHours())}:${pad(now.getMinutes())}`;
const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const replacements = {
'{{date}}': date,
'{{time}}': time,
'{{datetime}}': `${date} ${time}`,
'{{title}}': vars?.title || 'Untitled',
'{{year}}': String(now.getFullYear()),
'{{month}}': pad(now.getMonth() + 1),
'{{day}}': pad(now.getDate()),
'{{weekday}}': weekdays[now.getDay()],
};
// Allow callers to pass extra {{custom}} vars — keys must already include the braces
// to avoid accidentally replacing substrings inside already-substituted values.
if (vars) {
for (const [k, v] of Object.entries(vars)) {
const wrapped = k.startsWith('{{') ? k : `{{${k}}}`;
if (!replacements[wrapped]) replacements[wrapped] = String(v);
}
}
// Step 1: substitute all {{variables}} on the raw string first, so YAML
// never sees tokens like {{date}} which it misparses as flow mappings.
let content = rawTemplate;
for (const [placeholder, value] of Object.entries(replacements)) {
content = content.split(placeholder).join(value);
}
// Step 2: strip _shortcuts from the frontmatter using plain text manipulation.
// We deliberately avoid a parse→delete→stringify roundtrip because gray-matter
// coerces bare dates (2026-05-01) to JS Date objects, then serialises them back
// as timestamps — corrupting the frontmatter.
content = stripFrontmatterKey(content, '_shortcuts');
const safeOut = safePath(outputPath, NOTES_DIR);
// Guard against silent overwrites — require explicit ?overwrite=true
if (fs.existsSync(safeOut) && req.body.overwrite !== true) {
return res.status(409).json({ error: 'File already exists', path: safeOut });
}
const outDir = path.dirname(safeOut);
if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true });
fs.writeFileSync(safeOut, content, 'utf-8');
res.json({ success: true, path: safeOut, content });
// Commit the new file asynchronously
gitCommitFile(safeOut);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
app.get('/api/git/log', (req, res) => {
try {
const filePath = safePath(req.query.path, NOTES_DIR);
const repoDir = NOTES_DIR;
exec(`git -C ${JSON.stringify(repoDir)} rev-parse --show-toplevel`, (err, topLevel) => {
if (err) return res.status(500).json({ error: 'Not a git repository' });
const repoRoot = topLevel.trim();
const relToRoot = path.relative(repoRoot, filePath);
exec(`git -C ${JSON.stringify(repoRoot)} log --pretty=format:"%H|%ai|%s" -- ${JSON.stringify(relToRoot)}`, (err2, stdout, stderr2) => {
if (err2) return res.status(500).json({ error: (stderr2 || err2.message).trim() });
const commits = stdout.trim().split('\n').filter(Boolean).map(line => {
const idx1 = line.indexOf('|');
const idx2 = line.indexOf('|', idx1 + 1);
return {
hash: line.slice(0, idx1),
date: line.slice(idx1 + 1, idx2).trim(),
message: line.slice(idx2 + 1).trim(),
};
});
res.json(commits);
});
});
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// GET /api/git/diff?path=&hash= — unified diff of a single commit vs its parent
app.get('/api/git/diff', (req, res) => {
try {
const filePath = safePath(req.query.path, NOTES_DIR);
const hash = req.query.hash;
if (!hash || !/^[0-9a-f]{7,40}$/i.test(hash)) return res.status(400).json({ error: 'Invalid hash' });
exec(`git -C ${JSON.stringify(NOTES_DIR)} rev-parse --show-toplevel`, (err, topLevel) => {
if (err) return res.status(500).json({ error: 'Not a git repository' });
const repoRoot = topLevel.trim();
const relToRoot = path.relative(repoRoot, filePath);
// Diff this commit against its parent; for the first commit use --root
const cmd = `git -C ${JSON.stringify(repoRoot)} diff ${hash}~1 ${hash} -- ${JSON.stringify(relToRoot)} 2>/dev/null || git -C ${JSON.stringify(repoRoot)} show --format= ${hash} -- ${JSON.stringify(relToRoot)}`;
exec(cmd, (err2, stdout, stderr2) => {
if (err2) return res.status(500).json({ error: (stderr2 || err2.message).trim() });
res.type('text/plain').send(stdout);
});
});
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// GET /api/tasks — all checkbox items across every note
app.get('/api/tasks', (req, res) => {
try {
const results = [];
const TASK_RE = /^(\s*)- \[([ xX])\] (.+)$/;
function scanDir(dir) {
let entries;
try { entries = fs.readdirSync(dir); } catch { return; }
for (const entry of entries) {
if (entry.startsWith('.')) continue;
const fullPath = path.join(dir, entry);
let stat;
try { stat = fs.statSync(fullPath); } catch { continue; }
if (stat.isDirectory()) { scanDir(fullPath); continue; }
if (!entry.endsWith('.md')) continue;
try {
const lines = fs.readFileSync(fullPath, 'utf-8').split('\n');
lines.forEach((line, idx) => {
const m = line.match(TASK_RE);
if (m) results.push({
path: fullPath,
name: entry.replace(/\.md$/, ''),
lineNumber: idx + 1,
text: m[3].trim(),
done: m[2].toLowerCase() === 'x',
});
});
} catch { /* skip unreadable */ }
}
}
scanDir(NOTES_DIR);
res.json(results);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// POST /api/task/toggle — flip a checkbox `- [ ]` <-> `- [x]` at a given line
app.post('/api/task/toggle', (req, res) => {
try {
const { path: filePath, lineNumber } = req.body;
if (!filePath) return res.status(400).json({ error: 'path required' });
if (!Number.isInteger(lineNumber) || lineNumber < 1) {
return res.status(400).json({ error: 'lineNumber must be a positive integer' });
}
const safe = safePath(filePath, NOTES_DIR);
const content = fs.readFileSync(safe, 'utf-8');
const lines = content.split('\n');
const idx = lineNumber - 1;
if (idx >= lines.length) return res.status(400).json({ error: 'lineNumber out of range' });
const m = lines[idx].match(/^(\s*-\s*\[)([ xX])(\].*)$/);
if (!m) return res.status(400).json({ error: 'line is not a task' });
const done = m[2].toLowerCase() !== 'x';
lines[idx] = m[1] + (done ? 'x' : ' ') + m[3];
fs.writeFileSync(safe, lines.join('\n'), 'utf-8');
res.json({ success: true, path: safe, lineNumber, done });
gitCommitFile(safe);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// GET /api/backlinks?name=NoteName — files that contain [[NoteName]]
app.get('/api/backlinks', (req, res) => {
try {
const { name } = req.query;
if (!name) return res.status(400).json({ error: 'name required' });
const baseName = name.replace(/\.md$/, '');
const esc = baseName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const linkRe = new RegExp(`\\[\\[${esc}(?:\\.md)?(?:\\|[^\\]]*)?\\]\\]`, 'i');
const results = [];
function scanDir(dir) {
let entries;
try { entries = fs.readdirSync(dir); } catch { return; }
for (const entry of entries) {
if (entry.startsWith('.')) continue;
const fullPath = path.join(dir, entry);
let stat;
try { stat = fs.statSync(fullPath); } catch { continue; }
if (stat.isDirectory()) { scanDir(fullPath); continue; }
if (!entry.endsWith('.md')) continue;
// Skip the note itself
if (entry.replace(/\.md$/, '') === baseName) continue;
try {
const content = fs.readFileSync(fullPath, 'utf-8');
if (!linkRe.test(content)) continue;
const lines = content.split('\n');
let excerpt = '';
for (let i = 0; i < lines.length; i++) {
if (linkRe.test(lines[i])) {
const s = Math.max(0, i - 1), e = Math.min(lines.length - 1, i + 1);
excerpt = lines.slice(s, e + 1).join(' ').trim().slice(0, 120);
break;
}
}
results.push({ path: fullPath, name: entry.replace(/\.md$/, ''), excerpt });
} catch { /* skip */ }
}
}
scanDir(NOTES_DIR);
res.json(results);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.get('/api/git/show', (req, res) => {
try {
const filePath = safePath(req.query.path, NOTES_DIR);
const hash = req.query.hash;
if (!hash || !/^[0-9a-f]{7,40}$/i.test(hash)) return res.status(400).json({ error: 'Invalid hash' });
const repoDir = NOTES_DIR;
exec(`git -C ${JSON.stringify(repoDir)} rev-parse --show-toplevel`, (err, topLevel) => {
if (err) return res.status(500).json({ error: 'Not a git repository' });
const repoRoot = topLevel.trim();
const relToRoot = path.relative(repoRoot, filePath);
exec(`git -C ${JSON.stringify(repoRoot)} show ${JSON.stringify(hash + ':' + relToRoot)}`, (err2, stdout, stderr2) => {
if (err2) return res.status(500).json({ error: (stderr2 || err2.message).trim() });
res.type('text/plain').send(stdout);
});
});
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// SPA fallback — serve index.html for any non-API route
if (fs.existsSync(CLIENT_DIST)) {
app.get('*', (req, res) => {
res.sendFile(path.join(CLIENT_DIST, 'index.html'));
});
}
server.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(` Config: ${CONFIG_FILE}`);
console.log(` Notes: ${NOTES_DIR}`);
console.log(` Templates: ${TEMPLATES_DIR}`);
});