@arshdelight/practi 0.18.0 → 0.19.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.
Files changed (71) hide show
  1. package/README.md +76 -136
  2. package/dist/client.js +6 -6
  3. package/dist/client.js.map +1 -1
  4. package/dist/cmd/blob.js +21 -24
  5. package/dist/cmd/blob.js.map +1 -1
  6. package/dist/cmd/branch.js +5 -7
  7. package/dist/cmd/branch.js.map +1 -1
  8. package/dist/cmd/clone.js +29 -23
  9. package/dist/cmd/clone.js.map +1 -1
  10. package/dist/cmd/commit.js +97 -0
  11. package/dist/cmd/commit.js.map +1 -0
  12. package/dist/cmd/config.js +1 -17
  13. package/dist/cmd/config.js.map +1 -1
  14. package/dist/cmd/edit.js +18 -4
  15. package/dist/cmd/edit.js.map +1 -1
  16. package/dist/cmd/embed.js +30 -25
  17. package/dist/cmd/embed.js.map +1 -1
  18. package/dist/cmd/export.js +43 -0
  19. package/dist/cmd/export.js.map +1 -0
  20. package/dist/cmd/fix.js +9 -153
  21. package/dist/cmd/fix.js.map +1 -1
  22. package/dist/cmd/gc.js +6 -5
  23. package/dist/cmd/gc.js.map +1 -1
  24. package/dist/cmd/history.js +73 -70
  25. package/dist/cmd/history.js.map +1 -1
  26. package/dist/cmd/init.js +10 -5
  27. package/dist/cmd/init.js.map +1 -1
  28. package/dist/cmd/lint.js +23 -20
  29. package/dist/cmd/lint.js.map +1 -1
  30. package/dist/cmd/log.js +2 -4
  31. package/dist/cmd/log.js.map +1 -1
  32. package/dist/cmd/merge.js +13 -10
  33. package/dist/cmd/merge.js.map +1 -1
  34. package/dist/cmd/new.js +56 -54
  35. package/dist/cmd/new.js.map +1 -1
  36. package/dist/cmd/note.js +27 -42
  37. package/dist/cmd/note.js.map +1 -1
  38. package/dist/cmd/pull.js +17 -13
  39. package/dist/cmd/pull.js.map +1 -1
  40. package/dist/cmd/push.js +27 -12
  41. package/dist/cmd/push.js.map +1 -1
  42. package/dist/cmd/search.js +30 -44
  43. package/dist/cmd/search.js.map +1 -1
  44. package/dist/cmd/show.js +5 -4
  45. package/dist/cmd/show.js.map +1 -1
  46. package/dist/cmd/similar.js +7 -20
  47. package/dist/cmd/similar.js.map +1 -1
  48. package/dist/cmd/skill.js +16 -16
  49. package/dist/cmd/skill.js.map +1 -1
  50. package/dist/cmd/switch.js +11 -6
  51. package/dist/cmd/switch.js.map +1 -1
  52. package/dist/index.js +243 -447
  53. package/dist/index.js.map +1 -1
  54. package/dist/practice.js +120 -97
  55. package/dist/practice.js.map +1 -1
  56. package/dist/quality.js +2 -2
  57. package/dist/quality.js.map +1 -1
  58. package/dist/state.js +13 -73
  59. package/dist/state.js.map +1 -1
  60. package/dist/sync.js +6 -48
  61. package/dist/sync.js.map +1 -1
  62. package/dist/web.js +156 -492
  63. package/dist/web.js.map +1 -1
  64. package/dist/workspace.js +10 -52
  65. package/dist/workspace.js.map +1 -1
  66. package/package.json +1 -1
  67. package/skills/use-practi/SKILL.md +121 -125
  68. package/web-default/chain.html +39 -0
  69. package/web-default/chain.js +54 -0
  70. package/web-default/app.js +0 -132
  71. package/web-default/index.html +0 -28
package/dist/web.js CHANGED
@@ -3,16 +3,11 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { spawn } from 'node:child_process';
6
- import { aggregateView, computeNodeHash, exportSubtree, readBlob, resolveNodeRef, PracticeError } from '@arshdelight/pop-sdk';
7
- import { defaultDataDir, loadState } from './state.js';
8
- import { listRegistryPractices } from './practice.js';
9
- import { nodeFileTime, openWorkspace } from './workspace.js';
10
- import { loadNotes, subtreeHashes, insertNote, updateNote, removeNote, NOTES_FILE } from './notes.js';
11
- import { runNew } from './cmd/new.js';
6
+ import { aggregateView, computeNodeHash, exportSubtree, readBlob, resolveNodeRef } from '@arshdelight/pop-sdk';
7
+ import { openPool, resolveRepo } from './practice.js';
8
+ import { loadNotes, insertNote, updateNote, removeNote } from './notes.js';
12
9
  /** 内置默认前端(随包分发的普通文件):dist/../web-default 与 src/../web-default 都指向 cli/web-default */
13
10
  const DEFAULT_WEB_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'web-default');
