@tearleads/client-sdk 0.1.206 → 0.1.208
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/client/documents/index.d.ts +8 -0
- package/client/documents/index.js +14 -1
- package/client/documents/index.js.map +1 -1
- package/client/index.d.ts +1 -1
- package/client/index.js.map +1 -1
- package/data/documents/documentRestore.d.ts +30 -0
- package/data/documents/documentRestore.js +77 -0
- package/data/documents/documentRestore.js.map +1 -0
- package/data/documents/documentRowList.d.ts +6 -0
- package/data/documents/documentRowList.js +31 -0
- package/data/documents/documentRowList.js.map +1 -1
- package/data/documents/index.d.ts +1 -0
- package/data/documents/index.js.map +1 -1
- package/data/persistence/organizations/organizationDataUsagePersistence.js +90 -82
- package/data/persistence/organizations/organizationDataUsagePersistence.js.map +1 -1
- package/index.d.ts +3 -3
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/internal/loro/historyTimeline.d.ts +57 -0
- package/internal/loro/historyTimeline.js +271 -0
- package/internal/loro/historyTimeline.js.map +1 -0
- package/internal/loro/index.d.ts +1 -0
- package/internal/loro/index.js +1 -0
- package/internal/loro/index.js.map +1 -1
- package/package.json +1 -1
- package/stores/documents/documentStore/history/restoreContent.js +127 -0
- package/stores/documents/documentStore/history/restoreContent.js.map +1 -0
- package/stores/documents/documentStore/index.js +4 -4
- package/stores/documents/documentStore/index.js.map +1 -1
- package/stores/documents/documentStore/mutations.js +1 -1
- package/stores/documents/documentStore/mutations.js.map +1 -1
- package/stores/documents/documentStore/rows/index.js +8 -0
- package/stores/documents/documentStore/rows/index.js.map +1 -1
- package/stores/documents/registry.js +1 -0
- package/stores/documents/registry.js.map +1 -1
- package/stores/documents/removedDocumentStore.js +1 -0
- package/stores/documents/removedDocumentStore.js.map +1 -1
- package/stores/documents/types.d.ts +10 -1
- package/stores/documents/types.js.map +1 -1
- package/workflows/documents/history/documentHistory.d.ts +72 -0
- package/workflows/documents/history/documentHistory.js +103 -0
- package/workflows/documents/history/documentHistory.js.map +1 -0
- package/workflows/documents/history/documentHistoryChange.d.ts +51 -0
- package/workflows/documents/history/documentHistoryChange.js +110 -0
- package/workflows/documents/history/documentHistoryChange.js.map +1 -0
- package/workflows/documents/index.d.ts +2 -0
- package/workflows/documents/index.js +2 -0
- package/workflows/documents/index.js.map +1 -1
- package/workflows/organizations/readModel/dataUsageReadModel.js +4 -5
- package/workflows/organizations/readModel/dataUsageReadModel.js.map +1 -1
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import { LoroDoc, VersionVector } from "loro-crdt";
|
|
2
|
+
/**
|
|
3
|
+
* A document that only ever imports and reads. It has no stable peer and does
|
|
4
|
+
* not record change times, so it must never author.
|
|
5
|
+
*/
|
|
6
|
+
export function createReadOnlyDocument() {
|
|
7
|
+
return new LoroDoc();
|
|
8
|
+
}
|
|
9
|
+
function comparePeerIds(left, right) {
|
|
10
|
+
// Peer ids are decimal strings of unequal length: order them numerically.
|
|
11
|
+
if (left.length !== right.length)
|
|
12
|
+
return left.length - right.length;
|
|
13
|
+
return left < right ? -1 : Number(left > right);
|
|
14
|
+
}
|
|
15
|
+
function playsBefore(left, right) {
|
|
16
|
+
if (left.time !== right.time)
|
|
17
|
+
return left.time < right.time;
|
|
18
|
+
if (left.stop.lamport !== right.stop.lamport) {
|
|
19
|
+
return left.stop.lamport < right.stop.lamport;
|
|
20
|
+
}
|
|
21
|
+
const peerOrder = comparePeerIds(left.stop.peerId, right.stop.peerId);
|
|
22
|
+
if (peerOrder !== 0)
|
|
23
|
+
return peerOrder < 0;
|
|
24
|
+
return left.stop.startCounter < right.stop.startCounter;
|
|
25
|
+
}
|
|
26
|
+
/** A binary min-heap of node indexes ordered by {@link playsBefore}. */
|
|
27
|
+
class ReadyQueue {
|
|
28
|
+
nodes;
|
|
29
|
+
heap = [];
|
|
30
|
+
constructor(nodes) {
|
|
31
|
+
this.nodes = nodes;
|
|
32
|
+
}
|
|
33
|
+
get size() {
|
|
34
|
+
return this.heap.length;
|
|
35
|
+
}
|
|
36
|
+
push(nodeIndex) {
|
|
37
|
+
const { heap } = this;
|
|
38
|
+
let position = heap.length;
|
|
39
|
+
heap.push(nodeIndex);
|
|
40
|
+
while (position > 0) {
|
|
41
|
+
const parent = (position - 1) >> 1;
|
|
42
|
+
if (!this.before(heap[position], heap[parent]))
|
|
43
|
+
break;
|
|
44
|
+
this.swap(position, parent);
|
|
45
|
+
position = parent;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
pop() {
|
|
49
|
+
const { heap } = this;
|
|
50
|
+
const first = heap[0];
|
|
51
|
+
const last = heap.pop();
|
|
52
|
+
if (first === undefined || last === undefined)
|
|
53
|
+
return undefined;
|
|
54
|
+
if (heap.length === 0)
|
|
55
|
+
return first;
|
|
56
|
+
heap[0] = last;
|
|
57
|
+
let position = 0;
|
|
58
|
+
for (;;) {
|
|
59
|
+
const left = position * 2 + 1;
|
|
60
|
+
const right = left + 1;
|
|
61
|
+
let smallest = position;
|
|
62
|
+
if (this.before(heap[left], heap[smallest]))
|
|
63
|
+
smallest = left;
|
|
64
|
+
if (this.before(heap[right], heap[smallest]))
|
|
65
|
+
smallest = right;
|
|
66
|
+
if (smallest === position)
|
|
67
|
+
break;
|
|
68
|
+
this.swap(position, smallest);
|
|
69
|
+
position = smallest;
|
|
70
|
+
}
|
|
71
|
+
return first;
|
|
72
|
+
}
|
|
73
|
+
before(left, right) {
|
|
74
|
+
const leftNode = left === undefined ? undefined : this.nodes[left];
|
|
75
|
+
const rightNode = right === undefined ? undefined : this.nodes[right];
|
|
76
|
+
return (leftNode !== undefined &&
|
|
77
|
+
rightNode !== undefined &&
|
|
78
|
+
playsBefore(leftNode, rightNode));
|
|
79
|
+
}
|
|
80
|
+
swap(left, right) {
|
|
81
|
+
const { heap } = this;
|
|
82
|
+
const leftValue = heap[left];
|
|
83
|
+
const rightValue = heap[right];
|
|
84
|
+
if (leftValue === undefined || rightValue === undefined)
|
|
85
|
+
return;
|
|
86
|
+
heap[left] = rightValue;
|
|
87
|
+
heap[right] = leftValue;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** Index of the peer's change that holds `counter`, or -1 when none does. */
|
|
91
|
+
function findChangeIndex(peerNodes, counter) {
|
|
92
|
+
let low = 0;
|
|
93
|
+
let high = peerNodes.length - 1;
|
|
94
|
+
while (low <= high) {
|
|
95
|
+
const middle = (low + high) >> 1;
|
|
96
|
+
const candidate = peerNodes[middle];
|
|
97
|
+
if (candidate === undefined)
|
|
98
|
+
return -1;
|
|
99
|
+
if (counter < candidate.stop.startCounter) {
|
|
100
|
+
high = middle - 1;
|
|
101
|
+
}
|
|
102
|
+
else if (counter >= candidate.stop.endCounter) {
|
|
103
|
+
low = middle + 1;
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
return candidate.index;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return -1;
|
|
110
|
+
}
|
|
111
|
+
function toHistoryStop(peerId, change) {
|
|
112
|
+
return {
|
|
113
|
+
peerId,
|
|
114
|
+
startCounter: change.counter,
|
|
115
|
+
endCounter: change.counter + change.length,
|
|
116
|
+
lamport: change.lamport,
|
|
117
|
+
timestamp: change.timestamp > 0 ? change.timestamp : null,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
function buildTimelineGraph(changes) {
|
|
121
|
+
const graph = {
|
|
122
|
+
nodes: [],
|
|
123
|
+
nodesByPeer: new Map(),
|
|
124
|
+
declaredDependencies: [],
|
|
125
|
+
};
|
|
126
|
+
for (const [peerId, peerChanges] of changes) {
|
|
127
|
+
const peerNodes = [];
|
|
128
|
+
const ordered = [...peerChanges].sort((left, right) => left.counter - right.counter);
|
|
129
|
+
for (const change of ordered) {
|
|
130
|
+
const stop = toHistoryStop(peerId, change);
|
|
131
|
+
peerNodes.push({ index: graph.nodes.length, stop });
|
|
132
|
+
graph.nodes.push({
|
|
133
|
+
stop,
|
|
134
|
+
time: stop.timestamp ?? 0,
|
|
135
|
+
dependents: [],
|
|
136
|
+
unmetDependencies: 0,
|
|
137
|
+
});
|
|
138
|
+
graph.declaredDependencies.push(change.deps);
|
|
139
|
+
}
|
|
140
|
+
graph.nodesByPeer.set(peerId, peerNodes);
|
|
141
|
+
}
|
|
142
|
+
return graph;
|
|
143
|
+
}
|
|
144
|
+
/** The nodes that must play before `peerNodes[position]`. */
|
|
145
|
+
function dependenciesOf(graph, peerNodes, position) {
|
|
146
|
+
const dependencies = new Set();
|
|
147
|
+
const current = peerNodes[position];
|
|
148
|
+
if (current === undefined)
|
|
149
|
+
return dependencies;
|
|
150
|
+
// A peer's own changes always play in counter order.
|
|
151
|
+
const previous = peerNodes[position - 1];
|
|
152
|
+
if (previous !== undefined)
|
|
153
|
+
dependencies.add(previous.index);
|
|
154
|
+
for (const dependency of graph.declaredDependencies[current.index] ?? []) {
|
|
155
|
+
const holder = findChangeIndex(graph.nodesByPeer.get(dependency.peer) ?? [], dependency.counter);
|
|
156
|
+
// History that is not held locally cannot be ordered against.
|
|
157
|
+
if (holder >= 0 && holder !== current.index)
|
|
158
|
+
dependencies.add(holder);
|
|
159
|
+
}
|
|
160
|
+
return dependencies;
|
|
161
|
+
}
|
|
162
|
+
function linkDependencies(graph) {
|
|
163
|
+
for (const peerNodes of graph.nodesByPeer.values()) {
|
|
164
|
+
for (const [position, { index }] of peerNodes.entries()) {
|
|
165
|
+
const node = graph.nodes[index];
|
|
166
|
+
if (node === undefined)
|
|
167
|
+
continue;
|
|
168
|
+
const dependencies = dependenciesOf(graph, peerNodes, position);
|
|
169
|
+
node.unmetDependencies = dependencies.size;
|
|
170
|
+
for (const dependency of dependencies) {
|
|
171
|
+
graph.nodes[dependency]?.dependents.push(index);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/** Play every node whose dependencies have played, earliest first. */
|
|
177
|
+
function playInOrder(nodes) {
|
|
178
|
+
const ready = new ReadyQueue(nodes);
|
|
179
|
+
for (const [index, node] of nodes.entries()) {
|
|
180
|
+
if (node.unmetDependencies === 0)
|
|
181
|
+
ready.push(index);
|
|
182
|
+
}
|
|
183
|
+
const stops = [];
|
|
184
|
+
for (let index = ready.pop(); index !== undefined; index = ready.pop()) {
|
|
185
|
+
const node = nodes[index];
|
|
186
|
+
if (node === undefined)
|
|
187
|
+
continue;
|
|
188
|
+
stops.push(node.stop);
|
|
189
|
+
for (const dependent of node.dependents) {
|
|
190
|
+
const dependentNode = nodes[dependent];
|
|
191
|
+
if (dependentNode === undefined)
|
|
192
|
+
continue;
|
|
193
|
+
dependentNode.unmetDependencies -= 1;
|
|
194
|
+
if (dependentNode.unmetDependencies === 0)
|
|
195
|
+
ready.push(dependent);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return stops;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Order every change into one timeline: by recorded time, then Lamport time,
|
|
202
|
+
* then peer. A change never plays before a change it depends on, whatever
|
|
203
|
+
* times were recorded, so every prefix of the result is a real version of the
|
|
204
|
+
* document. Honest writers already record times that respect dependencies (a
|
|
205
|
+
* change is never stamped earlier than the newest time its document holds);
|
|
206
|
+
* the dependency check keeps a wrong or hostile clock from producing a prefix
|
|
207
|
+
* that was never a version.
|
|
208
|
+
*/
|
|
209
|
+
export function orderHistoryStops(changes) {
|
|
210
|
+
const graph = buildTimelineGraph(changes);
|
|
211
|
+
linkDependencies(graph);
|
|
212
|
+
const stops = playInOrder(graph.nodes);
|
|
213
|
+
if (stops.length !== graph.nodes.length) {
|
|
214
|
+
// Unreachable for a real document: its changes form an acyclic graph.
|
|
215
|
+
throw new Error("Document history has a dependency cycle.");
|
|
216
|
+
}
|
|
217
|
+
return stops;
|
|
218
|
+
}
|
|
219
|
+
class LoroHistoryViewer {
|
|
220
|
+
doc;
|
|
221
|
+
stops;
|
|
222
|
+
/** The version after `stops[0..cursorIndex]`, extended as the cursor moves. */
|
|
223
|
+
cursorIndex = -1;
|
|
224
|
+
cursorVersion = new Map();
|
|
225
|
+
constructor(doc) {
|
|
226
|
+
this.doc = doc;
|
|
227
|
+
doc.detach();
|
|
228
|
+
this.stops = orderHistoryStops(doc.getAllChanges());
|
|
229
|
+
}
|
|
230
|
+
checkout(index) {
|
|
231
|
+
this.doc.checkout(this.versionAt(index).map(({ counter, peerId }) => ({
|
|
232
|
+
counter,
|
|
233
|
+
peer: peerId,
|
|
234
|
+
})));
|
|
235
|
+
// Checking out the newest version re-attaches the document, which would
|
|
236
|
+
// make it editable; a viewer is read-only at every stop.
|
|
237
|
+
this.doc.detach();
|
|
238
|
+
}
|
|
239
|
+
versionAt(index) {
|
|
240
|
+
if (!Number.isInteger(index) || index < -1 || index >= this.stops.length) {
|
|
241
|
+
throw new RangeError(`History stop ${index} is out of range.`);
|
|
242
|
+
}
|
|
243
|
+
if (index < this.cursorIndex) {
|
|
244
|
+
this.cursorIndex = -1;
|
|
245
|
+
this.cursorVersion = new Map();
|
|
246
|
+
}
|
|
247
|
+
while (this.cursorIndex < index) {
|
|
248
|
+
this.cursorIndex += 1;
|
|
249
|
+
const stop = this.stops[this.cursorIndex];
|
|
250
|
+
if (stop !== undefined) {
|
|
251
|
+
this.cursorVersion.set(stop.peerId, stop.endCounter);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return this.doc
|
|
255
|
+
.vvToFrontiers(VersionVector.parseJSON(this.cursorVersion))
|
|
256
|
+
.map(({ counter, peer }) => ({ counter, peerId: peer }));
|
|
257
|
+
}
|
|
258
|
+
free() {
|
|
259
|
+
this.doc.free();
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Build a timeline over a document that already holds the history to browse,
|
|
264
|
+
* and take ownership of it. Pass a scratch document from
|
|
265
|
+
* {@link createReadOnlyDocument}, never a document that is being edited:
|
|
266
|
+
* checking out a version makes the document read-only.
|
|
267
|
+
*/
|
|
268
|
+
export function openHistoryViewer(doc) {
|
|
269
|
+
return new LoroHistoryViewer(doc);
|
|
270
|
+
}
|
|
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AI,CAAC,WAAW,IAAI,CAAC,CAAC;YACtB,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YAC1C,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;gBACvB,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;YACvD,CAAC;QACH,CAAC;QACD,OAAO,IAAI,CAAC,GAAG;aACZ,aAAa,CAAC,aAAa,CAAC,SAAS,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;aAC1D,GAAG,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAC7D,CAAC;IAED,IAAI;QACF,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;IAClB,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,GAAY;IAC5C,OAAO,IAAI,iBAAiB,CAAC,GAAG,CAAC,CAAC;AACpC,CAAC","sourcesContent":["import { type Change, LoroDoc, type PeerID, VersionVector } from \"loro-crdt\";\n\n/** One step of a document's history: a single change by a single peer. */\nexport interface HistoryStop {\n peerId: PeerID;\n /** Counter of the change's first operation. */\n startCounter: number;\n /** One past the counter of the change's last operation. */\n endCounter: number;\n lamport: number;\n /** Unix seconds the writer recorded, or null when the change carries none. */\n timestamp: number | null;\n}\n\n/** One entry of a version: the last operation it includes for a peer. */\nexport interface HistoryVersionEntry {\n peerId: PeerID;\n counter: number;\n}\n\nexport interface HistoryViewer {\n /**\n * The scratch document, showing the version last checked out. Read it; do\n * not edit it. It is detached from its own latest version.\n */\n readonly doc: LoroDoc;\n /** Every change in the document, in the order the timeline plays them. */\n readonly stops: ReadonlyArray<HistoryStop>;\n /**\n * Show the document as it was after `stops[0..index]`. `-1` shows the empty\n * document before the first change.\n */\n checkout(index: number): void;\n /** The version after `stops[0..index]`, as the operations that head it. */\n versionAt(index: number): HistoryVersionEntry[];\n /** Release the WASM document. The viewer is unusable afterwards. */\n free(): void;\n}\n\n/**\n * A document that only ever imports and reads. It has no stable peer and does\n * not record change times, so it must never author.\n */\nexport function createReadOnlyDocument(): LoroDoc {\n return new LoroDoc();\n}\n\nfunction comparePeerIds(left: PeerID, right: PeerID): number {\n // Peer ids are decimal strings of unequal length: order them numerically.\n if (left.length !== right.length) return left.length - right.length;\n return left < right ? -1 : Number(left > right);\n}\n\ninterface TimelineNode {\n readonly stop: HistoryStop;\n /** Sort key: the recorded time, or 0 when there is none. */\n readonly time: number;\n /** Nodes that cannot play before this one. */\n readonly dependents: number[];\n unmetDependencies: number;\n}\n\nfunction playsBefore(left: TimelineNode, right: TimelineNode): boolean {\n if (left.time !== right.time) return left.time < right.time;\n if (left.stop.lamport !== right.stop.lamport) {\n return left.stop.lamport < right.stop.lamport;\n }\n const peerOrder = comparePeerIds(left.stop.peerId, right.stop.peerId);\n if (peerOrder !== 0) return peerOrder < 0;\n return left.stop.startCounter < right.stop.startCounter;\n}\n\n/** A binary min-heap of node indexes ordered by {@link playsBefore}. */\nclass ReadyQueue {\n private readonly heap: number[] = [];\n\n constructor(private readonly nodes: readonly TimelineNode[]) {}\n\n get size(): number {\n return this.heap.length;\n }\n\n push(nodeIndex: number): void {\n const { heap } = this;\n let position = heap.length;\n heap.push(nodeIndex);\n while (position > 0) {\n const parent = (position - 1) >> 1;\n if (!this.before(heap[position], heap[parent])) break;\n this.swap(position, parent);\n position = parent;\n }\n }\n\n pop(): number | undefined {\n const { heap } = this;\n const first = heap[0];\n const last = heap.pop();\n if (first === undefined || last === undefined) return undefined;\n if (heap.length === 0) return first;\n heap[0] = last;\n let position = 0;\n for (;;) {\n const left = position * 2 + 1;\n const right = left + 1;\n let smallest = position;\n if (this.before(heap[left], heap[smallest])) smallest = left;\n if (this.before(heap[right], heap[smallest])) smallest = right;\n if (smallest === position) break;\n this.swap(position, smallest);\n position = smallest;\n }\n return first;\n }\n\n private before(left: number | undefined, right: number | undefined): boolean {\n const leftNode = left === undefined ? undefined : this.nodes[left];\n const rightNode = right === undefined ? undefined : this.nodes[right];\n return (\n leftNode !== undefined &&\n rightNode !== undefined &&\n playsBefore(leftNode, rightNode)\n );\n }\n\n private swap(left: number, right: number): void {\n const { heap } = this;\n const leftValue = heap[left];\n const rightValue = heap[right];\n if (leftValue === undefined || rightValue === undefined) return;\n heap[left] = rightValue;\n heap[right] = leftValue;\n }\n}\n\ninterface PeerNode {\n readonly index: number;\n readonly stop: HistoryStop;\n}\n\ninterface TimelineGraph {\n readonly nodes: TimelineNode[];\n readonly nodesByPeer: Map<PeerID, PeerNode[]>;\n /** The dependencies each change declares, by node index. */\n readonly declaredDependencies: Change[\"deps\"][];\n}\n\n/** Index of the peer's change that holds `counter`, or -1 when none does. */\nfunction findChangeIndex(\n peerNodes: readonly PeerNode[],\n counter: number,\n): number {\n let low = 0;\n let high = peerNodes.length - 1;\n while (low <= high) {\n const middle = (low + high) >> 1;\n const candidate = peerNodes[middle];\n if (candidate === undefined) return -1;\n if (counter < candidate.stop.startCounter) {\n high = middle - 1;\n } else if (counter >= candidate.stop.endCounter) {\n low = middle + 1;\n } else {\n return candidate.index;\n }\n }\n return -1;\n}\n\nfunction toHistoryStop(peerId: PeerID, change: Change): HistoryStop {\n return {\n peerId,\n startCounter: change.counter,\n endCounter: change.counter + change.length,\n lamport: change.lamport,\n timestamp: change.timestamp > 0 ? change.timestamp : null,\n };\n}\n\nfunction buildTimelineGraph(\n changes: ReadonlyMap<PeerID, readonly Change[]>,\n): TimelineGraph {\n const graph: TimelineGraph = {\n nodes: [],\n nodesByPeer: new Map(),\n declaredDependencies: [],\n };\n for (const [peerId, peerChanges] of changes) {\n const peerNodes: PeerNode[] = [];\n const ordered = [...peerChanges].sort(\n (left, right) => left.counter - right.counter,\n );\n for (const change of ordered) {\n const stop = toHistoryStop(peerId, change);\n peerNodes.push({ index: graph.nodes.length, stop });\n graph.nodes.push({\n stop,\n time: stop.timestamp ?? 0,\n dependents: [],\n unmetDependencies: 0,\n });\n graph.declaredDependencies.push(change.deps);\n }\n graph.nodesByPeer.set(peerId, peerNodes);\n }\n return graph;\n}\n\n/** The nodes that must play before `peerNodes[position]`. */\nfunction dependenciesOf(\n graph: TimelineGraph,\n peerNodes: readonly PeerNode[],\n position: number,\n): Set<number> {\n const dependencies = new Set<number>();\n const current = peerNodes[position];\n if (current === undefined) return dependencies;\n // A peer's own changes always play in counter order.\n const previous = peerNodes[position - 1];\n if (previous !== undefined) dependencies.add(previous.index);\n for (const dependency of graph.declaredDependencies[current.index] ?? []) {\n const holder = findChangeIndex(\n graph.nodesByPeer.get(dependency.peer) ?? [],\n dependency.counter,\n );\n // History that is not held locally cannot be ordered against.\n if (holder >= 0 && holder !== current.index) dependencies.add(holder);\n }\n return dependencies;\n}\n\nfunction linkDependencies(graph: TimelineGraph): void {\n for (const peerNodes of graph.nodesByPeer.values()) {\n for (const [position, { index }] of peerNodes.entries()) {\n const node = graph.nodes[index];\n if (node === undefined) continue;\n const dependencies = dependenciesOf(graph, peerNodes, position);\n node.unmetDependencies = dependencies.size;\n for (const dependency of dependencies) {\n graph.nodes[dependency]?.dependents.push(index);\n }\n }\n }\n}\n\n/** Play every node whose dependencies have played, earliest first. */\nfunction playInOrder(nodes: readonly TimelineNode[]): HistoryStop[] {\n const ready = new ReadyQueue(nodes);\n for (const [index, node] of nodes.entries()) {\n if (node.unmetDependencies === 0) ready.push(index);\n }\n const stops: HistoryStop[] = [];\n for (let index = ready.pop(); index !== undefined; index = ready.pop()) {\n const node = nodes[index];\n if (node === undefined) continue;\n stops.push(node.stop);\n for (const dependent of node.dependents) {\n const dependentNode = nodes[dependent];\n if (dependentNode === undefined) continue;\n dependentNode.unmetDependencies -= 1;\n if (dependentNode.unmetDependencies === 0) ready.push(dependent);\n }\n }\n return stops;\n}\n\n/**\n * Order every change into one timeline: by recorded time, then Lamport time,\n * then peer. A change never plays before a change it depends on, whatever\n * times were recorded, so every prefix of the result is a real version of the\n * document. Honest writers already record times that respect dependencies (a\n * change is never stamped earlier than the newest time its document holds);\n * the dependency check keeps a wrong or hostile clock from producing a prefix\n * that was never a version.\n */\nexport function orderHistoryStops(\n changes: ReadonlyMap<PeerID, readonly Change[]>,\n): HistoryStop[] {\n const graph = buildTimelineGraph(changes);\n linkDependencies(graph);\n const stops = playInOrder(graph.nodes);\n if (stops.length !== graph.nodes.length) {\n // Unreachable for a real document: its changes form an acyclic graph.\n throw new Error(\"Document history has a dependency cycle.\");\n }\n return stops;\n}\n\nclass LoroHistoryViewer implements HistoryViewer {\n readonly stops: ReadonlyArray<HistoryStop>;\n /** The version after `stops[0..cursorIndex]`, extended as the cursor moves. */\n private cursorIndex = -1;\n private cursorVersion = new Map<PeerID, number>();\n\n constructor(readonly doc: LoroDoc) {\n doc.detach();\n this.stops = orderHistoryStops(doc.getAllChanges());\n }\n\n checkout(index: number): void {\n this.doc.checkout(\n this.versionAt(index).map(({ counter, peerId }) => ({\n counter,\n peer: peerId,\n })),\n );\n // Checking out the newest version re-attaches the document, which would\n // make it editable; a viewer is read-only at every stop.\n this.doc.detach();\n }\n\n versionAt(index: number): HistoryVersionEntry[] {\n if (!Number.isInteger(index) || index < -1 || index >= this.stops.length) {\n throw new RangeError(`History stop ${index} is out of range.`);\n }\n if (index < this.cursorIndex) {\n this.cursorIndex = -1;\n this.cursorVersion = new Map();\n }\n while (this.cursorIndex < index) {\n this.cursorIndex += 1;\n const stop = this.stops[this.cursorIndex];\n if (stop !== undefined) {\n this.cursorVersion.set(stop.peerId, stop.endCounter);\n }\n }\n return this.doc\n .vvToFrontiers(VersionVector.parseJSON(this.cursorVersion))\n .map(({ counter, peer }) => ({ counter, peerId: peer }));\n }\n\n free(): void {\n this.doc.free();\n }\n}\n\n/**\n * Build a timeline over a document that already holds the history to browse,\n * and take ownership of it. Pass a scratch document from\n * {@link createReadOnlyDocument}, never a document that is being edited:\n * checking out a version makes the document read-only.\n */\nexport function openHistoryViewer(doc: LoroDoc): HistoryViewer {\n return new LoroHistoryViewer(doc);\n}\n"]}
|
package/internal/loro/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { LoroList, LoroMap } from "loro-crdt";
|
|
2
2
|
export { DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS } from "./changeTimestamps.js";
|
|
3
3
|
export { createDocument, decodeVersionVector, derivePeerId, emptyVersionVector, encodeEncodedVersionVector, encodeVersionVector, exportAllUpdates, exportFullHistoryIdentity, exportFullHistorySnapshot, exportUpdatesSince, type FieldEditor, getImportBlobMetadata, getTextValue, getUpdateVersionVectors, type ImportBlobMode, importSnapshot, importUpdates, LoroImportUnresolvedDependenciesError, listSnapshotCharBlameSource, listSnapshotCharOpIds, listSnapshotFieldEditors, listTextCharOpIds, listVersionVectorSpans, mergeVersionVectors, satisfiesVersionVector, type TextCharBlameSource, type TextCharOpId, type VersionVectorSpan, versionVectorsEqual, } from "./document.js";
|
|
4
|
+
export { createReadOnlyDocument, type HistoryStop, type HistoryVersionEntry, type HistoryViewer, openHistoryViewer, orderHistoryStops, } from "./historyTimeline.js";
|
|
4
5
|
export * from "./shared/index.js";
|
|
5
6
|
export { updateMatchesDocumentHistory } from "./updateIdentity.js";
|
|
6
7
|
export { exportUpdatesInVersionRange, minimumVersionVectors, } from "./versionRange.js";
|
package/internal/loro/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { LoroList, LoroMap } from "loro-crdt";
|
|
2
2
|
export { DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS } from "./changeTimestamps.js";
|
|
3
3
|
export { createDocument, decodeVersionVector, derivePeerId, emptyVersionVector, encodeEncodedVersionVector, encodeVersionVector, exportAllUpdates, exportFullHistoryIdentity, exportFullHistorySnapshot, exportUpdatesSince, getImportBlobMetadata, getTextValue, getUpdateVersionVectors, importSnapshot, importUpdates, LoroImportUnresolvedDependenciesError, listSnapshotCharBlameSource, listSnapshotCharOpIds, listSnapshotFieldEditors, listTextCharOpIds, listVersionVectorSpans, mergeVersionVectors, satisfiesVersionVector, versionVectorsEqual, } from "./document.js";
|
|
4
|
+
export { createReadOnlyDocument, openHistoryViewer, orderHistoryStops, } from "./historyTimeline.js";
|
|
4
5
|
export * from "./shared/index.js";
|
|
5
6
|
export { updateMatchesDocumentHistory } from "./updateIdentity.js";
|
|
6
7
|
export { exportUpdatesInVersionRange, minimumVersionVectors, } from "./versionRange.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,sCAAsC,EAAE,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,YAAY,EACZ,kBAAkB,EAClB,0BAA0B,EAC1B,mBAAmB,EACnB,gBAAgB,EAChB,yBAAyB,EACzB,yBAAyB,EACzB,kBAAkB,EAElB,qBAAqB,EACrB,YAAY,EACZ,uBAAuB,EAEvB,cAAc,EACd,aAAa,EACb,qCAAqC,EACrC,2BAA2B,EAC3B,qBAAqB,EACrB,wBAAwB,EACxB,iBAAiB,EACjB,sBAAsB,EACtB,mBAAmB,EACnB,sBAAsB,EAItB,mBAAmB,GACpB,MAAM,YAAY,CAAC;AACpB,cAAc,UAAU,CAAC;AACzB,OAAO,EAAE,4BAA4B,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EACL,2BAA2B,EAC3B,qBAAqB,GACtB,MAAM,gBAAgB,CAAC","sourcesContent":["export { LoroList, LoroMap } from \"loro-crdt\";\nexport { DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS } from \"./changeTimestamps\";\nexport {\n createDocument,\n decodeVersionVector,\n derivePeerId,\n emptyVersionVector,\n encodeEncodedVersionVector,\n encodeVersionVector,\n exportAllUpdates,\n exportFullHistoryIdentity,\n exportFullHistorySnapshot,\n exportUpdatesSince,\n type FieldEditor,\n getImportBlobMetadata,\n getTextValue,\n getUpdateVersionVectors,\n type ImportBlobMode,\n importSnapshot,\n importUpdates,\n LoroImportUnresolvedDependenciesError,\n listSnapshotCharBlameSource,\n listSnapshotCharOpIds,\n listSnapshotFieldEditors,\n listTextCharOpIds,\n listVersionVectorSpans,\n mergeVersionVectors,\n satisfiesVersionVector,\n type TextCharBlameSource,\n type TextCharOpId,\n type VersionVectorSpan,\n versionVectorsEqual,\n} from \"./document\";\nexport * from \"./shared\";\nexport { updateMatchesDocumentHistory } from \"./updateIdentity\";\nexport {\n exportUpdatesInVersionRange,\n minimumVersionVectors,\n} from \"./versionRange\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,sCAAsC,EAAE,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,YAAY,EACZ,kBAAkB,EAClB,0BAA0B,EAC1B,mBAAmB,EACnB,gBAAgB,EAChB,yBAAyB,EACzB,yBAAyB,EACzB,kBAAkB,EAElB,qBAAqB,EACrB,YAAY,EACZ,uBAAuB,EAEvB,cAAc,EACd,aAAa,EACb,qCAAqC,EACrC,2BAA2B,EAC3B,qBAAqB,EACrB,wBAAwB,EACxB,iBAAiB,EACjB,sBAAsB,EACtB,mBAAmB,EACnB,sBAAsB,EAItB,mBAAmB,GACpB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,sBAAsB,EAItB,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,mBAAmB,CAAC;AAC3B,cAAc,UAAU,CAAC;AACzB,OAAO,EAAE,4BAA4B,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EACL,2BAA2B,EAC3B,qBAAqB,GACtB,MAAM,gBAAgB,CAAC","sourcesContent":["export { LoroList, LoroMap } from \"loro-crdt\";\nexport { DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS } from \"./changeTimestamps\";\nexport {\n createDocument,\n decodeVersionVector,\n derivePeerId,\n emptyVersionVector,\n encodeEncodedVersionVector,\n encodeVersionVector,\n exportAllUpdates,\n exportFullHistoryIdentity,\n exportFullHistorySnapshot,\n exportUpdatesSince,\n type FieldEditor,\n getImportBlobMetadata,\n getTextValue,\n getUpdateVersionVectors,\n type ImportBlobMode,\n importSnapshot,\n importUpdates,\n LoroImportUnresolvedDependenciesError,\n listSnapshotCharBlameSource,\n listSnapshotCharOpIds,\n listSnapshotFieldEditors,\n listTextCharOpIds,\n listVersionVectorSpans,\n mergeVersionVectors,\n satisfiesVersionVector,\n type TextCharBlameSource,\n type TextCharOpId,\n type VersionVectorSpan,\n versionVectorsEqual,\n} from \"./document\";\nexport {\n createReadOnlyDocument,\n type HistoryStop,\n type HistoryVersionEntry,\n type HistoryViewer,\n openHistoryViewer,\n orderHistoryStops,\n} from \"./historyTimeline\";\nexport * from \"./shared\";\nexport { updateMatchesDocumentHistory } from \"./updateIdentity\";\nexport {\n exportUpdatesInVersionRange,\n minimumVersionVectors,\n} from \"./versionRange\";\n"]}
|
package/package.json
CHANGED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { encodeVersionVector } from "../../../../internal/loro/index.js";
|
|
2
|
+
import { restoreDocumentContent, } from "../../../../data/documents/documentRestore.js";
|
|
3
|
+
import { createPendingUpdateFields } from "../../../../data/documents/documentSync.js";
|
|
4
|
+
import { requestDocumentStoreSync } from "../../registry.js";
|
|
5
|
+
import { ensureDocumentStoreReady } from "../initialization/index.js";
|
|
6
|
+
import { chainQueuedWrite } from "../localWriteQueue/index.js";
|
|
7
|
+
import { settleDocumentLocalWrite } from "../mutations.js";
|
|
8
|
+
import { advancePendingBaseVersion, pendingDeltaSinceBase, persistDocument, } from "../persistence.js";
|
|
9
|
+
import { reportDocumentStoreWriteFailure } from "../reportWriteFailure.js";
|
|
10
|
+
import { resolveRowAttribution } from "../rows/rowAttribution.js";
|
|
11
|
+
import { canWriteDocument, } from "../state.js";
|
|
12
|
+
import { captureDocumentStoreSyncGeneration, isDocumentStoreSyncGenerationCurrent, } from "../sync/syncGeneration.js";
|
|
13
|
+
// Fixed literal: a reported message must never carry document content.
|
|
14
|
+
const RESTORE_FAILURE_MESSAGE = "Documents: content restore failed";
|
|
15
|
+
/**
|
|
16
|
+
* Leads the commit message of every restore. The rest of the message is
|
|
17
|
+
* random, so two restores in a row are two steps as well.
|
|
18
|
+
*/
|
|
19
|
+
const DOCUMENT_RESTORE_COMMIT_MESSAGE = "restore";
|
|
20
|
+
/**
|
|
21
|
+
* Apply and persist one restore. Resolves true when the document durably
|
|
22
|
+
* holds the content: it was written and saved, or it already matched.
|
|
23
|
+
*/
|
|
24
|
+
async function persistRestoredContent(state, expectedLocalWriteGeneration, content, options) {
|
|
25
|
+
if (state.localWriteGeneration !== expectedLocalWriteGeneration) {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
const currentDoc = state.doc;
|
|
29
|
+
if (!currentDoc || !canWriteDocument(state)) {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
const generation = captureDocumentStoreSyncGeneration(state, currentDoc);
|
|
33
|
+
if (!generation || options.stillCurrent?.() === false) {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
// A restore is always its own step of history. Loro folds a writer's
|
|
37
|
+
// commits into one change while they fall within the merge interval, which
|
|
38
|
+
// would fold a restore into the edit it replaces and take that version off
|
|
39
|
+
// the timeline. Changes with different messages never share a change, so
|
|
40
|
+
// close the edits before it and give the restore a message of its own.
|
|
41
|
+
currentDoc.commit();
|
|
42
|
+
const changed = restoreDocumentContent(currentDoc, content, resolveRowAttribution(state), state.runtime.infra.documentProjectors);
|
|
43
|
+
if (changed) {
|
|
44
|
+
currentDoc.commit({
|
|
45
|
+
message: `${DOCUMENT_RESTORE_COMMIT_MESSAGE} ${crypto.randomUUID()}`,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
// Every operation since the last persisted base travels in this update,
|
|
49
|
+
// including edits an earlier failed save left behind.
|
|
50
|
+
const update = pendingDeltaSinceBase(state, currentDoc);
|
|
51
|
+
const pendingUpdate = update.byteLength === 0 ? null : createPendingUpdateFields(update);
|
|
52
|
+
// The persist keeps whatever text and fields are on screen: an edit queued
|
|
53
|
+
// behind this restore has already shown its value, and publishing the
|
|
54
|
+
// restored document over it would regress an editor the user is typing in.
|
|
55
|
+
// The restored content is published when the local writes drain
|
|
56
|
+
// (settleDocumentLocalWrite), as it is for every other write.
|
|
57
|
+
const saveOptions = {
|
|
58
|
+
preserveSnapshotStructuredFields: true,
|
|
59
|
+
preserveSnapshotText: true,
|
|
60
|
+
};
|
|
61
|
+
if (!pendingUpdate) {
|
|
62
|
+
// Already this content: nothing to save, only the identity to revalidate.
|
|
63
|
+
return isPersistedAndCurrent(state, generation, await persistDocument(state, currentDoc, {}, saveOptions, generation));
|
|
64
|
+
}
|
|
65
|
+
const coveredVersion = encodeVersionVector(currentDoc);
|
|
66
|
+
// From here until a persist covers it, the doc holds edits SQLite lacks.
|
|
67
|
+
state.unsavedLocalEdits = true;
|
|
68
|
+
const persisted = await persistDocument(state, currentDoc, { snapshotEndVersion: coveredVersion }, { ...saveOptions, pendingUpdate }, generation);
|
|
69
|
+
if (!isPersistedAndCurrent(state, generation, persisted)) {
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
advancePendingBaseVersion(state, currentDoc);
|
|
73
|
+
requestDocumentStoreSync(state);
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Whether a persist landed on the document this write started against. A
|
|
78
|
+
* refused persist, a lost compare-and-set, or a superseded generation means
|
|
79
|
+
* the store now holds something else.
|
|
80
|
+
*/
|
|
81
|
+
function isPersistedAndCurrent(state, generation, persisted) {
|
|
82
|
+
return (persisted !== null &&
|
|
83
|
+
!persisted.pullContinuationSuperseded &&
|
|
84
|
+
!persisted.syncIdentitySuperseded &&
|
|
85
|
+
isDocumentStoreSyncGenerationCurrent(state, generation));
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Restore the document to `content` as one ordinary local write, queued
|
|
89
|
+
* behind the writes already in flight. Resolves false when the restore was
|
|
90
|
+
* refused or did not persist: the store is not ready, the document cannot be
|
|
91
|
+
* written, the caller's guard expired, or the save failed.
|
|
92
|
+
*/
|
|
93
|
+
export async function restoreDocumentStoreContent(state, scheduleSync, content, options = {}) {
|
|
94
|
+
let ready;
|
|
95
|
+
try {
|
|
96
|
+
ready = await ensureDocumentStoreReady(state, scheduleSync);
|
|
97
|
+
if (options.stillCurrent?.() === false)
|
|
98
|
+
ready = false;
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
reportDocumentStoreWriteFailure(state, RESTORE_FAILURE_MESSAGE, error);
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
if (!ready || !state.doc || !canWriteDocument(state)) {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
const writeGeneration = state.localWriteGeneration;
|
|
108
|
+
let restored = false;
|
|
109
|
+
// Counted as a local write in flight, like a text or field write: while the
|
|
110
|
+
// count is above zero a sync pass keeps the snapshot on screen, and the
|
|
111
|
+
// document is published once the count drains.
|
|
112
|
+
state.pendingLocalWrites += 1;
|
|
113
|
+
await chainQueuedWrite(state, state.writeChain
|
|
114
|
+
.catch(() => undefined)
|
|
115
|
+
.then(async () => {
|
|
116
|
+
restored = await persistRestoredContent(state, writeGeneration, content, options);
|
|
117
|
+
})
|
|
118
|
+
.catch((error) => {
|
|
119
|
+
reportDocumentStoreWriteFailure(state, RESTORE_FAILURE_MESSAGE, error);
|
|
120
|
+
})
|
|
121
|
+
// Always settle, so the count cannot stick above zero.
|
|
122
|
+
.finally(() => {
|
|
123
|
+
settleDocumentLocalWrite(state, writeGeneration);
|
|
124
|
+
}));
|
|
125
|
+
return restored;
|
|
126
|
+
}
|
|
127
|
+
//# sourceMappingURL=restoreContent.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"restoreContent.js","sourceRoot":"","sources":["restoreContent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAEL,sBAAsB,GACvB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAE1D,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EACL,yBAAyB,EACzB,qBAAqB,EACrB,eAAe,GAChB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,+BAA+B,EAAE,MAAM,uBAAuB,CAAC;AACxE,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EACL,gBAAgB,GAGjB,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,kCAAkC,EAElC,oCAAoC,GACrC,MAAM,wBAAwB,CAAC;AAEhC,uEAAuE;AACvE,MAAM,uBAAuB,GAAG,mCAAmC,CAAC;AAEpE;;;GAGG;AACH,MAAM,+BAA+B,GAAG,SAAS,CAAC;AAElD;;;GAGG;AACH,KAAK,UAAU,sBAAsB,CACnC,KAAyB,EACzB,4BAAoC,EACpC,OAA+B,EAC/B,OAA8B;IAE9B,IAAI,KAAK,CAAC,oBAAoB,KAAK,4BAA4B,EAAE,CAAC;QAChE,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,UAAU,GAAG,KAAK,CAAC,GAAG,CAAC;IAC7B,IAAI,CAAC,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C;QACvE,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IAAI,CAAC,KAAK,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,CAAC;QACrD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,eAAe,GAAG,KAAK,CAAC,oBAAoB,CAAC;IACnD,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,4EAA4E;IAC5E,wEAAwE;IACxE,+CAA+C;IAC/C,KAAK,CAAC,kBAAkB,IAAI,CAAC,CAAC;IAC9B,MAAM,gBAAgB,CACpB,KAAK,EACL,KAAK,CAAC,UAAU;SACb,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC;SACtB,IAAI,CAAC,KAAK,IAAI,EAAE;QACf,QAAQ,GAAG,MAAM,sBAAsB,CACrC,KAAK,EACL,eAAe,EACf,OAAO,EACP,OAAO,CACR,CAAC;IACJ,CAAC,CAAC;SACD,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QACxB,+BAA+B,CAAC,KAAK,EAAE,uBAAuB,EAAE,KAAK,CAAC,CAAC;IACzE,CAAC,CAAC;QACF,uDAAuD;SACtD,OAAO,CAAC,GAAG,EAAE;QACZ,wBAAwB,CAAC,KAAK,EAAE,eAAe,CAAC,CAAC;IACnD,CAAC,CAAC,CACL,CAAC;IACF,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import { encodeVersionVector } from \"@tearleads/loro\";\nimport {\n type DocumentRestoreContent,\n restoreDocumentContent,\n} from \"../../../../data/documents/documentRestore\";\nimport { createPendingUpdateFields } from \"../../../../data/documents/documentSync\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport type { DocumentMutationGuard } from \"../../types\";\nimport { ensureDocumentStoreReady } from \"../initialization\";\nimport { chainQueuedWrite } from \"../localWriteQueue\";\nimport { settleDocumentLocalWrite } from \"../mutations\";\nimport {\n advancePendingBaseVersion,\n pendingDeltaSinceBase,\n persistDocument,\n} from \"../persistence\";\nimport { reportDocumentStoreWriteFailure } from \"../reportWriteFailure\";\nimport { resolveRowAttribution } from \"../rows/rowAttribution\";\nimport {\n canWriteDocument,\n type DocumentStoreState,\n type SaveDocumentRecordOptions,\n} from \"../state\";\nimport {\n captureDocumentStoreSyncGeneration,\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"../sync/syncGeneration\";\n\n// Fixed literal: a reported message must never carry document content.\nconst RESTORE_FAILURE_MESSAGE = \"Documents: content restore failed\";\n\n/**\n * Leads the commit message of every restore. The rest of the message is\n * random, so two restores in a row are two steps as well.\n */\nconst DOCUMENT_RESTORE_COMMIT_MESSAGE = \"restore\";\n\n/**\n * Apply and persist one restore. Resolves true when the document durably\n * holds the content: it was written and saved, or it already matched.\n */\nasync function persistRestoredContent(\n state: DocumentStoreState,\n expectedLocalWriteGeneration: number,\n content: DocumentRestoreContent,\n options: DocumentMutationGuard,\n): Promise<boolean> {\n if (state.localWriteGeneration !== expectedLocalWriteGeneration) {\n return false;\n }\n const currentDoc = state.doc;\n if (!currentDoc || !canWriteDocument(state)) {\n return false;\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation || options.stillCurrent?.() === false) {\n return false;\n }\n\n // A restore is always its own step of history. Loro folds a writer's\n // commits into one change while they fall within the merge interval, which\n // would fold a restore into the edit it replaces and take that version off\n // the timeline. Changes with different messages never share a change, so\n // close the edits before it and give the restore a message of its own.\n currentDoc.commit();\n const changed = restoreDocumentContent(\n currentDoc,\n content,\n resolveRowAttribution(state),\n state.runtime.infra.documentProjectors,\n );\n if (changed) {\n currentDoc.commit({\n message: `${DOCUMENT_RESTORE_COMMIT_MESSAGE} ${crypto.randomUUID()}`,\n });\n }\n // Every operation since the last persisted base travels in this update,\n // including edits an earlier failed save left behind.\n const update = pendingDeltaSinceBase(state, currentDoc);\n const pendingUpdate =\n update.byteLength === 0 ? null : createPendingUpdateFields(update);\n // The persist keeps whatever text and fields are on screen: an edit queued\n // behind this restore has already shown its value, and publishing the\n // restored document over it would regress an editor the user is typing in.\n // The restored content is published when the local writes drain\n // (settleDocumentLocalWrite), as it is for every other write.\n const saveOptions: SaveDocumentRecordOptions = {\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n };\n if (!pendingUpdate) {\n // Already this content: nothing to save, only the identity to revalidate.\n return isPersistedAndCurrent(\n state,\n generation,\n await persistDocument(state, currentDoc, {}, saveOptions, generation),\n );\n }\n const coveredVersion = encodeVersionVector(currentDoc);\n // From here until a persist covers it, the doc holds edits SQLite lacks.\n state.unsavedLocalEdits = true;\n const persisted = await persistDocument(\n state,\n currentDoc,\n { snapshotEndVersion: coveredVersion },\n { ...saveOptions, pendingUpdate },\n generation,\n );\n if (!isPersistedAndCurrent(state, generation, persisted)) {\n return false;\n }\n advancePendingBaseVersion(state, currentDoc);\n requestDocumentStoreSync(state);\n return true;\n}\n\n/**\n * Whether a persist landed on the document this write started against. A\n * refused persist, a lost compare-and-set, or a superseded generation means\n * the store now holds something else.\n */\nfunction isPersistedAndCurrent(\n state: DocumentStoreState,\n generation: DocumentStoreSyncGeneration,\n persisted: Awaited<ReturnType<typeof persistDocument>>,\n): boolean {\n return (\n persisted !== null &&\n !persisted.pullContinuationSuperseded &&\n !persisted.syncIdentitySuperseded &&\n isDocumentStoreSyncGenerationCurrent(state, generation)\n );\n}\n\n/**\n * Restore the document to `content` as one ordinary local write, queued\n * behind the writes already in flight. Resolves false when the restore was\n * refused or did not persist: the store is not ready, the document cannot be\n * written, the caller's guard expired, or the save failed.\n */\nexport async function restoreDocumentStoreContent(\n state: DocumentStoreState,\n scheduleSync: () => void,\n content: DocumentRestoreContent,\n options: DocumentMutationGuard = {},\n): Promise<boolean> {\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n if (options.stillCurrent?.() === false) ready = false;\n } catch (error) {\n reportDocumentStoreWriteFailure(state, RESTORE_FAILURE_MESSAGE, error);\n return false;\n }\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return false;\n }\n\n const writeGeneration = state.localWriteGeneration;\n let restored = false;\n // Counted as a local write in flight, like a text or field write: while the\n // count is above zero a sync pass keeps the snapshot on screen, and the\n // document is published once the count drains.\n state.pendingLocalWrites += 1;\n await chainQueuedWrite(\n state,\n state.writeChain\n .catch(() => undefined)\n .then(async () => {\n restored = await persistRestoredContent(\n state,\n writeGeneration,\n content,\n options,\n );\n })\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, RESTORE_FAILURE_MESSAGE, error);\n })\n // Always settle, so the count cannot stick above zero.\n .finally(() => {\n settleDocumentLocalWrite(state, writeGeneration);\n }),\n );\n return restored;\n}\n"]}
|
|
@@ -4,13 +4,14 @@ import { createDocumentStoreFacade, emitPersistedDocument, getOrCreateDocumentSt
|
|
|
4
4
|
import { attachFilesToDocumentStore, replaceAttachmentInDocumentStore, } from "./attachments/index.js";
|
|
5
5
|
import { removeAttachmentFromDocumentStore } from "./attachments/attachmentRemoval.js";
|
|
6
6
|
import { discardDocumentStoreLocalState } from "./discard.js";
|
|
7
|
+
import { restoreDocumentStoreContent } from "./history/restoreContent.js";
|
|
7
8
|
import { ensureDocumentStoreInitialized, ensureDocumentStoreReady, relinkDocumentStore, } from "./initialization/index.js";
|
|
8
9
|
import { assertInitialContentFitsKind } from "./initialization/initialContent.js";
|
|
9
10
|
import { registerInternalDocumentRelink } from "./internalRelink.js";
|
|
10
11
|
import { countQueuedWrite } from "./localWriteQueue/index.js";
|
|
11
12
|
import { setDocumentStructuredFields, setDocumentText } from "./mutations.js";
|
|
12
13
|
import { assertLoadedDocumentStoreCanRotate } from "./rotation/rotationPreflight.js";
|
|
13
|
-
import {
|
|
14
|
+
import { createRowWrites } from "./rows/index.js";
|
|
14
15
|
import { createDocumentStoreState, refreshAttachabilitySnapshot, resetDocumentStore, subscribeToDocumentStore, } from "./state.js";
|
|
15
16
|
import { registerDocumentStoreSyncLane } from "./sync/index.js";
|
|
16
17
|
import { logRevalidationScheduled } from "./sync/remoteRevalidationTelemetry.js";
|
|
@@ -171,7 +172,7 @@ function createBackingDocumentStore(localId, initialRuntime, persistence = defau
|
|
|
171
172
|
// Local writes count as queued from the call, readiness wait included.
|
|
172
173
|
const liveWrite = (write) => withLiveSyncLane(() => countQueuedWrite(state, write()));
|
|
173
174
|
const store = {
|
|
174
|
-
|
|
175
|
+
...createRowWrites(state, scheduleSync, liveWrite),
|
|
175
176
|
assertCanRotateContentKey: (proof) => withLiveSyncLane(() => assertLoadedDocumentStoreCanRotate(state, scheduleSync, proof)),
|
|
176
177
|
attachFiles: (files) => liveWrite(() => attachFilesToDocumentStore(state, scheduleSync, files)),
|
|
177
178
|
discardLocalState: (expectedDocumentId) => withLiveSyncLane(() => discardBackingDocumentStoreLocalState(state, scheduleSync, expectedDocumentId)),
|
|
@@ -180,16 +181,15 @@ function createBackingDocumentStore(localId, initialRuntime, persistence = defau
|
|
|
180
181
|
hasQueuedWrites: () => state.queuedWrites > 0,
|
|
181
182
|
hasUnsavedLocalEdits: () => state.unsavedLocalEdits,
|
|
182
183
|
removeAttachment: (slotId) => liveWrite(() => removeAttachmentFromDocumentStore(state, scheduleSync, slotId)),
|
|
183
|
-
removeRow: (id, options) => liveWrite(() => removeRowFromDocumentStore(state, scheduleSync, id, options)),
|
|
184
184
|
replaceAttachment: (slotId, file) => liveWrite(() => replaceAttachmentInDocumentStore(state, scheduleSync, slotId, file)),
|
|
185
185
|
requestRemoteSync: () => withLiveSyncLane(() => requestRemoteDocumentStoreSync(state, scheduleSync)),
|
|
186
|
+
restoreContent: (content, options) => liveWrite(() => restoreDocumentStoreContent(state, scheduleSync, content, options)),
|
|
186
187
|
requestRemoteSyncAndWait: (signal) => requestRemoteDocumentStoreSyncAndWait(state, scheduleSync, signal),
|
|
187
188
|
requestSync: () => withLiveSyncLane(() => requestOrdinaryDocumentStoreSync(state, scheduleSync)),
|
|
188
189
|
relink: (input) => withLiveSyncLane(() => relinkDocumentStore(state, input, scheduleSync)),
|
|
189
190
|
setStructuredFields: (kind, patch, options) => liveWrite(() => setDocumentStructuredFields(state, scheduleSync, kind, patch, options)),
|
|
190
191
|
setText: (value) => liveWrite(() => setDocumentText(state, scheduleSync, value)),
|
|
191
192
|
subscribe: (listener) => subscribeToDocumentStore(state, listener),
|
|
192
|
-
updateRowFields: (id, patch, options) => liveWrite(() => updateRowInDocumentStore(state, scheduleSync, id, patch, options)),
|
|
193
193
|
updateRuntime: (runtime) => updateDocumentStoreRuntime(state, runtime, scheduleSync),
|
|
194
194
|
};
|
|
195
195
|
return registerBackingStoreInternalRelink({ ...context, store });
|