@coasys/ad4m 0.13.0-postmessage-ws-proxy.0 → 0.13.0-postmessage-ws-proxy.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 (33) hide show
  1. package/lib/index.cjs +564 -461
  2. package/lib/index.js +561 -462
  3. package/lib/src/index.d.ts +1 -0
  4. package/lib/src/index.js +1 -0
  5. package/lib/src/model/Ad4mModel.d.ts +9 -17
  6. package/lib/src/model/Ad4mModel.js +34 -148
  7. package/lib/src/model/ModelQueryBuilder.d.ts +5 -10
  8. package/lib/src/model/ModelQueryBuilder.js +8 -14
  9. package/lib/src/model/shacl-gen.js +115 -46
  10. package/lib/src/model/types.d.ts +138 -3
  11. package/lib/src/perspectives/PerspectiveClient.d.ts +4 -4
  12. package/lib/src/perspectives/PerspectiveClient.js +5 -6
  13. package/lib/src/perspectives/PerspectiveProxy.d.ts +8 -7
  14. package/lib/src/perspectives/PerspectiveProxy.js +10 -9
  15. package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
  16. package/lib/src/perspectives/SparqlBindings.js +65 -0
  17. package/lib/src/shacl/SHACLShape.d.ts +18 -0
  18. package/lib/src/shacl/SHACLShape.js +83 -0
  19. package/package.json +8 -11
  20. package/src/index.ts +1 -0
  21. package/src/model/Ad4mModel.test.ts +23 -64
  22. package/src/model/Ad4mModel.ts +52 -159
  23. package/src/model/ModelQueryBuilder.ts +17 -23
  24. package/src/model/relation-filtering.test.ts +46 -39
  25. package/src/model/shacl-gen.ts +122 -53
  26. package/src/model/shacl-roundtrip.test.ts +197 -0
  27. package/src/model/types-typed-query.test.ts +360 -0
  28. package/src/model/types.ts +194 -3
  29. package/src/perspectives/PerspectiveClient.ts +6 -8
  30. package/src/perspectives/PerspectiveProxy.ts +13 -13
  31. package/src/perspectives/SparqlBindings.ts +79 -0
  32. package/src/shacl/SHACLShape.test.ts +110 -0
  33. package/src/shacl/SHACLShape.ts +125 -0
