@coasys/ad4m 0.13.0-postmessage-ws-proxy.0 → 0.13.0-postmessage-ws-proxy.5

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 (52) hide show
  1. package/lib/index.cjs +825 -653
  2. package/lib/index.js +812 -654
  3. package/lib/src/Ad4mClient.d.ts +1 -0
  4. package/lib/src/Ad4mClient.js +1 -1
  5. package/lib/src/ai/AIClient.js +1 -1
  6. package/lib/src/apiClient.d.ts +4 -1
  7. package/lib/src/apiClient.js +6 -1
  8. package/lib/src/index.d.ts +4 -0
  9. package/lib/src/index.js +4 -0
  10. package/lib/src/model/Ad4mModel.d.ts +9 -32
  11. package/lib/src/model/Ad4mModel.js +36 -266
  12. package/lib/src/model/ModelQueryBuilder.d.ts +5 -10
  13. package/lib/src/model/ModelQueryBuilder.js +20 -36
  14. package/lib/src/model/decorators.d.ts +7 -4
  15. package/lib/src/model/shacl-gen.js +120 -47
  16. package/lib/src/model/types.d.ts +140 -4
  17. package/lib/src/perspectives/PerspectiveClient.d.ts +4 -4
  18. package/lib/src/perspectives/PerspectiveClient.js +5 -6
  19. package/lib/src/perspectives/PerspectiveProxy.d.ts +8 -7
  20. package/lib/src/perspectives/PerspectiveProxy.js +10 -9
  21. package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
  22. package/lib/src/perspectives/SparqlBindings.js +65 -0
  23. package/lib/src/shacl/NodeExpression.d.ts +44 -0
  24. package/lib/src/shacl/NodeExpression.js +39 -0
  25. package/lib/src/shacl/SHACLShape.d.ts +23 -0
  26. package/lib/src/shacl/SHACLShape.js +115 -1
  27. package/lib/src/shacl/builders.d.ts +58 -0
  28. package/lib/src/shacl/builders.js +76 -0
  29. package/lib/src/shacl/index.d.ts +36 -0
  30. package/lib/src/shacl/index.js +33 -0
  31. package/package.json +8 -11
  32. package/src/Ad4mClient.ts +2 -2
  33. package/src/ai/AIClient.ts +1 -1
  34. package/src/apiClient.ts +8 -1
  35. package/src/index.ts +4 -0
  36. package/src/model/Ad4mModel.test.ts +33 -74
  37. package/src/model/Ad4mModel.ts +54 -272
  38. package/src/model/ModelQueryBuilder.ts +29 -46
  39. package/src/model/decorators.ts +7 -4
  40. package/src/model/relation-filtering.test.ts +46 -39
  41. package/src/model/shacl-gen.ts +128 -54
  42. package/src/model/shacl-roundtrip.test.ts +197 -0
  43. package/src/model/types-typed-query.test.ts +360 -0
  44. package/src/model/types.ts +196 -4
  45. package/src/perspectives/PerspectiveClient.ts +6 -8
  46. package/src/perspectives/PerspectiveProxy.ts +13 -13
  47. package/src/perspectives/SparqlBindings.ts +79 -0
  48. package/src/shacl/NodeExpression.ts +54 -0
  49. package/src/shacl/SHACLShape.test.ts +172 -0
  50. package/src/shacl/SHACLShape.ts +173 -1
  51. package/src/shacl/builders.ts +86 -0
  52. package/src/shacl/index.ts +72 -0
