@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
@@ -540,13 +540,16 @@ export class PerspectiveProxy {
540
540
  /**
541
541
  * Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
542
542
  *
543
+ * The executor resolves the model's shape from the perspective's SHACL
544
+ * triples (written by `addSdna`). Callers no longer ship shape
545
+ * metadata with the query; the perspective is the source of truth.
546
+ *
543
547
  * @param className - The model class name (e.g. "Recipe")
544
548
  * @param queryJson - Structured query as JSON string
545
- * @param shapeJson - Optional shape metadata JSON from the model class
546
549
  * @returns Object with `instances` array and `totalCount`
547
550
  */
548
- async modelQuery(className, queryJson, shapeJson) {
549
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, shapeJson);
551
+ async modelQuery(className, queryJson) {
552
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
550
553
  }
551
554
  /**
552
555
  * Evaluate property getters for a batch of instances in a single RPC call.
@@ -557,12 +560,11 @@ export class PerspectiveProxy {
557
560
  *
558
561
  * @param className - The model class name (e.g. "Message")
559
562
  * @param instanceIds - Array of instance base expression URIs
560
- * @param shapeJson - Shape metadata JSON from the model class
561
563
  * @param propertyNames - Optional subset of property names to evaluate
562
564
  * @returns Map of instance ID → evaluated property values
563
565
  */
564
- async evaluateGetters(className, instanceIds, shapeJson, propertyNames) {
565
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, shapeJson, propertyNames);
566
+ async evaluateGetters(className, instanceIds, propertyNames) {
567
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, propertyNames);
566
568
  }
567
569
  /**
568
570
  * Subscribe to model query changes. Builds trigger SPARQL from the model shape
@@ -574,11 +576,10 @@ export class PerspectiveProxy {
574
576
  *
575
577
  * @param className - The model class name
576
578
  * @param queryJson - JSON-serialized query parameters (same as modelQuery)
577
- * @param shapeJson - Optional shape metadata JSON from the model class
578
579
  * @returns Object with `subscriptionId` and initial `result`
579
580
  */
580
- async modelSubscribe(className, queryJson, shapeJson) {
581
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, shapeJson);
581
+ async modelSubscribe(className, queryJson) {
582
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
582
583
  }
