@coasys/ad4m 0.13.0-test-1 → 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 (115) hide show
  1. package/lib/index.cjs +2377 -849
  2. package/lib/index.js +2354 -846
  3. package/lib/src/Literal.js +6 -5
  4. package/lib/src/agent/AgentClient.d.ts +5 -1
  5. package/lib/src/agent/AgentClient.js +48 -2
  6. package/lib/src/expression/ExpressionRef.js +2 -2
  7. package/lib/src/index.d.ts +0 -1
  8. package/lib/src/index.js +0 -1
  9. package/lib/src/language/Language.d.ts +26 -176
  10. package/lib/src/language/Language.js +28 -2
  11. package/lib/src/model/Ad4mModel.d.ts +52 -28
  12. package/lib/src/model/Ad4mModel.js +255 -118
  13. package/lib/src/model/Ad4mModel.test.js +1727 -537
  14. package/lib/src/model/ModelQueryBuilder.d.ts +67 -34
  15. package/lib/src/model/ModelQueryBuilder.js +208 -79
  16. package/lib/src/model/Subject.js +6 -6
  17. package/lib/src/model/decorators.d.ts +14 -8
  18. package/lib/src/model/decorators.js +41 -14
  19. package/lib/src/model/hydration-batch.d.ts +34 -0
  20. package/lib/src/model/hydration-batch.js +147 -0
  21. package/lib/src/model/hydration-batching.test.d.ts +7 -0
  22. package/lib/src/model/hydration-batching.test.js +456 -0
  23. package/lib/src/model/hydration.d.ts +4 -3
  24. package/lib/src/model/hydration.js +365 -86
  25. package/lib/src/model/index.d.ts +4 -1
  26. package/lib/src/model/index.js +4 -1
  27. package/lib/src/model/json-schema.js +2 -2
  28. package/lib/src/model/query-cache.d.ts +30 -0
  29. package/lib/src/model/query-cache.js +66 -0
  30. package/lib/src/model/query-cache.test.d.ts +1 -0
  31. package/lib/src/model/query-cache.test.js +43 -0
  32. package/lib/src/model/query-common.d.ts +1 -1
  33. package/lib/src/model/query-common.js +1 -1
  34. package/lib/src/model/query-sparql-batch.d.ts +17 -0
  35. package/lib/src/model/query-sparql-batch.js +260 -0
  36. package/lib/src/model/query-sparql.d.ts +124 -0
  37. package/lib/src/model/query-sparql.js +767 -0
  38. package/lib/src/model/query-sparql.test.d.ts +1 -0
  39. package/lib/src/model/query-sparql.test.js +495 -0
  40. package/lib/src/model/{surreal-utils.d.ts → query-utils.d.ts} +12 -9
  41. package/lib/src/model/{surreal-utils.js → query-utils.js} +43 -27
  42. package/lib/src/model/relation-filtering.test.js +15 -15
  43. package/lib/src/model/sdna.js +1 -1
  44. package/lib/src/model/shacl-gen.js +42 -18
  45. package/lib/src/model/subscription-delta.test.d.ts +24 -0
  46. package/lib/src/model/subscription-delta.test.js +180 -0
  47. package/lib/src/model/subscription-pool.d.ts +39 -0
  48. package/lib/src/model/subscription-pool.js +165 -0
  49. package/lib/src/model/types.d.ts +52 -4
  50. package/lib/src/model/types.js +1 -1
  51. package/lib/src/perspectives/PerspectiveClient.d.ts +3 -17
  52. package/lib/src/perspectives/PerspectiveClient.js +42 -66
  53. package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
  54. package/lib/src/perspectives/PerspectiveClient.test.js +169 -0
  55. package/lib/src/perspectives/PerspectiveProxy.d.ts +54 -30
  56. package/lib/src/perspectives/PerspectiveProxy.js +239 -177
  57. package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
  58. package/lib/src/perspectives/PerspectiveResolver.js +0 -11
  59. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +3 -3
  60. package/lib/src/perspectives/WakerSubscriptionManager.js +7 -8
  61. package/lib/src/runtime/RuntimeResolver.d.ts +11 -0
  62. package/lib/src/runtime/RuntimeResolver.js +56 -0
  63. package/lib/src/schema.gql +11 -1
  64. package/lib/src/shacl/SHACLFlow.d.ts +1 -1
  65. package/lib/src/shacl/SHACLFlow.js +9 -9
  66. package/lib/src/shacl/SHACLShape.d.ts +1 -1
  67. package/lib/src/shacl/SHACLShape.js +38 -38
  68. package/lib/src/typeDefs.js +11 -1
  69. package/lib/src/utils.d.ts +6 -6
  70. package/lib/src/utils.js +6 -6
  71. package/package.json +1 -1
  72. package/src/Ad4mClient.test.ts +56 -1
  73. package/src/Literal.test.ts +10 -5
  74. package/src/Literal.ts +6 -5
  75. package/src/agent/AgentClient.ts +53 -1
  76. package/src/expression/ExpressionRef.ts +2 -2
  77. package/src/index.ts +0 -1
  78. package/src/language/Language.ts +55 -231
  79. package/src/model/Ad4mModel.test.ts +1709 -572
  80. package/src/model/Ad4mModel.ts +274 -120
  81. package/src/model/ModelQueryBuilder.ts +234 -87
  82. package/src/model/Subject.ts +6 -6
  83. package/src/model/decorators.ts +51 -22
  84. package/src/model/hydration-batch.ts +205 -0
  85. package/src/model/hydration-batching.test.ts +563 -0
  86. package/src/model/hydration.ts +349 -84
  87. package/src/model/index.ts +4 -1
  88. package/src/model/json-schema.ts +2 -2
  89. package/src/model/query-cache.test.ts +54 -0
  90. package/src/model/query-cache.ts +79 -0
  91. package/src/model/query-common.ts +1 -1
  92. package/src/model/query-sparql-batch.ts +301 -0
  93. package/src/model/query-sparql.test.ts +568 -0
  94. package/src/model/query-sparql.ts +820 -0
  95. package/src/model/{surreal-utils.ts → query-utils.ts} +44 -27
  96. package/src/model/relation-filtering.test.ts +15 -15
  97. package/src/model/sdna.ts +1 -1
  98. package/src/model/shacl-gen.ts +42 -17
  99. package/src/model/subscription-delta.test.ts +207 -0
  100. package/src/model/subscription-pool.ts +211 -0
  101. package/src/model/types.ts +53 -4
  102. package/src/perspectives/PerspectiveClient.test.ts +204 -0
  103. package/src/perspectives/PerspectiveClient.ts +41 -68
  104. package/src/perspectives/PerspectiveProxy.ts +244 -181
  105. package/src/perspectives/PerspectiveResolver.ts +0 -8
  106. package/src/perspectives/WakerSubscriptionManager.ts +8 -9
  107. package/src/runtime/RuntimeResolver.ts +43 -0
  108. package/src/shacl/SHACLFlow.ts +9 -9
  109. package/src/shacl/SHACLShape.ts +39 -39
  110. package/src/utils.ts +6 -6
  111. package/lib/src/model/query-surreal.d.ts +0 -44
  112. package/lib/src/model/query-surreal.js +0 -249
  113. package/src/language/LanguageContext.ts +0 -37
  114. package/src/model/query-surreal.ts +0 -280
  115. package/tsconfig-browser.json +0 -82
