@coasys/ad4m 0.13.0-test-2 → 0.13.0-test-3

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 (54) hide show
  1. package/lib/index.cjs +1060 -147
  2. package/lib/index.js +1054 -147
  3. package/lib/src/index.d.ts +0 -1
  4. package/lib/src/index.js +0 -1
  5. package/lib/src/language/Language.d.ts +26 -214
  6. package/lib/src/language/Language.js +28 -2
  7. package/lib/src/model/Ad4mModel.d.ts +25 -1
  8. package/lib/src/model/Ad4mModel.js +139 -30
  9. package/lib/src/model/Ad4mModel.test.js +214 -32
  10. package/lib/src/model/ModelQueryBuilder.d.ts +19 -0
  11. package/lib/src/model/ModelQueryBuilder.js +62 -18
  12. package/lib/src/model/hydration-batching.test.d.ts +7 -0
  13. package/lib/src/model/hydration-batching.test.js +456 -0
  14. package/lib/src/model/hydration.d.ts +1 -0
  15. package/lib/src/model/hydration.js +279 -70
  16. package/lib/src/model/query-sparql.d.ts +78 -1
  17. package/lib/src/model/query-sparql.js +447 -16
  18. package/lib/src/model/query-sparql.test.d.ts +1 -0
  19. package/lib/src/model/query-sparql.test.js +495 -0
  20. package/lib/src/model/query-utils.js +4 -0
  21. package/lib/src/model/subscription-delta.test.d.ts +24 -0
  22. package/lib/src/model/subscription-delta.test.js +180 -0
  23. package/lib/src/model/subscription-pool.js +48 -2
  24. package/lib/src/model/types.d.ts +49 -1
  25. package/lib/src/perspectives/PerspectiveClient.d.ts +2 -0
  26. package/lib/src/perspectives/PerspectiveClient.js +37 -9
  27. package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
  28. package/lib/src/perspectives/PerspectiveClient.test.js +169 -0
  29. package/lib/src/perspectives/PerspectiveProxy.d.ts +3 -0
  30. package/lib/src/perspectives/PerspectiveProxy.js +15 -0
  31. package/package.json +1 -1
  32. package/src/Ad4mClient.test.ts +56 -1
  33. package/src/index.ts +0 -1
  34. package/src/language/Language.ts +54 -275
  35. package/src/model/Ad4mModel.test.ts +222 -35
  36. package/src/model/Ad4mModel.ts +144 -30
  37. package/src/model/ModelQueryBuilder.ts +66 -18
  38. package/src/model/hydration-batching.test.ts +563 -0
  39. package/src/model/hydration.ts +249 -47
  40. package/src/model/query-sparql.test.ts +568 -0
  41. package/src/model/query-sparql.ts +473 -16
  42. package/src/model/query-utils.ts +4 -0
  43. package/src/model/subscription-delta.test.ts +207 -0
  44. package/src/model/subscription-pool.ts +50 -2
  45. package/src/model/types.ts +50 -1
  46. package/src/perspectives/PerspectiveClient.test.ts +204 -0
  47. package/src/perspectives/PerspectiveClient.ts +36 -7
  48. package/src/perspectives/PerspectiveProxy.ts +18 -0
  49. package/lib/src/model/query-surreal.d.ts +0 -44
  50. package/lib/src/model/query-surreal.js +0 -249
  51. package/lib/src/model/surreal-utils.d.ts +0 -42
  52. package/lib/src/model/surreal-utils.js +0 -128
  53. package/src/language/LanguageContext.ts +0 -37
  54. package/tsconfig-browser.json +0 -82
