@dxos/echo-pipeline 0.8.4-main.fd6878d → 0.8.4-main.fffef41

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 (87) hide show
  1. package/dist/lib/browser/{chunk-2543T5DX.mjs → chunk-FR6GJ4S4.mjs} +50 -52
  2. package/dist/lib/browser/chunk-FR6GJ4S4.mjs.map +7 -0
  3. package/dist/lib/browser/chunk-WJJXJTNS.mjs +240 -0
  4. package/dist/lib/browser/chunk-WJJXJTNS.mjs.map +7 -0
  5. package/dist/lib/browser/filter/index.mjs +3 -1
  6. package/dist/lib/browser/index.mjs +828 -250
  7. package/dist/lib/browser/index.mjs.map +3 -3
  8. package/dist/lib/browser/meta.json +1 -1
  9. package/dist/lib/browser/testing/index.mjs +14 -17
  10. package/dist/lib/browser/testing/index.mjs.map +3 -3
  11. package/dist/lib/node-esm/{chunk-UQI6R3TD.mjs → chunk-JQCCVDLT.mjs} +50 -52
  12. package/dist/lib/node-esm/chunk-JQCCVDLT.mjs.map +7 -0
  13. package/dist/lib/node-esm/chunk-LEQ77KAT.mjs +240 -0
  14. package/dist/lib/node-esm/chunk-LEQ77KAT.mjs.map +7 -0
  15. package/dist/lib/node-esm/filter/index.mjs +3 -1
  16. package/dist/lib/node-esm/index.mjs +828 -250
  17. package/dist/lib/node-esm/index.mjs.map +3 -3
  18. package/dist/lib/node-esm/meta.json +1 -1
  19. package/dist/lib/node-esm/testing/index.mjs +14 -17
  20. package/dist/lib/node-esm/testing/index.mjs.map +3 -3
  21. package/dist/types/src/automerge/automerge-host.d.ts +14 -27
  22. package/dist/types/src/automerge/automerge-host.d.ts.map +1 -1
  23. package/dist/types/src/automerge/collection-synchronizer.d.ts +2 -1
  24. package/dist/types/src/automerge/collection-synchronizer.d.ts.map +1 -1
  25. package/dist/types/src/automerge/echo-network-adapter.d.ts +8 -1
  26. package/dist/types/src/automerge/echo-network-adapter.d.ts.map +1 -1
  27. package/dist/types/src/automerge/echo-replicator.d.ts +20 -1
  28. package/dist/types/src/automerge/echo-replicator.d.ts.map +1 -1
  29. package/dist/types/src/automerge/leveldb-storage-adapter.d.ts.map +1 -1
  30. package/dist/types/src/automerge/mesh-echo-replicator-connection.d.ts +1 -0
  31. package/dist/types/src/automerge/mesh-echo-replicator-connection.d.ts.map +1 -1
  32. package/dist/types/src/common/codec.d.ts +1 -1
  33. package/dist/types/src/common/codec.d.ts.map +1 -1
  34. package/dist/types/src/db-host/data-service.d.ts.map +1 -1
  35. package/dist/types/src/db-host/echo-host.d.ts.map +1 -1
  36. package/dist/types/src/db-host/query-service.d.ts.map +1 -1
  37. package/dist/types/src/edge/echo-edge-replicator.d.ts +4 -2
  38. package/dist/types/src/edge/echo-edge-replicator.d.ts.map +1 -1
  39. package/dist/types/src/filter/filter-match.d.ts +4 -1
  40. package/dist/types/src/filter/filter-match.d.ts.map +1 -1
  41. package/dist/types/src/query/errors.d.ts +14 -13
  42. package/dist/types/src/query/errors.d.ts.map +1 -1
  43. package/dist/types/src/query/plan.d.ts +8 -1
  44. package/dist/types/src/query/plan.d.ts.map +1 -1
  45. package/dist/types/src/query/query-executor.d.ts +12 -0
  46. package/dist/types/src/query/query-executor.d.ts.map +1 -1
  47. package/dist/types/src/query/query-planner.d.ts +2 -0
  48. package/dist/types/src/query/query-planner.d.ts.map +1 -1
  49. package/dist/types/src/space/control-pipeline.d.ts.map +1 -1
  50. package/dist/types/src/testing/test-data.d.ts.map +1 -1
  51. package/dist/types/src/testing/test-replicator.d.ts +1 -0
  52. package/dist/types/src/testing/test-replicator.d.ts.map +1 -1
  53. package/dist/types/src/testing/test-schema.d.ts +1 -1
  54. package/dist/types/src/testing/test-schema.d.ts.map +1 -1
  55. package/dist/types/tsconfig.tsbuildinfo +1 -1
  56. package/package.json +37 -38
  57. package/src/automerge/automerge-host.test.ts +15 -6
  58. package/src/automerge/automerge-host.ts +253 -64
  59. package/src/automerge/automerge-repo.test.ts +57 -0
  60. package/src/automerge/collection-synchronizer.test.ts +4 -3
  61. package/src/automerge/collection-synchronizer.ts +14 -9
  62. package/src/automerge/echo-network-adapter.ts +32 -1
  63. package/src/automerge/echo-replicator.ts +21 -1
  64. package/src/automerge/leveldb-storage-adapter.ts +6 -6
  65. package/src/automerge/mesh-echo-replicator-connection.ts +4 -0
  66. package/src/db-host/data-service.ts +1 -10
  67. package/src/db-host/echo-host.ts +1 -3
  68. package/src/db-host/query-service.ts +2 -1
  69. package/src/edge/echo-edge-replicator.test.ts +3 -2
  70. package/src/edge/echo-edge-replicator.ts +70 -13
  71. package/src/filter/filter-match.test.ts +32 -12
  72. package/src/filter/filter-match.ts +164 -10
  73. package/src/query/errors.ts +2 -0
  74. package/src/query/plan.ts +12 -1
  75. package/src/query/query-executor.ts +148 -8
  76. package/src/query/query-planner.test.ts +234 -6
  77. package/src/query/query-planner.ts +87 -12
  78. package/src/space/control-pipeline.ts +5 -2
  79. package/src/testing/test-data.ts +1 -1
  80. package/src/testing/test-replicator.ts +4 -0
  81. package/src/testing/test-schema.ts +1 -1
  82. package/dist/lib/browser/chunk-2543T5DX.mjs.map +0 -7
  83. package/dist/lib/browser/chunk-VUXUDIPM.mjs +0 -126
  84. package/dist/lib/browser/chunk-VUXUDIPM.mjs.map +0 -7
  85. package/dist/lib/node-esm/chunk-PGZYXNYE.mjs +0 -126
  86. package/dist/lib/node-esm/chunk-PGZYXNYE.mjs.map +0 -7
  87. package/dist/lib/node-esm/chunk-UQI6R3TD.mjs.map +0 -7
@@ -1,8 +1,9 @@
1
1
  import "@dxos/node-std/globals";
2
2
  import {
3
3
  filterMatchObject,
4
+ filterMatchObjectJSON,
4
5
  filterMatchValue
5
- } from "./chunk-VUXUDIPM.mjs";
6
+ } from "./chunk-WJJXJTNS.mjs";
6
7
  import {
7
8
  AuthExtension,
8
9
  AuthStatus,
@@ -25,7 +26,7 @@ import {
25
26
  mapTimeframeToFeedIndexes,
26
27
  startAfter,
27
28
  valueEncoding
28
- } from "./chunk-2543T5DX.mjs";
29
+ } from "./chunk-FR6GJ4S4.mjs";
29
30
  import "./chunk-CGS2ULMK.mjs";
30
31
 
31
32
  // src/db-host/data-service.ts
@@ -38,7 +39,7 @@ import { log as log7 } from "@dxos/log";
38
39
  // src/automerge/automerge-host.ts
39
40
  import { getBackend, getHeads, equals as headsEquals, isAutomerge, save } from "@automerge/automerge";
40
41
  import { Repo, interpretAsDocumentId } from "@automerge/automerge-repo";
41
- import { Event as Event2, asyncTimeout } from "@dxos/async";
42
+ import { DeferredTask, Event as Event2, asyncTimeout } from "@dxos/async";
42
43
  import { Context, Resource as Resource3, cancelWithContext } from "@dxos/context";
43
44
  import { DatabaseDirectory } from "@dxos/echo-protocol";
44
45
  import { invariant as invariant2 } from "@dxos/invariant";
@@ -46,10 +47,12 @@ import { PublicKey } from "@dxos/keys";
46
47
  import { log as log3 } from "@dxos/log";
47
48
  import { objectPointerCodec } from "@dxos/protocols";
48
49
  import { trace as trace2 } from "@dxos/tracing";
49
- import { bufferToArray } from "@dxos/util";
50
+ import { ComplexSet, bufferToArray, isNonNullable as isNonNullable2, range } from "@dxos/util";
50
51
 
51
52
  // src/automerge/collection-synchronizer.ts
52
- import { next as am } from "@automerge/automerge";
53
+ import { next as A } from "@automerge/automerge";
54
+ import * as Array2 from "effect/Array";
55
+ import * as Record from "effect/Record";
53
56
  import { Event, asyncReturn, scheduleTask, scheduleTaskInterval } from "@dxos/async";
54
57
  import { Resource } from "@dxos/context";
55
58
  import { log } from "@dxos/log";
@@ -106,7 +109,7 @@ var CollectionSynchronizer = class extends Resource {
106
109
  state
107
110
  }, {
108
111
  F: __dxlog_file,
109
- L: 76,
112
+ L: 78,
110
113
  S: this,
111
114
  C: (f, a) => f(...a)
112
115
  });
@@ -125,7 +128,7 @@ var CollectionSynchronizer = class extends Resource {
125
128
  collectionId
126
129
  }, {
127
130
  F: __dxlog_file,
128
- L: 90,
131
+ L: 92,
129
132
  S: this,
130
133
  C: (f, a) => f(...a)
131
134
  });
@@ -208,7 +211,7 @@ var CollectionSynchronizer = class extends Resource {
208
211
  state
209
212
  }, {
210
213
  F: __dxlog_file,
211
- L: 171,
214
+ L: 173,
212
215
  S: this,
213
216
  C: (f, a) => f(...a)
214
217
  });
@@ -264,19 +267,23 @@ CollectionSynchronizer = _ts_decorate([
264
267
  trace.resource()
265
268
  ], CollectionSynchronizer);