@@ -11,6 +11,9 @@ import type {
11
11
  Where, Order, IncludeMap, Query,
12
12
  AllInstancesResult, ResultsWithTotalCount, PaginationResult,
13
13
  } from "./types";
14
+ import { groupSPARQLResults, hasJsOnlyWhereFilters, parseSparqlCount } from "./query-sparql";
15
+ import { getRelationsMetadata } from "./decorators";
16
+ import { pooledSubscribe } from "./subscription-pool";
14
17
 
15
18
  /** Query builder for Ad4mModel queries.
16
19
  * Allows building queries with a fluent interface and either running them once
@@ -38,7 +41,7 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
38
41
  private modelClassName: string | null = null;
39
42
  private ctor: typeof Ad4mModel;
40
43
  private currentSubscription?: any;
41
- private useSurrealDBFlag: boolean = true;
44
+ private engineFlag: 'sparql' | 'prolog' = 'sparql';
42
45
 
43
46
  constructor(perspective: PerspectiveProxy, ctor: typeof Ad4mModel, query?: Query) {
44
47
  this.perspective = perspective;
@@ -224,6 +227,29 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
224
227
  return this;
225
228
  }
226
229
 
230
+ /**
231
+ * Opts in to evaluating SPARQL property getters during collection hydration.
232
+ *
233
+ * By default, collection queries skip getter evaluation for performance.
234
+ * Call `.deepQuery()` when you need getter-backed properties in the result set.
235
+ *
236
+ * @returns The query builder for chaining
237
+ *
238
+ * @example
239
+ * ```typescript
240
+ * const messages = await Message.query(perspective)
241
+ * .parent(channel)
242
+ * .deepQuery()
243
+ * .limit(30)
244
+ * .get();
245
+ * // messages[i].replyingTo is populated
246
+ * ```
247
+ */
248
+ deepQuery(): ModelQueryBuilder<T> {
249
+ (this.queryParams as any).deepQuery = true;
250
+ return this;
251
+ }
252
+
227
253
  /**
228
254
  * Specifies which relations to eager-load (hydrate into model instances).
229
255
  *
@@ -261,32 +287,10 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
261
287
  }
262
288
 
263
289
  /**
264
- * Enables or disables SurrealDB query path.
265
- *
266
- * @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
267
- * @returns The query builder for chaining
268
- *
269
- * @example
270
- * ```typescript
271
- * // Use SurrealDB (default)
272
- * const recipes = await Recipe.query(perspective)
273
- * .where({ category: "Dessert" })
274
- * .useSurrealDB(true)
275
- * .get();
276
- *
277
- * // Use Prolog (legacy)
278
- * const recipesProlog = await Recipe.query(perspective)
279
- * .where({ category: "Dessert" })
280
- * .useSurrealDB(false)
281
- * .get();
282
- * ```
283
- *
284
- * @remarks
285
- * Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
286
- * if useSurrealDB(true) is set (default).
290
+ * Sets the query engine to use.
287
291
  */
