@coasys/ad4m 0.12.0-rc1-dev.4 → 0.12.0-rc2

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 (166) hide show
  1. package/lib/index.cjs +5052 -4446
  2. package/lib/index.js +5019 -4442
  3. package/lib/src/agent/AgentClient.d.ts +4 -0
  4. package/lib/src/agent/AgentClient.js +34 -0
  5. package/lib/src/index.d.ts +2 -3
  6. package/lib/src/index.js +2 -3
  7. package/lib/src/model/Ad4mModel.d.ts +8 -782
  8. package/lib/src/model/Ad4mModel.js +160 -2354
  9. package/lib/src/model/ModelQueryBuilder.d.ts +370 -0
  10. package/lib/src/model/ModelQueryBuilder.js +556 -0
  11. package/lib/src/model/decorators.d.ts +71 -23
  12. package/lib/src/model/decorators.js +133 -384
  13. package/lib/src/model/hydration.d.ts +102 -0
  14. package/lib/src/model/hydration.js +709 -0
  15. package/lib/src/model/index.d.ts +20 -0
  16. package/lib/src/model/index.js +20 -0
  17. package/lib/src/model/{schema/fromJSONSchema.d.ts → json-schema.d.ts} +45 -12
  18. package/lib/src/model/json-schema.js +326 -0
  19. package/lib/src/model/prolog-facts.d.ts +37 -0
  20. package/lib/src/model/{prolog/generatePrologFacts.js → prolog-facts.js} +47 -52
  21. package/lib/src/model/query-common.d.ts +14 -0
  22. package/lib/src/model/query-common.js +36 -0
  23. package/lib/src/model/query-prolog.d.ts +15 -0
  24. package/lib/src/model/query-prolog.js +140 -0
  25. package/lib/src/model/query-surreal.d.ts +44 -0
  26. package/lib/src/model/query-surreal.js +249 -0
  27. package/lib/src/model/relation-filtering.test.js +838 -0
  28. package/lib/src/model/sdna.d.ts +14 -0
  29. package/lib/src/model/sdna.js +141 -0
  30. package/lib/src/model/shacl-gen.d.ts +31 -0
  31. package/lib/src/model/shacl-gen.js +246 -0
  32. package/lib/src/model/surreal-utils.d.ts +42 -0
  33. package/lib/src/model/surreal-utils.js +128 -0
  34. package/lib/src/model/types.d.ts +75 -96
  35. package/lib/src/model/types.js +4 -4
  36. package/lib/src/model/util.d.ts +4 -5
  37. package/lib/src/model/util.js +12 -32
  38. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
  39. package/lib/src/perspectives/PerspectiveProxy.d.ts +1 -1
  40. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +79 -0
  41. package/lib/src/perspectives/WakerSubscriptionManager.js +196 -0
  42. package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
  43. package/lib/src/runtime/RuntimeResolver.js +73 -0
  44. package/lib/src/schema.gql +14 -0
  45. package/lib/src/shacl/SHACLShape.d.ts +23 -0
  46. package/lib/src/shacl/SHACLShape.js +45 -0
  47. package/lib/src/typeDefs.js +14 -0
  48. package/package.json +13 -8
  49. package/src/agent/AgentClient.ts +45 -0
  50. package/src/index.ts +2 -3
  51. package/src/model/Ad4mModel.ts +1089 -3686
  52. package/src/model/ModelQueryBuilder.ts +617 -0
  53. package/src/model/Subject.ts +1 -1
  54. package/src/model/decorators.ts +218 -453
  55. package/src/model/hydration.ts +796 -0
  56. package/src/model/index.ts +21 -0
  57. package/src/model/json-schema.ts +424 -0
  58. package/src/model/prolog-facts.ts +145 -0
  59. package/src/model/query-common.ts +48 -0
  60. package/src/model/query-prolog.ts +148 -0
  61. package/src/model/query-surreal.ts +280 -0
  62. package/src/model/relation-filtering.test.ts +803 -0
  63. package/src/model/sdna.ts +170 -0
  64. package/src/model/shacl-gen.ts +292 -0
  65. package/src/model/surreal-utils.ts +147 -0
  66. package/src/model/types.ts +182 -0
  67. package/src/model/util.ts +13 -36
  68. package/src/perspectives/PerspectiveClient.ts +1 -1
  69. package/src/perspectives/PerspectiveProxy.ts +1 -1
  70. package/src/perspectives/WakerSubscriptionManager.ts +292 -0
  71. package/src/runtime/RuntimeResolver.ts +53 -0
  72. package/src/shacl/SHACLShape.ts +83 -0
  73. package/lib/src/Ad4mClient.test.js +0 -1204
  74. package/lib/src/Literal.test.d.ts +0 -1
  75. package/lib/src/Literal.test.js +0 -41
  76. package/lib/src/model/mutation.d.ts +0 -81
  77. package/lib/src/model/mutation.js +0 -317
  78. package/lib/src/model/parentUtils.d.ts +0 -32
  79. package/lib/src/model/parentUtils.js +0 -64
  80. package/lib/src/model/prolog/generatePrologFacts.d.ts +0 -36
  81. package/lib/src/model/prolog/index.d.ts +0 -1
  82. package/lib/src/model/prolog/index.js +0 -1
  83. package/lib/src/model/query/ModelQueryBuilder.d.ts +0 -82
  84. package/lib/src/model/query/ModelQueryBuilder.js +0 -115
  85. package/lib/src/model/query/QueryBuilder.d.ts +0 -101
  86. package/lib/src/model/query/QueryBuilder.js +0 -193
  87. package/lib/src/model/query/SurrealQueryBuilder.d.ts +0 -48
  88. package/lib/src/model/query/SurrealQueryBuilder.js +0 -371
  89. package/lib/src/model/query/fetchInstance.d.ts +0 -24
  90. package/lib/src/model/query/fetchInstance.js +0 -144
  91. package/lib/src/model/query/hydration.d.ts +0 -54
  92. package/lib/src/model/query/hydration.js +0 -214
  93. package/lib/src/model/query/operations.d.ts +0 -59
  94. package/lib/src/model/query/operations.js +0 -384
  95. package/lib/src/model/query/snapshot.d.ts +0 -59
  96. package/lib/src/model/query/snapshot.js +0 -106
  97. package/lib/src/model/query/surrealCompiler.d.ts +0 -42
  98. package/lib/src/model/query/surrealCompiler.js +0 -304
  99. package/lib/src/model/schema/fromJSONSchema.js +0 -264
  100. package/lib/src/model/schema/metadata.d.ts +0 -15
  101. package/lib/src/model/schema/metadata.js +0 -112
  102. package/lib/src/model/subscription.d.ts +0 -47
  103. package/lib/src/model/subscription.js +0 -231
  104. package/lib/src/model/transaction.d.ts +0 -27
  105. package/lib/src/model/transaction.js +0 -32
  106. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  107. package/lib/src/shims/type-graphql.d.ts +0 -32
  108. package/lib/src/src/Ad4mClient.d.ts +0 -28
  109. package/lib/src/src/Address.d.ts +0 -1
  110. package/lib/src/src/DID.d.ts +0 -1
  111. package/lib/src/src/Exception.d.ts +0 -7
  112. package/lib/src/src/Literal.d.ts +0 -7
  113. package/lib/src/src/PubSub.d.ts +0 -17
  114. package/lib/src/src/SmartLiteral.d.ts +0 -12
  115. package/lib/src/src/agent/Agent.d.ts +0 -110
  116. package/lib/src/src/agent/AgentClient.d.ts +0 -62
  117. package/lib/src/src/agent/AgentResolver.d.ts +0 -30
  118. package/lib/src/src/agent/AgentStatus.d.ts +0 -8
  119. package/lib/src/src/ai/AIClient.d.ts +0 -32
  120. package/lib/src/src/ai/AIResolver.d.ts +0 -75
  121. package/lib/src/src/ai/Tasks.d.ts +0 -37
  122. package/lib/src/src/buildSchema.d.ts +0 -1
  123. package/lib/src/src/expression/Expression.d.ts +0 -28
  124. package/lib/src/src/expression/ExpressionClient.d.ts +0 -13
  125. package/lib/src/src/expression/ExpressionRef.d.ts +0 -9
  126. package/lib/src/src/expression/ExpressionResolver.d.ts +0 -10
  127. package/lib/src/src/index.d.ts +0 -35
  128. package/lib/src/src/jestSetup.d.ts +0 -1
  129. package/lib/src/src/language/Icon.d.ts +0 -4
  130. package/lib/src/src/language/Language.d.ts +0 -206
  131. package/lib/src/src/language/LanguageClient.d.ts +0 -17
  132. package/lib/src/src/language/LanguageContext.d.ts +0 -37
  133. package/lib/src/src/language/LanguageHandle.d.ts +0 -9
  134. package/lib/src/src/language/LanguageMeta.d.ts +0 -35
  135. package/lib/src/src/language/LanguageRef.d.ts +0 -6
  136. package/lib/src/src/language/LanguageResolver.d.ts +0 -19
  137. package/lib/src/src/links/Links.d.ts +0 -39
  138. package/lib/src/src/links/Links.test.d.ts +0 -1
  139. package/lib/src/src/model/Ad4mModel.d.ts +0 -1438
  140. package/lib/src/src/model/Ad4mModel.test.d.ts +0 -1
  141. package/lib/src/src/model/Subject.d.ts +0 -25
  142. package/lib/src/src/model/decorators.d.ts +0 -545
  143. package/lib/src/src/model/util.d.ts +0 -12
  144. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +0 -10
  145. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +0 -25
  146. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +0 -19
  147. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +0 -1
  148. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +0 -24
  149. package/lib/src/src/perspectives/LinkQuery.d.ts +0 -11
  150. package/lib/src/src/perspectives/Perspective.d.ts +0 -38
  151. package/lib/src/src/perspectives/Perspective.test.d.ts +0 -1
  152. package/lib/src/src/perspectives/PerspectiveClient.d.ts +0 -97
  153. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +0 -9
  154. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +0 -18
  155. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +0 -865
  156. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +0 -57
  157. package/lib/src/src/runtime/RuntimeClient.d.ts +0 -56
  158. package/lib/src/src/runtime/RuntimeResolver.d.ts +0 -132
  159. package/lib/src/src/shacl/SHACLFlow.d.ts +0 -171
  160. package/lib/src/src/shacl/SHACLFlow.test.d.ts +0 -1
  161. package/lib/src/src/shacl/SHACLShape.d.ts +0 -117
  162. package/lib/src/src/shacl/SHACLShape.test.d.ts +0 -1
  163. package/lib/src/src/typeDefs.d.ts +0 -1
  164. package/lib/src/src/unwrapApolloResult.d.ts +0 -2
  165. package/lib/src/src/utils.d.ts +0 -25
  166. /package/lib/src/{Ad4mClient.test.d.ts → model/relation-filtering.test.d.ts} +0 -0
