@dxos/echo-doc 0.0.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 +105 -0
- package/README.md +8 -0
- package/dist/lib/neutral/index.mjs +320 -0
- package/dist/lib/neutral/index.mjs.map +7 -0
- package/dist/lib/neutral/meta.json +1 -0
- package/dist/types/src/Doc.d.ts +21 -0
- package/dist/types/src/Doc.d.ts.map +1 -0
- package/dist/types/src/Doc.test.d.ts +2 -0
- package/dist/types/src/Doc.test.d.ts.map +1 -0
- package/dist/types/src/edits.d.ts +19 -0
- package/dist/types/src/edits.d.ts.map +1 -0
- package/dist/types/src/index.d.ts +4 -0
- package/dist/types/src/index.d.ts.map +1 -0
- package/dist/types/src/record.d.ts +19 -0
- package/dist/types/src/record.d.ts.map +1 -0
- package/dist/types/src/store-adapter.d.ts +65 -0
- package/dist/types/src/store-adapter.d.ts.map +1 -0
- package/dist/types/src/store-adapter.test.d.ts +2 -0
- package/dist/types/src/store-adapter.test.d.ts.map +1 -0
- package/dist/types/tsconfig.tsbuildinfo +1 -0
- package/package.json +39 -0
- package/src/Doc.test.ts +98 -0
- package/src/Doc.ts +58 -0
- package/src/edits.ts +60 -0
- package/src/index.ts +13 -0
- package/src/record.ts +90 -0
- package/src/store-adapter.test.ts +100 -0
- package/src/store-adapter.ts +237 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# Functional Source License, Version 1.1, ALv2 Future License
|
|
2
|
+
|
|
3
|
+
## Abbreviation
|
|
4
|
+
|
|
5
|
+
FSL-1.1-Apache-2.0
|
|
6
|
+
|
|
7
|
+
## Notice
|
|
8
|
+
|
|
9
|
+
Copyright 2026 DXOS
|
|
10
|
+
|
|
11
|
+
## Terms and Conditions
|
|
12
|
+
|
|
13
|
+
### Licensor ("We")
|
|
14
|
+
|
|
15
|
+
The party offering the Software under these Terms and Conditions.
|
|
16
|
+
|
|
17
|
+
### The Software
|
|
18
|
+
|
|
19
|
+
The "Software" is each version of the software that we make available under
|
|
20
|
+
these Terms and Conditions, as indicated by our inclusion of these Terms and
|
|
21
|
+
Conditions with the Software.
|
|
22
|
+
|
|
23
|
+
### License Grant
|
|
24
|
+
|
|
25
|
+
Subject to your compliance with this License Grant and the Patents,
|
|
26
|
+
Redistribution and Trademark clauses below, we hereby grant you the right to
|
|
27
|
+
use, copy, modify, create derivative works, publicly perform, publicly display
|
|
28
|
+
and redistribute the Software for any Permitted Purpose identified below.
|
|
29
|
+
|
|
30
|
+
### Permitted Purpose
|
|
31
|
+
|
|
32
|
+
A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
|
|
33
|
+
means making the Software available to others in a commercial product or
|
|
34
|
+
service that:
|
|
35
|
+
|
|
36
|
+
1. substitutes for the Software;
|
|
37
|
+
|
|
38
|
+
2. substitutes for any other product or service we offer using the Software
|
|
39
|
+
that exists as of the date we make the Software available; or
|
|
40
|
+
|
|
41
|
+
3. offers the same or substantially similar functionality as the Software.
|
|
42
|
+
|
|
43
|
+
Permitted Purposes specifically include using the Software:
|
|
44
|
+
|
|
45
|
+
1. for your internal use and access;
|
|
46
|
+
|
|
47
|
+
2. for non-commercial education;
|
|
48
|
+
|
|
49
|
+
3. for non-commercial research; and
|
|
50
|
+
|
|
51
|
+
4. in connection with professional services that you provide to a licensee
|
|
52
|
+
using the Software in accordance with these Terms and Conditions.
|
|
53
|
+
|
|
54
|
+
### Patents
|
|
55
|
+
|
|
56
|
+
To the extent your use for a Permitted Purpose would necessarily infringe our
|
|
57
|
+
patents, the license grant above includes a license under our patents. If you
|
|
58
|
+
make a claim against any party that the Software infringes or contributes to
|
|
59
|
+
the infringement of any patent, then your patent license to the Software ends
|
|
60
|
+
immediately.
|
|
61
|
+
|
|
62
|
+
### Redistribution
|
|
63
|
+
|
|
64
|
+
The Terms and Conditions apply to all copies, modifications and derivatives of
|
|
65
|
+
the Software.
|
|
66
|
+
|
|
67
|
+
If you redistribute any copies, modifications or derivatives of the Software,
|
|
68
|
+
you must include a copy of or a link to these Terms and Conditions and not
|
|
69
|
+
remove any copyright notices provided in or with the Software.
|
|
70
|
+
|
|
71
|
+
### Disclaimer
|
|
72
|
+
|
|
73
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
|
|
74
|
+
IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
|
|
75
|
+
PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
|
|
76
|
+
|
|
77
|
+
IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
|
|
78
|
+
SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
|
|
79
|
+
EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
|
|
80
|
+
|
|
81
|
+
### Trademarks
|
|
82
|
+
|
|
83
|
+
Except for displaying the License Details and identifying us as the origin of
|
|
84
|
+
the Software, you have no right under these Terms and Conditions to use our
|
|
85
|
+
trademarks, trade names, service marks or product names.
|
|
86
|
+
|
|
87
|
+
## Grant of Future License
|
|
88
|
+
|
|
89
|
+
We hereby irrevocably grant you an additional license to use the Software under
|
|
90
|
+
the Apache License, Version 2.0 that is effective on the second anniversary of
|
|
91
|
+
the date we make the Software available. On or after that date, you may use the
|
|
92
|
+
Software under the Apache License, Version 2.0, in which case the following
|
|
93
|
+
will apply:
|
|
94
|
+
|
|
95
|
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
|
96
|
+
this file except in compliance with the License.
|
|
97
|
+
|
|
98
|
+
You may obtain a copy of the License at
|
|
99
|
+
|
|
100
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
101
|
+
|
|
102
|
+
Unless required by applicable law or agreed to in writing, software distributed
|
|
103
|
+
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
|
104
|
+
CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
|
105
|
+
specific language governing permissions and limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# @dxos/echo-doc
|
|
2
|
+
|
|
3
|
+
Opinionated Automerge document wrapper for ECHO.
|
|
4
|
+
|
|
5
|
+
Provides the `Doc.Accessor` abstraction — a value binding into an Automerge document at a key path —
|
|
6
|
+
and the higher-level patterns built on top of it (text edits via the `Edit` schema and `applyEdits`,
|
|
7
|
+
and `AbstractStoreAdapter` for syncing an id-keyed record map). The accessor is resolved via
|
|
8
|
+
`Doc.createAccessor`, which works identically for in-memory and database-attached objects.
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __export = (target, all) => {
|
|
3
|
+
for (var name in all)
|
|
4
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
// src/Doc.ts
|
|
8
|
+
var Doc_exports = {};
|
|
9
|
+
__export(Doc_exports, {
|
|
10
|
+
createAccessor: () => createAccessor,
|
|
11
|
+
getValue: () => getValue,
|
|
12
|
+
isKeyPath: () => isKeyPath,
|
|
13
|
+
updateText: () => updateText
|
|
14
|
+
});
|
|
15
|
+
import { next as A } from "@automerge/automerge";
|
|
16
|
+
import { Doc, createObject, getObjectCore, isEchoObject } from "@dxos/echo-client";
|
|
17
|
+
import { isProxy } from "@dxos/echo/internal";
|
|
18
|
+
import { assertArgument } from "@dxos/invariant";
|
|
19
|
+
var isKeyPath = Doc.isKeyPath;
|
|
20
|
+
var getValue = Doc.getValue;
|
|
21
|
+
var createAccessor = (obj, path) => {
|
|
22
|
+
const keyPath = Array.isArray(path) ? path : [
|
|
23
|
+
path
|
|
24
|
+
];
|
|
25
|
+
assertArgument(isProxy(obj), "obj", "expect obj to be a LiveObject");
|
|
26
|
+
assertArgument(isKeyPath(keyPath), "path", "expect path to be a valid key path");
|
|
27
|
+
const live = isEchoObject(obj) ? obj : createObject(obj);
|
|
28
|
+
return getObjectCore(live).getDocAccessor(keyPath);
|
|
29
|
+
};
|
|
30
|
+
var updateText = (obj, path, newText) => {
|
|
31
|
+
const accessor = createAccessor(obj, path);
|
|
32
|
+
accessor.handle.change((doc) => {
|
|
33
|
+
A.updateText(doc, accessor.path.slice(), newText);
|
|
34
|
+
});
|
|
35
|
+
return obj;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
// src/edits.ts
|
|
39
|
+
import { next as A2 } from "@automerge/automerge";
|
|
40
|
+
import * as Schema from "effect/Schema";
|
|
41
|
+
var Edit = Schema.Struct({
|
|
42
|
+
oldString: Schema.String.annotations({
|
|
43
|
+
description: "The exact text to find and replace."
|
|
44
|
+
}),
|
|
45
|
+
newString: Schema.String.annotations({
|
|
46
|
+
description: "The text to replace it with."
|
|
47
|
+
}),
|
|
48
|
+
replaceAll: Schema.optional(Schema.Boolean).annotations({
|
|
49
|
+
description: "Replace all occurrences of oldString (default: replace the first occurrence)."
|
|
50
|
+
})
|
|
51
|
+
});
|
|
52
|
+
var applyEdits = (accessor, edits) => {
|
|
53
|
+
for (const edit of edits) {
|
|
54
|
+
if (edit.oldString.length === 0) {
|
|
55
|
+
throw new Error("Edit oldString must be non-empty.");
|
|
56
|
+
}
|
|
57
|
+
accessor.handle.change((doc) => {
|
|
58
|
+
const text = getValue(accessor);
|
|
59
|
+
if (edit.replaceAll) {
|
|
60
|
+
let idx = text.indexOf(edit.oldString);
|
|
61
|
+
while (idx !== -1) {
|
|
62
|
+
A2.splice(doc, accessor.path, idx, edit.oldString.length, edit.newString);
|
|
63
|
+
const updated = getValue(accessor);
|
|
64
|
+
idx = updated.indexOf(edit.oldString, idx + edit.newString.length);
|
|
65
|
+
}
|
|
66
|
+
} else {
|
|
67
|
+
const idx = text.indexOf(edit.oldString);
|
|
68
|
+
if (idx === -1) {
|
|
69
|
+
throw new Error(`Edit not found: ${JSON.stringify(edit.oldString)}`);
|
|
70
|
+
}
|
|
71
|
+
A2.splice(doc, accessor.path, idx, edit.oldString.length, edit.newString);
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
return getValue(accessor);
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
// src/store-adapter.ts
|
|
79
|
+
import { next as A4 } from "@automerge/automerge";
|
|
80
|
+
import { invariant } from "@dxos/invariant";
|
|
81
|
+
import { log } from "@dxos/log";
|
|
82
|
+
import { isNonNullable as isNonNullable2 } from "@dxos/util";
|
|
83
|
+
|
|
84
|
+
// src/record.ts
|
|
85
|
+
import { next as A3 } from "@automerge/automerge";
|
|
86
|
+
import { isNonNullable } from "@dxos/util";
|
|
87
|
+
var STRING_CRDT_LIMIT = 3e5;
|
|
88
|
+
var encode = (value) => {
|
|
89
|
+
if (Array.isArray(value)) {
|
|
90
|
+
return value.map(encode);
|
|
91
|
+
}
|
|
92
|
+
if (value instanceof A3.RawString) {
|
|
93
|
+
throw new Error("Encode called on automerge data.");
|
|
94
|
+
}
|
|
95
|
+
if (typeof value === "object" && value !== null) {
|
|
96
|
+
return Object.fromEntries(Object.entries(value).map(([key, value2]) => {
|
|
97
|
+
const encoded = encode(value2);
|
|
98
|
+
if (encoded === void 0) {
|
|
99
|
+
return void 0;
|
|
100
|
+
}
|
|
101
|
+
return [
|
|
102
|
+
key,
|
|
103
|
+
encoded
|
|
104
|
+
];
|
|
105
|
+
}).filter(isNonNullable));
|
|
106
|
+
}
|
|
107
|
+
if (typeof value === "string" && value.length > STRING_CRDT_LIMIT) {
|
|
108
|
+
return new A3.RawString(value);
|
|
109
|
+
}
|
|
110
|
+
return value;
|
|
111
|
+
};
|
|
112
|
+
var decode = (value) => {
|
|
113
|
+
if (Array.isArray(value)) {
|
|
114
|
+
return value.map(decode);
|
|
115
|
+
}
|
|
116
|
+
if (value instanceof A3.RawString) {
|
|
117
|
+
return value.toString();
|
|
118
|
+
}
|
|
119
|
+
if (typeof value === "object" && value !== null) {
|
|
120
|
+
return Object.fromEntries(Object.entries(value).map(([key, value2]) => [
|
|
121
|
+
key,
|
|
122
|
+
decode(value2)
|
|
123
|
+
]));
|
|
124
|
+
}
|
|
125
|
+
return value;
|
|
126
|
+
};
|
|
127
|
+
var rebasePath = (path, base) => {
|
|
128
|
+
if (path.length < base.length) {
|
|
129
|
+
return void 0;
|
|
130
|
+
}
|
|
131
|
+
for (let i = 0; i < base.length; ++i) {
|
|
132
|
+
if (path[i] !== base[i]) {
|
|
133
|
+
return void 0;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return path.slice(base.length);
|
|
137
|
+
};
|
|
138
|
+
var getDeep = (obj, path, init = false) => {
|
|
139
|
+
let value = obj;
|
|
140
|
+
for (const key of path) {
|
|
141
|
+
if (init) {
|
|
142
|
+
value[key] ??= {};
|
|
143
|
+
}
|
|
144
|
+
value = value?.[key];
|
|
145
|
+
}
|
|
146
|
+
return value;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
// src/store-adapter.ts
|
|
150
|
+
var __dxlog_file = "/Users/jdw/Code/dxos/packages/core/echo/echo-doc/src/store-adapter.ts";
|
|
151
|
+
var Modified = class {
|
|
152
|
+
added = /* @__PURE__ */ new Map();
|
|
153
|
+
updated = /* @__PURE__ */ new Map();
|
|
154
|
+
deleted = /* @__PURE__ */ new Set();
|
|
155
|
+
batch() {
|
|
156
|
+
return {
|
|
157
|
+
added: Array.from(this.added.values()),
|
|
158
|
+
updated: Array.from(this.updated.values()),
|
|
159
|
+
deleted: Array.from(this.deleted.values())
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
clear() {
|
|
163
|
+
this.added.clear();
|
|
164
|
+
this.updated.clear();
|
|
165
|
+
this.deleted.clear();
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
var AbstractStoreAdapter = class {
|
|
169
|
+
#accessor;
|
|
170
|
+
#lastHeads;
|
|
171
|
+
#cleanup;
|
|
172
|
+
#readonly;
|
|
173
|
+
#encode;
|
|
174
|
+
#decode;
|
|
175
|
+
constructor(options = {}) {
|
|
176
|
+
this.#readonly = options.readonly ?? false;
|
|
177
|
+
this.#encode = options.encode ?? encode;
|
|
178
|
+
this.#decode = options.decode ?? decode;
|
|
179
|
+
}
|
|
180
|
+
get isOpen() {
|
|
181
|
+
return !!this.#accessor;
|
|
182
|
+
}
|
|
183
|
+
get readonly() {
|
|
184
|
+
return this.#readonly;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Binds the adapter to the element map at `accessor.path`. Returns a dispose function; calling it
|
|
188
|
+
* (or {@link close}) tears down the subscription and any listeners registered in {@link onOpen}.
|
|
189
|
+
*/
|
|
190
|
+
open(accessor) {
|
|
191
|
+
invariant(accessor.path.length, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 56, S: this, A: ["accessor.path.length", ""] });
|
|
192
|
+
if (this.isOpen) {
|
|
193
|
+
this.close();
|
|
194
|
+
}
|
|
195
|
+
log("opening...", {
|
|
196
|
+
path: accessor.path
|
|
197
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 60, S: this });
|
|
198
|
+
this.#accessor = accessor;
|
|
199
|
+
const onOpenCleanup = this.onOpen();
|
|
200
|
+
{
|
|
201
|
+
const map = getDeep(accessor.handle.doc(), accessor.path) ?? {};
|
|
202
|
+
const records = Object.values(map);
|
|
203
|
+
if (records.length === 0) {
|
|
204
|
+
accessor.handle.change((doc) => {
|
|
205
|
+
const map2 = getDeep(doc, accessor.path, true);
|
|
206
|
+
for (const record of this.getElements()) {
|
|
207
|
+
map2[record.id] = this.#encode(record);
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
} else {
|
|
211
|
+
this.onUpdate({
|
|
212
|
+
updated: records.map((record) => this.#decode(record))
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
this.#lastHeads = A4.getHeads(accessor.handle.doc());
|
|
217
|
+
const updateModel = () => {
|
|
218
|
+
const doc = accessor.handle.doc();
|
|
219
|
+
const map = getDeep(doc, accessor.path);
|
|
220
|
+
const updated = /* @__PURE__ */ new Set();
|
|
221
|
+
const deleted = /* @__PURE__ */ new Set();
|
|
222
|
+
const currentHeads = A4.getHeads(doc);
|
|
223
|
+
const diff = A4.equals(this.#lastHeads, currentHeads) ? [] : A4.diff(doc, this.#lastHeads ?? [], currentHeads);
|
|
224
|
+
diff.forEach((patch) => {
|
|
225
|
+
const relativePath = rebasePath(patch.path, accessor.path);
|
|
226
|
+
if (!relativePath) {
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (relativePath.length === 0) {
|
|
230
|
+
for (const id of Object.keys(map)) {
|
|
231
|
+
updated.add(id);
|
|
232
|
+
}
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
switch (patch.action) {
|
|
236
|
+
case "del": {
|
|
237
|
+
if (relativePath.length === 1) {
|
|
238
|
+
deleted.add(relativePath[0]);
|
|
239
|
+
break;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
// eslint-disable-next-line no-fallthrough
|
|
243
|
+
case "put":
|
|
244
|
+
case "insert":
|
|
245
|
+
case "inc":
|
|
246
|
+
case "splice": {
|
|
247
|
+
updated.add(relativePath[0]);
|
|
248
|
+
break;
|
|
249
|
+
}
|
|
250
|
+
default:
|
|
251
|
+
log.warn("did not process patch", {
|
|
252
|
+
patch,
|
|
253
|
+
path: accessor.path
|
|
254
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 122, S: this });
|
|
255
|
+
}
|
|
256
|
+
});
|
|
257
|
+
if (updated.size || deleted.size) {
|
|
258
|
+
this.onUpdate({
|
|
259
|
+
updated: Array.from(updated).map((id) => this.#decode(map[id])).filter(isNonNullable2),
|
|
260
|
+
deleted: Array.from(deleted)
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
this.#lastHeads = currentHeads;
|
|
264
|
+
};
|
|
265
|
+
accessor.handle.addListener("change", updateModel);
|
|
266
|
+
this.#cleanup = () => {
|
|
267
|
+
accessor.handle.removeListener("change", updateModel);
|
|
268
|
+
onOpenCleanup?.();
|
|
269
|
+
};
|
|
270
|
+
log("open", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 141, S: this });
|
|
271
|
+
return () => this.close();
|
|
272
|
+
}
|
|
273
|
+
close() {
|
|
274
|
+
if (!this.isOpen) {
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
log("closing...", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 148, S: this });
|
|
278
|
+
this.onClose();
|
|
279
|
+
this.#cleanup?.();
|
|
280
|
+
this.#cleanup = void 0;
|
|
281
|
+
this.#accessor = void 0;
|
|
282
|
+
this.#lastHeads = void 0;
|
|
283
|
+
log("closed", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 154, S: this });
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Writes a batch of element changes to the document.
|
|
287
|
+
*/
|
|
288
|
+
updateDatabase(batch) {
|
|
289
|
+
invariant(this.isOpen, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 159, S: this, A: ["this.isOpen", ""] });
|
|
290
|
+
if (this.#readonly) {
|
|
291
|
+
log.warn("attempting to update read-only store", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 161, S: this });
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
const accessor = this.#accessor;
|
|
295
|
+
accessor.handle.change((doc) => {
|
|
296
|
+
const map = getDeep(doc, accessor.path, true);
|
|
297
|
+
this.#removeDeleted(batch, batch.added)?.forEach((element) => map[element.id] = this.#encode(element));
|
|
298
|
+
this.#removeDeleted(batch, batch.updated)?.forEach((element) => map[element.id] = this.#encode(element));
|
|
299
|
+
batch.deleted?.forEach((id) => delete map[id]);
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
#removeDeleted(batch, elements) {
|
|
303
|
+
return batch.deleted ? elements?.filter((element) => !batch.deleted.includes(element.id)) : elements;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Called when the adapter opens; return a cleanup function to run on close (e.g. to remove store listeners).
|
|
307
|
+
*/
|
|
308
|
+
onOpen() {
|
|
309
|
+
}
|
|
310
|
+
onClose() {
|
|
311
|
+
}
|
|
312
|
+
};
|
|
313
|
+
export {
|
|
314
|
+
AbstractStoreAdapter,
|
|
315
|
+
Doc_exports as Doc,
|
|
316
|
+
Edit,
|
|
317
|
+
Modified,
|
|
318
|
+
applyEdits
|
|
319
|
+
};
|
|
320
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/Doc.ts", "../../../src/edits.ts", "../../../src/store-adapter.ts", "../../../src/record.ts"],
|
|
4
|
+
"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 { 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", "//\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"],
|
|
5
|
+
"mappings": ";;;;;;;AAAA;;;;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A;;;;;EAMF,SAAA;EAAA;;;;",
|
|
6
|
+
"names": ["next", "A", "Doc", "createObject", "getObjectCore", "isEchoObject", "isProxy", "assertArgument", "isKeyPath", "getValue", "createAccessor", "obj", "path", "keyPath", "Array", "isArray", "live", "getDocAccessor", "updateText", "newText", "accessor", "handle", "change", "doc", "slice", "next", "A", "Schema", "Edit", "Struct", "oldString", "String", "annotations", "description", "newString", "replaceAll", "optional", "Boolean", "applyEdits", "accessor", "edits", "edit", "length", "Error", "handle", "change", "doc", "text", "getValue", "idx", "indexOf", "A", "splice", "path", "updated", "JSON", "stringify", "next", "A", "invariant", "log", "isNonNullable", "next", "A", "isNonNullable", "STRING_CRDT_LIMIT", "encode", "value", "Array", "isArray", "map", "RawString", "Error", "Object", "fromEntries", "entries", "key", "encoded", "undefined", "filter", "length", "decode", "toString", "rebasePath", "path", "base", "i", "slice", "getDeep", "obj", "init", "updated", "deleted", "Set", "batch", "added", "Array", "from", "values", "clear", "options", "decode", "defaultDecode", "isOpen", "readonly", "close", "accessor", "onOpenCleanup", "onOpen", "records", "length", "handle", "change", "doc", "getDeep", "record", "getElements", "map", "updateModel", "currentHeads", "getHeads", "diff", "equals", "forEach", "patch", "relativePath", "rebasePath", "path", "add", "id", "log", "isNonNullable", "addListener", "removeListener", "warn"]
|
|
7
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"inputs":{"src/Doc.ts":{"bytes":6027,"imports":[{"path":"@automerge/automerge","kind":"import-statement","external":true},{"path":"@dxos/echo-client","kind":"import-statement","external":true},{"path":"@dxos/echo/internal","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"format":"esm"},"src/edits.ts":{"bytes":7454,"imports":[{"path":"@automerge/automerge","kind":"import-statement","external":true},{"path":"effect/Schema","kind":"import-statement","external":true},{"path":"src/Doc.ts","kind":"import-statement","original":"./Doc"}],"format":"esm"},"src/record.ts":{"bytes":7830,"imports":[{"path":"@automerge/automerge","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"src/store-adapter.ts":{"bytes":24113,"imports":[{"path":"@automerge/automerge","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"src/record.ts","kind":"import-statement","original":"./record"}],"format":"esm"},"src/index.ts":{"bytes":944,"imports":[{"path":"src/Doc.ts","kind":"import-statement","original":"./Doc"},{"path":"src/edits.ts","kind":"import-statement","original":"./edits"},{"path":"src/store-adapter.ts","kind":"import-statement","original":"./store-adapter"}],"format":"esm"}},"outputs":{"dist/lib/neutral/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":22165},"dist/lib/neutral/index.mjs":{"imports":[{"path":"@automerge/automerge","kind":"import-statement","external":true},{"path":"@dxos/echo-client","kind":"import-statement","external":true},{"path":"@dxos/echo/internal","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@automerge/automerge","kind":"import-statement","external":true},{"path":"effect/Schema","kind":"import-statement","external":true},{"path":"@automerge/automerge","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@automerge/automerge","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"exports":["AbstractStoreAdapter","Doc","Edit","Modified","applyEdits"],"entryPoint":"src/index.ts","inputs":{"src/Doc.ts":{"bytesInOutput":1047},"src/index.ts":{"bytesInOutput":0},"src/edits.ts":{"bytesInOutput":1375},"src/store-adapter.ts":{"bytesInOutput":5632},"src/record.ts":{"bytesInOutput":1541}},"bytes":9988}}}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Doc } from '@dxos/echo-client';
|
|
2
|
+
import { type AnyProperties } from '@dxos/echo/internal';
|
|
3
|
+
export type KeyPath = Doc.KeyPath;
|
|
4
|
+
export declare const isKeyPath: (value: unknown) => value is Doc.KeyPath;
|
|
5
|
+
export type Handle<T = any> = Doc.Handle<T>;
|
|
6
|
+
export type Accessor<T = any> = Doc.Accessor<T>;
|
|
7
|
+
export declare const getValue: <V, T = any>(accessor: Doc.Accessor<T>) => V;
|
|
8
|
+
/**
|
|
9
|
+
* Resolves an {@link Accessor} for a value within an object, agnostic to whether the object is
|
|
10
|
+
* in-memory or attached to a database. An `Obj.make` object has no `ObjectCore` until `db.add`,
|
|
11
|
+
* so an in-memory core is materialized (via `createObject`) to let the accessor bind before
|
|
12
|
+
* persistence; the object's edits then survive a later `db.add`.
|
|
13
|
+
*/
|
|
14
|
+
export declare const createAccessor: <T extends AnyProperties>(obj: T, path: KeyPath | Extract<keyof T, string | number>) => Accessor<T>;
|
|
15
|
+
/**
|
|
16
|
+
* Sets the text value at the given path, applying the change as a minimal Automerge delta (via
|
|
17
|
+
* `A.updateText`) rather than replacing the whole string. This preserves cursors/anchors and merges
|
|
18
|
+
* cleanly with concurrent edits — use it to write an edited string back into a collaborative text field.
|
|
19
|
+
*/
|
|
20
|
+
export declare const updateText: <T extends AnyProperties>(obj: T, path: KeyPath | Extract<keyof T, string | number>, newText: string) => T;
|
|
21
|
+
//# sourceMappingURL=Doc.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Doc.d.ts","sourceRoot":"","sources":["../../../src/Doc.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,GAAG,EAA6C,MAAM,mBAAmB,CAAC;AACnF,OAAO,EAAE,KAAK,aAAa,EAAW,MAAM,qBAAqB,CAAC;AAKlE,MAAM,MAAM,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC;AAElC,eAAO,MAAM,SAAS,0CAAgB,CAAC;AAEvC,MAAM,MAAM,MAAM,CAAC,CAAC,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AAE5C,MAAM,MAAM,QAAQ,CAAC,CAAC,GAAG,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;AAEhD,eAAO,MAAM,QAAQ,8CAAe,CAAC;AAErC;;;;;GAKG;AACH,eAAO,MAAM,cAAc,GAAI,CAAC,SAAS,aAAa,OAC/C,CAAC,QACA,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC,KAChD,QAAQ,CAAC,CAAC,CAOZ,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,UAAU,GAAI,CAAC,SAAS,aAAa,OAC3C,CAAC,QACA,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC,WACxC,MAAM,KACd,CAMF,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Doc.test.d.ts","sourceRoot":"","sources":["../../../src/Doc.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import * as Schema from 'effect/Schema';
|
|
2
|
+
import * as Doc from './Doc';
|
|
3
|
+
/**
|
|
4
|
+
* A single find/replace edit applied to a text document. This is the structured form of the diff
|
|
5
|
+
* protocol described in document skills' instructions.
|
|
6
|
+
*/
|
|
7
|
+
export declare const Edit: Schema.Struct<{
|
|
8
|
+
oldString: Schema.SchemaClass<string, string, never>;
|
|
9
|
+
newString: Schema.SchemaClass<string, string, never>;
|
|
10
|
+
replaceAll: Schema.optional<typeof Schema.Boolean>;
|
|
11
|
+
}>;
|
|
12
|
+
export interface Edit extends Schema.Schema.Type<typeof Edit> {
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Applies a sequence of find/replace {@link Edit}s to the string value an accessor points at,
|
|
16
|
+
* returning the resulting content. Throws if a non-`replaceAll` edit's `oldString` is not found.
|
|
17
|
+
*/
|
|
18
|
+
export declare const applyEdits: (accessor: Doc.Accessor, edits: readonly Edit[]) => string;
|
|
19
|
+
//# sourceMappingURL=edits.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"edits.d.ts","sourceRoot":"","sources":["../../../src/edits.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAExC,OAAO,KAAK,GAAG,MAAM,OAAO,CAAC;AAE7B;;;GAGG;AACH,eAAO,MAAM,IAAI;;;;EAUf,CAAC;AAEH,MAAM,WAAW,IAAK,SAAQ,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,IAAI,CAAC;CAAG;AAEhE;;;GAGG;AACH,eAAO,MAAM,UAAU,aAAc,GAAG,CAAC,QAAQ,SAAS,SAAS,IAAI,EAAE,KAAG,MA4B3E,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,GAAG,MAAM,OAAO,CAAC;AAC7B,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,EACL,oBAAoB,EACpB,KAAK,WAAW,EAChB,KAAK,KAAK,EACV,QAAQ,EACR,KAAK,mBAAmB,GACzB,MAAM,iBAAiB,CAAC"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { next as A } from '@automerge/automerge';
|
|
2
|
+
import * as Doc from './Doc';
|
|
3
|
+
/**
|
|
4
|
+
* Default codec: encode a model value to an Automerge record.
|
|
5
|
+
*/
|
|
6
|
+
export declare const encode: (value: any) => any;
|
|
7
|
+
/**
|
|
8
|
+
* Default codec: decode an Automerge record to a model value.
|
|
9
|
+
*/
|
|
10
|
+
export declare const decode: (value: any) => any;
|
|
11
|
+
/**
|
|
12
|
+
* Relative path from `base`, or `undefined` if `path` is not under `base`. Used to filter mutations.
|
|
13
|
+
*/
|
|
14
|
+
export declare const rebasePath: (path: A.Prop[], base: Doc.KeyPath) => A.Prop[] | undefined;
|
|
15
|
+
/**
|
|
16
|
+
* Read the value at `path`. When `init` is set, auto-vivifies intermediate records.
|
|
17
|
+
*/
|
|
18
|
+
export declare const getDeep: (obj: any, path: Doc.KeyPath, init?: boolean) => any;
|
|
19
|
+
//# sourceMappingURL=record.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"record.d.ts","sourceRoot":"","sources":["../../../src/record.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,IAAI,IAAI,CAAC,EAAE,MAAM,sBAAsB,CAAC;AAIjD,OAAO,KAAK,GAAG,MAAM,OAAO,CAAC;AAK7B;;GAEG;AACH,eAAO,MAAM,MAAM,UAAW,GAAG,KAAG,GAyBnC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,MAAM,UAAW,GAAG,KAAG,GAYnC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,UAAU,SAAU,CAAC,CAAC,IAAI,EAAE,QAAQ,GAAG,CAAC,OAAO,KAAG,CAAC,CAAC,IAAI,EAAE,GAAG,SAWzE,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,OAAO,QAAS,GAAG,QAAQ,GAAG,CAAC,OAAO,qBAAiB,GAUnE,CAAC"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import * as Doc from './Doc';
|
|
2
|
+
export type BaseElement = {
|
|
3
|
+
id: string;
|
|
4
|
+
};
|
|
5
|
+
/**
|
|
6
|
+
* Batch of element changes.
|
|
7
|
+
*/
|
|
8
|
+
export type Batch<Element extends BaseElement> = {
|
|
9
|
+
added?: Element[];
|
|
10
|
+
updated?: Element[];
|
|
11
|
+
deleted?: Element['id'][];
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Accumulates pending local mutations.
|
|
15
|
+
*/
|
|
16
|
+
export declare class Modified<Element extends BaseElement> {
|
|
17
|
+
readonly added: Map<Element["id"], Element>;
|
|
18
|
+
readonly updated: Map<Element["id"], Element>;
|
|
19
|
+
readonly deleted: Set<Element["id"]>;
|
|
20
|
+
batch(): Batch<Element>;
|
|
21
|
+
clear(): void;
|
|
22
|
+
}
|
|
23
|
+
export type StoreAdapterOptions = {
|
|
24
|
+
readonly?: boolean;
|
|
25
|
+
/** Encode a model value to an Automerge record (defaults to a structural codec). */
|
|
26
|
+
encode?: (value: any) => any;
|
|
27
|
+
/** Decode an Automerge record to a model value. */
|
|
28
|
+
decode?: (value: any) => any;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Two-way sync between an external store and an id-keyed `Record<string, Element>` held at an
|
|
32
|
+
* accessor's path within an Automerge document. Subclasses bind a concrete store (e.g. tldraw,
|
|
33
|
+
* excalidraw) by implementing {@link getElements} / {@link onUpdate} and registering store
|
|
34
|
+
* listeners in {@link onOpen}.
|
|
35
|
+
*/
|
|
36
|
+
export declare abstract class AbstractStoreAdapter<Element extends BaseElement> {
|
|
37
|
+
#private;
|
|
38
|
+
constructor(options?: StoreAdapterOptions);
|
|
39
|
+
get isOpen(): boolean;
|
|
40
|
+
get readonly(): boolean;
|
|
41
|
+
/**
|
|
42
|
+
* Binds the adapter to the element map at `accessor.path`. Returns a dispose function; calling it
|
|
43
|
+
* (or {@link close}) tears down the subscription and any listeners registered in {@link onOpen}.
|
|
44
|
+
*/
|
|
45
|
+
open(accessor: Doc.Accessor<any>): () => void;
|
|
46
|
+
close(): void;
|
|
47
|
+
/**
|
|
48
|
+
* Writes a batch of element changes to the document.
|
|
49
|
+
*/
|
|
50
|
+
protected updateDatabase(batch: Batch<Element>): void;
|
|
51
|
+
/**
|
|
52
|
+
* Returns all elements currently in the store.
|
|
53
|
+
*/
|
|
54
|
+
abstract getElements(): readonly Element[];
|
|
55
|
+
/**
|
|
56
|
+
* Applies document changes to the store.
|
|
57
|
+
*/
|
|
58
|
+
protected abstract onUpdate(batch: Batch<Element>): void;
|
|
59
|
+
/**
|
|
60
|
+
* Called when the adapter opens; return a cleanup function to run on close (e.g. to remove store listeners).
|
|
61
|
+
*/
|
|
62
|
+
protected onOpen(): (() => void) | void;
|
|
63
|
+
protected onClose(): void;
|
|
64
|
+
}
|
|
65
|
+
//# sourceMappingURL=store-adapter.d.ts.map
|