@dxos/echo-pipeline 0.8.4-main.a4bbb77 → 0.8.4-main.abd8ff62ef

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 (189) hide show
  1. package/dist/lib/{browser/chunk-XGG76KKU.mjs → neutral/chunk-VIHYDCCC.mjs} +404 -963
  2. package/dist/lib/neutral/chunk-VIHYDCCC.mjs.map +7 -0
  3. package/dist/lib/{browser/chunk-BVR7OOZK.mjs → neutral/chunk-YBC6ONBZ.mjs} +23 -27
  4. package/dist/lib/neutral/chunk-YBC6ONBZ.mjs.map +7 -0
  5. package/dist/lib/{browser → neutral}/filter/index.mjs +1 -2
  6. package/dist/lib/{browser → neutral}/index.mjs +3143 -2206
  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 +103 -395
  10. package/dist/lib/neutral/testing/index.mjs.map +7 -0
  11. package/dist/types/src/automerge/automerge-host.d.ts +43 -23
  12. package/dist/types/src/automerge/automerge-host.d.ts.map +1 -1
  13. package/dist/types/src/automerge/automerge-repo.test.d.ts +1 -1
  14. package/dist/types/src/automerge/automerge-repo.test.d.ts.map +1 -1
  15. package/dist/types/src/automerge/collection-synchronizer.d.ts +5 -3
  16. package/dist/types/src/automerge/collection-synchronizer.d.ts.map +1 -1
  17. package/dist/types/src/automerge/echo-data-monitor.d.ts.map +1 -1
  18. package/dist/types/src/automerge/echo-network-adapter.d.ts +17 -11
  19. package/dist/types/src/automerge/echo-network-adapter.d.ts.map +1 -1
  20. package/dist/types/src/automerge/echo-replicator.d.ts +20 -16
  21. package/dist/types/src/automerge/echo-replicator.d.ts.map +1 -1
  22. package/dist/types/src/automerge/heads-store.d.ts +9 -2
  23. package/dist/types/src/automerge/heads-store.d.ts.map +1 -1
  24. package/dist/types/src/automerge/leveldb-storage-adapter.d.ts +4 -4
  25. package/dist/types/src/automerge/leveldb-storage-adapter.d.ts.map +1 -1
  26. package/dist/types/src/automerge/mesh-echo-replicator-connection.d.ts +8 -8
  27. package/dist/types/src/automerge/mesh-echo-replicator-connection.d.ts.map +1 -1
  28. package/dist/types/src/automerge/mesh-echo-replicator.d.ts +6 -5
  29. package/dist/types/src/automerge/mesh-echo-replicator.d.ts.map +1 -1
  30. package/dist/types/src/automerge/network-protocol.d.ts.map +1 -1
  31. package/dist/types/src/automerge/space-collection.d.ts.map +1 -1
  32. package/dist/types/src/common/feeds.d.ts.map +1 -1
  33. package/dist/types/src/common/space-id.d.ts.map +1 -1
  34. package/dist/types/src/db-host/automerge-data-source.d.ts +35 -0
  35. package/dist/types/src/db-host/automerge-data-source.d.ts.map +1 -0
  36. package/dist/types/src/db-host/automerge-data-source.test.d.ts +2 -0
  37. package/dist/types/src/db-host/automerge-data-source.test.d.ts.map +1 -0
  38. package/dist/types/src/db-host/automerge-metrics.d.ts.map +1 -1
  39. package/dist/types/src/db-host/data-service.d.ts +7 -6
  40. package/dist/types/src/db-host/data-service.d.ts.map +1 -1
  41. package/dist/types/src/db-host/database-root.d.ts.map +1 -1
  42. package/dist/types/src/db-host/documents-synchronizer.d.ts +8 -7
  43. package/dist/types/src/db-host/documents-synchronizer.d.ts.map +1 -1
  44. package/dist/types/src/db-host/echo-host.d.ts +58 -28
  45. package/dist/types/src/db-host/echo-host.d.ts.map +1 -1
  46. package/dist/types/src/db-host/index.d.ts +2 -0
  47. package/dist/types/src/db-host/index.d.ts.map +1 -1
  48. package/dist/types/src/db-host/invalidation-hint.d.ts +19 -0
  49. package/dist/types/src/db-host/invalidation-hint.d.ts.map +1 -0
  50. package/dist/types/src/db-host/local-queue-service.d.ts +19 -0
  51. package/dist/types/src/db-host/local-queue-service.d.ts.map +1 -0
  52. package/dist/types/src/db-host/query-invalidation.test.d.ts +2 -0
  53. package/dist/types/src/db-host/query-invalidation.test.d.ts.map +1 -0
  54. package/dist/types/src/db-host/query-service.d.ts +18 -10
  55. package/dist/types/src/db-host/query-service.d.ts.map +1 -1
  56. package/dist/types/src/db-host/queue-data-source.d.ts +38 -0
  57. package/dist/types/src/db-host/queue-data-source.d.ts.map +1 -0
  58. package/dist/types/src/db-host/queue-service.test.d.ts +2 -0
  59. package/dist/types/src/db-host/queue-service.test.d.ts.map +1 -0
  60. package/dist/types/src/db-host/space-state-manager.d.ts +1 -0
  61. package/dist/types/src/db-host/space-state-manager.d.ts.map +1 -1
  62. package/dist/types/src/db-host/stub.d.ts +11 -0
  63. package/dist/types/src/db-host/stub.d.ts.map +1 -0
  64. package/dist/types/src/edge/echo-edge-replicator.d.ts +7 -6
  65. package/dist/types/src/edge/echo-edge-replicator.d.ts.map +1 -1
  66. package/dist/types/src/edge/inflight-request-limiter.d.ts.map +1 -1
  67. package/dist/types/src/filter/filter-match.d.ts +2 -2
  68. package/dist/types/src/filter/filter-match.d.ts.map +1 -1
  69. package/dist/types/src/metadata/metadata-store.d.ts.map +1 -1
  70. package/dist/types/src/pipeline/message-selector.d.ts.map +1 -1
  71. package/dist/types/src/pipeline/pipeline.d.ts +2 -2
  72. package/dist/types/src/pipeline/pipeline.d.ts.map +1 -1
  73. package/dist/types/src/pipeline/timeframe-clock.d.ts.map +1 -1
  74. package/dist/types/src/query/errors.d.ts +16 -20
  75. package/dist/types/src/query/errors.d.ts.map +1 -1
  76. package/dist/types/src/query/plan.d.ts +59 -8
  77. package/dist/types/src/query/plan.d.ts.map +1 -1
  78. package/dist/types/src/query/query-executor.d.ts +62 -10
  79. package/dist/types/src/query/query-executor.d.ts.map +1 -1
  80. package/dist/types/src/query/query-planner.d.ts +10 -1
  81. package/dist/types/src/query/query-planner.d.ts.map +1 -1
  82. package/dist/types/src/space/admission-discovery-extension.d.ts.map +1 -1
  83. package/dist/types/src/space/auth.d.ts +3 -3
  84. package/dist/types/src/space/auth.d.ts.map +1 -1
  85. package/dist/types/src/space/control-pipeline.d.ts +4 -3
  86. package/dist/types/src/space/control-pipeline.d.ts.map +1 -1
  87. package/dist/types/src/space/space-manager.d.ts +7 -7
  88. package/dist/types/src/space/space-manager.d.ts.map +1 -1
  89. package/dist/types/src/space/space-protocol.d.ts +9 -8
  90. package/dist/types/src/space/space-protocol.d.ts.map +1 -1
  91. package/dist/types/src/space/space.d.ts +5 -5
  92. package/dist/types/src/space/space.d.ts.map +1 -1
  93. package/dist/types/src/testing/change-metadata.d.ts.map +1 -1
  94. package/dist/types/src/testing/index.d.ts +0 -2
  95. package/dist/types/src/testing/index.d.ts.map +1 -1
  96. package/dist/types/src/testing/test-agent-builder.d.ts.map +1 -1
  97. package/dist/types/src/testing/test-feed-builder.d.ts.map +1 -1
  98. package/dist/types/src/testing/test-network-adapter.d.ts +1 -1
  99. package/dist/types/src/testing/test-network-adapter.d.ts.map +1 -1
  100. package/dist/types/src/testing/test-replicator.d.ts +13 -13
  101. package/dist/types/src/testing/test-replicator.d.ts.map +1 -1
  102. package/dist/types/src/util.d.ts.map +1 -1
  103. package/dist/types/tsconfig.tsbuildinfo +1 -1
  104. package/package.json +51 -54
  105. package/src/automerge/automerge-host.test.ts +42 -23
  106. package/src/automerge/automerge-host.ts +163 -88
  107. package/src/automerge/automerge-repo.test.ts +149 -32
  108. package/src/automerge/collection-synchronizer.test.ts +19 -13
  109. package/src/automerge/collection-synchronizer.ts +69 -28
  110. package/src/automerge/echo-network-adapter.test.ts +2 -1
  111. package/src/automerge/echo-network-adapter.ts +40 -29
  112. package/src/automerge/echo-replicator.ts +21 -16
  113. package/src/automerge/heads-store.ts +42 -3
  114. package/src/automerge/leveldb-storage-adapter.ts +4 -4
  115. package/src/automerge/mesh-echo-replicator-connection.ts +8 -8
  116. package/src/automerge/mesh-echo-replicator.ts +14 -11
  117. package/src/db-host/automerge-data-source.test.ts +299 -0
  118. package/src/db-host/automerge-data-source.ts +186 -0
  119. package/src/db-host/data-service.ts +17 -10
  120. package/src/db-host/documents-synchronizer.test.ts +143 -14
  121. package/src/db-host/documents-synchronizer.ts +54 -51
  122. package/src/db-host/echo-host.ts +321 -86
  123. package/src/db-host/index.ts +2 -0
  124. package/src/db-host/invalidation-hint.ts +50 -0
  125. package/src/db-host/local-queue-service.ts +127 -0
  126. package/src/db-host/query-invalidation.test.ts +270 -0
  127. package/src/db-host/query-service.ts +110 -112
  128. package/src/db-host/queue-data-source.ts +159 -0
  129. package/src/db-host/queue-service.test.ts +145 -0
  130. package/src/db-host/space-state-manager.ts +5 -1
  131. package/src/db-host/stub.ts +33 -0
  132. package/src/edge/echo-edge-replicator.test.ts +9 -9
  133. package/src/edge/echo-edge-replicator.ts +76 -47
  134. package/src/filter/filter-match.test.ts +41 -25
  135. package/src/filter/filter-match.ts +33 -36
  136. package/src/metadata/metadata-store.ts +8 -5
  137. package/src/pipeline/pipeline-stress.test.ts +1 -3
  138. package/src/pipeline/pipeline.test.ts +0 -1
  139. package/src/pipeline/pipeline.ts +2 -3
  140. package/src/query/errors.ts +2 -2
  141. package/src/query/plan.ts +71 -8
  142. package/src/query/query-executor.ts +1170 -197
  143. package/src/query/query-planner.test.ts +854 -86
  144. package/src/query/query-planner.ts +408 -38
  145. package/src/space/admission-discovery-extension.ts +1 -1
  146. package/src/space/auth.ts +6 -6
  147. package/src/space/control-pipeline.test.ts +2 -2
  148. package/src/space/control-pipeline.ts +7 -7
  149. package/src/space/space-manager.ts +12 -17
  150. package/src/space/space-protocol.browser.test.ts +13 -12
  151. package/src/space/space-protocol.test.ts +13 -13
  152. package/src/space/space-protocol.ts +16 -15
  153. package/src/space/space.test.ts +2 -2
  154. package/src/space/space.ts +9 -10
  155. package/src/testing/index.ts +0 -2
  156. package/src/testing/test-agent-builder.ts +0 -1
  157. package/src/testing/test-network-adapter.ts +16 -3
  158. package/src/testing/test-replicator.ts +19 -18
  159. package/src/util.ts +7 -3
  160. package/dist/lib/browser/chunk-BVR7OOZK.mjs.map +0 -7
  161. package/dist/lib/browser/chunk-CGS2ULMK.mjs +0 -11
  162. package/dist/lib/browser/chunk-CGS2ULMK.mjs.map +0 -7
  163. package/dist/lib/browser/chunk-XGG76KKU.mjs.map +0 -7
  164. package/dist/lib/browser/index.mjs.map +0 -7
  165. package/dist/lib/browser/meta.json +0 -1
  166. package/dist/lib/browser/testing/index.mjs.map +0 -7
  167. package/dist/lib/node-esm/chunk-CHMJJ4DG.mjs +0 -2230
  168. package/dist/lib/node-esm/chunk-CHMJJ4DG.mjs.map +0 -7
  169. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  170. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  171. package/dist/lib/node-esm/chunk-L3ZEKVDR.mjs +0 -251
  172. package/dist/lib/node-esm/chunk-L3ZEKVDR.mjs.map +0 -7
  173. package/dist/lib/node-esm/filter/index.mjs +0 -13
  174. package/dist/lib/node-esm/filter/index.mjs.map +0 -7
  175. package/dist/lib/node-esm/index.mjs +0 -5560
  176. package/dist/lib/node-esm/index.mjs.map +0 -7
  177. package/dist/lib/node-esm/meta.json +0 -1
  178. package/dist/lib/node-esm/testing/index.mjs +0 -805
  179. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  180. package/dist/types/src/db-host/documents-iterator.d.ts +0 -7
  181. package/dist/types/src/db-host/documents-iterator.d.ts.map +0 -1
  182. package/dist/types/src/testing/test-data.d.ts +0 -18
  183. package/dist/types/src/testing/test-data.d.ts.map +0 -1
  184. package/dist/types/src/testing/test-schema.d.ts +0 -37
  185. package/dist/types/src/testing/test-schema.d.ts.map +0 -1
  186. package/src/db-host/documents-iterator.ts +0 -74
  187. package/src/testing/test-data.ts +0 -127
  188. package/src/testing/test-schema.ts +0 -53
  189. /package/dist/lib/{browser → neutral}/filter/index.mjs.map +0 -0