@@ -589,24 +589,27 @@ export class PerspectiveProxy {
589
589
  * @param query - SPARQL query string
590
590
  * @returns Query results as parsed JSON
591
591
  */
592
- async querySparql(query: string): Promise<any> {
592
+ async querySparql<T = any>(query: string): Promise<T> {
593
593
  const cached = getCachedResult(this.#handle.uuid, query);
594
- if (cached !== undefined) return cached;
594
+ if (cached !== undefined) return cached as T;
595
595
  const result = await this.#client.querySparql(this.#handle.uuid, query);
596
596
  setCachedResult(this.#handle.uuid, query, result);
597
- return result;
597
+ return result as T;
598
598
  }
599
599
 
600
600
  /**
601
601
  * Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
602
- *
602
+ *
603
+ * The executor resolves the model's shape from the perspective's SHACL
604
+ * triples (written by `addSdna`). Callers no longer ship shape
605
+ * metadata with the query; the perspective is the source of truth.
606
+ *
603
607
  * @param className - The model class name (e.g. "Recipe")
604
608
  * @param queryJson - Structured query as JSON string
605
- * @param shapeJson - Optional shape metadata JSON from the model class
606
609
  * @returns Object with `instances` array and `totalCount`
607
610
  */
608
- async modelQuery(className: string, queryJson: string, shapeJson?: string): Promise<{ instances: any[], totalCount: number }> {
609
- return await this.#client.modelQuery(this.#handle.uuid, className, queryJson, shapeJson);
611
+ async modelQuery(className: string, queryJson: string): Promise<{ instances: any[], totalCount: number }> {
612
+ return await this.#client.modelQuery(this.#handle.uuid, className, queryJson);
610
613
  }
611
614
 
612
615
  /**
@@ -618,18 +621,16 @@ export class PerspectiveProxy {
618
621
  *
619
622
  * @param className - The model class name (e.g. "Message")
620
623
  * @param instanceIds - Array of instance base expression URIs
621
- * @param shapeJson - Shape metadata JSON from the model class
622
624
  * @param propertyNames - Optional subset of property names to evaluate
623
625
  * @returns Map of instance ID → evaluated property values
624
626
  */
625
627
  async evaluateGetters(
626
628
  className: string,
627
629
  instanceIds: string[],
628
- shapeJson: string,
629
630
  propertyNames?: string[],
630
631
  ): Promise<Record<string, Record<string, any>>> {
631
632
  return await this.#client.evaluateGetters(
632
- this.#handle.uuid, className, instanceIds, shapeJson, propertyNames,
633
+ this.#handle.uuid, className, instanceIds, propertyNames,
633
634
  );
634
635
  }
635
636
 
@@ -643,11 +644,10 @@ export class PerspectiveProxy {
643
644
  *
644
645
  * @param className - The model class name
645
646
  * @param queryJson - JSON-serialized query parameters (same as modelQuery)
646
- * @param shapeJson - Optional shape metadata JSON from the model class
647
647
  * @returns Object with `subscriptionId` and initial `result`
648
648
  */
649
- async modelSubscribe(className: string, queryJson: string, shapeJson?: string): Promise<{ subscriptionId: string, result: any }> {
650
- return await this.#client.modelSubscribe(this.#handle.uuid, className, queryJson, shapeJson);
649
+ async modelSubscribe(className: string, queryJson: string): Promise<{ subscriptionId: string, result: any }> {
650
+ return await this.#client.modelSubscribe(this.#handle.uuid, className, queryJson);
651
651
  }
652
652
 
653
653
  /**
@@ -0,0 +1,79 @@
1
+ /**
2
+ * SPARQL binding helpers — typed shapes and parsers for `querySparql<T>()`.
3
+ *
4
+ * AD4M stores non-string property values as URL-encoded `Literal` payloads
5
+ * (see {@link Literal}). When raw SPARQL queries pull these values out of the
6
+ * RDF store the bindings are still in encoded form; consumers must decode
7
+ * before use. The helpers here centralise that decode step so each call site
8
+ * can pick the variant matching its declared binding type.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * interface MessageBinding {
13
+ * id: string;
14
+ * timestamp: string; // raw literal — decode with parseLitNumber
15
+ * body?: string; // raw literal — decode with parseLit
16
+ * }
17
+ * const rows = await perspective.querySparql<MessageBinding[]>(query);
18
+ * const ts = parseLitNumber(rows[0].timestamp); // number
19
+ * const body = rows[0].body ? parseLit(rows[0].body) : '';
20
+ * ```
21
+ */
22
+
23
+ import { Literal } from "../Literal";
24
+
25
+ /** Common AD4M link binding — matches the `?source/?predicate/?target/?author/?timestamp` pattern. */
26
+ export interface LinkBinding {
27
+ source: string;
28
+ predicate: string;
29
+ target: string;
30
+ author?: string;
31
+ timestamp?: string;
32
+ }
33
+
34
+ /** COUNT(?x) result binding — SPARQL returns counts as string literals. */
35
+ export interface CountBinding {
36
+ count: string;
37
+ }
38
+
39
+ /** Sum a SPARQL COUNT(?x) result down to a plain number (returns 0 on empty). */
40
+ export function parseSparqlCount(result: CountBinding[] | undefined | null): number {
41
+ if (!result || result.length === 0) return 0;
42
+ const raw = result[0].count;
43
+ const n = parseInt(raw, 10);
44
+ return Number.isNaN(n) ? 0 : n;
45
+ }
46
+
47
+ /**
48
+ * Decode a `Literal`-encoded SPARQL binding back to a plain string.
49
+ *
50
+ * Mirrors Flux's local `parseLit` helper. Returns `''` for `undefined`/empty
51
+ * input. Falls through to the raw value if decoding fails (defensive — the
52
+ * binding may already be a plain string for unwrapped properties).
53
+ */
54
+ export function parseLit(val: string | undefined | null): string {
55
+ if (val === undefined || val === null || val === '') return '';
56
+ try {
57
+ const result = Literal.fromUrl(val).get();
58
+ if (result && typeof result === 'object') {
59
+ return (result as { data?: string }).data ?? JSON.stringify(result);
60
+ }
61
+ return String(result);
62
+ } catch {
63
+ return val;
64
+ }
65
+ }
66
+
67
+ /** Decode a `Literal`-encoded binding to a number. Returns 0 on empty/invalid input. */
68
+ export function parseLitNumber(val: string | undefined | null): number {
69
+ if (val === undefined || val === null || val === '') return 0;
70
+ const decoded = parseLit(val);
71
+ const n = Number(decoded);
72
+ return Number.isNaN(n) ? 0 : n;
73
+ }
74
+
75
+ /** Decode a `Literal`-encoded binding to a boolean. Returns false on empty input. */
76
+ export function parseLitBoolean(val: string | undefined | null): boolean {
77
+ if (val === undefined || val === null || val === '') return false;
78
+ return parseLit(val) === 'true';
79
+ }
@@ -491,4 +491,114 @@ describe('SHACLShape', () => {
491
491
  expect(reconstructed.properties[0].in).toEqual(original.properties[0].in);
492
492
  });
493
493
  });
494
+
495
+ describe('runtime metadata predicates (SHACL as source of truth)', () => {
496
+ it('emits and parses relationKind', () => {
497
+ const shape = new SHACLShape('ns://Recipe');
498
+ shape.addProperty({
499
+ name: 'ingredients',
500
+ path: 'ns://has_ingredient',
501
+ relationKind: 'hasMany',
502
+ });
503
+ const links = shape.toLinks();
504
+ const kindLink = links.find(l => l.predicate === 'ad4m://relationKind');
505
+ expect(kindLink?.target).toBe('literal:string:hasMany');
506
+
507
+ const round = SHACLShape.fromLinks(links, shape.nodeShapeUri);
508
+ expect(round.properties[0].relationKind).toBe('hasMany');
509
+ });
510
+
511
+ it('emits and parses targetClassName', () => {
512
+ const shape = new SHACLShape('ns://Recipe');
513
+ shape.addProperty({
514
+ name: 'ingredients',
515
+ path: 'ns://has_ingredient',
516
+ targetClassName: 'Ingredient',
517
+ });
518
+ const links = shape.toLinks();
519
+ const link = links.find(l => l.predicate === 'ad4m://targetClassName');
520
+ expect(link?.target).toBe('literal:string:Ingredient');
521
+
522
+ const round = SHACLShape.fromLinks(links, shape.nodeShapeUri);
523
+ expect(round.properties[0].targetClassName).toBe('Ingredient');
524
+ });
525
+
526
+ it('emits and parses whereFilter as a JSON literal', () => {
527
+ const shape = new SHACLShape('ns://Board');
528
+ shape.addProperty({
529
+ name: 'tasks',
530
+ path: 'ns://has_task',
531
+ whereFilter: { status: 'active' },
532
+ });
533
+ const links = shape.toLinks();
534
+ const link = links.find(l => l.predicate === 'ad4m://whereFilter');
535
+ expect(link?.target).toContain('"status"');
536
+
537
+ const round = SHACLShape.fromLinks(links, shape.nodeShapeUri);
538
+ expect(round.properties[0].whereFilter).toEqual({ status: 'active' });
539
+ });
540
+
541
+ it('emits and parses wherePredicates', () => {
542
+ const shape = new SHACLShape('ns://Board');
543
+ shape.addProperty({
544
+ name: 'tasks',
545
+ path: 'ns://has_task',
546
+ wherePredicates: { status: 'ns://status' },
547
+ });
548
+ const links = shape.toLinks();
549
+ const link = links.find(l => l.predicate === 'ad4m://wherePredicates');
550
+ expect(link).toBeDefined();
551
+
552
+ const round = SHACLShape.fromLinks(links, shape.nodeShapeUri);
553
+ expect(round.properties[0].wherePredicates).toEqual({ status: 'ns://status' });
554
+ });
555
+
556
+ it('omits wherePredicates link for empty maps', () => {
557
+ const shape = new SHACLShape('ns://Board');
558
+ shape.addProperty({
559
+ name: 'tasks',
560
+ path: 'ns://has_task',
561
+ wherePredicates: {},
562
+ });
563
+ const links = shape.toLinks();
564
+ const link = links.find(l => l.predicate === 'ad4m://wherePredicates');
565
+ expect(link).toBeUndefined();
566
+ });
567
+
568
+ it('emits and parses filter=false as a literal boolean', () => {
569
+ const shape = new SHACLShape('ns://Doc');
570
+ shape.addProperty({
571
+ name: 'tags',
572
+ path: 'ns://tag',
573
+ filter: false,
574
+ });
575
+ const links = shape.toLinks();
576
+ const link = links.find(l => l.predicate === 'ad4m://filter');
577
+ expect(link?.target).toBe('literal:false');
578
+
579
+ const round = SHACLShape.fromLinks(links, shape.nodeShapeUri);
580
+ expect(round.properties[0].filter).toBe(false);
581
+ });
582
+
583
+ it('round-trips all runtime metadata through toJSON() and fromJSON()', () => {
584
+ const original = new SHACLShape('ns://Board');
585
+ original.addProperty({
586
+ name: 'tasks',
587
+ path: 'ns://has_task',
588
+ relationKind: 'hasMany',
589
+ targetClassName: 'Task',
590
+ whereFilter: { status: 'active' },
591
+ wherePredicates: { status: 'ns://status' },
592
+ filter: false,
593
+ });
594
+ const json = original.toJSON();
595
+ const reconstructed = SHACLShape.fromJSON(json);
596
+ const prop = reconstructed.properties[0];
597
+ expect(prop.relationKind).toBe('hasMany');
598
+ expect(prop.targetClassName).toBe('Task');
599
+ expect(prop.whereFilter).toEqual({ status: 'active' });
600
+ expect(prop.wherePredicates).toEqual({ status: 'ns://status' });
601
+ expect(prop.filter).toBe(false);
602
+ });
603
+ });
494
604
  });
@@ -179,6 +179,29 @@ export interface SHACLPropertyShape {
179
179
  * Each entry has a `value` (the RDF term) and an optional `label` (human-readable name).
180
180
  * Standard SHACL `sh:in` only defines values; labels are an AD4M extension. */
181
181
  in?: Array<{ value: string; label?: string }>;
182
+
183
+ /** AD4M-specific: kind of relation this property describes.
184
+ * Drives direction (forward/reverse), scalar-vs-collection rendering,
185
+ * and default max-count. */
186
+ relationKind?: 'hasMany' | 'hasOne' | 'belongsToOne' | 'belongsToMany';
187
+
188
+ /** AD4M-specific: target class name (local-name) for a relation property.
189
+ * Complements `class` (the SHACL node-shape URI) by providing the bare
190
+ * model class name used by the executor to look up the target shape
191
+ * through the perspective's shape cache. */
192
+ targetClassName?: string;
193
+
194
+ /** AD4M-specific: post-getter where-clause filter for a relation property. */
195
+ whereFilter?: any;
196
+
197
+ /** AD4M-specific: predicate-IRI lookup map for `whereFilter` keys
198
+ * (property name → predicate URI on the target class). */
199
+ wherePredicates?: Record<string, string>;
200
+
201
+ /** AD4M-specific: whether conformance/type filtering is enabled for this
202
+ * relation. `false` opts out of DB-level type filtering while keeping
203
+ * hydration via `include`. */
204
+ filter?: boolean;
182
205
  }
183
206
 
184
207
  /**
@@ -558,6 +581,46 @@ export class SHACLShape {
558
581
  target: `literal:string:${JSON.stringify(prop.in)}`
559
582
  });
560
583
  }
584
+
585
+ if (prop.relationKind) {
586
+ links.push({
587
+ source: propShapeId,
588
+ predicate: "ad4m://relationKind",
589
+ target: `literal:string:${prop.relationKind}`
590
+ });
591
+ }
592
+
593
+ if (prop.targetClassName) {
594
+ links.push({
595
+ source: propShapeId,
596
+ predicate: "ad4m://targetClassName",
597
+ target: `literal:string:${prop.targetClassName}`
598
+ });
599
+ }
600
+
601
+ if (prop.whereFilter !== undefined && prop.whereFilter !== null) {
602
+ links.push({
603
+ source: propShapeId,
604
+ predicate: "ad4m://whereFilter",
605
+ target: `literal:string:${JSON.stringify(prop.whereFilter)}`
606
+ });
607
+ }
608
+
609
+ if (prop.wherePredicates && Object.keys(prop.wherePredicates).length > 0) {
610
+ links.push({
611
+ source: propShapeId,
612
+ predicate: "ad4m://wherePredicates",
613
+ target: `literal:string:${JSON.stringify(prop.wherePredicates)}`
614
+ });
615
+ }
616
+
617
+ if (prop.filter !== undefined) {
618
+ links.push({
619
+ source: propShapeId,
620
+ predicate: "ad4m://filter",
621
+ target: `literal:${prop.filter}`
622
+ });
623
+ }
561
624
  }
562
625
 
563
626
  return links;
@@ -800,6 +863,58 @@ export class SHACLShape {
800
863
  }
801
864
  }
802
865
 
866
+ const relationKindLink = links.find(l =>
867
+ l.source === propShapeId && l.predicate === "ad4m://relationKind"
868
+ );
869
+ if (relationKindLink) {
870
+ const val = relationKindLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
871
+ if (val === 'hasMany' || val === 'hasOne' || val === 'belongsToOne' || val === 'belongsToMany') {
872
+ prop.relationKind = val;
873
+ }
874
+ }
875
+
876
+ const targetClassNameLink = links.find(l =>
877
+ l.source === propShapeId && l.predicate === "ad4m://targetClassName"
878
+ );
879
+ if (targetClassNameLink) {
880
+ prop.targetClassName = targetClassNameLink.target.replace(
881
+ /^literal:\/\/string:|^literal:string:/, ''
882
+ );
883
+ }
884
+
885
+ const whereFilterLink = links.find(l =>
886
+ l.source === propShapeId && l.predicate === "ad4m://whereFilter"
887
+ );
888
+ if (whereFilterLink) {
889
+ try {
890
+ const jsonStr = whereFilterLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
891
+ prop.whereFilter = JSON.parse(jsonStr);
892
+ } catch (e) {
893
+ // Ignore parse errors
894
+ }
895
+ }
896
+
897
+ const wherePredicatesLink = links.find(l =>
898
+ l.source === propShapeId && l.predicate === "ad4m://wherePredicates"
899
+ );
900
+ if (wherePredicatesLink) {
901
+ try {
902
+ const jsonStr = wherePredicatesLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
903
+ prop.wherePredicates = JSON.parse(jsonStr);
904
+ } catch (e) {
905
+ // Ignore parse errors
906
+ }
907
+ }
908
+
909
+ const filterLink = links.find(l =>
910
+ l.source === propShapeId && l.predicate === "ad4m://filter"
911
+ );
912
+ if (filterLink) {
913
+ let val = filterLink.target.replace(/^literal:\/\/|^literal:/, '');
914
+ if (val.startsWith('boolean:')) val = val.substring(8);
915
+ prop.filter = val === 'true';
916
+ }
917
+
803
918
  shape.addProperty(prop);
804
919
  }
805
920
 
@@ -838,6 +953,11 @@ export class SHACLShape {
838
953
  conformance_conditions: p.conformanceConditions,
839
954
  class: p.class,
840
955
  in: p.in,
956
+ relation_kind: p.relationKind,
957
+ target_class_name: p.targetClassName,
958
+ where_filter: p.whereFilter,
959
+ where_predicates: p.wherePredicates,
960
+ filter: p.filter,
841
961
  })),
842
962
  constructor_actions: this.constructor_actions,
843
963
  destructor_actions: this.destructor_actions,
@@ -874,6 +994,11 @@ export class SHACLShape {
874
994
  conformanceConditions: p.conformance_conditions,
875
995
  class: p.class,
876
996
  in: p.in,
997
+ relationKind: p.relation_kind,
998
+ targetClassName: p.target_class_name,
999
+ whereFilter: p.where_filter,
1000
+ wherePredicates: p.where_predicates,
1001
+ filter: p.filter,
877
1002
  });
878
1003
  }
879
1004