tandem-kit-core 0.0.0 → 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 +7 -1
- package/dist/src/browser.d.ts +19 -0
- package/dist/src/browser.js +19 -0
- package/dist/src/client-tools.d.ts +31 -0
- package/dist/src/client-tools.js +82 -0
- package/dist/src/client.d.ts +179 -0
- package/dist/src/client.js +213 -0
- package/dist/src/delta.d.ts +16 -0
- package/dist/src/delta.js +99 -0
- package/dist/src/durable.d.ts +39 -0
- package/dist/src/durable.js +104 -0
- package/dist/src/errors.d.ts +5 -0
- package/dist/src/errors.js +10 -0
- package/dist/src/eventlog-file.d.ts +12 -0
- package/dist/src/eventlog-file.js +39 -0
- package/dist/src/eventlog.d.ts +31 -0
- package/dist/src/eventlog.js +63 -0
- package/dist/src/events.d.ts +15 -0
- package/dist/src/events.js +79 -0
- package/dist/src/events.json +80 -0
- package/dist/src/files.d.ts +34 -0
- package/dist/src/files.js +122 -0
- package/dist/src/fsutil.d.ts +8 -0
- package/dist/src/fsutil.js +68 -0
- package/dist/src/hash.d.ts +3 -0
- package/dist/src/hash.js +65 -0
- package/dist/src/images.d.ts +24 -0
- package/dist/src/images.js +70 -0
- package/dist/src/index.d.ts +25 -0
- package/dist/src/index.js +25 -0
- package/dist/src/json.d.ts +10 -0
- package/dist/src/json.js +68 -0
- package/dist/src/merge.d.ts +34 -0
- package/dist/src/merge.js +111 -0
- package/dist/src/persist.d.ts +49 -0
- package/dist/src/persist.js +29 -0
- package/dist/src/proposals-file.d.ts +12 -0
- package/dist/src/proposals-file.js +36 -0
- package/dist/src/proposals.d.ts +149 -0
- package/dist/src/proposals.js +296 -0
- package/dist/src/reconcile.d.ts +63 -0
- package/dist/src/reconcile.js +61 -0
- package/dist/src/replica.d.ts +147 -0
- package/dist/src/replica.js +320 -0
- package/dist/src/revisions-file.d.ts +14 -0
- package/dist/src/revisions-file.js +28 -0
- package/dist/src/revisions.d.ts +78 -0
- package/dist/src/revisions.js +152 -0
- package/dist/src/revisions.json +19 -0
- package/dist/src/schema.d.ts +12 -0
- package/dist/src/schema.js +49 -0
- package/dist/src/session-state.d.ts +36 -0
- package/dist/src/session-state.js +95 -0
- package/dist/src/sse.d.ts +17 -0
- package/dist/src/sse.js +59 -0
- package/dist/src/workcopy.d.ts +145 -0
- package/dist/src/workcopy.js +556 -0
- package/package.json +34 -4
|
@@ -0,0 +1,556 @@
|
|
|
1
|
+
import { apply, diff, formatDelta, formatPath } from "./delta.js";
|
|
2
|
+
import { TandemError } from "./errors.js";
|
|
3
|
+
import { nowIso } from "./events.js";
|
|
4
|
+
import { EventLog } from "./eventlog.js";
|
|
5
|
+
import { clone, equal } from "./json.js";
|
|
6
|
+
import { clashDelta, merge3 } from "./merge.js";
|
|
7
|
+
import { MAX_CLOSED_CLASHES, MemoryClashStore, savePolicyOf } from "./persist.js";
|
|
8
|
+
import { contentClashId, defaultPrint, primaryActor, reconcileStates, syncClashRecord } from "./reconcile.js";
|
|
9
|
+
import { MemoryRevisionStore } from "./revisions.js";
|
|
10
|
+
const UNDO_CHANGE = /^undo change (\S+)$/;
|
|
11
|
+
const DEFAULT_SAVE = { quietMs: 1200, maxMs: 8000 };
|
|
12
|
+
export class Workcopy {
|
|
13
|
+
name;
|
|
14
|
+
log;
|
|
15
|
+
adapter;
|
|
16
|
+
store;
|
|
17
|
+
clashStore;
|
|
18
|
+
snapshotStore;
|
|
19
|
+
keptStates;
|
|
20
|
+
policy;
|
|
21
|
+
wins;
|
|
22
|
+
clock;
|
|
23
|
+
draft;
|
|
24
|
+
versionNo;
|
|
25
|
+
lastWriter = 'system';
|
|
26
|
+
remembered = new Map();
|
|
27
|
+
open = new Map();
|
|
28
|
+
closedIds = [];
|
|
29
|
+
contentIds = false;
|
|
30
|
+
pending;
|
|
31
|
+
quietTimer;
|
|
32
|
+
maxTimer;
|
|
33
|
+
clashCount = 0;
|
|
34
|
+
revisionCount;
|
|
35
|
+
initialState;
|
|
36
|
+
constructor(options) {
|
|
37
|
+
this.name = options.name ?? 'doc';
|
|
38
|
+
this.adapter = options.adapter ?? {};
|
|
39
|
+
this.store = options.store ?? new MemoryRevisionStore();
|
|
40
|
+
this.keptStates = options.keptStates ?? 64;
|
|
41
|
+
this.policy = savePolicyOf(options, DEFAULT_SAVE);
|
|
42
|
+
this.clashStore = options.clashes ?? new MemoryClashStore();
|
|
43
|
+
this.snapshotStore = options.snapshot;
|
|
44
|
+
this.wins = options.wins ?? ((actor) => actor === 'human');
|
|
45
|
+
this.clock = options.clock ?? nowIso;
|
|
46
|
+
this.log = options.log ?? new EventLog(undefined, this.clock);
|
|
47
|
+
this.initialState = clone(options.initial);
|
|
48
|
+
this.revisionCount = this.store.list().length;
|
|
49
|
+
const head = this.last();
|
|
50
|
+
const saved = this.snapshotStore?.load() ?? null;
|
|
51
|
+
if (head) {
|
|
52
|
+
this.draft = clone(head.state);
|
|
53
|
+
this.versionNo = head.version;
|
|
54
|
+
this.lastWriter = head.actor;
|
|
55
|
+
if (saved && saved.version >= head.version && !equal(saved.state, head.state)) {
|
|
56
|
+
this.draft = clone(saved.state);
|
|
57
|
+
this.versionNo = saved.version;
|
|
58
|
+
this.lastWriter = saved.last_writer;
|
|
59
|
+
this.pending = { actor: saved.pending?.actor ?? saved.last_writer, reasons: saved.pending?.reasons ?? [], findings: saved.pending?.findings ?? [], from: clone(head.state) };
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
this.draft = saved ? clone(saved.state) : this.initialState;
|
|
64
|
+
this.versionNo = saved ? saved.version : 0;
|
|
65
|
+
this.store.append(this.revision({ op: 'init', actor: 'system', reason: 'init', delta: [], state: this.draft, findings: [], parent: null }));
|
|
66
|
+
}
|
|
67
|
+
this.remembered.set(this.versionNo, this.draft);
|
|
68
|
+
const clashState = this.clashStore.load();
|
|
69
|
+
for (const record of clashState.open)
|
|
70
|
+
this.open.set(record.id, record);
|
|
71
|
+
this.closedIds = clashState.closed.slice(-MAX_CLOSED_CLASHES);
|
|
72
|
+
this.clashCount = clashState.count;
|
|
73
|
+
this.contentIds = clashState.ids === 'content';
|
|
74
|
+
if (this.pending)
|
|
75
|
+
this.schedule();
|
|
76
|
+
}
|
|
77
|
+
get initial() {
|
|
78
|
+
return clone(this.initialState);
|
|
79
|
+
}
|
|
80
|
+
get pristine() {
|
|
81
|
+
return this.versionNo === 0;
|
|
82
|
+
}
|
|
83
|
+
get seq() {
|
|
84
|
+
return this.log.lastSeq;
|
|
85
|
+
}
|
|
86
|
+
get closedClashes() {
|
|
87
|
+
return [...this.closedIds];
|
|
88
|
+
}
|
|
89
|
+
useContentClashIds() {
|
|
90
|
+
if (this.contentIds)
|
|
91
|
+
return;
|
|
92
|
+
this.contentIds = true;
|
|
93
|
+
this.persistClashes();
|
|
94
|
+
}
|
|
95
|
+
get savePolicy() {
|
|
96
|
+
return this.policy;
|
|
97
|
+
}
|
|
98
|
+
get version() {
|
|
99
|
+
return this.versionNo;
|
|
100
|
+
}
|
|
101
|
+
get state() {
|
|
102
|
+
return this.draft;
|
|
103
|
+
}
|
|
104
|
+
get clashes() {
|
|
105
|
+
return [...this.open.values()];
|
|
106
|
+
}
|
|
107
|
+
get head() {
|
|
108
|
+
return this.last();
|
|
109
|
+
}
|
|
110
|
+
last() {
|
|
111
|
+
return this.store.head ? this.store.head() : this.store.list().at(-1);
|
|
112
|
+
}
|
|
113
|
+
revisions() {
|
|
114
|
+
return this.store.list();
|
|
115
|
+
}
|
|
116
|
+
revisionsSince(revisionId) {
|
|
117
|
+
const all = this.store.list();
|
|
118
|
+
const at = revisionId === null ? -1 : all.findIndex((r) => r.id === revisionId);
|
|
119
|
+
return at === -1 && revisionId !== null ? all : all.slice(at + 1);
|
|
120
|
+
}
|
|
121
|
+
fork(state = this.draft) {
|
|
122
|
+
return new Workcopy({ name: this.name, initial: state, adapter: this.adapter, wins: this.wins, clock: this.clock, autosave: false });
|
|
123
|
+
}
|
|
124
|
+
write(req) {
|
|
125
|
+
if (!Number.isInteger(req.version))
|
|
126
|
+
throw new TandemError(400, 'bad_request', 'version must be an integer');
|
|
127
|
+
if (!req.actor || typeof req.actor !== 'string')
|
|
128
|
+
throw new TandemError(400, 'bad_request', 'actor is required');
|
|
129
|
+
if (req.state === undefined && !req.delta)
|
|
130
|
+
throw new TandemError(400, 'bad_request', 'a write needs delta or state');
|
|
131
|
+
const current = this.draft;
|
|
132
|
+
let candidate;
|
|
133
|
+
let clashes = [];
|
|
134
|
+
let rebased = false;
|
|
135
|
+
let keptActor = req.actor;
|
|
136
|
+
let droppedActor = this.lastWriter;
|
|
137
|
+
if (req.version === this.versionNo && req.base === undefined) {
|
|
138
|
+
candidate = req.state !== undefined ? req.state : apply(current, req.delta);
|
|
139
|
+
}
|
|
140
|
+
else if (req.base !== undefined || this.remembered.has(req.version)) {
|
|
141
|
+
const base = req.base !== undefined ? req.base : this.remembered.get(req.version);
|
|
142
|
+
const written = req.state !== undefined ? req.state : apply(base, req.delta);
|
|
143
|
+
const writerWins = req.prefer === 'current' ? false : req.prefer === 'writer' ? true : this.wins(req.actor);
|
|
144
|
+
const mine = writerWins ? written : current;
|
|
145
|
+
const theirs = writerWins ? current : written;
|
|
146
|
+
if (!writerWins) {
|
|
147
|
+
keptActor = this.lastWriter;
|
|
148
|
+
droppedActor = req.actor;
|
|
149
|
+
}
|
|
150
|
+
const merged = this.adapter.merge ? this.adapter.merge(base, mine, theirs, { actor: req.actor, writerWins }) : merge3(base, mine, theirs, { keyed: this.adapter.keyed });
|
|
151
|
+
candidate = merged.merged;
|
|
152
|
+
clashes = merged.clashes;
|
|
153
|
+
rebased = true;
|
|
154
|
+
}
|
|
155
|
+
else {
|
|
156
|
+
return { status: 'stale', version: this.versionNo, changed: false, findings: [], clashes: [], state: this.draft };
|
|
157
|
+
}
|
|
158
|
+
const findings = this.adapter.validate?.(candidate, { actor: req.actor }) ?? [];
|
|
159
|
+
if (findings.some((f) => f.level === 'block')) {
|
|
160
|
+
this.log.publish({ type: 'rejected', actor: req.actor, reason: req.reason ?? null, findings, doc: this.name });
|
|
161
|
+
return { status: 'rejected', version: this.versionNo, changed: false, findings, clashes: [] };
|
|
162
|
+
}
|
|
163
|
+
const records = clashes.map((c) => this.recordClash(c, keptActor, droppedActor));
|
|
164
|
+
const delta = diff(current, candidate);
|
|
165
|
+
const changed = delta.length > 0;
|
|
166
|
+
const status = rebased ? 'rebased' : 'ok';
|
|
167
|
+
if (!changed)
|
|
168
|
+
return { status, version: this.versionNo, changed, findings, clashes: records, ...(rebased ? { state: this.draft } : {}) };
|
|
169
|
+
const revisionId = this.accept(candidate, { actor: req.actor, reason: req.reason ?? null, findings, commit: req.commit, via: req.via, delta });
|
|
170
|
+
return { status, version: this.versionNo, changed, findings, clashes: records, ...(rebased ? { state: this.draft } : {}), ...(revisionId ? { revision: revisionId } : {}) };
|
|
171
|
+
}
|
|
172
|
+
commit() {
|
|
173
|
+
this.clearTimers();
|
|
174
|
+
const pending = this.pending;
|
|
175
|
+
if (!pending)
|
|
176
|
+
return undefined;
|
|
177
|
+
this.pending = undefined;
|
|
178
|
+
if (equal(pending.from, this.draft)) {
|
|
179
|
+
this.persist();
|
|
180
|
+
return undefined;
|
|
181
|
+
}
|
|
182
|
+
const prior = this.last();
|
|
183
|
+
const revision = this.revision({
|
|
184
|
+
op: 'write',
|
|
185
|
+
actor: pending.actor,
|
|
186
|
+
reason: pending.reasons.length ? pending.reasons.join('; ') : null,
|
|
187
|
+
delta: diff(pending.from, this.draft),
|
|
188
|
+
state: this.draft,
|
|
189
|
+
findings: pending.findings,
|
|
190
|
+
parent: prior.id,
|
|
191
|
+
});
|
|
192
|
+
this.store.append(revision);
|
|
193
|
+
this.persist();
|
|
194
|
+
return revision;
|
|
195
|
+
}
|
|
196
|
+
turnEnded() {
|
|
197
|
+
return this.policy === 'turn-end' ? this.commit() : undefined;
|
|
198
|
+
}
|
|
199
|
+
actorsSince(seq, ignoreVia) {
|
|
200
|
+
if (seq > this.log.lastSeq)
|
|
201
|
+
return ['human'];
|
|
202
|
+
const actors = new Set();
|
|
203
|
+
const events = this.log.events(seq);
|
|
204
|
+
if (events.length && events[0].seq > seq + 1)
|
|
205
|
+
actors.add('human');
|
|
206
|
+
for (const event of events) {
|
|
207
|
+
if (event.type === 'change' && typeof event.actor === 'string' && (ignoreVia === undefined || event.via !== ignoreVia))
|
|
208
|
+
actors.add(event.actor);
|
|
209
|
+
}
|
|
210
|
+
return [...actors];
|
|
211
|
+
}
|
|
212
|
+
revert(revisionId, options = {}) {
|
|
213
|
+
const scope = options.scope ?? 'state';
|
|
214
|
+
if (scope !== 'state' && scope !== 'change')
|
|
215
|
+
throw new TandemError(400, 'bad_request', 'scope must be "state" or "change"');
|
|
216
|
+
if (options.onClash !== undefined && options.onClash !== 'keep-current' && options.onClash !== 'refuse')
|
|
217
|
+
throw new TandemError(400, 'bad_request', 'on_clash must be "keep-current" or "refuse"');
|
|
218
|
+
const target = this.store.list().find((r) => r.id === revisionId);
|
|
219
|
+
if (!target)
|
|
220
|
+
throw new TandemError(404, 'not_found', `no such revision: ${revisionId}`);
|
|
221
|
+
if (scope === 'change')
|
|
222
|
+
return this.revertChange(target, options);
|
|
223
|
+
if (!options.dryRun)
|
|
224
|
+
this.commit();
|
|
225
|
+
const actor = options.actor ?? 'human';
|
|
226
|
+
const candidate = clone(target.state);
|
|
227
|
+
const findings = this.adapter.validate?.(candidate, { actor }) ?? [];
|
|
228
|
+
if (findings.some((f) => f.level === 'block')) {
|
|
229
|
+
if (!options.dryRun)
|
|
230
|
+
this.log.publish({ type: 'rejected', actor, reason: options.reason ?? null, findings, doc: this.name });
|
|
231
|
+
return { status: 'rejected', version: this.versionNo, changed: false, findings, clashes: [] };
|
|
232
|
+
}
|
|
233
|
+
if (equal(candidate, this.draft))
|
|
234
|
+
return { status: 'ok', version: this.versionNo, changed: false, findings, clashes: [] };
|
|
235
|
+
if (options.dryRun)
|
|
236
|
+
return { status: 'ok', version: this.versionNo, changed: true, findings, clashes: [] };
|
|
237
|
+
const id = this.accept(candidate, { actor, reason: options.reason ?? `revert to ${revisionId}`, findings, commit: true, op: 'revert', of: revisionId });
|
|
238
|
+
return { status: 'ok', version: this.versionNo, changed: true, findings, clashes: [], revision: id };
|
|
239
|
+
}
|
|
240
|
+
revertChange(target, options) {
|
|
241
|
+
if (!target.parent)
|
|
242
|
+
throw new TandemError(409, 'nothing_to_undo', 'the first revision has no change to take back');
|
|
243
|
+
const parent = this.store.list().find((r) => r.id === target.parent);
|
|
244
|
+
if (!parent)
|
|
245
|
+
throw new TandemError(409, 'cannot_revert', `the revision before ${target.id} is no longer kept`);
|
|
246
|
+
if (!options.dryRun)
|
|
247
|
+
this.commit();
|
|
248
|
+
const actor = options.actor ?? 'human';
|
|
249
|
+
const current = this.draft;
|
|
250
|
+
const merged = this.adapter.merge
|
|
251
|
+
? this.adapter.merge(target.state, current, parent.state, { actor, writerWins: true })
|
|
252
|
+
: merge3(target.state, current, parent.state, { keyed: this.adapter.keyed });
|
|
253
|
+
const findings = this.adapter.validate?.(merged.merged, { actor }) ?? [];
|
|
254
|
+
const reason = options.reason ?? `undo change ${target.id}`;
|
|
255
|
+
const quiet = options.dryRun === true;
|
|
256
|
+
if (findings.some((f) => f.level === 'block')) {
|
|
257
|
+
if (!quiet)
|
|
258
|
+
this.log.publish({ type: 'rejected', actor, reason, findings, doc: this.name });
|
|
259
|
+
return { status: 'rejected', version: this.versionNo, changed: false, findings, clashes: [] };
|
|
260
|
+
}
|
|
261
|
+
if (quiet || options.onClash === 'refuse') {
|
|
262
|
+
const preview = merged.clashes.map((c) => syncClashRecord(c, this.lastWriter, actor));
|
|
263
|
+
if (options.onClash === 'refuse' && preview.length) {
|
|
264
|
+
const blocked = [...findings, { level: 'block', message: `taking back ${target.id} clashes with later changes at ${preview.map((c) => formatPath(c.path)).join(', ')}` }];
|
|
265
|
+
if (!quiet)
|
|
266
|
+
this.log.publish({ type: 'rejected', actor, reason, findings: blocked, doc: this.name });
|
|
267
|
+
return { status: 'rejected', version: this.versionNo, changed: false, findings: blocked, clashes: preview };
|
|
268
|
+
}
|
|
269
|
+
if (quiet)
|
|
270
|
+
return { status: 'ok', version: this.versionNo, changed: !equal(merged.merged, current), findings, clashes: preview };
|
|
271
|
+
}
|
|
272
|
+
const records = merged.clashes.map((c) => this.recordClash(c, this.lastWriter, actor));
|
|
273
|
+
if (equal(merged.merged, current))
|
|
274
|
+
return { status: 'ok', version: this.versionNo, changed: false, findings, clashes: records };
|
|
275
|
+
const id = this.accept(merged.merged, { actor, reason, findings, commit: true, op: 'revert', of: target.id });
|
|
276
|
+
return { status: 'ok', version: this.versionNo, changed: true, findings, clashes: records, revision: id };
|
|
277
|
+
}
|
|
278
|
+
undo(options = {}) {
|
|
279
|
+
if (options.scope !== undefined && options.scope !== 'state' && options.scope !== 'change')
|
|
280
|
+
throw new TandemError(400, 'bad_request', 'scope must be "state" or "change"');
|
|
281
|
+
this.commit();
|
|
282
|
+
const head = this.head;
|
|
283
|
+
if (options.stack === false) {
|
|
284
|
+
if (!head.parent)
|
|
285
|
+
throw new TandemError(409, 'nothing_to_undo', 'there is nothing to undo');
|
|
286
|
+
const reason = `undo ${head.id}`;
|
|
287
|
+
if (options.scope === 'change')
|
|
288
|
+
return this.revert(head.id, { actor: options.actor, reason, scope: 'change', onClash: options.onClash });
|
|
289
|
+
return this.revert(head.parent, { actor: options.actor, reason });
|
|
290
|
+
}
|
|
291
|
+
const target = this.nextToUndo();
|
|
292
|
+
if (!target)
|
|
293
|
+
throw new TandemError(409, 'nothing_to_undo', 'there is nothing left to undo');
|
|
294
|
+
const reason = `undo change ${target.id}`;
|
|
295
|
+
if (options.scope === 'state')
|
|
296
|
+
return this.revert(target.parent, { actor: options.actor, reason });
|
|
297
|
+
return this.revert(target.id, { actor: options.actor, reason, scope: 'change', onClash: options.onClash });
|
|
298
|
+
}
|
|
299
|
+
// the newest write that has not been taken back: an undo made by a stacking `undo()` marks its target, and undoing that undo clears the mark
|
|
300
|
+
nextToUndo() {
|
|
301
|
+
const all = this.store.list();
|
|
302
|
+
const taken = new Set();
|
|
303
|
+
for (let i = all.length - 1; i >= 0; i--) {
|
|
304
|
+
const r = all[i];
|
|
305
|
+
const marked = r.op === 'revert' ? UNDO_CHANGE.exec(r.reason ?? '') : null;
|
|
306
|
+
if (marked) {
|
|
307
|
+
if (!taken.has(r.id))
|
|
308
|
+
taken.add(marked[1]);
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
if (r.op === 'write' && r.parent && !taken.has(r.id))
|
|
312
|
+
return r;
|
|
313
|
+
}
|
|
314
|
+
return undefined;
|
|
315
|
+
}
|
|
316
|
+
resolveClash(id, choice, actor = 'human') {
|
|
317
|
+
const clash = this.open.get(id);
|
|
318
|
+
if (!clash)
|
|
319
|
+
throw new TandemError(404, 'not_found', `no such clash: ${id}`);
|
|
320
|
+
let delta = [];
|
|
321
|
+
if (choice === 'dropped') {
|
|
322
|
+
delta = clashDelta(this.draft, clash, this.adapter.keyed);
|
|
323
|
+
apply(this.draft, delta);
|
|
324
|
+
}
|
|
325
|
+
this.closeClash(id);
|
|
326
|
+
this.log.publish({ type: 'clash_resolved', id, choice, doc: this.name });
|
|
327
|
+
if (choice === 'kept')
|
|
328
|
+
return { status: 'ok', version: this.versionNo, changed: false, findings: [], clashes: [] };
|
|
329
|
+
return this.write({ version: this.versionNo, delta, actor, reason: `use the other side at ${clash.path.join('.') || '(root)'}`, commit: true });
|
|
330
|
+
}
|
|
331
|
+
reconcile(req) {
|
|
332
|
+
const clientActors = req.actors ?? [];
|
|
333
|
+
if (!Array.isArray(clientActors) || clientActors.some((a) => typeof a !== 'string'))
|
|
334
|
+
throw new TandemError(400, 'bad_request', 'actors must be an array of strings');
|
|
335
|
+
if (req.tie !== undefined && req.tie !== 'client' && req.tie !== 'server')
|
|
336
|
+
throw new TandemError(400, 'bad_request', 'tie must be "client" or "server"');
|
|
337
|
+
if (req.first !== undefined && !['compare', 'client', 'server'].includes(req.first))
|
|
338
|
+
throw new TandemError(400, 'bad_request', 'first must be "compare", "client" or "server"');
|
|
339
|
+
if (req.clashes !== undefined && !Array.isArray(req.clashes))
|
|
340
|
+
throw new TandemError(400, 'bad_request', 'clashes must be an array');
|
|
341
|
+
if (req.closed !== undefined && (!Array.isArray(req.closed) || req.closed.some((id) => typeof id !== 'string')))
|
|
342
|
+
throw new TandemError(400, 'bad_request', 'closed must be an array of strings');
|
|
343
|
+
if (req.mark !== undefined && !Number.isInteger(req.mark))
|
|
344
|
+
throw new TandemError(400, 'bad_request', 'mark must be an integer');
|
|
345
|
+
this.useContentClashIds();
|
|
346
|
+
this.adoptClashes(req.clashes ?? [], req.closed ?? []);
|
|
347
|
+
const serverActors = req.mark === undefined ? ['human'] : this.actorsSince(req.mark, req.site);
|
|
348
|
+
const caller = primaryActor(clientActors, this.wins, 'sync');
|
|
349
|
+
const adapter = this.adapter;
|
|
350
|
+
const result = reconcileStates({
|
|
351
|
+
base: req.base,
|
|
352
|
+
client: { state: req.state, actors: clientActors, pristine: req.pristine },
|
|
353
|
+
server: { state: this.draft, actors: serverActors, pristine: this.pristine },
|
|
354
|
+
tie: req.tie,
|
|
355
|
+
first: req.first,
|
|
356
|
+
wins: this.wins,
|
|
357
|
+
print: adapter.print ?? defaultPrint,
|
|
358
|
+
keyed: adapter.keyed,
|
|
359
|
+
merge: adapter.merge ? (base, mine, theirs, ctx) => adapter.merge(base, mine, theirs, { actor: caller, writerWins: ctx.writerWins }) : undefined,
|
|
360
|
+
});
|
|
361
|
+
const respond = (step, changed, findings) => ({
|
|
362
|
+
step,
|
|
363
|
+
version: this.versionNo,
|
|
364
|
+
mark: this.log.lastSeq,
|
|
365
|
+
actors: serverActors,
|
|
366
|
+
state: this.draft,
|
|
367
|
+
clashes: this.clashes,
|
|
368
|
+
closed: this.closedClashes,
|
|
369
|
+
changed,
|
|
370
|
+
findings,
|
|
371
|
+
});
|
|
372
|
+
if (result.step !== 'push' && result.step !== 'merge')
|
|
373
|
+
return respond(result.step, false, []);
|
|
374
|
+
const candidate = result.state;
|
|
375
|
+
const findings = adapter.validate?.(candidate, { actor: caller }) ?? [];
|
|
376
|
+
if (findings.some((f) => f.level === 'block')) {
|
|
377
|
+
this.log.publish({ type: 'rejected', actor: caller, reason: `sync from ${req.site ?? 'a replica'}`, findings, doc: this.name });
|
|
378
|
+
return respond('rejected', false, findings);
|
|
379
|
+
}
|
|
380
|
+
if (result.step === 'merge') {
|
|
381
|
+
const keptActor = result.winner === 'client' ? caller : primaryActor(serverActors, this.wins, 'sync');
|
|
382
|
+
const droppedActor = result.winner === 'client' ? primaryActor(serverActors, this.wins, 'sync') : caller;
|
|
383
|
+
for (const clash of result.clashes) {
|
|
384
|
+
const record = syncClashRecord(clash, keptActor, droppedActor);
|
|
385
|
+
if (!this.open.has(record.id) && !this.closedIds.includes(record.id))
|
|
386
|
+
this.openClash(record);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
const changed = !equal(candidate, this.draft);
|
|
390
|
+
if (changed)
|
|
391
|
+
this.accept(candidate, { actor: caller, reason: `sync ${result.step} from ${req.site ?? 'a replica'}`, findings, commit: true, via: req.site });
|
|
392
|
+
return respond(result.step, changed, findings.filter((f) => f.level === 'warn'));
|
|
393
|
+
}
|
|
394
|
+
dispose() {
|
|
395
|
+
this.commit();
|
|
396
|
+
}
|
|
397
|
+
recordClash(clash, keptActor, droppedActor) {
|
|
398
|
+
const record = this.contentIds
|
|
399
|
+
? syncClashRecord(clash, keptActor, droppedActor)
|
|
400
|
+
: {
|
|
401
|
+
id: `c${++this.clashCount}`,
|
|
402
|
+
path: clash.path,
|
|
403
|
+
kept: clash.mine === undefined ? null : clash.mine,
|
|
404
|
+
dropped: clash.theirs === undefined ? null : clash.theirs,
|
|
405
|
+
kept_actor: keptActor,
|
|
406
|
+
dropped_actor: droppedActor,
|
|
407
|
+
};
|
|
408
|
+
return this.openClash(record);
|
|
409
|
+
}
|
|
410
|
+
openClash(record) {
|
|
411
|
+
this.open.set(record.id, record);
|
|
412
|
+
this.persistClashes();
|
|
413
|
+
this.log.publish({ type: 'clash', id: record.id, path: record.path, kept_actor: record.kept_actor, dropped_actor: record.dropped_actor, doc: this.name });
|
|
414
|
+
return record;
|
|
415
|
+
}
|
|
416
|
+
closeClash(id) {
|
|
417
|
+
this.open.delete(id);
|
|
418
|
+
if (!this.closedIds.includes(id))
|
|
419
|
+
this.closedIds.push(id);
|
|
420
|
+
if (this.closedIds.length > MAX_CLOSED_CLASHES)
|
|
421
|
+
this.closedIds.splice(0, this.closedIds.length - MAX_CLOSED_CLASHES);
|
|
422
|
+
this.persistClashes();
|
|
423
|
+
}
|
|
424
|
+
persistClashes() {
|
|
425
|
+
this.clashStore.save({ open: [...this.open.values()], closed: this.closedIds, count: this.clashCount, ...(this.contentIds ? { ids: 'content' } : {}) });
|
|
426
|
+
}
|
|
427
|
+
persist() {
|
|
428
|
+
this.snapshotStore?.save({
|
|
429
|
+
version: this.versionNo,
|
|
430
|
+
state: this.draft,
|
|
431
|
+
last_writer: this.lastWriter,
|
|
432
|
+
pending: this.pending ? { actor: this.pending.actor, reasons: this.pending.reasons, findings: this.pending.findings } : null,
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
adoptClashes(records, closed) {
|
|
436
|
+
const known = new Set(this.closedIds);
|
|
437
|
+
const opened = [];
|
|
438
|
+
const shut = [];
|
|
439
|
+
for (const id of closed) {
|
|
440
|
+
known.add(id);
|
|
441
|
+
if (!this.open.has(id)) {
|
|
442
|
+
if (!this.closedIds.includes(id))
|
|
443
|
+
this.closedIds.push(id);
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
this.closeClash(id);
|
|
447
|
+
shut.push(id);
|
|
448
|
+
this.log.publish({ type: 'clash_resolved', id, choice: 'kept', via: 'sync', doc: this.name });
|
|
449
|
+
}
|
|
450
|
+
for (const record of records) {
|
|
451
|
+
const identity = contentClashId(record.path, record.kept, record.dropped);
|
|
452
|
+
if (known.has(record.id) || known.has(identity))
|
|
453
|
+
continue;
|
|
454
|
+
const twin = [...this.open.values()].find((own) => own.id === identity || contentClashId(own.path, own.kept, own.dropped) === identity);
|
|
455
|
+
if (twin) {
|
|
456
|
+
const label = (r) => `${r.kept_actor}\u0000${r.dropped_actor}`;
|
|
457
|
+
if (label(record) < label(twin))
|
|
458
|
+
this.open.set(twin.id, { ...twin, kept_actor: record.kept_actor, dropped_actor: record.dropped_actor });
|
|
459
|
+
continue;
|
|
460
|
+
}
|
|
461
|
+
const id = this.open.has(record.id) ? identity : record.id;
|
|
462
|
+
opened.push(this.openClash({ ...record, id, path: [...record.path] }));
|
|
463
|
+
}
|
|
464
|
+
if (this.closedIds.length > MAX_CLOSED_CLASHES)
|
|
465
|
+
this.closedIds.splice(0, this.closedIds.length - MAX_CLOSED_CLASHES);
|
|
466
|
+
this.persistClashes();
|
|
467
|
+
return { opened, closed: shut };
|
|
468
|
+
}
|
|
469
|
+
accept(candidate, meta) {
|
|
470
|
+
const before = this.draft;
|
|
471
|
+
if (this.pending && this.pending.actor !== meta.actor)
|
|
472
|
+
this.commit();
|
|
473
|
+
if (!this.pending)
|
|
474
|
+
this.pending = { actor: meta.actor, reasons: [], findings: [], from: before };
|
|
475
|
+
if (meta.reason)
|
|
476
|
+
this.pending.reasons.push(meta.reason);
|
|
477
|
+
this.pending.findings.push(...meta.findings.filter((f) => f.level === 'warn'));
|
|
478
|
+
this.draft = candidate;
|
|
479
|
+
this.versionNo += 1;
|
|
480
|
+
this.lastWriter = meta.actor;
|
|
481
|
+
this.remembered.set(this.versionNo, candidate);
|
|
482
|
+
for (const key of this.remembered.keys()) {
|
|
483
|
+
if (key <= this.versionNo - this.keptStates)
|
|
484
|
+
this.remembered.delete(key);
|
|
485
|
+
}
|
|
486
|
+
const delta = meta.delta ?? diff(before, candidate);
|
|
487
|
+
const warns = meta.findings.filter((f) => f.level === 'warn');
|
|
488
|
+
const summary = this.adapter.summarize?.(before, candidate) ?? formatDelta(delta, 300);
|
|
489
|
+
const immediate = meta.commit ?? (meta.actor !== 'human' || this.policy === 'immediate');
|
|
490
|
+
this.persist();
|
|
491
|
+
let revisionId;
|
|
492
|
+
if (immediate) {
|
|
493
|
+
const revision = meta.op === 'revert' ? this.commitRevert(meta) : this.commit();
|
|
494
|
+
revisionId = revision?.id;
|
|
495
|
+
}
|
|
496
|
+
else {
|
|
497
|
+
this.schedule();
|
|
498
|
+
}
|
|
499
|
+
this.log.publish({
|
|
500
|
+
type: 'change',
|
|
501
|
+
version: this.versionNo,
|
|
502
|
+
actor: meta.actor,
|
|
503
|
+
reason: meta.reason,
|
|
504
|
+
delta,
|
|
505
|
+
revision: revisionId ?? null,
|
|
506
|
+
summary,
|
|
507
|
+
findings: warns,
|
|
508
|
+
doc: this.name,
|
|
509
|
+
...(meta.via ? { via: meta.via } : {}),
|
|
510
|
+
});
|
|
511
|
+
return revisionId;
|
|
512
|
+
}
|
|
513
|
+
commitRevert(meta) {
|
|
514
|
+
const pending = this.pending;
|
|
515
|
+
this.pending = undefined;
|
|
516
|
+
this.clearTimers();
|
|
517
|
+
const prior = this.last();
|
|
518
|
+
const revision = this.revision({
|
|
519
|
+
op: 'revert',
|
|
520
|
+
actor: meta.actor,
|
|
521
|
+
reason: meta.reason,
|
|
522
|
+
delta: diff(pending.from, this.draft),
|
|
523
|
+
state: this.draft,
|
|
524
|
+
findings: meta.findings,
|
|
525
|
+
parent: prior.id,
|
|
526
|
+
of: meta.of,
|
|
527
|
+
});
|
|
528
|
+
this.store.append(revision);
|
|
529
|
+
this.persist();
|
|
530
|
+
return revision;
|
|
531
|
+
}
|
|
532
|
+
revision(parts) {
|
|
533
|
+
return { id: `r${++this.revisionCount}`, version: this.versionNo, at: this.clock(), ...parts };
|
|
534
|
+
}
|
|
535
|
+
schedule() {
|
|
536
|
+
if (typeof this.policy === 'string' || !this.pending)
|
|
537
|
+
return;
|
|
538
|
+
const { quietMs, maxMs } = this.policy;
|
|
539
|
+
if (this.quietTimer)
|
|
540
|
+
clearTimeout(this.quietTimer);
|
|
541
|
+
this.quietTimer = setTimeout(() => this.commit(), quietMs);
|
|
542
|
+
this.quietTimer.unref?.();
|
|
543
|
+
if (!this.maxTimer) {
|
|
544
|
+
this.maxTimer = setTimeout(() => this.commit(), maxMs);
|
|
545
|
+
this.maxTimer.unref?.();
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
clearTimers() {
|
|
549
|
+
if (this.quietTimer)
|
|
550
|
+
clearTimeout(this.quietTimer);
|
|
551
|
+
if (this.maxTimer)
|
|
552
|
+
clearTimeout(this.maxTimer);
|
|
553
|
+
this.quietTimer = undefined;
|
|
554
|
+
this.maxTimer = undefined;
|
|
555
|
+
}
|
|
556
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tandem-kit-core",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Tandem core: event protocol, delta, three-way merge, working copy, revisions, client.",
|
|
5
5
|
"license": "MIT",
|
|
6
|
-
"
|
|
7
|
-
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/Leppy-oss/tandem.git",
|
|
9
|
+
"directory": "packages/core"
|
|
10
|
+
},
|
|
11
|
+
"type": "module",
|
|
12
|
+
"sideEffects": false,
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"browser": {
|
|
16
|
+
"types": "./dist/src/browser.d.ts",
|
|
17
|
+
"default": "./dist/src/browser.js"
|
|
18
|
+
},
|
|
19
|
+
"types": "./dist/src/index.d.ts",
|
|
20
|
+
"default": "./dist/src/index.js"
|
|
21
|
+
},
|
|
22
|
+
"./package.json": "./package.json"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"README.md",
|
|
27
|
+
"LICENSE"
|
|
28
|
+
],
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public"
|
|
31
|
+
},
|
|
32
|
+
"scripts": {
|
|
33
|
+
"test": "node --test --test-reporter=spec test/*.test.ts"
|
|
34
|
+
},
|
|
35
|
+
"main": "./dist/src/index.js",
|
|
36
|
+
"types": "./dist/src/index.d.ts"
|
|
37
|
+
}
|