@@ -2,14 +2,31 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Order } from '@dxos/echo';
6
- import { type QueryAST } from '@dxos/echo-protocol';
5
+ import { Order, Query } from '@dxos/echo';
6
+ import { QueryAST } from '@dxos/echo-protocol';
7
7
  import { invariant } from '@dxos/invariant';
8
- import type { DXN, SpaceId } from '@dxos/keys';
8
+ import type { DXN } from '@dxos/keys';
9
9
 
10
10
  import { QueryError } from './errors';
11
11
  import { QueryPlan } from './plan';
12
12
 
13
+ /**
14
+ * Creates a QueryError with "Query too complex" message and includes the prettified query in the context.
15
+ */
16
+ const queryTooComplexError = (query: QueryAST.Query | null): QueryError => {
17
+ if (query === null) {
18
+ return new QueryError({
19
+ message: 'Query too complex',
20
+ context: { query: null },
21
+ });
22
+ }
23
+ const prettyQuery = Query.pretty(Query.fromAst(query));
24
+ return new QueryError({
25
+ message: `Query too complex: ${prettyQuery}`,
26
+ context: { query, prettyQuery },
27
+ });
28
+ };
29
+
13
30
  export type QueryPlannerOptions = {
14
31
  defaultTextSearchKind: QueryPlan.TextSearchKind;
15
32
  };
