@dxos/echo-pipeline 0.8.4-main.bc674ce → 0.8.4-main.bcb3aa67d6

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 (116) hide show
  1. package/dist/lib/{browser/chunk-WIQUYO7H.mjs → neutral/chunk-DN4YBAWV.mjs} +35 -41
  2. package/dist/lib/neutral/chunk-DN4YBAWV.mjs.map +7 -0
  3. package/dist/lib/{browser/chunk-FJPXA75J.mjs → neutral/chunk-IMPFMBJK.mjs} +7 -1
  4. package/dist/lib/neutral/chunk-IMPFMBJK.mjs.map +7 -0
  5. package/dist/lib/{browser → neutral}/filter/index.mjs +1 -1
  6. package/dist/lib/{browser → neutral}/index.mjs +1428 -1288
  7. package/dist/lib/neutral/index.mjs.map +7 -0
  8. package/dist/lib/neutral/meta.json +1 -0
  9. package/dist/lib/{browser → neutral}/testing/index.mjs +4 -4
  10. package/dist/lib/{browser → neutral}/testing/index.mjs.map +3 -3
  11. package/dist/types/src/automerge/automerge-host.d.ts +9 -12
  12. package/dist/types/src/automerge/automerge-host.d.ts.map +1 -1
  13. package/dist/types/src/automerge/automerge-repo.test.d.ts.map +1 -1
  14. package/dist/types/src/automerge/echo-network-adapter.d.ts +7 -6
  15. package/dist/types/src/automerge/echo-network-adapter.d.ts.map +1 -1
  16. package/dist/types/src/automerge/echo-replicator.d.ts +11 -10
  17. package/dist/types/src/automerge/echo-replicator.d.ts.map +1 -1
  18. package/dist/types/src/automerge/heads-store.d.ts.map +1 -1
  19. package/dist/types/src/automerge/mesh-echo-replicator-connection.d.ts +2 -2
  20. package/dist/types/src/automerge/mesh-echo-replicator-connection.d.ts.map +1 -1
  21. package/dist/types/src/automerge/mesh-echo-replicator.d.ts +6 -5
  22. package/dist/types/src/automerge/mesh-echo-replicator.d.ts.map +1 -1
  23. package/dist/types/src/db-host/automerge-data-source.d.ts +2 -1
  24. package/dist/types/src/db-host/automerge-data-source.d.ts.map +1 -1
  25. package/dist/types/src/db-host/data-service.d.ts.map +1 -1
  26. package/dist/types/src/db-host/documents-synchronizer.d.ts +2 -2
  27. package/dist/types/src/db-host/documents-synchronizer.d.ts.map +1 -1
  28. package/dist/types/src/db-host/echo-host.d.ts +33 -35
  29. package/dist/types/src/db-host/echo-host.d.ts.map +1 -1
  30. package/dist/types/src/db-host/local-queue-service.d.ts +5 -2
  31. package/dist/types/src/db-host/local-queue-service.d.ts.map +1 -1
  32. package/dist/types/src/db-host/query-service.d.ts +8 -8
  33. package/dist/types/src/db-host/query-service.d.ts.map +1 -1
  34. package/dist/types/src/db-host/queue-data-source.d.ts +11 -1
  35. package/dist/types/src/db-host/queue-data-source.d.ts.map +1 -1
  36. package/dist/types/src/db-host/stub.d.ts +2 -1
  37. package/dist/types/src/db-host/stub.d.ts.map +1 -1
  38. package/dist/types/src/edge/echo-edge-replicator.d.ts +5 -4
  39. package/dist/types/src/edge/echo-edge-replicator.d.ts.map +1 -1
  40. package/dist/types/src/filter/filter-match.d.ts.map +1 -1
  41. package/dist/types/src/query/plan.d.ts +30 -13
  42. package/dist/types/src/query/plan.d.ts.map +1 -1
  43. package/dist/types/src/query/query-executor.d.ts +15 -15
  44. package/dist/types/src/query/query-executor.d.ts.map +1 -1
  45. package/dist/types/src/query/query-planner.d.ts +4 -1
  46. package/dist/types/src/query/query-planner.d.ts.map +1 -1
  47. package/dist/types/src/space/control-pipeline.d.ts +2 -1
  48. package/dist/types/src/space/control-pipeline.d.ts.map +1 -1
  49. package/dist/types/src/space/space-manager.d.ts +2 -1
  50. package/dist/types/src/space/space-manager.d.ts.map +1 -1
  51. package/dist/types/src/space/space-protocol.d.ts +3 -2
  52. package/dist/types/src/space/space-protocol.d.ts.map +1 -1
  53. package/dist/types/src/space/space.d.ts +2 -2
  54. package/dist/types/src/space/space.d.ts.map +1 -1
  55. package/dist/types/src/testing/test-replicator.d.ts +8 -8
  56. package/dist/types/src/testing/test-replicator.d.ts.map +1 -1
  57. package/dist/types/tsconfig.tsbuildinfo +1 -1
  58. package/package.json +44 -49
  59. package/src/automerge/automerge-host.test.ts +8 -10
  60. package/src/automerge/automerge-host.ts +25 -42
  61. package/src/automerge/automerge-repo.test.ts +2 -1
  62. package/src/automerge/echo-network-adapter.test.ts +2 -1
  63. package/src/automerge/echo-network-adapter.ts +17 -17
  64. package/src/automerge/echo-replicator.ts +11 -10
  65. package/src/automerge/heads-store.ts +28 -1
  66. package/src/automerge/mesh-echo-replicator-connection.ts +2 -2
  67. package/src/automerge/mesh-echo-replicator.ts +13 -9
  68. package/src/db-host/automerge-data-source.test.ts +31 -25
  69. package/src/db-host/automerge-data-source.ts +48 -5
  70. package/src/db-host/data-service.ts +4 -3
  71. package/src/db-host/documents-synchronizer.test.ts +0 -4
  72. package/src/db-host/documents-synchronizer.ts +5 -3
  73. package/src/db-host/echo-host.ts +128 -141
  74. package/src/db-host/local-queue-service.ts +45 -46
  75. package/src/db-host/query-service.ts +21 -109
  76. package/src/db-host/queue-data-source.ts +50 -23
  77. package/src/db-host/queue-service.test.ts +15 -11
  78. package/src/db-host/space-state-manager.ts +1 -1
  79. package/src/db-host/stub.ts +5 -0
  80. package/src/edge/echo-edge-replicator.test.ts +9 -8
  81. package/src/edge/echo-edge-replicator.ts +27 -22
  82. package/src/filter/filter-match.test.ts +10 -0
  83. package/src/filter/filter-match.ts +13 -5
  84. package/src/metadata/metadata-store.ts +3 -3
  85. package/src/query/plan.ts +35 -17
  86. package/src/query/query-executor.ts +545 -378
  87. package/src/query/query-planner.test.ts +457 -163
  88. package/src/query/query-planner.ts +208 -55
  89. package/src/space/control-pipeline.test.ts +2 -1
  90. package/src/space/control-pipeline.ts +2 -3
  91. package/src/space/space-manager.ts +7 -3
  92. package/src/space/space-protocol.browser.test.ts +13 -12
  93. package/src/space/space-protocol.test.ts +13 -12
  94. package/src/space/space-protocol.ts +5 -4
  95. package/src/space/space.test.ts +2 -2
  96. package/src/space/space.ts +5 -5
  97. package/src/testing/test-replicator.ts +11 -11
  98. package/dist/lib/browser/chunk-FJPXA75J.mjs.map +0 -7
  99. package/dist/lib/browser/chunk-WIQUYO7H.mjs.map +0 -7
  100. package/dist/lib/browser/index.mjs.map +0 -7
  101. package/dist/lib/browser/meta.json +0 -1
  102. package/dist/lib/node-esm/chunk-7PL6UK4B.mjs +0 -2154
  103. package/dist/lib/node-esm/chunk-7PL6UK4B.mjs.map +0 -7
  104. package/dist/lib/node-esm/chunk-S5KGVQFZ.mjs +0 -235
  105. package/dist/lib/node-esm/chunk-S5KGVQFZ.mjs.map +0 -7
  106. package/dist/lib/node-esm/filter/index.mjs +0 -12
  107. package/dist/lib/node-esm/filter/index.mjs.map +0 -7
  108. package/dist/lib/node-esm/index.mjs +0 -6805
  109. package/dist/lib/node-esm/index.mjs.map +0 -7
  110. package/dist/lib/node-esm/meta.json +0 -1
  111. package/dist/lib/node-esm/testing/index.mjs +0 -591
  112. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  113. package/dist/types/src/db-host/documents-iterator.d.ts +0 -7
  114. package/dist/types/src/db-host/documents-iterator.d.ts.map +0 -1
  115. package/src/db-host/documents-iterator.ts +0 -76
  116. /package/dist/lib/{browser → neutral}/filter/index.mjs.map +0 -0
@@ -3,7 +3,7 @@ import {
3
3
  filterMatchObject,
4
4
  filterMatchObjectJSON,
5
5
  filterMatchValue
6
- } from "./chunk-FJPXA75J.mjs";
6
+ } from "./chunk-IMPFMBJK.mjs";
7
7
  import {
8
8
  AuthExtension,
9
9
  AuthStatus,
@@ -26,11 +26,11 @@ import {
26
26
  mapTimeframeToFeedIndexes,
27
27
  startAfter,
28
28
  valueEncoding
29
- } from "./chunk-WIQUYO7H.mjs";
29
+ } from "./chunk-DN4YBAWV.mjs";
30
30
 
31
31
  // src/db-host/automerge-data-source.ts
32
+ import * as A from "@automerge/automerge";
32
33
  import * as Effect from "effect/Effect";
33
- import { Context } from "@dxos/context";
34
34
  import { objectStructureToJson } from "@dxos/echo/internal";
35
35
  import { DatabaseDirectory, SpaceDocVersion } from "@dxos/echo-protocol";
36
36
  import { PublicKey } from "@dxos/keys";