@@ -0,0 +1,568 @@
1
+ import { buildSPARQLOrderLimitOffset, buildSPARQLQuery, buildSPARQLCountQuery, buildPaginationSubquery, hasJsOnlyWhereFilters, buildSPARQLGroupedCountQuery, parseSparqlGroupedCount } from './query-sparql';
2
+
3
+ // Minimal stubs for ModelMetadata — buildSPARQLOrderLimitOffset only uses the query arg
4
+ const emptyMetadata: any = { properties: {}, relations: {} };
5
+
6
+ // Metadata with a required (non-literal) property and a literal-stored property
7
+ const richMetadata: any = {
8
+ properties: {
9
+ name: {
10
+ name: 'name',
11
+ predicate: 'flux://name',
12
+ required: true,
13
+ resolveLanguage: 'literal',
14
+ },
15
+ category: {
16
+ name: 'category',
17
+ predicate: 'flux://category',
18
+ required: true,
19
+ resolveLanguage: 'did:lang:abc', // non-literal → URI stored
20
+ },
21
+ description: {
22
+ name: 'description',
23
+ predicate: 'flux://description',
24
+ initial: 'literal://string:empty',
25
+ resolveLanguage: 'literal',
26
+ },
27
+ },
28
+ relations: {},
29
+ };
30
+
31
+ const emptyRelations: any = {};
32
+
33
+ describe('hasJsOnlyWhereFilters', () => {
34
+ it('returns false when no where clause', () => {
35
+ expect(hasJsOnlyWhereFilters(richMetadata, emptyRelations, undefined)).toBe(false);
36
+ });
37
+
38
+ it('returns false when where has literal-stored property with equality filter (pushed to SPARQL)', () => {
39
+ expect(hasJsOnlyWhereFilters(richMetadata, emptyRelations, { name: 'Pasta' })).toBe(false);
40
+ });
41
+
42
+ it('returns true when where has literal-stored property with comparison operator', () => {
43
+ // gt/lt/gte/lte/between/contains remain JS-only
44
+ const meta: any = { properties: { rating: { name: 'rating', predicate: 'flux://rating', required: true, resolveLanguage: 'literal' } }, relations: {} };
45
+ expect(hasJsOnlyWhereFilters(meta, emptyRelations, { rating: { gt: 5 } })).toBe(true);
46
+ });
47
+
48
+ it('returns false when where only has non-literal property filter', () => {
49
+ expect(hasJsOnlyWhereFilters(richMetadata, emptyRelations, { category: 'some://uri' })).toBe(false);
50
+ });
51
+
52
+ it('returns true when where has author filter (count() fast path is unsafe — buildSPARQLCountQuery has no named graph)', () => {
53
+ expect(hasJsOnlyWhereFilters(richMetadata, emptyRelations, { author: 'did:key:abc' })).toBe(true);
54
+ });
55
+
56
+ it('returns true when where has timestamp filter (same reason — guards the COUNT fast path)', () => {
57
+ expect(hasJsOnlyWhereFilters(richMetadata, emptyRelations, { timestamp: { gt: 100 } })).toBe(true);
58
+ });
59
+
60
+ it('returns true for belongsToOne reverse relation', () => {
61
+ const relMeta: any = { parent: { kind: 'belongsToOne', predicate: 'flux://parent' } };
62
+ const meta: any = { properties: { parent: { name: 'parent', predicate: 'flux://parent' } }, relations: {} };
63
+ expect(hasJsOnlyWhereFilters(meta, relMeta, { parent: 'some://id' })).toBe(true);
64
+ });
65
+ });
66
+
67
+ describe('buildSPARQLQuery — SPARQL-level pagination via subquery', () => {
68
+ const modelClass: any = {};
69
+
70
+ it('includes LIMIT/OFFSET in a pagination subquery when query has them, no JS-only filters, and ORDER BY', () => {
71
+ const query = { limit: 10, offset: 0, where: { category: 'some://uri' }, order: { name: 'ASC' as const } };
72
+ const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
73
+ // SPARQL should contain LIMIT inside the pagination subquery
74
+ expect(sparql).toContain('LIMIT 10');
75
+ // The outer query should still exist
76
+ expect(sparql).toContain('SELECT ?source ?predicate ?target');
77
+ // Should have a subquery pattern
78
+ expect(sparql).toContain('SELECT DISTINCT ?source');
79
+ });
80
+
81
+ it('does NOT use SPARQL-level pagination when limit/offset present but no ORDER BY', () => {
82
+ const query = { limit: 10, offset: 0, where: { category: 'some://uri' } };
83
+ const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
84
+ // Without ORDER BY, SPARQL pagination is not used — JS-level slicing handles it
85
+ expect(sparql).not.toContain('LIMIT');
86
+ expect(sparql).not.toContain('OFFSET');
87
+ // No subquery needed
88
+ expect(sparql).not.toContain('SELECT DISTINCT');
89
+ });
90
+
91
+ it('does NOT include LIMIT/OFFSET when JS-only where filters exist (literal gt operator)', () => {
92
+ // gt on a literal-stored property is JS-only, so pagination must not be pushed to SPARQL
93
+ const meta: any = { properties: { rating: { name: 'rating', predicate: 'flux://rating', required: true, resolveLanguage: 'literal' } }, relations: {} };
94
+ const query = { limit: 10, offset: 0, where: { rating: { gt: 3 } } };
95
+ const sparql = buildSPARQLQuery(meta, emptyRelations, query, modelClass);
96
+ expect(sparql).not.toContain('LIMIT');
97
+ expect(sparql).not.toContain('OFFSET');
98
+ });
99
+ });
100
+
101
+ describe('buildSPARQLOrderLimitOffset', () => {
102
+ it('always returns empty string (pagination uses subquery pattern instead)', () => {
103
+ expect(buildSPARQLOrderLimitOffset(emptyMetadata, {})).toBe('');
104
+ expect(buildSPARQLOrderLimitOffset(emptyMetadata, { limit: 50 })).toBe('');
105
+ expect(buildSPARQLOrderLimitOffset(emptyMetadata, { limit: 50, offset: 100 })).toBe('');
106
+ expect(buildSPARQLOrderLimitOffset(emptyMetadata, { order: { timestamp: 'DESC' } })).toBe('');
107
+ expect(buildSPARQLOrderLimitOffset(emptyMetadata, {
108
+ order: { timestamp: 'DESC' },
109
+ limit: 50,
110
+ offset: 100,
111
+ })).toBe('');
112
+ });
113
+ });
114
+
115
+ describe('buildSPARQLQuery — parse_literal push-down filters', () => {
116
+ const modelClass: any = {};
117
+
118
+ it('generates parse_literal FILTER for equality on literal property', () => {
119
+ const query = { where: { name: 'Alice' } };
120
+ const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
121
+ expect(sparql).toContain('<ad4m://fn/parse_literal>');
122
+ expect(sparql).toContain('STR(<ad4m://fn/parse_literal>(?wTarget_name)) = "Alice"');
123
+ });
124
+
125
+ it('generates parse_literal IN FILTER for array on literal property', () => {
126
+ const query = { where: { name: ['Alice', 'Bob'] } };
127
+ const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
128
+ expect(sparql).toContain('STR(<ad4m://fn/parse_literal>(?wTarget_name)) IN ("Alice", "Bob")');
129
+ });
130
+
131
+ it('generates parse_literal NOT FILTER for not condition', () => {
132
+ const query = { where: { name: { not: 'deleted' } } };
133
+ const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
134
+ expect(sparql).toContain('STR(<ad4m://fn/parse_literal>(?wTarget_name)) != "deleted"');
135
+ });
136
+
137
+ it('does NOT use parse_literal for comparison operators (gt/lt)', () => {
138
+ const meta: any = {
139
+ properties: {
140
+ rating: { name: 'rating', predicate: 'flux://rating', required: true, resolveLanguage: 'literal' },
141
+ },
142
+ relations: {},
143
+ };
144
+ const query = { where: { rating: { gt: 5 } } };
145
+ const sparql = buildSPARQLQuery(meta, emptyRelations, query, modelClass);
146
+ expect(sparql).not.toContain('parse_literal');
147
+ expect(sparql).toContain('?wTarget_cmp_rating');
148
+ });
149
+
150
+ it('does NOT use parse_literal for non-literal properties', () => {
151
+ const query = { where: { category: 'some://uri' } };
152
+ const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
153
+ expect(sparql).not.toContain('parse_literal');
154
+ expect(sparql).toContain('<some://uri>');
155
+ });
156
+ });
157
+
158
+ describe('buildSPARQLQuery — structural correctness', () => {
159
+ const modelClass: any = {};
160
+
161
+ it('generates valid SPARQL with parent filter', () => {
162
+ const query = {
163
+ limit: 50,
164
+ offset: 0,
165
+ parent: { id: 'flux://channel-123', predicate: 'flux://has_message' },
166
+ where: { category: 'some://uri' },
167
+ order: { name: 'ASC' as const },
168
+ };
169
+ const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
170
+ expect(sparql).toContain('<flux://channel-123>');
171
+ // SPARQL-level pagination via subquery
172
+ expect(sparql).toContain('LIMIT 50');
173
+ expect(sparql).toContain('SELECT DISTINCT ?source');
174
+ });
175
+
176
+ it('does not allow injection through where clause IRI values', () => {
177
+ const query = {
178
+ where: { category: 'some://uri"> . } UNION { SELECT * WHERE { ?s ?p ?o' },
179
+ };
180
+ const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
181
+ // Value should be wrapped in angle brackets as an IRI
182
+ expect(sparql).toContain('<some://uri');
183
+ });
184
+ });
185
+
186
+ describe('buildSPARQLQuery — NOT with array push-down', () => {
187
+ const modelClass: any = {};
188
+
189
+ it('generates NOT IN filter for NOT with array of values', () => {
190
+ const query = { where: { name: { not: ['deleted', 'archived'] } } };
191
+ const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
192
+ // Should use NOT IN with parse_literal for literal properties
193
+ expect(sparql).toContain('NOT IN');
194
+ expect(sparql).toContain('"deleted"');
195
+ expect(sparql).toContain('"archived"');
196
+ });
197
+ });
198
+
199
+ describe('buildSPARQLQuery — mixed push-down + JS-only', () => {
200
+ const modelClass: any = {};
201
+ const mixedMeta: any = {
202
+ properties: {
203
+ name: { name: 'name', predicate: 'flux://name', required: true, resolveLanguage: 'literal' },
204
+ rating: { name: 'rating', predicate: 'flux://rating', required: true, resolveLanguage: 'literal' },
205
+ },
206
+ relations: {},
207
+ };
208
+
209
+ it('pushes equality to SPARQL but keeps gt as JS-only', () => {
210
+ const query = { where: { name: 'Alice', rating: { gt: 5 } } };
211
+ const sparql = buildSPARQLQuery(mixedMeta, emptyRelations, query, modelClass);
212
+ // name equality should be pushed to SPARQL
213
+ expect(sparql).toContain('parse_literal');
214
+ expect(sparql).toContain('Alice');
215
+ // hasJsOnlyWhereFilters should return true because of rating.gt
216
+ expect(hasJsOnlyWhereFilters(mixedMeta, emptyRelations, query.where)).toBe(true);
217
+ });
218
+ });
219
+
220
+ describe('buildSPARQLQuery — non-literal and flag properties', () => {
221
+ const modelClass: any = {};
222
+
223
+ it('does NOT use parse_literal for non-literal (resolveLanguage) properties', () => {
224
+ const meta: any = {
225
+ properties: {
226
+ avatar: { name: 'avatar', predicate: 'flux://avatar', required: true, resolveLanguage: 'did:lang:some-language' },
227
+ },
228
+ relations: {},
229
+ };
230
+ const query = { where: { avatar: 'https://example.com/pic.jpg' } };
231
+ const sparql = buildSPARQLQuery(meta, emptyRelations, query, modelClass);
232
+ expect(sparql).not.toContain('parse_literal');
233
+ });
234
+
235
+ it('does NOT use parse_literal for flag properties', () => {
236
+ const meta: any = {
237
+ properties: {
238
+ isPublic: { name: 'isPublic', predicate: 'flux://isPublic', flag: true, initial: 'flux://true' },
239
+ },
240
+ relations: {},
241
+ };
242
+ const query = { where: { isPublic: 'flux://true' } };
243
+ const sparql = buildSPARQLQuery(meta, emptyRelations, query, modelClass);
244
+ expect(sparql).not.toContain('parse_literal');
245
+ });
246
+ });
247
+
248
+ describe('buildSPARQLQuery — IRI correctness', () => {
249
+ const modelClass: any = {};
250
+
251
+ it('uses <ad4m://fn/parse_literal> IRI, not fn::parse_literal SurrealDB syntax', () => {
252
+ const query = { where: { name: 'test' } };
253
+ const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
254
+ expect(sparql).toContain('<ad4m://fn/parse_literal>');
255
+ expect(sparql).not.toContain('fn::parse_literal');
256
+ });
257
+ });
258
+
259
+ // ──────────────────────────────────────────────────────────
260
+ // SPARQL-level pagination (LIMIT/OFFSET in generated queries)
261
+ // ──────────────────────────────────────────────────────────
262
+
263
+ describe('SPARQL-level pagination', () => {
264
+ const modelClass: any = {};
265
+
266
+ it('includes LIMIT in SPARQL when query specifies limit + order', () => {
267
+ const query = { limit: 30, order: { name: 'ASC' as const } };
268
+ const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
269
+ expect(sparql).toContain('LIMIT 30');
270
+ expect(sparql).toContain('SELECT DISTINCT ?source');
271
+ });
272
+
273
+ it('does NOT push LIMIT to SPARQL when no ORDER BY is specified', () => {
274
+ const query = { limit: 30 };
275
+ const sparql = buildSPARQLQuery(emptyMetadata, emptyRelations, query, modelClass);
276
+ // Without ORDER BY, SPARQL-level pagination is not used
277
+ expect(sparql).not.toContain('LIMIT');
278
+ expect(sparql).not.toContain('SELECT DISTINCT');
279
+ });
280
+
281
+ it('includes OFFSET in SPARQL when query specifies offset > 0 with order', () => {
282
+ const query = { limit: 20, offset: 40, order: { name: 'ASC' as const } };
283
+ const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
284
+ expect(sparql).toContain('LIMIT 20');
285
+ expect(sparql).toContain('OFFSET 40');
286
+ });
287
+
288
+ it('does NOT include OFFSET when offset is 0', () => {
289
+ const query = { limit: 10, offset: 0, order: { name: 'ASC' as const } };
290
+ const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
291
+ expect(sparql).toContain('LIMIT 10');
292
+ expect(sparql).not.toContain('OFFSET');
293
+ });
294
+
295
+ it('includes ORDER BY in subquery when query.order is specified', () => {
296
+ const query = { limit: 10, order: { name: 'DESC' as const } };
297
+ const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
298
+ expect(sparql).toContain('ORDER BY DESC(');
299
+ expect(sparql).toContain('LIMIT 10');
300
+ });
301
+
302
+ it('uses SAMPLE() aggregate for ORDER BY variables in pagination subquery (SPARQL 1.1 compliance)', () => {
303
+ const query = { limit: 5, order: { name: 'ASC' as const } };
304
+ const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
305
+ // Must use SAMPLE() to aggregate the order variable under GROUP BY
306
+ expect(sparql).toMatch(/SAMPLE\(/);
307
+ expect(sparql).toMatch(/AS \?pg_sort_0/);
308
+ expect(sparql).toContain('GROUP BY ?source');
309
+ expect(sparql).toContain('ORDER BY ASC(?pg_sort_0)');
310
+ });
311
+
312
+ it('omits GROUP BY when ORDER BY is present (uses SAMPLE() aggregate instead)', () => {
313
+ // When ORDER BY is present, GROUP BY ?source is used with SAMPLE() aggregates.
314
+ // The old redundant GROUP BY (without ORDER BY) no longer applies because
315
+ // SPARQL-level pagination is only used when ORDER BY is present.
316
+ const query = { limit: 10, order: { name: 'ASC' as const } };
317
+ const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
318
+ expect(sparql).toContain('GROUP BY ?source');
319
+ expect(sparql).toContain('SAMPLE(');
320
+ expect(sparql).toContain('SELECT DISTINCT ?source');
321
+ expect(sparql).toContain('LIMIT 10');
322
+ });
323
+
324
+ it('does NOT default to ORDER BY timestamp when paginating without explicit order', () => {
325
+ const query = { limit: 30 };
326
+ const sparql = buildSPARQLQuery(emptyMetadata, emptyRelations, query, modelClass);
327
+ expect(sparql).not.toContain('ORDER BY');
328
+ expect(sparql).not.toContain('pg_minTs');
329
+ expect(sparql).not.toContain('GRAPH ?pg_g');
330
+ });
331
+
332
+ it('does NOT push pagination to SPARQL when JS-only where filters exist (literal gt operator)', () => {
333
+ // author equality is now SPARQL-pushable; use a literal gt which remains JS-only
334
+ const meta: any = { properties: { rating: { name: 'rating', predicate: 'flux://rating', required: true, resolveLanguage: 'literal' } }, relations: {} };
335
+ const query = { limit: 10, where: { rating: { gt: 5 } } };
336
+ const sparql = buildSPARQLQuery(meta, emptyRelations, query, modelClass);
337
+ expect(sparql).not.toContain('LIMIT');
338
+ expect(sparql).not.toContain('OFFSET');
339
+ });
340
+
341
+ it('does NOT push pagination to SPARQL when JS-only where filters exist (gt operator)', () => {
342
+ const meta: any = {
343
+ properties: {
344
+ rating: { name: 'rating', predicate: 'flux://rating', required: true, resolveLanguage: 'literal' },
345
+ },
346
+ relations: {},
347
+ };
348
+ const query = { limit: 10, where: { rating: { gt: 5 } } };
349
+ const sparql = buildSPARQLQuery(meta, emptyRelations, query, modelClass);
350
+ expect(sparql).not.toContain('LIMIT');
351
+ });
352
+
353
+ it('wraps pagination in a subquery (outer SELECT fetches all links for the page)', () => {
354
+ const query = { limit: 5, offset: 10, order: { name: 'DESC' as const } };
355
+ const sparql = buildSPARQLQuery(richMetadata, emptyRelations, query, modelClass);
356
+ expect(sparql).toContain('SELECT ?source ?predicate ?target ?author ?timestamp');
357
+ expect(sparql).toContain('SELECT DISTINCT ?source');
358
+ expect(sparql).toContain('LIMIT 5');
359
+ expect(sparql).toContain('OFFSET 10');
360
+ });
361
+
362
+ it('does NOT wrap pagination in a subquery when no ORDER BY (JS slicing preserves natural order)', () => {
363
+ const query = { limit: 5, offset: 10 };
364
+ const sparql = buildSPARQLQuery(emptyMetadata, emptyRelations, query, modelClass);
365
+ // Should be a plain SELECT without subquery
366
+ expect(sparql).toContain('SELECT ?source ?predicate ?target ?author ?timestamp');
367
+ expect(sparql).not.toContain('SELECT DISTINCT');
368
+ expect(sparql).not.toContain('LIMIT');
369
+ expect(sparql).not.toContain('OFFSET');
370
+ });
371
+
372
+ describe('buildSPARQLCountQuery', () => {
373
+ it('returns a COUNT(DISTINCT ?source) query', () => {
374
+ const query = { parent: { id: 'flux://ch-1', predicate: 'flux://has_child' } };
375
+ const countSparql = buildSPARQLCountQuery(emptyMetadata, emptyRelations, query, modelClass);
376
+ expect(countSparql).toContain('COUNT(DISTINCT ?source)');
377
+ expect(countSparql).toContain('?count');
378
+ expect(countSparql).toContain('<flux://ch-1>');
379
+ });
380
+
381
+ it('does NOT include LIMIT/OFFSET (counts full result set)', () => {
382
+ const query = { limit: 10, offset: 20, parent: { id: 'flux://ch-1', predicate: 'flux://has_child' } };
383
+ const countSparql = buildSPARQLCountQuery(emptyMetadata, emptyRelations, query, modelClass);
384
+ expect(countSparql).not.toContain('LIMIT');
385
+ expect(countSparql).not.toContain('OFFSET');
386
+ expect(countSparql).toContain('COUNT(DISTINCT ?source)');
387
+ });
388
+ });
389
+ });
390
+
391
+ describe('buildSPARQLQuery — set-difference patterns', () => {
392
+ const modelClass: any = {};
393
+
394
+ // Subgroups are grandchildren of channels (channel → conversation → subgroup).
395
+ // Never assume direct child relationships in set-difference queries.
396
+ // A global EXISTS pattern (no parent scoping) should match items regardless of depth.
397
+ it('generates global EXISTS without parent scoping when no parent filter', () => {
398
+ const meta: any = {
399
+ properties: {
400
+ status: { name: 'status', predicate: 'flux://status', required: true, resolveLanguage: 'literal' },
401
+ },
402
+ relations: {},
403
+ };
404
+ const query = { where: { status: 'active' } };
405
+ const sparql = buildSPARQLQuery(meta, emptyRelations, query, modelClass);
406
+ // Without a parent filter, the query should not scope to any specific parent
407
+ // This ensures grandchildren (items at any depth) are matched
408
+ expect(sparql).not.toContain('flux://has_child');
409
+ expect(sparql).toContain('SELECT ?source ?predicate ?target');
410
+ });
411
+ });
412
+
413
+ // ─────────────────────────────────────────────────────────────
414
+ // buildSPARQLWhereFilters — author / timestamp SPARQL push
415
+ // ─────────────────────────────────────────────────────────────
416
+ describe('buildSPARQLQuery — author/timestamp SPARQL filter push', () => {
417
+ const modelClass: any = {};
418
+
419
+ it('pushes author equality into SPARQL FILTER using STR(?author)', () => {
420
+ const query = { where: { author: 'did:key:zABC' } };
421
+ const sparql = buildSPARQLQuery(emptyMetadata, emptyRelations, query, modelClass);
422
+ expect(sparql).toContain('STR(?author) = "did:key:zABC"');
423
+ expect(sparql).toContain('?author');
424
+ });
425
+
426
+ it('pushes author IN array into SPARQL FILTER', () => {
427
+ const query = { where: { author: ['did:key:zABC', 'did:key:zDEF'] } };
428
+ const sparql = buildSPARQLQuery(emptyMetadata, emptyRelations, query, modelClass);
429
+ expect(sparql).toContain('STR(?author) IN');
430
+ expect(sparql).toContain('"did:key:zABC"');
431
+ expect(sparql).toContain('"did:key:zDEF"');
432
+ });
433
+
434
+ it('pushes author NOT into SPARQL FILTER', () => {
435
+ const query = { where: { author: { not: 'did:key:zABC' } } };
436
+ const sparql = buildSPARQLQuery(emptyMetadata, emptyRelations, query, modelClass);
437
+ expect(sparql).toContain('STR(?author) != "did:key:zABC"');
438
+ });
439
+
440
+ it('pushes timestamp gt/lt into SPARQL FILTER', () => {
441
+ const query = { where: { timestamp: { gt: 1000, lt: 9000 } } };
442
+ const sparql = buildSPARQLQuery(emptyMetadata, emptyRelations, query, modelClass);
443
+ expect(sparql).toContain('?timestamp > 1000');
444
+ expect(sparql).toContain('?timestamp < 9000');
445
+ });
446
+
447
+ it('pushes timestamp between into SPARQL FILTER', () => {
448
+ const query = { where: { timestamp: { between: [100, 200] as [number, number] } } };
449
+ const sparql = buildSPARQLQuery(emptyMetadata, emptyRelations, query, modelClass);
450
+ expect(sparql).toContain('?timestamp >= 100');
451
+ expect(sparql).toContain('?timestamp <= 200');
452
+ });
453
+
454
+ it('pushes timestamp equality into SPARQL FILTER', () => {
455
+ const query = { where: { timestamp: 1714000000000 } };
456
+ const sparql = buildSPARQLQuery(emptyMetadata, emptyRelations, query, modelClass);
457
+ expect(sparql).toContain('?timestamp = 1714000000000');
458
+ });
459
+ });
460
+
461
+ // ─────────────────────────────────────────────────────────────
462
+ // buildSPARQLGroupedCountQuery
463
+ // ─────────────────────────────────────────────────────────────
464
+ describe('buildSPARQLGroupedCountQuery', () => {
465
+ const signalMetadata: any = {
466
+ properties: {
467
+ signalTypeId: {
468
+ name: 'signalTypeId',
469
+ predicate: 'flux://signalTypeId',
470
+ required: true,
471
+ resolveLanguage: 'literal',
472
+ },
473
+ },
474
+ relations: {},
475
+ };
476
+
477
+ it('selects ?parent and COUNT(DISTINCT ?source)', () => {
478
+ const sparql = buildSPARQLGroupedCountQuery(signalMetadata, emptyRelations, 'flux://has-signal', ['flux://post/1'], undefined);
479
+ expect(sparql).toContain('SELECT ?parent (COUNT(DISTINCT ?source) AS ?count)');
480
+ });
481
+
482
+ it('groups by ?parent', () => {
483
+ const sparql = buildSPARQLGroupedCountQuery(signalMetadata, emptyRelations, 'flux://has-signal', ['flux://post/1'], undefined);
484
+ expect(sparql).toContain('GROUP BY ?parent');
485
+ });
486
+
487
+ it('includes parent → child join with the supplied predicate', () => {
488
+ const sparql = buildSPARQLGroupedCountQuery(signalMetadata, emptyRelations, 'flux://has-signal', ['flux://post/1', 'flux://post/2'], undefined);
489
+ expect(sparql).toContain('?parent <flux://has-signal> ?source');
490
+ });
491
+
492
+ it('includes FILTER(?parent IN (...)) for the supplied parent IDs', () => {
493
+ const sparql = buildSPARQLGroupedCountQuery(signalMetadata, emptyRelations, 'flux://has-signal', ['flux://post/1', 'flux://post/2'], undefined);
494
+ expect(sparql).toContain('?parent IN (<flux://post/1>, <flux://post/2>)');
495
+ });
496
+
497
+ it('includes the full named graph block (GRAPH ?linkGraph + author + timestamp)', () => {
498
+ const sparql = buildSPARQLGroupedCountQuery(signalMetadata, emptyRelations, 'flux://has-signal', ['flux://post/1'], undefined);
499
+ expect(sparql).toContain('GRAPH ?linkGraph');
500
+ expect(sparql).toContain('?linkGraph <ad4m://ontology/author> ?author');
501
+ expect(sparql).toContain('?linkGraph <ad4m://ontology/timestamp> ?timestamp');
502
+ });
503
+
504
+ it('includes conformance join for required properties', () => {
505
+ const sparql = buildSPARQLGroupedCountQuery(signalMetadata, emptyRelations, 'flux://has-signal', ['flux://post/1'], undefined);
506
+ expect(sparql).toContain('<flux://signalTypeId>');
507
+ });
508
+
509
+ it('applies a where clause filter (author equality) via SPARQL FILTER', () => {
510
+ const sparql = buildSPARQLGroupedCountQuery(signalMetadata, emptyRelations, 'flux://has-signal', ['flux://post/1'], { author: 'did:key:zABC' });
511
+ expect(sparql).toContain('STR(?author) = "did:key:zABC"');
512
+ });
513
+
514
+ it('applies a where clause filter (required property equality) via parse_literal', () => {
515
+ const sparql = buildSPARQLGroupedCountQuery(signalMetadata, emptyRelations, 'flux://has-signal', ['flux://post/1'], { signalTypeId: 'like' });
516
+ expect(sparql).toContain('parse_literal');
517
+ expect(sparql).toContain('"like"');
518
+ });
519
+ });
520
+
521
+ // ─────────────────────────────────────────────────────────────
522
+ // parseSparqlGroupedCount
523
+ // ─────────────────────────────────────────────────────────────
524
+ describe('parseSparqlGroupedCount', () => {
525
+ it('returns an empty map for empty input', () => {
526
+ expect(parseSparqlGroupedCount([]).size).toBe(0);
527
+ });
528
+
529
+ it('returns an empty map for non-array input', () => {
530
+ expect(parseSparqlGroupedCount(null as any).size).toBe(0);
531
+ });
532
+
533
+ it('parses RDF binding objects ({ parent: { value: ... }, count: { value: ... } })', () => {
534
+ const rows = [
535
+ { parent: { value: 'flux://post/1' }, count: { value: '3' } },
536
+ { parent: { value: 'flux://post/2' }, count: { value: '0' } },
537
+ ];
538
+ const map = parseSparqlGroupedCount(rows);
539
+ expect(map.get('flux://post/1')).toBe(3);
540
+ expect(map.get('flux://post/2')).toBe(0);
541
+ });
542
+
543
+ it('parses plain string/number values (non-RDF binding format)', () => {
544
+ const rows = [
545
+ { parent: 'flux://post/1', count: 5 },
546
+ { parent: 'flux://post/2', count: '2' },
547
+ ];
548
+ const map = parseSparqlGroupedCount(rows);
549
+ expect(map.get('flux://post/1')).toBe(5);
550
+ expect(map.get('flux://post/2')).toBe(2);
551
+ });
552
+
553
+ it('skips rows with missing parent or count', () => {
554
+ const rows = [
555
+ { parent: { value: 'flux://post/1' } }, // no count
556
+ { count: { value: '3' } }, // no parent
557
+ { parent: { value: 'flux://post/3' }, count: { value: '1' } },
558
+ ];
559
+ const map = parseSparqlGroupedCount(rows);
560
+ expect(map.size).toBe(1);
561
+ expect(map.get('flux://post/3')).toBe(1);
562
+ });
563
+
564
+ it('skips rows with NaN count', () => {
565
+ const rows = [{ parent: { value: 'flux://post/1' }, count: { value: 'not-a-number' } }];
566
+ expect(parseSparqlGroupedCount(rows).size).toBe(0);
567
+ });
568
+ });