@@ -318,16 +318,19 @@ export declare class PerspectiveProxy {
318
318
  * @param query - SPARQL query string
319
319
  * @returns Query results as parsed JSON
320
320
  */
321
- querySparql(query: string): Promise<any>;
321
+ querySparql<T = any>(query: string): Promise<T>;
322
322
  /**
323
323
  * Execute a model query — the executor-side replacement for SPARQL query building + JS hydration.
324
324
  *
325
+ * The executor resolves the model's shape from the perspective's SHACL
326
+ * triples (written by `addSdna`). Callers no longer ship shape
327
+ * metadata with the query; the perspective is the source of truth.
328
+ *
325
329
  * @param className - The model class name (e.g. "Recipe")
326
330
  * @param queryJson - Structured query as JSON string
327
- * @param shapeJson - Optional shape metadata JSON from the model class
328
331
  * @returns Object with `instances` array and `totalCount`
329
332
  */
330
- modelQuery(className: string, queryJson: string, shapeJson?: string): Promise<{
333
+ modelQuery(className: string, queryJson: string): Promise<{
331
334
  instances: any[];
332
335
  totalCount: number;
333
336
  }>;
@@ -340,11 +343,10 @@ export declare class PerspectiveProxy {
340
343
  *
341
344
  * @param className - The model class name (e.g. "Message")
342
345
  * @param instanceIds - Array of instance base expression URIs
343
- * @param shapeJson - Shape metadata JSON from the model class
344
346
  * @param propertyNames - Optional subset of property names to evaluate
345
347
  * @returns Map of instance ID → evaluated property values
346
348
  */
347
- evaluateGetters(className: string, instanceIds: string[], shapeJson: string, propertyNames?: string[]): Promise<Record<string, Record<string, any>>>;
349
+ evaluateGetters(className: string, instanceIds: string[], propertyNames?: string[]): Promise<Record<string, Record<string, any>>>;
348
350
  /**
349
351
  * Subscribe to model query changes. Builds trigger SPARQL from the model shape
350
352
  * internally in Rust, registers a subscription, runs the initial query, and
@@ -355,10 +357,9 @@ export declare class PerspectiveProxy {
355
357
  *
356
358
  * @param className - The model class name
357
359
  * @param queryJson - JSON-serialized query parameters (same as modelQuery)
358
- * @param shapeJson - Optional shape metadata JSON from the model class
359
360
  * @returns Object with `subscriptionId` and initial `result`
360
361
  */
361
- modelSubscribe(className: string, queryJson: string, shapeJson?: string): Promise<{
362
+ modelSubscribe(className: string, queryJson: string): Promise<{
362
363
  subscriptionId: string;
363
364
  result: any;
364
365
  }>;
@@ -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.
@@ -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
+ }
@@ -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
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * SHACL-AF Transform DSL — public API
3
+ *
4
+ * Re-exports builder functions and provides common built-in transforms.
5
+ */
6
+ import { focus, literal, path, exists, ifExpr, concat, coalesce, fn } from './builders';
7
+ export type { NodeExpression } from './NodeExpression';
8
+ export { isNodeExpression } from './NodeExpression';
9
+ export { focus, literal, path, exists, ifExpr, concat, coalesce, fn, };
10
+ /**
11
+ * Built-in transform: FileData → data: URI
12
+ *
13
+ * Converts a file stored via FILE_STORAGE_LANGUAGE into a data: URL.
14
+ * If the object has a `data_base64` field, returns:
15
+ * `data:{file_type};base64,{data_base64}`
16
+ * Otherwise passes through the input unchanged.
17
+ *
18
+ * This is the Rust equivalent of the JS `defaultFileDecode` function.
19
+ *
20
+ * Usage:
21
+ * ```typescript
22
+ * @Property({
23
+ * through: 'we://image',
24
+ * resolveLanguage: FILE_STORAGE_LANGUAGE,
25
+ * transform: fileToDataUri,
26
+ * })
27
+ * avatar?: string;
28
+ * ```
29
+ */
30
+ export declare const fileToDataUri: Readonly<{
31
+ readonly else: import("./NodeExpression").NodeExpression;
32
+ readonly type: "if";
33
+ readonly cond: import("./NodeExpression").NodeExpression;
34
+ readonly then: import("./NodeExpression").NodeExpression;
35
+ }>;
36
+ export { SHACLShape, SHACLPropertyShape, AD4MAction, ConformanceCondition, } from './SHACLShape';