@dxos/echo-pipeline 0.4.10-main.c42bfdb → 0.4.10-main.cb83c78

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.
Files changed (51) hide show
  1. package/dist/lib/browser/{chunk-RA6MLCZM.mjs → chunk-SYE4EK33.mjs} +17 -9
  2. package/dist/lib/browser/chunk-SYE4EK33.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +290 -229
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/testing/index.mjs +8 -2
  7. package/dist/lib/browser/testing/index.mjs.map +4 -4
  8. package/dist/lib/node/{chunk-KGIYLJBT.cjs → chunk-WCTX6RNS.cjs} +19 -11
  9. package/dist/lib/node/chunk-WCTX6RNS.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +305 -247
  11. package/dist/lib/node/index.cjs.map +4 -4
  12. package/dist/lib/node/meta.json +1 -1
  13. package/dist/lib/node/testing/index.cjs +18 -13
  14. package/dist/lib/node/testing/index.cjs.map +4 -4
  15. package/dist/types/src/automerge/automerge-host.d.ts +19 -17
  16. package/dist/types/src/automerge/automerge-host.d.ts.map +1 -1
  17. package/dist/types/src/automerge/index.d.ts +1 -0
  18. package/dist/types/src/automerge/index.d.ts.map +1 -1
  19. package/dist/types/src/automerge/level.test.d.ts +2 -0
  20. package/dist/types/src/automerge/level.test.d.ts.map +1 -0
  21. package/dist/types/src/automerge/leveldb-storage-adapter.d.ts +30 -0
  22. package/dist/types/src/automerge/leveldb-storage-adapter.d.ts.map +1 -0
  23. package/dist/types/src/automerge/local-host-network-adapter.d.ts +8 -1
  24. package/dist/types/src/automerge/local-host-network-adapter.d.ts.map +1 -1
  25. package/dist/types/src/automerge/migrations.d.ts +7 -0
  26. package/dist/types/src/automerge/migrations.d.ts.map +1 -0
  27. package/dist/types/src/automerge/storage-adapter.test.d.ts +2 -0
  28. package/dist/types/src/automerge/storage-adapter.test.d.ts.map +1 -0
  29. package/dist/types/src/automerge/types.d.ts +6 -0
  30. package/dist/types/src/automerge/types.d.ts.map +1 -1
  31. package/dist/types/src/metadata/metadata-store.d.ts +2 -1
  32. package/dist/types/src/metadata/metadata-store.d.ts.map +1 -1
  33. package/dist/types/src/testing/index.d.ts +1 -0
  34. package/dist/types/src/testing/index.d.ts.map +1 -1
  35. package/dist/types/src/testing/level.d.ts +3 -0
  36. package/dist/types/src/testing/level.d.ts.map +1 -0
  37. package/package.json +33 -30
  38. package/src/automerge/automerge-host.test.ts +22 -8
  39. package/src/automerge/automerge-host.ts +44 -113
  40. package/src/automerge/index.ts +1 -0
  41. package/src/automerge/level.test.ts +64 -0
  42. package/src/automerge/leveldb-storage-adapter.ts +117 -0
  43. package/src/automerge/local-host-network-adapter.ts +19 -13
  44. package/src/automerge/migrations.ts +41 -0
  45. package/src/automerge/storage-adapter.test.ts +90 -0
  46. package/src/automerge/types.ts +6 -3
  47. package/src/metadata/metadata-store.ts +17 -8
  48. package/src/testing/index.ts +1 -0
  49. package/src/testing/level.ts +11 -0
  50. package/dist/lib/browser/chunk-RA6MLCZM.mjs.map +0 -7
  51. package/dist/lib/node/chunk-KGIYLJBT.cjs.map +0 -7
