@coasys/ad4m 0.12.0-rc1-dev.5 → 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 (161) hide show
  1. package/lib/index.cjs +4968 -4805
  2. package/lib/index.js +4936 -4801
  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 -812
  8. package/lib/src/model/Ad4mModel.js +78 -2390
  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 +2 -20
  12. package/lib/src/model/decorators.js +5 -410
  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/sdna.d.ts +14 -0
  28. package/lib/src/model/sdna.js +141 -0
  29. package/lib/src/model/shacl-gen.d.ts +31 -0
  30. package/lib/src/model/shacl-gen.js +246 -0
  31. package/lib/src/model/surreal-utils.d.ts +1 -1
  32. package/lib/src/model/types.d.ts +75 -96
  33. package/lib/src/model/types.js +4 -4
  34. package/lib/src/model/util.d.ts +4 -5
  35. package/lib/src/model/util.js +12 -32
  36. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
  37. package/lib/src/perspectives/PerspectiveProxy.d.ts +1 -1
  38. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +79 -0
  39. package/lib/src/perspectives/WakerSubscriptionManager.js +196 -0
  40. package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
  41. package/lib/src/runtime/RuntimeResolver.js +73 -0
  42. package/lib/src/schema.gql +14 -0
  43. package/lib/src/typeDefs.js +14 -0
  44. package/package.json +13 -8
  45. package/src/agent/AgentClient.ts +45 -0
  46. package/src/index.ts +2 -3
  47. package/src/model/Ad4mModel.ts +1084 -3818
  48. package/src/model/ModelQueryBuilder.ts +617 -0
  49. package/src/model/Subject.ts +1 -1
  50. package/src/model/decorators.ts +17 -475
  51. package/src/model/hydration.ts +796 -0
  52. package/src/model/index.ts +21 -0
  53. package/src/model/json-schema.ts +424 -0
  54. package/src/model/prolog-facts.ts +145 -0
  55. package/src/model/query-common.ts +48 -0
  56. package/src/model/query-prolog.ts +148 -0
  57. package/src/model/query-surreal.ts +280 -0
  58. package/src/model/relation-filtering.test.ts +0 -1
  59. package/src/model/sdna.ts +170 -0
  60. package/src/model/shacl-gen.ts +292 -0
  61. package/src/model/surreal-utils.ts +1 -1
  62. package/src/model/types.ts +182 -0
  63. package/src/model/util.ts +13 -36
  64. package/src/perspectives/PerspectiveClient.ts +1 -1
  65. package/src/perspectives/PerspectiveProxy.ts +1 -1
  66. package/src/perspectives/WakerSubscriptionManager.ts +292 -0
  67. package/src/runtime/RuntimeResolver.ts +53 -0
  68. package/lib/src/Ad4mClient.test.d.ts +0 -1
  69. package/lib/src/Ad4mClient.test.js +0 -1204
  70. package/lib/src/Literal.test.d.ts +0 -1
  71. package/lib/src/Literal.test.js +0 -41
  72. package/lib/src/model/mutation.d.ts +0 -81
  73. package/lib/src/model/mutation.js +0 -317
  74. package/lib/src/model/parentUtils.d.ts +0 -32
  75. package/lib/src/model/parentUtils.js +0 -64
  76. package/lib/src/model/prolog/generatePrologFacts.d.ts +0 -36
  77. package/lib/src/model/prolog/index.d.ts +0 -1
  78. package/lib/src/model/prolog/index.js +0 -1
  79. package/lib/src/model/query/ModelQueryBuilder.d.ts +0 -82
  80. package/lib/src/model/query/ModelQueryBuilder.js +0 -115
  81. package/lib/src/model/query/QueryBuilder.d.ts +0 -101
  82. package/lib/src/model/query/QueryBuilder.js +0 -193
  83. package/lib/src/model/query/SurrealQueryBuilder.d.ts +0 -48
  84. package/lib/src/model/query/SurrealQueryBuilder.js +0 -371
  85. package/lib/src/model/query/fetchInstance.d.ts +0 -24
  86. package/lib/src/model/query/fetchInstance.js +0 -144
  87. package/lib/src/model/query/hydration.d.ts +0 -54
  88. package/lib/src/model/query/hydration.js +0 -214
  89. package/lib/src/model/query/operations.d.ts +0 -59
  90. package/lib/src/model/query/operations.js +0 -384
  91. package/lib/src/model/query/snapshot.d.ts +0 -59
  92. package/lib/src/model/query/snapshot.js +0 -106
  93. package/lib/src/model/query/surrealCompiler.d.ts +0 -42
  94. package/lib/src/model/query/surrealCompiler.js +0 -304
  95. package/lib/src/model/schema/fromJSONSchema.js +0 -264
  96. package/lib/src/model/schema/metadata.d.ts +0 -15
  97. package/lib/src/model/schema/metadata.js +0 -112
  98. package/lib/src/model/subscription.d.ts +0 -47
  99. package/lib/src/model/subscription.js +0 -231
  100. package/lib/src/model/transaction.d.ts +0 -27
  101. package/lib/src/model/transaction.js +0 -32
  102. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  103. package/lib/src/shims/type-graphql.d.ts +0 -32
  104. package/lib/src/src/Ad4mClient.d.ts +0 -28
  105. package/lib/src/src/Address.d.ts +0 -1
  106. package/lib/src/src/DID.d.ts +0 -1
  107. package/lib/src/src/Exception.d.ts +0 -7
  108. package/lib/src/src/Literal.d.ts +0 -7
  109. package/lib/src/src/PubSub.d.ts +0 -17
  110. package/lib/src/src/SmartLiteral.d.ts +0 -12
  111. package/lib/src/src/agent/Agent.d.ts +0 -110
  112. package/lib/src/src/agent/AgentClient.d.ts +0 -62
  113. package/lib/src/src/agent/AgentResolver.d.ts +0 -30
  114. package/lib/src/src/agent/AgentStatus.d.ts +0 -8
  115. package/lib/src/src/ai/AIClient.d.ts +0 -32
  116. package/lib/src/src/ai/AIResolver.d.ts +0 -75
  117. package/lib/src/src/ai/Tasks.d.ts +0 -37
  118. package/lib/src/src/buildSchema.d.ts +0 -1
  119. package/lib/src/src/expression/Expression.d.ts +0 -28
  120. package/lib/src/src/expression/ExpressionClient.d.ts +0 -13
  121. package/lib/src/src/expression/ExpressionRef.d.ts +0 -9
  122. package/lib/src/src/expression/ExpressionResolver.d.ts +0 -10
  123. package/lib/src/src/index.d.ts +0 -35
  124. package/lib/src/src/jestSetup.d.ts +0 -1
  125. package/lib/src/src/language/Icon.d.ts +0 -4
  126. package/lib/src/src/language/Language.d.ts +0 -206
  127. package/lib/src/src/language/LanguageClient.d.ts +0 -17
  128. package/lib/src/src/language/LanguageContext.d.ts +0 -37
  129. package/lib/src/src/language/LanguageHandle.d.ts +0 -9
  130. package/lib/src/src/language/LanguageMeta.d.ts +0 -35
  131. package/lib/src/src/language/LanguageRef.d.ts +0 -6
  132. package/lib/src/src/language/LanguageResolver.d.ts +0 -19
  133. package/lib/src/src/links/Links.d.ts +0 -39
  134. package/lib/src/src/links/Links.test.d.ts +0 -1
  135. package/lib/src/src/model/Ad4mModel.d.ts +0 -1438
  136. package/lib/src/src/model/Ad4mModel.test.d.ts +0 -1
  137. package/lib/src/src/model/Subject.d.ts +0 -25
  138. package/lib/src/src/model/decorators.d.ts +0 -545
  139. package/lib/src/src/model/util.d.ts +0 -12
  140. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +0 -10
  141. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +0 -25
  142. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +0 -19
  143. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +0 -1
  144. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +0 -24
  145. package/lib/src/src/perspectives/LinkQuery.d.ts +0 -11
  146. package/lib/src/src/perspectives/Perspective.d.ts +0 -38
  147. package/lib/src/src/perspectives/Perspective.test.d.ts +0 -1
  148. package/lib/src/src/perspectives/PerspectiveClient.d.ts +0 -97
  149. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +0 -9
  150. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +0 -18
  151. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +0 -865
  152. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +0 -57
  153. package/lib/src/src/runtime/RuntimeClient.d.ts +0 -56
  154. package/lib/src/src/runtime/RuntimeResolver.d.ts +0 -132
  155. package/lib/src/src/shacl/SHACLFlow.d.ts +0 -171
  156. package/lib/src/src/shacl/SHACLFlow.test.d.ts +0 -1
  157. package/lib/src/src/shacl/SHACLShape.d.ts +0 -117
  158. package/lib/src/src/shacl/SHACLShape.test.d.ts +0 -1
  159. package/lib/src/src/typeDefs.d.ts +0 -1
  160. package/lib/src/src/unwrapApolloResult.d.ts +0 -2
  161. package/lib/src/src/utils.d.ts +0 -25
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Prolog query building helpers for the Ad4mModel query pipeline.
3
+ *
4
+ * These pure functions translate the Ad4mModel `Query` DSL into Prolog clause
5
+ * fragments that are assembled by `Ad4mModel.queryToProlog()`.
6
+ */
7
+
8
+ import type { Where, WhereCondition, Order, ParentScope } from "./types";
9
+ import { capitalize } from "./util";
10
+
11
+ // ── Query clause builders ────────────────────────────────────────────────────
12
+
13
+ export function buildParentQuery(
14
+ parent: ParentScope | undefined,
15
+ resolvedPredicate?: string,
16
+ ): string {
17
+ if (!parent || !resolvedPredicate) return '';
18
+ return `triple("${parent.id}", "${resolvedPredicate}", Base)`;
19
+ }
20
+
21
+ export function buildAuthorAndTimestampQuery(): string {
22
+ // Gets the author and timestamp of a Ad4mModel instance (based on the first link mentioning the base)
23
+ return `
24
+ findall(
25
+ [T, A],
26
+ link(Base, _, _, T, A),
27
+ AllLinks
28
+ ),
29
+ sort(AllLinks, SortedLinks),
30
+ SortedLinks = [[Timestamp, Author]|_]
31
+ `;
32
+ }
33
+
34
+ export function buildPropertiesQuery(properties?: string[]): string {
35
+ // Gets the name, value, and resolve boolean for all (or some) properties on a Ad4mModel instance
36
+ // Resolves literals (if property_resolve/2 is true) to their value - either the data field if it is
37
+ // an Expression in JSON literal, or the direct literal value if it is a simple literal
38
+ // If no properties are provided, all are included
39
+ return `
40
+ findall([PropertyName, PropertyValue, Resolve], (
41
+ % Constrain to specified properties if provided
42
+ ${properties ? `member(PropertyName, [${properties.map((name) => `"${name}"`).join(", ")}]),` : ""}
43
+ resolve_property(SubjectClass, Base, PropertyName, PropertyValue, Resolve)
44
+ ), Properties)
45
+ `;
46
+ }
47
+
48
+ export function buildWhereQuery(where: Where = {}): string {
49
+ // Constrains the query to instances that match the provided where conditions
50
+ // 'id' maps to the Prolog 'Base' variable (the base expression of the instance).
51
+
52
+ function formatValue(value) {
53
+ // Wrap strings in quotes
54
+ return typeof value === "string" ? `"${value}"` : value;
55
+ }
56
+
57
+ return (Object.entries(where) as [string, WhereCondition][])
58
+ .map(([key, value]) => {
59
+ const isSpecial = ["id", "author", "timestamp"].includes(key);
60
+ const getter = `resolve_property(SubjectClass, Base, "${key}", Value${key}, _)`;
61
+ // For 'id' the Prolog variable is always 'Base'
62
+ const field = key === "id" ? "Base" : capitalize(key);
63
+
64
+ // Handle direct array values (for IN conditions)
65
+ if (Array.isArray(value)) {
66
+ const formattedValues = value.map((v) => formatValue(v)).join(", ");
67
+ if (isSpecial) return `member(${field}, [${formattedValues}])`;
68
+ else return `${getter}, member(Value${key}, [${formattedValues}])`;
69
+ }
70
+
71
+ // Handle operation object
72
+ if (typeof value === "object" && value !== null) {
73
+ const { not, between, lt, lte, gt, gte } = value;
74
+
75
+ // Handle NOT operation
76
+ if (not !== undefined) {
77
+ if (Array.isArray(not)) {
78
+ // NOT IN array
79
+ const formattedValues = not.map((v) => formatValue(v)).join(", ");
80
+ if (isSpecial) return `\\+ member(${field}, [${formattedValues}])`;
81
+ else return `${getter}, \\+ member(Value${key}, [${formattedValues}])`;
82
+ } else {
83
+ // NOT EQUAL
84
+ if (isSpecial) return `${field} \\= ${formatValue(not)}`;
85
+ else return `${getter}, Value${key} \\= ${formatValue(not)}`;
86
+ }
87
+ }
88
+
89
+ // Handle BETWEEN
90
+ if (between !== undefined && Array.isArray(between) && between.length === 2) {
91
+ if (isSpecial) return `${field} >= ${between[0]}, ${field} =< ${between[1]}`;
92
+ else return `${getter}, Value${key} >= ${between[0]}, Value${key} =< ${between[1]}`;
93
+ }
94
+
95
+ // Handle lt, lte, gt, & gte operations
96
+ const operators = [
97
+ { value: lt, symbol: "<" }, // LESS THAN
98
+ { value: lte, symbol: "=<" }, // LESS THAN OR EQUAL TO
99
+ { value: gt, symbol: ">" }, // GREATER THAN
100
+ { value: gte, symbol: ">=" }, // GREATER THAN OR EQUAL TO
101
+ ];
102
+
103
+ for (const { value, symbol } of operators) {
104
+ if (value !== undefined)
105
+ return isSpecial ? `${field} ${symbol} ${value}` : `${getter}, Value${key} ${symbol} ${value}`;
106
+ }
107
+ }
108
+
109
+ // Default to direct equality
110
+ if (isSpecial) return `${field} = ${formatValue(value)}`;
111
+ else return `${getter}, Value${key} = ${formatValue(value)}`;
112
+ })
113
+ .join(", ");
114
+ }
115
+
116
+ export function buildCountQuery(count?: boolean): string {
117
+ return count ? "length(UnsortedInstances, TotalCount)" : "";
118
+ }
119
+
120
+ export function buildOrderQuery(order?: Order): string {
121
+ if (!order) return "SortedInstances = UnsortedInstances";
122
+ const entries = Object.entries(order);
123
+ if (entries.length === 1) {
124
+ const [propertyName, direction] = entries[0];
125
+ return `sort_instances(UnsortedInstances, "${propertyName}", "${direction}", SortedInstances)`;
126
+ }
127
+ // Multi-field sort: sort from least-significant to most-significant key
128
+ // so that the final (primary) sort preserves secondary-key ordering for equal values.
129
+ // The merge_sort implementation is stable (equal elements keep original order).
130
+ const clauses: string[] = [];
131
+ for (let i = entries.length - 1; i >= 0; i--) {
132
+ const [propertyName, direction] = entries[i];
133
+ const inputVar = i === entries.length - 1 ? "UnsortedInstances" : `MultiSortIntermediate${i + 1}`;
134
+ const outputVar = i === 0 ? "SortedInstances" : `MultiSortIntermediate${i}`;
135
+ clauses.push(`sort_instances(${inputVar}, "${propertyName}", "${direction}", ${outputVar})`);
136
+ }
137
+ return clauses.join(",\n ");
138
+ }
139
+
140
+ export function buildOffsetQuery(offset?: number): string {
141
+ if (!offset || offset < 0) return "InstancesWithOffset = SortedInstances";
142
+ return `skipN(SortedInstances, ${offset}, InstancesWithOffset)`;
143
+ }
144
+
145
+ export function buildLimitQuery(limit?: number): string {
146
+ if (!limit || limit < 0) return "AllInstances = InstancesWithOffset";
147
+ return `takeN(InstancesWithOffset, ${limit}, AllInstances)`;
148
+ }
@@ -0,0 +1,280 @@
1
+ /**
2
+ * SurrealQL query building utilities for Ad4mModel.
3
+ *
4
+ * Contains the graph-traversal WHERE clause builder, legacy
5
+ * subquery-based clause builders, SELECT-field builders, and
6
+ * the main `buildSurrealQLQuery()` function that produces a
7
+ * complete SurrealQL query string from a `Query` object.
8
+ *
9
+ * All functions are stateless — model metadata and relation metadata
10
+ * are passed in as parameters instead of accessed via `this`.
11
+ *
12
+ * @module
13
+ */
14
+
15
+ import { escapeSurrealString } from "../utils";
16
+ import { formatSurrealValue } from "./surreal-utils";
17
+ import { resolveParentPredicate } from "./query-common";
18
+ import type { RelationMetadataEntry } from "./decorators";
19
+ import type {
20
+ Where, Query, ModelMetadata
21
+ } from "./types";
22
+
23
+ // ─── Graph Traversal WHERE Clause ────────────────────────────────────────────
24
+
25
+ /**
26
+ * Builds WHERE clause filters using SurrealDB graph traversal syntax.
27
+ *
28
+ * Translates where conditions into `->link[WHERE ...]` / `<-link[WHERE ...]`
29
+ * filters that SurrealDB can optimize via graph indexes.
30
+ *
31
+ * @param metadata - Model metadata from `getModelMetadata()`
32
+ * @param allRelationsMetadata - Full relation metadata (needed for belongs-to
33
+ * direction detection)
34
+ * @param where - User-supplied where conditions
35
+ * @returns Combined AND-joined condition string, or empty string
36
+ */
37
+ export function buildGraphTraversalWhereClause(
38
+ metadata: ModelMetadata,
39
+ allRelationsMetadata: Record<string, RelationMetadataEntry>,
40
+ where?: Where,
41
+ ): string {
42
+ if (!where) return '';
43
+
44
+ const conditions: string[] = [];
45
+
46
+ for (const [propertyName, condition] of Object.entries(where)) {
47
+ const isSpecial = ['id', 'author', 'timestamp'].includes(propertyName);
48
+
49
+ if (isSpecial) {
50
+ if (propertyName === 'author' || propertyName === 'timestamp') {
51
+ continue; // Filtered post-query in JS
52
+ }
53
+
54
+ const columnName = 'uri';
55
+
56
+ if (Array.isArray(condition)) {
57
+ const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
58
+ conditions.push(`${columnName} IN [${formattedValues}]`);
59
+ } else if (typeof condition === 'object' && condition !== null) {
60
+ const ops = condition as any;
61
+ if (ops.not !== undefined) {
62
+ if (Array.isArray(ops.not)) {
63
+ const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
64
+ conditions.push(`${columnName} NOT IN [${formattedValues}]`);
65
+ } else {
66
+ conditions.push(`${columnName} != ${formatSurrealValue(ops.not)}`);
67
+ }
68
+ }
69
+ if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
70
+ conditions.push(`${columnName} >= ${formatSurrealValue(ops.between[0])} AND ${columnName} <= ${formatSurrealValue(ops.between[1])}`);
71
+ }
72
+ if (ops.gt !== undefined) {
73
+ conditions.push(`${columnName} > ${formatSurrealValue(ops.gt)}`);
74
+ }
75
+ if (ops.gte !== undefined) {
76
+ conditions.push(`${columnName} >= ${formatSurrealValue(ops.gte)}`);
77
+ }
78
+ if (ops.lt !== undefined) {
79
+ conditions.push(`${columnName} < ${formatSurrealValue(ops.lt)}`);
80
+ }
81
+ if (ops.lte !== undefined) {
82
+ conditions.push(`${columnName} <= ${formatSurrealValue(ops.lte)}`);
83
+ }
84
+ if (ops.contains !== undefined) {
85
+ conditions.push(`${columnName} CONTAINS ${formatSurrealValue(ops.contains)}`);
86
+ }
87
+ } else {
88
+ conditions.push(`${columnName} = ${formatSurrealValue(condition)}`);
89
+ }
90
+ } else {
91
+ // Regular properties — check relation metadata first for direction
92
+ const relMeta = allRelationsMetadata[propertyName];
93
+ const isBelongs = relMeta?.kind === 'belongsToOne' || relMeta?.kind === 'belongsToMany';
94
+
95
+ if (relMeta) {
96
+ const predicate = escapeSurrealString(relMeta.predicate);
97
+
98
+ if (Array.isArray(condition)) {
99
+ const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
100
+ if (isBelongs) {
101
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) > 0`);
102
+ } else {
103
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) > 0`);
104
+ }
105
+ } else if (typeof condition === 'object' && condition !== null) {
106
+ const ops = condition as any;
107
+ if (ops.not !== undefined) {
108
+ if (Array.isArray(ops.not)) {
109
+ const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
110
+ if (isBelongs) {
111
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) = 0`);
112
+ } else {
113
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) = 0`);
114
+ }
115
+ } else {
116
+ if (isBelongs) {
117
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(ops.not)}]) = 0`);
118
+ } else {
119
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(ops.not)}]) = 0`);
120
+ }
121
+ }
122
+ }
123
+ } else {
124
+ if (isBelongs) {
125
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(condition)}]) > 0`);
126
+ } else {
127
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(condition)}]) > 0`);
128
+ }
129
+ }
130
+ continue;
131
+ }
132
+
133
+ const propMeta = metadata.properties[propertyName];
134
+ if (!propMeta) continue;
135
+
136
+ const predicate = escapeSurrealString(propMeta.predicate);
137
+ const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
138
+
139
+ if (Array.isArray(condition)) {
140
+ const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
141
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
142
+ } else if (typeof condition === 'object' && condition !== null) {
143
+ const ops = condition as any;
144
+ if (ops.not !== undefined) {
145
+ if (Array.isArray(ops.not)) {
146
+ const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
147
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
148
+ } else {
149
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
150
+ }
151
+ }
152
+ const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
153
+ ops.lt !== undefined || ops.lte !== undefined ||
154
+ ops.between !== undefined || ops.contains !== undefined;
155
+ if (hasComparisonOps) {
156
+ conditions.push(`count(->link[WHERE predicate = '${predicate}']) > 0`);
157
+ }
158
+ } else {
159
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`);
160
+ }
161
+ }
162
+ }
163
+
164
+ return conditions.join(' AND ');
165
+ }
166
+
167
+ // ─── Main Query Builder ─────────────────────────────────────────────────────
168
+
169
+ /**
170
+ * Builds a complete SurrealQL query from a Query object and model metadata.
171
+ *
172
+ * This is the core implementation behind `Ad4mModel.queryToSurrealQL()`.
173
+ * It produces a graph-traversal query that:
174
+ * 1. Filters nodes by required predicates (conformance check)
175
+ * 2. Applies user WHERE conditions
176
+ * 3. Fetches all outgoing links for hydration
177
+ *
178
+ * @param metadata - Model metadata from `getModelMetadata()`
179
+ * @param allRelationsMetadata - Full relation registry (for belongs-to detection)
180
+ * @param query - Query parameters
181
+ * @param modelClass - The model class (for `resolveParentPredicate`)
182
+ * @returns Complete SurrealQL query string
183
+ */
184
+ export function buildSurrealQLQuery(
185
+ metadata: ModelMetadata,
186
+ allRelationsMetadata: Record<string, RelationMetadataEntry>,
187
+ query: Query,
188
+ modelClass: any,
189
+ ): string {
190
+ const { where } = query;
191
+
192
+ // Build graph traversal filters for required predicates
193
+ const graphTraversalFilters: string[] = [];
194
+
195
+ // Parent filter
196
+ if (query.parent) {
197
+ const parentPredicate = resolveParentPredicate(query.parent, modelClass);
198
+ graphTraversalFilters.push(
199
+ `count(<-link[WHERE in.uri = ${formatSurrealValue(query.parent.id)} AND predicate = '${escapeSurrealString(parentPredicate)}']) > 0`
200
+ );
201
+ }
202
+
203
+ // Required property filters
204
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
205
+ if (propMeta.required) {
206
+ if (propMeta.getter) continue;
207
+ if (propMeta.flag && propMeta.initial) {
208
+ graphTraversalFilters.push(
209
+ `count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`
210
+ );
211
+ } else {
212
+ graphTraversalFilters.push(
213
+ `count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`
214
+ );
215
+ }
216
+ }
217
+ }
218
+
219
+ // Fallback: initial-value filters
220
+ if (graphTraversalFilters.length === 0) {
221
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
222
+ if (propMeta.initial) {
223
+ if (propMeta.flag) {
224
+ graphTraversalFilters.push(
225
+ `count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`
226
+ );
227
+ } else {
228
+ graphTraversalFilters.push(
229
+ `count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`
230
+ );
231
+ }
232
+ break;
233
+ }
234
+ }
235
+ }
236
+
237
+ // Fallback: open-world structural matching
238
+ if (graphTraversalFilters.length === 0) {
239
+ const structuralPredicates: string[] = [];
240
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
241
+ if (propMeta.predicate) {
242
+ structuralPredicates.push(`predicate = '${escapeSurrealString(propMeta.predicate)}'`);
243
+ }
244
+ }
245
+ if (metadata.relations) {
246
+ for (const [, relMeta] of Object.entries(metadata.relations)) {
247
+ if (relMeta.predicate) {
248
+ structuralPredicates.push(`predicate = '${escapeSurrealString(relMeta.predicate)}'`);
249
+ }
250
+ }
251
+ }
252
+ if (structuralPredicates.length > 0) {
253
+ graphTraversalFilters.push(
254
+ `count(->link[WHERE (${structuralPredicates.join(' OR ')})]) > 0`
255
+ );
256
+ }
257
+ }
258
+
259
+ // User WHERE clause
260
+ const userWhereClause = buildGraphTraversalWhereClause(metadata, allRelationsMetadata, where);
261
+
262
+ const whereConditions: string[] = [];
263
+ whereConditions.push(...graphTraversalFilters);
264
+ if (userWhereClause) {
265
+ whereConditions.push(userWhereClause);
266
+ }
267
+ whereConditions.push(`count(->link) > 0`);
268
+
269
+ const fullQuery = `
270
+ SELECT
271
+ id AS source,
272
+ uri AS source_uri,
273
+ ->link AS links
274
+ FROM node
275
+ WHERE ${whereConditions.join(' AND ')}
276
+ FETCH links
277
+ `.trim();
278
+
279
+ return fullQuery;
280
+ }
@@ -9,7 +9,6 @@
9
9
  * - filter:false and explicit getter options are respected
10
10
  */
11
11
  import { Ad4mModel } from "./Ad4mModel";
12
- import type { Where } from "./Ad4mModel";
13
12
  import {
14
13
  Model,
15
14
  Property,
@@ -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
+ }