techtools
Головна / scripts / comments.ts

comments.ts

TypeScript · 79 рядків

1// Клієнт Claude для коментарів порталу: забрати відкриті, подивитися «як було», закрити з відповіддю, переприв'язати.
2//   node --no-warnings scripts/comments.ts list [--all] [--url URL]     відкриті (або всі) + резервна копія бази в portal/data/backup/
3//   node --no-warnings scripts/comments.ts show C-12                    коментар і уривок тексту з його коміту
4//   node --no-warnings scripts/comments.ts close C-12 --answer "…" --where "R-33.2" [--commit HASH]   (коміт за замовчуванням — HEAD)
5//   node --no-warnings scripts/comments.ts reopen C-12 --answer "чому"
6//   node --no-warnings scripts/comments.ts anchor C-12 --quote "новий текст" [--heading "розділ"]   прив'язати до HEAD
7// Адреса й токен: portal/data/tokens.json — {"default": "URL", "URL": "ttc_…"} (поза git); токен видає
8// `node portal/src/comments/cli.ts token Claude` на машині порталу.
9import { execFileSync } from 'node:child_process'
10import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
11import { join, resolve } from 'node:path'
12import { parseArgs } from 'node:util'
13
14const ROOT = join(import.meta.dirname, '..')
15const PRIVATE = join(ROOT, 'private')
16const DATA = process.env.PORTAL_DATA ? resolve(process.env.PORTAL_DATA) : join(ROOT, 'portal', 'data')
17const { values, positionals } = parseArgs({
18  allowPositionals: true,
19  options: { url: { type: 'string' }, all: { type: 'boolean' }, answer: { type: 'string' }, where: { type: 'string' }, commit: { type: 'string' }, quote: { type: 'string' }, heading: { type: 'string' }, prefix: { type: 'string' }, suffix: { type: 'string' } },
20})
21const [cmd, ref] = positionals
22
23let tokens: Record<string, string> = {}
24try { tokens = JSON.parse(readFileSync(join(DATA, 'tokens.json'), 'utf8')) } catch {}
25const base = (values.url ?? process.env.COMMENTS_URL ?? tokens.default ?? 'http://localhost:4000').replace(/\/$/, '')
26const token = process.env.COMMENTS_TOKEN ?? tokens[base]
27
28async function api(method: string, path: string, body?: unknown) {
29  const r = await fetch(base + path, { method, headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...(body ? { 'content-type': 'application/json' } : {}) }, body: body ? JSON.stringify(body) : undefined })
30  const j = await r.json().catch(() => null)
31  if (!r.ok) throw new Error(`${r.status} ${j?.error ?? r.statusText}`)
32  return j
33}
34// коміт — того репозиторію, де лежить документ: приватний (private/, лише локально) чи проєкт
35const repoOf = (rel: string) => existsSync(join(PRIVATE, rel)) ? PRIVATE : ROOT
36const git = (rel: string, ...args: string[]) => execFileSync('git', args, { cwd: repoOf(rel), encoding: 'utf8' }).trim()
37const short = (s: string) => s.slice(0, 8)
38
39function print(c: any) {
40  console.log(`\n${c.ref} [${c.state}] ${c.path}${c.heading ? ' § ' + c.heading : ''}  — ${c.author}, ${c.created_at.slice(0, 16)}  коміт ${short(c.commit)}${c.dirty ? ' (не в коміті)' : ''}`)
41  console.log(`  «${c.quote.replace(/\s+/g, ' ')}»`)
42  console.log(`  ${c.text.replace(/\n/g, '\n  ')}`)
43  for (const l of c.log.filter((l: any) => l.action === 'reopen')) console.log(`  ↺ ${l.by}: ${l.text}`)
44  if (c.state === 'closed') console.log(`  → ${c.answer}${c.answer_where ? ` [${c.answer_where}]` : ''}${c.answer_commit ? ` ${short(c.answer_commit)}` : ''}`)
45}
46
47if (cmd === 'list') {
48  const list = await api('GET', `/api/comments${values.all ? '' : '?state=open'}`)
49  for (const c of list) print(c)
50  console.log(`\n${base}: ${list.length} ${values.all ? 'усього' : 'відкритих'}`)
51  if (token) { // резервна копія бази при кожному забиранні
52    const dump = await api('GET', '/api/comments-export')
53    mkdirSync(join(DATA, 'backup'), { recursive: true })
54    const file = join(DATA, 'backup', `${new URL(base).host.replace(/[^\w.-]/g, '_')}-${new Date().toISOString().slice(0, 10)}.json`)
55    writeFileSync(file, JSON.stringify(dump, null, 2))
56    console.log(`копія: ${file}`)
57  }
58} else if (cmd === 'show' && ref) {
59  const c = await api('GET', `/api/comments/${ref}`)
60  print(c)
61  const ctx = await api('GET', `/api/comments/${ref}/context`)
62  console.log(ctx.found ? `\n  у коміті ${short(c.commit)}: …${ctx.before.slice(-200)}【${ctx.quote}】${ctx.after.slice(0, 200)}…` : `\n  ${ctx.note}`)
63} else if (cmd === 'close' && ref) {
64  if (!values.answer) throw new Error('--answer обов\'язковий')
65  const c = await api('GET', `/api/comments/${ref}`)
66  print(await api('POST', `/api/comments/${ref}/close`, { answer: values.answer, where: values.where ?? '', commit: values.commit ?? git(c.path, 'rev-parse', 'HEAD') }))
67} else if (cmd === 'reopen' && ref) {
68  print(await api('POST', `/api/comments/${ref}/reopen`, { text: values.answer ?? '' }))
69} else if (cmd === 'anchor' && ref) {
70  const c = await api('GET', `/api/comments/${ref}`)
71  if (!values.quote) throw new Error('--quote обов\'язковий')
72  print(await api('POST', `/api/comments/${ref}/anchor`, {
73    commit: values.commit ?? git(c.path, 'rev-parse', 'HEAD'), blob: git(c.path, 'rev-parse', `${values.commit ?? 'HEAD'}:${c.path}`),
74    quote: values.quote, prefix: values.prefix ?? '', suffix: values.suffix ?? '', heading: values.heading ?? c.heading,
75  }))
76} else {
77  console.log('команди: list [--all] | show C-N | close C-N --answer … --where … | reopen C-N --answer … | anchor C-N --quote …')
78}
79