@@ -0,0 +1,170 @@
1
+ /**
2
+ * SDNA (Social DNA) Prolog code generation.
3
+ *
4
+ * Builds subject-class Prolog facts from a model's property and relation
5
+ * metadata. The heavy lifting used to live inside the `@Model` decorator
6
+ * closure — it is extracted here so decorators.ts stays focused on
7
+ * decorator registration logic.
8
+ */
9
+ import { makeRandomId, propertyNameToSetterName, stringifyObjectLiteral } from "./util";
10
+ import type { PropertyMetadataEntry, RelationMetadataEntry } from "./decorators";
11
+
12
+ /**
13
+ * Build SDNA (Social DNA) Prolog code for a model class.
14
+ *
15
+ * @param subjectName - The model's registered name (from `@Model({ name })`)
16
+ * @param obj - `target.prototype` — used to inspect prototype methods
17
+ * (e.g. setter stubs, `subjectConstructor`, `isSubjectInstance`)
18
+ * @param properties - Merged property metadata (from `getPropertiesMetadata`)
19
+ * @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)
20
+ */
21
+ export function buildSDNA(
22
+ subjectName: string,
23
+ obj: any,
24
+ properties: Record<string, PropertyMetadataEntry>,
25
+ allRelationsMeta: Record<string, RelationMetadataEntry>,
26
+ ): { sdna: string; name: string } {
27
+ let sdna = "";
28
+ let uuid = makeRandomId(8);
29
+
30
+ sdna += `subject_class("${subjectName}", ${uuid}).\n`;
31
+
32
+ let classRemoverActions: any[] = [];
33
+
34
+ let constructorActions: any[] = [];
35
+ if (obj.subjectConstructor && obj.subjectConstructor.length) {
36
+ constructorActions = constructorActions.concat(obj.subjectConstructor);
37
+ }
38
+
39
+ let instanceConditions: string[] = [];
40
+ if (obj.isSubjectInstance && obj.isSubjectInstance.length) {
41
+ instanceConditions = instanceConditions.concat(obj.isSubjectInstance);
42
+ }
43
+
44
+ let propertiesCode: string[] = [];
45
+ for (let property in properties) {
46
+ let propertyCode = `property(${uuid}, "${property}").\n`;
47
+
48
+ let { through, initial, required, resolveLanguage, writable, flag, prologGetter, prologSetter, local } = properties[property];
49
+
50
+ if (resolveLanguage) {
51
+ propertyCode += `property_resolve(${uuid}, "${property}").\n`;
52
+ propertyCode += `property_resolve_language(${uuid}, "${property}", "${resolveLanguage}").\n`;
53
+ }
54
+
55
+ if (prologGetter) {
56
+ propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${prologGetter}.\n`;
57
+ } else if (through) {
58
+ propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- triple(Base, "${through}", Value).\n`;
59
+
60
+ if (required) {
61
+ if (flag) {
62
+ instanceConditions.push(`triple(Base, "${through}", "${initial}")`);
63
+ } else {
64
+ instanceConditions.push(`triple(Base, "${through}", _)`);
65
+ }
66
+ }
67
+ }
68
+
69
+ if (prologSetter) {
70
+ propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${prologSetter}.\n`;
71
+ } else if (writable && through) {
72
+ let setter = obj[propertyNameToSetterName(property)];
73
+ if (typeof setter === "function") {
74
+ let action = [{
75
+ action: "setSingleTarget",
76
+ source: "this",
77
+ predicate: through,
78
+ target: "value",
79
+ ...(local && { local: true })
80
+ }];
81
+ propertyCode += `property_setter(${uuid}, "${property}", '${stringifyObjectLiteral(action)}').\n`;
82
+ }
83
+ }
84
+
85
+ propertiesCode.push(propertyCode);
86
+
87
+ // Auto-derive effectiveInitial for required, writable, non-flag properties
88
+ // so constructor/destructor always handle the property link.
89
+ // Optional properties (required: false) are excluded — they should
90
+ // remain unset (undefined) until explicitly assigned.
91
+ const effectiveInitial = initial
92
+ ?? (required && writable && !flag && through ? "literal://string:" : undefined);
93
+
94
+ if (effectiveInitial) {
95
+ constructorActions.push({
96
+ action: "addLink",
97
+ source: "this",
98
+ predicate: through,
99
+ target: effectiveInitial,
100
+ });
101
+
102
+ classRemoverActions.push({
103
+ action: "removeLink",
104
+ source: "this",
105
+ predicate: through,
106
+ target: "*",
107
+ });
108
+ }
109
+ }
110
+
111
+ let relationsCode: string[] = [];
112
+ const relations = Object.fromEntries(
113
+ Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany')
114
+ );
115
+ for (let relation in relations) {
116
+ let relationCode = `collection(${uuid}, "${relation}").\n`;
117
+
118
+ let { predicate: through, local } = relations[relation];
119
+
120
+ if (through) {
121
+ relationCode += `collection_getter(${uuid}, Base, "${relation}", List) :- findall(C, triple(Base, "${through}", C), List).\n`;
122
+
123
+ let relationAdderAction = [{
124
+ action: "addLink",
125
+ source: "this",
126
+ predicate: through,
127
+ target: "value",
128
+ ...(local && { local: true })
129
+ }];
130
+
131
+ let relationRemoverAction = [{
132
+ action: "removeLink",
133
+ source: "this",
134
+ predicate: through,
135
+ target: "value",
136
+ }];
137
+
138
+ let relationSetterAction = [{
139
+ action: "collectionSetter",
140
+ source: "this",
141
+ predicate: through,
142
+ target: "value",
143
+ ...(local && { local: true })
144
+ }];
145
+ relationCode += `collection_adder(${uuid}, "${relation}", '${stringifyObjectLiteral(relationAdderAction)}').\n`;
146
+ relationCode += `collection_remover(${uuid}, "${relation}", '${stringifyObjectLiteral(relationRemoverAction)}').\n`;
147
+ relationCode += `collection_setter(${uuid}, "${relation}", '${stringifyObjectLiteral(relationSetterAction)}').\n`;
148
+ }
149
+
150
+ relationsCode.push(relationCode);
151
+ }
152
+
153
+ let subjectContructorJSONString = stringifyObjectLiteral(constructorActions);
154
+ sdna += `constructor(${uuid}, '${subjectContructorJSONString}').\n`;
155
+ if (instanceConditions.length > 0) {
156
+ let instanceConditionProlog = instanceConditions.join(", ");
157
+ sdna += `instance(${uuid}, Base) :- ${instanceConditionProlog}.\n`;
158
+ sdna += "\n";
159
+ }
160
+ sdna += `destructor(${uuid}, '${stringifyObjectLiteral(classRemoverActions)}').\n`;
161
+ sdna += "\n";
162
+ sdna += propertiesCode.join("\n");
163
+ sdna += "\n";
164
+ sdna += relationsCode.join("\n");
165
+
166
+ return {
167
+ sdna,
168
+ name: subjectName
169
+ };
170
+ }
@@ -0,0 +1,292 @@
1
+ /**
2
+ * SHACL shape generation for AD4M model classes.
3
+ *
4
+ * Builds a W3C SHACL `SHACLShape` (with AD4M-specific action extensions)
5
+ * from a model's property and relation metadata. The heavy lifting used
6
+ * to live inside the `@Model` decorator closure — it is extracted here so
7
+ * decorators.ts stays focused on decorator registration logic.
8
+ */
9
+ import { SHACLShape } from "../shacl/SHACLShape";
10
+ import type { SHACLPropertyShape, ConformanceCondition } from "../shacl/SHACLShape";
11
+ import { escapeSurrealString } from "../utils";
12
+ import { compileWhereClause } from "./surreal-utils";
13
+ import { propertyNameToSetterName } from "./util";
14
+ import type { PropertyMetadataEntry, RelationMetadataEntry, Ad4mModelLike } from "./decorators";
15
+
16
+ /** Signature for the conformance-filter builder injected by the caller. */
17
+ export type ConformanceFilterFn = (
18
+ relationPredicate: string,
19
+ targetClass: Ad4mModelLike,
20
+ ) => { getter: string; conformanceConditions: ConformanceCondition[] } | undefined;
21
+
22
+ /**
23
+ * Build a SHACL shape for a model class.
24
+ *
25
+ * @param subjectName - The model's registered name (from `@Model({ name })`)
26
+ * @param target - The class constructor (used for prototype access,
27
+ * inheritance chain, and relation target resolution)
28
+ * @param properties - Merged property metadata (from `getPropertiesMetadata`)
29
+ * @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)
30
+ * @param conformanceFilterFn - Injected conformance-filter builder
31
+ * (avoids circular dependency back into decorators.ts)
32
+ */
33
+ export function buildSHACL(
34
+ subjectName: string,
35
+ target: any,
36
+ properties: Record<string, PropertyMetadataEntry>,
37
+ allRelationsMeta: Record<string, RelationMetadataEntry>,
38
+ conformanceFilterFn: ConformanceFilterFn,
39
+ ): { shape: SHACLShape; name: string } {
40
+ const obj = target.prototype;
41
+
42
+ // ── Determine namespace from first property or relation ─────────────
43
+ let namespace = "ad4m://";
44
+ const relations = Object.fromEntries(
45
+ Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany')
46
+ );
47
+
48
+ // Try properties first
49
+ if (Object.keys(properties).length > 0) {
50
+ const firstProp = properties[Object.keys(properties)[0]];
51
+ if (firstProp.through) {
52
+ const match = firstProp.through.match(/^([^:]+:\/\/)/);
53
+ if (match) {
54
+ namespace = match[1];
55
+ }
56
+ }
57
+ }
58
+ // Fall back to relations if no properties
59
+ else if (Object.keys(relations).length > 0) {
60
+ const firstRel = relations[Object.keys(relations)[0]];
61
+ if (firstRel.predicate) {
62
+ const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
63
+ if (match) {
64
+ namespace = match[1];
65
+ }
66
+ }
67
+ }
68
+
69
+ // ── Create SHACL shape ──────────────────────────────────────────────
70
+ const shapeUri = `${namespace}${subjectName}Shape`;
71
+ const targetClass = `${namespace}${subjectName}`;
72
+ const shape = new SHACLShape(shapeUri, targetClass);
73
+
74
+ // Detect @Model inheritance — if the parent class also has
75
+ // generateSHACL it is itself a @Model and we reference its shape
76
+ // via sh:node so SHACL validators can walk the hierarchy.
77
+ const parentCtor = Object.getPrototypeOf(target);
78
+ if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
79
+ const parentSHACL = parentCtor.generateSHACL();
80
+ if (parentSHACL?.shape?.nodeShapeUri) {
81
+ shape.addParentShape(parentSHACL.shape.nodeShapeUri);
82
+ }
83
+ }
84
+
85
+ // ── Constructor / Destructor actions ────────────────────────────────
86
+ let constructorActions: any[] = [];
87
+ if (obj.subjectConstructor && obj.subjectConstructor.length) {
88
+ constructorActions = constructorActions.concat(obj.subjectConstructor);
89
+ }
90
+
91
+ let destructorActions: any[] = [];
92
+
93
+ // ── Convert properties to SHACL property shapes ────────────────────
94
+ for (const propName in properties) {
95
+ const propMeta = properties[propName];
96
+
97
+ if (!propMeta.through) continue; // Skip properties without predicates
98
+
99
+ const propShape: SHACLPropertyShape = {
100
+ name: propName,
101
+ path: propMeta.through,
102
+ };
103
+
104
+ // Determine datatype from initial value or resolveLanguage
105
+ if (propMeta.resolveLanguage === "literal") {
106
+ propShape.datatype = "xsd://string";
107
+ } else if (propMeta.initial) {
108
+ const initialType = typeof obj[propName];
109
+ if (initialType === "number") {
110
+ propShape.datatype = "xsd://integer";
111
+ } else if (initialType === "boolean") {
112
+ propShape.datatype = "xsd://boolean";
113
+ } else if (initialType === "string") {
114
+ propShape.datatype = "xsd://string";
115
+ }
116
+ }
117
+
118
+ // Cardinality constraints
119
+ if (propMeta.required) {
120
+ propShape.minCount = 1;
121
+ }
122
+
123
+ // Single-valued properties get maxCount 1
124
+ propShape.maxCount = 1;
125
+
126
+ // Flag properties have fixed value
127
+ if (propMeta.flag && propMeta.initial) {
128
+ propShape.hasValue = propMeta.initial;
129
+ }
130
+
131
+ // AD4M-specific metadata
132
+ if (propMeta.local !== undefined) {
133
+ propShape.local = propMeta.local;
134
+ }
135
+
136
+ if (propMeta.writable !== undefined) {
137
+ propShape.writable = propMeta.writable;
138
+ }
139
+
140
+ if (propMeta.resolveLanguage) {
141
+ propShape.resolveLanguage = propMeta.resolveLanguage;
142
+ }
143
+
144
+ // ── Setter actions ──────────────────────────────────────────────
145
+ if (propMeta.prologSetter) {
146
+ console.warn(
147
+ `[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
148
+ `The property will be created without setter actions. Consider using standard writable properties or provide explicit SHACL JSON.`
149
+ );
150
+ } else if (propMeta.writable && propMeta.through) {
151
+ let setter = obj[propertyNameToSetterName(propName)];
152
+ if (typeof setter === "function") {
153
+ propShape.setter = [{
154
+ action: "setSingleTarget",
155
+ source: "this",
156
+ predicate: propMeta.through,
157
+ target: "value",
158
+ ...(propMeta.local && { local: true })
159
+ }];
160
+ }
161
+ }
162
+
163
+ // ── Constructor / Destructor entries ────────────────────────────
164
+ const effectiveInitial = propMeta.initial
165
+ ?? (propMeta.required && propMeta.writable && !propMeta.flag && propMeta.through
166
+ ? "literal://string:" : undefined);
167
+
168
+ if (effectiveInitial) {
169
+ constructorActions.push({
170
+ action: "addLink",
171
+ source: "this",
172
+ predicate: propMeta.through,
173
+ target: effectiveInitial,
174
+ });
175
+
176
+ destructorActions.push({
177
+ action: "removeLink",
178
+ source: "this",
179
+ predicate: propMeta.through,
180
+ target: "*",
181
+ });
182
+ }
183
+
184
+ shape.addProperty(propShape);
185
+ }
186
+
187
+ // ── Convert relations to SHACL property shapes ─────────────────────
188
+ for (const relName in relations) {
189
+ const relMeta = relations[relName];
190
+
191
+ if (!relMeta.predicate) continue;
192
+
193
+ const relShape: SHACLPropertyShape = {
194
+ name: relName,
195
+ path: relMeta.predicate,
196
+ };
197
+
198
+ // Relations typically contain IRIs
199
+ relShape.nodeKind = 'IRI';
200
+
201
+ // AD4M-specific metadata
202
+ if (relMeta.local !== undefined) {
203
+ relShape.local = relMeta.local;
204
+ }
205
+
206
+ // Adder action
207
+ relShape.adder = [{
208
+ action: "addLink",
209
+ source: "this",
210
+ predicate: relMeta.predicate,
211
+ target: "value",
212
+ ...(relMeta.local && { local: true })
213
+ }];
214
+
215
+ // Remover action
216
+ relShape.remover = [{
217
+ action: "removeLink",
218
+ source: "this",
219
+ predicate: relMeta.predicate,
220
+ target: "value",
221
+ ...(relMeta.local && { local: true })
222
+ }];
223
+
224
+ // ── Build Getter (conformance filter) ───────────────────────────
225
+ // Priority chain:
226
+ // 1. Explicit getter string → use verbatim
227
+ // 2. `where` clause → compile DSL to SurrealQL getter
228
+ // 3. target + filter !== false → auto-derive from shape
229
+ if (relMeta.getter) {
230
+ relShape.getter = relMeta.getter;
231
+ } else if (relMeta.where) {
232
+ try {
233
+ const TargetClass = relMeta.target?.();
234
+ const targetMetadata = TargetClass
235
+ ? (TargetClass as any).getModelMetadata?.() ?? null
236
+ : null;
237
+
238
+ const conditions = compileWhereClause(
239
+ relMeta.where,
240
+ targetMetadata,
241
+ );
242
+
243
+ if (conditions.length > 0) {
244
+ const escapedPredicate = escapeSurrealString(relMeta.predicate);
245
+ relShape.getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
246
+ }
247
+ } catch (e) {
248
+ // Target metadata may not be available yet
249
+ }
250
+ } else if (relMeta.target && relMeta.filter !== false) {
251
+ try {
252
+ const TargetClass = relMeta.target();
253
+ const filter = conformanceFilterFn(relMeta.predicate, TargetClass);
254
+ if (filter) {
255
+ relShape.getter = filter.getter;
256
+ relShape.conformanceConditions = filter.conformanceConditions;
257
+ }
258
+ } catch (e) {
259
+ // Target class may not be available yet — getter will be
260
+ // absent and runtime will fall back to unfiltered get_links
261
+ }
262
+ }
263
+
264
+ // ── sh:class — target shape reference ───────────────────────────
265
+ if (relMeta.target) {
266
+ try {
267
+ const TargetClass = relMeta.target();
268
+ const targetSHACL = (TargetClass as any).generateSHACL?.();
269
+ if (targetSHACL?.shape?.nodeShapeUri) {
270
+ relShape.class = targetSHACL.shape.nodeShapeUri;
271
+ }
272
+ } catch (e) {
273
+ // Target class may not be available yet
274
+ }
275
+ }
276
+
277
+ shape.addProperty(relShape);
278
+ }
279
+
280
+ // Always set constructor and destructor actions on the shape, even
281
+ // when empty. An empty array serialises to `literal://string:[]`
282
+ // which the Rust executor parses as a valid (no-op) command list,
283
+ // avoiding "No SHACL constructor found" errors for models whose
284
+ // properties are all optional and have no @Flag.
285
+ shape.setConstructorActions(constructorActions);
286
+ shape.setDestructorActions(destructorActions);
287
+
288
+ return {
289
+ shape,
290
+ name: subjectName
291
+ };
292
+ }
@@ -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 "./types";
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
+ }