@coasys/ad4m 0.13.0-test-7 → 0.13.0-test-8-profile-cache-fix

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 (63) hide show
  1. package/lib/index.cjs +1121 -835
  2. package/lib/index.js +1108 -835
  3. package/lib/src/Ad4mClient.d.ts +4 -1
  4. package/lib/src/Ad4mClient.js +2 -2
  5. package/lib/src/agent/AgentClient.d.ts +3 -0
  6. package/lib/src/agent/AgentClient.js +27 -5
  7. package/lib/src/ai/AIClient.js +1 -1
  8. package/lib/src/apiClient.d.ts +5 -1
  9. package/lib/src/apiClient.js +14 -6
  10. package/lib/src/index.d.ts +4 -0
  11. package/lib/src/index.js +4 -0
  12. package/lib/src/model/Ad4mModel.d.ts +30 -36
  13. package/lib/src/model/Ad4mModel.js +93 -382
  14. package/lib/src/model/ModelQueryBuilder.d.ts +5 -10
  15. package/lib/src/model/ModelQueryBuilder.js +142 -62
  16. package/lib/src/model/decorators.d.ts +7 -4
  17. package/lib/src/model/decorators.js +0 -7
  18. package/lib/src/model/query-sparql.d.ts +0 -10
  19. package/lib/src/model/query-sparql.js +12 -17
  20. package/lib/src/model/shacl-gen.js +120 -47
  21. package/lib/src/model/types.d.ts +140 -4
  22. package/lib/src/perspectives/PerspectiveClient.d.ts +13 -4
  23. package/lib/src/perspectives/PerspectiveClient.js +22 -6
  24. package/lib/src/perspectives/PerspectiveProxy.d.ts +27 -7
  25. package/lib/src/perspectives/PerspectiveProxy.js +60 -12
  26. package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
  27. package/lib/src/perspectives/SparqlBindings.js +65 -0
  28. package/lib/src/perspectives/WakerSubscriptionManager.js +5 -4
  29. package/lib/src/shacl/NodeExpression.d.ts +44 -0
  30. package/lib/src/shacl/NodeExpression.js +39 -0
  31. package/lib/src/shacl/SHACLShape.d.ts +23 -0
  32. package/lib/src/shacl/SHACLShape.js +115 -1
  33. package/lib/src/shacl/builders.d.ts +58 -0
  34. package/lib/src/shacl/builders.js +76 -0
  35. package/lib/src/shacl/index.d.ts +36 -0
  36. package/lib/src/shacl/index.js +33 -0
  37. package/package.json +1 -1
  38. package/src/Ad4mClient.ts +7 -2
  39. package/src/agent/AgentClient.ts +35 -7
  40. package/src/ai/AIClient.ts +1 -1
  41. package/src/apiClient.ts +17 -6
  42. package/src/index.ts +4 -0
  43. package/src/model/Ad4mModel.test.ts +274 -72
  44. package/src/model/Ad4mModel.ts +140 -420
  45. package/src/model/ModelQueryBuilder.ts +136 -71
  46. package/src/model/decorators.ts +7 -13
  47. package/src/model/query-sparql.test.ts +36 -20
  48. package/src/model/query-sparql.ts +12 -18
  49. package/src/model/relation-filtering.test.ts +46 -39
  50. package/src/model/shacl-gen.ts +128 -54
  51. package/src/model/shacl-roundtrip.test.ts +197 -0
  52. package/src/model/types-typed-query.test.ts +360 -0
  53. package/src/model/types.ts +196 -4
  54. package/src/perspectives/PerspectiveClient.ts +24 -8
  55. package/src/perspectives/PerspectiveProxy.test.ts +85 -1
  56. package/src/perspectives/PerspectiveProxy.ts +65 -20
  57. package/src/perspectives/SparqlBindings.ts +79 -0
  58. package/src/perspectives/WakerSubscriptionManager.ts +5 -4
  59. package/src/shacl/NodeExpression.ts +54 -0
  60. package/src/shacl/SHACLShape.test.ts +172 -0
  61. package/src/shacl/SHACLShape.ts +173 -1
  62. package/src/shacl/builders.ts +86 -0
  63. package/src/shacl/index.ts +72 -0
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import type { Ad4mModel } from "./Ad4mModel";
8
8
  import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