14
- /** workspace 里的覆盖目录名:里面的文件按文件级覆盖默认前端(不存在的文件回落默认) */
15
- const WEB_OVERRIDE_DIR = 'web';
16
11
  const STATIC_TYPES = {
17
12
  '.html': 'text/html; charset=utf-8',
18
13
  '.css': 'text/css; charset=utf-8',
@@ -23,300 +18,173 @@ const STATIC_TYPES = {
23
18
  '.png': 'image/png',
24
19
  '.ico': 'image/x-icon',
25
20
  };
26
- /** live reload 客户端:连 SSE,收到 reload 整页刷新(只读页面无状态,整刷即热更);
27
- * 收到 notes(笔记文件变更,服务器侧已不对其整刷)转发为 DOM 事件,详情页自行局部更新 */
28
- const LR_SCRIPT = "(function(){var es=new EventSource('/_lr');es.addEventListener('reload',function(){location.reload()});es.addEventListener('notes',function(){document.dispatchEvent(new CustomEvent('practi:notes'))});})();";
29
- function injectLiveReload(html) {
30
- const tag = '<script src="/_lr.js" defer></script>';
31
- return /<\/body>/i.test(html) ? html.replace(/<\/body>/i, `${tag}</body>`) : html + tag;
32
- }
33
21
  export function runWeb(opts) {
34
- const dataDir = opts.dataDir ?? defaultDataDir();
35
- // validate the data dir up front so a typo fails fast instead of on first request
36
- openWorkspace(dataDir);
22
+ const repo = resolveRepo({ dir: opts.dir, verb: 'web' });
23
+ if (repo === null)
24
+ return 1;
37
25
  const url = `http://127.0.0.1:${opts.port}/`;
38
- // live reload:SSE 客户端池 + 文件/数据监听。监听面 = 整个 data dir(nodes/、
39
- // 覆盖目录 web/、practi.json 全覆盖:另一终端 practi new 页面也会自动跟新)
40
- // + 内置默认前端目录(CLI 开发期改默认文件也即时生效)
41
- const clients = new Set();
42
- watchLive([dataDir, DEFAULT_WEB_DIR], clients);
43
- const overrideDir = path.join(dataDir, WEB_OVERRIDE_DIR);
44
- console.log(`frontend: ${fs.existsSync(overrideDir) ? `workspace override ${overrideDir} (missing files fall back to built-in)` : `built-in default (drop files into ${overrideDir}${path.sep} to customize)`}`);
45
26
  const server = http.createServer((req, res) => {
46
- try {
47
- // ws 每请求重建:命令写入(本端点的 /api/run,或另一终端的 practi new)
48
- // 必须立即可见,不能拿启动时的快照过滤数据窗
49
- handle(req, res, dataDir, openWorkspace(dataDir), clients);
50
- }
51
- catch (e) {
52
- if (e instanceof PracticeError) {
53
- send(res, 404, 'text/plain; charset=utf-8', `${e.code}: ${e.message}`);
54
- }
55
- else {
56
- res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
57
- res.end(e instanceof Error ? e.message : String(e));
58
- }
59
- }
60
- });
61
- // 端口占用是常人操作(重复开 practi web),不该甩 Node 堆栈——给出人话 + 出路
62
- server.on('error', (e) => {
63
- if (e.code !== 'EADDRINUSE')
64
- throw e;
65
- console.error(`port ${opts.port} is already in use.`);
66
- http.get({ host: '127.0.0.1', port: opts.port, path: '/healthz', timeout: 1000 }, r => {
67
- const chunks = [];
68
- r.on('data', c => void chunks.push(c));
69
- r.on('end', () => {
70
- if (Buffer.concat(chunks).toString('utf8') === 'ok') {
71
- console.error('it looks like another practi web is already serving there.');
72
- console.error(`open ${url} directly, or start on a different port: practi web --port <other>`);
73
- }
74
- else {
75
- console.error('something else occupies it — try: practi web --port <other>');
76
- }
77
- });
78
- }).on('error', () => {
79
- console.error('something else occupies it — try: practi web --port <other>');
80
- }).on('timeout', function () {
81
- this.destroy();
82
- console.error('something else occupies it — try: practi web --port <other>');
83
- });
84
- setTimeout(() => process.exit(1), 1500);
27
+ void handle(req, res, repo);
85
28
  });
86
29
  server.listen(opts.port, '127.0.0.1', () => {
87
- console.log(`practi web: ${url}`);
88
- console.log(`data dir: ${dataDir}`);
89
- console.log('press Ctrl-C to stop');
30
+ console.log(`practi web — ${repo.chain.name}@${repo.chain.current} → ${url}`);
31
+ console.log('Ctrl+C to stop');
90
32
  if (opts.open)
91
33
  openBrowser(url);
92
34
  });
93
35
  return 0;
94
36
  }
95
- function handle(req, res, dataDir, ws, clients) {
96
- const pathname = (req.url ?? '/').split('?')[0];
97
- const state = loadState(dataDir);
98
- if (pathname === '/_lr') {
99
- sseHandshake(req, res, clients);
100
- return;
101
- }
102
- if (pathname === '/_lr.js') {
103
- send(res, 200, 'text/javascript; charset=utf-8', LR_SCRIPT);
104
- return;
105
- }
106
- if (pathname === '/api/practices') {
107
- const practices = listRegistryPractices(dataDir).map(function (r) {
108
- const head = r.chain.branches[r.chain.current] ?? null;
109
- return {
110
- name: r.chain.name,
111
- owner: r.chain.owner,
112
- branch: r.chain.current,
113
- head: head,
114
- commits: r.chain.commits.length,
115
- unpushed: r.chain.commits.filter(function (c) { return !c.pushedAt; }).length,
116
- };
117
- });
118
- send(res, 200, 'application/json; charset=utf-8', JSON.stringify({ practices: practices }, null, 2));
119
- return;
120
- }
121
- if (pathname === '/api/directs') {
122
- send(res, 200, 'application/json; charset=utf-8', JSON.stringify(directsPayload(dataDir, ws, state), null, 2));
123
- return;
124
- }
125
- if (pathname === '/api/notes') {
126
- if (req.method === 'POST')
127
- void handleNoteWrite(req, res, dataDir, ws);
128
- else
129
- notesRoute(req, res, dataDir, ws);
130
- return;
131
- }
132
- if (pathname === '/api/run') {
133
- void handleRun(req, res, dataDir);
134
- return;
37
+ /** 打开系统默认浏览器(oauth 登录流程共用);失败静默——URL 已打印在终端 */
38
+ export function openBrowser(url) {
39
+ const opener = process.platform === 'win32' ? 'cmd' : process.platform === 'darwin' ? 'open' : 'xdg-open';
40
+ const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
41
+ try {
42
+ const child = spawn(opener, args, { stdio: 'ignore', detached: true });
43
+ child.on('error', () => console.log(`open this in your browser: ${url}`));
44
+ child.unref();
135
45
  }
136
- if (pathname === '/' || pathname === '/index.html') {
137
- if (serveStatic(res, 'index.html', dataDir))
138
- return;
139
- send(res, 500, 'text/plain; charset=utf-8', 'built-in web frontend missing — reinstall the CLI');
140
- return;
46
+ catch {
47
+ console.log(`open this in your browser: ${url}`);
141
48
  }
142
- // practice 详情:链 JSON(/practice/<name>.json)与提交历史页(/practice/<name>)
143
- const practice = pathname.match(/^\/practice\/([^/]+?)(\.json)?$/);
144
- if (practice) {
145
- const name = decodeURIComponent(practice[1]);
146
- const repo = listRegistryPractices(dataDir).find((r) => r.chain.name === name);
147
- if (!repo) {
148
- send(res, 404, 'application/json; charset=utf-8', JSON.stringify({ error: 'no such practice' }));
49
+ }
50
+ async function handle(req, res, repo) {
51
+ const pathname = decodeURIComponent(new URL(req.url ?? '/', 'http://x').pathname);
52
+ try {
53
+ if (pathname === '/api/repo') {
54
+ const branch = new URL(req.url ?? '/', 'http://x').searchParams.get('branch') ?? repo.chain.current;
55
+ const head = repo.chain.branches[branch] ?? null;
56
+ const byRoot = new Map(repo.chain.commits.map((c) => [c.root, c]));
57
+ const commits = [];
58
+ const seen = new Set();
59
+ let cur = head;
60
+ while (cur !== null && !seen.has(cur)) {
61
+ const c = byRoot.get(cur);
62
+ if (!c)
63
+ break;
64
+ seen.add(cur);
65
+ commits.push({ seq: c.seq, root: c.root, message: c.message, pushedAt: c.pushedAt ?? null });
66
+ cur = c.parent;
67
+ }
68
+ send(res, 200, 'application/json; charset=utf-8', JSON.stringify({
69
+ name: repo.chain.name,
70
+ owner: repo.chain.owner,
71
+ current: repo.chain.current,
72
+ branches: Object.entries(repo.chain.branches).map(([name, r]) => ({
73
+ name,
74
+ head: r,
75
+ isDefault: name === 'main',
76
+ current: name === repo.chain.current,
77
+ })),
78
+ branch,
79
+ head,
80
+ commits,
81
+ }, null, 2));
149
82
  return;
150
83
  }
151
- const rows = repo.chain.commits.slice().reverse().map((c) => ({
152
- seq: c.seq,
153
- root_hash: c.root,
154
- parent_hash: c.parent,
155
- message: c.message,
156
- pushed: c.pushedAt !== undefined,
157
- }));
158
- if (practice[2] === '.json') {
159
- send(res, 200, 'application/json; charset=utf-8', JSON.stringify({ name, owner: repo.chain.owner, branch: repo.chain.current, revisions: rows }, null, 2));
84
+ if (pathname === '/api/notes') {
85
+ if (req.method === 'POST') {
86
+ await handleNoteWrite(req, res, repo.poolDir);
87
+ }
88
+ else {
89
+ notesRoute(req, res, repo.poolDir);
90
+ }
160
91
  return;
161
92
  }
162
- const table = rows
163
- .map((r) => {
164
- const mark = r.root_hash === repo.chain.branches[repo.chain.current] ? ' ●' : '';
165
- return ('<tr><td>v' + r.seq + '</td><td><a class="doc-name" href="/pop/' + encodeURIComponent(r.root_hash) + '">' +
166
- r.root_hash.slice(7, 19) + '</a>' + mark + '</td><td>' +
167
- String(r.message).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]) + '</td><td>' + (r.pushed ? 'synced' : 'local') + '</td></tr>');
168
- })
169
- .join('\n');
170
- const owner = repo.chain.owner ? repo.chain.owner + '/' + name : name + ' (local only)';
171
- send(res, 200, 'text/html; charset=utf-8', '<!doctype html><html lang="en"><head><meta charset="utf-8"><title>' + name + ' — Practi</title>' +
172
- '<link rel="stylesheet" href="/style.css"></head><body><header><a class="brand-link" href="/"><span class="brand">practi</span></a></header>' +
173
- '<main id="app"><h3 class="page-title">' + owner + ' @ ' + repo.chain.current + '</h3>' +
174
- '<table class="doc-table"><thead><tr><th>Seq</th><th>Root</th><th>Message</th><th>Sync</th></tr></thead><tbody>' +
175
- table +
176
- '</tbody></table></main></body></html>');
177
- return;
178
- }
179
- const pop = pathname.match(/^\/pop\/(.+)$/);
180
- if (pop) {
181
- const hash = decodeURIComponent(pop[1]).replace(/\.json$/, '');
182
- const resolved = resolveNodeRef(ws, hash);
183
- if (pathname.endsWith('.json')) {
184
- const view = aggregateView(resolved, ws.nodes);
185
- send(res, 200, 'application/json; charset=utf-8', JSON.stringify(view, null, 2));
93
+ if (pathname === '/' || pathname === '/index.html') {
94
+ serveStatic(res, 'chain.html');
186
95
  return;
187
96
  }
188
- if (!serveStatic(res, 'detail.html', dataDir)) {
189
- send(res, 500, 'text/plain; charset=utf-8', 'built-in web frontend missing — reinstall the CLI');
97
+ const pop = pathname.match(/^\/pop\/(.+)$/);
98
+ if (pop) {
99
+ const hash = pop[1].replace(/\.json$/, '');
100
+ const ws = openPool(repo);
101
+ const resolved = resolveNodeRef(ws, hash);
102
+ if (pathname.endsWith('.json')) {
103
+ const view = aggregateView(resolved, ws.nodes, { full: true });
104
+ send(res, 200, 'application/json; charset=utf-8', JSON.stringify(view, null, 2));
105
+ return;
106
+ }
107
+ serveStatic(res, 'detail.html');
108
+ return;
190
109
  }
191
- return;
192
- }
193
- const blob = pathname.match(/^\/blobs\/(sha256:[0-9a-f]{64})$/);
194
- if (blob) {
195
- const bytes = readBlob(ws.root, blob[1]);
196
- if (bytes === null) {
197
- send(res, 404, 'text/plain; charset=utf-8', 'E_BLOB_MISSING: blob not present in this workspace');
110
+ const doc = pathname.match(/^\/doc\/(.+)$/);
111
+ if (doc) {
112
+ const hash = doc[1].replace(/\.json$/, '');
113
+ const ws = openPool(repo);
114
+ const node = ws.nodes.get(resolveNodeRef(ws, hash));
115
+ if (!node) {
116
+ send(res, 404, 'application/json; charset=utf-8', JSON.stringify({ error: 'node not found' }));
117
+ return;
118
+ }
119
+ const document = exportSubtree(node, ws.nodes);
120
+ // 加法演进:树字段在顶层(老前端照常读),nodeIndex 是新增兄弟键(前端把
121
+ // inputs.from 反解成 #编号引用用——哈希不在树里,引用靠旁路登记)
122
+ send(res, 200, 'application/json; charset=utf-8', JSON.stringify({ ...document, nodeIndex: buildNodeIndex(document) }, null, 2));
198
123
  return;
199
124
  }
200
- sendBytes(res, mimeFor(ws, blob[1]), bytes);
201
- return;
202
- }
203
- const doc = pathname.match(/^\/doc\/(.+)$/);
204
- if (doc) {
205
- const hash = decodeURIComponent(doc[1]).replace(/\.json$/, '');
206
- const node = ws.nodes.get(resolveNodeRef(ws, hash));
207
- if (node) {
208
- // 加法演进:树字段仍在顶层(老前端照常读),nodeIndex 是新增兄弟键(新前端才消费)。
209
- // 前端文件热更可能跑在服务器 dist 前面、用户覆盖的 web/ 也可能落后 CLI 升级——
210
- // 数据窗任何改动都必须新旧两端互容,不能用信封换结构
211
- const tree = exportSubtree(node, ws.nodes);
212
- send(res, 200, 'application/json; charset=utf-8', JSON.stringify({ ...tree, nodeIndex: buildNodeIndex(tree) }, null, 2));
125
+ const blob = pathname.match(/^\/blobs\/(sha256:[0-9a-f]{64})$/);
126
+ if (blob) {
127
+ const ws = openPool(repo);
128
+ const bytes = readBlob(ws.root, blob[1]);
129
+ if (bytes === null) {
130
+ send(res, 404, 'text/plain; charset=utf-8', 'E_BLOB_MISSING: blob not present in this practice');
131
+ return;
132
+ }
133
+ sendBytes(res, mimeFor(bytes), bytes);
213
134
  return;
214
135
  }
136
+ if (serveStatic(res, pathname.slice(1)))
137
+ return;
138
+ send(res, 404, 'text/plain; charset=utf-8', 'not found');
215
139
  }
216
- if (pathname === '/healthz') {
217
- send(res, 200, 'text/plain', 'ok');
218
- return;
219
- }
220
- // 静态资产兜底(style.css / app.js / 自定义前端文件):放在最后,不与 /pop /blobs /doc 抢路由
221
- if (serveStatic(res, pathname.slice(1), dataDir))
222
- return;
223
- send(res, 404, 'text/plain; charset=utf-8', 'not found');
224
- }
225
- class ApiError extends Error {
226
- status;
227
- constructor(status, message) {
228
- super(message);
229
- this.status = status;
230
- }
231
- }
232
- function asStr(v) {
233
- if (v !== undefined && typeof v !== 'string')
234
- throw new ApiError(400, 'string argument expected');
235
- return v;
236
- }
237
- const RUNNABLE = {
238
- new: {
239
- run: (a, d) => {
240
- const json = asStr(a.json);
241
- if (!json || !json.trim())
242
- throw new ApiError(400, 'new requires args.json (POP document text)');
243
- return runNew({ dataDir: d, json, positional: [] });
244
- },
245
- },
246
- };
247
- /** 命令输出捕获:命令函数走 console.log/error,调用期间临时替换收集,finally 恢复。
248
- * 进程级替换在并发下有竞态 → runQueue 互斥,同一时刻只跑一条命令(写操作本就不应并发) */
249
- let runQueue = Promise.resolve();
250
- function enqueueRun(fn) {
251
- const next = runQueue.then(fn, fn);
252
- runQueue = next.catch(() => { });
253
- return next;
254
- }
255
- async function captureConsole(fn) {
256
- const out = [];
257
- const errBuf = [];
258
- const origLog = console.log;
259
- const origErr = console.error;
260
- console.log = (...a) => void out.push(a.join(' '));
261
- console.error = (...a) => void errBuf.push(a.join(' '));
262
- try {
263
- return { code: await fn(), out: out.join('\n'), err: errBuf.join('\n') };
264
- }
265
- finally {
266
- console.log = origLog;
267
- console.error = origErr;
140
+ catch (e) {
141
+ send(res, 500, 'text/plain; charset=utf-8', e instanceof Error ? e.message : String(e));
268
142
  }
269
143
  }
270
- /** 安全闸:浏览器跨站 POST 必带 Origin;Origin 的 host 必须等于请求的 Host 头
271
- * (即 127.0.0.1:port 本身),否则 403——挡 CSRF 与 DNS rebinding */
272
- function sameOrigin(req) {
273
- const origin = req.headers.origin;
274
- const host = req.headers.host;
275
- if (typeof origin !== 'string' || typeof host !== 'string')
276
- return false;
277
- try {
278
- return new URL(origin).host === host;
279
- }
280
- catch {
281
- return false;
144
+ // ── 学习笔记(/api/notes,sidecar .practi/notes.json;GET 按哈希分组、?ref= 过滤;POST add/update/delete)──
145
+ function notesRoute(req, res, poolDir) {
146
+ const ref = new URL(req.url ?? '/', 'http://x').searchParams.get('ref') ?? undefined;
147
+ const byHash = {};
148
+ for (const n of loadNotes(poolDir).notes) {
149
+ if (ref !== undefined && n.hash !== ref)
150
+ continue;
151
+ (byHash[n.hash] ??= []).push(n);
282
152
  }
153
+ send(res, 200, 'application/json; charset=utf-8', JSON.stringify(byHash, null, 2));
283
154
  }
284
- async function handleRun(req, res, dataDir) {
155
+ async function handleNoteWrite(req, res, poolDir) {
285
156
  const fail = (status, message) => send(res, status, 'application/json; charset=utf-8', JSON.stringify({ error: message }));
286
157
  try {
287
158
  if (req.method !== 'POST')
288
- throw new ApiError(405, 'POST only');
289
- if (!sameOrigin(req))
290
- throw new ApiError(403, 'same-origin POST required (Origin header missing or foreign)');
291
- const ctype = String(req.headers['content-type'] ?? '');
292
- if (!ctype.startsWith('application/json'))
293
- throw new ApiError(415, 'content-type must be application/json');
294
- const body = await readBody(req, 2 * 1024 * 1024);
295
- let parsed;
296
- try {
297
- parsed = JSON.parse(body);
159
+ throw new Error('POST only');
160
+ const origin = req.headers.origin;
161
+ const host = req.headers.host;
162
+ if (typeof origin !== 'string' || typeof host !== 'string' || new URL(origin).host !== host) {
163
+ throw new Error('same-origin POST required');
164
+ }
165
+ const body = JSON.parse(await readBody(req, 1024 * 1024));
166
+ // 口径与 CLI 对齐:文本非空(trim 后),update/delete 的未知 id/歧义前缀如实 400
167
+ const fail = (m) => { throw new Error(m); };
168
+ if (body.op === 'add' && typeof body.hash === 'string' && typeof body.text === 'string' && body.text.trim() !== '') {
169
+ insertNote(poolDir, body.hash, body.text);
298
170
  }
299
- catch {
300
- throw new ApiError(400, 'request body is not valid JSON');
171
+ else if (body.op === 'update' && typeof body.id === 'string' && typeof body.text === 'string' && body.text.trim() !== '') {
172
+ const m = updateNote(poolDir, body.id, body.text);
173
+ if (!m.ok)
174
+ fail(m.reason === 'ambiguous' ? `ambiguous note id: ${body.id}` : 'no such note');
301
175
  }
302
- const spec = typeof parsed.cmd === 'string' ? RUNNABLE[parsed.cmd] : undefined;
303
- if (!spec)
304
- throw new ApiError(400, `unknown cmd — runnable: ${Object.keys(RUNNABLE).join(', ')}`);
305
- const args = parsed.args ?? {};
306
- const result = await enqueueRun(() => captureConsole(() => spec.run(args, dataDir)).catch(e => {
307
- // 参数校验错误透传为 4xx;命令自身的异常对齐 CLI 顶层语义(打印 + 退出码 1),
308
- // 命令失败是结果不是服务器错误,不该是 500
309
- if (e instanceof ApiError)
310
- throw e;
311
- return { code: 1, out: '', err: e instanceof Error ? e.message : String(e) };
312
- }));
313
- send(res, 200, 'application/json; charset=utf-8', JSON.stringify(result));
176
+ else if (body.op === 'delete' && typeof body.id === 'string') {
177
+ const m = removeNote(poolDir, body.id);
178
+ if (!m.ok)
179
+ fail(m.reason === 'ambiguous' ? `ambiguous note id: ${body.id}` : 'no such note');
180
+ }
181
+ else {
182
+ throw new Error('op must be add{hash,text} / update{id,text} / delete{id} (text must be non-empty)');
183
+ }
184
+ send(res, 200, 'application/json; charset=utf-8', JSON.stringify({ ok: true }));
314
185
  }
315
186
  catch (e) {
316
- if (e instanceof ApiError)
317
- fail(e.status, e.message);
318
- else
319
- fail(500, e instanceof Error ? e.message : String(e));
187
+ fail(400, e instanceof Error ? e.message : String(e));
320
188
  }
321
189
  }
322
190
  async function readBody(req, limit) {
@@ -326,7 +194,7 @@ async function readBody(req, limit) {
326
194
  req.on('data', (c) => {
327
195
  size += c.length;
328
196
  if (size > limit) {
329
- reject(new ApiError(413, 'request body too large'));
197
+ reject(new Error('request body too large'));
330
198
  req.destroy();
331
199
  return;
332
200
  }
@@ -337,8 +205,7 @@ async function readBody(req, limit) {
337
205
  });
338
206
  }
339
207
  /** 节点指纹登记簿(哈希→树内 children 下标路径),/doc 数据窗附带:前端把 inputs.from
340
- * 反解成 #编号引用用。与物化索引同一思路——内容寻址下哈希不在树里,
341
- * 引用靠旁路登记。根(空路径)不成节、无编号,不登记(from 指向根按未命中回落哈希)。 */
208
+ * 反解成 #编号引用用。根(空路径)不成节、无编号,不登记。 */
342
209
  function buildNodeIndex(tree) {
343
210
  const index = {};
344
211
  const visit = (n, p) => {
@@ -350,234 +217,31 @@ function buildNodeIndex(tree) {
350
217
  visit(tree, []);
351
218
  return index;
352
219
  }
353
- function send(res, code, type, body) {
354
- res.writeHead(code, { 'content-type': type });
355
- res.end(body);
356
- }
357
- /** 静态文件:workspace 的 web/ 按文件覆盖,缺失文件回落内置默认。
358
- * 拒绝 `..` 段做路径遍历防护;HTML 响应注入 live reload 脚本(对默认与自定义前端一视同仁) */
359
- function serveStatic(res, rel, dataDir) {
360
- const parts = rel.split('/').filter(Boolean);
361
- if (parts.length === 0 || parts.includes('..'))
362
- return false;
363
- const file = [path.join(dataDir, WEB_OVERRIDE_DIR, ...parts), path.join(DEFAULT_WEB_DIR, ...parts)]
364
- .find(f => fs.existsSync(f) && fs.statSync(f).isFile());
365
- if (!file)
220
+ function serveStatic(res, rel) {
221
+ const file = path.join(DEFAULT_WEB_DIR, rel);
222
+ if (!file.startsWith(DEFAULT_WEB_DIR) || !fs.existsSync(file) || !fs.statSync(file).isFile())
366
223
  return false;
367
- const type = STATIC_TYPES[path.extname(file).toLowerCase()] ?? 'application/octet-stream';
368
- const body = fs.readFileSync(file);
369
- res.writeHead(200, { 'content-type': type, 'cache-control': 'no-cache' });
370
- if (type.startsWith('text/html')) {
371
- res.end(injectLiveReload(body.toString('utf8')));
372
- }
373
- else {
374
- res.end(body);
375
- }
224
+ const type = STATIC_TYPES[path.extname(file)] ?? 'application/octet-stream';
225
+ sendBytes(res, type, fs.readFileSync(file));
376
226
  return true;
377
227
  }
378
- /** 目录数据窗:direct 列表的名称/描述/统计 + 数据目录路径(前端头部展示用)。
379
- * claimedAt=声明值(state.claims 盖戳);addedAt=生效值,未盖戳的老数据回落节点文件
380
- * mtime(推测值,前端弱化显示)——声明与推测不混装一个字段 */
381
- function directsPayload(dataDir, ws, state) {
382
- const docs = state.direct
383
- .filter(h => ws.nodes.has(h))
384
- .map(h => {
385
- const v = aggregateView(h, ws.nodes);
386
- const claimedAt = state.claims?.[h] ?? null;
387
- return {
388
- hash: v.hash,
389
- name: v.name,
390
- description: v.description,
391
- type: v.type,
392
- op: v.type === 'practice' ? v.op : null,
393
- steps: v.steps.length,
394
- // 全树节点数(含根,=详情页侧栏 countNodes 口径);steps 保留给既有消费者(加法演进)
395
- nodes: subtreeHashes(ws, h).size,
396
- outputs: v.outputs.length,
397
- claimedAt,
398
- addedAt: claimedAt ?? nodeFileTime(dataDir, h),
399
- };
400
- });
401
- return { dataDir, docs };
402
- }
403
- /** POST /api/notes:note 的第二个写入门(官方前端侧栏编辑用;CLI practi note 仍是第一门)。
404
- * 本地个人数据,无审核诉求,但 CSRF 闸与 /api/run 同规格(sameOrigin + application/json)。
405
- * body={op:'add',hash,content} | {op:'edit',id,content} | {op:'delete',id}。 */
406
- async function handleNoteWrite(req, res, dataDir, ws) {
407
- const fail = (status, message) => send(res, status, 'application/json; charset=utf-8', JSON.stringify({ error: message }));
408
- try {
409
- if (req.method !== 'POST')
410
- throw new ApiError(405, 'POST only');
411
- if (!sameOrigin(req))
412
- throw new ApiError(403, 'same-origin POST required (Origin header missing or foreign)');
413
- const ctype = String(req.headers['content-type'] ?? '');
414
- if (!ctype.startsWith('application/json'))
415
- throw new ApiError(415, 'content-type must be application/json');
416
- const body = await readBody(req, 256 * 1024);
417
- let parsed;
418
- try {
419
- parsed = JSON.parse(body);
420
- }
421
- catch {
422
- throw new ApiError(400, 'request body is not valid JSON');
423
- }
424
- const content = typeof parsed.content === 'string' ? parsed.content : '';
425
- const okBody = (note) => send(res, 200, 'application/json; charset=utf-8', JSON.stringify({ note }, null, 2));
426
- switch (parsed.op) {
427
- case 'add': {
428
- if (!content.trim())
429
- throw new ApiError(400, 'content required');
430
- const ref = typeof parsed.hash === 'string' ? parsed.hash : '';
431
- let hash;
432
- try {
433
- hash = resolveNodeRef(ws, ref);
434
- }
435
- catch (e) {
436
- throw new ApiError(404, e instanceof PracticeError ? `${e.code}: ${e.message}` : String(e));
437
- }
438
- return void okBody(insertNote(dataDir, hash, content));
439
- }
440
- case 'edit': {
441
- if (!content.trim())
442
- throw new ApiError(400, 'content required');
443
- const id = typeof parsed.id === 'string' ? parsed.id : '';
444
- const m = updateNote(dataDir, id, content);
445
- if (!m.ok)
446
- throw mutationError(id, m);
447
- return void okBody(m.note);
448
- }
449
- case 'delete': {
450
- const id = typeof parsed.id === 'string' ? parsed.id : '';
451
- const m = removeNote(dataDir, id);
452
- if (!m.ok)
453
- throw mutationError(id, m);
454
- return void send(res, 200, 'application/json; charset=utf-8', JSON.stringify({ deleted: true, id: m.note.id }, null, 2));
455
- }
456
- default:
457
- throw new ApiError(400, 'op must be add | edit | delete');
458
- }
459
- }
460
- catch (e) {
461
- if (e instanceof ApiError)
462
- fail(e.status, e.message);
463
- else
464
- fail(500, e instanceof Error ? e.message : String(e));
465
- }
466
- }
467
- function mutationError(id, m) {
468
- return m.reason === 'not_found'
469
- ? new ApiError(404, `note "${id}" not found`)
470
- : new ApiError(400, `note id prefix "${id}" matches ${m.matches} notes`);
471
- }
472
- /** 笔记数据窗:GET /api/notes?ref=<hash> → 该节点子树内的本地笔记(存入顺序=时间正序)。
473
- * 独立只读端点、纯加法(不碰既有数据窗);写入口在 CLI(practi note)。ref 缺失 400、
474
- * 解析不到 404——错误对齐其它路由的纯文本口径。notes.json 在 dataDir 下,live reload
475
- * 天然覆盖:另一终端 note add 后页面自动刷新出笔记 */
476
- function notesRoute(req, res, dataDir, ws) {
477
- const ref = new URL(req.url ?? '/', 'http://localhost').searchParams.get('ref');
478
- if (!ref) {
479
- send(res, 400, 'text/plain; charset=utf-8', 'E_ARGS: missing ?ref=<hash>');
480
- return;
481
- }
482
- let hash;
483
- try {
484
- hash = resolveNodeRef(ws, ref);
485
- }
486
- catch (e) {
487
- const msg = e instanceof PracticeError ? `${e.code}: ${e.message}` : String(e);
488
- send(res, 404, 'text/plain; charset=utf-8', msg);
489
- return;
490
- }
491
- const set = subtreeHashes(ws, hash);
492
- const notes = loadNotes(dataDir).notes.filter(n => set.has(n.hash));
493
- send(res, 200, 'application/json; charset=utf-8', JSON.stringify({ notes }, null, 2));
494
- }
495
- function sseHandshake(req, res, clients) {
496
- res.writeHead(200, {
497
- 'content-type': 'text/event-stream',
498
- 'cache-control': 'no-cache',
499
- connection: 'keep-alive',
500
- });
501
- res.write('retry: 1000\n\n');
502
- clients.add(res);
503
- req.on('close', () => clients.delete(res));
228
+ function mimeFor(bytes) {
229
+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff)
230
+ return 'image/jpeg';
231
+ if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47)
232
+ return 'image/png';
233
+ if (bytes.length >= 6 && bytes.toString('ascii', 0, 6) === 'GIF89a')
234
+ return 'image/gif';
235
+ if (bytes.length >= 5 && bytes.toString('ascii', 0, 5) === '<?xml')
236
+ return 'image/svg+xml';
237
+ return 'application/octet-stream';
504
238
  }
505
- /** 监听 roots(递归;平台不支持时降级单层,再失败静默跳过——live reload 是锦上添花,不致命)。
506
- * 事件去抖:一次保存或一条 practi 命令会喷一串文件事件,合并成一次广播。
507
- * notes.json 例外:不触发整页 reload(写字段的页面自己会局部更新,整刷会白屏闪烁),
508
- * 改发轻量 notes 事件——前端只重拉笔记数据重绘右栏,内容区/滚动位/草稿全程不动 */
509
- function watchLive(roots, clients) {
510
- let reloadTimer = null;
511
- let notesTimer = null;
512
- const broadcast = (event) => {
513
- if (clients.size === 0)
514
- return;
515
- for (const res of clients)
516
- res.write(`event: ${event}\ndata: 1\n\n`);
517
- };
518
- const onChange = (_event, filename) => {
519
- const isNotes = filename !== null && path.basename(filename) === NOTES_FILE;
520
- const unknown = filename === null; // 个别平台不给文件名:保守起见两种事件都发——宁多推一次不漏
521
- if (!isNotes || unknown) {
522
- if (reloadTimer === null) {
523
- reloadTimer = setTimeout(() => { reloadTimer = null; broadcast('reload'); }, 150);
524
- }
525
- }
526
- if (isNotes || unknown) {
527
- if (notesTimer === null) {
528
- notesTimer = setTimeout(() => { notesTimer = null; broadcast('notes'); }, 150);
529
- }
530
- }
531
- };
532
- for (const root of roots) {
533
- if (!fs.existsSync(root))
534
- continue;
535
- try {
536
- fs.watch(root, { recursive: true }, onChange);
537
- }
538
- catch {
539
- try {
540
- fs.watch(root, onChange);
541
- }
542
- catch {
543
- // fs.watch 完全不可用:live reload 静默失效,其余功能不受影响
544
- }
545
- }
546
- }
547
- // 保活注释行:防空闲 SSE 连接被掐(本地一般无此问题,防御性)
548
- setInterval(() => {
549
- for (const res of clients)
550
- res.write(': ping\n\n');
551
- }, 25000).unref();
239
+ function send(res, code, type, body) {
240
+ res.writeHead(code, { 'content-type': type });
241
+ res.end(body);
552
242
  }
553
243
  function sendBytes(res, type, body) {
554
- res.writeHead(200, { 'content-type': type, 'cache-control': 'public, max-age=31536000, immutable' });
244
+ res.writeHead(200, { 'content-type': type });
555
245
  res.end(body);
556
246
  }
557
- /** Best-effort mime for a local blob, looked up from any action that references it */
558
- function mimeFor(ws, hash) {
559
- for (const n of ws.nodes.values()) {
560
- if (n.type !== 'action')
561
- continue;
562
- for (const a of n.attachments ?? []) {
563
- if (a.hash === hash && a.mime)
564
- return a.mime;
565
- }
566
- }
567
- return 'application/octet-stream';
568
- }
569
- export function openBrowser(url) {
570
- if (process.platform === 'win32') {
571
- // cmd 把 & 当命令分隔符,URL 必须整体加引号(否则带 query 的 OAuth 授权 URL 被截断在首个 &);
572
- // start 的首个引号参数是窗口标题占位;/d /s + verbatim 让 cmd 按原样解析这条命令行
573
- spawn('cmd', ['/d', '/s', '/c', `start "" "${url}"`], {
574
- windowsVerbatimArguments: true,
575
- stdio: 'ignore',
576
- detached: true,
577
- }).unref();
578
- return;
579
- }
580
- const cmd = process.platform === 'darwin' ? 'open' : 'xdg-open';
581
- spawn(cmd, [url], { stdio: 'ignore', detached: true }).unref();
582
- }
583
247
  //# sourceMappingURL=web.js.map