@dxos/echo-doc 0.10.0 → 0.11.1
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.
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import { next } from "@automerge/automerge";
|
|
2
|
+
import { Doc, createObject, getObjectCore, isEchoObject } from "@dxos/echo-client";
|
|
3
|
+
import { isProxy } from "@dxos/echo/internal";
|
|
4
|
+
import { assertArgument, invariant } from "@dxos/invariant";
|
|
5
|
+
import * as Schema from "effect/Schema";
|
|
6
|
+
import { log } from "@dxos/log";
|
|
7
|
+
import { isNonNullable } from "@dxos/util";
|
|
8
|
+
//#region \0rolldown/runtime.js
|
|
9
|
+
var __defProp = Object.defineProperty;
|
|
10
|
+
var __exportAll = (all, no_symbols) => {
|
|
11
|
+
let target = {};
|
|
12
|
+
for (var name in all) __defProp(target, name, {
|
|
13
|
+
get: all[name],
|
|
14
|
+
enumerable: true
|
|
15
|
+
});
|
|
16
|
+
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
17
|
+
return target;
|
|
18
|
+
};
|
|
19
|
+
//#endregion
|
|
20
|
+
//#region src/Doc.ts
|
|
21
|
+
var Doc_exports = /* @__PURE__ */ __exportAll({
|
|
22
|
+
createAccessor: () => createAccessor,
|
|
23
|
+
getValue: () => getValue,
|
|
24
|
+
isKeyPath: () => isKeyPath,
|
|
25
|
+
updateText: () => updateText
|
|
26
|
+
});
|
|
27
|
+
var isKeyPath = Doc.isKeyPath;
|
|
28
|
+
var getValue = Doc.getValue;
|
|
29
|
+
/**
|
|
30
|
+
* Resolves an {@link Accessor} for a value within an object, agnostic to whether the object is
|
|
31
|
+
* in-memory or attached to a database. An `Obj.make` object has no `ObjectCore` until `db.add`,
|
|
32
|
+
* so an in-memory core is materialized (via `createObject`) to let the accessor bind before
|
|
33
|
+
* persistence; the object's edits then survive a later `db.add`.
|
|
34
|
+
*/
|
|
35
|
+
var createAccessor = (obj, path) => {
|
|
36
|
+
const keyPath = Array.isArray(path) ? path : [path];
|
|
37
|
+
assertArgument(isProxy(obj), "obj", "expect obj to be a LiveObject");
|
|
38
|
+
assertArgument(isKeyPath(keyPath), "path", "expect path to be a valid key path");
|
|
39
|
+
return getObjectCore(isEchoObject(obj) ? obj : createObject(obj)).getDocAccessor(keyPath);
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Sets the text value at the given path, applying the change as a minimal Automerge delta (via
|
|
43
|
+
* `A.updateText`) rather than replacing the whole string. This preserves cursors/anchors and merges
|
|
44
|
+
* cleanly with concurrent edits — use it to write an edited string back into a collaborative text field.
|
|
45
|
+
*/
|
|
46
|
+
var updateText = (obj, path, newText) => {
|
|
47
|
+
const accessor = createAccessor(obj, path);
|
|
48
|
+
accessor.handle.change((doc) => {
|
|
49
|
+
next.updateText(doc, accessor.path.slice(), newText);
|
|
50
|
+
});
|
|
51
|
+
return obj;
|
|
52
|
+
};
|
|
53
|
+
//#endregion
|
|
54
|
+
//#region src/edits.ts
|
|
55
|
+
/**
|
|
56
|
+
* A single find/replace edit applied to a text document. This is the structured form of the diff
|
|
57
|
+
* protocol described in document skills' instructions.
|
|
58
|
+
*/
|
|
59
|
+
var Edit = Schema.Struct({
|
|
60
|
+
oldString: Schema.String.annotations({ description: "The exact text to find and replace." }),
|
|
61
|
+
newString: Schema.String.annotations({ description: "The text to replace it with." }),
|
|
62
|
+
replaceAll: Schema.optional(Schema.Boolean).annotations({ description: "Replace all occurrences of oldString (default: replace the first occurrence)." })
|
|
63
|
+
});
|
|
64
|
+
/**
|
|
65
|
+
* Applies a sequence of find/replace {@link Edit}s to the string value an accessor points at,
|
|
66
|
+
* returning the resulting content. Throws if a non-`replaceAll` edit's `oldString` is not found.
|
|
67
|
+
*/
|
|
68
|
+
var applyEdits = (accessor, edits) => {
|
|
69
|
+
for (const edit of edits) {
|
|
70
|
+
if (edit.oldString.length === 0) throw new Error("Edit oldString must be non-empty.");
|
|
71
|
+
accessor.handle.change((doc) => {
|
|
72
|
+
const text = getValue(accessor);
|
|
73
|
+
if (edit.replaceAll) {
|
|
74
|
+
let idx = text.indexOf(edit.oldString);
|
|
75
|
+
while (idx !== -1) {
|
|
76
|
+
next.splice(doc, accessor.path, idx, edit.oldString.length, edit.newString);
|
|
77
|
+
idx = getValue(accessor).indexOf(edit.oldString, idx + edit.newString.length);
|
|
78
|
+
}
|
|
79
|
+
} else {
|
|
80
|
+
const idx = text.indexOf(edit.oldString);
|
|
81
|
+
if (idx === -1) throw new Error(`Edit not found: ${JSON.stringify(edit.oldString)}`);
|
|
82
|
+
next.splice(doc, accessor.path, idx, edit.oldString.length, edit.newString);
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
return getValue(accessor);
|
|
87
|
+
};
|
|
88
|
+
//#endregion
|
|
89
|
+
//#region src/record.ts
|
|
90
|
+
var STRING_CRDT_LIMIT = 3e5;
|
|
91
|
+
/**
|
|
92
|
+
* Default codec: encode a model value to an Automerge record.
|
|
93
|
+
*/
|
|
94
|
+
var encode = (value) => {
|
|
95
|
+
if (Array.isArray(value)) return value.map(encode);
|
|
96
|
+
if (value instanceof next.RawString) throw new Error("Encode called on automerge data.");
|
|
97
|
+
if (typeof value === "object" && value !== null) return Object.fromEntries(Object.entries(value).map(([key, value]) => {
|
|
98
|
+
const encoded = encode(value);
|
|
99
|
+
if (encoded === void 0) return;
|
|
100
|
+
return [key, encoded];
|
|
101
|
+
}).filter(isNonNullable));
|
|
102
|
+
if (typeof value === "string" && value.length > STRING_CRDT_LIMIT) return new next.RawString(value);
|
|
103
|
+
return value;
|
|
104
|
+
};
|
|
105
|
+
/**
|
|
106
|
+
* Default codec: decode an Automerge record to a model value.
|
|
107
|
+
*/
|
|
108
|
+
var decode = (value) => {
|
|
109
|
+
if (Array.isArray(value)) return value.map(decode);
|
|
110
|
+
if (value instanceof next.RawString) return value.toString();
|
|
111
|
+
if (typeof value === "object" && value !== null) return Object.fromEntries(Object.entries(value).map(([key, value]) => [key, decode(value)]));
|
|
112
|
+
return value;
|
|
113
|
+
};
|
|
114
|
+
/**
|
|
115
|
+
* Relative path from `base`, or `undefined` if `path` is not under `base`. Used to filter mutations.
|
|
116
|
+
*/
|
|
117
|
+
var rebasePath = (path, base) => {
|
|
118
|
+
if (path.length < base.length) return;
|
|
119
|
+
for (let i = 0; i < base.length; ++i) if (path[i] !== base[i]) return;
|
|
120
|
+
return path.slice(base.length);
|
|
121
|
+
};
|
|
122
|
+
/**
|
|
123
|
+
* Read the value at `path`. When `init` is set, auto-vivifies intermediate records.
|
|
124
|
+
*/
|
|
125
|
+
var getDeep = (obj, path, init = false) => {
|
|
126
|
+
let value = obj;
|
|
127
|
+
for (const key of path) {
|
|
128
|
+
if (init) value[key] ??= {};
|
|
129
|
+
value = value?.[key];
|
|
130
|
+
}
|
|
131
|
+
return value;
|
|
132
|
+
};
|
|
133
|
+
//#endregion
|
|
134
|
+
//#region src/store-adapter.ts
|
|
135
|
+
var __dxlog_file = "/__w/dxos/dxos/packages/core/echo/echo-doc/src/store-adapter.ts";
|
|
136
|
+
/**
|
|
137
|
+
* Accumulates pending local mutations.
|
|
138
|
+
*/
|
|
139
|
+
var Modified = class {
|
|
140
|
+
added = /* @__PURE__ */ new Map();
|
|
141
|
+
updated = /* @__PURE__ */ new Map();
|
|
142
|
+
deleted = /* @__PURE__ */ new Set();
|
|
143
|
+
batch() {
|
|
144
|
+
return {
|
|
145
|
+
added: Array.from(this.added.values()),
|
|
146
|
+
updated: Array.from(this.updated.values()),
|
|
147
|
+
deleted: Array.from(this.deleted.values())
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
clear() {
|
|
151
|
+
this.added.clear();
|
|
152
|
+
this.updated.clear();
|
|
153
|
+
this.deleted.clear();
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
/**
|
|
157
|
+
* Two-way sync between an external store and an id-keyed `Record<string, Element>` held at an
|
|
158
|
+
* accessor's path within an Automerge document. Subclasses bind a concrete store (e.g. tldraw,
|
|
159
|
+
* excalidraw) by implementing {@link getElements} / {@link onUpdate} and registering store
|
|
160
|
+
* listeners in {@link onOpen}.
|
|
161
|
+
*/
|
|
162
|
+
var AbstractStoreAdapter = class {
|
|
163
|
+
#accessor;
|
|
164
|
+
#lastHeads;
|
|
165
|
+
#cleanup;
|
|
166
|
+
#readonly;
|
|
167
|
+
#encode;
|
|
168
|
+
#decode;
|
|
169
|
+
constructor(options = {}) {
|
|
170
|
+
this.#readonly = options.readonly ?? false;
|
|
171
|
+
this.#encode = options.encode ?? encode;
|
|
172
|
+
this.#decode = options.decode ?? decode;
|
|
173
|
+
}
|
|
174
|
+
get isOpen() {
|
|
175
|
+
return !!this.#accessor;
|
|
176
|
+
}
|
|
177
|
+
get readonly() {
|
|
178
|
+
return this.#readonly;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Binds the adapter to the element map at `accessor.path`. Returns a dispose function; calling it
|
|
182
|
+
* (or {@link close}) tears down the subscription and any listeners registered in {@link onOpen}.
|
|
183
|
+
*/
|
|
184
|
+
open(accessor) {
|
|
185
|
+
invariant(accessor.path.length, void 0, {
|
|
186
|
+
"~LogMeta": "~LogMeta",
|
|
187
|
+
F: __dxlog_file,
|
|
188
|
+
L: 90,
|
|
189
|
+
S: this,
|
|
190
|
+
A: ["accessor.path.length", ""]
|
|
191
|
+
});
|
|
192
|
+
if (this.isOpen) this.close();
|
|
193
|
+
log("opening...", { path: accessor.path }, {
|
|
194
|
+
"~LogMeta": "~LogMeta",
|
|
195
|
+
F: __dxlog_file,
|
|
196
|
+
L: 95,
|
|
197
|
+
S: this
|
|
198
|
+
});
|
|
199
|
+
this.#accessor = accessor;
|
|
200
|
+
const onOpenCleanup = this.onOpen();
|
|
201
|
+
{
|
|
202
|
+
const map = getDeep(accessor.handle.doc(), accessor.path) ?? {};
|
|
203
|
+
const records = Object.values(map);
|
|
204
|
+
if (records.length === 0) accessor.handle.change((doc) => {
|
|
205
|
+
const map = getDeep(doc, accessor.path, true);
|
|
206
|
+
for (const record of this.getElements()) map[record.id] = this.#encode(record);
|
|
207
|
+
});
|
|
208
|
+
else this.onUpdate({ updated: records.map((record) => this.#decode(record)) });
|
|
209
|
+
}
|
|
210
|
+
this.#lastHeads = next.getHeads(accessor.handle.doc());
|
|
211
|
+
const updateModel = () => {
|
|
212
|
+
const doc = accessor.handle.doc();
|
|
213
|
+
const map = getDeep(doc, accessor.path);
|
|
214
|
+
const updated = /* @__PURE__ */ new Set();
|
|
215
|
+
const deleted = /* @__PURE__ */ new Set();
|
|
216
|
+
const currentHeads = next.getHeads(doc);
|
|
217
|
+
(next.equals(this.#lastHeads, currentHeads) ? [] : next.diff(doc, this.#lastHeads ?? [], currentHeads)).forEach((patch) => {
|
|
218
|
+
const relativePath = rebasePath(patch.path, accessor.path);
|
|
219
|
+
if (!relativePath) return;
|
|
220
|
+
if (relativePath.length === 0) {
|
|
221
|
+
for (const id of Object.keys(map)) updated.add(id);
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
switch (patch.action) {
|
|
225
|
+
case "del": if (relativePath.length === 1) {
|
|
226
|
+
deleted.add(relativePath[0]);
|
|
227
|
+
break;
|
|
228
|
+
}
|
|
229
|
+
case "put":
|
|
230
|
+
case "insert":
|
|
231
|
+
case "inc":
|
|
232
|
+
case "splice":
|
|
233
|
+
updated.add(relativePath[0]);
|
|
234
|
+
break;
|
|
235
|
+
default: log.warn("did not process patch", {
|
|
236
|
+
patch,
|
|
237
|
+
path: accessor.path
|
|
238
|
+
}, {
|
|
239
|
+
"~LogMeta": "~LogMeta",
|
|
240
|
+
F: __dxlog_file,
|
|
241
|
+
L: 158,
|
|
242
|
+
S: this
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
if (updated.size || deleted.size) this.onUpdate({
|
|
247
|
+
updated: Array.from(updated).map((id) => this.#decode(map[id])).filter(isNonNullable),
|
|
248
|
+
deleted: Array.from(deleted)
|
|
249
|
+
});
|
|
250
|
+
this.#lastHeads = currentHeads;
|
|
251
|
+
};
|
|
252
|
+
accessor.handle.addListener("change", updateModel);
|
|
253
|
+
this.#cleanup = () => {
|
|
254
|
+
accessor.handle.removeListener("change", updateModel);
|
|
255
|
+
onOpenCleanup?.();
|
|
256
|
+
};
|
|
257
|
+
log("open", void 0, {
|
|
258
|
+
"~LogMeta": "~LogMeta",
|
|
259
|
+
F: __dxlog_file,
|
|
260
|
+
L: 180,
|
|
261
|
+
S: this
|
|
262
|
+
});
|
|
263
|
+
return () => this.close();
|
|
264
|
+
}
|
|
265
|
+
close() {
|
|
266
|
+
if (!this.isOpen) return;
|
|
267
|
+
log("closing...", void 0, {
|
|
268
|
+
"~LogMeta": "~LogMeta",
|
|
269
|
+
F: __dxlog_file,
|
|
270
|
+
L: 189,
|
|
271
|
+
S: this
|
|
272
|
+
});
|
|
273
|
+
this.onClose();
|
|
274
|
+
this.#cleanup?.();
|
|
275
|
+
this.#cleanup = void 0;
|
|
276
|
+
this.#accessor = void 0;
|
|
277
|
+
this.#lastHeads = void 0;
|
|
278
|
+
log("closed", void 0, {
|
|
279
|
+
"~LogMeta": "~LogMeta",
|
|
280
|
+
F: __dxlog_file,
|
|
281
|
+
L: 195,
|
|
282
|
+
S: this
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Writes a batch of element changes to the document.
|
|
287
|
+
*/
|
|
288
|
+
updateDatabase(batch) {
|
|
289
|
+
invariant(this.isOpen, void 0, {
|
|
290
|
+
"~LogMeta": "~LogMeta",
|
|
291
|
+
F: __dxlog_file,
|
|
292
|
+
L: 202,
|
|
293
|
+
S: this,
|
|
294
|
+
A: ["this.isOpen", ""]
|
|
295
|
+
});
|
|
296
|
+
if (this.#readonly) {
|
|
297
|
+
log.warn("attempting to update read-only store", void 0, {
|
|
298
|
+
"~LogMeta": "~LogMeta",
|
|
299
|
+
F: __dxlog_file,
|
|
300
|
+
L: 204,
|
|
301
|
+
S: this
|
|
302
|
+
});
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
const accessor = this.#accessor;
|
|
306
|
+
accessor.handle.change((doc) => {
|
|
307
|
+
const map = getDeep(doc, accessor.path, true);
|
|
308
|
+
this.#removeDeleted(batch, batch.added)?.forEach((element) => map[element.id] = this.#encode(element));
|
|
309
|
+
this.#removeDeleted(batch, batch.updated)?.forEach((element) => map[element.id] = this.#encode(element));
|
|
310
|
+
batch.deleted?.forEach((id) => delete map[id]);
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
#removeDeleted(batch, elements) {
|
|
314
|
+
return batch.deleted ? elements?.filter((element) => !batch.deleted.includes(element.id)) : elements;
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Called when the adapter opens; return a cleanup function to run on close (e.g. to remove store listeners).
|
|
318
|
+
*/
|
|
319
|
+
onOpen() {}
|
|
320
|
+
onClose() {}
|
|
321
|
+
};
|
|
322
|
+
//#endregion
|
|
323
|
+
export { AbstractStoreAdapter, Doc_exports as Doc, Edit, Modified, applyEdits };
|
|
324
|
+
|
|
325
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/Doc.ts","../../src/edits.ts","../../src/record.ts","../../src/store-adapter.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport { next as A } from '@automerge/automerge';\n\nimport { Doc, createObject, getObjectCore, isEchoObject } from '@dxos/echo-client';\nimport { type AnyProperties, isProxy } from '@dxos/echo/internal';\nimport { assertArgument } from '@dxos/invariant';\n\n// TODO(burdon): Reduce the dependency on @dxos/echo-client (e.g. move ObjectCore lower or invert).\n\nexport type KeyPath = Doc.KeyPath;\n\nexport const isKeyPath = Doc.isKeyPath;\n\nexport type Handle<T = any> = Doc.Handle<T>;\n\nexport type Accessor<T = any> = Doc.Accessor<T>;\n\nexport const getValue = Doc.getValue;\n\n/**\n * Resolves an {@link Accessor} for a value within an object, agnostic to whether the object is\n * in-memory or attached to a database. An `Obj.make` object has no `ObjectCore` until `db.add`,\n * so an in-memory core is materialized (via `createObject`) to let the accessor bind before\n * persistence; the object's edits then survive a later `db.add`.\n */\nexport const createAccessor = <T extends AnyProperties>(\n obj: T,\n path: KeyPath | Extract<keyof T, string | number>,\n): Accessor<T> => {\n const keyPath: KeyPath = Array.isArray(path) ? path : [path];\n assertArgument(isProxy(obj), 'obj', 'expect obj to be a LiveObject');\n assertArgument(isKeyPath(keyPath), 'path', 'expect path to be a valid key path');\n\n const live: AnyProperties = isEchoObject(obj) ? obj : createObject(obj);\n return getObjectCore(live).getDocAccessor(keyPath);\n};\n\n/**\n * Sets the text value at the given path, applying the change as a minimal Automerge delta (via\n * `A.updateText`) rather than replacing the whole string. This preserves cursors/anchors and merges\n * cleanly with concurrent edits — use it to write an edited string back into a collaborative text field.\n */\nexport const updateText = <T extends AnyProperties>(\n obj: T,\n path: KeyPath | Extract<keyof T, string | number>,\n newText: string,\n): T => {\n const accessor = createAccessor(obj, path);\n accessor.handle.change((doc) => {\n A.updateText(doc, accessor.path.slice(), newText);\n });\n return obj;\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { next as A } from '@automerge/automerge';\nimport * as Schema from 'effect/Schema';\n\nimport * as Doc from './Doc';\n\n/**\n * A single find/replace edit applied to a text document. This is the structured form of the diff\n * protocol described in document skills' instructions.\n */\nexport const Edit = Schema.Struct({\n oldString: Schema.String.annotations({\n description: 'The exact text to find and replace.',\n }),\n newString: Schema.String.annotations({\n description: 'The text to replace it with.',\n }),\n replaceAll: Schema.optional(Schema.Boolean).annotations({\n description: 'Replace all occurrences of oldString (default: replace the first occurrence).',\n }),\n});\n\nexport interface Edit extends Schema.Schema.Type<typeof Edit> {}\n\n/**\n * Applies a sequence of find/replace {@link Edit}s to the string value an accessor points at,\n * returning the resulting content. Throws if a non-`replaceAll` edit's `oldString` is not found.\n */\nexport const applyEdits = (accessor: Doc.Accessor, edits: readonly Edit[]): string => {\n for (const edit of edits) {\n // `''.indexOf('')` is 0 (never -1), so a `replaceAll` with an empty match would loop forever.\n if (edit.oldString.length === 0) {\n throw new Error('Edit oldString must be non-empty.');\n }\n\n accessor.handle.change((doc) => {\n const text = Doc.getValue<string>(accessor);\n // Automerge's `splice` types the path as mutable `Prop[]`; our `KeyPath` is readonly and is not mutated here.\n if (edit.replaceAll) {\n let idx = text.indexOf(edit.oldString);\n while (idx !== -1) {\n A.splice(doc, accessor.path as A.Prop[], idx, edit.oldString.length, edit.newString);\n const updated = Doc.getValue<string>(accessor);\n idx = updated.indexOf(edit.oldString, idx + edit.newString.length);\n }\n } else {\n const idx = text.indexOf(edit.oldString);\n if (idx === -1) {\n throw new Error(`Edit not found: ${JSON.stringify(edit.oldString)}`);\n }\n A.splice(doc, accessor.path as A.Prop[], idx, edit.oldString.length, edit.newString);\n }\n });\n }\n\n return Doc.getValue<string>(accessor);\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { next as A } from '@automerge/automerge';\n\nimport { isNonNullable } from '@dxos/util';\n\nimport * as Doc from './Doc';\n\n// Strings longer than this have collaborative editing disabled for performance reasons.\nconst STRING_CRDT_LIMIT = 300_000;\n\n/**\n * Default codec: encode a model value to an Automerge record.\n */\nexport const encode = (value: any): any => {\n if (Array.isArray(value)) {\n return value.map(encode);\n }\n if (value instanceof A.RawString) {\n throw new Error('Encode called on automerge data.');\n }\n if (typeof value === 'object' && value !== null) {\n return Object.fromEntries(\n Object.entries(value)\n .map(([key, value]) => {\n const encoded = encode(value);\n if (encoded === undefined) {\n return undefined;\n }\n return [key, encoded];\n })\n .filter(isNonNullable),\n );\n }\n if (typeof value === 'string' && value.length > STRING_CRDT_LIMIT) {\n return new A.RawString(value);\n }\n\n return value;\n};\n\n/**\n * Default codec: decode an Automerge record to a model value.\n */\nexport const decode = (value: any): any => {\n if (Array.isArray(value)) {\n return value.map(decode);\n }\n if (value instanceof A.RawString) {\n return value.toString();\n }\n if (typeof value === 'object' && value !== null) {\n return Object.fromEntries(Object.entries(value).map(([key, value]) => [key, decode(value)]));\n }\n\n return value;\n};\n\n/**\n * Relative path from `base`, or `undefined` if `path` is not under `base`. Used to filter mutations.\n */\nexport const rebasePath = (path: A.Prop[], base: Doc.KeyPath): A.Prop[] | undefined => {\n if (path.length < base.length) {\n return undefined;\n }\n for (let i = 0; i < base.length; ++i) {\n if (path[i] !== base[i]) {\n return undefined;\n }\n }\n\n return path.slice(base.length);\n};\n\n/**\n * Read the value at `path`. When `init` is set, auto-vivifies intermediate records.\n */\nexport const getDeep = (obj: any, path: Doc.KeyPath, init = false): any => {\n let value = obj;\n for (const key of path) {\n if (init) {\n value[key] ??= {};\n }\n value = value?.[key];\n }\n\n return value;\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { next as A } from '@automerge/automerge';\n\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { isNonNullable } from '@dxos/util';\n\nimport * as Doc from './Doc';\nimport { decode as defaultDecode, encode as defaultEncode, getDeep, rebasePath } from './record';\n\nexport type BaseElement = { id: string };\n\n/**\n * Batch of element changes.\n */\nexport type Batch<Element extends BaseElement> = {\n added?: Element[];\n updated?: Element[];\n deleted?: Element['id'][];\n};\n\n/**\n * Accumulates pending local mutations.\n */\nexport class Modified<Element extends BaseElement> {\n readonly added = new Map<Element['id'], Element>();\n readonly updated = new Map<Element['id'], Element>();\n readonly deleted = new Set<Element['id']>();\n\n batch(): Batch<Element> {\n return {\n added: Array.from(this.added.values()),\n updated: Array.from(this.updated.values()),\n deleted: Array.from(this.deleted.values()),\n };\n }\n\n clear(): void {\n this.added.clear();\n this.updated.clear();\n this.deleted.clear();\n }\n}\n\nexport type StoreAdapterOptions = {\n readonly?: boolean;\n /** Encode a model value to an Automerge record (defaults to a structural codec). */\n encode?: (value: any) => any;\n /** Decode an Automerge record to a model value. */\n decode?: (value: any) => any;\n};\n\n/**\n * Two-way sync between an external store and an id-keyed `Record<string, Element>` held at an\n * accessor's path within an Automerge document. Subclasses bind a concrete store (e.g. tldraw,\n * excalidraw) by implementing {@link getElements} / {@link onUpdate} and registering store\n * listeners in {@link onOpen}.\n */\n// TODO(burdon): Make element id key configurable.\nexport abstract class AbstractStoreAdapter<Element extends BaseElement> {\n #accessor?: Doc.Accessor<any>;\n #lastHeads?: A.Heads;\n #cleanup?: () => void;\n readonly #readonly: boolean;\n readonly #encode: (value: any) => any;\n readonly #decode: (value: any) => any;\n\n constructor(options: StoreAdapterOptions = {}) {\n this.#readonly = options.readonly ?? false;\n this.#encode = options.encode ?? defaultEncode;\n this.#decode = options.decode ?? defaultDecode;\n }\n\n get isOpen(): boolean {\n return !!this.#accessor;\n }\n\n get readonly(): boolean {\n return this.#readonly;\n }\n\n /**\n * Binds the adapter to the element map at `accessor.path`. Returns a dispose function; calling it\n * (or {@link close}) tears down the subscription and any listeners registered in {@link onOpen}.\n */\n open(accessor: Doc.Accessor<any>): () => void {\n invariant(accessor.path.length);\n if (this.isOpen) {\n this.close();\n }\n\n log('opening...', { path: accessor.path });\n this.#accessor = accessor;\n const onOpenCleanup = this.onOpen();\n\n // Seed the document from the store, or hydrate the store from the document.\n {\n const map: Record<string, Element> = getDeep(accessor.handle.doc(), accessor.path) ?? {};\n const records = Object.values(map);\n if (records.length === 0) {\n accessor.handle.change((doc) => {\n const map: Record<string, Element> = getDeep(doc, accessor.path, true);\n for (const record of this.getElements()) {\n map[record.id] = this.#encode(record);\n }\n });\n } else {\n this.onUpdate({ updated: records.map((record) => this.#decode(record)) });\n }\n }\n\n // Baseline heads after seeding so the first change diffs only post-open mutations (not full history).\n this.#lastHeads = A.getHeads(accessor.handle.doc());\n\n // Propagate document mutations (local and remote) into the store.\n const updateModel = () => {\n const doc = accessor.handle.doc();\n const map: Record<string, Element> = getDeep(doc, accessor.path);\n\n const updated = new Set<Element['id']>();\n const deleted = new Set<Element['id']>();\n\n const currentHeads = A.getHeads(doc);\n const diff = A.equals(this.#lastHeads, currentHeads) ? [] : A.diff(doc, this.#lastHeads ?? [], currentHeads);\n diff.forEach((patch) => {\n const relativePath = rebasePath(patch.path, accessor.path);\n if (!relativePath) {\n return;\n }\n\n // A patch on the map root (e.g. initial assignment) touches every element.\n if (relativePath.length === 0) {\n for (const id of Object.keys(map)) {\n updated.add(id as Element['id']);\n }\n return;\n }\n\n switch (patch.action) {\n case 'del': {\n if (relativePath.length === 1) {\n deleted.add(relativePath[0] as Element['id']);\n break;\n }\n }\n // eslint-disable-next-line no-fallthrough\n case 'put':\n case 'insert':\n case 'inc':\n case 'splice': {\n updated.add(relativePath[0] as Element['id']);\n break;\n }\n default:\n log.warn('did not process patch', { patch, path: accessor.path });\n }\n });\n\n if (updated.size || deleted.size) {\n this.onUpdate({\n updated: Array.from(updated)\n .map((id) => this.#decode(map[id]))\n .filter(isNonNullable), // Elements modified then eventually removed.\n deleted: Array.from(deleted),\n });\n }\n\n this.#lastHeads = currentHeads;\n };\n\n accessor.handle.addListener('change', updateModel);\n this.#cleanup = () => {\n accessor.handle.removeListener('change', updateModel);\n onOpenCleanup?.();\n };\n\n log('open');\n return () => this.close();\n }\n\n close(): void {\n if (!this.isOpen) {\n return;\n }\n\n log('closing...');\n this.onClose();\n this.#cleanup?.();\n this.#cleanup = undefined;\n this.#accessor = undefined;\n this.#lastHeads = undefined;\n log('closed');\n }\n\n /**\n * Writes a batch of element changes to the document.\n */\n protected updateDatabase(batch: Batch<Element>): void {\n invariant(this.isOpen);\n if (this.#readonly) {\n log.warn('attempting to update read-only store');\n return;\n }\n\n const accessor = this.#accessor!;\n accessor.handle.change((doc) => {\n const map: Record<string, Element> = getDeep(doc, accessor.path, true);\n this.#removeDeleted(batch, batch.added)?.forEach((element) => (map[element.id] = this.#encode(element)));\n this.#removeDeleted(batch, batch.updated)?.forEach((element) => (map[element.id] = this.#encode(element)));\n batch.deleted?.forEach((id) => delete map[id]);\n });\n }\n\n #removeDeleted(batch: Batch<Element>, elements?: Element[]): Element[] | undefined {\n return batch.deleted ? elements?.filter((element) => !batch.deleted!.includes(element.id)) : elements;\n }\n\n /**\n * Returns all elements currently in the store.\n */\n abstract getElements(): readonly Element[];\n\n /**\n * Applies document changes to the store.\n */\n protected abstract onUpdate(batch: Batch<Element>): void;\n\n /**\n * Called when the adapter opens; return a cleanup function to run on close (e.g. to remove store listeners).\n */\n protected onOpen(): (() => void) | void {}\n\n protected onClose(): void {}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,IAAa,YAAY,IAAI;AAM7B,IAAa,WAAW,IAAI;;;;;;;AAQ5B,IAAa,kBACX,KACA,SACgB;CAChB,MAAM,UAAmB,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI;CAC3D,eAAe,QAAQ,GAAG,GAAG,OAAO,+BAA+B;CACnE,eAAe,UAAU,OAAO,GAAG,QAAQ,oCAAoC;CAG/E,OAAO,cADqB,aAAa,GAAG,IAAI,MAAM,aAAa,GAAG,CAC7C,CAAC,CAAC,eAAe,OAAO;AACnD;;;;;;AAOA,IAAa,cACX,KACA,MACA,YACM;CACN,MAAM,WAAW,eAAe,KAAK,IAAI;CACzC,SAAS,OAAO,QAAQ,QAAQ;EAC9B,KAAE,WAAW,KAAK,SAAS,KAAK,MAAM,GAAG,OAAO;CAClD,CAAC;CACD,OAAO;AACT;;;;;;;AC5CA,IAAa,OAAO,OAAO,OAAO;CAChC,WAAW,OAAO,OAAO,YAAY,EACnC,aAAa,sCACf,CAAC;CACD,WAAW,OAAO,OAAO,YAAY,EACnC,aAAa,+BACf,CAAC;CACD,YAAY,OAAO,SAAS,OAAO,OAAO,CAAC,CAAC,YAAY,EACtD,aAAa,gFACf,CAAC;AACH,CAAC;;;;;AAQD,IAAa,cAAc,UAAwB,UAAmC;CACpF,KAAK,MAAM,QAAQ,OAAO;EAExB,IAAI,KAAK,UAAU,WAAW,GAC5B,MAAM,IAAI,MAAM,mCAAmC;EAGrD,SAAS,OAAO,QAAQ,QAAQ;GAC9B,MA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