9
- import type { Where, Order, IncludeMap, Query, PaginationResult } from "./types";
9
+ import type { Query, PaginationResult, TypedWhere, TypedOrder, TypedIncludeMap, PropertyKeysOf } from "./types";
10
10
  /** Query builder for Ad4mModel queries.
11
11
  * Allows building queries with a fluent interface and either running them once
12
12
  * or subscribing to updates.
@@ -63,7 +63,7 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
63
63
  * })
64
64
  * ```
65
65
  */
66
- where(conditions: Where): ModelQueryBuilder<T>;
66
+ where(conditions: TypedWhere<T>): ModelQueryBuilder<T>;
67
67
  /**
68
68
  * Sets the order for the query results.
69
69
  *
@@ -75,7 +75,7 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
75
75
  * .order({ createdAt: "DESC" })
76
76
  * ```
77
77
  */
78
- order(orderBy: Order): ModelQueryBuilder<T>;
78
+ order(orderBy: TypedOrder<T>): ModelQueryBuilder<T>;
79
79
  /**
80
80
  * Sets the maximum number of results to return.
81
81
  *
@@ -156,7 +156,7 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
156
156
  * .properties(["name", "description", "rating"])
157
157
  * ```
158
158
  */
159
- properties(properties: string[]): ModelQueryBuilder<T>;
159
+ properties(properties: PropertyKeysOf<T>[] | string[]): ModelQueryBuilder<T>;
160
160
  /**
161
161
  * Controls whether SPARQL property getters are evaluated during hydration.
162
162
  *
@@ -202,13 +202,8 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
202
202
  * .run();
203
203
  * ```
204
204
  */
205
- include(map: IncludeMap): ModelQueryBuilder<T>;
205
+ include(map: TypedIncludeMap<T>): ModelQueryBuilder<T>;
206
206
  overrideModelClassName(className: string): ModelQueryBuilder<T>;
207
- /**
208
- * Sets the query engine to use.
209
- * @deprecated Prolog engine has been removed. All queries use SPARQL/Rust.
210
- */
211
- engine(_eng: 'sparql' | 'prolog'): ModelQueryBuilder<T>;
212
207
  /**
213
208
  * Executes the query once and returns the results.
214
209
  *
@@ -256,13 +256,6 @@ export class ModelQueryBuilder {
256
256
  this.modelClassName = className;
257
257
  return this;
258
258
  }
259
- /**
260
- * Sets the query engine to use.
261
- * @deprecated Prolog engine has been removed. All queries use SPARQL/Rust.
262
- */
263
- engine(_eng) {
264
- return this;
265
- }
266
259
  /**
267
260
  * Executes the query once and returns the results.
268
261
  *
@@ -306,8 +299,10 @@ export class ModelQueryBuilder {
306
299
  * ```
307
300
  */
308
301
  async first() {
302
+ const savedLimit = this.queryParams.limit;
309
303
  this.queryParams.limit = 1;
310
304
  const results = await this.get();
305
+ this.queryParams.limit = savedLimit;
311
306
  return results[0] ?? null;
312
307
  }
