@ttpt-ai/ttpt 0.0.0-stage → 0.1.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 +98 -2
- package/bin/ttpt.mjs +165 -0
- package/package.json +43 -4
- package/src/adopt.mjs +147 -0
- package/src/anchors.mjs +88 -0
- package/src/build.mjs +97 -0
- package/src/cite.mjs +80 -0
- package/src/derive.mjs +85 -0
- package/src/digest.mjs +95 -0
- package/src/format.mjs +48 -0
- package/src/locate.mjs +122 -0
- package/src/mcp.mjs +165 -0
- package/src/ops.mjs +164 -0
- package/src/publish.mjs +35 -0
- package/src/refs.mjs +139 -0
- package/src/store.mjs +115 -0
package/src/ops.mjs
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// Every operation, shared by the CLI and the MCP server so the two cannot
|
|
2
|
+
// drift apart. Each takes a context and plain arguments and returns text;
|
|
3
|
+
// refusals and failures throw TtptError.
|
|
4
|
+
|
|
5
|
+
import { readFile } from 'node:fs/promises';
|
|
6
|
+
import { Store, TtptError, parseId, idOf, ttptHome } from './store.mjs';
|
|
7
|
+
import { get as fetchDoc, locations as lookupOrder } from './locate.mjs';
|
|
8
|
+
import { parseAnchors } from './anchors.mjs';
|
|
9
|
+
import { referencedIds, referenceDefs, titleOf, path as walkPath, parseAddress } from './refs.mjs';
|
|
10
|
+
import { makeCitation, logCitation, citationLogPath, readCitations } from './cite.mjs';
|
|
11
|
+
import { publish as publishTo } from './publish.mjs';
|
|
12
|
+
import { build as buildSources } from './build.mjs';
|
|
13
|
+
import * as adoption from './adopt.mjs';
|
|
14
|
+
import { lineageOf, checkDerived, clauseDiff, lineDiff } from './derive.mjs';
|
|
15
|
+
import { formatPath, formatClauseDiff, formatLineDiff, formatAdoptions } from './format.mjs';
|
|
16
|
+
|
|
17
|
+
export function context({ env = process.env, cwd = process.cwd(), home = ttptHome(env), resolveTxt, fetchImpl } = {}) {
|
|
18
|
+
const store = new Store(home);
|
|
19
|
+
const load = async (hex) => (await fetchDoc(hex, { store, env, resolveTxt, fetchImpl })).text;
|
|
20
|
+
return { env, cwd, home, store, load, resolveTxt, fetchImpl, citations: citationLogPath(env, cwd) };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const lines = (...xs) => xs.flat().filter((x) => x !== null && x !== undefined && x !== false).join('\n');
|
|
24
|
+
|
|
25
|
+
export async function add(ctx, { files }) {
|
|
26
|
+
const out = [];
|
|
27
|
+
for (const file of files) {
|
|
28
|
+
const r = await ctx.store.add(await readFile(file));
|
|
29
|
+
out.push(`${r.id} ${file}${r.changed ? ' (normalised to canonical form)' : ''}`);
|
|
30
|
+
}
|
|
31
|
+
return out.join('\n');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function get(ctx, { id, hint }) {
|
|
35
|
+
const r = await fetchDoc(id, { store: ctx.store, hint, env: ctx.env, resolveTxt: ctx.resolveTxt, fetchImpl: ctx.fetchImpl });
|
|
36
|
+
return { text: r.text, source: r.source };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function clause(ctx, { address }) {
|
|
40
|
+
const { hex, anchor } = parseAddress(address);
|
|
41
|
+
const c = parseAnchors(await ctx.load(hex)).get(anchor);
|
|
42
|
+
if (!c) throw new TtptError(`${idOf(hex)} has no anchor "${anchor}"`);
|
|
43
|
+
return c.text;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function refs(ctx, { id }) {
|
|
47
|
+
const hex = parseId(id);
|
|
48
|
+
const text = await ctx.load(hex);
|
|
49
|
+
const labels = new Map([...referenceDefs(text)].map(([label, h]) => [h, label]));
|
|
50
|
+
const out = [];
|
|
51
|
+
const parent = lineageOf(text);
|
|
52
|
+
for (const h of referencedIds(text)) {
|
|
53
|
+
if (h === hex) continue;
|
|
54
|
+
let title;
|
|
55
|
+
try { title = titleOf(await ctx.load(h)); } catch { title = '(not available)'; }
|
|
56
|
+
const tag = h === parent ? '(parent) ' : labels.has(h) ? `[${labels.get(h)}] ` : '';
|
|
57
|
+
out.push(`${idOf(h)} ${tag}${title}`);
|
|
58
|
+
}
|
|
59
|
+
return out.join('\n') || 'It names no other documents.';
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function path(ctx, { address, full }) {
|
|
63
|
+
return formatPath(await walkPath(address, ctx.load), { full });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function cite(ctx, { address, stance, quote, changed, instead }) {
|
|
67
|
+
const { hex } = parseAddress(address);
|
|
68
|
+
const state = adoption.replay(await adoption.readEvents(ctx.home));
|
|
69
|
+
const c = await makeCitation({ address, stance, quote, changed, instead }, ctx.load, adoption.statusOf(state, hex));
|
|
70
|
+
await logCitation(c, ctx.citations);
|
|
71
|
+
const confirmed = await adoption.confirmFrom(c, hex, { home: ctx.home });
|
|
72
|
+
return lines(c.line, confirmed.map((r) => `This confirms your provisional adoption of ${r.title}.`));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function adopt(ctx, { id, expects, disagrees, dropIf, checked }) {
|
|
76
|
+
const hex = parseId(id);
|
|
77
|
+
const { chain } = await adoption.adopt(hex, { expects, disagrees, dropIf, checked }, { home: ctx.home, load: ctx.load });
|
|
78
|
+
const hexes = new Set(chain.map((c) => c.hex));
|
|
79
|
+
const disputes = (await readCitations(ctx.citations)).filter((c) => c.stance === 'disputed' && hexes.has(parseId(c.id)));
|
|
80
|
+
const text = await ctx.load(hex);
|
|
81
|
+
const parent = lineageOf(text);
|
|
82
|
+
let lineage = null;
|
|
83
|
+
if (parent) {
|
|
84
|
+
let diff;
|
|
85
|
+
try { diff = formatClauseDiff(clauseDiff(await ctx.load(parent), text)); } catch (e) { diff = `(parent not available: ${e.message.split('\n')[0]})`; }
|
|
86
|
+
lineage = [`It is derived from ${idOf(parent)}. Differences from its parent:`, diff.replace(/^/gm, ' ')];
|
|
87
|
+
}
|
|
88
|
+
return lines(
|
|
89
|
+
`Adopted provisionally: ${chain[0].title}`,
|
|
90
|
+
` ${idOf(hex)}`,
|
|
91
|
+
`The chain it rests on, all held locally (${chain.length}):`,
|
|
92
|
+
chain.map((c) => ` ${c.id} ${c.title}`),
|
|
93
|
+
lineage,
|
|
94
|
+
disputes.length
|
|
95
|
+
? ['Disputes in your citation log:', disputes.map((d) => ` ${d.line}`)]
|
|
96
|
+
: 'No disputes in your citation log.',
|
|
97
|
+
`Others' records: search public text for ${hex}.`,
|
|
98
|
+
'This adoption stays provisional until a clause changes a decision (a followed, blocked or redirected citation).',
|
|
99
|
+
'It is recorded in your adoption log. Tell the people you work for that you adopted it, and why.',
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export async function adopted(ctx) {
|
|
104
|
+
return formatAdoptions(adoption.replay(await adoption.readEvents(ctx.home)));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export async function deploy(ctx, { id }) {
|
|
108
|
+
const hex = parseId(id);
|
|
109
|
+
const { chain } = await adoption.deploy(hex, { home: ctx.home, load: ctx.load });
|
|
110
|
+
return lines(`Deployed: ${chain[0].title} and the ${chain.length - 1} document(s) it names.`, chain.map((c) => ` ${c.id} ${c.title}`));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export async function drop(ctx, { id, because, clause: anchor, quote }) {
|
|
114
|
+
const hex = parseId(id);
|
|
115
|
+
let recorded = null;
|
|
116
|
+
if (anchor || quote) {
|
|
117
|
+
if (!anchor || !quote) throw new TtptError('drop: give both --clause and --quote to record a disputed citation, or neither');
|
|
118
|
+
const c = await makeCitation({ address: `${idOf(hex)}#${anchor}`, stance: 'disputed', quote, changed: because }, ctx.load,
|
|
119
|
+
adoption.statusOf(adoption.replay(await adoption.readEvents(ctx.home)), hex));
|
|
120
|
+
await logCitation(c, ctx.citations);
|
|
121
|
+
recorded = c.line;
|
|
122
|
+
}
|
|
123
|
+
const r = await adoption.drop(hex, because, { home: ctx.home });
|
|
124
|
+
return lines(`Dropped ${r.title} (was ${r.status}). It stays in your local store as information.`, recorded && `Recorded: ${recorded}`);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export async function derive(ctx, { parent, text }) {
|
|
128
|
+
const parentHex = parseId(parent);
|
|
129
|
+
const parentText = await ctx.load(parentHex);
|
|
130
|
+
const problems = checkDerived(text, parentHex, parentText);
|
|
131
|
+
if (problems.length) throw new TtptError(`not accepted as a derived version:\n ${problems.join('\n ')}`);
|
|
132
|
+
const r = await ctx.store.add(text);
|
|
133
|
+
return lines(
|
|
134
|
+
`${r.id} ${titleOf(r.text)}`,
|
|
135
|
+
`Derived from ${idOf(parentHex)}. Differences from its parent:`,
|
|
136
|
+
formatClauseDiff(clauseDiff(parentText, r.text)).replace(/^/gm, ' '),
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export async function diff(ctx, { a, b, lines: byLine, full }) {
|
|
141
|
+
const ta = await ctx.load(parseId(a));
|
|
142
|
+
const tb = await ctx.load(parseId(b));
|
|
143
|
+
return byLine ? formatLineDiff(lineDiff(ta, tb)) : formatClauseDiff(clauseDiff(ta, tb), { full });
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export async function publish(ctx, { dir, ids = [] }) {
|
|
147
|
+
const r = await publishTo(ctx.store, dir, ids.map(parseId));
|
|
148
|
+
return lines(r.added.map((h) => `added ${idOf(h)}`), r.present.map((h) => `present ${idOf(h)}`)) || 'Nothing to publish.';
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export async function build(ctx, { sources, out }) {
|
|
152
|
+
const results = await buildSources(sources, { store: ctx.store, outDir: out });
|
|
153
|
+
return results.map((r) => `${r.id} ${r.title}${r.names.length ? ` (names ${r.names.join(', ')})` : ''}`).join('\n');
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export async function verify(ctx) {
|
|
157
|
+
const { good, bad } = await ctx.store.verify();
|
|
158
|
+
return { ok: bad.length === 0, text: lines(bad.map((b) => `quarantined ${b.name}: ${b.problems.join('; ')}`), `${good.length} document(s) verified, ${bad.length} quarantined`) };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export async function locations(ctx) {
|
|
162
|
+
const list = await lookupOrder({ home: ctx.home, env: ctx.env, resolveTxt: ctx.resolveTxt });
|
|
163
|
+
return lines(`local ${ctx.store.dir}`, list.map(({ location, from }) => `${from.padEnd(8)} ${location}`));
|
|
164
|
+
}
|
package/src/publish.mjs
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// Copy documents from the local store into a library directory, laid out as
|
|
2
|
+
// <hex>.md. Committing and pushing that directory is left to git: publishing
|
|
3
|
+
// goes to one place per command, and there is no broadcast.
|
|
4
|
+
|
|
5
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { storedFileProblems } from './digest.mjs';
|
|
8
|
+
import { idOf, TtptError } from './store.mjs';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @param {import('./store.mjs').Store} store
|
|
12
|
+
* @param {string} dir
|
|
13
|
+
* @param {string[]} [hexes] default: everything in the store
|
|
14
|
+
*/
|
|
15
|
+
export async function publish(store, dir, hexes) {
|
|
16
|
+
const list = hexes?.length ? hexes : await store.list();
|
|
17
|
+
await mkdir(dir, { recursive: true });
|
|
18
|
+
const added = [];
|
|
19
|
+
const present = [];
|
|
20
|
+
for (const hex of list) {
|
|
21
|
+
const text = await store.read(hex);
|
|
22
|
+
if (text === null) throw new TtptError(`${idOf(hex)} is not in the local store`);
|
|
23
|
+
const target = join(dir, `${hex}.md`);
|
|
24
|
+
try {
|
|
25
|
+
await writeFile(target, text, { encoding: 'utf8', flag: 'wx' });
|
|
26
|
+
added.push(hex);
|
|
27
|
+
} catch (err) {
|
|
28
|
+
if (err.code !== 'EEXIST') throw err;
|
|
29
|
+
const problems = storedFileProblems(`${hex}.md`, await readFile(target));
|
|
30
|
+
if (problems.length) throw new TtptError(`${target} exists but is not that document: ${problems[0]}`);
|
|
31
|
+
present.push(hex);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return { added, present };
|
|
35
|
+
}
|
package/src/refs.mjs
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// References between documents, derivation lines, and the thought path.
|
|
2
|
+
//
|
|
3
|
+
// A document names another by its full ID. A reference definition gives it a
|
|
4
|
+
// label for use in derivation lines:
|
|
5
|
+
// [upper]: ttpt:sha256:<hex>
|
|
6
|
+
// A derivation line names a clause here and the clauses it rests on:
|
|
7
|
+
// - p.4 ← [upper]#decline, [upper]#channel — gloss
|
|
8
|
+
// - #starts ← [upper]#difference, #copies — gloss (no label = this document)
|
|
9
|
+
|
|
10
|
+
import { parseAnchors, plain } from './anchors.mjs';
|
|
11
|
+
import { idOf, TtptError } from './store.mjs';
|
|
12
|
+
|
|
13
|
+
const ID_G = /ttpt:sha256:([0-9a-f]{64})/g;
|
|
14
|
+
const DEF = /^\[([^\]]+)\]:\s*ttpt:sha256:([0-9a-f]{64})\s*$/;
|
|
15
|
+
const DERIV = /^\s*[-*]\s+#?([A-Za-z0-9._-]+)\s*←\s*(.+?)\s*$/;
|
|
16
|
+
const SOURCE = /^(?:\[([^\]]+)\])?#([A-Za-z0-9._-]+)$/;
|
|
17
|
+
|
|
18
|
+
/** Every document ID named in the text, in order of first mention. */
|
|
19
|
+
export function referencedIds(text) {
|
|
20
|
+
return [...new Set([...text.matchAll(ID_G)].map((m) => m[1]))];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** @returns {Map<string, string>} label → hex */
|
|
24
|
+
export function referenceDefs(text) {
|
|
25
|
+
const defs = new Map();
|
|
26
|
+
for (const line of text.split('\n')) {
|
|
27
|
+
const m = DEF.exec(line.trim());
|
|
28
|
+
if (m) defs.set(m[1], m[2]);
|
|
29
|
+
}
|
|
30
|
+
return defs;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The document's title: its first level-1 heading. */
|
|
34
|
+
export function titleOf(text) {
|
|
35
|
+
const m = /^#\s+(.+)$/m.exec(text);
|
|
36
|
+
return m ? m[1].trim() : '(untitled)';
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* @returns {Map<string, {sources: Array<{label: string|null, anchor: string}>, gloss: string, line: number}>}
|
|
41
|
+
*/
|
|
42
|
+
export function derivations(text) {
|
|
43
|
+
const out = new Map();
|
|
44
|
+
text.split('\n').forEach((line, i) => {
|
|
45
|
+
const m = DERIV.exec(line);
|
|
46
|
+
if (!m) return;
|
|
47
|
+
const [body, gloss = ''] = m[2].split(/\s+—\s+/, 2);
|
|
48
|
+
const sources = body.split(',').map((s) => s.trim()).filter(Boolean).map((s) => {
|
|
49
|
+
const sm = SOURCE.exec(s);
|
|
50
|
+
if (!sm) throw new TtptError(`line ${i + 1}: cannot read source ${JSON.stringify(s)}`);
|
|
51
|
+
return { label: sm[1] ?? null, anchor: sm[2] };
|
|
52
|
+
});
|
|
53
|
+
if (out.has(m[1])) throw new TtptError(`line ${i + 1}: a second derivation line for "${m[1]}"`);
|
|
54
|
+
out.set(m[1], { sources, gloss: gloss.trim(), line: i + 1 });
|
|
55
|
+
});
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Split ttpt:sha256:<hex>#anchor. */
|
|
60
|
+
export function parseAddress(s) {
|
|
61
|
+
const m = /^(?:ttpt:)?(?:sha256:)?([0-9a-f]{64})#([A-Za-z0-9._-]+)$/.exec(String(s ?? '').trim());
|
|
62
|
+
if (!m) throw new TtptError(`not a clause address: ${JSON.stringify(s)} (expected ttpt:sha256:<hex>#<anchor>)`);
|
|
63
|
+
return { hex: m[1], anchor: m[2] };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Check a document's references: every label used is defined, every anchor it
|
|
68
|
+
* derives from exists, and every clause it derives exists here.
|
|
69
|
+
* @param {string} text
|
|
70
|
+
* @param {(hex: string) => Promise<string>} load text of another document
|
|
71
|
+
* @returns {Promise<string[]>} problems
|
|
72
|
+
*/
|
|
73
|
+
export async function checkReferences(text, load) {
|
|
74
|
+
const problems = [];
|
|
75
|
+
const here = parseAnchors(text);
|
|
76
|
+
const defs = referenceDefs(text);
|
|
77
|
+
const cache = new Map();
|
|
78
|
+
const anchorsOf = async (hex) => {
|
|
79
|
+
if (!cache.has(hex)) cache.set(hex, parseAnchors(await load(hex)));
|
|
80
|
+
return cache.get(hex);
|
|
81
|
+
};
|
|
82
|
+
for (const [clause, { sources, line }] of derivations(text)) {
|
|
83
|
+
if (!here.has(clause)) problems.push(`line ${line}: derives "${clause}", which is not an anchor in this document`);
|
|
84
|
+
for (const { label, anchor } of sources) {
|
|
85
|
+
if (label === null) {
|
|
86
|
+
if (!here.has(anchor)) problems.push(`line ${line}: #${anchor} is not an anchor in this document`);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
const hex = defs.get(label);
|
|
90
|
+
if (!hex) {
|
|
91
|
+
problems.push(`line ${line}: [${label}] has no reference definition`);
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
let anchors;
|
|
95
|
+
try {
|
|
96
|
+
anchors = await anchorsOf(hex);
|
|
97
|
+
} catch (err) {
|
|
98
|
+
problems.push(`line ${line}: [${label}] ${idOf(hex)} could not be loaded: ${err.message}`);
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
if (!anchors.has(anchor)) problems.push(`line ${line}: [${label}]#${anchor} is not an anchor in that document`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return problems;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The thought path from a clause: the clause, then each clause it rests on, recursively.
|
|
109
|
+
* @param {string} address ttpt:sha256:<hex>#anchor
|
|
110
|
+
* @param {(hex: string) => Promise<string>} load
|
|
111
|
+
* @returns {Promise<object>} node: {id, anchor, title, text, how, from: node[], seen?}
|
|
112
|
+
* how is the gloss of the derivation line: how this clause follows from those in `from`.
|
|
113
|
+
*/
|
|
114
|
+
export async function path(address, load) {
|
|
115
|
+
const { hex, anchor } = parseAddress(address);
|
|
116
|
+
const visited = new Set();
|
|
117
|
+
const walk = async (hex, anchor) => {
|
|
118
|
+
const key = `${hex}#${anchor}`;
|
|
119
|
+
const doc = await load(hex);
|
|
120
|
+
const clause = parseAnchors(doc).get(anchor);
|
|
121
|
+
if (!clause) throw new TtptError(`${idOf(hex)} has no anchor "${anchor}"`);
|
|
122
|
+
const node = { id: idOf(hex), anchor, title: titleOf(doc), text: clause.text, how: '', from: [] };
|
|
123
|
+
if (visited.has(key)) return { ...node, seen: true };
|
|
124
|
+
visited.add(key);
|
|
125
|
+
const d = derivations(doc).get(anchor);
|
|
126
|
+
if (!d) return node;
|
|
127
|
+
node.how = d.gloss;
|
|
128
|
+
const defs = referenceDefs(doc);
|
|
129
|
+
for (const s of d.sources) {
|
|
130
|
+
const target = s.label === null ? hex : defs.get(s.label);
|
|
131
|
+
if (!target) throw new TtptError(`${idOf(hex)}: [${s.label}] has no reference definition`);
|
|
132
|
+
node.from.push(await walk(target, s.anchor));
|
|
133
|
+
}
|
|
134
|
+
return node;
|
|
135
|
+
};
|
|
136
|
+
return walk(hex, anchor);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export { plain };
|
package/src/store.mjs
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// The local store: ~/.ttpt/store/<hex>.md (override the root with TTPT_HOME).
|
|
2
|
+
//
|
|
3
|
+
// Files are written once and never modified. Every read re-checks the file
|
|
4
|
+
// against its name; a file that fails is moved to quarantine, not served.
|
|
5
|
+
|
|
6
|
+
import { mkdir, readFile, writeFile, readdir, rename } from 'node:fs/promises';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { homedir } from 'node:os';
|
|
9
|
+
import { canonicalize, decode, textProblems, sha256Hex, storedFileProblems, HEX_PATTERN } from './digest.mjs';
|
|
10
|
+
|
|
11
|
+
export function ttptHome(env = process.env) {
|
|
12
|
+
return env.TTPT_HOME || join(homedir(), '.ttpt');
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class TtptError extends Error {}
|
|
16
|
+
|
|
17
|
+
/** Accepts ttpt:sha256:<hex>, sha256:<hex> or a bare <hex>; returns <hex>. */
|
|
18
|
+
export function parseId(s) {
|
|
19
|
+
const m = /^(?:ttpt:)?(?:sha256:)?([0-9a-f]{64})$/.exec(String(s ?? '').trim());
|
|
20
|
+
if (!m) throw new TtptError(`not a document ID: ${JSON.stringify(s)} (expected ttpt:sha256:<64 hex>)`);
|
|
21
|
+
return m[1];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const idOf = (hex) => `ttpt:sha256:${hex}`;
|
|
25
|
+
|
|
26
|
+
export class Store {
|
|
27
|
+
constructor(home = ttptHome()) {
|
|
28
|
+
this.home = home;
|
|
29
|
+
this.dir = join(home, 'store');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
path(hex) {
|
|
33
|
+
return join(this.dir, `${hex}.md`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Canonicalise and store. Never overwrites. */
|
|
37
|
+
async add(input) {
|
|
38
|
+
const original = decode(input);
|
|
39
|
+
const canonical = canonicalize(original);
|
|
40
|
+
const problems = textProblems(canonical);
|
|
41
|
+
if (problems.length) throw new TtptError(`not accepted as a document: ${problems.join('; ')}`);
|
|
42
|
+
const hex = sha256Hex(canonical);
|
|
43
|
+
await mkdir(this.dir, { recursive: true });
|
|
44
|
+
let existed = false;
|
|
45
|
+
try {
|
|
46
|
+
await writeFile(this.path(hex), canonical, { encoding: 'utf8', flag: 'wx' });
|
|
47
|
+
} catch (err) {
|
|
48
|
+
if (err.code !== 'EEXIST') throw err;
|
|
49
|
+
existed = true;
|
|
50
|
+
}
|
|
51
|
+
return { hex, id: idOf(hex), changed: original !== canonical, existed, text: canonical };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The text, or null if absent. A file that fails its check is quarantined. */
|
|
55
|
+
async read(hex) {
|
|
56
|
+
let bytes;
|
|
57
|
+
try {
|
|
58
|
+
bytes = await readFile(this.path(hex));
|
|
59
|
+
} catch (err) {
|
|
60
|
+
if (err.code === 'ENOENT') return null;
|
|
61
|
+
throw err;
|
|
62
|
+
}
|
|
63
|
+
const problems = storedFileProblems(`${hex}.md`, bytes);
|
|
64
|
+
if (problems.length) {
|
|
65
|
+
await this.quarantine(hex);
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
return bytes.toString('utf8');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async list() {
|
|
72
|
+
let names;
|
|
73
|
+
try {
|
|
74
|
+
names = await readdir(this.dir);
|
|
75
|
+
} catch (err) {
|
|
76
|
+
if (err.code === 'ENOENT') return [];
|
|
77
|
+
throw err;
|
|
78
|
+
}
|
|
79
|
+
return names.filter((n) => /^[0-9a-f]{64}\.md$/.test(n)).map((n) => n.slice(0, 64)).sort();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Check every stored file; quarantine the bad ones. */
|
|
83
|
+
async verify() {
|
|
84
|
+
const good = [];
|
|
85
|
+
const bad = [];
|
|
86
|
+
let names = [];
|
|
87
|
+
try {
|
|
88
|
+
names = await readdir(this.dir);
|
|
89
|
+
} catch (err) {
|
|
90
|
+
if (err.code !== 'ENOENT') throw err;
|
|
91
|
+
}
|
|
92
|
+
for (const name of names.sort()) {
|
|
93
|
+
const problems = storedFileProblems(name, await readFile(join(this.dir, name)));
|
|
94
|
+
if (problems.length) {
|
|
95
|
+
bad.push({ name, problems });
|
|
96
|
+
await this.quarantineName(name);
|
|
97
|
+
} else {
|
|
98
|
+
good.push(name.slice(0, 64));
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return { good, bad };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async quarantine(hex) {
|
|
105
|
+
return this.quarantineName(`${hex}.md`);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async quarantineName(name) {
|
|
109
|
+
const q = join(this.home, 'quarantine');
|
|
110
|
+
await mkdir(q, { recursive: true });
|
|
111
|
+
await rename(join(this.dir, name), join(q, `${name}.${Date.now()}`));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export { HEX_PATTERN };
|