@@ -62,7 +62,7 @@ var AutomergeDataSource = class {
62
62
  constructor(automergeHost) {
63
63
  this.#automergeHost = automergeHost;
64
64
  }
65
- getChangedObjects(cursors, opts) {
65
+ getChangedObjects(ctx, cursors, opts) {
66
66
  return Effect.gen(this, function* () {
67
67
  const cursorMap = /* @__PURE__ */ new Map();
68
68
  for (const cursor of cursors) {
@@ -91,10 +91,7 @@ var AutomergeDataSource = class {
91
91
  const updatedCursors = [];
92
92
  for (const { documentId, heads: docHeads } of changedDocuments) {
93
93
  try {
94
- const handle = yield* Effect.promise(() => this.#automergeHost.loadDoc(Context.default(void 0, {
95
- F: __dxlog_file,
96
- L: 97
97
- }), documentId));
94
+ const handle = yield* Effect.promise(() => this.#automergeHost.loadDoc(ctx, documentId));
98
95
  const doc = handle.doc();
99
96
  if (!doc) {
100
97
  continue;
@@ -108,14 +105,20 @@ var AutomergeDataSource = class {
108
105
  }
109
106
  const spaceKey = PublicKey.fromHex(spaceKeyHex);
110
107
  const spaceId = yield* Effect.promise(() => createIdFromSpaceKey(spaceKey));
108
+ const existingCursor = cursorMap.get(documentId);
109
+ const { changedObjectIds, updatedAt } = inspectDocChanges(doc, existingCursor);
111
110
  const docObjects = doc.objects ?? {};
112
111
  for (const [objectId, structure] of Object.entries(docObjects)) {
112
+ if (changedObjectIds && !changedObjectIds.has(objectId)) {
113
+ continue;
114
+ }
113
115
  objects.push({
114
116
  spaceId,
115
117
  documentId,
116
118
  queueId: null,
117
119
  recordId: null,
118
- data: objectStructureToJson(objectId, structure)
120
+ data: objectStructureToJson(objectId, structure),
121
+ updatedAt
119
122
  });
120
123
  }
121
124
  updatedCursors.push({
@@ -129,7 +132,7 @@ var AutomergeDataSource = class {
129
132
  error
130
133
  }, {
131
134
  F: __dxlog_file,
132
- L: 137,
135
+ L: 143,
133
136
  S: this,
134
137
  C: (f, a) => f(...a)
135
138
  });
@@ -142,29 +145,57 @@ var AutomergeDataSource = class {
142
145
  });
143
146
  }
144
147
  };
148
+ var inspectDocChanges = (doc, existingCursor) => {
149
+ if (!existingCursor) {
150
+ return {
151
+ changedObjectIds: null,
152
+ updatedAt: Date.now()
153
+ };
154
+ }
155
+ const oldHeads = headsCodec.decode(existingCursor);
156
+ const patches = A.diff(doc, oldHeads, A.getHeads(doc));
157
+ const changedObjectIds = /* @__PURE__ */ new Set();
158
+ for (const patch of patches) {
159
+ if (patch.path.length >= 2 && patch.path[0] === "objects") {
160
+ changedObjectIds.add(String(patch.path[1]));
161
+ }
162
+ }
163
+ const changes = A.getChangesMetaSince(doc, oldHeads);
164
+ let maxTime = 0;
165
+ for (const change of changes) {
166
+ if (change.time > maxTime) {
167
+ maxTime = change.time;
168
+ }
169
+ }
170
+ const updatedAt = maxTime > 0 ? maxTime * 1e3 : Date.now();
171
+ return {
172
+ changedObjectIds,
173
+ updatedAt
174
+ };
175
+ };
145
176
 
146
177
  // src/db-host/data-service.ts
147
178
  import { UpdateScheduler as UpdateScheduler2 } from "@dxos/async";
179
+ import { Context } from "@dxos/context";
148
180
  import { Stream } from "@dxos/codec-protobuf/stream";
149
181
  import { invariant as invariant7 } from "@dxos/invariant";
150
182
  import { SpaceId as SpaceId2 } from "@dxos/keys";
151
- import { log as log8 } from "@dxos/log";
183
+ import { log as log9 } from "@dxos/log";
152
184
 
153
185
  // src/automerge/automerge-host.ts
154
- import { getBackend, getHeads, equals as headsEquals, isAutomerge, save } from "@automerge/automerge";
186
+ import { getBackend, getHeads as getHeads2, equals as headsEquals, isAutomerge, save } from "@automerge/automerge";
155
187
  import { Repo, interpretAsDocumentId } from "@automerge/automerge-repo";
156
188
  import { DeferredTask, Event as Event3, asyncTimeout } from "@dxos/async";
157
- import { Context as Context2, Resource as Resource3, cancelWithContext } from "@dxos/context";
189
+ import { Resource as Resource3, cancelWithContext } from "@dxos/context";
158
190
  import { DatabaseDirectory as DatabaseDirectory2 } from "@dxos/echo-protocol";
159
191
  import { invariant as invariant2 } from "@dxos/invariant";
160
192
  import { PublicKey as PublicKey2 } from "@dxos/keys";
161
- import { log as log4 } from "@dxos/log";
162
- import { objectPointerCodec } from "@dxos/protocols";
193
+ import { log as log5 } from "@dxos/log";
163
194
  import { trace as trace2 } from "@dxos/tracing";
164
195
  import { ComplexSet, bufferToArray, defaultMap as defaultMap2, isNonNullable as isNonNullable2, range } from "@dxos/util";
165
196
 
166
197
  // src/automerge/collection-synchronizer.ts
167
- import { next as A } from "@automerge/automerge";
198
+ import { next as A2 } from "@automerge/automerge";
168
199
  import * as Array2 from "effect/Array";
169
200
  import * as Record from "effect/Record";
170
201
  import { Event, asyncReturn, scheduleTask, scheduleTaskInterval } from "@dxos/async";
@@ -371,9 +402,9 @@ var CollectionSynchronizer = class extends Resource {
371
402
  const localState = perCollectionState.localState ?? {
372
403
  documents: {}
373
404
  };
374
- const diff = diffCollectionState(localState, remoteState);
405
+ const diff2 = diffCollectionState(localState, remoteState);
375
406
  const spanId = getSpanName(peerId);
376
- if (diff.different.length === 0) {
407
+ if (diff2.different.length === 0) {
377
408
  trace.spanEnd(spanId);
378
409
  } else {
379
410
  trace.spanStart({
@@ -390,16 +421,16 @@ var CollectionSynchronizer = class extends Resource {
390
421
  log2("diff", {
391
422
  localState: localState.documents,
392
423
  remoteState: remoteState.documents,
393
- missingOnLocal: diff.missingOnLocal,
394
- missingOnRemote: diff.missingOnRemote,
395
- different: diff.different
424
+ missingOnLocal: diff2.missingOnLocal,
425
+ missingOnRemote: diff2.missingOnRemote,
426
+ different: diff2.different
396
427
  }, {
397
428
  F: __dxlog_file2,
398
429
  L: 210,
399
430
  S: this,
400
431
  C: (f, a) => f(...a)
401
432
  });
402
- if (diff.missingOnLocal.length > 0 || diff.different.length > 0 || diff.missingOnRemote.length > 0) {
433
+ if (diff2.missingOnLocal.length > 0 || diff2.different.length > 0 || diff2.missingOnRemote.length > 0) {
403
434
  log2("emit remote state update", void 0, {
404
435
  F: __dxlog_file2,
405
436
  L: 218,
@@ -409,7 +440,7 @@ var CollectionSynchronizer = class extends Resource {
409
440
  this.remoteStateUpdated.emit({
410
441
  peerId,
411
442
  collectionId,
412
- newDocsAppeared: diff.missingOnLocal.length > 0
443
+ newDocsAppeared: diff2.missingOnLocal.length > 0
413
444
  });
414
445
  }
415
446
  }
@@ -451,7 +482,7 @@ var diffCollectionState = (local, remote) => {
451
482
  missingOnLocal.push(documentId);
452
483
  } else if (!remoteDocuments[documentId]) {
453
484
  missingOnRemote.push(documentId);
454
- } else if (!A.equals(local.documents[documentId], remote.documents[documentId])) {
485
+ } else if (!A2.equals(local.documents[documentId], remote.documents[documentId])) {
455
486
  different.push(documentId);
456
487
  }
457
488
  }
@@ -558,7 +589,7 @@ var EchoNetworkAdapter = class extends NetworkAdapter {
558
589
  this._onConnectionAuthScopeChanged(entry.connection);
559
590
  }
560
591
  }
561
- async addReplicator(replicator) {
592
+ async addReplicator(ctx, replicator) {
562
593
  invariant(this._lifecycleState === LifecycleState.OPEN, void 0, {
563
594
  F: __dxlog_file3,
564
595
  L: 140,
@@ -587,7 +618,7 @@ var EchoNetworkAdapter = class extends NetworkAdapter {
587
618
  ]
588
619
  });
589
620
  this._replicators.add(replicator);
590
- await replicator.connect({
621
+ await replicator.connect(ctx, {
591
622
  peerId: this.peerId,
592
623
  onConnectionOpen: this._onConnectionOpen.bind(this),
593
624
  onConnectionClosed: this._onConnectionClosed.bind(this),
@@ -670,19 +701,19 @@ var EchoNetworkAdapter = class extends NetworkAdapter {
670
701
  }
671
702
  return connection.connection.bundleSyncEnabled;
672
703
  }
673
- async pushBundle(peerId, bundle) {
704
+ async pushBundle(ctx, peerId, bundle) {
674
705
  const connection = this._connections.get(peerId);
675
706
  if (!connection) {
676
707
  throw new Error("Connection not found.");
677
708
  }
678
- return connection.connection.pushBundle(bundle);
709
+ return connection.connection.pushBundle(ctx, bundle);
679
710
  }
680
- async pullBundle(peerId, docHeads) {
711
+ async pullBundle(ctx, peerId, docHeads) {
681
712
  const connection = this._connections.get(peerId);
682
713
  if (!connection) {
683
714
  throw new Error("Connection not found.");
684
715
  }
685
- return connection.connection.pullBundle(docHeads);
716
+ return connection.connection.pullBundle(ctx, docHeads);
686
717
  }
687
718
  _send(message) {
688
719
  const connectionEntry = this._connections.get(message.targetId);
@@ -870,7 +901,35 @@ var createEchoPeerMetadata = () => ({
870
901
  var isEchoPeerMetadata = (metadata) => metadata?.dxos_peerSource === "EchoNetworkAdapter";
871
902
 
872
903
  // src/automerge/heads-store.ts
873
- import { headsEncoding } from "@dxos/indexing";
904
+ import { log as log4 } from "@dxos/log";
905
+ import { schema } from "@dxos/protocols/proto";
906
+ var __dxlog_file4 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/heads-store.ts";
907
+ var headsCodec2;
908
+ var getHeadsCodec = () => headsCodec2 ??= schema.getCodecForType("dxos.echo.query.Heads");
909
+ var headsEncoding = {
910
+ encode: (value) => getHeadsCodec().encode({
911
+ hashes: value
912
+ }),
913
+ decode: (encodedValue) => {
914
+ try {
915
+ return getHeadsCodec().decode(encodedValue).hashes;
916
+ } catch {
917
+ log4.warn("Detected legacy encoding of heads in storage.", void 0, {
918
+ F: __dxlog_file4,
919
+ L: 26,
920
+ S: void 0,
921
+ C: (f, a) => f(...a)
922
+ });
923
+ const concatenatedHeads = Buffer.from(encodedValue).toString("utf8").replace(/"/g, "");
924
+ const heads = [];
925
+ for (let i = 0; i < concatenatedHeads.length; i += 64) {
926
+ heads.push(concatenatedHeads.slice(i, i + 64));
927
+ }
928
+ return heads;
929
+ }
930
+ },
931
+ format: "buffer"
932
+ };
874
933
  var HeadsStore = class {
875
934
  _db;
876
935
  constructor({ db }) {
@@ -1019,7 +1078,7 @@ function _ts_decorate3(decorators, target, key, desc) {
1019
1078
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1020
1079
  return c > 3 && r && Object.defineProperty(target, key, r), r;
1021
1080
  }
1022
- var __dxlog_file4 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/automerge-host.ts";
1081
+ var __dxlog_file5 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/automerge-host.ts";
1023
1082
  var FIND_PARAMS = {
1024
1083
  allowableStates: [
1025
1084
  "ready",
@@ -1032,7 +1091,6 @@ var BUNDLE_SYNC_THRESHOLD = 50;
1032
1091
  var OPTIMIZED_SHARE_POLICY = true;
1033
1092
  var AutomergeHost = class extends Resource3 {
1034
1093
  _db;
1035
- _indexMetadataStore;
1036
1094
  _echoNetworkAdapter;
1037
1095
  _collectionSynchronizer = new CollectionSynchronizer({
1038
1096
  queryCollectionState: this._queryCollectionState.bind(this),
@@ -1074,7 +1132,7 @@ var AutomergeHost = class extends Resource3 {
1074
1132
  */
1075
1133
  _documentsRequested = /* @__PURE__ */ new Map();
1076
1134
  _sharePolicyChangedTask;
1077
- constructor({ db, indexMetadataStore, dataMonitor, peerIdProvider, getSpaceKeyByRootDocumentId }) {
1135
+ constructor({ db, dataMonitor, peerIdProvider, getSpaceKeyByRootDocumentId }) {
1078
1136
  super();
1079
1137
  this._db = db;
1080
1138
  this._storage = new LevelDBStorageAdapter({
@@ -1099,11 +1157,10 @@ var AutomergeHost = class extends Resource3 {
1099
1157
  this._headsStore = new HeadsStore({
1100
1158
  db: db.sublevel("heads")
1101
1159
  });
1102
- this._indexMetadataStore = indexMetadataStore;
1103
1160
  this._peerIdProvider = peerIdProvider;
1104
1161
  this._getSpaceKeyByRootDocumentId = getSpaceKeyByRootDocumentId;
1105
1162
  }
1106
- async _open() {
1163
+ async _open(ctx) {
1107
1164
  this._peerId = `host-${this._peerIdProvider?.() ?? PublicKey2.random().toHex()}`;
1108
1165
  this._onHeadsChangedTask = new DeferredTask(this._ctx, async () => {
1109
1166
  const docHeads = Array.from(this._headsUpdates.entries());
@@ -1144,15 +1201,15 @@ var AutomergeHost = class extends Resource3 {
1144
1201
  }
1145
1202
  await Promise.all(collectionToSync.map(async ({ collectionId, peerId }) => {
1146
1203
  try {
1147
- await this._handleCollectionSync(collectionId, peerId);
1204
+ await this._handleCollectionSync(this._ctx, collectionId, peerId);
1148
1205
  } catch (err) {
1149
- log4.error("failed to sync collection", {
1206
+ log5.error("failed to sync collection", {
1150
1207
  collectionId,
1151
1208
  peerId,
1152
1209
  err
1153
1210
  }, {
1154
- F: __dxlog_file4,
1155
- L: 263,
1211
+ F: __dxlog_file5,
1212
+ L: 252,
1156
1213
  S: this,
1157
1214
  C: (f, a) => f(...a)
1158
1215
  });
@@ -1160,21 +1217,21 @@ var AutomergeHost = class extends Resource3 {
1160
1217
  }));
1161
1218
  });
1162
1219
  this._sharePolicyChangedTask = new DeferredTask(this._ctx, async () => {
1163
- log4("share policy changed", void 0, {
1164
- F: __dxlog_file4,
1165
- L: 270,
1220
+ log5("share policy changed", void 0, {
1221
+ F: __dxlog_file5,
1222
+ L: 259,
1166
1223
  S: this,
1167
1224
  C: (f, a) => f(...a)
1168
1225
  });
1169
1226
  this._repo.shareConfigChanged();
1170
1227
  });
1171
1228
  await this._echoNetworkAdapter.open();
1172
- await this._collectionSynchronizer.open();
1229
+ await this._collectionSynchronizer.open(ctx);
1173
1230
  await this._echoNetworkAdapter.open();
1174
1231
  await this._echoNetworkAdapter.whenConnected();
1175
1232
  }
1176
- async _close() {
1177
- await this._collectionSynchronizer.close();
1233
+ async _close(ctx) {
1234
+ await this._collectionSynchronizer.close(ctx);
1178
1235
  await this._storage.close?.();
1179
1236
  await this._echoNetworkAdapter.close();
1180
1237
  this._syncTask = void 0;
@@ -1190,22 +1247,22 @@ var AutomergeHost = class extends Resource3 {
1190
1247
  get handles() {
1191
1248
  return this._repo.handles;
1192
1249
  }
1193
- async addReplicator(replicator) {
1250
+ async addReplicator(ctx, replicator) {
1194
1251
  invariant2(this.isOpen, "AutomergeHost is not open", {
1195
- F: __dxlog_file4,
1196
- L: 302,
1252
+ F: __dxlog_file5,
1253
+ L: 291,
1197
1254
  S: this,
1198
1255
  A: [
1199
1256
  "this.isOpen",
1200
1257
  "'AutomergeHost is not open'"
1201
1258
  ]
1202
1259
  });
1203
- await this._echoNetworkAdapter.addReplicator(replicator);
1260
+ await this._echoNetworkAdapter.addReplicator(ctx, replicator);
1204
1261
  }
1205
1262
  async removeReplicator(replicator) {
1206
1263
  invariant2(this.isOpen, "AutomergeHost is not open", {
1207
- F: __dxlog_file4,
1208
- L: 307,
1264
+ F: __dxlog_file5,
1265
+ L: 296,
1209
1266
  S: this,
1210
1267
  A: [
1211
1268
  "this.isOpen",
@@ -1219,8 +1276,8 @@ var AutomergeHost = class extends Resource3 {
1219
1276
  */
1220
1277
  async loadDoc(ctx, documentId, opts) {
1221
1278
  invariant2(this.isOpen, "AutomergeHost is not open", {
1222
- F: __dxlog_file4,
1223
- L: 315,
1279
+ F: __dxlog_file5,
1280
+ L: 304,
1224
1281
  S: this,
1225
1282
  A: [
1226
1283
  "this.isOpen",
@@ -1248,12 +1305,12 @@ var AutomergeHost = class extends Resource3 {
1248
1305
  this._sharePolicyChangedTask.schedule();
1249
1306
  }
1250
1307
  } catch (err) {
1251
- log4.error("failed to load document", {
1308
+ log5.error("failed to load document", {
1252
1309
  documentId,
1253
1310
  err
1254
1311
  }, {
1255
- F: __dxlog_file4,
1256
- L: 334,
1312
+ F: __dxlog_file5,
1313
+ L: 323,
1257
1314
  S: this,
1258
1315
  C: (f, a) => f(...a)
1259
1316
  });
@@ -1270,10 +1327,10 @@ var AutomergeHost = class extends Resource3 {
1270
1327
  }
1271
1328
  return handle;
1272
1329
  }
1273
- async exportDoc(ctx, id) {
1330
+ async exportDoc(id) {
1274
1331
  invariant2(this.isOpen, "AutomergeHost is not open", {
1275
- F: __dxlog_file4,
1276
- L: 353,
1332
+ F: __dxlog_file5,
1333
+ L: 342,
1277
1334
  S: this,
1278
1335
  A: [
1279
1336
  "this.isOpen",
@@ -1291,8 +1348,8 @@ var AutomergeHost = class extends Resource3 {
1291
1348
  */
1292
1349
  async createDoc(initialValue, opts) {
1293
1350
  invariant2(this.isOpen, "AutomergeHost is not open", {
1294
- F: __dxlog_file4,
1295
- L: 364,
1351
+ F: __dxlog_file5,
1352
+ L: 353,
1296
1353
  S: this,
1297
1354
  A: [
1298
1355
  "this.isOpen",
@@ -1327,10 +1384,10 @@ var AutomergeHost = class extends Resource3 {
1327
1384
  return handle;
1328
1385
  }
1329
1386
  }
1330
- async waitUntilHeadsReplicated(heads) {
1387
+ async waitUntilHeadsReplicated(ctx, heads) {
1331
1388
  invariant2(this.isOpen, "AutomergeHost is not open", {
1332
- F: __dxlog_file4,
1333
- L: 395,
1389
+ F: __dxlog_file5,
1390
+ L: 384,
1334
1391
  S: this,
1335
1392
  A: [
1336
1393
  "this.isOpen",
@@ -1353,10 +1410,7 @@ var AutomergeHost = class extends Resource3 {
1353
1410
  });
1354
1411
  if (headsToWait.length > 0) {
1355
1412
  await Promise.all(headsToWait.map(async (entry) => {
1356
- const handle = await this.loadDoc(Context2.default(void 0, {
1357
- F: __dxlog_file4,
1358
- L: 413
1359
- }), entry.documentId);
1413
+ const handle = await this.loadDoc(ctx, entry.documentId);
1360
1414
  await waitForHeads(handle, entry.heads);
1361
1415
  }));
1362
1416
  }
@@ -1364,8 +1418,8 @@ var AutomergeHost = class extends Resource3 {
1364
1418
  }
1365
1419
  async reIndexHeads(documentIds) {
1366
1420
  invariant2(this.isOpen, "AutomergeHost is not open", {
1367
- F: __dxlog_file4,
1368
- L: 426,
1421
+ F: __dxlog_file5,
1422
+ L: 415,
1369
1423
  S: this,
1370
1424
  A: [
1371
1425
  "this.isOpen",
@@ -1373,21 +1427,21 @@ var AutomergeHost = class extends Resource3 {
1373
1427
  ]
1374
1428
  });
1375
1429
  for (const documentId of documentIds) {
1376
- log4("re-indexing heads for document", {
1430
+ log5("re-indexing heads for document", {
1377
1431
  documentId
1378
1432
  }, {
1379
- F: __dxlog_file4,
1380
- L: 428,
1433
+ F: __dxlog_file5,
1434
+ L: 417,
1381
1435
  S: this,
1382
1436
  C: (f, a) => f(...a)
1383
1437
  });
1384
1438
  const handle = await this._repo.find(documentId, FIND_PARAMS);
1385
1439
  if (!handle.isReady()) {
1386
- log4.warn("document is not available locally, skipping", {
1440
+ log5.warn("document is not available locally, skipping", {
1387
1441
  documentId
1388
1442
  }, {
1389
- F: __dxlog_file4,
1390
- L: 431,
1443
+ F: __dxlog_file5,
1444
+ L: 420,
1391
1445
  S: this,
1392
1446
  C: (f, a) => f(...a)
1393
1447
  });
@@ -1398,9 +1452,9 @@ var AutomergeHost = class extends Resource3 {
1398
1452
  this._headsStore.setHeads(documentId, heads, batch);
1399
1453
  await batch.write();
1400
1454
  }
1401
- log4("done re-indexing heads", void 0, {
1402
- F: __dxlog_file4,
1403
- L: 440,
1455
+ log5("done re-indexing heads", void 0, {
1456
+ F: __dxlog_file5,
1457
+ L: 429,
1404
1458
  S: this,
1405
1459
  C: (f, a) => f(...a)
1406
1460
  });
@@ -1441,20 +1495,8 @@ var AutomergeHost = class extends Resource3 {
1441
1495
  if (!doc) {
1442
1496
  return;
1443
1497
  }
1444
- const heads = getHeads(doc);
1498
+ const heads = getHeads2(doc);
1445
1499
  this._headsStore.setHeads(handle.documentId, heads, batch);
1446
- const spaceKey = DatabaseDirectory2.getSpaceKey(doc) ?? void 0;
1447
- const objectIds = Object.keys(doc.objects ?? {});
1448
- const encodedIds = objectIds.map((objectId) => objectPointerCodec.encode({
1449
- documentId: handle.documentId,
1450
- objectId,
1451
- spaceKey
1452
- }));
1453
- const idToLastHash = new Map(encodedIds.map((id) => [
1454
- id,
1455
- heads
1456
- ]));
1457
- this._indexMetadataStore.markDirty(idToLastHash, batch);
1458
1500
  }
1459
1501
  _shouldSyncCollection(collectionId, peerId) {
1460
1502
  const peerMetadata = this._repo.peerMetadataByPeerId[peerId];
@@ -1472,7 +1514,6 @@ var AutomergeHost = class extends Resource3 {
1472
1514
  if (!this.isOpen) {
1473
1515
  return void 0;
1474
1516
  }
1475
- this._indexMetadataStore.notifyMarkedDirty();
1476
1517
  const documentId = path[0];
1477
1518
  const handle = this._repo.handles[documentId];
1478
1519
  if (!handle || !handle.isReady()) {
@@ -1482,11 +1523,11 @@ var AutomergeHost = class extends Resource3 {
1482
1523
  if (!document) {
1483
1524
  return;
1484
1525
  }
1485
- const heads = getHeads(document);
1526
+ const heads = getHeads2(document);
1486
1527
  this._headsUpdates.set(documentId, heads);
1487
1528
  invariant2(this._onHeadsChangedTask, "onHeadsChangedTask is not initialized", {
1488
- F: __dxlog_file4,
1489
- L: 530,
1529
+ F: __dxlog_file5,
1530
+ L: 510,
1490
1531
  S: this,
1491
1532
  A: [
1492
1533
  "this._onHeadsChangedTask",
@@ -1529,7 +1570,7 @@ var AutomergeHost = class extends Resource3 {
1529
1570
  /**
1530
1571
  * Flush documents to disk.
1531
1572
  */
1532
- async flush({ documentIds } = {}) {
1573
+ async flush(ctx, { documentIds } = {}) {
1533
1574
  const loadedDocuments = (documentIds ?? Object.keys(this._repo.handles)).filter((documentId) => {
1534
1575
  const handle = this._repo.handles[documentId];
1535
1576
  return handle && handle.isReady();
@@ -1544,7 +1585,7 @@ var AutomergeHost = class extends Resource3 {
1544
1585
  for (const documentId of documentIds) {
1545
1586
  const handle = this._repo.handles[documentId];
1546
1587
  if (handle && handle.isReady() && handle.doc()) {
1547
- result.push(getHeads(handle.doc()));
1588
+ result.push(getHeads2(handle.doc()));
1548
1589
  } else {
1549
1590
  storeRequestIds.push(documentId);
1550
1591
  storeResultIndices.push(result.length);
@@ -1587,12 +1628,12 @@ var AutomergeHost = class extends Resource3 {
1587
1628
  return result;
1588
1629
  }
1589
1630
  for (const [peerId, state] of remoteState) {
1590
- const diff = diffCollectionState(localState, state);
1631
+ const diff2 = diffCollectionState(localState, state);
1591
1632
  result.peers.push({
1592
1633
  peerId,
1593
- missingOnRemote: diff.missingOnRemote.length,
1594
- missingOnLocal: diff.missingOnLocal.length,
1595
- differentDocuments: diff.different.length,
1634
+ missingOnRemote: diff2.missingOnRemote.length,
1635
+ missingOnLocal: diff2.missingOnLocal.length,
1636
+ differentDocuments: diff2.different.length,
1596
1637
  localDocumentCount: Object.entries(localState.documents).filter(([_, heads]) => heads.length > 0).length,
1597
1638
  remoteDocumentCount: Object.entries(state.documents).filter(([_, heads]) => heads.length > 0).length,
1598
1639
  totalDocumentCount: (/* @__PURE__ */ new Set([
@@ -1600,9 +1641,9 @@ var AutomergeHost = class extends Resource3 {
1600
1641
  ...Object.keys(state.documents)
1601
1642
  ])).size,
1602
1643
  unsyncedDocumentCount: (/* @__PURE__ */ new Set([
1603
- ...diff.missingOnLocal,
1604
- ...diff.missingOnRemote,
1605
- ...diff.different
1644
+ ...diff2.missingOnLocal,
1645
+ ...diff2.missingOnRemote,
1646
+ ...diff2.different
1606
1647
  ])).size
1607
1648
  });
1608
1649
  }
@@ -1657,7 +1698,7 @@ var AutomergeHost = class extends Resource3 {
1657
1698
  });
1658
1699
  this._syncTask?.schedule();
1659
1700
  }
1660
- async _handleCollectionSync(collectionId, peerId) {
1701
+ async _handleCollectionSync(ctx, collectionId, peerId) {
1661
1702
  const localState = this._collectionSynchronizer.getLocalCollectionState(collectionId);
1662
1703
  const remoteState = this._collectionSynchronizer.getRemoteCollectionStates(collectionId).get(peerId);
1663
1704
  if (!localState || !remoteState) {
@@ -1672,48 +1713,48 @@ var AutomergeHost = class extends Resource3 {
1672
1713
  ];
1673
1714
  const bundleSyncEnabled = this._echoNetworkAdapter.bundleSyncEnabledForPeer(peerId);
1674
1715
  if (bundleSyncEnabled && missingOnRemote.length >= BUNDLE_SYNC_THRESHOLD) {
1675
- log4("pushing bundle", {
1716
+ log5("pushing bundle", {
1676
1717
  amount: missingOnRemote.length
1677
1718
  }, {
1678
- F: __dxlog_file4,
1679
- L: 742,
1719
+ F: __dxlog_file5,
1720
+ L: 722,
1680
1721
  S: this,
1681
1722
  C: (f, a) => f(...a)
1682
1723
  });
1683
- const { syncInteractively } = await this._pushInBundles(peerId, missingOnRemote);
1724
+ const { syncInteractively } = await this._pushInBundles(ctx, peerId, missingOnRemote);
1684
1725
  toReplicateWithoutBatching.push(...syncInteractively);
1685
1726
  } else {
1686
- log4.verbose("failed to push bundle, replicating interactively", {
1727
+ log5.verbose("failed to push bundle, replicating interactively", {
1687
1728
  collectionId,
1688
1729
  peerId,
1689
1730
  amount: missingOnRemote.length
1690
1731
  }, {
1691
- F: __dxlog_file4,
1692
- L: 746,
1732
+ F: __dxlog_file5,
1733
+ L: 726,
1693
1734
  S: this,
1694
1735
  C: (f, a) => f(...a)
1695
1736
  });
1696
1737
  toReplicateWithoutBatching.push(...missingOnRemote);
1697
1738
  }
1698
1739
  if (bundleSyncEnabled && missingOnLocal.length >= BUNDLE_SYNC_THRESHOLD) {
1699
- log4("pulling bundle", {
1740
+ log5("pulling bundle", {
1700
1741
  amount: missingOnLocal.length
1701
1742
  }, {
1702
- F: __dxlog_file4,
1703
- L: 754,
1743
+ F: __dxlog_file5,
1744
+ L: 734,
1704
1745
  S: this,
1705
1746
  C: (f, a) => f(...a)
1706
1747
  });
1707
- const { syncInteractively } = await this._pullInBundles(peerId, missingOnLocal);
1748
+ const { syncInteractively } = await this._pullInBundles(ctx, peerId, missingOnLocal);
1708
1749
  toReplicateWithoutBatching.push(...syncInteractively);
1709
1750
  } else {
1710
- log4.verbose("failed to pull bundle, replicating interactively", {
1751
+ log5.verbose("failed to pull bundle, replicating interactively", {
1711
1752
  collectionId,
1712
1753
  peerId,
1713
1754
  amount: missingOnLocal.length
1714
1755
  }, {
1715
- F: __dxlog_file4,
1716
- L: 758,
1756
+ F: __dxlog_file5,
1757
+ L: 738,
1717
1758
  S: this,
1718
1759
  C: (f, a) => f(...a)
1719
1760
  });
@@ -1722,14 +1763,14 @@ var AutomergeHost = class extends Resource3 {
1722
1763
  if (toReplicateWithoutBatching.length === 0) {
1723
1764
  return;
1724
1765
  }
1725
- log4("replicating documents after collection sync", {
1766
+ log5("replicating documents after collection sync", {
1726
1767
  collectionId,
1727
1768
  peerId,
1728
1769
  toReplicateWithoutBatching,
1729
1770
  count: toReplicateWithoutBatching.length
1730
1771
  }, {
1731
- F: __dxlog_file4,
1732
- L: 770,
1772
+ F: __dxlog_file5,
1773
+ L: 750,
1733
1774
  S: this,
1734
1775
  C: (f, a) => f(...a)
1735
1776
  });
@@ -1740,7 +1781,7 @@ var AutomergeHost = class extends Resource3 {
1740
1781
  this._sharePolicyChangedTask.schedule();
1741
1782
  }
1742
1783
  // TODO(mykola): Add retries of batches https://gist.github.com/mykola-vrmchk/fde270259e9209fcbf1331e5abbf12cf
1743
- async _pushInBundles(peerId, documentIds) {
1784
+ async _pushInBundles(ctx, peerId, documentIds) {
1744
1785
  const documentsToPush = [
1745
1786
  ...documentIds
1746
1787
  ];
@@ -1751,14 +1792,14 @@ var AutomergeHost = class extends Resource3 {
1751
1792
  if (bundle.length === 0) {
1752
1793
  return;
1753
1794
  }
1754
- await this._pushBundle(peerId, bundle).catch((err) => {
1755
- log4.warn("failed to push bundle, replicating interactively", {
1795
+ await this._pushBundle(ctx, peerId, bundle).catch((err) => {
1796
+ log5.warn("failed to push bundle, replicating interactively", {
1756
1797
  peerId,
1757
1798
  bundle,
1758
1799
  err
1759
1800
  }, {
1760
- F: __dxlog_file4,
1761
- L: 803,
1801
+ F: __dxlog_file5,
1802
+ L: 784,
1762
1803
  S: this,
1763
1804
  C: (f, a) => f(...a)
1764
1805
  });
@@ -1770,18 +1811,18 @@ var AutomergeHost = class extends Resource3 {
1770
1811
  syncInteractively
1771
1812
  };
1772
1813
  }
1773
- async _pushBundle(peerId, documentIds) {
1814
+ async _pushBundle(ctx, peerId, documentIds) {
1774
1815
  if (this._ctx.disposed) {
1775
1816
  return;
1776
1817
  }
1777
1818
  const docs = documentIds.map((documentId) => {
1778
1819
  const handle = this._repo.handles[documentId];
1779
1820
  if (!handle || !handle.isReady()) {
1780
- log4.warn("document not ready, skipping", {
1821
+ log5.warn("document not ready, skipping", {
1781
1822
  documentId
1782
1823
  }, {
1783
- F: __dxlog_file4,
1784
- L: 821,
1824
+ F: __dxlog_file5,
1825
+ L: 802,
1785
1826
  S: this,
1786
1827
  C: (f, a) => f(...a)
1787
1828
  });
@@ -1789,11 +1830,11 @@ var AutomergeHost = class extends Resource3 {
1789
1830
  }
1790
1831
  const doc = handle.doc();
1791
1832
  if (!doc) {
1792
- log4.warn("document not available, skipping", {
1833
+ log5.warn("document not available, skipping", {
1793
1834
  documentId
1794
1835
  }, {
1795
- F: __dxlog_file4,
1796
- L: 826,
1836
+ F: __dxlog_file5,
1837
+ L: 807,
1797
1838
  S: this,
1798
1839
  C: (f, a) => f(...a)
1799
1840
  });
@@ -1802,12 +1843,12 @@ var AutomergeHost = class extends Resource3 {
1802
1843
  return {
1803
1844
  documentId,
1804
1845
  data: save(doc),
1805
- heads: getHeads(doc)
1846
+ heads: getHeads2(doc)
1806
1847
  };
1807
1848
  });
1808
- await this._echoNetworkAdapter.pushBundle(peerId, docs.filter(isNonNullable2));
1849
+ await this._echoNetworkAdapter.pushBundle(ctx, peerId, docs.filter(isNonNullable2));
1809
1850
  }
1810
- async _pullInBundles(peerId, documentIds) {
1851
+ async _pullInBundles(ctx, peerId, documentIds) {
1811
1852
  const documentsToPull = [
1812
1853
  ...documentIds
1813
1854
  ];
@@ -1819,14 +1860,14 @@ var AutomergeHost = class extends Resource3 {
1819
1860
  if (bundle.length === 0) {
1820
1861
  return;
1821
1862
  }
1822
- const result = await this._pullBundle(peerId, bundle).catch((err) => {
1823
- log4.warn("failed to pull bundle, replicating interactively", {
1863
+ const result = await this._pullBundle(ctx, peerId, bundle).catch((err) => {
1864
+ log5.warn("failed to pull bundle, replicating interactively", {
1824
1865
  peerId,
1825
1866
  bundle,
1826
1867
  err
1827
1868
  }, {
1828
- F: __dxlog_file4,
1829
- L: 856,
1869
+ F: __dxlog_file5,
1870
+ L: 838,
1830
1871
  S: this,
1831
1872
  C: (f, a) => f(...a)
1832
1873
  });
@@ -1847,7 +1888,7 @@ var AutomergeHost = class extends Resource3 {
1847
1888
  syncInteractively
1848
1889
  };
1849
1890
  }
1850
- async _pullBundle(peerId, documentIds) {
1891
+ async _pullBundle(ctx, peerId, documentIds) {
1851
1892
  if (this._ctx.disposed) {
1852
1893
  return;
1853
1894
  }
@@ -1855,7 +1896,7 @@ var AutomergeHost = class extends Resource3 {
1855
1896
  documentId,
1856
1897
  []
1857
1898
  ]));
1858
- const bundle = await this._echoNetworkAdapter.pullBundle(peerId, docHeads);
1899
+ const bundle = await this._echoNetworkAdapter.pullBundle(ctx, peerId, docHeads);
1859
1900
  return {
1860
1901
  docsToImport: bundle
1861
1902
  };
@@ -1921,8 +1962,8 @@ var changeIsPresentInDoc = (doc, changeHash) => {
1921
1962
  };
1922
1963
  var decodeCollectionState = (state) => {
1923
1964
  invariant2(typeof state === "object" && state !== null, "Invalid state", {
1924
- F: __dxlog_file4,
1925
- L: 939,
1965
+ F: __dxlog_file5,
1966
+ L: 922,
1926
1967
  S: void 0,
1927
1968
  A: [
1928
1969
  "typeof state === 'object' && state !== null",
@@ -1938,17 +1979,17 @@ var encodeCollectionState = (state) => {
1938
1979
  // src/automerge/mesh-echo-replicator.ts
1939
1980
  import { invariant as invariant5 } from "@dxos/invariant";
1940
1981
  import { PublicKey as PublicKey3 } from "@dxos/keys";
1941
- import { log as log6 } from "@dxos/log";
1982
+ import { log as log7 } from "@dxos/log";
1942
1983
  import { ComplexSet as ComplexSet2, defaultMap as defaultMap3 } from "@dxos/util";
1943
1984
 
1944
1985
  // src/automerge/mesh-echo-replicator-connection.ts
1945
- import * as A2 from "@automerge/automerge";
1986
+ import * as A3 from "@automerge/automerge";
1946
1987
  import { cbor } from "@automerge/automerge-repo";
1947
1988
  import { Resource as Resource4 } from "@dxos/context";
1948
1989
  import { invariant as invariant3 } from "@dxos/invariant";
1949
- import { log as log5 } from "@dxos/log";
1990
+ import { log as log6 } from "@dxos/log";
1950
1991
  import { AutomergeReplicator } from "@dxos/teleport-extension-automerge-replicator";
1951
- var __dxlog_file5 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/mesh-echo-replicator-connection.ts";
1992
+ var __dxlog_file6 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/mesh-echo-replicator-connection.ts";
1952
1993
  var DEFAULT_FACTORY = (params) => new AutomergeReplicator(...params);
1953
1994
  var MeshReplicatorConnection = class extends Resource4 {
1954
1995
  _params;
@@ -1970,7 +2011,7 @@ var MeshReplicatorConnection = class extends Resource4 {
1970
2011
  this.writable = new WritableStream({
1971
2012
  write: async (message, controller) => {
1972
2013
  invariant3(this._isEnabled, "Writing to a disabled connection", {
1973
- F: __dxlog_file5,
2014
+ F: __dxlog_file6,
1974
2015
  L: 51,
1975
2016
  S: this,
1976
2017
  A: [
@@ -1998,12 +2039,12 @@ var MeshReplicatorConnection = class extends Resource4 {
1998
2039
  onStartReplication: async (info, remotePeerId) => {
1999
2040
  this.remoteDeviceKey = remotePeerId;
2000
2041
  this._remotePeerId = info.id;
2001
- log5("onStartReplication", {
2042
+ log6("onStartReplication", {
2002
2043
  id: info.id,
2003
2044
  thisPeerId: this.peerId,
2004
2045
  remotePeerId: remotePeerId.toHex()
2005
2046
  }, {
2006
- F: __dxlog_file5,
2047
+ F: __dxlog_file6,
2007
2048
  L: 80,
2008
2049
  S: this,
2009
2050
  C: (f, a) => f(...a)
@@ -2030,7 +2071,7 @@ var MeshReplicatorConnection = class extends Resource4 {
2030
2071
  }
2031
2072
  get peerId() {
2032
2073
  invariant3(this._remotePeerId != null, "Remote peer has not connected yet.", {
2033
- F: __dxlog_file5,
2074
+ F: __dxlog_file6,
2034
2075
  L: 106,
2035
2076
  S: this,
2036
2077
  A: [
@@ -2058,7 +2099,7 @@ var MeshReplicatorConnection = class extends Resource4 {
2058
2099
  */
2059
2100
  enable() {
2060
2101
  invariant3(this._remotePeerId != null, "Remote peer has not connected yet.", {
2061
- F: __dxlog_file5,
2102
+ F: __dxlog_file6,
2062
2103
  L: 131,
2063
2104
  S: this,
2064
2105
  A: [
@@ -2076,8 +2117,8 @@ var MeshReplicatorConnection = class extends Resource4 {
2076
2117
  }
2077
2118
  };
2078
2119
  var logSendSync = (message) => {
2079
- log5("sendSyncMessage", () => {
2080
- const decodedSyncMessage = message.type === "sync" && message.data ? A2.decodeSyncMessage(message.data) : void 0;
2120
+ log6("sendSyncMessage", () => {
2121
+ const decodedSyncMessage = message.type === "sync" && message.data ? A3.decodeSyncMessage(message.data) : void 0;
2081
2122
  return {
2082
2123
  sync: decodedSyncMessage && {
2083
2124
  headsLength: decodedSyncMessage.heads.length,
@@ -2089,7 +2130,7 @@ var logSendSync = (message) => {
2089
2130
  to: message.targetId
2090
2131
  };
2091
2132
  }, {
2092
- F: __dxlog_file5,
2133
+ F: __dxlog_file6,
2093
2134
  L: 144,
2094
2135
  S: void 0,
2095
2136
  C: (f, a) => f(...a)
@@ -2099,12 +2140,12 @@ var logSendSync = (message) => {
2099
2140
  // src/automerge/space-collection.ts
2100
2141
  import { invariant as invariant4 } from "@dxos/invariant";
2101
2142
  import { SpaceId } from "@dxos/keys";
2102
- var __dxlog_file6 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/space-collection.ts";
2143
+ var __dxlog_file7 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/space-collection.ts";
2103
2144
  var deriveCollectionIdFromSpaceId = (spaceId, rootDocumentId) => rootDocumentId ? `space:${spaceId}:${rootDocumentId}` : `space:${spaceId}`;
2104
2145
  var getSpaceIdFromCollectionId = (collectionId) => {
2105
2146
  const spaceId = collectionId.split(":")[1];
2106
2147
  invariant4(SpaceId.isValid(spaceId), void 0, {
2107
- F: __dxlog_file6,
2148
+ F: __dxlog_file7,
2108
2149
  L: 16,
2109
2150
  S: void 0,
2110
2151
  A: [
@@ -2116,7 +2157,7 @@ var getSpaceIdFromCollectionId = (collectionId) => {
2116
2157
  };
2117
2158
 
2118
2159
  // src/automerge/mesh-echo-replicator.ts
2119
- var __dxlog_file7 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/mesh-echo-replicator.ts";
2160
+ var __dxlog_file8 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/mesh-echo-replicator.ts";
2120
2161
  var MeshEchoReplicator = class {
2121
2162
  /**
2122
2163
  * We might have multiple connections open with a peer (one per space), but there'll be only one enabled
@@ -2134,7 +2175,7 @@ var MeshEchoReplicator = class {
2134
2175
  */
2135
2176
  _authorizedDevices = /* @__PURE__ */ new Map();
2136
2177
  _context = null;
2137
- async connect(context) {
2178
+ async connect(_ctx, context) {
2138
2179
  this._context = context;
2139
2180
  }
2140
2181
  async disconnect() {
@@ -2152,8 +2193,8 @@ var MeshEchoReplicator = class {
2152
2193
  }
2153
2194
  createExtension(extensionFactory) {
2154
2195
  invariant5(this._context, void 0, {
2155
- F: __dxlog_file7,
2156
- L: 68,
2196
+ F: __dxlog_file8,
2197
+ L: 72,
2157
2198
  S: this,
2158
2199
  A: [
2159
2200
  "this._context",
@@ -2164,17 +2205,17 @@ var MeshEchoReplicator = class {
2164
2205
  ownPeerId: this._context.peerId,
2165
2206
  replicatorFactory: extensionFactory,
2166
2207
  onRemoteConnected: async () => {
2167
- log6("onRemoteConnected", {
2208
+ log7("onRemoteConnected", {
2168
2209
  peerId: connection.peerId
2169
2210
  }, {
2170
- F: __dxlog_file7,
2171
- L: 74,
2211
+ F: __dxlog_file8,
2212
+ L: 78,
2172
2213
  S: this,
2173
2214
  C: (f, a) => f(...a)
2174
2215
  });
2175
2216
  invariant5(this._context, void 0, {
2176
- F: __dxlog_file7,
2177
- L: 75,
2217
+ F: __dxlog_file8,
2218
+ L: 79,
2178
2219
  S: this,
2179
2220
  A: [
2180
2221
  "this._context",
@@ -2195,11 +2236,11 @@ var MeshEchoReplicator = class {
2195
2236
  }
2196
2237
  },
2197
2238
  onRemoteDisconnected: async () => {
2198
- log6("onRemoteDisconnected", {
2239
+ log7("onRemoteDisconnected", {
2199
2240
  peerId: connection.peerId
2200
2241
  }, {
2201
- F: __dxlog_file7,
2202
- L: 89,
2242
+ F: __dxlog_file8,
2243
+ L: 93,
2203
2244
  S: this,
2204
2245
  C: (f, a) => f(...a)
2205
2246
  });
@@ -2207,11 +2248,11 @@ var MeshEchoReplicator = class {
2207
2248
  const existingConnections = this._connectionsPerPeer.get(connection.peerId) ?? [];
2208
2249
  const index = existingConnections.indexOf(connection);
2209
2250
  if (index < 0) {
2210
- log6.warn("disconnected connection not found", {
2251
+ log7.warn("disconnected connection not found", {
2211
2252
  peerId: connection.peerId
2212
2253
  }, {
2213
- F: __dxlog_file7,
2214
- L: 97,
2254
+ F: __dxlog_file8,
2255
+ L: 101,
2215
2256
  S: this,
2216
2257
  C: (f, a) => f(...a)
2217
2258
  });
@@ -2228,18 +2269,18 @@ var MeshEchoReplicator = class {
2228
2269
  }
2229
2270
  },
2230
2271
  shouldAdvertise: async (params) => {
2231
- log6("shouldAdvertise", {
2272
+ log7("shouldAdvertise", {
2232
2273
  peerId: connection.peerId,
2233
2274
  documentId: params.documentId
2234
2275
  }, {
2235
- F: __dxlog_file7,
2236
- L: 115,
2276
+ F: __dxlog_file8,
2277
+ L: 119,
2237
2278
  S: this,
2238
2279
  C: (f, a) => f(...a)
2239
2280
  });
2240
2281
  invariant5(this._context, void 0, {
2241
- F: __dxlog_file7,
2242
- L: 116,
2282
+ F: __dxlog_file8,
2283
+ L: 120,
2243
2284
  S: this,
2244
2285
  A: [
2245
2286
  "this._context",
@@ -2253,13 +2294,13 @@ var MeshEchoReplicator = class {
2253
2294
  documentId: params.documentId,
2254
2295
  peerId: connection.peerId
2255
2296
  });
2256
- log6("document not found locally for share policy check", {
2297
+ log7("document not found locally for share policy check", {
2257
2298
  peerId: connection.peerId,
2258
2299
  documentId: params.documentId,
2259
2300
  acceptDocument: remoteDocumentExists
2260
2301
  }, {
2261
- F: __dxlog_file7,
2262
- L: 124,
2302
+ F: __dxlog_file8,
2303
+ L: 128,
2263
2304
  S: this,
2264
2305
  C: (f, a) => f(...a)
2265
2306
  });
@@ -2268,19 +2309,19 @@ var MeshEchoReplicator = class {
2268
2309
  const spaceId = await createIdFromSpaceKey(spaceKey);
2269
2310
  const authorizedDevices = this._authorizedDevices.get(spaceId);
2270
2311
  if (!connection.remoteDeviceKey) {
2271
- log6("device key not found for share policy check", {
2312
+ log7("device key not found for share policy check", {
2272
2313
  peerId: connection.peerId,
2273
2314
  documentId: params.documentId
2274
2315
  }, {
2275
- F: __dxlog_file7,
2276
- L: 141,
2316
+ F: __dxlog_file8,
2317
+ L: 145,
2277
2318
  S: this,
2278
2319
  C: (f, a) => f(...a)
2279
2320
  });
2280
2321
  return false;
2281
2322
  }
2282
2323
  const isAuthorized = authorizedDevices?.has(connection.remoteDeviceKey) ?? false;
2283
- log6("share policy check", {
2324
+ log7("share policy check", {
2284
2325
  localPeer: this._context.peerId,
2285
2326
  remotePeer: connection.peerId,
2286
2327
  documentId: params.documentId,
@@ -2288,16 +2329,16 @@ var MeshEchoReplicator = class {
2288
2329
  spaceKey,
2289
2330
  isAuthorized
2290
2331
  }, {
2291
- F: __dxlog_file7,
2292
- L: 149,
2332
+ F: __dxlog_file8,
2333
+ L: 153,
2293
2334
  S: this,
2294
2335
  C: (f, a) => f(...a)
2295
2336
  });
2296
2337
  return isAuthorized;
2297
2338
  } catch (err) {
2298
- log6.catch(err, void 0, {
2299
- F: __dxlog_file7,
2300
- L: 159,
2339
+ log7.catch(err, void 0, {
2340
+ F: __dxlog_file8,
2341
+ L: 163,
2301
2342
  S: this,
2302
2343
  C: (f, a) => f(...a)
2303
2344
  });
@@ -2308,12 +2349,12 @@ var MeshEchoReplicator = class {
2308
2349
  const spaceId = getSpaceIdFromCollectionId(collectionId);
2309
2350
  const authorizedDevices = this._authorizedDevices.get(spaceId);
2310
2351
  if (!connection.remoteDeviceKey) {
2311
- log6("device key not found for collection sync check", {
2352
+ log7("device key not found for collection sync check", {
2312
2353
  peerId: connection.peerId,
2313
2354
  collectionId
2314
2355
  }, {
2315
- F: __dxlog_file7,
2316
- L: 169,
2356
+ F: __dxlog_file8,
2357
+ L: 173,
2317
2358
  S: this,
2318
2359
  C: (f, a) => f(...a)
2319
2360
  });
@@ -2327,12 +2368,12 @@ var MeshEchoReplicator = class {
2327
2368
  return connection.replicatorExtension;
2328
2369
  }
2329
2370
  async authorizeDevice(spaceKey, deviceKey) {
2330
- log6("authorizeDevice", {
2371
+ log7("authorizeDevice", {
2331
2372
  spaceKey,
2332
2373
  deviceKey
2333
2374
  }, {
2334
- F: __dxlog_file7,
2335
- L: 186,
2375
+ F: __dxlog_file8,
2376
+ L: 190,
2336
2377
  S: this,
2337
2378
  C: (f, a) => f(...a)
2338
2379
  });
@@ -2712,13 +2753,13 @@ var getByteCount = (message) => {
2712
2753
  };
2713
2754
 
2714
2755
  // src/db-host/documents-synchronizer.ts
2715
- import { next as A3 } from "@automerge/automerge";
2756
+ import { next as A4 } from "@automerge/automerge";
2716
2757
  import { UpdateScheduler } from "@dxos/async";
2717
- import { Context as Context3, LifecycleState as LifecycleState2, Resource as Resource5 } from "@dxos/context";
2758
+ import { LifecycleState as LifecycleState2, Resource as Resource5 } from "@dxos/context";
2718
2759
  import { invariant as invariant6 } from "@dxos/invariant";
2719
- import { log as log7 } from "@dxos/log";
2760
+ import { log as log8 } from "@dxos/log";
2720
2761
  import { retry } from "@dxos/util";
2721
- var __dxlog_file8 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/documents-synchronizer.ts";
2762
+ var __dxlog_file9 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/documents-synchronizer.ts";
2722
2763
  var MAX_UPDATE_FREQ = 10;
2723
2764
  var WRAP_AROUND_RETRY_LIMIT = 3;
2724
2765
  var WRAP_AROUND_RETRY_INITIAL_DELAY = 100;
@@ -2746,28 +2787,25 @@ var DocumentsSynchronizer = class extends Resource5 {
2746
2787
  exponent: 2
2747
2788
  }, async () => {
2748
2789
  try {
2749
- log7("loading document", {
2790
+ log8("loading document", {
2750
2791
  documentId
2751
2792
  }, {
2752
- F: __dxlog_file8,
2793
+ F: __dxlog_file9,
2753
2794
  L: 62,
2754
2795
  S: this,
2755
2796
  C: (f, a) => f(...a)
2756
2797
  });
2757
- const doc = await this._params.automergeHost.loadDoc(Context3.default(void 0, {
2758
- F: __dxlog_file8,
2759
- L: 64
2760
- }), documentId, {
2798
+ const doc = await this._params.automergeHost.loadDoc(this._ctx, documentId, {
2761
2799
  fetchFromNetwork: true
2762
2800
  });
2763
2801
  this._startSync(doc);
2764
2802
  this._pendingUpdates.add(doc.documentId);
2765
2803
  this._sendUpdatesJob.trigger();
2766
2804
  } catch (err) {
2767
- log7.warn("failed to load document", {
2805
+ log8.warn("failed to load document", {
2768
2806
  err
2769
2807
  }, {
2770
- F: __dxlog_file8,
2808
+ F: __dxlog_file9,
2771
2809
  L: 72,
2772
2810
  S: this,
2773
2811
  C: (f, a) => f(...a)
@@ -2776,8 +2814,8 @@ var DocumentsSynchronizer = class extends Resource5 {
2776
2814
  }
2777
2815
  });
2778
2816
  } catch (err) {
2779
- log7.catch(err, void 0, {
2780
- F: __dxlog_file8,
2817
+ log8.catch(err, void 0, {
2818
+ F: __dxlog_file9,
2781
2819
  L: 78,
2782
2820
  S: this,
2783
2821
  C: (f, a) => f(...a)
@@ -2801,21 +2839,21 @@ var DocumentsSynchronizer = class extends Resource5 {
2801
2839
  await this._sendUpdatesJob.join();
2802
2840
  this._syncStates.clear();
2803
2841
  }
2804
- async update(updates) {
2842
+ async update(ctx, updates) {
2805
2843
  for (const { documentId, mutation } of updates) {
2806
2844
  await this._writeMutation(documentId, mutation);
2807
2845
  }
2808
- await this._params.automergeHost.flush({
2846
+ await this._params.automergeHost.flush(ctx, {
2809
2847
  documentIds: updates.map(({ documentId }) => documentId)
2810
2848
  });
2811
2849
  }
2812
2850
  _startSync(doc) {
2813
2851
  if (this._syncStates.has(doc.documentId)) {
2814
- log7("Document already being synced", {
2852
+ log8("Document already being synced", {
2815
2853
  documentId: doc.documentId
2816
2854
  }, {
2817
- F: __dxlog_file8,
2818
- L: 113,
2855
+ F: __dxlog_file9,
2856
+ L: 115,
2819
2857
  S: this,
2820
2858
  C: (f, a) => f(...a)
2821
2859
  });
@@ -2858,8 +2896,8 @@ var DocumentsSynchronizer = class extends Resource5 {
2858
2896
  _getPendingChanges(documentId) {
2859
2897
  const syncState = this._syncStates.get(documentId);
2860
2898
  invariant6(syncState, "Sync state for document not found", {
2861
- F: __dxlog_file8,
2862
- L: 155,
2899
+ F: __dxlog_file9,
2900
+ L: 157,
2863
2901
  S: this,
2864
2902
  A: [
2865
2903
  "syncState",
@@ -2871,48 +2909,48 @@ var DocumentsSynchronizer = class extends Resource5 {
2871
2909
  return;
2872
2910
  }
2873
2911
  const doc = handle.doc();
2874
- const mutation = syncState.lastSentHead ? A3.saveSince(doc, syncState.lastSentHead) : A3.save(doc);
2912
+ const mutation = syncState.lastSentHead ? A4.saveSince(doc, syncState.lastSentHead) : A4.save(doc);
2875
2913
  if (mutation.length === 0) {
2876
2914
  return;
2877
2915
  }
2878
- syncState.lastSentHead = A3.getHeads(doc);
2916
+ syncState.lastSentHead = A4.getHeads(doc);
2879
2917
  return mutation;
2880
2918
  }
2881
2919
  async _writeMutation(documentId, mutation) {
2882
2920
  if (this._lifecycleState === LifecycleState2.CLOSED) {
2883
2921
  return;
2884
2922
  }
2885
- log7("write mutation", {
2923
+ log8("write mutation", {
2886
2924
  documentId
2887
2925
  }, {
2888
- F: __dxlog_file8,
2889
- L: 173,
2926
+ F: __dxlog_file9,
2927
+ L: 175,
2890
2928
  S: this,
2891
2929
  C: (f, a) => f(...a)
2892
2930
  });
2893
2931
  const syncState = this._syncStates.get(documentId);
2894
2932
  invariant6(syncState, "Sync state for document not found", {
2895
- F: __dxlog_file8,
2896
- L: 176,
2933
+ F: __dxlog_file9,
2934
+ L: 178,
2897
2935
  S: this,
2898
2936
  A: [
2899
2937
  "syncState",
2900
2938
  "'Sync state for document not found'"
2901
2939
  ]
2902
2940
  });
2903
- const headsBefore = A3.getHeads(syncState.handle.doc());
2941
+ const headsBefore = A4.getHeads(syncState.handle.doc());
2904
2942
  await this._params.automergeHost.createDoc(mutation, {
2905
2943
  documentId,
2906
2944
  preserveHistory: true
2907
2945
  });
2908
- if (A3.equals(headsBefore, syncState.lastSentHead)) {
2909
- syncState.lastSentHead = A3.getHeads(syncState.handle.doc());
2946
+ if (A4.equals(headsBefore, syncState.lastSentHead)) {
2947
+ syncState.lastSentHead = A4.getHeads(syncState.handle.doc());
2910
2948
  }
2911
2949
  }
2912
2950
  };
2913
2951
 
2914
2952
  // src/db-host/data-service.ts
2915
- var __dxlog_file9 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/data-service.ts";
2953
+ var __dxlog_file10 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/data-service.ts";
2916
2954
  var DataServiceImpl = class {
2917
2955
  /**
2918
2956
  * Map of subscriptions.
@@ -2936,9 +2974,9 @@ var DataServiceImpl = class {
2936
2974
  synchronizer.open().then(() => {
2937
2975
  this._subscriptions.set(request.subscriptionId, synchronizer);
2938
2976
  ready();
2939
- }).catch((err) => log8.catch(err, void 0, {
2940
- F: __dxlog_file9,
2941
- L: 74,
2977
+ }).catch((err) => log9.catch(err, void 0, {
2978
+ F: __dxlog_file10,
2979
+ L: 75,
2942
2980
  S: this,
2943
2981
  C: (f, a) => f(...a)
2944
2982
  }));
@@ -2948,8 +2986,8 @@ var DataServiceImpl = class {
2948
2986
  async updateSubscription(request) {
2949
2987
  const synchronizer = this._subscriptions.get(request.subscriptionId);
2950
2988
  invariant7(synchronizer, "Subscription not found", {
2951
- F: __dxlog_file9,
2952
- L: 81,
2989
+ F: __dxlog_file10,
2990
+ L: 82,
2953
2991
  S: this,
2954
2992
  A: [
2955
2993
  "synchronizer",
@@ -2975,18 +3013,24 @@ var DataServiceImpl = class {
2975
3013
  }
2976
3014
  const synchronizer = this._subscriptions.get(request.subscriptionId);
2977
3015
  invariant7(synchronizer, "Subscription not found", {
2978
- F: __dxlog_file9,
2979
- L: 101,
3016
+ F: __dxlog_file10,
3017
+ L: 102,
2980
3018
  S: this,
2981
3019
  A: [
2982
3020
  "synchronizer",
2983
3021
  "'Subscription not found'"
2984
3022
  ]
2985
3023
  });
2986
- await synchronizer.update(request.updates);
3024
+ await synchronizer.update(Context.default(void 0, {
3025
+ F: __dxlog_file10,
3026
+ L: 104
3027
+ }), request.updates);
2987
3028
  }
2988
3029
  async flush(request) {
2989
- await this._automergeHost.flush(request);
3030
+ await this._automergeHost.flush(Context.default(void 0, {
3031
+ F: __dxlog_file10,
3032
+ L: 108
3033
+ }), request);
2990
3034
  }
2991
3035
  async getDocumentHeads(request) {
2992
3036
  const documentIds = request.documentIds;
@@ -3008,7 +3052,10 @@ var DataServiceImpl = class {
3008
3052
  };
3009
3053
  }
3010
3054
  async waitUntilHeadsReplicated(request, options) {
3011
- await this._automergeHost.waitUntilHeadsReplicated(request.heads);
3055
+ await this._automergeHost.waitUntilHeadsReplicated(Context.default(void 0, {
3056
+ F: __dxlog_file10,
3057
+ L: 128
3058
+ }), request.heads);
3012
3059
  }
3013
3060
  async reIndexHeads(request, options) {
3014
3061
  await this._automergeHost.reIndexHeads(request.documentIds ?? []);
@@ -3020,8 +3067,8 @@ var DataServiceImpl = class {
3020
3067
  return new Stream(({ ctx, next, ready }) => {
3021
3068
  const spaceId = request.spaceId;
3022
3069
  invariant7(SpaceId2.isValid(spaceId), void 0, {
3023
- F: __dxlog_file9,
3024
- L: 141,
3070
+ F: __dxlog_file10,
3071
+ L: 142,
3025
3072
  S: this,
3026
3073
  A: [
3027
3074
  "SpaceId.isValid(spaceId)",
@@ -3056,129 +3103,41 @@ var DataServiceImpl = class {
3056
3103
  };
3057
3104
 
3058
3105
  // src/db-host/echo-host.ts
3059
- import { DeferredTask as DeferredTask3, sleep } from "@dxos/async";
3060
- import { Context as Context8, LifecycleState as LifecycleState5, Resource as Resource9 } from "@dxos/context";
3106
+ import * as SqlClient from "@effect/sql/SqlClient";
3107
+ import { asyncTimeout as asyncTimeout2, DeferredTask as DeferredTask3, sleep } from "@dxos/async";
3108
+ import { LifecycleState as LifecycleState5, Resource as Resource9 } from "@dxos/context";
3061
3109
  import { todo } from "@dxos/debug";
3062
- import { SpaceDocVersion as SpaceDocVersion4, createIdFromSpaceKey as createIdFromSpaceKey2 } from "@dxos/echo-protocol";
3110
+ import { SpaceDocVersion as SpaceDocVersion3, createIdFromSpaceKey as createIdFromSpaceKey2 } from "@dxos/echo-protocol";
3063
3111
  import { RuntimeProvider as RuntimeProvider3 } from "@dxos/effect";
3064
3112
  import { FeedStore } from "@dxos/feed";
3065
3113
  import { IndexEngine } from "@dxos/index-core";
3066
- import { IndexMetadataStore, IndexStore, Indexer } from "@dxos/indexing";
3067
- import { invariant as invariant14 } from "@dxos/invariant";
3114
+ import { invariant as invariant13 } from "@dxos/invariant";
3068
3115
  import { log as log14 } from "@dxos/log";
3069
- import { IndexKind } from "@dxos/protocols/proto/dxos/echo/indexing";
3070
3116
  import { trace as trace5 } from "@dxos/tracing";
3071
3117
 
3072
- // src/db-host/documents-iterator.ts
3073
- import * as A4 from "@automerge/automerge";
3074
- import { Context as Context4 } from "@dxos/context";
3075
- import { DatabaseDirectory as DatabaseDirectory3, SpaceDocVersion as SpaceDocVersion2 } from "@dxos/echo-protocol";
3076
- import { invariant as invariant8 } from "@dxos/invariant";
3077
- import { log as log9 } from "@dxos/log";
3078
- import { ObjectPointerVersion, objectPointerCodec as objectPointerCodec2 } from "@dxos/protocols";
3079
- var __dxlog_file10 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/documents-iterator.ts";
3080
- var LOG_VIEW_OPERATION_THRESHOLD = 300;
3081
- var createSelectedDocumentsIterator = (automergeHost) => (
3082
- /**
3083
- * Get object data blobs from Automerge Repo by ids.
3084
- */
3085
- // TODO(mykola): Unload automerge handles after usage.
3086
- async function* loadDocuments(objects) {
3087
- for (const [id, heads] of objects.entries()) {
3088
- try {
3089
- const { documentId, objectId } = objectPointerCodec2.decode(id);
3090
- const handle = await automergeHost.loadDoc(Context4.default(void 0, {
3091
- F: __dxlog_file10,
3092
- L: 31
3093
- }), documentId, {
3094
- fetchFromNetwork: true
3095
- });
3096
- let doc = handle.doc();
3097
- invariant8(doc, void 0, {
3098
- F: __dxlog_file10,
3099
- L: 36,
3100
- S: this,
3101
- A: [
3102
- "doc",
3103
- ""
3104
- ]
3105
- });
3106
- const currentHeads = A4.getHeads(doc);
3107
- if (!A4.equals(currentHeads, heads)) {
3108
- const begin = Date.now();
3109
- doc = A4.view(doc, heads);
3110
- const end = Date.now();
3111
- if (end - begin > LOG_VIEW_OPERATION_THRESHOLD) {
3112
- log9("Checking out document version is taking too long", {
3113
- duration: end - begin,
3114
- requestedHeads: heads,
3115
- originalHeads: currentHeads
3116
- }, {
3117
- F: __dxlog_file10,
3118
- L: 47,
3119
- S: this,
3120
- C: (f, a) => f(...a)
3121
- });
3122
- }
3123
- }
3124
- if (doc.version !== SpaceDocVersion2.CURRENT) {
3125
- continue;
3126
- }
3127
- if (!doc.objects?.[objectId]) {
3128
- continue;
3129
- }
3130
- let newId = id;
3131
- if (objectPointerCodec2.getVersion(id) === ObjectPointerVersion.V0) {
3132
- const spaceKey = DatabaseDirectory3.getSpaceKey(doc) ?? void 0;
3133
- newId = objectPointerCodec2.encode({
3134
- documentId,
3135
- objectId,
3136
- spaceKey
3137
- });
3138
- }
3139
- yield [
3140
- {
3141
- id: newId,
3142
- object: doc.objects[objectId],
3143
- heads
3144
- }
3145
- ];
3146
- } catch (error) {
3147
- log9.error("Error loading document", {
3148
- heads,
3149
- id,
3150
- error
3151
- }, {
3152
- F: __dxlog_file10,
3153
- L: 73,
3154
- S: this,
3155
- C: (f, a) => f(...a)
3156
- });
3157
- }
3158
- }
3159
- }
3160
- );
3161
-
3162
3118
  // src/db-host/local-queue-service.ts
3163
3119
  import * as Effect2 from "effect/Effect";
3164
3120
  import * as Function from "effect/Function";
3165
- import { ATTR_META } from "@dxos/echo/internal";
3121
+ import { EchoFeedCodec } from "@dxos/echo-protocol";
3166
3122
  import { RuntimeProvider } from "@dxos/effect";
3167
- import { invariant as invariant9 } from "@dxos/invariant";
3168
- import { KEY_QUEUE_POSITION } from "@dxos/protocols";
3123
+ import { assertArgument, invariant as invariant8 } from "@dxos/invariant";
3124
+ import { FeedProtocol } from "@dxos/protocols";
3125
+ import { Context as Context2 } from "@dxos/context";
3169
3126
  var __dxlog_file11 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/local-queue-service.ts";
3170
3127
  var LocalQueueServiceImpl = class {
3171
3128
  #runtime;
3172
3129
  #feedStore;
3173
- constructor(runtime, feedStore) {
3130
+ #syncQueue;
3131
+ constructor(runtime, feedStore, syncQueue) {
3174
3132
  this.#runtime = runtime;
3175
3133
  this.#feedStore = feedStore;
3134
+ this.#syncQueue = syncQueue;
3176
3135
  }
3177
3136
  queryQueue(request) {
3178
3137
  const { query } = request;
3179
- invariant9(query, "query is required", {
3138
+ invariant8(query, "query is required", {
3180
3139
  F: __dxlog_file11,
3181
- L: 37,
3140
+ L: 47,
3182
3141
  S: this,
3183
3142
  A: [
3184
3143
  "query",
@@ -3190,6 +3149,7 @@ var LocalQueueServiceImpl = class {
3190
3149
  const cursor = query.after ? parseInt(query.after) : -1;
3191
3150
  const result = yield* this.#feedStore.query({
3192
3151
  requestId: crypto.randomUUID(),
3152
+ feedNamespace: request.query.queuesNamespace || FeedProtocol.WellKnownNamespaces.data,
3193
3153
  spaceId,
3194
3154
  query: {
3195
3155
  feedIds: queueIds ?? []
@@ -3197,13 +3157,7 @@ var LocalQueueServiceImpl = class {
3197
3157
  position: cursor,
3198
3158
  limit: query.limit
3199
3159
  });
3200
- const objects = result.blocks.map((block) => {
3201
- const data = JSON.parse(new TextDecoder().decode(block.data));
3202
- if (block.position !== null) {
3203
- setQueuePosition(data, block.position);
3204
- }
3205
- return data;
3206
- });
3160
+ const objects = result.blocks.map((block) => EchoFeedCodec.decode(block.data, block.position ?? void 0));
3207
3161
  const lastBlock = result.blocks[result.blocks.length - 1];
3208
3162
  const nextCursor = lastBlock && lastBlock.position != null ? String(lastBlock.position) : null;
3209
3163
  return Function.identity({
@@ -3216,85 +3170,65 @@ var LocalQueueServiceImpl = class {
3216
3170
  }
3217
3171
  insertIntoQueue(request) {
3218
3172
  const { subspaceTag, spaceId, queueId, objects } = request;
3173
+ const feedNamespace = subspaceTag ?? FeedProtocol.WellKnownNamespaces.data;
3174
+ assertArgument(FeedProtocol.isWellKnownNamespace(feedNamespace), "request.subspaceTag", "expected a well-known queue namespace");
3219
3175
  return RuntimeProvider.runPromise(this.#runtime)(Effect2.gen(this, function* () {
3220
- const messages = objects.map((obj) => {
3221
- const data = structuredClone(obj);
3222
- if (data[ATTR_META]?.keys?.find((key) => key.source === KEY_QUEUE_POSITION)) {
3223
- data[ATTR_META].keys = data[ATTR_META].keys.filter((key) => key.source !== KEY_QUEUE_POSITION);
3224
- }
3225
- return {
3226
- spaceId,
3227
- feedId: queueId,
3228
- feedNamespace: subspaceTag,
3229
- data: new TextEncoder().encode(JSON.stringify(obj))
3230
- };
3231
- });
3176
+ const messages = objects.map((obj) => ({
3177
+ spaceId,
3178
+ feedId: queueId,
3179
+ feedNamespace,
3180
+ data: EchoFeedCodec.encode(obj)
3181
+ }));
3232
3182
  yield* this.#feedStore.appendLocal(messages);
3233
3183
  }));
3234
3184
  }
3235
3185
  deleteFromQueue(request) {
3236
3186
  const { subspaceTag, spaceId, queueId, objectIds } = request;
3187
+ const feedNamespace = subspaceTag ?? FeedProtocol.WellKnownNamespaces.data;
3188
+ assertArgument(FeedProtocol.isWellKnownNamespace(feedNamespace), "request.subspaceTag", "expected a well-known queue namespace");
3237
3189
  return RuntimeProvider.runPromise(this.#runtime)(Effect2.gen(this, function* () {
3238
3190
  const messages = objectIds.map((id) => ({
3239
3191
  spaceId,
3240
3192
  feedId: queueId,
3241
- feedNamespace: subspaceTag,
3242
- data: new TextEncoder().encode(JSON.stringify({
3193
+ feedNamespace,
3194
+ data: EchoFeedCodec.encode({
3243
3195
  id,
3244
3196
  "@deleted": true
3245
- }))
3197
+ })
3246
3198
  }));
3247
3199
  yield* this.#feedStore.appendLocal(messages);
3248
3200
  }));
3249
3201
  }
3250
- };
3251
- var setQueuePosition = (obj, position) => {
3252
- obj[ATTR_META] ??= {
3253
- keys: []
3254
- };
3255
- obj[ATTR_META].keys ??= [];
3256
- for (let i = 0; i < obj[ATTR_META].keys.length; i++) {
3257
- const key = obj[ATTR_META].keys[i];
3258
- if (key.source === KEY_QUEUE_POSITION) {
3259
- obj[ATTR_META].keys.splice(i, 1);
3260
- i--;
3261
- }
3202
+ async syncQueue(request) {
3203
+ await this.#syncQueue?.(Context2.default(void 0, {
3204
+ F: __dxlog_file11,
3205
+ L: 124
3206
+ }), request);
3262
3207
  }
3263
- obj[ATTR_META].keys.push({
3264
- source: KEY_QUEUE_POSITION,
3265
- id: position.toString()
3266
- });
3267
3208
  };
3268
3209
 
3269
3210
  // src/db-host/query-service.ts
3270
- import { getHeads as getHeads3 } from "@automerge/automerge";
3271
3211
  import * as Schema from "effect/Schema";
3272
3212
  import { DeferredTask as DeferredTask2, scheduleMicroTask, synchronized as synchronized2 } from "@dxos/async";
3273
3213
  import { Stream as Stream2 } from "@dxos/codec-protobuf/stream";
3274
- import { Context as Context6, Resource as Resource7 } from "@dxos/context";
3214
+ import { Resource as Resource7 } from "@dxos/context";
3275
3215
  import { raise } from "@dxos/debug";
3276
- import { DatabaseDirectory as DatabaseDirectory5, QueryAST } from "@dxos/echo-protocol";
3216
+ import { QueryAST as QueryAST2 } from "@dxos/echo-protocol";
3277
3217
  import { log as log11 } from "@dxos/log";
3278
- import { objectPointerCodec as objectPointerCodec4 } from "@dxos/protocols";
3279
3218
  import { trace as trace4 } from "@dxos/tracing";
3280
3219
 
3281
3220
  // src/query/query-executor.ts
3282
- import * as Match from "effect/Match";
3283
3221
  import * as Runtime from "effect/Runtime";
3284
- import { Context as Context5, ContextDisposedError, LifecycleState as LifecycleState3, Resource as Resource6 } from "@dxos/context";
3285
- import { ATTR_RELATION_SOURCE, ATTR_RELATION_TARGET } from "@dxos/echo/internal";
3286
- import { DatabaseDirectory as DatabaseDirectory4, ObjectStructure, isEncodedReference } from "@dxos/echo-protocol";
3222
+ import { ContextDisposedError, LifecycleState as LifecycleState3, Resource as Resource6 } from "@dxos/context";
3223
+ import { Query as Query2 } from "@dxos/echo";
3224
+ import { ATTR_PARENT, ATTR_RELATION_SOURCE, ATTR_RELATION_TARGET } from "@dxos/echo/internal";
3225
+ import { DatabaseDirectory as DatabaseDirectory3, EncodedReference, ObjectStructure, isEncodedReference } from "@dxos/echo-protocol";
3287
3226
  import { runAndForwardErrors, unwrapExit } from "@dxos/effect";
3288
- import { EscapedPropPath } from "@dxos/indexing";
3289
- import { invariant as invariant11 } from "@dxos/invariant";
3290
- import { DXN, PublicKey as PublicKey4 } from "@dxos/keys";
3291
- import { log as log10 } from "@dxos/log";
3292
- import { objectPointerCodec as objectPointerCodec3 } from "@dxos/protocols";
3293
- import { getDeep, isNonNullable as isNonNullable3 } from "@dxos/util";
3294
-
3295
- // src/query/query-planner.ts
3296
- import { Order } from "@dxos/echo";
3227
+ import { EscapedPropPath } from "@dxos/index-core";
3297
3228
  import { invariant as invariant10 } from "@dxos/invariant";
3229
+ import { DXN } from "@dxos/keys";
3230
+ import { log as log10 } from "@dxos/log";
3231
+ import { compositeKey, getDeep, isNonNullable as isNonNullable3 } from "@dxos/util";
3298
3232
 
3299
3233
  // src/query/errors.ts
3300
3234
  import { BaseError } from "@dxos/errors";
@@ -3303,6 +3237,11 @@ var QueryError = class extends BaseError.extend("QueryError") {
3303
3237
  var InvalidQueryError = class extends QueryError.extend("InvalidQueryError") {
3304
3238
  };
3305
3239
 
3240
+ // src/query/query-planner.ts
3241
+ import { Order, Query } from "@dxos/echo";
3242
+ import { QueryAST } from "@dxos/echo-protocol";
3243
+ import { invariant as invariant9 } from "@dxos/invariant";
3244
+
3306
3245
  // src/query/plan.ts
3307
3246
  (function(QueryPlan2) {
3308
3247
  QueryPlan2.Plan = Object.freeze({
@@ -3326,6 +3265,24 @@ var QueryPlan;
3326
3265
 
3327
3266
  // src/query/query-planner.ts
3328
3267
  var __dxlog_file12 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/query/query-planner.ts";
3268
+ var queryTooComplexError = (query) => {
3269
+ if (query === null) {
3270
+ return new QueryError({
3271
+ message: "Query too complex",
3272
+ context: {
3273
+ query: null
3274
+ }
3275
+ });
3276
+ }
3277
+ const prettyQuery = Query.pretty(Query.fromAst(query));
3278
+ return new QueryError({
3279
+ message: `Query too complex: ${prettyQuery}`,
3280
+ context: {
3281
+ query,
3282
+ prettyQuery
3283
+ }
3284
+ });
3285
+ };
3329
3286
  var DEFAULT_OPTIONS = {
3330
3287
  defaultTextSearchKind: "full-text"
3331
3288
  };
@@ -3338,6 +3295,7 @@ var QueryPlanner = class {
3338
3295
  };
3339
3296
  }
3340
3297
  createPlan(query) {
3298
+ this._validateQueryScoped(query);
3341
3299
  let plan = this._generate(query, {
3342
3300
  ...DEFAULT_CONTEXT,
3343
3301
  originalQuery: query
@@ -3364,6 +3322,8 @@ var QueryPlanner = class {
3364
3322
  return this._generateRelationTraversalClause(query, context);
3365
3323
  case "reference-traversal":
3366
3324
  return this._generateReferenceTraversalClause(query, context);
3325
+ case "hierarchy-traversal":
3326
+ return this._generateHierarchyTraversalClause(query, context);
3367
3327
  case "union":
3368
3328
  return this._generateUnionClause(query, context);
3369
3329
  case "set-difference":
@@ -3372,6 +3332,8 @@ var QueryPlanner = class {
3372
3332
  return this._generateOrderClause(query, context);
3373
3333
  case "limit":
3374
3334
  return this._generateLimitClause(query, context);
3335
+ case "from":
3336
+ return this._generateFromClause(query, context);
3375
3337
  default:
3376
3338
  throw new QueryError({
3377
3339
  message: `Unsupported query type: ${query.type}`,
@@ -3385,20 +3347,26 @@ var QueryPlanner = class {
3385
3347
  const newContext = {
3386
3348
  ...context
3387
3349
  };
3388
- if (query.options.spaceIds) {
3389
- newContext.selectionSpaces = query.options.spaceIds;
3390
- }
3391
- if (query.options.allQueuesFromSpaces !== void 0) {
3392
- newContext.selectionAllQueuesFromSpaces = query.options.allQueuesFromSpaces;
3393
- }
3394
- if (query.options.queues) {
3395
- newContext.selectionQueues = query.options.queues;
3396
- }
3397
3350
  if (query.options.deleted) {
3398
3351
  newContext.deletedHandling = query.options.deleted;
3399
3352
  }
3400
3353
  return this._generate(query.query, newContext);
3401
3354
  }
3355
+ _generateFromClause(query, context) {
3356
+ if (query.from._tag === "scope") {
3357
+ return this._generate(query.query, {
3358
+ ...context,
3359
+ scope: query.from.scope
3360
+ });
3361
+ }
3362
+ const subquery = query.from.query;
3363
+ const rewritten = QueryAST.map(query.query, (node) => node.type === "select" ? {
3364
+ type: "filter",
3365
+ selection: subquery,
3366
+ filter: node.filter
3367
+ } : node);
3368
+ return this._generate(rewritten, context);
3369
+ }
3402
3370
  _generateSelectClause(query, context) {
3403
3371
  return this._generateSelectionFromFilter(query.filter, context);
3404
3372
  }
@@ -3417,20 +3385,13 @@ var QueryPlanner = class {
3417
3385
  ]);
3418
3386
  }
3419
3387
  if (context.selectionInverted) {
3420
- throw new QueryError({
3421
- message: "Query too complex",
3422
- context: {
3423
- query: context.originalQuery
3424
- }
3425
- });
3388
+ throw queryTooComplexError(context.originalQuery);
3426
3389
  }
3427
3390
  if (filter2.id && filter2.id?.length > 0) {
3428
3391
  return QueryPlan.Plan.make([
3429
3392
  {
3430
3393
  _tag: "SelectStep",
3431
- spaces: context.selectionSpaces,
3432
- allQueuesFromSpaces: context.selectionAllQueuesFromSpaces,
3433
- queues: context.selectionQueues,
3394
+ scope: context.scope,
3434
3395
  selector: {
3435
3396
  _tag: "IdSelector",
3436
3397
  objectIds: filter2.id
@@ -3449,9 +3410,7 @@ var QueryPlanner = class {
3449
3410
  return QueryPlan.Plan.make([
3450
3411
  {
3451
3412
  _tag: "SelectStep",
3452
- spaces: context.selectionSpaces,
3453
- allQueuesFromSpaces: context.selectionAllQueuesFromSpaces,
3454
- queues: context.selectionQueues,
3413
+ scope: context.scope,
3455
3414
  selector: {
3456
3415
  _tag: "TypeSelector",
3457
3416
  typename: [
@@ -3473,9 +3432,7 @@ var QueryPlanner = class {
3473
3432
  return QueryPlan.Plan.make([
3474
3433
  {
3475
3434
  _tag: "SelectStep",
3476
- spaces: context.selectionSpaces,
3477
- allQueuesFromSpaces: context.selectionAllQueuesFromSpaces,
3478
- queues: context.selectionQueues,
3435
+ scope: context.scope,
3479
3436
  selector: {
3480
3437
  _tag: "WildcardSelector"
3481
3438
  }
@@ -3495,9 +3452,7 @@ var QueryPlanner = class {
3495
3452
  return QueryPlan.Plan.make([
3496
3453
  {
3497
3454
  _tag: "SelectStep",
3498
- spaces: context.selectionSpaces,
3499
- allQueuesFromSpaces: context.selectionAllQueuesFromSpaces,
3500
- queues: context.selectionQueues,
3455
+ scope: context.scope,
3501
3456
  selector: {
3502
3457
  _tag: "WildcardSelector"
3503
3458
  }
@@ -3516,9 +3471,7 @@ var QueryPlanner = class {
3516
3471
  return QueryPlan.Plan.make([
3517
3472
  {
3518
3473
  _tag: "SelectStep",
3519
- spaces: context.selectionSpaces,
3520
- allQueuesFromSpaces: context.selectionAllQueuesFromSpaces,
3521
- queues: context.selectionQueues,
3474
+ scope: context.scope,
3522
3475
  selector: {
3523
3476
  _tag: "TextSelector",
3524
3477
  text: filter2.text,
@@ -3529,47 +3482,102 @@ var QueryPlanner = class {
3529
3482
  ...this._generateDeletedHandlingSteps(context)
3530
3483
  ]);
3531
3484
  }
3485
+ // Timestamp
3486
+ case "timestamp": {
3487
+ if (context.selectionInverted) {
3488
+ throw new QueryError({
3489
+ message: "Negated timestamp filters are not supported. Use Filter.updated/Filter.created with the inverted range instead.",
3490
+ context: {
3491
+ query: context.originalQuery
3492
+ }
3493
+ });
3494
+ }
3495
+ return QueryPlan.Plan.make([
3496
+ {
3497
+ _tag: "SelectStep",
3498
+ scope: context.scope,
3499
+ selector: _timestampFilterToSelector(filter2)
3500
+ },
3501
+ ...this._generateDeletedHandlingSteps(context)
3502
+ ]);
3503
+ }
3532
3504
  // Compare
3533
3505
  case "compare":
3534
- throw new QueryError({
3535
- message: "Query too complex",
3536
- context: {
3537
- query: context.originalQuery
3538
- }
3539
- });
3506
+ throw queryTooComplexError(context.originalQuery);
3540
3507
  case "in":
3541
- throw new QueryError({
3542
- message: "Query too complex",
3543
- context: {
3544
- query: context.originalQuery
3545
- }
3546
- });
3508
+ throw queryTooComplexError(context.originalQuery);
3547
3509
  case "range":
3548
- throw new QueryError({
3549
- message: "Query too complex",
3550
- context: {
3551
- query: context.originalQuery
3552
- }
3553
- });
3510
+ throw queryTooComplexError(context.originalQuery);
3554
3511
  // Boolean
3555
3512
  case "not":
3556
3513
  return this._generateSelectionFromFilter(filter2.filter, {
3557
3514
  ...context,
3558
3515
  selectionInverted: !context.selectionInverted
3559
3516
  });
3560
- case "and":
3561
- throw new QueryError({
3562
- message: "Query too complex",
3563
- context: {
3564
- query: context.originalQuery
3517
+ case "and": {
3518
+ const flatFilters = _flattenAnd(filter2.filters);
3519
+ const timestampFilters = flatFilters.filter((f) => f.type === "timestamp");
3520
+ const nonTimestampFilters = flatFilters.filter((f) => f.type !== "timestamp");
3521
+ if (timestampFilters.length > 0 && context.selectionInverted) {
3522
+ throw new QueryError({
3523
+ message: "Negated timestamp filters are not supported. Use Filter.updated/Filter.created with the inverted range instead.",
3524
+ context: {
3525
+ query: context.originalQuery
3526
+ }
3527
+ });
3528
+ }
3529
+ if (timestampFilters.length > 0 && nonTimestampFilters.length <= 1) {
3530
+ const innerFilter = nonTimestampFilters[0];
3531
+ const innerPlan = innerFilter ? this._generateSelectionFromFilter(innerFilter, context) : QueryPlan.Plan.make([
3532
+ {
3533
+ _tag: "SelectStep",
3534
+ scope: context.scope,
3535
+ selector: {
3536
+ _tag: "WildcardSelector"
3537
+ }
3538
+ },
3539
+ ...this._generateDeletedHandlingSteps(context)
3540
+ ]);
3541
+ const selectIdx = innerPlan.steps.findIndex((s) => s._tag === "SelectStep");
3542
+ if (selectIdx !== -1) {
3543
+ const newSteps = [
3544
+ ...innerPlan.steps
3545
+ ];
3546
+ newSteps.splice(selectIdx + 1, 0, {
3547
+ _tag: "FilterStep",
3548
+ filter: {
3549
+ type: "and",
3550
+ filters: timestampFilters
3551
+ }
3552
+ });
3553
+ return QueryPlan.Plan.make(newSteps);
3565
3554
  }
3566
- });
3555
+ const selector = _mergeTimestampSelectors(timestampFilters.map(_timestampFilterToSelector));
3556
+ return QueryPlan.Plan.make([
3557
+ {
3558
+ _tag: "SelectStep",
3559
+ scope: context.scope,
3560
+ selector
3561
+ },
3562
+ ...this._generateDeletedHandlingSteps(context)
3563
+ ]);
3564
+ }
3565
+ if (timestampFilters.length > 0) {
3566
+ throw new QueryError({
3567
+ message: "Timestamp filters can only be combined with a single type or property filter via AND. Split complex filters into a subquery.",
3568
+ context: {
3569
+ query: context.originalQuery
3570
+ }
3571
+ });
3572
+ }
3573
+ throw queryTooComplexError(context.originalQuery);
3574
+ }
3567
3575
  case "or":
3568
3576
  if (filter2.filters.every(isTrivialTypenameFilter)) {
3569
3577
  const typenames = filter2.filters.map((filter3) => {
3570
- invariant10(filter3.type === "object" && filter3.typename !== null, void 0, {
3578
+ invariant9(filter3.type === "object" && filter3.typename !== null, void 0, {
3571
3579
  F: __dxlog_file12,
3572
- L: 245,
3580
+ L: 332,
3573
3581
  S: this,
3574
3582
  A: [
3575
3583
  "filter.type === 'object' && filter.typename !== null",
@@ -3581,9 +3589,7 @@ var QueryPlanner = class {
3581
3589
  return QueryPlan.Plan.make([
3582
3590
  {
3583
3591
  _tag: "SelectStep",
3584
- spaces: context.selectionSpaces,
3585
- allQueuesFromSpaces: context.selectionAllQueuesFromSpaces,
3586
- queues: context.selectionQueues,
3592
+ scope: context.scope,
3587
3593
  selector: {
3588
3594
  _tag: "TypeSelector",
3589
3595
  typename: typenames,
@@ -3599,12 +3605,7 @@ var QueryPlanner = class {
3599
3605
  }
3600
3606
  ]);
3601
3607
  } else {
3602
- throw new QueryError({
3603
- message: "Query too complex",
3604
- context: {
3605
- query: context.originalQuery
3606
- }
3607
- });
3608
+ throw queryTooComplexError(context.originalQuery);
3608
3609
  }
3609
3610
  default:
3610
3611
  throw new QueryError({
@@ -3781,10 +3782,39 @@ var QueryPlanner = class {
3781
3782
  }
3782
3783
  ]);
3783
3784
  }
3784
- /**
3785
- * Removes filter steps that have no predicates.
3786
- */
3787
- _optimizeEmptyFilters(plan) {
3785
+ _generateHierarchyTraversalClause(query, context) {
3786
+ return QueryPlan.Plan.make([
3787
+ ...this._generate(query.anchor, context).steps,
3788
+ {
3789
+ _tag: "TraverseStep",
3790
+ traversal: {
3791
+ _tag: "HierarchyTraversal",
3792
+ direction: query.direction
3793
+ }
3794
+ },
3795
+ ...this._generateDeletedHandlingSteps(context)
3796
+ ]);
3797
+ }
3798
+ _validateQueryScoped(query) {
3799
+ let hasScope = false;
3800
+ QueryAST.visit(query, (node) => {
3801
+ if (node.type === "from") {
3802
+ hasScope = true;
3803
+ }
3804
+ });
3805
+ if (!hasScope) {
3806
+ throw new QueryError({
3807
+ message: "Query must be scoped with a from() clause",
3808
+ context: {
3809
+ query
3810
+ }
3811
+ });
3812
+ }
3813
+ }
3814
+ /**
3815
+ * Removes filter steps that have no predicates.
3816
+ */
3817
+ _optimizeEmptyFilters(plan) {
3788
3818
  return QueryPlan.Plan.make(plan.steps.filter((step) => {
3789
3819
  if (step._tag === "FilterStep") {
3790
3820
  return !QueryPlan.FilterStep.isNoop(step);
@@ -3964,9 +3994,7 @@ var QueryPlanner = class {
3964
3994
  };
3965
3995
  var DEFAULT_CONTEXT = {
3966
3996
  originalQuery: null,
3967
- selectionSpaces: [],
3968
- selectionAllQueuesFromSpaces: false,
3969
- selectionQueues: [],
3997
+ scope: {},
3970
3998
  deletedHandling: "exclude",
3971
3999
  selectionInverted: false
3972
4000
  };
@@ -3983,6 +4011,45 @@ var createRelationTraversalStep = (direction) => ({
3983
4011
  direction
3984
4012
  }
3985
4013
  });
4014
+ var _flattenAnd = (filters) => {
4015
+ const result = [];
4016
+ for (const f of filters) {
4017
+ if (f.type === "and") {
4018
+ result.push(..._flattenAnd(f.filters));
4019
+ } else {
4020
+ result.push(f);
4021
+ }
4022
+ }
4023
+ return result;
4024
+ };
4025
+ var _timestampFilterToSelector = (filter2) => {
4026
+ const selector = {
4027
+ _tag: "TimestampSelector"
4028
+ };
4029
+ const key = filter2.field === "updatedAt" ? filter2.operator === "gte" || filter2.operator === "gt" ? "updatedAfter" : "updatedBefore" : filter2.operator === "gte" || filter2.operator === "gt" ? "createdAfter" : "createdBefore";
4030
+ selector[key] = filter2.value;
4031
+ return selector;
4032
+ };
4033
+ var _mergeTimestampSelectors = (selectors) => {
4034
+ const merged = {
4035
+ _tag: "TimestampSelector"
4036
+ };
4037
+ for (const s of selectors) {
4038
+ if (s.updatedAfter != null) {
4039
+ merged.updatedAfter = Math.max(merged.updatedAfter ?? 0, s.updatedAfter);
4040
+ }
4041
+ if (s.updatedBefore != null) {
4042
+ merged.updatedBefore = Math.min(merged.updatedBefore ?? Infinity, s.updatedBefore);
4043
+ }
4044
+ if (s.createdAfter != null) {
4045
+ merged.createdAfter = Math.max(merged.createdAfter ?? 0, s.createdAfter);
4046
+ }
4047
+ if (s.createdBefore != null) {
4048
+ merged.createdBefore = Math.min(merged.createdBefore ?? Infinity, s.createdBefore);
4049
+ }
4050
+ }
4051
+ return merged;
4052
+ };
3986
4053
  var isTrivialTypenameFilter = (filter2) => {
3987
4054
  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);
3988
4055
  };
@@ -3990,6 +4057,10 @@ var isTrivialTypenameFilter = (filter2) => {
3990
4057
  // src/query/query-executor.ts
3991
4058
  var __dxlog_file13 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/query/query-executor.ts";
3992
4059
  var QueryItem = Object.freeze({
4060
+ /**
4061
+ * Checks if the item is deleted.
4062
+ * Only applies to this item, not its parents.
4063
+ */
3993
4064
  isDeleted: (item) => {
3994
4065
  if (item.doc) {
3995
4066
  return ObjectStructure.isDeleted(item.doc);
@@ -4008,6 +4079,15 @@ var QueryItem = Object.freeze({
4008
4079
  throw new Error("Invalid query item");
4009
4080
  }
4010
4081
  },
4082
+ getParent: (item) => {
4083
+ if (item.doc) {
4084
+ return ObjectStructure.getParent(item.doc)?.["/"];
4085
+ } else if (item.data) {
4086
+ return item.data[ATTR_PARENT];
4087
+ } else {
4088
+ throw new Error("Invalid query item");
4089
+ }
4090
+ },
4011
4091
  getRelationSource: (item) => {
4012
4092
  if (item.doc) {
4013
4093
  return ObjectStructure.getRelationSource(item.doc)?.["/"];
@@ -4041,14 +4121,14 @@ var ExecutionTrace = Object.freeze({
4041
4121
  executionTime: 0,
4042
4122
  children: []
4043
4123
  }),
4044
- markEnd: (trace6) => {
4045
- trace6.endTs = performance.now();
4046
- trace6.executionTime = trace6.endTs - trace6.beginTs;
4124
+ markEnd: (trace7) => {
4125
+ trace7.endTs = performance.now();
4126
+ trace7.executionTime = trace7.endTs - trace7.beginTs;
4047
4127
  },
4048
- putOnPerformanceTimeline: (trace6) => {
4049
- performance.measure(trace6.name, {
4050
- start: trace6.beginTs,
4051
- end: trace6.endTs,
4128
+ putOnPerformanceTimeline: (trace7) => {
4129
+ performance.measure(trace7.name, {
4130
+ start: trace7.beginTs,
4131
+ end: trace7.endTs,
4052
4132
  detail: {
4053
4133
  devtools: {
4054
4134
  dataType: "track-entry",
@@ -4058,49 +4138,49 @@ var ExecutionTrace = Object.freeze({
4058
4138
  properties: [
4059
4139
  [
4060
4140
  "objectCount",
4061
- trace6.objectCount
4141
+ trace7.objectCount
4062
4142
  ],
4063
4143
  [
4064
4144
  "documentsLoaded",
4065
- trace6.documentsLoaded
4145
+ trace7.documentsLoaded
4066
4146
  ],
4067
4147
  [
4068
4148
  "index hits",
4069
- trace6.indexHits
4149
+ trace7.indexHits
4070
4150
  ],
4071
4151
  [
4072
4152
  "indexQueryTime",
4073
- trace6.indexQueryTime
4153
+ trace7.indexQueryTime
4074
4154
  ],
4075
4155
  [
4076
4156
  "documentLoadTime",
4077
- trace6.documentLoadTime
4157
+ trace7.documentLoadTime
4078
4158
  ]
4079
4159
  ],
4080
- tooltipText: trace6.details
4160
+ tooltipText: trace7.details
4081
4161
  }
4082
4162
  }
4083
4163
  });
4084
- for (const child of trace6.children) {
4164
+ for (const child of trace7.children) {
4085
4165
  ExecutionTrace.putOnPerformanceTimeline(child);
4086
4166
  }
4087
4167
  },
4088
- format: (trace6) => {
4089
- const go = (trace7, indent) => {
4168
+ format: (trace7) => {
4169
+ const go = (trace8, indent) => {
4090
4170
  return [
4091
- `${" ".repeat(indent)} - ${trace7.name}(${trace7.details})`,
4092
- `${" ".repeat(indent)} objects: ${trace7.objectCount} docs: ${trace7.documentsLoaded} index hits: ${trace7.indexHits} | total: ${trace7.executionTime.toFixed(0)}ms index: ${trace7.indexQueryTime.toFixed(0)}ms load: ${trace7.documentLoadTime.toFixed(0)}ms`,
4171
+ `${" ".repeat(indent)} - ${trace8.name}(${trace8.details})`,
4172
+ `${" ".repeat(indent)} objects: ${trace8.objectCount} docs: ${trace8.documentsLoaded} index hits: ${trace8.indexHits} | total: ${trace8.executionTime.toFixed(0)}ms index: ${trace8.indexQueryTime.toFixed(0)}ms load: ${trace8.documentLoadTime.toFixed(0)}ms`,
4093
4173
  "",
4094
- ...trace7.children.map((child) => go(child, indent + 2))
4174
+ ...trace8.children.map((child) => go(child, indent + 2))
4095
4175
  ].join("\n");
4096
4176
  };
4097
- return go(trace6, 0);
4177
+ return go(trace7, 0);
4098
4178
  }
4099
4179
  });
4100
- var TRACE_QUERY_EXECUTION = false;
4180
+ var TRACE_QUERY_EXECUTION = !!import.meta.env.DX_TRACE_QUERY_EXECUTION;
4181
+ var MAX_DEPTH_FOR_DELETION_TRACING = 10;
4101
4182
  var QueryExecutor = class _QueryExecutor extends Resource6 {
4102
- _indexer;
4103
- _indexer2;
4183
+ _indexEngine;
4104
4184
  _runtime;
4105
4185
  _automergeHost;
4106
4186
  _spaceStateManager;
@@ -4116,8 +4196,7 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4116
4196
  _lastResultSet = [];
4117
4197
  constructor(options) {
4118
4198
  super();
4119
- this._indexer = options.indexer;
4120
- this._indexer2 = options.indexer2;
4199
+ this._indexEngine = options.indexEngine;
4121
4200
  this._runtime = options.runtime;
4122
4201
  this._automergeHost = options.automergeHost;
4123
4202
  this._spaceStateManager = options.spaceStateManager;
@@ -4148,9 +4227,9 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4148
4227
  }));
4149
4228
  }
4150
4229
  async execQuery() {
4151
- invariant11(this._lifecycleState === LifecycleState3.OPEN, void 0, {
4230
+ invariant10(this._lifecycleState === LifecycleState3.OPEN, void 0, {
4152
4231
  F: __dxlog_file13,
4153
- L: 285,
4232
+ L: 306,
4154
4233
  S: this,
4155
4234
  A: [
4156
4235
  "this._lifecycleState === LifecycleState.OPEN",
@@ -4158,36 +4237,37 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4158
4237
  ]
4159
4238
  });
4160
4239
  const prevResultSet = this._lastResultSet;
4161
- const { workingSet, trace: trace6 } = await this._execPlan(this._plan, []);
4240
+ const { workingSet, trace: trace7 } = await this._execPlan(this._plan, []);
4162
4241
  this._lastResultSet = workingSet;
4163
- trace6.name = "Root";
4164
- trace6.details = JSON.stringify({
4165
- id: this._id
4242
+ trace7.name = "Root";
4243
+ trace7.details = JSON.stringify({
4244
+ id: this._id,
4245
+ query: Query2.pretty(Query2.fromAst(this._query))
4166
4246
  });
4167
- this._trace = trace6;
4247
+ this._trace = trace7;
4168
4248
  const changed = prevResultSet.length !== workingSet.length || prevResultSet.some((item, index) => workingSet[index].objectId !== item.objectId || workingSet[index].spaceId !== item.spaceId || workingSet[index].documentId !== item.documentId);
4169
4249
  if (TRACE_QUERY_EXECUTION) {
4170
- console.log(ExecutionTrace.format(trace6));
4250
+ console.log(ExecutionTrace.format(trace7));
4171
4251
  }
4172
4252
  return {
4173
4253
  changed
4174
4254
  };
4175
4255
  }
4176
4256
  async _execPlan(plan, workingSet) {
4177
- const trace6 = ExecutionTrace.makeEmpty();
4257
+ const trace7 = ExecutionTrace.makeEmpty();
4178
4258
  for (const step of plan.steps) {
4179
4259
  if (this._ctx.disposed) {
4180
4260
  throw new ContextDisposedError();
4181
4261
  }
4182
4262
  const result = await this._execStep(step, workingSet);
4183
4263
  workingSet = result.workingSet;
4184
- trace6.children.push(result.trace);
4264
+ trace7.children.push(result.trace);
4185
4265
  }
4186
- trace6.objectCount = workingSet.length;
4187
- ExecutionTrace.markEnd(trace6);
4266
+ trace7.objectCount = workingSet.length;
4267
+ ExecutionTrace.markEnd(trace7);
4188
4268
  return {
4189
4269
  workingSet,
4190
- trace: trace6
4270
+ trace: trace7
4191
4271
  };
4192
4272
  }
4193
4273
  async _execStep(step, workingSet) {
@@ -4197,52 +4277,55 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4197
4277
  trace: ExecutionTrace.makeEmpty()
4198
4278
  };
4199
4279
  }
4200
- let newWorkingSet, trace6;
4280
+ let newWorkingSet, trace7;
4201
4281
  const begin = performance.now();
4202
4282
  switch (step._tag) {
4203
4283
  case "ClearWorkingSetStep":
4204
4284
  newWorkingSet = [];
4205
- trace6 = ExecutionTrace.makeEmpty();
4285
+ trace7 = ExecutionTrace.makeEmpty();
4206
4286
  break;
4207
4287
  case "SelectStep":
4208
- ({ workingSet: newWorkingSet, trace: trace6 } = await this._execSelectStep(step, workingSet));
4288
+ ({ workingSet: newWorkingSet, trace: trace7 } = await this._execSelectStep(step, workingSet));
4209
4289
  break;
4210
4290
  case "FilterStep":
4211
- ({ workingSet: newWorkingSet, trace: trace6 } = await this._execFilterStep(step, workingSet));
4291
+ ({ workingSet: newWorkingSet, trace: trace7 } = await this._execFilterStep(step, workingSet));
4212
4292
  break;
4213
4293
  case "FilterDeletedStep":
4214
- ({ workingSet: newWorkingSet, trace: trace6 } = await this._execFilterDeletedStep(step, workingSet));
4294
+ ({ workingSet: newWorkingSet, trace: trace7 } = await this._execFilterDeletedStep(step, workingSet));
4215
4295
  break;
4216
4296
  case "UnionStep":
4217
- ({ workingSet: newWorkingSet, trace: trace6 } = await this._execUnionStep(step, workingSet));
4297
+ ({ workingSet: newWorkingSet, trace: trace7 } = await this._execUnionStep(step, workingSet));
4218
4298
  break;
4219
4299
  case "SetDifferenceStep":
4220
- ({ workingSet: newWorkingSet, trace: trace6 } = await this._execSetDifferenceStep(step, workingSet));
4300
+ ({ workingSet: newWorkingSet, trace: trace7 } = await this._execSetDifferenceStep(step, workingSet));
4221
4301
  break;
4222
4302
  case "TraverseStep":
4223
- ({ workingSet: newWorkingSet, trace: trace6 } = await this._execTraverseStep(step, workingSet));
4303
+ ({ workingSet: newWorkingSet, trace: trace7 } = await this._execTraverseStep(step, workingSet));
4224
4304
  break;
4225
4305
  case "OrderStep":
4226
- ({ workingSet: newWorkingSet, trace: trace6 } = await this._execOrderStep(step, workingSet));
4306
+ ({ workingSet: newWorkingSet, trace: trace7 } = await this._execOrderStep(step, workingSet));
4227
4307
  break;
4228
4308
  case "LimitStep":
4229
- ({ workingSet: newWorkingSet, trace: trace6 } = await this._execLimitStep(step, workingSet));
4309
+ ({ workingSet: newWorkingSet, trace: trace7 } = await this._execLimitStep(step, workingSet));
4230
4310
  break;
4231
4311
  default:
4232
4312
  throw new Error(`Unknown step type: ${step._tag}`);
4233
4313
  }
4234
- trace6.beginTs = begin;
4235
- ExecutionTrace.markEnd(trace6);
4314
+ trace7.beginTs = begin;
4315
+ ExecutionTrace.markEnd(trace7);
4236
4316
  return {
4237
4317
  workingSet: newWorkingSet,
4238
- trace: trace6
4318
+ trace: trace7
4239
4319
  };
4240
4320
  }
4241
4321
  async _execSelectStep(step, workingSet) {
4242
4322
  workingSet = [
4243
4323
  ...workingSet
4244
4324
  ];
4245
- const trace6 = {
4325
+ const spaces = step.scope.spaceIds ?? [];
4326
+ const queues = step.scope.queues ?? [];
4327
+ const allQueuesFromSpaces = step.scope.allQueuesFromSpaces ?? false;
4328
+ const trace7 = {
4246
4329
  ...ExecutionTrace.makeEmpty(),
4247
4330
  name: "Select",
4248
4331
  details: JSON.stringify(step.selector),
@@ -4250,204 +4333,191 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4250
4333
  };
4251
4334
  switch (step.selector._tag) {
4252
4335
  case "WildcardSelector": {
4253
- if (this._supportsSqlIndexing()) {
4254
- const beginIndexQuery = performance.now();
4255
- const metas = await this._queryAllFromSqlIndex(step.spaces);
4256
- trace6.indexHits = metas.length;
4257
- trace6.indexQueryTime += performance.now() - beginIndexQuery;
4258
- if (this._ctx.disposed) {
4259
- return {
4260
- workingSet,
4261
- trace: trace6
4262
- };
4263
- }
4264
- const documentLoadStart = performance.now();
4265
- const results = await this._loadDocumentsAfterSqlQuery(metas);
4266
- trace6.documentsLoaded += results.length;
4267
- trace6.documentLoadTime += performance.now() - documentLoadStart;
4268
- workingSet.push(...results.filter(isNonNullable3));
4269
- } else {
4270
- const beginIndexQuery = performance.now();
4271
- const indexHits = await this._indexer.execQuery({
4272
- typenames: [],
4273
- inverted: false
4274
- });
4275
- trace6.indexHits = +indexHits.length;
4276
- trace6.indexQueryTime += performance.now() - beginIndexQuery;
4277
- if (this._ctx.disposed) {
4278
- return {
4279
- workingSet,
4280
- trace: trace6
4281
- };
4282
- }
4283
- const documentLoadStart = performance.now();
4284
- const results = await this._loadDocumentsAfterIndexQuery(indexHits);
4285
- trace6.documentsLoaded += results.length;
4286
- trace6.documentLoadTime += performance.now() - documentLoadStart;
4287
- workingSet.push(...results.filter(isNonNullable3).filter((item) => step.spaces.includes(item.spaceId)));
4336
+ const beginIndexQuery = performance.now();
4337
+ const queueIds = extractQueueIds(queues);
4338
+ const metas = await this._queryAllFromSqlIndex(spaces, allQueuesFromSpaces, queueIds);
4339
+ trace7.indexHits = metas.length;
4340
+ trace7.indexQueryTime += performance.now() - beginIndexQuery;
4341
+ if (this._ctx.disposed) {
4342
+ return {
4343
+ workingSet,
4344
+ trace: trace7
4345
+ };
4288
4346
  }
4289
- trace6.objectCount = workingSet.length;
4347
+ const documentLoadStart = performance.now();
4348
+ const results = await this._loadDocumentsAfterSqlQuery(metas);
4349
+ trace7.documentsLoaded += results.length;
4350
+ trace7.documentLoadTime += performance.now() - documentLoadStart;
4351
+ workingSet.push(...results.filter(isNonNullable3));
4352
+ trace7.objectCount = workingSet.length;
4290
4353
  break;
4291
4354
  }
4292
4355
  case "IdSelector": {
4293
4356
  const beginLoad = performance.now();
4294
- const items = await Promise.all(step.selector.objectIds.map((id) => this._loadFromDXN(DXN.fromLocalObjectId(id), {
4295
- sourceSpaceId: step.spaces[0]
4296
- })));
4297
- trace6.documentLoadTime += performance.now() - beginLoad;
4357
+ const items = await Promise.all(step.selector.objectIds.map((id) => {
4358
+ if (queues.length > 0) {
4359
+ const { spaceId } = DXN.parse(queues[0]).asQueueDXN();
4360
+ return this._loadFromDXN(DXN.parse(queues[0]).extend([
4361
+ id
4362
+ ]), {
4363
+ sourceSpaceId: spaceId
4364
+ });
4365
+ } else if (spaces.length > 0) {
4366
+ return this._loadFromDXN(DXN.fromLocalObjectId(id), {
4367
+ sourceSpaceId: spaces[0]
4368
+ });
4369
+ } else {
4370
+ return null;
4371
+ }
4372
+ }));
4373
+ trace7.documentLoadTime += performance.now() - beginLoad;
4298
4374
  workingSet.push(...items.filter(isNonNullable3));
4299
- trace6.objectCount = workingSet.length;
4375
+ trace7.objectCount = workingSet.length;
4300
4376
  break;
4301
4377
  }
4302
4378
  case "TypeSelector": {
4303
- if (this._supportsSqlIndexing()) {
4304
- const beginIndexQuery = performance.now();
4305
- const metas = await this._queryTypesFromSqlIndex(step.spaces, step.selector.typename, step.selector.inverted);
4306
- trace6.indexHits = metas.length;
4307
- trace6.indexQueryTime += performance.now() - beginIndexQuery;
4308
- if (this._ctx.disposed) {
4309
- return {
4310
- workingSet,
4311
- trace: trace6
4312
- };
4313
- }
4314
- const documentLoadStart = performance.now();
4315
- const results = await this._loadDocumentsAfterSqlQuery(metas);
4316
- trace6.documentsLoaded += results.length;
4317
- trace6.documentLoadTime += performance.now() - documentLoadStart;
4318
- workingSet.push(...results.filter(isNonNullable3));
4319
- } else {
4320
- const beginIndexQuery = performance.now();
4321
- const indexHits = await this._indexer.execQuery({
4322
- typenames: step.selector.typename,
4323
- inverted: step.selector.inverted
4324
- });
4325
- trace6.indexHits = +indexHits.length;
4326
- trace6.indexQueryTime += performance.now() - beginIndexQuery;
4327
- if (this._ctx.disposed) {
4328
- return {
4329
- workingSet,
4330
- trace: trace6
4331
- };
4332
- }
4333
- const documentLoadStart = performance.now();
4334
- const results = await this._loadDocumentsAfterIndexQuery(indexHits);
4335
- trace6.documentsLoaded += results.length;
4336
- trace6.documentLoadTime += performance.now() - documentLoadStart;
4337
- workingSet.push(...results.filter(isNonNullable3).filter((item) => step.spaces.includes(item.spaceId)));
4379
+ const beginIndexQuery = performance.now();
4380
+ const queueIds = extractQueueIds(queues);
4381
+ const metas = await this._queryTypesFromSqlIndex(spaces, step.selector.typename, step.selector.inverted, allQueuesFromSpaces, queueIds);
4382
+ trace7.indexHits = metas.length;
4383
+ trace7.indexQueryTime += performance.now() - beginIndexQuery;
4384
+ if (this._ctx.disposed) {
4385
+ return {
4386
+ workingSet,
4387
+ trace: trace7
4388
+ };
4389
+ }
4390
+ const documentLoadStart = performance.now();
4391
+ const results = await this._loadDocumentsAfterSqlQuery(metas);
4392
+ trace7.documentsLoaded += results.length;
4393
+ trace7.documentLoadTime += performance.now() - documentLoadStart;
4394
+ workingSet.push(...results.filter(isNonNullable3));
4395
+ trace7.objectCount = workingSet.length;
4396
+ break;
4397
+ }
4398
+ case "TimestampSelector": {
4399
+ const beginIndexQuery = performance.now();
4400
+ const queueIds = extractQueueIds(queues);
4401
+ const metas = await this._runInRuntime(this._indexEngine.queryByTimeRange({
4402
+ spaceIds: spaces,
4403
+ updatedAfter: step.selector.updatedAfter,
4404
+ updatedBefore: step.selector.updatedBefore,
4405
+ createdAfter: step.selector.createdAfter,
4406
+ createdBefore: step.selector.createdBefore,
4407
+ includeAllQueues: allQueuesFromSpaces,
4408
+ queueIds
4409
+ }));
4410
+ trace7.indexHits = metas.length;
4411
+ trace7.indexQueryTime += performance.now() - beginIndexQuery;
4412
+ if (this._ctx.disposed) {
4413
+ return {
4414
+ workingSet,
4415
+ trace: trace7
4416
+ };
4338
4417
  }
4339
- trace6.objectCount = workingSet.length;
4418
+ const documentLoadStart = performance.now();
4419
+ const results = await this._loadDocumentsAfterSqlQuery(metas);
4420
+ trace7.documentsLoaded += results.length;
4421
+ trace7.documentLoadTime += performance.now() - documentLoadStart;
4422
+ workingSet.push(...results.filter(isNonNullable3));
4423
+ trace7.objectCount = workingSet.length;
4340
4424
  break;
4341
4425
  }
4342
4426
  case "TextSelector": {
4343
- if (step.selector.searchKind === "full-text" && this._supportsSqlIndexing()) {
4344
- const beginIndexQuery = performance.now();
4345
- invariant11(this._indexer2, "SQL indexer is required.", {
4427
+ if (step.selector.searchKind === "vector") {
4428
+ log10.warn("Vector search is not supported", void 0, {
4346
4429
  F: __dxlog_file13,
4347
- L: 492,
4430
+ L: 522,
4348
4431
  S: this,
4349
- A: [
4350
- "this._indexer2",
4351
- "'SQL indexer is required.'"
4352
- ]
4353
- });
4354
- invariant11(step.spaces.length <= 1, "Multiple spaces are not supported for full-text search", {
4355
- F: __dxlog_file13,
4356
- L: 493,
4357
- S: this,
4358
- A: [
4359
- "step.spaces.length <= 1",
4360
- "'Multiple spaces are not supported for full-text search'"
4361
- ]
4432
+ C: (f, a) => f(...a)
4362
4433
  });
4363
- const queueIds = step.queues.length > 0 ? step.queues.map((dxnStr) => DXN.parse(dxnStr).asQueueDXN()?.queueId).filter(Boolean) : null;
4364
- const textResults = await this._runInRuntime(this._indexer2.queryText({
4365
- query: step.selector.text,
4366
- spaceId: step.spaces,
4367
- includeAllQueues: step.allQueuesFromSpaces,
4368
- queueIds
4369
- }));
4370
- trace6.indexHits = textResults.length;
4371
- trace6.indexQueryTime += performance.now() - beginIndexQuery;
4372
- if (this._ctx.disposed) {
4434
+ break;
4435
+ }
4436
+ const beginIndexQuery = performance.now();
4437
+ invariant10(spaces.length <= 1, "Multiple spaces are not supported for full-text search", {
4438
+ F: __dxlog_file13,
4439
+ L: 528,
4440
+ S: this,
4441
+ A: [
4442
+ "spaces.length <= 1",
4443
+ "'Multiple spaces are not supported for full-text search'"
4444
+ ]
4445
+ });
4446
+ const queueIds = extractQueueIds(queues);
4447
+ const textResults = await this._runInRuntime(this._indexEngine.queryText({
4448
+ query: step.selector.text,
4449
+ spaceId: spaces,
4450
+ includeAllQueues: allQueuesFromSpaces,
4451
+ queueIds
4452
+ }));
4453
+ trace7.indexHits = textResults.length;
4454
+ trace7.indexQueryTime += performance.now() - beginIndexQuery;
4455
+ if (this._ctx.disposed) {
4456
+ return {
4457
+ workingSet,
4458
+ trace: trace7
4459
+ };
4460
+ }
4461
+ const documentLoadStart = performance.now();
4462
+ const queueResults = textResults.filter((r) => r.queueId);
4463
+ const spaceResults = textResults.filter((r) => !r.queueId);
4464
+ const rankMap = new Map(textResults.map((r) => [
4465
+ r.recordId,
4466
+ r.rank
4467
+ ]));
4468
+ let queueItems = [];
4469
+ if (queueResults.length > 0) {
4470
+ const snapshots = await this._runInRuntime(this._indexEngine.querySnapshotsJSON(queueResults.map((r) => r.recordId)));
4471
+ const snapshotMap = new Map(snapshots.map((s) => [
4472
+ s.recordId,
4473
+ s.snapshot
4474
+ ]));
4475
+ queueItems = queueResults.map((result) => {
4476
+ const snapshot = snapshotMap.get(result.recordId);
4477
+ if (!snapshot || typeof snapshot !== "object") {
4478
+ return null;
4479
+ }
4373
4480
  return {
4374
- workingSet,
4375
- trace: trace6
4481
+ objectId: result.objectId,
4482
+ spaceId: result.spaceId,
4483
+ queueId: result.queueId,
4484
+ queueNamespace: "data",
4485
+ documentId: null,
4486
+ doc: null,
4487
+ data: snapshot,
4488
+ rank: rankMap.get(result.recordId) ?? 1
4376
4489
  };
4490
+ }).filter(isNonNullable3);
4491
+ }
4492
+ const spaceItems = await Promise.all(spaceResults.map(async (result) => {
4493
+ const dxn = DXN.fromLocalObjectId(result.objectId);
4494
+ const item = await this._loadFromDXN(dxn, {
4495
+ sourceSpaceId: result.spaceId
4496
+ });
4497
+ if (item) {
4498
+ item.rank = rankMap.get(result.recordId) ?? 1;
4377
4499
  }
4378
- const documentLoadStart = performance.now();
4379
- const queueResults = textResults.filter((r) => r.queueId);
4380
- const spaceResults = textResults.filter((r) => !r.queueId);
4381
- const rankMap = new Map(textResults.map((r) => [
4382
- r.recordId,
4383
- r.rank
4384
- ]));
4385
- let queueItems = [];
4386
- if (queueResults.length > 0) {
4387
- const snapshots = await this._runInRuntime(this._indexer2.querySnapshotsJSON(queueResults.map((r) => r.recordId)));
4388
- const snapshotMap = new Map(snapshots.map((s) => [
4389
- s.recordId,
4390
- s.snapshot
4391
- ]));
4392
- queueItems = queueResults.map((result) => {
4393
- const snapshot = snapshotMap.get(result.recordId);
4394
- if (!snapshot || typeof snapshot !== "object") {
4395
- return null;
4396
- }
4397
- return {
4398
- objectId: result.objectId,
4399
- spaceId: result.spaceId,
4400
- queueId: result.queueId,
4401
- queueNamespace: "data",
4402
- documentId: null,
4403
- doc: null,
4404
- data: snapshot,
4405
- rank: rankMap.get(result.recordId) ?? 1
4406
- };
4407
- }).filter(isNonNullable3);
4500
+ return item;
4501
+ }));
4502
+ const items = [
4503
+ ...queueItems,
4504
+ ...spaceItems.filter(isNonNullable3)
4505
+ ];
4506
+ trace7.documentsLoaded += items.length;
4507
+ trace7.documentLoadTime += performance.now() - documentLoadStart;
4508
+ workingSet.push(...items.filter((item) => {
4509
+ if (spaces.includes(item.spaceId)) {
4510
+ return true;
4408
4511
  }
4409
- const spaceItems = await Promise.all(spaceResults.map(async (result) => {
4410
- const dxn = DXN.fromLocalObjectId(result.objectId);
4411
- const item = await this._loadFromDXN(dxn, {
4412
- sourceSpaceId: result.spaceId
4512
+ if (item.queueId) {
4513
+ return queues.some((dxn) => {
4514
+ const { queueId, spaceId } = DXN.parse(dxn).asQueueDXN();
4515
+ return queueId === item.queueId && spaceId === item.spaceId;
4413
4516
  });
4414
- if (item) {
4415
- item.rank = rankMap.get(result.recordId) ?? 1;
4416
- }
4417
- return item;
4418
- }));
4419
- const items = [
4420
- ...queueItems,
4421
- ...spaceItems.filter(isNonNullable3)
4422
- ];
4423
- trace6.documentsLoaded += items.length;
4424
- trace6.documentLoadTime += performance.now() - documentLoadStart;
4425
- workingSet.push(...items.filter((item) => step.spaces.includes(item.spaceId)));
4426
- trace6.objectCount = workingSet.length;
4427
- } else {
4428
- const beginIndexQuery = performance.now();
4429
- const indexHits = await this._indexer.execQuery({
4430
- typenames: [],
4431
- text: {
4432
- query: step.selector.text,
4433
- kind: Match.type().pipe(Match.withReturnType(), Match.when("full-text", () => "text"), Match.when("vector", () => "vector"), Match.orElseAbsurd)(step.selector.searchKind)
4434
- }
4435
- });
4436
- trace6.indexHits = +indexHits.length;
4437
- trace6.indexQueryTime += performance.now() - beginIndexQuery;
4438
- if (this._ctx.disposed) {
4439
- return {
4440
- workingSet,
4441
- trace: trace6
4442
- };
4443
4517
  }
4444
- const documentLoadStart = performance.now();
4445
- const results = await this._loadDocumentsAfterIndexQuery(indexHits);
4446
- trace6.documentsLoaded += results.length;
4447
- trace6.documentLoadTime += performance.now() - documentLoadStart;
4448
- workingSet.push(...results.filter(isNonNullable3).filter((item) => step.spaces.includes(item.spaceId)));
4449
- trace6.objectCount = workingSet.length;
4450
- }
4518
+ return false;
4519
+ }));
4520
+ trace7.objectCount = workingSet.length;
4451
4521
  break;
4452
4522
  }
4453
4523
  default:
@@ -4455,14 +4525,24 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4455
4525
  }
4456
4526
  if (step.limit !== void 0 && workingSet.length > step.limit) {
4457
4527
  workingSet = workingSet.slice(0, step.limit);
4458
- trace6.objectCount = workingSet.length;
4528
+ trace7.objectCount = workingSet.length;
4459
4529
  }
4460
4530
  return {
4461
4531
  workingSet,
4462
- trace: trace6
4532
+ trace: trace7
4463
4533
  };
4464
4534
  }
4465
4535
  async _execFilterStep(step, workingSet) {
4536
+ const timestampParams = extractTimestampParams(step.filter);
4537
+ if (timestampParams !== null) {
4538
+ return this._execTimestampFilterStep(step, workingSet, timestampParams);
4539
+ }
4540
+ if (filterContainsTimestamp(step.filter)) {
4541
+ throw new QueryError({
4542
+ message: "Timestamp filter in unsupported composition (not, or). Use Filter.updated/Filter.created with explicit range instead.",
4543
+ context: {}
4544
+ });
4545
+ }
4466
4546
  const result = workingSet.filter((item) => {
4467
4547
  if (item.doc) {
4468
4548
  return filterMatchObject(step.filter, {
@@ -4486,9 +4566,38 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4486
4566
  }
4487
4567
  };
4488
4568
  }
4569
+ async _execTimestampFilterStep(step, workingSet, params) {
4570
+ const spaces = [
4571
+ ...new Set(workingSet.map((item) => item.spaceId).filter(isNonNullable3))
4572
+ ];
4573
+ const metas = await this._runInRuntime(this._indexEngine.queryByTimeRange({
4574
+ spaceIds: spaces,
4575
+ ...params,
4576
+ includeAllQueues: false,
4577
+ queueIds: []
4578
+ }));
4579
+ const matchingIds = new Set(metas.map((m) => m.objectId));
4580
+ const result = workingSet.filter((item) => matchingIds.has(item.objectId));
4581
+ return {
4582
+ workingSet: result,
4583
+ trace: {
4584
+ ...ExecutionTrace.makeEmpty(),
4585
+ name: "Filter(timestamp)",
4586
+ details: JSON.stringify(params),
4587
+ objectCount: result.length
4588
+ }
4589
+ };
4590
+ }
4489
4591
  async _execFilterDeletedStep(step, workingSet) {
4490
4592
  const expected = step.mode === "only-deleted";
4491
- const result = workingSet.filter((item) => QueryItem.isDeleted(item) === expected);
4593
+ const deletedState = workingSet.map((item) => QueryItem.isDeleted(item));
4594
+ await Promise.all(workingSet.map(async (item, index) => {
4595
+ if (deletedState[index]) {
4596
+ return;
4597
+ }
4598
+ deletedState[index] ||= await this._getTransitiveDeletionState(item, MAX_DEPTH_FOR_DELETION_TRACING);
4599
+ }));
4600
+ const result = workingSet.filter((item, index) => deletedState[index] === expected);
4492
4601
  return {
4493
4602
  workingSet: result,
4494
4603
  trace: {
@@ -4501,7 +4610,7 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4501
4610
  }
4502
4611
  // TODO(dmaretskyi): This needs to be completed.
4503
4612
  async _execTraverseStep(step, workingSet) {
4504
- const trace6 = {
4613
+ const trace7 = {
4505
4614
  ...ExecutionTrace.makeEmpty(),
4506
4615
  name: "Traverse",
4507
4616
  details: JSON.stringify(step.traversal)
@@ -4511,9 +4620,9 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4511
4620
  case "ReferenceTraversal": {
4512
4621
  switch (step.traversal.direction) {
4513
4622
  case "outgoing": {
4514
- invariant11(step.traversal.property !== null, "Outgoing reference traversal requires a property", {
4623
+ invariant10(step.traversal.property !== null, "Outgoing reference traversal requires a property", {
4515
4624
  F: __dxlog_file13,
4516
- L: 674,
4625
+ L: 740,
4517
4626
  S: this,
4518
4627
  A: [
4519
4628
  "step.traversal.property !== null",
@@ -4537,7 +4646,7 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4537
4646
  ref: ref2["/"]
4538
4647
  }, {
4539
4648
  F: __dxlog_file13,
4540
- L: 690,
4649
+ L: 756,
4541
4650
  S: this,
4542
4651
  C: (f, a) => f(...a)
4543
4652
  });
@@ -4549,41 +4658,22 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4549
4658
  const items = await Promise.all(refs.map(({ ref, spaceId }) => this._loadFromDXN(ref, {
4550
4659
  sourceSpaceId: spaceId
4551
4660
  })));
4552
- trace6.documentLoadTime += performance.now() - beginLoad;
4661
+ trace7.documentLoadTime += performance.now() - beginLoad;
4553
4662
  newWorkingSet.push(...items.filter(isNonNullable3));
4554
- trace6.objectCount = newWorkingSet.length;
4663
+ trace7.objectCount = newWorkingSet.length;
4555
4664
  break;
4556
4665
  }
4557
4666
  case "incoming": {
4558
- if (this._supportsSqlIndexing()) {
4559
- const beginIndexQuery = performance.now();
4560
- const metas = await this._queryIncomingReferencesFromSqlIndex(workingSet, step.traversal.property);
4561
- trace6.indexHits += metas.length;
4562
- trace6.indexQueryTime += performance.now() - beginIndexQuery;
4563
- const documentLoadStart = performance.now();
4564
- const results = await this._loadDocumentsAfterSqlQuery(metas);
4565
- trace6.documentsLoaded += results.length;
4566
- trace6.documentLoadTime += performance.now() - documentLoadStart;
4567
- newWorkingSet.push(...results.filter(isNonNullable3));
4568
- trace6.objectCount = newWorkingSet.length;
4569
- } else {
4570
- const indexHits = await this._indexer.execQuery({
4571
- typenames: [],
4572
- inverted: false,
4573
- graph: {
4574
- kind: "inbound-reference",
4575
- property: step.traversal.property,
4576
- anchors: workingSet.map((item) => item.objectId)
4577
- }
4578
- });
4579
- trace6.indexHits += indexHits.length;
4580
- const documentLoadStart = performance.now();
4581
- const results = await this._loadDocumentsAfterIndexQuery(indexHits);
4582
- trace6.documentsLoaded += results.length;
4583
- trace6.documentLoadTime += performance.now() - documentLoadStart;
4584
- newWorkingSet.push(...results.filter(isNonNullable3));
4585
- trace6.objectCount = newWorkingSet.length;
4586
- }
4667
+ const beginIndexQuery = performance.now();
4668
+ const metas = await this._queryIncomingReferencesFromSqlIndex(workingSet, step.traversal.property);
4669
+ trace7.indexHits += metas.length;
4670
+ trace7.indexQueryTime += performance.now() - beginIndexQuery;
4671
+ const documentLoadStart = performance.now();
4672
+ const results = await this._loadDocumentsAfterSqlQuery(metas);
4673
+ trace7.documentsLoaded += results.length;
4674
+ trace7.documentLoadTime += performance.now() - documentLoadStart;
4675
+ newWorkingSet.push(...results.filter(isNonNullable3));
4676
+ trace7.objectCount = newWorkingSet.length;
4587
4677
  break;
4588
4678
  }
4589
4679
  }
@@ -4595,6 +4685,9 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4595
4685
  case "relation-to-target": {
4596
4686
  const refs = workingSet.map((item) => {
4597
4687
  const dxn = step.traversal.direction === "relation-to-source" ? QueryItem.getRelationSource(item) : QueryItem.getRelationTarget(item);
4688
+ if (!dxn) {
4689
+ return null;
4690
+ }
4598
4691
  try {
4599
4692
  return {
4600
4693
  ref: DXN.parse(dxn),
@@ -4605,7 +4698,7 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4605
4698
  ref: dxn
4606
4699
  }, {
4607
4700
  F: __dxlog_file13,
4608
- L: 764,
4701
+ L: 812,
4609
4702
  S: this,
4610
4703
  C: (f, a) => f(...a)
4611
4704
  });
@@ -4616,42 +4709,101 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4616
4709
  const items = await Promise.all(refs.map(({ ref, spaceId }) => this._loadFromDXN(ref, {
4617
4710
  sourceSpaceId: spaceId
4618
4711
  })));
4619
- trace6.documentLoadTime += performance.now() - beginLoad;
4712
+ trace7.documentLoadTime += performance.now() - beginLoad;
4620
4713
  newWorkingSet.push(...items.filter(isNonNullable3));
4621
- trace6.objectCount = newWorkingSet.length;
4714
+ trace7.objectCount = newWorkingSet.length;
4622
4715
  break;
4623
4716
  }
4624
4717
  case "source-to-relation":
4625
4718
  case "target-to-relation": {
4626
- if (this._supportsSqlIndexing()) {
4627
- const beginIndexQuery = performance.now();
4628
- const metas = await this._queryRelationsFromSqlIndex(workingSet, step.traversal.direction === "source-to-relation" ? "source" : "target");
4629
- trace6.indexHits += metas.length;
4630
- trace6.indexQueryTime += performance.now() - beginIndexQuery;
4631
- const documentLoadStart = performance.now();
4632
- const results = await this._loadDocumentsAfterSqlQuery(metas);
4633
- trace6.documentsLoaded += results.length;
4634
- trace6.documentLoadTime += performance.now() - documentLoadStart;
4635
- newWorkingSet.push(...results.filter(isNonNullable3));
4636
- trace6.objectCount = newWorkingSet.length;
4637
- } else {
4638
- const indexHits = await this._indexer.execQuery({
4639
- typenames: [],
4640
- inverted: false,
4641
- graph: {
4642
- kind: step.traversal.direction === "source-to-relation" ? "relation-source" : "relation-target",
4643
- anchors: workingSet.map((item) => item.objectId),
4644
- property: null
4645
- }
4646
- });
4647
- trace6.indexHits += indexHits.length;
4648
- const documentLoadStart = performance.now();
4649
- const results = await this._loadDocumentsAfterIndexQuery(indexHits);
4650
- trace6.documentsLoaded += results.length;
4651
- trace6.documentLoadTime += performance.now() - documentLoadStart;
4652
- newWorkingSet.push(...results.filter(isNonNullable3));
4653
- trace6.objectCount = newWorkingSet.length;
4719
+ const beginIndexQuery = performance.now();
4720
+ const metas = await this._queryRelationsFromSqlIndex(workingSet, step.traversal.direction === "source-to-relation" ? "source" : "target");
4721
+ trace7.indexHits += metas.length;
4722
+ trace7.indexQueryTime += performance.now() - beginIndexQuery;
4723
+ const documentLoadStart = performance.now();
4724
+ const results = await this._loadDocumentsAfterSqlQuery(metas);
4725
+ trace7.documentsLoaded += results.length;
4726
+ trace7.documentLoadTime += performance.now() - documentLoadStart;
4727
+ newWorkingSet.push(...results.filter(isNonNullable3));
4728
+ trace7.objectCount = newWorkingSet.length;
4729
+ break;
4730
+ }
4731
+ }
4732
+ break;
4733
+ }
4734
+ case "HierarchyTraversal": {
4735
+ switch (step.traversal.direction) {
4736
+ case "to-parent": {
4737
+ const refs = workingSet.map((item) => {
4738
+ if (!item.doc) {
4739
+ return null;
4740
+ }
4741
+ const ref = ObjectStructure.getParent(item.doc);
4742
+ if (!EncodedReference.isEncodedReference(ref)) {
4743
+ return null;
4744
+ }
4745
+ try {
4746
+ return {
4747
+ ref: DXN.parse(ref["/"]),
4748
+ spaceId: item.spaceId
4749
+ };
4750
+ } catch {
4751
+ log10.warn("invalid parent reference", {
4752
+ ref: ref["/"]
4753
+ }, {
4754
+ F: __dxlog_file13,
4755
+ L: 872,
4756
+ S: this,
4757
+ C: (f, a) => f(...a)
4758
+ });
4759
+ return null;
4760
+ }
4761
+ }).filter(isNonNullable3);
4762
+ const beginLoad = performance.now();
4763
+ const items = await Promise.all(refs.map(({ ref, spaceId }) => this._loadFromDXN(ref, {
4764
+ sourceSpaceId: spaceId
4765
+ })));
4766
+ trace7.documentLoadTime += performance.now() - beginLoad;
4767
+ newWorkingSet.push(...items.filter(isNonNullable3));
4768
+ trace7.objectCount = newWorkingSet.length;
4769
+ break;
4770
+ }
4771
+ case "to-children": {
4772
+ const bySpace = /* @__PURE__ */ new Map();
4773
+ for (const item of workingSet) {
4774
+ const existing = bySpace.get(item.spaceId);
4775
+ if (existing) {
4776
+ existing.push(item.objectId);
4777
+ } else {
4778
+ bySpace.set(item.spaceId, [
4779
+ item.objectId
4780
+ ]);
4781
+ }
4654
4782
  }
4783
+ const allChildren = [];
4784
+ for (const [spaceId, parentIds] of bySpace) {
4785
+ const children = await this._runInRuntime(this._indexEngine.queryChildren({
4786
+ spaceId: [
4787
+ spaceId
4788
+ ],
4789
+ parentIds
4790
+ }));
4791
+ for (const child of children) {
4792
+ allChildren.push({
4793
+ spaceId,
4794
+ objectId: child.objectId
4795
+ });
4796
+ }
4797
+ }
4798
+ trace7.indexHits += allChildren.length;
4799
+ const documentLoadStart = performance.now();
4800
+ const results = await Promise.all(allChildren.map(({ spaceId, objectId }) => this._loadFromDXN(DXN.fromLocalObjectId(objectId), {
4801
+ sourceSpaceId: spaceId
4802
+ })));
4803
+ trace7.documentsLoaded += results.filter(isNonNullable3).length;
4804
+ trace7.documentLoadTime += performance.now() - documentLoadStart;
4805
+ newWorkingSet.push(...results.filter(isNonNullable3));
4806
+ trace7.objectCount = newWorkingSet.length;
4655
4807
  break;
4656
4808
  }
4657
4809
  }
@@ -4662,7 +4814,7 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4662
4814
  }
4663
4815
  return {
4664
4816
  workingSet: newWorkingSet,
4665
- trace: trace6
4817
+ trace: trace7
4666
4818
  };
4667
4819
  }
4668
4820
  async _execUnionStep(step, workingSet) {
@@ -4670,25 +4822,25 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4670
4822
  const resultSets = await Promise.all(step.plans.map((plan) => this._execPlan(plan, [
4671
4823
  ...workingSet
4672
4824
  ])));
4673
- const trace6 = {
4825
+ const trace7 = {
4674
4826
  ...ExecutionTrace.makeEmpty(),
4675
4827
  name: "Union"
4676
4828
  };
4677
4829
  for (const resultSet of resultSets) {
4678
4830
  for (const item of resultSet.workingSet) {
4679
- results.set(`${item.spaceId}:${item.documentId}:${item.objectId}`, item);
4831
+ results.set(compositeKey(item.spaceId, String(item.documentId), item.objectId), item);
4680
4832
  }
4681
- trace6.children.push(resultSet.trace);
4833
+ trace7.children.push(resultSet.trace);
4682
4834
  }
4683
4835
  return {
4684
4836
  workingSet: [
4685
4837
  ...results.values()
4686
4838
  ],
4687
- trace: trace6
4839
+ trace: trace7
4688
4840
  };
4689
4841
  }
4690
4842
  async _execSetDifferenceStep(step, workingSet) {
4691
- const trace6 = {
4843
+ const trace7 = {
4692
4844
  ...ExecutionTrace.makeEmpty(),
4693
4845
  name: "SetDifference"
4694
4846
  };
@@ -4698,13 +4850,13 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4698
4850
  const excludeResult = await this._execPlan(step.exclude, [
4699
4851
  ...workingSet
4700
4852
  ]);
4701
- trace6.children.push(sourceResult.trace, excludeResult.trace);
4853
+ trace7.children.push(sourceResult.trace, excludeResult.trace);
4702
4854
  return {
4703
4855
  workingSet: sourceResult.workingSet.filter((item) => {
4704
4856
  const index = excludeResult.workingSet.findIndex((i) => i.objectId === item.objectId);
4705
4857
  return index === -1;
4706
4858
  }),
4707
- trace: trace6
4859
+ trace: trace7
4708
4860
  };
4709
4861
  }
4710
4862
  async _execOrderStep(step, workingSet) {
@@ -4798,19 +4950,11 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4798
4950
  }
4799
4951
  return String(aValue).localeCompare(String(bValue));
4800
4952
  }
4801
- async _loadDocumentsAfterIndexQuery(indexHits) {
4802
- return Promise.all(indexHits.map(async (hit) => {
4803
- return this._loadFromIndexHit(hit);
4804
- }));
4805
- }
4806
- _supportsSqlIndexing() {
4807
- return !!this._indexer2 && !!this._runtime;
4808
- }
4809
4953
  async _runInRuntime(effect) {
4810
4954
  const runtimeProvider = this._runtime;
4811
- invariant11(runtimeProvider, "SQL runtime is required.", {
4955
+ invariant10(runtimeProvider, "SQL runtime is required.", {
4812
4956
  F: __dxlog_file13,
4813
- L: 1002,
4957
+ L: 1095,
4814
4958
  S: this,
4815
4959
  A: [
4816
4960
  "runtimeProvider",
@@ -4820,48 +4964,25 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4820
4964
  const runtime = await runAndForwardErrors(runtimeProvider);
4821
4965
  return await unwrapExit(await effect.pipe(Runtime.runPromiseExit(runtime)));
4822
4966
  }
4823
- async _queryAllFromSqlIndex(spaceIds) {
4824
- invariant11(this._indexer2, "SQL indexer is required.", {
4825
- F: __dxlog_file13,
4826
- L: 1008,
4827
- S: this,
4828
- A: [
4829
- "this._indexer2",
4830
- "'SQL indexer is required.'"
4831
- ]
4832
- });
4833
- return await this._runInRuntime(this._indexer2.queryAll({
4834
- spaceIds
4967
+ async _queryAllFromSqlIndex(spaceIds, includeAllQueues, queueIds) {
4968
+ return await this._runInRuntime(this._indexEngine.queryAll({
4969
+ spaceIds,
4970
+ includeAllQueues,
4971
+ queueIds
4835
4972
  }));
4836
4973
  }
4837
- async _queryTypesFromSqlIndex(spaceIds, typeDxns, inverted) {
4838
- invariant11(this._indexer2, "SQL indexer is required.", {
4839
- F: __dxlog_file13,
4840
- L: 1017,
4841
- S: this,
4842
- A: [
4843
- "this._indexer2",
4844
- "'SQL indexer is required.'"
4845
- ]
4846
- });
4847
- return await this._runInRuntime(this._indexer2.queryTypes({
4974
+ async _queryTypesFromSqlIndex(spaceIds, typeDxns, inverted, includeAllQueues, queueIds) {
4975
+ return await this._runInRuntime(this._indexEngine.queryTypes({
4848
4976
  spaceIds,
4849
4977
  typeDxns,
4850
- inverted
4978
+ inverted,
4979
+ includeAllQueues,
4980
+ queueIds
4851
4981
  }));
4852
4982
  }
4853
4983
  async _queryIncomingReferencesFromSqlIndex(workingSet, property) {
4854
4984
  const anchorDxns = workingSet.map((item) => DXN.fromLocalObjectId(item.objectId).toString());
4855
- invariant11(this._indexer2, "SQL indexer is required.", {
4856
- F: __dxlog_file13,
4857
- L: 1026,
4858
- S: this,
4859
- A: [
4860
- "this._indexer2",
4861
- "'SQL indexer is required.'"
4862
- ]
4863
- });
4864
- const rows = (await Promise.all(anchorDxns.map((targetDxn) => this._runInRuntime(this._indexer2.queryReverseRef({
4985
+ const rows = (await Promise.all(anchorDxns.map((targetDxn) => this._runInRuntime(this._indexEngine.queryReverseRef({
4865
4986
  targetDxn
4866
4987
  }))))).flat();
4867
4988
  const recordIds = rows.filter((row) => {
@@ -4873,7 +4994,7 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4873
4994
  return _QueryExecutor._matchesReferencePropertyPath(rowPath, queryPath);
4874
4995
  }).map((row) => row.recordId);
4875
4996
  const uniqueRecordIds = Array.from(new Set(recordIds));
4876
- return await this._runInRuntime(this._indexer2.lookupByRecordIds(uniqueRecordIds));
4997
+ return await this._runInRuntime(this._indexEngine.lookupByRecordIds(uniqueRecordIds));
4877
4998
  }
4878
4999
  /**
4879
5000
  * Matches a reverse-reference row path against a query property path.
@@ -4912,17 +5033,8 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4912
5033
  return true;
4913
5034
  }
4914
5035
  async _queryRelationsFromSqlIndex(workingSet, endpoint) {
4915
- invariant11(this._indexer2, "SQL indexer is required.", {
4916
- F: __dxlog_file13,
4917
- L: 1100,
4918
- S: this,
4919
- A: [
4920
- "this._indexer2",
4921
- "'SQL indexer is required.'"
4922
- ]
4923
- });
4924
5036
  const anchorDxns = workingSet.map((item) => DXN.fromLocalObjectId(item.objectId).toString());
4925
- return await this._runInRuntime(this._indexer2.queryRelations({
5037
+ return await this._runInRuntime(this._indexEngine.queryRelations({
4926
5038
  endpoint,
4927
5039
  anchorDxns
4928
5040
  }));
@@ -4944,16 +5056,7 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4944
5056
  if (queueMetas.length === 0) {
4945
5057
  return /* @__PURE__ */ new Map();
4946
5058
  }
4947
- invariant11(this._indexer2, "SQL indexer is required.", {
4948
- F: __dxlog_file13,
4949
- L: 1130,
4950
- S: this,
4951
- A: [
4952
- "this._indexer2",
4953
- "'SQL indexer is required.'"
4954
- ]
4955
- });
4956
- const snapshots = await this._runInRuntime(this._indexer2.querySnapshotsJSON(queueMetas.map((meta) => meta.recordId)));
5059
+ const snapshots = await this._runInRuntime(this._indexEngine.querySnapshotsJSON(queueMetas.map((meta) => meta.recordId)));
4957
5060
  return new Map(snapshots.map((s) => [
4958
5061
  s.recordId,
4959
5062
  s.snapshot
@@ -4988,17 +5091,14 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
4988
5091
  if (!meta.documentId) {
4989
5092
  return null;
4990
5093
  }
4991
- const handle = await this._automergeHost.loadDoc(Context5.default(void 0, {
4992
- F: __dxlog_file13,
4993
- L: 1169
4994
- }), meta.documentId, {
5094
+ const handle = await this._automergeHost.loadDoc(this._ctx, meta.documentId, {
4995
5095
  fetchFromNetwork: true
4996
5096
  });
4997
5097
  const doc = handle.doc();
4998
5098
  if (!doc) {
4999
5099
  return null;
5000
5100
  }
5001
- const object = DatabaseDirectory4.getInlineObject(doc, meta.objectId);
5101
+ const object = DatabaseDirectory3.getInlineObject(doc, meta.objectId);
5002
5102
  if (!object) {
5003
5103
  return null;
5004
5104
  }
@@ -5013,127 +5113,201 @@ var QueryExecutor = class _QueryExecutor extends Resource6 {
5013
5113
  rank: 1
5014
5114
  };
5015
5115
  }
5016
- /**
5017
- * Space key hex -> SpaceId.
5018
- */
5019
- _spaceIdCache = /* @__PURE__ */ new Map();
5020
- async _loadFromIndexHit(hit) {
5021
- const { objectId, documentId, spaceKey: spaceKeyInIndex } = objectPointerCodec3.decode(hit.id);
5022
- const handle = await this._automergeHost.loadDoc(Context5.default(void 0, {
5023
- F: __dxlog_file13,
5024
- L: 1203
5025
- }), documentId, {
5026
- fetchFromNetwork: true
5027
- });
5028
- const doc = handle.doc();
5029
- if (!doc) {
5030
- return null;
5031
- }
5032
- const spaceKey = spaceKeyInIndex ?? DatabaseDirectory4.getSpaceKey(doc);
5033
- if (!spaceKey) {
5034
- return null;
5035
- }
5036
- let spaceId = this._spaceIdCache.get(spaceKey);
5037
- if (!spaceId) {
5038
- spaceId = await createIdFromSpaceKey(PublicKey4.from(spaceKey));
5039
- this._spaceIdCache.set(spaceKey, spaceId);
5040
- }
5041
- const object = DatabaseDirectory4.getInlineObject(doc, objectId);
5042
- if (!object) {
5043
- return null;
5044
- }
5045
- return {
5046
- objectId,
5047
- documentId,
5048
- spaceId,
5049
- queueId: null,
5050
- queueNamespace: null,
5051
- data: null,
5052
- doc: object,
5053
- rank: hit.rank
5054
- };
5055
- }
5056
5116
  async _loadFromDXN(dxn, { sourceSpaceId }) {
5057
- const echoDxn = dxn.asEchoDXN();
5058
- if (!echoDxn) {
5059
- log10.warn("unable to resolve DXN", {
5060
- dxn
5061
- }, {
5062
- F: __dxlog_file13,
5063
- L: 1242,
5064
- S: this,
5065
- C: (f, a) => f(...a)
5066
- });
5067
- return null;
5068
- }
5069
- const spaceId = echoDxn.spaceId ?? sourceSpaceId;
5070
- const spaceRoot = this._spaceStateManager.getRootBySpaceId(spaceId);
5071
- if (!spaceRoot) {
5072
- log10.warn("no space state found for", {
5073
- spaceId
5074
- }, {
5075
- F: __dxlog_file13,
5076
- L: 1250,
5077
- S: this,
5078
- C: (f, a) => f(...a)
5079
- });
5080
- return null;
5081
- }
5082
- const dbDirectory = spaceRoot.doc();
5083
- if (!dbDirectory) {
5084
- log10.warn("no space state found for", {
5085
- spaceId
5086
- }, {
5087
- F: __dxlog_file13,
5088
- L: 1255,
5089
- S: this,
5090
- C: (f, a) => f(...a)
5091
- });
5092
- return null;
5117
+ switch (dxn.kind) {
5118
+ case DXN.kind.ECHO: {
5119
+ const echoDxn = dxn.asEchoDXN();
5120
+ if (!echoDxn) {
5121
+ log10.warn("unable to resolve DXN", {
5122
+ dxn
5123
+ }, {
5124
+ F: __dxlog_file13,
5125
+ L: 1292,
5126
+ S: this,
5127
+ C: (f, a) => f(...a)
5128
+ });
5129
+ return null;
5130
+ }
5131
+ const spaceId = echoDxn.spaceId ?? sourceSpaceId;
5132
+ const spaceRoot = this._spaceStateManager.getRootBySpaceId(spaceId);
5133
+ if (!spaceRoot) {
5134
+ log10.warn("no space state found for", {
5135
+ spaceId
5136
+ }, {
5137
+ F: __dxlog_file13,
5138
+ L: 1300,
5139
+ S: this,
5140
+ C: (f, a) => f(...a)
5141
+ });
5142
+ return null;
5143
+ }
5144
+ const dbDirectory = spaceRoot.doc();
5145
+ if (!dbDirectory) {
5146
+ log10.warn("no space state found for", {
5147
+ spaceId
5148
+ }, {
5149
+ F: __dxlog_file13,
5150
+ L: 1305,
5151
+ S: this,
5152
+ C: (f, a) => f(...a)
5153
+ });
5154
+ return null;
5155
+ }
5156
+ const inlineObject = DatabaseDirectory3.getInlineObject(dbDirectory, echoDxn.echoId);
5157
+ if (inlineObject) {
5158
+ return {
5159
+ objectId: echoDxn.echoId,
5160
+ documentId: spaceRoot.documentId,
5161
+ spaceId,
5162
+ queueId: null,
5163
+ queueNamespace: null,
5164
+ data: null,
5165
+ doc: inlineObject,
5166
+ rank: 1
5167
+ };
5168
+ }
5169
+ const link = DatabaseDirectory3.getLink(dbDirectory, echoDxn.echoId);
5170
+ if (!link) {
5171
+ return null;
5172
+ }
5173
+ const handle = await this._automergeHost.loadDoc(this._ctx, link, {
5174
+ fetchFromNetwork: true
5175
+ });
5176
+ const doc = handle.doc();
5177
+ if (!doc) {
5178
+ return null;
5179
+ }
5180
+ const object = DatabaseDirectory3.getInlineObject(doc, echoDxn.echoId);
5181
+ if (!object) {
5182
+ return null;
5183
+ }
5184
+ return {
5185
+ objectId: echoDxn.echoId,
5186
+ documentId: handle.documentId,
5187
+ spaceId,
5188
+ queueId: null,
5189
+ queueNamespace: null,
5190
+ data: null,
5191
+ doc: object,
5192
+ rank: 1
5193
+ };
5194
+ break;
5195
+ }
5196
+ case DXN.kind.QUEUE: {
5197
+ const queueDxn = dxn.asQueueDXN();
5198
+ if (!queueDxn || !queueDxn.objectId) {
5199
+ log10.warn("unable to resolve queue DXN", {
5200
+ dxn
5201
+ }, {
5202
+ F: __dxlog_file13,
5203
+ L: 1356,
5204
+ S: this,
5205
+ C: (f, a) => f(...a)
5206
+ });
5207
+ return null;
5208
+ }
5209
+ const { spaceId, queueId, objectId } = queueDxn;
5210
+ const meta = await this._runInRuntime(this._indexEngine.lookupByObjectId({
5211
+ objectId,
5212
+ spaceId,
5213
+ queueId
5214
+ }));
5215
+ if (!meta) {
5216
+ return null;
5217
+ }
5218
+ const snapshotMap = await this._loadQueueSnapshotMap([
5219
+ meta
5220
+ ]);
5221
+ return this._loadFromQueue(meta, snapshotMap);
5222
+ }
5223
+ default: {
5224
+ log10.warn("unable to resolve DXN", {
5225
+ dxn
5226
+ }, {
5227
+ F: __dxlog_file13,
5228
+ L: 1376,
5229
+ S: this,
5230
+ C: (f, a) => f(...a)
5231
+ });
5232
+ return null;
5233
+ }
5093
5234
  }
5094
- const inlineObject = DatabaseDirectory4.getInlineObject(dbDirectory, echoDxn.echoId);
5095
- if (inlineObject) {
5096
- return {
5097
- objectId: echoDxn.echoId,
5098
- documentId: spaceRoot.documentId,
5099
- spaceId,
5100
- queueId: null,
5101
- queueNamespace: null,
5102
- data: null,
5103
- doc: inlineObject,
5104
- rank: 1
5105
- };
5235
+ }
5236
+ async _getTransitiveDeletionState(item, remainingDepth) {
5237
+ const strongDeps = [
5238
+ QueryItem.getParent(item),
5239
+ QueryItem.getRelationSource(item),
5240
+ QueryItem.getRelationTarget(item)
5241
+ ].filter((x) => x !== void 0);
5242
+ if (strongDeps.length === 0) {
5243
+ return false;
5106
5244
  }
5107
- const link = DatabaseDirectory4.getLink(dbDirectory, echoDxn.echoId);
5108
- if (!link) {
5109
- return null;
5245
+ const strongDepStates = await Promise.all(strongDeps.map(async (dxn) => {
5246
+ const dep = await this._loadFromDXN(DXN.parse(dxn), {
5247
+ sourceSpaceId: item.spaceId
5248
+ });
5249
+ if (!dep) {
5250
+ return false;
5251
+ }
5252
+ if (QueryItem.isDeleted(dep)) {
5253
+ return true;
5254
+ }
5255
+ if (remainingDepth > 0) {
5256
+ return this._getTransitiveDeletionState(dep, remainingDepth - 1);
5257
+ }
5258
+ return false;
5259
+ }));
5260
+ return strongDepStates.some((x) => x);
5261
+ }
5262
+ };
5263
+ var extractQueueIds = (queues) => {
5264
+ if (queues.length === 0) {
5265
+ return null;
5266
+ }
5267
+ return queues.map((dxnStr) => DXN.parse(dxnStr).asQueueDXN()?.queueId).filter(Boolean);
5268
+ };
5269
+ var extractTimestampParams = (filter2) => {
5270
+ const collect = (f) => {
5271
+ if (f.type === "timestamp") {
5272
+ return [
5273
+ f
5274
+ ];
5110
5275
  }
5111
- const handle = await this._automergeHost.loadDoc(Context5.default(void 0, {
5112
- F: __dxlog_file13,
5113
- L: 1278
5114
- }), link, {
5115
- fetchFromNetwork: true
5116
- });
5117
- const doc = handle.doc();
5118
- if (!doc) {
5119
- return null;
5276
+ if (f.type === "and") {
5277
+ return f.filters.flatMap(collect);
5120
5278
  }
5121
- const object = DatabaseDirectory4.getInlineObject(doc, echoDxn.echoId);
5122
- if (!object) {
5123
- return null;
5279
+ return [];
5280
+ };
5281
+ const timestamps = collect(filter2);
5282
+ if (timestamps.length === 0) {
5283
+ return null;
5284
+ }
5285
+ const params = {};
5286
+ for (const ts of timestamps) {
5287
+ if (ts.field === "updatedAt" && (ts.operator === "gt" || ts.operator === "gte")) {
5288
+ params.updatedAfter = ts.value;
5289
+ } else if (ts.field === "updatedAt" && (ts.operator === "lt" || ts.operator === "lte")) {
5290
+ params.updatedBefore = ts.value;
5291
+ } else if (ts.field === "createdAt" && (ts.operator === "gt" || ts.operator === "gte")) {
5292
+ params.createdAfter = ts.value;
5293
+ } else if (ts.field === "createdAt" && (ts.operator === "lt" || ts.operator === "lte")) {
5294
+ params.createdBefore = ts.value;
5124
5295
  }
5125
- return {
5126
- objectId: echoDxn.echoId,
5127
- documentId: handle.documentId,
5128
- spaceId,
5129
- queueId: null,
5130
- queueNamespace: null,
5131
- data: null,
5132
- doc: object,
5133
- rank: 1
5134
- };
5135
5296
  }
5297
+ return params;
5136
5298
  };
5299
+ function filterContainsTimestamp(filter2) {
5300
+ if (filter2.type === "timestamp") {
5301
+ return true;
5302
+ }
5303
+ if (filter2.type === "and" || filter2.type === "or") {
5304
+ return filter2.filters.some(filterContainsTimestamp);
5305
+ }
5306
+ if (filter2.type === "not") {
5307
+ return filterContainsTimestamp(filter2.filter);
5308
+ }
5309
+ return false;
5310
+ }
5137
5311
 
5138
5312
  // src/db-host/query-service.ts
5139
5313
  function _ts_decorate5(decorators, target, key, desc) {
@@ -5166,30 +5340,30 @@ var QueryServiceImpl = class extends Resource7 {
5166
5340
  });
5167
5341
  }
5168
5342
  async _open() {
5169
- this._params.indexer.updated.on(this._ctx, () => this.invalidateQueries());
5170
- this._updateQueries = new DeferredTask2(this._ctx, this._executeQueries.bind(this));
5343
+ this._updateQueries = new DeferredTask2(this._ctx, () => this._executeQueries(this._ctx));
5171
5344
  }
5172
5345
  async _close() {
5173
5346
  await this._updateQueries.join();
5174
5347
  await Promise.all(Array.from(this._queries).map((query) => query.close()));
5175
5348
  }
5176
- async setConfig(config) {
5177
- await this._params.indexer.setConfig(config);
5349
+ /**
5350
+ * @deprecated No longer needed with SQL-based indexing.
5351
+ */
5352
+ async setConfig() {
5353
+ }
5354
+ /**
5355
+ * @deprecated No longer needed with SQL-based indexing.
5356
+ */
5357
+ async reindex() {
5358
+ log11.warn("reindex() is deprecated and no longer has any effect", void 0, {
5359
+ F: __dxlog_file14,
5360
+ L: 104,
5361
+ S: this,
5362
+ C: (f, a) => f(...a)
5363
+ });
5178
5364
  }
5179
5365
  execQuery(request) {
5180
5366
  return new Stream2(({ next, close, ctx }) => {
5181
- if (this._params.indexer.config?.enabled !== true) {
5182
- log11.error("indexer is disabled", {
5183
- config: this._params.indexer.config
5184
- }, {
5185
- F: __dxlog_file14,
5186
- L: 107,
5187
- S: this,
5188
- C: (f, a) => f(...a)
5189
- });
5190
- close();
5191
- return;
5192
- }
5193
5367
  const queryEntry = this._createQuery(ctx, request, next, close, close);
5194
5368
  scheduleMicroTask(ctx, async () => {
5195
5369
  await queryEntry.executor.open();
@@ -5200,43 +5374,6 @@ var QueryServiceImpl = class extends Resource7 {
5200
5374
  });
5201
5375
  }
5202
5376
  /**
5203
- * Re-index all loaded documents.
5204
- */
5205
- async reindex() {
5206
- log11("Reindexing all documents...", void 0, {
5207
- F: __dxlog_file14,
5208
- L: 126,
5209
- S: this,
5210
- C: (f, a) => f(...a)
5211
- });
5212
- const iterator = createDocumentsIterator(this._params.automergeHost);
5213
- const ids = /* @__PURE__ */ new Map();
5214
- for await (const documents of iterator()) {
5215
- for (const { id, heads } of documents) {
5216
- ids.set(id, heads);
5217
- }
5218
- if (ids.size % 100 === 0) {
5219
- log11("Collected documents...", {
5220
- count: ids.size
5221
- }, {
5222
- F: __dxlog_file14,
5223
- L: 134,
5224
- S: this,
5225
- C: (f, a) => f(...a)
5226
- });
5227
- }
5228
- }
5229
- log11("Marking all documents as dirty...", {
5230
- count: ids.size
5231
- }, {
5232
- F: __dxlog_file14,
5233
- L: 138,
5234
- S: this,
5235
- C: (f, a) => f(...a)
5236
- });
5237
- await this._params.indexer.reindex(ids);
5238
- }
5239
- /**
5240
5377
  * Schedule re-execution of all queries.
5241
5378
  */
5242
5379
  invalidateQueries() {
@@ -5246,11 +5383,10 @@ var QueryServiceImpl = class extends Resource7 {
5246
5383
  this._updateQueries.schedule();
5247
5384
  }
5248
5385
  _createQuery(ctx, request, onResults, onError, onClose) {
5249
- const parsedQuery = QueryAST.Query.pipe(Schema.decodeUnknownSync)(JSON.parse(request.query));
5386
+ const parsedQuery = QueryAST2.Query.pipe(Schema.decodeUnknownSync)(JSON.parse(request.query));
5250
5387
  const queryEntry = {
5251
5388
  executor: new QueryExecutor({
5252
- indexer: this._params.indexer,
5253
- indexer2: this._params.indexer2,
5389
+ indexEngine: this._params.indexEngine,
5254
5390
  runtime: this._params.runtime,
5255
5391
  automergeHost: this._params.automergeHost,
5256
5392
  queryId: request.queryId ?? raise(new Error("query id required")),
@@ -5280,7 +5416,7 @@ var QueryServiceImpl = class extends Resource7 {
5280
5416
  this._queries.add(queryEntry);
5281
5417
  return queryEntry;
5282
5418
  }
5283
- async _executeQueries() {
5419
+ async _executeQueries(_ctx) {
5284
5420
  const begin = performance.now();
5285
5421
  let count = 0;
5286
5422
  await Promise.all(Array.from(this._queries).map(async (query) => {
@@ -5298,7 +5434,7 @@ var QueryServiceImpl = class extends Resource7 {
5298
5434
  } catch (err) {
5299
5435
  log11.catch(err, void 0, {
5300
5436
  F: __dxlog_file14,
5301
- L: 211,
5437
+ L: 187,
5302
5438
  S: this,
5303
5439
  C: (f, a) => f(...a)
5304
5440
  });
@@ -5309,7 +5445,7 @@ var QueryServiceImpl = class extends Resource7 {
5309
5445
  duration: performance.now() - begin
5310
5446
  }, {
5311
5447
  F: __dxlog_file14,
5312
- L: 215,
5448
+ L: 191,
5313
5449
  S: this,
5314
5450
  C: (f, a) => f(...a)
5315
5451
  });
@@ -5320,78 +5456,28 @@ _ts_decorate5([
5320
5456
  ], QueryServiceImpl.prototype, "_close", null);
5321
5457
  _ts_decorate5([
5322
5458
  trace4.span({
5323
- showInBrowserTimeline: true
5459
+ showInBrowserTimeline: true,
5460
+ showInRemoteTracing: false
5324
5461
  })
5325
5462
  ], QueryServiceImpl.prototype, "_executeQueries", null);
5326
5463
  QueryServiceImpl = _ts_decorate5([
5327
5464
  trace4.resource()
5328
5465
  ], QueryServiceImpl);
5329
- var createDocumentsIterator = (automergeHost) => (
5330
- /**
5331
- * Recursively get all object data blobs from loaded documents from Automerge Repo.
5332
- */
5333
- // TODO(mykola): Unload automerge handles after usage.
5334
- async function* getAllDocuments() {
5335
- const visited = /* @__PURE__ */ new Set();
5336
- async function* getObjectsFromHandle(handle) {
5337
- if (visited.has(handle.documentId) || !handle.isReady()) {
5338
- return;
5339
- }
5340
- const doc = handle.doc();
5341
- const spaceKey = DatabaseDirectory5.getSpaceKey(doc) ?? void 0;
5342
- if (doc.objects) {
5343
- yield Object.entries(doc.objects).map(([objectId, object]) => {
5344
- return {
5345
- id: objectPointerCodec4.encode({
5346
- documentId: handle.documentId,
5347
- objectId,
5348
- spaceKey
5349
- }),
5350
- object,
5351
- heads: getHeads3(doc)
5352
- };
5353
- });
5354
- }
5355
- if (doc.links) {
5356
- for (const id of Object.values(doc.links)) {
5357
- const urlString = id.toString();
5358
- if (visited.has(urlString)) {
5359
- continue;
5360
- }
5361
- const linkHandle = await automergeHost.loadDoc(Context6.default(void 0, {
5362
- F: __dxlog_file14,
5363
- L: 256
5364
- }), urlString, {
5365
- fetchFromNetwork: true
5366
- });
5367
- for await (const result of getObjectsFromHandle(linkHandle)) {
5368
- yield result;
5369
- }
5370
- }
5371
- }
5372
- visited.add(handle.documentId);
5373
- }
5374
- for (const handle of Object.values(automergeHost.handles)) {
5375
- if (visited.has(handle.documentId)) {
5376
- continue;
5377
- }
5378
- for await (const result of getObjectsFromHandle(handle)) {
5379
- yield result;
5380
- }
5381
- visited.add(handle.documentId);
5382
- }
5383
- }
5384
- );
5385
5466
 
5386
5467
  // src/db-host/queue-data-source.ts
5387
5468
  import * as Effect3 from "effect/Effect";
5469
+ import { EchoFeedCodec as EchoFeedCodec2 } from "@dxos/echo-protocol";
5388
5470
  import { RuntimeProvider as RuntimeProvider2 } from "@dxos/effect";
5389
- import { FeedCursor } from "@dxos/feed";
5390
5471
  import { failedInvariant } from "@dxos/invariant";
5391
5472
  import { log as log12 } from "@dxos/log";
5473
+ import { FeedProtocol as FeedProtocol2 } from "@dxos/protocols";
5392
5474
  var __dxlog_file15 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/queue-data-source.ts";
5393
5475
  var QueueDataSource = class {
5394
5476
  sourceName = "queue";
5477
+ /**
5478
+ * Feed namespaces to index.
5479
+ */
5480
+ _feedNamespaces;
5395
5481
  _feedStore;
5396
5482
  _runtime;
5397
5483
  _getSpaceIds;
@@ -5399,23 +5485,27 @@ var QueueDataSource = class {
5399
5485
  this._feedStore = options.feedStore;
5400
5486
  this._runtime = options.runtime;
5401
5487
  this._getSpaceIds = options.getSpaceIds;
5488
+ this._feedNamespaces = options.feedNamespaces ?? [
5489
+ FeedProtocol2.WellKnownNamespaces.data,
5490
+ FeedProtocol2.WellKnownNamespaces.trace
5491
+ ];
5402
5492
  }
5403
- getChangedObjects(cursors, opts) {
5493
+ getChangedObjects(_ctx, cursors, opts) {
5404
5494
  return Effect3.gen(this, function* () {
5405
5495
  const objects = [];
5406
5496
  const updatedCursors = [];
5407
- const existingSpaceIds = new Set(cursors.map((c) => c.spaceId).filter(Boolean));
5408
- const allSpaceIds = this._getSpaceIds();
5409
- const augmentedCursors = [
5497
+ let augmentedCursors = [
5410
5498
  ...cursors
5411
- ];
5412
- for (const spaceId of allSpaceIds) {
5413
- if (!existingSpaceIds.has(spaceId)) {
5414
- augmentedCursors.push({
5415
- spaceId,
5416
- resourceId: null,
5417
- cursor: ""
5418
- });
5499
+ ].filter((c) => c.resourceId !== null);
5500
+ for (const spaceId of this._getSpaceIds()) {
5501
+ for (const feedNamespace of this._feedNamespaces) {
5502
+ if (!augmentedCursors.some((c) => c.spaceId === spaceId && c.resourceId === feedNamespace)) {
5503
+ augmentedCursors.push({
5504
+ spaceId,
5505
+ resourceId: feedNamespace,
5506
+ cursor: ""
5507
+ });
5508
+ }
5419
5509
  }
5420
5510
  }
5421
5511
  let remainingLimit = opts?.limit ?? Infinity;
@@ -5428,27 +5518,36 @@ var QueueDataSource = class {
5428
5518
  updatedCursors.push(cursor);
5429
5519
  continue;
5430
5520
  }
5431
- const currentCursor = typeof cursor.cursor === "string" && cursor.cursor !== "" ? FeedCursor.make(cursor.cursor) : void 0;
5521
+ if (FeedProtocol2.WellKnownNamespaces.data !== cursor.resourceId && FeedProtocol2.WellKnownNamespaces.trace !== cursor.resourceId) {
5522
+ log12.warn("Ignoring cursor with invaliding feed namespace", {
5523
+ namespace: cursor.resourceId
5524
+ }, {
5525
+ F: __dxlog_file15,
5526
+ L: 107,
5527
+ S: this,
5528
+ C: (f, a) => f(...a)
5529
+ });
5530
+ updatedCursors.push(cursor);
5531
+ continue;
5532
+ }
5533
+ const currentCursor = typeof cursor.cursor === "string" && cursor.cursor !== "" ? FeedProtocol2.FeedCursor.make(cursor.cursor) : void 0;
5432
5534
  try {
5433
5535
  const result = yield* this._feedStore.query({
5434
5536
  spaceId: cursor.spaceId,
5537
+ feedNamespace: cursor.resourceId,
5435
5538
  cursor: currentCursor,
5436
- query: {
5437
- // Query all feeds in data namespace
5438
- feedNamespace: "data"
5439
- },
5440
5539
  limit: remainingLimit
5441
5540
  });
5442
5541
  for (const block of result.blocks) {
5443
5542
  try {
5444
- const dataString = new TextDecoder().decode(block.data);
5445
- const data = JSON.parse(dataString);
5543
+ const data = EchoFeedCodec2.decode(block.data);
5446
5544
  objects.push({
5447
5545
  spaceId: cursor.spaceId,
5448
5546
  queueId: block.feedId ?? failedInvariant(),
5449
5547
  documentId: null,
5450
5548
  recordId: null,
5451
- data
5549
+ data,
5550
+ updatedAt: block.timestamp
5452
5551
  });
5453
5552
  } catch (err) {
5454
5553
  log12.warn("Failed to parse block data for indexing", {
@@ -5456,7 +5555,7 @@ var QueueDataSource = class {
5456
5555
  err
5457
5556
  }, {
5458
5557
  F: __dxlog_file15,
5459
- L: 114,
5558
+ L: 141,
5460
5559
  S: this,
5461
5560
  C: (f, a) => f(...a)
5462
5561
  });
@@ -5465,7 +5564,7 @@ var QueueDataSource = class {
5465
5564
  remainingLimit -= result.blocks.length;
5466
5565
  updatedCursors.push({
5467
5566
  spaceId: cursor.spaceId,
5468
- resourceId: null,
5567
+ resourceId: cursor.resourceId,
5469
5568
  cursor: result.nextCursor
5470
5569
  });
5471
5570
  } catch (error) {
@@ -5474,7 +5573,7 @@ var QueueDataSource = class {
5474
5573
  error
5475
5574
  }, {
5476
5575
  F: __dxlog_file15,
5477
- L: 125,
5576
+ L: 152,
5478
5577
  S: this,
5479
5578
  C: (f, a) => f(...a)
5480
5579
  });
@@ -5490,15 +5589,15 @@ var QueueDataSource = class {
5490
5589
 
5491
5590
  // src/db-host/space-state-manager.ts
5492
5591
  import { interpretAsDocumentId as interpretAsDocumentId3 } from "@automerge/automerge-repo";
5493
- import isEqual from "lodash.isequal";
5592
+ import isEqual from "fast-deep-equal";
5494
5593
  import { Event as Event4, UpdateScheduler as UpdateScheduler3 } from "@dxos/async";
5495
- import { Context as Context7, LifecycleState as LifecycleState4, Resource as Resource8 } from "@dxos/context";
5496
- import { invariant as invariant13 } from "@dxos/invariant";
5594
+ import { Context as Context3, LifecycleState as LifecycleState4, Resource as Resource8 } from "@dxos/context";
5595
+ import { invariant as invariant12 } from "@dxos/invariant";
5497
5596
 
5498
5597
  // src/db-host/database-root.ts
5499
5598
  import { interpretAsDocumentId as interpretAsDocumentId2 } from "@automerge/automerge-repo";
5500
- import { DatabaseDirectory as DatabaseDirectory6, SpaceDocVersion as SpaceDocVersion3 } from "@dxos/echo-protocol";
5501
- import { invariant as invariant12 } from "@dxos/invariant";
5599
+ import { DatabaseDirectory as DatabaseDirectory4, SpaceDocVersion as SpaceDocVersion2 } from "@dxos/echo-protocol";
5600
+ import { invariant as invariant11 } from "@dxos/invariant";
5502
5601
 
5503
5602
  // src/db-host/automerge-metrics.ts
5504
5603
  import * as A5 from "@automerge/automerge";
@@ -5570,14 +5669,14 @@ var DatabaseRoot = class {
5570
5669
  if (!doc) {
5571
5670
  return null;
5572
5671
  }
5573
- return doc.version ?? SpaceDocVersion3.LEGACY;
5672
+ return doc.version ?? SpaceDocVersion2.LEGACY;
5574
5673
  }
5575
5674
  getSpaceKey() {
5576
5675
  const doc = this.doc();
5577
5676
  if (!doc) {
5578
5677
  return null;
5579
5678
  }
5580
- return DatabaseDirectory6.getSpaceKey(doc);
5679
+ return DatabaseDirectory4.getSpaceKey(doc);
5581
5680
  }
5582
5681
  getInlineObjectCount() {
5583
5682
  const doc = this.doc();
@@ -5595,7 +5694,7 @@ var DatabaseRoot = class {
5595
5694
  }
5596
5695
  getAllLinkedDocuments() {
5597
5696
  const doc = this.doc();
5598
- invariant12(doc, void 0, {
5697
+ invariant11(doc, void 0, {
5599
5698
  F: __dxlog_file17,
5600
5699
  L: 88,
5601
5700
  S: this,
@@ -5642,7 +5741,7 @@ var SpaceStateManager = class extends Resource8 {
5642
5741
  return this._rootBySpace.get(spaceId);
5643
5742
  }
5644
5743
  getRootBySpaceId(spaceId) {
5645
- invariant13(this._lifecycleState === LifecycleState4.OPEN, void 0, {
5744
+ invariant12(this._lifecycleState === LifecycleState4.OPEN, void 0, {
5646
5745
  F: __dxlog_file18,
5647
5746
  L: 48,
5648
5747
  S: this,
@@ -5674,7 +5773,7 @@ var SpaceStateManager = class extends Resource8 {
5674
5773
  this._perRootContext.delete(prevRootId);
5675
5774
  }
5676
5775
  this._rootBySpace.set(spaceId, root.handle.documentId);
5677
- const ctx = new Context7(void 0, {
5776
+ const ctx = new Context3(void 0, {
5678
5777
  F: __dxlog_file18,
5679
5778
  L: 76
5680
5779
  });
@@ -5712,120 +5811,58 @@ var SpaceDocumentListUpdatedEvent = class {
5712
5811
  }
5713
5812
  };
5714
5813
 
5715
- // src/db-host/stub.ts
5716
- var QueueServiceStub = class {
5717
- queryQueue(request) {
5718
- throw new Error("Not available.");
5719
- }
5720
- insertIntoQueue(request) {
5721
- throw new Error("Not available.");
5722
- }
5723
- deleteFromQueue(request) {
5724
- throw new Error("Not available.");
5725
- }
5726
- };
5727
-
5728
5814
  // src/db-host/echo-host.ts
5815
+ import * as Effect4 from "effect/Effect";
5729
5816
  var __dxlog_file19 = "/__w/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/echo-host.ts";
5730
- var DEFAULT_INDEXING_CONFIG = {
5731
- // TODO(mykola): Enable by default when SQLite indexer is stable.
5732
- sqlIndex: false,
5733
- vector: false
5734
- };
5735
5817
  var EchoHost = class extends Resource9 {
5736
- _indexMetadataStore;
5737
- _indexer;
5738
5818
  _automergeHost;
5739
5819
  _queryService;
5740
5820
  _dataService;
5741
5821
  _spaceStateManager = new SpaceStateManager();
5742
5822
  _echoDataMonitor;
5743
5823
  _automergeDataSource;
5744
- _indexer2;
5745
- _indexConfig;
5824
+ _indexEngine;
5746
5825
  _runtime;
5747
5826
  _feedStore;
5748
5827
  _queueDataSource;
5749
5828
  _updateIndexes;
5750
5829
  _queuesService;
5751
5830
  _indexesUpToDate = false;
5752
- constructor({ kv, localQueues, indexing = {}, peerIdProvider, getSpaceKeyByRootDocumentId, runtime, assignQueuePositions = false }) {
5831
+ constructor({ kv, peerIdProvider, getSpaceKeyByRootDocumentId, runtime, assignQueuePositions = false, syncQueue }) {
5753
5832
  super();
5754
- this._indexConfig = {
5755
- ...DEFAULT_INDEXING_CONFIG,
5756
- ...indexing
5757
- };
5758
- this._indexMetadataStore = new IndexMetadataStore({
5759
- db: kv.sublevel("index-metadata")
5760
- });
5761
5833
  this._echoDataMonitor = new EchoDataMonitor();
5762
5834
  this._automergeHost = new AutomergeHost({
5763
5835
  db: kv,
5764
5836
  dataMonitor: this._echoDataMonitor,
5765
- indexMetadataStore: this._indexMetadataStore,
5766
5837
  peerIdProvider,
5767
5838
  getSpaceKeyByRootDocumentId
5768
5839
  });
5769
5840
  this._runtime = runtime;
5770
5841
  this._automergeDataSource = new AutomergeDataSource(this._automergeHost);
5771
- if (localQueues) {
5772
- this._feedStore = new FeedStore({
5773
- assignPositions: assignQueuePositions,
5774
- localActorId: crypto.randomUUID()
5775
- });
5776
- this._queueDataSource = new QueueDataSource({
5777
- feedStore: this._feedStore,
5778
- runtime: this._runtime,
5779
- getSpaceIds: () => this._spaceStateManager.spaceIds
5780
- });
5781
- this._queuesService = new LocalQueueServiceImpl(runtime, this._feedStore);
5782
- } else {
5783
- this._queuesService = new QueueServiceStub();
5784
- }
5785
- this._indexer = new Indexer({
5786
- db: kv,
5787
- indexStore: new IndexStore({
5788
- db: kv.sublevel("index-storage")
5789
- }),
5790
- metadataStore: this._indexMetadataStore,
5791
- loadDocuments: createSelectedDocumentsIterator(this._automergeHost),
5792
- indexCooldownTime: false ? 0 : void 0
5793
- });
5794
- void this._indexer.setConfig({
5795
- enabled: true,
5796
- indexes: [
5797
- //
5798
- {
5799
- kind: IndexKind.Kind.SCHEMA_MATCH
5800
- },
5801
- {
5802
- kind: IndexKind.Kind.GRAPH
5803
- },
5804
- ...this._indexConfig.vector ? [
5805
- {
5806
- kind: IndexKind.Kind.VECTOR
5807
- }
5808
- ] : []
5809
- ]
5842
+ this._feedStore = new FeedStore({
5843
+ assignPositions: assignQueuePositions,
5844
+ localActorId: crypto.randomUUID()
5845
+ });
5846
+ this._queueDataSource = new QueueDataSource({
5847
+ feedStore: this._feedStore,
5848
+ runtime: this._runtime,
5849
+ getSpaceIds: () => this._spaceStateManager.spaceIds
5810
5850
  });
5811
- this._indexer2 = new IndexEngine();
5851
+ this._queuesService = new LocalQueueServiceImpl(runtime, this._feedStore, syncQueue);
5852
+ this._indexEngine = new IndexEngine();
5812
5853
  this._queryService = new QueryServiceImpl({
5813
5854
  automergeHost: this._automergeHost,
5814
- indexer: this._indexer,
5815
- indexer2: this._indexConfig.sqlIndex ? this._indexer2 : void 0,
5816
- runtime: this._indexConfig.sqlIndex ? this._runtime : void 0,
5855
+ indexEngine: this._indexEngine,
5856
+ runtime: this._runtime,
5817
5857
  spaceStateManager: this._spaceStateManager
5818
5858
  });
5819
5859
  this._dataService = new DataServiceImpl({
5820
5860
  automergeHost: this._automergeHost,
5821
5861
  spaceStateManager: this._spaceStateManager,
5822
5862
  updateIndexes: async () => {
5823
- await this._indexer.updateIndexes();
5824
- if (this._indexConfig.sqlIndex) {
5825
- do {
5826
- await this._updateIndexes.runBlocking();
5827
- } while (!this._indexesUpToDate);
5828
- }
5863
+ do {
5864
+ await this._updateIndexes.runBlocking();
5865
+ } while (!this._indexesUpToDate);
5829
5866
  }
5830
5867
  });
5831
5868
  trace5.diagnostic({
@@ -5866,6 +5903,9 @@ var EchoHost = class extends Resource9 {
5866
5903
  }
5867
5904
  });
5868
5905
  }
5906
+ get spaceIds() {
5907
+ return this._spaceStateManager.spaceIds;
5908
+ }
5869
5909
  get queryService() {
5870
5910
  return this._queryService;
5871
5911
  }
@@ -5878,30 +5918,87 @@ var EchoHost = class extends Resource9 {
5878
5918
  get roots() {
5879
5919
  return this._spaceStateManager.roots;
5880
5920
  }
5921
+ get feedStore() {
5922
+ return this._feedStore;
5923
+ }
5881
5924
  /**
5882
- * New index-core indexer for text and other queries.
5925
+ * Index engine for queries.
5883
5926
  */
5884
- get indexer2() {
5885
- return this._indexer2;
5927
+ get indexEngine() {
5928
+ return this._indexEngine;
5886
5929
  }
5887
5930
  async _open(ctx) {
5888
- await this._automergeHost.open();
5889
- await this._indexer.open(ctx);
5931
+ log14("echo-host: opening automerge host...", void 0, {
5932
+ F: __dxlog_file19,
5933
+ L: 211,
5934
+ S: this,
5935
+ C: (f, a) => f(...a)
5936
+ });
5937
+ await this._automergeHost.open(ctx);
5938
+ log14("echo-host: automerge host opened", void 0, {
5939
+ F: __dxlog_file19,
5940
+ L: 213,
5941
+ S: this,
5942
+ C: (f, a) => f(...a)
5943
+ });
5944
+ log14("echo-host: opening query service...", void 0, {
5945
+ F: __dxlog_file19,
5946
+ L: 215,
5947
+ S: this,
5948
+ C: (f, a) => f(...a)
5949
+ });
5890
5950
  await this._queryService.open(ctx);
5951
+ log14("echo-host: query service opened", void 0, {
5952
+ F: __dxlog_file19,
5953
+ L: 217,
5954
+ S: this,
5955
+ C: (f, a) => f(...a)
5956
+ });
5957
+ log14("echo-host: opening space state manager...", void 0, {
5958
+ F: __dxlog_file19,
5959
+ L: 219,
5960
+ S: this,
5961
+ C: (f, a) => f(...a)
5962
+ });
5891
5963
  await this._spaceStateManager.open(ctx);
5892
- if (this._feedStore) {
5893
- await RuntimeProvider3.runPromise(this._runtime)(this._feedStore.migrate());
5894
- this._feedStore.onNewBlocks.on(this._ctx, () => {
5895
- this._queryService.invalidateQueries();
5896
- if (this._indexConfig.sqlIndex) {
5897
- this._updateIndexes.schedule();
5898
- }
5899
- });
5900
- }
5901
- if (this._indexConfig.sqlIndex) {
5902
- await RuntimeProvider3.runPromise(this._runtime)(this._indexer2.migrate());
5903
- this._updateIndexes = new DeferredTask3(this._ctx, this._runUpdateIndexes);
5904
- }
5964
+ log14("echo-host: space state manager opened", void 0, {
5965
+ F: __dxlog_file19,
5966
+ L: 221,
5967
+ S: this,
5968
+ C: (f, a) => f(...a)
5969
+ });
5970
+ await asyncTimeout2(RuntimeProvider3.runPromise(this._runtime)(testSqlite()), 15e3, new Error("SQLite quick check timed out"));
5971
+ log14("echo-host: running index engine migration...", void 0, {
5972
+ F: __dxlog_file19,
5973
+ L: 230,
5974
+ S: this,
5975
+ C: (f, a) => f(...a)
5976
+ });
5977
+ await RuntimeProvider3.runPromise(this._runtime)(this._indexEngine.migrate());
5978
+ log14("echo-host: index engine migration done", void 0, {
5979
+ F: __dxlog_file19,
5980
+ L: 232,
5981
+ S: this,
5982
+ C: (f, a) => f(...a)
5983
+ });
5984
+ this._updateIndexes = new DeferredTask3(this._ctx, this._runUpdateIndexes);
5985
+ log14("echo-host: running feed store migration...", void 0, {
5986
+ F: __dxlog_file19,
5987
+ L: 235,
5988
+ S: this,
5989
+ C: (f, a) => f(...a)
5990
+ });
5991
+ await RuntimeProvider3.runPromise(this._runtime)(this._feedStore.migrate());
5992
+ log14("echo-host: feed store migration done", void 0, {
5993
+ F: __dxlog_file19,
5994
+ L: 237,
5995
+ S: this,
5996
+ C: (f, a) => f(...a)
5997
+ });
5998
+ this._feedStore.onNewBlocks.on(this._ctx, () => {
5999
+ this._queryService.invalidateQueries();
6000
+ this._updateIndexes.schedule();
6001
+ });
5905
6002
  this._spaceStateManager.spaceDocumentListUpdated.on(this._ctx, (e) => {
5906
6003
  if (e.previousRootId) {
5907
6004
  void this._automergeHost.clearLocalCollectionState(deriveCollectionIdFromSpaceId(e.spaceId, e.previousRootId));
@@ -5910,31 +6007,34 @@ var EchoHost = class extends Resource9 {
5910
6007
  });
5911
6008
  this._automergeHost.documentsSaved.on(this._ctx, () => {
5912
6009
  this._queryService.invalidateQueries();
5913
- if (this._indexConfig.sqlIndex) {
5914
- this._updateIndexes.schedule();
5915
- }
5916
- });
5917
- if (this._indexConfig.sqlIndex) {
5918
6010
  this._updateIndexes.schedule();
5919
- }
6011
+ });
6012
+ this._updateIndexes.schedule();
6013
+ log14("echo-host: open complete", void 0, {
6014
+ F: __dxlog_file19,
6015
+ L: 257,
6016
+ S: this,
6017
+ C: (f, a) => f(...a)
6018
+ });
5920
6019
  }
5921
6020
  async _close(ctx) {
5922
6021
  await this._queryService.close(ctx);
5923
6022
  await this._spaceStateManager.close(ctx);
5924
- await this._indexer.close(ctx);
5925
6023
  await this._automergeHost.close();
5926
6024
  }
5927
6025
  /**
5928
6026
  * Flush all pending writes to the underlying storage.
5929
6027
  */
5930
- async flush() {
5931
- await this._automergeHost.flush();
6028
+ async flush(ctx) {
6029
+ await this._automergeHost.flush(ctx);
5932
6030
  }
5933
6031
  /**
5934
6032
  * Perform any pending index updates.
5935
6033
  */
5936
6034
  async updateIndexes() {
5937
- await this._indexer.updateIndexes();
6035
+ do {
6036
+ await this._updateIndexes.runBlocking();
6037
+ } while (!this._indexesUpToDate);
5938
6038
  }
5939
6039
  /**
5940
6040
  * Loads the document handle from the repo and waits for it to be ready.
@@ -5942,8 +6042,8 @@ var EchoHost = class extends Resource9 {
5942
6042
  async loadDoc(ctx, documentId, opts) {
5943
6043
  return await this._automergeHost.loadDoc(ctx, documentId, opts);
5944
6044
  }
5945
- async exportDoc(ctx, id) {
5946
- return await this._automergeHost.exportDoc(ctx, id);
6045
+ async exportDoc(id) {
6046
+ return await this._automergeHost.exportDoc(id);
5947
6047
  }
5948
6048
  /**
5949
6049
  * Create new persisted document.
@@ -5954,10 +6054,10 @@ var EchoHost = class extends Resource9 {
5954
6054
  /**
5955
6055
  * Create new space root.
5956
6056
  */
5957
- async createSpaceRoot(spaceKey) {
5958
- invariant14(this._lifecycleState === LifecycleState5.OPEN, void 0, {
6057
+ async createSpaceRoot(ctx, spaceKey) {
6058
+ invariant13(this._lifecycleState === LifecycleState5.OPEN, void 0, {
5959
6059
  F: __dxlog_file19,
5960
- L: 342,
6060
+ L: 304,
5961
6061
  S: this,
5962
6062
  A: [
5963
6063
  "this._lifecycleState === LifecycleState.OPEN",
@@ -5966,7 +6066,7 @@ var EchoHost = class extends Resource9 {
5966
6066
  });
5967
6067
  const spaceId = await createIdFromSpaceKey2(spaceKey);
5968
6068
  const automergeRoot = await this._automergeHost.createDoc({
5969
- version: SpaceDocVersion4.CURRENT,
6069
+ version: SpaceDocVersion3.CURRENT,
5970
6070
  access: {
5971
6071
  spaceKey: spaceKey.toHex()
5972
6072
  },
@@ -5974,28 +6074,25 @@ var EchoHost = class extends Resource9 {
5974
6074
  objects: {},
5975
6075
  links: {}
5976
6076
  });
5977
- await this._automergeHost.flush({
6077
+ await this._automergeHost.flush(ctx, {
5978
6078
  documentIds: [
5979
6079
  automergeRoot.documentId
5980
6080
  ]
5981
6081
  });
5982
- return await this.openSpaceRoot(spaceId, automergeRoot.url);
6082
+ return await this.openSpaceRoot(ctx, spaceId, automergeRoot.url);
5983
6083
  }
5984
6084
  // TODO(dmaretskyi): Change to document id.
5985
- async openSpaceRoot(spaceId, automergeUrl) {
5986
- invariant14(this._lifecycleState === LifecycleState5.OPEN, void 0, {
6085
+ async openSpaceRoot(ctx, spaceId, automergeUrl) {
6086
+ invariant13(this._lifecycleState === LifecycleState5.OPEN, void 0, {
5987
6087
  F: __dxlog_file19,
5988
- L: 361,
6088
+ L: 323,
5989
6089
  S: this,
5990
6090
  A: [
5991
6091
  "this._lifecycleState === LifecycleState.OPEN",
5992
6092
  ""
5993
6093
  ]
5994
6094
  });
5995
- const handle = await this._automergeHost.loadDoc(Context8.default(void 0, {
5996
- F: __dxlog_file19,
5997
- L: 362
5998
- }), automergeUrl, {
6095
+ const handle = await this._automergeHost.loadDoc(ctx, automergeUrl, {
5999
6096
  fetchFromNetwork: true
6000
6097
  });
6001
6098
  await handle.whenReady();
@@ -6008,8 +6105,8 @@ var EchoHost = class extends Resource9 {
6008
6105
  /**
6009
6106
  * Install data replicator.
6010
6107
  */
6011
- async addReplicator(replicator) {
6012
- await this._automergeHost.addReplicator(replicator);
6108
+ async addReplicator(ctx, replicator) {
6109
+ await this._automergeHost.addReplicator(ctx, replicator);
6013
6110
  }
6014
6111
  /**
6015
6112
  * Remove data replicator.
@@ -6028,22 +6125,28 @@ var EchoHost = class extends Resource9 {
6028
6125
  }
6029
6126
  this._automergeHost.refreshCollection(deriveCollectionIdFromSpaceId(spaceId, root.documentId));
6030
6127
  }
6128
+ /**
6129
+ * Get all feeds and their blocks for a space.
6130
+ * Used for space archive export.
6131
+ */
6132
+ async getAllFeedsForSpace(spaceId) {
6133
+ return RuntimeProvider3.runPromise(this._runtime)(this._feedStore.getAllFeedsForSpace({
6134
+ spaceId
6135
+ }));
6136
+ }
6031
6137
  _runUpdateIndexes = async () => {
6032
- if (!this._indexer2) {
6033
- return;
6034
- }
6035
6138
  let totalUpdated = 0;
6036
6139
  let totalDone = true;
6037
6140
  {
6038
- performance.mark("indexer2.update.automerge:start");
6039
- const { updated, done } = await this._indexer2.update(this._automergeDataSource, {
6141
+ performance.mark("indexEngine.update.automerge:start");
6142
+ const { updated, done } = await this._indexEngine.update(this._ctx, this._automergeDataSource, {
6040
6143
  spaceId: null,
6041
6144
  limit: 50
6042
6145
  }).pipe(RuntimeProvider3.runPromise(this._runtime));
6043
6146
  totalUpdated += updated;
6044
6147
  totalDone &&= done;
6045
6148
  performance.measure("Index Automerge", {
6046
- start: "indexer2.update.automerge:start",
6149
+ start: "indexEngine.update.automerge:start",
6047
6150
  detail: {
6048
6151
  devtools: {
6049
6152
  dataType: "track-entry",
@@ -6060,16 +6163,16 @@ var EchoHost = class extends Resource9 {
6060
6163
  }
6061
6164
  });
6062
6165
  }
6063
- if (this._queueDataSource) {
6064
- performance.mark("indexer2.update.queue:start");
6065
- const { updated, done } = await this._indexer2.update(this._queueDataSource, {
6166
+ {
6167
+ performance.mark("indexEngine.update.queue:start");
6168
+ const { updated, done } = await this._indexEngine.update(this._ctx, this._queueDataSource, {
6066
6169
  spaceId: null,
6067
6170
  limit: 50
6068
6171
  }).pipe(RuntimeProvider3.runPromise(this._runtime));
6069
6172
  totalUpdated += updated;
6070
6173
  totalDone &&= done;
6071
6174
  performance.measure("Index Queues", {
6072
- start: "indexer2.update.queue:start",
6175
+ start: "indexEngine.update.queue:start",
6073
6176
  detail: {
6074
6177
  devtools: {
6075
6178
  dataType: "track-entry",
@@ -6086,12 +6189,12 @@ var EchoHost = class extends Resource9 {
6086
6189
  }
6087
6190
  });
6088
6191
  }
6089
- log14.verbose("indexer2 update completed", {
6192
+ log14.verbose("indexEngine update completed", {
6090
6193
  updated: totalUpdated,
6091
6194
  done: totalDone
6092
6195
  }, {
6093
6196
  F: __dxlog_file19,
6094
- L: 452,
6197
+ L: 419,
6095
6198
  S: this,
6096
6199
  C: (f, a) => f(...a)
6097
6200
  });
@@ -6102,21 +6205,47 @@ var EchoHost = class extends Resource9 {
6102
6205
  } else {
6103
6206
  this._indexesUpToDate = true;
6104
6207
  }
6208
+ if (totalUpdated > 0) {
6209
+ this._queryService.invalidateQueries();
6210
+ }
6105
6211
  };
6106
6212
  };
6213
+ var testSqlite = () => Effect4.gen(function* () {
6214
+ const sql = yield* SqlClient.SqlClient;
6215
+ const databases = yield* sql`PRAGMA database_list`;
6216
+ log14("SQLite databases", {
6217
+ databases
6218
+ }, {
6219
+ F: __dxlog_file19,
6220
+ L: 449,
6221
+ S: this,
6222
+ C: (f, a) => f(...a)
6223
+ });
6224
+ const [result] = yield* sql`PRAGMA quick_check`;
6225
+ if (result.quick_check !== "ok") {
6226
+ throw new Error("SQLite quick check failed");
6227
+ }
6228
+ log14("SQLite quick check passed", void 0, {
6229
+ F: __dxlog_file19,
6230
+ L: 454,
6231
+ S: this,
6232
+ C: (f, a) => f(...a)
6233
+ });
6234
+ });
6107
6235
 
6108
6236
  // src/edge/echo-edge-replicator.ts
6109
6237
  import * as Automerge from "@automerge/automerge";
6110
6238
  import { cbor as cbor2 } from "@automerge/automerge-repo";
6111
6239
  import { Mutex, scheduleMicroTask as scheduleMicroTask2, scheduleTask as scheduleTask2 } from "@dxos/async";
6112
- import { Context as Context9, Resource as Resource11 } from "@dxos/context";
6240
+ import { Resource as Resource11 } from "@dxos/context";
6113
6241
  import { randomUUID } from "@dxos/crypto";
6114
- import { invariant as invariant15 } from "@dxos/invariant";
6242
+ import { invariant as invariant14 } from "@dxos/invariant";
6115
6243
  import { log as log16 } from "@dxos/log";
6116
6244
  import { DocumentCodec, EdgeService } from "@dxos/protocols";
6117
6245
  import { buf } from "@dxos/protocols/buf";
6118
6246
  import { MessageSchema as RouterMessageSchema } from "@dxos/protocols/buf/dxos/edge/messenger_pb";
6119
- import { bufferToArray as bufferToArray2, setDeep } from "@dxos/util";
6247
+ import { trace as trace6 } from "@dxos/tracing";
6248
+ import { bufferToArray as bufferToArray2, compositeKey as compositeKey2, setDeep } from "@dxos/util";
6120
6249
 
6121
6250
  // src/edge/inflight-request-limiter.ts
6122
6251
  import { Trigger as Trigger2 } from "@dxos/async";
@@ -6181,6 +6310,12 @@ var InflightRequestLimiter = class extends Resource10 {
6181
6310
  };
6182
6311
 
6183
6312
  // src/edge/echo-edge-replicator.ts
6313
+ function _ts_decorate6(decorators, target, key, desc) {
6314
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
6315
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
6316
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6317
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6318
+ }
6184
6319
  function _ts_add_disposable_resource(env, value, async) {
6185
6320
  if (value !== null && value !== void 0) {
6186
6321
  if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
@@ -6264,21 +6399,18 @@ var EchoEdgeReplicator = class {
6264
6399
  this._edgeHttpClient = edgeHttpClient;
6265
6400
  this._sharePolicyEnabled = !disableSharePolicy;
6266
6401
  }
6267
- async connect(context) {
6402
+ async connect(ctx, context) {
6268
6403
  log16("connecting...", {
6269
6404
  peerId: context.peerId,
6270
6405
  connectedSpaces: this._connectedSpaces.size
6271
6406
  }, {
6272
6407
  F: __dxlog_file21,
6273
- L: 74,
6408
+ L: 76,
6274
6409
  S: this,
6275
6410
  C: (f, a) => f(...a)
6276
6411
  });
6277
6412
  this._context = context;
6278
- this._ctx = Context9.default(void 0, {
6279
- F: __dxlog_file21,
6280
- L: 76
6281
- });
6413
+ this._ctx = ctx.derive();
6282
6414
  this._ctx.onDispose(this._edgeConnection.onReconnected(() => {
6283
6415
  this._ctx && scheduleMicroTask2(this._ctx, () => this._handleReconnect());
6284
6416
  }));
@@ -6330,7 +6462,7 @@ var EchoEdgeReplicator = class {
6330
6462
  _ts_dispose_resources(env);
6331
6463
  }
6332
6464
  }
6333
- async connectToSpace(spaceId) {
6465
+ async connectToSpace(ctx, spaceId) {
6334
6466
  const env = {
6335
6467
  stack: [],
6336
6468
  error: void 0,
@@ -6341,7 +6473,7 @@ var EchoEdgeReplicator = class {
6341
6473
  spaceId
6342
6474
  }, {
6343
6475
  F: __dxlog_file21,
6344
- L: 111,
6476
+ L: 114,
6345
6477
  S: this,
6346
6478
  C: (f, a) => f(...a)
6347
6479
  });
@@ -6382,18 +6514,18 @@ var EchoEdgeReplicator = class {
6382
6514
  }
6383
6515
  }
6384
6516
  async _openConnection(spaceId, reconnects = 0) {
6385
- invariant15(this._context, void 0, {
6517
+ invariant14(this._context, void 0, {
6386
6518
  F: __dxlog_file21,
6387
- L: 138,
6519
+ L: 141,
6388
6520
  S: this,
6389
6521
  A: [
6390
6522
  "this._context",
6391
6523
  ""
6392
6524
  ]
6393
6525
  });
6394
- invariant15(!this._connections.has(spaceId), void 0, {
6526
+ invariant14(!this._connections.has(spaceId), void 0, {
6395
6527
  F: __dxlog_file21,
6396
- L: 139,
6528
+ L: 142,
6397
6529
  S: this,
6398
6530
  A: [
6399
6531
  "!this._connections.has(spaceId)",
@@ -6412,7 +6544,7 @@ var EchoEdgeReplicator = class {
6412
6544
  spaceId
6413
6545
  }, {
6414
6546
  F: __dxlog_file21,
6415
- L: 150,
6547
+ L: 153,
6416
6548
  S: this,
6417
6549
  C: (f, a) => f(...a)
6418
6550
  });
@@ -6423,7 +6555,7 @@ var EchoEdgeReplicator = class {
6423
6555
  spaceId
6424
6556
  }, {
6425
6557
  F: __dxlog_file21,
6426
- L: 154,
6558
+ L: 157,
6427
6559
  S: this,
6428
6560
  C: (f, a) => f(...a)
6429
6561
  });
@@ -6440,7 +6572,7 @@ var EchoEdgeReplicator = class {
6440
6572
  restartDelay
6441
6573
  }, {
6442
6574
  F: __dxlog_file21,
6443
- L: 165,
6575
+ L: 168,
6444
6576
  S: this,
6445
6577
  C: (f, a) => f(...a)
6446
6578
  });
@@ -6468,7 +6600,7 @@ var EchoEdgeReplicator = class {
6468
6600
  restartDelay
6469
6601
  }, {
6470
6602
  F: __dxlog_file21,
6471
- L: 182,
6603
+ L: 185,
6472
6604
  S: this,
6473
6605
  C: (f, a) => f(...a)
6474
6606
  });
@@ -6486,6 +6618,14 @@ var EchoEdgeReplicator = class {
6486
6618
  await connection.open();
6487
6619
  }
6488
6620
  };
6621
+ _ts_decorate6([
6622
+ trace6.span({
6623
+ showInBrowserTimeline: true
6624
+ })
6625
+ ], EchoEdgeReplicator.prototype, "connectToSpace", null);
6626
+ EchoEdgeReplicator = _ts_decorate6([
6627
+ trace6.resource()
6628
+ ], EchoEdgeReplicator);
6489
6629
  var MAX_INFLIGHT_REQUESTS = 5;
6490
6630
  var MAX_RATE_LIMIT_WAIT_TIME_MS = 3e3;
6491
6631
  var EdgeReplicatorConnection = class extends Resource11 {
@@ -6514,8 +6654,8 @@ var EdgeReplicatorConnection = class extends Resource11 {
6514
6654
  this._edgeHttpClient = edgeHttpClient;
6515
6655
  this._spaceId = spaceId;
6516
6656
  this._context = context;
6517
- this._remotePeerId = `${EdgeService.AUTOMERGE_REPLICATOR}:${spaceId}-${this._connectionId}`;
6518
- this._targetServiceId = `${EdgeService.AUTOMERGE_REPLICATOR}:${spaceId}`;
6657
+ this._targetServiceId = compositeKey2(EdgeService.AUTOMERGE_REPLICATOR, spaceId);
6658
+ this._remotePeerId = `${this._targetServiceId}-${this._connectionId}`;
6519
6659
  this._sharedPolicyEnabled = sharedPolicyEnabled;
6520
6660
  this._onRemoteConnected = onRemoteConnected;
6521
6661
  this._onRemoteDisconnected = onRemoteDisconnected;
@@ -6528,14 +6668,14 @@ var EdgeReplicatorConnection = class extends Resource11 {
6528
6668
  this.writable = new WritableStream({
6529
6669
  write: async (message, controller) => {
6530
6670
  await this._requestLimiter.rateLimit(message);
6531
- await this._sendMessage(message);
6671
+ await this._sendMessage(this._ctx, message);
6532
6672
  }
6533
6673
  });
6534
6674
  }
6535
6675
  async _open(ctx) {
6536
6676
  log16("opening...", void 0, {
6537
6677
  F: __dxlog_file21,
6538
- L: 275,
6678
+ L: 279,
6539
6679
  S: this,
6540
6680
  C: (f, a) => f(...a)
6541
6681
  });
@@ -6550,7 +6690,7 @@ var EdgeReplicatorConnection = class extends Resource11 {
6550
6690
  if (firstReconnect) {
6551
6691
  log16.verbose("first reconnect skipped", void 0, {
6552
6692
  F: __dxlog_file21,
6553
- L: 290,
6693
+ L: 294,
6554
6694
  S: this,
6555
6695
  C: (f, a) => f(...a)
6556
6696
  });
@@ -6562,10 +6702,10 @@ var EdgeReplicatorConnection = class extends Resource11 {
6562
6702
  );
6563
6703
  await this._onRemoteConnected();
6564
6704
  }
6565
- async _close() {
6705
+ async _close(ctx) {
6566
6706
  log16("closing...", void 0, {
6567
6707
  F: __dxlog_file21,
6568
- L: 303,
6708
+ L: 307,
6569
6709
  S: this,
6570
6710
  C: (f, a) => f(...a)
6571
6711
  });
@@ -6574,9 +6714,9 @@ var EdgeReplicatorConnection = class extends Resource11 {
6574
6714
  await this._onRemoteDisconnected();
6575
6715
  }
6576
6716
  get peerId() {
6577
- invariant15(this._remotePeerId, "Not connected", {
6717
+ invariant14(this._remotePeerId, "Not connected", {
6578
6718
  F: __dxlog_file21,
6579
- L: 312,
6719
+ L: 316,
6580
6720
  S: this,
6581
6721
  A: [
6582
6722
  "this._remotePeerId",
@@ -6601,7 +6741,7 @@ var EdgeReplicatorConnection = class extends Resource11 {
6601
6741
  remoteId: this._remotePeerId
6602
6742
  }, {
6603
6743
  F: __dxlog_file21,
6604
- L: 327,
6744
+ L: 331,
6605
6745
  S: this,
6606
6746
  C: (f, a) => f(...a)
6607
6747
  });
@@ -6626,7 +6766,7 @@ var EdgeReplicatorConnection = class extends Resource11 {
6626
6766
  remoteId: this._remotePeerId
6627
6767
  }, {
6628
6768
  F: __dxlog_file21,
6629
- L: 356,
6769
+ L: 360,
6630
6770
  S: this,
6631
6771
  C: (f, a) => f(...a)
6632
6772
  });
@@ -6636,7 +6776,7 @@ var EdgeReplicatorConnection = class extends Resource11 {
6636
6776
  get bundleSyncEnabled() {
6637
6777
  return true;
6638
6778
  }
6639
- async pushBundle(bundle) {
6779
+ async pushBundle(ctx, bundle) {
6640
6780
  const request = {
6641
6781
  bundle: bundle.map(({ documentId, data, heads }) => ({
6642
6782
  documentId,
@@ -6644,13 +6784,13 @@ var EdgeReplicatorConnection = class extends Resource11 {
6644
6784
  heads
6645
6785
  }))
6646
6786
  };
6647
- await this._edgeHttpClient.importBundle(this._spaceId, request);
6787
+ await this._edgeHttpClient.importBundle(ctx, this._spaceId, request);
6648
6788
  }
6649
- async pullBundle(docHeads) {
6789
+ async pullBundle(ctx, docHeads) {
6650
6790
  const request = {
6651
6791
  docHeads
6652
6792
  };
6653
- const response = await this._edgeHttpClient.exportBundle(this._spaceId, request);
6793
+ const response = await this._edgeHttpClient.exportBundle(ctx, this._spaceId, request);
6654
6794
  return Object.fromEntries(response.bundle.map((doc) => [
6655
6795
  doc.documentId,
6656
6796
  DocumentCodec.decode(doc.mutation)
@@ -6662,7 +6802,7 @@ var EdgeReplicatorConnection = class extends Resource11 {
6662
6802
  error: message.message
6663
6803
  }, {
6664
6804
  F: __dxlog_file21,
6665
- L: 392,
6805
+ L: 396,
6666
6806
  S: this,
6667
6807
  C: (f, a) => f(...a)
6668
6808
  });
@@ -6672,7 +6812,7 @@ var EdgeReplicatorConnection = class extends Resource11 {
6672
6812
  this._requestLimiter.handleResponse(message);
6673
6813
  this._readableStreamController.enqueue(message);
6674
6814
  }
6675
- async _sendMessage(message) {
6815
+ async _sendMessage(ctx, message) {
6676
6816
  message.targetId = this._targetServiceId;
6677
6817
  setDeep(message, [
6678
6818
  "metadata",
@@ -6687,13 +6827,13 @@ var EdgeReplicatorConnection = class extends Resource11 {
6687
6827
  remoteId: this._remotePeerId
6688
6828
  }, {
6689
6829
  F: __dxlog_file21,
6690
- L: 410,
6830
+ L: 414,
6691
6831
  S: this,
6692
6832
  C: (f, a) => f(...a)
6693
6833
  });
6694
6834
  const encoded = cbor2.encode(message);
6695
6835
  try {
6696
- await this._edgeConnection.send(buf.create(RouterMessageSchema, {
6836
+ await this._edgeConnection.send(ctx, buf.create(RouterMessageSchema, {
6697
6837
  serviceId: this._targetServiceId,
6698
6838
  source: {
6699
6839
  identityKey: this._edgeConnection.identityKey,
@@ -6708,7 +6848,7 @@ var EdgeReplicatorConnection = class extends Resource11 {
6708
6848
  err
6709
6849
  }, {
6710
6850
  F: __dxlog_file21,
6711
- L: 429,
6851
+ L: 434,
6712
6852
  S: this,
6713
6853
  C: (f, a) => f(...a)
6714
6854
  });
@@ -6734,13 +6874,13 @@ var getMessageInfo = (msg) => {
6734
6874
  };
6735
6875
 
6736
6876
  // src/util.ts
6737
- import { EncodedReference, ObjectStructure as ObjectStructure2 } from "@dxos/echo-protocol";
6877
+ import { EncodedReference as EncodedReference2, ObjectStructure as ObjectStructure2 } from "@dxos/echo-protocol";
6738
6878
  var findInlineObjectOfType = (spaceDoc, typename) => {
6739
6879
  for (const id in spaceDoc.objects ?? {}) {
6740
6880
  const obj = spaceDoc.objects[id];
6741
6881
  const objType = ObjectStructure2.getTypeReference(obj);
6742
6882
  if (objType) {
6743
- const typeDXN = EncodedReference.toDXN(objType);
6883
+ const typeDXN = EncodedReference2.toDXN(objType);
6744
6884
  const typeDXNInfo = typeDXN.asTypeDXN();
6745
6885
  if (typeDXNInfo?.type === typename) {
6746
6886
  return [