@coasys/ad4m 0.12.0-rc1-dev.4 → 0.12.0-rc1-dev.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.
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Shared SurrealQL compilation utilities.
3
+ *
4
+ * These functions are used by both the runtime query builder (`Ad4mModel`) and
5
+ * the compile-time SHACL generator (`decorators.ts`).
6
+ */
7
+
8
+ import type { WhereCondition, Where, ModelMetadata } from "./Ad4mModel";
9
+ import { escapeSurrealString } from "../utils";
10
+
11
+ /**
12
+ * Format a JavaScript value for embedding in a SurrealQL expression.
13
+ *
14
+ * - Strings are single-quoted with backslash / quote / newline escaping
15
+ * - Numbers and booleans are passed through as-is
16
+ * - Arrays are recursed
17
+ */
18
+ export function formatSurrealValue(value: any): string {
19
+ if (typeof value === 'string') {
20
+ // Escape backslashes first, then single quotes and other special characters
21
+ const escaped = value
22
+ .replace(/\\/g, '\\\\') // Backslash -> \\
23
+ .replace(/'/g, "\\'") // Single quote -> \'
24
+ .replace(/"/g, '\\"') // Double quote -> \"
25
+ .replace(/\n/g, '\\n') // Newline -> \n
26
+ .replace(/\r/g, '\\r') // Carriage return -> \r
27
+ .replace(/\t/g, '\\t'); // Tab -> \t
28
+ return `'${escaped}'`;
29
+ } else if (typeof value === 'number' || typeof value === 'boolean') {
30
+ return String(value);
31
+ } else if (Array.isArray(value)) {
32
+ return `[${value.map(v => formatSurrealValue(v)).join(', ')}]`;
33
+ } else {
34
+ return String(value);
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Compile a single Where condition for a property into a SurrealQL
40
+ * graph-traversal sub-expression.
41
+ *
42
+ * Operates on the **target node** — generates `count(->link[WHERE ...]) > 0`
43
+ * style checks that can be used inside a `[WHERE ...]` filter on nodes.
44
+ *
45
+ * @param predicate - The predicate URI for the property
46
+ * @param condition - The Where condition value
47
+ * @param opts - Optional settings (e.g. `resolveLanguage`)
48
+ * @returns A single SurrealQL condition string
49
+ */
50
+ export function buildWhereCondition(
51
+ predicate: string,
52
+ condition: WhereCondition,
53
+ opts?: { resolveLanguage?: string },
54
+ ): string {
55
+ const escapedPredicate = escapeSurrealString(predicate);
56
+ const targetField = opts?.resolveLanguage === 'literal'
57
+ ? 'fn::parse_literal(out.uri)'
58
+ : 'out.uri';
59
+
60
+ if (Array.isArray(condition)) {
61
+ // Array values → IN clause
62
+ const formattedValues = (condition as any[]).map(v => formatSurrealValue(v)).join(', ');
63
+ return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) > 0`;
64
+ } else if (typeof condition === 'object' && condition !== null) {
65
+ // Operator object
66
+ const ops = condition as any;
67
+ const parts: string[] = [];
68
+
69
+ if (ops.not !== undefined) {
70
+ if (Array.isArray(ops.not)) {
71
+ const formattedValues = ops.not.map((v: any) => formatSurrealValue(v)).join(', ');
72
+ parts.push(
73
+ `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) = 0`,
74
+ );
75
+ } else {
76
+ parts.push(
77
+ `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`,
78
+ );
79
+ }
80
+ }
81
+
82
+ // Comparison operators — ensure property exists (actual comparison
83
+ // may be post-filtered in JS at runtime, but the SurrealQL condition
84
+ // is valid for compile-time getter generation too).
85
+ const hasComparisonOps =
86
+ ops.gt !== undefined || ops.gte !== undefined ||
87
+ ops.lt !== undefined || ops.lte !== undefined ||
88
+ ops.between !== undefined || ops.contains !== undefined;
89
+ if (hasComparisonOps) {
90
+ parts.push(
91
+ `count(->link[WHERE predicate = '${escapedPredicate}']) > 0`,
92
+ );
93
+ }
94
+
95
+ return parts.join(' AND ');
96
+ } else {
97
+ // Simple equality
98
+ return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`;
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Compile a full `Where` clause to an array of SurrealQL condition strings.
104
+ *
105
+ * When `metadata` is provided, property names are resolved to predicates
106
+ * using the model's property metadata. When `metadata` is `null`, property
107
+ * names are treated as raw predicate URIs.
108
+ *
109
+ * Only handles **regular properties** — special fields (`id`, `author`,
110
+ * `timestamp`) and relation fields are skipped (they are only relevant at
111
+ * runtime query time, not for compile-time getter generation).
112
+ */
113
+ export function compileWhereClause(
114
+ where: Where,
115
+ metadata: ModelMetadata | null,
116
+ ): string[] {
117
+ const conditions: string[] = [];
118
+
119
+ for (const [propertyName, condition] of Object.entries(where)) {
120
+ // Skip special fields that don't apply at compile time
121
+ if (['id', 'author', 'timestamp'].includes(propertyName)) continue;
122
+
123
+ let predicate: string;
124
+ let resolveLanguage: string | undefined;
125
+
126
+ if (metadata) {
127
+ const propMeta = metadata.properties[propertyName];
128
+ if (propMeta) {
129
+ predicate = propMeta.predicate;
130
+ resolveLanguage = propMeta.resolveLanguage;
131
+ } else {
132
+ // Property not found in metadata — treat name as raw predicate URI
133
+ predicate = propertyName;
134
+ }
135
+ } else {
136
+ // No metadata — treat name as raw predicate URI
137
+ predicate = propertyName;
138
+ }
139
+
140
+ const cond = buildWhereCondition(predicate, condition, { resolveLanguage });
141
+ if (cond) {
142
+ conditions.push(cond);
143
+ }
144
+ }
145
+
146
+ return conditions;
147
+ }
@@ -95,6 +95,19 @@ export interface AD4MAction {
95
95
  local?: boolean;
96
96
  }
97
97
 
98
+ /**
99
+ * A single structured conformance condition for relation filtering.
100
+ * DB-agnostic representation that can be translated to any query language.
101
+ */
102
+ export interface ConformanceCondition {
103
+ /** Type of check: 'flag' (predicate + value) or 'required' (predicate exists) */
104
+ type: 'flag' | 'required';
105
+ /** The predicate URI to check on the target node */
106
+ predicate: string;
107
+ /** For 'flag' conditions: the expected value */
108
+ value?: string;
109
+ }
110
+
98
111
  /**
99
112
  * SHACL Property Shape
100
113
  * Represents constraints on a single property path
@@ -147,6 +160,20 @@ export interface SHACLPropertyShape {
147
160
 
148
161
  /** AD4M-specific: Remover action for collection properties */
149
162
  remover?: AD4MAction[];
163
+
164
+ /** AD4M-specific: Pre-computed SurrealQL getter expression for reading this relation/property.
165
+ * For relations with a target model, this encodes conformance filtering
166
+ * so that Rust/MCP can execute the exact same query as the JS runtime. */
167
+ getter?: string;
168
+
169
+ /** AD4M-specific: Structured conformance conditions (DB-agnostic).
170
+ * Each condition describes a check on the target node (flag match or required property). */
171
+ conformanceConditions?: ConformanceCondition[];
172
+
173
+ /** sh:class — the target SHACL node shape URI that linked nodes must conform to.
174
+ * Set automatically when a relation has a `target` model. Enables typed construction
175
+ * on the Rust/MCP side by referencing the full target shape. */
176
+ class?: string;
150
177
  }
151
178
 
152
179
  /**
@@ -494,6 +521,30 @@ export class SHACLShape {
494
521
  target: `literal://string:${JSON.stringify(prop.remover)}`
495
522
  });
496
523
  }
524
+
525
+ if (prop.getter) {
526
+ links.push({
527
+ source: propShapeId,
528
+ predicate: "ad4m://getter",
529
+ target: `literal://string:${prop.getter}`
530
+ });
531
+ }
532
+
533
+ if (prop.conformanceConditions && prop.conformanceConditions.length > 0) {
534
+ links.push({
535
+ source: propShapeId,
536
+ predicate: "ad4m://conformanceConditions",
537
+ target: `literal://string:${JSON.stringify(prop.conformanceConditions)}`
538
+ });
539
+ }
540
+
541
+ if (prop.class) {
542
+ links.push({
543
+ source: propShapeId,
544
+ predicate: "sh://class",
545
+ target: prop.class
546
+ });
547
+ }
497
548
  }
498
549
 
499
550
  return links;
@@ -698,6 +749,32 @@ export class SHACLShape {
698
749
  }
699
750
  }
700
751
 
752
+ const getterLink = links.find(l =>
753
+ l.source === propShapeId && l.predicate === "ad4m://getter"
754
+ );
755
+ if (getterLink) {
756
+ prop.getter = getterLink.target.replace('literal://string:', '');
757
+ }
758
+
759
+ const conditionsLink = links.find(l =>
760
+ l.source === propShapeId && l.predicate === "ad4m://conformanceConditions"
761
+ );
762
+ if (conditionsLink) {
763
+ try {
764
+ const jsonStr = conditionsLink.target.replace('literal://string:', '');
765
+ prop.conformanceConditions = JSON.parse(jsonStr);
766
+ } catch (e) {
767
+ // Ignore parse errors
768
+ }
769
+ }
770
+
771
+ const classLink = links.find(l =>
772
+ l.source === propShapeId && l.predicate === "sh://class"
773
+ );
774
+ if (classLink) {
775
+ prop.class = classLink.target;
776
+ }
777
+
701
778
  shape.addProperty(prop);
702
779
  }
703
780
 
@@ -732,6 +809,9 @@ export class SHACLShape {
732
809
  setter: p.setter,
733
810
  adder: p.adder,
734
811
  remover: p.remover,
812
+ getter: p.getter,
813
+ conformance_conditions: p.conformanceConditions,
814
+ class: p.class,
735
815
  })),
736
816
  constructor_actions: this.constructor_actions,
737
817
  destructor_actions: this.destructor_actions,
@@ -764,6 +844,9 @@ export class SHACLShape {
764
844
  setter: p.setter,
765
845
  adder: p.adder,
766
846
  remover: p.remover,
847
+ getter: p.getter,
848
+ conformanceConditions: p.conformance_conditions,
849
+ class: p.class,
767
850
  });
768
851
  }
769
852