288
- useSurrealDB(enabled: boolean = true): ModelQueryBuilder<T> {
289
- this.useSurrealDBFlag = enabled;
292
+ engine(eng: 'sparql' | 'prolog'): ModelQueryBuilder<T> {
293
+ this.engineFlag = eng;
290
294
  return this;
291
295
  }
292
296
 
@@ -304,10 +308,8 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
304
308
  */
305
309
  async get(): Promise<T[]> {
306
310
  let results: T[];
307
- if (this.useSurrealDBFlag) {
308
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
309
- const result = await this.perspective.querySurrealDB(surrealQuery);
310
- ({ results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result) as { results: T[] });
311
+ if (this.engineFlag === 'sparql') {
312
+ results = await this.executeSparqlQuery();
311
313
  } else {
312
314
  const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
313
315
  const result = await this.perspective.infer(query);
@@ -317,6 +319,32 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
317
319
  return results;
318
320
  }
319
321
 
322
+ /**
323
+ * Executes the query once using SPARQL and returns the results.
324
+ */
325
+ async getSparql(): Promise<T[]> {
326
+ return this.executeSparqlQuery();
327
+ }
328
+
329
+ /**
330
+ * Shared SPARQL query execution logic used by both get() and getSparql().
331
+ */
332
+ private async executeSparqlQuery(): Promise<T[]> {
333
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
334
+ const rawResult = await this.perspective.querySparql(sparqlQuery);
335
+ const { results } = await this.processSparqlResult(rawResult);
336
+ return results;
337
+ }
338
+
339
+ /**
340
+ * Groups raw SPARQL results and hydrates them into model instances.
341
+ * Centralises the repeated groupSPARQLResults → instancesFromQueryResult pipeline.
342
+ */
343
+ private async processSparqlResult(rawResult: any, queryOverride?: Query, computeTotalCount: boolean = false): Promise<{ results: T[], totalCount: number }> {
344
+ const grouped = groupSPARQLResults(Array.isArray(rawResult) ? rawResult : []);
345
+ return await this.ctor.instancesFromQueryResult(this.perspective, queryOverride || this.queryParams, grouped, computeTotalCount) as { results: T[], totalCount: number };
346
+ }
347
+
320
348
  /**
321
349
  * Returns the first matching instance, or `null` if none match.
322
350
  *
@@ -341,7 +369,7 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
341
369
  * Subscribes to the query and receives updates when results change.
342
370
  *
343
371
  * This method:
344
- * 1. Creates and initializes a SurrealDB live query subscription (default)
372
+ * 1. Creates and initializes a SPARQL live query subscription (default)
345
373
  * 2. Sets up the callback to process future updates
346
374
  * 3. Returns the initial results immediately
347
375
  *
@@ -365,8 +393,8 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
365
393
  * ```
366
394
  *
367
395
  * @remarks
368
- * By default, this uses SurrealDB live queries for real-time updates.
369
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
396
+ * By default, this uses SPARQL live queries for real-time updates.
397
+ * Prolog subscriptions remain available via `.useSPARQL(false)`.
370
398
  */
371
399
  async subscribe(callback: (results: T[]) => void): Promise<T[]> {
372
400
  // Clean up any existing subscription
@@ -374,26 +402,44 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
374
402
 
375
403
  const ctor = this.ctor;
376
404
 
377
- if (this.useSurrealDBFlag) {
378
- const surrealQuery = await ctor.queryToSurrealQL(this.perspective, this.queryParams);
379
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
405
+ if (this.engineFlag === 'sparql') {
406
+ const sparqlQuery = await ctor.queryToSPARQL(this.perspective, this.queryParams);
380
407
 
381
- const processResults = async (result: any) => {
382
- const { results } = await ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
383
- callback(results as T[]);
408
+ // Track last emitted result fingerprint to suppress duplicate callbacks
409
+ let lastResultFingerprint: string | null = null;
410
+
411
+ const buildFingerprint = (results: any[]) => {
412
+ if (results.length === 0) return '0:';
413
+ // Must include relation data (e.g. tags) — not just id/timestamp.
414
+ // Otherwise @HasMany changes on existing instances are suppressed as duplicates.
415
+ return JSON.stringify(results, (_, v) =>
416
+ typeof v === 'function' ? undefined : v
417
+ );
384
418
  };
385
419
 
386
- this.currentSubscription.onResult(processResults);
387
-
388
- // Process initial result
389
- const { results } = await ctor.instancesFromSurrealResult(
390
- this.perspective,
391
- this.queryParams,
392
- this.currentSubscription.result
420
+ const hydrate = async (rawResult: any) => {
421
+ const { results } = await this.processSparqlResult(rawResult);
422
+ return results;
423
+ };
424
+
425
+ const pooled = await pooledSubscribe(
426
+ this.perspective,
427
+ sparqlQuery,
428
+ hydrate,
429
+ (hydratedResults: T[]) => {
430
+ const fp = buildFingerprint(hydratedResults);
431
+ if (fp === lastResultFingerprint) return;
432
+ lastResultFingerprint = fp;
433
+ callback(hydratedResults);
434
+ },
393
435
  );
394
- // Also invoke callback with initial results so subscribers see them
395
- callback(results as T[]);
396
- return results as T[];
436
+
437
+ // Store dispose function as subscription
438
+ this.currentSubscription = { dispose: pooled.dispose };
439
+
440
+ const initialResults = pooled.initialResult as T[];
441
+ lastResultFingerprint = buildFingerprint(initialResults);
442
+ return initialResults;
397
443
  } else {
398
444
  const query = await ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
399
445
  this.currentSubscription = await this.perspective.subscribeInfer(query);
@@ -409,12 +455,32 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
409
455
  this.queryParams,
410
456
  this.currentSubscription.result
411
457
  );
412
- // Also invoke callback with initial results so subscribers see them
413
- callback(results as T[]);
458
+ // Initial results returned via Promise only — callback is for subsequent updates
414
459
  return results as T[];
415
460
  }
416
461
  }
417
462
 
463
+ /**
464
+ * Subscribes to the query and receives updates using SPARQL.
465
+ */
466
+ async subscribeSparql(callback: (results: T[]) => void): Promise<T[]> {
467
+ this.dispose();
468
+
469
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
470
+ this.currentSubscription = await this.perspective.subscribeQuery(sparqlQuery);
471
+
472
+ const processResults = async (result: any) => {
473
+ const { results } = await this.processSparqlResult(result);
474
+ callback(results as T[]);
475
+ };
476
+
477
+ this.currentSubscription.onResult(processResults);
478
+
479
+ const { results } = await this.processSparqlResult(this.currentSubscription.result);
480
+ // Initial results returned via Promise only — callback is for subsequent updates
481
+ return results as T[];
482
+ }
483
+
418
484
  /**
419
485
  * Gets the total count of matching entities.
420
486
  *
@@ -428,14 +494,20 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
428
494
  * ```
429
495
  */
430
496
  async count(): Promise<number> {
431
- if (this.useSurrealDBFlag) {
432
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
433
- const result = await this.perspective.querySurrealDB(surrealQuery);
434
- // Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
435
- // (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
436
- // This ensures count() returns the same number as get().length
437
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
438
- return totalCount;
497
+ if (this.engineFlag === 'sparql') {
498
+ // When query has JS-only where filters, fall back to full hydration
499
+ const metadata = this.ctor.getModelMetadata();
500
+ const allRelMeta = getRelationsMetadata(this.ctor as any);
501
+ if (hasJsOnlyWhereFilters(metadata, allRelMeta, this.queryParams.where)) {
502
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
503
+ const rawResult = await this.perspective.querySparql(sparqlQuery);
504
+ const { totalCount } = await this.processSparqlResult(rawResult, undefined, true);
505
+ return totalCount;
506
+ }
507
+ // Use efficient COUNT query — no hydration
508
+ const countSparql = await this.ctor.countQueryToSPARQL(this.perspective, this.queryParams);
509
+ const countResult = await this.perspective.querySparql(countSparql);
510
+ return parseSparqlCount(countResult) ?? 0;
439
511
  } else {
440
512
  const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
441
513
  const result = await this.perspective.infer(query);
@@ -443,11 +515,25 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
443
515
  }
444
516
  }
445
517
 
518
+ /**
519
+ * Gets the total count of matching entities using SPARQL.
520
+ * Delegates to count() with SPARQL engine forced.
521
+ */
522
+ async countSparql(): Promise<number> {
523
+ const prev = this.engineFlag;
524
+ this.engineFlag = 'sparql';
525
+ try {
526
+ return await this.count();
527
+ } finally {
528
+ this.engineFlag = prev;
529
+ }
530
+ }
531
+
446
532
  /**
447
533
  * Subscribes to count updates for matching entities.
448
534
  *
449
535
  * This method:
450
- * 1. Creates and initializes a SurrealDB live query subscription for the count (default)
536
+ * 1. Creates and initializes a SPARQL live query subscription for the count (default)
451
537
  * 2. Sets up the callback to process future count updates
452
538
  * 3. Returns the initial count immediately
453
539
  *
@@ -471,29 +557,25 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
471
557
  * ```
472
558
  *
473
559
  * @remarks
474
- * By default, this uses SurrealDB live queries for real-time updates.
475
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
560
+ * By default, this uses SPARQL live queries for real-time updates.
561
+ * Prolog subscriptions remain available via `.useSPARQL(false)`.
476
562
  */
477
563
  async countSubscribe(callback: (count: number) => void): Promise<number> {
478
564
  // Clean up any existing subscription
479
565
  this.dispose();
480
566
 
481
- if (this.useSurrealDBFlag) {
482
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
483
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
567
+ if (this.engineFlag === 'sparql') {
568
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
569
+ this.currentSubscription = await this.perspective.subscribeQuery(sparqlQuery);
484
570
 
485
571
  const processResults = async (result: any) => {
486
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
572
+ const { totalCount } = await this.processSparqlResult(result, undefined, true);
487
573
  callback(totalCount);
488
574
  };
489
575
 
490
576
  this.currentSubscription.onResult(processResults);
491
- const { totalCount } = await this.ctor.instancesFromSurrealResult(
492
- this.perspective,
493
- this.queryParams,
494
- this.currentSubscription.result
495
- );
496
- callback(totalCount);
577
+ const { totalCount } = await this.processSparqlResult(this.currentSubscription.result, undefined, true);
578
+ // Initial count returned via Promise — callback for updates only
497
579
  return totalCount;
498
580
  } else {
499
581
  const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
@@ -506,11 +588,31 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
506
588
 
507
589
  this.currentSubscription.onResult(processResults);
508
590
  const initialCount = this.currentSubscription.result?.[0]?.TotalCount || 0;
509
- callback(initialCount);
591
+ // Initial count returned via Promise — callback for subsequent updates only
510
592
  return initialCount;
511
593
  }
512
594
  }
513
595
 
596
+ /**
597
+ * Subscribes to count updates using SPARQL.
598
+ */
599
+ async countSubscribeSparql(callback: (count: number) => void): Promise<number> {
600
+ this.dispose();
601
+
602
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, this.queryParams);
603
+ this.currentSubscription = await this.perspective.subscribeQuery(sparqlQuery);
604
+
605
+ const processResults = async (result: any) => {
606
+ const { totalCount } = await this.processSparqlResult(result, undefined, true);
607
+ callback(totalCount);
608
+ };
609
+
610
+ this.currentSubscription.onResult(processResults);
611
+ const { totalCount } = await this.processSparqlResult(this.currentSubscription.result, undefined, true);
612
+ // Initial count returned via Promise — callback for updates only
613
+ return totalCount;
614
+ }
615
+
514
616
  /**
515
617
  * Gets a page of results with pagination metadata.
516
618
  *
@@ -528,10 +630,10 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
528
630
  */
529
631
  async paginate(pageSize: number, pageNumber: number): Promise<PaginationResult<T>> {
530
632
  const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
531
- if (this.useSurrealDBFlag) {
532
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
533
- const result = await this.perspective.querySurrealDB(surrealQuery);
534
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result)) as ResultsWithTotalCount<T>;
633
+ if (this.engineFlag === 'sparql') {
634
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, paginationQuery);
635
+ const result = await this.perspective.querySparql(sparqlQuery);
636
+ const { results, totalCount } = await this.processSparqlResult(result, paginationQuery, true) as ResultsWithTotalCount<T>;
535
637
  return { results, totalCount, pageSize, pageNumber };
536
638
  } else {
537
639
  const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
@@ -541,11 +643,25 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
541
643
  }
542
644
  }
543
645
 
646
+ /**
647
+ * Gets a page of results using SPARQL.
648
+ * Delegates to paginate() with SPARQL engine forced.
649
+ */
650
+ async paginateSparql(pageSize: number, pageNumber: number): Promise<PaginationResult<T>> {
651
+ const prev = this.engineFlag;
652
+ this.engineFlag = 'sparql';
653
+ try {
654
+ return await this.paginate(pageSize, pageNumber);
655
+ } finally {
656
+ this.engineFlag = prev;
657
+ }
658
+ }
659
+
544
660
  /**
545
661
  * Subscribes to paginated results updates.
546
662
  *
547
663
  * This method:
548
- * 1. Creates and initializes a SurrealDB live query subscription for the paginated results (default)
664
+ * 1. Creates and initializes a SPARQL live query subscription for the paginated results (default)
549
665
  * 2. Sets up the callback to process future page updates
550
666
  * 3. Returns the initial page immediately
551
667
  *
@@ -571,8 +687,8 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
571
687
  * ```
572
688
  *
573
689
  * @remarks
574
- * By default, this uses SurrealDB live queries for real-time updates.
575
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
690
+ * By default, this uses SPARQL live queries for real-time updates.
691
+ * Prolog subscriptions remain available via `.useSPARQL(false)`.
576
692
  */
577
693
  async paginateSubscribe(
578
694
  pageSize: number,
@@ -584,19 +700,32 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
584
700
 
585
701
  const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
586
702
 
587
- if (this.useSurrealDBFlag) {
588
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
589
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
703
+ if (this.engineFlag === 'sparql') {
704
+ // Subscribe to the FULL result set (no LIMIT/OFFSET) so the subscription
705
+ // detects changes anywhere in the dataset (e.g. new items beyond current page).
706
+ // Pagination is applied in JS when processing each update.
707
+ const subscriptionParams = { ...(this.queryParams || {}) };
708
+ delete subscriptionParams.limit;
709
+ delete subscriptionParams.offset;
710
+ const sparqlQuery = await this.ctor.queryToSPARQL(this.perspective, subscriptionParams);
711
+ this.currentSubscription = await this.perspective.subscribeQuery(sparqlQuery);
712
+
713
+ // Query for processSparqlResult has NO limit/offset — gets all results, totalCount via count:true
714
+ const fullQuery = { ...(this.queryParams || {}), count: true };
590
715
 
591
716
  const processResults = async (result: any) => {
592
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result)) as ResultsWithTotalCount<T>;
717
+ const { results: allResults, totalCount } = await this.processSparqlResult(result, fullQuery, true) as ResultsWithTotalCount<T>;
718
+ const start = pageSize * (pageNumber - 1);
719
+ const results = allResults.slice(start, start + pageSize);
593
720
  callback({ results, totalCount, pageSize, pageNumber });
594
721
  };
595
722
 
596
723
  this.currentSubscription.onResult(processResults);
597
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, this.currentSubscription.result)) as ResultsWithTotalCount<T>;
724
+ const { results: allResults, totalCount } = await this.processSparqlResult(this.currentSubscription.result, fullQuery, true) as ResultsWithTotalCount<T>;
725
+ const start = pageSize * (pageNumber - 1);
726
+ const results = allResults.slice(start, start + pageSize);
598
727
  const initialPage = { results, totalCount, pageSize, pageNumber };
599
- callback(initialPage);
728
+ // Initial page returned via Promise — callback for subsequent updates only
600
729
  return initialPage;
601
730
  } else {
602
731
  const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
@@ -610,8 +739,26 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
610
739
  this.currentSubscription.onResult(processResults);
611
740
  const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result)) as ResultsWithTotalCount<T>;
612
741
  const initialPrologPage = { results, totalCount, pageSize, pageNumber };
613
- callback(initialPrologPage);
742
+ // Initial page returned via Promise — callback for subsequent updates only
614
743
  return initialPrologPage;
615
744
  }
