@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,14 @@
1
+ import type { PropertyMetadataEntry, RelationMetadataEntry } from "./decorators";
2
+ /**
3
+ * Build SDNA (Social DNA) Prolog code for a model class.
4
+ *
5
+ * @param subjectName - The model's registered name (from `@Model({ name })`)
6
+ * @param obj - `target.prototype` — used to inspect prototype methods
7
+ * (e.g. setter stubs, `subjectConstructor`, `isSubjectInstance`)
8
+ * @param properties - Merged property metadata (from `getPropertiesMetadata`)
9
+ * @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)
10
+ */
11
+ export declare function buildSDNA(subjectName: string, obj: any, properties: Record<string, PropertyMetadataEntry>, allRelationsMeta: Record<string, RelationMetadataEntry>): {
12
+ sdna: string;
13
+ name: string;
14
+ };
@@ -0,0 +1,141 @@
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
+ /**
11
+ * Build SDNA (Social DNA) Prolog code for a model class.
12
+ *
13
+ * @param subjectName - The model's registered name (from `@Model({ name })`)
14
+ * @param obj - `target.prototype` — used to inspect prototype methods
15
+ * (e.g. setter stubs, `subjectConstructor`, `isSubjectInstance`)
16
+ * @param properties - Merged property metadata (from `getPropertiesMetadata`)
17
+ * @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)
18
+ */
19
+ export function buildSDNA(subjectName, obj, properties, allRelationsMeta) {
20
+ let sdna = "";
21
+ let uuid = makeRandomId(8);
22
+ sdna += `subject_class("${subjectName}", ${uuid}).\n`;
23
+ let classRemoverActions = [];
24
+ let constructorActions = [];
25
+ if (obj.subjectConstructor && obj.subjectConstructor.length) {
26
+ constructorActions = constructorActions.concat(obj.subjectConstructor);
27
+ }
28
+ let instanceConditions = [];
29
+ if (obj.isSubjectInstance && obj.isSubjectInstance.length) {
30
+ instanceConditions = instanceConditions.concat(obj.isSubjectInstance);
31
+ }
32
+ let propertiesCode = [];
33
+ for (let property in properties) {
34
+ let propertyCode = `property(${uuid}, "${property}").\n`;
35
+ let { through, initial, required, resolveLanguage, writable, flag, prologGetter, prologSetter, local } = properties[property];
36
+ if (resolveLanguage) {
37
+ propertyCode += `property_resolve(${uuid}, "${property}").\n`;
38
+ propertyCode += `property_resolve_language(${uuid}, "${property}", "${resolveLanguage}").\n`;
39
+ }
40
+ if (prologGetter) {
41
+ propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${prologGetter}.\n`;
42
+ }
43
+ else if (through) {
44
+ propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- triple(Base, "${through}", Value).\n`;
45
+ if (required) {
46
+ if (flag) {
47
+ instanceConditions.push(`triple(Base, "${through}", "${initial}")`);
48
+ }
49
+ else {
50
+ instanceConditions.push(`triple(Base, "${through}", _)`);
51
+ }
52
+ }
53
+ }
54
+ if (prologSetter) {
55
+ propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${prologSetter}.\n`;
56
+ }
57
+ else if (writable && through) {
58
+ let setter = obj[propertyNameToSetterName(property)];
59
+ if (typeof setter === "function") {
60
+ let action = [{
61
+ action: "setSingleTarget",
62
+ source: "this",
63
+ predicate: through,
64
+ target: "value",
65
+ ...(local && { local: true })
66
+ }];
67
+ propertyCode += `property_setter(${uuid}, "${property}", '${stringifyObjectLiteral(action)}').\n`;
68
+ }
69
+ }
70
+ propertiesCode.push(propertyCode);
71
+ // Auto-derive effectiveInitial for required, writable, non-flag properties
72
+ // so constructor/destructor always handle the property link.
73
+ // Optional properties (required: false) are excluded — they should
74
+ // remain unset (undefined) until explicitly assigned.
75
+ const effectiveInitial = initial
76
+ ?? (required && writable && !flag && through ? "literal://string:" : undefined);
77
+ if (effectiveInitial) {
78
+ constructorActions.push({
79
+ action: "addLink",
80
+ source: "this",
81
+ predicate: through,
82
+ target: effectiveInitial,
83
+ });
84
+ classRemoverActions.push({
85
+ action: "removeLink",
86
+ source: "this",
87
+ predicate: through,
88
+ target: "*",
89
+ });
90
+ }
91
+ }
92
+ let relationsCode = [];
93
+ const relations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
94
+ for (let relation in relations) {
95
+ let relationCode = `collection(${uuid}, "${relation}").\n`;
96
+ let { predicate: through, local } = relations[relation];
97
+ if (through) {
98
+ relationCode += `collection_getter(${uuid}, Base, "${relation}", List) :- findall(C, triple(Base, "${through}", C), List).\n`;
99
+ let relationAdderAction = [{
100
+ action: "addLink",
101
+ source: "this",
102
+ predicate: through,
103
+ target: "value",
104
+ ...(local && { local: true })
105
+ }];
106
+ let relationRemoverAction = [{
107
+ action: "removeLink",
108
+ source: "this",
109
+ predicate: through,
110
+ target: "value",
111
+ }];
112
+ let relationSetterAction = [{
113
+ action: "collectionSetter",
114
+ source: "this",
115
+ predicate: through,
116
+ target: "value",
117
+ ...(local && { local: true })
118
+ }];
119
+ relationCode += `collection_adder(${uuid}, "${relation}", '${stringifyObjectLiteral(relationAdderAction)}').\n`;
120
+ relationCode += `collection_remover(${uuid}, "${relation}", '${stringifyObjectLiteral(relationRemoverAction)}').\n`;
121
+ relationCode += `collection_setter(${uuid}, "${relation}", '${stringifyObjectLiteral(relationSetterAction)}').\n`;
122
+ }
123
+ relationsCode.push(relationCode);
124
+ }
125
+ let subjectContructorJSONString = stringifyObjectLiteral(constructorActions);
126
+ sdna += `constructor(${uuid}, '${subjectContructorJSONString}').\n`;
127
+ if (instanceConditions.length > 0) {
128
+ let instanceConditionProlog = instanceConditions.join(", ");
129
+ sdna += `instance(${uuid}, Base) :- ${instanceConditionProlog}.\n`;
130
+ sdna += "\n";
131
+ }
132
+ sdna += `destructor(${uuid}, '${stringifyObjectLiteral(classRemoverActions)}').\n`;
133
+ sdna += "\n";
134
+ sdna += propertiesCode.join("\n");
135
+ sdna += "\n";
136
+ sdna += relationsCode.join("\n");
137
+ return {
138
+ sdna,
139
+ name: subjectName
140
+ };
141
+ }
@@ -0,0 +1,31 @@
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 { ConformanceCondition } from "../shacl/SHACLShape";
11
+ import type { PropertyMetadataEntry, RelationMetadataEntry, Ad4mModelLike } from "./decorators";
12
+ /** Signature for the conformance-filter builder injected by the caller. */
13
+ export type ConformanceFilterFn = (relationPredicate: string, targetClass: Ad4mModelLike) => {
14
+ getter: string;
15
+ conformanceConditions: ConformanceCondition[];
16
+ } | undefined;
17
+ /**
18
+ * Build a SHACL shape for a model class.
19
+ *
20
+ * @param subjectName - The model's registered name (from `@Model({ name })`)
21
+ * @param target - The class constructor (used for prototype access,
22
+ * inheritance chain, and relation target resolution)
23
+ * @param properties - Merged property metadata (from `getPropertiesMetadata`)
24
+ * @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)
25
+ * @param conformanceFilterFn - Injected conformance-filter builder
26
+ * (avoids circular dependency back into decorators.ts)
27
+ */
28
+ export declare function buildSHACL(subjectName: string, target: any, properties: Record<string, PropertyMetadataEntry>, allRelationsMeta: Record<string, RelationMetadataEntry>, conformanceFilterFn: ConformanceFilterFn): {
29
+ shape: SHACLShape;
30
+ name: string;
31
+ };
@@ -0,0 +1,246 @@
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 { escapeSurrealString } from "../utils";
11
+ import { compileWhereClause } from "./surreal-utils";
12
+ import { propertyNameToSetterName } from "./util";
13
+ /**
14
+ * Build a SHACL shape for a model class.
15
+ *
16
+ * @param subjectName - The model's registered name (from `@Model({ name })`)
17
+ * @param target - The class constructor (used for prototype access,
18
+ * inheritance chain, and relation target resolution)
19
+ * @param properties - Merged property metadata (from `getPropertiesMetadata`)
20
+ * @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)
21
+ * @param conformanceFilterFn - Injected conformance-filter builder
22
+ * (avoids circular dependency back into decorators.ts)
23
+ */
24
+ export function buildSHACL(subjectName, target, properties, allRelationsMeta, conformanceFilterFn) {
25
+ const obj = target.prototype;
26
+ // ── Determine namespace from first property or relation ─────────────
27
+ let namespace = "ad4m://";
28
+ const relations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
29
+ // Try properties first
30
+ if (Object.keys(properties).length > 0) {
31
+ const firstProp = properties[Object.keys(properties)[0]];
32
+ if (firstProp.through) {
33
+ const match = firstProp.through.match(/^([^:]+:\/\/)/);
34
+ if (match) {
35
+ namespace = match[1];
36
+ }
37
+ }
38
+ }
39
+ // Fall back to relations if no properties
40
+ else if (Object.keys(relations).length > 0) {
41
+ const firstRel = relations[Object.keys(relations)[0]];
42
+ if (firstRel.predicate) {
43
+ const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
44
+ if (match) {
45
+ namespace = match[1];
46
+ }
47
+ }
48
+ }
49
+ // ── Create SHACL shape ──────────────────────────────────────────────
50
+ const shapeUri = `${namespace}${subjectName}Shape`;
51
+ const targetClass = `${namespace}${subjectName}`;
52
+ const shape = new SHACLShape(shapeUri, targetClass);
53
+ // Detect @Model inheritance — if the parent class also has
54
+ // generateSHACL it is itself a @Model and we reference its shape
55
+ // via sh:node so SHACL validators can walk the hierarchy.
56
+ const parentCtor = Object.getPrototypeOf(target);
57
+ if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
58
+ const parentSHACL = parentCtor.generateSHACL();
59
+ if (parentSHACL?.shape?.nodeShapeUri) {
60
+ shape.addParentShape(parentSHACL.shape.nodeShapeUri);
61
+ }
62
+ }
63
+ // ── Constructor / Destructor actions ────────────────────────────────
64
+ let constructorActions = [];
65
+ if (obj.subjectConstructor && obj.subjectConstructor.length) {
66
+ constructorActions = constructorActions.concat(obj.subjectConstructor);
67
+ }
68
+ let destructorActions = [];
69
+ // ── Convert properties to SHACL property shapes ────────────────────
70
+ for (const propName in properties) {
71
+ const propMeta = properties[propName];
72
+ if (!propMeta.through)
73
+ continue; // Skip properties without predicates
74
+ const propShape = {
75
+ name: propName,
76
+ path: propMeta.through,
77
+ };
78
+ // Determine datatype from initial value or resolveLanguage
79
+ if (propMeta.resolveLanguage === "literal") {
80
+ propShape.datatype = "xsd://string";
81
+ }
82
+ else if (propMeta.initial) {
83
+ const initialType = typeof obj[propName];
84
+ if (initialType === "number") {
85
+ propShape.datatype = "xsd://integer";
86
+ }
87
+ else if (initialType === "boolean") {
88
+ propShape.datatype = "xsd://boolean";
89
+ }
90
+ else if (initialType === "string") {
91
+ propShape.datatype = "xsd://string";
92
+ }
93
+ }
94
+ // Cardinality constraints
95
+ if (propMeta.required) {
96
+ propShape.minCount = 1;
97
+ }
98
+ // Single-valued properties get maxCount 1
99
+ propShape.maxCount = 1;
100
+ // Flag properties have fixed value
101
+ if (propMeta.flag && propMeta.initial) {
102
+ propShape.hasValue = propMeta.initial;
103
+ }
104
+ // AD4M-specific metadata
105
+ if (propMeta.local !== undefined) {
106
+ propShape.local = propMeta.local;
107
+ }
108
+ if (propMeta.writable !== undefined) {
109
+ propShape.writable = propMeta.writable;
110
+ }
111
+ if (propMeta.resolveLanguage) {
112
+ propShape.resolveLanguage = propMeta.resolveLanguage;
113
+ }
114
+ // ── Setter actions ──────────────────────────────────────────────
115
+ if (propMeta.prologSetter) {
116
+ console.warn(`[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
117
+ `The property will be created without setter actions. Consider using standard writable properties or provide explicit SHACL JSON.`);
118
+ }
119
+ else if (propMeta.writable && propMeta.through) {
120
+ let setter = obj[propertyNameToSetterName(propName)];
121
+ if (typeof setter === "function") {
122
+ propShape.setter = [{
123
+ action: "setSingleTarget",
124
+ source: "this",
125
+ predicate: propMeta.through,
126
+ target: "value",
127
+ ...(propMeta.local && { local: true })
128
+ }];
129
+ }
130
+ }
131
+ // ── Constructor / Destructor entries ────────────────────────────
132
+ const effectiveInitial = propMeta.initial
133
+ ?? (propMeta.required && propMeta.writable && !propMeta.flag && propMeta.through
134
+ ? "literal://string:" : undefined);
135
+ if (effectiveInitial) {
136
+ constructorActions.push({
137
+ action: "addLink",
138
+ source: "this",
139
+ predicate: propMeta.through,
140
+ target: effectiveInitial,
141
+ });
142
+ destructorActions.push({
143
+ action: "removeLink",
144
+ source: "this",
145
+ predicate: propMeta.through,
146
+ target: "*",
147
+ });
148
+ }
149
+ shape.addProperty(propShape);
150
+ }
151
+ // ── Convert relations to SHACL property shapes ─────────────────────
152
+ for (const relName in relations) {
153
+ const relMeta = relations[relName];
154
+ if (!relMeta.predicate)
155
+ continue;
156
+ const relShape = {
157
+ name: relName,
158
+ path: relMeta.predicate,
159
+ };
160
+ // Relations typically contain IRIs
161
+ relShape.nodeKind = 'IRI';
162
+ // AD4M-specific metadata
163
+ if (relMeta.local !== undefined) {
164
+ relShape.local = relMeta.local;
165
+ }
166
+ // Adder action
167
+ relShape.adder = [{
168
+ action: "addLink",
169
+ source: "this",
170
+ predicate: relMeta.predicate,
171
+ target: "value",
172
+ ...(relMeta.local && { local: true })
173
+ }];
174
+ // Remover action
175
+ relShape.remover = [{
176
+ action: "removeLink",
177
+ source: "this",
178
+ predicate: relMeta.predicate,
179
+ target: "value",
180
+ ...(relMeta.local && { local: true })
181
+ }];
182
+ // ── Build Getter (conformance filter) ───────────────────────────
183
+ // Priority chain:
184
+ // 1. Explicit getter string → use verbatim
185
+ // 2. `where` clause → compile DSL to SurrealQL getter
186
+ // 3. target + filter !== false → auto-derive from shape
187
+ if (relMeta.getter) {
188
+ relShape.getter = relMeta.getter;
189
+ }
190
+ else if (relMeta.where) {
191
+ try {
192
+ const TargetClass = relMeta.target?.();
193
+ const targetMetadata = TargetClass
194
+ ? TargetClass.getModelMetadata?.() ?? null
195
+ : null;
196
+ const conditions = compileWhereClause(relMeta.where, targetMetadata);
197
+ if (conditions.length > 0) {
198
+ const escapedPredicate = escapeSurrealString(relMeta.predicate);
199
+ relShape.getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
200
+ }
201
+ }
202
+ catch (e) {
203
+ // Target metadata may not be available yet
204
+ }
205
+ }
206
+ else if (relMeta.target && relMeta.filter !== false) {
207
+ try {
208
+ const TargetClass = relMeta.target();
209
+ const filter = conformanceFilterFn(relMeta.predicate, TargetClass);
210
+ if (filter) {
211
+ relShape.getter = filter.getter;
212
+ relShape.conformanceConditions = filter.conformanceConditions;
213
+ }
214
+ }
215
+ catch (e) {
216
+ // Target class may not be available yet — getter will be
217
+ // absent and runtime will fall back to unfiltered get_links
218
+ }
219
+ }
220
+ // ── sh:class — target shape reference ───────────────────────────
221
+ if (relMeta.target) {
222
+ try {
223
+ const TargetClass = relMeta.target();
224
+ const targetSHACL = TargetClass.generateSHACL?.();
225
+ if (targetSHACL?.shape?.nodeShapeUri) {
226
+ relShape.class = targetSHACL.shape.nodeShapeUri;
227
+ }
228
+ }
229
+ catch (e) {
230
+ // Target class may not be available yet
231
+ }
232
+ }
233
+ shape.addProperty(relShape);
234
+ }
235
+ // Always set constructor and destructor actions on the shape, even
236
+ // when empty. An empty array serialises to `literal://string:[]`
237
+ // which the Rust executor parses as a valid (no-op) command list,
238
+ // avoiding "No SHACL constructor found" errors for models whose
239
+ // properties are all optional and have no @Flag.
240
+ shape.setConstructorActions(constructorActions);
241
+ shape.setDestructorActions(destructorActions);
242
+ return {
243
+ shape,
244
+ name: subjectName
245
+ };
246
+ }
@@ -0,0 +1,42 @@
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
+ import type { WhereCondition, Where, ModelMetadata } from "./types";
8
+ /**
9
+ * Format a JavaScript value for embedding in a SurrealQL expression.
10
+ *
11
+ * - Strings are single-quoted with backslash / quote / newline escaping
12
+ * - Numbers and booleans are passed through as-is
13
+ * - Arrays are recursed
14
+ */
15
+ export declare function formatSurrealValue(value: any): string;
16
+ /**
17
+ * Compile a single Where condition for a property into a SurrealQL
18
+ * graph-traversal sub-expression.
19
+ *
20
+ * Operates on the **target node** — generates `count(->link[WHERE ...]) > 0`
21
+ * style checks that can be used inside a `[WHERE ...]` filter on nodes.
22
+ *
23
+ * @param predicate - The predicate URI for the property
24
+ * @param condition - The Where condition value
25
+ * @param opts - Optional settings (e.g. `resolveLanguage`)
26
+ * @returns A single SurrealQL condition string
27
+ */
28
+ export declare function buildWhereCondition(predicate: string, condition: WhereCondition, opts?: {
29
+ resolveLanguage?: string;
30
+ }): string;
31
+ /**
32
+ * Compile a full `Where` clause to an array of SurrealQL condition strings.
33
+ *
34
+ * When `metadata` is provided, property names are resolved to predicates
35
+ * using the model's property metadata. When `metadata` is `null`, property
36
+ * names are treated as raw predicate URIs.
37
+ *
38
+ * Only handles **regular properties** — special fields (`id`, `author`,
39
+ * `timestamp`) and relation fields are skipped (they are only relevant at
40
+ * runtime query time, not for compile-time getter generation).
41
+ */
42
+ export declare function compileWhereClause(where: Where, metadata: ModelMetadata | null): string[];
@@ -0,0 +1,128 @@
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
+ import { escapeSurrealString } from "../utils";
8
+ /**
9
+ * Format a JavaScript value for embedding in a SurrealQL expression.
10
+ *
11
+ * - Strings are single-quoted with backslash / quote / newline escaping
12
+ * - Numbers and booleans are passed through as-is
13
+ * - Arrays are recursed
14
+ */
15
+ export function formatSurrealValue(value) {
16
+ if (typeof value === 'string') {
17
+ // Escape backslashes first, then single quotes and other special characters
18
+ const escaped = value
19
+ .replace(/\\/g, '\\\\') // Backslash -> \\
20
+ .replace(/'/g, "\\'") // Single quote -> \'
21
+ .replace(/"/g, '\\"') // Double quote -> \"
22
+ .replace(/\n/g, '\\n') // Newline -> \n
23
+ .replace(/\r/g, '\\r') // Carriage return -> \r
24
+ .replace(/\t/g, '\\t'); // Tab -> \t
25
+ return `'${escaped}'`;
26
+ }
27
+ else if (typeof value === 'number' || typeof value === 'boolean') {
28
+ return String(value);
29
+ }
30
+ else if (Array.isArray(value)) {
31
+ return `[${value.map(v => formatSurrealValue(v)).join(', ')}]`;
32
+ }
33
+ else {
34
+ return String(value);
35
+ }
36
+ }
37
+ /**
38
+ * Compile a single Where condition for a property into a SurrealQL
39
+ * graph-traversal sub-expression.
40
+ *
41
+ * Operates on the **target node** — generates `count(->link[WHERE ...]) > 0`
42
+ * style checks that can be used inside a `[WHERE ...]` filter on nodes.
43
+ *
44
+ * @param predicate - The predicate URI for the property
45
+ * @param condition - The Where condition value
46
+ * @param opts - Optional settings (e.g. `resolveLanguage`)
47
+ * @returns A single SurrealQL condition string
48
+ */
49
+ export function buildWhereCondition(predicate, condition, opts) {
50
+ const escapedPredicate = escapeSurrealString(predicate);
51
+ const targetField = opts?.resolveLanguage === 'literal'
52
+ ? 'fn::parse_literal(out.uri)'
53
+ : 'out.uri';
54
+ if (Array.isArray(condition)) {
55
+ // Array values → IN clause
56
+ const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
57
+ return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) > 0`;
58
+ }
59
+ else if (typeof condition === 'object' && condition !== null) {
60
+ // Operator object
61
+ const ops = condition;
62
+ const parts = [];
63
+ if (ops.not !== undefined) {
64
+ if (Array.isArray(ops.not)) {
65
+ const formattedValues = ops.not.map((v) => formatSurrealValue(v)).join(', ');
66
+ parts.push(`count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
67
+ }
68
+ else {
69
+ parts.push(`count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
70
+ }
71
+ }
72
+ // Comparison operators — ensure property exists (actual comparison
73
+ // may be post-filtered in JS at runtime, but the SurrealQL condition
74
+ // is valid for compile-time getter generation too).
75
+ const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
76
+ ops.lt !== undefined || ops.lte !== undefined ||
77
+ ops.between !== undefined || ops.contains !== undefined;
78
+ if (hasComparisonOps) {
79
+ parts.push(`count(->link[WHERE predicate = '${escapedPredicate}']) > 0`);
80
+ }
81
+ return parts.join(' AND ');
82
+ }
83
+ else {
84
+ // Simple equality
85
+ return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`;
86
+ }
87
+ }
88
+ /**
89
+ * Compile a full `Where` clause to an array of SurrealQL condition strings.
90
+ *
91
+ * When `metadata` is provided, property names are resolved to predicates
92
+ * using the model's property metadata. When `metadata` is `null`, property
93
+ * names are treated as raw predicate URIs.
94
+ *
95
+ * Only handles **regular properties** — special fields (`id`, `author`,
96
+ * `timestamp`) and relation fields are skipped (they are only relevant at
97
+ * runtime query time, not for compile-time getter generation).
98
+ */
99
+ export function compileWhereClause(where, metadata) {
100
+ const conditions = [];
101
+ for (const [propertyName, condition] of Object.entries(where)) {
102
+ // Skip special fields that don't apply at compile time
103
+ if (['id', 'author', 'timestamp'].includes(propertyName))
104
+ continue;
105
+ let predicate;
106
+ let resolveLanguage;
107
+ if (metadata) {
108
+ const propMeta = metadata.properties[propertyName];
109
+ if (propMeta) {
110
+ predicate = propMeta.predicate;
111
+ resolveLanguage = propMeta.resolveLanguage;
112
+ }
113
+ else {
114
+ // Property not found in metadata — treat name as raw predicate URI
115
+ predicate = propertyName;
116
+ }
117
+ }
118
+ else {
119
+ // No metadata — treat name as raw predicate URI
120
+ predicate = propertyName;
121
+ }
122
+ const cond = buildWhereCondition(predicate, condition, { resolveLanguage });
123
+ if (cond) {
124
+ conditions.push(cond);
125
+ }
126
+ }
127
+ return conditions;
128
+ }