313
308
  /**
@@ -342,23 +337,18 @@ export class ModelQueryBuilder {
342
337
  // Clean up any existing subscription
343
338
  this.dispose();
344
339
  const ctor = this.ctor;
345
- // Build the model query params (className, queryJson, shapeJson)
346
- const { className, queryJson, shapeJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);
340
+ // Build the model query params (className, queryJson). The executor
341
+ // resolves the shape from the perspective's SHACL triples.
342
+ const { className, queryJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);
347
343
  // Register model subscription via Rust — this builds trigger SPARQL internally,
348
344
  // registers the subscription, and runs the initial query in one call.
349
- const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
345
+ const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
350
346
  // Convert JSON instances to model class instances
351
347
  const parseResults = (raw) => {
352
348
  return ctor.parseModelResult(this.perspective, raw, this.queryParams.include, this.queryParams.properties);
353
349
  };
354
- // Resolve non-literal (file-language) properties — handles both raw URI strings
355
- // and already-resolved FileData objects returned by the Rust executor.
356
- const resolveAndReturn = async (instances) => {
357
- await ctor.resolveNonLiteralProps(this.perspective, instances);
358
- return instances;
359
- };
360
- // Parse initial results (with non-literal resolution)
361
- const initialResults = await resolveAndReturn(parseResults(initialModelResult));
350
+ // Transforms are now applied by the Rust executor during hydration
351
+ const initialResults = parseResults(initialModelResult);
362
352
  // Track last emitted result fingerprint to suppress duplicate callbacks
363
353
  let lastResultFingerprint = null;
364
354
  const buildFingerprint = (results) => {
@@ -371,34 +361,65 @@ export class ModelQueryBuilder {
371
361
  // When Rust re-runs the model query and finds changed results, it pushes them.
372
362
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
373
363
  try {
374
- resolveAndReturn(parseResults(rawResult)).then((results) => {
375
- const fp = buildFingerprint(results);
376
- if (fp === lastResultFingerprint)
377
- return;
378
- lastResultFingerprint = fp;
379
- callback(results);
380
- }).catch((e) => {
381
- console.error('Model subscription update resolve error:', e);
382
- });
364
+ const results = parseResults(rawResult);
365
+ console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${results.length} instances`);
366
+ const fp = buildFingerprint(results);
367
+ if (fp === lastResultFingerprint) {
368
+ console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
369
+ return;
370
+ }
371
+ console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
372
+ lastResultFingerprint = fp;
373
+ callback(results);
383
374
  }
384
375
  catch (e) {
385
376
  console.error('Model subscription update parse error:', e);
386
377
  }
387
378
  });
388
- // Set up keepalive with failure tracking
389
- let keepaliveFailures = 0;
390
- const keepaliveTimer = setInterval(() => {
391
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
392
- keepaliveFailures = 0;
393
- }).catch((e) => {
394
- keepaliveFailures++;
395
- console.warn(`Model subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
396
- });
397
- }, 30000);
379
+ // Set up keepalive with recovery — uses setTimeout loop so we can
380
+ // break out and resubscribe when the server evicts the subscription.
381
+ let disposed = false;
382
+ let keepaliveTimer;
383
+ let resubscribeAttempts = 0;
384
+ const MAX_RESUBSCRIBE_ATTEMPTS = 5;
385
+ const keepaliveLoop = async () => {
386
+ if (disposed)
387
+ return;
388
+ try {
389
+ await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
390
+ resubscribeAttempts = 0; // Reset on success
391
+ }
392
+ catch (e) {
393
+ console.warn(`Model subscription keepalive failed for ${subscriptionId}:`, e);
394
+ if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
395
+ resubscribeAttempts++;
396
+ const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
397
+ console.warn(`Resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
398
+ await new Promise(r => setTimeout(r, backoffMs));
399
+ try {
400
+ unsubscribe();
401
+ await this.subscribe(callback);
402
+ }
403
+ catch (resubErr) {
404
+ console.error('Model subscription resubscribe failed:', resubErr);
405
+ }
406
+ }
407
+ else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
408
+ console.error(`Model subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
409
+ }
410
+ return; // new subscription owns its own keepalive loop
411
+ }
412
+ if (!disposed) {
413
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
414
+ }
415
+ };
416
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
398
417
  // Store dispose function
399
418
  this.currentSubscription = {
400
419
  dispose: () => {
401
- clearInterval(keepaliveTimer);
420
+ disposed = true;
421
+ if (keepaliveTimer)
422
+ clearTimeout(keepaliveTimer);
402
423
  unsubscribe();
403
424
  this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });
404
425
  },
@@ -471,8 +492,8 @@ export class ModelQueryBuilder {
471
492
  // Clean up any existing subscription
472
493
  this.dispose();
473
494
  const countParams = { ...this.queryParams, limit: 0 };
474
- const { className, queryJson, shapeJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);
475
- const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
495
+ const { className, queryJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);
496
+ const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson);
476
497
  const parseCount = (raw) => {
477
498
  const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
478
499
  return data.totalCount ?? 0;
@@ -486,18 +507,47 @@ export class ModelQueryBuilder {
486
507
  console.error('Count subscription update parse error:', e);
487
508
  }
488
509
  });
489
- let keepaliveFailures = 0;
490
- const keepaliveTimer = setInterval(() => {
491
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
492
- keepaliveFailures = 0;
493
- }).catch((e) => {
494
- keepaliveFailures++;
495
- console.warn(`Count subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
496
- });
497
- }, 30000);
510
+ let disposed = false;
511
+ let keepaliveTimer;
512
+ let resubscribeAttempts = 0;
513
+ const MAX_RESUBSCRIBE_ATTEMPTS = 5;
514
+ const keepaliveLoop = async () => {
515
+ if (disposed)
516
+ return;
517
+ try {
518
+ await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
519
+ resubscribeAttempts = 0;
520
+ }
521
+ catch (e) {
522
+ console.warn(`Count subscription keepalive failed for ${subscriptionId}:`, e);
523
+ if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
524
+ resubscribeAttempts++;
525
+ const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
526
+ console.warn(`Count resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
527
+ await new Promise(r => setTimeout(r, backoffMs));
528
+ try {
529
+ unsubscribe();
530
+ await this.countSubscribe(callback);
531
+ }
532
+ catch (resubErr) {
533
+ console.error('Count subscription resubscribe failed:', resubErr);
534
+ }
535
+ }
536
+ else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
537
+ console.error(`Count subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
538
+ }
539
+ return;
540
+ }
541
+ if (!disposed) {
542
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
543
+ }
544
+ };
545
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
498
546
  this.currentSubscription = {
499
547
  dispose: () => {
500
- clearInterval(keepaliveTimer);
548
+ disposed = true;
549
+ if (keepaliveTimer)
550
+ clearTimeout(keepaliveTimer);
501
551
  unsubscribe();
502
552
  this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });
503
553
  },
@@ -578,8 +628,8 @@ export class ModelQueryBuilder {
578
628
  const subscriptionParams = { ...(this.queryParams || {}) };
579
629
  delete subscriptionParams.limit;
580
630
  delete subscriptionParams.offset;
581
- const { className, queryJson, shapeJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);
582
- const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);
631
+ const { className, queryJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);
632
+ const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson);
583
633
  // Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)
584
634
  const paginatedQuery = {
585
635
  ...(this.queryParams || {}),
@@ -592,20 +642,50 @@ export class ModelQueryBuilder {
592
642
  callback({ results, totalCount, pageSize, pageNumber });
593
643
  };
594
644
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
645
+ console.debug(`[ModelQueryBuilder.paginateSubscribe] Update received for ${subscriptionId}, re-fetching paginated data...`);
595
646
  processResults().catch(e => console.error('Paginate subscription error:', e));
596
647
  });
597
- let keepaliveFailures = 0;
598
- const keepaliveTimer = setInterval(() => {
599
- this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId).then(() => {
600
- keepaliveFailures = 0;
601
- }).catch((e) => {
602
- keepaliveFailures++;
603
- console.warn(`Paginate subscription keepalive failed (attempt ${keepaliveFailures}) for ${subscriptionId}:`, e);
604
- });
605
- }, 30000);
648
+ let disposed = false;
649
+ let keepaliveTimer;
650
+ let resubscribeAttempts = 0;
651
+ const MAX_RESUBSCRIBE_ATTEMPTS = 5;
652
+ const keepaliveLoop = async () => {
653
+ if (disposed)
654
+ return;
655
+ try {
656
+ await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);
657
+ resubscribeAttempts = 0;
658
+ }
659
+ catch (e) {
660
+ console.warn(`Paginate subscription keepalive failed for ${subscriptionId}:`, e);
661
+ if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {
662
+ resubscribeAttempts++;
663
+ const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);
664
+ console.warn(`Paginate resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);
665
+ await new Promise(r => setTimeout(r, backoffMs));
666
+ try {
667
+ unsubscribe();
668
+ await this.paginateSubscribe(pageSize, pageNumber, callback);
669
+ }
670
+ catch (resubErr) {
671
+ console.error('Paginate subscription resubscribe failed:', resubErr);
672
+ }
673
+ }
674
+ else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {
675
+ console.error(`Paginate subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);
676
+ }
677
+ return;
678
+ }
679
+ if (!disposed) {
680
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
681
+ }
682
+ };
683
+ keepaliveTimer = setTimeout(keepaliveLoop, 30000);
606
684
  this.currentSubscription = {
607
685
  dispose: () => {
608
- clearInterval(keepaliveTimer);
686
+ disposed = true;
687
+ if (keepaliveTimer)
688
+ clearTimeout(keepaliveTimer);
609
689
  unsubscribe();
610
690
  this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });
611
691
  },
@@ -130,11 +130,14 @@ export interface PropertyOptions {
130
130
  */