@@ -18,173 +18,168 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var node_exports = {};
20
20
  __export(node_exports, {
21
- AuthExtension: () => import_chunk_KGIYLJBT.AuthExtension,
22
- AuthStatus: () => import_chunk_KGIYLJBT.AuthStatus,
21
+ AuthExtension: () => import_chunk_WCTX6RNS.AuthExtension,
22
+ AuthStatus: () => import_chunk_WCTX6RNS.AuthStatus,
23
23
  AutomergeDocumentLoaderImpl: () => AutomergeDocumentLoaderImpl,
24
24
  AutomergeHost: () => AutomergeHost,
25
25
  AutomergeStorageAdapter: () => AutomergeStorageAdapter,
26
- DataServiceImpl: () => import_chunk_KGIYLJBT.DataServiceImpl,
26
+ DataServiceImpl: () => import_chunk_WCTX6RNS.DataServiceImpl,
27
+ LevelDBStorageAdapter: () => LevelDBStorageAdapter,
27
28
  LocalHostNetworkAdapter: () => LocalHostNetworkAdapter,
28
- MOCK_AUTH_PROVIDER: () => import_chunk_KGIYLJBT.MOCK_AUTH_PROVIDER,
29
- MOCK_AUTH_VERIFIER: () => import_chunk_KGIYLJBT.MOCK_AUTH_VERIFIER,
29
+ MOCK_AUTH_PROVIDER: () => import_chunk_WCTX6RNS.MOCK_AUTH_PROVIDER,
30
+ MOCK_AUTH_VERIFIER: () => import_chunk_WCTX6RNS.MOCK_AUTH_VERIFIER,
30
31
  MeshNetworkAdapter: () => MeshNetworkAdapter,
31
- MetadataStore: () => import_chunk_KGIYLJBT.MetadataStore,
32
- Pipeline: () => import_chunk_KGIYLJBT.Pipeline,
32
+ MetadataStore: () => import_chunk_WCTX6RNS.MetadataStore,
33
+ Pipeline: () => import_chunk_WCTX6RNS.Pipeline,
33
34
  REFERENCE_TYPE_TAG: () => REFERENCE_TYPE_TAG,
34
- SnapshotManager: () => import_chunk_KGIYLJBT.SnapshotManager,
35
- SnapshotStore: () => import_chunk_KGIYLJBT.SnapshotStore,
36
- Space: () => import_chunk_KGIYLJBT.Space,
37
- SpaceManager: () => import_chunk_KGIYLJBT.SpaceManager,
38
- SpaceProtocol: () => import_chunk_KGIYLJBT.SpaceProtocol,
39
- SpaceProtocolSession: () => import_chunk_KGIYLJBT.SpaceProtocolSession,
40
- TimeframeClock: () => import_chunk_KGIYLJBT.TimeframeClock,
41
- codec: () => import_chunk_KGIYLJBT.codec,
42
- createMappedFeedWriter: () => import_chunk_KGIYLJBT.createMappedFeedWriter,
35
+ SnapshotManager: () => import_chunk_WCTX6RNS.SnapshotManager,
36
+ SnapshotStore: () => import_chunk_WCTX6RNS.SnapshotStore,
37
+ Space: () => import_chunk_WCTX6RNS.Space,
38
+ SpaceManager: () => import_chunk_WCTX6RNS.SpaceManager,
39
+ SpaceProtocol: () => import_chunk_WCTX6RNS.SpaceProtocol,
40
+ SpaceProtocolSession: () => import_chunk_WCTX6RNS.SpaceProtocolSession,
41
+ TimeframeClock: () => import_chunk_WCTX6RNS.TimeframeClock,
42
+ codec: () => import_chunk_WCTX6RNS.codec,
43
+ createMappedFeedWriter: () => import_chunk_WCTX6RNS.createMappedFeedWriter,
43
44
  decodeReference: () => decodeReference,
44
45
  encodeReference: () => encodeReference,
46
+ encodingOptions: () => encodingOptions,
45
47
  getSpaceKeyFromDoc: () => getSpaceKeyFromDoc,
48
+ hasInvitationExpired: () => import_chunk_WCTX6RNS.hasInvitationExpired,
46
49
  isEncodedReferenceObject: () => isEncodedReferenceObject,
47
- mapFeedIndexesToTimeframe: () => import_chunk_KGIYLJBT.mapFeedIndexesToTimeframe,
48
- mapTimeframeToFeedIndexes: () => import_chunk_KGIYLJBT.mapTimeframeToFeedIndexes,
49
- startAfter: () => import_chunk_KGIYLJBT.startAfter,
50
- valueEncoding: () => import_chunk_KGIYLJBT.valueEncoding
50
+ mapFeedIndexesToTimeframe: () => import_chunk_WCTX6RNS.mapFeedIndexesToTimeframe,
51
+ mapTimeframeToFeedIndexes: () => import_chunk_WCTX6RNS.mapTimeframeToFeedIndexes,
52
+ startAfter: () => import_chunk_WCTX6RNS.startAfter,
53
+ valueEncoding: () => import_chunk_WCTX6RNS.valueEncoding
51
54
  });
52
55
  module.exports = __toCommonJS(node_exports);
53
- var import_chunk_KGIYLJBT = require("./chunk-KGIYLJBT.cjs");
56
+ var import_chunk_WCTX6RNS = require("./chunk-WCTX6RNS.cjs");
54
57
  var import_automerge = require("@dxos/automerge/automerge");
55
58
  var import_automerge_repo = require("@dxos/automerge/automerge-repo");
56
- var import_automerge_repo_storage_indexeddb = require("@dxos/automerge/automerge-repo-storage-indexeddb");
57
59
  var import_context = require("@dxos/context");
58
60
  var import_keys = require("@dxos/keys");
59
61
  var import_log = require("@dxos/log");
60
- var import_protocols = require("@dxos/protocols");
61
- var import_random_access_storage = require("@dxos/random-access-storage");
62
62
  var import_tracing = require("@dxos/tracing");
63
63
  var import_util = require("@dxos/util");
64
- var import_util2 = require("@dxos/util");
64
+ var import_context2 = require("@dxos/context");
65
65
  var import_async = require("@dxos/async");
66
66
  var import_automerge_repo2 = require("@dxos/automerge/automerge-repo");
67
67
  var import_codec_protobuf = require("@dxos/codec-protobuf");
68
68
  var import_invariant = require("@dxos/invariant");
69
- var import_log2 = require("@dxos/log");
70
69
  var import_async2 = require("@dxos/async");
71
70
  var import_automerge_repo3 = require("@dxos/automerge/automerge-repo");
72
71
  var import_invariant2 = require("@dxos/invariant");
73
- var import_log3 = require("@dxos/log");
72
+ var import_log2 = require("@dxos/log");
74
73
  var import_teleport_extension_automerge_replicator = require("@dxos/teleport-extension-automerge-replicator");
74
+ var import_automerge_repo_storage_indexeddb = require("@dxos/automerge/automerge-repo-storage-indexeddb");
75
+ var import_log3 = require("@dxos/log");
76
+ var import_random_access_storage = require("@dxos/random-access-storage");
77
+ var import_util2 = require("@dxos/util");
75
78
  var import_async3 = require("@dxos/async");
