@coasys/ad4m 0.12.0-rc1-dev.5 → 0.12.0

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,36 @@
1
+ /**
2
+ * Shared query helpers used by both the Prolog and SurrealQL query pipelines.
3
+ */
4
+ import { getRelationsMetadata } from "./decorators";
5
+ /**
6
+ * Resolves the predicate for a parent query.
7
+ *
8
+ * Uses TS discriminated union narrowing:
9
+ * - Raw form (`{ id, predicate }`) → predicate used as-is
10
+ * - Model form (`{ model, id, field? }`) → lookup from relation metadata
11
+ * - With `field`: direct key lookup
12
+ * - Without `field`: scan for a relation whose `target()` matches `childCtor`
13
+ */
14
+ export function resolveParentPredicate(parent, childCtor) {
15
+ // Raw form — explicit predicate
16
+ if ('predicate' in parent)
17
+ return parent.predicate;
18
+ // Model form — resolve from relation metadata
19
+ const { model } = parent;
20
+ const relMeta = getRelationsMetadata(model);
21
+ // Direct lookup by field name when provided
22
+ if (parent.field) {
23
+ const entry = relMeta[parent.field];
24
+ if (!entry) {
25
+ throw new Error(`parent(): field "${parent.field}" is not a registered relation on ${model.name}`);
26
+ }
27
+ return entry.predicate;
28
+ }
29
+ // Fallback: scan for a relation whose target matches the child class
30
+ for (const [, entry] of Object.entries(relMeta)) {
31
+ if (entry.target && entry.target() === childCtor) {
32
+ return entry.predicate;
33
+ }
34
+ }
35
+ throw new Error(`parent(): could not resolve predicate — no relation on ${model.name} targets ${childCtor.name || 'the queried class'}`);
36
+ }
@@ -0,0 +1,15 @@
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
+ import type { Where, Order, ParentScope } from "./types";
8
+ export declare function buildParentQuery(parent: ParentScope | undefined, resolvedPredicate?: string): string;
9
+ export declare function buildAuthorAndTimestampQuery(): string;
10
+ export declare function buildPropertiesQuery(properties?: string[]): string;
11
+ export declare function buildWhereQuery(where?: Where): string;
12
+ export declare function buildCountQuery(count?: boolean): string;
13
+ export declare function buildOrderQuery(order?: Order): string;
14
+ export declare function buildOffsetQuery(offset?: number): string;
15
+ export declare function buildLimitQuery(limit?: number): string;
@@ -0,0 +1,140 @@
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
+ import { capitalize } from "./util";
8
+ // ── Query clause builders ────────────────────────────────────────────────────
9
+ export function buildParentQuery(parent, resolvedPredicate) {
10
+ if (!parent || !resolvedPredicate)
11
+ return '';
12
+ return `triple("${parent.id}", "${resolvedPredicate}", Base)`;
13
+ }
14
+ export function buildAuthorAndTimestampQuery() {
15
+ // Gets the author and timestamp of a Ad4mModel instance (based on the first link mentioning the base)
16
+ return `
17
+ findall(
18
+ [T, A],
19
+ link(Base, _, _, T, A),
20
+ AllLinks
21
+ ),
22
+ sort(AllLinks, SortedLinks),
23
+ SortedLinks = [[Timestamp, Author]|_]
24
+ `;
25
+ }
26
+ export function buildPropertiesQuery(properties) {
27
+ // Gets the name, value, and resolve boolean for all (or some) properties on a Ad4mModel instance
28
+ // Resolves literals (if property_resolve/2 is true) to their value - either the data field if it is
29
+ // an Expression in JSON literal, or the direct literal value if it is a simple literal
30
+ // If no properties are provided, all are included
31
+ return `
32
+ findall([PropertyName, PropertyValue, Resolve], (
33
+ % Constrain to specified properties if provided
34
+ ${properties ? `member(PropertyName, [${properties.map((name) => `"${name}"`).join(", ")}]),` : ""}
35
+ resolve_property(SubjectClass, Base, PropertyName, PropertyValue, Resolve)
36
+ ), Properties)
37
+ `;
38
+ }
39
+ export function buildWhereQuery(where = {}) {
40
+ // Constrains the query to instances that match the provided where conditions
41
+ // 'id' maps to the Prolog 'Base' variable (the base expression of the instance).
42
+ function formatValue(value) {
43
+ // Wrap strings in quotes
44
+ return typeof value === "string" ? `"${value}"` : value;
45
+ }
46
+ return Object.entries(where)
47
+ .map(([key, value]) => {
48
+ const isSpecial = ["id", "author", "timestamp"].includes(key);
49
+ const getter = `resolve_property(SubjectClass, Base, "${key}", Value${key}, _)`;
50
+ // For 'id' the Prolog variable is always 'Base'
51
+ const field = key === "id" ? "Base" : capitalize(key);
52
+ // Handle direct array values (for IN conditions)
53
+ if (Array.isArray(value)) {
54
+ const formattedValues = value.map((v) => formatValue(v)).join(", ");
55
+ if (isSpecial)
56
+ return `member(${field}, [${formattedValues}])`;
57
+ else
58
+ return `${getter}, member(Value${key}, [${formattedValues}])`;
59
+ }
60
+ // Handle operation object
61
+ if (typeof value === "object" && value !== null) {
62
+ const { not, between, lt, lte, gt, gte } = value;
63
+ // Handle NOT operation
64
+ if (not !== undefined) {
65
+ if (Array.isArray(not)) {
66
+ // NOT IN array
67
+ const formattedValues = not.map((v) => formatValue(v)).join(", ");
68
+ if (isSpecial)
69
+ return `\\+ member(${field}, [${formattedValues}])`;
70
+ else
71
+ return `${getter}, \\+ member(Value${key}, [${formattedValues}])`;
72
+ }
73
+ else {
74
+ // NOT EQUAL
75
+ if (isSpecial)
76
+ return `${field} \\= ${formatValue(not)}`;
77
+ else
78
+ return `${getter}, Value${key} \\= ${formatValue(not)}`;
79
+ }
80
+ }
81
+ // Handle BETWEEN
82
+ if (between !== undefined && Array.isArray(between) && between.length === 2) {
83
+ if (isSpecial)
84
+ return `${field} >= ${between[0]}, ${field} =< ${between[1]}`;
85
+ else
86
+ return `${getter}, Value${key} >= ${between[0]}, Value${key} =< ${between[1]}`;
87
+ }
88
+ // Handle lt, lte, gt, & gte operations
89
+ const operators = [
90
+ { value: lt, symbol: "<" },
91
+ { value: lte, symbol: "=<" },
92
+ { value: gt, symbol: ">" },
93
+ { value: gte, symbol: ">=" }, // GREATER THAN OR EQUAL TO
94
+ ];
95
+ for (const { value, symbol } of operators) {
96
+ if (value !== undefined)
97
+ return isSpecial ? `${field} ${symbol} ${value}` : `${getter}, Value${key} ${symbol} ${value}`;
98
+ }
99
+ }
100
+ // Default to direct equality
101
+ if (isSpecial)
102
+ return `${field} = ${formatValue(value)}`;
103
+ else
104
+ return `${getter}, Value${key} = ${formatValue(value)}`;
105
+ })
106
+ .join(", ");
107
+ }
108
+ export function buildCountQuery(count) {
109
+ return count ? "length(UnsortedInstances, TotalCount)" : "";
110
+ }
111
+ export function buildOrderQuery(order) {
112
+ if (!order)
113
+ return "SortedInstances = UnsortedInstances";
114
+ const entries = Object.entries(order);
115
+ if (entries.length === 1) {
116
+ const [propertyName, direction] = entries[0];
117
+ return `sort_instances(UnsortedInstances, "${propertyName}", "${direction}", SortedInstances)`;
118
+ }
119
+ // Multi-field sort: sort from least-significant to most-significant key
120
+ // so that the final (primary) sort preserves secondary-key ordering for equal values.
121
+ // The merge_sort implementation is stable (equal elements keep original order).
122
+ const clauses = [];
123
+ for (let i = entries.length - 1; i >= 0; i--) {
124
+ const [propertyName, direction] = entries[i];
125
+ const inputVar = i === entries.length - 1 ? "UnsortedInstances" : `MultiSortIntermediate${i + 1}`;
126
+ const outputVar = i === 0 ? "SortedInstances" : `MultiSortIntermediate${i}`;
127
+ clauses.push(`sort_instances(${inputVar}, "${propertyName}", "${direction}", ${outputVar})`);
128
+ }
129
+ return clauses.join(",\n ");
130
+ }
131
+ export function buildOffsetQuery(offset) {
132
+ if (!offset || offset < 0)
133
+ return "InstancesWithOffset = SortedInstances";
134
+ return `skipN(SortedInstances, ${offset}, InstancesWithOffset)`;
135
+ }
136
+ export function buildLimitQuery(limit) {
137
+ if (!limit || limit < 0)
138
+ return "AllInstances = InstancesWithOffset";
139
+ return `takeN(InstancesWithOffset, ${limit}, AllInstances)`;
140
+ }
@@ -0,0 +1,44 @@
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
+ import type { RelationMetadataEntry } from "./decorators";
15
+ import type { Where, Query, ModelMetadata } from "./types";
16
+ /**
17
+ * Builds WHERE clause filters using SurrealDB graph traversal syntax.
18
+ *
19
+ * Translates where conditions into `->link[WHERE ...]` / `<-link[WHERE ...]`
20
+ * filters that SurrealDB can optimize via graph indexes.
21
+ *
22
+ * @param metadata - Model metadata from `getModelMetadata()`
23
+ * @param allRelationsMetadata - Full relation metadata (needed for belongs-to
24
+ * direction detection)
25
+ * @param where - User-supplied where conditions
26
+ * @returns Combined AND-joined condition string, or empty string
27
+ */
28
+ export declare function buildGraphTraversalWhereClause(metadata: ModelMetadata, allRelationsMetadata: Record<string, RelationMetadataEntry>, where?: Where): string;
29
+ /**
30
+ * Builds a complete SurrealQL query from a Query object and model metadata.
31
+ *
32
+ * This is the core implementation behind `Ad4mModel.queryToSurrealQL()`.
33
+ * It produces a graph-traversal query that:
34
+ * 1. Filters nodes by required predicates (conformance check)
35
+ * 2. Applies user WHERE conditions
36
+ * 3. Fetches all outgoing links for hydration
37
+ *
38
+ * @param metadata - Model metadata from `getModelMetadata()`
39
+ * @param allRelationsMetadata - Full relation registry (for belongs-to detection)
40
+ * @param query - Query parameters
41
+ * @param modelClass - The model class (for `resolveParentPredicate`)
42
+ * @returns Complete SurrealQL query string
43
+ */
44
+ export declare function buildSurrealQLQuery(metadata: ModelMetadata, allRelationsMetadata: Record<string, RelationMetadataEntry>, query: Query, modelClass: any): string;
@@ -0,0 +1,249 @@
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
+ import { escapeSurrealString } from "../utils";
15
+ import { formatSurrealValue } from "./surreal-utils";
16
+ import { resolveParentPredicate } from "./query-common";
17
+ // ─── Graph Traversal WHERE Clause ────────────────────────────────────────────
18
+ /**
19
+ * Builds WHERE clause filters using SurrealDB graph traversal syntax.
20
+ *
21
+ * Translates where conditions into `->link[WHERE ...]` / `<-link[WHERE ...]`
22
+ * filters that SurrealDB can optimize via graph indexes.
23
+ *
24
+ * @param metadata - Model metadata from `getModelMetadata()`
25
+ * @param allRelationsMetadata - Full relation metadata (needed for belongs-to
26
+ * direction detection)
27
+ * @param where - User-supplied where conditions
28
+ * @returns Combined AND-joined condition string, or empty string
29
+ */
30
+ export function buildGraphTraversalWhereClause(metadata, allRelationsMetadata, where) {
31
+ if (!where)
32
+ return '';
33
+ const conditions = [];
34
+ for (const [propertyName, condition] of Object.entries(where)) {
35
+ const isSpecial = ['id', 'author', 'timestamp'].includes(propertyName);
36
+ if (isSpecial) {
37
+ if (propertyName === 'author' || propertyName === 'timestamp') {
38
+ continue; // Filtered post-query in JS
39
+ }
40
+ const columnName = 'uri';
41
+ if (Array.isArray(condition)) {
42
+ const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
43
+ conditions.push(`${columnName} IN [${formattedValues}]`);
44
+ }
45
+ else if (typeof condition === 'object' && condition !== null) {
46
+ const ops = condition;
47
+ if (ops.not !== undefined) {
48
+ if (Array.isArray(ops.not)) {
49
+ const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
50
+ conditions.push(`${columnName} NOT IN [${formattedValues}]`);
51
+ }
52
+ else {
53
+ conditions.push(`${columnName} != ${formatSurrealValue(ops.not)}`);
54
+ }
55
+ }
56
+ if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
57
+ conditions.push(`${columnName} >= ${formatSurrealValue(ops.between[0])} AND ${columnName} <= ${formatSurrealValue(ops.between[1])}`);
58
+ }
59
+ if (ops.gt !== undefined) {
60
+ conditions.push(`${columnName} > ${formatSurrealValue(ops.gt)}`);
61
+ }
62
+ if (ops.gte !== undefined) {
63
+ conditions.push(`${columnName} >= ${formatSurrealValue(ops.gte)}`);
64
+ }
65
+ if (ops.lt !== undefined) {
66
+ conditions.push(`${columnName} < ${formatSurrealValue(ops.lt)}`);
67
+ }
68
+ if (ops.lte !== undefined) {
69
+ conditions.push(`${columnName} <= ${formatSurrealValue(ops.lte)}`);
70
+ }
71
+ if (ops.contains !== undefined) {
72
+ conditions.push(`${columnName} CONTAINS ${formatSurrealValue(ops.contains)}`);
73
+ }
74
+ }
75
+ else {
76
+ conditions.push(`${columnName} = ${formatSurrealValue(condition)}`);
77
+ }
78
+ }
79
+ else {
80
+ // Regular properties — check relation metadata first for direction
81
+ const relMeta = allRelationsMetadata[propertyName];
82
+ const isBelongs = relMeta?.kind === 'belongsToOne' || relMeta?.kind === 'belongsToMany';
83
+ if (relMeta) {
84
+ const predicate = escapeSurrealString(relMeta.predicate);
85
+ if (Array.isArray(condition)) {
86
+ const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
87
+ if (isBelongs) {
88
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) > 0`);
89
+ }
90
+ else {
91
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) > 0`);
92
+ }
93
+ }
94
+ else if (typeof condition === 'object' && condition !== null) {
95
+ const ops = condition;
96
+ if (ops.not !== undefined) {
97
+ if (Array.isArray(ops.not)) {
98
+ const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
99
+ if (isBelongs) {
100
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) = 0`);
101
+ }
102
+ else {
103
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) = 0`);
104
+ }
105
+ }
106
+ else {
107
+ if (isBelongs) {
108
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(ops.not)}]) = 0`);
109
+ }
110
+ else {
111
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(ops.not)}]) = 0`);
112
+ }
113
+ }
114
+ }
115
+ }
116
+ else {
117
+ if (isBelongs) {
118
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(condition)}]) > 0`);
119
+ }
120
+ else {
121
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(condition)}]) > 0`);
122
+ }
123
+ }
124
+ continue;
125
+ }
126
+ const propMeta = metadata.properties[propertyName];
127
+ if (!propMeta)
128
+ continue;
129
+ const predicate = escapeSurrealString(propMeta.predicate);
130
+ const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
131
+ if (Array.isArray(condition)) {
132
+ const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
133
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
134
+ }
135
+ else if (typeof condition === 'object' && condition !== null) {
136
+ const ops = condition;
137
+ if (ops.not !== undefined) {
138
+ if (Array.isArray(ops.not)) {
139
+ const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
140
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
141
+ }
142
+ else {
143
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
144
+ }
145
+ }
146
+ const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
147
+ ops.lt !== undefined || ops.lte !== undefined ||
148
+ ops.between !== undefined || ops.contains !== undefined;
149
+ if (hasComparisonOps) {
150
+ conditions.push(`count(->link[WHERE predicate = '${predicate}']) > 0`);
151
+ }
152
+ }
153
+ else {
154
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`);
155
+ }
156
+ }
157
+ }
158
+ return conditions.join(' AND ');
159
+ }
160
+ // ─── Main Query Builder ─────────────────────────────────────────────────────
161
+ /**
162
+ * Builds a complete SurrealQL query from a Query object and model metadata.
163
+ *
164
+ * This is the core implementation behind `Ad4mModel.queryToSurrealQL()`.
165
+ * It produces a graph-traversal query that:
166
+ * 1. Filters nodes by required predicates (conformance check)
167
+ * 2. Applies user WHERE conditions
168
+ * 3. Fetches all outgoing links for hydration
169
+ *
170
+ * @param metadata - Model metadata from `getModelMetadata()`
171
+ * @param allRelationsMetadata - Full relation registry (for belongs-to detection)
172
+ * @param query - Query parameters
173
+ * @param modelClass - The model class (for `resolveParentPredicate`)
174
+ * @returns Complete SurrealQL query string
175
+ */
176
+ export function buildSurrealQLQuery(metadata, allRelationsMetadata, query, modelClass) {
177
+ const { where } = query;
178
+ // Build graph traversal filters for required predicates
179
+ const graphTraversalFilters = [];
180
+ // Parent filter
181
+ if (query.parent) {
182
+ const parentPredicate = resolveParentPredicate(query.parent, modelClass);
183
+ graphTraversalFilters.push(`count(<-link[WHERE in.uri = ${formatSurrealValue(query.parent.id)} AND predicate = '${escapeSurrealString(parentPredicate)}']) > 0`);
184
+ }
185
+ // Required property filters
186
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
187
+ if (propMeta.required) {
188
+ if (propMeta.getter)
189
+ continue;
190
+ if (propMeta.flag && propMeta.initial) {
191
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
192
+ }
193
+ else {
194
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
195
+ }
196
+ }
197
+ }
198
+ // Fallback: initial-value filters
199
+ if (graphTraversalFilters.length === 0) {
200
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
201
+ if (propMeta.initial) {
202
+ if (propMeta.flag) {
203
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
204
+ }
205
+ else {
206
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
207
+ }
208
+ break;
209
+ }
210
+ }
211
+ }
212
+ // Fallback: open-world structural matching
213
+ if (graphTraversalFilters.length === 0) {
214
+ const structuralPredicates = [];
215
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
216
+ if (propMeta.predicate) {
217
+ structuralPredicates.push(`predicate = '${escapeSurrealString(propMeta.predicate)}'`);
218
+ }
219
+ }
220
+ if (metadata.relations) {
221
+ for (const [, relMeta] of Object.entries(metadata.relations)) {
222
+ if (relMeta.predicate) {
223
+ structuralPredicates.push(`predicate = '${escapeSurrealString(relMeta.predicate)}'`);
224
+ }
225
+ }
226
+ }
227
+ if (structuralPredicates.length > 0) {
228
+ graphTraversalFilters.push(`count(->link[WHERE (${structuralPredicates.join(' OR ')})]) > 0`);
229
+ }
230
+ }
231
+ // User WHERE clause
232
+ const userWhereClause = buildGraphTraversalWhereClause(metadata, allRelationsMetadata, where);
233
+ const whereConditions = [];
234
+ whereConditions.push(...graphTraversalFilters);
235
+ if (userWhereClause) {
236
+ whereConditions.push(userWhereClause);
237
+ }
238
+ whereConditions.push(`count(->link) > 0`);
239
+ const fullQuery = `
240
+ SELECT
241
+ id AS source,
242
+ uri AS source_uri,
243
+ ->link AS links
244
+ FROM node
245
+ WHERE ${whereConditions.join(' AND ')}
246
+ FETCH links
247
+ `.trim();
248
+ return fullQuery;
249
+ }
@@ -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
+ }