583
584
  /**
584
585
  * Adds a new link to the perspective.
@@ -766,17 +767,30 @@ export class PerspectiveProxy {
766
767
  async removeListener(type, cb) {
767
768
  if (type === 'link-added') {
768
769
  const index = __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").indexOf(cb);
769
- __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").splice(index, 1);
770
+ if (index >= 0)
771
+ __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").splice(index, 1);
770
772
  }
771
773
  else if (type === 'link-removed') {
772
774
  const index = __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").indexOf(cb);
773
- __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").splice(index, 1);
775
+ if (index >= 0)
776
+ __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").splice(index, 1);
774
777
  }
775
778
  else if (type === 'link-updated') {
776
779
  const index = __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").indexOf(cb);
777
- __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").splice(index, 1);
780
+ if (index >= 0)
781
+ __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").splice(index, 1);
778
782
  }
779
783
  }
784
+ /** Clean up all subscriptions registered by this proxy.
785
+ * Call this when the proxy is no longer needed to prevent subscription leaks.
786
+ * After calling dispose(), the proxy should not be used. */
787
+ dispose() {
788
+ __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeAllListeners(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
789
+ __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").length = 0;
790
+ __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").length = 0;
791
+ __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").length = 0;
792
+ __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f").length = 0;
793
+ }
780
794
  /**
781
795
  * Creates a snapshot of the current perspective state.
782
796
  * Useful for backup or sharing.
@@ -1066,6 +1080,40 @@ export class PerspectiveProxy {
1066
1080
  async addSdna(name, sdnaCode, sdnaType, shaclJson) {
1067
1081
  return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addSdna(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, name, sdnaCode, sdnaType, shaclJson);
1068
1082
  }
1083
+ /**
1084
+ * Batch variant of addSdna — registers multiple SDNA entries in a single RPC call.
1085
+ * Acquires the Rust-side mutex once for the entire batch.
1086
+ */
1087
+ async addSdnaAll(entries) {
1088
+ return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addSdnaBatch(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, entries);
1089
+ }
1090
+ /**
1091
+ * Batch-registers multiple model classes as SHACL subject classes in a single RPC call.
1092
+ * Skips classes already registered on this perspective instance.
1093
+ */
1094
+ async ensureSubjectClasses(jsClasses) {
1095
+ const entries = [];
1096
+ for (const jsClass of jsClasses) {
1097
+ const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
1098
+ if (__classPrivateFieldGet(this, _PerspectiveProxy_ensuredSubjectClasses, "f").has(className))
1099
+ continue;
1100
+ if (!jsClass.generateSHACL) {
1101
+ throw new Error(`Class ${jsClass.name} must have generateSHACL(). Use @Model decorator.`);
1102
+ }
1103
+ const { shape } = jsClass.generateSHACL();
1104
+ entries.push({
1105
+ name: className,
1106
+ sdnaType: 'subject_class',
1107
+ shaclJson: JSON.stringify(shape.toJSON()),
1108
+ });
1109
+ }
1110
+ if (entries.length === 0)
1111
+ return;
1112
+ await this.addSdnaAll(entries);
1113
+ for (const entry of entries) {
1114
+ __classPrivateFieldGet(this, _PerspectiveProxy_ensuredSubjectClasses, "f").add(entry.name);
1115
+ }
1116
+ }
1069
1117
  /**
1070
1118
  * Adds a subject class to the perspective.
1071
1119
  * Alias for addSdna() with sdnaType='subject_class'.
@@ -0,0 +1,47 @@
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
+ /** Common AD4M link binding — matches the `?source/?predicate/?target/?author/?timestamp` pattern. */
23
+ export interface LinkBinding {
24
+ source: string;
25
+ predicate: string;
26
+ target: string;
27
+ author?: string;
28
+ timestamp?: string;
29
+ }
30
+ /** COUNT(?x) result binding — SPARQL returns counts as string literals. */
31
+ export interface CountBinding {
32
+ count: string;
33
+ }
34
+ /** Sum a SPARQL COUNT(?x) result down to a plain number (returns 0 on empty). */
35
+ export declare function parseSparqlCount(result: CountBinding[] | undefined | null): number;
36
+ /**
37
+ * Decode a `Literal`-encoded SPARQL binding back to a plain string.
38
+ *
39
+ * Mirrors Flux's local `parseLit` helper. Returns `''` for `undefined`/empty
40
+ * input. Falls through to the raw value if decoding fails (defensive — the
41
+ * binding may already be a plain string for unwrapped properties).
42
+ */
43
+ export declare function parseLit(val: string | undefined | null): string;
44
+ /** Decode a `Literal`-encoded binding to a number. Returns 0 on empty/invalid input. */
45
+ export declare function parseLitNumber(val: string | undefined | null): number;
46
+ /** Decode a `Literal`-encoded binding to a boolean. Returns false on empty input. */
47
+ export declare function parseLitBoolean(val: string | undefined | null): boolean;
@@ -0,0 +1,65 @@
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
+ import { Literal } from "../Literal";
23
+ /** Sum a SPARQL COUNT(?x) result down to a plain number (returns 0 on empty). */
24
+ export function parseSparqlCount(result) {
25
+ if (!result || result.length === 0)
26
+ return 0;
27
+ const raw = result[0].count;
28
+ const n = parseInt(raw, 10);
29
+ return Number.isNaN(n) ? 0 : n;
30
+ }
31
+ /**
32
+ * Decode a `Literal`-encoded SPARQL binding back to a plain string.
33
+ *
34
+ * Mirrors Flux's local `parseLit` helper. Returns `''` for `undefined`/empty
35
+ * input. Falls through to the raw value if decoding fails (defensive — the
36
+ * binding may already be a plain string for unwrapped properties).
37
+ */
38
+ export function parseLit(val) {
39
+ if (val === undefined || val === null || val === '')
40
+ return '';
41
+ try {
42
+ const result = Literal.fromUrl(val).get();
43
+ if (result && typeof result === 'object') {
44
+ return result.data ?? JSON.stringify(result);
45
+ }
46
+ return String(result);
47
+ }
48
+ catch {
49
+ return val;
50
+ }
51
+ }
52
+ /** Decode a `Literal`-encoded binding to a number. Returns 0 on empty/invalid input. */
53
+ export function parseLitNumber(val) {
54
+ if (val === undefined || val === null || val === '')
55
+ return 0;
56
+ const decoded = parseLit(val);
57
+ const n = Number(decoded);
58
+ return Number.isNaN(n) ? 0 : n;
59
+ }
60
+ /** Decode a `Literal`-encoded binding to a boolean. Returns false on empty input. */
61
+ export function parseLitBoolean(val) {
62
+ if (val === undefined || val === null || val === '')
63
+ return false;
64
+ return parseLit(val) === 'true';
65
+ }
@@ -97,10 +97,11 @@ export class WakerSubscriptionManager {
97
97
  const parentQuery = `SELECT ?source WHERE { ?source <ad4m://has_child> <${msgAddr}> . }`;
98
98
  this.logger.info(`[waker] ${sub.id}: resolving parents for ${msgAddr}`);
99
99
  const parentResult = await this.perspectiveClient.querySparql(sub.perspective, parentQuery);
100
- if (Array.isArray(parentResult)) {
101
- for (const link of parentResult) {
102
- if (link && link.source) {
103
- parents.push(link.source);
100
+ const bindings = parentResult?.results?.bindings;
101
+ if (Array.isArray(bindings)) {
102
+ for (const binding of bindings) {
103
+ if (binding?.source?.value) {
104
+ parents.push(binding.source.value);
104
105
  }
105
106
  }
106
107
  }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * SHACL-AF Node Expressions for property transforms.
3
+ *
4
+ * A `NodeExpression` is a JSON-serializable tree that describes how to transform
5
+ * a resolved property value. Unlike JS lambdas, these are portable, inspectable,
6
+ * and can be executed in the Rust model query engine.
7
+ *
8
+ * Each expression is a tagged union that evaluates to a `Value` (JSON-compatible).
9
+ */
10
+ /**
11
+ * Union type representing all supported transform expressions.
12
+ * Each variant maps to a SHACL-AF §6 expression construct.
13
+ */
14
+ export type NodeExpression = {
15
+ type: 'focus';
16
+ } | {
17
+ type: 'literal';
18
+ value: string | number | boolean;
19
+ } | {
20
+ type: 'path';
21
+ predicate: string;
22
+ } | {
23
+ type: 'exists';
24
+ expr: NodeExpression;
25
+ } | {
26
+ type: 'if';
27
+ cond: NodeExpression;
28
+ then: NodeExpression;
29
+ else?: NodeExpression;
30
+ } | {
31
+ type: 'concat';
32
+ args: NodeExpression[];
33
+ } | {
34
+ type: 'coalesce';
35
+ args: NodeExpression[];
36
+ } | {
37
+ type: 'function';
38
+ iri: string;
39
+ args: NodeExpression[];
40
+ };
41
+ /**
42
+ * Type guard to check if a value is a valid NodeExpression.
43
+ */
44
+ export declare function isNodeExpression(v: unknown): v is NodeExpression;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * SHACL-AF Node Expressions for property transforms.
3
+ *
4
+ * A `NodeExpression` is a JSON-serializable tree that describes how to transform
5
+ * a resolved property value. Unlike JS lambdas, these are portable, inspectable,
6
+ * and can be executed in the Rust model query engine.
7
+ *
8
+ * Each expression is a tagged union that evaluates to a `Value` (JSON-compatible).
9
+ */
10
+ /**
11
+ * Type guard to check if a value is a valid NodeExpression.
12
+ */
13
+ export function isNodeExpression(v) {
14
+ if (typeof v !== 'object' || v === null)
15
+ return false;
16
+ const obj = v;
17
+ const type = obj.type;
18
+ switch (type) {
19
+ case 'focus':
20
+ return typeof obj.type === 'string';
21
+ case 'literal':
22
+ return typeof obj.value === 'string' || typeof obj.value === 'number' || typeof obj.value === 'boolean';
23
+ case 'path':
24
+ return typeof obj.predicate === 'string';
25
+ case 'exists':
26
+ return isNodeExpression(obj.expr);
27
+ case 'if':
28
+ return isNodeExpression(obj.cond) && isNodeExpression(obj.then) &&
29
+ (obj.else === undefined || isNodeExpression(obj.else));
30
+ case 'concat':
31
+ return Array.isArray(obj.args) && obj.args.every(isNodeExpression);
32
+ case 'coalesce':
33
+ return Array.isArray(obj.args) && obj.args.every(isNodeExpression);
34
+ case 'function':
35
+ return typeof obj.iri === 'string' && Array.isArray(obj.args) && obj.args.every(isNodeExpression);
36
+ default:
37
+ return false;
38
+ }
39
+ }
@@ -1,4 +1,5 @@
1
1
  import { Link } from "../links/Links";
2
+ import type { NodeExpression } from "./NodeExpression";
2
3
  /**
3
4
  * AD4M Action - represents a link operation
4
5
  */
@@ -76,6 +77,28 @@ export interface SHACLPropertyShape {
76
77
  value: string;
77
78
  label?: string;
78
79
  }>;
80
+ /** AD4M-specific: kind of relation this property describes.
81
+ * Drives direction (forward/reverse), scalar-vs-collection rendering,
82
+ * and default max-count. */
83
+ relationKind?: 'hasMany' | 'hasOne' | 'belongsToOne' | 'belongsToMany';
84
+ /** AD4M-specific: target class name (local-name) for a relation property.
85
+ * Complements `class` (the SHACL node-shape URI) by providing the bare
86
+ * model class name used by the executor to look up the target shape
87
+ * through the perspective's shape cache. */
88
+ targetClassName?: string;
89
+ /** AD4M-specific: post-getter where-clause filter for a relation property. */
90
+ whereFilter?: any;
91
+ /** AD4M-specific: predicate-IRI lookup map for `whereFilter` keys
92
+ * (property name → predicate URI on the target class). */
93
+ wherePredicates?: Record<string, string>;
94
+ /** AD4M-specific: whether conformance/type filtering is enabled for this
95
+ * relation. `false` opts out of DB-level type filtering while keeping
96
+ * hydration via `include`. */
97
+ filter?: boolean;
98
+ /** AD4M-specific: Transform expression (SHACL-AF Node Expression).
99
+ * Applied to resolved property values in the Rust model query engine.
100
+ * Only used for properties with resolveLanguage set. */
101
+ transform?: NodeExpression;
79
102
  }
80
103
  /**
81
104
  * SHACL Node Shape
@@ -1,3 +1,4 @@
1
+ import { isNodeExpression } from "./NodeExpression";
1
2
  /**
2
3
  * Extract namespace from a URI
3
4
  * Examples:
@@ -328,7 +329,7 @@ export class SHACLShape {
328
329
  target: `literal:${prop.writable}`
329
330
  });
330
331
  }
331
- if (prop.resolveLanguage) {
332
+ if (prop.resolveLanguage != null) {
332
333
  links.push({
333
334
  source: propShapeId,
334
335
  predicate: "ad4m://resolveLanguage",
@@ -385,6 +386,48 @@ export class SHACLShape {
385
386
  target: `literal:string:${JSON.stringify(prop.in)}`
386
387
  });
387
388
  }
389
+ if (prop.relationKind) {
390
+ links.push({
391
+ source: propShapeId,
392
+ predicate: "ad4m://relationKind",
393
+ target: `literal:string:${prop.relationKind}`
394
+ });
395
+ }
396
+ if (prop.targetClassName) {
397
+ links.push({
398
+ source: propShapeId,
399
+ predicate: "ad4m://targetClassName",
400
+ target: `literal:string:${prop.targetClassName}`
401
+ });
402
+ }
403
+ if (prop.whereFilter !== undefined && prop.whereFilter !== null) {
404
+ links.push({
405
+ source: propShapeId,
406
+ predicate: "ad4m://whereFilter",
407
+ target: `literal:string:${JSON.stringify(prop.whereFilter)}`
408
+ });
409
+ }
410
+ if (prop.wherePredicates && Object.keys(prop.wherePredicates).length > 0) {
411
+ links.push({
412
+ source: propShapeId,
413
+ predicate: "ad4m://wherePredicates",
414
+ target: `literal:string:${JSON.stringify(prop.wherePredicates)}`
415
+ });
416
+ }
417
+ if (prop.filter !== undefined) {
418
+ links.push({
419
+ source: propShapeId,
420
+ predicate: "ad4m://filter",
421
+ target: `literal:${prop.filter}`
422
+ });
423
+ }
424
+ if (prop.transform && typeof prop.transform === 'object') {
425
+ links.push({
426
+ source: propShapeId,
427
+ predicate: "ad4m://transform",
428
+ target: `literal:string:${JSON.stringify(prop.transform)}`
429
+ });
430
+ }
388
431
  }
389
432
  return links;
390
433
  }
@@ -566,6 +609,60 @@ export class SHACLShape {
566
609
  // Ignore parse errors
567
610
  }
568
611
  }
612
+ const relationKindLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://relationKind");
613
+ if (relationKindLink) {
614
+ const val = relationKindLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
615
+ if (val === 'hasMany' || val === 'hasOne' || val === 'belongsToOne' || val === 'belongsToMany') {
616
+ prop.relationKind = val;
617
+ }
618
+ }
619
+ const targetClassNameLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://targetClassName");
620
+ if (targetClassNameLink) {
621
+ prop.targetClassName = targetClassNameLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
622
+ }
623
+ const whereFilterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://whereFilter");
624
+ if (whereFilterLink) {
625
+ try {
626
+ const jsonStr = whereFilterLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
627
+ prop.whereFilter = JSON.parse(jsonStr);
628
+ }
629
+ catch (e) {
630
+ // Ignore parse errors
631
+ }
632
+ }
633
+ const wherePredicatesLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://wherePredicates");
634
+ if (wherePredicatesLink) {
635
+ try {
636
+ const jsonStr = wherePredicatesLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
637
+ prop.wherePredicates = JSON.parse(jsonStr);
638
+ }
639
+ catch (e) {
640
+ // Ignore parse errors
641
+ }
642
+ }
643
+ const filterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://filter");
644
+ if (filterLink) {
645
+ let val = filterLink.target.replace(/^literal:\/\/|^literal:/, '');
646
+ if (val.startsWith('boolean:'))
647
+ val = val.substring(8);
648
+ prop.filter = val === 'true';
649
+ }
650
+ const transformLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://transform");
651
+ if (transformLink) {
652
+ const jsonStr = transformLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
653
+ try {
654
+ const parsed = JSON.parse(jsonStr);
655
+ if (!isNodeExpression(parsed)) {
656
+ throw new Error(`Invalid transform for property ${propShapeId}: ` +
657
+ `payload is not a valid NodeExpression. Received: ${jsonStr}`);
658
+ }
659
+ prop.transform = parsed;
660
+ }
661
+ catch (e) {
662
+ throw new Error(`Failed to deserialize transform for property ${propShapeId}: ` +
663
+ `${e instanceof Error ? e.message : String(e)}. Payload: ${jsonStr}`);
664
+ }
665
+ }
569
666
  shape.addProperty(prop);
570
667
  }
571
668
  return shape;
@@ -602,6 +699,12 @@ export class SHACLShape {
602
699
  conformance_conditions: p.conformanceConditions,
603
700
  class: p.class,
604
701
  in: p.in,
702
+ relation_kind: p.relationKind,
703
+ target_class_name: p.targetClassName,
704
+ where_filter: p.whereFilter,
705
+ where_predicates: p.wherePredicates,
706
+ filter: p.filter,
707
+ transform: p.transform,
605
708
  })),
606
709
  constructor_actions: this.constructor_actions,
607
710
  destructor_actions: this.destructor_actions,
@@ -615,6 +718,11 @@ export class SHACLShape {
615
718
  ? new SHACLShape(json.node_shape_uri, json.target_class)
616
719
  : new SHACLShape(json.target_class);
617
720
  for (const p of json.properties || []) {
721
+ // Validate transform if present
722
+ if (p.transform && !isNodeExpression(p.transform)) {
723
+ throw new Error(`Invalid transform for property ${p.name}: ` +
724
+ `payload is not a valid NodeExpression. Received: ${JSON.stringify(p.transform)}`);
725
+ }
618
726
  shape.addProperty({
619
727
  path: p.path,
620
728
  name: p.name,
@@ -636,6 +744,12 @@ export class SHACLShape {
636
744
  conformanceConditions: p.conformance_conditions,
637
745
  class: p.class,
638
746
  in: p.in,
747
+ relationKind: p.relation_kind,
748
+ targetClassName: p.target_class_name,
749
+ whereFilter: p.where_filter,
750
+ wherePredicates: p.where_predicates,
751
+ filter: p.filter,
752
+ transform: p.transform,
639
753
  });
640
754
  }
641
755
  if (json.constructor_actions) {
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Builder functions for SHACL-AF Node Expressions.
3
+ *
4
+ * These functions construct JSON-serializable expression trees for property transforms.
5
+ * All builders return frozen objects to prevent accidental mutation.
6
+ */
7
+ import type { NodeExpression } from './NodeExpression';
8
+ /**
9
+ * Identity expression: pass the focus node through unchanged.
10
+ */
11
+ export declare function focus(): NodeExpression;
12
+ /**
13
+ * Literal constant expression.
14
+ */
15
+ export declare function literal(value: string | number | boolean): NodeExpression;
16
+ /**
17
+ * Path expression: navigate to a property on the resolved object.
18
+ * The predicate can be a full IRI (e.g., "file_storage://data_base64")
19
+ * or a simple property name. The Rust evaluator will strip the namespace.
20
+ */
21
+ export declare function path(predicate: string): NodeExpression;
22
+ /**
23
+ * Existence check: returns true if the inner expression is non-null and non-empty.
24
+ */
25
+ export declare function exists(expr: NodeExpression): NodeExpression;
26
+ /**
27
+ * Conditional expression with optional else branch.
28
+ * Returns a chainable builder that supports `.then()` and `.else()`.
29
+ */
30
+ export declare function ifExpr(cond: NodeExpression): {
31
+ then: (thenExpr: NodeExpression) => {
32
+ else: (elseExpr?: NodeExpression) => Readonly<{
33
+ readonly else: NodeExpression;
34
+ readonly type: "if";
35
+ readonly cond: NodeExpression;
36
+ readonly then: NodeExpression;
37
+ }>;
38
+ toExpression: () => Readonly<{
39
+ readonly type: "if";
40
+ readonly cond: NodeExpression;
41
+ readonly then: NodeExpression;
42
+ }>;
43
+ };
44
+ };
45
+ /**
46
+ * String concatenation: joins evaluated arguments as strings.
47
+ * Null/undefined arguments are skipped.
48
+ */
49
+ export declare function concat(...args: NodeExpression[]): NodeExpression;
50
+ /**
51
+ * Coalesce: returns the first non-null evaluated argument.
52
+ */
53
+ export declare function coalesce(...args: NodeExpression[]): NodeExpression;
54
+ /**
55
+ * Function call: invoke a named transform function by IRI.
56
+ * Primarily used for built-in functions like "ad4m://fn/defaultFileDecode".
57
+ */
58
+ export declare function fn(iri: string, args?: NodeExpression[]): NodeExpression;
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Builder functions for SHACL-AF Node Expressions.
3
+ *
4
+ * These functions construct JSON-serializable expression trees for property transforms.
5
+ * All builders return frozen objects to prevent accidental mutation.
6
+ */
7
+ /**
8
+ * Identity expression: pass the focus node through unchanged.
9
+ */
10
+ export function focus() {
11
+ return Object.freeze({ type: 'focus' });
12
+ }
13
+ /**
14
+ * Literal constant expression.
15
+ */
16
+ export function literal(value) {
17
+ return Object.freeze({ type: 'literal', value });
18
+ }
19
+ /**
20
+ * Path expression: navigate to a property on the resolved object.
21
+ * The predicate can be a full IRI (e.g., "file_storage://data_base64")
22
+ * or a simple property name. The Rust evaluator will strip the namespace.
23
+ */
24
+ export function path(predicate) {
25
+ return Object.freeze({ type: 'path', predicate });
26
+ }
27
+ /**
28
+ * Existence check: returns true if the inner expression is non-null and non-empty.
29
+ */
30
+ export function exists(expr) {
31
+ return Object.freeze({ type: 'exists', expr });
32
+ }
33
+ /**
34
+ * Conditional expression with optional else branch.
35
+ * Returns a chainable builder that supports `.then()` and `.else()`.
36
+ */
37
+ export function ifExpr(cond) {
38
+ return {
39
+ then: (thenExpr) => ({
40
+ else: (elseExpr) => {
41
+ return Object.freeze({
42
+ type: 'if',
43
+ cond,
44
+ then: thenExpr,
45
+ ...(elseExpr !== undefined && { else: elseExpr }),
46
+ });
47
+ },
48
+ // Allow chaining without explicit else()
49
+ toExpression: () => Object.freeze({
50
+ type: 'if',
51
+ cond,
52
+ then: thenExpr,
53
+ }),
54
+ }),
55
+ };
56
+ }
57
+ /**
58
+ * String concatenation: joins evaluated arguments as strings.
59
+ * Null/undefined arguments are skipped.
60
+ */
61
+ export function concat(...args) {
62
+ return Object.freeze({ type: 'concat', args });
63
+ }
64
+ /**
65
+ * Coalesce: returns the first non-null evaluated argument.
66
+ */
67
+ export function coalesce(...args) {
68
+ return Object.freeze({ type: 'coalesce', args });
69
+ }
70
+ /**
71
+ * Function call: invoke a named transform function by IRI.
72
+ * Primarily used for built-in functions like "ad4m://fn/defaultFileDecode".
73
+ */
74
+ export function fn(iri, args = []) {
75
+ return Object.freeze({ type: 'function', iri, args });
76
+ }