chatshelf 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +152 -2
- package/bin/chatshelf.mjs +45 -0
- package/package.json +44 -4
- package/public/app.js +1536 -0
- package/public/index.html +371 -0
- package/public/style.css +610 -0
- package/server.mjs +732 -0
- package/sources.mjs +674 -0
package/server.mjs
ADDED
|
@@ -0,0 +1,732 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Chatshelf: a local web app to browse AI coding chats (Claude Code, Codex, Cursor, Copilot…) and
|
|
3
|
+
// move them when a project folder is renamed. Node built-ins only.
|
|
4
|
+
import http from 'node:http';
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import fsp from 'node:fs/promises';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import crypto from 'node:crypto';
|
|
10
|
+
import readline from 'node:readline';
|
|
11
|
+
import { once } from 'node:events';
|
|
12
|
+
import { spawn } from 'node:child_process';
|
|
13
|
+
import { fileURLToPath } from 'node:url';
|
|
14
|
+
import { READERS, reader, importExport, removeImport } from './sources.mjs';
|
|
15
|
+
|
|
16
|
+
const HOME = os.homedir();
|
|
17
|
+
const CLAUDE = process.env.CLAUDE_CONFIG_DIR || path.join(HOME, '.claude');
|
|
18
|
+
const ROOT = path.join(CLAUDE, 'projects');
|
|
19
|
+
const BACKUP = path.join(CLAUDE, 'projects-backup');
|
|
20
|
+
const DATA_ROOT = process.env.XDG_DATA_HOME || path.join(HOME, '.local', 'share');
|
|
21
|
+
const DATA_DIR = path.join(DATA_ROOT, 'chatshelf');
|
|
22
|
+
// Earlier builds were called claude-session-manager: carry their bookmarks and imports over once.
|
|
23
|
+
const OLD_DATA_DIR = path.join(DATA_ROOT, 'claude-session-manager');
|
|
24
|
+
if (!fs.existsSync(DATA_DIR) && fs.existsSync(OLD_DATA_DIR)) { try { fs.renameSync(OLD_DATA_DIR, DATA_DIR); } catch { /* keep going with a fresh folder */ } }
|
|
25
|
+
const BOOKMARKS = path.join(DATA_DIR, 'bookmarks.json');
|
|
26
|
+
const CACHE_FILE = path.join(process.env.XDG_CACHE_HOME || path.join(HOME, '.cache'), 'chatshelf', 'index.json');
|
|
27
|
+
const PORT = Number(process.env.PORT || 4317);
|
|
28
|
+
const HOST = '127.0.0.1';
|
|
29
|
+
const TOKEN = crypto.randomBytes(24).toString('hex');
|
|
30
|
+
const PUBLIC = path.join(path.dirname(fileURLToPath(import.meta.url)), 'public');
|
|
31
|
+
|
|
32
|
+
// Claude Code names a project's session folder after its path, with every
|
|
33
|
+
// character that is not a letter or digit replaced by "-".
|
|
34
|
+
const CACHE_VERSION = 2;
|
|
35
|
+
const encode = (p) => path.resolve(p).replace(/[^a-zA-Z0-9]/g, '-');
|
|
36
|
+
const isDir = (p) => { try { return fs.statSync(p).isDirectory(); } catch { return false; } };
|
|
37
|
+
const exists = (p) => fs.existsSync(p);
|
|
38
|
+
const expand = (p) => (p === '~' ? HOME : p.startsWith('~/') ? path.join(HOME, p.slice(2)) : p);
|
|
39
|
+
|
|
40
|
+
class HttpError extends Error {
|
|
41
|
+
constructor(status, message) { super(message); this.status = status; }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// ---------- index cache (per file, keyed by mtime + size) ----------
|
|
45
|
+
let cache = {};
|
|
46
|
+
try { cache = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf8')); } catch { cache = {}; }
|
|
47
|
+
let cacheDirty = false;
|
|
48
|
+
function saveCache(seen) {
|
|
49
|
+
for (const k of Object.keys(cache)) if (!seen.has(k)) { delete cache[k]; cacheDirty = true; }
|
|
50
|
+
if (!cacheDirty) return;
|
|
51
|
+
fs.mkdirSync(path.dirname(CACHE_FILE), { recursive: true });
|
|
52
|
+
fs.writeFileSync(CACHE_FILE, JSON.stringify(cache));
|
|
53
|
+
cacheDirty = false;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function textOf(content) {
|
|
57
|
+
if (typeof content === 'string') return content;
|
|
58
|
+
if (Array.isArray(content)) return content.filter((b) => b && b.type === 'text').map((b) => b.text).join('\n');
|
|
59
|
+
return '';
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function cleanPrompt(t, keepLines = false) {
|
|
63
|
+
t = (t || '').trim();
|
|
64
|
+
if (t.startsWith('<command-name>')) return t.split('<command-name>')[1].split('</command-name>')[0].trim();
|
|
65
|
+
if (!t || t.startsWith('<') || t.startsWith('[Request interrupted')) return '';
|
|
66
|
+
return keepLines ? t : t.replace(/\s+/g, ' ');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function lines(file) {
|
|
70
|
+
return readline.createInterface({ input: fs.createReadStream(file, 'utf8'), crlfDelay: Infinity });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function parseSession(file) {
|
|
74
|
+
const st = await fsp.stat(file);
|
|
75
|
+
const hit = cache[file];
|
|
76
|
+
if (hit && hit.v === CACHE_VERSION && hit.m === st.mtimeMs && hit.s === st.size) return { ...hit.d, mtime: st.mtimeMs, size: st.size };
|
|
77
|
+
|
|
78
|
+
const d = { cwd: '', branch: '', custom: '', summary: '', prompts: [], promptCount: 0, start: '', last: '' };
|
|
79
|
+
for await (const line of lines(file)) {
|
|
80
|
+
if (!line.includes('"type":"user"') && !line.includes('"customTitle"') && !line.startsWith('{"type":"summary"')) continue;
|
|
81
|
+
let o;
|
|
82
|
+
try { o = JSON.parse(line); } catch { continue; }
|
|
83
|
+
if (o.type === 'custom-title' && o.customTitle) { d.custom = o.customTitle; continue; }
|
|
84
|
+
if (o.type === 'summary') { if (!d.summary && o.summary) d.summary = o.summary; continue; }
|
|
85
|
+
if (o.type !== 'user') continue;
|
|
86
|
+
if (!d.cwd && o.cwd) d.cwd = o.cwd;
|
|
87
|
+
if (!d.branch && o.gitBranch) d.branch = o.gitBranch;
|
|
88
|
+
if (!d.start && o.timestamp) d.start = o.timestamp;
|
|
89
|
+
if (o.isMeta || o.isSidechain) continue;
|
|
90
|
+
const t = cleanPrompt(textOf(o.message && o.message.content));
|
|
91
|
+
if (t) { d.promptCount++; d.last = t.slice(0, 300); if (d.prompts.length < 60) d.prompts.push(t.slice(0, 300)); }
|
|
92
|
+
}
|
|
93
|
+
// The first prompt is often a shortcut like "c-p" or "ok": prefer the first one that says something.
|
|
94
|
+
const meaningful = d.prompts.find((t) => !t.startsWith('/') && t.split(/\s+/).length >= 4);
|
|
95
|
+
d.title = d.custom || d.summary || meaningful || d.prompts[0] || 'Empty session';
|
|
96
|
+
if (d.last === d.title || d.promptCount < 2) d.last = '';
|
|
97
|
+
delete d.custom; delete d.summary;
|
|
98
|
+
cache[file] = { v: CACHE_VERSION, m: st.mtimeMs, s: st.size, d };
|
|
99
|
+
cacheDirty = true;
|
|
100
|
+
return { ...d, mtime: st.mtimeMs, size: st.size };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function pool(items, n, fn) {
|
|
104
|
+
let i = 0;
|
|
105
|
+
await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => {
|
|
106
|
+
while (i < items.length) await fn(items[i++]);
|
|
107
|
+
}));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
let scanning = null;
|
|
111
|
+
function scan() {
|
|
112
|
+
if (!scanning) scanning = doScan().finally(() => { scanning = null; });
|
|
113
|
+
return scanning;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function doScan() {
|
|
117
|
+
if (!isDir(ROOT)) return [];
|
|
118
|
+
const entries = (await fsp.readdir(ROOT, { withFileTypes: true })).filter((e) => e.isDirectory());
|
|
119
|
+
const projects = [];
|
|
120
|
+
const jobs = [];
|
|
121
|
+
for (const e of entries) {
|
|
122
|
+
const dir = path.join(ROOT, e.name);
|
|
123
|
+
let names;
|
|
124
|
+
try { names = await fsp.readdir(dir); } catch { continue; }
|
|
125
|
+
const p = { key: e.name, source: 'claude', cwd: '', exists: false, missing: false, memory: names.includes('memory'), sessions: [] };
|
|
126
|
+
projects.push(p);
|
|
127
|
+
for (const n of names) if (n.endsWith('.jsonl')) jobs.push({ p, id: n.slice(0, -6), file: path.join(dir, n) });
|
|
128
|
+
}
|
|
129
|
+
const seen = new Set(jobs.map((j) => j.file));
|
|
130
|
+
await pool(jobs, 8, async (j) => {
|
|
131
|
+
try { j.p.sessions.push({ id: j.id, ...(await parseSession(j.file)) }); } catch { /* unreadable file */ }
|
|
132
|
+
});
|
|
133
|
+
saveCache(seen);
|
|
134
|
+
for (const p of projects) {
|
|
135
|
+
p.sessions.sort((a, b) => b.mtime - a.mtime);
|
|
136
|
+
const cwds = p.sessions.map((s) => s.cwd).filter(Boolean);
|
|
137
|
+
p.cwd = cwds.find((c) => encode(c) === p.key) || cwds[0] || '';
|
|
138
|
+
p.exists = p.cwd ? isDir(p.cwd) : false;
|
|
139
|
+
p.missing = Boolean(p.cwd) && !p.exists;
|
|
140
|
+
p.updated = p.sessions[0] ? p.sessions[0].mtime : 0;
|
|
141
|
+
}
|
|
142
|
+
for (const p of projects) for (const s of p.sessions) s.source = 'claude';
|
|
143
|
+
const others = await scanOtherTools();
|
|
144
|
+
return [...projects.filter((p) => p.sessions.length || p.memory), ...others].sort((a, b) => b.updated - a.updated);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Chats from other tools, grouped by tool + folder. `refs` maps "key|id" to the reader's own handle.
|
|
148
|
+
const refs = new Map();
|
|
149
|
+
const toolErrors = new Map();
|
|
150
|
+
async function scanOtherTools() {
|
|
151
|
+
const groups = new Map();
|
|
152
|
+
for (const r of READERS) {
|
|
153
|
+
let items = [];
|
|
154
|
+
try { items = await r.list(); toolErrors.delete(r.id); } catch (e) { toolErrors.set(r.id, e.message); continue; }
|
|
155
|
+
for (const it of items) {
|
|
156
|
+
const key = `${r.id}:${it.cwd ? encode(it.cwd) : 'none'}`;
|
|
157
|
+
if (!groups.has(key)) {
|
|
158
|
+
groups.set(key, { key, source: r.id, cwd: it.cwd || '', exists: it.cwd ? isDir(it.cwd) : false, missing: false, memory: false, sessions: [] });
|
|
159
|
+
}
|
|
160
|
+
const { ref, ...pub } = it;
|
|
161
|
+
refs.set(`${key}|${it.id}`, { reader: r.id, ref });
|
|
162
|
+
groups.get(key).sessions.push({ ...pub, source: r.id });
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
for (const p of groups.values()) {
|
|
166
|
+
p.sessions.sort((a, b) => b.mtime - a.mtime);
|
|
167
|
+
p.updated = p.sessions[0] ? p.sessions[0].mtime : 0;
|
|
168
|
+
}
|
|
169
|
+
return [...groups.values()];
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async function getProject(key) {
|
|
173
|
+
if (typeof key !== 'string' || !/^[A-Za-z0-9:._-]{1,400}$/.test(key) || (!key.includes(':') && !isDir(path.join(ROOT, key)))) {
|
|
174
|
+
throw new HttpError(404, 'Unknown project.');
|
|
175
|
+
}
|
|
176
|
+
const p = (await scan()).find((x) => x.key === key);
|
|
177
|
+
if (!p) throw new HttpError(404, 'Unknown project.');
|
|
178
|
+
return p;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// ---------- transcript ----------
|
|
182
|
+
async function transcript(file) {
|
|
183
|
+
const msgs = [];
|
|
184
|
+
for await (const line of lines(file)) {
|
|
185
|
+
if (!line.includes('"type":"user"') && !line.includes('"type":"assistant"')) continue;
|
|
186
|
+
let o;
|
|
187
|
+
try { o = JSON.parse(line); } catch { continue; }
|
|
188
|
+
if ((o.type !== 'user' && o.type !== 'assistant') || o.isMeta || o.isSidechain) continue;
|
|
189
|
+
const c = o.message && o.message.content;
|
|
190
|
+
let text = '';
|
|
191
|
+
const tools = [];
|
|
192
|
+
if (typeof c === 'string') text = c;
|
|
193
|
+
else if (Array.isArray(c)) {
|
|
194
|
+
for (const b of c) {
|
|
195
|
+
if (b.type === 'text') text += (text ? '\n' : '') + b.text;
|
|
196
|
+
else if (b.type === 'tool_use') {
|
|
197
|
+
const inp = b.input || {};
|
|
198
|
+
let detail = inp.command || inp.file_path || inp.path || inp.pattern || inp.url || inp.query || inp.description || inp.skill || '';
|
|
199
|
+
if (typeof detail !== 'string') detail = '';
|
|
200
|
+
detail = detail.replace(/\s+/g, ' ').replace(HOME, '~');
|
|
201
|
+
tools.push({ name: b.name, detail: detail.length > 90 ? detail.slice(0, 90) + '…' : detail });
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (o.type === 'user') text = cleanPrompt(text, true);
|
|
206
|
+
text = text.trim();
|
|
207
|
+
if (!text && !tools.length) continue;
|
|
208
|
+
const last = msgs[msgs.length - 1];
|
|
209
|
+
if (last && last.role === 'assistant' && o.type === 'assistant') {
|
|
210
|
+
if (text) last.text = (last.text ? last.text + '\n\n' : '') + text;
|
|
211
|
+
last.tools.push(...tools);
|
|
212
|
+
if (typeof o.uuid === 'string') last.uuids.push(o.uuid);
|
|
213
|
+
} else {
|
|
214
|
+
const uuid = typeof o.uuid === 'string' ? o.uuid : '';
|
|
215
|
+
msgs.push({ role: o.type, text, tools, ts: o.timestamp || '', uuid, uuids: uuid ? [uuid] : [] });
|
|
216
|
+
}
|
|
217
|
+
if (msgs.length >= 3000) break;
|
|
218
|
+
}
|
|
219
|
+
for (const m of msgs) if (m.text.length > 8000) m.text = m.text.slice(0, 8000) + '\n…';
|
|
220
|
+
return msgs;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// ---------- folder suggestions and browsing ----------
|
|
224
|
+
function bigrams(s) {
|
|
225
|
+
const out = new Map();
|
|
226
|
+
for (let i = 0; i < s.length - 1; i++) { const g = s.slice(i, i + 2); out.set(g, (out.get(g) || 0) + 1); }
|
|
227
|
+
return out;
|
|
228
|
+
}
|
|
229
|
+
function similarity(a, b) {
|
|
230
|
+
if (a === b) return 1;
|
|
231
|
+
const A = bigrams(a), B = bigrams(b);
|
|
232
|
+
let hit = 0, total = 0;
|
|
233
|
+
for (const v of A.values()) total += v;
|
|
234
|
+
for (const v of B.values()) total += v;
|
|
235
|
+
for (const [g, v] of A) hit += Math.min(v, B.get(g) || 0);
|
|
236
|
+
return total ? (2 * hit) / total : 0;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function suggest(oldCwd, knownCwds) {
|
|
240
|
+
let anc = path.dirname(oldCwd);
|
|
241
|
+
while (anc !== path.dirname(anc) && !isDir(anc)) anc = path.dirname(anc);
|
|
242
|
+
const base = path.basename(oldCwd).toLowerCase();
|
|
243
|
+
const found = [];
|
|
244
|
+
const walk = (dir, depth) => {
|
|
245
|
+
let ents;
|
|
246
|
+
try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
247
|
+
for (const e of ents) {
|
|
248
|
+
if (!e.isDirectory() || e.name.startsWith('.') || e.name === 'node_modules' || e.name === 'vendor') continue;
|
|
249
|
+
const full = path.join(dir, e.name);
|
|
250
|
+
let score = similarity(base, e.name.toLowerCase());
|
|
251
|
+
if (!knownCwds.has(full)) score += 0.1; // a renamed folder usually has no sessions of its own yet
|
|
252
|
+
if (path.dirname(full) === path.dirname(oldCwd)) score += 0.1; // same parent as before
|
|
253
|
+
found.push({ path: full, score });
|
|
254
|
+
if (depth > 1) walk(full, depth - 1);
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
walk(anc, 2);
|
|
258
|
+
return found.filter((f) => f.score > 0.35).sort((a, b) => b.score - a.score).slice(0, 8);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function listDirs(p) {
|
|
262
|
+
let dir = path.resolve(expand(p || HOME));
|
|
263
|
+
if (!isDir(dir)) dir = HOME;
|
|
264
|
+
let dirs = [];
|
|
265
|
+
try {
|
|
266
|
+
dirs = fs.readdirSync(dir, { withFileTypes: true })
|
|
267
|
+
.filter((e) => e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules')
|
|
268
|
+
.map((e) => e.name)
|
|
269
|
+
.sort((a, b) => a.localeCompare(b));
|
|
270
|
+
} catch { /* unreadable */ }
|
|
271
|
+
return { path: dir, parent: path.dirname(dir) === dir ? null : path.dirname(dir), dirs };
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// ---------- move, backup, restore ----------
|
|
275
|
+
async function mergeMove(s, d, moved, skipped) {
|
|
276
|
+
if (!exists(d)) { await fsp.rename(s, d); moved.push(d); return; }
|
|
277
|
+
if (isDir(s) && isDir(d)) {
|
|
278
|
+
for (const n of await fsp.readdir(s)) await mergeMove(path.join(s, n), path.join(d, n), moved, skipped);
|
|
279
|
+
try { await fsp.rmdir(s); } catch { /* not empty: something was skipped */ }
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
skipped.push(path.relative(ROOT, s));
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
async function jsonlFiles(p, out = []) {
|
|
286
|
+
if (isDir(p)) for (const n of await fsp.readdir(p)) await jsonlFiles(path.join(p, n), out);
|
|
287
|
+
else if (p.endsWith('.jsonl')) out.push(p);
|
|
288
|
+
return out;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async function rewriteCwd(file, oldCwd, newCwd) {
|
|
292
|
+
const st = await fsp.stat(file);
|
|
293
|
+
const tmp = `${file}.csm-tmp`;
|
|
294
|
+
const out = fs.createWriteStream(tmp, 'utf8');
|
|
295
|
+
let changed = false;
|
|
296
|
+
for await (const line of lines(file)) {
|
|
297
|
+
let l = line;
|
|
298
|
+
if (line.includes('"cwd"')) {
|
|
299
|
+
try {
|
|
300
|
+
const o = JSON.parse(line);
|
|
301
|
+
if (typeof o.cwd === 'string' && (o.cwd === oldCwd || o.cwd.startsWith(oldCwd + '/'))) {
|
|
302
|
+
o.cwd = newCwd + o.cwd.slice(oldCwd.length);
|
|
303
|
+
l = JSON.stringify(o);
|
|
304
|
+
changed = true;
|
|
305
|
+
}
|
|
306
|
+
} catch { /* keep line as is */ }
|
|
307
|
+
}
|
|
308
|
+
if (!out.write(l + '\n')) await once(out, 'drain');
|
|
309
|
+
}
|
|
310
|
+
out.end();
|
|
311
|
+
await once(out, 'finish');
|
|
312
|
+
if (changed) {
|
|
313
|
+
await fsp.rename(tmp, file);
|
|
314
|
+
await fsp.utimes(file, st.atime, st.mtime); // keep the original "last used" time
|
|
315
|
+
} else {
|
|
316
|
+
await fsp.unlink(tmp);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
async function moveSessions({ key, to, ids }) {
|
|
321
|
+
const p = await getProject(key);
|
|
322
|
+
if (p.source !== 'claude') throw new HttpError(400, 'Only Claude Code sessions are filed by folder, so only they can be moved.');
|
|
323
|
+
if (typeof to !== 'string' || !to.trim()) throw new HttpError(400, 'Choose a folder.');
|
|
324
|
+
const newCwd = path.resolve(expand(to.trim()));
|
|
325
|
+
if (!isDir(newCwd)) throw new HttpError(400, `Folder does not exist: ${newCwd}`);
|
|
326
|
+
const oldCwd = p.cwd;
|
|
327
|
+
const dstKey = encode(newCwd);
|
|
328
|
+
if (dstKey === key) throw new HttpError(400, 'These sessions already belong to that folder.');
|
|
329
|
+
|
|
330
|
+
const src = path.join(ROOT, key);
|
|
331
|
+
const dst = path.join(ROOT, dstKey);
|
|
332
|
+
let names;
|
|
333
|
+
if (Array.isArray(ids) && ids.length) {
|
|
334
|
+
const known = new Set(p.sessions.map((s) => s.id));
|
|
335
|
+
names = [];
|
|
336
|
+
for (const id of ids) {
|
|
337
|
+
if (!known.has(id)) throw new HttpError(400, `Unknown session: ${id}`);
|
|
338
|
+
names.push(`${id}.jsonl`);
|
|
339
|
+
if (exists(path.join(src, id))) names.push(id); // subagent and tool-result files
|
|
340
|
+
}
|
|
341
|
+
} else {
|
|
342
|
+
names = await fsp.readdir(src);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
|
|
346
|
+
const backup = path.join(BACKUP, `${key}__${stamp}`);
|
|
347
|
+
await fsp.mkdir(backup, { recursive: true });
|
|
348
|
+
for (const n of names) {
|
|
349
|
+
await fsp.cp(path.join(src, n), path.join(backup, n), { recursive: true, preserveTimestamps: true });
|
|
350
|
+
}
|
|
351
|
+
await fsp.writeFile(path.join(backup, 'backup.json'), JSON.stringify({
|
|
352
|
+
key, from: oldCwd, to: newCwd, toKey: dstKey, items: names, at: new Date().toISOString(),
|
|
353
|
+
}, null, 2));
|
|
354
|
+
|
|
355
|
+
await fsp.mkdir(dst, { recursive: true });
|
|
356
|
+
const moved = [];
|
|
357
|
+
const skipped = [];
|
|
358
|
+
for (const n of names) await mergeMove(path.join(src, n), path.join(dst, n), moved, skipped);
|
|
359
|
+
if (oldCwd) {
|
|
360
|
+
for (const m of moved) for (const f of await jsonlFiles(m)) await rewriteCwd(f, oldCwd, newCwd);
|
|
361
|
+
}
|
|
362
|
+
try { await fsp.rmdir(src); } catch { /* still holds other sessions */ }
|
|
363
|
+
|
|
364
|
+
return {
|
|
365
|
+
moved: names.filter((n) => n.endsWith('.jsonl') && !skipped.includes(path.join(key, n))).length,
|
|
366
|
+
skipped,
|
|
367
|
+
backup,
|
|
368
|
+
to: newCwd,
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
async function listBackups() {
|
|
373
|
+
if (!isDir(BACKUP)) return [];
|
|
374
|
+
const out = [];
|
|
375
|
+
for (const name of await fsp.readdir(BACKUP)) {
|
|
376
|
+
const dir = path.join(BACKUP, name);
|
|
377
|
+
if (!isDir(dir)) continue;
|
|
378
|
+
let meta = {};
|
|
379
|
+
try { meta = JSON.parse(await fsp.readFile(path.join(dir, 'backup.json'), 'utf8')); } catch { /* older backup */ }
|
|
380
|
+
const files = await fsp.readdir(dir);
|
|
381
|
+
out.push({
|
|
382
|
+
name,
|
|
383
|
+
key: meta.key || name.split('__')[0],
|
|
384
|
+
from: meta.from || '',
|
|
385
|
+
to: meta.to || '',
|
|
386
|
+
at: meta.at || (await fsp.stat(dir)).mtime.toISOString(),
|
|
387
|
+
sessions: files.filter((f) => f.endsWith('.jsonl')).length,
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
return out.sort((a, b) => b.at.localeCompare(a.at));
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
async function restoreBackup(name) {
|
|
394
|
+
if (typeof name !== 'string' || !/^[A-Za-z0-9_-]+$/.test(name) || !isDir(path.join(BACKUP, name))) {
|
|
395
|
+
throw new HttpError(404, 'Unknown backup.');
|
|
396
|
+
}
|
|
397
|
+
const b = (await listBackups()).find((x) => x.name === name);
|
|
398
|
+
const dst = path.join(ROOT, b.key);
|
|
399
|
+
const src = path.join(BACKUP, name);
|
|
400
|
+
await fsp.mkdir(dst, { recursive: true });
|
|
401
|
+
let restored = 0;
|
|
402
|
+
const skipped = [];
|
|
403
|
+
for (const n of await fsp.readdir(src)) {
|
|
404
|
+
if (n === 'backup.json') continue;
|
|
405
|
+
if (exists(path.join(dst, n))) { skipped.push(n); continue; }
|
|
406
|
+
await fsp.cp(path.join(src, n), path.join(dst, n), { recursive: true, preserveTimestamps: true });
|
|
407
|
+
if (n.endsWith('.jsonl')) restored++;
|
|
408
|
+
}
|
|
409
|
+
return { restored, skipped, to: dst };
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// ---------- open a terminal running `claude --resume` ----------
|
|
413
|
+
function which(cmd) {
|
|
414
|
+
for (const dir of (process.env.PATH || '').split(path.delimiter)) {
|
|
415
|
+
const f = path.join(dir, cmd);
|
|
416
|
+
try { fs.accessSync(f, fs.constants.X_OK); return f; } catch { /* keep looking */ }
|
|
417
|
+
}
|
|
418
|
+
return null;
|
|
419
|
+
}
|
|
420
|
+
const shq = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
421
|
+
|
|
422
|
+
function terminalCommand(cwd, command) {
|
|
423
|
+
const run = `${command}; exec "\${SHELL:-bash}"`;
|
|
424
|
+
if (process.platform === 'darwin') {
|
|
425
|
+
const script = `cd ${shq(cwd)} && ${command}`.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
|
|
426
|
+
return ['osascript', ['-e', `tell application "Terminal" to do script "${script}"`, '-e', 'tell application "Terminal" to activate']];
|
|
427
|
+
}
|
|
428
|
+
const wanted = process.env.CHATSHELF_TERMINAL || process.env.CSM_TERMINAL;
|
|
429
|
+
const options = {
|
|
430
|
+
'gnome-terminal': [`--working-directory=${cwd}`, '--', 'bash', '-lc', run],
|
|
431
|
+
ptyxis: ['--new-window', '--working-directory', cwd, '--', 'bash', '-lc', run],
|
|
432
|
+
konsole: ['--workdir', cwd, '-e', 'bash', '-lc', run],
|
|
433
|
+
kitty: ['--directory', cwd, 'bash', '-lc', run],
|
|
434
|
+
alacritty: ['--working-directory', cwd, '-e', 'bash', '-lc', run],
|
|
435
|
+
wezterm: ['start', '--cwd', cwd, '--', 'bash', '-lc', run],
|
|
436
|
+
'xfce4-terminal': [`--working-directory=${cwd}`, '-x', 'bash', '-lc', run],
|
|
437
|
+
xterm: ['-e', 'bash', '-lc', `cd ${shq(cwd)} && ${run}`],
|
|
438
|
+
};
|
|
439
|
+
const order = wanted ? [wanted] : ['gnome-terminal', 'ptyxis', 'konsole', 'kitty', 'alacritty', 'wezterm', 'xfce4-terminal', 'xterm'];
|
|
440
|
+
for (const name of order) if (options[name] && which(name)) return [name, options[name]];
|
|
441
|
+
return null;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
async function openTerminal({ key, id }) {
|
|
445
|
+
const p = await getProject(key);
|
|
446
|
+
const s = p.sessions.find((x) => x.id === id);
|
|
447
|
+
if (!s) throw new HttpError(404, 'Unknown session.');
|
|
448
|
+
if (!/^[A-Za-z0-9_-]+$/.test(id)) throw new HttpError(400, 'Bad session id.');
|
|
449
|
+
if (!p.exists) {
|
|
450
|
+
throw new HttpError(409, p.source === 'claude' ? 'The project folder no longer exists. Move this session to the new folder first.' : 'This chat has no project folder on this computer.');
|
|
451
|
+
}
|
|
452
|
+
// Editors: open the project folder in the app; the chat is in that app's own history.
|
|
453
|
+
const apps = { cursor: 'cursor', copilot: 'code' };
|
|
454
|
+
if (apps[p.source]) {
|
|
455
|
+
if (!which(apps[p.source])) throw new HttpError(501, `The "${apps[p.source]}" command isn't on your PATH.`);
|
|
456
|
+
spawn(apps[p.source], [p.cwd], { stdio: 'ignore', detached: true }).unref();
|
|
457
|
+
return { terminal: p.source === 'cursor' ? 'Cursor' : 'VS Code', app: true };
|
|
458
|
+
}
|
|
459
|
+
const clis = { claude: ['claude', `claude --resume ${id}`], codex: ['codex', `codex resume ${id}`], opencode: ['opencode', 'opencode'], gemini: ['gemini', 'gemini'] };
|
|
460
|
+
const cli = clis[p.source];
|
|
461
|
+
if (!cli) throw new HttpError(400, 'This chat can only be opened on the website.');
|
|
462
|
+
if (!which(cli[0])) throw new HttpError(501, `The "${cli[0]}" command isn't installed or isn't on your PATH. Copy the command instead.`);
|
|
463
|
+
const cmd = terminalCommand(p.cwd, cli[1]);
|
|
464
|
+
if (!cmd) throw new HttpError(501, 'No supported terminal found. Copy the command instead, or set CHATSHELF_TERMINAL.');
|
|
465
|
+
spawn(cmd[0], cmd[1], { cwd: p.cwd, stdio: 'ignore', detached: true }).unref();
|
|
466
|
+
return { terminal: path.basename(cmd[0]) };
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// ---------- bookmarks (one JSON file, written atomically) ----------
|
|
470
|
+
function readBookmarks() {
|
|
471
|
+
try { const v = JSON.parse(fs.readFileSync(BOOKMARKS, 'utf8')); return Array.isArray(v) ? v : []; } catch { return []; }
|
|
472
|
+
}
|
|
473
|
+
function writeBookmarks(list) {
|
|
474
|
+
fs.mkdirSync(DATA_DIR, { recursive: true });
|
|
475
|
+
const tmp = `${BOOKMARKS}.tmp`;
|
|
476
|
+
fs.writeFileSync(tmp, JSON.stringify(list, null, 2));
|
|
477
|
+
fs.renameSync(tmp, BOOKMARKS);
|
|
478
|
+
}
|
|
479
|
+
const str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : '');
|
|
480
|
+
const ID_RE = /^[A-Za-z0-9_.:-]{1,120}$/;
|
|
481
|
+
|
|
482
|
+
function saveBookmark(b) {
|
|
483
|
+
const kind = b.kind === 'chat' ? 'chat' : 'message';
|
|
484
|
+
if (!ID_RE.test(b.sessionId || '') || (kind === 'message' && !ID_RE.test(b.msgUuid || ''))) throw new HttpError(400, 'Bad bookmark.');
|
|
485
|
+
const list = readBookmarks();
|
|
486
|
+
const same = (x) => x.sessionId === b.sessionId && (kind === 'chat' ? x.kind === 'chat' : x.kind !== 'chat' && x.msgUuid === b.msgUuid);
|
|
487
|
+
let item = list.find(same);
|
|
488
|
+
if (!item) {
|
|
489
|
+
item = { id: crypto.randomUUID(), kind, sessionId: b.sessionId, createdAt: new Date().toISOString() };
|
|
490
|
+
if (kind === 'message') item.msgUuid = b.msgUuid;
|
|
491
|
+
list.push(item);
|
|
492
|
+
}
|
|
493
|
+
item.kind = kind;
|
|
494
|
+
// Only overwrite what the request actually sends, so a partial update never wipes a note.
|
|
495
|
+
const set = (k, max) => { if (typeof b[k] === 'string') item[k] = str(b[k], max); else if (item[k] === undefined) item[k] = ''; };
|
|
496
|
+
if (kind === 'message') {
|
|
497
|
+
if (b.role) item.role = b.role === 'assistant' ? 'assistant' : 'user';
|
|
498
|
+
else if (!item.role) item.role = 'user';
|
|
499
|
+
set('text', 600);
|
|
500
|
+
set('ts', 40);
|
|
501
|
+
}
|
|
502
|
+
set('title', 200);
|
|
503
|
+
set('cwd', 500);
|
|
504
|
+
set('note', 500);
|
|
505
|
+
item.updatedAt = new Date().toISOString();
|
|
506
|
+
writeBookmarks(list);
|
|
507
|
+
return { bookmark: item };
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
// ---------- read-only: bookmarks made with the Claude Code VS Code extension ----------
|
|
511
|
+
// The extension keeps one JSON file per session: { bookmarks: [{ uuid, addedAt }] }, where uuid is a
|
|
512
|
+
// transcript line id. We only read these files; the format belongs to the extension.
|
|
513
|
+
const EDITOR_BM_DIRS = (() => {
|
|
514
|
+
const bases = process.platform === 'darwin' ? [path.join(HOME, 'Library', 'Application Support')]
|
|
515
|
+
: process.platform === 'win32' ? [process.env.APPDATA || path.join(HOME, 'AppData', 'Roaming')]
|
|
516
|
+
: [process.env.XDG_CONFIG_HOME || path.join(HOME, '.config')];
|
|
517
|
+
const apps = { Code: 'VS Code', 'Code - Insiders': 'VS Code Insiders', VSCodium: 'VSCodium', Cursor: 'Cursor', Windsurf: 'Windsurf' };
|
|
518
|
+
return bases.flatMap((b) => Object.entries(apps).map(([dir, label]) => ({
|
|
519
|
+
label, dir: path.join(b, dir, 'User', 'globalStorage', 'anthropic.claude-code', 'session-bookmarks'),
|
|
520
|
+
})));
|
|
521
|
+
})();
|
|
522
|
+
const editorCache = new Map();
|
|
523
|
+
|
|
524
|
+
async function findSessionFile(id) {
|
|
525
|
+
for (const d of await fsp.readdir(ROOT)) {
|
|
526
|
+
const f = path.join(ROOT, d, `${id}.jsonl`);
|
|
527
|
+
if (exists(f)) return f;
|
|
528
|
+
}
|
|
529
|
+
return null;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
async function lookupLines(file, uuids) {
|
|
533
|
+
const want = new Set(uuids);
|
|
534
|
+
const found = new Map();
|
|
535
|
+
for await (const line of lines(file)) {
|
|
536
|
+
if (!want.size) break;
|
|
537
|
+
let hit = null;
|
|
538
|
+
for (const u of want) if (line.includes(u)) { hit = u; break; }
|
|
539
|
+
if (!hit) continue;
|
|
540
|
+
let o;
|
|
541
|
+
try { o = JSON.parse(line); } catch { continue; }
|
|
542
|
+
if (!o.uuid || !want.has(o.uuid)) continue;
|
|
543
|
+
const c = o.message && o.message.content;
|
|
544
|
+
let text = typeof c === 'string' ? c : Array.isArray(c) ? c.filter((x) => x.type === 'text').map((x) => x.text).join('\n') : '';
|
|
545
|
+
if (!text && Array.isArray(c)) text = c.filter((x) => x.type === 'tool_use').map((x) => x.name).join(', ');
|
|
546
|
+
found.set(o.uuid, { role: o.type === 'user' ? 'user' : 'assistant', text: text.replace(/\s+/g, ' ').trim().slice(0, 600), ts: o.timestamp || '' });
|
|
547
|
+
want.delete(o.uuid);
|
|
548
|
+
}
|
|
549
|
+
return found;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
async function readEditorBookmarks() {
|
|
553
|
+
const out = [];
|
|
554
|
+
for (const { label, dir } of EDITOR_BM_DIRS) {
|
|
555
|
+
let names;
|
|
556
|
+
try { names = await fsp.readdir(dir); } catch { continue; }
|
|
557
|
+
for (const n of names) {
|
|
558
|
+
const sid = n.slice(0, -5);
|
|
559
|
+
if (!n.endsWith('.json') || !ID_RE.test(sid)) continue;
|
|
560
|
+
const f = path.join(dir, n);
|
|
561
|
+
let st;
|
|
562
|
+
try { st = await fsp.stat(f); } catch { continue; }
|
|
563
|
+
const c = editorCache.get(f);
|
|
564
|
+
if (c && c.m === st.mtimeMs) { out.push(...c.items); continue; }
|
|
565
|
+
let data;
|
|
566
|
+
try { data = JSON.parse(await fsp.readFile(f, 'utf8')); } catch { continue; }
|
|
567
|
+
const marks = (Array.isArray(data.bookmarks) ? data.bookmarks : []).filter((b) => b && typeof b.uuid === 'string' && ID_RE.test(b.uuid));
|
|
568
|
+
const sf = marks.length ? await findSessionFile(sid) : null;
|
|
569
|
+
const found = sf ? await lookupLines(sf, marks.map((b) => b.uuid)) : new Map();
|
|
570
|
+
const items = marks.map((b) => {
|
|
571
|
+
const m = found.get(b.uuid) || {};
|
|
572
|
+
return {
|
|
573
|
+
id: `editor:${sid}:${b.uuid}`, kind: 'message', source: label, readOnly: true, sessionId: sid, msgUuid: b.uuid,
|
|
574
|
+
createdAt: new Date(Number(b.addedAt) || st.mtimeMs).toISOString(), role: m.role || 'assistant', text: m.text || '', ts: m.ts || '', note: '',
|
|
575
|
+
};
|
|
576
|
+
});
|
|
577
|
+
editorCache.set(f, { m: st.mtimeMs, items });
|
|
578
|
+
out.push(...items);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
return out;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function deleteBookmark(id) {
|
|
585
|
+
const list = readBookmarks();
|
|
586
|
+
const next = list.filter((x) => x.id !== id);
|
|
587
|
+
if (next.length === list.length) throw new HttpError(404, 'Unknown bookmark.');
|
|
588
|
+
writeBookmarks(next);
|
|
589
|
+
return { ok: true };
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// ---------- HTTP ----------
|
|
593
|
+
function send(res, status, body, type = 'application/json; charset=utf-8') {
|
|
594
|
+
const data = type.startsWith('application/json') ? JSON.stringify(body) : body;
|
|
595
|
+
res.writeHead(status, {
|
|
596
|
+
'Content-Type': type,
|
|
597
|
+
'Cache-Control': 'no-store',
|
|
598
|
+
'X-Content-Type-Options': 'nosniff',
|
|
599
|
+
'Referrer-Policy': 'no-referrer',
|
|
600
|
+
});
|
|
601
|
+
res.end(data);
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
async function readBody(req, max) {
|
|
605
|
+
const chunks = [];
|
|
606
|
+
let n = 0;
|
|
607
|
+
for await (const c of req) { n += c.length; if (n > max) throw new HttpError(413, 'That file is too large.'); chunks.push(c); }
|
|
608
|
+
return Buffer.concat(chunks);
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
async function sourceStatus() {
|
|
612
|
+
const claudeCount = (await scan()).filter((p) => p.source === 'claude').reduce((a, p) => a + p.sessions.length, 0);
|
|
613
|
+
const out = [{ id: 'claude', label: 'Claude Code', found: claudeCount > 0, path: ROOT, count: claudeCount }];
|
|
614
|
+
for (const r of READERS) {
|
|
615
|
+
try { out.push({ ...(await r.status()), note: toolErrors.get(r.id) || undefined }); } catch (e) { out.push({ id: r.id, label: r.label, found: false, count: 0, note: e.message }); }
|
|
616
|
+
}
|
|
617
|
+
return out;
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
async function readJson(req) {
|
|
621
|
+
if (!String(req.headers['content-type'] || '').startsWith('application/json')) throw new HttpError(415, 'Expected JSON.');
|
|
622
|
+
let raw = '';
|
|
623
|
+
for await (const chunk of req) { raw += chunk; if (raw.length > 1e6) throw new HttpError(413, 'Too large.'); }
|
|
624
|
+
try { return JSON.parse(raw || '{}'); } catch { throw new HttpError(400, 'Bad JSON.'); }
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
async function api(req, res, url) {
|
|
628
|
+
const route = `${req.method} ${url.pathname}`;
|
|
629
|
+
const q = url.searchParams;
|
|
630
|
+
switch (route) {
|
|
631
|
+
case 'GET /api/projects':
|
|
632
|
+
return send(res, 200, { projects: await scan(), root: ROOT, backupRoot: BACKUP, home: HOME });
|
|
633
|
+
case 'GET /api/session': {
|
|
634
|
+
const p = await getProject(q.get('key'));
|
|
635
|
+
const s = p.sessions.find((x) => x.id === q.get('id'));
|
|
636
|
+
if (!s) throw new HttpError(404, 'Unknown session.');
|
|
637
|
+
if (p.source === 'claude') return send(res, 200, { messages: await transcript(path.join(ROOT, p.key, `${s.id}.jsonl`)) });
|
|
638
|
+
const handle = refs.get(`${p.key}|${s.id}`);
|
|
639
|
+
if (!handle) throw new HttpError(404, 'Unknown session.');
|
|
640
|
+
return send(res, 200, { messages: await reader(handle.reader).transcript(handle.ref) });
|
|
641
|
+
}
|
|
642
|
+
case 'GET /api/suggest': {
|
|
643
|
+
const p = await getProject(q.get('key'));
|
|
644
|
+
if (p.source !== 'claude') return send(res, 200, { suggestions: [] });
|
|
645
|
+
const known = new Set((await scan()).map((x) => x.cwd));
|
|
646
|
+
return send(res, 200, { suggestions: p.cwd ? suggest(p.cwd, known) : [] });
|
|
647
|
+
}
|
|
648
|
+
case 'GET /api/dirs':
|
|
649
|
+
return send(res, 200, listDirs(q.get('path')));
|
|
650
|
+
case 'POST /api/move':
|
|
651
|
+
return send(res, 200, await moveSessions(await readJson(req)));
|
|
652
|
+
case 'POST /api/open-terminal':
|
|
653
|
+
return send(res, 200, await openTerminal(await readJson(req)));
|
|
654
|
+
case 'GET /api/bookmarks':
|
|
655
|
+
return send(res, 200, { bookmarks: readBookmarks(), external: await readEditorBookmarks() });
|
|
656
|
+
case 'POST /api/bookmarks':
|
|
657
|
+
return send(res, 200, saveBookmark(await readJson(req)));
|
|
658
|
+
case 'POST /api/bookmarks/delete':
|
|
659
|
+
return send(res, 200, deleteBookmark((await readJson(req)).id));
|
|
660
|
+
case 'GET /api/sources':
|
|
661
|
+
return send(res, 200, { sources: await sourceStatus() });
|
|
662
|
+
case 'POST /api/import': {
|
|
663
|
+
const buf = await readBody(req, 600 * 1024 * 1024);
|
|
664
|
+
try { return send(res, 200, await importExport(buf, String(req.headers['x-filename'] || ''))); } catch (e) { throw new HttpError(400, e.message); }
|
|
665
|
+
}
|
|
666
|
+
case 'POST /api/imports/delete': {
|
|
667
|
+
try { await removeImport((await readJson(req)).source); } catch (e) { throw new HttpError(400, e.message); }
|
|
668
|
+
return send(res, 200, { ok: true });
|
|
669
|
+
}
|
|
670
|
+
case 'GET /api/backups':
|
|
671
|
+
return send(res, 200, { backups: await listBackups() });
|
|
672
|
+
case 'POST /api/restore':
|
|
673
|
+
return send(res, 200, await restoreBackup((await readJson(req)).name));
|
|
674
|
+
default:
|
|
675
|
+
throw new HttpError(404, 'Not found.');
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
const STATIC = { '/': 'index.html', '/app.js': 'app.js', '/style.css': 'style.css' };
|
|
680
|
+
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8' };
|
|
681
|
+
|
|
682
|
+
const server = http.createServer(async (req, res) => {
|
|
683
|
+
try {
|
|
684
|
+
const host = req.headers.host;
|
|
685
|
+
if (!ALLOWED_HOSTS.has(host)) return send(res, 403, { error: 'Bad host.' });
|
|
686
|
+
const url = new URL(req.url, `http://${host}`);
|
|
687
|
+
if (url.pathname.startsWith('/api/')) {
|
|
688
|
+
if (req.headers['x-token'] !== TOKEN) return send(res, 403, { error: 'Session expired. Reload the page.' });
|
|
689
|
+
return await api(req, res, url);
|
|
690
|
+
}
|
|
691
|
+
const file = STATIC[url.pathname];
|
|
692
|
+
if (!file || req.method !== 'GET') return send(res, 404, 'Not found', 'text/plain; charset=utf-8');
|
|
693
|
+
let body = await fsp.readFile(path.join(PUBLIC, file), 'utf8');
|
|
694
|
+
if (file === 'index.html') body = body.replace('__TOKEN__', TOKEN);
|
|
695
|
+
return send(res, 200, body, TYPES[path.extname(file)]);
|
|
696
|
+
} catch (e) {
|
|
697
|
+
if (!(e instanceof HttpError)) console.error(e);
|
|
698
|
+
return send(res, e.status || 500, { error: e.message || 'Something went wrong.' });
|
|
699
|
+
}
|
|
700
|
+
});
|
|
701
|
+
|
|
702
|
+
// Browsers send any *.localhost name to this computer, so chatshelf.localhost needs no setup and,
|
|
703
|
+
// like 127.0.0.1, can never point anywhere else (which keeps the DNS-rebinding protection).
|
|
704
|
+
// Safari on macOS may not resolve *.localhost, so macOS opens 127.0.0.1; both always work.
|
|
705
|
+
const NICE_HOST = 'chatshelf.localhost';
|
|
706
|
+
const ALLOWED_HOSTS = new Set([`${HOST}:${PORT}`, `localhost:${PORT}`, `${NICE_HOST}:${PORT}`]);
|
|
707
|
+
const niceUrl = `http://${NICE_HOST}:${PORT}/`;
|
|
708
|
+
const ipUrl = `http://${HOST}:${PORT}/`;
|
|
709
|
+
const appUrl = process.platform === 'darwin' ? ipUrl : niceUrl;
|
|
710
|
+
const open = () => {
|
|
711
|
+
if (process.argv.includes('--no-open')) return;
|
|
712
|
+
const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'explorer' : 'xdg-open';
|
|
713
|
+
spawn(cmd, [appUrl], { stdio: 'ignore', detached: true }).unref();
|
|
714
|
+
};
|
|
715
|
+
|
|
716
|
+
server.on('error', (e) => {
|
|
717
|
+
if (e.code === 'EADDRINUSE') {
|
|
718
|
+
console.log(`Chatshelf is already running at ${appUrl}`);
|
|
719
|
+
open();
|
|
720
|
+
process.exit(0);
|
|
721
|
+
}
|
|
722
|
+
throw e;
|
|
723
|
+
});
|
|
724
|
+
|
|
725
|
+
server.listen(PORT, HOST, () => {
|
|
726
|
+
console.log(`Chatshelf is running at ${appUrl}`);
|
|
727
|
+
console.log(` also at ${appUrl === niceUrl ? ipUrl : niceUrl} (Ctrl+C to stop)`);
|
|
728
|
+
console.log(`Reading sessions from ${ROOT}`);
|
|
729
|
+
const t = Date.now();
|
|
730
|
+
scan().then((p) => console.log(`Indexed ${p.reduce((n, x) => n + x.sessions.length, 0)} sessions in ${Date.now() - t} ms`));
|
|
731
|
+
open();
|
|
732
|
+
});
|