131
131
  local?: boolean;
132
132
  /**
133
- * Optional transform function to modify the property value after it is retrieved.
134
- * This is useful for transforming raw data into a more usable format.
135
- * The function takes the raw value as input and returns the transformed value.
133
+ * Optional transform expression to modify the property value.
134
+ * This is a SHACL-AF Node Expression that runs in the Rust model query engine.
135
+ * Examples: `fileToDataUri`, `concat(literal('prefix_'), focus())`, etc.
136
+ * Builders (`focus`, `literal`, `path`, `exists`, `ifExpr`, `concat`,
137
+ * `coalesce`, `fn`) and the `fileToDataUri` built-in are exported from
138
+ * the package root: `import { concat, literal, focus } from '@coasys/ad4m'`.
136
139
  */
137
- transform?: (value: any) => any;
140
+ transform?: import('../shacl/NodeExpression').NodeExpression;
138
141
  /**
139
142
  * Allowed values for this property (enum constraint).
140
143
  * Maps to SHACL `sh:in`. Each entry has a `value` (the stored RDF term)
@@ -521,15 +521,8 @@ function resolveRelationArgs(first, second) {
521
521
  return opts;
522
522
  }
523
523
  export function HasMany(first, second) {
524
- const explicitThrough = typeof first === 'function' ? second?.through : first.through;
525
524
  const opts = resolveRelationArgs(first, second);
526
525
  return function (target, key) {
527
- if (!explicitThrough && !opts.getter) {
528
- const className = (target.constructor?.name) ?? 'unknown';
529
- console.warn(`@HasMany on ${className}.${String(key)} has no 'through' predicate — defaulting to 'ad4m://has_child'. ` +
530
- `Add { through: 'ad4m://has_child' } to silence this warning, or use a semantic predicate ` +
531
- `like { through: 'myns://has_${String(key)}' } for efficient targeted queries.`);
532
- }
533
526
  // --- relation registry ---
534
527
  const ctor = target.constructor;
535
528
  if (!relationRegistry.has(ctor))
@@ -38,16 +38,6 @@ export declare function formatSPARQLValue(value: any): string;
38
38
  * with named graph storage and metadata keyed by graph IRI.
39
39
  */