266
269
  var diffCollectionState = (local, remote) => {
267
- const allDocuments = /* @__PURE__ */ new Set([
268
- ...Object.keys(local.documents),
269
- ...Object.keys(remote.documents)
270
- ]);
270
+ const localDocuments = Record.filter(local.documents, (heads) => heads.length > 0);
271
+ const remoteDocuments = Record.filter(remote.documents, (heads) => heads.length > 0);
272
+ const allDocuments = [
273
+ .../* @__PURE__ */ new Set([
274
+ ...Record.keys(localDocuments),
275
+ ...Record.keys(remoteDocuments)
276
+ ])
277
+ ];
271
278
  const missingOnRemote = [];
272
279
  const missingOnLocal = [];
273
280
  const different = [];
274
281
  for (const documentId of allDocuments) {
275
- if (!local.documents[documentId]) {
282
+ if (!localDocuments[documentId]) {
276
283
  missingOnLocal.push(documentId);
277
- } else if (!remote.documents[documentId]) {
284
+ } else if (!remoteDocuments[documentId]) {
278
285
  missingOnRemote.push(documentId);
279
- } else if (!am.equals(local.documents[documentId], remote.documents[documentId])) {
286
+ } else if (!A.equals(local.documents[documentId], remote.documents[documentId])) {
280
287
  different.push(documentId);
281
288
  }
282
289
  }
@@ -291,7 +298,7 @@ var validateCollectionState = (state) => {
291
298
  if (!isValidDocumentId(documentId)) {
292
299
  throw new Error(`Invalid documentId: ${documentId}`);
293
300
  }
294
- if (Array.isArray(heads) && heads.some((head) => typeof head !== "string")) {
301
+ if (Array2.isArray(heads) && heads.some((head) => typeof head !== "string")) {
295
302
  throw new Error(`Invalid heads: ${heads}`);
296
303
  }
297
304
  });
@@ -326,16 +333,16 @@ function _ts_decorate2(decorators, target, key, desc) {
326
333
  var __dxlog_file2 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/echo-network-adapter.ts";
327
334
  var EchoNetworkAdapter = class extends NetworkAdapter {
328
335
  _params;
329
- _replicators;
336
+ _replicators = /* @__PURE__ */ new Set();
330
337
  /**
331
338
  * Remote peer id -> connection.
332
339
  */
333
- _connections;
334
- _lifecycleState;
335
- _connected;
336
- _ready;
340
+ _connections = /* @__PURE__ */ new Map();
341
+ _lifecycleState = LifecycleState.CLOSED;
342
+ _connected = new Trigger();
343
+ _ready = new Trigger();
337
344
  constructor(_params) {
338
- super(), this._params = _params, this._replicators = /* @__PURE__ */ new Set(), this._connections = /* @__PURE__ */ new Map(), this._lifecycleState = LifecycleState.CLOSED, this._connected = new Trigger(), this._ready = new Trigger();
345
+ super(), this._params = _params;
339
346
  }
340
347
  isReady() {
341
348
  return this._lifecycleState === LifecycleState.OPEN;
@@ -385,7 +392,7 @@ var EchoNetworkAdapter = class extends NetworkAdapter {
385
392
  async addReplicator(replicator) {
386
393
  invariant(this._lifecycleState === LifecycleState.OPEN, void 0, {
387
394
  F: __dxlog_file2,
388
- L: 130,
395
+ L: 137,
389
396
  S: this,
390
397
  A: [
391
398
  "this._lifecycleState === LifecycleState.OPEN",
@@ -394,7 +401,7 @@ var EchoNetworkAdapter = class extends NetworkAdapter {
394
401
  });
395
402
  invariant(this.peerId, void 0, {
396
403
  F: __dxlog_file2,
397
- L: 131,
404
+ L: 138,
398
405
  S: this,
399
406
  A: [
400
407
  "this.peerId",
@@ -403,7 +410,7 @@ var EchoNetworkAdapter = class extends NetworkAdapter {
403
410
  });
404
411
  invariant(!this._replicators.has(replicator), void 0, {
405
412
  F: __dxlog_file2,
406
- L: 132,
413
+ L: 139,
407
414
  S: this,
408
415
  A: [
409
416
  "!this._replicators.has(replicator)",
@@ -427,7 +434,7 @@ var EchoNetworkAdapter = class extends NetworkAdapter {
427
434
  async removeReplicator(replicator) {
428
435
  invariant(this._lifecycleState === LifecycleState.OPEN, void 0, {
429
436
  F: __dxlog_file2,
430
- L: 151,
437
+ L: 158,
431
438
  S: this,
432
439
  A: [
433
440
  "this._lifecycleState === LifecycleState.OPEN",
@@ -436,7 +443,7 @@ var EchoNetworkAdapter = class extends NetworkAdapter {
436
443
  });
437
444
  invariant(this._replicators.has(replicator), void 0, {
438
445
  F: __dxlog_file2,
439
- L: 152,
446
+ L: 159,
440
447
  S: this,
441
448
  A: [
442
449
  "this._replicators.has(replicator)",
@@ -487,6 +494,27 @@ var EchoNetworkAdapter = class extends NetworkAdapter {
487
494
  }) ? connection.connection.peerId : null;
488
495
  }).filter(isNonNullable);
489
496
  }
497
+ bundleSyncEnabledForPeer(peerId) {
498
+ const connection = this._connections.get(peerId);
499
+ if (!connection) {
500
+ return false;
501
+ }
502
+ return connection.connection.bundleSyncEnabled;
503
+ }
504
+ async pushBundle(peerId, bundle) {
505
+ const connection = this._connections.get(peerId);
506
+ if (!connection) {
507
+ throw new Error("Connection not found.");
508
+ }
509
+ return connection.connection.pushBundle(bundle);
510
+ }
511
+ async pullBundle(peerId, docHeads) {
512
+ const connection = this._connections.get(peerId);
513
+ if (!connection) {
514
+ throw new Error("Connection not found.");
515
+ }
516
+ return connection.connection.pullBundle(docHeads);
517
+ }
490
518
  _send(message) {
491
519
  const connectionEntry = this._connections.get(message.targetId);
492
520
  if (!connectionEntry) {
@@ -499,7 +527,7 @@ var EchoNetworkAdapter = class extends NetworkAdapter {
499
527
  if (connectionEntry.isOpen) {
500
528
  log2.catch(err, void 0, {
501
529
  F: __dxlog_file2,
502
- L: 222,
530
+ L: 253,
503
531
  S: this,
504
532
  C: (f, a) => f(...a)
505
533
  });
@@ -512,13 +540,13 @@ var EchoNetworkAdapter = class extends NetworkAdapter {
512
540
  peerId: connection.peerId
513
541
  }, {
514
542
  F: __dxlog_file2,
515
- L: 230,
543
+ L: 261,
516
544
  S: this,
517
545
  C: (f, a) => f(...a)
518
546
  });
519
547
  invariant(!this._connections.has(connection.peerId), void 0, {
520
548
  F: __dxlog_file2,
521
- L: 231,
549
+ L: 262,
522
550
  S: this,
523
551
  A: [
524
552
  "!this._connections.has(connection.peerId as PeerId)",
@@ -545,7 +573,7 @@ var EchoNetworkAdapter = class extends NetworkAdapter {
545
573
  if (connectionEntry.isOpen) {
546
574
  log2.catch(err, void 0, {
547
575
  F: __dxlog_file2,
548
- L: 255,
576
+ L: 286,
549
577
  S: this,
550
578
  C: (f, a) => f(...a)
551
579
  });
@@ -556,7 +584,7 @@ var EchoNetworkAdapter = class extends NetworkAdapter {
556
584
  peerId: connection.peerId
557
585
  }, {
558
586
  F: __dxlog_file2,
559
- L: 260,
587
+ L: 291,
560
588
  S: this,
561
589
  C: (f, a) => f(...a)
562
590
  });
@@ -578,14 +606,14 @@ var EchoNetworkAdapter = class extends NetworkAdapter {
578
606
  peerId: connection.peerId
579
607
  }, {
580
608
  F: __dxlog_file2,
581
- L: 277,
609
+ L: 308,
582
610
  S: this,
583
611
  C: (f, a) => f(...a)
584
612
  });
585
613
  const entry = this._connections.get(connection.peerId);
586
614
  invariant(entry, void 0, {
587
615
  F: __dxlog_file2,
588
- L: 279,
616
+ L: 310,
589
617
  S: this,
590
618
  A: [
591
619
  "entry",
@@ -599,13 +627,13 @@ var EchoNetworkAdapter = class extends NetworkAdapter {
599
627
  this._params.monitor?.recordPeerDisconnected(connection.peerId);
600
628
  void entry.writer.abort().catch((err) => log2.catch(err, void 0, {
601
629
  F: __dxlog_file2,
602
- L: 285,
630
+ L: 316,
603
631
  S: this,
604
632
  C: (f, a) => f(...a)
605
633
  }));
606
634
  void entry.reader.cancel().catch((err) => log2.catch(err, void 0, {
607
635
  F: __dxlog_file2,
608
- L: 286,
636
+ L: 317,
609
637
  S: this,
610
638
  C: (f, a) => f(...a)
611
639
  }));
@@ -620,14 +648,14 @@ var EchoNetworkAdapter = class extends NetworkAdapter {
620
648
  peerId: connection.peerId
621
649
  }, {
622
650
  F: __dxlog_file2,
623
- L: 296,
651
+ L: 327,
624
652
  S: this,
625
653
  C: (f, a) => f(...a)
626
654
  });
627
655
  const entry = this._connections.get(connection.peerId);
628
656
  invariant(entry, void 0, {
629
657
  F: __dxlog_file2,
630
- L: 298,
658
+ L: 329,
631
659
  S: this,
632
660
  A: [
633
661
  "entry",
@@ -688,7 +716,7 @@ var HeadsStore = class {
688
716
  };
689
717
 
690
718
  // src/automerge/leveldb-storage-adapter.ts
691
- import { LifecycleState as LifecycleState2, Resource as Resource2 } from "@dxos/context";
719
+ import { Resource as Resource2 } from "@dxos/context";
692
720
  var LevelDBStorageAdapter = class extends Resource2 {
693
721
  _params;
694
722
  constructor(_params) {
@@ -696,7 +724,7 @@ var LevelDBStorageAdapter = class extends Resource2 {
696
724
  }
697
725
  async load(keyArray) {
698
726
  try {
699
- if (this._lifecycleState !== LifecycleState2.OPEN) {
727
+ if (!this.isOpen) {
700
728
  return void 0;
701
729
  }
702
730
  const startMs = Date.now();
@@ -714,7 +742,7 @@ var LevelDBStorageAdapter = class extends Resource2 {
714
742
  }
715
743
  }
716
744
  async save(keyArray, binary) {
717
- if (this._lifecycleState !== LifecycleState2.OPEN) {
745
+ if (!this.isOpen) {
718
746
  return void 0;
719
747
  }
720
748
  const startMs = Date.now();
@@ -732,7 +760,7 @@ var LevelDBStorageAdapter = class extends Resource2 {
732
760
  this._params.monitor?.recordStoreDuration(Date.now() - startMs);
733
761
  }
734
762
  async remove(keyArray) {
735
- if (this._lifecycleState !== LifecycleState2.OPEN) {
763
+ if (!this.isOpen) {
736
764
  return void 0;
737
765
  }
738
766
  await this._params.db.del(keyArray, {
@@ -740,7 +768,7 @@ var LevelDBStorageAdapter = class extends Resource2 {
740
768
  });
741
769
  }
742
770
  async loadRange(keyPrefix) {
743
- if (this._lifecycleState !== LifecycleState2.OPEN) {
771
+ if (!this.isOpen) {
744
772
  return [];
745
773
  }
746
774
  const startMs = Date.now();
@@ -763,7 +791,7 @@ var LevelDBStorageAdapter = class extends Resource2 {
763
791
  return result;
764
792
  }
765
793
  async removeRange(keyPrefix) {
766
- if (this._lifecycleState !== LifecycleState2.OPEN) {
794
+ if (!this.isOpen) {
767
795
  return void 0;
768
796
  }
769
797
  const batch = this._params.db.batch();
@@ -807,6 +835,9 @@ var FIND_PARAMS = {
807
835
  "requesting"
808
836
  ]
809
837
  };
838
+ var BUNDLE_SIZE = 100;
839
+ var BUNDLE_SYNC_CONCURRENCY = 2;
840
+ var BUNDLE_SYNC_THRESHOLD = 50;
810
841
  var AutomergeHost = class extends Resource3 {
811
842
  _db;
812
843
  _indexMetadataStore;
@@ -819,6 +850,11 @@ var AutomergeHost = class extends Resource3 {
819
850
  _repo;
820
851
  _storage;
821
852
  _headsStore;
853
+ _syncTask = void 0;
854
+ /**
855
+ * Cache of collections that would be synced on next sync task run.
856
+ */
857
+ _collectionsToSync = new ComplexSet(({ collectionId, peerId }) => `${collectionId}|${peerId}`);
822
858
  _peerId;
823
859
  _peerIdProvider;
824
860
  _getSpaceKeyByRootDocumentId;
@@ -827,6 +863,8 @@ var AutomergeHost = class extends Resource3 {
827
863
  * Fired after a batch of documents was saved to disk.
828
864
  */
829
865
  documentsSaved = new Event2();
866
+ _headsUpdates = /* @__PURE__ */ new Map();
867
+ _onHeadsChangedTask;
830
868
  constructor({ db, indexMetadataStore, dataMonitor, peerIdProvider, getSpaceKeyByRootDocumentId }) {
831
869
  super();
832
870
  this._db = db;
@@ -854,6 +892,11 @@ var AutomergeHost = class extends Resource3 {
854
892
  }
855
893
  async _open() {
856
894
  this._peerId = `host-${this._peerIdProvider?.() ?? PublicKey.random().toHex()}`;
895
+ this._onHeadsChangedTask = new DeferredTask(this._ctx, async () => {
896
+ const docHeads = Array.from(this._headsUpdates.entries());
897
+ this._headsUpdates.clear();
898
+ this._onHeadsChanged(docHeads);
899
+ });
857
900
  await this._storage.open?.();
858
901
  this._repo = new Repo({
859
902
  peerId: this._peerId,
@@ -881,6 +924,28 @@ var AutomergeHost = class extends Resource3 {
881
924
  }
882
925
  }
883
926
  });
927
+ this._syncTask = new DeferredTask(this._ctx, async () => {
928
+ const collectionToSync = Array.from(this._collectionsToSync.values());
929
+ if (collectionToSync.length === 0) {
930
+ return;
931
+ }
932
+ await Promise.all(collectionToSync.map(async ({ collectionId, peerId }) => {
933
+ try {
934
+ await this._handleCollectionSync(collectionId, peerId);
935
+ } catch (err) {
936
+ log3.error("failed to sync collection", {
937
+ collectionId,
938
+ peerId,
939
+ err
940
+ }, {
941
+ F: __dxlog_file3,
942
+ L: 223,
943
+ S: this,
944
+ C: (f, a) => f(...a)
945
+ });
946
+ }
947
+ }));
948
+ });
884
949
  await this._echoNetworkAdapter.open();
885
950
  await this._collectionSynchronizer.open();
886
951
  await this._echoNetworkAdapter.open();
@@ -890,7 +955,8 @@ var AutomergeHost = class extends Resource3 {
890
955
  await this._collectionSynchronizer.close();
891
956
  await this._storage.close?.();
892
957
  await this._echoNetworkAdapter.close();
893
- await this._ctx.dispose();
958
+ this._syncTask = void 0;
959
+ this._onHeadsChangedTask = void 0;
894
960
  }
895
961
  /**
896
962
  * @deprecated To be abstracted away.
@@ -905,15 +971,42 @@ var AutomergeHost = class extends Resource3 {
905
971
  return Object.keys(this._repo.handles).length;
906
972
  }
907
973
  async addReplicator(replicator) {
974
+ invariant2(this.isOpen, "AutomergeHost is not open", {
975
+ F: __dxlog_file3,
976
+ L: 259,
977
+ S: this,
978
+ A: [
979
+ "this.isOpen",
980
+ "'AutomergeHost is not open'"
981
+ ]
982
+ });
908
983
  await this._echoNetworkAdapter.addReplicator(replicator);
909
984
  }
910
985
  async removeReplicator(replicator) {
986
+ invariant2(this.isOpen, "AutomergeHost is not open", {
987
+ F: __dxlog_file3,
988
+ L: 264,
989
+ S: this,
990
+ A: [
991
+ "this.isOpen",
992
+ "'AutomergeHost is not open'"
993
+ ]
994
+ });
911
995
  await this._echoNetworkAdapter.removeReplicator(replicator);
912
996
  }
913
997
  /**
914
998
  * Loads the document handle from the repo and waits for it to be ready.
915
999
  */
916
1000
  async loadDoc(ctx, documentId, opts) {
1001
+ invariant2(this.isOpen, "AutomergeHost is not open", {
1002
+ F: __dxlog_file3,
1003
+ L: 272,
1004
+ S: this,
1005
+ A: [
1006
+ "this.isOpen",
1007
+ "'AutomergeHost is not open'"
1008
+ ]
1009
+ });
917
1010
  let handle;
918
1011
  if (typeof documentId === "string") {
919
1012
  handle = this._repo.handles[documentId];
@@ -931,6 +1024,15 @@ var AutomergeHost = class extends Resource3 {
931
1024
  return handle;
932
1025
  }
933
1026
  async exportDoc(ctx, id) {
1027
+ invariant2(this.isOpen, "AutomergeHost is not open", {
1028
+ F: __dxlog_file3,
1029
+ L: 295,
1030
+ S: this,
1031
+ A: [
1032
+ "this.isOpen",
1033
+ "'AutomergeHost is not open'"
1034
+ ]
1035
+ });
934
1036
  const documentId = interpretAsDocumentId(id);
935
1037
  const chunks = await this._storage.loadRange([
936
1038
  documentId
@@ -941,6 +1043,15 @@ var AutomergeHost = class extends Resource3 {
941
1043
  * Create new persisted document.
942
1044
  */
943
1045
  createDoc(initialValue, opts) {
1046
+ invariant2(this.isOpen, "AutomergeHost is not open", {
1047
+ F: __dxlog_file3,
1048
+ L: 306,
1049
+ S: this,
1050
+ A: [
1051
+ "this.isOpen",
1052
+ "'AutomergeHost is not open'"
1053
+ ]
1054
+ });
944
1055
  if (opts?.preserveHistory) {
945
1056
  if (initialValue instanceof Uint8Array) {
946
1057
  return this._repo.import(initialValue);
@@ -957,6 +1068,15 @@ var AutomergeHost = class extends Resource3 {
957
1068
  }
958
1069
  }
959
1070
  async waitUntilHeadsReplicated(heads) {
1071
+ invariant2(this.isOpen, "AutomergeHost is not open", {
1072
+ F: __dxlog_file3,
1073
+ L: 328,
1074
+ S: this,
1075
+ A: [
1076
+ "this.isOpen",
1077
+ "'AutomergeHost is not open'"
1078
+ ]
1079
+ });
960
1080
  const entries = heads.entries;
961
1081
  if (!entries?.length) {
962
1082
  return;
@@ -972,10 +1092,10 @@ var AutomergeHost = class extends Resource3 {
972
1092
  return !(currentHeads !== null && headsEquals(currentHeads, targetHeads));
973
1093
  });
974
1094
  if (headsToWait.length > 0) {
975
- await Promise.all(headsToWait.map(async (entry, index) => {
1095
+ await Promise.all(headsToWait.map(async (entry) => {
976
1096
  const handle = await this.loadDoc(Context.default(void 0, {
977
1097
  F: __dxlog_file3,
978
- L: 293
1098
+ L: 346
979
1099
  }), entry.documentId);
980
1100
  await waitForHeads(handle, entry.heads);
981
1101
  }));
@@ -983,12 +1103,21 @@ var AutomergeHost = class extends Resource3 {
983
1103
  await this._repo.flush(documentIds.filter((documentId) => this._repo.handles[documentId] && this._repo.handles[documentId].isReady()));
984
1104
  }
985
1105
  async reIndexHeads(documentIds) {
1106
+ invariant2(this.isOpen, "AutomergeHost is not open", {
1107
+ F: __dxlog_file3,
1108
+ L: 359,
1109
+ S: this,
1110
+ A: [
1111
+ "this.isOpen",
1112
+ "'AutomergeHost is not open'"
1113
+ ]
1114
+ });
986
1115
  for (const documentId of documentIds) {
987
1116
  log3("re-indexing heads for document", {
988
1117
  documentId
989
1118
  }, {
990
1119
  F: __dxlog_file3,
991
- L: 307,
1120
+ L: 361,
992
1121
  S: this,
993
1122
  C: (f, a) => f(...a)
994
1123
  });
@@ -998,7 +1127,7 @@ var AutomergeHost = class extends Resource3 {
998
1127
  documentId
999
1128
  }, {
1000
1129
  F: __dxlog_file3,
1001
- L: 310,
1130
+ L: 364,
1002
1131
  S: this,
1003
1132
  C: (f, a) => f(...a)
1004
1133
  });
@@ -1011,7 +1140,7 @@ var AutomergeHost = class extends Resource3 {
1011
1140
  }
1012
1141
  log3("done re-indexing heads", void 0, {
1013
1142
  F: __dxlog_file3,
1014
- L: 319,
1143
+ L: 373,
1015
1144
  S: this,
1016
1145
  C: (f, a) => f(...a)
1017
1146
  });
@@ -1021,9 +1150,6 @@ var AutomergeHost = class extends Resource3 {
1021
1150
  // NOTE: If both peers return sharePolicy=false the replication will not happen
1022
1151
  // https://github.com/automerge/automerge-repo/pull/292
1023
1152
  async _sharePolicy(peerId, documentId) {
1024
- if (peerId.startsWith("client-")) {
1025
- return false;
1026
- }
1027
1153
  if (!documentId) {
1028
1154
  return false;
1029
1155
  }
@@ -1072,13 +1198,31 @@ var AutomergeHost = class extends Resource3 {
1072
1198
  * Called by AutomergeStorageAdapter after levelDB batch commit.
1073
1199
  */
1074
1200
  async _afterSave(path) {
1201
+ if (!this.isOpen) {
1202
+ return void 0;
1203
+ }
1075
1204
  this._indexMetadataStore.notifyMarkedDirty();
1076
1205
  const documentId = path[0];
1077
- const document = this._repo.handles[documentId]?.doc();
1078
- if (document) {
1079
- const heads = getHeads(document);
1080
- this._onHeadsChanged(documentId, heads);
1206
+ const handle = this._repo.handles[documentId];
1207
+ if (!handle || !handle.isReady()) {
1208
+ return;
1209
+ }
1210
+ const document = handle.doc();
1211
+ if (!document) {
1212
+ return;
1081
1213
  }
1214
+ const heads = getHeads(document);
1215
+ this._headsUpdates.set(documentId, heads);
1216
+ invariant2(this._onHeadsChangedTask, "onHeadsChangedTask is not initialized", {
1217
+ F: __dxlog_file3,
1218
+ L: 445,
1219
+ S: this,
1220
+ A: [
1221
+ "this._onHeadsChangedTask",
1222
+ "'onHeadsChangedTask is not initialized'"
1223
+ ]
1224
+ });
1225
+ this._onHeadsChangedTask.schedule();
1082
1226
  this.documentsSaved.emit();
1083
1227
  }
1084
1228
  _automergePeers() {
@@ -1115,11 +1259,12 @@ var AutomergeHost = class extends Resource3 {
1115
1259
  * Flush documents to disk.
1116
1260
  */
1117
1261
  async flush({ documentIds } = {}) {
1118
- const loadedDocuments = documentIds?.filter((documentId) => {
1262
+ const loadedDocuments = (documentIds ?? Object.keys(this._repo.handles)).filter((documentId) => {
1119
1263
  const handle = this._repo.handles[documentId];
1120
1264
  return handle && handle.isReady();
1121
1265
  });
1122
1266
  await this._repo.flush(loadedDocuments);
1267
+ await this._onHeadsChangedTask?.runBlocking();
1123
1268
  }
1124
1269
  async getHeads(documentIds) {
1125
1270
  const result = [];
@@ -1171,8 +1316,17 @@ var AutomergeHost = class extends Resource3 {
1171
1316
  missingOnRemote: diff.missingOnRemote.length,
1172
1317
  missingOnLocal: diff.missingOnLocal.length,
1173
1318
  differentDocuments: diff.different.length,
1174
- localDocumentCount: Object.keys(localState.documents).length,
1175
- remoteDocumentCount: Object.keys(state.documents).length
1319
+ localDocumentCount: Object.entries(localState.documents).filter(([_, heads]) => heads.length > 0).length,
1320
+ remoteDocumentCount: Object.entries(state.documents).filter(([_, heads]) => heads.length > 0).length,
1321
+ totalDocumentCount: (/* @__PURE__ */ new Set([
1322
+ ...Object.keys(localState.documents),
1323
+ ...Object.keys(state.documents)
1324
+ ])).size,
1325
+ unsyncedDocumentCount: (/* @__PURE__ */ new Set([
1326
+ ...diff.missingOnLocal,
1327
+ ...diff.missingOnRemote,
1328
+ ...diff.different
1329
+ ])).size
1176
1330
  });
1177
1331
  }
1178
1332
  return result;
@@ -1220,42 +1374,231 @@ var AutomergeHost = class extends Resource3 {
1220
1374
  this._collectionSynchronizer.onConnectionClosed(peerId);
1221
1375
  }
1222
1376
  _onRemoteCollectionStateUpdated(collectionId, peerId) {
1377
+ this._collectionsToSync.add({
1378
+ collectionId,
1379
+ peerId
1380
+ });
1381
+ this._syncTask?.schedule();
1382
+ }
1383
+ async _handleCollectionSync(collectionId, peerId) {
1223
1384
  const localState = this._collectionSynchronizer.getLocalCollectionState(collectionId);
1224
1385
  const remoteState = this._collectionSynchronizer.getRemoteCollectionStates(collectionId).get(peerId);
1225
1386
  if (!localState || !remoteState) {
1226
1387
  return;
1227
1388
  }
1228
1389
  const { different, missingOnLocal, missingOnRemote } = diffCollectionState(localState, remoteState);
1229
- const toReplicate = [
1230
- ...missingOnLocal,
1231
- ...missingOnRemote,
1390
+ if (different.length === 0 && missingOnLocal.length === 0 && missingOnRemote.length === 0) {
1391
+ return;
1392
+ }
1393
+ const toReplicateWithoutBatching = [
1232
1394
  ...different
1233
1395
  ];
1234
- if (toReplicate.length === 0) {
1396
+ const bundleSyncEnabled = this._echoNetworkAdapter.bundleSyncEnabledForPeer(peerId);
1397
+ if (bundleSyncEnabled && missingOnRemote.length >= BUNDLE_SYNC_THRESHOLD) {
1398
+ log3("pushing bundle", {
1399
+ amount: missingOnRemote.length
1400
+ }, {
1401
+ F: __dxlog_file3,
1402
+ L: 650,
1403
+ S: this,
1404
+ C: (f, a) => f(...a)
1405
+ });
1406
+ const { syncInteractively } = await this._pushInBundles(peerId, missingOnRemote);
1407
+ toReplicateWithoutBatching.push(...syncInteractively);
1408
+ } else {
1409
+ log3.verbose("failed to push bundle, replicating interactively", {
1410
+ collectionId,
1411
+ peerId,
1412
+ amount: missingOnRemote.length
1413
+ }, {
1414
+ F: __dxlog_file3,
1415
+ L: 654,
1416
+ S: this,
1417
+ C: (f, a) => f(...a)
1418
+ });
1419
+ toReplicateWithoutBatching.push(...missingOnRemote);
1420
+ }
1421
+ if (bundleSyncEnabled && missingOnLocal.length >= BUNDLE_SYNC_THRESHOLD) {
1422
+ log3("pulling bundle", {
1423
+ amount: missingOnLocal.length
1424
+ }, {
1425
+ F: __dxlog_file3,
1426
+ L: 662,
1427
+ S: this,
1428
+ C: (f, a) => f(...a)
1429
+ });
1430
+ const { syncInteractively } = await this._pullInBundles(peerId, missingOnLocal);
1431
+ toReplicateWithoutBatching.push(...syncInteractively);
1432
+ } else {
1433
+ log3.verbose("failed to pull bundle, replicating interactively", {
1434
+ collectionId,
1435
+ peerId,
1436
+ amount: missingOnLocal.length
1437
+ }, {
1438
+ F: __dxlog_file3,
1439
+ L: 666,
1440
+ S: this,
1441
+ C: (f, a) => f(...a)
1442
+ });
1443
+ toReplicateWithoutBatching.push(...missingOnLocal);
1444
+ }
1445
+ if (toReplicateWithoutBatching.length === 0) {
1235
1446
  return;
1236
1447
  }
1237
1448
  log3("replicating documents after collection sync", {
1238
1449
  collectionId,
1239
1450
  peerId,
1240
- toReplicate,
1241
- count: toReplicate.length
1451
+ toReplicateWithoutBatching,
1452
+ count: toReplicateWithoutBatching.length
1242
1453
  }, {
1243
1454
  F: __dxlog_file3,
1244
- L: 573,
1455
+ L: 678,
1245
1456
  S: this,
1246
1457
  C: (f, a) => f(...a)
1247
1458
  });
1248
- for (const documentId of toReplicate) {
1459
+ for (const documentId of toReplicateWithoutBatching) {
1249
1460
  this._repo.findWithProgress(documentId);
1250
1461
  }
1251
1462
  }
1252
- _onHeadsChanged(documentId, heads) {
1463
+ // TODO(mykola): Add retries of batches https://gist.github.com/mykola-vrmchk/fde270259e9209fcbf1331e5abbf12cf
1464
+ // TODO(mykola): Use effect to retry batches.
1465
+ async _pushInBundles(peerId, documentIds) {
1466
+ const documentsToPush = [
1467
+ ...documentIds
1468
+ ];
1469
+ const syncInteractively = [];
1470
+ while (documentsToPush.length > 0) {
1471
+ await Promise.all(range(BUNDLE_SYNC_CONCURRENCY).map(async () => {
1472
+ const bundle = documentsToPush.splice(0, BUNDLE_SIZE);
1473
+ if (bundle.length === 0) {
1474
+ return;
1475
+ }
1476
+ await this._pushBundle(peerId, bundle).catch((err) => {
1477
+ log3.warn("failed to push bundle, replicating interactively", {
1478
+ peerId,
1479
+ bundle,
1480
+ err
1481
+ }, {
1482
+ F: __dxlog_file3,
1483
+ L: 709,
1484
+ S: this,
1485
+ C: (f, a) => f(...a)
1486
+ });
1487
+ syncInteractively.push(...bundle);
1488
+ });
1489
+ }));
1490
+ }
1491
+ return {
1492
+ syncInteractively
1493
+ };
1494
+ }
1495
+ async _pushBundle(peerId, documentIds) {
1496
+ if (this._ctx.disposed) {
1497
+ return;
1498
+ }
1499
+ const docs = documentIds.map((documentId) => {
1500
+ const handle = this._repo.handles[documentId];
1501
+ if (!handle || !handle.isReady()) {
1502
+ log3.warn("document not ready, skipping", {
1503
+ documentId
1504
+ }, {
1505
+ F: __dxlog_file3,
1506
+ L: 727,
1507
+ S: this,
1508
+ C: (f, a) => f(...a)
1509
+ });
1510
+ return;
1511
+ }
1512
+ const doc = handle.doc();
1513
+ if (!doc) {
1514
+ log3.warn("document not available, skipping", {
1515
+ documentId
1516
+ }, {
1517
+ F: __dxlog_file3,
1518
+ L: 732,
1519
+ S: this,
1520
+ C: (f, a) => f(...a)
1521
+ });
1522
+ return;
1523
+ }
1524
+ return {
1525
+ documentId,
1526
+ data: save(doc),
1527
+ heads: getHeads(doc)
1528
+ };
1529
+ });
1530
+ await this._echoNetworkAdapter.pushBundle(peerId, docs.filter(isNonNullable2));
1531
+ }
1532
+ async _pullInBundles(peerId, documentIds) {
1533
+ const documentsToPull = [
1534
+ ...documentIds
1535
+ ];
1536
+ const syncInteractively = [];
1537
+ const docsToImport = {};
1538
+ while (documentsToPull.length > 0) {
1539
+ await Promise.all(range(BUNDLE_SYNC_CONCURRENCY).map(async () => {
1540
+ const bundle = documentsToPull.splice(0, BUNDLE_SIZE);
1541
+ if (bundle.length === 0) {
1542
+ return;
1543
+ }
1544
+ const result = await this._pullBundle(peerId, bundle).catch((err) => {
1545
+ log3.warn("failed to pull bundle, replicating interactively", {
1546
+ peerId,
1547
+ bundle,
1548
+ err
1549
+ }, {
1550
+ F: __dxlog_file3,
1551
+ L: 762,
1552
+ S: this,
1553
+ C: (f, a) => f(...a)
1554
+ });
1555
+ syncInteractively.push(...bundle);
1556
+ });
1557
+ if (result) {
1558
+ Object.assign(docsToImport, result.docsToImport);
1559
+ }
1560
+ }));
1561
+ }
1562
+ for (const [documentId, data] of Object.entries(docsToImport)) {
1563
+ this._repo.import(data, {
1564
+ docId: documentId
1565
+ });
1566
+ }
1567
+ await this._repo.flush(Object.keys(docsToImport));
1568
+ return {
1569
+ syncInteractively
1570
+ };
1571
+ }
1572
+ async _pullBundle(peerId, documentIds) {
1573
+ if (this._ctx.disposed) {
1574
+ return;
1575
+ }
1576
+ const docHeads = Object.fromEntries(documentIds.map((documentId) => [
1577
+ documentId,
1578
+ []
1579
+ ]));
1580
+ const bundle = await this._echoNetworkAdapter.pullBundle(peerId, docHeads);
1581
+ return {
1582
+ docsToImport: bundle
1583
+ };
1584
+ }
1585
+ _onHeadsChanged(docHeads) {
1253
1586
  const collectionsChanged = /* @__PURE__ */ new Set();
1254
1587
  for (const collectionId of this._collectionSynchronizer.getRegisteredCollectionIds()) {
1255
1588
  const state = this._collectionSynchronizer.getLocalCollectionState(collectionId);
1256
- if (state?.documents[documentId]) {
1257
- const newState = structuredClone(state);
1258
- newState.documents[documentId] = heads;
1589
+ if (!state) {
1590
+ continue;
1591
+ }
1592
+ let newState;
1593
+ for (const [documentId, heads] of docHeads) {
1594
+ if (documentId in state.documents) {
1595
+ if (!newState) {
1596
+ newState = structuredClone(state);
1597
+ }
1598
+ newState.documents[documentId] = heads;
1599
+ }
1600
+ }
1601
+ if (newState) {
1259
1602
  this._collectionSynchronizer.setLocalCollectionState(collectionId, newState);
1260
1603
  collectionsChanged.add(collectionId);
1261
1604
  }
@@ -1301,7 +1644,7 @@ var changeIsPresentInDoc = (doc, changeHash) => {
1301
1644
  var decodeCollectionState = (state) => {
1302
1645
  invariant2(typeof state === "object" && state !== null, "Invalid state", {
1303
1646
  F: __dxlog_file3,
1304
- L: 624,
1647
+ L: 845,
1305
1648
  S: void 0,
1306
1649
  A: [
1307
1650
  "typeof state === 'object' && state !== null",
@@ -1318,10 +1661,10 @@ var encodeCollectionState = (state) => {
1318
1661
  import { invariant as invariant5 } from "@dxos/invariant";
1319
1662
  import { PublicKey as PublicKey2 } from "@dxos/keys";
1320
1663
  import { log as log5 } from "@dxos/log";
1321
- import { ComplexSet, defaultMap as defaultMap2 } from "@dxos/util";
1664
+ import { ComplexSet as ComplexSet2, defaultMap as defaultMap2 } from "@dxos/util";
1322
1665
 
1323
1666
  // src/automerge/mesh-echo-replicator-connection.ts
1324
- import * as A from "@automerge/automerge";
1667
+ import * as A2 from "@automerge/automerge";
1325
1668
  import { cbor } from "@automerge/automerge-repo";
1326
1669
  import { Resource as Resource4 } from "@dxos/context";
1327
1670
  import { invariant as invariant3 } from "@dxos/invariant";
@@ -1333,12 +1676,12 @@ var MeshReplicatorConnection = class extends Resource4 {
1333
1676
  _params;
1334
1677
  readable;
1335
1678
  writable;
1336
- remoteDeviceKey;
1679
+ remoteDeviceKey = null;
1337
1680
  replicatorExtension;
1338
- _remotePeerId;
1339
- _isEnabled;
1681
+ _remotePeerId = null;
1682
+ _isEnabled = false;
1340
1683
  constructor(_params) {
1341
- super(), this._params = _params, this.remoteDeviceKey = null, this._remotePeerId = null, this._isEnabled = false;
1684
+ super(), this._params = _params;
1342
1685
  let readableStreamController;
1343
1686
  this.readable = new ReadableStream({
1344
1687
  start: (controller) => {
@@ -1422,6 +1765,9 @@ var MeshReplicatorConnection = class extends Resource4 {
1422
1765
  get isEnabled() {
1423
1766
  return this._isEnabled;
1424
1767
  }
1768
+ get bundleSyncEnabled() {
1769
+ return false;
1770
+ }
1425
1771
  async shouldAdvertise(params) {
1426
1772
  return this._params.shouldAdvertise(params);
1427
1773
  }
@@ -1435,7 +1781,7 @@ var MeshReplicatorConnection = class extends Resource4 {
1435
1781
  enable() {
1436
1782
  invariant3(this._remotePeerId != null, "Remote peer has not connected yet.", {
1437
1783
  F: __dxlog_file4,
1438
- L: 127,
1784
+ L: 131,
1439
1785
  S: this,
1440
1786
  A: [
1441
1787
  "this._remotePeerId != null",
@@ -1453,7 +1799,7 @@ var MeshReplicatorConnection = class extends Resource4 {
1453
1799
  };
1454
1800
  var logSendSync = (message) => {
1455
1801
  log4("sendSyncMessage", () => {
1456
- const decodedSyncMessage = message.type === "sync" && message.data ? A.decodeSyncMessage(message.data) : void 0;
1802
+ const decodedSyncMessage = message.type === "sync" && message.data ? A2.decodeSyncMessage(message.data) : void 0;
1457
1803
  return {
1458
1804
  sync: decodedSyncMessage && {
1459
1805
  headsLength: decodedSyncMessage.heads.length,
@@ -1466,7 +1812,7 @@ var logSendSync = (message) => {
1466
1812
  };
1467
1813
  }, {
1468
1814
  F: __dxlog_file4,
1469
- L: 140,
1815
+ L: 144,
1470
1816
  S: void 0,
1471
1817
  C: (f, a) => f(...a)
1472
1818
  });
@@ -1713,7 +2059,7 @@ var MeshEchoReplicator = class {
1713
2059
  C: (f, a) => f(...a)
1714
2060
  });
1715
2061
  const spaceId = await createIdFromSpaceKey(spaceKey);
1716
- defaultMap2(this._authorizedDevices, spaceId, () => new ComplexSet(PublicKey2.hash)).add(deviceKey);
2062
+ defaultMap2(this._authorizedDevices, spaceId, () => new ComplexSet2(PublicKey2.hash)).add(deviceKey);
1717
2063
  for (const connection of this._connections) {
1718
2064
  if (connection.isEnabled && connection.remoteDeviceKey && connection.remoteDeviceKey.equals(deviceKey)) {
1719
2065
  if (this._connectionsPerPeer.has(connection.peerId)) {
@@ -1737,29 +2083,20 @@ var PER_SECOND_RATE_AVG_WINDOW_SIZE = 5;
1737
2083
  var DEFAULT_AVG_WINDOW_SIZE = 25;
1738
2084
  var EchoDataMonitor = class {
1739
2085
  _params;
1740
- _lastTick;
1741
- _activeCounters;
2086
+ _lastTick = 0;
2087
+ _activeCounters = createLocalCounters();
1742
2088
  _lastCompleteCounters;
1743
- _localTimeSeries;
1744
- _storageAverages;
1745
- _replicationAverages;
1746
- _sizeByMessage;
1747
- _lastReceivedMessages;
1748
- _lastSentMessages;
1749
- _connectionsCount;
2089
+ _localTimeSeries = createLocalTimeSeries();
2090
+ _storageAverages = createStorageAverages();
2091
+ _replicationAverages = createNetworkAverages();
2092
+ _sizeByMessage = {};
2093
+ _lastReceivedMessages = new CircularBuffer(100);
2094
+ _lastSentMessages = new CircularBuffer(100);
2095
+ _connectionsCount = 0;
1750
2096
  constructor(_params = {
1751
2097
  timeSeriesLength: 30
1752
2098
  }) {
1753
2099
  this._params = _params;
1754
- this._lastTick = 0;
1755
- this._activeCounters = createLocalCounters();
1756
- this._localTimeSeries = createLocalTimeSeries();
1757
- this._storageAverages = createStorageAverages();
1758
- this._replicationAverages = createNetworkAverages();
1759
- this._sizeByMessage = {};
1760
- this._lastReceivedMessages = new CircularBuffer(100);
1761
- this._lastSentMessages = new CircularBuffer(100);
1762
- this._connectionsCount = 0;
1763
2100
  }
1764
2101
  tick(timeMs) {
1765
2102
  this._advanceTimeWindow(timeMs - this._lastTick);
@@ -2097,9 +2434,9 @@ var getByteCount = (message) => {
2097
2434
  };
2098
2435
 
2099
2436
  // src/db-host/documents-synchronizer.ts
2100
- import { next as A2 } from "@automerge/automerge";
2437
+ import { next as A3 } from "@automerge/automerge";
2101
2438
  import { UpdateScheduler, sleep } from "@dxos/async";
2102
- import { LifecycleState as LifecycleState3, Resource as Resource5, cancelWithContext as cancelWithContext2 } from "@dxos/context";
2439
+ import { LifecycleState as LifecycleState2, Resource as Resource5, cancelWithContext as cancelWithContext2 } from "@dxos/context";
2103
2440
  import { invariant as invariant6 } from "@dxos/invariant";
2104
2441
  import { log as log6 } from "@dxos/log";
2105
2442
  var __dxlog_file7 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/documents-synchronizer.ts";
@@ -2108,18 +2445,18 @@ var WRAP_AROUND_RETRY_LIMIT = 3;
2108
2445
  var WRAP_AROUND_RETRY_INITIAL_DELAY = 100;
2109
2446
  var DocumentsSynchronizer = class extends Resource5 {
2110
2447
  _params;
2111
- _syncStates;
2448
+ _syncStates = /* @__PURE__ */ new Map();
2112
2449
  /**
2113
2450
  * Documents that have pending updates.
2114
2451
  * Used to batch updates.
2115
2452
  */
2116
- _pendingUpdates;
2453
+ _pendingUpdates = /* @__PURE__ */ new Set();
2117
2454
  /**
2118
2455
  * Job that schedules if there are pending updates.
2119
2456
  */
2120
- _sendUpdatesJob;
2457
+ _sendUpdatesJob = void 0;
2121
2458
  constructor(_params) {
2122
- super(), this._params = _params, this._syncStates = /* @__PURE__ */ new Map(), this._pendingUpdates = /* @__PURE__ */ new Set(), this._sendUpdatesJob = void 0;
2459
+ super(), this._params = _params;
2123
2460
  }
2124
2461
  addDocuments(documentIds, retryCounter = 0, wrapAroundRetryDelay = WRAP_AROUND_RETRY_INITIAL_DELAY) {
2125
2462
  if (retryCounter > WRAP_AROUND_RETRY_LIMIT) {
@@ -2239,15 +2576,15 @@ var DocumentsSynchronizer = class extends Resource5 {
2239
2576
  return;
2240
2577
  }
2241
2578
  const doc = handle.doc();
2242
- const mutation = syncState.lastSentHead ? A2.saveSince(doc, syncState.lastSentHead) : A2.save(doc);
2579
+ const mutation = syncState.lastSentHead ? A3.saveSince(doc, syncState.lastSentHead) : A3.save(doc);
2243
2580
  if (mutation.length === 0) {
2244
2581
  return;
2245
2582
  }
2246
- syncState.lastSentHead = A2.getHeads(doc);
2583
+ syncState.lastSentHead = A3.getHeads(doc);
2247
2584
  return mutation;
2248
2585
  }
2249
2586
  _writeMutation(documentId, mutation, isNew) {
2250
- if (this._lifecycleState === LifecycleState3.CLOSED) {
2587
+ if (this._lifecycleState === LifecycleState2.CLOSED) {
2251
2588
  return;
2252
2589
  }
2253
2590
  if (isNew) {
@@ -2255,7 +2592,7 @@ var DocumentsSynchronizer = class extends Resource5 {
2255
2592
  docId: documentId
2256
2593
  });
2257
2594
  const syncState = this._startSync(newHandle);
2258
- syncState.lastSentHead = A2.getHeads(newHandle.doc());
2595
+ syncState.lastSentHead = A3.getHeads(newHandle.doc());
2259
2596
  } else {
2260
2597
  const syncState = this._syncStates.get(documentId);
2261
2598
  invariant6(syncState, "Sync state for document not found", {
@@ -2267,12 +2604,12 @@ var DocumentsSynchronizer = class extends Resource5 {
2267
2604
  "'Sync state for document not found'"
2268
2605
  ]
2269
2606
  });
2270
- const headsBefore = A2.getHeads(syncState.handle.doc());
2607
+ const headsBefore = A3.getHeads(syncState.handle.doc());
2271
2608
  this._params.repo.import(mutation, {
2272
2609
  docId: documentId
2273
2610
  });
2274
- if (A2.equals(headsBefore, syncState.lastSentHead)) {
2275
- syncState.lastSentHead = A2.getHeads(syncState.handle.doc());
2611
+ if (A3.equals(headsBefore, syncState.lastSentHead)) {
2612
+ syncState.lastSentHead = A3.getHeads(syncState.handle.doc());
2276
2613
  }
2277
2614
  }
2278
2615
  }
@@ -2403,14 +2740,7 @@ var DataServiceImpl = class {
2403
2740
  peers: []
2404
2741
  };
2405
2742
  next({
2406
- peers: state.peers.map((peer) => ({
2407
- peerId: peer.peerId,
2408
- missingOnRemote: peer.missingOnRemote,
2409
- missingOnLocal: peer.missingOnLocal,
2410
- differentDocuments: peer.differentDocuments,
2411
- localDocumentCount: peer.localDocumentCount,
2412
- remoteDocumentCount: peer.remoteDocumentCount
2413
- }))
2743
+ peers: state.peers
2414
2744
  });
2415
2745
  });
2416
2746
  this._automergeHost.collectionStateUpdated.on(ctx, (e) => {
@@ -2424,7 +2754,7 @@ var DataServiceImpl = class {
2424
2754
  };
2425
2755
 
2426
2756
  // src/db-host/echo-host.ts
2427
- import { LifecycleState as LifecycleState6, Resource as Resource9 } from "@dxos/context";
2757
+ import { LifecycleState as LifecycleState5, Resource as Resource9 } from "@dxos/context";
2428
2758
  import { todo } from "@dxos/debug";
2429
2759
  import { SpaceDocVersion as SpaceDocVersion3, createIdFromSpaceKey as createIdFromSpaceKey2 } from "@dxos/echo-protocol";
2430
2760
  import { IndexMetadataStore, IndexStore, Indexer } from "@dxos/indexing";
@@ -2433,7 +2763,7 @@ import { IndexKind } from "@dxos/protocols/proto/dxos/echo/indexing";
2433
2763
  import { trace as trace5 } from "@dxos/tracing";
2434
2764
 
2435
2765
  // src/db-host/documents-iterator.ts
2436
- import * as A3 from "@automerge/automerge";
2766
+ import * as A4 from "@automerge/automerge";
2437
2767
  import { Context as Context2 } from "@dxos/context";
2438
2768
  import { DatabaseDirectory as DatabaseDirectory2, SpaceDocVersion } from "@dxos/echo-protocol";
2439
2769
  import { invariant as invariant8 } from "@dxos/invariant";
@@ -2464,10 +2794,10 @@ var createSelectedDocumentsIterator = (automergeHost) => (
2464
2794
  ""
2465
2795
  ]
2466
2796
  });
2467
- const currentHeads = A3.getHeads(doc);
2468
- if (!A3.equals(currentHeads, heads)) {
2797
+ const currentHeads = A4.getHeads(doc);
2798
+ if (!A4.equals(currentHeads, heads)) {
2469
2799
  const begin = Date.now();
2470
- doc = A3.view(doc, heads);
2800
+ doc = A4.view(doc, heads);
2471
2801
  const end = Date.now();
2472
2802
  if (end - begin > LOG_VIEW_OPERATION_THRESHOLD) {
2473
2803
  log8("Checking out document version is taking too long", {
@@ -2522,8 +2852,8 @@ var createSelectedDocumentsIterator = (automergeHost) => (
2522
2852
 
2523
2853
  // src/db-host/query-service.ts
2524
2854
  import { getHeads as getHeads3 } from "@automerge/automerge";
2525
- import { Schema } from "effect";
2526
- import { DeferredTask, scheduleMicroTask, synchronized as synchronized2 } from "@dxos/async";
2855
+ import * as Schema from "effect/Schema";
2856
+ import { DeferredTask as DeferredTask2, scheduleMicroTask, synchronized as synchronized2 } from "@dxos/async";
2527
2857
  import { Stream as Stream2 } from "@dxos/codec-protobuf/stream";
2528
2858
  import { Context as Context4, Resource as Resource7 } from "@dxos/context";
2529
2859
  import { raise } from "@dxos/debug";
@@ -2533,23 +2863,27 @@ import { objectPointerCodec as objectPointerCodec4 } from "@dxos/protocols";
2533
2863
  import { trace as trace4 } from "@dxos/tracing";
2534
2864
 
2535
2865
  // src/query/query-executor.ts
2536
- import { Match } from "effect";
2537
- import { Context as Context3, ContextDisposedError, LifecycleState as LifecycleState4, Resource as Resource6 } from "@dxos/context";
2866
+ import * as Match from "effect/Match";
2867
+ import * as Predicate from "effect/Predicate";
2868
+ import { Context as Context3, ContextDisposedError, LifecycleState as LifecycleState3, Resource as Resource6 } from "@dxos/context";
2538
2869
  import { DatabaseDirectory as DatabaseDirectory3, ObjectStructure, isEncodedReference } from "@dxos/echo-protocol";
2539
2870
  import { EscapedPropPath } from "@dxos/indexing";
2540
2871
  import { invariant as invariant10 } from "@dxos/invariant";
2541
2872
  import { DXN, PublicKey as PublicKey3 } from "@dxos/keys";
2542
2873
  import { log as log9 } from "@dxos/log";
2543
2874
  import { objectPointerCodec as objectPointerCodec3 } from "@dxos/protocols";
2544
- import { getDeep, isNonNullable as isNonNullable2 } from "@dxos/util";
2875
+ import { getDeep, isNonNullable as isNonNullable3 } from "@dxos/util";
2545
2876
 
2546
2877
  // src/query/query-planner.ts
2878
+ import { Order } from "@dxos/echo";
2547
2879
  import { invariant as invariant9 } from "@dxos/invariant";
2548
2880
 
2549
2881
  // src/query/errors.ts
2550
2882
  import { BaseError } from "@dxos/errors";
2551
2883
  var QueryError = class extends BaseError.extend("QUERY_ERROR") {
2552
2884
  };
2885
+ var InvalidQueryError = class extends QueryError.extend("INVALID_QUERY") {
2886
+ };
2553
2887
 
2554
2888
  // src/query/plan.ts
2555
2889
  (function(QueryPlan2) {
@@ -2592,6 +2926,7 @@ var QueryPlanner = class {
2592
2926
  });
2593
2927
  plan = this._optimizeEmptyFilters(plan);
2594
2928
  plan = this._optimizeSoloUnions(plan);
2929
+ plan = this._ensureOrderStep(plan);
2595
2930
  return plan;
2596
2931
  }
2597
2932
  _generate(query, context) {
@@ -2614,8 +2949,11 @@ var QueryPlanner = class {
2614
2949
  return this._generateUnionClause(query, context);
2615
2950
  case "set-difference":
2616
2951
  return this._generateSetDifferenceClause(query, context);
2952
+ case "order":
2953
+ return this._generateOrderClause(query, context);
2617
2954
  default:
2618
- throw new QueryError(`Unsupported query type: ${query.type}`, {
2955
+ throw new QueryError({
2956
+ message: `Unsupported query type: ${query.type}`,
2619
2957
  context: {
2620
2958
  query: context.originalQuery
2621
2959
  }
@@ -2639,10 +2977,11 @@ var QueryPlanner = class {
2639
2977
  }
2640
2978
  // TODO(dmaretskyi): This can be rewritten as a function of (filter[]) -> (selection ? undefined, rest: filter[]) that recurses onto itself.
2641
2979
  // TODO(dmaretskyi): If the tip of the query ast is a [select, ...filter] shape we can reorder the filters so the query is most efficient.
2642
- _generateSelectionFromFilter(filter, context) {
2643
- switch (filter.type) {
2980
+ _generateSelectionFromFilter(filter2, context) {
2981
+ switch (filter2.type) {
2982
+ // Props
2644
2983
  case "object": {
2645
- if (context.selectionInverted && filter.id === void 0 && filter.typename === null && Object.keys(filter.props).length === 0) {
2984
+ if (context.selectionInverted && filter2.id === void 0 && filter2.typename === null && Object.keys(filter2.props).length === 0) {
2646
2985
  return QueryPlan.Plan.make([
2647
2986
  {
2648
2987
  _tag: "ClearWorkingSetStep"
@@ -2651,32 +2990,33 @@ var QueryPlanner = class {
2651
2990
  ]);
2652
2991
  }
2653
2992
  if (context.selectionInverted) {
2654
- throw new QueryError("Query too complex", {
2993
+ throw new QueryError({
2994
+ message: "Query too complex",
2655
2995
  context: {
2656
2996
  query: context.originalQuery
2657
2997
  }
2658
2998
  });
2659
2999
  }
2660
- if (filter.id && filter.id?.length > 0) {
3000
+ if (filter2.id && filter2.id?.length > 0) {
2661
3001
  return QueryPlan.Plan.make([
2662
3002
  {
2663
3003
  _tag: "SelectStep",
2664
3004
  spaces: context.selectionSpaces,
2665
3005
  selector: {
2666
3006
  _tag: "IdSelector",
2667
- objectIds: filter.id
3007
+ objectIds: filter2.id
2668
3008
  }
2669
3009
  },
2670
3010
  ...this._generateDeletedHandlingSteps(context),
2671
3011
  {
2672
3012
  _tag: "FilterStep",
2673
3013
  filter: {
2674
- ...filter,
3014
+ ...filter2,
2675
3015
  id: void 0
2676
3016
  }
2677
3017
  }
2678
3018
  ]);
2679
- } else if (filter.typename) {
3019
+ } else if (filter2.typename) {
2680
3020
  return QueryPlan.Plan.make([
2681
3021
  {
2682
3022
  _tag: "SelectStep",
@@ -2684,17 +3024,17 @@ var QueryPlanner = class {
2684
3024
  selector: {
2685
3025
  _tag: "TypeSelector",
2686
3026
  typename: [
2687
- filter.typename
3027
+ filter2.typename
2688
3028
  ],
2689
3029
  inverted: false
2690
3030
  }
2691
3031
  },
2692
3032
  ...this._generateDeletedHandlingSteps(context),
3033
+ // TODO(dmaretskyi): Normally we could skip filtering by typename here, but since the index does not separate schema versions, we need to do additional filter to only select the correct version.
2693
3034
  {
2694
3035
  _tag: "FilterStep",
2695
3036
  filter: {
2696
- ...filter,
2697
- typename: null
3037
+ ...filter2
2698
3038
  }
2699
3039
  }
2700
3040
  ]);
@@ -2711,12 +3051,32 @@ var QueryPlanner = class {
2711
3051
  {
2712
3052
  _tag: "FilterStep",
2713
3053
  filter: {
2714
- ...filter
3054
+ ...filter2
2715
3055
  }
2716
3056
  }
2717
3057
  ]);
2718
3058
  }
2719
3059
  }
3060
+ // Tag
3061
+ case "tag": {
3062
+ return QueryPlan.Plan.make([
3063
+ {
3064
+ _tag: "SelectStep",
3065
+ spaces: context.selectionSpaces,
3066
+ selector: {
3067
+ _tag: "WildcardSelector"
3068
+ }
3069
+ },
3070
+ ...this._generateDeletedHandlingSteps(context),
3071
+ {
3072
+ _tag: "FilterStep",
3073
+ filter: {
3074
+ ...filter2
3075
+ }
3076
+ }
3077
+ ]);
3078
+ }
3079
+ // Text
2720
3080
  case "text-search": {
2721
3081
  return QueryPlan.Plan.make([
2722
3082
  {
@@ -2724,55 +3084,61 @@ var QueryPlanner = class {
2724
3084
  spaces: context.selectionSpaces,
2725
3085
  selector: {
2726
3086
  _tag: "TextSelector",
2727
- text: filter.text,
2728
- searchKind: filter.searchKind ?? this._options.defaultTextSearchKind
3087
+ text: filter2.text,
3088
+ searchKind: filter2.searchKind ?? this._options.defaultTextSearchKind
2729
3089
  }
2730
3090
  },
2731
3091
  ...this._generateDeletedHandlingSteps(context)
2732
3092
  ]);
2733
3093
  }
3094
+ // Compare
2734
3095
  case "compare":
2735
- throw new QueryError("Query too complex", {
3096
+ throw new QueryError({
3097
+ message: "Query too complex",
2736
3098
  context: {
2737
3099
  query: context.originalQuery
2738
3100
  }
2739
3101
  });
2740
3102
  case "in":
2741
- throw new QueryError("Query too complex", {
3103
+ throw new QueryError({
3104
+ message: "Query too complex",
2742
3105
  context: {
2743
3106
  query: context.originalQuery
2744
3107
  }
2745
3108
  });
2746
3109
  case "range":
2747
- throw new QueryError("Query too complex", {
3110
+ throw new QueryError({
3111
+ message: "Query too complex",
2748
3112
  context: {
2749
3113
  query: context.originalQuery
2750
3114
  }
2751
3115
  });
3116
+ // Boolean
2752
3117
  case "not":
2753
- return this._generateSelectionFromFilter(filter.filter, {
3118
+ return this._generateSelectionFromFilter(filter2.filter, {
2754
3119
  ...context,
2755
3120
  selectionInverted: !context.selectionInverted
2756
3121
  });
2757
3122
  case "and":
2758
- throw new QueryError("Query too complex", {
3123
+ throw new QueryError({
3124
+ message: "Query too complex",
2759
3125
  context: {
2760
3126
  query: context.originalQuery
2761
3127
  }
2762
3128
  });
2763
3129
  case "or":
2764
- if (filter.filters.every(isTrivialTypenameFilter)) {
2765
- const typenames = filter.filters.map((f) => {
2766
- invariant9(f.type === "object" && f.typename !== null, void 0, {
3130
+ if (filter2.filters.every(isTrivialTypenameFilter)) {
3131
+ const typenames = filter2.filters.map((filter3) => {
3132
+ invariant9(filter3.type === "object" && filter3.typename !== null, void 0, {
2767
3133
  F: __dxlog_file10,
2768
- L: 191,
3134
+ L: 225,
2769
3135
  S: this,
2770
3136
  A: [
2771
- "f.type === 'object' && f.typename !== null",
3137
+ "filter.type === 'object' && filter.typename !== null",
2772
3138
  ""
2773
3139
  ]
2774
3140
  });
2775
- return f.typename;
3141
+ return filter3.typename;
2776
3142
  });
2777
3143
  return QueryPlan.Plan.make([
2778
3144
  {
@@ -2784,17 +3150,25 @@ var QueryPlanner = class {
2784
3150
  inverted: context.selectionInverted
2785
3151
  }
2786
3152
  },
2787
- ...this._generateDeletedHandlingSteps(context)
3153
+ ...this._generateDeletedHandlingSteps(context),
3154
+ {
3155
+ _tag: "FilterStep",
3156
+ filter: {
3157
+ ...filter2
3158
+ }
3159
+ }
2788
3160
  ]);
2789
3161
  } else {
2790
- throw new QueryError("Query too complex", {
3162
+ throw new QueryError({
3163
+ message: "Query too complex",
2791
3164
  context: {
2792
3165
  query: context.originalQuery
2793
3166
  }
2794
3167
  });
2795
3168
  }
2796
3169
  default:
2797
- throw new QueryError(`Unsupported filter type: ${filter.type}`, {
3170
+ throw new QueryError({
3171
+ message: `Unsupported filter type: ${filter2.type}`,
2798
3172
  context: {
2799
3173
  query: context.originalQuery
2800
3174
  }
@@ -2994,6 +3368,45 @@ var QueryPlanner = class {
2994
3368
  _optimizeSoloUnions(plan) {
2995
3369
  return plan;
2996
3370
  }
3371
+ _generateOrderClause(query, context) {
3372
+ return QueryPlan.Plan.make([
3373
+ ...this._generate(query.query, context).steps,
3374
+ {
3375
+ _tag: "OrderStep",
3376
+ order: query.order
3377
+ }
3378
+ ]);
3379
+ }
3380
+ // After complete plan is built, inspect it from the end:
3381
+ // - Walk backwards until hitting an object set changer.
3382
+ // - If an order step is found, skip.
3383
+ // - Otherwise append natural order to the end.
3384
+ _ensureOrderStep(plan) {
3385
+ const OBJECT_SET_CHANGERS = /* @__PURE__ */ new Set([
3386
+ "SelectStep",
3387
+ "TraverseStep",
3388
+ "UnionStep",
3389
+ "SetDifferenceStep"
3390
+ ]);
3391
+ for (let i = plan.steps.length - 1; i >= 0; i--) {
3392
+ const step = plan.steps[i];
3393
+ if (step._tag === "OrderStep") {
3394
+ return plan;
3395
+ }
3396
+ if (OBJECT_SET_CHANGERS.has(step._tag)) {
3397
+ break;
3398
+ }
3399
+ }
3400
+ return QueryPlan.Plan.make([
3401
+ ...plan.steps,
3402
+ {
3403
+ _tag: "OrderStep",
3404
+ order: [
3405
+ Order.natural.ast
3406
+ ]
3407
+ }
3408
+ ]);
3409
+ }
2997
3410
  };
2998
3411
  var DEFAULT_CONTEXT = {
2999
3412
  originalQuery: null,
@@ -3014,8 +3427,8 @@ var createRelationTraversalStep = (direction) => ({
3014
3427
  direction
3015
3428
  }
3016
3429
  });
3017
- var isTrivialTypenameFilter = (filter) => {
3018
- return filter.type === "object" && filter.typename !== null && Object.keys(filter.props).length === 0 && (filter.id === void 0 || filter.id.length === 0) && (filter.foreignKeys === void 0 || filter.foreignKeys.length === 0);
3430
+ var isTrivialTypenameFilter = (filter2) => {
3431
+ return filter2.type === "object" && filter2.typename !== null && Object.keys(filter2.props).length === 0 && (filter2.id === void 0 || filter2.id.length === 0) && (filter2.foreignKeys === void 0 || filter2.foreignKeys.length === 0);
3019
3432
  };
3020
3433
 
3021
3434
  // src/query/query-executor.ts
@@ -3027,11 +3440,57 @@ var ExecutionTrace = Object.freeze({
3027
3440
  objectCount: 0,
3028
3441
  documentsLoaded: 0,
3029
3442
  indexHits: 0,
3443
+ beginTs: 0,
3444
+ endTs: 0,
3030
3445
  indexQueryTime: 0,
3031
3446
  documentLoadTime: 0,
3032
3447
  executionTime: 0,
3033
3448
  children: []
3034
3449
  }),
3450
+ markEnd: (trace6) => {
3451
+ trace6.endTs = performance.now();
3452
+ trace6.executionTime = trace6.endTs - trace6.beginTs;
3453
+ },
3454
+ putOnPerformanceTimeline: (trace6) => {
3455
+ performance.measure(trace6.name, {
3456
+ start: trace6.beginTs,
3457
+ end: trace6.endTs,
3458
+ detail: {
3459
+ devtools: {
3460
+ dataType: "track-entry",
3461
+ track: "Query Execution",
3462
+ trackGroup: "ECHO",
3463
+ color: "tertiary-dark",
3464
+ properties: [
3465
+ [
3466
+ "objectCount",
3467
+ trace6.objectCount
3468
+ ],
3469
+ [
3470
+ "documentsLoaded",
3471
+ trace6.documentsLoaded
3472
+ ],
3473
+ [
3474
+ "index hits",
3475
+ trace6.indexHits
3476
+ ],
3477
+ [
3478
+ "indexQueryTime",
3479
+ trace6.indexQueryTime
3480
+ ],
3481
+ [
3482
+ "documentLoadTime",
3483
+ trace6.documentLoadTime
3484
+ ]
3485
+ ],
3486
+ tooltipText: trace6.details
3487
+ }
3488
+ }
3489
+ });
3490
+ for (const child of trace6.children) {
3491
+ ExecutionTrace.putOnPerformanceTimeline(child);
3492
+ }
3493
+ },
3035
3494
  format: (trace6) => {
3036
3495
  const go = (trace7, indent) => {
3037
3496
  return [
@@ -3093,9 +3552,9 @@ var QueryExecutor = class extends Resource6 {
3093
3552
  }));
3094
3553
  }
3095
3554
  async execQuery() {
3096
- invariant10(this._lifecycleState === LifecycleState4.OPEN, void 0, {
3555
+ invariant10(this._lifecycleState === LifecycleState3.OPEN, void 0, {
3097
3556
  F: __dxlog_file11,
3098
- L: 174,
3557
+ L: 211,
3099
3558
  S: this,
3100
3559
  A: [
3101
3560
  "this._lifecycleState === LifecycleState.OPEN",
@@ -3130,7 +3589,7 @@ var QueryExecutor = class extends Resource6 {
3130
3589
  trace6.children.push(result.trace);
3131
3590
  }
3132
3591
  trace6.objectCount = workingSet.length;
3133
- trace6.executionTime = performance.now() - begin;
3592
+ ExecutionTrace.markEnd(trace6);
3134
3593
  return {
3135
3594
  workingSet,
3136
3595
  trace: trace6
@@ -3168,10 +3627,14 @@ var QueryExecutor = class extends Resource6 {
3168
3627
  case "TraverseStep":
3169
3628
  ({ workingSet: newWorkingSet, trace: trace6 } = await this._execTraverseStep(step, workingSet));
3170
3629
  break;
3630
+ case "OrderStep":
3631
+ ({ workingSet: newWorkingSet, trace: trace6 } = await this._execOrderStep(step, workingSet));
3632
+ break;
3171
3633
  default:
3172
3634
  throw new Error(`Unknown step type: ${step._tag}`);
3173
3635
  }
3174
- trace6.executionTime = performance.now() - begin;
3636
+ trace6.beginTs = begin;
3637
+ ExecutionTrace.markEnd(trace6);
3175
3638
  return {
3176
3639
  workingSet: newWorkingSet,
3177
3640
  trace: trace6
@@ -3184,7 +3647,8 @@ var QueryExecutor = class extends Resource6 {
3184
3647
  const trace6 = {
3185
3648
  ...ExecutionTrace.makeEmpty(),
3186
3649
  name: "Select",
3187
- details: JSON.stringify(step.selector)
3650
+ details: JSON.stringify(step.selector),
3651
+ beginTs: performance.now()
3188
3652
  };
3189
3653
  switch (step.selector._tag) {
3190
3654
  case "WildcardSelector": {
@@ -3205,7 +3669,7 @@ var QueryExecutor = class extends Resource6 {
3205
3669
  const results = await this._loadDocumentsAfterIndexQuery(indexHits);
3206
3670
  trace6.documentsLoaded += results.length;
3207
3671
  trace6.documentLoadTime += performance.now() - documentLoadStart;
3208
- workingSet.push(...results.filter(isNonNullable2).filter((item) => step.spaces.includes(item.spaceId)));
3672
+ workingSet.push(...results.filter(isNonNullable3).filter((item) => step.spaces.includes(item.spaceId)));
3209
3673
  trace6.objectCount = workingSet.length;
3210
3674
  break;
3211
3675
  }
@@ -3215,7 +3679,7 @@ var QueryExecutor = class extends Resource6 {
3215
3679
  sourceSpaceId: step.spaces[0]
3216
3680
  })));
3217
3681
  trace6.documentLoadTime += performance.now() - beginLoad;
3218
- workingSet.push(...items.filter(isNonNullable2));
3682
+ workingSet.push(...items.filter(isNonNullable3));
3219
3683
  trace6.objectCount = workingSet.length;
3220
3684
  break;
3221
3685
  }
@@ -3237,7 +3701,7 @@ var QueryExecutor = class extends Resource6 {
3237
3701
  const results = await this._loadDocumentsAfterIndexQuery(indexHits);
3238
3702
  trace6.documentsLoaded += results.length;
3239
3703
  trace6.documentLoadTime += performance.now() - documentLoadStart;
3240
- workingSet.push(...results.filter(isNonNullable2).filter((item) => step.spaces.includes(item.spaceId)));
3704
+ workingSet.push(...results.filter(isNonNullable3).filter((item) => step.spaces.includes(item.spaceId)));
3241
3705
  trace6.objectCount = workingSet.length;
3242
3706
  break;
3243
3707
  }
@@ -3262,7 +3726,7 @@ var QueryExecutor = class extends Resource6 {
3262
3726
  const results = await this._loadDocumentsAfterIndexQuery(indexHits);
3263
3727
  trace6.documentsLoaded += results.length;
3264
3728
  trace6.documentLoadTime += performance.now() - documentLoadStart;
3265
- workingSet.push(...results.filter(isNonNullable2).filter((item) => step.spaces.includes(item.spaceId)));
3729
+ workingSet.push(...results.filter(isNonNullable3).filter((item) => step.spaces.includes(item.spaceId)));
3266
3730
  trace6.objectCount = workingSet.length;
3267
3731
  break;
3268
3732
  }
@@ -3291,17 +3755,6 @@ var QueryExecutor = class extends Resource6 {
3291
3755
  };
3292
3756
  }
3293
3757
  async _execFilterDeletedStep(step, workingSet) {
3294
- if (workingSet.length === 6) {
3295
- log9("filter deleted step", {
3296
- step,
3297
- workingSet
3298
- }, {
3299
- F: __dxlog_file11,
3300
- L: 386,
3301
- S: this,
3302
- C: (f, a) => f(...a)
3303
- });
3304
- }
3305
3758
  const expected = step.mode === "only-deleted";
3306
3759
  const result = workingSet.filter((item) => ObjectStructure.isDeleted(item.doc) === expected);
3307
3760
  return {
@@ -3343,20 +3796,20 @@ var QueryExecutor = class extends Resource6 {
3343
3796
  ref: ref2["/"]
3344
3797
  }, {
3345
3798
  F: __dxlog_file11,
3346
- L: 431,
3799
+ L: 477,
3347
3800
  S: this,
3348
3801
  C: (f, a) => f(...a)
3349
3802
  });
3350
3803
  return null;
3351
3804
  }
3352
3805
  });
3353
- }).filter(isNonNullable2);
3806
+ }).filter(isNonNullable3);
3354
3807
  const beginLoad = performance.now();
3355
3808
  const items = await Promise.all(refs.map(({ ref, spaceId }) => this._loadFromDXN(ref, {
3356
3809
  sourceSpaceId: spaceId
3357
3810
  })));
3358
3811
  trace6.documentLoadTime += performance.now() - beginLoad;
3359
- newWorkingSet.push(...items.filter(isNonNullable2));
3812
+ newWorkingSet.push(...items.filter(isNonNullable3));
3360
3813
  trace6.objectCount = newWorkingSet.length;
3361
3814
  break;
3362
3815
  }
@@ -3375,7 +3828,7 @@ var QueryExecutor = class extends Resource6 {
3375
3828
  const results = await this._loadDocumentsAfterIndexQuery(indexHits);
3376
3829
  trace6.documentsLoaded += results.length;
3377
3830
  trace6.documentLoadTime += performance.now() - documentLoadStart;
3378
- newWorkingSet.push(...results.filter(isNonNullable2));
3831
+ newWorkingSet.push(...results.filter(isNonNullable3));
3379
3832
  trace6.objectCount = newWorkingSet.length;
3380
3833
  break;
3381
3834
  }
@@ -3401,19 +3854,19 @@ var QueryExecutor = class extends Resource6 {
3401
3854
  ref: ref["/"]
3402
3855
  }, {
3403
3856
  F: __dxlog_file11,
3404
- L: 494,
3857
+ L: 540,
3405
3858
  S: this,
3406
3859
  C: (f, a) => f(...a)
3407
3860
  });
3408
3861
  return null;
3409
3862
  }
3410
- }).filter(isNonNullable2);
3863
+ }).filter(isNonNullable3);
3411
3864
  const beginLoad = performance.now();
3412
3865
  const items = await Promise.all(refs.map(({ ref, spaceId }) => this._loadFromDXN(ref, {
3413
3866
  sourceSpaceId: spaceId
3414
3867
  })));
3415
3868
  trace6.documentLoadTime += performance.now() - beginLoad;
3416
- newWorkingSet.push(...items.filter(isNonNullable2));
3869
+ newWorkingSet.push(...items.filter(isNonNullable3));
3417
3870
  trace6.objectCount = newWorkingSet.length;
3418
3871
  break;
3419
3872
  }
@@ -3433,7 +3886,7 @@ var QueryExecutor = class extends Resource6 {
3433
3886
  const results = await this._loadDocumentsAfterIndexQuery(indexHits);
3434
3887
  trace6.documentsLoaded += results.length;
3435
3888
  trace6.documentLoadTime += performance.now() - documentLoadStart;
3436
- newWorkingSet.push(...results.filter(isNonNullable2));
3889
+ newWorkingSet.push(...results.filter(isNonNullable3));
3437
3890
  trace6.objectCount = newWorkingSet.length;
3438
3891
  break;
3439
3892
  }
@@ -3490,16 +3943,83 @@ var QueryExecutor = class extends Resource6 {
3490
3943
  trace: trace6
3491
3944
  };
3492
3945
  }
3946
+ async _execOrderStep(step, workingSet) {
3947
+ const sortedWorkingSet = [
3948
+ ...workingSet
3949
+ ].sort((a, b) => this._compareMultiOrder(a, b, step.order));
3950
+ return {
3951
+ workingSet: sortedWorkingSet,
3952
+ trace: {
3953
+ ...ExecutionTrace.makeEmpty(),
3954
+ name: "Order",
3955
+ details: JSON.stringify(step.order),
3956
+ objectCount: sortedWorkingSet.length
3957
+ }
3958
+ };
3959
+ }
3960
+ _compareMultiOrder(a, b, orders) {
3961
+ if (orders.length === 0) {
3962
+ return 0;
3963
+ } else if (orders.length === 1) {
3964
+ return this._compareByOrder(a, b, orders[0]);
3965
+ }
3966
+ for (const order of orders) {
3967
+ const comparison = this._compareByOrder(a, b, order);
3968
+ if (comparison !== 0) {
3969
+ return comparison;
3970
+ }
3971
+ }
3972
+ return 0;
3973
+ }
3974
+ _compareByOrder(a, b, order) {
3975
+ switch (order.kind) {
3976
+ case "natural":
3977
+ return a.objectId.localeCompare(b.objectId);
3978
+ case "property": {
3979
+ const comparison = this._compareByProperty(a, b, order.property);
3980
+ return order.direction === "desc" ? -comparison : comparison;
3981
+ }
3982
+ default:
3983
+ return 0;
3984
+ }
3985
+ }
3986
+ _compareByProperty(a, b, property) {
3987
+ const aValue = a.doc.data[property];
3988
+ const bValue = b.doc.data[property];
3989
+ if (aValue == null && bValue == null) {
3990
+ return 0;
3991
+ }
3992
+ if (aValue == null) {
3993
+ return 1;
3994
+ }
3995
+ if (bValue == null) {
3996
+ return -1;
3997
+ }
3998
+ if (typeof aValue === "string" && typeof bValue === "string") {
3999
+ return aValue.localeCompare(bValue);
4000
+ }
4001
+ if (typeof aValue === "number" && typeof bValue === "number") {
4002
+ return aValue - bValue;
4003
+ }
4004
+ if (typeof aValue === "boolean" && typeof bValue === "boolean") {
4005
+ return aValue === bValue ? 0 : aValue ? 1 : -1;
4006
+ }
4007
+ return String(aValue).localeCompare(String(bValue));
4008
+ }
3493
4009
  async _loadDocumentsAfterIndexQuery(indexHits) {
3494
4010
  return Promise.all(indexHits.map(async (hit) => {
3495
4011
  return this._loadFromIndexHit(hit);
3496
4012
  }));
3497
4013
  }
4014
+ /**
4015
+ * Space key hex -> SpaceId.
4016
+ */
4017
+ _spaceIdCache = /* @__PURE__ */ new Map();
3498
4018
  async _loadFromIndexHit(hit) {
3499
4019
  const { objectId, documentId, spaceKey: spaceKeyInIndex } = objectPointerCodec3.decode(hit.id);
3500
4020
  const handle = await this._automergeHost.loadDoc(Context3.default(void 0, {
3501
4021
  F: __dxlog_file11,
3502
- L: 604
4022
+ L: 738
3503
4023
  }), documentId);
3504
4024
  const doc = handle.doc();
3505
4025
  if (!doc) {
@@ -3509,6 +4029,11 @@ var QueryExecutor = class extends Resource6 {
3509
4029
  if (!spaceKey) {
3510
4030
  return null;
3511
4031
  }
4032
+ let spaceId = this._spaceIdCache.get(spaceKey);
4033
+ if (!spaceId) {
4034
+ spaceId = await createIdFromSpaceKey(PublicKey3.from(spaceKey));
4035
+ this._spaceIdCache.set(spaceKey, spaceId);
4036
+ }
3512
4037
  const object = DatabaseDirectory3.getInlineObject(doc, objectId);
3513
4038
  if (!object) {
3514
4039
  return null;
@@ -3516,7 +4041,7 @@ var QueryExecutor = class extends Resource6 {
3516
4041
  return {
3517
4042
  objectId,
3518
4043
  documentId,
3519
- spaceId: await createIdFromSpaceKey(PublicKey3.from(spaceKey)),
4044
+ spaceId,
3520
4045
  doc: object
3521
4046
  };
3522
4047
  }
@@ -3527,7 +4052,7 @@ var QueryExecutor = class extends Resource6 {
3527
4052
  dxn
3528
4053
  }, {
3529
4054
  F: __dxlog_file11,
3530
- L: 631,
4055
+ L: 771,
3531
4056
  S: this,
3532
4057
  C: (f, a) => f(...a)
3533
4058
  });
@@ -3540,7 +4065,7 @@ var QueryExecutor = class extends Resource6 {
3540
4065
  spaceId
3541
4066
  }, {
3542
4067
  F: __dxlog_file11,
3543
- L: 639,
4068
+ L: 779,
3544
4069
  S: this,
3545
4070
  C: (f, a) => f(...a)
3546
4071
  });
@@ -3552,7 +4077,7 @@ var QueryExecutor = class extends Resource6 {
3552
4077
  spaceId
3553
4078
  }, {
3554
4079
  F: __dxlog_file11,
3555
- L: 644,
4080
+ L: 784,
3556
4081
  S: this,
3557
4082
  C: (f, a) => f(...a)
3558
4083
  });
@@ -3573,7 +4098,7 @@ var QueryExecutor = class extends Resource6 {
3573
4098
  }
3574
4099
  const handle = await this._automergeHost.loadDoc(Context3.default(void 0, {
3575
4100
  F: __dxlog_file11,
3576
- L: 663
4101
+ L: 803
3577
4102
  }), link);
3578
4103
  const doc = handle.doc();
3579
4104
  if (!doc) {
@@ -3602,11 +4127,12 @@ function _ts_decorate5(decorators, target, key, desc) {
3602
4127
  var __dxlog_file12 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/query-service.ts";
3603
4128
  var QueryServiceImpl = class extends Resource7 {
3604
4129
  _params;
3605
- _queries;
4130
+ // TODO(dmaretskyi): We need to implement query deduping. Idle composer has 80 queries with only 10 being unique.
4131
+ _queries = /* @__PURE__ */ new Set();
3606
4132
  _updateQueries;
3607
4133
  // TODO(burdon): OK for options, but not params. Pass separately and type readonly here.
3608
4134
  constructor(_params) {
3609
- super(), this._params = _params, this._queries = /* @__PURE__ */ new Set();
4135
+ super(), this._params = _params;
3610
4136
  trace4.diagnostic({
3611
4137
  id: "active-queries",
3612
4138
  name: "Active Queries",
@@ -3623,7 +4149,7 @@ var QueryServiceImpl = class extends Resource7 {
3623
4149
  }
3624
4150
  async _open() {
3625
4151
  this._params.indexer.updated.on(this._ctx, () => this.invalidateQueries());
3626
- this._updateQueries = new DeferredTask(this._ctx, this._executeQueries.bind(this));
4152
+ this._updateQueries = new DeferredTask2(this._ctx, this._executeQueries.bind(this));
3627
4153
  }
3628
4154
  async _close() {
3629
4155
  await this._updateQueries.join();
@@ -3639,7 +4165,7 @@ var QueryServiceImpl = class extends Resource7 {
3639
4165
  config: this._params.indexer.config
3640
4166
  }, {
3641
4167
  F: __dxlog_file12,
3642
- L: 101,
4168
+ L: 102,
3643
4169
  S: this,
3644
4170
  C: (f, a) => f(...a)
3645
4171
  });
@@ -3661,7 +4187,7 @@ var QueryServiceImpl = class extends Resource7 {
3661
4187
  async reindex() {
3662
4188
  log10("Reindexing all documents...", void 0, {
3663
4189
  F: __dxlog_file12,
3664
- L: 120,
4190
+ L: 121,
3665
4191
  S: this,
3666
4192
  C: (f, a) => f(...a)
3667
4193
  });
@@ -3676,7 +4202,7 @@ var QueryServiceImpl = class extends Resource7 {
3676
4202
  count: ids.size
3677
4203
  }, {
3678
4204
  F: __dxlog_file12,
3679
- L: 128,
4205
+ L: 129,
3680
4206
  S: this,
3681
4207
  C: (f, a) => f(...a)
3682
4208
  });
@@ -3686,7 +4212,7 @@ var QueryServiceImpl = class extends Resource7 {
3686
4212
  count: ids.size
3687
4213
  }, {
3688
4214
  F: __dxlog_file12,
3689
- L: 132,
4215
+ L: 133,
3690
4216
  S: this,
3691
4217
  C: (f, a) => f(...a)
3692
4218
  });
@@ -3752,7 +4278,7 @@ var QueryServiceImpl = class extends Resource7 {
3752
4278
  } catch (err) {
3753
4279
  log10.catch(err, void 0, {
3754
4280
  F: __dxlog_file12,
3755
- L: 203,
4281
+ L: 204,
3756
4282
  S: this,
3757
4283
  C: (f, a) => f(...a)
3758
4284
  });
@@ -3763,7 +4289,7 @@ var QueryServiceImpl = class extends Resource7 {
3763
4289
  duration: performance.now() - begin
3764
4290
  }, {
3765
4291
  F: __dxlog_file12,
3766
- L: 207,
4292
+ L: 208,
3767
4293
  S: this,
3768
4294
  C: (f, a) => f(...a)
3769
4295
  });
@@ -3814,7 +4340,7 @@ var createDocumentsIterator = (automergeHost) => (
3814
4340
  }
3815
4341
  const linkHandle = await automergeHost.loadDoc(Context4.default(void 0, {
3816
4342
  F: __dxlog_file12,
3817
- L: 247
4343
+ L: 248
3818
4344
  }), urlString);
3819
4345
  for await (const result of getObjectsFromHandle(linkHandle)) {
3820
4346
  yield result;
@@ -3839,7 +4365,7 @@ var createDocumentsIterator = (automergeHost) => (
3839
4365
  import { interpretAsDocumentId as interpretAsDocumentId3 } from "@automerge/automerge-repo";
3840
4366
  import isEqual from "lodash.isequal";
3841
4367
  import { Event as Event3, UpdateScheduler as UpdateScheduler3 } from "@dxos/async";
3842
- import { Context as Context5, LifecycleState as LifecycleState5, Resource as Resource8 } from "@dxos/context";
4368
+ import { Context as Context5, LifecycleState as LifecycleState4, Resource as Resource8 } from "@dxos/context";
3843
4369
  import { invariant as invariant12 } from "@dxos/invariant";
3844
4370
 
3845
4371
  // src/db-host/database-root.ts
@@ -3848,17 +4374,17 @@ import { DatabaseDirectory as DatabaseDirectory5, SpaceDocVersion as SpaceDocVer
3848
4374
  import { invariant as invariant11 } from "@dxos/invariant";
3849
4375
 
3850
4376
  // src/db-host/automerge-metrics.ts
3851
- import * as A4 from "@automerge/automerge";
4377
+ import * as A5 from "@automerge/automerge";
3852
4378
  import { log as log11 } from "@dxos/log";
3853
4379
  var __dxlog_file13 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/automerge-metrics.ts";
3854
4380
  var measureDocMetrics = (doc) => {
3855
- const snapshot = A4.save(doc);
4381
+ const snapshot = A5.save(doc);
3856
4382
  const start = Date.now();
3857
- const temp = A4.load(snapshot);
4383
+ const temp = A5.load(snapshot);
3858
4384
  const end = Date.now();
3859
- A4.free(temp);
4385
+ A5.free(temp);
3860
4386
  const getAllChangesStart = Date.now();
3861
- const mutationCount = A4.getAllChanges(doc).length;
4387
+ const mutationCount = A5.getAllChanges(doc).length;
3862
4388
  const getAllChangesEnd = Date.now();
3863
4389
  if (getAllChangesEnd - getAllChangesStart > 300) {
3864
4390
  log11.warn("getAllChanges took too long", {
@@ -3986,7 +4512,7 @@ var SpaceStateManager = class extends Resource8 {
3986
4512
  return this._rootBySpace.get(spaceId);
3987
4513
  }
3988
4514
  getRootBySpaceId(spaceId) {
3989
- invariant12(this._lifecycleState === LifecycleState5.OPEN, void 0, {
4515
+ invariant12(this._lifecycleState === LifecycleState4.OPEN, void 0, {
3990
4516
  F: __dxlog_file15,
3991
4517
  L: 44,
3992
4518
  S: this,
@@ -4193,7 +4719,6 @@ var EchoHost = class extends Resource9 {
4193
4719
  if (e.previousRootId) {
4194
4720
  void this._automergeHost.clearLocalCollectionState(deriveCollectionIdFromSpaceId(e.spaceId, e.previousRootId));
4195
4721
  }
4196
- void this._automergeHost.updateLocalCollectionState(deriveCollectionIdFromSpaceId(e.spaceId), e.documentIds);
4197
4722
  void this._automergeHost.updateLocalCollectionState(deriveCollectionIdFromSpaceId(e.spaceId, e.spaceRootId), e.documentIds);
4198
4723
  });
4199
4724
  this._automergeHost.documentsSaved.on(this._ctx, () => {
@@ -4210,7 +4735,7 @@ var EchoHost = class extends Resource9 {
4210
4735
  * Flush all pending writes to the underlying storage.
4211
4736
  */
4212
4737
  async flush() {
4213
- await this._automergeHost.repo.flush();
4738
+ await this._automergeHost.flush();
4214
4739
  }
4215
4740
  /**
4216
4741
  * Perform any pending index updates.
@@ -4237,9 +4762,9 @@ var EchoHost = class extends Resource9 {
4237
4762
  * Create new space root.
4238
4763
  */
4239
4764
  async createSpaceRoot(spaceKey) {
4240
- invariant13(this._lifecycleState === LifecycleState6.OPEN, void 0, {
4765
+ invariant13(this._lifecycleState === LifecycleState5.OPEN, void 0, {
4241
4766
  F: __dxlog_file16,
4242
- L: 256,
4767
+ L: 254,
4243
4768
  S: this,
4244
4769
  A: [
4245
4770
  "this._lifecycleState === LifecycleState.OPEN",
@@ -4265,9 +4790,9 @@ var EchoHost = class extends Resource9 {
4265
4790
  }
4266
4791
  // TODO(dmaretskyi): Change to document id.
4267
4792
  async openSpaceRoot(spaceId, automergeUrl) {
4268
- invariant13(this._lifecycleState === LifecycleState6.OPEN, void 0, {
4793
+ invariant13(this._lifecycleState === LifecycleState5.OPEN, void 0, {
4269
4794
  F: __dxlog_file16,
4270
- L: 275,
4795
+ L: 273,
4271
4796
  S: this,
4272
4797
  A: [
4273
4798
  "this._lifecycleState === LifecycleState.OPEN",
@@ -4297,16 +4822,17 @@ var EchoHost = class extends Resource9 {
4297
4822
  };
4298
4823
 
4299
4824
  // src/edge/echo-edge-replicator.ts
4825
+ import * as Automerge from "@automerge/automerge";
4300
4826
  import { cbor as cbor2 } from "@automerge/automerge-repo";
4301
4827
  import { Mutex, scheduleMicroTask as scheduleMicroTask2, scheduleTask as scheduleTask2 } from "@dxos/async";
4302
4828
  import { Context as Context6, Resource as Resource11 } from "@dxos/context";
4303
4829
  import { randomUUID } from "@dxos/crypto";
4304
4830
  import { invariant as invariant14 } from "@dxos/invariant";
4305
4831
  import { log as log13 } from "@dxos/log";
4306
- import { EdgeService } from "@dxos/protocols";
4832
+ import { DocumentCodec, EdgeService } from "@dxos/protocols";
4307
4833
  import { buf } from "@dxos/protocols/buf";
4308
4834
  import { MessageSchema as RouterMessageSchema } from "@dxos/protocols/buf/dxos/edge/messenger_pb";
4309
- import { bufferToArray as bufferToArray2 } from "@dxos/util";
4835
+ import { bufferToArray as bufferToArray2, setDeep } from "@dxos/util";
4310
4836
 
4311
4837
  // src/edge/inflight-request-limiter.ts
4312
4838
  import { Trigger as Trigger2 } from "@dxos/async";
@@ -4320,11 +4846,11 @@ var InflightRequestLimiter = class extends Resource10 {
4320
4846
  * Can't exceed _config.maxInflightRequests.
4321
4847
  * Resets after timeout to avoid replicator being stuck.
4322
4848
  */
4323
- _inflightRequestBalance;
4324
- _requestBarrier;
4849
+ _inflightRequestBalance = 0;
4850
+ _requestBarrier = new Trigger2();
4325
4851
  _resetBalanceTimeout;
4326
4852
  constructor(_config) {
4327
- super(), this._config = _config, this._inflightRequestBalance = 0, this._requestBarrier = new Trigger2();
4853
+ super(), this._config = _config;
4328
4854
  }
4329
4855
  async _open() {
4330
4856
  this._inflightRequestBalance = 0;
@@ -4442,14 +4968,16 @@ var RESTART_DELAY_JITTER = 250;
4442
4968
  var MAX_RESTART_DELAY = 5e3;
4443
4969
  var EchoEdgeReplicator = class {
4444
4970
  _edgeConnection;
4971
+ _edgeHttpClient;
4445
4972
  _mutex = new Mutex();
4446
4973
  _ctx = void 0;
4447
4974
  _context = null;
4448
4975
  _connectedSpaces = /* @__PURE__ */ new Set();
4449
4976
  _connections = /* @__PURE__ */ new Map();
4450
4977
  _sharePolicyEnabled = true;
4451
- constructor({ edgeConnection, disableSharePolicy }) {
4978
+ constructor({ edgeConnection, edgeHttpClient, disableSharePolicy }) {
4452
4979
  this._edgeConnection = edgeConnection;
4980
+ this._edgeHttpClient = edgeHttpClient;
4453
4981
  this._sharePolicyEnabled = !disableSharePolicy;
4454
4982
  }
4455
4983
  async connect(context) {
@@ -4458,14 +4986,14 @@ var EchoEdgeReplicator = class {
4458
4986
  connectedSpaces: this._connectedSpaces.size
4459
4987
  }, {
4460
4988
  F: __dxlog_file18,
4461
- L: 62,
4989
+ L: 73,
4462
4990
  S: this,
4463
4991
  C: (f, a) => f(...a)
4464
4992
  });
4465
4993
  this._context = context;
4466
4994
  this._ctx = Context6.default(void 0, {
4467
4995
  F: __dxlog_file18,
4468
- L: 64
4996
+ L: 75
4469
4997
  });
4470
4998
  this._ctx.onDispose(this._edgeConnection.onReconnected(() => {
4471
4999
  this._ctx && scheduleMicroTask2(this._ctx, () => this._handleReconnect());
@@ -4564,7 +5092,7 @@ var EchoEdgeReplicator = class {
4564
5092
  async _openConnection(spaceId, reconnects = 0) {
4565
5093
  invariant14(this._context, void 0, {
4566
5094
  F: __dxlog_file18,
4567
- L: 125,
5095
+ L: 136,
4568
5096
  S: this,
4569
5097
  A: [
4570
5098
  "this._context",
@@ -4573,7 +5101,7 @@ var EchoEdgeReplicator = class {
4573
5101
  });
4574
5102
  invariant14(!this._connections.has(spaceId), void 0, {
4575
5103
  F: __dxlog_file18,
4576
- L: 126,
5104
+ L: 137,
4577
5105
  S: this,
4578
5106
  A: [
4579
5107
  "!this._connections.has(spaceId)",
@@ -4582,6 +5110,7 @@ var EchoEdgeReplicator = class {
4582
5110
  });
4583
5111
  let restartScheduled = false;
4584
5112
  const connection = new EdgeReplicatorConnection({
5113
+ edgeHttpClient: this._edgeHttpClient,
4585
5114
  edgeConnection: this._edgeConnection,
4586
5115
  spaceId,
4587
5116
  context: this._context,
@@ -4591,7 +5120,7 @@ var EchoEdgeReplicator = class {
4591
5120
  spaceId
4592
5121
  }, {
4593
5122
  F: __dxlog_file18,
4594
- L: 136,
5123
+ L: 148,
4595
5124
  S: this,
4596
5125
  C: (f, a) => f(...a)
4597
5126
  });
@@ -4602,7 +5131,7 @@ var EchoEdgeReplicator = class {
4602
5131
  spaceId
4603
5132
  }, {
4604
5133
  F: __dxlog_file18,
4605
- L: 140,
5134
+ L: 152,
4606
5135
  S: this,
4607
5136
  C: (f, a) => f(...a)
4608
5137
  });
@@ -4619,7 +5148,7 @@ var EchoEdgeReplicator = class {
4619
5148
  restartDelay
4620
5149
  }, {
4621
5150
  F: __dxlog_file18,
4622
- L: 151,
5151
+ L: 163,
4623
5152
  S: this,
4624
5153
  C: (f, a) => f(...a)
4625
5154
  });
@@ -4647,7 +5176,7 @@ var EchoEdgeReplicator = class {
4647
5176
  restartDelay
4648
5177
  }, {
4649
5178
  F: __dxlog_file18,
4650
- L: 168,
5179
+ L: 180,
4651
5180
  S: this,
4652
5181
  C: (f, a) => f(...a)
4653
5182
  });
@@ -4668,7 +5197,9 @@ var EchoEdgeReplicator = class {
4668
5197
  var MAX_INFLIGHT_REQUESTS = 5;
4669
5198
  var MAX_RATE_LIMIT_WAIT_TIME_MS = 3e3;
4670
5199
  var EdgeReplicatorConnection = class extends Resource11 {
5200
+ _connectionId = randomUUID();
4671
5201
  _edgeConnection;
5202
+ _edgeHttpClient;
4672
5203
  _remotePeerId = null;
4673
5204
  _targetServiceId;
4674
5205
  _spaceId;
@@ -4677,6 +5208,7 @@ var EdgeReplicatorConnection = class extends Resource11 {
4677
5208
  _onRemoteConnected;
4678
5209
  _onRemoteDisconnected;
4679
5210
  _onRestartRequested;
5211
+ _sequence = 0;
4680
5212
  _requestLimiter = new InflightRequestLimiter({
4681
5213
  maxInflightRequests: MAX_INFLIGHT_REQUESTS,
4682
5214
  resetBalanceTimeoutMs: MAX_RATE_LIMIT_WAIT_TIME_MS
@@ -4684,12 +5216,13 @@ var EdgeReplicatorConnection = class extends Resource11 {
4684
5216
  _readableStreamController;
4685
5217
  readable;
4686
5218
  writable;
4687
- constructor({ edgeConnection, spaceId, context, sharedPolicyEnabled, onRemoteConnected, onRemoteDisconnected, onRestartRequested }) {
5219
+ constructor({ edgeConnection, edgeHttpClient, spaceId, context, sharedPolicyEnabled, onRemoteConnected, onRemoteDisconnected, onRestartRequested }) {
4688
5220
  super();
4689
5221
  this._edgeConnection = edgeConnection;
5222
+ this._edgeHttpClient = edgeHttpClient;
4690
5223
  this._spaceId = spaceId;
4691
5224
  this._context = context;
4692
- this._remotePeerId = `${EdgeService.AUTOMERGE_REPLICATOR}:${spaceId}-${randomUUID()}`;
5225
+ this._remotePeerId = `${EdgeService.AUTOMERGE_REPLICATOR}:${spaceId}-${this._connectionId}`;
4693
5226
  this._targetServiceId = `${EdgeService.AUTOMERGE_REPLICATOR}:${spaceId}`;
4694
5227
  this._sharedPolicyEnabled = sharedPolicyEnabled;
4695
5228
  this._onRemoteConnected = onRemoteConnected;
@@ -4710,7 +5243,7 @@ var EdgeReplicatorConnection = class extends Resource11 {
4710
5243
  async _open(ctx) {
4711
5244
  log13("opening...", void 0, {
4712
5245
  F: __dxlog_file18,
4713
- L: 255,
5246
+ L: 273,
4714
5247
  S: this,
4715
5248
  C: (f, a) => f(...a)
4716
5249
  });
@@ -4725,7 +5258,7 @@ var EdgeReplicatorConnection = class extends Resource11 {
4725
5258
  if (firstReconnect) {
4726
5259
  log13.verbose("first reconnect skipped", void 0, {
4727
5260
  F: __dxlog_file18,
4728
- L: 270,
5261
+ L: 288,
4729
5262
  S: this,
4730
5263
  C: (f, a) => f(...a)
4731
5264
  });
@@ -4740,7 +5273,7 @@ var EdgeReplicatorConnection = class extends Resource11 {
4740
5273
  async _close() {
4741
5274
  log13("closing...", void 0, {
4742
5275
  F: __dxlog_file18,
4743
- L: 283,
5276
+ L: 301,
4744
5277
  S: this,
4745
5278
  C: (f, a) => f(...a)
4746
5279
  });
@@ -4751,7 +5284,7 @@ var EdgeReplicatorConnection = class extends Resource11 {
4751
5284
  get peerId() {
4752
5285
  invariant14(this._remotePeerId, "Not connected", {
4753
5286
  F: __dxlog_file18,
4754
- L: 292,
5287
+ L: 310,
4755
5288
  S: this,
4756
5289
  A: [
4757
5290
  "this._remotePeerId",
@@ -4776,7 +5309,7 @@ var EdgeReplicatorConnection = class extends Resource11 {
4776
5309
  remoteId: this._remotePeerId
4777
5310
  }, {
4778
5311
  F: __dxlog_file18,
4779
- L: 307,
5312
+ L: 325,
4780
5313
  S: this,
4781
5314
  C: (f, a) => f(...a)
4782
5315
  });
@@ -4797,20 +5330,42 @@ var EdgeReplicatorConnection = class extends Resource11 {
4797
5330
  }
4798
5331
  const payload = cbor2.decode(message.payload.value);
4799
5332
  log13.verbose("received", {
4800
- type: payload.type,
4801
- documentId: payload.type === "sync" && payload.documentId,
5333
+ ...getMessageInfo(payload),
4802
5334
  remoteId: this._remotePeerId
4803
5335
  }, {
4804
5336
  F: __dxlog_file18,
4805
- L: 336,
5337
+ L: 354,
4806
5338
  S: this,
4807
5339
  C: (f, a) => f(...a)
4808
5340
  });
4809
5341
  payload.senderId = this._remotePeerId;
4810
5342
  this._processMessage(payload);
4811
5343
  }
5344
+ get bundleSyncEnabled() {
5345
+ return true;
5346
+ }
5347
+ async pushBundle(bundle) {
5348
+ const request = {
5349
+ bundle: bundle.map(({ documentId, data, heads }) => ({
5350
+ documentId,
5351
+ mutation: DocumentCodec.encode(data),
5352
+ heads
5353
+ }))
5354
+ };
5355
+ await this._edgeHttpClient.importBundle(this._spaceId, request);
5356
+ }
5357
+ async pullBundle(docHeads) {
5358
+ const request = {
5359
+ docHeads
5360
+ };
5361
+ const response = await this._edgeHttpClient.exportBundle(this._spaceId, request);
5362
+ return Object.fromEntries(response.bundle.map((doc) => [
5363
+ doc.documentId,
5364
+ DocumentCodec.decode(doc.mutation)
5365
+ ]));
5366
+ }
4812
5367
  _processMessage(message) {
4813
- if (isForbiddenErrorMessage(message)) {
5368
+ if (isErrorMessage(message)) {
4814
5369
  this._onRestartRequested();
4815
5370
  return;
4816
5371
  }
@@ -4819,13 +5374,20 @@ var EdgeReplicatorConnection = class extends Resource11 {
4819
5374
  }
4820
5375
  async _sendMessage(message) {
4821
5376
  message.targetId = this._targetServiceId;
5377
+ setDeep(message, [
5378
+ "metadata",
5379
+ "dxos_sequence"
5380
+ ], this._getSequence());
5381
+ setDeep(message, [
5382
+ "metadata",
5383
+ "dxos_connectionId"
5384
+ ], this._connectionId);
4822
5385
  log13.verbose("sending...", {
4823
- type: message.type,
4824
- documentId: message.type === "sync" && message.documentId,
5386
+ ...getMessageInfo(message),
4825
5387
  remoteId: this._remotePeerId
4826
5388
  }, {
4827
5389
  F: __dxlog_file18,
4828
- L: 365,
5390
+ L: 407,
4829
5391
  S: this,
4830
5392
  C: (f, a) => f(...a)
4831
5393
  });
@@ -4846,14 +5408,29 @@ var EdgeReplicatorConnection = class extends Resource11 {
4846
5408
  err
4847
5409
  }, {
4848
5410
  F: __dxlog_file18,
4849
- L: 385,
5411
+ L: 426,
4850
5412
  S: this,
4851
5413
  C: (f, a) => f(...a)
4852
5414
  });
4853
5415
  }
4854
5416
  }
5417
+ _getSequence() {
5418
+ return this._sequence++;
5419
+ }
5420
+ };
5421
+ var isErrorMessage = (message) => message.type === "error";
5422
+ var getMessageInfo = (msg) => {
5423
+ const { have, heads, need, changes } = msg.type === "sync" ? Automerge.decodeSyncMessage(msg.data) : {};
5424
+ return {
5425
+ type: msg.type,
5426
+ documentId: "documentId" in msg ? msg.documentId : void 0,
5427
+ have,
5428
+ heads,
5429
+ need,
5430
+ changes: changes?.length,
5431
+ sequence: msg.metadata?.dxos_sequence
5432
+ };
4855
5433
  };
4856
- var isForbiddenErrorMessage = (message) => message.type === "error" && message.message === "Forbidden";
4857
5434
 
4858
5435
  // src/util.ts
4859
5436
  import { ObjectStructure as ObjectStructure2, decodeReference } from "@dxos/echo-protocol";
@@ -4908,6 +5485,7 @@ export {
4908
5485
  diffCollectionState,
4909
5486
  encodingOptions,
4910
5487
  filterMatchObject,
5488
+ filterMatchObjectJSON,
4911
5489
  filterMatchValue,
4912
5490
  findInlineObjectOfType,
4913
5491
  getSpaceIdFromCollectionId,