76
- var import_context2 = require("@dxos/context");
79
+ var import_context3 = require("@dxos/context");
77
80
  var import_debug = require("@dxos/debug");
78
81
  var import_invariant3 = require("@dxos/invariant");
79
82
  var import_log4 = require("@dxos/log");
80
83
  var import_echo_db = require("@dxos/echo-db");
81
- var AutomergeStorageAdapter = class {
82
- constructor(_directory) {
83
- this._directory = _directory;
84
- this._state = "opened";
84
+ var LevelDBStorageAdapter = class extends import_context2.Resource {
85
+ constructor(_params) {
86
+ super();
87
+ this._params = _params;
85
88
  }
86
- async load(key) {
87
- if (this._state !== "opened") {
88
- return void 0;
89
- }
90
- const filename = this._getFilename(key);
91
- const file = this._directory.getOrCreateFile(filename);
92
- const { size } = await file.stat();
93
- if (!size || size === 0) {
94
- return void 0;
89
+ async load(keyArray) {
90
+ try {
91
+ if (this._lifecycleState !== import_context2.LifecycleState.OPEN) {
92
+ return void 0;
93
+ }
94
+ return await this._params.db.get(keyArray, {
95
+ ...encodingOptions
96
+ });
97
+ } catch (err) {
98
+ if (isLevelDbNotFoundError(err)) {
99
+ return void 0;
100
+ }
101
+ throw err;
95
102
  }
96
- const buffer = await file.read(0, size);
97
- return (0, import_util2.bufferToArray)(buffer);
98
103
  }
99
- async save(key, data) {
100
- if (this._state !== "opened") {
104
+ async save(keyArray, binary) {
105
+ if (this._lifecycleState !== import_context2.LifecycleState.OPEN) {
101
106
  return void 0;
102
107
  }
103
- const filename = this._getFilename(key);
104
- const file = this._directory.getOrCreateFile(filename);
105
- await file.write(0, (0, import_util2.arrayToBuffer)(data));
106
- await file.truncate?.(data.length);
107
- await file.flush?.();
108
+ const batch = this._params.db.batch();
109
+ await this._params.callbacks?.beforeSave?.({
110
+ path: keyArray,
111
+ batch
112
+ });
113
+ batch.put(keyArray, Buffer.from(binary), {
114
+ ...encodingOptions
115
+ });
116
+ await batch.write();
117
+ await this._params.callbacks?.afterSave?.(keyArray);
108
118
  }
109
- async remove(key) {
110
- if (this._state !== "opened") {
119
+ async remove(keyArray) {
120
+ if (this._lifecycleState !== import_context2.LifecycleState.OPEN) {
111
121
  return void 0;
112
122
  }
113
- const filename = this._getFilename(key);
114
- const file = this._directory.getOrCreateFile(filename);
115
- await file.destroy();
123
+ await this._params.db.del(keyArray, {
124
+ ...encodingOptions
125
+ });
116
126
  }
117
127
  async loadRange(keyPrefix) {
118
- if (this._state !== "opened") {
128
+ if (this._lifecycleState !== import_context2.LifecycleState.OPEN) {
119
129
  return [];
120
130
  }
121
- const filename = this._getFilename(keyPrefix);
122
- const entries = await this._directory.list();
123
- return Promise.all(entries.filter((entry) => entry.startsWith(filename)).map(async (entry) => {
124
- const file = this._directory.getOrCreateFile(entry);
125
- const { size } = await file.stat();
126
- const buffer = await file.read(0, size);
127
- return {
128
- key: this._getKeyFromFilename(entry),
129
- data: (0, import_util2.bufferToArray)(buffer)
130
- };
131
- }));
131
+ const result = [];
132
+ for await (const [key, value] of this._params.db.iterator({
133
+ gte: keyPrefix,
134
+ lte: [
135
+ ...keyPrefix,
136
+ "\uFFFF"
137
+ ],
138
+ ...encodingOptions
139
+ })) {
140
+ result.push({
141
+ key,
142
+ data: value
143
+ });
144
+ }
145
+ return result;
132
146
  }
133
147
  async removeRange(keyPrefix) {
134
- if (this._state !== "opened") {
148
+ if (this._lifecycleState !== import_context2.LifecycleState.OPEN) {
135
149
  return void 0;
136
150
  }
137
- const filename = this._getFilename(keyPrefix);
138
- const entries = await this._directory.list();
139
- await Promise.all(entries.filter((entry) => entry.startsWith(filename)).map(async (entry) => {
140
- const file = this._directory.getOrCreateFile(entry);
141
- await file.destroy();
142
- }));
143
- }
144
- async close() {
145
- this._state = "closed";
146
- }
147
- _getFilename(key) {
148
- return key.map((k) => k.replaceAll("%", "%25").replaceAll("-", "%2D")).join("-");
149
- }
150
- _getKeyFromFilename(filename) {
151
- return filename.split("-").map((k) => k.replaceAll("%2D", "-").replaceAll("%25", "%"));
152
- }
153
- };
154
- var AutomergeStorageWrapper = class {
155
- constructor({ storage, callbacks }) {
156
- this._storage = storage;
157
- this._callbacks = callbacks;
158
- }
159
- async load(key) {
160
- return this._storage.load(key);
161
- }
162
- async save(key, value) {
163
- await this._callbacks.beforeSave?.(key);
164
- await this._storage.save(key, value);
165
- await this._callbacks.afterSave?.(key);
166
- }
167
- async remove(key) {
168
- return this._storage.remove(key);
169
- }
170
- async loadRange(keyPrefix) {
171
- return this._storage.loadRange(keyPrefix);
172
- }
173
- async removeRange(keyPrefix) {
174
- return this._storage.removeRange(keyPrefix);
175
- }
176
- async close() {
177
- if (this._storage instanceof AutomergeStorageAdapter) {
178
- return this._storage.close();
151
+ const batch = this._params.db.batch();
152
+ for await (const [key] of this._params.db.iterator({
153
+ gte: keyPrefix,
154
+ lte: [
155
+ ...keyPrefix,
156
+ "\uFFFF"
157
+ ],
158
+ ...encodingOptions
159
+ })) {
160
+ batch.del(key, {
161
+ ...encodingOptions
162
+ });
179
163
  }
164
+ await batch.write();
180
165
  }
181
166
  };
167
+ var keyEncoder = {
168
+ encode: (key) => Buffer.from(key.map((k) => k.replaceAll("%", "%25").replaceAll("-", "%2D")).join("-")),
169
+ decode: (key) => Buffer.from(key).toString().split("-").map((k) => k.replaceAll("%2D", "-").replaceAll("%25", "%"))
170
+ };
171
+ var encodingOptions = {
172
+ keyEncoding: keyEncoder,
173
+ valueEncoding: "buffer"
174
+ };
175
+ var isLevelDbNotFoundError = (err) => err.code === "LEVEL_NOT_FOUND";
182
176
  var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/local-host-network-adapter.ts";
183
177
  var LocalHostNetworkAdapter = class extends import_automerge_repo2.NetworkAdapter {
184
178
  constructor() {
185
179
  super(...arguments);
186
180
  this._peers = /* @__PURE__ */ new Map();
187
181
  this._connected = new import_async.Trigger();
182
+ this._isConnected = false;
188
183
  }
189
184
  /**
190
185
  * Emits `ready` event. That signals to `Repo` that it can start using the adapter.
@@ -194,15 +189,21 @@ var LocalHostNetworkAdapter = class extends import_automerge_repo2.NetworkAdapte
194
189
  network: this
195
190
  });
196
191
  }
192
+ /**
193
+ * Called by `Repo` to connect to the network.
194
+ *
195
+ * @param peerId Our peer Id.
196
+ */
197
197
  connect(peerId) {
198
198
  this.peerId = peerId;
199
+ this._isConnected = true;
199
200
  this._connected.wake();
200
201
  }
201
202
  send(message) {
202
203
  const peer = this._peers.get(message.targetId);
203
204
  (0, import_invariant.invariant)(peer, "Peer not found.", {
204
205
  F: __dxlog_file,
205
- L: 45,
206
+ L: 51,
206
207
  S: this,
207
208
  A: [
208
209
  "peer",
@@ -217,12 +218,17 @@ var LocalHostNetworkAdapter = class extends import_automerge_repo2.NetworkAdapte
217
218
  }
218
219
  disconnect() {
219
220
  }
221
+ async whenConnected() {
222
+ await this._connected.wait({
223
+ timeout: 1e4
224
+ });
225
+ }
220
226
  syncRepo({ id, syncMessage }) {
221
227
  const peerId = this._getPeerId(id);
222
228
  return new import_codec_protobuf.Stream(({ next, close }) => {
223
229
  (0, import_invariant.invariant)(!this._peers.has(peerId), "Peer already connected.", {
224
230
  F: __dxlog_file,
225
- L: 63,
231
+ L: 73,
226
232
  S: this,
227
233
  A: [
228
234
  "!this._peers.has(peerId)",
@@ -244,35 +250,47 @@ var LocalHostNetworkAdapter = class extends import_automerge_repo2.NetworkAdapte
244
250
  });
245
251
  }
246
252
  });
247
- this._connected.wait({
248
- timeout: 1e3
249
- }).then(() => {
250
- this.emit("peer-candidate", {
251
- peerMetadata: {},
252
- peerId
253
- });
254
- }).catch((err) => import_log2.log.catch(err, void 0, {
253
+ (0, import_invariant.invariant)(this._isConnected, void 0, {
255
254
  F: __dxlog_file,
256
- L: 88,
255
+ L: 90,
257
256
  S: this,
258
- C: (f, a) => f(...a)
259
- }));
257
+ A: [
258
+ "this._isConnected",
259
+ ""
260
+ ]
261
+ });
262
+ this.emit("peer-candidate", {
263
+ peerMetadata: {},
264
+ peerId
265
+ });
260
266
  });
261
267
  }
262
268
  async sendSyncMessage({ id, syncMessage }) {
263
- await this._connected.wait({
264
- timeout: 1e3
269
+ (0, import_invariant.invariant)(this._isConnected, void 0, {
270
+ F: __dxlog_file,
271
+ L: 99,
272
+ S: this,
273
+ A: [
274
+ "this._isConnected",
275
+ ""
276
+ ]
265
277
  });
266
278
  const message = import_automerge_repo2.cbor.decode(syncMessage);
267
279
  this.emit("message", message);
268
280
  }
269
281
  async getHostInfo() {
270
- await this._connected.wait({
271
- timeout: 1e3
282
+ (0, import_invariant.invariant)(this._isConnected, void 0, {
283
+ F: __dxlog_file,
284
+ L: 105,
285
+ S: this,
286
+ A: [
287
+ "this._isConnected",
288
+ ""
289
+ ]
272
290
  });
273
291
  (0, import_invariant.invariant)(this.peerId, "Peer id not set.", {
274
292
  F: __dxlog_file,
275
- L: 100,
293
+ L: 106,
276
294
  S: this,
277
295
  A: [
278
296
  "this.peerId",
@@ -320,7 +338,7 @@ var MeshNetworkAdapter = class extends import_automerge_repo3.NetworkAdapter {
320
338
  });
321
339
  extension.sendSyncMessage({
322
340
  payload: import_automerge_repo3.cbor.encode(message)
323
- }).catch((err) => import_log3.log.catch(err, void 0, {
341
+ }).catch((err) => import_log2.log.catch(err, void 0, {
324
342
  F: __dxlog_file2,
325
343
  L: 39,
326
344
  S: this,
@@ -345,7 +363,7 @@ var MeshNetworkAdapter = class extends import_automerge_repo3.NetworkAdapter {
345
363
  }, {
346
364
  onStartReplication: async (info, remotePeerId) => {
347
365
  await this._connected.wait();
348
- (0, import_log3.log)("onStartReplication", {
366
+ (0, import_log2.log)("onStartReplication", {
349
367
  id: info.id,
350
368
  thisPeerId: this.peerId,
351
369
  remotePeerId: remotePeerId.toHex()
@@ -358,7 +376,7 @@ var MeshNetworkAdapter = class extends import_automerge_repo3.NetworkAdapter {
358
376
  if (!this._extensions.has(info.id)) {
359
377
  peerInfo = info;
360
378
  this._extensions.set(info.id, extension);
361
- (0, import_log3.log)("peer-candidate", {
379
+ (0, import_log2.log)("peer-candidate", {
362
380
  id: info.id,
363
381
  thisPeerId: this.peerId,
364
382
  remotePeerId: remotePeerId.toHex()
@@ -397,6 +415,108 @@ var MeshNetworkAdapter = class extends import_automerge_repo3.NetworkAdapter {
397
415
  return extension;
398
416
  }
399
417
  };
418
+ var AutomergeStorageAdapter = class {
419
+ constructor(_directory) {
420
+ this._directory = _directory;
421
+ this._state = "opened";
422
+ }
423
+ async load(key) {
424
+ if (this._state !== "opened") {
425
+ return void 0;
426
+ }
427
+ const filename = this._getFilename(key);
428
+ const file = this._directory.getOrCreateFile(filename);
429
+ const { size } = await file.stat();
430
+ if (!size || size === 0) {
431
+ return void 0;
432
+ }
433
+ const buffer = await file.read(0, size);
434
+ return (0, import_util2.bufferToArray)(buffer);
435
+ }
436
+ async save(key, data) {
437
+ if (this._state !== "opened") {
438
+ return void 0;
439
+ }
440
+ const filename = this._getFilename(key);
441
+ const file = this._directory.getOrCreateFile(filename);
442
+ await file.write(0, (0, import_util2.arrayToBuffer)(data));
443
+ await file.truncate?.(data.length);
444
+ await file.flush?.();
445
+ }
446
+ async remove(key) {
447
+ if (this._state !== "opened") {
448
+ return void 0;
449
+ }
450
+ const filename = this._getFilename(key);
451
+ const file = this._directory.getOrCreateFile(filename);
452
+ await file.destroy();
453
+ }
454
+ async loadRange(keyPrefix) {
455
+ if (this._state !== "opened") {
456
+ return [];
457
+ }
458
+ const filename = this._getFilename(keyPrefix);
459
+ const entries = await this._directory.list();
460
+ return Promise.all(entries.filter((entry) => entry.startsWith(filename)).map(async (entry) => {
461
+ const file = this._directory.getOrCreateFile(entry);
462
+ const { size } = await file.stat();
463
+ const buffer = await file.read(0, size);
464
+ return {
465
+ key: this._getKeyFromFilename(entry),
466
+ data: (0, import_util2.bufferToArray)(buffer)
467
+ };
468
+ }));
469
+ }
470
+ async removeRange(keyPrefix) {
471
+ if (this._state !== "opened") {
472
+ return void 0;
473
+ }
474
+ const filename = this._getFilename(keyPrefix);
475
+ const entries = await this._directory.list();
476
+ await Promise.all(entries.filter((entry) => entry.startsWith(filename)).map(async (entry) => {
477
+ const file = this._directory.getOrCreateFile(entry);
478
+ await file.destroy();
479
+ }));
480
+ }
481
+ async close() {
482
+ this._state = "closed";
483
+ }
484
+ _getFilename(key) {
485
+ return key.map((k) => k.replaceAll("%", "%25").replaceAll("-", "%2D")).join("-");
486
+ }
487
+ _getKeyFromFilename(filename) {
488
+ return filename.split("-").map((k) => k.replaceAll("%2D", "-").replaceAll("%25", "%"));
489
+ }
490
+ };
491
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/migrations.ts";
492
+ var levelMigration = async ({ db, directory }) => {
493
+ const isNewLevel = !await db.iterator({
494
+ ...encodingOptions
495
+ }).next();
496
+ if (!isNewLevel) {
497
+ return;
498
+ }
499
+ const oldStorageAdapter = directory.type === import_random_access_storage.StorageType.IDB ? new import_automerge_repo_storage_indexeddb.IndexedDBStorageAdapter(directory.path, "data") : new AutomergeStorageAdapter(directory);
500
+ const chunks = await oldStorageAdapter.loadRange([]);
501
+ if (chunks.length === 0) {
502
+ return;
503
+ }
504
+ const batch = db.batch();
505
+ import_log3.log.info("found chunks on old storage adapter", {
506
+ chunks: chunks.length
507
+ }, {
508
+ F: __dxlog_file3,
509
+ L: 36,
510
+ S: void 0,
511
+ C: (f, a) => f(...a)
512
+ });
513
+ for (const { key, data } of await oldStorageAdapter.loadRange([])) {
514
+ data && batch.put(key, data, {
515
+ ...encodingOptions
516
+ });
517
+ }
518
+ await batch.write();
519
+ };
400
520
  function _ts_decorate(decorators, target, key, desc) {
401
521
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
402
522
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -407,26 +527,29 @@ function _ts_decorate(decorators, target, key, desc) {
407
527
  r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
408
528
  return c > 3 && r && Object.defineProperty(target, key, r), r;
409
529
  }
410
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/automerge-host.ts";
530
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/automerge-host.ts";
411
531
  var AutomergeHost = class {
412
- constructor({ directory, metadata }) {
532
+ constructor({ directory, db, storageCallbacks }) {
413
533
  this._ctx = new import_context.Context();
414
534
  this._authorizedDevices = new import_util.ComplexMap(import_keys.PublicKey.hash);
415
- this._updatingMetadata = /* @__PURE__ */ new Map();
416
535
  this._requestedDocs = /* @__PURE__ */ new Set();
417
- this._metadata = metadata;
418
- this._meshNetwork = new MeshNetworkAdapter();
419
- this._clientNetwork = new LocalHostNetworkAdapter();
420
- this._storage = new AutomergeStorageWrapper({
421
- storage: (
422
- // TODO(mykola): Delete specific handling of IDB storage.
423
- directory.type === import_random_access_storage.StorageType.IDB ? new import_automerge_repo_storage_indexeddb.IndexedDBStorageAdapter(directory.path, "data") : new AutomergeStorageAdapter(directory)
424
- ),
425
- callbacks: {
426
- beforeSave: (params) => this._beforeSave(params)
427
- }
536
+ this._directory = directory;
537
+ this._db = db;
538
+ this._storageCallbacks = storageCallbacks;
539
+ }
540
+ async open() {
541
+ this._directory && await levelMigration({
542
+ db: this._db,
543
+ directory: this._directory
428
544
  });
545
+ this._storage = new LevelDBStorageAdapter({
546
+ db: this._db,
547
+ callbacks: this._storageCallbacks
548
+ });
549
+ await this._storage.open?.();
429
550
  this._peerId = `host-${import_keys.PublicKey.random().toHex()}`;
551
+ this._meshNetwork = new MeshNetworkAdapter();
552
+ this._clientNetwork = new LocalHostNetworkAdapter();
430
553
  this._repo = new import_automerge_repo.Repo({
431
554
  peerId: this._peerId,
432
555
  network: [
@@ -451,8 +574,8 @@ var AutomergeHost = class {
451
574
  documentId,
452
575
  isRequested
453
576
  }, {
454
- F: __dxlog_file3,
455
- L: 101,
577
+ F: __dxlog_file4,
578
+ L: 98,
456
579
  S: this,
457
580
  C: (f, a) => f(...a)
458
581
  });
@@ -465,8 +588,8 @@ var AutomergeHost = class {
465
588
  peerId,
466
589
  documentId
467
590
  }, {
468
- F: __dxlog_file3,
469
- L: 108,
591
+ F: __dxlog_file4,
592
+ L: 105,
470
593
  S: this,
471
594
  C: (f, a) => f(...a)
472
595
  });
@@ -479,8 +602,8 @@ var AutomergeHost = class {
479
602
  peerId,
480
603
  documentId
481
604
  }, {
482
- F: __dxlog_file3,
483
- L: 117,
605
+ F: __dxlog_file4,
606
+ L: 114,
484
607
  S: this,
485
608
  C: (f, a) => f(...a)
486
609
  });
@@ -496,16 +619,16 @@ var AutomergeHost = class {
496
619
  spaceKey,
497
620
  isAuthorized
498
621
  }, {
499
- F: __dxlog_file3,
500
- L: 123,
622
+ F: __dxlog_file4,
623
+ L: 120,
501
624
  S: this,
502
625
  C: (f, a) => f(...a)
503
626
  });
504
627
  return isAuthorized;
505
628
  } catch (err) {
506
629
  import_log.log.catch(err, void 0, {
507
- F: __dxlog_file3,
508
- L: 133,
630
+ F: __dxlog_file4,
631
+ L: 130,
509
632
  S: this,
510
633
  C: (f, a) => f(...a)
511
634
  });
@@ -515,61 +638,16 @@ var AutomergeHost = class {
515
638
  });
516
639
  this._clientNetwork.ready();
517
640
  this._meshNetwork.ready();
518
- {
519
- const listener = ({ handle }) => this._onDocument(handle);
520
- this._repo.on("document", listener);
521
- this._ctx.onDispose(() => {
522
- this._repo.off("document", listener);
523
- Object.values(this._repo.handles).forEach((handle) => handle.off("change"));
524
- });
525
- }
641
+ await this._clientNetwork.whenConnected();
642
+ }
643
+ async close() {
644
+ await this._storage.close?.();
645
+ await this._clientNetwork.close();
646
+ await this._ctx.dispose();
526
647
  }
527
648
  get repo() {
528
649
  return this._repo;
529
650
  }
530
- async _beforeSave(path) {
531
- const id = path[0];
532
- if (this._updatingMetadata.has(id)) {
533
- return this._updatingMetadata.get(id);
534
- }
535
- }
536
- _onDocument(handle) {
537
- const listener = (event) => this._onUpdate(event);
538
- handle.on("change", listener);
539
- }
540
- _onUpdate(event) {
541
- if (this._metadata == null) {
542
- return;
543
- }
544
- const objectIds = getInlineChanges(event);
545
- if (objectIds.length === 0) {
546
- return;
547
- }
548
- const heads = (0, import_automerge.getHeads)(event.doc);
549
- const lastAvailableHash = heads.join("");
550
- if (!lastAvailableHash) {
551
- return;
552
- }
553
- const encodedIds = objectIds.map((objectId) => import_protocols.idCodec.encode({
554
- documentId: event.handle.documentId,
555
- objectId
556
- }));
557
- const idToLastHash = new Map(encodedIds.map((id) => [
558
- id,
559
- lastAvailableHash
560
- ]));
561
- const markingDirtyPromise = this._metadata.markDirty(idToLastHash).then(() => {
562
- this._updatingMetadata.delete(event.handle.documentId);
563
- }).catch((err) => {
564
- this._ctx.disposed && import_log.log.catch(err, void 0, {
565
- F: __dxlog_file3,
566
- L: 191,
567
- S: this,
568
- C: (f, a) => f(...a)
569
- });
570
- });
571
- this._updatingMetadata.set(event.handle.documentId, markingDirtyPromise);
572
- }
573
651
  _automergeDocs() {
574
652
  return (0, import_util.mapValues)(this._repo.handles, (handle) => ({
575
653
  state: handle.state,
@@ -595,11 +673,6 @@ var AutomergeHost = class {
595
673
  _automergePeers() {
596
674
  return this._repo.peers;
597
675
  }
598
- async close() {
599
- await this._storage.close();
600
- await this._clientNetwork.close();
601
- await this._ctx.dispose();
602
- }
603
676
  //
604
677
  // Methods for client-services.
605
678
  //
@@ -627,8 +700,8 @@ var AutomergeHost = class {
627
700
  spaceKey,
628
701
  deviceKey
629
702
  }, {
630
- F: __dxlog_file3,
631
- L: 264,
703
+ F: __dxlog_file4,
704
+ L: 213,
632
705
  S: this,
633
706
  C: (f, a) => f(...a)
634
707
  });
@@ -651,24 +724,6 @@ _ts_decorate([
651
724
  AutomergeHost = _ts_decorate([
652
725
  import_tracing.trace.resource()
653
726
  ], AutomergeHost);
654
- var getInlineChanges = (event) => {
655
- const inlineChangedObjectIds = /* @__PURE__ */ new Set();
656
- for (const { path } of event.patches) {
657
- if (path.length < 2) {
658
- continue;
659
- }
660
- switch (path[0]) {
661
- case "objects":
662
- if (path.length >= 2) {
663
- inlineChangedObjectIds.add(path[1]);
664
- }
665
- break;
666
- }
667
- }
668
- return [
669
- ...inlineChangedObjectIds
670
- ];
671
- };
672
727
  var getSpaceKeyFromDoc = (doc) => {
673
728
  const rawSpaceKey = doc.access?.spaceKey ?? doc.experimental_spaceKey;
674
729
  if (rawSpaceKey == null) {
@@ -676,7 +731,7 @@ var getSpaceKeyFromDoc = (doc) => {
676
731
  }
677
732
  return String(rawSpaceKey);
678
733
  };
679
- var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/automerge-doc-loader.ts";
734
+ var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/automerge-doc-loader.ts";
680
735
  var AutomergeDocumentLoaderImpl = class {
681
736
  constructor(_spaceKey, _repo) {
682
737
  this._spaceKey = _spaceKey;
@@ -699,7 +754,7 @@ var AutomergeDocumentLoaderImpl = class {
699
754
  import_log4.log.error("Database opened with no rootUrl", {
700
755
  spaceKey: this._spaceKey
701
756
  }, {
702
- F: __dxlog_file4,
757
+ F: __dxlog_file5,
703
758
  L: 66,
704
759
  S: this,
705
760
  C: (f, a) => f(...a)
@@ -709,7 +764,7 @@ var AutomergeDocumentLoaderImpl = class {
709
764
  const existingDocHandle = await this._initDocHandle(ctx, spaceState.rootUrl);
710
765
  const doc = existingDocHandle.docSync();
711
766
  (0, import_invariant3.invariant)(doc, void 0, {
712
- F: __dxlog_file4,
767
+ F: __dxlog_file5,
713
768
  L: 71,
714
769
  S: this,
715
770
  A: [
@@ -725,7 +780,7 @@ var AutomergeDocumentLoaderImpl = class {
725
780
  }
726
781
  loadObjectDocument(objectId) {
727
782
  (0, import_invariant3.invariant)(this._spaceRootDocHandle, void 0, {
728
- F: __dxlog_file4,
783
+ F: __dxlog_file5,
729
784
  L: 80,
730
785
  S: this,
731
786
  A: [
@@ -738,7 +793,7 @@ var AutomergeDocumentLoaderImpl = class {
738
793
  }
739
794
  const spaceRootDoc = this._spaceRootDocHandle.docSync();
740
795
  (0, import_invariant3.invariant)(spaceRootDoc, void 0, {
741
- F: __dxlog_file4,
796
+ F: __dxlog_file5,
742
797
  L: 85,
743
798
  S: this,
744
799
  A: [
@@ -752,7 +807,7 @@ var AutomergeDocumentLoaderImpl = class {
752
807
  import_log4.log.info("loading delayed until object links are initialized", {
753
808
  objectId
754
809
  }, {
755
- F: __dxlog_file4,
810
+ F: __dxlog_file5,
756
811
  L: 89,
757
812
  S: this,
758
813
  C: (f, a) => f(...a)
@@ -773,7 +828,7 @@ var AutomergeDocumentLoaderImpl = class {
773
828
  }
774
829
  getSpaceRootDocHandle() {
775
830
  (0, import_invariant3.invariant)(this._spaceRootDocHandle, void 0, {
776
- F: __dxlog_file4,
831
+ F: __dxlog_file5,
777
832
  L: 107,
778
833
  S: this,
779
834
  A: [
@@ -785,7 +840,7 @@ var AutomergeDocumentLoaderImpl = class {
785
840
  }
786
841
  createDocumentForObject(objectId) {
787
842
  (0, import_invariant3.invariant)(this._spaceRootDocHandle, void 0, {
788
- F: __dxlog_file4,
843
+ F: __dxlog_file5,
789
844
  L: 112,
790
845
  S: this,
791
846
  A: [
@@ -828,7 +883,7 @@ var AutomergeDocumentLoaderImpl = class {
828
883
  ...logMeta,
829
884
  actualDocumentUrl: objectDocumentHandle.url
830
885
  }, {
831
- F: __dxlog_file4,
886
+ F: __dxlog_file5,
832
887
  L: 142,
833
888
  S: this,
834
889
  C: (f, a) => f(...a)
@@ -837,7 +892,7 @@ var AutomergeDocumentLoaderImpl = class {
837
892
  }
838
893
  if (objectDocumentHandle?.url === automergeUrl) {
839
894
  import_log4.log.warn("object document was already loaded", logMeta, {
840
- F: __dxlog_file4,
895
+ F: __dxlog_file5,
841
896
  L: 149,
842
897
  S: this,
843
898
  C: (f, a) => f(...a)
@@ -846,7 +901,7 @@ var AutomergeDocumentLoaderImpl = class {
846
901
  }
847
902
  const handle = this._repo.find(automergeUrl);
848
903
  import_log4.log.debug("document loading triggered", logMeta, {
849
- F: __dxlog_file4,
904
+ F: __dxlog_file5,
850
905
  L: 153,
851
906
  S: this,
852
907
  C: (f, a) => f(...a)
@@ -860,7 +915,7 @@ var AutomergeDocumentLoaderImpl = class {
860
915
  while (true) {
861
916
  try {
862
917
  await (0, import_debug.warnAfterTimeout)(5e3, "Automerge root doc load timeout (AutomergeDb)", async () => {
863
- await (0, import_context2.cancelWithContext)(ctx, docHandle.whenReady());
918
+ await (0, import_context3.cancelWithContext)(ctx, docHandle.whenReady());
864
919
  });
865
920
  break;
866
921
  } catch (err) {
@@ -869,7 +924,7 @@ var AutomergeDocumentLoaderImpl = class {
869
924
  id: docHandle.documentId,
870
925
  state: docHandle.state
871
926
  }, {
872
- F: __dxlog_file4,
927
+ F: __dxlog_file5,
873
928
  L: 169,
874
929
  S: this,
875
930
  C: (f, a) => f(...a)
@@ -911,7 +966,7 @@ var AutomergeDocumentLoaderImpl = class {
911
966
  };
912
967
  if (this.onObjectDocumentLoaded.listenerCount() === 0) {
913
968
  import_log4.log.info("document loaded after all listeners were removed", logMeta, {
914
- F: __dxlog_file4,
969
+ F: __dxlog_file5,
915
970
  L: 205,
916
971
  S: this,
917
972
  C: (f, a) => f(...a)
@@ -921,7 +976,7 @@ var AutomergeDocumentLoaderImpl = class {
921
976
  const objectDocHandle = this._objectDocumentHandles.get(objectId);
922
977
  if (objectDocHandle?.url !== handle.url) {
923
978
  import_log4.log.warn("object was rebound while a document was loading, discarding handle", logMeta, {
924
- F: __dxlog_file4,
979
+ F: __dxlog_file5,
925
980
  L: 210,
926
981
  S: this,
927
982
  C: (f, a) => f(...a)
@@ -940,7 +995,7 @@ var AutomergeDocumentLoaderImpl = class {
940
995
  retryLoading: shouldRetryLoading,
941
996
  err
942
997
  }, {
943
- F: __dxlog_file4,
998
+ F: __dxlog_file5,
944
999
  L: 216,
945
1000
  S: this,
946
1001
  C: (f, a) => f(...a)
@@ -969,6 +1024,7 @@ var isEncodedReferenceObject = (value) => typeof value === "object" && value !==
969
1024
  AutomergeHost,
970
1025
  AutomergeStorageAdapter,
971
1026
  DataServiceImpl,
1027
+ LevelDBStorageAdapter,
972
1028
  LocalHostNetworkAdapter,
973
1029
  MOCK_AUTH_PROVIDER,
974
1030
  MOCK_AUTH_VERIFIER,
@@ -987,7 +1043,9 @@ var isEncodedReferenceObject = (value) => typeof value === "object" && value !==
987
1043
  createMappedFeedWriter,
988
1044
  decodeReference,
989
1045
  encodeReference,
1046
+ encodingOptions,
990
1047
  getSpaceKeyFromDoc,
1048
+ hasInvitationExpired,
991
1049
  isEncodedReferenceObject,
992
1050
  mapFeedIndexesToTimeframe,
993
1051
  mapTimeframeToFeedIndexes,