40
40
  export declare function buildSPARQLQuery(metadata: ModelMetadata, allRelationsMetadata: Record<string, RelationMetadataEntry>, query: Query, modelClass: any): string;
41
- /**
42
- * Build ORDER BY / LIMIT / OFFSET clauses for the SPARQL query.
43
- *
44
- * NOTE: The outer SELECT returns multiple rows per instance (one per link),
45
- * so LIMIT/OFFSET at the outer level would cut off links mid-instance.
46
- * This function is kept for backward compatibility and always returns "".
47
- * SPARQL-level pagination is handled via a subquery in buildSPARQLQuery
48
- * using buildPaginationSubquery().
49
- */
50
- export declare function buildSPARQLOrderLimitOffset(_metadata: ModelMetadata, query: Query): string;
51
41
  /**
52
42
  * Build an inner subquery that selects DISTINCT ?source URIs with
53
43
  * ORDER BY, LIMIT, and OFFSET applied at the instance level.
@@ -109,7 +109,9 @@ function escapeSPARQL(value) {
109
109
  .replace(/"/g, '\\"')
110
110
  .replace(/\n/g, "\\n")
111
111
  .replace(/\r/g, "\\r")
112
- .replace(/\t/g, "\\t");
112
+ .replace(/\t/g, "\\t")
113
+ .replace(/\0/g, "")
114
+ .replace(/\f/g, "\\u000C");
113
115
  }
114
116
  /**
115
117
  * Format a value as a SPARQL string literal (double-quoted).
@@ -124,8 +126,14 @@ export function formatSPARQLValue(value) {
124
126
  * Format an AD4M URI as an RDF IRI for use in SPARQL triple patterns.
125
127
  * All AD4M link source/predicate/target values become IRIs in angle brackets.
126
128
  * The Rust SPARQL service transparently transforms these to valid IRI format.
129
+ *
130
+ * Rejects characters that would break or inject into a SPARQL IRI token,
131
+ * matching the Rust-side `validate_iri()` function.
127
132
  */