616
745
  }
746
+
747
+ /**
748
+ * Subscribes to paginated results updates using SPARQL.
749
+ * Delegates to paginateSubscribe() with SPARQL engine forced.
750
+ */
751
+ async paginateSubscribeSparql(
752
+ pageSize: number,
753
+ pageNumber: number,
754
+ callback: (results: PaginationResult<T>) => void
755
+ ): Promise<PaginationResult<T>> {
756
+ const prev = this.engineFlag;
757
+ this.engineFlag = 'sparql';
758
+ try {
759
+ return await this.paginateSubscribe(pageSize, pageNumber, callback);
760
+ } finally {
761
+ this.engineFlag = prev;
762
+ }
763
+ }
617
764
  }
@@ -50,11 +50,11 @@ export class Subject {
50
50
  Object.defineProperty(this, p, {
51
51
  configurable: true,
52
52
  get: async () => {
53
- // Use SurrealDB for data queries
53
+ // Use SPARQL for data queries
54
54
  try {
55
- return await this.#perspective.getPropertyValueViaSurreal(this.#baseExpression, this.#subjectClassName, p);
55
+ return await this.#perspective.getPropertyValueViaSparql(this.#baseExpression, this.#subjectClassName, p);
56
56
  } catch (err) {
57
- console.warn(`Failed to get property ${p} via SurrealDB:`, err);
57
+ console.warn(`Failed to get property ${p} via SPARQL:`, err);
58
58
  return undefined;
59
59
  }
60
60
  }
@@ -91,11 +91,11 @@ export class Subject {
91
91
  Object.defineProperty(this, c, {
92
92
  configurable: true,
93
93
  get: async () => {
94
- // Use SurrealDB for data queries
94
+ // Use SPARQL for data queries
95
95
  try {
96
- return await this.#perspective.getRelationValuesViaSurreal(this.#baseExpression, this.#subjectClassName, c);
96
+ return await this.#perspective.getRelationValuesViaSparql(this.#baseExpression, this.#subjectClassName, c);
97
97
  } catch (err) {
98
- console.warn(`Failed to get relation ${c} via SurrealDB:`, err);
98
+ console.warn(`Failed to get relation ${c} via SPARQL:`, err);
99
99
  return [];
100
100
  }
101
101
  }