@@ -33,10 +50,12 @@ export class QueryPlanner {
33
50
  }
34
51
 
35
52
  createPlan(query: QueryAST.Query): QueryPlan.Plan {
53
+ this._validateQueryScoped(query);
36
54
  let plan = this._generate(query, { ...DEFAULT_CONTEXT, originalQuery: query });
37
55
  plan = this._optimizeEmptyFilters(plan);
38
56
  plan = this._optimizeSoloUnions(plan);
39
57
  plan = this._ensureOrderStep(plan);
58
+ plan = this._optimizeLimits(plan);
40
59
  return plan;
41
60
  }
42
61
 
@@ -56,12 +75,18 @@ export class QueryPlanner {
56
75
  return this._generateRelationTraversalClause(query, context);
57
76
  case 'reference-traversal':
58
77
  return this._generateReferenceTraversalClause(query, context);
78
+ case 'hierarchy-traversal':
79
+ return this._generateHierarchyTraversalClause(query, context);
59
80
  case 'union':
60
81
  return this._generateUnionClause(query, context);
61
82
  case 'set-difference':
62
83
  return this._generateSetDifferenceClause(query, context);
63
84
  case 'order':
64
85
  return this._generateOrderClause(query, context);
86
+ case 'limit':
87
+ return this._generateLimitClause(query, context);
88
+ case 'from':
89
+ return this._generateFromClause(query, context);
65
90
  default:
66
91
  throw new QueryError({
67
92
  message: `Unsupported query type: ${(query as any).type}`,
@@ -74,15 +99,25 @@ export class QueryPlanner {
74
99
  const newContext = {
75
100
  ...context,
76
101
  };
77
- if (query.options.spaceIds) {
78
- newContext.selectionSpaces = query.options.spaceIds as readonly SpaceId[];
79
- }
80
102
  if (query.options.deleted) {
81
103
  newContext.deletedHandling = query.options.deleted;
82
104
  }
83
105
  return this._generate(query.query, newContext);
84
106
  }
85
107
 
108
+ private _generateFromClause(query: QueryAST.QueryFromClause, context: GenerationContext): QueryPlan.Plan {
109
+ if (query.from._tag === 'scope') {
110
+ return this._generate(query.query, { ...context, scope: query.from.scope });
111
+ }
112
+
113
+ // Subquery from: flatten by rewriting the outer query's leaf select into a filter on the subquery.
114
+ const subquery = query.from.query;
115
+ const rewritten = QueryAST.map(query.query, (node) =>
116
+ node.type === 'select' ? { type: 'filter', selection: subquery, filter: node.filter } : node,
117
+ );
118
+ return this._generate(rewritten, context);
119
+ }
120
+
86
121
  private _generateSelectClause(query: QueryAST.QuerySelectClause, context: GenerationContext): QueryPlan.Plan {
87
122
  return this._generateSelectionFromFilter(query.filter, context);
88
123
  }
@@ -108,10 +143,7 @@ export class QueryPlanner {
108
143
  ]);
109
144
  }
110
145
  if (context.selectionInverted) {
111
- throw new QueryError({
112
- message: 'Query too complex',
113
- context: { query: context.originalQuery },
114
- });
146
+ throw queryTooComplexError(context.originalQuery);
115
147
  }
116
148
 
117
149
  // Try to utilize indexes during selection, prioritizing selecting by id, then by typename.
@@ -120,7 +152,7 @@ export class QueryPlanner {
120
152
  return QueryPlan.Plan.make([
121
153
  {
122
154
  _tag: 'SelectStep',
123
- spaces: context.selectionSpaces,
155
+ scope: context.scope,
124
156
  selector: {
125
157
  _tag: 'IdSelector',
126
158
  objectIds: filter.id,
@@ -136,7 +168,7 @@ export class QueryPlanner {
136
168
  return QueryPlan.Plan.make([
137
169
  {
138
170
  _tag: 'SelectStep',
139
- spaces: context.selectionSpaces,
171
+ scope: context.scope,
140
172
  selector: {
141
173
  _tag: 'TypeSelector',
142
174
  typename: [filter.typename as DXN.String],
@@ -144,16 +176,17 @@ export class QueryPlanner {
144
176
  },
145
177
  },
146
178
  ...this._generateDeletedHandlingSteps(context),
179
+ // TODO(dmaretskyi): Normally we could skip filtering by typename here, but since the index does not separate schema versions, we need to do additional filter to only select the correct version.
147
180
  {
148
181
  _tag: 'FilterStep',
149
- filter: { ...filter, typename: null },
182
+ filter: { ...filter },
150
183
  },
151
184
  ]);
152
185
  } else {
153
186
  return QueryPlan.Plan.make([
154
187
  {
155
188
  _tag: 'SelectStep',
156
- spaces: context.selectionSpaces,
189
+ scope: context.scope,
157
190
  selector: {
158
191
  _tag: 'WildcardSelector',
159
192
  },
@@ -172,7 +205,7 @@ export class QueryPlanner {
172
205
  return QueryPlan.Plan.make([
173
206
  {
174
207
  _tag: 'SelectStep',
175
- spaces: context.selectionSpaces,
208
+ scope: context.scope,
176
209
  selector: {
177
210
  _tag: 'WildcardSelector',
178
211
  },
@@ -190,24 +223,62 @@ export class QueryPlanner {
190
223
  return QueryPlan.Plan.make([
191
224
  {
192
225
  _tag: 'SelectStep',
193
- spaces: context.selectionSpaces,
226
+ scope: context.scope,
194
227
  selector: {
195
228
  _tag: 'TextSelector',
196
229
  text: filter.text,
197
230
  searchKind: filter.searchKind ?? this._options.defaultTextSearchKind,
231
+ typename: null,
198
232
  },
199
233
  },
200
234
  ...this._generateDeletedHandlingSteps(context),
201
235
  ]);
202
236
  }
203
237
 
238
+ // Timestamp
239
+ case 'timestamp': {
240
+ if (context.selectionInverted) {
241
+ throw new QueryError({
242
+ message:
243
+ 'Negated timestamp filters are not supported. Use Filter.updated/Filter.created with the inverted range instead.',
244
+ context: { query: context.originalQuery },
245
+ });
246
+ }
247
+ return QueryPlan.Plan.make([
248
+ {
249
+ _tag: 'SelectStep',
250
+ scope: context.scope,
251
+ selector: _timestampFilterToSelector(filter),
252
+ },
253
+ ...this._generateDeletedHandlingSteps(context),
254
+ ]);
255
+ }
256
+
257
+ // ChildOf
258
+ case 'child-of': {
259
+ return QueryPlan.Plan.make([
260
+ {
261
+ _tag: 'SelectStep',
262
+ scope: context.scope,
263
+ selector: {
264
+ _tag: 'WildcardSelector',
265
+ },
266
+ },
267
+ ...this._generateDeletedHandlingSteps(context),
268
+ {
269
+ _tag: 'FilterStep',
270
+ filter: { ...filter },
271
+ },
272
+ ]);
273
+ }
274
+
204
275
  // Compare
205
276
  case 'compare':
206
- throw new QueryError({ message: 'Query too complex', context: { query: context.originalQuery } });
277
+ throw queryTooComplexError(context.originalQuery);
207
278
  case 'in':
208
- throw new QueryError({ message: 'Query too complex', context: { query: context.originalQuery } });
279
+ throw queryTooComplexError(context.originalQuery);
209
280
  case 'range':
210
- throw new QueryError({ message: 'Query too complex', context: { query: context.originalQuery } });
281
+ throw queryTooComplexError(context.originalQuery);
211
282
 
212
283
  // Boolean
213
284
  case 'not':
@@ -215,8 +286,88 @@ export class QueryPlanner {
215
286
  ...context,
216
287
  selectionInverted: !context.selectionInverted,
217
288
  });
218
- case 'and':
219
- throw new QueryError({ message: 'Query too complex', context: { query: context.originalQuery } });
289
+ case 'and': {
290
+ const flatFilters = _flattenAnd(filter.filters);
291
+ const timestampFilters = flatFilters.filter((f): f is QueryAST.FilterTimestamp => f.type === 'timestamp');
292
+ const childOfFilters = flatFilters.filter((f): f is QueryAST.FilterChildOf => f.type === 'child-of');
293
+ const otherFilters = flatFilters.filter((f) => f.type !== 'timestamp' && f.type !== 'child-of');
294
+
295
+ if (timestampFilters.length > 0 && context.selectionInverted) {
296
+ throw new QueryError({
297
+ message:
298
+ 'Negated timestamp filters are not supported. Use Filter.updated/Filter.created with the inverted range instead.',
299
+ context: { query: context.originalQuery },
300
+ });
301
+ }
302
+
303
+ if (timestampFilters.length > 0 && otherFilters.length <= 1 && childOfFilters.length === 0) {
304
+ const innerFilter = otherFilters[0];
305
+ const innerPlan = innerFilter
306
+ ? this._generateSelectionFromFilter(innerFilter, context)
307
+ : QueryPlan.Plan.make([
308
+ {
309
+ _tag: 'SelectStep',
310
+ scope: context.scope,
311
+ selector: { _tag: 'WildcardSelector' },
312
+ },
313
+ ...this._generateDeletedHandlingSteps(context),
314
+ ]);
315
+
316
+ const selectIdx = innerPlan.steps.findIndex((s) => s._tag === 'SelectStep');
317
+ if (selectIdx !== -1) {
318
+ const newSteps = [...innerPlan.steps];
319
+ newSteps.splice(selectIdx + 1, 0, {
320
+ _tag: 'FilterStep',
321
+ filter: { type: 'and', filters: timestampFilters },
322
+ });
323
+ return QueryPlan.Plan.make(newSteps);
324
+ }
325
+
326
+ const selector = _mergeTimestampSelectors(timestampFilters.map(_timestampFilterToSelector));
327
+ return QueryPlan.Plan.make([
328
+ {
329
+ _tag: 'SelectStep',
330
+ scope: context.scope,
331
+ selector,
332
+ },
333
+ ...this._generateDeletedHandlingSteps(context),
334
+ ]);
335
+ }
336
+
337
+ if (timestampFilters.length > 0 && childOfFilters.length === 0) {
338
+ throw new QueryError({
339
+ message:
340
+ 'Timestamp filters can only be combined with a single type or property filter via AND. Split complex filters into a subquery.',
341
+ context: { query: context.originalQuery },
342
+ });
343
+ }
344
+
345
+ if (childOfFilters.length > 0) {
346
+ const remainingFilters = flatFilters.filter((f) => f.type !== 'child-of');
347
+ const innerPlan =
348
+ remainingFilters.length === 1
349
+ ? this._generateSelectionFromFilter(remainingFilters[0], context)
350
+ : remainingFilters.length > 1
351
+ ? this._generateSelectionFromFilter({ type: 'and', filters: remainingFilters }, context)
352
+ : QueryPlan.Plan.make([
353
+ {
354
+ _tag: 'SelectStep',
355
+ scope: context.scope,
356
+ selector: { _tag: 'WildcardSelector' },
357
+ },
358
+ ...this._generateDeletedHandlingSteps(context),
359
+ ]);
360
+
361
+ const childOfSteps: QueryPlan.Step[] = childOfFilters.map((f) => ({
362
+ _tag: 'FilterStep' as const,
363
+ filter: f,
364
+ }));
365
+
366
+ return QueryPlan.Plan.make([...innerPlan.steps, ...childOfSteps]);
367
+ }
368
+
369
+ throw queryTooComplexError(context.originalQuery);
370
+ }
220
371
  case 'or':
221
372
  // Optimized case
222
373
  if (filter.filters.every(isTrivialTypenameFilter)) {
@@ -228,7 +379,7 @@ export class QueryPlanner {
228
379
  return QueryPlan.Plan.make([
229
380
  {
230
381
  _tag: 'SelectStep',
231
- spaces: context.selectionSpaces,
382
+ scope: context.scope,
232
383
  selector: {
233
384
  _tag: 'TypeSelector',
234
385
  typename: typenames as DXN.String[],
@@ -236,9 +387,13 @@ export class QueryPlanner {
236
387
  },
237
388
  },
238
389
  ...this._generateDeletedHandlingSteps(context),
390
+ {
391
+ _tag: 'FilterStep',
392
+ filter: { ...filter },
393
+ },
239
394
  ]);
240
395
  } else {
241
- throw new QueryError({ message: 'Query too complex', context: { query: context.originalQuery } });
396
+ throw queryTooComplexError(context.originalQuery);
242
397
  }
243
398
 
244
399
  default:
@@ -321,7 +476,7 @@ export class QueryPlanner {
321
476
  traversal: {
322
477
  _tag: 'ReferenceTraversal',
323
478
  direction: 'incoming',
324
- property: query.property,
479
+ property: query.property ?? null,
325
480
  },
326
481
  },
327
482
  ...this._generateDeletedHandlingSteps(context),
@@ -427,6 +582,38 @@ export class QueryPlanner {
427
582
  ]);
428
583
  }
429
584
 
585
+ private _generateHierarchyTraversalClause(
586
+ query: QueryAST.QueryHierarchyTraversalClause,
587
+ context: GenerationContext,
588
+ ): QueryPlan.Plan {
589
+ return QueryPlan.Plan.make([
590
+ ...this._generate(query.anchor, context).steps,
591
+ {
592
+ _tag: 'TraverseStep',
593
+ traversal: {
594
+ _tag: 'HierarchyTraversal',
595
+ direction: query.direction,
596
+ },
597
+ },
598
+ ...this._generateDeletedHandlingSteps(context),
599
+ ]);
600
+ }
601
+
602
+ private _validateQueryScoped(query: QueryAST.Query): void {
603
+ let hasScope = false;
604
+ QueryAST.visit(query, (node) => {
605
+ if (node.type === 'from') {
606
+ hasScope = true;
607
+ }
608
+ });
609
+ if (!hasScope) {
610
+ throw new QueryError({
611
+ message: 'Query must be scoped with a from() clause',
612
+ context: { query },
613
+ });
614
+ }
615
+ }
616
+
430
617
  /**
431
618
  * Removes filter steps that have no predicates.
432
619
  */
@@ -471,29 +658,164 @@ export class QueryPlanner {
471
658
  ]);
472
659
  }
473
660
 
661
+ private _generateLimitClause(query: QueryAST.QueryLimitClause, context: GenerationContext): QueryPlan.Plan {
662
+ return QueryPlan.Plan.make([
663
+ ...this._generate(query.query, context).steps,
664
+ {
665
+ _tag: 'LimitStep',
666
+ limit: query.limit,
667
+ },
668
+ ]);
669
+ }
670
+
474
671
  // After complete plan is built, inspect it from the end:
475
672
  // - Walk backwards until hitting an object set changer.
476
673
  // - If an order step is found, skip.
477
- // - Otherwise append natural order to the end.
674
+ // - Otherwise insert natural order before any limit steps (since limit should be applied after ordering).
675
+ // This method is recursive and also processes sub-plans in unions and set differences.
478
676
  private _ensureOrderStep(plan: QueryPlan.Plan): QueryPlan.Plan {
677
+ // First, recursively process any sub-plans.
678
+ const processedSteps = plan.steps.map((step): QueryPlan.Step => {
679
+ if (step._tag === 'UnionStep') {
680
+ return {
681
+ _tag: 'UnionStep',
682
+ plans: step.plans.map((subPlan) => this._ensureOrderStep(subPlan)),
683
+ };
684
+ } else if (step._tag === 'SetDifferenceStep') {
685
+ return {
686
+ _tag: 'SetDifferenceStep',
687
+ source: this._ensureOrderStep(step.source),
688
+ exclude: this._ensureOrderStep(step.exclude),
689
+ };
690
+ }
691
+ return step;
692
+ });
693
+
694
+ const processedPlan = QueryPlan.Plan.make(processedSteps);
695
+
479
696
  const OBJECT_SET_CHANGERS = new Set(['SelectStep', 'TraverseStep', 'UnionStep', 'SetDifferenceStep']);
480
- for (let i = plan.steps.length - 1; i >= 0; i--) {
481
- const step = plan.steps[i];
697
+ for (let i = processedPlan.steps.length - 1; i >= 0; i--) {
698
+ const step = processedPlan.steps[i];
482
699
  if (step._tag === 'OrderStep') {
483
- return plan;
700
+ return processedPlan;
484
701
  }
485
702
  if (OBJECT_SET_CHANGERS.has(step._tag)) {
486
703
  break;
487
704
  }
488
705
  }
489
706
 
490
- return QueryPlan.Plan.make([
491
- ...plan.steps,
492
- {
493
- _tag: 'OrderStep',
494
- order: [Order.natural.ast],
495
- },
496
- ]);
707
+ // Find the position to insert the order step (before any limit steps).
708
+ let insertIndex = processedPlan.steps.length;
709
+ for (let i = processedPlan.steps.length - 1; i >= 0; i--) {
710
+ if (processedPlan.steps[i]._tag === 'LimitStep') {
711
+ insertIndex = i;
712
+ } else {
713
+ break;
714
+ }
715
+ }
716
+
717
+ const newSteps = [...processedPlan.steps];
718
+ newSteps.splice(insertIndex, 0, {
719
+ _tag: 'OrderStep',
720
+ order: [Order.natural.ast],
721
+ });
722
+
723
+ return QueryPlan.Plan.make(newSteps);
724
+ }
725
+
726
+ /**
727
+ * Propagates limits from LimitStep to SelectStep and OrderStep when possible.
728
+ * Limits can only be propagated if there are no unions or traversals between the LimitStep and SelectStep/OrderStep.
729
+ */
730
+ private _optimizeLimits(plan: QueryPlan.Plan): QueryPlan.Plan {
731
+ // First, recursively process any sub-plans.
732
+ const processedSteps = plan.steps.map((step): QueryPlan.Step => {
733
+ if (step._tag === 'UnionStep') {
734
+ return {
735
+ _tag: 'UnionStep',
736
+ plans: step.plans.map((subPlan) => this._optimizeLimits(subPlan)),
737
+ };
738
+ } else if (step._tag === 'SetDifferenceStep') {
739
+ return {
740
+ _tag: 'SetDifferenceStep',
741
+ source: this._optimizeLimits(step.source),
742
+ exclude: this._optimizeLimits(step.exclude),
743
+ };
744
+ }
745
+ return step;
746
+ });
747
+
748
+ // Find if there's a LimitStep at the end (possibly after OrderStep).
749
+ let limitStepIndex = -1;
750
+ let limitValue: number | undefined;
751
+
752
+ for (let i = processedSteps.length - 1; i >= 0; i--) {
753
+ const step = processedSteps[i];
754
+ if (step._tag === 'LimitStep') {
755
+ limitStepIndex = i;
756
+ limitValue = step.limit;
757
+ break;
758
+ }
759
+ // Only allow OrderStep after LimitStep when looking backwards.
760
+ if (step._tag !== 'OrderStep') {
761
+ break;
762
+ }
763
+ }
764
+
765
+ if (limitStepIndex === -1 || limitValue === undefined) {
766
+ return QueryPlan.Plan.make(processedSteps);
767
+ }
768
+
769
+ // Check if we can propagate the limit to a SelectStep and/or OrderStep.
770
+ // We can only do this if there are no unions, traversals, or set differences between them.
771
+ const BLOCKERS = new Set(['UnionStep', 'TraverseStep', 'SetDifferenceStep']);
772
+
773
+ let selectStepIndex = -1;
774
+ let orderStepIndex = -1;
775
+ for (let i = 0; i < limitStepIndex; i++) {
776
+ const step = processedSteps[i];
777
+ if (step._tag === 'SelectStep') {
778
+ selectStepIndex = i;
779
+ }
780
+ if (step._tag === 'OrderStep') {
781
+ orderStepIndex = i;
782
+ }
783
+ if (BLOCKERS.has(step._tag)) {
784
+ // Found a blocker after the select/order step - can't propagate.
785
+ selectStepIndex = -1;
786
+ orderStepIndex = -1;
787
+ }
788
+ }
789
+
790
+ if (selectStepIndex === -1 && orderStepIndex === -1) {
791
+ return QueryPlan.Plan.make(processedSteps);
792
+ }
793
+
794
+ // Create a mutable copy of steps to modify.
795
+ const newSteps = [...processedSteps];
796
+
797
+ // Propagate the limit to the SelectStep if found.
798
+ if (selectStepIndex !== -1) {
799
+ const selectStep = newSteps[selectStepIndex] as QueryPlan.SelectStep;
800
+ newSteps[selectStepIndex] = {
801
+ ...selectStep,
802
+ limit: limitValue,
803
+ };
804
+ }
805
+
806
+ // Propagate the limit to the OrderStep if found.
807
+ if (orderStepIndex !== -1) {
808
+ const orderStep = newSteps[orderStepIndex] as QueryPlan.OrderStep;
809
+ newSteps[orderStepIndex] = {
810
+ ...orderStep,
811
+ limit: limitValue,
812
+ };
813
+ }
814
+
815
+ // Remove the LimitStep since limit is now propagated.
816
+ newSteps.splice(limitStepIndex, 1);
817
+
818
+ return QueryPlan.Plan.make(newSteps);
497
819
  }
498
820
  }
499
821
 
@@ -507,9 +829,9 @@ type GenerationContext = {
507
829
  originalQuery: QueryAST.Query | null;
508
830
 
509
831
  /**
510
- * Which spaces to select from.
832
+ * The scope to select from (space IDs, queues, etc.).
511
833
  */
512
- selectionSpaces: readonly SpaceId[];
834
+ scope: QueryAST.Scope;
513
835
 
514
836
  /**
515
837
  * How to handle deleted objects.
@@ -524,7 +846,7 @@ type GenerationContext = {
524
846
 
525
847
  const DEFAULT_CONTEXT: GenerationContext = {
526
848
  originalQuery: null,
527
- selectionSpaces: [],
849
+ scope: {},
528
850
  deletedHandling: 'exclude',
529
851
  selectionInverted: false,
530
852
  };
@@ -544,6 +866,54 @@ const createRelationTraversalStep = (direction: QueryPlan.RelationTraversal['dir
544
866
  },
545
867
  });
546
868
 
869
+ /**
870
+ * Recursively flattens nested `and` filters into a single list.
871
+ */
872
+ const _flattenAnd = (filters: readonly QueryAST.Filter[]): QueryAST.Filter[] => {
873
+ const result: QueryAST.Filter[] = [];
874
+ for (const f of filters) {
875
+ if (f.type === 'and') {
876
+ result.push(..._flattenAnd(f.filters));
877
+ } else {
878
+ result.push(f);
879
+ }
880
+ }
881
+ return result;
882
+ };
883
+
884
+ const _timestampFilterToSelector = (filter: QueryAST.FilterTimestamp): QueryPlan.TimestampSelector => {
885
+ const selector: QueryPlan.TimestampSelector = { _tag: 'TimestampSelector' };
886
+ const key =
887
+ filter.field === 'updatedAt'
888
+ ? filter.operator === 'gte' || filter.operator === 'gt'
889
+ ? 'updatedAfter'
890
+ : 'updatedBefore'
891
+ : filter.operator === 'gte' || filter.operator === 'gt'
892
+ ? 'createdAfter'
893
+ : 'createdBefore';
894
+ selector[key] = filter.value;
895
+ return selector;
896
+ };
897
+
898
+ const _mergeTimestampSelectors = (selectors: QueryPlan.TimestampSelector[]): QueryPlan.TimestampSelector => {
899
+ const merged: QueryPlan.TimestampSelector = { _tag: 'TimestampSelector' };
900
+ for (const s of selectors) {
901
+ if (s.updatedAfter != null) {
902
+ merged.updatedAfter = Math.max(merged.updatedAfter ?? 0, s.updatedAfter);
903
+ }
904
+ if (s.updatedBefore != null) {
905
+ merged.updatedBefore = Math.min(merged.updatedBefore ?? Infinity, s.updatedBefore);
906
+ }
907
+ if (s.createdAfter != null) {
908
+ merged.createdAfter = Math.max(merged.createdAfter ?? 0, s.createdAfter);
909
+ }
910
+ if (s.createdBefore != null) {
911
+ merged.createdBefore = Math.min(merged.createdBefore ?? Infinity, s.createdBefore);
912
+ }
913
+ }
914
+ return merged;
915
+ };
916
+
547
917
  const isTrivialTypenameFilter = (filter: QueryAST.Filter): boolean => {
548
918
  return (
549
919
  filter.type === 'object' &&
@@ -81,7 +81,7 @@ export class CredentialServerExtension extends RpcExtension<
81
81
  ): Promise<GetAdmissionCredentialResponse> => {
82
82
  const memberInfo = this._space.spaceState.members.get(request.memberKey);
83
83
  if (!memberInfo?.credential) {
84
- throw new ProtocolError('Space member not found.', request);
84
+ throw new ProtocolError({ message: 'Space member not found.', context: { ...request } });
85
85
  }
86
86
  return { admissionCredential: memberInfo.credential };
87
87
  },
package/src/space/auth.ts CHANGED
@@ -15,7 +15,7 @@ export type AuthProvider = (nonce: Uint8Array) => Promise<Uint8Array | undefined
15
15
 
16
16
  export type AuthVerifier = (nonce: Uint8Array, credential: Uint8Array) => Promise<boolean>;
17
17
 
18
- export type AuthExtensionParams = {
18
+ export type AuthExtensionProps = {
19
19
  provider: AuthProvider;
20
20
  verifier: AuthVerifier;
21
21
  onAuthSuccess: () => void;
@@ -29,7 +29,7 @@ export class AuthExtension extends RpcExtension<Services, Services> {
29
29
  },
30
30
  });
31
31
 
32
- constructor(private readonly _authParams: AuthExtensionParams) {
32
+ constructor(private readonly _authProps: AuthExtensionProps) {
33
33
  super({
34
34
  requested: {
35
35
  AuthService: schema.getService('dxos.mesh.teleport.auth.AuthService'),
@@ -46,7 +46,7 @@ export class AuthExtension extends RpcExtension<Services, Services> {
46
46
  AuthService: {
47
47
  authenticate: async ({ challenge }) => {
48
48
  try {
49
- const credential = await this._authParams.provider(challenge);
49
+ const credential = await this._authProps.provider(challenge);
50
50
  if (!credential) {
51
51
  throw new Error('auth rejected');
52
52
  }
@@ -67,13 +67,13 @@ export class AuthExtension extends RpcExtension<Services, Services> {
67
67
  const challenge = randomBytes(32);
68
68
  const { credential } = await this.rpc.AuthService.authenticate({ challenge });
69
69
  invariant(credential?.length > 0, 'invalid credential');
70
- const success = await this._authParams.verifier(challenge, credential);
70
+ const success = await this._authProps.verifier(challenge, credential);
71
71
  invariant(success, 'credential not verified');
72
- runInContext(this._ctx, () => this._authParams.onAuthSuccess());
72
+ runInContext(this._ctx, () => this._authProps.onAuthSuccess());
73
73
  } catch (err) {
74
74
  log('auth failed', err);
75
75
  this.close();
76
- this._authParams.onAuthFailure();
76
+ this._authProps.onAuthFailure();
77
77
  }
78
78
  });
79
79
  }