128
133
  function iri(value) {
134
+ if (/[<>{}" ]/.test(value)) {
135
+ throw new Error(`Invalid IRI component: '${value}'`);
136
+ }
129
137
  return `<${value}>`;
130
138
  }
131
139
  /**
@@ -271,21 +279,8 @@ export function buildSPARQLQuery(metadata, allRelationsMetadata, query, modelCla
271
279
  ?_reifier <ad4m://ontology/timestamp> ?timestamp .
272
280
  ${filterClause}
273
281
  }
274
- ${buildSPARQLOrderLimitOffset(metadata, query)}
275
282
  `.trim();
276
283
  }
277
- /**
278
- * Build ORDER BY / LIMIT / OFFSET clauses for the SPARQL query.
279
- *
280
- * NOTE: The outer SELECT returns multiple rows per instance (one per link),
281
- * so LIMIT/OFFSET at the outer level would cut off links mid-instance.
282
- * This function is kept for backward compatibility and always returns "".
283
- * SPARQL-level pagination is handled via a subquery in buildSPARQLQuery
284
- * using buildPaginationSubquery().
285
- */
286
- export function buildSPARQLOrderLimitOffset(_metadata, query) {
287
- return "";
288
- }
289
284
  /**
290
285
  * Build an inner subquery that selects DISTINCT ?source URIs with
291
286
  * ORDER BY, LIMIT, and OFFSET applied at the instance level.
@@ -332,7 +327,7 @@ export function buildPaginationSubquery(joinPatterns, filterExpressions, metadat
332
327
  { SELECT DISTINCT ?source${tsSelect} WHERE {${innerJoin}${orderJoinPatterns.join('')}${tsPattern}
333
328
  FILTER(isIRI(?source))
334
329
  ${innerFilter}
335
- } GROUP BY ?source ${orderByClause} ${limitClause} ${offsetClause} }\n`;
330
+ } ${orderByClause} ${limitClause} ${offsetClause} }\n`;
336
331
  }
337
332
  /**
338
333
  * Build SPARQL FILTER expressions from user `where` conditions.
@@ -384,8 +379,8 @@ function buildSPARQLWhereFilters(metadata, _allRelationsMetadata, where) {
384
379
  const useParseLiteral = isLiteralStoredProperty(propMeta);
385
380
  // For literal-stored properties, push equality/IN/NOT filters to SPARQL using
386
381
  // <ad4m://fn/parse_literal>() which extracts the raw value from literal: IRIs.
387
- // The correct SPARQL syntax is <ad4m://fn/parse_literal>(?var) — NOT fn::parse_literal
388
- // (which was SurrealDB syntax that Oxigraph rejects at parse time).
382
+ // Use IRI form <ad4m://fn/parse_literal>(?var); the namespaced form
383
+ // fn::parse_literal is invalid SPARQL and Oxigraph rejects it at parse time.
389
384
  // Comparison operators (gt/lt/gte/lte/between/contains) remain JS-only because
390
385
  // parse_literal returns strings and numeric/date comparisons would be unreliable.
391
386
  // JS post-filter in instancesFromQueryResult remains as a safety net for all cases.